sessions: a Claude reply evicted from the window is used again for the next

A Claude history's read keeps a window of recent messages to fold
revisions together. Each message made a contribution, a branch map and
its tool and block maps, and dropped them when it left the window: on a
cold start of a real history copy that was ~750MB of message() and
~690MB of ccTool's maps. An evicted contribution and its emptied branch
map now go on a short free list (16 contributions, maps over 64 entries
dropped) and the next message takes them, cleared.

Measured on mote, cold start over a copy of real Claude and Codex
histories (acold.sh, 120s), against v0.1.3128's build:
  allocated 8.96GB -> 8.79GB, GCs 277 -> 266,
  footprint peak 197MB -> 189MB, heap peak 194MB -> 186MB.
message() 750MB -> 565MB, ccTool 689MB -> 466MB.

Tried and dropped: doubling the calls list by hand saved ~0.5GB of
allocation but raised the footprint peak to 265MB (lists held at up to
twice their size while read), so the calls list grows as before.

Tests:
- TestClaudeEvictedContributionsLeaveNothing: 3 windows of replies
  through both reads; every live contribution holds only its own
  message's tools and blocks, usage, calls, replies and output totals
  are right, a replayed reply makes no call. Red by hand without the
  maps' clear ("holds another message's tool") and without recycling
  ("nothing evicted was kept").
- TestClaudeHistoryReadAllocations: 3156 bytes a reply once the window
  is full, bar 4200; 5348 without recycling (red by hand).

Full suite on mote (gofmt, vet darwin/linux/windows, go test -timeout 45m ./...):
85 packages ok; red only TestMainWindowCorners (#3949) and
TestRenewLoginsKeepsClaudeReading (#5481), both filed and red on main.
internal/sessions run again at the rebased head.
This commit is contained in:
yetone
2026-11-06 18:38:51 +08:00
parent 2b2abec457
commit 9a0aab32c1
2 changed files with 175 additions and 2 deletions
+118
View File
@@ -0,0 +1,118 @@
package sessions
import (
"bytes"
"fmt"
"runtime"
"runtime/debug"
"strings"
"testing"
"time"
)
// reuseLine is reply i of a history: its own message, block and two tools.
func reuseLine(i int, at time.Time) []byte {
content := fmt.Sprintf(`[{"type":"tool_use","id":"t%da","name":"Read","input":{}},{"type":"tool_use","id":"t%db","name":"Skill","input":{"skill":"s%d"}}]`, i, i, i)
b := claudeUsageLine(at.Add(time.Duration(i)*time.Second), fmt.Sprint(i), fmt.Sprint("r", i), "m", Tokens{Input: 1, Output: i + 1}, content, true)
return bytes.Replace(b, []byte(`{`), []byte(fmt.Sprintf(`{"uuid":"u%d",`, i)), 1)
}
// A contribution evicted from the window is made again for a later
// message: what it held of its own message is gone, in the Sessions read
// and in the calls' read alike.
func TestClaudeEvictedContributionsLeaveNothing(t *testing.T) {
at := time.Date(2026, 9, 20, 12, 0, 0, 0, time.UTC)
n := 3 * claudeRevisionEntries
s, st := &state{}, &callFile{Agent: "claude"}
for i := range n {
b := reuseLine(i, at)
claudeLine(s, b, true)
claudeCallLine(st, b)
}
if len(s.Claude.free) == 0 || len(st.Claude.free) == 0 {
t.Fatal("nothing evicted was kept to use again")
}
for j, r := range []*claudeUsageState{s.Claude, st.Claude} {
// the Sessions read keeps a message's tools, the calls' read its blocks
tools, blocks := 2*(1-j), j
for key, branches := range r.Messages {
id := strings.TrimPrefix(key, "message:")
for request, m := range branches {
if request != "r"+id || m.Request != request || m.key != key {
t.Fatalf("%s: a branch %q holds %q of %q", key, request, m.Request, m.key)
}
for tool := range m.Tools {
if !strings.HasPrefix(tool, "t"+id) || len(tool) != len(id)+2 {
t.Fatalf("%s holds another message's tool %s", key, tool)
}
}
if len(m.Tools) != tools || len(m.Blocks) != blocks || blocks == 1 && !m.Blocks["uuid:u"+id] {
t.Fatalf("%s: tools %v blocks %v", key, m.Tools, m.Blocks)
}
if m.Usage == nil || m.Usage.Tokens.Output != atoi(id)+1 || len(m.Previous) != 0 {
t.Fatalf("%s: usage %+v previous %v", key, m.Usage, m.Previous)
}
}
}
}
if len(st.Calls) != n {
t.Fatalf("%d calls of %d replies", len(st.Calls), n)
}
for i, c := range st.Calls {
if c.Output != i+1 || c.RequestID != fmt.Sprint("r", i) {
t.Fatalf("call %d: %+v", i, c)
}
}
if got := claudeUsageReplies(s); got != n {
t.Fatalf("%d replies counted of %d", got, n)
}
if got := s.Models.of("m").Output; got != n*(n+1)/2 {
t.Fatalf("output %d, want %d", got, n*(n+1)/2)
}
// the last reply read again is the same call, not a new one
last := reuseLine(n-1, at)
claudeCallLine(st, last)
claudeLine(s, last, true)
if len(st.Calls) != n || claudeUsageReplies(s) != n {
t.Fatalf("a replay made a call: %d calls, %d replies", len(st.Calls), claudeUsageReplies(s))
}
}
func atoi(s string) int {
n := 0
fmt.Sscan(s, &n)
return n
}
// TestClaudeHistoryReadAllocations: once the window is full, a reply of
// a history's read makes no contribution, branch list or maps of its own.
func TestClaudeHistoryReadAllocations(t *testing.T) {
at := time.Date(2026, 9, 20, 12, 0, 0, 0, time.UTC)
n := 2 * claudeRevisionEntries
lines := make([][]byte, 2*n)
for i := range lines {
lines[i] = reuseLine(i, at)
}
s, st := &state{}, &callFile{Agent: "claude"}
for _, b := range lines[:n] {
claudeLine(s, b, true)
claudeCallLine(st, b)
}
runtime.GC()
defer debug.SetGCPercent(debug.SetGCPercent(-1))
var ms runtime.MemStats
runtime.ReadMemStats(&ms)
before := ms.TotalAlloc
for _, b := range lines[n:] {
claudeLine(s, b, true)
claudeCallLine(st, b)
}
runtime.ReadMemStats(&ms)
per := (ms.TotalAlloc - before) / uint64(n)
t.Logf("%d bytes a reply", per)
// ~3.2 KB: the two reads' decoding and the call's strings; a
// contribution, branch list and maps for each made ~5.3 KB
if per > 4200 {
t.Fatalf("a reply's two reads made %d bytes, want at most 4200", per)
}
}
+57 -2
View File
@@ -13,8 +13,23 @@ type claudeUsageState struct {
Messages map[string]map[string]*claudeContribution `json:"messages,omitempty"`
recent list.List
entries int
// what finish evicted, for message to use again: a history's read
// made a contribution, its branches and its maps for every message,
// and threw all but the last few thousand away (~1.5 GB on a first
// start's read of a 21 GB Claude Code history, #2278)
free []*claudeContribution
freeBranches []map[string]*claudeContribution
}
// claudeFree is how many evicted contributions are kept to use again:
// one is evicted for each one made once the window is full.
const claudeFree = 16
// claudeFreeMap is the most a map of an evicted contribution may hold to
// be used again: clear keeps a map's room, and one long message's would
// stay with a short one's.
const claudeFreeMap = 64
// Each active file keeps a recent window even when the whole source exceeds
// the shared index budget. Older messages fall back to the original reader
// behavior; their complete replay history is not retained.
@@ -133,7 +148,13 @@ func (r *claudeUsageState) message(id, request string) *claudeContribution {
}
branches := r.Messages[key]
if branches == nil {
branches = make(map[string]*claudeContribution)
if n := len(r.freeBranches); n > 0 {
branches = r.freeBranches[n-1]
r.freeBranches[n-1] = nil
r.freeBranches = r.freeBranches[:n-1]
} else {
branches = make(map[string]*claudeContribution)
}
r.Messages[key] = branches
}
if m := branches[request]; m != nil {
@@ -151,7 +172,15 @@ func (r *claudeUsageState) message(id, request string) *claudeContribution {
return m
}
}
m := &claudeContribution{Request: request, Call: -1, key: key}
var m *claudeContribution
if n := len(r.free); n > 0 {
m = r.free[n-1]
r.free[n-1] = nil
r.free = r.free[:n-1]
m.Request, m.Call, m.key = request, -1, key
} else {
m = &claudeContribution{Request: request, Call: -1, key: key}
}
m.node = r.recent.PushBack(m)
branches[request] = m
return m
@@ -181,13 +210,39 @@ func (r *claudeUsageState) finish(m *claudeContribution) {
delete(branches, old.Request)
if len(branches) == 0 {
delete(r.Messages, old.key)
if len(r.freeBranches) < claudeFree {
r.freeBranches = append(r.freeBranches, branches)
}
}
r.entries -= old.weight
r.recent.Remove(e)
old.node = nil
if len(r.free) < claudeFree {
r.free = append(r.free, old.reset())
}
}
}
// reset is m emptied to be used again, keeping its maps' and list's room
// when they are small. Nothing else holds an evicted contribution: clone
// copies each, and window reads only those still in the window.
func (m *claudeContribution) reset() *claudeContribution {
tools, blocks, previous := m.Tools, m.Blocks, m.Previous[:0]
if len(tools) > claudeFreeMap {
tools = nil
}
if len(blocks) > claudeFreeMap {
blocks = nil
}
if cap(previous) > claudeFreeMap {
previous = nil
}
clear(tools)
clear(blocks)
*m = claudeContribution{Tools: tools, Blocks: blocks, Previous: previous}
return m
}
func (m *claudeContribution) entryWeight() int {
n := 2 + len(m.Previous) + len(m.Tools) + len(m.Blocks)
for _, tool := range m.Tools {