Files
magpie/internal/sessions/claude_historical_test.go
T
yetone b8270850df sessions: a kept parse's rarely set fields live in a StateMore made only when one is set (#2278)
Each of the ~18k files the Sessions cache keeps had a 760-byte state, and
~330 bytes of it were fields almost no file sets: the Codex spawn and agent
maps, Named/Custom/First, the dsh and Claude conversation lists, Root/Leaf,
Compacts, and the six per-agent tails (Grok, Droid, Kimi, Agy, Dsh, Cline).
On the owner's real cache (18,331 files) Root and Leaf are set in 150,
Named in 117, Compacts in 78, First in 35. They move to an embedded
*StateMore, nil unless something is in it: reads go through more() (a
shared empty one when nil), writes through own(). The JSON is the same
(embedded fields are inlined), so the cache version stays.

- parseWith drops an extra that only had empty values written to it, and
  share() drops one the decode made empty.
- clone() deep-copies the extra, so growing a clone leaves the kept state
  alone. Copies that never write (withoutRevisions, the Agent rename)
  share it, as they shared the maps before.

Run on mote at this tree:
- gofmt -l internal/sessions: clean. go vet ./internal/sessions/ on
  darwin, GOOS=linux and GOOS=windows: ok.
- go test -count=1 ./internal/sessions/: ok (26s).
- Every selector was checked by renaming the embedding to a named field
  and compiling with -gcflags=-e until only the struct literals were left,
  so no field is reached through a nil *StateMore.
- New tests in state_more_test.go: zero() knows every field (reflect), a
  read makes no extra and a write never reaches the shared empty one, a
  clone owns its extra, and a cache round trip keeps no empty extra.
  Broken by hand: dropping Cline from zero() and sharing the extra in
  clone() each turn their test red; restored.
- Real-account idle heap (copy of the owner's config and 24.6MB sessions
  cache, gateway idle 180s, heap after GC): decodeCache's retained heap
  35.0MB -> 22.5MB, reflect.unsafe_New 20.0MB -> 10.5MB. The total
  (128.7MB -> 133.6MB) moves by more than that between runs of one binary
  (118-140MB), from late passes that happened to be live.

Not tried: the full ./... suite (state is unexported; only internal/sessions
uses it, and the whole binary builds).
2026-11-09 18:08:28 +08:00

123 lines
5.1 KiB
Go

package sessions
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestHistoricalClaudeFilesDoNotDisplaceActiveWindows(t *testing.T) {
for _, sourceReader := range []bool{false, true} {
t.Run(fmt.Sprint("source-reader=", sourceReader), func(t *testing.T) {
d := setupCalls(t)
at := time.Now().UTC().Add(-time.Minute)
var historical []string
for i := 0; i < revisionFiles; i++ {
path := filepath.Join(d.claude, "projects", "fixture", fmt.Sprintf("history-%d.jsonl", i))
historical = append(historical, path)
writeLines(t, path, string(claudeUsageLine(at, fmt.Sprint("old-", i), "", "m", Tokens{Output: 1}, `[{"type":"text","text":"`+strings.Repeat("x", 64<<10)+`"}]`, true)))
old := time.Now().Add(-48 * time.Hour)
if err := os.Chtimes(path, old, old); err != nil {
t.Fatal(err)
}
}
claude := filepath.Join(d.claude, "projects", "fixture", "active.jsonl")
writeLines(t, claude, string(claudeUsageLine(at, "active", "r", "m", Tokens{Input: 100, Output: 1}, `[{"type":"text","text":"`+strings.Repeat("x", 32<<10)+`"}]`, true)))
codex := filepath.Join(d.codex, "sessions", "rollout-2026-09-20T10-00-00-0190aaaa-1111-7222-8333-444455556666.jsonl")
writeLines(t, codex, append(cxTurnLines(0, "t", "gpt-6-astra", "high"), tokenCountLine(1, cxUse(100, 0, 0, 1, 0), cxUse(100, 0, 0, 1, 0)))...)
read := func() {
List(0)
var calls []Call
if sourceReader {
for _, s := range CallSources() {
calls = append(calls, ReadCallSource(s)...)
}
} else {
calls = Calls(time.Time{})
}
totals := map[string]Tokens{}
for _, c := range calls {
v := totals[c.File]
v.add(c.Tokens)
totals[c.File] = v
}
if totals[claude] != cache[claude].Models.of("m") || totals[codex] != cache[codex].Models.of("gpt-6-astra") {
t.Fatal("calls and summaries disagree", totals[claude], totals[codex])
}
}
read()
saved() // the marker below is written on a parse a save may be encoding
before := map[string]os.FileInfo{}
for _, path := range []string{claude, codex} {
if cache[path].revisionWeight() == 0 {
t.Fatal("history displaced active summary", path)
}
cache[path].own().Named = "incremental marker"
st, err := os.Stat(callCachePath(path))
if err != nil {
t.Fatal(err)
}
before[path] = st
}
for i := 0; i < 3; i++ {
appendText(t, claude, string(claudeUsageLine(at.Add(time.Duration(i+1)*time.Second), "active", "r", "m", Tokens{Input: 100, Output: i + 2}, "", true))+"\n")
appendText(t, codex, tokenCountLine(i+2, cxUse(100*(i+2), 0, 0, i+2, 0), cxUse(100, 0, 0, 1, 0))+"\n")
read()
for _, path := range []string{claude, codex} {
if cache[path].more().Named != "incremental marker" {
t.Fatal("reparsed active summary", path)
}
st, err := os.Stat(callCachePath(path))
if err != nil {
t.Fatal(err)
}
if !os.SameFile(before[path], st) {
t.Fatal("rebuilt active call shard", path)
}
}
if got := cache[claude].Models.of("m"); got != (Tokens{Input: 100, Output: i + 2}) {
t.Fatal(got)
}
if got := cache[codex].Models.of("gpt-6-astra"); got != (Tokens{Input: 100 * (i + 2), Output: i + 2}) {
t.Fatal(got)
}
}
for _, path := range historical {
if cache[path].Claude != nil || callCache[path] != nil && callCache[path].Claude != nil || callContinuations[path].state.Claude != nil {
t.Fatal("cold-only historical source retained a window")
}
}
})
}
}
func TestIdleWindowsYieldToRecentWork(t *testing.T) {
now := time.Now()
var candidates []revisionCandidate
for i := 0; i < revisionFiles; i++ {
candidates = append(candidates, revisionCandidate{path: fmt.Sprint("old-", i), mod: now.Add(-48 * time.Hour).UnixNano(), size: 13 << 20, weight: claudeRevisionEntries, bounded: true})
}
// These old windows were previously admitted while live. Age alone should
// not drop them, but new work of either format has priority under pressure.
if len(retainedRevisions(append([]revisionCandidate(nil), candidates...), now)) != revisionFiles {
t.Fatal("idle windows lost spare slots")
}
candidates = append(candidates, revisionCandidate{path: "active-claude", mod: now.UnixNano(), size: 11 << 20, weight: claudeRevisionEntries, bounded: true}, revisionCandidate{path: "active-codex", mod: now.UnixNano(), size: 128, weight: 4})
keep := retainedRevisions(candidates, now)
if !keep["active-claude"] || !keep["active-codex"] || len(keep) > revisionFiles {
t.Fatal("old windows displaced current work", keep)
}
// A ten-minute pause is still in the working set. Cost outranks the eight
// newer tiny transcripts, so this does not restore the five-minute cliff.
candidates = []revisionCandidate{{path: "large", mod: now.Add(-10 * time.Minute).UnixNano(), size: 1 << 30, weight: claudeRevisionEntries, bounded: true}}
for i := 0; i < revisionFiles; i++ {
candidates = append(candidates, revisionCandidate{path: fmt.Sprint("small-", i), mod: now.UnixNano(), size: 1024, weight: 2, bounded: true})
}
if !retainedRevisions(candidates, now)["large"] {
t.Fatal("short pause lost expensive window")
}
}