diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index 0fb61742d..5aff798d9 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -134,7 +134,8 @@ reads only the agent shown and the agents with gateway sessions (#2776). It answers before a first read of a long history (hey_boyce on X: the page stood on its placeholder rows on its first open). A file it would read whole (no parse kept, an older index, a file written over, or a Claude Code or -Codex parse that can't be read on after a restart) is read behind the +Codex parse that can't be read on after a restart because its window +wasn't kept on disk) is read behind the answer once more than `quickBytes` (32 MB) of them is waiting; until then its row stands on the parse kept, or on a glance at its first 256 KB (id, folder, first prompt, start) and, for Claude Code, the titles in its last @@ -144,6 +145,21 @@ glance is never saved in the index (`savable`) nor taken by a refresh as a parse (`parsed`). See [`internal/sessions/manage_quick.go`](../../internal/sessions/manage_quick.go), `TestManageAnswersBeforeFirstReads` and `sessions-pending-fill.test.cjs`. +A file being written (changed within the hour, `workingRevision`) keeps +what its reads have seen on disk with where they stopped, so after a +restart the next line it gains is read on from there, not from its first +line. A Claude Code session's is in `sessions.json` and its shard's `.rev` +file (#3493). A Codex rollout's summary window goes in +`codex-windows/.gob` beside `sessions.json`, written with it and +taken away once the cache drops that window, and its calls' window +(`cxRun`) in the shard's `.rev` file. Each names the parser and window +versions it was written by, the size, offset and content hash of its read, +and is taken only when all match. Before this, the first line a 100 MB +rollout gained after a restart had it read whole twice, 2.2 s of the +Sessions list on an M5 and over ten seconds on a slower Windows PC +(shangyuan0818 on X). See +[`internal/sessions/codex_window.go`](../../internal/sessions/codex_window.go) +and `TestCodexSessionReadOnAfterRestart`. A Claude Code session's folder is its first line's `cwd`, unless Claude Code's `/cd` moved it: the file goes to the new folder's project directory with a `{"type":"relocated","relocatedCwd":…}` line, while the diff --git a/internal/sessions/call_cache.go b/internal/sessions/call_cache.go index 2a9abcf47..5f0b04710 100644 --- a/internal/sessions/call_cache.go +++ b/internal/sessions/call_cache.go @@ -427,7 +427,7 @@ func readCalls(f file) *callFile { if st.Claude != nil && (old == nil || old.Claude == nil) && !workingRevision(f.mod.UnixNano(), time.Now()) { st = st.withoutRevisions() } - if err == nil && (f.agent == "claude" || f.agent == "claude-desktop") { + if err == nil && (f.agent == "claude" || f.agent == "claude-desktop" || f.agent == "codex") { writeCallRevisions(st) } @@ -538,8 +538,8 @@ func (r *callsRide) finish(off int64, err error) { if st.Claude != nil && !workingRevision(f.mod.UnixNano(), time.Now()) { st = st.withoutRevisions() } - writeCallRevisions(st) } + writeCallRevisions(st) st.dirty = nil if r.claude { // on disk only: a Sessions read keeps no calls (readCalls loads them) diff --git a/internal/sessions/call_revisions.go b/internal/sessions/call_revisions.go index 69789168e..d02b03157 100644 --- a/internal/sessions/call_revisions.go +++ b/internal/sessions/call_revisions.go @@ -6,6 +6,7 @@ import ( "os" "path/filepath" "strings" + "time" ) // A Claude Code session's revision window (claudeUsageState) lived in memory @@ -15,12 +16,18 @@ import ( // update (#3493). The window is bounded (claudeRevisionEntries), so it is // kept beside the file's shard, with where the read that made it stopped. -// callRevisions is a shard's Claude window, for the read that ended at Off. +// A Codex rollout's (cxRun) is kept the same way while the rollout is +// being written (codex_window.go). + +// callRevisions is a shard's Claude window, or its Codex rollout's read +// state, for the read that ended at Off. type callRevisions struct { Off int64 ContentHash string CompactMs int64 Window []claudeWindowEntry + CX *cxRun + CXVersion int // codexWindowVersion } func callRevisionsPath(path string) string { @@ -31,11 +38,16 @@ func callRevisionsPath(path string) string { // window kept before when st has none. func writeCallRevisions(st *callFile) { path := callRevisionsPath(st.Path) - if st.Claude == nil { + r := callRevisions{Off: st.Off, ContentHash: st.ContentHash.String(), CompactMs: st.CompactMs} + switch { + case st.Claude != nil: + r.Window = st.Claude.window() + case codexCallsKept(st): + r.CX, r.CXVersion = st.CX, codexWindowVersion + default: _ = os.Remove(path) return } - r := callRevisions{Off: st.Off, ContentHash: st.ContentHash.String(), CompactMs: st.CompactMs, Window: st.Claude.window()} var data bytes.Buffer if gob.NewEncoder(&data).Encode(r) != nil { return @@ -57,7 +69,11 @@ func writeCallRevisions(st *callFile) { // withCallRevisions is old with the window kept for it, when old is a // Claude file's read without one and the window kept is of that same read. func withCallRevisions(old *callFile) *callFile { - if old == nil || old.Claude != nil || (old.Agent != "claude" && old.Agent != "claude-desktop") || old.ContentHash == (digest{}) { + if old == nil || old.ContentHash == (digest{}) { + return old + } + codex := old.Agent == "codex" && (old.CX == nil || old.CX.Usage == nil) + if !codex && (old.Claude != nil || (old.Agent != "claude" && old.Agent != "claude-desktop")) { return old } data, err := os.ReadFile(callRevisionsPath(old.Path)) @@ -69,6 +85,20 @@ func withCallRevisions(old *callFile) *callFile { return old } c := *old + if codex { + if r.CX == nil || r.CX.Usage == nil || r.CXVersion != codexWindowVersion { + return old + } + c.CX = r.CX + return &c + } c.Claude, c.CompactMs = claudeWindowOf(r.Window), r.CompactMs return &c } + +// codexCallsKept says whether st is a rollout's calls whose read state is +// kept on disk: one being written, its window no larger than the cache +// keeps for a working session (revisionActiveEntries). +func codexCallsKept(st *callFile) bool { + return st.Agent == "codex" && st.CX != nil && st.CX.Usage != nil && workingRevision(st.Mod, time.Now()) && st.revisionWeight() <= revisionActiveEntries +} diff --git a/internal/sessions/codex_plain_ride_test.go b/internal/sessions/codex_plain_ride_test.go index 4497c0651..f5edde2de 100644 --- a/internal/sessions/codex_plain_ride_test.go +++ b/internal/sessions/codex_plain_ride_test.go @@ -11,11 +11,12 @@ import ( ) // TestPlainRolloutReadOnceForSessionsAndCalls: a plain rollout read from -// its first line, at a start with nothing kept or after a restart once it -// grew (neither read keeps its Codex window on disk), has its calls read on -// the summary's own pass, as a packed one has. Read apart, a cold start +// its first line, at a start with nothing kept, has its calls read on the +// summary's own pass, as a packed one has. Read apart, a cold start // read every rollout twice: 3.5 GB of reads for 1.7 GB of real rollouts -// (#4369). A rollout read on from where it was is read by each as before. +// (#4369). A rollout read on from where it was, in the same run or after a +// restart (its windows are kept on disk, codex_window.go), is read on by +// each as before. func TestPlainRolloutReadOnceForSessionsAndCalls(t *testing.T) { _, codex := setup(t) long := filepath.Join(codex, "sessions", "2026", "09", "21", "rollout-2026-09-21T10-00-00-0190aaaa-1111-7222-8333-444455556666.jsonl") @@ -134,16 +135,21 @@ func TestPlainRolloutReadOnceForSessionsAndCalls(t *testing.T) { } same("an append", got) - // grown while magpie was closed: neither read keeps its window on - // disk, so both read it from its first line, on one pass + // grown while magpie was closed: both windows are kept on disk, so + // each read goes on from where it was forget() run() grow(42, 43) Reset() counted() got = run() - if offs := got.scans[long]; len(got.scans) != 1 || len(offs) != 1 || offs[0] != 0 { - t.Errorf("grown after a restart: %v scanned, want the long rollout once from 0", got.scans) + if len(got.scans) != 1 || len(got.scans[long]) == 0 { + t.Errorf("grown after a restart: %v scanned, want the long rollout only", got.scans) + } + for _, off := range got.scans[long] { + if off == 0 { + t.Errorf("grown after a restart: the long rollout read again from its first line: %v", got.scans[long]) + } } same("grown after a restart", got) } diff --git a/internal/sessions/codex_window.go b/internal/sessions/codex_window.go new file mode 100644 index 000000000..5031d3138 --- /dev/null +++ b/internal/sessions/codex_window.go @@ -0,0 +1,151 @@ +package sessions + +import ( + "bufio" + "bytes" + "encoding/gob" + "os" + "path/filepath" + "strings" + "sync" +) + +// A Codex rollout's summary window (state.Codex) lived in memory alone, as +// its calls' (cxRun) did, so once magpie started again the first line a +// live rollout added had it read again from its first line, for the +// summary and for the calls: a 100 MB rollout took 2.2 s of the first +// Sessions list after it grew on an M5, and over ten seconds on a slower +// Windows PC (shangyuan0818 on X). Like a Claude session's (#3493), the +// window of a rollout being written is kept on disk with where the read +// that made it stopped: the summary's beside sessions.json, written with +// it, and the calls' beside the file's shard (writeCallRevisions). + +// codexWindowVersion is the shape of a kept window: raised whenever +// codexUsageState or cxRun changes what its fields mean, so a window an +// older magpie kept is read again from the source rather than taken in. +const codexWindowVersion = 1 + +// codexWindowHead says which read a kept summary window is of. It is +// written ahead of the window, so readsWhole reads it alone. +type codexWindowHead struct { + Version int + Parser int // parseVersions["codex"] + Size, Off int64 + ContentHash string +} + +func codexWindowDir() string { return filepath.Join(filepath.Dir(CachePath()), "codex-windows") } + +func codexWindowPath(path string) string { + return filepath.Join(codexWindowDir(), hashHead(path)+".gob") +} + +// codexWindowHeadOf is the head of the window kept for path, and the +// decoder its window is read on from. +func codexWindowHeadOf(path string) (codexWindowHead, *gob.Decoder, func(), bool) { + var h codexWindowHead + in, err := os.Open(codexWindowPath(path)) + if err != nil { + return h, nil, nil, false + } + dec := gob.NewDecoder(bufio.NewReader(in)) + if dec.Decode(&h) != nil { + in.Close() + return h, nil, nil, false + } + return h, dec, func() { in.Close() }, true +} + +func (h codexWindowHead) of(s *state) bool { + return s != nil && h.Version == codexWindowVersion && h.Parser == parseVersions["codex"] && s.ContentHash != (digest{}) && h.Size == s.Size && h.Off == s.Off && parseDigest(h.ContentHash) == s.ContentHash +} + +// codexWindowKept says whether a window of old's read is kept for f. +func codexWindowKept(f file, old *state) bool { + h, _, done, ok := codexWindowHeadOf(f.path) + if ok { + done() + } + return ok && h.of(old) +} + +// codexWindowed is old with the window kept for its read, when old is a +// rollout's summary without one; old as it is otherwise. A window kept +// for another read, or none, leaves old as it is, read again whole. +func codexWindowed(f file, old *state) *state { + if f.agent != "codex" || old == nil || old.Codex != nil { + return old + } + h, dec, done, ok := codexWindowHeadOf(f.path) + if !ok { + return old + } + defer done() + var w codexUsageState + if !h.of(old) || dec.Decode(&w) != nil { + return old + } + c := *old + c.Codex = &w + return &c +} + +// codexWindowsWritten are the summaries whose windows are on disk: a +// parse is never changed once in the cache, so one written is not +// written again. +var codexWindowsWritten struct { + sync.Mutex + files map[string]*state +} + +// writeCodexWindows keeps the windows of files' rollouts on disk, and +// takes away those of rollouts that have none now. The windows in the +// cache are already only those trimSummaryRevisions keeps. +func writeCodexWindows(files map[string]*state) { + codexWindowsWritten.Lock() + defer codexWindowsWritten.Unlock() + dir := codexWindowDir() + keep := map[string]bool{} + written := map[string]*state{} + for path, s := range files { + if s == nil || s.Agent != "codex" || s.Codex == nil || s.ContentHash == (digest{}) { + continue + } + name := filepath.Base(codexWindowPath(path)) + if codexWindowsWritten.files[path] == s { + keep[name], written[path] = true, s + continue + } + var data bytes.Buffer + enc := gob.NewEncoder(&data) + if enc.Encode(codexWindowHead{Version: codexWindowVersion, Parser: parseVersions["codex"], Size: s.Size, Off: s.Off, ContentHash: s.ContentHash.String()}) != nil || enc.Encode(s.Codex) != nil { + continue + } + if os.MkdirAll(dir, 0o700) != nil { + return + } + out, err := os.CreateTemp(dir, "window-*.tmp") + if err != nil { + return + } + _, err = out.Write(data.Bytes()) + if closeErr := out.Close(); err == nil { + err = closeErr + } + if err == nil { + err = os.Rename(out.Name(), codexWindowPath(path)) + } + if err != nil { + os.Remove(out.Name()) + continue + } + keep[name], written[path] = true, s + } + codexWindowsWritten.files = written + entries, _ := os.ReadDir(dir) + for _, e := range entries { + if !keep[e.Name()] && (strings.HasSuffix(e.Name(), ".gob") || strings.HasSuffix(e.Name(), ".tmp")) { + os.Remove(filepath.Join(dir, e.Name())) + } + } +} diff --git a/internal/sessions/codex_window_test.go b/internal/sessions/codex_window_test.go new file mode 100644 index 000000000..e6a353532 --- /dev/null +++ b/internal/sessions/codex_window_test.go @@ -0,0 +1,111 @@ +package sessions + +import ( + "os" + "path/filepath" + "reflect" + "strings" + "sync" + "testing" +) + +// TestCodexSessionReadOnAfterRestart: a live Codex rollout that grew after +// magpie started again is read on from where the last read ended, by the +// Sessions list and the Requests reader alike, and counts what a read from +// its first line counts. Its window lived in memory alone, so the first +// line after a restart read the whole rollout again for each: a 100 MB +// one took over ten seconds of the Sessions page on Windows +// (shangyuan0818 on X). +func TestCodexSessionReadOnAfterRestart(t *testing.T) { + d := setupCalls(t) + path := filepath.Join(d.codex, "sessions", "rollout-2026-09-20T10-00-00-0190aaaa-1111-7222-8333-444455556666.jsonl") + const turns = 60 + lines := longRollout(0, turns) + writeLines(t, path, lines...) + var mu sync.Mutex + var starts []int64 + scanHook = func(p string, off int64) { + if p == path { + mu.Lock() + starts = append(starts, off) + mu.Unlock() + } + } + t.Cleanup(func() { scanHook = nil }) + read := func() ([]Call, []Session) { + t.Helper() + var calls []Call + for _, s := range CallSources() { + if s.Path == path { + calls = ReadCallSource(s) + } + } + ss := List(0) + if len(ss) != 1 { + t.Fatalf("%d sessions", len(ss)) + } + return calls, ss + } + if cs, _ := read(); len(cs) != turns { + t.Fatalf("%d calls", len(cs)) + } + Reset() // a restart: what was read is on disk alone + // the last turn's usage written again, as a resumed rollout replays + // it, and a new turn: a window that lost what it had seen counts the + // replay a second time + var replay string + for _, l := range lines { + if strings.Contains(l, `"token_count"`) { + replay = l + } + } + appendText(t, path, replay+"\n"+strings.Join(longRollout(turns, turns+1), "\n")+"\n") + mu.Lock() + starts = nil + mu.Unlock() + got, gotList := read() + mu.Lock() + if len(starts) < 2 { + t.Fatalf("the summary and the calls weren't both read: %v", starts) + } + for _, off := range starts { + if off == 0 { + t.Fatalf("the rollout was read from its first line after a restart: %v", starts) + } + } + mu.Unlock() + Reset() + for _, p := range []string{CachePath(), callCachePath(path), callRevisionsPath(path), codexWindowPath(path)} { + os.Remove(p) + } + want, wantList := read() + if len(got) != turns+1 || !reflect.DeepEqual(got, want) { + t.Fatalf("read on: %d calls, from the start: %d", len(got), len(want)) + } + if g, w := gotList[0], wantList[0]; !reflect.DeepEqual(g.Tokens, w.Tokens) || !reflect.DeepEqual(g.Models, w.Models) || g.Cost != w.Cost || g.Tokens == (Tokens{}) { + t.Fatalf("read on: %+v\nfrom the start: %+v", g, w) + } +} + +// A rollout no longer being written keeps no window on disk: what is kept +// is the windows the cache keeps (trimSummaryRevisions). +func TestCodexWindowLeavesWithItsSession(t *testing.T) { + setupCalls(t) + s := &state{Agent: "codex", Size: 10, Off: 10, ContentHash: digest{1}, Codex: &codexUsageState{Session: "s"}} + writeCodexWindows(map[string]*state{"/a.jsonl": s}) + if _, err := os.Stat(codexWindowPath("/a.jsonl")); err != nil { + t.Fatal(err) + } + if got := codexWindowed(file{agent: "codex", path: "/a.jsonl"}, s.withoutRevisions()); got.Codex == nil || got.Codex.Session != "s" { + t.Fatalf("the window kept wasn't read back: %+v", got.Codex) + } + other := *s + other.Off = 9 + if got := codexWindowed(file{agent: "codex", path: "/a.jsonl"}, other.withoutRevisions()); got.Codex != nil { + t.Fatal("a window of another read was taken") + } + writeCodexWindows(map[string]*state{"/a.jsonl": s.withoutRevisions()}) + if _, err := os.Stat(codexWindowPath("/a.jsonl")); !os.IsNotExist(err) { + t.Fatalf("a window without its session stayed: %v", err) + } +} diff --git a/internal/sessions/manage_quick.go b/internal/sessions/manage_quick.go index 764773ea3..6402adbed 100644 --- a/internal/sessions/manage_quick.go +++ b/internal/sessions/manage_quick.go @@ -57,7 +57,7 @@ func readsWhole(f file, old *state) bool { return true } if f.agent == "codex" && old.Codex == nil { - return true + return !codexWindowKept(f, old) } return p.claude && old.Claude == nil } diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 55f455a0b..6de9e38f3 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -1669,6 +1669,7 @@ func writeCache(c *save) { return } ok = true + writeCodexWindows(c.Files) } // refresh parses those of want that changed since their parse was kept, a @@ -1768,13 +1769,16 @@ func refresh(want, all []file) { j := &jobs[i] // its file's calls lock is taken before a read slot, as // readCalls takes them - calls := callsAlong(j.f, j.old) + // a rollout's window kept on disk: its calls are read on + // too, by readCalls, rather than ride a read from the start + old := codexWindowed(j.f, j.old) + calls := callsAlong(j.f, old) release := readSlot() end := readBegin() if parseHook != nil { parseHook() } - j.parsed = parseWith(j.f, j.old, calls) + j.parsed = parseWith(j.f, old, calls) end() release() if j.parsed.Agent != j.f.agent { @@ -2331,8 +2335,10 @@ func parseRead(f file, old *state, calls *callsRide) *state { calls.release() } }() - // Summary caches contain aggregates only. After a restart, a changed - // Codex file rebuilds its transient response index from the source. + // sessions.json keeps aggregates only, and a rollout's window beside it + // (codex_window.go). A changed rollout with no window of its read kept + // rebuilds it from the source. + old = codexWindowed(f, old) if f.agent == "codex" && old != nil && old.Codex == nil { old = nil }