sessions: a range's stats are aliased once, as made, and kept aliased (#2278)

With any model alias set, every Stats read copied each kept range's
days and every session's summary into a second, aliased Stats, and kept
that copy (aliasedKept) beside the unaliased one. With a long history
(~14k sessions) the copy held ~5 MB of summaries for as long as the
kept ranges lived.

Now statsKept aliases a range's Stats in place right after
statsOfRange made it (aliasOwned: only st's own Days and Sessions
arrays are written; the usage, model and effort slices are replaced,
never written into) and keeps that one. keptStats carries the alias
names it was made under, so a changed alias makes the ranges again,
as a changed price or title already did. aliasedKept, aliasKept and
aliasStats are gone.

Tests: TestSessionsCountAliasedModelsAsOne now checks that the kept
range's summaries are the very ones the read returned. Broken by hand
(a copy of Sessions before keeping): it went red ("an aliased read
keeps a copy of its summaries beside the kept ones"), and so did
alias_kept_test's "range 0 named again with nothing changed".
TestAliasOwnedLeavesSharedSlicesAlone replaces
TestAliasStatsLeavesItsInputAlone.

Run at 846cc2b9b (rebased on 96c65e3e7), on mica: gofmt -l clean; go vet,
GOOS=windows go vet and GOOS=linux go vet -tags nogui ./... ok;
go test -timeout 45m -count=1 ./...: 97 packages ok, none failed.

Real account (mote, sandbox HOME with the owner's history and an alias
set), late.sh at 120s, v0.1.3814 vs this: footprint 127 → 124 MB, live
heap after GC 100.8 → 95.9 MB; aliasStats' 5.01 MB is gone from the
profile.

Not tried: Windows and Linux runs of the package (no OS-specific code).
This commit is contained in:
yetone
2026-11-12 08:39:44 +08:00
parent 908c9986cd
commit 67d2df72d9
6 changed files with 52 additions and 110 deletions
+10 -75
View File
@@ -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
+12 -4
View File
@@ -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)
+17 -20
View File
@@ -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
}
+9 -7
View File
@@ -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,
+3 -3
View File
@@ -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 != ""
+1 -1
View File
@@ -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)
}