Files
magpie/internal/usage/codex_effort_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

162 lines
6.4 KiB
Go

package usage
import (
"fmt"
"os"
"path/filepath"
"reflect"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/sessions"
)
// effortFixture is one Codex thread's call in a sandbox home.
func effortFixture(t *testing.T) (now time.Time, rollout string) {
t.Helper()
pageHome(t)
now = holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC))
rollout = filepath.Join(sessions.CodexDir(), "sessions", "2026", "09", "30", "rollout-2026-09-30T10-00-00-main-a.jsonl")
writeCodexCall(t, rollout, "main-a", "main-a", `"vscode"`, "resp-1", "m", "low", now.Add(-time.Hour), 20, 3)
return now, rollout
}
// The Sessions page's overview and list ask for every Codex thread's
// consumption at once, each refresh. Each ask built its own ledger of all
// history, and with 68k session files the app grew to 85 GB (#2278).
// Asks arriving together are answered by one build.
func TestCodexModelEffortConcurrentAsksBuildOnce(t *testing.T) {
effortFixture(t)
var built atomic.Int32
release := make(chan struct{})
effortBuilt = func() {
if built.Add(1) == 1 {
<-release
}
}
t.Cleanup(func() { effortBuilt = nil })
const asks = 8
results := make([]map[string][]sessions.ModelEffort, asks)
var wg sync.WaitGroup
for i := range asks {
wg.Add(1)
go func() {
defer wg.Done()
results[i] = CodexModelEffort(All)
}()
}
// give the other asks time to start builds of their own, as they did
deadline := time.Now().Add(time.Second)
for built.Load() < asks && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
close(release)
wg.Wait()
if n := built.Load(); n != 1 {
t.Fatalf("%d asks at once built the ledger %d times, want 1", asks, n)
}
for i, r := range results {
if got, ok := findModelEffort(r["main-a"], "m", "low"); !ok || got.Input != 20 {
t.Fatalf("ask %d got %+v", i, r)
}
}
}
// While the next answer is built, an ask for the same period is told the
// last one at once rather than building another ledger beside it.
func TestCodexModelEffortAnswersLastWhileBuilding(t *testing.T) {
now, rollout := effortFixture(t)
var built atomic.Int32
effortBuilt = func() { built.Add(1) }
t.Cleanup(func() { effortBuilt = nil })
CodexModelEffort(All)
writeCodexCall(t, rollout, "main-a", "main-a", `"vscode"`, "resp-1", "m", "low", now.Add(-time.Hour), 2000, 30)
later := now.Add(time.Minute)
if err := os.Chtimes(rollout, later, later); err != nil {
t.Fatal(err)
}
entered, release := make(chan struct{}), make(chan struct{})
effortBuilt = func() {
if built.Add(1) == 2 {
close(entered)
<-release
}
}
done := make(chan map[string][]sessions.ModelEffort)
go func() { done <- CodexModelEffort(All) }()
<-entered
meanwhile := CodexModelEffort(All)
close(release)
next := <-done
if n := built.Load(); n != 2 {
t.Fatalf("an ask during a build built the ledger again: %d builds, want 2", n)
}
if got, _ := findModelEffort(meanwhile["main-a"], "m", "low"); got.Input != 20 {
t.Fatalf("an ask during the build got %+v, want the last answer", meanwhile)
}
if got, _ := findModelEffort(next["main-a"], "m", "low"); got.Input != 2000 {
t.Fatalf("the build got %+v", next)
}
if got, _ := findModelEffort(CodexModelEffort(All)["main-a"], "m", "low"); built.Load() != 2 || got.Input != 2000 {
t.Fatalf("the next ask: builds %d, %+v", built.Load(), got)
}
}
// An answer is kept when there is no gateway log yet, and when the log grew
// while it was built: the next ask builds again only if the state did change.
func TestCodexModelEffortKeptWithoutLogAndAcrossAWrite(t *testing.T) {
now, _ := effortFixture(t)
var built atomic.Int32
effortBuilt = func() { built.Add(1) }
t.Cleanup(func() { effortBuilt = nil })
CodexModelEffort(All)
CodexModelEffort(All)
if n := built.Load(); n != 1 {
t.Fatalf("with no usage.jsonl the ledger was built %d times, want 1", n)
}
effortBuilt = func() {
if built.Add(1) == 2 { // the gateway writes while the ledger is built
Append(Record{Time: now.Add(-time.Minute), Agent: "codex", Provider: "openai", Model: "m", Input: 5, Output: 1, Status: 200, ResponseID: "resp-2"})
}
}
Append(Record{Time: now.Add(-2 * time.Minute), Agent: "pi", Provider: "openai", Model: "m", Input: 1, Output: 1, Status: 200})
CodexModelEffort(All) // built under the state before the write
CodexModelEffort(All) // the write changed it
CodexModelEffort(All)
if n := built.Load(); n != 3 {
t.Fatalf("builds = %d, want 3", n)
}
}
// CodexModelEffort reads Codex's session files only; what it reports is what
// the whole ledger, every agent's files read, says of each Codex thread.
func TestCodexModelEffortIsTheWholeLedgers(t *testing.T) {
now, _ := effortFixture(t)
root := filepath.Join(sessions.CodexDir(), "sessions", "2026", "09", "30")
writeCodexCall(t, filepath.Join(root, "rollout-2026-09-30T11-00-00-main-b.jsonl"), "main-b", "main-b", `"cli"`, "resp-b", "m", "high", now.Add(-30*time.Minute), 300, 30)
Append(Record{Time: now.Add(-30 * time.Minute), Agent: "codex", Provider: "openai", Model: "m", Effort: "xhigh", Input: 300, Output: 30, Status: 200, ResponseID: "resp-b", Session: "main-b"})
Append(Record{Time: now.Add(-20 * time.Minute), Agent: "codex", Provider: "openai", Model: "m", Input: 9, Output: 9, Status: 200, ResponseID: "resp-unpaired"})
// a Claude Code session the gateway saw a call of
claude := filepath.Join(sessions.ClaudeDir(), "projects", "-work-app", "sess1.jsonl")
at := now.Add(-10 * time.Minute)
line := fmt.Sprintf(`{"type":"assistant","uuid":"u1","timestamp":%q,"message":{"id":"msg1","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"hi"}],"usage":{"input_tokens":40,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":4}},"requestId":"req_1","sessionId":"sess1","cwd":"/work/app","entrypoint":"cli"}`+"\n", at.Format(time.RFC3339Nano))
if err := os.MkdirAll(filepath.Dir(claude), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(claude, []byte(line), 0o600); err != nil {
t.Fatal(err)
}
Append(Record{Time: at, Agent: "claude-code", Provider: "anthropic", Model: "claude-opus-5-5", Input: 40, Output: 4, Status: 200, RequestID: "req_1", Session: "sess1"})
whole := codexModelEffort(LedgerOfAt(All, Filter{}, now).Rows)
if len(whole) != 2 {
t.Fatalf("fixture: the whole ledger has %d Codex threads: %+v", len(whole), whole)
}
if got := CodexModelEffort(All); !reflect.DeepEqual(got, whole) {
t.Fatalf("Codex-only ledger:\n got %+v\nwant %+v", got, whole)
}
}