sessions: a turn of a long Claude session reads none of its copies again (shangyuan0818 on X)
Usage → Sessions took ~20s on Windows for long Claude Code sessions (tens to ~100 MB each, few rows). A session resumed or forked into new files leaves whole copies of it, listed as one row, and the live one is the file they are kept in. Each turn it gained re-read every copy whole, twice: - ccFamily dropped the uuids read of a group whose verdict it found on disk, so the next change judged the group by reading every file's uuids from the start. It now keeps them while the files start alike, as ccUUIDMemo's comment says, and reads on from where it stopped. - ccRest read each copy whole again whenever the keeper changed. It now keeps the uuids of a copy's own messages, and while the copy didn't change and the keeper only grew and holds none of them, the rest stands. A keeper that took one of them has the rest read again (TestClaudeKeeperTurnTheBranchHeldIsCountedOnce, red with that check turned off: 90 in, want 80). Timings, Windows (xiaomi-gpu), a 100 MB Claude session from a real one with its text scrambled, copied under new ids: - in process, 4 copies, /api/sessions after a turn: 261 ms and 332 ms, now 26 ms and 27 ms; after a start and a turn 523 ms, now 239 ms. - the real dev backend (magpie app, sandbox HOME), 8 copies, the page's three calls after a turn: 607 ms, now 31 ms. Cold start 1.9 s both. These scale with the copies and their size; the reporter's machine is slower than this one. Run: - TestClaudeKeeperTurnReadsNoCopy red on the old code (copies and keeper read whole each turn); red with each half undone alone. - win-run go test ./internal/sessions ./internal/gui: 14 reds, the same 14 on origin/main4a4424ea8run alone (#6071, #6068, #5324, #5928, #6059). - wsl-run go test ./internal/sessions at this head (on4a4424ea8): ok. TestCCListingKeepsItsNames passes on Linux at base and head. - go vet ./internal/sessions for linux, windows, darwin; gofmt clean. Not tried: the reporter's own files; WSL-hosted Claude sessions; mote and mica were over load, so no macOS run. After a start, the first change to a group still reads each file's uuids once.
This commit is contained in:
@@ -1230,6 +1230,19 @@ the session itself was hidden as a fork's copy. See
|
||||
`TestClaudeCopyBeforeACompactionIsCounted`; the fixtures in
|
||||
`testdata/claude-forks` are Claude Code 2.1.312's own files.
|
||||
|
||||
A group's verdict is kept on disk by its files' sizes and times
|
||||
(`cc_family_memo.go`), and each copy's rest by both files. While the
|
||||
process runs, the uuids read of a group's files stay in memory, a group
|
||||
found on disk included, so when the keeper grows (the live session the
|
||||
copies were made of) the group is judged on the added lines only. A copy
|
||||
that didn't change keeps its rest while the keeper only grew and holds
|
||||
none of the rest's messages; one it now holds has the rest read again. A
|
||||
long session resumed into copies of ~100 MB each re-read every copy whole
|
||||
on each turn, a second or more per change on the Sessions page (on X).
|
||||
After a start, the first change to such a group still reads each file's
|
||||
uuids once. See `TestClaudeKeeperTurnReadsNoCopy` and
|
||||
`TestClaudeKeeperTurnTheBranchHeldIsCountedOnce`.
|
||||
|
||||
A session whose agent keeps its subagents' conversations beside its own
|
||||
lists them in `subagents` on the sessions API (`/api/sessions`, `one`, `manage`; #2261,
|
||||
[`subagents.go`](../../internal/sessions/subagents.go)), only for agents with
|
||||
|
||||
@@ -110,6 +110,13 @@ func ccFamily(files []file) (copies, branches map[string]string) {
|
||||
}
|
||||
sig := ccGroupSig(g)
|
||||
if kept := ccFamilyKept(sig); kept != nil {
|
||||
// its files still start alike: the uuids read of them stay,
|
||||
// so when one grows the group is judged on what it added,
|
||||
// not on every file of it read whole again (a long session
|
||||
// resumed into copies, each ~100 MB, took seconds a change)
|
||||
for _, o := range g {
|
||||
used[o.f.path] = true
|
||||
}
|
||||
if len(kept.Copies) > 0 {
|
||||
if out == nil {
|
||||
out = map[string]string{}
|
||||
@@ -334,6 +341,10 @@ type ccRestOf struct {
|
||||
keeper string
|
||||
ksize, kmod int64
|
||||
st *state
|
||||
// ids is the uuids of the messages st was read from, nil when not
|
||||
// known (kept on disk): while the copy stays as it is and the keeper
|
||||
// only grows, st stands as long as the keeper holds none of them
|
||||
ids []string
|
||||
}
|
||||
|
||||
// ccRest is the copy's file read for its messages the keeper's file
|
||||
@@ -349,8 +360,20 @@ func ccRest(copyFile, keeper file) *state {
|
||||
return m.st
|
||||
}
|
||||
held := ccUUIDsOf(keeper)
|
||||
// the keeper only grew (a live session the copies were made of): what
|
||||
// it added is new messages, so the copy's rest is what it was unless
|
||||
// the keeper now holds one of them, and the copy, as large as the
|
||||
// session, is not read again on each turn
|
||||
if m != nil && m.ids != nil && m.size == copyFile.size && m.mod == copyFile.mod.UnixNano() &&
|
||||
m.keeper == keeper.path && keeper.size > m.ksize &&
|
||||
!slices.ContainsFunc(m.ids, held.has) {
|
||||
m.ksize, m.kmod = keeper.size, keeper.mod.UnixNano()
|
||||
ccRestKept.dirty = true
|
||||
return m.st
|
||||
}
|
||||
line := parserFor(copyFile.agent).line
|
||||
s := &state{}
|
||||
ids := []string{}
|
||||
_, err := scanThin(copyFile.path, 0, nil, thinClaude, func(b []byte, _, _ int64) bool {
|
||||
if !bytes.Contains(b, ccUser) && !bytes.Contains(b, ccAssistant) {
|
||||
return true
|
||||
@@ -359,6 +382,7 @@ func ccRest(copyFile, keeper file) *state {
|
||||
if t := r[0].String(); t != "user" && t != "assistant" || r[1].Type != gjson.String || held.has(r[1].Str) {
|
||||
return true
|
||||
}
|
||||
ids = append(ids, r[1].Str)
|
||||
line(s, b, copyFile.main)
|
||||
return true
|
||||
})
|
||||
@@ -367,7 +391,7 @@ func ccRest(copyFile, keeper file) *state {
|
||||
// known to be one, until it reads
|
||||
return cache[copyFile.path]
|
||||
}
|
||||
ccRestMemo[copyFile.path] = &ccRestOf{copyFile.size, copyFile.mod.UnixNano(), keeper.path, keeper.size, keeper.mod.UnixNano(), s}
|
||||
ccRestMemo[copyFile.path] = &ccRestOf{copyFile.size, copyFile.mod.UnixNano(), keeper.path, keeper.size, keeper.mod.UnixNano(), s, ids}
|
||||
ccRestKept.dirty = true
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -630,3 +632,112 @@ func TestClaudeFamilyKeptAcrossStarts(t *testing.T) {
|
||||
t.Fatalf("after the copy went on, rows = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// A long session resumed into copies (each a whole copy of it, ~100 MB
|
||||
// a file for the reporter's sessions, on X) goes on in one file, the one
|
||||
// the copies are kept in. A turn added to it is read on its own: the
|
||||
// copies, which didn't change, are not read again, neither for their
|
||||
// uuids (ccFamily) nor for what they hold that it doesn't (ccRest), and
|
||||
// the turn is counted.
|
||||
func TestClaudeKeeperTurnReadsNoCopy(t *testing.T) {
|
||||
claude, _ := setup(t)
|
||||
ccForkFixture(t, claude,
|
||||
[2]string{"original.jsonl", ccOriginal},
|
||||
[2]string{"original.jsonl", ccCopyIDs[0]},
|
||||
[2]string{"fork-on.jsonl", ccForkOn})
|
||||
if got := ccRows("claude"); !slices.Equal(got, []string{ccForkOn}) {
|
||||
t.Fatalf("rows = %v, want the fork only", got)
|
||||
}
|
||||
before, _ := ccStatTokens(t)
|
||||
proj := filepath.Join(claude, "projects", "-w-proj")
|
||||
keeper := filepath.Join(proj, ccForkOn+".jsonl")
|
||||
turn := func(n int) {
|
||||
t.Helper()
|
||||
id := fmt.Sprintf("0c0c0c0c-0000-4000-8000-%012d", n)
|
||||
line := `{"parentUuid":null,"isSidechain":false,"message":{"id":"msg_turn_` + id + `","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"more"}],"stop_reason":"end_turn","usage":{"input_tokens":1000,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":5}},"type":"assistant","uuid":"` + id + `","timestamp":"` + time.Now().Add(-time.Duration(10-n)*time.Minute).UTC().Format(time.RFC3339Nano) + `","sessionId":"` + ccForkOn + `","cwd":"/w/proj"}` + "\n"
|
||||
f, err := os.OpenFile(keeper, os.O_APPEND|os.O_WRONLY, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.WriteString(line); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.Close()
|
||||
at := time.Now().Add(-time.Duration(10-n) * time.Minute)
|
||||
if err := os.Chtimes(keeper, at, at); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var hmu sync.Mutex
|
||||
var whole []string // files read from their start
|
||||
scanHook = func(p string, off int64) {
|
||||
if off == 0 && strings.HasPrefix(p, proj) {
|
||||
hmu.Lock()
|
||||
whole = append(whole, filepath.Base(p))
|
||||
hmu.Unlock()
|
||||
}
|
||||
}
|
||||
t.Cleanup(func() { scanHook = nil })
|
||||
for n := 1; n <= 2; n++ {
|
||||
turn(n)
|
||||
hmu.Lock()
|
||||
whole = nil
|
||||
hmu.Unlock()
|
||||
if got := ccRows("claude"); !slices.Equal(got, []string{ccForkOn}) {
|
||||
t.Fatalf("turn %d: rows = %v, want the fork only", n, got)
|
||||
}
|
||||
days, _ := ccStatTokens(t)
|
||||
if want := before.Input + n*1000; days.Input != want {
|
||||
t.Errorf("turn %d: tokens in = %d, want %d", n, days.Input, want)
|
||||
}
|
||||
hmu.Lock()
|
||||
got := whole
|
||||
hmu.Unlock()
|
||||
if len(got) > 0 {
|
||||
t.Errorf("turn %d read files whole again: %v", n, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// When the file a branch is kept in grows with a message the branch held
|
||||
// on its own, that message is counted once still: the branch's own part
|
||||
// is read again, not kept as it was (ccRest).
|
||||
func TestClaudeKeeperTurnTheBranchHeldIsCountedOnce(t *testing.T) {
|
||||
ccCompactedBranchFixture(t)
|
||||
if days, _ := ccStatTokens(t); days.Input != 80 {
|
||||
t.Fatalf("tokens in = %d, want 80", days.Input)
|
||||
}
|
||||
claude := os.Getenv("CLAUDE_CONFIG_DIR")
|
||||
proj := filepath.Join(claude, "projects", "-w-proj")
|
||||
b, err := os.ReadFile(filepath.Join(proj, ccBranch+".jsonl"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var own string
|
||||
for _, l := range strings.SplitAfter(string(b), "\n") {
|
||||
if strings.Contains(l, `"type":"assistant"`) && strings.Contains(l, `"input_tokens"`) {
|
||||
own = l
|
||||
}
|
||||
}
|
||||
if own == "" {
|
||||
t.Fatal("the branch has no reply")
|
||||
}
|
||||
p := filepath.Join(proj, ccCompacted+".jsonl")
|
||||
fi, err := os.Stat(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, err := os.OpenFile(p, os.O_APPEND|os.O_WRONLY, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.WriteString(strings.ReplaceAll(own, ccBranch, ccCompacted))
|
||||
f.Close()
|
||||
at := fi.ModTime().Add(time.Minute)
|
||||
if err := os.Chtimes(p, at, at); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if days, sessions := ccStatTokens(t); days.Input != 80 || sessions.Input != 80 {
|
||||
t.Errorf("tokens in = %d (days), %d (sessions); want 80, the branch's reply counted once", days.Input, sessions.Input)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user