summaryrefslogtreecommitdiff
path: root/internal/stats/stats_test.go
blob: 47e3068830a355cee370cb9155c21b308c49d436 (plain)
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
package stats

import (
	"context"
	"encoding/json"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"testing"
	"time"
)

func TestUpdateAndSnapshot_Single(t *testing.T) {
	t.Setenv("XDG_CACHE_HOME", t.TempDir())
	SetWindow(2 * time.Minute)
	if err := Update(context.Background(), "prov", "model", 10, 20); err != nil {
		t.Fatalf("update: %v", err)
	}
	snap, err := TakeSnapshot()
	if err != nil {
		t.Fatalf("snapshot: %v", err)
	}
	if snap.Global.Reqs != 1 || snap.Global.Sent != 10 || snap.Global.Recv != 20 {
		t.Fatalf("unexpected snap: %+v", snap)
	}
	if snap.Providers["prov"].Totals.Reqs != 1 || snap.Providers["prov"].Models["model"].Reqs != 1 {
		t.Fatalf("missing provider/model aggregates: %+v", snap)
	}
}

func TestUpdate_PrunesOld_ByWindow(t *testing.T) {
	t.Setenv("XDG_CACHE_HOME", t.TempDir())
	SetWindow(2 * time.Second)
	ctx := context.Background()

	// Inject a fake clock so we can advance time without sleeping.
	fakeNow := time.Now()
	nowFunc = func() time.Time { return fakeNow }
	defer func() { nowFunc = time.Now }()

	if err := Update(ctx, "p", "m", 1, 1); err != nil {
		t.Fatal(err)
	}
	// Advance fake time past the 2-second window so the first event is pruned.
	fakeNow = fakeNow.Add(3 * time.Second)
	if err := Update(ctx, "p", "m", 2, 2); err != nil {
		t.Fatal(err)
	}
	snap, err := TakeSnapshot()
	if err != nil {
		t.Fatal(err)
	}
	if snap.Global.Reqs != 1 || snap.Global.Sent != 2 || snap.Global.Recv != 2 {
		t.Fatalf("expected first event pruned, got %+v", snap)
	}
}

func TestConcurrentUpdates_LockSafety(t *testing.T) {
	t.Setenv("XDG_CACHE_HOME", t.TempDir())
	SetWindow(1 * time.Minute)
	ctx := context.Background()
	var wg sync.WaitGroup
	n := 20
	for i := 0; i < n; i++ {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()
			if err := Update(ctx, "p", "m", i, i); err != nil {
				t.Errorf("update %d: %v", i, err)
			}
		}(i)
	}
	wg.Wait()
	snap, err := TakeSnapshot()
	if err != nil {
		t.Fatal(err)
	}
	if snap.Global.Reqs != int64(n) {
		t.Fatalf("reqs mismatch: %d", snap.Global.Reqs)
	}
}

func TestCacheDir_XDG(t *testing.T) {
	dir := t.TempDir()
	t.Setenv("XDG_CACHE_HOME", dir)
	got, err := CacheDir()
	if err != nil {
		t.Fatal(err)
	}
	want := filepath.Join(dir, "hexai")
	if got != want {
		t.Fatalf("got %q want %q", got, want)
	}
}

// TestCacheDir_FallbackHome covers the branch where XDG_CACHE_HOME is unset,
// so CacheDir falls back to $HOME/.local/hexai/cache.
func TestCacheDir_FallbackHome(t *testing.T) {
	t.Setenv("XDG_CACHE_HOME", "")
	got, err := CacheDir()
	if err != nil {
		t.Fatal(err)
	}
	home, _ := os.UserHomeDir()
	want := filepath.Join(home, ".local", "hexai", "cache")
	if got != want {
		t.Fatalf("got %q want %q", got, want)
	}
}

// TestCacheDir_WhitespaceXDG covers the branch where XDG_CACHE_HOME contains
// only whitespace, which strings.TrimSpace reduces to "" so the fallback is used.
func TestCacheDir_WhitespaceXDG(t *testing.T) {
	t.Setenv("XDG_CACHE_HOME", "  \t\n ")
	got, err := CacheDir()
	if err != nil {
		t.Fatal(err)
	}
	home, _ := os.UserHomeDir()
	want := filepath.Join(home, ".local", "hexai", "cache")
	if got != want {
		t.Fatalf("got %q want %q", got, want)
	}
}

// TestSetWindow_ClampLow covers the branch where d < 1s is clamped to 1s.
func TestSetWindow_ClampLow(t *testing.T) {
	SetWindow(100 * time.Millisecond)
	got := Window()
	if got != time.Second {
		t.Fatalf("expected 1s, got %v", got)
	}
}

// TestSetWindow_ClampHigh covers the branch where d > 24h is clamped to 24h.
func TestSetWindow_ClampHigh(t *testing.T) {
	SetWindow(48 * time.Hour)
	got := Window()
	if got != 24*time.Hour {
		t.Fatalf("expected 24h, got %v", got)
	}
	// Restore a reasonable default for other tests.
	SetWindow(time.Hour)
}

// TestStringsTrim_NoTrimNeeded covers the early-return branch where the input
// has no leading or trailing whitespace, so the original string is returned.
func TestStringsTrim_NoTrimNeeded(t *testing.T) {
	in := "hello"
	got := strings.TrimSpace(in)
	if got != "hello" {
		t.Fatalf("expected %q, got %q", "hello", got)
	}
}

// TestStringsTrim_AllWhitespace covers trimming a string that is entirely whitespace.
func TestStringsTrim_AllWhitespace(t *testing.T) {
	got := strings.TrimSpace("  \t\r\n  ")
	if got != "" {
		t.Fatalf("expected empty, got %q", got)
	}
}

// TestStringsTrim_LeadingAndTrailing covers trimming from both ends.
func TestStringsTrim_LeadingAndTrailing(t *testing.T) {
	got := strings.TrimSpace("  abc  ")
	if got != "abc" {
		t.Fatalf("expected %q, got %q", "abc", got)
	}
}

// TestStringsTrim_Empty covers the empty string edge case.
func TestStringsTrim_Empty(t *testing.T) {
	got := strings.TrimSpace("")
	if got != "" {
		t.Fatalf("expected empty, got %q", got)
	}
}

// TestUpdate_CorruptFile covers the branch where the existing stats file has
// invalid JSON or a wrong version, forcing a reset.
func TestUpdate_CorruptFile(t *testing.T) {
	dir := t.TempDir()
	t.Setenv("XDG_CACHE_HOME", dir)
	SetWindow(1 * time.Minute)

	// Write a corrupt stats file.
	statsDir := filepath.Join(dir, "hexai")
	if err := os.MkdirAll(statsDir, 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(statsDir, fileName), []byte("{invalid json"), 0o644); err != nil {
		t.Fatal(err)
	}

	// Update should still succeed: the corrupt file is discarded.
	if err := Update(context.Background(), "p", "m", 5, 5); err != nil {
		t.Fatalf("update after corrupt file: %v", err)
	}
	snap, err := TakeSnapshot()
	if err != nil {
		t.Fatal(err)
	}
	if snap.Global.Reqs != 1 {
		t.Fatalf("expected 1 req, got %d", snap.Global.Reqs)
	}
}

// TestUpdate_WrongVersion covers the branch where the file version does not
// match fileVersion, causing a reset of the file structure.
func TestUpdate_WrongVersion(t *testing.T) {
	dir := t.TempDir()
	t.Setenv("XDG_CACHE_HOME", dir)
	SetWindow(1 * time.Minute)

	statsDir := filepath.Join(dir, "hexai")
	if err := os.MkdirAll(statsDir, 0o755); err != nil {
		t.Fatal(err)
	}
	// Write a valid JSON file but with version=99 (wrong).
	wrongVer := File{Version: 99, Events: []Event{{TS: time.Now(), Provider: "old", Model: "old", Sent: 100, Recv: 100}}}
	b, _ := json.Marshal(wrongVer)
	if err := os.WriteFile(filepath.Join(statsDir, fileName), b, 0o644); err != nil {
		t.Fatal(err)
	}

	if err := Update(context.Background(), "p", "m", 1, 1); err != nil {
		t.Fatalf("update: %v", err)
	}
	snap, err := TakeSnapshot()
	if err != nil {
		t.Fatal(err)
	}
	// The old event from version 99 should be discarded.
	if snap.Global.Reqs != 1 {
		t.Fatalf("expected 1 req after version reset, got %d", snap.Global.Reqs)
	}
}

// TestTakeSnapshot_NoFile covers the ErrNotExist branch in TakeSnapshot.
func TestTakeSnapshot_NoFile(t *testing.T) {
	dir := t.TempDir()
	t.Setenv("XDG_CACHE_HOME", dir)
	SetWindow(5 * time.Minute)

	snap, err := TakeSnapshot()
	if err != nil {
		t.Fatal(err)
	}
	if snap.Global.Reqs != 0 {
		t.Fatalf("expected 0 reqs, got %d", snap.Global.Reqs)
	}
	if snap.Providers == nil {
		t.Fatal("expected non-nil Providers map")
	}
}

// TestTakeSnapshot_BadJSON covers the json.Unmarshal error branch in TakeSnapshot.
func TestTakeSnapshot_BadJSON(t *testing.T) {
	dir := t.TempDir()
	t.Setenv("XDG_CACHE_HOME", dir)

	statsDir := filepath.Join(dir, "hexai")
	if err := os.MkdirAll(statsDir, 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(statsDir, fileName), []byte("not json"), 0o644); err != nil {
		t.Fatal(err)
	}

	_, err := TakeSnapshot()
	if err == nil {
		t.Fatal("expected error for bad JSON, got nil")
	}
}

// TestTakeSnapshot_ZeroWindowSeconds covers the branch where the file has
// WindowSeconds <= 0, causing TakeSnapshot to use the process-level Window().
func TestTakeSnapshot_ZeroWindowSeconds(t *testing.T) {
	dir := t.TempDir()
	t.Setenv("XDG_CACHE_HOME", dir)
	SetWindow(5 * time.Minute)

	statsDir := filepath.Join(dir, "hexai")
	if err := os.MkdirAll(statsDir, 0o755); err != nil {
		t.Fatal(err)
	}
	sf := File{
		Version:       fileVersion,
		WindowSeconds: 0, // triggers the win <= 0 branch
		Events:        []Event{{TS: time.Now(), Provider: "p", Model: "m", Sent: 1, Recv: 1}},
	}
	b, _ := json.Marshal(sf)
	if err := os.WriteFile(filepath.Join(statsDir, fileName), b, 0o644); err != nil {
		t.Fatal(err)
	}

	snap, err := TakeSnapshot()
	if err != nil {
		t.Fatal(err)
	}
	if snap.Window != 5*time.Minute {
		t.Fatalf("expected 5m window fallback, got %v", snap.Window)
	}
	if snap.Global.Reqs != 1 {
		t.Fatalf("expected 1 req, got %d", snap.Global.Reqs)
	}
}

// TestUpdate_CancelledContext covers the context cancellation branch in
// acquireFileLock when the lock is already held.
func TestUpdate_CancelledContext(t *testing.T) {
	dir := t.TempDir()
	t.Setenv("XDG_CACHE_HOME", dir)
	SetWindow(1 * time.Minute)

	statsDir := filepath.Join(dir, "hexai")
	if err := os.MkdirAll(statsDir, 0o755); err != nil {
		t.Fatal(err)
	}

	// Hold the lock file to force acquireFileLock to spin.
	lockPath := filepath.Join(statsDir, lockFileName)
	lf, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600)
	if err != nil {
		t.Fatal(err)
	}
	defer func() { _ = lf.Close() }()
	unlock, err := acquireFileLock(context.Background(), lf)
	if err != nil {
		t.Fatal(err)
	}
	defer func() { _ = unlock() }()

	// Now try to Update with an already-cancelled context.
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	err = Update(ctx, "p", "m", 1, 1)
	if err == nil {
		t.Fatal("expected error from cancelled context, got nil")
	}
}

func TestSnapshot_ScopeReqs(t *testing.T) {
	snap := Snapshot{
		Providers: map[string]ProviderEntry{
			"openai": {Models: map[string]Counters{"gpt-5.0": {Reqs: 42}}},
		},
	}
	if got := snap.ScopeReqs("openai", "gpt-5.0"); got != 42 {
		t.Fatalf("expected 42, got %d", got)
	}
	if got := snap.ScopeReqs("openai", "gpt-4.1"); got != 0 {
		t.Fatalf("expected 0 for missing model, got %d", got)
	}
	if got := snap.ScopeReqs("anthropic", "gpt-5.0"); got != 0 {
		t.Fatalf("expected 0 for missing provider, got %d", got)
	}
}

func TestSnapshot_ScopeRPM(t *testing.T) {
	snap := Snapshot{
		Providers: map[string]ProviderEntry{
			"openai": {Models: map[string]Counters{"gpt-5.0": {Reqs: 60}}},
		},
		Window: time.Hour,
	}
	rpm := snap.ScopeRPM("openai", "gpt-5.0")
	if rpm != 1.0 {
		t.Fatalf("expected 1.0 rpm, got %v", rpm)
	}
	// Missing model should return 0
	if rpm := snap.ScopeRPM("openai", "missing"); rpm != 0 {
		t.Fatalf("expected 0 rpm for missing, got %v", rpm)
	}
}

func TestSnapshot_ScopeRPM_ZeroWindow(t *testing.T) {
	snap := Snapshot{
		Providers: map[string]ProviderEntry{
			"openai": {Models: map[string]Counters{"gpt-5.0": {Reqs: 10}}},
		},
		Window: 0, // edge case
	}
	rpm := snap.ScopeRPM("openai", "gpt-5.0")
	if rpm <= 0 {
		t.Fatalf("expected positive rpm even with zero window, got %v", rpm)
	}
}