| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "strings" |
| 6 | "sync/atomic" |
| 7 | "testing" |
| 8 | "time" |
| 9 | |
| 10 | "reasonix/internal/event" |
| 11 | "reasonix/internal/provider" |
| 12 | ) |
| 13 | |
| 14 | func TestDisplayTurnBufferPreservesStreamingReplacementAndTools(t *testing.T) { |
| 15 | var buffer displayTurnBuffer |
| 16 | recordHistoryDisplayEvent(&buffer, event.Event{Kind: event.Reasoning, Text: "draft reason "}) |
| 17 | recordHistoryDisplayEvent(&buffer, event.Event{Kind: event.Reasoning, Text: "continued"}) |
| 18 | recordHistoryDisplayEvent(&buffer, event.Event{Kind: event.Text, Text: "draft answer"}) |
| 19 | recordHistoryDisplayEvent(&buffer, event.Event{ |
| 20 | Kind: event.Message, |
| 21 | Text: "final answer", |
| 22 | Reasoning: "final reason", |
| 23 | MemoryCitations: []provider.MemoryCitation{{ |
| 24 | ID: "memory-1", Source: "project", |
| 25 | }}, |
| 26 | }) |
| 27 | recordHistoryDisplayEvent(&buffer, event.Event{Kind: event.ToolDispatch, Tool: event.Tool{ |
| 28 | ID: "call-1", Name: "read_file", Args: `{"path":"settings.json"}`, |
| 29 | }}) |
| 30 | recordHistoryDisplayEvent(&buffer, event.Event{Kind: event.ToolResult, Tool: event.Tool{ |
| 31 | ID: "call-1", Output: "settings contents", |
| 32 | }}) |
| 33 | |
| 34 | got := buffer.materialize() |
| 35 | if len(got) != 3 { |
| 36 | t.Fatalf("messages = %d, want 3: %+v", len(got), got) |
| 37 | } |
| 38 | if got[0].Role != "assistant" || got[0].Content != "final answer" || got[0].Reasoning != "final reason" { |
| 39 | t.Fatalf("stream replacement changed: %+v", got[0]) |
| 40 | } |
| 41 | if len(got[0].MemoryCitations) != 1 || got[0].MemoryCitations[0].ID != "memory-1" { |
| 42 | t.Fatalf("memory citations changed: %+v", got[0].MemoryCitations) |
| 43 | } |
| 44 | if got[1].Role != "assistant" || len(got[1].ToolCalls) != 1 || got[1].ToolCalls[0].ID != "call-1" || got[1].ToolCalls[0].Summary == "" { |
| 45 | t.Fatalf("tool call changed: %+v", got[1]) |
| 46 | } |
| 47 | if got[2].Role != "tool" || got[2].ToolCallID != "call-1" || got[2].ToolName != "read_file" { |
| 48 | t.Fatalf("tool result changed: %+v", got[2]) |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | func TestDisplayTurnBufferStreamingAllocationsStayNearLinear(t *testing.T) { |
| 53 | const ( |
| 54 | chunks = 2_000 |
| 55 | chunkSize = 32 |
| 56 | ) |
| 57 | chunk := strings.Repeat("x", chunkSize) |
| 58 | result := testing.Benchmark(func(b *testing.B) { |
| 59 | b.ReportAllocs() |
| 60 | for i := 0; i < b.N; i++ { |
| 61 | var buffer displayTurnBuffer |
| 62 | for part := 0; part < chunks; part++ { |
| 63 | recordHistoryDisplayEvent(&buffer, event.Event{Kind: event.Text, Text: chunk}) |
| 64 | } |
| 65 | messages := buffer.materialize() |
| 66 | if len(messages) != 1 || len(messages[0].Content) != chunks*chunkSize { |
| 67 | b.Fatalf("materialized display length changed") |
| 68 | } |
| 69 | } |
| 70 | }) |
| 71 | |
| 72 | // Repeated string concatenation allocated roughly one full growing prefix |
| 73 | // per chunk (>69 MiB for this 64 KiB stream). Keep a generous ceiling for |
| 74 | // platform/runtime variance while pinning the intended near-linear shape. |
| 75 | if got, max := result.AllocedBytesPerOp(), int64(chunks*chunkSize*16); got > max { |
| 76 | t.Fatalf("stream allocated %d bytes/op, want <= %d (%s)", got, max, result.String()) |
| 77 | } |
| 78 | if got := result.AllocsPerOp(); got > 100 { |
| 79 | t.Fatalf("stream allocated %d objects/op, want <= 100 (%s)", got, result.String()) |
| 80 | } |
| 81 | t.Logf("64 KiB stream: %d bytes/op, %d allocs/op", result.AllocedBytesPerOp(), result.AllocsPerOp()) |
| 82 | } |
| 83 | |
| 84 | func TestPendingDisplayWriteRetriesWithoutDroppingTurn(t *testing.T) { |
| 85 | state := &tabDisplayState{} |
| 86 | var attempts atomic.Int32 |
| 87 | persisted := make(chan struct{}) |
| 88 | write := &pendingDisplayWrite{ |
| 89 | dir: "sessions", |
| 90 | sessionPath: "sessions/session.jsonl", |
| 91 | userContent: "prompt", |
| 92 | messages: []HistoryMessage{{Role: "assistant", Content: "partial answer"}}, |
| 93 | persist: func(_, _, _ string, messages []HistoryMessage) error { |
| 94 | attempt := attempts.Add(1) |
| 95 | if len(messages) != 1 || messages[0].Content != "partial answer" { |
| 96 | return errors.New("queued turn changed") |
| 97 | } |
| 98 | if attempt < 3 { |
| 99 | return errors.New("temporary lock contention") |
| 100 | } |
| 101 | close(persisted) |
| 102 | return nil |
| 103 | }, |
| 104 | } |
| 105 | persistOrEnqueueDisplayWrite(state, write) |
| 106 | select { |
| 107 | case <-persisted: |
| 108 | case <-time.After(3 * time.Second): |
| 109 | t.Fatal("pending display write was not retried") |
| 110 | } |
| 111 | deadline := time.Now().Add(time.Second) |
| 112 | for { |
| 113 | state.mu.Lock() |
| 114 | pending := len(state.pendingWrites) |
| 115 | running := state.persistRunning |
| 116 | state.mu.Unlock() |
| 117 | if pending == 0 && !running { |
| 118 | break |
| 119 | } |
| 120 | if time.Now().After(deadline) { |
| 121 | t.Fatalf("retry worker did not drain: pending=%d running=%v", pending, running) |
| 122 | } |
| 123 | time.Sleep(5 * time.Millisecond) |
| 124 | } |
| 125 | if got := attempts.Load(); got != 3 { |
| 126 | t.Fatalf("persist attempts = %d, want 3", got) |
| 127 | } |
| 128 | } |
| 129 |