From 9cd4ef6a19163d8274bc2dec43ccf43ba13053ca Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 11 Nov 2026 09:30:45 +0800 Subject: [PATCH] sessions: an aliased range is named once per change, not on every 10 s read While the Sessions page is open, the GUI reads the 7, 30 and all-days ranges again every 10 s. Those ranges are kept (keptStats), so a read with nothing changed costs almost nothing, except when a model is counted under another name (a usage alias, or a shared group's spelled name). Then aliasStats copied every day's usage and every session's summary of each range on each read: ~5 MB a read for the owner's real history, which was then thrown away because nothing had changed. aliasKept keeps each range's aliased Stats with the kept Stats it came from and the names (provider.UsageNamesKey). When the kept Stats are the same slices and the names haven't changed, it returns the same answer. Kept Stats are never written, and MergeExternalStats copies before it writes, so the answer can be shared. The memo is dropped with the kept ranges (forgetKeptStats), so it never outlives them. UsageAliasKeyed reads settings once for both the alias and its key. Run: TestAliasedRangeMadeOncePerNames (new) passes. With the memo skipped it fails at "named again with nothing changed". With the key and source check removed it fails at "the old names' range given after the names changed". go test ./internal/sessions ./internal/provider ./internal/gui and GOOS=windows / GOOS=linux -tags nogui vet: ok at 328dc97e2 plus this change. Real account (mote, ~/r2278/acct, /api/sessions/stats polled every 10 s for days 0, 7 and 30, 4 minutes of alloc_space diffed): aliasStats 75.1 MB before (v0.1.3664 build), not in the profile after; everything allocated 519.7 -> 467.3 MB. Not tried: Windows and Linux runs (nothing here is per OS). --- internal/provider/usagealias.go | 19 ++++- internal/sessions/alias.go | 53 +++++++++++++ internal/sessions/alias_kept_test.go | 111 +++++++++++++++++++++++++++ internal/sessions/stats.go | 8 +- internal/sessions/stats_kept.go | 1 + 5 files changed, 185 insertions(+), 7 deletions(-) create mode 100644 internal/sessions/alias_kept_test.go diff --git a/internal/provider/usagealias.go b/internal/provider/usagealias.go index c3ed26091..d99284d35 100644 --- a/internal/provider/usagealias.go +++ b/internal/provider/usagealias.go @@ -170,7 +170,18 @@ func usageAliasesNow() map[string]string { // old session files. Read once before any usage lock; the returned function // reads no settings or providers. It is nil when no names need mapping. func UsageAlias() func(string) string { - alias, groups := usageAliasOf(usageAliasesNow()), usageGroupNames() + return usageAliasFrom(usageAliasesNow(), usageGroupNames()) +} + +// UsageAliasKeyed is UsageAlias and the UsageNamesKey of the names it was +// made from, from one read of them. +func UsageAliasKeyed() (func(string) string, string) { + aliases, groups := usageAliasesNow(), usageGroupNames() + return usageAliasFrom(aliases, groups), usageNamesKey(aliases, groups) +} + +func usageAliasFrom(aliases, groups map[string]string) func(string) string { + alias := usageAliasOf(aliases) if len(groups) == 0 { return alias } @@ -211,10 +222,12 @@ func usageGroupNames() map[string]string { // UsageNamesKey changes when an alias or a found group's public spelling does, // so a cached view never holds the names from before a catalog change. -func UsageNamesKey() string { +func UsageNamesKey() string { return usageNamesKey(usageAliasesNow(), usageGroupNames()) } + +func usageNamesKey(aliases, groups map[string]string) string { b, _ := json.Marshal(struct { Aliases, Groups map[string]string - }{usageAliasesNow(), usageGroupNames()}) + }{aliases, groups}) return string(b) } diff --git a/internal/sessions/alias.go b/internal/sessions/alias.go index 0706ea09b..1ce33ae61 100644 --- a/internal/sessions/alias.go +++ b/internal/sessions/alias.go @@ -3,6 +3,8 @@ package sessions import ( "slices" "sort" + "sync" + "unsafe" ) // A session's models are counted under the names the user gave them @@ -72,6 +74,57 @@ func aliasManaged(ms []Managed, alias func(string) string) { } } +// aliasedKept is each range's kept Stats as aliasStats last named them, +// and the names it was asked under. The Sessions page reads 7, 30 and +// every day again every 10 s, and each read copied every session's +// summary of every range when one model was aliased (~5 MB for a long +// history), to the same answer while nothing changed. +var aliasedKept struct { + sync.Mutex + m map[int]aliasedRange +} + +type aliasedRange struct { + names string + // src is held so that a new range is never taken for it by an + // address it gave back + src, st Stats +} + +// aliasKept is aliasStats of a range's kept Stats st, made once for st +// and the names (provider.UsageNamesKey). Kept Stats are never written, +// so the same slices are the same Stats. +func aliasKept(days int, st Stats, alias func(string) string, names string) Stats { + aliasedKept.Lock() + defer aliasedKept.Unlock() + if a, ok := aliasedKept.m[days]; ok && a.names == names && sameKept(a.src, st) { + return a.st + } + out := aliasStats(st, alias) + if aliasedKept.m == nil || len(aliasedKept.m) >= 2*keptRanges { + aliasedKept.m = map[int]aliasedRange{} + } + aliasedKept.m[days] = aliasedRange{names, st, out} + return out +} + +func forgetAliasedKept() { + aliasedKept.Lock() + aliasedKept.m = nil + aliasedKept.Unlock() +} + +// sameKept reports whether a and b are one kept Stats. +func sameKept(a, b Stats) bool { + return a.From == b.From && a.To == b.To && a.shift == b.shift && + sameSlice(a.Days, b.Days) && sameSlice(a.Sessions, b.Sessions) && + sameSlice(a.Keys, b.Keys) && sameSlice(a.gateway, b.gateway) +} + +func sameSlice[T any](a, b []T) bool { + return len(a) == len(b) && unsafe.SliceData(a) == unsafe.SliceData(b) +} + // aliasStats is st with each day's usage and each session's models counted // under their aliases. func aliasStats(st Stats, alias func(string) string) Stats { diff --git a/internal/sessions/alias_kept_test.go b/internal/sessions/alias_kept_test.go new file mode 100644 index 000000000..308c1bcd9 --- /dev/null +++ b/internal/sessions/alias_kept_test.go @@ -0,0 +1,111 @@ +package sessions + +import ( + "os" + "path/filepath" + "testing" + "time" + "unsafe" + + "github.com/yetone/magpie/internal/provider" +) + +// The Sessions page reads its ranges again every 10 s. While no file and +// no alias changed, an aliased range is the one made last time, not a new +// copy of every session's summary; a changed alias names them again. +func TestAliasedRangeMadeOncePerNames(t *testing.T) { + inZone(t, 0) + claude, _ := setup(t) + dir := filepath.Join(claude, "projects", "-work-alias") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + body := aliasMsg("m1", "claude-opus-5-5", "2026-09-25T10:00:00Z", 1000) + + aliasMsg("m2", "gpt-6-astra", "2026-09-25T10:01:00Z", 1000) + if err := os.WriteFile(filepath.Join(dir, "44444444-2222-3333-4444-555555555555.jsonl"), []byte(body), 0o600); err != nil { + t.Fatal(err) + } + if _, err := provider.SetUsageAlias("gpt-6-astra", "claude-opus-5-5"); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _, _ = provider.SetUsageAlias("gpt-6-astra", "") + _, _ = provider.SetUsageAlias("claude-opus-5-5", "") + }) + ranges := []int{0, 7} + read := func() []Stats { + t.Helper() + out, _ := StatsAndNativeAll(ranges) + if len(out[0].Sessions) == 0 || len(out[0].Days) == 0 { + t.Fatalf("nothing read: %+v", out[0]) + } + return out + } + models := func(st Stats) []string { + for _, d := range st.Days { + for _, u := range d.Usage { + if u.Cwd == "/work/alias" { + return append([]string(nil), u.Model) + } + } + } + return nil + } + same := func(a, b Stats) bool { + return unsafe.SliceData(a.Sessions) == unsafe.SliceData(b.Sessions) && unsafe.SliceData(a.Days) == unsafe.SliceData(b.Days) + } + first := read() + if m := models(first[0]); len(m) != 1 || m[0] != "claude-opus-5-5" { + t.Fatalf("aliased: %v", m) + } + again := read() + for i := range ranges { + if !same(first[i], again[i]) { + t.Fatalf("range %d named again with nothing changed", ranges[i]) + } + } + + // another name: made again, and it says what the names say now + if _, err := provider.SetUsageAlias("gpt-6-astra", ""); err != nil { + t.Fatal(err) + } + if _, err := provider.SetUsageAlias("claude-opus-5-5", "gpt-6-astra"); err != nil { + t.Fatal(err) + } + renamed := read() + if same(renamed[0], first[0]) { + t.Fatal("the old names' range given after the names changed") + } + var seen []string + for _, d := range renamed[0].Days { + for _, u := range d.Usage { + if u.Cwd == "/work/alias" { + seen = append(seen, u.Model) + } + } + } + if len(seen) != 1 || seen[0] != "gpt-6-astra" { + t.Fatalf("renamed: %v", seen) + } + + // a file changed: its range is read again and named again + if err := os.WriteFile(filepath.Join(dir, "44444444-2222-3333-4444-555555555555.jsonl"), []byte(body+aliasMsg("m3", "claude-opus-5-5", "2026-09-25T10:02:00Z", 1000)), 0o600); err != nil { + t.Fatal(err) + } + later := time.Now().Add(time.Minute) + if err := os.Chtimes(filepath.Join(dir, "44444444-2222-3333-4444-555555555555.jsonl"), later, later); err != nil { + t.Fatal(err) + } + grown := read() + var in int + for _, d := range grown[0].Days { + for _, u := range d.Usage { + if u.Cwd == "/work/alias" { + in += u.Input + } + } + } + if in != 3000 { + t.Fatalf("after the file grew: %d input tokens, want 3000", in) + } +} diff --git a/internal/sessions/stats.go b/internal/sessions/stats.go index 6920a142a..20aff16bf 100644 --- a/internal/sessions/stats.go +++ b/internal/sessions/stats.go @@ -210,11 +210,11 @@ func StatsAndNative(days int) (Stats, map[string]bool) { // are the same whatever the range, and the page keeps 7, 30 and every // day, each read again behind it (statsFor in internal/gui, #2278). func StatsAndNativeAll(days []int) ([]Stats, map[string]bool) { - alias := provider.UsageAlias() + alias, names := provider.UsageAliasKeyed() out, native := statsKept(days, time.Now(), true) if alias != nil { for i := range out { - out[i] = aliasStats(out[i], alias) + out[i] = aliasKept(days[i], out[i], alias, names) } } return out, native @@ -225,10 +225,10 @@ func statsAt(days int, now time.Time) Stats { return statsIn(days, now, nil) } // statsIn is statsAt, filling native as StatsAndNative says when not nil. func statsIn(days int, now time.Time, native map[string]bool) Stats { // read before the locks: it reads settings.json - alias := provider.UsageAlias() + alias, names := provider.UsageAliasKeyed() st := statsRead(days, now, native) if alias != nil { - st = aliasStats(st, alias) + st = aliasKept(days, st, alias, names) } return st } diff --git a/internal/sessions/stats_kept.go b/internal/sessions/stats_kept.go index 3d68d574f..7224683f5 100644 --- a/internal/sessions/stats_kept.go +++ b/internal/sessions/stats_kept.go @@ -203,6 +203,7 @@ func keepDesktop(st Stats) { func forgetKeptStats() { keptStats.files, keptStats.ranges, keptStats.native = nil, nil, nil keptStats.prices, keptStats.titles, keptStats.desktop = nil, titleAnswers{}, nil + forgetAliasedKept() } // ForgetKeptRanges lets go of the ranges' Stats kept for the next read,