sessions: a grown Claude file is read on after a restart, with the window it had (#3493)

A Claude Code session's revision window lived in memory alone, so after
magpie started again (every update), or let a ninth live session's
window go, each Claude file that had grown was read again from its
first line. On the owner's real ~/.claude a live 2 GB session and a
372 MB one were read whole for the first Requests page: 2.4 GB, 7.4s.

The window is bounded (claudeRevisionEntries), so readCalls now keeps
it beside the file's shard (<hash>.rev, temp and rename, ~60 KB), with
the Off and ContentHash of the read that made it. A read whose old
state has no window takes it from there when both match, and reads on.
A file no longer being worked on drops its window as before, and its
.rev with it; pruneCalls takes away a .rev whose shard is gone.

Measured (internal/gui handler, sandbox HOME with the owner's real
~/.codex and ~/.claude, 15,553 sources): the first ledger week after a
restart 7.4s -> 1.7-2.4s across three restarts; 14 .rev files, 8-67 KB.

Run at this tree: go test -count=1 -timeout 45m ./internal/sessions
./internal/usage ./internal/usageapi ok; GOOS=linux and windows go vet
-tags nogui ./internal/sessions ok. TestClaudeFileReadOnAfterRestart is
red with withCallRevisions turned off ("read again from its start"),
and checks the calls read on equal a read from the start, a revised
recent message included.

The Sessions summary's own Claude window, in memory alone the same way,
is kept by the next commit.
This commit is contained in:
yetone
2026-10-24 23:40:00 +08:00
parent 3b5a2f612d
commit ff6f3188bd
3 changed files with 166 additions and 2 deletions
+6 -2
View File
@@ -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()
+102
View File
@@ -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
}
+58
View File
@@ -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)
}
}
}