| 1 | package agent |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "reflect" |
| 7 | "strings" |
| 8 | "testing" |
| 9 | |
| 10 | "reasonix/internal/event" |
| 11 | "reasonix/internal/provider" |
| 12 | "reasonix/internal/tool" |
| 13 | ) |
| 14 | |
| 15 | // countingProvider records every summarizer call so tests can assert that a |
| 16 | // fold costs exactly one request. |
| 17 | type countingProvider struct { |
| 18 | reply string |
| 19 | got []provider.Request |
| 20 | } |
| 21 | |
| 22 | type deadlineInspectProvider struct { |
| 23 | hadDeadline bool |
| 24 | } |
| 25 | |
| 26 | type summaryChunksProvider struct { |
| 27 | chunks []provider.Chunk |
| 28 | } |
| 29 | |
| 30 | func (p *summaryChunksProvider) Name() string { return "summary-chunks" } |
| 31 | func (p *summaryChunksProvider) Stream(context.Context, provider.Request) (<-chan provider.Chunk, error) { |
| 32 | ch := make(chan provider.Chunk, len(p.chunks)+1) |
| 33 | for _, chunk := range p.chunks { |
| 34 | ch <- chunk |
| 35 | } |
| 36 | ch <- provider.Chunk{Type: provider.ChunkDone} |
| 37 | close(ch) |
| 38 | return ch, nil |
| 39 | } |
| 40 | |
| 41 | func (p *deadlineInspectProvider) Name() string { return "deadline-inspect" } |
| 42 | func (p *deadlineInspectProvider) Stream(ctx context.Context, _ provider.Request) (<-chan provider.Chunk, error) { |
| 43 | _, p.hadDeadline = ctx.Deadline() |
| 44 | ch := make(chan provider.Chunk, 2) |
| 45 | ch <- provider.Chunk{Type: provider.ChunkText, Text: "digest"} |
| 46 | ch <- provider.Chunk{Type: provider.ChunkDone} |
| 47 | close(ch) |
| 48 | return ch, nil |
| 49 | } |
| 50 | |
| 51 | func TestSummaryDoesNotAddInternalWallClockDeadline(t *testing.T) { |
| 52 | prov := &deadlineInspectProvider{} |
| 53 | a := New(prov, tool.NewRegistry(), &Session{Messages: []provider.Message{{Role: provider.RoleSystem, Content: "sys"}}}, Options{}, event.Discard) |
| 54 | if _, err := a.foldToSummary(context.Background(), []provider.Message{{Role: provider.RoleUser, Content: "old"}}, ""); err != nil { |
| 55 | t.Fatal(err) |
| 56 | } |
| 57 | if prov.hadDeadline { |
| 58 | t.Fatal("summary provider context unexpectedly has an internal deadline") |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | func TestSummaryCollectorStoresOnlyVisibleText(t *testing.T) { |
| 63 | prov := &summaryChunksProvider{chunks: []provider.Chunk{ |
| 64 | {Type: provider.ChunkReasoning, Text: "PRIVATE REASONING"}, |
| 65 | {Type: provider.ChunkToolCall, ToolCall: &provider.ToolCall{ID: "call-1", Name: "read_file", Arguments: `{}`}}, |
| 66 | {Type: provider.ChunkText, Text: "VISIBLE DIGEST"}, |
| 67 | {Type: provider.ChunkDone}, |
| 68 | }} |
| 69 | a := New(prov, tool.NewRegistry(), NewSession("system"), Options{}, event.Discard) |
| 70 | got, _, err := a.summarize(context.Background(), []provider.Message{{Role: provider.RoleUser, Content: "old"}}, "") |
| 71 | if err != nil { |
| 72 | t.Fatal(err) |
| 73 | } |
| 74 | if got != "VISIBLE DIGEST" { |
| 75 | t.Fatalf("summary = %q, want visible text only", got) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | func TestSummaryCollectorRejectsEmptyAndLengthLimitedOutput(t *testing.T) { |
| 80 | for _, tc := range []struct { |
| 81 | name string |
| 82 | chunks []provider.Chunk |
| 83 | want string |
| 84 | }{ |
| 85 | { |
| 86 | name: "reasoning and tool call are empty", |
| 87 | chunks: []provider.Chunk{ |
| 88 | {Type: provider.ChunkReasoning, Text: "PRIVATE REASONING"}, |
| 89 | {Type: provider.ChunkToolCall, ToolCall: &provider.ToolCall{ID: "call-1", Name: "read_file"}}, |
| 90 | }, |
| 91 | want: "empty output", |
| 92 | }, |
| 93 | { |
| 94 | name: "length finish", |
| 95 | chunks: []provider.Chunk{ |
| 96 | {Type: provider.ChunkText, Text: "partial"}, |
| 97 | {Type: provider.ChunkUsage, Usage: &provider.Usage{FinishReason: "length"}}, |
| 98 | }, |
| 99 | want: "output token limit", |
| 100 | }, |
| 101 | } { |
| 102 | t.Run(tc.name, func(t *testing.T) { |
| 103 | prov := &summaryChunksProvider{chunks: tc.chunks} |
| 104 | a := New(prov, tool.NewRegistry(), NewSession("system"), Options{}, event.Discard) |
| 105 | if _, _, err := a.summarize(context.Background(), []provider.Message{{Role: provider.RoleUser, Content: "old"}}, ""); err == nil || !strings.Contains(err.Error(), tc.want) { |
| 106 | t.Fatalf("summarize error = %v, want %q", err, tc.want) |
| 107 | } |
| 108 | }) |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | func TestSummaryRequestReplaysSystemToolsAndSelectedPrefix(t *testing.T) { |
| 113 | prov := &countingProvider{reply: "digest"} |
| 114 | reg := tool.NewRegistry() |
| 115 | reg.Add(echoTool{}) |
| 116 | system := provider.Message{Role: provider.RoleSystem, Content: "stable system", CreatedAt: 11} |
| 117 | fold := []provider.Message{ |
| 118 | {Role: provider.RoleUser, Content: "old task", CreatedAt: 12}, |
| 119 | {Role: provider.RoleAssistant, Content: "old work", CreatedAt: 13}, |
| 120 | } |
| 121 | a := New(prov, reg, &Session{Messages: append([]provider.Message{system}, fold...)}, Options{ContextWindow: 100_000, MaxOutputTokens: 1024}, event.Discard) |
| 122 | |
| 123 | if _, err := a.foldToSummary(context.Background(), fold, "keep exact identifiers"); err != nil { |
| 124 | t.Fatalf("foldToSummary: %v", err) |
| 125 | } |
| 126 | if len(prov.got) != 1 { |
| 127 | t.Fatalf("summary requests = %d, want 1", len(prov.got)) |
| 128 | } |
| 129 | req := prov.got[0] |
| 130 | if len(req.Messages) != 4 { |
| 131 | t.Fatalf("summary messages = %d, want system + 2 prefix messages + instruction", len(req.Messages)) |
| 132 | } |
| 133 | wantPrefix := []provider.Message{system, fold[0], fold[1]} |
| 134 | for i := range wantPrefix { |
| 135 | wantPrefix[i].CreatedAt = 0 |
| 136 | if !reflect.DeepEqual(req.Messages[i], wantPrefix[i]) { |
| 137 | t.Fatalf("prefix message %d = %+v, want %+v", i, req.Messages[i], wantPrefix[i]) |
| 138 | } |
| 139 | } |
| 140 | last := req.Messages[len(req.Messages)-1] |
| 141 | if last.Role != provider.RoleUser || !strings.Contains(last.Content, "keep exact identifiers") || !strings.Contains(last.Content, "Do not call tools") { |
| 142 | t.Fatalf("final compaction instruction = %+v", last) |
| 143 | } |
| 144 | if len(req.Tools) != 1 || req.Tools[0].Name != "echo" { |
| 145 | t.Fatalf("summary tools = %+v, want normal echo schema", req.Tools) |
| 146 | } |
| 147 | if req.MaxTokens != summaryOutputMaxTokens { |
| 148 | t.Fatalf("summary max tokens = %d, want fixed cap %d", req.MaxTokens, summaryOutputMaxTokens) |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | func (p *countingProvider) Name() string { return "counting" } |
| 153 | |
| 154 | func (p *countingProvider) Stream(_ context.Context, req provider.Request) (<-chan provider.Chunk, error) { |
| 155 | p.got = append(p.got, req) |
| 156 | ch := make(chan provider.Chunk, 2) |
| 157 | ch <- provider.Chunk{Type: provider.ChunkText, Text: fmt.Sprintf("%s %d", p.reply, len(p.got))} |
| 158 | ch <- provider.Chunk{Type: provider.ChunkDone} |
| 159 | close(ch) |
| 160 | return ch, nil |
| 161 | } |
| 162 | |
| 163 | func foldOfToolResults(n, size int) []provider.Message { |
| 164 | fold := make([]provider.Message, 0, n*2) |
| 165 | for i := range n { |
| 166 | fold = append(fold, |
| 167 | provider.Message{Role: provider.RoleAssistant, ToolCalls: []provider.ToolCall{{ID: fmt.Sprint(i), Name: "read_file", Arguments: "{}"}}}, |
| 168 | provider.Message{Role: provider.RoleTool, ToolCallID: fmt.Sprint(i), Name: "read_file", Content: strings.Repeat(fmt.Sprintf("line %d filler\n", i), size)}, |
| 169 | ) |
| 170 | } |
| 171 | return fold |
| 172 | } |
| 173 | |
| 174 | func newFoldAgent(t *testing.T, window int, prov provider.Provider) *Agent { |
| 175 | t.Helper() |
| 176 | return New(prov, nil, &Session{}, Options{ContextWindow: window}, event.Discard) |
| 177 | } |
| 178 | |
| 179 | func TestFoldUnderBudgetIsSummarizedVerbatimInOneCall(t *testing.T) { |
| 180 | prov := &countingProvider{reply: "digest"} |
| 181 | a := newFoldAgent(t, 200000, prov) |
| 182 | fold := foldOfToolResults(3, 40) |
| 183 | |
| 184 | res, err := a.foldToSummary(context.Background(), fold, "") |
| 185 | if err != nil { |
| 186 | t.Fatalf("foldToSummary: %v", err) |
| 187 | } |
| 188 | if len(prov.got) != 1 || res.Spans != 1 { |
| 189 | t.Fatalf("requests=%d spans=%d, want a single call", len(prov.got), res.Spans) |
| 190 | } |
| 191 | if body := joinContents(prov.got[0].Messages); strings.Contains(body, snippedMarker) { |
| 192 | t.Fatal("an under-budget fold must reach the summarizer unshortened") |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | func TestManualFoldDoesNotPrivatelyShortenToolResults(t *testing.T) { |
| 197 | prov := &countingProvider{reply: "digest"} |
| 198 | a := newFoldAgent(t, 24000, prov) |
| 199 | fold := foldOfToolResults(6, 300) |
| 200 | |
| 201 | res, err := a.foldToSummary(context.Background(), fold, "") |
| 202 | if err != nil { |
| 203 | t.Fatalf("foldToSummary: %v", err) |
| 204 | } |
| 205 | if len(prov.got) != 1 || res.Spans != 1 { |
| 206 | t.Fatalf("requests=%d spans=%d, want exactly one call", len(prov.got), res.Spans) |
| 207 | } |
| 208 | body := joinContents(prov.got[0].Messages) |
| 209 | if strings.Contains(body, snippedMarker) || strings.Contains(body, toolPruneMarker) { |
| 210 | t.Fatalf("manual summary input was privately pruned:\n%.300q", body) |
| 211 | } |
| 212 | if !strings.Contains(body, "line 5 filler") { |
| 213 | t.Fatalf("complete tool results did not reach summarizer:\n%.300q", body) |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | func TestHugeFoldNeverMultiSpan(t *testing.T) { |
| 218 | // Even a very large fold gets at most one complete-prefix provider request. |
| 219 | // If it cannot fit, the transaction fails rather than shortening or splitting. |
| 220 | prov := &countingProvider{reply: "digest"} |
| 221 | a := newFoldAgent(t, 32000, prov) |
| 222 | fold := foldOfToolResults(80, 800) |
| 223 | |
| 224 | res, err := a.foldToSummary(context.Background(), fold, "focus on the parser") |
| 225 | if err != nil { |
| 226 | // Failure without a second attempt is acceptable for an unfittable fold. |
| 227 | if len(prov.got) != 0 { |
| 228 | t.Fatalf("failed fold still made %d provider requests", len(prov.got)) |
| 229 | } |
| 230 | return |
| 231 | } |
| 232 | if len(prov.got) != 1 || res.Spans != 1 { |
| 233 | t.Fatalf("requests=%d spans=%d, want at most one call", len(prov.got), res.Spans) |
| 234 | } |
| 235 | if !strings.Contains(prov.got[0].Messages[len(prov.got[0].Messages)-1].Content, "focus on the parser") { |
| 236 | t.Fatal("focus instructions lost") |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | func TestNoContextWindowLeavesTheFoldUnbounded(t *testing.T) { |
| 241 | prov := &countingProvider{reply: "digest"} |
| 242 | a := New(prov, nil, &Session{}, Options{}, event.Discard) |
| 243 | fold := foldOfToolResults(40, 400) |
| 244 | |
| 245 | res, err := a.foldToSummary(context.Background(), fold, "") |
| 246 | if err != nil { |
| 247 | // Without a window the input budget is 0 and the single-call path |
| 248 | // refuses before paying for a request. |
| 249 | if len(prov.got) != 0 { |
| 250 | t.Fatalf("no-window failure still called provider %d times", len(prov.got)) |
| 251 | } |
| 252 | return |
| 253 | } |
| 254 | if len(prov.got) != 1 || res.Spans != 1 { |
| 255 | t.Fatalf("requests=%d spans=%d, want one unbounded call", len(prov.got), res.Spans) |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | func TestSummarizeOnceNoRetry(t *testing.T) { |
| 260 | prov := &failOnceProvider{} |
| 261 | a := newFoldAgent(t, 200000, prov) |
| 262 | _, _, err := a.summarizeOnce(context.Background(), []provider.Message{ |
| 263 | {Role: provider.RoleUser, Content: "hello"}, |
| 264 | }, "") |
| 265 | if err == nil { |
| 266 | t.Fatal("expected error") |
| 267 | } |
| 268 | if prov.calls != 1 { |
| 269 | t.Fatalf("provider calls = %d, want exactly 1 (no application-layer retry)", prov.calls) |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | type failOnceProvider struct{ calls int } |
| 274 | |
| 275 | func (p *failOnceProvider) Name() string { return "fail-once" } |
| 276 | |
| 277 | func (p *failOnceProvider) Stream(_ context.Context, _ provider.Request) (<-chan provider.Chunk, error) { |
| 278 | p.calls++ |
| 279 | ch := make(chan provider.Chunk, 1) |
| 280 | ch <- provider.Chunk{Type: provider.ChunkError, Err: fmt.Errorf("network glitch")} |
| 281 | close(ch) |
| 282 | return ch, nil |
| 283 | } |
| 284 |