sessions: a call shard is written in frames of 2048 calls (#3493)

writeCalls wrote a shard's whole state as one frame, whatever its
size. The largest Codex session on the test copy (52,500 calls) was one
8MB gob frame, and decoding it allocated ~100MB and held ~70MB at once,
which is most of the gap between a cold warm-up's memory peak and a
warm one's.

A write now splits its patches into frames of framePatches (2048).
Every frame but the last has More set, and each carries Calls, the
file's call count after the write, so loadCalls sizes its slice once.
A file whose last frame has More was cut off mid-write and reads as
nil, the same as a bad CRC. A shard read from a frame over
framePatches (the old format) is written again in frames once, at its
first load (loadKept), so existing caches shrink their peak too.

Run at this tree (04439c859 + this change):
- go test -count=1 -timeout 45m ./internal/sessions/ ./internal/usage/:
  ok; go test -run 'Warm|Session' ./internal/gui/: ok.
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/sessions/:
  ok; gofmt -l clean.
- TestCallsWrittenInFrames (frames 2048/2048/100, a file cut after the
  first frame reads nil, an old one-frame file loads and is rewritten)
  went red with each of: no More check, no rewrite, no Calls presize,
  no split.
- The real warm-up (gui warmSteps inside sessions.Warm) on a copy of
  the owner's ~/.claude and ~/.codex sessions, 15,719 shards / 118MB,
  alternating parent and change:
  - cold (requests-v1.bin removed): phys_footprint_peak 418/462/406/
    454MB before, 355/399/328MB after; allocated in step 2 ~1790MB
    before, ~1575MB after; step 2 2.2-4.9s before, 1.8-2.1s after.
  - the first run after the change, which rewrites the old shards:
    424MB peak, 2161MB allocated, 3.4s step 2 (once).
  - warm: peak 366/372MB before, 295/330MB after.

Not tried: Windows with real session data (the box has none).
This commit is contained in:
yetone
2026-10-25 15:55:54 +08:00
parent 3e400b6346
commit 67a137744f
3 changed files with 188 additions and 26 deletions
+71 -18
View File
@@ -266,7 +266,7 @@ func readCalls(f file) *callFile {
old, generation := callCache[f.path], callGeneration
callsMu.Unlock()
if old == nil {
old = restoreCallContinuation(loadCalls(f))
old = loadKept(f)
}
if old != nil && old.Size == f.size && old.Mod == f.mod.UnixNano() {
callsMu.Lock()
@@ -399,7 +399,7 @@ func callsAlong(f file) *callsRide {
old, generation := callCache[f.path], callGeneration
callsMu.Unlock()
if old == nil {
old = restoreCallContinuation(loadCalls(f))
old = loadKept(f)
}
if old != nil && old.Size == f.size && old.Mod == f.mod.UnixNano() {
lock.Unlock()
@@ -460,8 +460,23 @@ type callFrame struct {
State callDiskState
Strings []string
Patches []callPatch
// More: the frames after it, up to one without More, are one write's
// (framePatches); a file ending in one was cut off mid-write
More bool
// Calls is how many calls the file holds after this write's frames,
// to make room for them all at the first
Calls int
}
// framePatches is the most patches one frame holds. A write was one frame
// whatever its size, and a frame is decoded whole: a Codex session of 52k
// calls was one 8 MB frame, and reading it allocated ~100 MB and held ~70 MB
// at once (24 MB of patches beside the calls made of them), the largest
// part of the peak a start after an update reached in rebuilding the
// Requests cache (#3493). A write is cut into frames of this many, read one
// after another into the same buffers.
const framePatches = 2048
// Disk state contains only scalar continuation metadata. Even a nil runtime
// index makes gob emit its recursive type descriptors in every append frame.
// Keep those types entirely outside the wire schema.
@@ -552,6 +567,7 @@ func loadCalls(f file) *callFile {
}()
var st *callFile
var calls []Call
var big, more bool
msgs := map[string]int{}
began := map[string]time.Time{}
for {
@@ -583,10 +599,13 @@ func loadCalls(f file) *callFile {
if st != nil && frame.State.Off < st.Off {
return nil
}
// a frame's patches are mostly new calls: room for them at once,
// rather than append's doublings, which a warm start paid ~500 MB
// for across every cached file
calls = slices.Grow(calls, len(frame.Patches))
big = big || len(frame.Patches) > framePatches
more = frame.More
// room for the write's calls at once (its frames' Calls; an older
// frame's patches, mostly new calls), rather than append's
// doublings, which a warm start paid ~500 MB for across every
// cached file
calls = slices.Grow(calls, max(len(frame.Patches), frame.Calls-len(calls)))
for _, p := range frame.Patches {
if p.Index < 0 || p.Index > len(calls) {
return nil
@@ -612,17 +631,58 @@ func loadCalls(f file) *callFile {
}
st = frame.State.restore()
}
if st == nil {
if st == nil || more {
return nil
}
st.Calls, st.Msgs, st.Began = calls, msgs, began
st.bigFrame = big
return st
}
// loadKept is the calls kept on disk for f, under f's callLock. A file
// written as one frame larger than framePatches, before frames were cut,
// is written again in frames, once.
func loadKept(f file) *callFile {
st := restoreCallContinuation(loadCalls(f))
if st != nil && st.bigFrame {
st.bigFrame = false
writeCalls(st, 0, false)
}
return st
}
func writeCalls(st *callFile, start int, appendOnly bool) {
frame := callFrame{State: diskCallState(st), Strings: []string{""}}
dict := map[string]uint32{"": 0}
state := diskCallState(st)
var data bytes.Buffer
var frame callFrame
var dict map[string]uint32
var header [8]byte
ok := true
// flush adds the frame to data, its header in front
flush := func(more bool) {
frame.More = more
at := data.Len()
data.Write(header[:])
if gob.NewEncoder(&data).Encode(frame) != nil {
ok = false
return
}
b := data.Bytes()
binary.LittleEndian.PutUint32(b[at:], uint32(len(b)-at-len(header)))
binary.LittleEndian.PutUint32(b[at+4:], crc32.ChecksumIEEE(b[at+len(header):]))
}
begin := func() {
frame = callFrame{State: state, Strings: []string{""}, Calls: len(st.Calls)}
dict = map[string]uint32{"": 0}
}
begin()
add := func(i int) {
if len(frame.Patches) == framePatches {
if flush(true); !ok {
return
}
begin()
}
p := callPatch{Index: i, Call: st.Calls[i], Began: st.Began[st.Calls[i].Msg]}
p.Call.File = ""
for j, field := range callText(&p.Call) {
@@ -645,13 +705,9 @@ func writeCalls(st *callFile, start int, appendOnly bool) {
for i := start; i < len(st.Calls); i++ {
add(i)
}
var data bytes.Buffer
if gob.NewEncoder(&data).Encode(frame) != nil {
if flush(false); !ok {
return
}
var header [8]byte
binary.LittleEndian.PutUint32(header[:4], uint32(data.Len()))
binary.LittleEndian.PutUint32(header[4:], crc32.ChecksumIEEE(data.Bytes()))
dir := callCacheDir()
if os.MkdirAll(dir, 0700) != nil {
return
@@ -669,10 +725,7 @@ func writeCalls(st *callFile, start int, appendOnly bool) {
if !appendOnly {
defer os.Remove(out.Name())
}
_, err = out.Write(header[:])
if err == nil {
_, err = out.Write(data.Bytes())
}
_, err = out.Write(data.Bytes())
if closeErr := out.Close(); err == nil {
err = closeErr
}
+107
View File
@@ -1,8 +1,14 @@
package sessions
import (
"bytes"
"encoding/binary"
"encoding/gob"
"fmt"
"hash/crc32"
"os"
"path/filepath"
"slices"
"testing"
"time"
)
@@ -77,3 +83,104 @@ func TestLoadedCallsKeepNothingOfTheLastShard(t *testing.T) {
}
}
}
// A write is cut into frames of framePatches, read back as one (#3493); a
// file cut off after one of them is no file, as a torn frame is; and a
// file written as one large frame before is read whole and written again
// in frames.
func TestCallsWrittenInFrames(t *testing.T) {
d := setupCalls(t)
path := filepath.Join(d.claude, "projects", "p", "s.jsonl")
st := &callFile{Path: path, Agent: "claude", Off: 77, Began: map[string]time.Time{}}
n := 2*framePatches + 100
for i := range n {
msg := fmt.Sprint("msg", i)
st.Calls = append(st.Calls, Call{Time: time.Unix(int64(i), 0), Agent: "claude", Session: "s", Model: fmt.Sprint("m", i%3), Msg: msg})
st.Began[msg] = time.Unix(int64(i)-1, 0)
}
frames := func() (sizes []int) {
b, err := os.ReadFile(callCachePath(path))
if err != nil {
t.Fatal(err)
}
for len(b) >= 8 {
size := int(binary.LittleEndian.Uint32(b))
var f callFrame
if decodeFrame(b[8:8+size], &f) != nil {
t.Fatal("a frame doesn't decode")
}
sizes = append(sizes, len(f.Patches))
b = b[8+size:]
}
return sizes
}
check := func(what string) {
t.Helper()
got := loadKept(file{path: path, agent: "claude"})
if got == nil || len(got.Calls) != n || got.Off != 77 {
t.Fatalf("%s: not read back", what)
}
for i, c := range got.Calls {
if c.Msg != fmt.Sprint("msg", i) || c.Model != fmt.Sprint("m", i%3) || !c.Time.Equal(time.Unix(int64(i), 0)) || c.File != path {
t.Fatalf("%s: call %d is %+v", what, i, c)
}
}
if !got.Began["msg4000"].Equal(time.Unix(3999, 0)) || got.Msgs["msg4000"] != 4000 {
t.Fatalf("%s: messages not read back", what)
}
if cap(got.Calls)-len(got.Calls) > len(got.Calls)/100 {
t.Fatalf("%s: %d calls read into a slice of %d", what, n, cap(got.Calls))
}
}
writeCalls(st, 0, false)
if got := frames(); !slices.Equal(got, []int{framePatches, framePatches, 100}) {
t.Fatalf("frames of %v patches", got)
}
check("cut")
// cut off after the first frame
b, _ := os.ReadFile(callCachePath(path))
first := 8 + int(binary.LittleEndian.Uint32(b))
if err := os.WriteFile(callCachePath(path), b[:first], 0600); err != nil {
t.Fatal(err)
}
if loadCalls(file{path: path, agent: "claude"}) != nil {
t.Fatal("a file cut off mid-write read as whole")
}
// as written before frames were cut: one frame of every patch
old := callFrame{State: diskCallState(st), Strings: []string{""}}
dict := map[string]uint32{"": 0}
for i := range st.Calls {
p := callPatch{Index: i, Call: st.Calls[i], Began: st.Began[st.Calls[i].Msg]}
for j, field := range callText(&p.Call) {
id, ok := dict[*field]
if !ok {
id = uint32(len(old.Strings))
dict[*field] = id
old.Strings = append(old.Strings, *field)
}
p.Text[j] = id
*field = ""
}
old.Patches = append(old.Patches, p)
}
var data bytes.Buffer
if err := gob.NewEncoder(&data).Encode(old); err != nil {
t.Fatal(err)
}
var header [8]byte
binary.LittleEndian.PutUint32(header[:4], uint32(data.Len()))
binary.LittleEndian.PutUint32(header[4:], crc32.ChecksumIEEE(data.Bytes()))
if err := os.WriteFile(callCachePath(path), append(header[:], data.Bytes()...), 0600); err != nil {
t.Fatal(err)
}
if got := frames(); !slices.Equal(got, []int{n}) {
t.Fatalf("old file: frames of %v patches", got)
}
check("one large frame")
if got := frames(); !slices.Equal(got, []int{framePatches, framePatches, 100}) {
t.Fatalf("one large frame written again as frames of %v patches", got)
}
check("written again")
}
+10 -8
View File
@@ -69,14 +69,16 @@ type callFile struct {
Claude *claudeUsageState
ContentHash string
dirty map[int]bool
Size int64
Mod int64 // unix nanoseconds
Off int64 // after the last whole line read
Head string // hash of the prefix, to tell one replaced from one grown
HeadSize int
Path string
Calls []Call
Agent string
// bigFrame: read from a frame of more than framePatches (loadCalls)
bigFrame bool
Size int64
Mod int64 // unix nanoseconds
Off int64 // after the last whole line read
Head string // hash of the prefix, to tell one replaced from one grown
HeadSize int
Path string
Calls []Call
Agent string
// where the line being handled begins and ends, and where the last reply's did
At, End, AsstEnd int64
Strs map[string]string