sessions: a Claude session read from its start has its calls read on the parse's own pass (#2278)

A first start parsed every Claude session for the Sessions page
(parseWith, claudeLine) and then scanned each again for Requests' calls
(readCalls, claudeCallLine): on the 13 GB fixture HOME that second scan
was ~20 s of the start's CPU (scanThin under readCalls in the profile).

callsAlong, which already let a packed Codex rollout's calls ride along
its parse, now does the same for claude and claude-desktop files whose
calls are read from the start: nothing kept, or kept without their
revision window (prepareCalls would start over anyway). Each line is
shown to both heads and handed to claudeLine and claudeCallLine as each
asked, both thinned by thinClaude as on their own scans. finish keeps
what readCalls keeps for Claude: writeCalls, then withoutRevisions for a
file not being worked on when the kept calls had no window, then
writeCallRevisions. Calls kept with their window are read on from where
they were by readCalls, as before, and a summary read on from its own
offset drops the ride (parseWith) so neither reader misses a line.

The ride keeps its calls on disk only (the shard and the revision
window), so a Sessions read still loads no calls into memory
(TestCallsDoNotInflateSessionIndex); readCalls' fast path takes the
window back from disk for a shard it loads (withCallRevisions), as
prepareCalls did for a changed one. Only Claude files with no shard and
nothing kept ride: calls read before are read on or again by readCalls
exactly as they were.

Run on mote (M5 Pro) at the pushed tree:
- go test -count=1 -timeout 45m ./internal/sessions ./internal/usage: ok.
  ./internal/gui: ok but TestCoveredWindowStaysUp, killed at its 30s
  deadline alone too (an AppKit window on mote, #4125/#2645).
- go vet sessions; GOOS=linux and windows go vet sessions, usage: ok.
- New TestClaudeSessionReadOnceForSessionsAndCalls: each Claude file
  scanned once on sessions-then-calls, calls and sessions equal to a read
  of each on its own, and a grown file read on, not from its start.
- Broken by hand: the ride off for Claude turns the new test red
  (scanned 2 times); dropping the fast path's withCallRevisions turns
  TestEvictedClaudeRevisionsReleasedAndRebuilt,
  TestClaudeLargeWindowSurvivesIdleAndSmallFiles,
  TestClaudeWindowReservationsAndRemoval and
  TestLargeClaudeFileKeepsAppendContinuation red.
- Cold start on the fixture HOME (13 GB of Claude projects, 52 GB of
  Codex), 75 s each, alternating, load 12-19: previous head 3:27.98 and
  3:18.01 of CPU, this one 3:03.74 and 3:06.88. Footprint peak 328/334
  MB before, 339/333 MB after (unchanged). The heatmap, requests,
  sessions overview (0, 7, 30 days) and stats answers are byte-equal in
  both rounds.

Not tried: Claude Desktop's Code tab files on a real Desktop install
(they take the same path as claude, agent claude-desktop).
This commit is contained in:
yetone
2026-10-31 16:54:37 +08:00
parent 6893cfbe34
commit e4c7841779
3 changed files with 178 additions and 9 deletions
+40 -6
View File
@@ -9,10 +9,12 @@ import (
"encoding/binary"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"hash/crc32"
"hash/fnv"
"io"
"io/fs"
"maps"
"os"
"path/filepath"
@@ -295,6 +297,11 @@ func readCalls(f file) *callFile {
owned = true
}
if old != nil && old.Size == f.size && old.Mod == f.mod.UnixNano() {
if owned {
// a Claude session's calls a parse read along (callsRide) left
// their window on disk, not here
old = withCallRevisions(old)
}
callsMu.Lock()
if generation == callGeneration {
keepCalls(f.path, old)
@@ -402,21 +409,26 @@ func readCalls(f file) *callFile {
// Codex app packs or repacks every rollout (11,591 on 10-20) the start's
// warm-up parsed each for the Sessions page and then read each again for
// Requests' calls: ~48 GB decompressed twice. Reading both on one pass
// leaves readCalls a shard on disk that is already up to date.
// leaves readCalls a shard on disk that is already up to date. A Claude
// session read from its start rides too: a first start scanned each again
// for its calls, ~20 s of its CPU on 13 GB of them (#2278).
type callsRide struct {
f file
st *callFile
generation uint64
lock *sync.Mutex
sum, calls bool // what each reader's head said of the line being read
claude bool
}
// callsAlong is a ride for f's calls when f is a packed Codex rollout whose
// calls are to be read again, and nil otherwise. It holds the file's calls
// lock until release, so a readCalls of the file meanwhile waits for what
// the ride reads rather than read it again.
// calls are to be read again, or a Claude session whose calls were never
// read, and nil otherwise. It holds the file's calls lock until release, so
// a readCalls of the file meanwhile waits for what the ride reads rather
// than read it again.
func callsAlong(f file) *callsRide {
if f.agent != "codex" || !packed(f.path) || f.cold || wslCold(f.path) {
claude := f.agent == "claude" || f.agent == "claude-desktop"
if !(f.agent == "codex" && packed(f.path)) && !claude || f.cold || wslCold(f.path) {
return nil
}
lock := callLock(f.path)
@@ -424,6 +436,14 @@ func callsAlong(f file) *callsRide {
callsMu.Lock()
old, generation := callCache[f.path], callGeneration
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) {
lock.Unlock()
return nil
}
return &callsRide{f: f, st: prepareCalls(f, nil, false), generation: generation, lock: lock, claude: true}
}
owned := false
if old == nil {
old = loadKept(f)
@@ -450,7 +470,11 @@ func (r *callsRide) ride(head func([]byte) bool, line func([]byte, int64, int64)
}
if r.calls {
r.st.At, r.st.End = start, end
codexCallLine(r.st, b)
if r.claude {
claudeCallLine(r.st, b)
} else {
codexCallLine(r.st, b)
}
}
return true
}
@@ -469,7 +493,17 @@ func (r *callsRide) finish(off int64, err error) {
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()
}
writeCallRevisions(st)
}
st.dirty = nil
if r.claude {
// on disk only: a Sessions read keeps no calls (readCalls loads them)
return
}
callsMu.Lock()
if r.generation == callGeneration {
keepCalls(f.path, st)
+129
View File
@@ -0,0 +1,129 @@
package sessions
import (
"fmt"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
"testing"
"time"
)
// TestClaudeSessionReadOnceForSessionsAndCalls: a first start parsed every
// Claude session for the Sessions page, then scanned each again for
// Requests' calls (#2278). A session read from its start now has its calls
// read on the parse's own pass, and what both pages get is what the two
// reads gave; one that grew is read on from where each was.
func TestClaudeSessionReadOnceForSessionsAndCalls(t *testing.T) {
claude, _ := setup(t)
path := filepath.Join(claude, "projects", "-work-night", "33333333-2222-3333-4444-555555555555.jsonl")
var lines []string
for i := 0; i < 40; i++ {
lines = append(lines, strings.TrimSuffix(ccMsg(fmt.Sprintf("msg_%02d", i), fmt.Sprintf("2026-09-21T10:%02d:00Z", i), 100+i, 20+i), "\n"))
}
writeLines(t, path, lines...)
forget := func() {
os.Remove(CachePath())
os.RemoveAll(callCacheDir())
Reset()
}
var mu sync.Mutex
scans := map[string][]int64{}
scanHook = func(p string, off int64) {
if strings.HasPrefix(p, claude) && strings.HasSuffix(p, ".jsonl") {
mu.Lock()
scans[p] = append(scans[p], off)
mu.Unlock()
}
}
t.Cleanup(func() { scanHook = nil })
counted := func() map[string][]int64 {
mu.Lock()
defer mu.Unlock()
out := scans
scans = map[string][]int64{}
return out
}
readCallsAll := func() map[string][]Call {
out := map[string][]Call{}
for _, s := range CallSources() {
if s.Agent == "claude" {
out[s.Path] = ReadCallSource(s)
}
}
return out
}
day := time.Date(2026, 9, 30, 0, 0, 0, 0, time.UTC)
reference := func() (map[string][]Call, []Session, Stats) {
forget()
calls := readCallsAll()
list, stats := List(0), StatsAt(0, day)
counted()
return calls, list, stats
}
// as before: calls read first, then the summaries, each on a scan of
// its own
wantCalls, wantList, wantStats := reference()
calls := 0
for _, cs := range wantCalls {
calls += len(cs)
}
if calls < 40 {
t.Fatalf("only %d calls read: the fixture tests nothing", calls)
}
// the warm-up's order with nothing kept: sessions, then calls
forget()
counted()
list, stats := List(0), StatsAt(0, day)
got := readCallsAll()
n := 0
for p, offs := range counted() {
if len(offs) != 1 {
t.Errorf("%s scanned %d times, want once", p, len(offs))
}
n++
}
if n < 2 {
t.Fatalf("%d Claude sessions scanned: the fixture tests nothing", n)
}
if !reflect.DeepEqual(got, wantCalls) {
t.Errorf("calls differ from their own read's")
}
if !reflect.DeepEqual(list, wantList) || !reflect.DeepEqual(stats, wantStats) {
t.Errorf("sessions differ from a read without the calls")
}
// a session grows: each reader reads on from where it was, and both
// pages get what a read from nothing gives
f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
t.Fatal(err)
}
if _, err := f.WriteString(ccMsg("msg_99", "2026-09-21T11:30:00Z", 500, 50)); err != nil {
t.Fatal(err)
}
f.Close()
later := time.Now().Add(time.Minute)
if err := os.Chtimes(path, later, later); err != nil {
t.Fatal(err)
}
list, stats = List(0), StatsAt(0, day)
got = readCallsAll()
for _, off := range counted()[path] {
if off == 0 {
t.Errorf("the grown session was read again from its start")
}
}
wantCalls, wantList, wantStats = reference()
if !reflect.DeepEqual(got, wantCalls) {
t.Errorf("after growing: calls differ from a read from nothing")
}
if !reflect.DeepEqual(list, wantList) || !reflect.DeepEqual(stats, wantStats) {
t.Errorf("after growing: sessions differ from a read from nothing")
}
}
+9 -3
View File
@@ -1824,9 +1824,11 @@ func parse(f file, old *state) *state { return parseWith(f, old, nil) }
// parseWith is parse with calls, when not nil, reading the file's calls on
// the same pass.
func parseWith(f file, old *state, calls *callsRide) *state {
if calls != nil {
defer calls.release()
}
defer func() {
if calls != nil {
calls.release()
}
}()
// Summary caches contain aggregates only. After a restart, a changed
// Codex file rebuilds its transient response index from the source.
if f.agent == "codex" && old != nil && old.Codex == nil {
@@ -1862,6 +1864,10 @@ func parseWith(f file, old *state, calls *callsRide) *state {
parser.line(s, b, f.main)
return true
}
if calls != nil && s.Off != 0 {
calls.release() // the summary reads on from where it was
calls = nil
}
if calls != nil {
head, line = calls.ride(head, line)
}