diff --git a/internal/sessions/call_revisions.go b/internal/sessions/call_revisions.go index a82dfd7b3..b0291d550 100644 --- a/internal/sessions/call_revisions.go +++ b/internal/sessions/call_revisions.go @@ -23,13 +23,6 @@ type callRevisions struct { 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" } @@ -42,11 +35,7 @@ func writeCallRevisions(st *callFile) { _ = 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}) - } + r := callRevisions{Off: st.Off, ContentHash: st.ContentHash, CompactMs: st.CompactMs, Window: st.Claude.window()} var data bytes.Buffer if gob.NewEncoder(&data).Encode(r) != nil { return @@ -79,24 +68,7 @@ func withCallRevisions(old *callFile) *callFile { 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 + c.Claude, c.CompactMs = claudeWindowOf(r.Window), r.CompactMs return &c } diff --git a/internal/sessions/claude_native_review_test.go b/internal/sessions/claude_native_review_test.go index ccf74ec76..820aeee98 100644 --- a/internal/sessions/claude_native_review_test.go +++ b/internal/sessions/claude_native_review_test.go @@ -49,12 +49,14 @@ func TestClaudeNativeReplayAcrossReadersAndRestart(t *testing.T) { if list := List(0); len(list) != 1 || list[0].Tokens != want { t.Fatalf("summary differs: %+v", list) } + // The summary keeps its window on disk (#3493), bounded as in memory. b, err := json.Marshal(cache[path]) if err != nil { t.Fatal(err) } - if strings.Contains(string(b), "claude_usage") || strings.Contains(string(b), "blocks") || strings.Contains(string(b), "message_4") { - t.Fatal("summary persisted message state") + var kept state + if err := json.Unmarshal(b, &kept); err != nil || kept.Claude.weight() > claudeRevisionEntries { + t.Fatalf("summary window kept: %v weight=%d", err, kept.Claude.weight()) } info, err := os.Stat(path) if err != nil { diff --git a/internal/sessions/claude_retention_test.go b/internal/sessions/claude_retention_test.go index f7c5d557a..69da601bf 100644 --- a/internal/sessions/claude_retention_test.go +++ b/internal/sessions/claude_retention_test.go @@ -1,6 +1,8 @@ package sessions import ( + "bytes" + "encoding/json" "fmt" "os" "path/filepath" @@ -19,7 +21,23 @@ func TestQoderUsageAfterWindowLoss(t *testing.T) { writeLines(t, path, string(claudeUsageLine(at, "a", "r", "m", Tokens{Input: 100, Output: 1}, "", true))) List(0) if restart { + // A sessions.json from before the window was kept (#3493). Saved() + b, err := os.ReadFile(CachePath()) + if err != nil { + t.Fatal(err) + } + var c map[string]any + dec := json.NewDecoder(bytes.NewReader(b)) + dec.UseNumber() + if err := dec.Decode(&c); err != nil { + t.Fatal(err) + } + delete(c["files"].(map[string]any)[path].(map[string]any), "claude") + b, _ = json.Marshal(c) + if err := os.WriteFile(CachePath(), b, 0o644); err != nil { + t.Fatal(err) + } Reset() List(0) } else { diff --git a/internal/sessions/claude_usage.go b/internal/sessions/claude_usage.go index d46c443c6..fcd85f536 100644 --- a/internal/sessions/claude_usage.go +++ b/internal/sessions/claude_usage.go @@ -2,11 +2,13 @@ package sessions import ( "container/list" + "encoding/json" "time" ) // claudeUsageState tracks message revisions while a source is live. It is -// never persisted: a changed source reconstructs it after a cache reload. +// kept on disk with the read it belongs to (MarshalJSON, writeCallRevisions); +// a changed source without one reconstructs it from its first line. type claudeUsageState struct { Messages map[string]map[string]*claudeContribution `json:"messages,omitempty"` recent list.List @@ -49,6 +51,65 @@ type claudeToolUsage struct { type claudeToolVersion struct{ Name, Skill string } +// claudeWindowEntry is one contribution of a window, oldest first, as its +// eviction order has them. +type claudeWindowEntry struct { + Key string `json:"key"` + M *claudeContribution `json:"m"` +} + +// window is r's contributions in their eviction order, to keep on disk. +func (r *claudeUsageState) window() []claudeWindowEntry { + var out []claudeWindowEntry + for e := r.recent.Front(); e != nil; e = e.Next() { + m := e.Value.(*claudeContribution) + out = append(out, claudeWindowEntry{m.key, m}) + } + return out +} + +// claudeWindowOf is the window kept as entries. +func claudeWindowOf(entries []claudeWindowEntry) *claudeUsageState { + w := &claudeUsageState{} + w.fill(entries) + return w +} + +func (r *claudeUsageState) fill(entries []claudeWindowEntry) { + r.Messages = map[string]map[string]*claudeContribution{} + for _, e := range entries { + m := e.M + if m == nil { + continue + } + m.key = e.Key + m.weight = m.entryWeight() + m.node = r.recent.PushBack(m) + r.entries += m.weight + branches := r.Messages[e.Key] + if branches == nil { + branches = map[string]*claudeContribution{} + r.Messages[e.Key] = branches + } + branches[m.Request] = m + } +} + +// A summary's window is kept in sessions.json with it, so a session that grew +// while magpie was not running is read on, not again from its first line: a +// live 2 GB one took seconds of the first Sessions list after every update +// (#3493). Only a few bounded windows are kept at once (trimSummaryRevisions). +func (r *claudeUsageState) MarshalJSON() ([]byte, error) { return json.Marshal(r.window()) } + +func (r *claudeUsageState) UnmarshalJSON(b []byte) error { + var entries []claudeWindowEntry + if err := json.Unmarshal(b, &entries); err != nil { + return err + } + r.fill(entries) + return nil +} + func ccUsageState(p **claudeUsageState) *claudeUsageState { if *p == nil { *p = &claudeUsageState{} diff --git a/internal/sessions/claude_window_test.go b/internal/sessions/claude_window_test.go index 1de8bfeee..0c55d2a5c 100644 --- a/internal/sessions/claude_window_test.go +++ b/internal/sessions/claude_window_test.go @@ -257,3 +257,45 @@ func TestClaudeFileReadOnAfterRestart(t *testing.T) { } } } + +// The Sessions list's own window is kept in sessions.json: after a restart a +// grown Claude file is read on, and what it counts is what a read from the +// start counts (#3493). +func TestClaudeSummaryReadOnAfterRestart(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...) + List(0) + // a reparse from the start cannot know this marker: it proves the read + // after the restart went on from the kept parse + mu.Lock() + marked := *cache[path] + marked.Named = "read on marker" + cache[path] = &marked + saveCache() + mu.Unlock() + Reset() + appendText(t, path, line(count, "2990", 9)+"\n"+lines[count-1]+"\n"+line(count+1, "new", 2)+"\n") + got := List(0) + mu.Lock() + named := cache[path].Named + mu.Unlock() + if named != "read on marker" { + t.Fatal("the grown file was parsed again from its start") + } + Reset() + os.Remove(CachePath()) + want := List(0) + if len(got) != 1 || len(want) != 1 || got[0].Input != want[0].Input || got[0].Output != want[0].Output || got[0].Input != count+1 || got[0].Output != 2*(count+1)+7 { + t.Fatalf("read on: %+v, from the start: %+v", got, want) + } +} diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index e5542b0ba..aeb9fe592 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -175,7 +175,7 @@ const All = 5000 // state is what one file's parse has come to, enough to read on from Off. type state struct { Codex *codexUsageState `json:"-"` - Claude *claudeUsageState `json:"-"` + Claude *claudeUsageState `json:"claude,omitempty"` DBRevision string `json:"db_revision,omitempty"` Head string `json:"head,omitempty"` HeadSize int `json:"head_size,omitempty"`