sessions: a long Codex rollout is read on after a restart, not read again whole

shangyuan0818 on X: on Windows, Usage > Sessions took over ten seconds to
open with one very long session (tens to 100 MB), though there were only
a few sessions.

Cause: a Codex rollout's summary window (state.Codex) and its calls'
window (cxRun) lived in memory only. After a restart, or once the window
had been dropped, the first line a live rollout gained made parseRead,
prepareCalls and readsWhole read the rollout again from its first line:
once for the summary and once for the calls. Claude Code sessions were
already read on through their kept windows (#3493).

Fix: the window of a rollout being written (changed within the hour, the
same files memory keeps windows for) is now kept on disk with the parser
version, a window version, and the size, offset and content hash of the
read that made it. The summary's goes in codex-windows/<hash>.gob next
to sessions.json. It is written with sessions.json, and it is removed
once the cache drops that window. The calls' window goes in the shard's
.rev file next to Claude's. Each is used only when all of those match,
so a window from another read, or from an older layout, is never used;
the file is read whole instead, as before.

Measured (100 MB rollout built from testdata/codex-native-paginated.jsonl,
plus a 100 MB Claude Code session, GET /api/sessions in a sandbox HOME):
  mote (M5), before: after one line appended following a restart, 2.51 s
    (Codex alone 2.25 s). After: 9.7 ms (Codex alone 6.3 ms).
  Windows (xiaomi-gpu), before: 2.61 s. After: 22.8 ms.
  The first read with nothing kept is unchanged: 2.6 s on mote, 2.8 s on
    Windows. Warm and plain-restart opens were already 10 to 30 ms. stats
    and overview stayed at a few ms throughout.
  A real 32 MB rollout: 24 ms after an append, with 2 KB and 4 KB windows.
    A 100 MB rollout with a unique response id per turn: 11 ms, with
    623 KB and 834 KB windows.

Tests: TestCodexSessionReadOnAfterRestart reads a rollout, restarts, then
appends a replayed token_count and a new turn. It checks that neither
reader starts at offset 0, and that calls and the session's tokens,
models and cost match a read from scratch. TestCodexWindowLeavesWithItsSession
covers writing, reading back, refusing another read's window and
removal. TestPlainRolloutReadOnceForSessionsAndCalls (#4369) expected
both readers to start from 0 after a restart; it now expects them to
read on.

Broken by hand, each red: the summary window not read (starts [319830 0]);
the calls window not read ([0 319830]); a summary window emptied of what
it had seen (it panicked in codexUsageState.count, which is why the
version guard was added); a calls window emptied (62 calls vs 61).

Run: gofmt -l clean. GOOS=linux and GOOS=windows go vet -tags nogui ./...
on mote. Full go test -tags nogui -timeout 45m ./... on Linux (wsl-run,
magpie-desktop) at this change on 70bd270ae: every package ok but
internal/usage, whose TestRequestStateKeptAcrossACatalogFetchedAgain is
red the same way alone on origin/main 7b50e1f2c (11 of 20; a same-size
catalog write in one mtime tick, filed as #6572). mote's suite.lock had
five runs queued ahead, so its run of this change is still waiting.
Rebased onto 7b50e1f2c (7 files in internal/provider and internal/usage,
none under internal/sessions); provider, usage and sessions run again
there on Linux: all ok (#6572 passed this time). win-run ./internal/sessions/: only TestAgySessions,
TestAgyRowOnly, TestAntigravityAppFolder and TestCCListingKeepsItsNames
fail, and they fail the same way on origin/main ea9f2639b (#6071).
win-run -run 'Session|Usage|Calls' ./internal/gui/: only
TestGatewayModeStatsNameTheGatewaySessions fails, the same on ea9f2639b
(#6068).

Old data: right after updating, every user's live rollout is read whole
once more on its next change, since no window has been kept yet. From
then on it is read on. Nothing else changes for files not written within
the hour.

Not changed: WorkBuddy, WorkBuddy AI and CodeBuddy calls are still read
whole on every line (556 ms per 100 MB on mote), filed as #6565. Not
tried: the reporter's own machine and files.
This commit is contained in:
yetone
2026-11-14 03:28:08 +08:00
parent 7b50e1f2c6
commit ab4b1cf38f
8 changed files with 340 additions and 20 deletions
+17 -1
View File
@@ -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/<hash>.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
+2 -2
View File
@@ -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)
+34 -4
View File
@@ -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
}
+14 -8
View File
@@ -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)
}
+151
View File
@@ -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()))
}
}
}
+111
View File
@@ -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)
}
}
+1 -1
View File
@@ -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
}
+10 -4
View File
@@ -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
}