686690f7b4
Reading a history page parsed the whole session file (tens of MB) on every chat_messages. A per-file index now records which lines build each shown message; a page re-reads and replays only its own messages' lines, and the index follows appends by reading only the new bytes. Results match the whole-file read (compared page by page on synthetic transcripts); shapes the index cannot replay exactly fall back to the whole-file read. chat_subscribe may ask (history: true) for the newest page in its reply, read once the subscription is attached, saving the client a round trip. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
438 lines
15 KiB
Go
438 lines
15 KiB
Go
package claude
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"math/rand"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// synthTranscript writes a synthetic, real-shaped Claude session file: turns
|
|
// of prompts, thinking, text and parallel tool calls whose results carry large
|
|
// toolUseResult payloads, with sidechain (subagent) entries, compaction,
|
|
// queued prompts, task notifications and agent reports (some delivered twice),
|
|
// image prompts, signature-only thinking, malformed and blank lines. No real
|
|
// transcript is read.
|
|
type synthTranscript struct {
|
|
rand *rand.Rand
|
|
lines []string
|
|
clock time.Time
|
|
turn int
|
|
tool int
|
|
}
|
|
|
|
func newSynthTranscript(seed int64) *synthTranscript {
|
|
return &synthTranscript{rand: rand.New(rand.NewSource(seed)), clock: time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)}
|
|
}
|
|
|
|
func (g *synthTranscript) emit(entry map[string]any) {
|
|
g.clock = g.clock.Add(time.Duration(1+g.rand.Intn(2000)) * time.Millisecond)
|
|
base := map[string]any{
|
|
"parentUuid": nil, "isSidechain": false, "userType": "external", "cwd": "/home/op/work",
|
|
"sessionId": "ses_synth", "version": "2.1.0", "gitBranch": "main",
|
|
"uuid": fmt.Sprintf("uuid-%d", len(g.lines)), "timestamp": g.clock.Format(time.RFC3339Nano),
|
|
}
|
|
for key, value := range entry {
|
|
base[key] = value
|
|
}
|
|
raw, err := json.Marshal(base)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
g.lines = append(g.lines, string(raw))
|
|
}
|
|
|
|
func (g *synthTranscript) words(n int) string {
|
|
vocabulary := []string{"build", "the", "server", "reads", "a", "page", "of", "chat", "history", "quickly", "and", "tests", "pass", "<tag>", "\"quoted\"", "naïve", "→"}
|
|
var builder strings.Builder
|
|
for i := 0; i < n; i++ {
|
|
if i > 0 {
|
|
builder.WriteByte(' ')
|
|
}
|
|
builder.WriteString(vocabulary[g.rand.Intn(len(vocabulary))])
|
|
}
|
|
return builder.String()
|
|
}
|
|
|
|
func (g *synthTranscript) assistant(messageID string, sidechain bool, blocks ...map[string]any) {
|
|
for _, block := range blocks {
|
|
g.emit(map[string]any{
|
|
"type": "assistant", "isSidechain": sidechain, "requestId": "req_" + messageID,
|
|
"message": map[string]any{
|
|
"id": messageID, "type": "message", "role": "assistant", "model": "claude-opus-4-5",
|
|
"content": []any{block}, "stop_reason": nil,
|
|
"usage": map[string]any{"input_tokens": 3, "output_tokens": 120, "cache_read_input_tokens": 51234},
|
|
},
|
|
})
|
|
}
|
|
}
|
|
|
|
func (g *synthTranscript) user(content any, extra map[string]any) {
|
|
entry := map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": content}}
|
|
for key, value := range extra {
|
|
entry[key] = value
|
|
}
|
|
g.emit(entry)
|
|
}
|
|
|
|
// addTurn appends one turn; resultBytes sizes the tool payloads.
|
|
func (g *synthTranscript) addTurn(prompt string, resultBytes int) {
|
|
g.turn++
|
|
turn := g.turn
|
|
switch g.rand.Intn(10) {
|
|
case 0:
|
|
g.emit(queued(fmt.Sprintf("q-%d", len(g.lines)), "prompt", textBlocks(prompt), nil))
|
|
case 1:
|
|
g.user([]any{map[string]any{"type": "text", "text": prompt}, map[string]any{"type": "image", "source": map[string]any{"type": "base64", "media_type": "image/png", "data": strings.Repeat("iVBO", 50)}}}, nil)
|
|
default:
|
|
g.user(textBlocks(prompt), map[string]any{"promptSource": "sdk"})
|
|
}
|
|
for step := 0; step < 1+g.rand.Intn(4); step++ {
|
|
messageID := fmt.Sprintf("msg_%d_%d", turn, step)
|
|
g.assistant(messageID, false, map[string]any{"type": "thinking", "thinking": "", "signature": strings.Repeat("s", 300)})
|
|
if g.rand.Intn(2) == 0 {
|
|
g.assistant(messageID, false, map[string]any{"type": "thinking", "thinking": g.words(40), "signature": "sig"})
|
|
}
|
|
g.assistant(messageID, false, map[string]any{"type": "text", "text": g.words(30 + g.rand.Intn(80))})
|
|
var calls []string
|
|
for call := 0; call < g.rand.Intn(3); call++ {
|
|
g.tool++
|
|
toolID := fmt.Sprintf("toolu_%06d", g.tool)
|
|
calls = append(calls, toolID)
|
|
g.assistant(messageID, false, map[string]any{"type": "tool_use", "id": toolID, "name": "Bash", "input": map[string]any{"command": "go test ./... " + g.words(5), "description": "Run tests"}})
|
|
if call == 0 && g.rand.Intn(3) == 0 {
|
|
// A result landing between two blocks of one message.
|
|
g.result(toolID, resultBytes)
|
|
calls = calls[:0]
|
|
}
|
|
}
|
|
for _, toolID := range calls {
|
|
g.result(toolID, resultBytes)
|
|
}
|
|
if g.rand.Intn(6) == 0 {
|
|
// A subagent's work is a sidechain of the same file.
|
|
g.assistant(fmt.Sprintf("msg_side_%d_%d", turn, step), true, map[string]any{"type": "text", "text": "subagent " + g.words(20)})
|
|
g.user(textBlocks("subagent prompt"), map[string]any{"isSidechain": true})
|
|
}
|
|
}
|
|
switch g.rand.Intn(12) {
|
|
case 0:
|
|
notice := strings.Replace(taskNotification, "toolu_bg1", fmt.Sprintf("toolu_bg%d", turn%5), 1)
|
|
g.user(notice, map[string]any{"origin": map[string]any{"kind": "task-notification"}})
|
|
g.emit(queued(fmt.Sprintf("q-%d", len(g.lines)), "task-notification", notice, map[string]any{"origin": map[string]any{"kind": "task-notification"}}))
|
|
case 1:
|
|
g.emit(queued(fmt.Sprintf("q-%d", len(g.lines)), "prompt", subagentReport, map[string]any{"isMeta": true, "origin": peerOrigin(fmt.Sprintf("a%d", turn%3), true, "## Report "+strconv.Itoa(turn%4))}))
|
|
case 2:
|
|
g.user("<system-reminder>\nnothing for the operator\n</system-reminder>", map[string]any{"isMeta": true})
|
|
case 3:
|
|
g.emit(map[string]any{"type": "system", "subtype": "compact_boundary", "content": "Conversation compacted", "compactMetadata": map[string]any{"trigger": "auto", "preTokens": 160000}})
|
|
g.user(textBlocks("This session is being continued from a previous conversation. "+g.words(200)), map[string]any{"isCompactSummary": true, "isVisibleInTranscriptOnly": true})
|
|
case 4:
|
|
g.lines = append(g.lines, `{"type":"assistant","message":{"id":"broken`, "")
|
|
case 5:
|
|
g.user(textBlocks(midTurnWrapped), nil)
|
|
case 6:
|
|
g.emit(map[string]any{"type": "file-history-snapshot", "snapshot": map[string]any{"files": g.words(50)}})
|
|
}
|
|
}
|
|
|
|
func (g *synthTranscript) result(toolID string, size int) {
|
|
output := strings.Repeat(g.words(12)+"\n", 1+size/80)
|
|
content := any(output)
|
|
isError := g.rand.Intn(9) == 0
|
|
if g.rand.Intn(4) == 0 {
|
|
content = []any{map[string]any{"type": "text", "text": output + "\nexit code 1"}}
|
|
}
|
|
g.user([]any{map[string]any{"type": "tool_result", "tool_use_id": toolID, "content": content, "is_error": isError}},
|
|
map[string]any{"toolUseResult": map[string]any{"stdout": output, "stderr": "", "interrupted": false, "file": map[string]any{"content": output}}})
|
|
}
|
|
|
|
func (g *synthTranscript) build(turns, resultBytes int) *synthTranscript {
|
|
prompts := []string{"continue", "run the tests", "ship it now", "also check the docs"}
|
|
for i := 0; i < turns; i++ {
|
|
prompt := prompts[g.rand.Intn(len(prompts))]
|
|
if g.rand.Intn(2) == 0 {
|
|
prompt = fmt.Sprintf("turn %d: %s", i, g.words(10))
|
|
}
|
|
g.addTurn(prompt, resultBytes)
|
|
}
|
|
return g
|
|
}
|
|
|
|
func (g *synthTranscript) text() string { return strings.Join(g.lines, "\n") + "\n" }
|
|
|
|
func writeSynthFile(t testing.TB, id, text string) string {
|
|
t.Helper()
|
|
config := t.TempDir()
|
|
t.Setenv("CLAUDE_CONFIG_DIR", config)
|
|
dir := filepath.Join(config, "projects", "-home-op-work")
|
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
path := filepath.Join(dir, id+".jsonl")
|
|
if err := os.WriteFile(path, []byte(text), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return path
|
|
}
|
|
|
|
func appendFile(t testing.TB, path, text string) {
|
|
t.Helper()
|
|
file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer file.Close()
|
|
if _, err := file.WriteString(text); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
// assertIndexedMatchesFull compares every page of the file, served by the
|
|
// index, with the same page built from the whole file.
|
|
func assertIndexedMatchesFull(t *testing.T, path string, prompts []promptRecord) {
|
|
t.Helper()
|
|
for _, limit := range []int{7, 20, 50, 100, 200} {
|
|
cursor := ""
|
|
for pages := 0; ; pages++ {
|
|
want, err := fullTranscriptPage(path, "ses_synth", prompts, limit, cursor)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
got, ok, err := indexedTranscriptPage(path, "ses_synth", prompts, limit, cursor)
|
|
if err != nil || !ok {
|
|
t.Fatalf("limit %d cursor %q: indexed page not served (ok=%v err=%v)", limit, cursor, ok, err)
|
|
}
|
|
wantJSON, _ := json.Marshal(want)
|
|
gotJSON, _ := json.Marshal(got)
|
|
if string(wantJSON) != string(gotJSON) {
|
|
t.Fatalf("limit %d cursor %q: indexed page differs\n got %.600s\nwant %.600s", limit, cursor, gotJSON, wantJSON)
|
|
}
|
|
if !want.HasMore || pages > 400 {
|
|
break
|
|
}
|
|
cursor = want.NextCursor
|
|
}
|
|
}
|
|
for _, cursor := range []string{"0", "3", "-2", "x", "999999"} {
|
|
want, _ := fullTranscriptPage(path, "ses_synth", prompts, 20, cursor)
|
|
got, _, _ := indexedTranscriptPage(path, "ses_synth", prompts, 20, cursor)
|
|
wantJSON, _ := json.Marshal(want)
|
|
gotJSON, _ := json.Marshal(got)
|
|
if string(wantJSON) != string(gotJSON) {
|
|
t.Fatalf("cursor %q: indexed page differs", cursor)
|
|
}
|
|
}
|
|
}
|
|
|
|
func synthPrompts() []promptRecord {
|
|
return []promptRecord{
|
|
{id: "op-1", text: "continue"}, {id: "op-2", text: "continue"}, {id: "op-3", text: "run the tests"},
|
|
{id: "op-4", text: "also check the docs"}, {id: "op-5", text: "ship it now"}, {id: "op-6", text: "continue"},
|
|
}
|
|
}
|
|
|
|
func TestIndexedHistoryMatchesTheWholeFileRead(t *testing.T) {
|
|
for seed := int64(1); seed <= 4; seed++ {
|
|
text := newSynthTranscript(seed).build(60, 300).text()
|
|
path := writeSynthFile(t, fmt.Sprintf("ses_seed%d", seed), text)
|
|
assertIndexedMatchesFull(t, path, nil)
|
|
assertIndexedMatchesFull(t, path, synthPrompts())
|
|
if seed == 1 {
|
|
assertFixtureCoverage(t, path)
|
|
}
|
|
}
|
|
}
|
|
|
|
// assertFixtureCoverage checks the synthetic file exercises what the
|
|
// comparison is meant to cover.
|
|
func assertFixtureCoverage(t *testing.T, path string) {
|
|
t.Helper()
|
|
seen := map[string]int{}
|
|
cursor := ""
|
|
for {
|
|
page, err := fullTranscriptPage(path, "ses_synth", synthPrompts(), 100, cursor)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, message := range page.Messages {
|
|
seen["kind:"+message.Kind]++
|
|
if strings.HasPrefix(message.ID, "op-") {
|
|
seen["prompt id"]++
|
|
}
|
|
if strings.HasPrefix(message.ID, "q-") {
|
|
seen["queued prompt"]++
|
|
}
|
|
for _, part := range message.Parts {
|
|
seen["part:"+part.Type]++
|
|
if part.State != nil && len(part.State.Content) > 0 {
|
|
seen["tool result"]++
|
|
}
|
|
if part.State != nil && part.State.Error != nil {
|
|
seen["tool error"]++
|
|
}
|
|
}
|
|
}
|
|
if !page.HasMore {
|
|
break
|
|
}
|
|
cursor = page.NextCursor
|
|
}
|
|
for _, want := range []string{"kind:notice", "kind:agent_report", "prompt id", "queued prompt", "part:reasoning", "part:file", "tool result", "tool error"} {
|
|
if seen[want] == 0 {
|
|
t.Fatalf("fixture lacks %q: %v", want, seen)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Appending turns, a half-written last line and its completion, are read
|
|
// incrementally and still match the whole-file read.
|
|
func TestIndexedHistoryFollowsAppends(t *testing.T) {
|
|
g := newSynthTranscript(7).build(30, 200)
|
|
path := writeSynthFile(t, "ses_append", g.text())
|
|
assertIndexedMatchesFull(t, path, synthPrompts())
|
|
written := len(g.lines)
|
|
for round := 0; round < 4; round++ {
|
|
g.build(3, 200)
|
|
appendFile(t, path, strings.Join(g.lines[written:], "\n")+"\n")
|
|
written = len(g.lines)
|
|
assertIndexedMatchesFull(t, path, synthPrompts())
|
|
}
|
|
before := transcriptIndexFor(path).offset
|
|
// A line still being written is left for the next read.
|
|
appendFile(t, path, `{"type":"assistant","uuid":"tail","message":{"id":"msg_tail","role":"assistant","content":[{"type":"text","text":"half`)
|
|
assertIndexedMatchesFull(t, path, nil)
|
|
appendFile(t, path, ` done"}]}}`)
|
|
// A parseable line with no newline yet is read whole, as before.
|
|
if _, ok, _ := indexedTranscriptPage(path, "ses_synth", nil, 20, ""); ok {
|
|
t.Fatal("a parseable unterminated last line must be read from the whole file")
|
|
}
|
|
appendFile(t, path, "\n")
|
|
assertIndexedMatchesFull(t, path, nil)
|
|
if index := transcriptIndexFor(path); index.offset <= before || index.start != 0 {
|
|
t.Fatalf("index did not grow incrementally: offset %d (was %d)", index.offset, before)
|
|
}
|
|
}
|
|
|
|
// A file rewritten in place (same size or shorter) is indexed again.
|
|
func TestIndexedHistoryNoticesARewrite(t *testing.T) {
|
|
first := newSynthTranscript(8).build(20, 100).text()
|
|
path := writeSynthFile(t, "ses_rewrite", first)
|
|
assertIndexedMatchesFull(t, path, nil)
|
|
second := newSynthTranscript(9).build(10, 100).text()
|
|
if err := os.WriteFile(path, []byte(second), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
assertIndexedMatchesFull(t, path, nil)
|
|
// Same length, different content: the boundary check catches it.
|
|
third := []byte(second)
|
|
copy(third[len(third)-40:], strings.Repeat(" ", 38))
|
|
if err := os.WriteFile(path, third, 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
future := time.Now().Add(time.Hour)
|
|
_ = os.Chtimes(path, future, future)
|
|
assertIndexedMatchesFull(t, path, nil)
|
|
}
|
|
|
|
// An oversized file is indexed from its newest maxTranscriptBytes, with the
|
|
// same earlier-history notice.
|
|
func TestIndexedHistoryOfAnOversizedFile(t *testing.T) {
|
|
g := newSynthTranscript(10).build(40, 200)
|
|
path := writeSynthFile(t, "ses_big", g.text())
|
|
defer func(limit int64) { maxTranscriptBytes = limit }(maxTranscriptBytes)
|
|
maxTranscriptBytes = int64(len(g.text()) / 3)
|
|
assertIndexedMatchesFull(t, path, synthPrompts())
|
|
written := len(g.lines)
|
|
g.build(2, 200)
|
|
appendFile(t, path, strings.Join(g.lines[written:], "\n")+"\n")
|
|
assertIndexedMatchesFull(t, path, synthPrompts())
|
|
}
|
|
|
|
// The session description read from the index matches the whole-file read.
|
|
func TestIndexedTranscriptMetaMatches(t *testing.T) {
|
|
text := newSynthTranscript(11).build(20, 100).text()
|
|
path := writeSynthFile(t, "ses_meta", text)
|
|
entries, err := readTranscript(path)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
want := transcriptMeta{}
|
|
for _, entry := range entries {
|
|
want.note(entry)
|
|
}
|
|
got, ok := indexedTranscriptMeta(path)
|
|
if !ok || got != want {
|
|
t.Fatalf("meta = %+v ok=%v, want %+v", got, ok, want)
|
|
}
|
|
}
|
|
|
|
// benchmarkFile synthesizes a transcript of about 40 MB, shaped like a long
|
|
// working session.
|
|
func benchmarkFile(b *testing.B) string {
|
|
b.Helper()
|
|
text := newSynthTranscript(42).build(1100, 6000).text()
|
|
path := writeSynthFile(b, "ses_bench", text)
|
|
b.Logf("synthetic transcript: %.1f MB", float64(len(text))/(1<<20))
|
|
return path
|
|
}
|
|
|
|
func BenchmarkTranscriptNewestPageWholeFile(b *testing.B) {
|
|
path := benchmarkFile(b)
|
|
b.ResetTimer()
|
|
for i := 0; i < b.N; i++ {
|
|
if _, err := fullTranscriptPage(path, "ses_bench", nil, 100, ""); err != nil {
|
|
b.Fatal(err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func BenchmarkTranscriptNewestPageIndexed(b *testing.B) {
|
|
path := benchmarkFile(b)
|
|
if _, ok, err := indexedTranscriptPage(path, "ses_bench", nil, 100, ""); !ok || err != nil {
|
|
b.Fatal("index not served")
|
|
}
|
|
b.ResetTimer()
|
|
for i := 0; i < b.N; i++ {
|
|
if _, ok, err := indexedTranscriptPage(path, "ses_bench", nil, 100, ""); !ok || err != nil {
|
|
b.Fatal("index not served")
|
|
}
|
|
}
|
|
}
|
|
|
|
func BenchmarkTranscriptNewestPageIndexedAfterAppend(b *testing.B) {
|
|
path := benchmarkFile(b)
|
|
if _, ok, err := indexedTranscriptPage(path, "ses_bench", nil, 100, ""); !ok || err != nil {
|
|
b.Fatal("index not served")
|
|
}
|
|
g := newSynthTranscript(43)
|
|
g.turn, g.tool = 100000, 1000000
|
|
b.ResetTimer()
|
|
for i := 0; i < b.N; i++ {
|
|
b.StopTimer()
|
|
g.lines = g.lines[:0]
|
|
g.addTurn("continue", 6000)
|
|
appendFile(b, path, g.text())
|
|
b.StartTimer()
|
|
if _, ok, err := indexedTranscriptPage(path, "ses_bench", nil, 100, ""); !ok || err != nil {
|
|
b.Fatal("index not served")
|
|
}
|
|
}
|
|
}
|
|
|
|
func BenchmarkTranscriptIndexColdBuild(b *testing.B) {
|
|
path := benchmarkFile(b)
|
|
b.ResetTimer()
|
|
for i := 0; i < b.N; i++ {
|
|
forgetTranscriptIndex(path)
|
|
if _, ok, err := indexedTranscriptPage(path, "ses_bench", nil, 100, ""); !ok || err != nil {
|
|
b.Fatal("index not served")
|
|
}
|
|
}
|
|
}
|