-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadvisor_test.go
More file actions
628 lines (555 loc) · 17.4 KB
/
advisor_test.go
File metadata and controls
628 lines (555 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
package tok
import (
"strings"
"testing"
"time"
)
func TestNewCompressionAdvisor(t *testing.T) {
ca := NewCompressionAdvisor()
if ca == nil {
t.Fatal("NewCompressionAdvisor returned nil")
}
if len(ca.History) != 0 {
t.Errorf("expected empty history, got %d events", len(ca.History))
}
if len(ca.Strategies) != 0 {
t.Errorf("expected empty strategies, got %d entries", len(ca.Strategies))
}
}
func TestRecord(t *testing.T) {
ca := NewCompressionAdvisor()
event := CompressionEvent{
Input: "func main() { fmt.Println(\"hello\") }",
Output: "func main(){fmt.Println(\"hello\")}",
Mode: "full",
InputTokens: 100,
OutputTokens: 60,
ContentType: "code",
Timestamp: time.Now(),
}
ca.Record(event)
if len(ca.History) != 1 {
t.Fatalf("expected 1 event, got %d", len(ca.History))
}
if ca.History[0].Savings != 0.4 {
t.Errorf("expected savings 0.4, got %f", ca.History[0].Savings)
}
key := "full:code"
stats, ok := ca.Strategies[key]
if !ok {
t.Fatalf("expected strategy %q to exist", key)
}
if stats.TotalEvents != 1 {
t.Errorf("expected 1 event, got %d", stats.TotalEvents)
}
if stats.AvgSavings != 0.4 {
t.Errorf("expected avg savings 0.4, got %f", stats.AvgSavings)
}
}
func TestRecordMultipleEvents(t *testing.T) {
ca := NewCompressionAdvisor()
events := []CompressionEvent{
{Input: "code1", Output: "c1", Mode: "full", InputTokens: 100, OutputTokens: 50, ContentType: "code", Timestamp: time.Now()},
{Input: "code2", Output: "c2", Mode: "full", InputTokens: 200, OutputTokens: 120, ContentType: "code", Timestamp: time.Now()},
}
for _, e := range events {
ca.Record(e)
}
if len(ca.History) != 2 {
t.Fatalf("expected 2 events, got %d", len(ca.History))
}
stats := ca.Strategies["full:code"]
if stats.TotalEvents != 2 {
t.Errorf("expected 2 events, got %d", stats.TotalEvents)
}
// First event: 0.5, Second event: 0.4, avg should be 0.45
expectedAvg := 0.45
if abs(stats.AvgSavings-expectedAvg) > 0.001 {
t.Errorf("expected avg savings ~%.3f, got %.3f", expectedAvg, stats.AvgSavings)
}
if stats.BestSavings != 0.5 {
t.Errorf("expected best savings 0.5, got %f", stats.BestSavings)
}
if stats.WorstSavings != 0.4 {
t.Errorf("expected worst savings 0.4, got %f", stats.WorstSavings)
}
}
func TestRecordAutoClassifiesContent(t *testing.T) {
ca := NewCompressionAdvisor()
event := CompressionEvent{
Input: "func main() {\n\tfmt.Println(\"hello\")\n\treturn\n}\nfunc foo() {\n\tvar x int\n}",
Output: "compressed",
Mode: "full",
InputTokens: 50,
OutputTokens: 30,
Timestamp: time.Now(),
}
ca.Record(event)
if ca.History[0].ContentType != "code" {
t.Errorf("expected auto-classification 'code', got %q", ca.History[0].ContentType)
}
}
func TestRecordAutoTimestamp(t *testing.T) {
ca := NewCompressionAdvisor()
before := time.Now()
ca.Record(CompressionEvent{
Input: "test",
Output: "t",
Mode: "lite",
InputTokens: 10,
OutputTokens: 5,
ContentType: "natural_language",
})
after := time.Now()
ts := ca.History[0].Timestamp
if ts.Before(before) || ts.After(after) {
t.Errorf("expected timestamp between %v and %v, got %v", before, after, ts)
}
}
func TestClassifyContentCode(t *testing.T) {
code := `package main
import "fmt"
func main() {
var x int
for i := 0; i < 10; i++ {
x += i
}
fmt.Println(x)
return
}`
result := ClassifyContent(code)
if result != "code" {
t.Errorf("expected 'code', got %q", result)
}
}
func TestClassifyContentNaturalLanguage(t *testing.T) {
text := `The quick brown fox jumps over the lazy dog. This is a paragraph of
natural language text that describes something interesting. It contains multiple
sentences and has proper grammar and punctuation throughout the passage. The text
flows naturally from one idea to the next without any code or technical markers.`
result := ClassifyContent(text)
if result != "natural_language" {
t.Errorf("expected 'natural_language', got %q", result)
}
}
func TestClassifyContentError(t *testing.T) {
errorText := `panic: runtime error: index out of range [5] with length 3
goroutine 1 [running]:
main.process(...)
/app/main.go:42
main.handler(...)
/app/main.go:28
Error: failed to process request
caused by: connection timeout`
result := ClassifyContent(errorText)
if result != "error" {
t.Errorf("expected 'error', got %q", result)
}
}
func TestClassifyContentDiff(t *testing.T) {
diff := `diff --git a/main.go b/main.go
--- a/main.go
+++ b/main.go
@@ -10,6 +10,8 @@ func main() {
+ fmt.Println("added")
+ x := 42
- old := true
unchanged line
+ another addition`
result := ClassifyContent(diff)
if result != "diff" {
t.Errorf("expected 'diff', got %q", result)
}
}
func TestClassifyContentData(t *testing.T) {
json := `{
"name": "test",
"value": 42,
"items": [1, 2, 3]
}`
result := ClassifyContent(json)
if result != "data" {
t.Errorf("expected 'data' for JSON, got %q", result)
}
csv := `name,age,city
Alice,30,NYC
Bob,25,LA
Charlie,35,Chicago
David,28,Seattle`
result = ClassifyContent(csv)
if result != "data" {
t.Errorf("expected 'data' for CSV, got %q", result)
}
}
func TestClassifyContentLog(t *testing.T) {
log := `2024-01-15 10:30:45 INFO Starting server on port 8080
2024-01-15 10:30:46 INFO Connected to database
2024-01-15 10:30:47 WARN High memory usage detected
2024-01-15 10:30:48 ERROR Connection refused
2024-01-15 10:30:49 DEBUG Processing request #1234`
result := ClassifyContent(log)
if result != "log" {
t.Errorf("expected 'log', got %q", result)
}
}
func TestClassifyContentTestOutput(t *testing.T) {
testOut := `=== RUN TestFoo
--- PASS: TestFoo (0.01s)
=== RUN TestBar
--- FAIL: TestBar (0.03s)
bar_test.go:15: expected 5, got 3
=== RUN TestBaz
--- PASS: TestBaz (0.00s)
FAIL
FAIL github.com/example/pkg 0.05s`
result := ClassifyContent(testOut)
if result != "test_output" {
t.Errorf("expected 'test_output', got %q", result)
}
}
func TestClassifyContentEmpty(t *testing.T) {
result := ClassifyContent("")
if result != "natural_language" {
t.Errorf("expected 'natural_language' for empty string, got %q", result)
}
}
func TestRecommendMode(t *testing.T) {
tests := []struct {
contentType string
budget int
expected string
}{
{"code", 1000, "full"},
{"code", 100, "aggressive"},
{"natural_language", 500, "ultra"},
{"natural_language", 100, "aggressive"},
{"error", 500, "lite"},
{"error", 50, "aggressive"},
{"diff", 1000, "aggressive"},
{"diff", 100, "aggressive"},
{"test_output", 1000, "full"},
{"test_output", 100, "aggressive"},
{"log", 1000, "aggressive"},
{"log", 100, "aggressive"},
{"data", 1000, "full"},
{"data", 100, "aggressive"},
{"unknown", 1000, "full"},
{"unknown", 100, "aggressive"},
}
for _, tt := range tests {
result := RecommendMode(tt.contentType, tt.budget)
if result != tt.expected {
t.Errorf("RecommendMode(%q, %d) = %q, want %q", tt.contentType, tt.budget, result, tt.expected)
}
}
}
func TestOptimalBudget(t *testing.T) {
tests := []struct {
contentType string
importance float64
minExpected int
maxExpected int
}{
{"code", 1.0, 3500, 4500}, // 2000 * 2.0 = 4000
{"code", 0.0, 500, 700}, // 2000 * 0.3 = 600
{"code", 0.5, 2000, 2500}, // 2000 * 1.15 = 2300
{"natural_language", 1.0, 1800, 2200}, // 1000 * 2.0 = 2000
{"error", 0.5, 1500, 1800}, // 1500 * 1.15 = 1725
{"test_output", 0.0, 100, 200}, // 500 * 0.3 = 150
{"unknown", 0.5, 1000, 1300}, // 1000 * 1.15 = 1150
}
for _, tt := range tests {
result := OptimalBudget(tt.contentType, tt.importance)
if result < tt.minExpected || result > tt.maxExpected {
t.Errorf("OptimalBudget(%q, %.1f) = %d, want between %d and %d",
tt.contentType, tt.importance, result, tt.minExpected, tt.maxExpected)
}
}
}
func TestOptimalBudgetClamps(t *testing.T) {
// Importance below 0 should clamp to 0
result := OptimalBudget("code", -1.0)
expected := OptimalBudget("code", 0.0)
if result != expected {
t.Errorf("OptimalBudget with negative importance should clamp: got %d, want %d", result, expected)
}
// Importance above 1 should clamp to 1
result = OptimalBudget("code", 5.0)
expected = OptimalBudget("code", 1.0)
if result != expected {
t.Errorf("OptimalBudget with >1 importance should clamp: got %d, want %d", result, expected)
}
}
func TestWastedTokens(t *testing.T) {
events := []CompressionEvent{
{ContentType: "test_output", InputTokens: 10000, Savings: 0.30}, // optimal 0.85, wasted: (0.85-0.30)*10000 = 5500
{ContentType: "code", InputTokens: 5000, Savings: 0.40}, // optimal 0.40, wasted: 0
{ContentType: "natural_language", InputTokens: 3000, Savings: 0.20}, // optimal 0.60, wasted: (0.60-0.20)*3000 = 1200
}
wasted := WastedTokens(events)
// Expected: 5500 + 0 + 1200 = 6700
if wasted != 6700 {
t.Errorf("WastedTokens = %d, want 6700", wasted)
}
}
func TestWastedTokensNoWaste(t *testing.T) {
events := []CompressionEvent{
{ContentType: "code", InputTokens: 5000, Savings: 0.50}, // better than optimal 0.40, no waste
{ContentType: "error", InputTokens: 3000, Savings: 0.30}, // better than optimal 0.20, no waste
}
wasted := WastedTokens(events)
if wasted != 0 {
t.Errorf("WastedTokens = %d, want 0", wasted)
}
}
func TestWastedTokensEmpty(t *testing.T) {
wasted := WastedTokens(nil)
if wasted != 0 {
t.Errorf("WastedTokens(nil) = %d, want 0", wasted)
}
}
func TestAnalyze(t *testing.T) {
ca := NewCompressionAdvisor()
now := time.Now()
events := []CompressionEvent{
{Input: "func foo() {}", ContentType: "code", Mode: "full", InputTokens: 100, OutputTokens: 60, Timestamp: now},
{Input: "Hello world text", ContentType: "natural_language", Mode: "lite", InputTokens: 200, OutputTokens: 150, Timestamp: now},
{Input: "Error: panic", ContentType: "error", Mode: "full", InputTokens: 150, OutputTokens: 100, Timestamp: now},
}
for _, e := range events {
ca.Record(e)
}
recs := ca.Analyze()
if len(recs) == 0 {
t.Fatal("Analyze returned no recommendations")
}
// Check that we have recommendations for recorded content types
hasCode := false
hasNL := false
hasError := false
for _, r := range recs {
switch r.ContentType {
case "code":
hasCode = true
if r.Strategy != "full" {
t.Errorf("expected 'full' strategy for code, got %q", r.Strategy)
}
case "natural_language":
hasNL = true
if r.Strategy != "ultra" {
t.Errorf("expected 'ultra' strategy for natural_language, got %q", r.Strategy)
}
case "error":
hasError = true
if r.Strategy != "lite" {
t.Errorf("expected 'lite' strategy for error, got %q", r.Strategy)
}
}
}
if !hasCode {
t.Error("no recommendation for code content type")
}
if !hasNL {
t.Error("no recommendation for natural_language content type")
}
if !hasError {
t.Error("no recommendation for error content type")
}
}
func TestAnalyzeEmpty(t *testing.T) {
ca := NewCompressionAdvisor()
recs := ca.Analyze()
if len(recs) == 0 {
t.Fatal("Analyze with no history should return default recommendations")
}
// Default recommendations should include standard content types
found := false
for _, r := range recs {
if r.ContentType == "test_output" || r.ContentType == "code" {
found = true
}
}
if !found {
t.Error("default recommendations missing expected content types")
}
}
func TestAnalyzeSortedByPriority(t *testing.T) {
ca := NewCompressionAdvisor()
now := time.Now()
events := []CompressionEvent{
{ContentType: "code", Mode: "full", InputTokens: 100, OutputTokens: 60, Timestamp: now},
{ContentType: "diff", Mode: "lite", InputTokens: 200, OutputTokens: 100, Timestamp: now},
{ContentType: "test_output", Mode: "lite", InputTokens: 300, OutputTokens: 200, Timestamp: now},
{ContentType: "natural_language", Mode: "lite", InputTokens: 150, OutputTokens: 100, Timestamp: now},
}
for _, e := range events {
ca.Record(e)
}
recs := ca.Analyze()
for i := 1; i < len(recs); i++ {
if recs[i].Priority < recs[i-1].Priority {
t.Errorf("recommendations not sorted by priority: %d at index %d after %d at index %d",
recs[i].Priority, i, recs[i-1].Priority, i-1)
}
}
}
func TestFormatAdvice(t *testing.T) {
ca := NewCompressionAdvisor()
now := time.Now()
events := []CompressionEvent{
{ContentType: "code", Mode: "full", InputTokens: 15000, OutputTokens: 9000, Timestamp: now},
{ContentType: "test_output", Mode: "lite", InputTokens: 20000, OutputTokens: 15000, Timestamp: now},
{ContentType: "natural_language", Mode: "lite", InputTokens: 10000, OutputTokens: 7000, Timestamp: now},
{ContentType: "error", Mode: "full", InputTokens: 5000, OutputTokens: 4000, Timestamp: now},
}
for _, e := range events {
ca.Record(e)
}
advice := ca.FormatAdvice()
if !strings.Contains(advice, "Compression Advisor:") {
t.Error("advice missing header")
}
if !strings.Contains(advice, "───") {
t.Error("advice missing separator")
}
if !strings.Contains(advice, "tokens/session") {
t.Error("advice missing session info")
}
if !strings.Contains(advice, "savings") {
t.Error("advice missing savings info")
}
if !strings.Contains(advice, "By content type:") {
t.Error("advice missing content type section")
}
if !strings.Contains(advice, "Top recommendations:") {
t.Error("advice missing recommendations section")
}
if !strings.Contains(advice, "Code output") {
t.Error("advice missing code output entry")
}
}
func TestFormatAdviceEmpty(t *testing.T) {
ca := NewCompressionAdvisor()
advice := ca.FormatAdvice()
if !strings.Contains(advice, "Compression Advisor:") {
t.Error("empty advice missing header")
}
if !strings.Contains(advice, "No compression history") {
t.Error("empty advice missing no-history message")
}
}
func TestConcurrentAccess(t *testing.T) {
ca := NewCompressionAdvisor()
done := make(chan bool, 10)
// Concurrent writes
for i := 0; i < 5; i++ {
go func(n int) {
ca.Record(CompressionEvent{
Input: "test",
Output: "t",
Mode: "full",
InputTokens: 100,
OutputTokens: 50,
ContentType: "code",
Timestamp: time.Now(),
})
done <- true
}(i)
}
// Concurrent reads
for i := 0; i < 5; i++ {
go func() {
_ = ca.Analyze()
_ = ca.FormatAdvice()
done <- true
}()
}
for i := 0; i < 10; i++ {
<-done
}
if len(ca.History) != 5 {
t.Errorf("expected 5 events after concurrent writes, got %d", len(ca.History))
}
}
func TestStrategyStatsUpdatedCorrectly(t *testing.T) {
ca := NewCompressionAdvisor()
events := []CompressionEvent{
{Mode: "ultra", ContentType: "natural_language", InputTokens: 1000, OutputTokens: 400, Timestamp: time.Now()},
{Mode: "ultra", ContentType: "natural_language", InputTokens: 1000, OutputTokens: 300, Timestamp: time.Now()},
{Mode: "ultra", ContentType: "natural_language", InputTokens: 1000, OutputTokens: 500, Timestamp: time.Now()},
}
for _, e := range events {
ca.Record(e)
}
stats := ca.Strategies["ultra:natural_language"]
if stats == nil {
t.Fatal("strategy stats not found")
}
if stats.TotalEvents != 3 {
t.Errorf("expected 3 events, got %d", stats.TotalEvents)
}
// Savings: 0.6, 0.7, 0.5 => avg 0.6
if abs(stats.AvgSavings-0.6) > 0.001 {
t.Errorf("expected avg savings ~0.6, got %f", stats.AvgSavings)
}
if stats.BestSavings != 0.7 {
t.Errorf("expected best savings 0.7, got %f", stats.BestSavings)
}
if stats.WorstSavings != 0.5 {
t.Errorf("expected worst savings 0.5, got %f", stats.WorstSavings)
}
}
func TestRecommendModeAllContentTypes(t *testing.T) {
contentTypes := []string{"code", "natural_language", "error", "diff", "test_output", "log", "data"}
budgets := []int{50, 200, 500, 1000, 5000}
for _, ct := range contentTypes {
for _, budget := range budgets {
result := RecommendMode(ct, budget)
if result == "" {
t.Errorf("RecommendMode(%q, %d) returned empty string", ct, budget)
}
validModes := map[string]bool{"full": true, "lite": true, "ultra": true, "aggressive": true}
if !validModes[result] {
t.Errorf("RecommendMode(%q, %d) = %q, not a valid mode", ct, budget, result)
}
}
}
}
func TestOptimalBudgetAllTypes(t *testing.T) {
contentTypes := []string{"code", "natural_language", "error", "diff", "test_output", "log", "data", "unknown"}
for _, ct := range contentTypes {
low := OptimalBudget(ct, 0.0)
mid := OptimalBudget(ct, 0.5)
high := OptimalBudget(ct, 1.0)
if low >= mid {
t.Errorf("OptimalBudget(%q): low(%d) >= mid(%d)", ct, low, mid)
}
if mid >= high {
t.Errorf("OptimalBudget(%q): mid(%d) >= high(%d)", ct, mid, high)
}
if low <= 0 {
t.Errorf("OptimalBudget(%q, 0.0) = %d, should be positive", ct, low)
}
}
}
func TestMultipleSessionsDetection(t *testing.T) {
ca := NewCompressionAdvisor()
base := time.Now()
// Session 1: events close together
ca.Record(CompressionEvent{ContentType: "code", Mode: "full", InputTokens: 1000, OutputTokens: 600, Timestamp: base})
ca.Record(CompressionEvent{ContentType: "code", Mode: "full", InputTokens: 1000, OutputTokens: 600, Timestamp: base.Add(5 * time.Minute)})
// Session 2: 1 hour later
ca.Record(CompressionEvent{ContentType: "code", Mode: "full", InputTokens: 1000, OutputTokens: 600, Timestamp: base.Add(1 * time.Hour)})
ca.Record(CompressionEvent{ContentType: "code", Mode: "full", InputTokens: 1000, OutputTokens: 600, Timestamp: base.Add(1*time.Hour + 5*time.Minute)})
advice := ca.FormatAdvice()
// Should detect 2 sessions
if !strings.Contains(advice, "tokens/session") {
t.Error("advice should mention per-session stats")
}
}
func abs(x float64) float64 {
if x < 0 {
return -x
}
return x
}