sessions: the page's 7, 30 and all-time stats are read again in one pass (#2278)

statsFor keeps each ?days range the Usage page asks for and reads it
again behind the page once it is 10s old. Each of the three ranges
(7, 30, 0) was its own combinedSessionStats: a listing of every Claude
Code and Codex file, a refresh, the Codex identities and task titles,
every session assembled for the native keys, and the ccCopies, all
identical whatever the range. With 25k Codex rollouts that was ~4.2s of
CPU a minute on a polled page.

Now a stale range takes every other stale range with it, and
statsReadAll does the shared part once and sums each range from it
(statsOfRange). The sessions assembled for the native keys are reused
for each range's list instead of assembling them again.

Rebased onto b4267de59; the tests and vets below ran again on mote at
the rebased head, same results. The A/B ran before the rebase:
- TestStatsAllRangesOnePass (new): ranges 0, 1, 7, 30 from one pass
  are each DeepEqual to statsRead of that range alone, and the files
  are listed once.
- GOOS=linux/windows/darwin go vet -tags nogui ./internal/sessions
  ./internal/gui: clean.
- go test ./internal/sessions ./internal/usage: ok. ./internal/gui: ok
  but for TestMainWindowCorners/macOS_26_SDK, the macOS 27 red in #3949
  (titlebar, untouched here).
- A/B on mote, sandbox HOME with a copy of the real 115MB usage.jsonl
  (240k rows) and 25k Codex rollouts, the page's 10 reads every 5s and
  4 appends a second, 240s each, v0.1.1959 (d7e9c3745) then this:
    stats refresh (statsFor.func1) CPU  4.17s -> 2.22s a minute
    process CPU in the 60s profile      33.8s -> 30.7s
    stats?days=0/30/7 mean              0.76/0.77/0.78s -> 0.39/0.36/0.39s
    /api/sessions/overview mean         1.29s -> 0.72s
    /api/sessions mean                  2.01s -> 1.37s
    every read's mean                   0.99s -> 0.62s
    peak RSS                            985 -> 1033 MiB (mote at load
                                        ~35 from other sessions; peak is
                                        next)
This commit is contained in:
yetone
2026-10-29 05:29:36 +08:00
parent b4267de595
commit fa2dfc1458
3 changed files with 126 additions and 25 deletions
+29 -4
View File
@@ -476,16 +476,28 @@ func statsFor(days int) sessions.Stats {
statsMemo.asks++
k.used = statsMemo.asks
if !k.busy && time.Since(k.at) > 10*time.Second {
k.busy = true
// every range kept that is as old is read again with it, in
// one pass: the page asks for 7, 30 and every day, and each
// read alone listed and summed every session file (#2278)
var ranges []int
var kept []*statsKept
for d, o := range statsMemo.m {
if !o.busy && time.Since(o.at) > 10*time.Second {
o.busy = true
ranges, kept = append(ranges, d), append(kept, o)
}
}
// read beside the page's own reads: with their listing of
// the session files, and handed back once they all rest
shared, rest := sessions.ShareListing(), readingPage()
go func() {
defer rest()
defer shared()
st := combinedSessionStats(days)
sts := combinedSessionStatsAll(ranges)
statsMemo.Lock()
k.at, k.st, k.busy = time.Now(), st, false
for i, o := range kept {
o.at, o.st, o.busy = time.Now(), sts[i], false
}
statsMemo.Unlock()
}()
}
@@ -517,7 +529,20 @@ func statsFor(days int) sessions.Stats {
}
func combinedSessionStats(days int) sessions.Stats {
st, nativeKeys := sessions.StatsAndNative(days)
return combinedSessionStatsAll([]int{days})[0]
}
// combinedSessionStatsAll is combinedSessionStats for each of days, the
// session files read once for all of them.
func combinedSessionStatsAll(days []int) []sessions.Stats {
sts, nativeKeys := sessions.StatsAndNativeAll(days)
for i := range sts {
sts[i] = withGatewaySessions(sts[i], days[i], nativeKeys)
}
return sts
}
func withGatewaySessions(st sessions.Stats, days int, nativeKeys map[string]bool) sessions.Stats {
var since time.Time
if days > 0 && st.From != "" {
since, _ = time.ParseInLocation(time.DateOnly, st.From, time.Local)
+69 -20
View File
@@ -10,6 +10,7 @@ import (
"time"
"unicode/utf8"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
@@ -149,8 +150,24 @@ func StatsAt(days int, now time.Time) Stats { return statsAt(days, now) }
// from one only magpie saw. Both come of one pass over the files, as the
// overview asks for both on every poll (#2776).
func StatsAndNative(days int) (Stats, map[string]bool) {
st, native := StatsAndNativeAll([]int{days})
return st[0], native
}
// StatsAndNativeAll is StatsAndNative for each of days, from one pass:
// the listing, the reads of changed files and every session's own sums
// 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) {
native := map[string]bool{}
return statsIn(days, time.Now(), native), native
alias := provider.UsageAlias()
out := statsReadAll(days, time.Now(), native)
if alias != nil {
for i := range out {
out[i] = aliasStats(out[i], alias)
}
}
return out, native
}
func statsAt(days int, now time.Time) Stats { return statsIn(days, now, nil) }
@@ -167,15 +184,14 @@ func statsIn(days int, now time.Time, native map[string]bool) Stats {
}
func statsRead(days int, now time.Time, native map[string]bool) Stats {
return statsReadAll([]int{days}, now, native)[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 {
now = now.In(time.Local)
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
var since time.Time
from := ""
if days > 0 {
since = today.AddDate(0, 0, 1-days)
from = since.Format(time.DateOnly)
}
out := Stats{From: from, To: today.Format(time.DateOnly), Days: []Day{}, Sessions: []Summary{}, Keys: []string{}}
storeMu.RLock()
defer storeMu.RUnlock()
@@ -189,13 +205,18 @@ func statsRead(days int, now time.Time, native map[string]bool) Stats {
refresh(files, files)
identities := codexIdentitySnapshot(files)
taskTitles := codexSubagentTaskTitles(files)
price, titles := pricer(), codexTitleOf()
// each session as listed, by key: what native is made of, and what a
// range's sessions are summed up from
var listed map[string]Session
if native != nil {
groups := byKey(files, nil)
price, titles := pricer(), codexTitleOf()
for _, fs := range groups {
listed = make(map[string]Session, len(groups))
for key, fs := range groups {
// as List: a session nothing was said in is not listed
if s, ok := assembleListed(fs, price, titles); ok {
native[s.Agent+"|"+s.ID] = true
listed[key] = s
}
}
}
@@ -204,13 +225,6 @@ func statsRead(days int, now time.Time, native map[string]bool) Stats {
// the keeper's doesn't (ccCopyStates), not the messages both hold
copies := ccCopies(files)
copied := ccCopyStates(files, copies)
var want []file
for _, f := range files {
if !f.mod.Before(since) && (copies[f.key] == "" || copied[f.path] != nil) {
want = append(want, f)
}
}
// a subagent's file counts in the folder of its session's own file
folder := map[string]string{}
for _, f := range files {
@@ -218,6 +232,33 @@ func statsRead(days int, now time.Time, native map[string]bool) Stats {
folder[f.key] = st.Cwd
}
}
out := make([]Stats, len(ranges))
for i, days := range ranges {
out[i] = statsOfRange(days, today, files, copies, copied, folder, listed, identities, taskTitles, price, titles)
}
return out
}
// statsOfRange is one range's Stats from what statsReadAll read, with the
// locks it holds. listed is every session as listed, by key, or nil to
// assemble the range's own.
func statsOfRange(days int, today time.Time, files []file, copies map[string]string, copied map[string]*state,
folder map[string]string, listed map[string]Session, identities map[string]CodexIdentity, taskTitles map[codexTaskTitle]string,
price func(string) *catalog.Price, titles func(string) string) Stats {
var since time.Time
from := ""
if days > 0 {
since = today.AddDate(0, 0, 1-days)
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 }
type act0 struct {
@@ -334,7 +375,6 @@ func statsRead(days int, now time.Time, native map[string]bool) Stats {
for date := range dates {
byDate[date] = &Day{Date: date, Usage: []Usage{}, Active: []Active{}}
}
price, titles := pricer(), codexTitleOf()
for k, t := range use {
u := Usage{Agent: k.agent, Cwd: k.cwd, Model: k.model, Tokens: t}
if p := price(k.model); p != nil {
@@ -380,7 +420,10 @@ func statsRead(days int, now time.Time, native map[string]bool) Stats {
}
}
groups := byKey(files, func(f *file) bool { return shares[f.key] != nil })
var groups map[string][]file
if listed == nil {
groups = byKey(files, func(f *file) bool { return shares[f.key] != nil })
}
first, _ := time.ParseInLocation(time.DateOnly, out.From, time.Local)
// made to size: grown by append, 34k sessions' list held a quarter
// more than its rows, and every copy it was grown through (#2278)
@@ -389,7 +432,13 @@ func statsRead(days int, now time.Time, native map[string]bool) Stats {
if len(sh.dates) == 0 {
continue
}
s, ok := assembleListed(groups[key], price, titles)
var s Session
var ok bool
if listed != nil {
s, ok = listed[key]
} else {
s, ok = assembleListed(groups[key], price, titles)
}
if !ok {
continue
}
+28 -1
View File
@@ -1,6 +1,10 @@
package sessions
import "testing"
import (
"reflect"
"testing"
"time"
)
// The overview's stats and the sessions that tell its gateway sessions
// apart come of one pass over every agent's files (#2776): it took a second
@@ -30,3 +34,26 @@ func TestStatsAndNativeOnePass(t *testing.T) {
}
}
}
// TestStatsAllRangesOnePass: the ranges statsFor keeps are read again in
// one pass, and each comes out as its own read would (#2278).
func TestStatsAllRangesOnePass(t *testing.T) {
setup(t)
now := time.Now()
ranges := []int{0, 1, 7, 30}
passes := 0
filesHook = func() { passes++ }
t.Cleanup(func() { filesHook = nil })
all := statsReadAll(ranges, now, map[string]bool{})
if passes != 1 {
t.Fatalf("%d passes over the files", passes)
}
if len(all[0].Sessions) == 0 {
t.Fatalf("no stats: %+v", all[0])
}
for i, days := range ranges {
if one := statsRead(days, now, nil); !reflect.DeepEqual(all[i], one) {
t.Fatalf("days=%d: one pass %+v\nalone %+v", days, all[i], one)
}
}
}