-
Notifications
You must be signed in to change notification settings - Fork 498
Expand file tree
/
Copy pathsession_stats_test.go
More file actions
2679 lines (2448 loc) · 92.2 KB
/
Copy pathsession_stats_test.go
File metadata and controls
2679 lines (2448 loc) · 92.2 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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package db
import (
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.kenn.io/agentsview/internal/money"
)
// itoa is a thin alias for strconv.Itoa kept short so seedModelMessages'
// inline JSON construction stays readable.
func itoa(n int) string { return strconv.Itoa(n) }
// sessionFixture is a compact description of a seeded session used by
// session-stats tests. Fields mirror the subset of sessions-table
// columns the stats pipeline actually reads; extend in future tasks.
type sessionFixture struct {
id string
project string
agent string
userMsgs int
messageCount int
startedAt string // RFC3339; required to place row in window
endedAt string // RFC3339 or ""
// durationMin, when > 0 and endedAt is empty, derives endedAt as
// startedAt + durationMin minutes. Ignored if endedAt is set.
durationMin float64
peakContext int
hasPeakContext bool
totalOutputTok int
hasTotalOutputToks bool
isAutomated bool
relationshipType string
// totalToolCalls seeds that many rows in the tool_calls table for
// this session, each attached to a synthetic assistant message.
totalToolCalls int
// assistantTurns seeds that many assistant-role messages for this
// session. Set alongside totalToolCalls so tests can control the
// tools_per_turn denominator precisely.
assistantTurns int
// cwd is the working directory recorded on the session. Consumed by
// outcome_stats tests that exercise git-repo discovery.
cwd string
}
// hoursAgo returns an RFC3339 timestamp N hours before now in UTC.
// Used to place fixture rows safely inside the default 28-day window.
func hoursAgo(n int) string {
return time.Now().UTC().Add(-time.Duration(n) * time.Hour).
Format(time.RFC3339)
}
func Test_insertSessionFixture_isAutomated_patch(t *testing.T) {
d := testDB(t)
insertSessionFixture(t, d, sessionFixture{
id: "auto-1", userMsgs: 5, startedAt: hoursAgo(1),
isAutomated: true,
})
insertSessionFixture(t, d, sessionFixture{
id: "human-1", userMsgs: 1, startedAt: hoursAgo(1),
isAutomated: false,
})
var autoFlag, humanFlag int
require.NoError(t, d.getReader().QueryRow(
"SELECT is_automated FROM sessions WHERE id = ?", "auto-1",
).Scan(&autoFlag), "read auto-1")
require.NoError(t, d.getReader().QueryRow(
"SELECT is_automated FROM sessions WHERE id = ?", "human-1",
).Scan(&humanFlag), "read human-1")
require.Equal(t, 1, autoFlag, "auto-1 is_automated")
require.Equal(t, 0, humanFlag, "human-1 is_automated")
}
func Test_loadSessionsInWindow_isAutomated(t *testing.T) {
d := testDB(t)
insertSessionFixture(t, d, sessionFixture{
id: "auto", userMsgs: 5, startedAt: hoursAgo(1),
isAutomated: true,
})
insertSessionFixture(t, d, sessionFixture{
id: "human", userMsgs: 1, startedAt: hoursAgo(1),
isAutomated: false,
})
ctx := t.Context()
from := time.Now().Add(-24 * time.Hour)
to := time.Now().Add(1 * time.Hour)
rows, err := d.loadSessionsInWindow(ctx, StatsFilter{}, from, to, false)
require.NoError(t, err, "loadSessionsInWindow")
byID := map[string]bool{}
for _, r := range rows {
byID[r.id] = r.isAutomated
}
require.Equal(t, true, byID["auto"], "auto.isAutomated")
require.Equal(t, false, byID["human"], "human.isAutomated")
}
// insertSessionFixture inserts a sessionFixture via the standard
// UpsertSession path so triggers and defaults stay authoritative.
// Defaults mirror insertSession in db_test.go (machine=local,
// agent=claude) but let tests override agent/project.
func insertSessionFixture(t *testing.T, d *DB, f sessionFixture) {
t.Helper()
project := f.project
if project == "" {
project = "proj"
}
agent := f.agent
if agent == "" {
agent = defaultAgent
}
// message_count must be > 0 so analytics WHERE clauses don't skip
// the row; default to userMsgs*2 when not set explicitly.
mc := f.messageCount
if mc == 0 {
mc = f.userMsgs * 2
if mc == 0 {
mc = 1
}
}
endedAt := f.endedAt
if endedAt == "" && f.durationMin > 0 && f.startedAt != "" {
start, err := time.Parse(time.RFC3339, f.startedAt)
require.NoError(t, err,
"insertSessionFixture %s: parsing startedAt %q",
f.id, f.startedAt)
dur := time.Duration(f.durationMin * float64(time.Minute))
endedAt = start.Add(dur).UTC().Format(time.RFC3339Nano)
}
insertSession(t, d, f.id, project, func(s *Session) {
s.Agent = agent
s.UserMessageCount = f.userMsgs
s.MessageCount = mc
if f.startedAt != "" {
s.StartedAt = new(f.startedAt)
}
if endedAt != "" {
s.EndedAt = new(endedAt)
}
s.PeakContextTokens = f.peakContext
s.HasPeakContextTokens = f.hasPeakContext
s.TotalOutputTokens = f.totalOutputTok
// Flip has_total_output_tokens whenever the fixture supplies a
// non-zero token count; tests that explicitly want to leave the
// flag false can override via hasTotalOutputToks.
if f.hasTotalOutputToks || f.totalOutputTok > 0 {
s.HasTotalOutputTokens = true
}
s.IsAutomated = f.isAutomated
s.RelationshipType = f.relationshipType
s.Cwd = f.cwd
})
seedAssistantActivity(t, d, f.id, f.assistantTurns, f.totalToolCalls)
// UpsertSession recomputes is_automated from FirstMessage, so a
// fixture's f.isAutomated alone would be silently clobbered when
// no first message is set. Patch the column after the upsert so
// f.isAutomated is the authoritative value the stats pipeline
// reads. Test-only path; production ingest always flows through
// UpsertSession's classifier.
var want int
if f.isAutomated {
want = 1
}
_, err := d.getWriter().Exec(
"UPDATE sessions SET is_automated = ? WHERE id = ?",
want, f.id,
)
require.NoError(t, err,
"insertSessionFixture %s: patch is_automated", f.id)
}
// seedAssistantActivity inserts `turns` assistant messages and
// spreads `toolCalls` rows across them (or across a single synthetic
// message when turns==0 but toolCalls>0). Purpose: let stats tests
// control both the assistant-turn count (denominator of
// tools_per_turn) and the total tool-call count (numerator) without
// reaching into the full parser pipeline.
func seedAssistantActivity(
t *testing.T, d *DB, sessionID string, turns, toolCalls int,
) {
t.Helper()
if turns == 0 && toolCalls == 0 {
return
}
n := turns
if n == 0 {
n = 1 // need at least one host message for tool_calls FK
}
msgs := make([]Message, 0, n)
for i := range n {
msgs = append(msgs, asstMsg(sessionID, i+1, "reply"))
}
require.NoError(t, d.InsertMessages(msgs),
"seedAssistantActivity %s: InsertMessages", sessionID)
if toolCalls == 0 {
return
}
// Distribute tool_calls round-robin across inserted messages so
// they all attach to a real message row. Rely on the router-like
// INSERT ... SELECT ordinal to find the message_id.
for i := range toolCalls {
ord := (i % n) + 1
_, err := d.getWriter().Exec(`
INSERT INTO tool_calls
(message_id, session_id, tool_name, category)
SELECT id, session_id, 'Read', 'file'
FROM messages
WHERE session_id = ? AND ordinal = ?`,
sessionID, ord,
)
require.NoError(t, err,
"seedAssistantActivity %s: tool_call", sessionID)
}
}
// seedToolCallsByCategory inserts one assistant message per entry in
// categories and a matching tool_calls row. Used by tool_mix tests
// that need precise control over category values (unlike
// seedAssistantActivity, which always writes category='file').
func seedToolCallsByCategory(
t *testing.T, d *DB, sessionID string, categories []string,
) {
t.Helper()
if len(categories) == 0 {
return
}
msgs := make([]Message, 0, len(categories))
for i, cat := range categories {
msgs = append(msgs, asstMsg(sessionID, i+1, "reply-"+cat))
}
require.NoError(t, d.InsertMessages(msgs),
"seedToolCallsByCategory %s: InsertMessages", sessionID)
for i, cat := range categories {
ord := i + 1
_, err := d.getWriter().Exec(`
INSERT INTO tool_calls
(message_id, session_id, tool_name, category)
SELECT id, session_id, ?, ?
FROM messages
WHERE session_id = ? AND ordinal = ?`,
cat, cat, sessionID, ord,
)
require.NoError(t, err,
"seedToolCallsByCategory %s: %q", sessionID, cat)
}
}
// seedModelMessages inserts one assistant message per (model, tokens)
// pair so the model_mix query sees a stable per-message row with known
// output_tokens. Ordinals are taken relative to startOrd so callers can
// layer multiple seed passes onto the same session without colliding.
func seedModelMessages(
t *testing.T, d *DB, sessionID string, startOrd int,
pairs []struct {
model string
tokens int
},
) {
t.Helper()
if len(pairs) == 0 {
return
}
msgs := make([]Message, 0, len(pairs))
for i, p := range pairs {
m := asstMsg(sessionID, startOrd+i, "reply")
m.Model = p.model
m.OutputTokens = p.tokens
m.HasOutputTokens = true
// model_mix's eligibility filter (mirrors
// usageMessageEligibility) requires token_usage != ''. Stamp a
// minimal JSON blob so these fixtures qualify; the contents
// don't matter to model_mix, which sums output_tokens.
m.TokenUsage = json.RawMessage(
`{"output_tokens":` + itoa(p.tokens) + `}`,
)
msgs = append(msgs, m)
}
require.NoError(t, d.InsertMessages(msgs),
"seedModelMessages %s: InsertMessages", sessionID)
}
func TestSessionShapeLabel(t *testing.T) {
// Automation is decided upstream via sessions.is_automated; this
// helper classifies only non-automated sessions, so the lower band
// starts at 0 and includes userMsgs=1.
cases := []struct {
userMsgs int
want string
}{
{0, "quick"},
{1, "quick"},
{2, "quick"},
{5, "quick"},
{6, "standard"},
{15, "standard"},
{16, "deep"},
{50, "deep"},
{51, "marathon"},
{1000, "marathon"},
}
for _, c := range cases {
got := sessionShapeLabel(c.userMsgs)
assert.Equal(t, c.want, got,
"sessionShapeLabel(%d)", c.userMsgs)
}
}
func TestPickMaxLabel_TiesBreakByPriority(t *testing.T) {
// automation (2) vs deep (2) — priority says automation wins.
counts := map[string]int{"automation": 2, "deep": 2, "quick": 1}
priority := []string{
"automation", "marathon", "deep", "standard", "quick",
}
assert.Equal(t, "automation", pickMaxLabel(counts, priority),
"tie break")
// PrimaryHuman excludes automation; marathon should win a 1/1/1
// tie over deep/standard/quick.
humanCounts := map[string]int{
"quick": 1, "standard": 1, "deep": 1, "marathon": 1,
}
humanPriority := []string{"marathon", "deep", "standard", "quick"}
assert.Equal(t, "marathon",
pickMaxLabel(humanCounts, humanPriority),
"human tie break")
// Strictly greater wins regardless of priority.
c2 := map[string]int{"quick": 5, "deep": 2}
assert.Equal(t, "quick", pickMaxLabel(c2, priority),
"strict max")
}
func TestGetSessionStats_TotalsAndArchetypes(t *testing.T) {
d := testDB(t)
ctx := context.Background()
// 5 sessions: 2 automation (is_automated=true),
// 2 deep (userMsgs 20, 40),
// 1 marathon (userMsgs 100).
// Automation is now authoritative via sessions.is_automated; the
// two short rows carry the flag so they flow through the automation
// branch regardless of user_message_count.
fixtures := []sessionFixture{
{id: "s1", userMsgs: 0, startedAt: hoursAgo(5), isAutomated: true},
{id: "s2", userMsgs: 1, startedAt: hoursAgo(5), isAutomated: true},
{id: "s3", userMsgs: 20, startedAt: hoursAgo(5)},
{id: "s4", userMsgs: 40, startedAt: hoursAgo(5)},
{id: "s5", userMsgs: 100, startedAt: hoursAgo(5)},
}
for _, f := range fixtures {
insertSessionFixture(t, d, f)
}
stats, err := d.GetSessionStats(ctx, StatsFilter{Since: "28d"})
require.NoError(t, err, "GetSessionStats")
assert.Equal(t, 2, stats.SchemaVersion, "schema_version: got")
assert.Equal(t, 5, stats.Totals.SessionsAll, "sessions_all")
assert.Equal(t, 2, stats.Totals.SessionsAutomation,
"sessions_automation")
assert.Equal(t, 3, stats.Totals.SessionsHuman, "sessions_human")
// Invariant: human + automation + subagent must equal all. This
// fixture has no subagents, so subagent is 0 and the partition still
// reduces to human + automation.
assert.Equal(t, 0, stats.Totals.SessionsSubagent,
"sessions_subagent (no subagents seeded)")
assert.Equal(t, stats.Totals.SessionsAll,
stats.Totals.SessionsHuman+stats.Totals.SessionsAutomation+
stats.Totals.SessionsSubagent,
"invariant: human (%d) + automation (%d) + subagent (%d) != all (%d)",
stats.Totals.SessionsHuman,
stats.Totals.SessionsAutomation,
stats.Totals.SessionsSubagent,
stats.Totals.SessionsAll)
assert.Equal(t, 161, stats.Totals.UserMessagesTotal,
"user_messages_total")
assert.Equal(t, 2, stats.Archetypes.Automation,
"archetypes.automation")
assert.Equal(t, 0, stats.Archetypes.Quick, "archetypes.quick")
assert.Equal(t, 0, stats.Archetypes.Standard,
"archetypes.standard")
assert.Equal(t, 2, stats.Archetypes.Deep, "archetypes.deep")
assert.Equal(t, 1, stats.Archetypes.Marathon,
"archetypes.marathon")
// 2 automation, 2 deep — tie broken by priority: automation first.
assert.Equal(t, "automation", stats.Archetypes.Primary,
"archetypes.primary")
// Human subset: 2 deep, 1 marathon. Deep wins.
assert.Equal(t, "deep", stats.Archetypes.PrimaryHuman,
"archetypes.primary_human")
// Window bookkeeping: Since = now-28d, Until = now, days = 28.
assert.Equal(t, 28, stats.Window.Days, "window.days: got")
assert.NotEmpty(t, stats.Window.Since,
"window.since (until=%q)", stats.Window.Until)
assert.NotEmpty(t, stats.Window.Until,
"window.until (since=%q)", stats.Window.Since)
_, errSince := time.Parse(time.RFC3339, stats.Window.Since)
assert.NoError(t, errSince, "window.since not RFC3339")
_, errUntil := time.Parse(time.RFC3339, stats.Window.Until)
assert.NoError(t, errUntil, "window.until not RFC3339")
// Filters echo the inputs and default Agent to "all".
assert.Equal(t, "all", stats.Filters.Agent, "filters.agent")
assert.Equal(t, "UTC", stats.Filters.Timezone,
"filters.timezone")
assert.NotNil(t, stats.Filters.ProjectsExcluded,
"filters.projects_excluded must be non-nil slice")
assert.NotEmpty(t, stats.GeneratedAt, "generated_at")
}
// TestGetSessionStats_SubagentTotals verifies the two-bucket split in
// the stats pipeline: subagent sessions (e.g. workflow subagents) count
// toward the additive token/session totals, but stay out of the
// distribution and human-vs-automation breakdowns so their short,
// signal-less shape does not skew those. The subagent here is one-shot
// (userMsgs 1) and short, like a real workflow subagent.
func TestGetSessionStats_SubagentTotals(t *testing.T) {
d := testDB(t)
ctx := context.Background()
// One multi-turn root session (10 user msgs, 20 messages, ~100 min,
// 1000 output tokens) and one one-shot subagent (1 user msg, 5
// messages, ~8 min, 400 output tokens). Both agent "claude" so the
// agent-portfolio assertions reconcile against the totals.
insertSessionFixture(t, d, sessionFixture{
id: "root", agent: "claude", userMsgs: 10, messageCount: 20,
startedAt: hoursAgo(5), durationMin: 100,
totalOutputTok: 1000, hasTotalOutputToks: true,
})
insertSessionFixture(t, d, sessionFixture{
id: "agent-x", agent: "claude", userMsgs: 1, messageCount: 5,
startedAt: hoursAgo(5), durationMin: 8,
totalOutputTok: 400, hasTotalOutputToks: true,
relationshipType: "subagent",
})
stats, err := d.GetSessionStats(ctx, StatsFilter{Since: "28d"})
require.NoError(t, err, "GetSessionStats")
// Additive totals include the subagent.
assert.Equal(t, 2, stats.Totals.SessionsAll, "sessions_all")
assert.Equal(t, 25, stats.Totals.MessagesTotal, "messages_total")
assert.Equal(t, 11, stats.Totals.UserMessagesTotal,
"user_messages_total")
// SessionsHuman stays root-only: a subagent is not a human session.
assert.Equal(t, 1, stats.Totals.SessionsHuman, "sessions_human")
assert.Equal(t, 0, stats.Totals.SessionsAutomation,
"sessions_automation")
// The subagent lands in its own bucket so the partition holds.
assert.Equal(t, 1, stats.Totals.SessionsSubagent, "sessions_subagent")
assert.Equal(t, stats.Totals.SessionsAll,
stats.Totals.SessionsHuman+stats.Totals.SessionsAutomation+
stats.Totals.SessionsSubagent,
"invariant: all == human + automation + subagent")
// Distributions stay root-only: only the root session is in the
// user-messages histogram, so its bucket counts sum to 1, not 2.
gotN := 0
for _, b := range stats.Distributions.UserMessages.ScopeAll.Buckets {
gotN += b.Count
}
assert.Equal(t, 1, gotN,
"user-messages distribution must exclude the subagent")
// Duration distribution likewise root-only (subagent's 8 min absent).
durN := 0
for _, b := range stats.Distributions.DurationMinutes.ScopeAll.Buckets {
durN += b.Count
}
assert.Equal(t, 1, durN,
"duration distribution must exclude the subagent")
// Agent portfolio all-session maps count the subagent so they
// reconcile with the inclusive totals; the _human maps stay
// root-only (a subagent is not human).
ap := stats.AgentPortfolio
assert.Equal(t, 2, ap.BySessions["claude"], "by_sessions counts subagent")
assert.Equal(t, 25, ap.ByMessages["claude"], "by_messages counts subagent")
assert.Equal(t, int64(1400), ap.ByTokens["claude"],
"by_tokens counts subagent spend (1000 + 400)")
assert.Equal(t, 1, ap.BySessionsHuman["claude"],
"by_sessions_human stays root-only")
assert.Equal(t, int64(1000), ap.ByTokensHuman["claude"],
"by_tokens_human excludes the subagent")
// Reconciliation: the all-session agent-portfolio sums must equal
// the (subagent-inclusive) totals. These would have caught the
// per-panel undercount.
sumSessions, sumMessages := 0, 0
for _, v := range ap.BySessions {
sumSessions += v
}
for _, v := range ap.ByMessages {
sumMessages += v
}
assert.Equal(t, stats.Totals.SessionsAll, sumSessions,
"sum(by_sessions) must equal sessions_all")
assert.Equal(t, stats.Totals.MessagesTotal, sumMessages,
"sum(by_messages) must equal messages_total")
}
func Test_computeTotalsAndArchetypes_flagAuthority(t *testing.T) {
d := testDB(t)
// Short non-automated session — must count as human, bucket as "quick".
insertSessionFixture(t, d, sessionFixture{
id: "short-human", userMsgs: 1, startedAt: hoursAgo(1),
isAutomated: false,
})
// Automated session — bucket as "automation" regardless of its
// userMsgs shape. userMsgs=7 is chosen so that under the old
// heuristic this row would have landed in "standard", making the
// Archetypes.Quick == 1 assertion a real regression guard: old
// code produces Quick=0, new code produces Quick=1 from the
// short-human fixture.
insertSessionFixture(t, d, sessionFixture{
id: "auto", userMsgs: 7, startedAt: hoursAgo(1),
isAutomated: true,
})
got, err := d.GetSessionStats(t.Context(), StatsFilter{Since: "1d"})
require.NoError(t, err, "GetSessionStats")
require.Equal(t, 1, got.Totals.SessionsHuman, "SessionsHuman")
require.Equal(t, 1, got.Totals.SessionsAutomation, "SessionsAutomation")
require.Equal(t, 1, got.Archetypes.Quick, "Archetypes.Quick")
require.Equal(t, 1, got.Archetypes.Automation, "Archetypes.Automation")
}
func TestGetSessionStats_FilterByAgent(t *testing.T) {
d := testDB(t)
ctx := context.Background()
insertSessionFixture(t, d, sessionFixture{
id: "c1", agent: "claude", userMsgs: 10,
startedAt: hoursAgo(3),
})
insertSessionFixture(t, d, sessionFixture{
id: "x1", agent: "codex", userMsgs: 10,
startedAt: hoursAgo(3),
})
all, err := d.GetSessionStats(ctx, StatsFilter{Since: "28d"})
require.NoError(t, err, "GetSessionStats all")
assert.Equal(t, 2, all.Totals.SessionsAll, "all agents")
onlyClaude, err := d.GetSessionStats(
ctx, StatsFilter{Since: "28d", Agent: "claude"},
)
require.NoError(t, err, "GetSessionStats claude")
assert.Equal(t, 1, onlyClaude.Totals.SessionsAll, "agent=claude")
assert.Equal(t, "claude", onlyClaude.Filters.Agent,
"agent filter echoed")
// Comma-separated agents with surrounding whitespace must match
// every listed agent; the CSV values are trimmed before filtering.
multi, err := d.GetSessionStats(
ctx, StatsFilter{Since: "28d", Agent: "claude, codex"},
)
require.NoError(t, err, "GetSessionStats multi-agent")
assert.Equal(t, 2, multi.Totals.SessionsAll,
"comma-separated agents with whitespace match both")
}
func TestGetSessionStats_FilterByProject(t *testing.T) {
d := testDB(t)
ctx := context.Background()
for i, p := range []string{"alpha", "alpha", "beta", "gamma"} {
insertSessionFixture(t, d, sessionFixture{
id: fmt.Sprintf("p%d", i),
project: p,
userMsgs: 10,
startedAt: hoursAgo(2),
})
}
includeAlpha, err := d.GetSessionStats(ctx, StatsFilter{
Since: "28d",
IncludeProjects: []string{"alpha"},
})
require.NoError(t, err, "include alpha")
assert.Equal(t, 2, includeAlpha.Totals.SessionsAll,
"include=alpha")
excludeAlpha, err := d.GetSessionStats(ctx, StatsFilter{
Since: "28d",
ExcludeProjects: []string{"alpha"},
})
require.NoError(t, err, "exclude alpha")
assert.Equal(t, 2, excludeAlpha.Totals.SessionsAll,
"exclude=alpha want 2 (beta + gamma)")
}
func TestWindowBounds(t *testing.T) {
// Fixed reference time so the tests are deterministic.
now := time.Date(2026, 4, 18, 12, 0, 0, 0, time.UTC)
t.Run("default 28d", func(t *testing.T) {
from, to, days, err := windowBounds(StatsFilter{}, now)
require.NoError(t, err, "windowBounds")
assert.Equal(t, 28, days, "days: got")
assert.True(t, to.Equal(now),
"until: got %v want %v", to, now)
wantFrom := now.Add(-28 * 24 * time.Hour)
assert.True(t, from.Equal(wantFrom),
"since: got %v want %v", from, wantFrom)
})
t.Run("Nd duration", func(t *testing.T) {
_, _, days, err := windowBounds(
StatsFilter{Since: "7d"}, now,
)
require.NoError(t, err, "windowBounds")
assert.Equal(t, 7, days, "days: got")
})
t.Run("Nh duration", func(t *testing.T) {
from, to, _, err := windowBounds(
StatsFilter{Since: "48h"}, now,
)
require.NoError(t, err, "windowBounds")
assert.Equal(t, 48*time.Hour, to.Sub(from), "span")
})
t.Run("bare date", func(t *testing.T) {
from, _, _, err := windowBounds(
StatsFilter{Since: "2026-04-01"}, now,
)
require.NoError(t, err, "windowBounds")
assert.Equal(t, 2026, from.Year(),
"since parsed: got %v want 2026-04-01", from)
assert.Equal(t, time.April, from.Month(),
"since parsed: got %v want 2026-04-01", from)
assert.Equal(t, 1, from.Day(),
"since parsed: got %v want 2026-04-01", from)
})
t.Run("invalid since", func(t *testing.T) {
_, _, _, err := windowBounds(
StatsFilter{Since: "bogus"}, now,
)
assert.Error(t, err, "expected error for invalid Since")
})
}
func TestParseWindowPoint(t *testing.T) {
now := time.Date(2026, 4, 18, 12, 0, 0, 0, time.UTC)
tests := []struct {
name string
in string
want time.Time
wantErrSubstring string
}{
{name: "Nd duration anchors at now", in: "7d",
want: time.Date(2026, 4, 11, 12, 0, 0, 0, time.UTC)},
{name: "Nh duration", in: "48h",
want: time.Date(2026, 4, 16, 12, 0, 0, 0, time.UTC)},
{name: "bare date is start of UTC day", in: "2026-04-01",
want: time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC)},
{name: "garbage is a hard error", in: "7x",
wantErrSubstring: "Nd, Nh, or YYYY-MM-DD"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, err := ParseWindowPoint(tc.in, now)
if tc.wantErrSubstring != "" {
require.Error(t, err, "expected an error")
assert.Contains(t, err.Error(), tc.wantErrSubstring)
return
}
require.NoError(t, err)
assert.True(t, got.Equal(tc.want), "got %v want %v", got, tc.want)
})
}
}
func TestGetSessionStats_Distributions(t *testing.T) {
d := testDB(t)
ctx := context.Background()
// Seven sessions chosen to place rows in each interesting bucket
// for duration and peak_context. is_automated drives the scope_human
// filter: a,b,g → automation (isAutomated=true); c,d,e,f → human.
// f is intentionally a short non-automated session: duration scope_human
// includes it, while user_messages scope_human filters values below 2.
// g is intentionally multi-turn automation so scope_human excludes it.
fixtures := []struct {
id string
userMsgs int
peakCtx int
durMin float64
toolCalls int
assistantTurns int
isAutomated bool
}{
{"a", 0, 2_000, 0.5, 0, 0, true},
{"b", 1, 8_000, 0.9, 1, 1, true},
{"c", 3, 25_000, 10.0, 6, 3, false},
{"d", 10, 60_000, 25.0, 15, 10, false},
{"e", 30, 150_000, 120.0, 30, 30, false},
{"f", 1, 12_000, 3.0, 0, 0, false},
{"g", 4, 75_000, 30.0, 0, 0, true},
}
for _, f := range fixtures {
insertSessionFixture(t, d, sessionFixture{
id: f.id,
agent: "claude",
userMsgs: f.userMsgs,
peakContext: f.peakCtx,
hasPeakContext: true,
durationMin: f.durMin,
startedAt: hoursAgo(10),
totalToolCalls: f.toolCalls,
assistantTurns: f.assistantTurns,
isAutomated: f.isAutomated,
})
}
stats, err := d.GetSessionStats(ctx, StatsFilter{Since: "28d"})
require.NoError(t, err, "GetSessionStats")
// duration scope_all: 0.5→bucket0, 0.9→bucket0, 3→bucket1,
// 10→bucket2, 25/30→bucket3, 120→bucket5 (top).
gotAll := stats.Distributions.DurationMinutes.ScopeAll.Buckets
wantCountsAll := []int{2, 1, 1, 2, 0, 1}
require.Len(t, gotAll, len(wantCountsAll),
"duration scope_all buckets")
for i, w := range wantCountsAll {
assert.Equal(t, w, gotAll[i].Count,
"duration scope_all bucket %d", i)
}
// duration scope_human (c,d,e,f): bucket1=1, bucket2=1,
// bucket3=1, bucket5=1.
gotHuman := stats.Distributions.DurationMinutes.ScopeHuman.Buckets
wantCountsHuman := []int{0, 1, 1, 1, 0, 1}
require.Len(t, gotHuman, len(wantCountsHuman),
"duration scope_human buckets")
for i, w := range wantCountsHuman {
assert.Equal(t, w, gotHuman[i].Count,
"duration scope_human bucket %d", i)
}
// Means (arithmetic over included sessions).
wantAllMean := (0.5 + 0.9 + 10 + 25 + 120 + 3 + 30) / 7.0
gotAllMean := stats.Distributions.DurationMinutes.ScopeAll.Mean
assert.InDelta(t, wantAllMean, gotAllMean, 0.01,
"duration scope_all mean")
wantHumanMean := (10.0 + 25.0 + 120.0 + 3.0) / 4.0
gotHumanMean := stats.Distributions.DurationMinutes.ScopeHuman.Mean
assert.InDelta(t, wantHumanMean, gotHumanMean, 0.01,
"duration scope_human mean")
// user_messages scope_all uses userMessagesEdgesAll
// ([0,2),[2,6),[6,16),[16,31),[31,51),[51,inf)):
// 0→0, 1→0, 3→1, 10→2, 30→3, 1→0, 4→1.
gotUM := stats.Distributions.UserMessages.ScopeAll.Buckets
wantUM := []int{3, 2, 1, 1, 0, 0}
require.Len(t, gotUM, len(wantUM),
"user_messages scope_all buckets")
for i, w := range wantUM {
assert.Equal(t, w, gotUM[i].Count,
"user_messages scope_all bucket %d", i)
}
// user_messages scope_human uses userMessagesEdgesHuman (5 buckets,
// dropping the automation band): 3→0, 10→1, 30→2. The short
// non-automated session with userMsgs=1 is filtered out before
// mean and bucket accumulation.
gotUMH := stats.Distributions.UserMessages.ScopeHuman.Buckets
wantUMH := []int{1, 1, 1, 0, 0}
require.Len(t, gotUMH, len(wantUMH),
"user_messages scope_human buckets")
for i, w := range wantUMH {
assert.Equal(t, w, gotUMH[i].Count,
"user_messages scope_human bucket %d", i)
}
assert.InDelta(t, (3.0+10.0+30.0)/3.0,
stats.Distributions.UserMessages.ScopeHuman.Mean, 0.01,
"user_messages scope_human mean filters values below 2")
// peak_context scope_all: 2k/8k→0, 12k/25k→1,
// 60k/75k→2, 150k→4.
gotPCAll := stats.Distributions.PeakContextTokens.ScopeAll.Buckets
wantPCAll := []int{2, 2, 2, 0, 1, 0}
for i, w := range wantPCAll {
assert.Equal(t, w, gotPCAll[i].Count,
"peak_context scope_all bucket %d", i)
}
// peak_context scope_human (c,d,e,f): 12k/25k→1,
// 60k→2, 150k→4.
gotPC := stats.Distributions.PeakContextTokens.ScopeHuman.Buckets
assert.Equal(t, 2, gotPC[1].Count,
"peak_context scope_human: %+v", gotPC)
assert.Equal(t, 1, gotPC[2].Count,
"peak_context scope_human: %+v", gotPC)
assert.Equal(t, 1, gotPC[4].Count,
"peak_context scope_human: %+v", gotPC)
assert.False(t, stats.Distributions.PeakContextTokens.ClaudeOnly,
"peak_context.claude_only is always false since #646")
assert.Equal(t, 0,
stats.Distributions.PeakContextTokens.NullCount,
"peak_context.null_count")
// tools_per_turn: a skipped (assistantTurns==0),
// b=1/1=1, c=6/3=2, d=15/10=1.5, e=30/30=1.
// toolsPerTurnEdges = [0,1,2,4,7,11,+Inf].
gotTPT := stats.Distributions.ToolsPerTurn.ScopeAll.Buckets
wantTPT := []int{0, 3, 1, 0, 0, 0}
require.Len(t, gotTPT, len(wantTPT),
"tools_per_turn scope_all buckets")
for i, w := range wantTPT {
assert.Equal(t, w, gotTPT[i].Count,
"tools_per_turn scope_all bucket %d", i)
}
}
func TestGetSessionStats_Distributions_NullPeakContext(t *testing.T) {
d := testDB(t)
ctx := context.Background()
// One Claude session lacks peak-context data; it must land in
// NullCount rather than any peak_context bucket (including bucket 0).
insertSessionFixture(t, d, sessionFixture{
id: "np1", agent: "claude", userMsgs: 5,
startedAt: hoursAgo(5),
durationMin: 3.0,
// peakContext left at zero value AND hasPeakContext=false
})
insertSessionFixture(t, d, sessionFixture{
id: "wp1", agent: "claude", userMsgs: 5,
startedAt: hoursAgo(5),
durationMin: 3.0,
peakContext: 20_000,
hasPeakContext: true,
})
// Session from an agent that never reports peak context in this
// window must NOT increment NullCount: such agents are outside the
// metric entirely, only data-less rows of peak-context-reporting
// agents tally as null (#646).
insertSessionFixture(t, d, sessionFixture{
id: "cx1", agent: "codex", userMsgs: 5,
startedAt: hoursAgo(5),
durationMin: 3.0,
// hasPeakContext left at false
})
stats, err := d.GetSessionStats(ctx, StatsFilter{Since: "28d"})
require.NoError(t, err, "GetSessionStats")
pc := stats.Distributions.PeakContextTokens
assert.Equal(t, 1, pc.NullCount,
"null_count want 1 (only np1; codex cx1 must not count)")
total := 0
for _, b := range pc.ScopeAll.Buckets {
total += b.Count
}
assert.Equal(t, 1, total,
"scope_all bucket total want 1 "+
"(the one Claude session with hasPeakContext=true)")
}
func TestGetSessionStats_Distributions_PeakContextNonClaude(t *testing.T) {
d := testDB(t)
ctx := context.Background()
// Regression for #646: hermes (and kimi/forge/zed) sessions carry
// peak_context_tokens, but the distribution only counted rows with
// agent == "claude" — an agent-filtered stats run reported all-zero
// buckets despite has_peak_context_tokens being true on every row.
insertSessionFixture(t, d, sessionFixture{
id: "h1", agent: "hermes", userMsgs: 5,
startedAt: hoursAgo(5),
durationMin: 3.0,
peakContext: 25_000,
hasPeakContext: true,
})
insertSessionFixture(t, d, sessionFixture{
id: "h2", agent: "hermes", userMsgs: 5,
startedAt: hoursAgo(5),
durationMin: 3.0,
peakContext: 120_000,
hasPeakContext: true,
})
// A hermes row without the data lands in NullCount, because hermes
// demonstrably reports the metric in this window.
insertSessionFixture(t, d, sessionFixture{
id: "h3", agent: "hermes", userMsgs: 5,
startedAt: hoursAgo(5),
durationMin: 3.0,
// hasPeakContext left at false
})
stats, err := d.GetSessionStats(ctx, StatsFilter{Since: "28d", Agent: "hermes"})
require.NoError(t, err, "GetSessionStats")
pc := stats.Distributions.PeakContextTokens
total := 0
for _, b := range pc.ScopeAll.Buckets {
total += b.Count
}
assert.Equal(t, 2, total,
"scope_all bucket total want 2 (both hermes rows with data): %+v",
pc.ScopeAll.Buckets)
// peakContextEdges: 25k → [10k,50k) bucket 1; 120k → [100k,150k) bucket 3.
assert.Equal(t, 1, pc.ScopeAll.Buckets[1].Count,
"25k hermes session in bucket 1: %+v", pc.ScopeAll.Buckets)
assert.Equal(t, 1, pc.ScopeAll.Buckets[3].Count,
"120k hermes session in bucket 3: %+v", pc.ScopeAll.Buckets)
assert.InDelta(t, (25_000.0+120_000.0)/2.0, pc.ScopeAll.Mean, 0.01,
"scope_all mean over the two hermes rows with data")
assert.Equal(t, 1, pc.NullCount,
"null_count want 1 (h3: hermes reports the metric, h3 lacks it)")
assert.False(t, pc.ClaudeOnly, "claude_only must be false")
}
// seedVelocityMessages inserts len(offsetsSec) messages for sessionID,
// alternating user/assistant starting at role[0], with timestamps at
// startedAt+offsetsSec[i]. Used by velocity tests that need precise
// intervals between adjacent messages. Returns nothing; panics via t
// on any insert error.
func seedVelocityMessages(
t *testing.T, d *DB, sessionID, startedAt string,
offsetsSec []int,
) {
t.Helper()
start, err := time.Parse(time.RFC3339, startedAt)
require.NoError(t, err,
"seedVelocityMessages %s: parse startedAt %q",
sessionID, startedAt)
msgs := make([]Message, 0, len(offsetsSec))
for i, off := range offsetsSec {
role := "user"
if i%2 == 1 {
role = "assistant"
}
ts := start.Add(time.Duration(off) * time.Second).
UTC().Format(time.RFC3339)
msgs = append(msgs, Message{
SessionID: sessionID,
Ordinal: i,
Role: role,
Content: fmt.Sprintf("m%d", i),
ContentLength: 5,
Timestamp: ts,
})
}
require.NoError(t, d.InsertMessages(msgs),
"seedVelocityMessages %s: InsertMessages", sessionID)
}
func TestGetSessionStats_Velocity(t *testing.T) {
d := testDB(t)
ctx := context.Background()
// Two sessions with carefully chosen per-message gaps so the
// expected percentile/mean/hourly values are determined.
//
// Session v1: 6 msgs at offsets 0,10,20,25,35,50 (seconds).
// Turn cycles (user→assistant): 10, 5, 15.
// First response: 10.
// Adjacent gaps: 10,10,5,10,15 = 50s active.
// Session v2: 4 msgs at offsets 0,30,60,80.
// Turn cycles: 30, 20.
// First response: 30.
// Adjacent gaps: 30,30,20 = 80s active.
//
// Combined: turn cycles=[5,10,15,20,30], first responses=[10,30],
// active seconds=130, messages=10.
start := time.Now().UTC().Add(-5 * time.Hour).
Format(time.RFC3339)
insertSessionFixture(t, d, sessionFixture{
id: "v1", agent: "claude", userMsgs: 3,
messageCount: 6, startedAt: start,
})
seedVelocityMessages(t, d, "v1", start,
[]int{0, 10, 20, 25, 35, 50})
insertSessionFixture(t, d, sessionFixture{
id: "v2", agent: "claude", userMsgs: 2,
messageCount: 4, startedAt: start,
})
seedVelocityMessages(t, d, "v2", start,
[]int{0, 30, 60, 80})
stats, err := d.GetSessionStats(ctx, StatsFilter{Since: "28d"})