| 1 | //go:build live |
| 2 | |
| 3 | package boot |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "net/http/httptrace" |
| 11 | "os" |
| 12 | "strings" |
| 13 | "sync" |
| 14 | "testing" |
| 15 | "time" |
| 16 | |
| 17 | "reasonix/internal/config" |
| 18 | "reasonix/internal/provider" |
| 19 | ) |
| 20 | |
| 21 | // Opt-in, synthetic coding traffic only: eight logical inference requests, |
| 22 | // each capped at 768 output tokens/60 seconds, plus shared-model discovery. |
| 23 | // No credentials or generated text are logged. |
| 24 | func TestLiveOpenCodeGoInferenceV41(t *testing.T) { |
| 25 | runLiveOpenCodeGoInferenceV41(t, false) |
| 26 | } |
| 27 | |
| 28 | // A focused rerun keeps one conversation in memory through three dependent |
| 29 | // requests, with at most five explicit 503-only probe retries shared across it. |
| 30 | // This is test orchestration, not a change to the production retry policy. |
| 31 | func TestLiveOpenCodeGoInferenceV41ToolReplay(t *testing.T) { |
| 32 | runLiveOpenCodeGoInferenceV41(t, true) |
| 33 | } |
| 34 | |
| 35 | func runLiveOpenCodeGoInferenceV41(t *testing.T, replayOnly bool) { |
| 36 | key := os.Getenv("OPENCODE_GO_API_KEY") |
| 37 | if key == "" { |
| 38 | t.Skip("OPENCODE_GO_API_KEY is required") |
| 39 | } |
| 40 | t.Setenv("REASONIX_HOME", t.TempDir()) |
| 41 | requests, input, output, cache := 0, 0, 0, 0 |
| 42 | t.Cleanup(func() { |
| 43 | t.Logf("requests=%d input_tokens=%d output_tokens=%d cached_input_tokens=%d", requests, input, output, cache) |
| 44 | }) |
| 45 | newModel := func(kind, base, model string) provider.Provider { |
| 46 | e := config.ProviderEntry{Name: "opencode-go-live", Kind: kind, BaseURL: base, Model: model, APIKeyEnv: "OPENCODE_GO_API_KEY", MaxOutputTokens: 768, ResponsesMode: "stateless"} |
| 47 | e.ResolveAPIKeyFromProcessEnvForProbe() |
| 48 | p, err := NewProvider(&e) |
| 49 | if err != nil { |
| 50 | t.Fatal(strings.ReplaceAll(err.Error(), key, "[redacted]")) |
| 51 | } |
| 52 | if kind == "openai" { |
| 53 | resolved := config.ResolveReasoningEntry(&e) |
| 54 | if config.ReasoningProtocolForEntry(resolved) != "deepseek" || config.ReasoningCapabilityForEntry(resolved).Default != "high" || !provider.RequiresToolCallReasoning(p) { |
| 55 | t.Fatal("boot factory lost the automatic DeepSeek reasoning/replay contract") |
| 56 | } |
| 57 | } |
| 58 | if closer, ok := p.(interface{ CloseIdleConnections() }); ok { |
| 59 | t.Cleanup(closer.CloseIdleConnections) |
| 60 | } |
| 61 | return p |
| 62 | } |
| 63 | sessions := map[string]string{} |
| 64 | probeSession := provider.NewCacheSessionID() |
| 65 | probeRetries := 0 |
| 66 | if replayOnly { |
| 67 | probeRetries = 5 |
| 68 | } |
| 69 | var collect func(string, provider.Provider, provider.Request) provider.Message |
| 70 | collect = func(label string, p provider.Provider, req provider.Request) provider.Message { |
| 71 | t.Helper() |
| 72 | requests++ |
| 73 | if requests > 8 { |
| 74 | t.Fatal("logical request budget exceeded") |
| 75 | } |
| 76 | req.MaxTokens = 768 |
| 77 | ctx, cancel := context.WithTimeout(t.Context(), 60*time.Second) |
| 78 | defer cancel() |
| 79 | conversation := label |
| 80 | if strings.HasPrefix(label, "new-default-") { |
| 81 | conversation = "default-tool-history" |
| 82 | } |
| 83 | identity := probeSession + "/" + conversation |
| 84 | // An explicit synthetic identity permits an affinity-control probe. |
| 85 | // Never use a real user's conversation identity in this live fixture. |
| 86 | if pinned := os.Getenv("REASONIX_OPENCODE_LIVE_SESSION"); pinned != "" { |
| 87 | identity = pinned |
| 88 | } |
| 89 | ctx = provider.WithIndependentRequestAttemptCounter(provider.WithCacheSession(ctx, identity)) |
| 90 | var mu sync.Mutex |
| 91 | var status int |
| 92 | var path, session, userAgent string |
| 93 | ctx = provider.WithRequestObserver(ctx, func(o provider.RequestObservation) { |
| 94 | mu.Lock() |
| 95 | defer mu.Unlock() |
| 96 | if o.Status != 0 { |
| 97 | status = o.Status |
| 98 | } |
| 99 | if o.RequestPath != "" { |
| 100 | path = o.RequestPath |
| 101 | } |
| 102 | }) |
| 103 | ctx = httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{WroteHeaderField: func(name string, values []string) { |
| 104 | mu.Lock() |
| 105 | defer mu.Unlock() |
| 106 | if len(values) == 0 { |
| 107 | return |
| 108 | } |
| 109 | switch strings.ToLower(name) { |
| 110 | case "x-opencode-session": |
| 111 | session = values[0] |
| 112 | case "user-agent": |
| 113 | userAgent = values[0] |
| 114 | } |
| 115 | }}) |
| 116 | start := time.Now() |
| 117 | ch, err := p.Stream(ctx, req) |
| 118 | message := provider.Message{Role: provider.RoleAssistant} |
| 119 | var usage provider.Usage |
| 120 | if err == nil { |
| 121 | for chunk := range ch { |
| 122 | switch chunk.Type { |
| 123 | case provider.ChunkText: |
| 124 | message.Content += chunk.Text |
| 125 | case provider.ChunkReasoning: |
| 126 | message.ReasoningContent += chunk.Text |
| 127 | case provider.ChunkToolCall: |
| 128 | if chunk.ToolCall != nil { |
| 129 | message.ToolCalls = append(message.ToolCalls, *chunk.ToolCall) |
| 130 | } |
| 131 | case provider.ChunkUsage: |
| 132 | if chunk.Usage != nil { |
| 133 | usage = *chunk.Usage |
| 134 | } |
| 135 | case provider.ChunkError: |
| 136 | if chunk.Err != nil { |
| 137 | err = chunk.Err |
| 138 | } |
| 139 | } |
| 140 | } |
| 141 | } |
| 142 | mu.Lock() |
| 143 | gotStatus, gotPath, gotSession, gotAgent := status, path, session, userAgent |
| 144 | mu.Unlock() |
| 145 | input += usage.PromptTokens |
| 146 | output += usage.CompletionTokens |
| 147 | cache += usage.CacheHitTokens |
| 148 | t.Logf("case=%s status=%d path=%s elapsed=%s attempts=%d input=%d output=%d cache=%d text_bytes=%d reasoning_bytes=%d tools=%d session_header=%t client_header=%t", label, gotStatus, gotPath, time.Since(start).Round(time.Millisecond), provider.RequestAttemptCount(ctx), usage.PromptTokens, usage.CompletionTokens, usage.CacheHitTokens, len(message.Content), len(message.ReasoningContent), len(message.ToolCalls), gotSession != "", gotAgent != "") |
| 149 | if err != nil { |
| 150 | detail := err.Error() |
| 151 | var api *provider.APIError |
| 152 | if errors.As(err, &api) { |
| 153 | detail = fmt.Sprintf("HTTP %d: %s", api.Status, api.Body) |
| 154 | } |
| 155 | detail = strings.ReplaceAll(detail, key, "[redacted]") |
| 156 | if len(detail) > 1024 { |
| 157 | detail = detail[:1024] |
| 158 | } |
| 159 | if replayOnly && gotStatus == 503 && probeRetries > 0 { |
| 160 | probeRetries-- |
| 161 | t.Logf("explicit_probe_retry case=%s remaining=%d delay=10s error=%s", label, probeRetries, detail) |
| 162 | timer := time.NewTimer(10 * time.Second) |
| 163 | defer timer.Stop() |
| 164 | select { |
| 165 | case <-t.Context().Done(): |
| 166 | t.Fatal(t.Context().Err()) |
| 167 | case <-timer.C: |
| 168 | } |
| 169 | return collect(label, p, req) |
| 170 | } |
| 171 | if gotStatus == 401 || gotStatus == 403 { |
| 172 | t.Fatal(detail) |
| 173 | } |
| 174 | t.Error(detail) |
| 175 | return message |
| 176 | } |
| 177 | if gotStatus != 200 || gotSession == "" || gotAgent != "Reasonix" { |
| 178 | t.Fatal("missing successful HTTP response or Go client/session identity") |
| 179 | } |
| 180 | if old := sessions[conversation]; old != "" && old != gotSession { |
| 181 | t.Fatal("conversation session header changed") |
| 182 | } |
| 183 | sessions[conversation] = gotSession |
| 184 | if usage.PromptTokens == 0 || usage.CompletionTokens == 0 { |
| 185 | t.Fatal("missing usage accounting") |
| 186 | } |
| 187 | if message.Content == "" && len(message.ToolCalls) == 0 { |
| 188 | t.Fatal("no deliverable response within output cap") |
| 189 | } |
| 190 | return message |
| 191 | } |
| 192 | chat := newModel("openai", provider.OpenCodeGoChatBaseURL, "deepseek-v4.1-flash") |
| 193 | smoke := provider.Request{Messages: []provider.Message{{Role: provider.RoleSystem, Content: "You are Reasonix, a coding assistant running a small integration test. Follow instructions briefly."}, {Role: provider.RoleUser, Content: "Reply with only OK."}}, EffortOverride: "disabled"} |
| 194 | if !replayOnly { |
| 195 | collect("new-disabled", chat, smoke) |
| 196 | } |
| 197 | tools := []provider.ToolSchema{{Name: "get_marker", Description: "Return the synthetic coding integration marker. Call exactly once when requested.", Parameters: json.RawMessage(`{"type":"object","properties":{},"additionalProperties":false}`)}} |
| 198 | messages := []provider.Message{{Role: provider.RoleSystem, Content: "You are Reasonix, a coding assistant. Call get_marker exactly once when asked. After a tool result, reply with only the returned marker. Never call it again unless asked."}, {Role: provider.RoleUser, Content: "Call get_marker now."}} |
| 199 | first := collect("new-default-tool", chat, provider.Request{Messages: messages, Tools: tools}) |
| 200 | if len(first.ToolCalls) != 1 || first.ToolCalls[0].Name != "get_marker" { |
| 201 | t.Error("missing requested tool call") |
| 202 | } else { |
| 203 | messages = append(messages, first, provider.Message{Role: provider.RoleTool, ToolCallID: first.ToolCalls[0].ID, Name: "get_marker", Content: "reasonix-v41-protocol-ok"}) |
| 204 | second := collect("new-default-tool-result", chat, provider.Request{Messages: messages, Tools: tools}) |
| 205 | if !strings.Contains(second.Content, "reasonix-v41-protocol-ok") || len(second.ToolCalls) != 0 { |
| 206 | t.Error("tool replay did not preserve result") |
| 207 | } else { |
| 208 | messages = append(messages, second, provider.Message{Role: provider.RoleUser, Content: "Repeat only the previous marker. Do not call any tool."}) |
| 209 | third := collect("new-default-multiturn", chat, provider.Request{Messages: messages, Tools: tools}) |
| 210 | if !strings.Contains(third.Content, "reasonix-v41-protocol-ok") || len(third.ToolCalls) != 0 { |
| 211 | t.Error("multi-turn reasoning/history replay failed") |
| 212 | } |
| 213 | } |
| 214 | } |
| 215 | if replayOnly { |
| 216 | return |
| 217 | } |
| 218 | for _, effort := range []string{"low", "max"} { |
| 219 | smoke.EffortOverride = effort |
| 220 | collect("new-"+effort, chat, smoke) |
| 221 | } |
| 222 | legacy := newModel("openai", "https://opencode.ai/zen/go/v1", "deepseek-v4.1-flash") |
| 223 | smoke.EffortOverride = "disabled" |
| 224 | collect("legacy-disabled", legacy, smoke) |
| 225 | // The second documented protocol family shares the same migrated Go key. |
| 226 | anthropic := newModel("anthropic", provider.OpenCodeGoAnthropicBaseURL, "qwen3.7-plus") |
| 227 | smoke.EffortOverride = "" |
| 228 | collect("new-anthropic", anthropic, smoke) |
| 229 | entry := config.ProviderEntry{Name: "opencode-go-live", Kind: "openai", BaseURL: provider.OpenCodeGoChatBaseURL, APIKeyEnv: "OPENCODE_GO_API_KEY"} |
| 230 | entry.ResolveAPIKeyFromProcessEnvForProbe() |
| 231 | ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) |
| 232 | defer cancel() |
| 233 | models, err := entry.FetchModelCatalog(ctx) |
| 234 | if err != nil { |
| 235 | t.Error(strings.ReplaceAll(err.Error(), key, "[redacted]")) |
| 236 | return |
| 237 | } |
| 238 | found := false |
| 239 | for _, model := range models { |
| 240 | if model.ID == "deepseek-v4.1-flash" { |
| 241 | found = true |
| 242 | t.Logf("discovery_v41=true image_input=%t context=%d max_output=%d", model.SupportsInput(provider.ModalityImage), model.ContextWindow, model.MaxOutputTokens) |
| 243 | } |
| 244 | } |
| 245 | t.Logf("discovered_chat_models=%d", len(models)) |
| 246 | if !found { |
| 247 | t.Error("V4.1 Flash missing from shared-model discovery") |
| 248 | } |
| 249 | } |
| 250 |