diff --git a/internal/sessions/call_cache.go b/internal/sessions/call_cache.go index 96105f869..3caddb6de 100644 --- a/internal/sessions/call_cache.go +++ b/internal/sessions/call_cache.go @@ -135,7 +135,8 @@ func pruneCalls(files []file) { if e.IsDir() { continue } - orphan := strings.HasSuffix(e.Name(), ".gob") && !shards[e.Name()] + orphan := strings.HasSuffix(e.Name(), ".gob") && !shards[e.Name()] || + strings.HasSuffix(e.Name(), ".rev") && !shards[strings.TrimSuffix(e.Name(), ".rev")+".gob"] if strings.HasPrefix(e.Name(), "calls-") && strings.HasSuffix(e.Name(), ".tmp") { if st, err := e.Info(); err == nil && time.Since(st.ModTime()) > time.Hour { orphan = true @@ -298,7 +299,7 @@ func readCalls(f file) *callFile { if r, ok := lineCallReaders[f.agent]; ok && r.kept != nil && old != nil && !r.kept(old) { old = nil } - st := prepareCalls(f, old) + st := prepareCalls(f, withCallRevisions(old)) continued := old != nil && st.Off == old.Off && st.Off > 0 start := 0 if continued { @@ -331,6 +332,9 @@ 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") { + writeCallRevisions(st) + } st.dirty = nil callsMu.Lock() diff --git a/internal/sessions/call_revisions.go b/internal/sessions/call_revisions.go new file mode 100644 index 000000000..a82dfd7b3 --- /dev/null +++ b/internal/sessions/call_revisions.go @@ -0,0 +1,102 @@ +package sessions + +import ( + "bytes" + "encoding/gob" + "os" + "path/filepath" + "strings" +) + +// A Claude Code session's revision window (claudeUsageState) lived in memory +// alone, so once magpie started again, or let a ninth live session's window +// go, every Claude file that had grown was read again from its first line: a +// live 2 GB session took seconds of the first Requests page after every +// 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. +type callRevisions struct { + Off int64 + ContentHash string + CompactMs int64 + Window []claudeWindowEntry +} + +// claudeWindowEntry is one contribution, oldest first, as the window's +// eviction order has them. +type claudeWindowEntry struct { + Key string + M *claudeContribution +} + +func callRevisionsPath(path string) string { + return strings.TrimSuffix(callCachePath(path), ".gob") + ".rev" +} + +// writeCallRevisions keeps st's window beside its shard, or takes away a +// window kept before when st has none. +func writeCallRevisions(st *callFile) { + path := callRevisionsPath(st.Path) + if st.Claude == nil { + _ = os.Remove(path) + return + } + r := callRevisions{Off: st.Off, ContentHash: st.ContentHash, CompactMs: st.CompactMs} + for e := st.Claude.recent.Front(); e != nil; e = e.Next() { + m := e.Value.(*claudeContribution) + r.Window = append(r.Window, claudeWindowEntry{m.key, m}) + } + var data bytes.Buffer + if gob.NewEncoder(&data).Encode(r) != nil { + return + } + out, err := os.CreateTemp(filepath.Dir(path), "calls-*.tmp") + if err != nil { + return + } + defer os.Remove(out.Name()) + _, err = out.Write(data.Bytes()) + if closeErr := out.Close(); err == nil { + err = closeErr + } + if err == nil { + _ = os.Rename(out.Name(), path) + } +} + +// 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 == "" { + return old + } + data, err := os.ReadFile(callRevisionsPath(old.Path)) + if err != nil { + return old + } + var r callRevisions + if gob.NewDecoder(bytes.NewReader(data)).Decode(&r) != nil || r.Off != old.Off || r.ContentHash != old.ContentHash { + return old + } + w := &claudeUsageState{Messages: map[string]map[string]*claudeContribution{}} + for _, e := range r.Window { + m := e.M + if m == nil { + return old + } + m.key = e.Key + m.weight = m.entryWeight() + m.node = w.recent.PushBack(m) + w.entries += m.weight + branches := w.Messages[e.Key] + if branches == nil { + branches = map[string]*claudeContribution{} + w.Messages[e.Key] = branches + } + branches[m.Request] = m + } + c := *old + c.Claude, c.CompactMs = w, r.CompactMs + return &c +} diff --git a/internal/sessions/claude_window_test.go b/internal/sessions/claude_window_test.go index 62673b1ac..1de8bfeee 100644 --- a/internal/sessions/claude_window_test.go +++ b/internal/sessions/claude_window_test.go @@ -199,3 +199,61 @@ func BenchmarkClaudeLargeActive(b *testing.B) { }) } } + +// After a restart a grown Claude file is read on from where it was left, with +// the window it had: a live 2 GB session was read from its first line on the +// first Requests page after every update (#3493). What it reads is what a +// read from the start makes. +func TestClaudeFileReadOnAfterRestart(t *testing.T) { + d := setupCalls(t) + path := filepath.Join(d.claude, "projects", "fixture", "session.jsonl") + const count = 3000 + at := time.Date(2026, 9, 20, 12, 0, 0, 0, time.UTC) + line := func(i int, id string, out int) string { + return string(claudeUsageLine(at.Add(time.Duration(i)*time.Second), id, "req-"+id, "m", Tokens{Input: 1, Output: out}, "", true)) + } + lines := make([]string, count) + for i := range lines { + lines[i] = line(i, fmt.Sprint(i), 2) + } + writeLines(t, path, lines...) + read := func() []Call { + t.Helper() + for _, source := range CallSources() { + if source.Path == path { + return ReadCallSource(source) + } + } + t.Fatal("source missing") + return nil + } + read() + before, err := os.Stat(callCachePath(path)) + if err != nil { + t.Fatal(err) + } + Reset() + // a recent message written again with more output, the last one replayed + // as it was, and a new one + appendText(t, path, line(count, "2990", 9)+"\n"+lines[count-1]+"\n"+line(count+1, "new", 2)+"\n") + got := read() + after, err := os.Stat(callCachePath(path)) + if err != nil { + t.Fatal(err) + } + if !os.SameFile(before, after) { + t.Fatal("the grown file was read again from its start") + } + Reset() + os.Remove(callCachePath(path)) + os.Remove(callRevisionsPath(path)) + want := read() + if len(got) != count+1 || !reflect.DeepEqual(got, want) { + t.Fatalf("read on: %d calls, from the start: %d", len(got), len(want)) + } + for _, c := range got { + if c.Msg == "2990" && c.Output != 9 { + t.Fatalf("the rewritten message kept its old output: %+v", c) + } + } +}