| 1 | package agent |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "reflect" |
| 7 | "testing" |
| 8 | |
| 9 | "reasonix/internal/agent/testutil" |
| 10 | "reasonix/internal/event" |
| 11 | "reasonix/internal/provider" |
| 12 | ) |
| 13 | |
| 14 | type strictNoWarningReasoningProvider struct{ *testutil.MockProvider } |
| 15 | |
| 16 | func (p strictNoWarningReasoningProvider) RequiresToolCallReasoning() bool { return true } |
| 17 | func (p strictNoWarningReasoningProvider) WarnOnMissingToolCallReasoning() bool { return false } |
| 18 | |
| 19 | func TestStrictNoWarningReplayDoesNotLeakSpeculativeEvents(t *testing.T) { |
| 20 | missingTurn := func(id string) testutil.Turn { |
| 21 | call := provider.ToolCall{ID: id, Name: "echo", Arguments: `{"text":"must not run"}`} |
| 22 | return testutil.Turn{Chunks: []provider.Chunk{ |
| 23 | {Type: provider.ChunkText, Text: "speculative"}, |
| 24 | {Type: provider.ChunkToolCallStart, ToolCall: &call}, |
| 25 | {Type: provider.ChunkToolCall, ToolCall: &call}, |
| 26 | {Type: provider.ChunkDone}, |
| 27 | }} |
| 28 | } |
| 29 | providerMock := testutil.NewMock("strict-no-warning", missingTurn("c1"), missingTurn("c2")) |
| 30 | sink := &recordSink{} |
| 31 | agent := New(strictNoWarningReasoningProvider{providerMock}, echoRegistry(), NewSession(""), Options{}, sink) |
| 32 | |
| 33 | var replayErr *ReasoningReplayError |
| 34 | if err := agent.Run(withNoClosedLoop(context.Background()), "go"); !errors.As(err, &replayErr) { |
| 35 | t.Fatalf("Run error = %v, want ReasoningReplayError", err) |
| 36 | } |
| 37 | if got := providerMock.CallCount(); got != 2 { |
| 38 | t.Fatalf("provider calls = %d, want malformed turn plus one exact retry", got) |
| 39 | } |
| 40 | for _, kind := range []event.Kind{event.ToolDispatch, event.ToolResult, event.Text, event.Message} { |
| 41 | if got := len(sink.kinds(kind)); got != 0 { |
| 42 | t.Fatalf("speculative %v events = %d, want 0", kind, got) |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | func thinkingReplay400Error() error { |
| 48 | return provider.ParseReasoningReplayError(&provider.APIError{ |
| 49 | Provider: "strict-replay", Status: 400, |
| 50 | Body: `{"error":{"message":"The ` + "`content[].thinking`" + ` in the thinking mode must be passed back to the API"}}`, |
| 51 | }) |
| 52 | } |
| 53 | |
| 54 | func reasoningReplaySeededSession() *Session { |
| 55 | session := NewSession("system") |
| 56 | session.Add(provider.Message{Role: provider.RoleUser, Content: "earlier"}) |
| 57 | session.Add(provider.Message{Role: provider.RoleAssistant, Content: "old answer", ReasoningContent: "stale thinking"}) |
| 58 | return session |
| 59 | } |
| 60 | |
| 61 | func TestReasoningReplay400RepairsProjectionAndRetriesOnce(t *testing.T) { |
| 62 | mp := testutil.NewMock("strict-replay", |
| 63 | testutil.ErrorTurn(thinkingReplay400Error()), |
| 64 | testutil.Turn{Text: "done"}, |
| 65 | testutil.Turn{Text: "again done"}, |
| 66 | ) |
| 67 | sink := &recordSink{} |
| 68 | session := reasoningReplaySeededSession() |
| 69 | a := New(strictAssistantReasoningProvider{mp}, echoRegistry(), session, Options{}, sink) |
| 70 | |
| 71 | if err := a.Run(withNoClosedLoop(context.Background()), "next"); err != nil { |
| 72 | t.Fatalf("Run: %v", err) |
| 73 | } |
| 74 | if got := mp.CallCount(); got != 2 { |
| 75 | t.Fatalf("provider calls = %d, want rejected attempt plus one repair retry", got) |
| 76 | } |
| 77 | requests := mp.Requests() |
| 78 | var firstReasoning, secondReasoning int |
| 79 | for _, m := range requests[0].Messages { |
| 80 | if m.ReasoningContent != "" { |
| 81 | firstReasoning++ |
| 82 | } |
| 83 | } |
| 84 | for _, m := range requests[1].Messages { |
| 85 | if m.ReasoningContent != "" { |
| 86 | secondReasoning++ |
| 87 | } |
| 88 | } |
| 89 | if firstReasoning != 1 || secondReasoning != 0 { |
| 90 | t.Fatalf("reasoning in attempts = %d then %d, want the repair retry stripped", firstReasoning, secondReasoning) |
| 91 | } |
| 92 | // The frozen request may change only in Messages; everything else is |
| 93 | // byte-identical to the rejected attempt. |
| 94 | strippedTools := requests[1] |
| 95 | strippedTools.Messages = requests[0].Messages |
| 96 | if !reflect.DeepEqual(requests[0], strippedTools) { |
| 97 | t.Fatalf("repair retry changed more than Messages:\nfirst=%+v\nretry=%+v", requests[0], requests[1]) |
| 98 | } |
| 99 | // Canonical history is never modified by the provider-visible projection. |
| 100 | for _, m := range session.Snapshot() { |
| 101 | if m.Role == provider.RoleAssistant && m.Content == "old answer" && m.ReasoningContent != "stale thinking" { |
| 102 | t.Fatalf("canonical history lost its reasoning: %+v", m) |
| 103 | } |
| 104 | } |
| 105 | if got := sink.recoveryCount(event.ProtocolRecoveryReasoningReplay400Detected); got != 1 { |
| 106 | t.Fatalf("reasoning_replay_400_detected audits = %d, want 1", got) |
| 107 | } |
| 108 | if got := sink.recoveryCount(event.ProtocolRecoveryReasoningReplay400Recovered); got != 1 { |
| 109 | t.Fatalf("reasoning_replay_400_recovered audits = %d, want 1", got) |
| 110 | } |
| 111 | var repairNotices int |
| 112 | for _, e := range sink.kinds(event.Notice) { |
| 113 | if e.Code == event.NoticeCodeReasoningReplayRepair { |
| 114 | repairNotices++ |
| 115 | if e.Level != event.LevelWarn { |
| 116 | t.Fatalf("repair notice level = %v, want warn", e.Level) |
| 117 | } |
| 118 | } |
| 119 | } |
| 120 | if repairNotices != 1 { |
| 121 | t.Fatalf("repair notices = %d, want 1", repairNotices) |
| 122 | } |
| 123 | |
| 124 | // The strong projection stays active for the rest of the conversation. |
| 125 | if err := a.Run(withNoClosedLoop(context.Background()), "again"); err != nil { |
| 126 | t.Fatalf("second Run: %v", err) |
| 127 | } |
| 128 | if got := mp.CallCount(); got != 3 { |
| 129 | t.Fatalf("provider calls = %d, want no fresh 400 on the next run", got) |
| 130 | } |
| 131 | for _, m := range mp.Requests()[2].Messages { |
| 132 | if m.ReasoningContent != "" { |
| 133 | t.Fatalf("later request still carries reasoning under strong projection: %+v", m) |
| 134 | } |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | func TestReasoningReplay400KeepsNewToolRoundOutsideStrongProjection(t *testing.T) { |
| 139 | call := provider.ToolCall{ID: "fresh", Name: "echo", Arguments: `{"text":"hello"}`} |
| 140 | mp := testutil.NewMock("strict-replay", |
| 141 | testutil.ErrorTurn(thinkingReplay400Error()), |
| 142 | testutil.Turn{Text: "repaired"}, |
| 143 | testutil.Turn{Reasoning: "fresh reasoning", ToolCalls: []provider.ToolCall{call}}, |
| 144 | testutil.Turn{Text: "fresh final"}, |
| 145 | ) |
| 146 | a := New(strictAssistantReasoningProvider{mp}, echoRegistry(), reasoningReplaySeededSession(), Options{}, event.Discard) |
| 147 | if err := a.Run(withNoClosedLoop(context.Background()), "first"); err != nil { |
| 148 | t.Fatalf("first Run: %v", err) |
| 149 | } |
| 150 | if err := a.Run(withNoClosedLoop(context.Background()), "second"); err != nil { |
| 151 | t.Fatalf("second Run: %v", err) |
| 152 | } |
| 153 | |
| 154 | requests := mp.Requests() |
| 155 | if len(requests) != 4 { |
| 156 | t.Fatalf("requests = %d, want repair plus a two-step follow-up", len(requests)) |
| 157 | } |
| 158 | var sawFreshToolRound bool |
| 159 | for _, message := range requests[3].Messages { |
| 160 | if len(message.ToolCalls) > 0 || message.Role == provider.RoleTool { |
| 161 | sawFreshToolRound = true |
| 162 | break |
| 163 | } |
| 164 | } |
| 165 | if !sawFreshToolRound { |
| 166 | t.Fatal("strong projection dropped the new tool round from the follow-up request") |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | func TestReasoningReplay400ProjectsAllStaleToolRoundsBeforeFreshRound(t *testing.T) { |
| 171 | old1 := provider.ToolCall{ID: "old-1", Name: "echo", Arguments: `{"text":"old one"}`} |
| 172 | old2 := provider.ToolCall{ID: "old-2", Name: "echo", Arguments: `{"text":"old two"}`} |
| 173 | old3 := provider.ToolCall{ID: "old-3", Name: "echo", Arguments: `{"text":"old three"}`} |
| 174 | fresh := provider.ToolCall{ID: "fresh", Name: "echo", Arguments: `{"text":"fresh"}`} |
| 175 | mp := testutil.NewMock("strict-replay", |
| 176 | testutil.ErrorTurn(thinkingReplay400Error()), |
| 177 | testutil.Turn{Text: "repaired"}, |
| 178 | testutil.Turn{Reasoning: "fresh reasoning", ToolCalls: []provider.ToolCall{fresh}}, |
| 179 | testutil.Turn{Text: "fresh final"}, |
| 180 | ) |
| 181 | session := NewSession("system") |
| 182 | session.Add(provider.Message{Role: provider.RoleUser, Content: "first"}) |
| 183 | session.Add(provider.Message{Role: provider.RoleAssistant, Content: "old one", ReasoningContent: "stale one", ToolCalls: []provider.ToolCall{old1}}) |
| 184 | session.Add(provider.Message{Role: provider.RoleTool, ToolCallID: old1.ID, Name: old1.Name, Content: "old result one"}) |
| 185 | session.Add(provider.Message{Role: provider.RoleUser, Content: "second"}) |
| 186 | session.Add(provider.Message{Role: provider.RoleAssistant, Content: "old two", ReasoningContent: "stale two", ToolCalls: []provider.ToolCall{old2}}) |
| 187 | session.Add(provider.Message{Role: provider.RoleTool, ToolCallID: old2.ID, Name: old2.Name, Content: "old result two"}) |
| 188 | session.Add(provider.Message{Role: provider.RoleUser, Content: "third"}) |
| 189 | session.Add(provider.Message{Role: provider.RoleAssistant, Content: "old three", ReasoningContent: "stale three", ToolCalls: []provider.ToolCall{old3}}) |
| 190 | session.Add(provider.Message{Role: provider.RoleTool, ToolCallID: old3.ID, Name: old3.Name, Content: "old result three"}) |
| 191 | a := New(strictAssistantReasoningProvider{mp}, echoRegistry(), session, Options{}, event.Discard) |
| 192 | if err := a.Run(withNoClosedLoop(context.Background()), "repair"); err != nil { |
| 193 | t.Fatalf("first Run: %v", err) |
| 194 | } |
| 195 | if err := a.Run(withNoClosedLoop(context.Background()), "fresh"); err != nil { |
| 196 | t.Fatalf("second Run: %v", err) |
| 197 | } |
| 198 | requests := mp.Requests() |
| 199 | if len(requests) != 4 { |
| 200 | t.Fatalf("requests = %d, want repair plus a two-step follow-up", len(requests)) |
| 201 | } |
| 202 | for _, message := range requests[3].Messages { |
| 203 | if message.ReasoningContent == "stale one" || message.ReasoningContent == "stale two" || message.ReasoningContent == "stale three" { |
| 204 | t.Fatalf("stale reasoning survived prefix projection: %+v", message) |
| 205 | } |
| 206 | } |
| 207 | var sawFreshToolRound bool |
| 208 | for _, message := range requests[3].Messages { |
| 209 | if len(message.ToolCalls) > 0 || message.Role == provider.RoleTool { |
| 210 | sawFreshToolRound = true |
| 211 | break |
| 212 | } |
| 213 | } |
| 214 | if !sawFreshToolRound { |
| 215 | t.Fatal("strong projection dropped the fresh tool round") |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | func TestReasoningReplayAnchorMissFallsBackToNormalProjection(t *testing.T) { |
| 220 | call := provider.ToolCall{ID: "stale", Name: "echo", Arguments: `{"text":"old"}`} |
| 221 | session := NewSession("system") |
| 222 | session.Add(provider.Message{Role: provider.RoleUser, Content: "old"}) |
| 223 | session.Add(provider.Message{Role: provider.RoleAssistant, Content: "old answer", ToolCalls: []provider.ToolCall{call}}) |
| 224 | session.Add(provider.Message{Role: provider.RoleTool, ToolCallID: call.ID, Name: call.Name, Content: "old result"}) |
| 225 | a := New(strictAssistantReasoningProvider{testutil.NewMock("strict-replay")}, echoRegistry(), session, Options{}, event.Discard) |
| 226 | a.sess.reasoningReplayStrongProjection = 2 |
| 227 | a.sess.reasoningReplayStrongProjectionAnchor = "anchor no longer present" |
| 228 | |
| 229 | got := a.providerProjectionMessages(modelInputMessages(session.Snapshot())) |
| 230 | if a.sess.reasoningReplayStrongProjection != 0 || a.sess.reasoningReplayStrongProjectionAnchor != "" { |
| 231 | t.Fatalf("stale strong projection survived anchor miss: cutoff=%d anchor=%q", a.sess.reasoningReplayStrongProjection, a.sess.reasoningReplayStrongProjectionAnchor) |
| 232 | } |
| 233 | for _, message := range got { |
| 234 | if len(message.ToolCalls) > 0 || message.Role == provider.RoleTool { |
| 235 | t.Fatalf("normal projection did not remove unreplayable tool history: %+v", got) |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | func TestReasoningReplayProjectionInvalidationClearsOverlay(t *testing.T) { |
| 241 | a := New(nil, echoRegistry(), NewSession("system"), Options{}, event.Discard) |
| 242 | a.sess.reasoningReplayStrongProjection = 7 |
| 243 | a.sess.reasoningReplayStrongProjectionAnchor = "anchor" |
| 244 | |
| 245 | a.InvalidateProjection() |
| 246 | if a.sess.reasoningReplayStrongProjection != 0 || a.sess.reasoningReplayStrongProjectionAnchor != "" { |
| 247 | t.Fatalf("projection invalidation retained repair overlay: cutoff=%d anchor=%q", a.sess.reasoningReplayStrongProjection, a.sess.reasoningReplayStrongProjectionAnchor) |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | func TestReasoningReplay400RepairExhaustionStaysTerminal(t *testing.T) { |
| 252 | mp := testutil.NewMock("strict-replay", |
| 253 | testutil.ErrorTurn(thinkingReplay400Error()), |
| 254 | testutil.ErrorTurn(thinkingReplay400Error()), |
| 255 | testutil.Turn{Text: "unreachable"}, |
| 256 | ) |
| 257 | sink := &recordSink{} |
| 258 | a := New(strictAssistantReasoningProvider{mp}, echoRegistry(), reasoningReplaySeededSession(), Options{}, sink) |
| 259 | |
| 260 | err := a.Run(withNoClosedLoop(context.Background()), "next") |
| 261 | var replayErr *provider.ReasoningReplayError |
| 262 | if !errors.As(err, &replayErr) { |
| 263 | t.Fatalf("Run error = %v, want ReasoningReplayError", err) |
| 264 | } |
| 265 | if got := mp.CallCount(); got != 2 { |
| 266 | t.Fatalf("provider calls = %d, want exactly one repair retry", got) |
| 267 | } |
| 268 | if got := sink.recoveryCount(event.ProtocolRecoveryReasoningReplay400Detected); got != 1 { |
| 269 | t.Fatalf("reasoning_replay_400_detected audits = %d, want 1", got) |
| 270 | } |
| 271 | if got := sink.recoveryCount(event.ProtocolRecoveryReasoningReplay400Recovered); got != 0 { |
| 272 | t.Fatalf("reasoning_replay_400_recovered audits = %d, want 0 after a failed repair", got) |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | func TestNonReplay400DoesNotTriggerReasoningRepair(t *testing.T) { |
| 277 | mp := testutil.NewMock("strict-replay", |
| 278 | testutil.ErrorTurn(&provider.APIError{Provider: "strict-replay", Status: 400, Body: `{"error":{"message":"invalid request: unknown tool"}}`}), |
| 279 | testutil.Turn{Text: "unreachable"}, |
| 280 | ) |
| 281 | sink := &recordSink{} |
| 282 | a := New(strictAssistantReasoningProvider{mp}, echoRegistry(), reasoningReplaySeededSession(), Options{}, sink) |
| 283 | |
| 284 | err := a.Run(withNoClosedLoop(context.Background()), "next") |
| 285 | var apiErr *provider.APIError |
| 286 | if !errors.As(err, &apiErr) { |
| 287 | t.Fatalf("Run error = %v, want the raw APIError", err) |
| 288 | } |
| 289 | if replayErr := provider.AsReasoningReplayError(err); replayErr != nil { |
| 290 | t.Fatalf("unrelated 400 misclassified as reasoning replay: %v", replayErr) |
| 291 | } |
| 292 | if got := mp.CallCount(); got != 1 { |
| 293 | t.Fatalf("provider calls = %d, want no retry for an unrelated 400", got) |
| 294 | } |
| 295 | if got := sink.recoveryCount(event.ProtocolRecoveryReasoningReplay400Detected); got != 0 { |
| 296 | t.Fatalf("reasoning_replay_400_detected audits = %d, want 0", got) |
| 297 | } |
| 298 | } |
| 299 |