diff --git a/internal/sessions/alias.go b/internal/sessions/alias.go index 1ce33ae61..a10212dab 100644 --- a/internal/sessions/alias.go +++ b/internal/sessions/alias.go @@ -3,8 +3,6 @@ package sessions import ( "slices" "sort" - "sync" - "unsafe" ) // A session's models are counted under the names the user gave them @@ -74,83 +72,20 @@ 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 +// aliasOwned counts st's days' usage and sessions' models under their +// aliases, in st's own slices: st was just made and is not kept yet. The +// Stats kept for the next read are kept as aliased (keptStats.names), so +// no read copies every session's summary of every range again: that copy +// was ~5 MB a long history held beside the unaliased one (#2278). +func aliasOwned(st *Stats, alias func(string) string) { + for i := range st.Days { + st.Days[i].Usage = aliasUsage(st.Days[i].Usage, alias) } - 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 { - changed := slices.ContainsFunc(st.Days, func(d Day) bool { - return slices.ContainsFunc(d.Usage, func(u Usage) bool { return alias(u.Model) != u.Model }) - }) || slices.ContainsFunc(st.Sessions, func(s Summary) bool { - return slices.ContainsFunc(s.Models, func(m string) bool { return alias(m) != m }) || - slices.ContainsFunc(s.ModelEffort, func(e ModelEffort) bool { return alias(e.Model) != e.Model }) - }) - if !changed { - return st - } - days := make([]Day, len(st.Days)) - for i, d := range st.Days { - d.Usage = aliasUsage(d.Usage, alias) - days[i] = d - } - st.Days = days - sums := make([]Summary, len(st.Sessions)) - for i, s := range st.Sessions { + for i := range st.Sessions { + s := &st.Sessions[i] s.Models = aliasNames(s.Models, alias) s.ModelEffort = aliasEffort(s.ModelEffort, alias) - sums[i] = s } - st.Sessions = sums - return st } // aliasUsage is a day's usage with the rows of one agent, folder and diff --git a/internal/sessions/alias_test.go b/internal/sessions/alias_test.go index 2f81af0e6..52cda040b 100644 --- a/internal/sessions/alias_test.go +++ b/internal/sessions/alias_test.go @@ -86,6 +86,11 @@ func TestSessionsCountAliasedModelsAsOne(t *testing.T) { t.Fatalf("aliased summary models: %v", sum.Models) } } + // the Stats kept for the next read are the aliased ones themselves: + // no second copy of every summary beside them (#2278) + if k, ok := keptStats.ranges[0]; !ok || len(k.Sessions) == 0 || &k.Sessions[0] != &st.Sessions[0] { + t.Fatalf("an aliased read keeps a copy of its summaries beside the kept ones") + } // what List and Stats keep for the next read is not changed: with the // alias gone, the next read has two rows again if _, err := provider.SetUsageAlias("gpt-6-astra", ""); err != nil { @@ -99,9 +104,9 @@ func TestSessionsCountAliasedModelsAsOne(t *testing.T) { } } -// Merging never writes into the slices it was given: a memo's copy stays -// as it was. -func TestAliasStatsLeavesItsInputAlone(t *testing.T) { +// Aliasing a Stats made for the read never writes into the slices its days +// and sessions were given: a memo's copy stays as it was. +func TestAliasOwnedLeavesSharedSlicesAlone(t *testing.T) { alias := provider.UsageAliasIn(map[string]string{"b-model": "a-model"}) in := Stats{ Days: []Day{{Date: "2026-09-25", Usage: []Usage{ @@ -114,7 +119,10 @@ func TestAliasStatsLeavesItsInputAlone(t *testing.T) { {Model: "b-model", Effort: "high", Tokens: Tokens{Input: 2}, Reasoning: 2, Cost: 2, Priced: true}, }}}, } - out := aliasStats(in, alias) + memo := Stats{Days: []Day{in.Days[0]}, Sessions: []Summary{in.Sessions[0]}} + out := in + aliasOwned(&out, alias) + in = memo u := out.Days[0].Usage if len(u) != 2 || u[0].Model != "a-model" || u[0].Input != 3 || u[0].Cost != 3 || u[0].Priced || u[1].Cwd != "/v" || u[1].Model != "a-model" { t.Fatalf("usage: %+v", u) diff --git a/internal/sessions/stats.go b/internal/sessions/stats.go index 20aff16bf..08c675941 100644 --- a/internal/sessions/stats.go +++ b/internal/sessions/stats.go @@ -211,13 +211,7 @@ func StatsAndNative(days int) (Stats, map[string]bool) { // day, each read again behind it (statsFor in internal/gui, #2278). func StatsAndNativeAll(days []int) ([]Stats, map[string]bool) { alias, names := provider.UsageAliasKeyed() - out, native := statsKept(days, time.Now(), true) - if alias != nil { - for i := range out { - out[i] = aliasKept(days[i], out[i], alias, names) - } - } - return out, native + return statsKept(days, time.Now(), true, alias, names) } func statsAt(days int, now time.Time) Stats { return statsIn(days, now, nil) } @@ -226,21 +220,18 @@ func statsAt(days int, now time.Time) Stats { return statsIn(days, now, nil) } func statsIn(days int, now time.Time, native map[string]bool) Stats { // read before the locks: it reads settings.json alias, names := provider.UsageAliasKeyed() - st := statsRead(days, now, native) - if alias != nil { - st = aliasKept(days, st, alias, names) - } - return st + return statsReadAll([]int{days}, now, native, alias, names)[0] } func statsRead(days int, now time.Time, native map[string]bool) Stats { - return statsReadAll([]int{days}, now, native)[0] + return statsReadAll([]int{days}, now, native, nil, "")[0] } // statsReadAll is statsRead for each of days, sharing what doesn't -// depend on the range. -func statsReadAll(ranges []int, now time.Time, native map[string]bool) []Stats { - out, listed := statsKept(ranges, now, native != nil) +// depend on the range, with the models counted under alias's names (none +// when nil), which names stands for (provider.UsageNamesKey). +func statsReadAll(ranges []int, now time.Time, native map[string]bool, alias func(string) string, names string) []Stats { + out, listed := statsKept(ranges, now, native != nil, alias, names) if native != nil { maps.Copy(native, listed) } @@ -248,9 +239,9 @@ func statsReadAll(ranges []int, now time.Time, native map[string]bool) []Stats { } // statsKept is statsReadAll, and the agent|id of every session listed when -// native is asked for. The ranges' Stats and the map are kept for the -// next read (keptStats), so neither is written. -func statsKept(ranges []int, now time.Time, wantNative bool) ([]Stats, map[string]bool) { +// native is asked for. The ranges' Stats, aliased, and the map are kept for +// the next read (keptStats), so neither is written. +func statsKept(ranges []int, now time.Time, wantNative bool, alias func(string) string, names string) ([]Stats, map[string]bool) { now = now.In(time.Local) today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local) @@ -265,7 +256,10 @@ func statsKept(ranges []int, now time.Time, wantNative bool) ([]Stats, map[strin // finds them read rather than starting another run refresh(files, files) price, titles := pricer(), codexTitleOf() - keptFor(files, today, price, titles) + if alias == nil { + names = "\x00none" + } + keptFor(files, today, names, price, titles) out := make([]Stats, len(ranges)) var todo []int for i, days := range ranges { @@ -317,6 +311,9 @@ func statsKept(ranges []int, now time.Time, wantNative bool) ([]Stats, map[strin for _, i := range todo { st := statsOfRange(ranges[i], today, files, copies, copied, folder, listed, identities, taskTitles, price, titles) keepDesktop(st) + if alias != nil { + aliasOwned(&st, alias) + } keepRange(ranges[i], st, ranges) out[i] = st } diff --git a/internal/sessions/stats_kept.go b/internal/sessions/stats_kept.go index 7224683f5..aa9ed7c36 100644 --- a/internal/sessions/stats_kept.go +++ b/internal/sessions/stats_kept.go @@ -15,9 +15,12 @@ import ( // again: ~1.1 GB a minute and a third, a fifth of all magpie allocated // (#2278). Guarded by mu. var keptStats struct { - files []keptFile - today time.Time - gen uint64 + files []keptFile + today time.Time + gen uint64 + // names are the aliases the ranges' models are counted under + // (provider.UsageNamesKey) + names string ranges map[int]Stats // native is every listed session's agent|id, nil when no read asked // for it; shared, so read only @@ -89,13 +92,13 @@ func keptFileOf(f file) keptFile { // keptFor reports whether the kept ranges were read from files as they // are now, today, with the prices and names they got still the same. When // they weren't, what was kept is let go. -func keptFor(files []file, today time.Time, price func(string) *catalog.Price, titles func(string) string) bool { +func keptFor(files []file, today time.Time, names string, price func(string) *catalog.Price, titles func(string) string) bool { k := &keptStats - same := k.ranges != nil && k.gen == cacheGeneration && k.today.Equal(today) && + same := k.ranges != nil && k.gen == cacheGeneration && k.today.Equal(today) && k.names == names && keptStill(k.files, files, k.prices, &k.titles, k.desktop, price, titles) if !same { forgetKeptStats() - k.files, k.today, k.gen = make([]keptFile, len(files)), today, cacheGeneration + k.files, k.today, k.gen, k.names = make([]keptFile, len(files)), today, cacheGeneration, names for i, f := range files { k.files[i] = keptFileOf(f) } @@ -203,7 +206,6 @@ 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, diff --git a/internal/sessions/stats_kept_test.go b/internal/sessions/stats_kept_test.go index fad2a8afc..78c16ac2a 100644 --- a/internal/sessions/stats_kept_test.go +++ b/internal/sessions/stats_kept_test.go @@ -104,8 +104,8 @@ func TestTitleAnswersSettled(t *testing.T) { func TestStatsKeptNewDay(t *testing.T) { setup(t) now := time.Now() - a := statsReadAll([]int{7}, now, nil)[0] - b := statsReadAll([]int{7}, now.AddDate(0, 0, 1), nil)[0] + a := statsReadAll([]int{7}, now, nil, nil, "")[0] + b := statsReadAll([]int{7}, now.AddDate(0, 0, 1), nil, nil, "")[0] if a.To == b.To { t.Fatalf("the next day's range is today's: %s", b.To) } @@ -116,7 +116,7 @@ func TestStatsKeptRangesBounded(t *testing.T) { setup(t) now := time.Now() for d := 1; d <= 40; d++ { - statsReadAll([]int{0, d}, now, nil) + statsReadAll([]int{0, d}, now, nil, nil, "") } mu.Lock() n, all := len(keptStats.ranges), keptStats.ranges[0].To != "" diff --git a/internal/sessions/stats_native_test.go b/internal/sessions/stats_native_test.go index 1bdeca7e8..15cac433b 100644 --- a/internal/sessions/stats_native_test.go +++ b/internal/sessions/stats_native_test.go @@ -44,7 +44,7 @@ func TestStatsAllRangesOnePass(t *testing.T) { passes := 0 filesHook = func() { passes++ } t.Cleanup(func() { filesHook = nil }) - all := statsReadAll(ranges, now, map[string]bool{}) + all := statsReadAll(ranges, now, map[string]bool{}, nil, "") if passes != 1 { t.Fatalf("%d passes over the files", passes) }