| 1 | //go:build live |
| 2 | |
| 3 | package agent |
| 4 | |
| 5 | import ( |
| 6 | "bytes" |
| 7 | "context" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "io" |
| 11 | "net/http" |
| 12 | "net/http/httptest" |
| 13 | "os" |
| 14 | "strings" |
| 15 | "sync" |
| 16 | "sync/atomic" |
| 17 | "testing" |
| 18 | "time" |
| 19 | |
| 20 | "reasonix/internal/event" |
| 21 | "reasonix/internal/provider" |
| 22 | "reasonix/internal/provider/anthropic" |
| 23 | "reasonix/internal/provider/openai" |
| 24 | "reasonix/internal/provider/responses" |
| 25 | "reasonix/internal/tool" |
| 26 | ) |
| 27 | |
| 28 | // Only synthetic echo is exposed: no shell, filesystem reader, MCP, or access |
| 29 | // to credentials. Faults affect real completed upstream streams locally, not |
| 30 | // the public service. Raw requests/responses remain in memory. |
| 31 | func TestLiveOfficialRecoveryMatrix(t *testing.T) { |
| 32 | key := os.Getenv("DEEPSEEK_API_KEY") |
| 33 | if key == "" { |
| 34 | t.Skip("DEEPSEEK_API_KEY not set") |
| 35 | } |
| 36 | for _, model := range []string{"deepseek-v4-flash", "deepseek-v4-pro"} { |
| 37 | for _, protocol := range []string{"chat", "responses", "anthropic"} { |
| 38 | for _, scenario := range []string{"low", "max", "disabled", "cut_once", "missing_once", "missing_persistent", "followup_503", "server_replay_rejection", "cancel_before_commit"} { |
| 39 | t.Run(model+"/"+protocol+"/"+scenario, func(t *testing.T) { |
| 40 | ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second) |
| 41 | defer cancel() |
| 42 | proxy := &officialRecoveryProxy{protocol: protocol, scenario: scenario, cancel: cancel} |
| 43 | srv := httptest.NewServer(proxy) |
| 44 | defer srv.Close() |
| 45 | effort := "high" |
| 46 | if scenario == "low" || scenario == "max" || scenario == "disabled" { |
| 47 | effort = scenario |
| 48 | } |
| 49 | p := officialMatrixProvider(t, key, model, protocol, effort, srv.URL) |
| 50 | var executions atomic.Int32 |
| 51 | reg := tool.NewRegistry() |
| 52 | reg.Add(liveRecoveryEchoTool{executions: &executions}) |
| 53 | sink := &recordSink{} |
| 54 | session := NewSession("You are a concise tool-using assistant. Call echo exactly once when asked, then report the marker. Do not repeat a completed tool.") |
| 55 | a := New(p, reg, session, Options{MaxSteps: 4, MaxOutputTokens: 2048, MissingReasoningWarnStateDir: t.TempDir()}, sink) |
| 56 | start := time.Now() |
| 57 | err := a.Run(ctx, "Call echo exactly once, then report its result.") |
| 58 | wantRequests, wantExecutions := 2, int32(1) |
| 59 | switch scenario { |
| 60 | case "cut_once", "followup_503", "server_replay_rejection": |
| 61 | wantRequests = 3 |
| 62 | case "missing_once": |
| 63 | if protocol == "anthropic" { |
| 64 | wantRequests = 3 |
| 65 | } |
| 66 | case "missing_persistent": |
| 67 | if protocol == "anthropic" { |
| 68 | wantExecutions = 0 |
| 69 | if err == nil { |
| 70 | t.Fatal("strict missing proof accepted") |
| 71 | } |
| 72 | } |
| 73 | case "cancel_before_commit": |
| 74 | wantRequests, wantExecutions = 1, 0 |
| 75 | if !errors.Is(err, context.Canceled) { |
| 76 | t.Fatalf("cancellation error=%v", err) |
| 77 | } |
| 78 | } |
| 79 | stopped := scenario == "cancel_before_commit" || scenario == "missing_persistent" && protocol == "anthropic" |
| 80 | if !stopped && err != nil { |
| 81 | t.Fatalf("live run: %v", err) |
| 82 | } |
| 83 | if scenario == "server_replay_rejection" && err == nil { |
| 84 | t.Logf("before_continuation_tool_executions=%d", executions.Load()) |
| 85 | if err := a.Run(ctx, "Without calling tools, report the already known marker from the completed request."); err != nil { |
| 86 | t.Fatalf("post-repair continuation: %v", err) |
| 87 | } |
| 88 | wantRequests = 4 |
| 89 | } |
| 90 | proxy.mu.Lock() |
| 91 | requests, upstream, mutations := proxy.requests, proxy.upstream, proxy.mutations |
| 92 | frozen := len(proxy.bodies) > 1 && bytes.Equal(proxy.bodies[0], proxy.bodies[1]) |
| 93 | proxy.mu.Unlock() |
| 94 | if requests != wantRequests || executions.Load() != wantExecutions { |
| 95 | t.Fatalf("requests=%d executions=%d want=%d/%d err=%v", requests, executions.Load(), wantRequests, wantExecutions, err) |
| 96 | } |
| 97 | if strings.HasPrefix(scenario, "missing") || scenario == "cut_once" { |
| 98 | if mutations == 0 { |
| 99 | t.Fatal("requested fault was not injected") |
| 100 | } |
| 101 | } |
| 102 | if scenario == "cut_once" && !frozen { |
| 103 | t.Fatal("stream retry did not reuse frozen request") |
| 104 | } |
| 105 | if !stopped { |
| 106 | msgs := session.Snapshot() |
| 107 | if len(msgs) == 0 || strings.TrimSpace(msgs[len(msgs)-1].Content) == "" { |
| 108 | t.Fatal("no final text") |
| 109 | } |
| 110 | } |
| 111 | prompt, completion, accounted, unknown := 0, 0, 0, false |
| 112 | for _, e := range sink.kinds(event.Usage) { |
| 113 | if u := e.Usage; u != nil { |
| 114 | prompt += u.PromptTokens |
| 115 | completion += u.CompletionTokens |
| 116 | accounted += u.RequestCount |
| 117 | unknown = unknown || u.Unknown |
| 118 | } |
| 119 | } |
| 120 | if (scenario == "cut_once" || scenario == "cancel_before_commit" || scenario == "followup_503" || scenario == "server_replay_rejection") && !unknown { |
| 121 | t.Fatal("missing terminal usage must stay unknown") |
| 122 | } |
| 123 | if accounted != requests { |
| 124 | t.Fatalf("accounted=%d HTTP=%d", accounted, requests) |
| 125 | } |
| 126 | t.Logf("protocol=%s scenario=%s http_attempts=%d upstream_requests=%d mutations=%d tool_executions=%d retry_events=%d prompt=%d completion=%d accounted_requests=%d usage_unknown=%t elapsed_ms=%d", protocol, scenario, requests, upstream, mutations, executions.Load(), len(sink.kinds(event.Retrying)), prompt, completion, accounted, unknown, time.Since(start).Milliseconds()) |
| 127 | }) |
| 128 | } |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | func officialMatrixProvider(t *testing.T, key, model, protocol, effort, url string) provider.Provider { |
| 134 | t.Helper() |
| 135 | extra := map[string]any{"api_key_env": "DEEPSEEK_API_KEY", "request_url": url, "reasoning_protocol": "deepseek", "thinking": "enabled", "effort": effort, "reject_redirects": true} |
| 136 | if effort == "disabled" { |
| 137 | extra["thinking"] = "disabled" |
| 138 | } |
| 139 | var p provider.Provider |
| 140 | var err error |
| 141 | switch protocol { |
| 142 | case "chat": |
| 143 | p, err = openai.New(provider.Config{Name: "official-live-chat", BaseURL: "https://api.deepseek.com", Model: model, APIKey: key, Extra: extra}) |
| 144 | case "anthropic": |
| 145 | p, err = anthropic.New(provider.Config{Name: "official-live-anthropic", BaseURL: "https://api.deepseek.com/anthropic", Model: model, APIKey: key, Extra: extra}) |
| 146 | case "responses": |
| 147 | p = responses.New(responses.Config{Name: "official-live-responses", BaseURL: "https://api.deepseek.com", RequestURL: url, Model: model, APIKey: key, KeyEnv: "DEEPSEEK_API_KEY", Effort: effort, Mode: "stateless", MaxOutputTokens: 2048}) |
| 148 | default: |
| 149 | t.Fatal("unsupported test protocol") |
| 150 | } |
| 151 | if err != nil { |
| 152 | t.Fatal(err) |
| 153 | } |
| 154 | if c, ok := p.(interface{ CloseIdleConnections() }); ok { |
| 155 | t.Cleanup(c.CloseIdleConnections) |
| 156 | } |
| 157 | return p |
| 158 | } |
| 159 | |
| 160 | type officialRecoveryProxy struct { |
| 161 | mu sync.Mutex |
| 162 | protocol, scenario string |
| 163 | upstreamURL, sessionHeader string |
| 164 | statuses []int |
| 165 | wireTools, wireStops []string |
| 166 | requests, upstream, mutations int |
| 167 | bodies [][]byte |
| 168 | searchResponses [][]byte |
| 169 | cancel context.CancelFunc |
| 170 | } |
| 171 | |
| 172 | func (p *officialRecoveryProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 173 | body, err := io.ReadAll(r.Body) |
| 174 | if err != nil { |
| 175 | http.Error(w, "read test request", 400) |
| 176 | return |
| 177 | } |
| 178 | p.mu.Lock() |
| 179 | p.requests++ |
| 180 | n := p.requests |
| 181 | p.bodies = append(p.bodies, body) |
| 182 | p.mu.Unlock() |
| 183 | if n > 16 || n > 5 && p.scenario != "continuity" { |
| 184 | http.Error(w, "live test request limit", 401) |
| 185 | return |
| 186 | } |
| 187 | if p.scenario == "followup_503" && n == 2 { |
| 188 | w.WriteHeader(503) |
| 189 | _, _ = io.WriteString(w, `{"error":{"message":"injected temporary service failure"}}`) |
| 190 | return |
| 191 | } |
| 192 | // Drop proof and replace the call identity only in the outbound request. |
| 193 | // This forces the official service to validate unavailable replay content, |
| 194 | // while the canonical local transcript still retains the completed tool. |
| 195 | if p.scenario == "server_replay_rejection" && n == 2 { |
| 196 | body = breakOfficialReplay(p.protocol, body) |
| 197 | } |
| 198 | path := map[string]string{"chat": "/chat/completions", "responses": "/responses", "anthropic": "/anthropic/v1/messages"}[p.protocol] |
| 199 | target := p.upstreamURL |
| 200 | if target == "" { |
| 201 | target = "https://api.deepseek.com" + path |
| 202 | } |
| 203 | req, err := http.NewRequestWithContext(r.Context(), http.MethodPost, target, bytes.NewReader(body)) |
| 204 | if err != nil { |
| 205 | http.Error(w, "create upstream", 500) |
| 206 | return |
| 207 | } |
| 208 | for _, name := range []string{"Authorization", "x-api-key", "anthropic-version", "Content-Type", "User-Agent", "x-opencode-session"} { |
| 209 | if v := r.Header.Get(name); v != "" { |
| 210 | req.Header.Set(name, v) |
| 211 | } |
| 212 | } |
| 213 | if p.sessionHeader != "" { |
| 214 | req.Header.Set("User-Agent", "Reasonix/live-validation") |
| 215 | req.Header.Set("x-opencode-session", p.sessionHeader) |
| 216 | } |
| 217 | client := &http.Client{Timeout: 90 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| 218 | p.mu.Lock() |
| 219 | p.upstream++ |
| 220 | p.mu.Unlock() |
| 221 | resp, err := client.Do(req) |
| 222 | if err != nil { |
| 223 | http.Error(w, "upstream failed", 502) |
| 224 | return |
| 225 | } |
| 226 | defer resp.Body.Close() |
| 227 | p.mu.Lock() |
| 228 | p.statuses = append(p.statuses, resp.StatusCode) |
| 229 | p.mu.Unlock() |
| 230 | data, err := io.ReadAll(resp.Body) |
| 231 | if err != nil { |
| 232 | http.Error(w, "upstream read failed", 502) |
| 233 | return |
| 234 | } |
| 235 | if p.scenario == "search" { |
| 236 | p.mu.Lock() |
| 237 | p.searchResponses = append(p.searchResponses, bytes.Clone(data)) |
| 238 | p.mu.Unlock() |
| 239 | } |
| 240 | if p.protocol == "chat" && resp.StatusCode == 200 { |
| 241 | var names, stops []string |
| 242 | for _, line := range bytes.Split(data, []byte("\n")) { |
| 243 | if !bytes.HasPrefix(line, []byte("data:")) { |
| 244 | continue |
| 245 | } |
| 246 | var frame struct { |
| 247 | Choices []struct { |
| 248 | FinishReason string `json:"finish_reason"` |
| 249 | Delta struct { |
| 250 | ToolCalls []struct { |
| 251 | Function struct { |
| 252 | Name string `json:"name"` |
| 253 | } `json:"function"` |
| 254 | } `json:"tool_calls"` |
| 255 | } `json:"delta"` |
| 256 | } `json:"choices"` |
| 257 | } |
| 258 | if json.Unmarshal(bytes.TrimSpace(bytes.TrimPrefix(line, []byte("data:"))), &frame) != nil { |
| 259 | continue |
| 260 | } |
| 261 | for _, choice := range frame.Choices { |
| 262 | if choice.FinishReason != "" { |
| 263 | stops = append(stops, choice.FinishReason) |
| 264 | } |
| 265 | for _, call := range choice.Delta.ToolCalls { |
| 266 | if call.Function.Name != "" { |
| 267 | names = append(names, call.Function.Name) |
| 268 | } |
| 269 | } |
| 270 | } |
| 271 | } |
| 272 | p.mu.Lock() |
| 273 | p.wireTools = append(p.wireTools, names...) |
| 274 | p.wireStops = append(p.wireStops, stops...) |
| 275 | p.mu.Unlock() |
| 276 | } |
| 277 | if resp.StatusCode == 200 { |
| 278 | if p.scenario == "cancel_before_commit" && n == 1 { |
| 279 | p.cancel() |
| 280 | } |
| 281 | if p.scenario == "cut_once" && n == 1 { |
| 282 | data = data[:len(data)/2] |
| 283 | p.mu.Lock() |
| 284 | p.mutations++ |
| 285 | p.mu.Unlock() |
| 286 | } |
| 287 | if strings.HasPrefix(p.scenario, "missing") && (n == 1 || p.scenario == "missing_persistent") { |
| 288 | switch p.protocol { |
| 289 | case "chat": |
| 290 | s := &liveReasoningStripProxy{} |
| 291 | data = s.stripReasoning(data) |
| 292 | p.mu.Lock() |
| 293 | p.mutations += int(s.strippedFields.Load()) |
| 294 | p.mu.Unlock() |
| 295 | case "responses": |
| 296 | var count int |
| 297 | data, count = stripResponsesReasoningEvents(data) |
| 298 | p.mu.Lock() |
| 299 | p.mutations += count |
| 300 | p.mu.Unlock() |
| 301 | case "anthropic": |
| 302 | var count int |
| 303 | data, count = stripOfficialThinking(data) |
| 304 | p.mu.Lock() |
| 305 | p.mutations += count |
| 306 | p.mu.Unlock() |
| 307 | } |
| 308 | } |
| 309 | } |
| 310 | w.Header().Set("Content-Type", resp.Header.Get("Content-Type")) |
| 311 | w.WriteHeader(resp.StatusCode) |
| 312 | _, _ = w.Write(data) |
| 313 | } |
| 314 | func stripOfficialThinking(data []byte) ([]byte, int) { |
| 315 | var out bytes.Buffer |
| 316 | count := 0 |
| 317 | thinking := map[int]bool{} |
| 318 | for _, frame := range bytes.Split(data, []byte("\n\n")) { |
| 319 | skip := false |
| 320 | for _, line := range bytes.Split(frame, []byte("\n")) { |
| 321 | if !bytes.HasPrefix(line, []byte("data:")) { |
| 322 | continue |
| 323 | } |
| 324 | var e struct { |
| 325 | Type string `json:"type"` |
| 326 | Index int `json:"index"` |
| 327 | Block struct { |
| 328 | Type string `json:"type"` |
| 329 | } `json:"content_block"` |
| 330 | } |
| 331 | if json.Unmarshal(bytes.TrimSpace(bytes.TrimPrefix(line, []byte("data:"))), &e) != nil { |
| 332 | continue |
| 333 | } |
| 334 | if e.Type == "content_block_start" && e.Block.Type == "thinking" { |
| 335 | thinking[e.Index] = true |
| 336 | } |
| 337 | if strings.HasPrefix(e.Type, "content_block_") && thinking[e.Index] { |
| 338 | skip = true |
| 339 | } |
| 340 | } |
| 341 | if skip { |
| 342 | count++ |
| 343 | continue |
| 344 | } |
| 345 | out.Write(frame) |
| 346 | out.WriteString("\n\n") |
| 347 | } |
| 348 | return out.Bytes(), count |
| 349 | } |
| 350 | |
| 351 | func breakOfficialReplay(protocol string, body []byte) []byte { |
| 352 | var request map[string]any |
| 353 | if json.Unmarshal(body, &request) != nil { |
| 354 | return body |
| 355 | } |
| 356 | const replacement = "call_live_missing_proof" |
| 357 | if protocol == "responses" { |
| 358 | var input []any |
| 359 | for _, v := range request["input"].([]any) { |
| 360 | item := v.(map[string]any) |
| 361 | if item["type"] == "reasoning" { |
| 362 | continue |
| 363 | } |
| 364 | if item["type"] == "function_call" { |
| 365 | item["id"] = "fc_live_missing_proof" |
| 366 | item["call_id"] = replacement |
| 367 | } |
| 368 | if item["type"] == "function_call_output" { |
| 369 | item["call_id"] = replacement |
| 370 | } |
| 371 | input = append(input, item) |
| 372 | } |
| 373 | request["input"] = input |
| 374 | } else { |
| 375 | for _, v := range request["messages"].([]any) { |
| 376 | msg := v.(map[string]any) |
| 377 | if protocol == "chat" { |
| 378 | delete(msg, "reasoning_content") |
| 379 | if calls, ok := msg["tool_calls"].([]any); ok { |
| 380 | for _, c := range calls { |
| 381 | c.(map[string]any)["id"] = replacement |
| 382 | } |
| 383 | } |
| 384 | if msg["role"] == "tool" { |
| 385 | msg["tool_call_id"] = replacement |
| 386 | } |
| 387 | } else if blocks, ok := msg["content"].([]any); ok { |
| 388 | var content []any |
| 389 | for _, v := range blocks { |
| 390 | b := v.(map[string]any) |
| 391 | if b["type"] == "thinking" { |
| 392 | continue |
| 393 | } |
| 394 | if b["type"] == "tool_use" { |
| 395 | b["id"] = replacement |
| 396 | } |
| 397 | if b["type"] == "tool_result" { |
| 398 | b["tool_use_id"] = replacement |
| 399 | } |
| 400 | content = append(content, b) |
| 401 | } |
| 402 | msg["content"] = content |
| 403 | } |
| 404 | } |
| 405 | } |
| 406 | encoded, err := json.Marshal(request) |
| 407 | if err != nil { |
| 408 | return body |
| 409 | } |
| 410 | return encoded |
| 411 | } |
| 412 |