Files
magpie/internal/sessions/calls_shared_test.go
T
yetone 8a1b5916f3 sessions, usage, gui: one read of every call at a time, the Codex effort built once and kept, and the Sessions page asks for an overview once, so the app no longer grows to 85 GB (#2278)
On a long history (the reporter's: 68k call files in calls-v15, 415 MB;
42 MB usage.jsonl; 75k calls in 7 days), the app's main process grew to
85 GB in about 90 minutes and the gateway froze. `magpie serve` alone held
83-153 MB for 20 minutes (the reporter's follow-up), so the growth is in
the app's Sessions path:
/api/sessions/overview -> usage.CodexModelEffort -> LedgerOfAt ->
sessions.Calls(all history).

Why it grew:
- CodexModelEffort's cache key changes on every gateway write, and it
  never kept an answer when usage.jsonl was missing or grew during the
  build. So every /api/sessions, overview, /one and /manage ask with a Codex
  session rebuilt the all-history ledger, gob-decoding every shard (only
  64 stay in memory).
- Nothing joined concurrent asks.
- The page's 15s reload asked for an overview again while the last one
  was still under way, so slow asks piled up.

What changes:
- sessions.Calls and the new AgentCalls go through sharedCalls. An ask
  while the same read is under way waits for it and gets a copy, and
  reads run one at a time.
- AgentCalls(since, "codex") reads Codex's files only. pruneCalls still
  sees every file.
- CodexModelEffort is built from Codex's calls plus the gateway's records.
  Only those name a Codex actor, and TestCodexModelEffortIsTheWholeLedgers
  checks the answer equals the whole ledger's on a mixed Claude + Codex +
  gateway fixture.
  - One build per period at a time. An ask during a build gets the last
    answer for the same home (root), or waits if there is none.
  - The answer is kept when usage.jsonl is missing or grows during the
    build.
  - At most 8 periods are kept.
- page.js: sessOverview shares one promise per query, so the filter's ask
  and the 15s reload's ask for the same overview send one request.
- docs/subsystems/gateway-sessions.md says this.

Reproduced (temporary test, not committed): a sandbox HOME with 62k
Claude Code session files, 5.9k Codex rollouts and 100k gateway records.
Sessions routes in-process, 4 rounds x 6 concurrent asks
(overview?days=0 and /api/sessions), a usage record appended every 300ms:
  before (2b0037f41): 7m39s total, slowest ask 2m01s; 66264 MB allocated
    (2761 MB per ask); peak heap in use 4620 MB, peak Go sys 6274 MB,
    peak RSS 5325 MB
  after:              20.4s total, slowest ask 7.1s; 20728 MB allocated
    (863 MB per ask); peak heap in use 1168 MB, peak Go sys 1487 MB,
    peak RSS 1415 MB
Cold warm-up (index plus every shard) was 21m before and 18.5s after on the
same home. The after run reused the shards on disk, so it is not a
comparable number.

Tests, each red on the old code:
- TestConcurrentCallsShareOneRead: 8 reads, not 1. It also goes red when
  the join is broken by hand.
- TestCodexModelEffortConcurrentAsksBuildOnce: 8 builds.
- TestCodexModelEffortAnswersLastWhileBuilding: 3 builds.
- TestCodexModelEffortKeptWithoutLogAndAcrossAWrite: 2 builds.
- sessions-overview-once.test.cjs: 2 overview requests, not 1. That is
  chromium and webkit; en, zh, zh-TW and ja at 1100/900px, de at 420px.
  It was red with the old page.js served.
TestAgentCallsReadsOneAgent and TestCodexModelEffortIsTheWholeLedgers pass
on both versions.

Run:
- gofmt -l: clean.
- go vet -tags nogui for darwin, linux and windows: sessions, usage,
  gui. Before that, the whole tree for linux and windows.
- go test -race on ./internal/sessions/ and ./internal/usage/.
- go test of internal/sessions, internal/usage and internal/gui at the
  rebased head (on 95e7c6bcc): green. gui was red once, in a run whose
  output was cut, at load ~100; it was green on two reruns.
- Full suite: SUITE_LINE
- GUI: the 13 files that ask for sessions/overview, at the rebased head,
  in chromium and webkit: 198/198. Before the rebase, those plus every
  usage*.test.cjs,
  in chromium and webkit: 749 pass. The 24 failures are usage-fold
  (#2163) and usage-agents-hide (#2276). The same 24 fail with the old
  page.js on 2b0037f41, and both are filed.

Not tried: the real app on the reporter's data; an hour-long run.
2026-10-15 23:08:00 +08:00

92 lines
2.8 KiB
Go

package sessions
import (
"path/filepath"
"sync"
"sync/atomic"
"testing"
"time"
)
// The Sessions page's requests arriving together each read every session
// file's calls, and with 68k files the app grew to 85 GB (#2278). Callers
// asking at once share one read, and each is handed a copy of its own.
func TestConcurrentCallsShareOneRead(t *testing.T) {
d := setupCalls(t)
writeLines(t, filepath.Join(d.claude, "projects", "-work-app", "sess1.jsonl"),
claudeMsg("m1", "claude-opus-5-5", 100, 1, 5000, 1000, 1),
claudeMsg("m2", "claude-opus-5-5", 7, 8, 0, 0, 4))
const callers = 8
var reads atomic.Int32
release := make(chan struct{})
readingCalls = func() {
if reads.Add(1) == 1 {
<-release
}
}
t.Cleanup(func() { readingCalls = nil })
results := make([][]Call, callers)
var wg sync.WaitGroup
for i := range callers {
wg.Add(1)
go func() {
defer wg.Done()
results[i] = Calls(time.Time{})
}()
}
// release the first read once every other caller waits on it
deadline := time.Now().Add(10 * time.Second)
for {
callsFlights.Lock()
waiting := 0
for _, fl := range callsFlights.on {
waiting += fl.waiters
}
callsFlights.Unlock()
if waiting == callers-1 || time.Now().After(deadline) {
break
}
time.Sleep(5 * time.Millisecond)
}
close(release)
wg.Wait()
if n := reads.Load(); n != 1 {
t.Fatalf("%d callers asking at once read the files %d times, want 1", callers, n)
}
for i, cs := range results {
if len(cs) != 2 || cs[0].RequestID != "req_m2" {
t.Fatalf("caller %d got %+v", i, cs)
}
}
results[0][0].Model = "changed"
for i := 1; i < callers; i++ {
if results[i][0].Model != "claude-opus-5-5" {
t.Fatalf("caller %d sees another caller's change: %+v", i, results[i][0])
}
}
}
// AgentCalls reads one agent's files only, and its calls are the ones Calls
// gives for that agent.
func TestAgentCallsReadsOneAgent(t *testing.T) {
d := setupCalls(t)
writeLines(t, filepath.Join(d.claude, "projects", "-work-app", "sess1.jsonl"),
claudeMsg("m1", "claude-opus-5-5", 100, 1, 5000, 1000, 1))
name := "rollout-2026-09-20T10-00-00-0190aaaa-1111-7222-8333-444455556666.jsonl"
lines := []string{`{"timestamp":"` + stamp(0) + `","type":"session_meta","payload":{"id":"thread-id","session_id":"sess-x","cwd":"/work/start"}}`}
lines = append(lines, cxTurnLines(1, "t1", "gpt-6-astra", "high")...)
lines = append(lines, tokenCountLine(2, cxUse(1000, 600, 0, 50, 20), cxUse(1000, 600, 0, 50, 20)), cxDoneLine(5, "t1", 5000, 700))
writeLines(t, filepath.Join(d.codex, "sessions", "2026", "09", "20", name), lines...)
codex := AgentCalls(time.Time{}, "codex")
var want []Call
for _, c := range Calls(time.Time{}) {
if c.Agent == "codex" {
want = append(want, c)
}
}
if len(codex) != 1 || len(want) != 1 || bare(codex[0]) != bare(want[0]) {
t.Fatalf("codex calls %+v, want %+v", codex, want)
}
}