From 3ec9babe7d207eba22ee57669054ef0351064028 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 29 Oct 2026 00:47:21 +0800 Subject: [PATCH] sessions: the overview points to the sessions it sums up, not copies (#2278) Stats.Overview copied every Summary (~400 bytes) into its working slice, then cloned that slice once per Top ranking. Over 34k sessions the Sessions page's poll allocated ~1.5 GB in two minutes this way while an agent worked (alloc profile of v0.1.1928 on mote: `in = append` 958 MB, slices.Clone 557 MB). It now ranks pointers into st.Sessions and copies only the k sessions each ranking keeps. shapes, toolUse and skillUse take the pointers. TestOverviewCopiesOnlyItsTop: a second Overview over 5000 sessions allocates at most half of their Summaries' size, and its count and rankings are what they were. Red on the old code (14,923,144 bytes over a 1,020,000 bar), green on the new. A/B on mote (34,040 session files, 240k-row usage.jsonl, the feed run of run2278c.sh: 230s, feed from 60s, Usage and Sessions pages polled), v0.1.1928 code vs this change. mote's load was 47 to 66 from other runs throughout, so the numbers are noisy: avg CPU after the feed starts 122.8% -> 69.4% heatmap poll mean 6.97s -> 4.84s all polls mean 3.11s -> 2.16s footprint peak 685.6M -> 626.1M footprint at the end 402.8M -> 337.5M Run on mote, at base b5d2858f4: go test -count=1 -timeout 45m ./internal/sessions/ ./internal/usage/ ok (30.9s, 18.0s) go test ./internal/gui/: FAIL only in TestMainWindowCorners, the open macOS 27 red #3949 Rebased onto origin/main 7a7931833 (no change to internal/sessions), and run again at the pushed head on mote: go test -count=1 -timeout 45m ./internal/sessions/ ./internal/usage/ ok (16.8s, 16.1s) GOOS=linux/windows/darwin go vet -tags nogui ./internal/sessions/ ./internal/usage/ ./internal/gui/ ok --- internal/sessions/overview_alloc_test.go | 30 ++++++++++++++++++++++ internal/sessions/stats.go | 32 +++++++++++++++--------- internal/sessions/stats_tools_test.go | 2 +- 3 files changed, 51 insertions(+), 13 deletions(-) create mode 100644 internal/sessions/overview_alloc_test.go diff --git a/internal/sessions/overview_alloc_test.go b/internal/sessions/overview_alloc_test.go new file mode 100644 index 000000000..9fef4db68 --- /dev/null +++ b/internal/sessions/overview_alloc_test.go @@ -0,0 +1,30 @@ +package sessions + +import ( + "fmt" + "runtime" + "testing" + "unsafe" +) + +// The overview points to the sessions it sums up and copies only the few +// it shows: the Sessions page's poll copied every Summary four times, ~1.5 +// GB in two minutes over 34k sessions while an agent worked (#2278). +func TestOverviewCopiesOnlyItsTop(t *testing.T) { + st := Stats{From: "2026-10-01", To: "2026-10-28"} + for i := range 5000 { + st.Sessions = append(st.Sessions, Summary{Key: fmt.Sprint("claude:", i), Agent: "claude", ID: fmt.Sprint(i), Tokens: Tokens{Input: i, Output: 1}, Cost: float64(i), Active: int64(i), Days: []int{i % 28}}) + } + st.Overview("", "", "", 8) // the maps' first growth + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + o := st.Overview("", "", "", 8) + runtime.ReadMemStats(&after) + if o.Count != 5000 || len(o.Top["tokens"]) != 8 || o.Top["tokens"][0].ID != "4999" || o.Top["cost"][7].ID != "4992" { + t.Fatalf("count %d, top %d, first %q", o.Count, len(o.Top["tokens"]), o.Top["tokens"][0].ID) + } + all := uint64(len(st.Sessions)) * uint64(unsafe.Sizeof(Summary{})) + if got := after.TotalAlloc - before.TotalAlloc; got > all/2 { + t.Fatalf("the overview allocated %d bytes; its sessions are %d", got, all) + } +} diff --git a/internal/sessions/stats.go b/internal/sessions/stats.go index 8cb9ed5d1..189bedf07 100644 --- a/internal/sessions/stats.go +++ b/internal/sessions/stats.go @@ -553,9 +553,13 @@ func (st Stats) Overview(agent, model, cwd string, n int) Overview { out.Days = make([]int, int(math.Round(last.Sub(first).Hours()/24))+1) } out.Messages, out.Output = make([]int, len(out.Days)), make([]int, len(out.Days)) - var in []Summary - var spent []int - for _, s := range st.Sessions { + // the sessions are pointed to, not copied: a Summary is ~400 bytes, and + // the Sessions page's poll copied all of them four times, ~1.5 GB in + // two minutes over 34k sessions while an agent worked (#2278) + in := make([]*Summary, 0, len(st.Sessions)) + spent := make([]int, 0, len(st.Sessions)) + for i := range st.Sessions { + s := &st.Sessions[i] if agent != "" && s.Agent != agent || cwd != "" && s.Cwd != cwd || model != "" && !slices.Contains(s.Models, model) { continue } @@ -583,25 +587,29 @@ func (st Stats) Overview(agent, model, cwd string, n int) Overview { rank := func(p float64) int { return spent[max(0, int(math.Ceil(p*float64(len(spent))))-1)] } out.Median, out.P90 = rank(0.5), rank(0.9) } - for by, v := range map[string]func(Summary) float64{ - "tokens": func(s Summary) float64 { return float64(s.Input + s.Output) }, - "cost": func(s Summary) float64 { return s.Cost }, - "active": func(s Summary) float64 { return float64(s.Active) }, + top := make([]*Summary, len(in)) + for by, v := range map[string]func(*Summary) float64{ + "tokens": func(s *Summary) float64 { return float64(s.Input + s.Output) }, + "cost": func(s *Summary) float64 { return s.Cost }, + "active": func(s *Summary) float64 { return float64(s.Active) }, } { - top := slices.Clone(in) + copy(top, in) sort.SliceStable(top, func(i, j int) bool { return v(top[i]) > v(top[j]) }) k := 0 for k < len(top) && k < n && v(top[k]) > 0 { k++ } - out.Top[by] = top[:k] + out.Top[by] = make([]Summary, k) + for i, s := range top[:k] { + out.Top[by][i] = *s + } } return out } // shapes buckets the sessions that told their messages, or for minutes // those that were at work. -func shapes(in []Summary) map[string]Shape { +func shapes(in []*Summary) map[string]Shape { out := map[string]Shape{} for by, edges := range shapeEdges { sh := Shape{Edges: edges, Counts: make([]int, len(edges))} @@ -636,7 +644,7 @@ func shapes(in []Summary) map[string]Shape { } // toolUse sums up the sessions' tool calls, the n most called. -func toolUse(in []Summary, first time.Time, n int) ToolUse { +func toolUse(in []*Summary, first time.Time, n int) ToolUse { out := ToolUse{Top: []ToolStat{}, Categories: []ToolStat{}, Weeks: []ToolWeek{}} tools, cats := map[string]*ToolStat{}, map[string]*ToolStat{} weeks := map[string]map[string]int{} @@ -701,7 +709,7 @@ func toolUse(in []Summary, first time.Time, n int) ToolUse { } // skillUse sums up the skills the sessions called up, the n most called. -func skillUse(in []Summary, n int) SkillUse { +func skillUse(in []*Summary, n int) SkillUse { out := SkillUse{Top: []Skill{}} skills := map[string]*Skill{} projects := map[string]map[string]int{} diff --git a/internal/sessions/stats_tools_test.go b/internal/sessions/stats_tools_test.go index fd92d3358..a449e3f46 100644 --- a/internal/sessions/stats_tools_test.go +++ b/internal/sessions/stats_tools_test.go @@ -112,7 +112,7 @@ func TestStatsToolsAndSkills(t *testing.T) { // TestShapesMinutesWithoutMessages: a session whose agent tells no messages // (pi, grok…) still counts by its minutes at work, and only there. func TestShapesMinutesWithoutMessages(t *testing.T) { - sh := shapes([]Summary{ + sh := shapes([]*Summary{ {Agent: "claude", Prompts: 2, Replies: 3, ToolCalls: 4, Active: 600}, {Agent: "pi", Active: 1200}, {Agent: "grok"},