diff --git a/internal/sessions/call_cache.go b/internal/sessions/call_cache.go index 3caddb6de..34ce208e5 100644 --- a/internal/sessions/call_cache.go +++ b/internal/sessions/call_cache.go @@ -305,16 +305,16 @@ func readCalls(f file) *callFile { if continued { start = len(old.Calls) } - line := claudeCallLine + line, thin := claudeCallLine, thinClaude if f.agent == "codex" { - line = codexCallLine + line, thin = codexCallLine, nil } else if r, ok := lineCallReaders[f.agent]; ok { if st.Off == 0 { r.begin(st, f) } - line = r.line + line, thin = r.line, nil } - off, err := scanAt(f.path, st.Off, func(b []byte) bool { return callHead(st, b) }, func(b []byte, start, end int64) bool { + off, err := scanThin(f.path, st.Off, func(b []byte) bool { return callHead(st, b) }, thin, func(b []byte, start, end int64) bool { st.At, st.End = start, end line(st, b) return true diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index aeb9fe592..28f847850 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -1394,7 +1394,14 @@ func parseWith(f file, old *state, calls *callsRide) *state { if calls != nil { head, line = calls.ride(head, line) } - off, err := scanAt(f.path, s.Off, head, line) + var thin func([]byte) (thinner, bool) + switch { + case parser.claude: + thin = thinClaude + case f.agent == "codex": + thin = thinCodex + } + off, err := scanThin(f.path, s.Off, head, thin, line) if err == nil { s.Off = off } @@ -1435,6 +1442,14 @@ func scanHead(path string, off int64, head func([]byte) bool, fn func([]byte)) ( // A compressed file's places are those of its lines decompressed; it is read // from its start, what comes before off passed over. func scanAt(path string, off int64, head func([]byte) bool, fn func(b []byte, start, end int64) bool) (int64, error) { + return scanThin(path, off, head, nil, fn) +} + +// scanThin is scanAt handing fn a long line thin says yes to, from its +// first chunk, with its strings cut to thinKeep bytes (thinner): +// what the line holds besides long strings is kept as it was, and the +// line is never gathered whole. A nil thin thins nothing. +func scanThin(path string, off int64, head func([]byte) bool, thin func([]byte) (thinner, bool), fn func(b []byte, start, end int64) bool) (int64, error) { if scanHook != nil { scanHook(path, off) } @@ -1468,14 +1483,28 @@ func scanAt(path string, off int64, head func([]byte) bool, fn func(b []byte, st defer parts.release() var n int64 // bytes of the line so far skip, seen := false, false + var th thinner // the line's state while it is thinned + thinning := false for { chunk, err := r.ReadSlice('\n') + first := n == 0 n += int64(len(chunk)) if errors.Is(err, bufio.ErrBufferFull) { if !seen && head != nil { seen = true skip = skip || !head(chunk) } + if first && !skip && thin != nil { + th, thinning = thin(chunk) + } + if thinning { + if n > maxLine { + skip, thinning, long = true, false, long[:0] + } else if !skip { + long = th.add(long, chunk) + } + continue + } if plain && !skip && len(long) == 0 { // gathered in one buffer of the line's own size, not grown a // chunk at a time (~5 times the line allocated, #2515) @@ -1515,7 +1544,10 @@ func scanAt(path string, off int64, head func([]byte) bool, fn func(b []byte, st parts.release() } b := chunk - if len(long) > 0 { + if thinning { + long = th.add(long, chunk) + b = long + } else if len(long) > 0 { long = append(long, chunk...) b = long } @@ -1527,7 +1559,7 @@ func scanAt(path string, off int64, head func([]byte) bool, fn func(b []byte, st } } off += n - n, skip, seen, long = 0, false, false, long[:0] + n, skip, seen, thinning, long = 0, false, false, false, long[:0] } } diff --git a/internal/sessions/thin.go b/internal/sessions/thin.go new file mode 100644 index 000000000..0532ff32b --- /dev/null +++ b/internal/sessions/thin.go @@ -0,0 +1,177 @@ +package sessions + +import "bytes" + +// A Claude Code tool result holds what the tool gave back twice, in its +// message and in toolUseResult: a screenshot is a line of megabytes, and a +// cold read gathered each one whole (takeLong) to read a timestamp, the +// folder and the session id off it. ~200 such lines in a 10GB projects +// folder held 110MB live at the read's peak and set magpie's RSS (#3318). +// Such a line is now handed on thinned: every string in it cut to thinKeep +// bytes, the rest kept as it was. A Codex prompt with screenshots is the +// same (a line of 5 to 15MB, 154 of them in a 50GB sessions folder): its +// images are cut, its text is kept. + +// thinKeep is how much of a string a thinned line keeps. Over the 1024 +// bytes claudeLine routes by, so a line's head reads the same thinned. +const thinKeep = 4 << 10 + +// thinner cuts a JSON line's strings, a chunk at a time. Every byte +// outside a string is kept, so every key, number and short string is where +// a search of the whole line finds it: a string can't hold an unescaped +// quote, so no search for a quoted key matches inside a cut one. +type thinner struct { + urls bool // only a data: URL is cut + + in bool // inside a string + cut bool // the string is past thinKeep: the rest of it is dropped + n int // the string's bytes so far + at int // where in dst the string starts + esc int // an escape's bytes still to come: -1 just after its backslash +} + +// add appends chunk, thinned, to dst. +func (t *thinner) add(dst, c []byte) []byte { + for i := 0; i < len(c); { + if !t.in { + j := bytes.IndexByte(c[i:], '"') + if j < 0 { + return append(dst, c[i:]...) + } + dst = append(dst, c[i:i+j+1]...) + i += j + 1 + t.in, t.cut, t.n, t.esc, t.at = true, false, 0, 0, len(dst) + continue + } + if t.esc != 0 { + b := c[i] + switch { + case t.esc > 0: + t.esc-- + case b == 'u': + t.esc = 4 + default: + t.esc = 0 + } + if !t.cut { + dst = append(dst, b) + } + t.n++ + i++ + continue + } + r := c[i:] + q := bytes.IndexByte(r, '"') + if q < 0 { + q = len(r) + } + e := bytes.IndexByte(r[:q], '\\') + if e < 0 { + e = q + } + dst = t.keep(dst, r[:e]) + if i += e; i == len(c) { + break + } + if c[i] == '"' { + dst = append(dst, '"') + t.in = false + i++ + continue + } + // an escape is kept whole or not at all + if !t.cut && t.n >= thinKeep && t.cuts(dst) { + t.cut = true + } + if !t.cut { + dst = append(dst, '\\') + } + t.n++ + t.esc = -1 + i++ + } + return dst +} + +// keep appends what of s, a run of a string with no quote or backslash, +// is under thinKeep. +func (t *thinner) keep(dst, s []byte) []byte { + if t.cut { + t.n += len(s) + return dst + } + room := thinKeep - t.n + t.n += len(s) + if len(s) <= room { + return append(dst, s...) + } + if dst = append(dst, s[:max(room, 0)]...); !t.cuts(dst) { + return append(dst, s[max(room, 0):]...) + } + t.cut = true + return wholeRunes(dst) +} + +// cuts says whether the string, kept to thinKeep bytes in dst, is cut. +func (t *thinner) cuts(dst []byte) bool { + return !t.urls || bytes.HasPrefix(dst[t.at:], dataURL) +} + +var dataURL = []byte("data:") + +// wholeRunes is b without a UTF-8 rune its end cuts. +func wholeRunes(b []byte) []byte { + i := len(b) - 1 + for i >= 0 && len(b)-i < 4 && b[i]&0xC0 == 0x80 { + i-- + } + if i < 0 || b[i] < 0xC0 { + return b + } + need := 2 + switch { + case b[i] >= 0xF0: + need = 4 + case b[i] >= 0xE0: + need = 3 + } + if len(b)-i < need { + return b[:i] + } + return b +} + +// thinClaude thins a long Claude line, from its first chunk, that is a +// tool's result, or a line of Claude Code's own that is read for its +// timestamp (an api-request-blob of 15MB): claudeLine and claudeCallLine +// read such a line only for its timestamp, folder, session id and keys, +// all of which a thinned line keeps. +func thinClaude(c []byte) (thinner, bool) { + return thinner{}, ccResultHead(c) +} + +// thinCodex cuts the images of a Codex line its head has let through: +// codexBody reads a prompt's text, never its images. +func thinCodex([]byte) (thinner, bool) { + return thinner{urls: true}, true +} + +func ccResultHead(c []byte) bool { + c = bytes.TrimLeft(c, " \t\r\n") + h := c[:min(len(c), 1024)] + if bytes.HasPrefix(h, ccTop) { + switch typeAfter(h, ccTop) { + case "user", "assistant": + case "ai-title", "custom-title", "summary": + return false + default: + return true + } + } + m, a := bytes.Index(h, ccMessage), bytes.Index(h, ccAttach) + if m < 0 || a >= 0 && a < m { + return false + } + msg := h[m+len(ccMessage):] + return bytes.HasPrefix(msg, ccRole) && typeAfter(msg, ccRole) == "user" && ccToolResult(msg) +} diff --git a/internal/sessions/thin_test.go b/internal/sessions/thin_test.go new file mode 100644 index 000000000..0bf810962 --- /dev/null +++ b/internal/sessions/thin_test.go @@ -0,0 +1,213 @@ +package sessions + +import ( + "encoding/json" + "math/rand" + "os" + "path/filepath" + "reflect" + "runtime" + "strings" + "testing" + "unicode/utf8" +) + +// a Claude Code tool result laid out as Claude Code writes it: the image +// in the message and again in toolUseResult, the timestamp between them, +// the folder and session id at the end +func toolResultLine(size int) string { + img := strings.Repeat("iVBORw0KGgoAAAANSUhEUgAA", size/24+1)[:size] + text := strings.Repeat(`中文 \"quoted\" \\ é 😀 é`, size/60+1) + return `{"parentUuid":"p-1","isSidechain":false,"message":{"role":"user","content":[{"tool_use_id":"toolu_1","type":"tool_result","content":[{"type":"text","text":"` + text + `"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"` + img + `"}}]}]},"type":"user","uuid":"u-1","timestamp":"2026-10-20T01:02:03.456Z","toolUseResult":[{"type":"image","source":{"data":"` + img + `"}}],"userType":"external","cwd":"/Users/someone/proj","sessionId":"sess-1","version":"2.0.1"}` +} + +func TestThinnerKeepsJSON(t *testing.T) { + line := toolResultLine(64 << 10) + var want any + if err := json.Unmarshal([]byte(line), &want); err != nil { + t.Fatal(err) + } + rng := rand.New(rand.NewSource(1)) + for round := 0; round < 200; round++ { + var th thinner + var out []byte + for rest := []byte(line); len(rest) > 0; { + n := min(len(rest), 1+rng.Intn(9000)) + if round%2 == 0 { + n = min(len(rest), 1+rng.Intn(7)) + } + out = th.add(out, rest[:n]) + rest = rest[n:] + } + if !utf8.Valid(out) { + t.Fatalf("round %d: a rune was cut", round) + } + var got any + if err := json.Unmarshal(out, &got); err != nil { + t.Fatalf("round %d: thinned line is not JSON: %v", round, err) + } + prefixes(t, want, got) + if len(out) > 40<<10 { + t.Fatalf("round %d: thinned to %d bytes", round, len(out)) + } + } +} + +// prefixes checks that got is want with each string cut to a prefix of +// itself, at most thinKeep bytes of the line long +func prefixes(t *testing.T, want, got any) { + t.Helper() + switch w := want.(type) { + case map[string]any: + g := got.(map[string]any) + if len(g) != len(w) { + t.Fatalf("keys: %d, want %d", len(g), len(w)) + } + for k, v := range w { + prefixes(t, v, g[k]) + } + case []any: + g := got.([]any) + if len(g) != len(w) { + t.Fatalf("items: %d, want %d", len(g), len(w)) + } + for i := range w { + prefixes(t, w[i], g[i]) + } + case string: + g := got.(string) + // a surrogate pair cut in two decodes as U+FFFD + g = strings.TrimSuffix(g, "�") + if !strings.HasPrefix(w, g) || len(w) > thinKeep && len(g) < thinKeep/4 { + t.Fatalf("string %.40q… is not cut from %.40q…", g, w) + } + default: + if !reflect.DeepEqual(want, got) { + t.Fatalf("%v, want %v", got, want) + } + } +} + +// A tool result of megabytes reads the same thinned as whole, for a +// session's summary and for its calls, and is never gathered whole. +func TestThinToolResultReadsTheSame(t *testing.T) { + path := filepath.Join(t.TempDir(), "s.jsonl") + big := toolResultLine(3 << 20) + data := strings.Join([]string{ + `{"type":"user","message":{"role":"user","content":"hi"},"uuid":"u-0","timestamp":"2026-10-20T01:00:00.000Z","cwd":"/Users/someone/proj","sessionId":"sess-1"}`, + big, + `{"type":"assistant","message":{"model":"claude-x","id":"msg_1","type":"message","role":"assistant","content":[{"type":"text","text":"ok"}],"usage":{"input_tokens":3,"output_tokens":4}},"requestId":"req_1","uuid":"u-2","timestamp":"2026-10-20T01:05:00.000Z","cwd":"/Users/someone/proj","sessionId":"sess-1"}`, + big, + }, "\n") + "\n" + if err := os.WriteFile(path, []byte(data), 0o600); err != nil { + t.Fatal(err) + } + if !ccResultHead([]byte(big[:1<<20])) { + t.Fatal("a tool result's head is not known as one") + } + + for _, main := range []bool{true, false} { + read := func(thin func([]byte) (thinner, bool)) (*state, int64) { + s := &state{} + off, err := scanThin(path, 0, nil, thin, func(b []byte, _, _ int64) bool { + claudeLine(s, b, main) + return true + }) + if err != nil { + t.Fatal(err) + } + return s, off + } + whole, wOff := read(nil) + thin, tOff := read(thinClaude) + if wOff != tOff || wOff != int64(len(data)) { + t.Fatalf("read to %d thinned, %d whole, of %d", tOff, wOff, len(data)) + } + if !reflect.DeepEqual(whole, thin) { + t.Fatalf("main=%v: thinned\n%+v\nwhole\n%+v", main, thin, whole) + } + if thin.ID != "sess-1" || thin.Last.IsZero() { + t.Fatalf("main=%v: read %+v", main, thin) + } + } + + calls := func(thin func([]byte) (thinner, bool)) *callFile { + st := &callFile{Path: path, Agent: "claude"} + if _, err := scanThin(path, 0, nil, thin, func(b []byte, start, end int64) bool { + st.At, st.End = start, end + claudeCallLine(st, b) + return true + }); err != nil { + t.Fatal(err) + } + return st + } + whole, thin := calls(nil), calls(thinClaude) + if !reflect.DeepEqual(whole, thin) { + t.Fatalf("calls thinned\n%+v\nwhole\n%+v", thin, whole) + } + if len(thin.Calls) != 1 || thin.LastUser.IsZero() { + t.Fatalf("calls %+v", thin) + } + + // allocated: a few times the reader's buffer, not the 13MB of the lines + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + calls(thinClaude) + runtime.ReadMemStats(&after) + if got := after.TotalAlloc - before.TotalAlloc; got > 3<<20 { + t.Fatalf("a thinned read allocated %d bytes", got) + } +} + +// A Codex prompt with screenshots reads the same with its images cut: its +// text, however long, is kept whole. +func TestThinCodexKeepsPromptText(t *testing.T) { + prompt := strings.Repeat("重要执行方式:", 3000) + img := "data:image/png;base64," + strings.Repeat("iVBORw0KGgo", 300<<10) + big := `{"timestamp":"2026-10-21T09:24:46.501Z","type":"response_item","payload":{"type":"message","id":"msg_1","role":"user","content":[{"type":"input_text","text":"` + prompt + `"},{"type":"input_image","image_url":"` + img + `"},{"type":"input_text","text":"` + prompt + `"}]}}` + path := filepath.Join(t.TempDir(), "rollout.jsonl") + data := `{"timestamp":"2026-10-21T09:24:40.000Z","type":"session_meta","payload":{"id":"thread-1","cwd":"/work/x"}}` + "\n" + big + "\n" + + `{"timestamp":"2026-10-21T09:25:00.000Z","type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}}` + "\n" + if err := os.WriteFile(path, []byte(data), 0o600); err != nil { + t.Fatal(err) + } + var th thinner + th.urls = true + out := th.add(nil, []byte(big)) + var m struct { + Payload struct { + Content []struct { + Text string `json:"text"` + Image string `json:"image_url"` + } `json:"content"` + } `json:"payload"` + } + if err := json.Unmarshal(out, &m); err != nil { + t.Fatal(err) + } + if c := m.Payload.Content; len(c) != 3 || c[0].Text != prompt || c[2].Text != prompt || len(c[1].Image) > thinKeep || !strings.HasPrefix(c[1].Image, "data:image/png;base64,") { + t.Fatalf("thinned to %d bytes: %.80q", len(out), out) + } + + for _, main := range []bool{true, false} { + read := func(thin func([]byte) (thinner, bool)) *state { + s := &state{} + if _, err := scanThin(path, 0, func(b []byte) bool { return codexHead(s, b, main) }, thin, func(b []byte, _, _ int64) bool { + codexBody(s, b, main) + return true + }); err != nil { + t.Fatal(err) + } + return s + } + whole, thin := read(nil), read(thinCodex) + if !reflect.DeepEqual(whole, thin) { + t.Fatalf("main=%v: thinned\n%+v\nwhole\n%+v", main, thin, whole) + } + if thin.Title == "" { + t.Fatalf("main=%v: no title: %+v", main, thin) + } + } +}