diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index a3a1e6519..462504d2c 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -1062,6 +1062,24 @@ writes rebuilt the whole ledger, and the app grew to 85 GB. Verification: `TestCodexModelEffort*` in `codex_effort_shared_test.go` (the codex-only answer equals the whole ledger's), and `sessions-overview-once.test.cjs`. +The calls a Sessions read rides along for an idle Claude Code session +(not changed within the hour) it reads from the start go to a pack +(`calls-v15/*.pack`), not to a shard of the session's own: one file for +every such session the pass read, written when the pass ends (and every +32 MB, and in `Saved`), with each session's frames as its shard would +hold them and an index with a CRC at its end. A session being written +keeps its shard and `.rev`, which the lines it gains are appended to. +A session's own shard, which any later read of it writes whole (a pack is never appended to), is read before the pack. A +pack that can't be read whole is as if it were not there, and its +sessions are read again; the hourly sweep removes a pack none of whose +sessions is listed. Before this, a cold read of 12,000 sessions made +~21,000 files, and on Windows Defender scanned each as it closed: a +cold page took 20.7 to 31.7 s on xiaomi-gpu, against 5.7 to 5.9 s with +the pack, and 2.0 to 2.2 s on a restart (shangyuan0818 on X). See +[`internal/sessions/call_pack.go`](../../internal/sessions/call_pack.go), +`TestColdSessionsReadWritesOnePack`, `TestPackedCallsServeRequests` and +`TestPackedSessionGrows`. + ### Calls an app reports itself `POST /v1/magpie/usage/requests` diff --git a/internal/sessions/call_cache.go b/internal/sessions/call_cache.go index 8d323e713..0306398de 100644 --- a/internal/sessions/call_cache.go +++ b/internal/sessions/call_cache.go @@ -114,6 +114,7 @@ func callCacheDir() string { return filepath.Join(filepath.Dir(Cache func callCachePath(path string) string { return filepath.Join(callCacheDir(), hashHead(path)+".gob") } func resetCalls() { + forgetCallPacks() callsMu.Lock() defer callsMu.Unlock() callCache, callOrder = map[string]*callFile{}, nil @@ -199,6 +200,7 @@ func pruneCalls(files []file) { for _, f := range files { shards[hashHead(f.path)+".gob"] = true } + sweepCallPacks(root, on) entries, _ := os.ReadDir(root) for _, e := range entries { if e.IsDir() { @@ -482,7 +484,7 @@ func callsAlong(f file, sum *state) *callsRide { callsMu.Unlock() if claude { // calls read before are read on, or again, by readCalls as they were - if _, err := os.Stat(callCachePath(f.path)); old != nil || !errors.Is(err, fs.ErrNotExist) { + if _, err := os.Stat(callCachePath(f.path)); old != nil || !errors.Is(err, fs.ErrNotExist) || callsPacked(f.path) { lock.Unlock() return nil } @@ -536,12 +538,16 @@ func (r *callsRide) finish(off int64, err error) { st, f := r.st, r.f st.Off, st.Size, st.Mod = off, f.size, f.mod.UnixNano() st.ContentHash = prefixHash(f.path, off) - writeCalls(st, 0, false) - if r.claude { - if st.Claude != nil && !workingRevision(f.mod.UnixNano(), time.Now()) { - st = st.withoutRevisions() - } + if r.claude && !workingRevision(f.mod.UnixNano(), time.Now()) { + // idle: in the pass's pack, with no window, not a shard of its + // own (call_pack.go); a session being written keeps its shard, + // which the lines it gains are appended to + packCalls(st.withoutRevisions()) + _ = os.Remove(callRevisionsPath(st.Path)) // one an older read left + st.dirty = nil + return } + writeCalls(st, 0, false) writeCallRevisions(st) st.dirty = nil if r.claude { @@ -673,11 +679,16 @@ func (k *frameBuffer) frame() *callFrame { } func loadCalls(f file) *callFile { - in, err := os.Open(callCachePath(f.path)) - if err != nil { + var in io.Reader + if sf, err := os.Open(callCachePath(f.path)); err == nil { + defer sf.Close() + in = sf + } else if b, ok := packedCalls(f.path); ok { + in = bytes.NewReader(b) + } else { return nil } - defer in.Close() + var err error k := frameBuffers.Get().(*frameBuffer) defer func() { k.frame() // the pool holds no file's strings @@ -783,7 +794,6 @@ var framePatchBufs = sync.Pool{New: func() any { return new([]callPatch) }} var frameBytes = sync.Pool{New: func() any { return new(bytes.Buffer) }} func writeCalls(st *callFile, start int, appendOnly bool) { - state := diskCallState(st) dir := callCacheDir() if os.MkdirAll(dir, 0700) != nil { return @@ -792,7 +802,14 @@ func writeCalls(st *callFile, start int, appendOnly bool) { var err error if appendOnly { out, err = os.OpenFile(callCachePath(st.Path), os.O_WRONLY|os.O_APPEND, 0600) - } else { + if errors.Is(err, fs.ErrNotExist) { + // kept in a pack (call_pack.go), which is never appended to: + // the calls are written whole to a shard of their own, which + // is read before the pack + start, appendOnly = 0, false + } + } + if !appendOnly { out, err = os.CreateTemp(dir, "calls-*.tmp") } if err != nil { @@ -801,6 +818,16 @@ func writeCalls(st *callFile, start int, appendOnly bool) { if !appendOnly { defer os.Remove(out.Name()) } + ok := encodeCalls(out, st, start) + if closeErr := out.Close(); ok && closeErr == nil && !appendOnly { + _ = os.Rename(out.Name(), callCachePath(st.Path)) + } +} + +// encodeCalls writes st's calls from start, and those before it that +// changed, to out as frames, and says whether every frame was written. +func encodeCalls(out io.Writer, st *callFile, start int) bool { + state := diskCallState(st) data := frameBytes.Get().(*bytes.Buffer) defer func() { if data.Cap() <= 4<<20 { @@ -884,7 +911,5 @@ func writeCalls(st *callFile, start int, appendOnly bool) { if ok { flush(false) } - if closeErr := out.Close(); ok && closeErr == nil && !appendOnly { - _ = os.Rename(out.Name(), callCachePath(st.Path)) - } + return ok } diff --git a/internal/sessions/call_pack.go b/internal/sessions/call_pack.go new file mode 100644 index 000000000..f81e3e830 --- /dev/null +++ b/internal/sessions/call_pack.go @@ -0,0 +1,311 @@ +package sessions + +import ( + "bytes" + "encoding/binary" + "encoding/gob" + "hash/crc32" + "io" + "os" + "path/filepath" + "slices" + "strconv" + "sync" + "time" +) + +// A cold read of a Claude Code history wrote each session's calls to a +// shard of its own, made, closed and renamed for each of ~12,000 +// sessions (and a revisions file beside the recent ones). On Windows +// Defender scans every file as it is closed, and those writes were 15 s of +// a Sessions page's 19 s. The calls a Sessions read rides along for an +// idle session are kept in packs instead: one file for many sessions, +// written once a pass (or every packFlushBytes), each session's frames as +// its shard holds them. A session being written keeps its own shard and +// revisions, so the lines it gains are appended there. +// +// A session's own shard, written by any later read of it, is read before +// its pack's section, and a pack is never written to again. A pack that +// can't be read whole (cut off, its trailer or a frame's CRC wrong) is as +// if it were not there: its sessions' calls are read again from their +// files. + +const packMagic = "MPCALLS1" + +// packFlushBytes is how much of a pass is held before it goes to a pack. +const packFlushBytes = 32 << 20 + +type packEntry struct { + Path string + Off, N int64 // the calls' frames +} + +// packRef is where a session's packed calls are: in file at the entry's +// offsets, or, before its pack is written, in mem. +type packRef struct { + file string + e packEntry + mem []byte +} + +var callPacks struct { + sync.Mutex + root string // the calls dir byPath is of + loaded bool + byPath map[string]*packRef + pending []*packRef + bytes int + seq int +} + +// packsFor makes byPath that of root, reading the packs there once. Held +// with callPacks' lock. +func packsFor(root string) { + if callPacks.root == root && callPacks.loaded { + return + } + callPacks.root, callPacks.loaded = root, true + callPacks.byPath = map[string]*packRef{} + callPacks.pending, callPacks.bytes = nil, 0 + names, _ := filepath.Glob(filepath.Join(root, "*.pack")) + slices.Sort(names) // named by when written: a later pack's entry stands + for _, name := range names { + for _, e := range readPackIndex(name) { + callPacks.byPath[e.Path] = &packRef{file: name, e: e} + } + } +} + +// readPackIndex is the entries of the pack at name, or none when it can't +// be read whole. +func readPackIndex(name string) []packEntry { + f, err := os.Open(name) + if err != nil { + return nil + } + defer f.Close() + st, err := f.Stat() + tail := int64(len(packMagic) + 8) + if err != nil || st.Size() < int64(len(packMagic))+tail { + return nil + } + head := make([]byte, len(packMagic)) + end := make([]byte, tail) + if _, err := f.ReadAt(head, 0); err != nil || string(head) != packMagic { + return nil + } + if _, err := f.ReadAt(end, st.Size()-tail); err != nil || string(end[8:]) != packMagic { + return nil + } + n := int64(binary.LittleEndian.Uint32(end[:4])) + at := st.Size() - tail - n + if n == 0 || at < int64(len(packMagic)) { + return nil + } + b := make([]byte, n) + if _, err := f.ReadAt(b, at); err != nil || crc32.ChecksumIEEE(b) != binary.LittleEndian.Uint32(end[4:8]) { + return nil + } + var es []packEntry + if gob.NewDecoder(bytes.NewReader(b)).Decode(&es) != nil { + return nil + } + for _, e := range es { + if e.Off < int64(len(packMagic)) || e.N <= 0 || e.Off+e.N > at { + return nil + } + } + return es +} + +// packCalls holds st's calls, with no revisions window, for the pass's +// pack. +func packCalls(st *callFile) { + var b bytes.Buffer + if !encodeCalls(&b, st, 0) { + return + } + root := callCacheDir() + callPacks.Lock() + packsFor(root) + r := &packRef{e: packEntry{Path: st.Path}, mem: b.Bytes()} + callPacks.byPath[st.Path] = r + callPacks.pending = append(callPacks.pending, r) + callPacks.bytes += len(r.mem) + full := callPacks.bytes >= packFlushBytes + callPacks.Unlock() + if full { + flushCallPack() + } +} + +// flushCallPack writes the calls packCalls holds to a pack of their own. +func flushCallPack() { + callPacks.Lock() + refs, root := callPacks.pending, callPacks.root + callPacks.pending, callPacks.bytes = nil, 0 + callPacks.seq++ + name := filepath.Join(root, time.Now().UTC().Format("20060102T150405.000000000")+"-"+strconv.Itoa(callPacks.seq)+".pack") + callPacks.Unlock() + if len(refs) == 0 { + return + } + es, ok := writePack(name, refs) + callPacks.Lock() + defer callPacks.Unlock() + for i, r := range refs { + if callPacks.root != root || callPacks.byPath[r.e.Path] != r { + continue // forgotten (Reset), or packed again since + } + if ok { + callPacks.byPath[r.e.Path] = &packRef{file: name, e: es[i]} + } else { + // not on disk: read again from its file next time + delete(callPacks.byPath, r.e.Path) + } + } +} + +// writePack writes refs to a pack at name, through a temp file renamed +// over it, and says where each one's bytes went. +func writePack(name string, refs []*packRef) ([]packEntry, bool) { + dir := filepath.Dir(name) + if os.MkdirAll(dir, 0700) != nil { + return nil, false + } + out, err := os.CreateTemp(dir, "calls-*.tmp") + if err != nil { + return nil, false + } + defer os.Remove(out.Name()) + w := &countingWriter{w: out} + ok := writeAll(w, []byte(packMagic)) + es := make([]packEntry, len(refs)) + for i, r := range refs { + es[i] = packEntry{Path: r.e.Path, Off: w.n, N: int64(len(r.mem))} + ok = ok && writeAll(w, r.mem) + } + var idx bytes.Buffer + ok = ok && gob.NewEncoder(&idx).Encode(es) == nil + var end [8]byte + binary.LittleEndian.PutUint32(end[:4], uint32(idx.Len())) + binary.LittleEndian.PutUint32(end[4:], crc32.ChecksumIEEE(idx.Bytes())) + ok = ok && writeAll(w, idx.Bytes()) && writeAll(w, end[:]) && writeAll(w, []byte(packMagic)) + if cerr := out.Close(); !ok || cerr != nil || os.Rename(out.Name(), name) != nil { + return nil, false + } + return es, true +} + +type countingWriter struct { + w io.Writer + n int64 +} + +func (c *countingWriter) Write(b []byte) (int, error) { + n, err := c.w.Write(b) + c.n += int64(n) + return n, err +} + +func writeAll(w io.Writer, b []byte) bool { + _, err := w.Write(b) + return err == nil +} + +// packedCalls is the frames kept in a pack for path; ok false when it has +// none or they can't be read. +func packedCalls(path string) (calls []byte, ok bool) { + root := callCacheDir() + callPacks.Lock() + packsFor(root) + r := callPacks.byPath[path] + callPacks.Unlock() + if r == nil { + return nil, false + } + if r.mem != nil { + return r.mem, true + } + f, err := os.Open(r.file) + if err != nil { + forgetPacked(path, r) // removed: its calls are read again + return nil, false + } + defer f.Close() + calls = make([]byte, r.e.N) + if _, err := f.ReadAt(calls, r.e.Off); err != nil { + forgetPacked(path, r) + return nil, false + } + return calls, true +} + +// callsPacked says whether a pack holds path's calls. +func callsPacked(path string) bool { + root := callCacheDir() + callPacks.Lock() + defer callPacks.Unlock() + packsFor(root) + r := callPacks.byPath[path] + if r != nil && r.file != "" { + if _, err := os.Stat(r.file); err != nil { + delete(callPacks.byPath, path) + return false + } + } + return r != nil +} + +// forgetPacked forgets path's packed calls when they are still r. +func forgetPacked(path string, r *packRef) { + callPacks.Lock() + if callPacks.byPath[path] == r { + delete(callPacks.byPath, path) + } + callPacks.Unlock() +} + +// forgetCallPacks writes what is held and forgets the packs read, for a +// Reset or another HOME. +func forgetCallPacks() { + flushCallPack() + callPacks.Lock() + callPacks.root, callPacks.loaded, callPacks.byPath = "", false, nil + callPacks.Unlock() +} + +// sweepCallPacks removes the packs in root none of whose sessions is +// still listed (on), and forgets them. A pack written in the last minute +// is left: its sessions may not point at it yet (flushCallPack). +func sweepCallPacks(root string, on map[string]struct{}) { + callPacks.Lock() + packsFor(root) + live := map[string]bool{} + for p, r := range callPacks.byPath { + if r.file == "" { + continue + } + if _, ok := on[p]; ok { + live[r.file] = true + } + } + callPacks.Unlock() + names, _ := filepath.Glob(filepath.Join(root, "*.pack")) + for _, name := range names { + if live[name] { + continue + } + if st, err := os.Stat(name); err != nil || time.Since(st.ModTime()) < time.Minute { + continue + } + callPacks.Lock() + for p, r := range callPacks.byPath { + if r.file == name { + delete(callPacks.byPath, p) + } + } + callPacks.Unlock() + _ = os.Remove(name) + } +} diff --git a/internal/sessions/call_pack_test.go b/internal/sessions/call_pack_test.go new file mode 100644 index 000000000..0f414b0af --- /dev/null +++ b/internal/sessions/call_pack_test.go @@ -0,0 +1,209 @@ +package sessions + +import ( + "fmt" + "os" + "path/filepath" + "reflect" + "strings" + "sync" + "testing" + "time" +) + +// packFixture writes n Claude Code sessions, the first `working` of them +// changed now (their revision windows kept) and the rest two days ago. +func packFixture(t *testing.T, claude string, n, working int) []string { + t.Helper() + var paths []string + for s := 0; s < n; s++ { + path := filepath.Join(claude, "projects", "-work-pack", fmt.Sprintf("44444444-2222-3333-4444-%012d.jsonl", s)) + var lines []string + for i := 0; i < 6; i++ { + lines = append(lines, strings.TrimSuffix(ccMsg(fmt.Sprintf("msg_%d_%d", s, i), fmt.Sprintf("2026-09-21T10:%02d:00Z", i), 100+i, 20+i), "\n")) + } + writeLines(t, path, lines...) + if s >= working { + old := time.Now().Add(-48 * time.Hour) + if err := os.Chtimes(path, old, old); err != nil { + t.Fatal(err) + } + } + paths = append(paths, path) + } + return paths +} + +// packDirFiles counts the files in the calls cache, by kind. +func packDirFiles(t *testing.T) map[string]int { + t.Helper() + out := map[string]int{} + entries, _ := os.ReadDir(callCacheDir()) + for _, e := range entries { + out[filepath.Ext(e.Name())]++ + } + return out +} + +// TestColdSessionsReadWritesOnePack: a cold Sessions read of a long +// Claude Code history made a shard and a revisions file for each session, +// each made, closed and renamed: ~21,000 files for 12,000 sessions, and on +// Windows Defender scanned each one as it closed, 15 s of the page's 19 s. +// The idle sessions' calls read along go to one pack a pass; one being +// written keeps its shard, which its new lines are appended to. +func TestColdSessionsReadWritesOnePack(t *testing.T) { + claude, codex := setup(t) + os.RemoveAll(codex) // Codex's calls are kept as before + paths := packFixture(t, claude, 60, 5) + Reset() + List(0) + Saved() + got := packDirFiles(t) + if got[".pack"] != 1 || got[".gob"] > 10 { + t.Fatalf("a cold read of 55 idle sessions and 5 being written wrote %v to the calls cache, want one .pack and shards for the 5 (and testdata's 3)", got) + } + for i, p := range paths { + _, err := os.Stat(callCachePath(p)) + if working := i < 5; working != (err == nil) { + t.Fatalf("session %d (being written %v) has a shard of its own: %v", i, working, err == nil) + } + if _, err := os.Stat(callRevisionsPath(p)); err == nil && i >= 5 { + t.Fatalf("idle session %d has a revisions file", i) + } + } +} + +// TestPackedCallsServeRequests: the calls a Sessions read packed are what +// Requests reads, after a restart too, without reading a session again; +// a pack cut off is as if it were not there, and its sessions are read +// again from their files. +func TestPackedCallsServeRequests(t *testing.T) { + claude, _ := setup(t) + paths := packFixture(t, claude, 20, 3) + readAll := func() map[string][]Call { + out := map[string][]Call{} + for _, s := range CallSources() { + if s.Agent == "claude" && strings.Contains(s.Path, "-work-pack") { + out[s.Path] = ReadCallSource(s) + } + } + return out + } + var mu sync.Mutex + scanned := map[string]int{} + scanHook = func(p string, _ int64) { + if strings.Contains(p, "-work-pack") { + mu.Lock() + scanned[p]++ + mu.Unlock() + } + } + t.Cleanup(func() { scanHook = nil }) + scans := func() int { + mu.Lock() + defer mu.Unlock() + n := 0 + for _, c := range scanned { + n += c + } + scanned = map[string]int{} + return n + } + + // the reference: calls read on their own, no cache + Reset() + want := readAll() + if len(want) != len(paths) { + t.Fatalf("%d sources read, want %d", len(want), len(paths)) + } + for p, cs := range want { + if len(cs) != 6 { + t.Fatalf("%s: %d calls, want 6", p, len(cs)) + } + } + Reset() + os.Remove(CachePath()) + os.RemoveAll(callCacheDir()) + + List(0) // packs the calls it reads along + Saved() + scans() + if got := readAll(); !reflect.DeepEqual(got, want) { + t.Fatalf("calls from the live pack differ from a read of their own") + } + if n := scans(); n != 0 { + t.Fatalf("the packed calls were read again: %d scans", n) + } + Reset() // a restart: the pack is read from disk + if got := readAll(); !reflect.DeepEqual(got, want) { + t.Fatalf("calls from the pack on disk differ from a read of their own") + } + if n := scans(); n != 0 { + t.Fatalf("the packed calls were read again after a restart: %d scans", n) + } + + // cut off: read again, and right + Reset() + os.Remove(CachePath()) + for p := range want { + os.Remove(callCachePath(p)) + os.Remove(callRevisionsPath(p)) + } + packs, _ := filepath.Glob(filepath.Join(callCacheDir(), "*.pack")) + if len(packs) != 1 { + t.Fatalf("%d packs, want 1", len(packs)) + } + b, err := os.ReadFile(packs[0]) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(packs[0], b[:len(b)/2], 0600); err != nil { + t.Fatal(err) + } + Reset() + if got := readAll(); !reflect.DeepEqual(got, want) { + t.Fatalf("calls with their pack cut off differ from a read of their own") + } + if n := scans(); n < len(paths) { + t.Fatalf("with the pack cut off only %d of %d sessions were read again", n, len(paths)) + } +} + +// TestPackedSessionGrows: a packed session that grows is read on, and its +// calls written whole to a shard of their own, which is read before the +// pack from then on. +func TestPackedSessionGrows(t *testing.T) { + claude, _ := setup(t) + paths := packFixture(t, claude, 4, 0) + Reset() + List(0) + Saved() + path := paths[0] + f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + t.Fatal(err) + } + f.WriteString(ccMsg("msg_grown", "2026-09-21T11:00:00Z", 500, 50)) + f.Close() + var calls []Call + for _, s := range CallSources() { + if s.Path == path { + calls = ReadCallSource(s) + } + } + if len(calls) != 7 { + t.Fatalf("%d calls after the session grew, want 7", len(calls)) + } + if _, err := os.Stat(callCachePath(path)); err != nil { + t.Fatalf("the grown session's calls have no shard of their own: %v", err) + } + Reset() + for _, s := range CallSources() { + if s.Path == path { + calls = ReadCallSource(s) + } + } + if len(calls) != 7 || calls[6].Msg != "msg_grown" { + t.Fatalf("after a restart: %d calls, want 7 ending in msg_grown", len(calls)) + } +} diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 045db6eeb..1ba882433 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -1656,6 +1656,7 @@ func saved() { saving.Unlock() ccFamilyWrites.Wait() ccRestWrites.Wait() + flushCallPack() } // saveHook, when a test sets it, runs before each save is written. @@ -1857,6 +1858,7 @@ func refresh(want, all []file) { if !unsaved { continue } + flushCallPack() mu.Lock() if generation == cacheGeneration { saveCacheWithin(checkpointGap) @@ -1865,6 +1867,7 @@ func refresh(want, all []file) { unsaved = false } } + flushCallPack() // the calls read along, in one pack (call_pack.go) mu.Lock() progress.finish() if generation == cacheGeneration {