sessions: the Sessions list keeps a Claude file's window in sessions.json, read on after a restart (#3493)

The summary's Claude revision window (state.Claude) was json:"-", and a
Claude file's parse with no window starts again from byte 0. So after
every restart, which is every update, the Sessions list read each grown
Claude session from its first line: the live 2 GB session on the
owner's machine took seconds of the first list.

state.Claude now goes into sessions.json as its bounded window
(claudeUsageState MarshalJSON/UnmarshalJSON, the entries in eviction
order; window() and claudeWindowOf are shared with the calls .rev
sidecar). It is bounded by claudeRevisionEntries and trimSummaryRevisions
as in memory. A sessions.json from an older magpie has no "claude" and
reads from the start as before; an entry without a contribution is
skipped, so a bad window never loses the whole index.

#697 kept message maps out of the index because they were unbounded;
the window is bounded now, so TestClaudeNativeReplayAcrossReadersAndRestart
checks the kept window's weight instead of its absence, and
TestQoderUsageAfterWindowLoss's restart case strips "claude" from
sessions.json to stand for an older index.

Real data (a sandbox HOME with the owner's real ~/.claude and ~/.codex,
read only): cold Sessions list after a restart with the live sessions
grown, 6.3s with the 2 GB file reparsed -> 0.77-0.96s over three runs,
only small subagent files reparsed. sessions.json: 7 windows, ~1 MB of
21.7 MB.

Run at this tree: go test -count=1 -timeout 45m ./internal/sessions
./internal/usage ./internal/usageapi ./internal/gui ok (sessions after
the two test updates); go test -race ./internal/sessions ok; GOOS=linux
and windows go vet -tags nogui ./internal/sessions ok; gofmt clean.
TestClaudeSummaryReadOnAfterRestart is red with the tag back at "-"
(the summary is read again from its start, its marker lost).
This commit is contained in:
yetone
2026-10-24 23:40:00 +08:00
parent ff6f3188bd
commit ccf403bda9
6 changed files with 129 additions and 34 deletions
+2 -30
View File
@@ -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
}
@@ -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 {
@@ -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 {
+62 -1
View File
@@ -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{}
+42
View File
@@ -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)
}
}
+1 -1
View File
@@ -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"`