From f193c3865f29892ae693d21f1b923bbb65a8ae72 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 29 Oct 2026 07:37:29 +0800 Subject: [PATCH] sessions: a stats share keeps its days and models in slices, not maps (#2278) statsOfRange made each session three maps per range on every poll (its models, the dates it counted and its per-date shares) and a list of the range's files first. A session has few models and few days, so they are small slices now, and the files are filtered as they are read. The output is the same: models are summed in name order and listed by tokens, then name, as before. Measured on mote (Usage stats polled every 5s with gateway feed, heap diff 120s to 200s, A/B against v0.1.1971 2f5548371, load 40 to 73): statsOfRange 870MB -> 417MB and statsReadAll 1578MB -> 1103MB per 80s, total 7787MB -> 6386MB, while this binary answered 33 rounds of polls to the other's 26. Peak RSS 1020 -> 976 MiB. CPU and latency are not comparable at that load. /api/sessions/stats?days=0/7/30 and /api/sessions/overview are byte for byte the same from both binaries on the bench's copy of real data (1.97MB, 156KB, 656KB, 21KB). Rebased onto fae438b4a (an agent change, no sessions files) and run again at this head, on mote: GOOS=linux/windows/darwin go vet -tags nogui ./internal/sessions/ ./internal/gui/ ./internal/agent/ ok; go test -count=1 ./internal/sessions/ ./internal/usageapi/ ok. Before the rebase, on magpie-desktop (wsl-run): go test -tags nogui -run 'Stat|Overview|Session' ./internal/gui/ ./internal/sessions/ ok. Not run: the full suite. --- internal/sessions/stats.go | 102 ++++++++++++++++++++----------------- 1 file changed, 56 insertions(+), 46 deletions(-) diff --git a/internal/sessions/stats.go b/internal/sessions/stats.go index a7a6f8936..cfd35f269 100644 --- a/internal/sessions/stats.go +++ b/internal/sessions/stats.go @@ -2,7 +2,6 @@ package sessions import ( "cmp" - "maps" "math" "slices" "sort" @@ -252,12 +251,6 @@ func statsOfRange(days int, today time.Time, files []file, copies map[string]str from = since.Format(time.DateOnly) } out := Stats{From: from, To: today.Format(time.DateOnly), Days: []Day{}, Sessions: []Summary{}, Keys: []string{}} - var want []file - for _, f := range files { - if !f.mod.Before(since) && (copies[f.key] == "" || copied[f.path] != nil) { - want = append(want, f) - } - } type uk struct{ date, agent, cwd, model string } type ak struct{ date, agent, cwd string } @@ -268,22 +261,32 @@ func statsOfRange(days int, today time.Time, files []file, copies map[string]str use := map[uk]Tokens{} act := map[ak]*act0{} dates := map[string]bool{} - // each session's share: its files' models and dates in range + // each session's share: its files' models and dates in range. A + // session has few of either, so they are slices, not maps: each poll + // made a session's maps for every session of every range (#2278) type dayShare struct { + date string + counted bool // something was said, spent or worked that day messages, output int tools map[string]int } + type modelShare struct { + model string + t Tokens + } type share struct { - models map[string]Tokens + models []modelShare active int64 - dates map[string]bool prompts, replies int tools, skills map[string]int skillLast map[string]string - perDate map[string]*dayShare + perDate []dayShare } shares := map[string]*share{} - for _, f := range want { + for _, f := range files { + if f.mod.Before(since) || (copies[f.key] != "" && copied[f.path] == nil) { + continue + } st := cache[f.path] if keeper := copies[f.key]; keeper != "" { st, f.key = copied[f.path], keeper @@ -330,29 +333,36 @@ func statsOfRange(days int, today time.Time, files []file, copies map[string]str sh := shares[f.key] if sh == nil { // tools and skills are made once a day has some: most - // sessions' days have none, and each poll made them for - // every session of every range (#2278) - sh = &share{models: map[string]Tokens{}, dates: map[string]bool{}, perDate: map[string]*dayShare{}} + // sessions' days have none + sh = &share{} shares[f.key] = sh } - pd := sh.perDate[date] - if pd == nil { - pd = &dayShare{} - sh.perDate[date] = pd + // a session's files mostly come in date order: look from the end + pi := len(sh.perDate) - 1 + for pi >= 0 && sh.perDate[pi].date != date { + pi-- } + if pi < 0 { + sh.perDate = append(sh.perDate, dayShare{date: date}) + pi = len(sh.perDate) - 1 + } + pd := &sh.perDate[pi] for model, t := range d.Models.all() { if !t.zero() { - u := sh.models[model] - u.add(t) - sh.models[model] = u - sh.dates[date] = true + mi := slices.IndexFunc(sh.models, func(m modelShare) bool { return m.model == model }) + if mi < 0 { + sh.models = append(sh.models, modelShare{model: model}) + mi = len(sh.models) - 1 + } + sh.models[mi].t.add(t) + pd.counted = true pd.output += t.Output } } sh.prompts += d.Prompts sh.replies += d.Replies if d.Prompts+d.Replies > 0 { - sh.dates[date] = true + pd.counted = true dates[date] = true } pd.messages += d.Prompts + d.Replies @@ -377,7 +387,7 @@ func statsOfRange(days int, today time.Time, files []file, copies map[string]str } if d.Active > 0 { sh.active += d.Active - sh.dates[date] = true + pd.counted = true } } } @@ -440,7 +450,7 @@ func statsOfRange(days int, today time.Time, files []file, copies map[string]str // more than its rows, and every copy it was grown through (#2278) out.Sessions = make([]Summary, 0, len(shares)) for key, sh := range shares { - if len(sh.dates) == 0 { + if !slices.ContainsFunc(sh.perDate, func(pd dayShare) bool { return pd.counted }) { continue } var s Session @@ -463,35 +473,35 @@ func statsOfRange(days int, today time.Time, files []file, copies map[string]str sum.ToolCalls += n } sum.perDay = make([]summaryDay, 0, len(sh.perDate)) - for date, pd := range sh.perDate { - if t, err := time.ParseInLocation(time.DateOnly, date, time.Local); err == nil { - sum.perDay = append(sum.perDay, summaryDay{day: int(math.Round(t.Sub(first).Hours() / 24)), messages: pd.messages, output: pd.output, tools: countsOf(pd.tools, nil)}) + for _, pd := range sh.perDate { + t, err := time.ParseInLocation(time.DateOnly, pd.date, time.Local) + if err != nil { + continue + } + // whole days, across a change of the clocks too + day := int(math.Round(t.Sub(first).Hours() / 24)) + sum.perDay = append(sum.perDay, summaryDay{day: day, messages: pd.messages, output: pd.output, tools: countsOf(pd.tools, nil)}) + if pd.counted { + sum.Days = append(sum.Days, day) } } slices.SortFunc(sum.perDay, func(a, b summaryDay) int { return cmp.Compare(a.day, b.day) }) // in the models' order, as assembleListed sums a session's cost - for _, model := range slices.Sorted(maps.Keys(sh.models)) { - t := sh.models[model] - sum.Tokens.add(t) - sum.Models = append(sum.Models, model) - if p := price(model); p != nil { - sum.Cost += p.At(0).CostSplit(t.Input, t.Output, t.CacheRead, t.CacheWrite, t.CacheWrite1h) + slices.SortFunc(sh.models, func(a, b modelShare) int { return cmp.Compare(a.model, b.model) }) + for _, m := range sh.models { + sum.Tokens.add(m.t) + if p := price(m.model); p != nil { + sum.Cost += p.At(0).CostSplit(m.t.Input, m.t.Output, m.t.CacheRead, m.t.CacheWrite, m.t.CacheWrite1h) } else { sum.Priced = false } } - sort.Slice(sum.Models, func(i, j int) bool { - a, b := sh.models[sum.Models[i]], sh.models[sum.Models[j]] - if a.Input+a.Output != b.Input+b.Output { - return a.Input+a.Output > b.Input+b.Output - } - return sum.Models[i] < sum.Models[j] + slices.SortStableFunc(sh.models, func(a, b modelShare) int { + return cmp.Compare(b.t.Input+b.t.Output, a.t.Input+a.t.Output) }) - for date := range sh.dates { - if t, err := time.ParseInLocation(time.DateOnly, date, time.Local); err == nil { - // whole days, across a change of the clocks too - sum.Days = append(sum.Days, int(math.Round(t.Sub(first).Hours()/24))) - } + sum.Models = make([]string, 0, len(sh.models)) + for _, m := range sh.models { + sum.Models = append(sum.Models, m.model) } sort.Ints(sum.Days) out.Sessions = append(out.Sessions, sum)