From 1de4c8152dc9fdbe605f809e98da5173d57119ad Mon Sep 17 00:00:00 2001 From: haswysa <1344672204@qq.com> Date: Wed, 26 Aug 2026 06:33:06 +0800 Subject: [PATCH 01/12] fix(gateway): failover account on reasoning recovery failure and strip unportable reasoning In multi-account pools, server-side encrypted compaction blobs and reasoning states can fail to decode when a session drifts across accounts or upstream nodes, causing xAI to return HTTP 400 ("Could not decode the compaction blob"). Previously, isRetryable(400) evaluated to false in the gateway service, treating all 400 responses as non-retryable client errors. When provider reasoning recovery failed on the active account, the gateway immediately propagated the 400 to the client instead of attempting other healthy accounts in the candidate pool. Fixes: 1. Gateway failover: Recognize reasoning_recovery_failed in isRetryableResponse so the gateway excludes the failing account and attempts the next candidate within the request attempt loop. 2. Reasoning recovery: Completely strip all reasoning items and convert compaction items to compatibility boundary messages during downgrade retries. 3. History normalization: Convert unencrypted reasoning items without portable content to developer boundary messages. 4. Error markers: Add compaction decode patterns to reasoningDecodeFailureMarkers. Tested: - Added TestRecoverReasoningDecodeFailureCompactionBlob - Updated TestReasoningWithoutEncryptedContentBecomesBoundary - All backend packages pass (go test ./...) --- .../internal/application/gateway/service.go | 29 +++++++++++- .../cli/responses_codex_tools_test.go | 10 ++-- .../infra/provider/cli/responses_history.go | 30 ++++-------- .../cli/responses_reasoning_recovery.go | 47 ++++++++----------- .../cli/responses_reasoning_recovery_test.go | 38 +++++++++++++-- 5 files changed, 94 insertions(+), 60 deletions(-) diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index e6b99685..bed3e780 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -2092,8 +2092,35 @@ func isRetryable(status int) bool { return status == 402 || status == 403 || status == 429 || status >= 500 } +func isReasoningRecoveryFailedResponse(response *provider.Response) bool { + if response == nil { + return false + } + warnings := response.Header.Get("X-Grok2api-Compatibility-Warnings") + if strings.Contains(warnings, "reasoning_recovery_failed") { + return true + } + if response.Diagnostic != nil { + lower := strings.ToLower(string(response.Diagnostic.Body)) + if strings.Contains(lower, "compaction blob") || + strings.Contains(lower, "encrypted_content") || + strings.Contains(lower, "could not decrypt") || + strings.Contains(lower, "could not decode") || + strings.Contains(lower, "invalid_encrypted_content") { + return true + } + } + return false +} + func isRetryableResponse(response *provider.Response, upstreamProvider accountdomain.Provider) bool { - if response == nil || !isRetryable(response.StatusCode) { + if response == nil { + return false + } + if response.StatusCode == http.StatusBadRequest && isReasoningRecoveryFailedResponse(response) { + return true + } + if !isRetryable(response.StatusCode) { return false } // Account-scoped payment failures must always rotate accounts. diff --git a/backend/internal/infra/provider/cli/responses_codex_tools_test.go b/backend/internal/infra/provider/cli/responses_codex_tools_test.go index 23573302..6c370fc1 100644 --- a/backend/internal/infra/provider/cli/responses_codex_tools_test.go +++ b/backend/internal/infra/provider/cli/responses_codex_tools_test.go @@ -404,7 +404,7 @@ func TestNativeBuildHistoryItemsArePreservedAndSanitized(t *testing.T) { } } -func TestReasoningWithoutEncryptedContentRemainsNative(t *testing.T) { +func TestReasoningWithoutEncryptedContentBecomesBoundary(t *testing.T) { normalized, _, err := normalizeResponsesRequest([]byte(`{ "model":"public","input":[ {"type":"reasoning","id":"rs_1","status":"completed","summary":[{"type":"summary_text","text":"who am I"}],"content":null,"encrypted_content":null,"internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, @@ -421,12 +421,8 @@ func TestReasoningWithoutEncryptedContentRemainsNative(t *testing.T) { } items := request["input"].([]any) first := items[0].(map[string]any) - if first["type"] != "reasoning" || first["status"] != nil || first["encrypted_content"] != nil || first["content"] != nil { - t.Fatalf("reasoning history = %#v", first) - } - summary := first["summary"].([]any)[0].(map[string]any) - if summary["text"] != "who am I" { - t.Fatalf("reasoning summary = %#v", first["summary"]) + if first["type"] != "message" || first["role"] != "developer" { + t.Fatalf("unencrypted reasoning should become boundary, got %#v", first) } if items[1].(map[string]any)["content"] != "hi" { t.Fatalf("assistant history = %#v", items[1]) diff --git a/backend/internal/infra/provider/cli/responses_history.go b/backend/internal/infra/provider/cli/responses_history.go index c5675dec..6de683c0 100644 --- a/backend/internal/infra/provider/cli/responses_history.go +++ b/backend/internal/infra/provider/cli/responses_history.go @@ -259,31 +259,19 @@ func (c *responsesToolCompatibility) normalizeCustomToolCallInput(item map[strin } func sanitizeReasoningInput(item map[string]any) map[string]any { - // 官方 Grok Build 回放 reasoning 时会删除 output-only status,但会保留 - // id、summary、content 和可选 encrypted_content。密文不是回放的前置条件。 - converted := copyNonNullHistoryFields(item, "id", "summary", "content", "encrypted_content") - converted["type"] = "reasoning" - if encrypted, ok := converted["encrypted_content"].(string); ok && strings.TrimSpace(encrypted) != "" { + // Grok Build Responses API 中 type: "reasoning" 严格用于不透明密文回放, + // 上游强制要求携带合法的 encrypted_content。 + // 若缺少 encrypted_content,则降级为 developer 兼容边界消息,杜绝向 Grok 发送裸 reasoning。 + encrypted, ok := item["encrypted_content"].(string) + if ok && strings.TrimSpace(encrypted) != "" { + converted := copyNonNullHistoryFields(item, "id", "summary", "content", "encrypted_content") + converted["type"] = "reasoning" if _, exists := converted["summary"]; !exists { converted["summary"] = []any{} } + return converted } - if !hasPortableReasoningContent(converted) { - return compatibilityBoundaryMessage("A prior model reasoning item was omitted because it has no portable content for Grok Build.") - } - return converted -} - -func hasPortableReasoningContent(item map[string]any) bool { - if encrypted, ok := item["encrypted_content"].(string); ok && strings.TrimSpace(encrypted) != "" { - return true - } - for _, key := range []string{"summary", "content"} { - if values, ok := item[key].([]any); ok && len(values) > 0 { - return true - } - } - return false + return compatibilityBoundaryMessage("A prior model reasoning item was omitted because it has no portable content for Grok Build.") } // sanitizeNativeHistoryInput rebuilds history from native Grok Build InputItem fields diff --git a/backend/internal/infra/provider/cli/responses_reasoning_recovery.go b/backend/internal/infra/provider/cli/responses_reasoning_recovery.go index e0527dce..6fcda885 100644 --- a/backend/internal/infra/provider/cli/responses_reasoning_recovery.go +++ b/backend/internal/infra/provider/cli/responses_reasoning_recovery.go @@ -15,6 +15,11 @@ import ( var reasoningDecodeFailureMarkers = [][]byte{ []byte("could not decode the compaction blob"), []byte("could not decrypt the provided encrypted_content"), + []byte("invalid_encrypted_content"), + []byte("could not be decrypted or parsed"), + []byte("could not decrypt"), + []byte("decode the compaction blob"), + []byte("compaction blob"), } type reasoningRecoveryOutcome struct { @@ -239,9 +244,12 @@ func isReasoningDecodeFailure(body []byte) bool { return false } -// stripReasoningEncryptedContent removes opaque reasoning state while -// preserving any readable summary/content. An encrypted-only reasoning item -// becomes empty after stripping and is removed entirely. +// stripReasoningEncryptedContent removes undecodable opaque reasoning and compaction +// states so Grok Build does not fail on server-side decryption. +// In Grok Build Responses API, type: "reasoning" is exclusively used for opaque encrypted replay; +// sending type: "reasoning" without encrypted_content is rejected by the upstream. +// Any reasoning item (whether it contains encrypted_content or bare summary) is removed, and any +// compaction item is converted to a compatibility boundary message. func stripReasoningEncryptedContent(body []byte) ([]byte, bool) { var payload map[string]any if json.Unmarshal(body, &payload) != nil { @@ -255,23 +263,21 @@ func stripReasoningEncryptedContent(body []byte) ([]byte, bool) { rebuilt := make([]any, 0, len(input)) for _, raw := range input { item, ok := raw.(map[string]any) - if !ok || stringField(item, "type") != "reasoning" { + if !ok { rebuilt = append(rebuilt, raw) continue } - encrypted, ok := item["encrypted_content"].(string) - if !ok || strings.TrimSpace(encrypted) == "" { - rebuilt = append(rebuilt, raw) + itemType := stringField(item, "type") + if itemType == "reasoning" { + changed = true continue } - cleaned := cloneJSONObject(item) - delete(cleaned, "encrypted_content") - delete(cleaned, "id") - delete(cleaned, "status") - changed = true - if hasReadableReasoningContent(cleaned) { - rebuilt = append(rebuilt, cleaned) + if itemType == "compaction" { + changed = true + rebuilt = append(rebuilt, compatibilityBoundaryMessage("A prior compacted context could not be decoded by upstream. Continue from the retained conversation messages.")) + continue } + rebuilt = append(rebuilt, raw) } if !changed { return body, false @@ -284,19 +290,6 @@ func stripReasoningEncryptedContent(body []byte) ([]byte, bool) { return encoded, true } -func hasReadableReasoningContent(item map[string]any) bool { - for _, field := range []string{"summary", "content"} { - parts, _ := item[field].([]any) - for _, raw := range parts { - part, _ := raw.(map[string]any) - if strings.TrimSpace(stringField(part, "text")) != "" { - return true - } - } - } - return false -} - func appendCompatibilityWarning(header http.Header, warning string) { if header == nil || strings.TrimSpace(warning) == "" { return diff --git a/backend/internal/infra/provider/cli/responses_reasoning_recovery_test.go b/backend/internal/infra/provider/cli/responses_reasoning_recovery_test.go index d5580c97..e7cff462 100644 --- a/backend/internal/infra/provider/cli/responses_reasoning_recovery_test.go +++ b/backend/internal/infra/provider/cli/responses_reasoning_recovery_test.go @@ -22,6 +22,7 @@ func TestStripReasoningEncryptedContentPreservesOnlyPortableHistory(t *testing.T {"type":"reasoning","id":"rs_empty","status":"completed","summary":[],"encrypted_content":"opaque-empty"}, {"type":"reasoning","summary":[{"type":"summary_text","text":""}],"encrypted_content":"opaque-blank"}, {"type":"reasoning","id":"rs_summary","status":"completed","summary":[{"type":"summary_text","text":"readable"}],"encrypted_content":"opaque-summary"}, + {"type":"compaction","id":"cmp_1","encrypted_content":"opaque-compaction"}, {"type":"message","role":"assistant","content":"answer","encrypted_content":"message-value"}, {"type":"message","role":"user","content":"continue"} ] @@ -34,15 +35,17 @@ func TestStripReasoningEncryptedContentPreservesOnlyPortableHistory(t *testing.T Input []map[string]any `json:"input"` } if json.Unmarshal(downgraded, &payload) != nil || len(payload.Input) != 3 { - t.Fatalf("downgraded = %s", downgraded) + t.Fatalf("downgraded = %s, len=%d", downgraded, len(payload.Input)) } - reasoning := payload.Input[0] - if reasoning["type"] != "reasoning" || reasoning["id"] != nil || reasoning["status"] != nil || reasoning["encrypted_content"] != nil { - t.Fatalf("reasoning = %#v", reasoning) + if payload.Input[0]["type"] != "message" || payload.Input[0]["role"] != "developer" { + t.Fatalf("compaction boundary item = %#v", payload.Input[0]) } if payload.Input[1]["encrypted_content"] != "message-value" { t.Fatalf("non-reasoning encrypted content changed: %#v", payload.Input[1]) } + if payload.Input[2]["role"] != "user" { + t.Fatalf("user message changed: %#v", payload.Input[2]) + } } func TestRecoverReasoningDecodeFailureRetriesSameUpstreamOnce(t *testing.T) { @@ -466,3 +469,30 @@ type reasoningRecoveryFallbackMarker struct{} func (reasoningRecoveryFallbackMarker) MarkBuildAPIFallback(context.Context, uint64, bool) error { return nil } + +func TestRecoverReasoningDecodeFailureCompactionBlob(t *testing.T) { + adapter, encrypted := newReasoningRecoveryTestAdapter(t) + var calls atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + call := calls.Add(1) + if call == 1 { + return jsonHTTPResponse(request, http.StatusBadRequest, `{"code":"invalid-argument","error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), nil + } + return jsonHTTPResponse(request, http.StatusOK, `{"id":"resp_ok","status":"completed","output":[]}`), nil + }) + + body := []byte(`{"model":"grok-4.6","messages":[{"role":"user","content":"hello"}]}`) + resp, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{ + Credential: account.Credential{ID: 131, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted}, + Method: http.MethodPost, Path: "/responses", Model: "grok-4.6", PromptCacheKey: "session-compaction-test", + NormalizeBody: true, Operation: conversation.OperationChat, Body: body, + }) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected status 200, got %d", resp.StatusCode) + } +} + From 2408b67ddb6e1228979f3d393ee01ac8cb7af3ee Mon Sep 17 00:00:00 2001 From: haswysa <1344672204@qq.com> Date: Wed, 26 Aug 2026 08:05:12 +0800 Subject: [PATCH 02/12] fix(gateway): keep portable reasoning summaries during compaction recovery Same-account recovery now strips ciphertext while rewriting readable summaries as developer messages, continues to session reset when the stripped retry still returns 400, and only rotates accounts after reasoning_recovery_failed. Drop Diagnostic substring matching so unrelated 400s do not scan the account pool. --- .../application/gateway/failure_test.go | 33 +++++++ .../internal/application/gateway/service.go | 13 +-- .../cli/responses_codex_tools_test.go | 8 +- .../infra/provider/cli/responses_history.go | 16 ++-- .../cli/responses_reasoning_recovery.go | 95 +++++++++++++----- .../cli/responses_reasoning_recovery_test.go | 96 +++++++++++++++++-- 6 files changed, 209 insertions(+), 52 deletions(-) diff --git a/backend/internal/application/gateway/failure_test.go b/backend/internal/application/gateway/failure_test.go index 74b6e912..0a384d4f 100644 --- a/backend/internal/application/gateway/failure_test.go +++ b/backend/internal/application/gateway/failure_test.go @@ -243,6 +243,39 @@ func TestHTTPUpstreamFailureLeavesPaymentRecoveryKindToBilling(t *testing.T) { } } +func TestRetryableResponseRotatesOnlyOnReasoningRecoveryFailedWarning(t *testing.T) { + failedHeader := make(http.Header) + failedHeader.Set("X-Grok2API-Compatibility-Warnings", "reasoning_encrypted_content_downgraded,reasoning_recovery_failed") + failed := &provider.Response{ + StatusCode: http.StatusBadRequest, + Header: failedHeader, + Body: io.NopCloser(strings.NewReader(`{"error":"Could not decode the compaction blob"}`)), + } + if !isRetryableResponse(failed, accountdomain.ProviderBuild) { + t.Fatal("reasoning_recovery_failed 400 must rotate accounts") + } + + plain := &provider.Response{ + StatusCode: http.StatusBadRequest, + Header: make(http.Header), + Body: io.NopCloser(strings.NewReader(`{"error":"Could not decode the compaction blob"}`)), + Diagnostic: &provider.DiagnosticResponse{Body: []byte(`{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`)}, + } + if isRetryableResponse(plain, accountdomain.ProviderBuild) { + t.Fatal("plain compaction 400 must not rotate accounts without reasoning_recovery_failed") + } + + unrelated := &provider.Response{ + StatusCode: http.StatusBadRequest, + Header: make(http.Header), + Body: io.NopCloser(strings.NewReader(`{"error":"invalid request history"}`)), + Diagnostic: &provider.DiagnosticResponse{Body: []byte(`{"error":"could not decode request json"}`)}, + } + if isRetryableResponse(unrelated, accountdomain.ProviderBuild) { + t.Fatal("unrelated 400 must not match encrypted_content/decode substrings") + } +} + func TestRetryableResponseHonorsUpstreamRetryVeto(t *testing.T) { response := &provider.Response{ StatusCode: http.StatusInternalServerError, diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index bed3e780..1224b3f2 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -2096,17 +2096,8 @@ func isReasoningRecoveryFailedResponse(response *provider.Response) bool { if response == nil { return false } - warnings := response.Header.Get("X-Grok2api-Compatibility-Warnings") - if strings.Contains(warnings, "reasoning_recovery_failed") { - return true - } - if response.Diagnostic != nil { - lower := strings.ToLower(string(response.Diagnostic.Body)) - if strings.Contains(lower, "compaction blob") || - strings.Contains(lower, "encrypted_content") || - strings.Contains(lower, "could not decrypt") || - strings.Contains(lower, "could not decode") || - strings.Contains(lower, "invalid_encrypted_content") { + for _, value := range strings.Split(response.Header.Get("X-Grok2API-Compatibility-Warnings"), ",") { + if strings.TrimSpace(value) == "reasoning_recovery_failed" { return true } } diff --git a/backend/internal/infra/provider/cli/responses_codex_tools_test.go b/backend/internal/infra/provider/cli/responses_codex_tools_test.go index 6c370fc1..44186ee3 100644 --- a/backend/internal/infra/provider/cli/responses_codex_tools_test.go +++ b/backend/internal/infra/provider/cli/responses_codex_tools_test.go @@ -404,7 +404,7 @@ func TestNativeBuildHistoryItemsArePreservedAndSanitized(t *testing.T) { } } -func TestReasoningWithoutEncryptedContentBecomesBoundary(t *testing.T) { +func TestReasoningWithoutEncryptedContentBecomesPortableSummary(t *testing.T) { normalized, _, err := normalizeResponsesRequest([]byte(`{ "model":"public","input":[ {"type":"reasoning","id":"rs_1","status":"completed","summary":[{"type":"summary_text","text":"who am I"}],"content":null,"encrypted_content":null,"internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, @@ -422,7 +422,11 @@ func TestReasoningWithoutEncryptedContentBecomesBoundary(t *testing.T) { items := request["input"].([]any) first := items[0].(map[string]any) if first["type"] != "message" || first["role"] != "developer" { - t.Fatalf("unencrypted reasoning should become boundary, got %#v", first) + t.Fatalf("unencrypted reasoning should become portable summary, got %#v", first) + } + text := first["content"].([]any)[0].(map[string]any)["text"].(string) + if !strings.Contains(text, "who am I") || strings.Contains(text, "omitted") { + t.Fatalf("portable reasoning text = %q", text) } if items[1].(map[string]any)["content"] != "hi" { t.Fatalf("assistant history = %#v", items[1]) diff --git a/backend/internal/infra/provider/cli/responses_history.go b/backend/internal/infra/provider/cli/responses_history.go index 6de683c0..070bdbf6 100644 --- a/backend/internal/infra/provider/cli/responses_history.go +++ b/backend/internal/infra/provider/cli/responses_history.go @@ -259,18 +259,20 @@ func (c *responsesToolCompatibility) normalizeCustomToolCallInput(item map[strin } func sanitizeReasoningInput(item map[string]any) map[string]any { - // Grok Build Responses API 中 type: "reasoning" 严格用于不透明密文回放, - // 上游强制要求携带合法的 encrypted_content。 - // 若缺少 encrypted_content,则降级为 developer 兼容边界消息,杜绝向 Grok 发送裸 reasoning。 - encrypted, ok := item["encrypted_content"].(string) - if ok && strings.TrimSpace(encrypted) != "" { - converted := copyNonNullHistoryFields(item, "id", "summary", "content", "encrypted_content") - converted["type"] = "reasoning" + // Keep ciphertext-backed reasoning native. Summary-only items are rewritten + // as developer messages so the readable plan survives without sending a + // bare type=reasoning item that Grok Build may reject. + converted := copyNonNullHistoryFields(item, "id", "summary", "content", "encrypted_content") + converted["type"] = "reasoning" + if encrypted, ok := converted["encrypted_content"].(string); ok && strings.TrimSpace(encrypted) != "" { if _, exists := converted["summary"]; !exists { converted["summary"] = []any{} } return converted } + if portable, ok := portableReasoningSummaryMessage(converted); ok { + return portable + } return compatibilityBoundaryMessage("A prior model reasoning item was omitted because it has no portable content for Grok Build.") } diff --git a/backend/internal/infra/provider/cli/responses_reasoning_recovery.go b/backend/internal/infra/provider/cli/responses_reasoning_recovery.go index 6fcda885..427a9914 100644 --- a/backend/internal/infra/provider/cli/responses_reasoning_recovery.go +++ b/backend/internal/infra/provider/cli/responses_reasoning_recovery.go @@ -16,10 +16,6 @@ var reasoningDecodeFailureMarkers = [][]byte{ []byte("could not decode the compaction blob"), []byte("could not decrypt the provided encrypted_content"), []byte("invalid_encrypted_content"), - []byte("could not be decrypted or parsed"), - []byte("could not decrypt"), - []byte("decode the compaction blob"), - []byte("compaction blob"), } type reasoningRecoveryOutcome struct { @@ -51,12 +47,14 @@ func (o reasoningRecoveryOutcome) appendWarnings(header http.Header) { // recoverReasoningDecodeFailure handles only the upstream's explicit // pre-generation opaque-reasoning decode rejection. Recovery never changes // credential or Build/XAI plane: -// 1. remove replayed encrypted_content and retry in the same session; -// 2. when the same decode error remains (or no opaque item exists), clear the -// server-side session identity and retry once with the full portable input. +// 1. remove replayed encrypted_content, keep any readable summary as a +// portable developer message, and retry in the same session; +// 2. when a 400 remains (or no opaque item exists), clear the server-side +// session identity and retry once with the full portable input. // -// If recovery is unsuccessful, the original 400 is returned so the Gateway -// does not rotate accounts or obscure the first failure. +// If recovery is unsuccessful, the original 400 is returned with +// reasoning_recovery_failed so the Gateway can rotate accounts. The Provider +// itself never changes credential. func (a *Adapter) recoverReasoningDecodeFailure( ctx context.Context, request provider.ResponseResourceRequest, @@ -109,12 +107,23 @@ func (a *Adapter) recoverReasoningDecodeFailure( a.logReasoningRecovery(request, base, "encrypted_content", "rate_limited", retry.StatusCode, nil) return retry, retryURL, reasoningRecoveryOutcome{encryptedContentDowngraded: true} } + retryStatus := retry.StatusCode sameDecodeFailure, inspectErr := responseHasReasoningDecodeFailure(retry) - if inspectErr != nil || !sameDecodeFailure { - a.logReasoningRecovery(request, base, "encrypted_content", "retry_rejected", retry.StatusCode, inspectErr) + if inspectErr != nil { + a.logReasoningRecovery(request, base, "encrypted_content", "retry_rejected", retryStatus, inspectErr) return original, requestURL, reasoningRecoveryOutcome{failed: true} } - a.logReasoningRecovery(request, base, "encrypted_content", "decode_error_persisted", retry.StatusCode, nil) + if retryStatus != http.StatusBadRequest { + a.logReasoningRecovery(request, base, "encrypted_content", "retry_rejected", retryStatus, nil) + return original, requestURL, reasoningRecoveryOutcome{failed: true} + } + if sameDecodeFailure { + a.logReasoningRecovery(request, base, "encrypted_content", "decode_error_persisted", retryStatus, nil) + } else { + // Stripping ciphertext can reword the 400 (for example a bare + // reasoning item). Keep going to session reset instead of aborting. + a.logReasoningRecovery(request, base, "encrypted_content", "retry_still_400", retryStatus, nil) + } } if !canResetReasoningSession(request, portableBody) { @@ -244,12 +253,11 @@ func isReasoningDecodeFailure(body []byte) bool { return false } -// stripReasoningEncryptedContent removes undecodable opaque reasoning and compaction -// states so Grok Build does not fail on server-side decryption. -// In Grok Build Responses API, type: "reasoning" is exclusively used for opaque encrypted replay; -// sending type: "reasoning" without encrypted_content is rejected by the upstream. -// Any reasoning item (whether it contains encrypted_content or bare summary) is removed, and any -// compaction item is converted to a compatibility boundary message. +// stripReasoningEncryptedContent removes undecodable opaque reasoning and +// compaction ciphertext so Grok Build does not fail on server-side decryption. +// Readable reasoning summaries are kept as portable developer messages; empty +// encrypted-only reasoning items are dropped. Foreign compaction blobs become +// a boundary note because this gateway cannot decrypt them. func stripReasoningEncryptedContent(body []byte) ([]byte, bool) { var payload map[string]any if json.Unmarshal(body, &payload) != nil { @@ -267,17 +275,32 @@ func stripReasoningEncryptedContent(body []byte) ([]byte, bool) { rebuilt = append(rebuilt, raw) continue } - itemType := stringField(item, "type") - if itemType == "reasoning" { + switch stringField(item, "type") { + case "reasoning": + encrypted, hasEncrypted := item["encrypted_content"].(string) + if !hasEncrypted || strings.TrimSpace(encrypted) == "" { + if portable, ok := portableReasoningSummaryMessage(item); ok { + changed = true + rebuilt = append(rebuilt, portable) + continue + } + rebuilt = append(rebuilt, raw) + continue + } changed = true - continue - } - if itemType == "compaction" { + if portable, ok := portableReasoningSummaryMessage(item); ok { + rebuilt = append(rebuilt, portable) + } + case "compaction": changed = true + if portable, ok := portableReasoningSummaryMessage(item); ok { + rebuilt = append(rebuilt, portable) + continue + } rebuilt = append(rebuilt, compatibilityBoundaryMessage("A prior compacted context could not be decoded by upstream. Continue from the retained conversation messages.")) - continue + default: + rebuilt = append(rebuilt, raw) } - rebuilt = append(rebuilt, raw) } if !changed { return body, false @@ -290,6 +313,28 @@ func stripReasoningEncryptedContent(body []byte) ([]byte, bool) { return encoded, true } +func portableReasoningSummaryMessage(item map[string]any) (map[string]any, bool) { + text := reasoningPortableText(item) + if text == "" { + return nil, false + } + return compatibilityBoundaryMessage("Prior model reasoning summary:\n" + text), true +} + +func reasoningPortableText(item map[string]any) string { + var parts []string + for _, field := range []string{"summary", "content"} { + values, _ := item[field].([]any) + for _, raw := range values { + part, _ := raw.(map[string]any) + if text := strings.TrimSpace(stringField(part, "text")); text != "" { + parts = append(parts, text) + } + } + } + return strings.Join(parts, "\n") +} + func appendCompatibilityWarning(header http.Header, warning string) { if header == nil || strings.TrimSpace(warning) == "" { return diff --git a/backend/internal/infra/provider/cli/responses_reasoning_recovery_test.go b/backend/internal/infra/provider/cli/responses_reasoning_recovery_test.go index e7cff462..a11d6384 100644 --- a/backend/internal/infra/provider/cli/responses_reasoning_recovery_test.go +++ b/backend/internal/infra/provider/cli/responses_reasoning_recovery_test.go @@ -34,17 +34,26 @@ func TestStripReasoningEncryptedContentPreservesOnlyPortableHistory(t *testing.T var payload struct { Input []map[string]any `json:"input"` } - if json.Unmarshal(downgraded, &payload) != nil || len(payload.Input) != 3 { + if json.Unmarshal(downgraded, &payload) != nil || len(payload.Input) != 4 { t.Fatalf("downgraded = %s, len=%d", downgraded, len(payload.Input)) } - if payload.Input[0]["type"] != "message" || payload.Input[0]["role"] != "developer" { - t.Fatalf("compaction boundary item = %#v", payload.Input[0]) + summary := payload.Input[0] + if summary["type"] != "message" || summary["role"] != "developer" { + t.Fatalf("readable reasoning = %#v", summary) } - if payload.Input[1]["encrypted_content"] != "message-value" { - t.Fatalf("non-reasoning encrypted content changed: %#v", payload.Input[1]) + summaryText, _ := summary["content"].([]any)[0].(map[string]any)["text"].(string) + if !strings.Contains(summaryText, "readable") || strings.Contains(summaryText, "omitted") { + t.Fatalf("readable reasoning text = %q", summaryText) } - if payload.Input[2]["role"] != "user" { - t.Fatalf("user message changed: %#v", payload.Input[2]) + compaction := payload.Input[1] + if compaction["type"] != "message" || compaction["role"] != "developer" { + t.Fatalf("compaction boundary item = %#v", compaction) + } + if payload.Input[2]["encrypted_content"] != "message-value" { + t.Fatalf("non-reasoning encrypted content changed: %#v", payload.Input[2]) + } + if payload.Input[3]["role"] != "user" { + t.Fatalf("user message changed: %#v", payload.Input[3]) } } @@ -470,6 +479,79 @@ func (reasoningRecoveryFallbackMarker) MarkBuildAPIFallback(context.Context, uin return nil } +func TestRecoverReasoningDecodeFailureKeepsReadableSummary(t *testing.T) { + adapter, encrypted := newReasoningRecoveryTestAdapter(t) + var calls atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + call := calls.Add(1) + data, _ := io.ReadAll(request.Body) + if call == 1 { + if !strings.Contains(string(data), `"encrypted_content":"opaque"`) { + t.Fatalf("first body = %s", data) + } + return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decrypt the provided encrypted_content. Ensure the value is unmodified."}`), nil + } + if strings.Contains(string(data), `"encrypted_content"`) || strings.Contains(string(data), `"type":"reasoning"`) { + t.Fatalf("retry still has opaque reasoning: %s", data) + } + if !strings.Contains(string(data), "do not touch Y") { + t.Fatalf("retry dropped readable summary: %s", data) + } + return jsonHTTPResponse(request, http.StatusOK, `{"id":"resp_ok","status":"completed","output":[]}`), nil + }) + response, err := adapter.ForwardResponse(t.Context(), provider.ResponseResourceRequest{ + Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted}, + Method: http.MethodPost, Path: "/responses", Model: "grok-4.5", PromptCacheKey: "session-1", + Body: []byte(`{"model":"grok-4.5","input":[{"type":"reasoning","summary":[{"type":"summary_text","text":"do not touch Y"}],"encrypted_content":"opaque"},{"role":"user","content":"continue"}]}`), + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if calls.Load() != 2 || response.StatusCode != http.StatusOK || !strings.Contains(response.Header.Get("X-Grok2API-Compatibility-Warnings"), "reasoning_encrypted_content_downgraded") { + t.Fatalf("calls=%d status=%d warnings=%q", calls.Load(), response.StatusCode, response.Header.Get("X-Grok2API-Compatibility-Warnings")) + } +} + +func TestRecoverReasoningDecodeFailureContinuesToSessionResetWhenStripRewords400(t *testing.T) { + adapter, encrypted := newReasoningRecoveryTestAdapter(t) + var calls atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + call := calls.Add(1) + data, _ := io.ReadAll(request.Body) + switch call { + case 1: + return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decrypt the provided encrypted_content. Ensure the value is unmodified."}`), nil + case 2: + if strings.Contains(string(data), `"encrypted_content"`) || request.Header.Get("x-grok-session-id") == "" { + t.Fatalf("opaque downgrade body=%s headers=%#v", data, request.Header) + } + return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"invalid request history"}`), nil + case 3: + if strings.Contains(string(data), `"encrypted_content"`) || strings.Contains(string(data), `"prompt_cache_key"`) || request.Header.Get("x-grok-session-id") != "" { + t.Fatalf("session reset body=%s headers=%#v", data, request.Header) + } + return jsonHTTPResponse(request, http.StatusOK, `{"id":"resp_ok","status":"completed","output":[]}`), nil + default: + t.Fatalf("unexpected call %d", call) + return nil, nil + } + }) + response, err := adapter.ForwardResponse(t.Context(), provider.ResponseResourceRequest{ + Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted}, + Method: http.MethodPost, Path: "/responses", Model: "grok-4.5", PromptCacheKey: "session-1", + Body: []byte(`{"model":"grok-4.5","input":[{"type":"reasoning","summary":[],"encrypted_content":"opaque"},{"role":"user","content":"continue"}]}`), + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + warnings := response.Header.Get("X-Grok2API-Compatibility-Warnings") + if calls.Load() != 3 || response.StatusCode != http.StatusOK || !strings.Contains(warnings, "reasoning_encrypted_content_downgraded") || !strings.Contains(warnings, "reasoning_session_reset") { + t.Fatalf("calls=%d status=%d warnings=%q", calls.Load(), response.StatusCode, warnings) + } +} + func TestRecoverReasoningDecodeFailureCompactionBlob(t *testing.T) { adapter, encrypted := newReasoningRecoveryTestAdapter(t) var calls atomic.Int32 From f343670fa77781cc93f89e36eab8704694356d3c Mon Sep 17 00:00:00 2001 From: lij768423-svg Date: Thu, 27 Aug 2026 19:03:27 +0800 Subject: [PATCH 03/12] fix: treat short encrypted_content stubs as missing thinking Non-empty ciphertext is not proof of reasoning. HasThinking now requires encrypted_content / Anthropic signature to meet max(256B, 4 bytes per usage reasoning token). A hold-expired short greeting billed as heavy thinking, or a barely-over-floor flush in under a second, is withheld. Recommended requestRetry values stay 30s / minOutput 8 / 6 attempts / fail_closed / 12h / 15m idle, plus the new floor knobs. enabled remains false so stock installs do not intercept. --- backend/internal/app/application.go | 16 +-- .../application/gateway/quality_retry.go | 86 +++++++++++++--- .../application/gateway/quality_retry_scan.go | 77 ++++++++++----- .../application/gateway/quality_retry_test.go | 98 +++++++++++++++++-- backend/internal/infra/config/config.go | 11 ++- backend/internal/infra/config/config_test.go | 2 +- config.example.yaml | 8 +- 7 files changed, 241 insertions(+), 57 deletions(-) diff --git a/backend/internal/app/application.go b/backend/internal/app/application.go index faa2c964..d03ceb40 100644 --- a/backend/internal/app/application.go +++ b/backend/internal/app/application.go @@ -491,13 +491,15 @@ func accountAutoCleanConfig(value config.AccountsConfig) accountapp.AutoCleanCon func qualityRetryRuntime(value config.QualityGuardRequestRetryConfig) gateway.QualityRetryRuntime { return gateway.QualityRetryRuntime{ - Enabled: value.Enabled, - MaxAttempts: value.MaxAttempts, - HoldTimeout: value.HoldTimeout.Value(), - MinOutputTokens: int64(value.MinOutputTokens), - OnExhausted: value.OnExhausted, - AccountCooldown: value.AccountCooldown.Value(), - IdleAccountCooldown: value.IdleAccountCooldown.Value(), + Enabled: value.Enabled, + MaxAttempts: value.MaxAttempts, + HoldTimeout: value.HoldTimeout.Value(), + MinOutputTokens: int64(value.MinOutputTokens), + OnExhausted: value.OnExhausted, + AccountCooldown: value.AccountCooldown.Value(), + IdleAccountCooldown: value.IdleAccountCooldown.Value(), + MinEncryptedBytes: value.MinEncryptedBytes, + EncryptedBytesPerReasoningToken: value.EncryptedBytesPerReasoningToken, } } diff --git a/backend/internal/application/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go index 3a386944..8bfcaf98 100644 --- a/backend/internal/application/gateway/quality_retry.go +++ b/backend/internal/application/gateway/quality_retry.go @@ -17,15 +17,20 @@ import ( ) const ( - ErrorQualityDegraded = "quality_degraded" - qualityRetryFailOpen = "fail_open" - qualityRetryFailClosed = "fail_closed" - defaultQualityMaxAttempts = 6 - defaultQualityHoldTimeout = 30 * time.Second - defaultQualityMinOutput = int64(8) - defaultMissingThinkingCooldown = 12 * time.Hour - lastErrorMissingThinking = accountdomain.LastErrorMissingThinking - lastErrorMissingThinkingDisabled = accountdomain.LastErrorMissingThinkingDisabled + ErrorQualityDegraded = "quality_degraded" + qualityRetryFailOpen = "fail_open" + qualityRetryFailClosed = "fail_closed" + defaultQualityMaxAttempts = 6 + defaultQualityHoldTimeout = 30 * time.Second + defaultQualityMinOutput = int64(8) + defaultMinEncryptedBytes = 256 + defaultEncryptedBytesPerReasoningToken = 4 + defaultBurstFlushMS = int64(1000) + defaultBurstMaxVisible = int64(32) + defaultBurstMinReasoning = int64(80) + defaultMissingThinkingCooldown = 12 * time.Hour + lastErrorMissingThinking = accountdomain.LastErrorMissingThinking + lastErrorMissingThinkingDisabled = accountdomain.LastErrorMissingThinkingDisabled // An empty stream that idles while held is treated as an account-quality // failure: the request can still rotate before any bytes reach the client. qualityIdleAccountCooldown = 15 * time.Minute @@ -47,7 +52,9 @@ type QualityRetryRuntime struct { AccountCooldown time.Duration // IdleAccountCooldown is applied to truly empty upstream streams // (idle timeout / empty peek). Missing-thinking still uses AccountCooldown. - IdleAccountCooldown time.Duration + IdleAccountCooldown time.Duration + MinEncryptedBytes int + EncryptedBytesPerReasoningToken int } // QualityStreamSignals is the hold classifier input. Tests drive this @@ -61,6 +68,9 @@ type QualityStreamSignals struct { VisibleTokens int64 ReasoningTokens int64 OutputTokens int64 + EncryptedBytes int + FirstVisible bool + VisibleFlushMS int64 Terminal bool HoldExpired bool } @@ -100,6 +110,12 @@ func normalizeQualityRetry(cfg QualityRetryRuntime) QualityRetryRuntime { if cfg.IdleAccountCooldown <= 0 { cfg.IdleAccountCooldown = qualityIdleAccountCooldown } + if cfg.MinEncryptedBytes <= 0 { + cfg.MinEncryptedBytes = defaultMinEncryptedBytes + } + if cfg.EncryptedBytesPerReasoningToken <= 0 { + cfg.EncryptedBytesPerReasoningToken = defaultEncryptedBytesPerReasoningToken + } cfg.OnExhausted = normalizeQualityExhaustionPolicy(cfg.OnExhausted) return cfg } @@ -119,12 +135,47 @@ func (s *Service) qualityRetryConfig() QualityRetryRuntime { return normalizeQualityRetry(QualityRetryRuntime{}) } +// encryptedThinkingFloor is max(minBytes, reasoningTokens*bytesPerToken). +// A non-empty stub such as "gAAAA-cipher" is not thinking. +func encryptedThinkingFloor(minBytes, bytesPerToken int, reasoningTokens int64) int { + if minBytes <= 0 { + minBytes = defaultMinEncryptedBytes + } + if bytesPerToken <= 0 { + bytesPerToken = defaultEncryptedBytesPerReasoningToken + } + floor := minBytes + if reasoningTokens > 0 { + need := int(reasoningTokens) * bytesPerToken + if need > floor { + floor = need + } + } + return floor +} + +func qualityIsBurstDump(sig QualityStreamSignals, minOutput int64) bool { + visible := sig.VisibleTokens + floor := encryptedThinkingFloor(0, 0, sig.ReasoningTokens) + barelyCipher := sig.EncryptedBytes > 0 && sig.EncryptedBytes < floor*2 + flushed := sig.FirstVisible && sig.VisibleFlushMS >= 0 && sig.VisibleFlushMS < defaultBurstFlushMS + // Hold timed out, then a short greeting dumped with a large reasoning bill + // (TUI "你好" after 30s / 954 thinking tokens). + if sig.HoldExpired && visible > 0 && visible < defaultBurstMaxVisible && sig.ReasoningTokens >= defaultBurstMinReasoning { + return true + } + if barelyCipher && flushed && (visible >= minOutput || sig.ReasoningTokens >= defaultBurstMinReasoning) { + return true + } + return false +} + // ClassifyQualityHold decides whether a held stream may be forwarded. -// Streamed thinking always delivers: reasoning/summary deltas, or a -// reasoning item with encrypted_content. Usage.reasoning_tokens alone -// does not — degraded upstreams fill that field without ciphertext or -// deltas. A finished sample with enough visible output and no streamed -// thinking is withheld. +// Streamed thinking delivers: reasoning/summary deltas, or a reasoning item +// whose encrypted_content meets the ciphertext floor. A non-empty stub such +// as "gAAAA-cipher" is not thinking. Usage.reasoning_tokens alone does not — +// degraded upstreams fill that field without ciphertext or deltas. A finished +// sample with enough visible output and no streamed thinking is withheld. // Short replies below minOutput are delivered so "ok"/"yes" is not retried. // A hold timeout with no visible output is not fail-open: keep waiting for // more bytes or a stream abort so an empty hang is not flushed as HTTP 200. @@ -135,11 +186,16 @@ func (s *Service) qualityRetryConfig() QualityRetryRuntime { // release it without penalizing the account. A stub-only empty stream keeps // waiting for idle/terminal handling. This keeps HoldTimeout a real latency // bound without reopening the empty-stream 200 response path. +// HasThinking that is only a thin ciphertext dump after the hold (or a +// barely-over-floor flush in <1s) is still withheld. func ClassifyQualityHold(sig QualityStreamSignals, minOutput int64) QualityVerdict { if minOutput <= 0 { minOutput = defaultQualityMinOutput } if sig.HasThinking { + if qualityIsBurstDump(sig, minOutput) { + return QualityWithhold + } return QualityDeliver } // Prefer observed/derived visible output. Total output includes reasoning diff --git a/backend/internal/application/gateway/quality_retry_scan.go b/backend/internal/application/gateway/quality_retry_scan.go index c5aa4169..6f9b163a 100644 --- a/backend/internal/application/gateway/quality_retry_scan.go +++ b/backend/internal/application/gateway/quality_retry_scan.go @@ -23,18 +23,23 @@ const ( ) type qualityScanState struct { - protocol string - pending []byte - hasThinking bool - reasoningStarted bool - visibleRunes int - aggregateRunes int - semanticOutput bool - reasoningTokens int64 - outputTokens int64 - usage Usage - responseID string - terminal bool + protocol string + pending []byte + hasThinking bool + reasoningStarted bool + visibleRunes int + aggregateRunes int + semanticOutput bool + reasoningTokens int64 + outputTokens int64 + encryptedBytes int + minEncryptedBytes int + encryptedBytesPerReasoningToken int + usage Usage + responseID string + terminal bool + holdExpired bool + firstVisibleAt time.Time } type qualityReadResult struct { @@ -144,13 +149,27 @@ func (s *qualityScanState) signals() QualityStreamSignals { // Usage.reasoning_tokens is not proof of thinking. 降智 accounts report // hundreds of reasoning tokens on completed while the stream never sent // reasoning_text / reasoning_summary deltas (TUI shows no thoughts). + // A non-empty encrypted_content stub is also not thinking until it meets + // the ciphertext floor (default 256 bytes, or 4 bytes per reasoning token). + reasoningTokens := max(s.reasoningTokens, s.usage.ReasoningTokens) + floor := encryptedThinkingFloor(s.minEncryptedBytes, s.encryptedBytesPerReasoningToken, reasoningTokens) + hasThinking := s.hasThinking || s.encryptedBytes >= floor + firstVisible := !s.firstVisibleAt.IsZero() + var flushMS int64 + if firstVisible { + flushMS = time.Since(s.firstVisibleAt).Milliseconds() + } return QualityStreamSignals{ - HasThinking: s.hasThinking, - ReasoningStarted: s.reasoningStarted || s.hasThinking, + HasThinking: hasThinking, + ReasoningStarted: s.reasoningStarted || hasThinking, VisibleTokens: visible, - ReasoningTokens: max(s.reasoningTokens, s.usage.ReasoningTokens), + ReasoningTokens: reasoningTokens, OutputTokens: output, + EncryptedBytes: s.encryptedBytes, + FirstVisible: firstVisible, + VisibleFlushMS: flushMS, Terminal: s.terminal, + HoldExpired: s.holdExpired, } } @@ -277,6 +296,12 @@ type qualityResponsesOutputItem struct { } `json:"content"` } +func noteEncryptedBytes(state *qualityScanState, blob string) { + if n := len(strings.TrimSpace(blob)); n > state.encryptedBytes { + state.encryptedBytes = n + } +} + func noteResponsesReasoningItem(state *qualityScanState, item qualityResponsesOutputItem) { if !strings.EqualFold(strings.TrimSpace(item.Type), "reasoning") { return @@ -284,9 +309,7 @@ func noteResponsesReasoningItem(state *qualityScanState, item qualityResponsesOu if strings.TrimSpace(item.ID) != "" { state.reasoningStarted = true } - if strings.TrimSpace(item.EncryptedContent) != "" { - state.hasThinking = true - } + noteEncryptedBytes(state, item.EncryptedContent) } func observeQualityResponses(state *qualityScanState, payload []byte) { @@ -420,9 +443,7 @@ func observeQualityAnthropic(state *qualityScanState, payload []byte) { state.reasoningStarted = true case "redacted_thinking": state.reasoningStarted = true - if strings.TrimSpace(event.ContentBlock.Data) != "" { - state.hasThinking = true - } + noteEncryptedBytes(state, event.ContentBlock.Data) case "text": if event.ContentBlock.Text != "" { noteVisibleContent(state, event.ContentBlock.Text) @@ -438,9 +459,9 @@ func observeQualityAnthropic(state *qualityScanState, payload []byte) { } if event.Delta.Type == "signature_delta" && strings.TrimSpace(event.Delta.Signature) != "" { // Anthropic Messages represents Responses encrypted_content as a - // signature delta. A non-empty signature is encrypted thinking proof. + // signature delta. Length is judged against the ciphertext floor. state.reasoningStarted = true - state.hasThinking = true + noteEncryptedBytes(state, event.Delta.Signature) } if event.Delta.Type == "text_delta" && event.Delta.Text != "" { noteVisibleContent(state, event.Delta.Text) @@ -462,6 +483,9 @@ func noteVisibleContent(state *qualityScanState, text string) { if text == "" { return } + if state.firstVisibleAt.IsZero() { + state.firstVisibleAt = time.Now() + } state.visibleRunes += utf8.RuneCountInString(text) } @@ -471,7 +495,11 @@ func peekQualityStream(ctx context.Context, body io.ReadCloser, protocol string, return io.NopCloser(bytes.NewReader(nil)), QualityWait, Usage{}, "", errQualityEmptyStream } pump := newQualityReadPump(body) - state := qualityScanState{protocol: protocol} + state := qualityScanState{ + protocol: protocol, + minEncryptedBytes: cfg.MinEncryptedBytes, + encryptedBytesPerReasoningToken: cfg.EncryptedBytesPerReasoningToken, + } var held bytes.Buffer holdTimer := time.NewTimer(cfg.HoldTimeout) defer holdTimer.Stop() @@ -492,6 +520,7 @@ func peekQualityStream(ctx context.Context, body io.ReadCloser, protocol string, _ = pump.Close() return io.NopCloser(bytes.NewReader(held.Bytes())), QualityWait, state.usage, state.responseID, qualityPeekAbortError(ctx, ctx.Err()) case <-holdTimer.C: + state.holdExpired = true sig.HoldExpired = true if verdict := ClassifyQualityHold(sig, cfg.MinOutputTokens); verdict != QualityWait { return newPrefixReplay(&held, pump), verdict, state.usage, state.responseID, nil diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go index e86c8b47..ee272837 100644 --- a/backend/internal/application/gateway/quality_retry_test.go +++ b/backend/internal/application/gateway/quality_retry_test.go @@ -59,6 +59,44 @@ func TestClassifyQualityHold(t *testing.T) { } } +func TestClassifyQualityHoldBurst(t *testing.T) { + t.Parallel() + tests := []struct { + name string + sig QualityStreamSignals + want QualityVerdict + }{ + { + name: "hold-expired hello dump withholds", + sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 2, ReasoningTokens: 954, EncryptedBytes: 4000, HoldExpired: true}, + want: QualityWithhold, + }, + { + name: "hold-expired long answer delivers", + sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 200, ReasoningTokens: 954, EncryptedBytes: 8000, HoldExpired: true}, + want: QualityDeliver, + }, + { + name: "barely-over-floor flush withholds", + sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 50, ReasoningTokens: 60, EncryptedBytes: 300, FirstVisible: true, VisibleFlushMS: 100}, + want: QualityWithhold, + }, + { + name: "large cipher flush delivers", + sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 50, ReasoningTokens: 60, EncryptedBytes: 2000, FirstVisible: true, VisibleFlushMS: 100}, + want: QualityDeliver, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + if got := ClassifyQualityHold(test.sig, 8); got != test.want { + t.Fatalf("ClassifyQualityHold() = %s, want %s (%#v)", got, test.want, test.sig) + } + }) + } +} + func TestDecideQualityRetry(t *testing.T) { t.Parallel() if got := DecideQualityRetry(QualityDeliver, 0, 2, qualityRetryFailOpen); got != QualityActionDeliver { @@ -289,10 +327,11 @@ func TestObserveQualityChunkShortNoThinkIgnoresFakeReasoningUsage(t *testing.T) func TestObserveQualityConvertedEncryptedThinking(t *testing.T) { t.Parallel() + cipher := strings.Repeat("A", defaultMinEncryptedBytes*8) source := sse( `data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4.6"}}`, `data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`, - `data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"gAAAA-cipher"}}`, + `data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"`+cipher+`"}}`, `data: {"type":"response.output_text.delta","delta":"`+strings.Repeat("word ", 40)+`"}`, `data: {"type":"response.completed","response":{"id":"resp_1","model":"grok-4.6","usage":{"output_tokens":90,"output_tokens_details":{"reasoning_tokens":60}}}}`, ) @@ -350,12 +389,21 @@ func TestObserveQualityChunkWhitespaceIsNotThinking(t *testing.T) { func TestObserveQualityChunkAnthropicSignatureIsThinking(t *testing.T) { t.Parallel() - state := qualityScanState{protocol: qualityProtocolAnthropic} - ObserveQualityChunk(&state, []byte(sse( + short := qualityScanState{protocol: qualityProtocolAnthropic} + ObserveQualityChunk(&short, []byte(sse( `data: {"type":"content_block_delta","delta":{"type":"signature_delta","signature":"gAAAA-cipher"}}`, ))) + if sig := short.signals(); sig.HasThinking || !sig.ReasoningStarted || sig.EncryptedBytes == 0 { + t.Fatalf("short Anthropic signature stub must not count as thinking: %#v", sig) + } + + cipher := strings.Repeat("A", defaultMinEncryptedBytes) + state := qualityScanState{protocol: qualityProtocolAnthropic} + ObserveQualityChunk(&state, []byte(sse( + `data: {"type":"content_block_delta","delta":{"type":"signature_delta","signature":"`+cipher+`"}}`, + ))) if sig := state.signals(); !sig.HasThinking || !sig.ReasoningStarted { - t.Fatalf("non-empty Anthropic signature must count as encrypted thinking: %#v", sig) + t.Fatalf("floor-sized Anthropic signature must count as encrypted thinking: %#v", sig) } } @@ -392,20 +440,54 @@ func TestObserveQualityChunkResponsesReasoningItem(t *testing.T) { t.Fatalf("streamed reasoning summary should deliver: %#v", realSig) } + short := qualityScanState{protocol: qualityProtocolResponses} + ObserveQualityChunk(&short, []byte(sse( + `data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`, + `data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"gAAAA-cipher"}}`, + `data: {"type":"response.output_text.delta","delta":"`+strings.Repeat("word ", 40)+`"}`, + `data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":90,"output_tokens_details":{"reasoning_tokens":60}}}}`, + ))) + shortSig := short.signals() + if shortSig.HasThinking { + t.Fatalf("short encrypted stub must not count as thinking: %#v", shortSig) + } + if shortSig.EncryptedBytes == 0 || !shortSig.ReasoningStarted || shortSig.ReasoningTokens != 60 { + t.Fatalf("short encrypted stub signals = %#v", shortSig) + } + if ClassifyQualityHold(shortSig, 32) != QualityWithhold { + t.Fatalf("short encrypted stub must withhold: %#v", shortSig) + } + + cipher := strings.Repeat("A", defaultMinEncryptedBytes*8) encrypted := qualityScanState{protocol: qualityProtocolResponses} ObserveQualityChunk(&encrypted, []byte(sse( `data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`, - `data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"gAAAA-cipher"}}`, - `data: {"type":"response.output_text.delta","delta":"hello hello hello hello hello hello hello hello"}`, + `data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"`+cipher+`"}}`, + `data: {"type":"response.output_text.delta","delta":"`+strings.Repeat("word ", 40)+`"}`, `data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":90,"output_tokens_details":{"reasoning_tokens":60}}}}`, ))) encSig := encrypted.signals() - if !encSig.HasThinking || encSig.ReasoningTokens != 60 { + if !encSig.HasThinking || encSig.ReasoningTokens != 60 || encSig.EncryptedBytes < defaultMinEncryptedBytes { t.Fatalf("encrypted reasoning item must count as thinking: %#v", encSig) } if ClassifyQualityHold(encSig, 32) != QualityDeliver { t.Fatalf("encrypted thinking should deliver: %#v", encSig) } + + floorCipher := strings.Repeat("A", defaultMinEncryptedBytes) + undersized := qualityScanState{protocol: qualityProtocolResponses} + ObserveQualityChunk(&undersized, []byte(sse( + `data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"`+floorCipher+`"}}`, + `data: {"type":"response.output_text.delta","delta":"`+strings.Repeat("word ", 40)+`"}`, + `data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":1200,"output_tokens_details":{"reasoning_tokens":1000}}}}`, + ))) + underSig := undersized.signals() + if underSig.HasThinking { + t.Fatalf("256B cipher must not satisfy 1000 reasoning tokens: %#v", underSig) + } + if ClassifyQualityHold(underSig, 32) != QualityWithhold { + t.Fatalf("undersized cipher vs usage must withhold: %#v", underSig) + } } func TestObserveQualityChunkEmptyReasoningStubIsNotThinking(t *testing.T) { @@ -1409,7 +1491,7 @@ func TestAttemptLoopQualityFailOpenFallbackAndTotalAttemptCap(t *testing.T) { func TestNormalizeQualityRetryDefaults(t *testing.T) { t.Parallel() got := normalizeQualityRetry(QualityRetryRuntime{Enabled: true}) - if !got.Enabled || got.MaxAttempts != 6 || got.MinOutputTokens != 8 || got.OnExhausted != qualityRetryFailClosed || got.HoldTimeout != 30*time.Second || got.AccountCooldown != 12*time.Hour || got.IdleAccountCooldown != 15*time.Minute { + if !got.Enabled || got.MaxAttempts != 6 || got.MinOutputTokens != 8 || got.OnExhausted != qualityRetryFailClosed || got.HoldTimeout != 30*time.Second || got.AccountCooldown != 12*time.Hour || got.IdleAccountCooldown != 15*time.Minute || got.MinEncryptedBytes != defaultMinEncryptedBytes || got.EncryptedBytesPerReasoningToken != defaultEncryptedBytesPerReasoningToken { t.Fatalf("defaults = %#v", got) } } diff --git a/backend/internal/infra/config/config.go b/backend/internal/infra/config/config.go index 28541940..889b5415 100644 --- a/backend/internal/infra/config/config.go +++ b/backend/internal/infra/config/config.go @@ -297,7 +297,9 @@ type QualityGuardRequestRetryConfig struct { AccountCooldown Duration `yaml:"accountCooldown"` // IdleAccountCooldown cools an account after a truly empty upstream // stream. Independent of accountCooldown (missing-thinking). Zero uses 15m. - IdleAccountCooldown Duration `yaml:"idleAccountCooldown"` + IdleAccountCooldown Duration `yaml:"idleAccountCooldown"` + MinEncryptedBytes int `yaml:"minEncryptedBytes"` + EncryptedBytesPerReasoningToken int `yaml:"encryptedBytesPerReasoningToken"` } type ClientKeyDefaultsConfig struct { @@ -809,6 +811,12 @@ func validateQualityGuardRequestRetry(value QualityGuardRequestRetryConfig) erro if d := value.IdleAccountCooldown.Value(); d != 0 && (d < time.Minute || d > 168*time.Hour) { return errors.New("qualityGuard.requestRetry.idleAccountCooldown 必须在 1m 到 168h 之间") } + if value.MinEncryptedBytes != 0 && (value.MinEncryptedBytes < 64 || value.MinEncryptedBytes > 4096) { + return errors.New("qualityGuard.requestRetry.minEncryptedBytes 必须在 64 到 4096 之间") + } + if value.EncryptedBytesPerReasoningToken != 0 && (value.EncryptedBytesPerReasoningToken < 1 || value.EncryptedBytesPerReasoningToken > 16) { + return errors.New("qualityGuard.requestRetry.encryptedBytesPerReasoningToken 必须在 1 到 16 之间") + } return nil } @@ -944,6 +952,7 @@ func defaultConfig() Config { RequestRetry: QualityGuardRequestRetryConfig{ MaxAttempts: 6, HoldTimeout: Duration(30 * time.Second), MinOutputTokens: 8, OnExhausted: "fail_closed", AccountCooldown: Duration(12 * time.Hour), IdleAccountCooldown: Duration(15 * time.Minute), + MinEncryptedBytes: 256, EncryptedBytesPerReasoningToken: 4, }, }, ClientKeyDefaults: ClientKeyDefaultsConfig{RPMLimit: clientkeydomain.DefaultRPMLimit, MaxConcurrent: clientkeydomain.DefaultMaxConcurrent}, diff --git a/backend/internal/infra/config/config_test.go b/backend/internal/infra/config/config_test.go index fb12df85..058fffc0 100644 --- a/backend/internal/infra/config/config_test.go +++ b/backend/internal/infra/config/config_test.go @@ -223,7 +223,7 @@ qualityGuard: func TestDefaultQualityGuardRequestRetryContract(t *testing.T) { t.Parallel() got := defaultConfig().QualityGuard.RequestRetry - if got.Enabled || got.MaxAttempts != 6 || got.HoldTimeout.Value() != 30*time.Second || got.MinOutputTokens != 8 || got.OnExhausted != "fail_closed" || got.AccountCooldown.Value() != 12*time.Hour || got.IdleAccountCooldown.Value() != 15*time.Minute { + if got.Enabled || got.MaxAttempts != 6 || got.HoldTimeout.Value() != 30*time.Second || got.MinOutputTokens != 8 || got.OnExhausted != "fail_closed" || got.AccountCooldown.Value() != 12*time.Hour || got.IdleAccountCooldown.Value() != 15*time.Minute || got.MinEncryptedBytes != 256 || got.EncryptedBytesPerReasoningToken != 4 { t.Fatalf("requestRetry defaults = %#v", got) } } diff --git a/config.example.yaml b/config.example.yaml index ecc9cc0e..a1ea8cc8 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -150,6 +150,8 @@ qualityGuard: nodeIDs: [] rotatableNodeIDs: [] # Optional request-path withhold/retry for thinking models. + # Recommended lab values are filled in; enabled stays false so stock + # installs do not intercept. Set enabled: true to turn the hold on. # Observe up to 30s for real reasoning evidence. If upstream has announced # a reasoning item and visible output but proof arrives later, the still-open # stream is released at the deadline without penalizing the account. Empty or @@ -158,8 +160,10 @@ qualityGuard: # account is tried (up to maxAttempts). fail_closed returns 503 instead # of the last body. Sidecar qualityGuard.enabled stays false until you # start the quality-guard profile. + # Non-empty encrypted_content stubs are not thinking. The ciphertext floor + # is max(minEncryptedBytes, reasoning_tokens * encryptedBytesPerReasoningToken). requestRetry: - enabled: true + enabled: false maxAttempts: 6 holdTimeout: 30s minOutputTokens: 8 @@ -171,3 +175,5 @@ qualityGuard: # Single-account pools should set this lower; toggling enabled does not # clear cooldown — use POST /api/admin/v1/accounts/:id/clear-cooldown. idleAccountCooldown: 15m + minEncryptedBytes: 256 + encryptedBytesPerReasoningToken: 4 From ffaa2c7ba27067d616aa62f3802747b3208dd28d Mon Sep 17 00:00:00 2001 From: lij768423-svg Date: Thu, 27 Aug 2026 23:53:28 +0800 Subject: [PATCH 04/12] fix: hold TUI follow-ups and hosted-tool turns Do not skip missing-thinking intercept on previous_response_id or hosted tools. TUI always declares those. First attempt stays pinned; withhold unpins and rotates. Compaction with no reasoning is held unless the gateway set skipQualityHold. --- .../application/gateway/quality_retry.go | 26 +++++-------------- .../application/gateway/quality_retry_test.go | 18 ++++++------- .../internal/application/gateway/service.go | 18 ++++++++----- 3 files changed, 27 insertions(+), 35 deletions(-) diff --git a/backend/internal/application/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go index 8bfcaf98..7eb4fc6f 100644 --- a/backend/internal/application/gateway/quality_retry.go +++ b/backend/internal/application/gateway/quality_retry.go @@ -342,34 +342,22 @@ func CommitQualityHold(verdict QualityVerdict, qualityAttempt, maxAttempts int, } func shouldHoldQualityStream(input Input, ownership *inferencedomain.ResponseOwnership, route modeldomain.Route, operation audit.Operation, cfg QualityRetryRuntime) bool { - if !cfg.Enabled || !input.Streaming || input.ForcedEgressNodeID != 0 || ownership != nil || input.skipQualityHold { + if !cfg.Enabled || !input.Streaming || input.ForcedEgressNodeID != 0 || input.skipQualityHold { return false } switch operation { - case audit.OperationChat, audit.OperationResponses, audit.OperationMessages, "": + case audit.OperationChat, audit.OperationResponses, audit.OperationMessages, audit.OperationCompaction, "": default: return false } - // TUI compaction is a normal /v1/responses body (no compaction_trigger). - // Keep this defensive body check in addition to skipQualityHold so a caller - // that bypasses CreateResponse cannot withhold a 100s+ summary as missing-thinking. - if isResponsesCompactionRequest(input.Body) { - return false - } if route.Provider != accountdomain.ProviderBuild && route.Provider != accountdomain.ProviderConsole { return false } - // Client-executed tools are safe to hold: their calls have not reached the - // client yet, and completed results in the next request are immutable input. - // Hosted tools are different. Retrying them can repeat an upstream search, - // sandbox run, image job, or remote MCP call, so retain the old no-replay - // safety boundary for any request that declares one. - if qualityRequestHasReplayUnsafeHostedTools(input.Body) { - return false - } - // Aliases are rewritten before this gate, so inspect the effective request - // body instead of only the reasoning-capable base model. In particular, - // grok-4.3-none becomes grok-4.3 plus an explicit disabled setting. + // TUI always declares tools (including hosted web_search / image jobs) and + // follow-ups carry previous_response_id. Skipping either let 0-thinking + // dumps through on the common agent loop. Keep holding; the attempt loop + // unpins after the first missing-thinking hit. Skip only when the request + // explicitly disables reasoning. if qualityRequestDisablesReasoning(input.Body) { return false } diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go index ee272837..190f6be6 100644 --- a/backend/internal/application/gateway/quality_retry_test.go +++ b/backend/internal/application/gateway/quality_retry_test.go @@ -1053,24 +1053,24 @@ func TestShouldHoldQualityStreamGates(t *testing.T) { t.Fatal("forced egress must not hold") } owned := inferencedomain.ResponseOwnership{ResponseID: "r1", AccountID: 1} - if shouldHoldQualityStream(input, &owned, route, audit.OperationChat, cfg) { - t.Fatal("pinned response must not hold") + if !shouldHoldQualityStream(input, &owned, route, audit.OperationChat, cfg) { + t.Fatal("pinned previous_response_id must still hold on missing thinking") } if shouldHoldQualityStream(input, nil, route, audit.OperationImage, cfg) { t.Fatal("image must not hold") } - if shouldHoldQualityStream(input, nil, route, audit.OperationCompaction, cfg) { - t.Fatal("codex compaction operation must not hold") + if !shouldHoldQualityStream(input, nil, route, audit.OperationCompaction, cfg) { + t.Fatal("compaction with no reasoning must hold") } classified := input classified.skipQualityHold = true if shouldHoldQualityStream(classified, nil, route, audit.OperationResponses, cfg) { - t.Fatal("gateway-classified compaction must not hold") + t.Fatal("explicit skipQualityHold must not hold") } tui := input tui.Body = []byte(`{"input":[{"role":"user","content":"` + tuiCompactionPrompt + `"}]}`) - if shouldHoldQualityStream(tui, nil, route, audit.OperationResponses, cfg) { - t.Fatal("tui compaction prompt must not hold even when tagged responses") + if !shouldHoldQualityStream(tui, nil, route, audit.OperationResponses, cfg) { + t.Fatal("tui compaction prompt with no reasoning must hold") } for _, test := range []struct { name string @@ -1154,8 +1154,8 @@ func TestShouldHoldQualityStreamGates(t *testing.T) { if !qualityRequestHasReplayUnsafeHostedTools(request.Body) { t.Fatal("fixture must be classified as replay-unsafe hosted tooling") } - if shouldHoldQualityStream(request, nil, route, audit.OperationChat, cfg) { - t.Fatal("hosted tools must not be held because account retry can execute them again") + if !shouldHoldQualityStream(request, nil, route, audit.OperationChat, cfg) { + t.Fatal("hosted tools must still hold; TUI always declares them") } }) } diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index e6b99685..f66929bb 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -1018,7 +1018,9 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string // A lease recovery probe stays on exactly one account and one rendered proxy // identity. Retrying the same pinned account would provide neither failover // nor new evidence and can multiply a slow/failing probe. - attemptPolicy := newRequestRoutingAttemptPolicy(int(s.maxAttempts.Load()), ownership != nil || input.ForcedAccountID != 0) + holdCfg := s.qualityRetryConfig() + qualityHoldEnabled := shouldHoldQualityStream(input, ownership, route, operation, holdCfg) + attemptPolicy := newRequestRoutingAttemptPolicy(int(s.maxAttempts.Load()), input.ForcedAccountID != 0 || (ownership != nil && !qualityHoldEnabled)) idempotencyID, _ := security.NewOpaqueToken(18) pricingModel := s.providers.PricingModel(route.Provider, route.UpstreamModel) if err := s.checkLedgerReady(); err != nil { @@ -1032,8 +1034,6 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string excluded := make(map[uint64]bool) failureFingerprints := make(map[string]int) authRecoveryAttempted := make(map[uint64]bool) - holdCfg := s.qualityRetryConfig() - qualityHoldEnabled := shouldHoldQualityStream(input, ownership, route, operation, holdCfg) // Count accounts that actually reached the upstream. Credential-only skips // do not consume the quality retry budget; refreshes stay on the same account. qualityAccountAttempts := 0 @@ -1244,7 +1244,7 @@ attemptLoop: err = &SelectionUnavailableError{Reason: SelectionNoAccounts} } } - } else if ownership != nil { + } else if ownership != nil && qualityAccountAttempts == 0 { lease, err = s.selector.AcquirePinnedForKey(ctx, route.Provider, ownership.AccountID, route.ID, route.UpstreamModel, quotaMode, true, accountScope) } else if input.ForcedEgressNodeID != 0 { lease, err = s.selector.AcquireForKeyOnEgressNode(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, affinityKey, excluded, !quotaProbeAttempted, accountScope, input.ForcedEgressNodeID) @@ -1276,7 +1276,7 @@ attemptLoop: // Stored Responses are pinned to one account. Return the cached 429 // immediately instead of spinning until the cooldown expires or // replaying the request on the same account. - if ownership != nil || input.ForcedAccountID != 0 { + if input.ForcedAccountID != 0 || (ownership != nil && (!qualityHoldEnabled || qualityAccountAttempts == 0)) { break attemptLoop } attempt-- @@ -1617,8 +1617,12 @@ attemptLoop: continue } response.Body = replay - hasNextAccount := attemptPolicy.hasNext(attempt) && selection.hasAvailableCandidate(excluded, !quotaProbeAttempted) - hasNextAccount = hasNextAccount && qualityAccountAttempts < holdCfg.MaxAttempts + hasNextAccount := attemptPolicy.hasNext(attempt) && qualityAccountAttempts < holdCfg.MaxAttempts + if selection != nil { + hasNextAccount = hasNextAccount && selection.hasAvailableCandidate(excluded, !quotaProbeAttempted) + } else if ownership == nil { + hasNextAccount = false + } commit := CommitQualityHold(verdict, qualityAccountAttempts-1, holdCfg.MaxAttempts, hasNextAccount, holdCfg.OnExhausted) if verdict == QualityWithhold { s.applyMissingThinkingPenalty(ctx, input.RequestID, credential, holdCfg.AccountCooldown) From 318c2dacd708b84a8d9d089141a9fb813f28f8b9 Mon Sep 17 00:00:00 2001 From: lij768423-svg Date: Fri, 28 Aug 2026 01:40:40 +0800 Subject: [PATCH 05/12] fix: withhold stub-only thinking when hold expires with enough output A reasoning item start plus visible tokens at the deadline is not late ciphertext. Treat it as missing thinking and rotate, matching the TUI dump after 30s. --- .../internal/application/gateway/quality_retry.go | 13 ++++--------- .../application/gateway/quality_retry_test.go | 6 +++--- 2 files changed, 7 insertions(+), 12 deletions(-) diff --git a/backend/internal/application/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go index 7eb4fc6f..bf2cd7a6 100644 --- a/backend/internal/application/gateway/quality_retry.go +++ b/backend/internal/application/gateway/quality_retry.go @@ -181,11 +181,9 @@ func qualityIsBurstDump(sig QualityStreamSignals, minOutput int64) bool { // more bytes or a stream abort so an empty hang is not flushed as HTTP 200. // // An empty reasoning stub is not thinking. Before the hold deadline, wait for -// real evidence or a terminal event. If the deadline expires while the stream -// is still open and already has visible output, the result is inconclusive: -// release it without penalizing the account. A stub-only empty stream keeps -// waiting for idle/terminal handling. This keeps HoldTimeout a real latency -// bound without reopening the empty-stream 200 response path. +// real evidence or a terminal event. A stub plus enough visible output at the +// deadline is withheld — that is the TUI dump after 30s, not late ciphertext. +// Stub-only empty streams keep waiting for idle/terminal handling. // HasThinking that is only a thin ciphertext dump after the hold (or a // barely-over-floor flush in <1s) is still withheld. func ClassifyQualityHold(sig QualityStreamSignals, minOutput int64) QualityVerdict { @@ -207,10 +205,7 @@ func ClassifyQualityHold(sig QualityStreamSignals, minOutput int64) QualityVerdi output = sig.OutputTokens } enough := output >= minOutput - if sig.ReasoningStarted && !sig.Terminal { - if sig.HoldExpired && output > 0 { - return QualityDeliver - } + if sig.ReasoningStarted && !sig.Terminal && !sig.HoldExpired { return QualityWait } if sig.Terminal { diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go index 190f6be6..f0528883 100644 --- a/backend/internal/application/gateway/quality_retry_test.go +++ b/backend/internal/application/gateway/quality_retry_test.go @@ -41,7 +41,7 @@ func TestClassifyQualityHold(t *testing.T) { {name: "empty terminal waits for transport handling", sig: QualityStreamSignals{Terminal: true}, want: QualityWait}, {name: "midstream enough content withhold", sig: QualityStreamSignals{VisibleTokens: 64}, want: QualityWithhold}, {name: "stub midstream waits even with enough visible", sig: QualityStreamSignals{ReasoningStarted: true, VisibleTokens: 64}, want: QualityWait}, - {name: "stub hold expiry is inconclusive and delivers", sig: QualityStreamSignals{ReasoningStarted: true, VisibleTokens: 64, HoldExpired: true}, want: QualityDeliver}, + {name: "stub hold expiry with enough visible withholds", sig: QualityStreamSignals{ReasoningStarted: true, VisibleTokens: 64, HoldExpired: true}, want: QualityWithhold}, {name: "stub-only hold expiry keeps waiting", sig: QualityStreamSignals{ReasoningStarted: true, HoldExpired: true}, want: QualityWait}, {name: "stub terminal enough withhold", sig: QualityStreamSignals{ReasoningStarted: true, VisibleTokens: 64, Terminal: true}, want: QualityWithhold}, {name: "wait for more", sig: QualityStreamSignals{VisibleTokens: 8}, want: QualityWait}, @@ -732,8 +732,8 @@ func TestPeekQualityStreamHoldTimeoutDeliversStartedReasoningAndPreservesLateEvi if elapsed := time.Since(started); elapsed < 20*time.Millisecond || elapsed > 200*time.Millisecond { t.Fatalf("peek returned after %s, want the 30ms hold timeout", elapsed) } - if verdict != QualityDeliver { - t.Fatalf("started reasoning at hold timeout verdict = %s, want deliver", verdict) + if verdict != QualityWithhold { + t.Fatalf("started reasoning stub at hold timeout verdict = %s, want withhold", verdict) } close(continueWrite) body, err := io.ReadAll(replay) From 7b2cba3f438529500009427152d274551f2cca2e Mon Sep 17 00:00:00 2001 From: lij768423-svg Date: Fri, 28 Aug 2026 09:12:58 +0800 Subject: [PATCH 06/12] fix: withhold floor-met thinking that dumps a short answer in under 1s Encrypted_content can clear the byte floor while usage still bills hundreds of reasoning tokens against a few visible tokens. Treat that fast dump as missing thinking even before the hold deadline. --- .../internal/application/gateway/quality_retry.go | 11 +++++++++-- .../application/gateway/quality_retry_test.go | 15 +++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/backend/internal/application/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go index bf2cd7a6..50aea410 100644 --- a/backend/internal/application/gateway/quality_retry.go +++ b/backend/internal/application/gateway/quality_retry.go @@ -159,12 +159,19 @@ func qualityIsBurstDump(sig QualityStreamSignals, minOutput int64) bool { floor := encryptedThinkingFloor(0, 0, sig.ReasoningTokens) barelyCipher := sig.EncryptedBytes > 0 && sig.EncryptedBytes < floor*2 flushed := sig.FirstVisible && sig.VisibleFlushMS >= 0 && sig.VisibleFlushMS < defaultBurstFlushMS + heavyReasoning := sig.ReasoningTokens >= defaultBurstMinReasoning + shortVisible := visible > 0 && visible < defaultBurstMaxVisible // Hold timed out, then a short greeting dumped with a large reasoning bill // (TUI "你好" after 30s / 954 thinking tokens). - if sig.HoldExpired && visible > 0 && visible < defaultBurstMaxVisible && sig.ReasoningTokens >= defaultBurstMinReasoning { + if sig.HoldExpired && shortVisible && heavyReasoning { return true } - if barelyCipher && flushed && (visible >= minOutput || sig.ReasoningTokens >= defaultBurstMinReasoning) { + // Cipher met the floor so HasThinking is true, but visible tokens then + // dump in <1s with almost no answer (148 out / 140 reasoning in 0.7s). + if flushed && shortVisible && heavyReasoning { + return true + } + if barelyCipher && flushed && (visible >= minOutput || heavyReasoning) { return true } return false diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go index f0528883..93bd6537 100644 --- a/backend/internal/application/gateway/quality_retry_test.go +++ b/backend/internal/application/gateway/quality_retry_test.go @@ -86,6 +86,21 @@ func TestClassifyQualityHoldBurst(t *testing.T) { sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 50, ReasoningTokens: 60, EncryptedBytes: 2000, FirstVisible: true, VisibleFlushMS: 100}, want: QualityDeliver, }, + { + name: "floor-met short visible fast dump withholds", + sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 3, ReasoningTokens: 1371, EncryptedBytes: 8000, FirstVisible: true, VisibleFlushMS: 200}, + want: QualityWithhold, + }, + { + name: "floor-met 8 visible 140 reasoning in under 1s withholds", + sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 8, ReasoningTokens: 140, EncryptedBytes: 2000, FirstVisible: true, VisibleFlushMS: 660}, + want: QualityWithhold, + }, + { + name: "floor-met long visible fast flush delivers", + sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 80, ReasoningTokens: 140, EncryptedBytes: 2000, FirstVisible: true, VisibleFlushMS: 200}, + want: QualityDeliver, + }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { From 31557e80890208cb241a85f206c436d0ee3096ac Mon Sep 17 00:00:00 2001 From: lij768423-svg Date: Fri, 28 Aug 2026 11:37:37 +0800 Subject: [PATCH 07/12] docs: match requestRetry comments to TUI hold and stub withhold enabled stays false. A stub plus visible output at the deadline is withheld, not released as late ciphertext. Floor-met short dumps and previous_response_id / hosted-tool turns are held when intercept is on. --- README.md | 7 ++++--- README.zh-CN.md | 6 +++--- config.example.yaml | 10 ++++++---- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 616cd3c1..44bd4dc8 100644 --- a/README.md +++ b/README.md @@ -369,8 +369,9 @@ qualityGuard: enabled: true model: "grok-4.6" # Withhold thinking-model streams that have no streamed reasoning. - # Observe for up to 30s. An open stream with a reasoning start and visible - # output is released at the deadline; empty/terminal failures still retry. + # Observe for up to 30s. A stub plus enough visible output at the deadline + # is withheld; empty stub-only streams keep waiting. Floor-met dumps that + # flush a short greeting in under 1s are also withheld. requestRetry: enabled: true maxAttempts: 6 @@ -381,7 +382,7 @@ qualityGuard: idleAccountCooldown: 15m ``` -`requestRetry` runs on the gateway request path and is independent of the sidecar. The example enables it. When enabled, a thinking-model stream with enough visible output and no streamed reasoning is **not delivered**; another account is tried. If every attempt still has no reasoning, `onExhausted` either returns `503 quality_degraded` or delivers the last body. Image, video, stored-response, and ForcedEgress probe requests are unchanged. Grok TUI tool turns stay held so 0-thinking dumps cannot skip the gate. +`requestRetry` runs on the gateway request path and is independent of the sidecar. `config.example.yaml` keeps `enabled: false`; set it true to intercept. When enabled, a thinking-model stream with enough visible output and no streamed reasoning is **not delivered**; another account is tried. TUI follow-ups (`previous_response_id`) and hosted-tool turns stay held — the first attempt stays pinned, a withhold unpins and rotates. Image, video, and ForcedEgress probe requests are unchanged. If every attempt still has no reasoning, `onExhausted` either returns `503 quality_degraded` or delivers the last body. ```bash docker compose --profile quality-guard up -d --build diff --git a/README.zh-CN.md b/README.zh-CN.md index 94de403b..41437d5f 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -365,8 +365,8 @@ qualityGuard: enabled: true model: "grok-4.6" # 思考模型缺流式 reasoning 时先扣住响应,换号再打,不把降智正文发给用户。 - # 最多观察 30 秒;已有 reasoning 起始信号和可见输出的进行中流会在超时后放行, - # 空流和终态仍无 thinking 的响应继续换号。 + # 最多观察 30 秒;stub 加上足够可见输出在超时后扣住(TUI 30s 后的短问候), + # 空 stub 继续等。floor 已达标但 1 秒内吐短回复的也扣。 requestRetry: enabled: true maxAttempts: 6 @@ -377,7 +377,7 @@ qualityGuard: idleAccountCooldown: 15m ``` -`requestRetry` 在网关请求路径上生效,与 sidecar 探测/隔离相互独立。示例配置默认开启。开启后,可见输出达到 `minOutputTokens` 且全程无流式 reasoning 时**不发给用户**,排除该账号再试;全部仍无推理则按 `onExhausted` 返回 `503 quality_degraded` 或放出最后一枪。不处理图/视频、stored response 钉账号和 ForcedEgress 探针。Grok TUI 带 tools 的回合仍会 hold,避免 0-thinking 降智流跳过闸门。 +`requestRetry` 在网关请求路径上生效,与 sidecar 探测/隔离相互独立。`config.example.yaml` 里 `enabled` 仍为 false,打开后才拦截。开启后,可见输出达到 `minOutputTokens` 且全程无流式 reasoning 时**不发给用户**,排除该账号再试。TUI 续聊(`previous_response_id`)和 hosted tools 仍 hold:第一枪钉原账号,扣住后 unpin 换号。不处理图/视频和 ForcedEgress 探针。全部仍无推理则按 `onExhausted` 返回 `503 quality_degraded` 或放出最后一枪。 ```bash docker compose --profile quality-guard up -d --build diff --git a/config.example.yaml b/config.example.yaml index a1ea8cc8..2f6942a8 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -152,10 +152,12 @@ qualityGuard: # Optional request-path withhold/retry for thinking models. # Recommended lab values are filled in; enabled stays false so stock # installs do not intercept. Set enabled: true to turn the hold on. - # Observe up to 30s for real reasoning evidence. If upstream has announced - # a reasoning item and visible output but proof arrives later, the still-open - # stream is released at the deadline without penalizing the account. Empty or - # terminal no-thinking responses are still retried. + # Observe up to 30s for real reasoning evidence. A reasoning-item stub plus + # enough visible output at the deadline is withheld (TUI dump after 30s), + # not released as late ciphertext. Empty stub-only streams keep waiting. + # Floor-met ciphertext that then dumps a short greeting in under 1s is + # also withheld. TUI follow-ups (previous_response_id) and hosted tools + # stay held; the attempt loop unpins after the first missing-thinking hit. # Missing thinking with enough visible output is not delivered; another # account is tried (up to maxAttempts). fail_closed returns 503 instead # of the last body. Sidecar qualityGuard.enabled stays false until you From c7805f823c32fe0dc8a76068358dda95d21a9e67 Mon Sep 17 00:00:00 2001 From: buddhism5080 Date: Fri, 28 Aug 2026 22:43:50 +0800 Subject: [PATCH 08/12] fix(audit): record stream failure after a prior 429 retry When the first account returns 429 and the next account's 2xx stream later fails, diagnostics previously kept only the 429 row. Always append a response_stream attempt for the handed-off account unless one is already present. --- .../internal/application/gateway/attempt.go | 35 ++++++++ .../application/gateway/attempt_test.go | 29 ++++++ .../internal/application/gateway/service.go | 22 +---- .../application/gateway/service_test.go | 90 +++++++++++++++++++ 4 files changed, 157 insertions(+), 19 deletions(-) diff --git a/backend/internal/application/gateway/attempt.go b/backend/internal/application/gateway/attempt.go index 972d198e..76663394 100644 --- a/backend/internal/application/gateway/attempt.go +++ b/backend/internal/application/gateway/attempt.go @@ -171,6 +171,41 @@ func (r *failureAttemptRecorder) captureStreamFailure(credential accountdomain.C }) } +func (r *failureAttemptRecorder) hasStreamFailureFor(accountID uint64) bool { + for _, attempt := range r.attempts { + if attempt.Stage != "response_stream" || attempt.AccountID == nil || *attempt.AccountID != accountID { + continue + } + return true + } + return false +} + +// ensureStreamFailureAttempt records the handed-off 2xx stream when it later +// fails. Prior 4xx/transport attempts must not suppress this row — otherwise +// diagnostics only show the first 429 while the list account is the retry. +func (r *failureAttemptRecorder) ensureStreamFailureAttempt(credential accountdomain.Credential, startedAt time.Time, response *provider.Response, errorCode string) { + if response == nil || r.hasStreamFailureFor(credential.ID) { + return + } + statusCode := response.StatusCode + r.append(audit.Attempt{ + Source: audit.AttemptSourceUpstreamHTTP, + Stage: "response_stream", + AccountID: auditAccountID(credential.ID), + AccountName: credential.Name, + Method: r.method, + RequestPath: r.path, + UpstreamURL: sanitizeUpstreamURL(response.UpstreamURL), + StartedAt: startedAt.UTC(), + DurationMS: time.Since(startedAt).Milliseconds(), + UpstreamStatusCode: &statusCode, + UpstreamStatus: response.Status, + ResponseHeaders: sanitizeDiagnosticHeaders(response.Header), + TransportError: errorCode, + }) +} + func (r *failureAttemptRecorder) captureQualityDegraded(credential accountdomain.Credential, startedAt time.Time) { status := http.StatusOK r.append(audit.Attempt{ diff --git a/backend/internal/application/gateway/attempt_test.go b/backend/internal/application/gateway/attempt_test.go index 98f23d26..77e9d257 100644 --- a/backend/internal/application/gateway/attempt_test.go +++ b/backend/internal/application/gateway/attempt_test.go @@ -95,6 +95,35 @@ func TestFailureAttemptRecorderCapturesStreamFailure(t *testing.T) { } } +func TestEnsureStreamFailureAttemptKeepsPrior429AndSkipsDuplicate(t *testing.T) { + recorder := newFailureAttemptRecorder(http.MethodPost, "/responses") + first := account.Credential{ID: 11, Name: "retry-a"} + second := account.Credential{ID: 12, Name: "retry-b"} + exhausted := &provider.Response{StatusCode: http.StatusTooManyRequests, Status: "Too Many Requests", Body: io.NopCloser(strings.NewReader(`{"code":"subscription:free-usage-exhausted"}`))} + if err := recorder.captureResponse(first, time.Now(), exhausted, nil); err != nil { + t.Fatal(err) + } + stream := &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: http.Header{"Content-Type": {"text/event-stream"}}, UpstreamURL: "https://cli-chat-proxy.grok.com/v1/responses"} + recorder.ensureStreamFailureAttempt(second, time.Now().Add(-time.Second), stream, "upstream_stream_interrupted") + stored := recorder.snapshot() + if len(stored) != 2 || stored[0].Stage != "upstream_response" || stored[1].Stage != "response_stream" { + t.Fatalf("attempts = %#v", stored) + } + if stored[1].AccountID == nil || *stored[1].AccountID != second.ID || stored[1].TransportError != "upstream_stream_interrupted" { + t.Fatalf("retry stream attempt = %#v", stored[1]) + } + recorder.ensureStreamFailureAttempt(second, time.Now(), stream, "upstream_stream_interrupted") + if got := recorder.snapshot(); len(got) != 2 { + t.Fatalf("duplicate stream attempt = %#v", got) + } + inStream := newFailureAttemptRecorder(http.MethodPost, "/responses") + inStream.captureStreamFailure(second, time.Now(), stream, StreamFailureDiagnostic{Body: []byte(`{"type":"response.failed"}`)}) + inStream.ensureStreamFailureAttempt(second, time.Now(), stream, "upstream_stream_error") + if got := inStream.snapshot(); len(got) != 1 || got[0].Stage != "response_stream" { + t.Fatalf("ensure after in-stream capture = %#v", got) + } +} + func TestFailureAttemptRecorderClassifiesTransportErrorChain(t *testing.T) { dnsErr := &net.DNSError{Err: "no such host", Name: "api.example.test", IsNotFound: true} requestErr := &url.Error{Op: "Post", URL: "https://user:password@api.example.test/v1/responses?token=secret", Err: dnsErr} diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index e6b99685..ea693ec9 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -1118,26 +1118,10 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string } record.DurationMS = time.Since(startedAt).Milliseconds() record.ErrorCode = errorCode - attempts := failureAttempts.snapshot() - if !successful && len(attempts) == 0 { - statusCode := response.StatusCode - failureAttempts.append(audit.Attempt{ - Source: audit.AttemptSourceUpstreamHTTP, - Stage: "response_stream", - AccountID: auditAccountID(credential.ID), - AccountName: credential.Name, - Method: http.MethodPost, - RequestPath: sanitizeRequestPath(path), - UpstreamURL: sanitizeUpstreamURL(response.UpstreamURL), - StartedAt: upstreamStartedAt.UTC(), - DurationMS: time.Since(upstreamStartedAt).Milliseconds(), - UpstreamStatusCode: &statusCode, - UpstreamStatus: response.Status, - ResponseHeaders: sanitizeDiagnosticHeaders(response.Header), - TransportError: errorCode, - }) - attempts = failureAttempts.snapshot() + if !successful { + failureAttempts.ensureStreamFailureAttempt(credential, upstreamStartedAt, response, errorCode) } + attempts := failureAttempts.snapshot() if !successful || len(attempts) > 0 { record.Attempts = attempts } diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index f7f5c07e..89ee48b2 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -3492,6 +3492,96 @@ func TestGatewayGeneric429CoolsAccountAndRotates(t *testing.T) { } } +func TestGatewayRetryStreamFailureRecordsPrior429AndRetryStream(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "retry-stream-failure.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accountRepo := relational.NewAccountRepository(database) + modelRepo := relational.NewModelRepository(database) + auditRepo := relational.NewAuditRepository(database) + responseRepo := relational.NewResponseRepository(database) + keyRepo := relational.NewClientKeyRepository(database) + + credentials := make([]account.Credential, 0, 2) + for index, name := range []string{"retry-a", "retry-b"} { + credential, _, createErr := accountRepo.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, Name: name, SourceKey: name, EncryptedAccessToken: name, + ExpiresAt: time.Now().Add(time.Hour), Enabled: true, AuthStatus: account.AuthStatusActive, + Priority: 200 - index, MaxConcurrent: 1, + }) + if createErr != nil { + t.Fatal(createErr) + } + credentials = append(credentials, credential) + } + if err := modelRepo.UpsertDiscovered(ctx, account.ProviderBuild, []string{"grok-retry-stream"}); err != nil { + t.Fatal(err) + } + for _, credential := range credentials { + if err := modelRepo.ReplaceAccountCapabilities(ctx, credential.ID, []string{"grok-retry-stream"}, time.Now().UTC()); err != nil { + t.Fatal(err) + } + } + clientKey, err := keyRepo.Create(ctx, clientkey.Key{ + Name: "retry-stream-key", Prefix: "retrystream", SecretHash: strings.Repeat("4", 64), EncryptedSecret: "encrypted", + Enabled: true, RPMLimit: 120, MaxConcurrent: 8, + }) + if err != nil { + t.Fatal(err) + } + exhausted := `{"code":"subscription:free-usage-exhausted","error":"You've used all the included free usage for model grok-4.6 for now. Usage resets over a rolling 24-hour window — tokens (actual/limit): 558975/500000."}` + adapter := &scriptedBuildAdapter{responses: map[uint64][]scriptedBuildResponse{ + credentials[0].ID: {{status: http.StatusTooManyRequests, body: exhausted}}, + credentials[1].ID: {{status: http.StatusOK, header: http.Header{"Content-Type": {"text/event-stream"}}, body: "data: {\"type\":\"response.created\"}\n\n"}}, + }} + registry := provider.NewRegistry(adapter) + sticky := memory.NewStickyStore() + accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil) + selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute) + service := NewService(modelRepo, auditRepo, accountService, clientkeyapp.NewService(nil, nil, nil, 60, 4, nil), registry, selector, responseRepo, 3) + + result, err := service.CreateResponse(ctx, Input{ + RequestID: "req-retry-stream", ClientKey: clientKey, PublicModel: "grok-retry-stream", + Body: []byte(`{"model":"grok-retry-stream","input":"hello"}`), Streaming: true, + }) + if err != nil { + t.Fatal(err) + } + result.Finalize(Usage{}, "", "upstream_stream_interrupted") + _ = result.Body.Close() + if attempts := adapter.Attempts(); len(attempts) != 2 || attempts[0] != credentials[0].ID || attempts[1] != credentials[1].ID { + t.Fatalf("429 must rotate before stream failure, attempts=%#v", attempts) + } + + logs, _, err := auditRepo.List(ctx, 0, 10) + if err != nil || len(logs) == 0 { + t.Fatalf("audits = %#v, err = %v", logs, err) + } + detail, err := auditRepo.Get(ctx, logs[0].ID) + if err != nil { + t.Fatal(err) + } + if detail.ErrorCode != "upstream_stream_interrupted" || detail.AccountID == nil || *detail.AccountID != credentials[1].ID { + t.Fatalf("audit = %#v", detail) + } + if detail.AttemptCount != 2 || len(detail.Attempts) != 2 { + t.Fatalf("attempt count = %d stored = %d, attempts=%#v", detail.AttemptCount, len(detail.Attempts), detail.Attempts) + } + first, second := detail.Attempts[0], detail.Attempts[1] + if first.Stage != "upstream_response" || first.UpstreamStatusCode == nil || *first.UpstreamStatusCode != http.StatusTooManyRequests || first.AccountID == nil || *first.AccountID != credentials[0].ID { + t.Fatalf("first attempt = %#v", first) + } + if second.Stage != "response_stream" || second.UpstreamStatusCode == nil || *second.UpstreamStatusCode != http.StatusOK || second.AccountID == nil || *second.AccountID != credentials[1].ID || second.TransportError != "upstream_stream_interrupted" { + t.Fatalf("retry stream attempt = %#v", second) + } +} + func TestGatewayNonAccount5xxSoftCoolsAndRotates(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "soft-5xx.db")) From 7caa52c14fd80e3012356bb058ad0b45a6ad71c2 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Mon, 31 Aug 2026 09:40:39 +0800 Subject: [PATCH 09/12] fix: preserve upstream outcomes during reasoning recovery --- .../application/gateway/failure_test.go | 21 ++- .../internal/application/gateway/service.go | 14 +- .../internal/infra/provider/cli/adapter.go | 14 +- .../cli/responses_codex_tools_test.go | 4 +- .../infra/provider/cli/responses_history.go | 2 +- .../cli/responses_reasoning_recovery.go | 82 ++++++----- .../cli/responses_reasoning_recovery_test.go | 129 ++++++++++++++++-- backend/internal/infra/provider/provider.go | 4 + 8 files changed, 191 insertions(+), 79 deletions(-) diff --git a/backend/internal/application/gateway/failure_test.go b/backend/internal/application/gateway/failure_test.go index 0a384d4f..b93aff5d 100644 --- a/backend/internal/application/gateway/failure_test.go +++ b/backend/internal/application/gateway/failure_test.go @@ -243,17 +243,30 @@ func TestHTTPUpstreamFailureLeavesPaymentRecoveryKindToBilling(t *testing.T) { } } -func TestRetryableResponseRotatesOnlyOnReasoningRecoveryFailedWarning(t *testing.T) { +func TestRetryableResponseRotatesOnlyOnInternalBuildReasoningRecoveryFailure(t *testing.T) { failedHeader := make(http.Header) failedHeader.Set("X-Grok2API-Compatibility-Warnings", "reasoning_encrypted_content_downgraded,reasoning_recovery_failed") failed := &provider.Response{ - StatusCode: http.StatusBadRequest, - Header: failedHeader, - Body: io.NopCloser(strings.NewReader(`{"error":"Could not decode the compaction blob"}`)), + StatusCode: http.StatusBadRequest, + Header: failedHeader, + Body: io.NopCloser(strings.NewReader(`{"error":"Could not decode the compaction blob"}`)), + ReasoningRecoveryFailed: true, } if !isRetryableResponse(failed, accountdomain.ProviderBuild) { t.Fatal("reasoning_recovery_failed 400 must rotate accounts") } + if isRetryableResponse(failed, accountdomain.ProviderWeb) { + t.Fatal("reasoning recovery failover must remain Build-specific") + } + + spoofed := &provider.Response{ + StatusCode: http.StatusBadRequest, + Header: failedHeader, + Body: io.NopCloser(strings.NewReader(`{"error":"unrelated bad request"}`)), + } + if isRetryableResponse(spoofed, accountdomain.ProviderBuild) { + t.Fatal("an upstream-controlled compatibility warning must not trigger account rotation") + } plain := &provider.Response{ StatusCode: http.StatusBadRequest, diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index 1224b3f2..566f9ac9 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -2092,23 +2092,15 @@ func isRetryable(status int) bool { return status == 402 || status == 403 || status == 429 || status >= 500 } -func isReasoningRecoveryFailedResponse(response *provider.Response) bool { - if response == nil { - return false - } - for _, value := range strings.Split(response.Header.Get("X-Grok2API-Compatibility-Warnings"), ",") { - if strings.TrimSpace(value) == "reasoning_recovery_failed" { - return true - } - } - return false +func isReasoningRecoveryFailedResponse(response *provider.Response, upstreamProvider accountdomain.Provider) bool { + return upstreamProvider == accountdomain.ProviderBuild && response != nil && response.ReasoningRecoveryFailed } func isRetryableResponse(response *provider.Response, upstreamProvider accountdomain.Provider) bool { if response == nil { return false } - if response.StatusCode == http.StatusBadRequest && isReasoningRecoveryFailedResponse(response) { + if response.StatusCode == http.StatusBadRequest && isReasoningRecoveryFailedResponse(response, upstreamProvider) { return true } if !isRetryable(response.StatusCode) { diff --git a/backend/internal/infra/provider/cli/adapter.go b/backend/internal/infra/provider/cli/adapter.go index 7e5dfbd9..8bfe22f8 100644 --- a/backend/internal/infra/provider/cli/adapter.go +++ b/backend/internal/infra/provider/cli/adapter.go @@ -328,7 +328,11 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response if err := normalizeGzipResponse(resp); err != nil { return nil, err } - resp, reqURL, reasoningRecovery := a.recoverReasoningDecodeFailure(ctx, request, accessToken, body, base, replayKey, resp, reqURL) + var reasoningRecovery reasoningRecoveryOutcome + resp, reqURL, reasoningRecovery, err = a.recoverReasoningDecodeFailure(ctx, request, accessToken, body, base, replayKey, resp, reqURL) + if err != nil { + return nil, err + } var recoveredPrimaryFailure *provider.DiagnosticResponse // Only eligible operations probe XAI with an equivalent request after the Build primary explicitly returns 403. if strings.EqualFold(base, primaryBase) && shouldProbeXAIInferenceFallback(request.Credential, request.Billing, request.Method, request.Path, resp.StatusCode) { @@ -352,7 +356,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response } fallbackRecovery := reasoningRecoveryOutcome{} if fallbackErr == nil { - fallbackResp, fallbackURL, fallbackRecovery = a.recoverReasoningDecodeFailure(ctx, request, accessToken, fallbackBody, fallbackBase, fallbackReplayKey, fallbackResp, fallbackURL) + fallbackResp, fallbackURL, fallbackRecovery, fallbackErr = a.recoverReasoningDecodeFailure(ctx, request, accessToken, fallbackBody, fallbackBase, fallbackReplayKey, fallbackResp, fallbackURL) } if fallbackErr == nil && isHTTPSuccess(fallbackResp.StatusCode) { recoveredPrimaryFailure = bufferedFailureDiagnostic(primaryResp, primaryBody, primaryTruncated) @@ -471,15 +475,15 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response if diagnostic == nil { return nil, convertErr } - return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: diagnostic.Header.Clone(), Body: io.NopCloser(bytes.NewReader(data)), UpstreamURL: reqURL, Diagnostic: diagnostic, RecoveredPrimaryFailure: recoveredPrimaryFailure, RateLimit: rateLimit, ModelCatalogChanged: modelCatalogChanged}, nil + return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: diagnostic.Header.Clone(), Body: io.NopCloser(bytes.NewReader(data)), UpstreamURL: reqURL, Diagnostic: diagnostic, ReasoningRecoveryFailed: reasoningRecovery.failed, RecoveredPrimaryFailure: recoveredPrimaryFailure, RateLimit: rateLimit, ModelCatalogChanged: modelCatalogChanged}, nil } resp.Body = io.NopCloser(bytes.NewReader(converted)) resp.Header.Set("Content-Length", strconv.Itoa(len(converted))) resp.Header.Set("Content-Type", "application/json") - return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: resp.Header.Clone(), Body: resp.Body, UpstreamURL: reqURL, Diagnostic: diagnostic, RecoveredPrimaryFailure: recoveredPrimaryFailure, RateLimit: rateLimit, ModelCatalogChanged: modelCatalogChanged}, nil + return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: resp.Header.Clone(), Body: resp.Body, UpstreamURL: reqURL, Diagnostic: diagnostic, ReasoningRecoveryFailed: reasoningRecovery.failed, RecoveredPrimaryFailure: recoveredPrimaryFailure, RateLimit: rateLimit, ModelCatalogChanged: modelCatalogChanged}, nil } } - return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: resp.Header.Clone(), Body: resp.Body, UpstreamURL: reqURL, Diagnostic: rateLimitDiagnostic, RecoveredPrimaryFailure: recoveredPrimaryFailure, RateLimit: rateLimit, ModelCatalogChanged: modelCatalogChanged}, nil + return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: resp.Header.Clone(), Body: resp.Body, UpstreamURL: reqURL, Diagnostic: rateLimitDiagnostic, ReasoningRecoveryFailed: reasoningRecovery.failed, RecoveredPrimaryFailure: recoveredPrimaryFailure, RateLimit: rateLimit, ModelCatalogChanged: modelCatalogChanged}, nil } func (a *Adapter) shouldCaptureReplay(request provider.ResponseResourceRequest, resp *http.Response, replayKey string) bool { diff --git a/backend/internal/infra/provider/cli/responses_codex_tools_test.go b/backend/internal/infra/provider/cli/responses_codex_tools_test.go index 44186ee3..2e68f2b6 100644 --- a/backend/internal/infra/provider/cli/responses_codex_tools_test.go +++ b/backend/internal/infra/provider/cli/responses_codex_tools_test.go @@ -421,10 +421,10 @@ func TestReasoningWithoutEncryptedContentBecomesPortableSummary(t *testing.T) { } items := request["input"].([]any) first := items[0].(map[string]any) - if first["type"] != "message" || first["role"] != "developer" { + if first["type"] != "message" || first["role"] != "assistant" { t.Fatalf("unencrypted reasoning should become portable summary, got %#v", first) } - text := first["content"].([]any)[0].(map[string]any)["text"].(string) + text := first["content"].(string) if !strings.Contains(text, "who am I") || strings.Contains(text, "omitted") { t.Fatalf("portable reasoning text = %q", text) } diff --git a/backend/internal/infra/provider/cli/responses_history.go b/backend/internal/infra/provider/cli/responses_history.go index 070bdbf6..9d470d2b 100644 --- a/backend/internal/infra/provider/cli/responses_history.go +++ b/backend/internal/infra/provider/cli/responses_history.go @@ -260,7 +260,7 @@ func (c *responsesToolCompatibility) normalizeCustomToolCallInput(item map[strin func sanitizeReasoningInput(item map[string]any) map[string]any { // Keep ciphertext-backed reasoning native. Summary-only items are rewritten - // as developer messages so the readable plan survives without sending a + // as assistant messages so the readable plan survives without sending a // bare type=reasoning item that Grok Build may reject. converted := copyNonNullHistoryFields(item, "id", "summary", "content", "encrypted_content") converted["type"] = "reasoning" diff --git a/backend/internal/infra/provider/cli/responses_reasoning_recovery.go b/backend/internal/infra/provider/cli/responses_reasoning_recovery.go index 427a9914..c1854c03 100644 --- a/backend/internal/infra/provider/cli/responses_reasoning_recovery.go +++ b/backend/internal/infra/provider/cli/responses_reasoning_recovery.go @@ -48,7 +48,7 @@ func (o reasoningRecoveryOutcome) appendWarnings(header http.Header) { // pre-generation opaque-reasoning decode rejection. Recovery never changes // credential or Build/XAI plane: // 1. remove replayed encrypted_content, keep any readable summary as a -// portable developer message, and retry in the same session; +// portable assistant message, and retry in the same session; // 2. when a 400 remains (or no opaque item exists), clear the server-side // session identity and retry once with the full portable input. // @@ -64,18 +64,18 @@ func (a *Adapter) recoverReasoningDecodeFailure( replayKey string, response *http.Response, requestURL string, -) (*http.Response, string, reasoningRecoveryOutcome) { +) (*http.Response, string, reasoningRecoveryOutcome, error) { if response == nil || response.StatusCode != http.StatusBadRequest { - return response, requestURL, reasoningRecoveryOutcome{} + return response, requestURL, reasoningRecoveryOutcome{}, nil } errorBody, truncated, err := provider.ReadDiagnosticBody(response.Body) _ = response.Body.Close() if err != nil { - return cloneBufferedResponse(response, errorBody, truncated), requestURL, reasoningRecoveryOutcome{} + return cloneBufferedResponse(response, errorBody, truncated), requestURL, reasoningRecoveryOutcome{}, nil } original := cloneBufferedResponse(response, errorBody, truncated) if truncated || !isReasoningDecodeFailure(errorBody) { - return original, requestURL, reasoningRecoveryOutcome{} + return original, requestURL, reasoningRecoveryOutcome{}, nil } // 一旦上游明确拒绝 opaque reasoning,立即清理该账号/平面的服务端回放, // 防止下次请求再次注入同一份已失效密文。成功响应会按正常 Capture 流程写回新状态。 @@ -88,34 +88,30 @@ func (a *Adapter) recoverReasoningDecodeFailure( retry, retryURL, retryErr := a.retryReasoningRecovery(ctx, request, accessToken, portableBody, base, false) if retryErr != nil { a.logReasoningRecovery(request, base, "encrypted_content", "transport_failed", 0, retryErr) - return original, requestURL, reasoningRecoveryOutcome{failed: true} + _ = original.Body.Close() + return nil, requestURL, reasoningRecoveryOutcome{}, retryErr } if err := normalizeGzipResponse(retry); err != nil { _ = retry.Body.Close() a.logReasoningRecovery(request, base, "encrypted_content", "response_decode_failed", retry.StatusCode, err) - return original, requestURL, reasoningRecoveryOutcome{failed: true} - } - if isHTTPSuccess(retry.StatusCode) { _ = original.Body.Close() - a.logReasoningRecovery(request, base, "encrypted_content", "recovered", retry.StatusCode, nil) - return retry, retryURL, reasoningRecoveryOutcome{encryptedContentDowngraded: true} + return nil, retryURL, reasoningRecoveryOutcome{}, err } - if retry.StatusCode == http.StatusTooManyRequests { - // 去除失效密文后得到的 429 是当前账号的真实上游状态。保留它, - // 让网关进行账号冷却和切换,不能回退成已无效的初始解码 400。 + if retry.StatusCode != http.StatusBadRequest { _ = original.Body.Close() - a.logReasoningRecovery(request, base, "encrypted_content", "rate_limited", retry.StatusCode, nil) - return retry, retryURL, reasoningRecoveryOutcome{encryptedContentDowngraded: true} + result := "retry_response" + if isHTTPSuccess(retry.StatusCode) { + result = "recovered" + } + a.logReasoningRecovery(request, base, "encrypted_content", result, retry.StatusCode, nil) + return retry, retryURL, reasoningRecoveryOutcome{encryptedContentDowngraded: true}, nil } retryStatus := retry.StatusCode sameDecodeFailure, inspectErr := responseHasReasoningDecodeFailure(retry) if inspectErr != nil { a.logReasoningRecovery(request, base, "encrypted_content", "retry_rejected", retryStatus, inspectErr) - return original, requestURL, reasoningRecoveryOutcome{failed: true} - } - if retryStatus != http.StatusBadRequest { - a.logReasoningRecovery(request, base, "encrypted_content", "retry_rejected", retryStatus, nil) - return original, requestURL, reasoningRecoveryOutcome{failed: true} + _ = original.Body.Close() + return nil, retryURL, reasoningRecoveryOutcome{}, inspectErr } if sameDecodeFailure { a.logReasoningRecovery(request, base, "encrypted_content", "decode_error_persisted", retryStatus, nil) @@ -128,42 +124,37 @@ func (a *Adapter) recoverReasoningDecodeFailure( if !canResetReasoningSession(request, portableBody) { a.logReasoningRecovery(request, base, "session_reset", "not_safe", 0, nil) - return original, requestURL, reasoningRecoveryOutcome{failed: true} + return original, requestURL, reasoningRecoveryOutcome{failed: true}, nil } statelessBody := removePromptCacheKey(portableBody) retry, retryURL, retryErr := a.retryReasoningRecovery(ctx, request, accessToken, statelessBody, base, true) if retryErr != nil { a.logReasoningRecovery(request, base, "session_reset", "transport_failed", 0, retryErr) - return original, requestURL, reasoningRecoveryOutcome{failed: true} + _ = original.Body.Close() + return nil, requestURL, reasoningRecoveryOutcome{}, retryErr } if err := normalizeGzipResponse(retry); err != nil { _ = retry.Body.Close() a.logReasoningRecovery(request, base, "session_reset", "response_decode_failed", retry.StatusCode, err) - return original, requestURL, reasoningRecoveryOutcome{failed: true} - } - if retry.StatusCode == http.StatusTooManyRequests { - // 无状态恢复也可能命中当前账号的真实限流。与去密文恢复保持一致, - // 必须把 429 交回网关,才能执行账号冷却和候选账号切换。 _ = original.Body.Close() - a.logReasoningRecovery(request, base, "session_reset", "rate_limited", retry.StatusCode, nil) + return nil, retryURL, reasoningRecoveryOutcome{}, err + } + if retry.StatusCode != http.StatusBadRequest { + _ = original.Body.Close() + result := "retry_response" + if isHTTPSuccess(retry.StatusCode) { + result = "recovered" + } + a.logReasoningRecovery(request, base, "session_reset", result, retry.StatusCode, nil) return retry, retryURL, reasoningRecoveryOutcome{ encryptedContentDowngraded: encryptedChanged, sessionReset: true, - } - } - if !isHTTPSuccess(retry.StatusCode) { - status := retry.StatusCode - _ = retry.Body.Close() - a.logReasoningRecovery(request, base, "session_reset", "retry_rejected", status, nil) - return original, requestURL, reasoningRecoveryOutcome{failed: true} + }, nil } - _ = original.Body.Close() - a.logReasoningRecovery(request, base, "session_reset", "recovered", retry.StatusCode, nil) - return retry, retryURL, reasoningRecoveryOutcome{ - encryptedContentDowngraded: encryptedChanged, - sessionReset: true, - } + _ = retry.Body.Close() + a.logReasoningRecovery(request, base, "session_reset", "retry_rejected", retry.StatusCode, nil) + return original, requestURL, reasoningRecoveryOutcome{failed: true}, nil } func (a *Adapter) retryReasoningRecovery(ctx context.Context, request provider.ResponseResourceRequest, accessToken string, body []byte, base string, resetSession bool) (*http.Response, string, error) { @@ -255,7 +246,7 @@ func isReasoningDecodeFailure(body []byte) bool { // stripReasoningEncryptedContent removes undecodable opaque reasoning and // compaction ciphertext so Grok Build does not fail on server-side decryption. -// Readable reasoning summaries are kept as portable developer messages; empty +// Readable reasoning summaries are kept as portable assistant messages; empty // encrypted-only reasoning items are dropped. Foreign compaction blobs become // a boundary note because this gateway cannot decrypt them. func stripReasoningEncryptedContent(body []byte) ([]byte, bool) { @@ -318,7 +309,10 @@ func portableReasoningSummaryMessage(item map[string]any) (map[string]any, bool) if text == "" { return nil, false } - return compatibilityBoundaryMessage("Prior model reasoning summary:\n" + text), true + return map[string]any{ + "type": "message", "role": "assistant", + "content": "Prior model reasoning summary:\n" + text, + }, true } func reasoningPortableText(item map[string]any) string { diff --git a/backend/internal/infra/provider/cli/responses_reasoning_recovery_test.go b/backend/internal/infra/provider/cli/responses_reasoning_recovery_test.go index a11d6384..888979bb 100644 --- a/backend/internal/infra/provider/cli/responses_reasoning_recovery_test.go +++ b/backend/internal/infra/provider/cli/responses_reasoning_recovery_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/base64" "encoding/json" + "errors" "io" "net/http" "strings" @@ -38,10 +39,10 @@ func TestStripReasoningEncryptedContentPreservesOnlyPortableHistory(t *testing.T t.Fatalf("downgraded = %s, len=%d", downgraded, len(payload.Input)) } summary := payload.Input[0] - if summary["type"] != "message" || summary["role"] != "developer" { + if summary["type"] != "message" || summary["role"] != "assistant" { t.Fatalf("readable reasoning = %#v", summary) } - summaryText, _ := summary["content"].([]any)[0].(map[string]any)["text"].(string) + summaryText, _ := summary["content"].(string) if !strings.Contains(summaryText, "readable") || strings.Contains(summaryText, "omitted") { t.Fatalf("readable reasoning text = %q", summaryText) } @@ -180,6 +181,50 @@ func TestRecoverReasoningDecodeFailureStaysOnXAIFallbackPlane(t *testing.T) { } } +func TestRecoverReasoningDecodeFailureLetsRecoveredForbiddenReachPlaneFallback(t *testing.T) { + adapter, encrypted := newReasoningRecoveryTestAdapter(t) + adapter.SetFallbackMarker(reasoningRecoveryFallbackMarker{}) + var calls atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + switch call := calls.Add(1); call { + case 1: + if request.URL.Host != "build.test" { + t.Fatalf("primary host = %q", request.URL.Host) + } + return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decrypt the provided encrypted_content. Ensure the value is unmodified."}`), nil + case 2: + data, _ := io.ReadAll(request.Body) + if request.URL.Host != "build.test" || strings.Contains(string(data), `"encrypted_content"`) { + t.Fatalf("portable retry host=%q body=%s", request.URL.Host, data) + } + return jsonHTTPResponse(request, http.StatusForbidden, `{"error":"build denied"}`), nil + case 3: + if request.URL.Host != "xai.test" { + t.Fatalf("fallback host = %q", request.URL.Host) + } + return jsonHTTPResponse(request, http.StatusOK, `{"id":"resp_ok","status":"completed","output":[]}`), nil + default: + t.Fatalf("unexpected call %d", call) + return nil, nil + } + }) + response, err := adapter.ForwardResponse(t.Context(), provider.ResponseResourceRequest{ + Credential: account.Credential{ + ID: 1, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted, + BuildRouteMode: account.BuildRouteAuto, BuildSuperEntitled: true, + }, + Method: http.MethodPost, Path: "/responses", Model: "grok-4.5", + Body: []byte(`{"model":"grok-4.5","input":[{"type":"reasoning","summary":[],"encrypted_content":"opaque"},{"role":"user","content":"continue"}]}`), + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if calls.Load() != 3 || response.StatusCode != http.StatusOK || response.RecoveredPrimaryFailure == nil || response.RecoveredPrimaryFailure.StatusCode != http.StatusForbidden { + t.Fatalf("calls=%d status=%d recovered_primary=%#v", calls.Load(), response.StatusCode, response.RecoveredPrimaryFailure) + } +} + func TestRecoverReasoningDecodeFailureResetsSessionWithoutOpaqueInput(t *testing.T) { adapter, encrypted := newReasoningRecoveryTestAdapter(t) var calls atomic.Int32 @@ -340,6 +385,37 @@ func TestRecoverReasoningDecodeFailurePreservesRateLimitAfterSessionReset(t *tes } } +func TestRecoverReasoningDecodeFailurePreservesServerErrorAfterSessionReset(t *testing.T) { + adapter, encrypted := newReasoningRecoveryTestAdapter(t) + var calls atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + if calls.Add(1) == 1 { + return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), nil + } + return jsonHTTPResponse(request, http.StatusBadGateway, `{"error":"stateless retry failed upstream"}`), nil + }) + response, err := adapter.ForwardResponse(t.Context(), provider.ResponseResourceRequest{ + Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted}, + Method: http.MethodPost, + Path: "/responses", + Model: "grok-4.5", + PromptCacheKey: "session-1", + Body: []byte(`{"model":"grok-4.5","input":[{"role":"user","content":"continue"}]}`), + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + body, _ := io.ReadAll(response.Body) + warnings := response.Header.Get("X-Grok2API-Compatibility-Warnings") + if calls.Load() != 2 || response.StatusCode != http.StatusBadGateway || !strings.Contains(string(body), "stateless retry failed upstream") { + t.Fatalf("calls=%d status=%d body=%s", calls.Load(), response.StatusCode, body) + } + if response.ReasoningRecoveryFailed || !strings.Contains(warnings, "reasoning_session_reset") || strings.Contains(warnings, "reasoning_recovery_failed") { + t.Fatalf("internal_failure=%t warnings=%q", response.ReasoningRecoveryFailed, warnings) + } +} + // TestRecoverReasoningDecodeFailureWithMillionTokenScaleCompactionBlob 覆盖 Claude Code // 在超长上下文压缩后回放大体积 opaque 状态、且上游拒绝该状态的恢复路径。 func TestRecoverReasoningDecodeFailureWithMillionTokenScaleCompactionBlob(t *testing.T) { @@ -422,29 +498,59 @@ func TestRecoverReasoningDecodeFailureDoesNotResetStoredResponseChain(t *testing if calls.Load() != 1 || response.StatusCode != http.StatusBadRequest || !strings.Contains(response.Header.Get("X-Grok2API-Compatibility-Warnings"), "reasoning_recovery_failed") { t.Fatalf("calls=%d status=%d warnings=%q", calls.Load(), response.StatusCode, response.Header.Get("X-Grok2API-Compatibility-Warnings")) } + if !response.ReasoningRecoveryFailed { + t.Fatal("exhausted same-account recovery must set the internal gateway retry hint") + } } -func TestRecoverReasoningDecodeFailurePreservesOriginalWhenRetryFails(t *testing.T) { +func TestRecoverReasoningDecodeFailureReturnsNon400RetryResponse(t *testing.T) { + for _, status := range []int{http.StatusUnauthorized, http.StatusServiceUnavailable} { + t.Run(http.StatusText(status), func(t *testing.T) { + adapter, encrypted := newReasoningRecoveryTestAdapter(t) + var calls atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + if calls.Add(1) == 1 { + return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), nil + } + return jsonHTTPResponse(request, status, `{"error":"recovery retry response"}`), nil + }) + response, err := adapter.ForwardResponse(t.Context(), provider.ResponseResourceRequest{ + Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted}, + Method: http.MethodPost, Path: "/responses", Model: "grok-4.5", + Body: []byte(`{"model":"grok-4.5","input":[{"type":"reasoning","summary":[],"encrypted_content":"opaque"}]}`), + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + data, _ := io.ReadAll(response.Body) + if calls.Load() != 2 || response.StatusCode != status || !strings.Contains(string(data), "recovery retry response") { + t.Fatalf("calls=%d status=%d headers=%#v body=%s", calls.Load(), response.StatusCode, response.Header, data) + } + if response.ReasoningRecoveryFailed || strings.Contains(response.Header.Get("X-Grok2API-Compatibility-Warnings"), "reasoning_recovery_failed") { + t.Fatalf("non-400 retry was mislabeled as recovery failure: %#v", response) + } + }) + } +} + +func TestRecoverReasoningDecodeFailurePropagatesRetryTransportError(t *testing.T) { adapter, encrypted := newReasoningRecoveryTestAdapter(t) + wantErr := errors.New("recovery transport failed") var calls atomic.Int32 adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { if calls.Add(1) == 1 { return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), nil } - return jsonHTTPResponse(request, http.StatusServiceUnavailable, `{"error":"temporary failure"}`), nil + return nil, wantErr }) response, err := adapter.ForwardResponse(t.Context(), provider.ResponseResourceRequest{ Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted}, Method: http.MethodPost, Path: "/responses", Model: "grok-4.5", Body: []byte(`{"model":"grok-4.5","input":[{"type":"reasoning","summary":[],"encrypted_content":"opaque"}]}`), }) - if err != nil { - t.Fatal(err) - } - defer response.Body.Close() - data, _ := io.ReadAll(response.Body) - if calls.Load() != 2 || response.StatusCode != http.StatusBadRequest || !strings.Contains(string(data), "Could not decode") || !strings.Contains(response.Header.Get("X-Grok2API-Compatibility-Warnings"), "reasoning_recovery_failed") { - t.Fatalf("calls=%d status=%d headers=%#v body=%s", calls.Load(), response.StatusCode, response.Header, data) + if response != nil || !errors.Is(err, wantErr) || calls.Load() != 2 { + t.Fatalf("response=%#v err=%v calls=%d", response, err, calls.Load()) } } @@ -577,4 +683,3 @@ func TestRecoverReasoningDecodeFailureCompactionBlob(t *testing.T) { t.Fatalf("expected status 200, got %d", resp.StatusCode) } } - diff --git a/backend/internal/infra/provider/provider.go b/backend/internal/infra/provider/provider.go index 652a3b4c..058066e7 100644 --- a/backend/internal/infra/provider/provider.go +++ b/backend/internal/infra/provider/provider.go @@ -385,6 +385,10 @@ type Response struct { QuotaUnits int UpstreamURL string Diagnostic *DiagnosticResponse + // ReasoningRecoveryFailed is an internal retry hint emitted only after the Build + // adapter exhausts same-account recovery for an opaque reasoning 400. Gateway + // policy must not infer this state from an upstream-controlled response header. + ReasoningRecoveryFailed bool // RecoveredPrimaryFailure records a primary-plane failure hidden by a successful Provider fallback. RecoveredPrimaryFailure *DiagnosticResponse RateLimit *RateLimitMetadata From b3d4c972c5ff5ca0bb29ddf58734538b9e76d54f Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Mon, 31 Aug 2026 10:05:25 +0800 Subject: [PATCH 10/12] fix: make encrypted-thinking hold split-safe --- .../application/gateway/quality_retry.go | 46 ++++- .../application/gateway/quality_retry_scan.go | 36 ++-- .../application/gateway/quality_retry_test.go | 160 +++++++++++++++++- .../conversation/conversation_test.go | 4 +- .../infra/provider/conversation/stream.go | 79 ++++----- 5 files changed, 256 insertions(+), 69 deletions(-) diff --git a/backend/internal/application/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go index 8bfcaf98..a70ea8da 100644 --- a/backend/internal/application/gateway/quality_retry.go +++ b/backend/internal/application/gateway/quality_retry.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "math" "net/http" "strings" "time" @@ -60,7 +61,8 @@ type QualityRetryRuntime struct { // QualityStreamSignals is the hold classifier input. Tests drive this // directly and via ObserveQualityChunk on SSE fixtures. type QualityStreamSignals struct { - HasThinking bool + HasThinking bool + HasReasoningDelta bool // ReasoningStarted is an empty reasoning item or the Chat SSE stub // `: grok2api-reasoning-start`. That is not proof of thinking: 降智 // still emits the stub, then dumps visible tokens with usage 0. @@ -69,6 +71,8 @@ type QualityStreamSignals struct { ReasoningTokens int64 OutputTokens int64 EncryptedBytes int + EncryptedFloor int64 + UsageReported bool FirstVisible bool VisibleFlushMS int64 Terminal bool @@ -137,16 +141,19 @@ func (s *Service) qualityRetryConfig() QualityRetryRuntime { // encryptedThinkingFloor is max(minBytes, reasoningTokens*bytesPerToken). // A non-empty stub such as "gAAAA-cipher" is not thinking. -func encryptedThinkingFloor(minBytes, bytesPerToken int, reasoningTokens int64) int { +func encryptedThinkingFloor(minBytes, bytesPerToken int, reasoningTokens int64) int64 { if minBytes <= 0 { minBytes = defaultMinEncryptedBytes } if bytesPerToken <= 0 { bytesPerToken = defaultEncryptedBytesPerReasoningToken } - floor := minBytes + floor := int64(minBytes) if reasoningTokens > 0 { - need := int(reasoningTokens) * bytesPerToken + if reasoningTokens > math.MaxInt64/int64(bytesPerToken) { + return math.MaxInt64 + } + need := reasoningTokens * int64(bytesPerToken) if need > floor { floor = need } @@ -156,8 +163,15 @@ func encryptedThinkingFloor(minBytes, bytesPerToken int, reasoningTokens int64) func qualityIsBurstDump(sig QualityStreamSignals, minOutput int64) bool { visible := sig.VisibleTokens - floor := encryptedThinkingFloor(0, 0, sig.ReasoningTokens) - barelyCipher := sig.EncryptedBytes > 0 && sig.EncryptedBytes < floor*2 + floor := sig.EncryptedFloor + if floor <= 0 { + floor = encryptedThinkingFloor(0, 0, sig.ReasoningTokens) + } + barelyCeiling := int64(math.MaxInt64) + if floor <= math.MaxInt64/2 { + barelyCeiling = floor * 2 + } + barelyCipher := sig.EncryptedBytes > 0 && int64(sig.EncryptedBytes) < barelyCeiling flushed := sig.FirstVisible && sig.VisibleFlushMS >= 0 && sig.VisibleFlushMS < defaultBurstFlushMS // Hold timed out, then a short greeting dumped with a large reasoning bill // (TUI "你好" after 30s / 954 thinking tokens). @@ -192,9 +206,27 @@ func ClassifyQualityHold(sig QualityStreamSignals, minOutput int64) QualityVerdi if minOutput <= 0 { minOutput = defaultQualityMinOutput } + // Readable reasoning deltas are direct proof and can preserve the original + // low-latency release path. Ciphertext-only evidence remains provisional so + // the classifier can observe visible output and terminal usage regardless of + // how the SSE events were split across transport reads. + if sig.HasReasoningDelta { + return QualityDeliver + } if sig.HasThinking { + if !sig.FirstVisible && !sig.Terminal { + return QualityWait + } if qualityIsBurstDump(sig, minOutput) { - return QualityWithhold + if sig.Terminal { + return QualityWithhold + } + return QualityWait + } + // The token-relative floor cannot be final until usage arrives. Preserve + // HoldTimeout as the fail-open latency bound for still-open streams. + if !sig.Terminal && !sig.HoldExpired && !sig.UsageReported { + return QualityWait } return QualityDeliver } diff --git a/backend/internal/application/gateway/quality_retry_scan.go b/backend/internal/application/gateway/quality_retry_scan.go index 6f9b163a..48582e3b 100644 --- a/backend/internal/application/gateway/quality_retry_scan.go +++ b/backend/internal/application/gateway/quality_retry_scan.go @@ -5,6 +5,7 @@ import ( "context" "encoding/json" "io" + "strconv" "strings" "sync" "time" @@ -153,23 +154,26 @@ func (s *qualityScanState) signals() QualityStreamSignals { // the ciphertext floor (default 256 bytes, or 4 bytes per reasoning token). reasoningTokens := max(s.reasoningTokens, s.usage.ReasoningTokens) floor := encryptedThinkingFloor(s.minEncryptedBytes, s.encryptedBytesPerReasoningToken, reasoningTokens) - hasThinking := s.hasThinking || s.encryptedBytes >= floor + hasThinking := s.hasThinking || int64(s.encryptedBytes) >= floor firstVisible := !s.firstVisibleAt.IsZero() var flushMS int64 if firstVisible { flushMS = time.Since(s.firstVisibleAt).Milliseconds() } return QualityStreamSignals{ - HasThinking: hasThinking, - ReasoningStarted: s.reasoningStarted || hasThinking, - VisibleTokens: visible, - ReasoningTokens: reasoningTokens, - OutputTokens: output, - EncryptedBytes: s.encryptedBytes, - FirstVisible: firstVisible, - VisibleFlushMS: flushMS, - Terminal: s.terminal, - HoldExpired: s.holdExpired, + HasThinking: hasThinking, + HasReasoningDelta: s.hasThinking, + ReasoningStarted: s.reasoningStarted || hasThinking, + VisibleTokens: visible, + ReasoningTokens: reasoningTokens, + OutputTokens: output, + EncryptedBytes: s.encryptedBytes, + EncryptedFloor: floor, + UsageReported: s.usage.Reported, + FirstVisible: firstVisible, + VisibleFlushMS: flushMS, + Terminal: s.terminal, + HoldExpired: s.holdExpired, } } @@ -198,11 +202,15 @@ func ObserveQualityChunk(state *qualityScanState, chunk []byte) { state.reasoningStarted = true continue } - if bytes.Equal(line, []byte(qualityReasoningEvidenceSSEComment)) { + if bytes.HasPrefix(line, []byte(qualityReasoningEvidenceSSEComment)) { // Protocol converters cannot expose encrypted_content in every public - // JSON contract. This internal SSE comment preserves that evidence. + // JSON contract. This internal SSE comment preserves its byte length so + // short stubs cannot bypass the ciphertext floor. state.reasoningStarted = true - state.hasThinking = true + value := strings.TrimSpace(strings.TrimPrefix(string(line), qualityReasoningEvidenceSSEComment)) + if count, err := strconv.Atoi(value); err == nil && count > state.encryptedBytes { + state.encryptedBytes = count + } continue } if !bytes.HasPrefix(line, []byte("data:")) { diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go index ee272837..78c7f0d2 100644 --- a/backend/internal/application/gateway/quality_retry_test.go +++ b/backend/internal/application/gateway/quality_retry_test.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "io" + "math" "net/http" "path/filepath" "strings" @@ -32,7 +33,7 @@ func TestClassifyQualityHold(t *testing.T) { sig QualityStreamSignals want QualityVerdict }{ - {name: "thinking delivers", sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 10}, want: QualityDeliver}, + {name: "thinking delivers", sig: QualityStreamSignals{HasThinking: true, HasReasoningDelta: true, VisibleTokens: 10}, want: QualityDeliver}, {name: "usage reasoning tokens alone withhold", sig: QualityStreamSignals{ReasoningTokens: 40, VisibleTokens: 80, Terminal: true}, want: QualityWithhold}, {name: "visible 32 no think withhold", sig: QualityStreamSignals{VisibleTokens: 32, Terminal: true}, want: QualityWithhold}, {name: "output 40 no think withhold", sig: QualityStreamSignals{OutputTokens: 40, Terminal: true}, want: QualityWithhold}, @@ -67,23 +68,28 @@ func TestClassifyQualityHoldBurst(t *testing.T) { want QualityVerdict }{ { - name: "hold-expired hello dump withholds", - sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 2, ReasoningTokens: 954, EncryptedBytes: 4000, HoldExpired: true}, + name: "terminal hold-expired hello dump withholds", + sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 2, ReasoningTokens: 954, EncryptedBytes: 4000, EncryptedFloor: 3816, UsageReported: true, FirstVisible: true, HoldExpired: true, Terminal: true}, want: QualityWithhold, }, { name: "hold-expired long answer delivers", - sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 200, ReasoningTokens: 954, EncryptedBytes: 8000, HoldExpired: true}, + sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 200, ReasoningTokens: 954, EncryptedBytes: 8000, EncryptedFloor: 3816, UsageReported: true, FirstVisible: true, HoldExpired: true}, want: QualityDeliver, }, { - name: "barely-over-floor flush withholds", - sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 50, ReasoningTokens: 60, EncryptedBytes: 300, FirstVisible: true, VisibleFlushMS: 100}, + name: "non-terminal barely-over-floor flush keeps observing", + sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 50, ReasoningTokens: 60, EncryptedBytes: 300, EncryptedFloor: 256, UsageReported: true, FirstVisible: true, VisibleFlushMS: 100}, + want: QualityWait, + }, + { + name: "terminal barely-over-floor flush withholds", + sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 50, ReasoningTokens: 60, EncryptedBytes: 300, EncryptedFloor: 256, UsageReported: true, FirstVisible: true, VisibleFlushMS: 100, Terminal: true}, want: QualityWithhold, }, { name: "large cipher flush delivers", - sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 50, ReasoningTokens: 60, EncryptedBytes: 2000, FirstVisible: true, VisibleFlushMS: 100}, + sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 50, ReasoningTokens: 60, EncryptedBytes: 2000, EncryptedFloor: 256, UsageReported: true, FirstVisible: true, VisibleFlushMS: 100}, want: QualityDeliver, }, } @@ -97,6 +103,33 @@ func TestClassifyQualityHoldBurst(t *testing.T) { } } +func TestClassifyQualityHoldBurstUsesConfiguredFloor(t *testing.T) { + t.Parallel() + configuredHigh := QualityStreamSignals{ + HasThinking: true, VisibleTokens: 40, ReasoningTokens: 100, + EncryptedBytes: 1100, EncryptedFloor: 1024, UsageReported: true, + FirstVisible: true, VisibleFlushMS: 100, Terminal: true, + } + if got := ClassifyQualityHold(configuredHigh, 8); got != QualityWithhold { + t.Fatalf("configured high floor verdict = %s, want withhold", got) + } + configuredLow := QualityStreamSignals{ + HasThinking: true, VisibleTokens: 40, ReasoningTokens: 60, + EncryptedBytes: 300, EncryptedFloor: 64, UsageReported: true, + FirstVisible: true, VisibleFlushMS: 100, Terminal: true, + } + if got := ClassifyQualityHold(configuredLow, 8); got != QualityDeliver { + t.Fatalf("configured low floor verdict = %s, want deliver", got) + } +} + +func TestEncryptedThinkingFloorSaturates(t *testing.T) { + t.Parallel() + if got := encryptedThinkingFloor(256, 16, math.MaxInt64); got != math.MaxInt64 { + t.Fatalf("overflowing floor = %d, want %d", got, int64(math.MaxInt64)) + } +} + func TestDecideQualityRetry(t *testing.T) { t.Parallel() if got := DecideQualityRetry(QualityDeliver, 0, 2, qualityRetryFailOpen); got != QualityActionDeliver { @@ -365,6 +398,45 @@ func TestObserveQualityConvertedEncryptedThinking(t *testing.T) { } } +func TestObserveQualityConvertedShortEncryptedStubDoesNotBypassFloor(t *testing.T) { + t.Parallel() + const stub = "gAAAA-cipher" + source := sse( + `data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4.6"}}`, + `data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`, + `data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"`+stub+`"}}`, + `data: {"type":"response.output_text.delta","delta":"`+strings.Repeat("word ", 40)+`"}`, + `data: {"type":"response.completed","response":{"id":"resp_1","model":"grok-4.6","usage":{"output_tokens":90,"output_tokens_details":{"reasoning_tokens":60}}}}`, + ) + for _, test := range []struct { + name string + operation string + protocol string + options conversation.ResponseOptions + }{ + {name: "chat", operation: conversation.OperationChat, protocol: qualityProtocolChat}, + {name: "messages", operation: conversation.OperationMessages, protocol: qualityProtocolAnthropic, options: conversation.ResponseOptions{AnthropicThinking: true}}, + } { + t.Run(test.name, func(t *testing.T) { + converted, err := io.ReadAll(conversation.ConvertResponseStreamWithOptions( + io.NopCloser(strings.NewReader(source)), test.operation, test.options, + )) + if err != nil { + t.Fatal(err) + } + state := qualityScanState{protocol: test.protocol} + ObserveQualityChunk(&state, converted) + sig := state.signals() + if sig.HasThinking || sig.EncryptedBytes != len(stub) || !sig.ReasoningStarted { + t.Fatalf("converted short stub signals = %#v\n%s", sig, converted) + } + if got := ClassifyQualityHold(sig, 32); got != QualityWithhold { + t.Fatalf("converted short stub verdict = %s, want withhold", got) + } + }) + } +} + func TestObserveQualityChunkWhitespaceIsNotThinking(t *testing.T) { t.Parallel() tests := []struct { @@ -560,6 +632,80 @@ func TestPeekQualityStreamThinkingDeliversRemainder(t *testing.T) { } } +func TestPeekQualityStreamCipherBurstWaitsAcrossEventSplits(t *testing.T) { + t.Parallel() + cipher := strings.Repeat("A", 400) + createdAndCipher := sse( + `data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4.6","usage":{"output_tokens":80,"output_tokens_details":{"reasoning_tokens":80}}}}`, + `data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"`+cipher+`"}}`, + ) + visible := sse(`data: {"type":"response.output_text.delta","delta":"你好"}`) + completed := sse(`data: {"type":"response.completed","response":{"id":"resp_1","model":"grok-4.6","usage":{"output_tokens":82,"output_tokens_details":{"reasoning_tokens":80}}}}`) + cfg := QualityRetryRuntime{MinOutputTokens: 8, HoldTimeout: 2 * time.Second} + + coalesced, coalescedVerdict, _, _, err := peekQualityStream( + context.Background(), io.NopCloser(strings.NewReader(createdAndCipher+visible+completed)), qualityProtocolResponses, cfg, + ) + if err != nil { + t.Fatal(err) + } + _ = coalesced.Close() + if coalescedVerdict != QualityWithhold { + t.Fatalf("coalesced verdict = %s, want withhold", coalescedVerdict) + } + + reader, writer := io.Pipe() + type peekResult struct { + replay io.ReadCloser + verdict QualityVerdict + err error + } + done := make(chan peekResult, 1) + go func() { + replay, verdict, _, _, peekErr := peekQualityStream(context.Background(), reader, qualityProtocolResponses, cfg) + done <- peekResult{replay: replay, verdict: verdict, err: peekErr} + }() + if _, err := io.WriteString(writer, createdAndCipher); err != nil { + t.Fatal(err) + } + select { + case result := <-done: + if result.replay != nil { + _ = result.replay.Close() + } + t.Fatalf("ciphertext-only partial stream returned early: verdict=%s err=%v", result.verdict, result.err) + case <-time.After(40 * time.Millisecond): + } + if _, err := io.WriteString(writer, visible); err != nil { + t.Fatal(err) + } + select { + case result := <-done: + if result.replay != nil { + _ = result.replay.Close() + } + t.Fatalf("non-terminal burst was finalized early: verdict=%s err=%v", result.verdict, result.err) + case <-time.After(40 * time.Millisecond): + } + if _, err := io.WriteString(writer, completed); err != nil { + t.Fatal(err) + } + if err := writer.Close(); err != nil { + t.Fatal(err) + } + select { + case result := <-done: + if result.replay != nil { + _ = result.replay.Close() + } + if result.err != nil || result.verdict != QualityWithhold { + t.Fatalf("split verdict=%s err=%v, want withhold", result.verdict, result.err) + } + case <-time.After(2 * time.Second): + t.Fatal("split terminal stream did not finish") + } +} + func TestPeekQualityStreamWithholdsNoThinkEnough(t *testing.T) { t.Parallel() content := strings.Repeat("abcd", 16) // 64 runes → 16 tokens... need 32 tokens = 128 runes diff --git a/backend/internal/infra/provider/conversation/conversation_test.go b/backend/internal/infra/provider/conversation/conversation_test.go index 425cf81c..d07ae3b2 100644 --- a/backend/internal/infra/provider/conversation/conversation_test.go +++ b/backend/internal/infra/provider/conversation/conversation_test.go @@ -944,7 +944,7 @@ func TestConvertResponsesStreamMarksEncryptedChatReasoningEvidence(t *testing.T) t.Fatal(err) } text := string(converted) - if strings.Count(text, ": grok2api-reasoning-start\n\n") != 1 || strings.Count(text, ": grok2api-reasoning-evidence\n\n") != 1 { + if strings.Count(text, ": grok2api-reasoning-start\n\n") != 1 || strings.Count(text, ": grok2api-reasoning-evidence 9\n\n") != 1 { t.Fatalf("encrypted reasoning markers missing or duplicated: %s", text) } if strings.Contains(text, "signature") || strings.Contains(text, "encrypted_content") { @@ -964,7 +964,7 @@ func TestConvertResponsesStreamMarksFinalEnvelopeReasoningEvidence(t *testing.T) t.Fatal(err) } text := string(converted) - if strings.Count(text, ": grok2api-reasoning-evidence\n\n") != 1 { + if strings.Count(text, ": grok2api-reasoning-evidence 9\n\n") != 1 { t.Fatalf("final-envelope reasoning evidence missing or duplicated: %s", text) } if strings.Contains(text, "signature") || strings.Contains(text, "encrypted_content") { diff --git a/backend/internal/infra/provider/conversation/stream.go b/backend/internal/infra/provider/conversation/stream.go index ea67644e..18bcdf4c 100644 --- a/backend/internal/infra/provider/conversation/stream.go +++ b/backend/internal/infra/provider/conversation/stream.go @@ -52,36 +52,36 @@ func ConvertResponseStreamWithOptions(source io.ReadCloser, operation string, op } type streamConverter struct { - writer io.Writer - operation string - id string - model string - created int64 - started bool - finished bool - textStarted bool - textIndex int - thinkingStarted bool - thinkingClosed bool - thinkingIndex int - thinkingItemID string - chatReasoningMark bool - evidenceMarked bool - reasoningItems map[string]*reasoningStreamState - reasoningOrder []string - activeReasoningID string - nextIndex int - tools map[string]streamTool - webSearch []webSearchCall - webSearchEmitted map[string]bool - deferSearchText bool - pendingSearchText strings.Builder - usage responseUsage - options ResponseOptions - stopFilter *anthropicStreamStopFilter - stopSequence string - refused bool - repeatTracker streamRepeatTracker + writer io.Writer + operation string + id string + model string + created int64 + started bool + finished bool + textStarted bool + textIndex int + thinkingStarted bool + thinkingClosed bool + thinkingIndex int + thinkingItemID string + chatReasoningMark bool + reasoningEvidenceBytes int + reasoningItems map[string]*reasoningStreamState + reasoningOrder []string + activeReasoningID string + nextIndex int + tools map[string]streamTool + webSearch []webSearchCall + webSearchEmitted map[string]bool + deferSearchText bool + pendingSearchText strings.Builder + usage responseUsage + options ResponseOptions + stopFilter *anthropicStreamStopFilter + stopSequence string + refused bool + repeatTracker streamRepeatTracker } // streamRepeatTracker 在协议转换、缓冲和 stop filter 之前跟踪上游增量, @@ -148,20 +148,21 @@ func newStreamConverter(writer io.Writer, operation string, options ResponseOpti } } -// markReasoningEvidence preserves non-empty upstream encrypted_content for the -// request-path quality scanner after protocol conversion. SSE clients ignore -// comments, so Chat and Messages public event payloads remain unchanged. -func (c *streamConverter) markReasoningEvidence() error { - if c.evidenceMarked { +// markReasoningEvidence preserves the upstream encrypted_content byte length +// for the request-path quality scanner after protocol conversion. SSE clients +// ignore comments, so Chat and Messages public event payloads remain unchanged. +func (c *streamConverter) markReasoningEvidence(encrypted string) error { + byteCount := len(strings.TrimSpace(encrypted)) + if byteCount <= c.reasoningEvidenceBytes { return nil } if err := c.start(); err != nil { return err } - if _, err := io.WriteString(c.writer, ": grok2api-reasoning-evidence\n\n"); err != nil { + if _, err := fmt.Fprintf(c.writer, ": grok2api-reasoning-evidence %d\n\n", byteCount); err != nil { return err } - c.evidenceMarked = true + c.reasoningEvidenceBytes = byteCount return nil } @@ -381,7 +382,7 @@ func (c *streamConverter) handle(event string, data []byte) error { } } if strings.TrimSpace(item.Encrypted) != "" { - if err := c.markReasoningEvidence(); err != nil { + if err := c.markReasoningEvidence(item.Encrypted); err != nil { return err } } @@ -398,7 +399,7 @@ func (c *streamConverter) handle(event string, data []byte) error { c.setResponse(response) for _, item := range response.Output { if item.Type == "reasoning" && strings.TrimSpace(item.Encrypted) != "" { - if err := c.markReasoningEvidence(); err != nil { + if err := c.markReasoningEvidence(item.Encrypted); err != nil { return err } } From 95915fad2894902162ba3b976288bc8d99d0ff29 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Mon, 31 Aug 2026 10:34:58 +0800 Subject: [PATCH 11/12] refactor: enhance quality hold logic and replay safety across accounts --- README.md | 2 +- README.zh-CN.md | 2 +- .../application/gateway/quality_retry.go | 27 ++- .../application/gateway/quality_retry_test.go | 198 +++++++++++++++++- .../internal/application/gateway/service.go | 17 +- config.example.yaml | 10 +- 6 files changed, 227 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 44bd4dc8..18b57fd6 100644 --- a/README.md +++ b/README.md @@ -382,7 +382,7 @@ qualityGuard: idleAccountCooldown: 15m ``` -`requestRetry` runs on the gateway request path and is independent of the sidecar. `config.example.yaml` keeps `enabled: false`; set it true to intercept. When enabled, a thinking-model stream with enough visible output and no streamed reasoning is **not delivered**; another account is tried. TUI follow-ups (`previous_response_id`) and hosted-tool turns stay held — the first attempt stays pinned, a withhold unpins and rotates. Image, video, and ForcedEgress probe requests are unchanged. If every attempt still has no reasoning, `onExhausted` either returns `503 quality_degraded` or delivers the last body. +`requestRetry` runs on the gateway request path and is independent of the sidecar. `config.example.yaml` keeps `enabled: false`; set it true to intercept. When enabled, a thinking-model stream with enough visible output and no streamed reasoning is **not delivered**; replay-safe stateless requests may try another account. TUI follow-ups (`previous_response_id`) and hosted-tool turns are still held for classification, but a quality withhold never replays account-bound state or side-effecting tools across accounts; `onExhausted` returns `503 quality_degraded` or releases that held body. Context compaction, image, video, and ForcedEgress probe requests are unchanged. ```bash docker compose --profile quality-guard up -d --build diff --git a/README.zh-CN.md b/README.zh-CN.md index 41437d5f..152f48d5 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -377,7 +377,7 @@ qualityGuard: idleAccountCooldown: 15m ``` -`requestRetry` 在网关请求路径上生效,与 sidecar 探测/隔离相互独立。`config.example.yaml` 里 `enabled` 仍为 false,打开后才拦截。开启后,可见输出达到 `minOutputTokens` 且全程无流式 reasoning 时**不发给用户**,排除该账号再试。TUI 续聊(`previous_response_id`)和 hosted tools 仍 hold:第一枪钉原账号,扣住后 unpin 换号。不处理图/视频和 ForcedEgress 探针。全部仍无推理则按 `onExhausted` 返回 `503 quality_degraded` 或放出最后一枪。 +`requestRetry` 在网关请求路径上生效,与 sidecar 探测/隔离相互独立。`config.example.yaml` 里 `enabled` 仍为 false,打开后才拦截。开启后,可见输出达到 `minOutputTokens` 且全程无流式 reasoning 时**不发给用户**;只有可安全重放的无状态请求才会排除账号重试。TUI 续聊(`previous_response_id`)和 hosted tools 仍会进入 hold 检测,但质量拦截不会把账号绑定状态或有副作用的工具跨账号重放,最终按 `onExhausted` 返回 `503 quality_degraded` 或放出当前响应。上下文压缩、图片、视频和 ForcedEgress 探针不受影响。 ```bash docker compose --profile quality-guard up -d --build diff --git a/backend/internal/application/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go index c091fbcf..dedfe445 100644 --- a/backend/internal/application/gateway/quality_retry.go +++ b/backend/internal/application/gateway/quality_retry.go @@ -380,18 +380,24 @@ func shouldHoldQualityStream(input Input, ownership *inferencedomain.ResponseOwn return false } switch operation { - case audit.OperationChat, audit.OperationResponses, audit.OperationMessages, audit.OperationCompaction, "": + case audit.OperationChat, audit.OperationResponses, audit.OperationMessages, "": default: return false } + // Context compaction is a system summary operation, not a normal reasoning + // turn. Holding it can quarantine a healthy account for producing the + // expected summary without streamed reasoning. Keep both compaction forms + // excluded even if a caller reaches this gate without skipQualityHold. + if isResponsesCompactionRequest(input.Body) { + return false + } if route.Provider != accountdomain.ProviderBuild && route.Provider != accountdomain.ProviderConsole { return false } - // TUI always declares tools (including hosted web_search / image jobs) and - // follow-ups carry previous_response_id. Skipping either let 0-thinking - // dumps through on the common agent loop. Keep holding; the attempt loop - // unpins after the first missing-thinking hit. Skip only when the request - // explicitly disables reasoning. + // TUI commonly declares tools and follow-ups carry previous_response_id. + // They still need quality classification, but replay safety is decided + // separately: detecting a degraded response must not imply that an + // account-bound or side-effecting request can run on another account. if qualityRequestDisablesReasoning(input.Body) { return false } @@ -401,6 +407,15 @@ func shouldHoldQualityStream(input Input, ownership *inferencedomain.ResponseOwn return modeldomain.SupportsReasoningForProvider(route.Provider, route.UpstreamModel) } +// canReplayQualityHoldAcrossAccounts separates response classification from +// retry authority. Stored Responses are account-bound, while hosted tools may +// already have produced an external side effect before their held response is +// rejected. Both may be held, audited, and penalized, but neither is replayed +// on another account. +func canReplayQualityHoldAcrossAccounts(input Input, ownership *inferencedomain.ResponseOwnership) bool { + return ownership == nil && !qualityRequestHasReplayUnsafeHostedTools(input.Body) +} + func qualityRequestHasReplayUnsafeHostedTools(body []byte) bool { var payload map[string]any if json.Unmarshal(body, &payload) != nil || payload == nil { diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go index 77386916..47ab4174 100644 --- a/backend/internal/application/gateway/quality_retry_test.go +++ b/backend/internal/application/gateway/quality_retry_test.go @@ -92,19 +92,24 @@ func TestClassifyQualityHoldBurst(t *testing.T) { sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 50, ReasoningTokens: 60, EncryptedBytes: 2000, EncryptedFloor: 256, UsageReported: true, FirstVisible: true, VisibleFlushMS: 100}, want: QualityDeliver, }, + { + name: "non-terminal floor-met short burst keeps observing", + sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 3, ReasoningTokens: 1371, EncryptedBytes: 8000, EncryptedFloor: 5484, UsageReported: true, FirstVisible: true, VisibleFlushMS: 200}, + want: QualityWait, + }, { name: "floor-met short visible fast dump withholds", - sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 3, ReasoningTokens: 1371, EncryptedBytes: 8000, FirstVisible: true, VisibleFlushMS: 200}, + sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 3, ReasoningTokens: 1371, EncryptedBytes: 8000, EncryptedFloor: 5484, UsageReported: true, FirstVisible: true, VisibleFlushMS: 200, Terminal: true}, want: QualityWithhold, }, { name: "floor-met 8 visible 140 reasoning in under 1s withholds", - sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 8, ReasoningTokens: 140, EncryptedBytes: 2000, FirstVisible: true, VisibleFlushMS: 660}, + sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 8, ReasoningTokens: 140, EncryptedBytes: 2000, EncryptedFloor: 560, UsageReported: true, FirstVisible: true, VisibleFlushMS: 660, Terminal: true}, want: QualityWithhold, }, { name: "floor-met long visible fast flush delivers", - sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 80, ReasoningTokens: 140, EncryptedBytes: 2000, FirstVisible: true, VisibleFlushMS: 200}, + sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 80, ReasoningTokens: 140, EncryptedBytes: 2000, EncryptedFloor: 560, UsageReported: true, FirstVisible: true, VisibleFlushMS: 200, Terminal: true}, want: QualityDeliver, }, } @@ -1220,8 +1225,8 @@ func TestShouldHoldQualityStreamGates(t *testing.T) { if shouldHoldQualityStream(input, nil, route, audit.OperationImage, cfg) { t.Fatal("image must not hold") } - if !shouldHoldQualityStream(input, nil, route, audit.OperationCompaction, cfg) { - t.Fatal("compaction with no reasoning must hold") + if shouldHoldQualityStream(input, nil, route, audit.OperationCompaction, cfg) { + t.Fatal("compaction must not enter missing-thinking hold") } classified := input classified.skipQualityHold = true @@ -1230,8 +1235,8 @@ func TestShouldHoldQualityStreamGates(t *testing.T) { } tui := input tui.Body = []byte(`{"input":[{"role":"user","content":"` + tuiCompactionPrompt + `"}]}`) - if !shouldHoldQualityStream(tui, nil, route, audit.OperationResponses, cfg) { - t.Fatal("tui compaction prompt with no reasoning must hold") + if shouldHoldQualityStream(tui, nil, route, audit.OperationResponses, cfg) { + t.Fatal("tui compaction prompt must not enter missing-thinking hold") } for _, test := range []struct { name string @@ -1337,6 +1342,185 @@ func TestShouldHoldQualityStreamGates(t *testing.T) { } } +func TestCanReplayQualityHoldAcrossAccounts(t *testing.T) { + t.Parallel() + plain := Input{Body: []byte(`{"input":"hello"}`)} + if !canReplayQualityHoldAcrossAccounts(plain, nil) { + t.Fatal("stateless text request should allow account retry") + } + owned := inferencedomain.ResponseOwnership{ResponseID: "resp_1", AccountID: 1} + if canReplayQualityHoldAcrossAccounts(plain, &owned) { + t.Fatal("stored response must remain pinned to its owner account") + } + hosted := Input{Body: []byte(`{"tools":[{"type":"web_search"}],"input":"hello"}`)} + if canReplayQualityHoldAcrossAccounts(hosted, nil) { + t.Fatal("hosted tool must not be replayed across accounts") + } + clientTool := Input{Body: []byte(`{"tools":[{"type":"function","name":"read_file"}],"input":"hello"}`)} + if !canReplayQualityHoldAcrossAccounts(clientTool, nil) { + t.Fatal("client-executed tool declaration is safe to retry before delivery") + } +} + +func TestAttemptLoopQualityHoldPreservesReplaySafety(t *testing.T) { + tests := []struct { + name string + previous bool + body string + onExhausted string + wantError bool + empty bool + wantMissing bool + }{ + { + name: "previous response remains account bound", + previous: true, + body: `{"model":"grok-4.6","previous_response_id":"resp-root","input":"continue","stream":true}`, + onExhausted: qualityRetryFailClosed, + wantError: true, + wantMissing: true, + }, + { + name: "hosted tool fail closed executes once", + body: `{"model":"grok-4.6","tools":[{"type":"web_search"}],"input":"search","stream":true}`, + onExhausted: qualityRetryFailClosed, + wantError: true, + wantMissing: true, + }, + { + name: "hosted tool fail open delivers same attempt", + body: `{"model":"grok-4.6","tools":[{"type":"web_search"}],"input":"search","stream":true}`, + onExhausted: qualityRetryFailOpen, + wantMissing: true, + }, + { + name: "hosted tool empty stream executes once", + body: `{"model":"grok-4.6","tools":[{"type":"web_search"}],"input":"search","stream":true}`, + onExhausted: qualityRetryFailClosed, + wantError: true, + empty: true, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "quality-replay-safety.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accountRepo := relational.NewAccountRepository(database) + modelRepo := relational.NewModelRepository(database) + auditRepo := relational.NewAuditRepository(database) + responseRepo := relational.NewResponseRepository(database) + keyRepo := relational.NewClientKeyRepository(database) + + credentials := make([]accountdomain.Credential, 0, 2) + for index, name := range []string{"quality-safe-a", "quality-safe-b"} { + credential, _, createErr := accountRepo.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderBuild, Name: name, SourceKey: name, + EncryptedAccessToken: name, EncryptedRefreshToken: "refresh-" + name, + ExpiresAt: time.Now().Add(time.Hour), Enabled: true, + AuthStatus: accountdomain.AuthStatusActive, Priority: 200 - index, MaxConcurrent: 1, + }) + if createErr != nil { + t.Fatal(createErr) + } + credentials = append(credentials, credential) + } + if err := modelRepo.UpsertDiscovered(ctx, accountdomain.ProviderBuild, []string{"grok-4.6"}); err != nil { + t.Fatal(err) + } + for _, credential := range credentials { + if err := modelRepo.ReplaceAccountCapabilities(ctx, credential.ID, []string{"grok-4.6"}, time.Now().UTC()); err != nil { + t.Fatal(err) + } + } + key, err := keyRepo.Create(ctx, clientkey.Key{ + Name: "quality-safe-key", Prefix: "qsafe", SecretHash: strings.Repeat("8", 64), + EncryptedSecret: "encrypted", Enabled: true, RPMLimit: 120, MaxConcurrent: 8, + }) + if err != nil { + t.Fatal(err) + } + if test.previous { + now := time.Now().UTC() + if err := responseRepo.Save(ctx, inferencedomain.ResponseOwnership{ + ResponseID: "resp-root", AccountID: credentials[0].ID, ClientKeyID: key.ID, + Provider: accountdomain.ProviderBuild, PromptCacheKey: "session-root", + CreatedAt: now, UpdatedAt: now, ExpiresAt: now.Add(time.Hour), + }); err != nil { + t.Fatal(err) + } + } + + noThinking := sse( + `data: {"type":"response.created","response":{"id":"resp-bad","model":"grok-4.6"}}`, + `data: {"type":"response.output_text.delta","delta":"`+strings.Repeat("bad ", 20)+`"}`, + `data: {"type":"response.completed","response":{"id":"resp-bad","model":"grok-4.6","usage":{"output_tokens":40,"output_tokens_details":{"reasoning_tokens":0}}}}`, + ) + thinking := sse( + `data: {"type":"response.created","response":{"id":"resp-good","model":"grok-4.6"}}`, + `data: {"type":"response.reasoning_summary_text.delta","delta":"real reasoning"}`, + `data: {"type":"response.output_text.delta","delta":"good answer"}`, + `data: {"type":"response.completed","response":{"id":"resp-good","model":"grok-4.6","usage":{"output_tokens":40,"output_tokens_details":{"reasoning_tokens":20}}}}`, + ) + firstBody := noThinking + if test.empty { + firstBody = "" + } + adapter := &scriptedBuildAdapter{responses: map[uint64][]scriptedBuildResponse{ + credentials[0].ID: {{status: http.StatusOK, body: firstBody}}, + credentials[1].ID: {{status: http.StatusOK, body: thinking}}, + }} + registry := provider.NewRegistry(adapter) + sticky := memory.NewStickyStore() + accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil) + selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute) + service := NewService(modelRepo, auditRepo, accountService, clientkeyapp.NewService(nil, nil, nil, 60, 4, nil), registry, selector, responseRepo, 3) + service.UpdateQualityRetry(QualityRetryRuntime{ + Enabled: true, MaxAttempts: 2, MinOutputTokens: 8, + OnExhausted: test.onExhausted, HoldTimeout: time.Second, + }) + + input := Input{ + RequestID: "req-quality-safe", ClientKey: key, PublicModel: "grok-4.6", + Streaming: true, Body: []byte(test.body), + } + if test.previous { + input.PreviousResponseID = "resp-root" + } + result, requestErr := service.CreateResponse(ctx, input) + var responseBody []byte + if result != nil { + responseBody, _ = io.ReadAll(result.Body) + result.Finalize(Usage{}, "", "") + _ = result.Body.Close() + } + if (requestErr != nil) != test.wantError { + t.Fatalf("request error = %v, wantError=%t", requestErr, test.wantError) + } + if !test.wantError && !strings.Contains(string(responseBody), "bad ") { + t.Fatalf("fail-open did not deliver the held first attempt: %s", responseBody) + } + attempts := adapter.Attempts() + if len(attempts) != 1 || attempts[0] != credentials[0].ID { + t.Fatalf("request crossed its replay-safety boundary, attempts=%v", attempts) + } + cooled, err := accountRepo.Get(ctx, credentials[0].ID) + if err != nil { + t.Fatal(err) + } + if cooled.CooldownUntil == nil || (test.wantMissing && cooled.LastError != lastErrorMissingThinking) { + t.Fatalf("degraded account was not penalized: %#v", cooled) + } + }) + } +} + func TestAttemptLoopQualityHold(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "quality-hold-loop.db")) diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index 97315f59..fab0b375 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -1020,7 +1020,8 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string // nor new evidence and can multiply a slow/failing probe. holdCfg := s.qualityRetryConfig() qualityHoldEnabled := shouldHoldQualityStream(input, ownership, route, operation, holdCfg) - attemptPolicy := newRequestRoutingAttemptPolicy(int(s.maxAttempts.Load()), input.ForcedAccountID != 0 || (ownership != nil && !qualityHoldEnabled)) + qualityCrossAccountReplay := canReplayQualityHoldAcrossAccounts(input, ownership) + attemptPolicy := newRequestRoutingAttemptPolicy(int(s.maxAttempts.Load()), ownership != nil || input.ForcedAccountID != 0) idempotencyID, _ := security.NewOpaqueToken(18) pricingModel := s.providers.PricingModel(route.Provider, route.UpstreamModel) if err := s.checkLedgerReady(); err != nil { @@ -1244,7 +1245,7 @@ attemptLoop: err = &SelectionUnavailableError{Reason: SelectionNoAccounts} } } - } else if ownership != nil && qualityAccountAttempts == 0 { + } else if ownership != nil { lease, err = s.selector.AcquirePinnedForKey(ctx, route.Provider, ownership.AccountID, route.ID, route.UpstreamModel, quotaMode, true, accountScope) } else if input.ForcedEgressNodeID != 0 { lease, err = s.selector.AcquireForKeyOnEgressNode(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, affinityKey, excluded, !quotaProbeAttempted, accountScope, input.ForcedEgressNodeID) @@ -1276,7 +1277,7 @@ attemptLoop: // Stored Responses are pinned to one account. Return the cached 429 // immediately instead of spinning until the cooldown expires or // replaying the request on the same account. - if input.ForcedAccountID != 0 || (ownership != nil && (!qualityHoldEnabled || qualityAccountAttempts == 0)) { + if ownership != nil || input.ForcedAccountID != 0 { break attemptLoop } attempt-- @@ -1611,17 +1612,15 @@ attemptLoop: } writeCancel() } - if shouldStopForNonAccountFingerprint(failureFingerprints, lastFailure) { + if !qualityCrossAccountReplay || shouldStopForNonAccountFingerprint(failureFingerprints, lastFailure) { break } continue } response.Body = replay - hasNextAccount := attemptPolicy.hasNext(attempt) && qualityAccountAttempts < holdCfg.MaxAttempts - if selection != nil { - hasNextAccount = hasNextAccount && selection.hasAvailableCandidate(excluded, !quotaProbeAttempted) - } else if ownership == nil { - hasNextAccount = false + hasNextAccount := qualityCrossAccountReplay && attemptPolicy.hasNext(attempt) && qualityAccountAttempts < holdCfg.MaxAttempts + if hasNextAccount { + hasNextAccount = selection != nil && selection.hasAvailableCandidate(excluded, !quotaProbeAttempted) } commit := CommitQualityHold(verdict, qualityAccountAttempts-1, holdCfg.MaxAttempts, hasNextAccount, holdCfg.OnExhausted) if verdict == QualityWithhold { diff --git a/config.example.yaml b/config.example.yaml index 2f6942a8..7a3ae2f4 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -157,11 +157,11 @@ qualityGuard: # not released as late ciphertext. Empty stub-only streams keep waiting. # Floor-met ciphertext that then dumps a short greeting in under 1s is # also withheld. TUI follow-ups (previous_response_id) and hosted tools - # stay held; the attempt loop unpins after the first missing-thinking hit. - # Missing thinking with enough visible output is not delivered; another - # account is tried (up to maxAttempts). fail_closed returns 503 instead - # of the last body. Sidecar qualityGuard.enabled stays false until you - # start the quality-guard profile. + # stay held for classification, but a quality withhold never replays + # account-bound state or side-effecting tools. Context compaction stays exempt. + # Replay-safe missing-thinking requests try another account (up to + # maxAttempts). fail_closed returns 503 instead of the held body. Sidecar + # qualityGuard.enabled stays false until you start the quality-guard profile. # Non-empty encrypted_content stubs are not thinking. The ciphertext floor # is max(minEncryptedBytes, reasoning_tokens * encryptedBytesPerReasoningToken). requestRetry: From cf13fe1a2db4ba6280e7e96d80b54e01aca534ea Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Mon, 31 Aug 2026 11:28:07 +0800 Subject: [PATCH 12/12] fix: limit stream failure attempts to 2xx responses --- backend/internal/application/gateway/attempt.go | 7 +++---- backend/internal/application/gateway/attempt_test.go | 10 ++++++++++ backend/internal/application/gateway/service.go | 2 +- backend/internal/application/gateway/service_test.go | 11 +++++++++++ 4 files changed, 25 insertions(+), 5 deletions(-) diff --git a/backend/internal/application/gateway/attempt.go b/backend/internal/application/gateway/attempt.go index 76663394..5db3627a 100644 --- a/backend/internal/application/gateway/attempt.go +++ b/backend/internal/application/gateway/attempt.go @@ -181,11 +181,10 @@ func (r *failureAttemptRecorder) hasStreamFailureFor(accountID uint64) bool { return false } -// ensureStreamFailureAttempt records the handed-off 2xx stream when it later -// fails. Prior 4xx/transport attempts must not suppress this row — otherwise -// diagnostics only show the first 429 while the list account is the retry. +// ensureStreamFailureAttempt 补记已完成 2xx 响应头握手、但随后失败的流式尝试。 +// 既有 4xx 或传输失败记录不能屏蔽该尝试;同一账号已有 response_stream 时不重复追加。 func (r *failureAttemptRecorder) ensureStreamFailureAttempt(credential accountdomain.Credential, startedAt time.Time, response *provider.Response, errorCode string) { - if response == nil || r.hasStreamFailureFor(credential.ID) { + if response == nil || response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices || r.hasStreamFailureFor(credential.ID) { return } statusCode := response.StatusCode diff --git a/backend/internal/application/gateway/attempt_test.go b/backend/internal/application/gateway/attempt_test.go index 77e9d257..e03928a4 100644 --- a/backend/internal/application/gateway/attempt_test.go +++ b/backend/internal/application/gateway/attempt_test.go @@ -124,6 +124,16 @@ func TestEnsureStreamFailureAttemptKeepsPrior429AndSkipsDuplicate(t *testing.T) } } +func TestEnsureStreamFailureAttemptSkipsNon2xx(t *testing.T) { + recorder := newFailureAttemptRecorder(http.MethodPost, "/responses") + credential := account.Credential{ID: 12, Name: "retry-b"} + forbidden := &provider.Response{StatusCode: http.StatusForbidden, Status: "403 Forbidden"} + recorder.ensureStreamFailureAttempt(credential, time.Now(), forbidden, "upstream_forbidden") + if got := recorder.snapshot(); len(got) != 0 { + t.Fatalf("non-2xx stream attempt = %#v", got) + } +} + func TestFailureAttemptRecorderClassifiesTransportErrorChain(t *testing.T) { dnsErr := &net.DNSError{Err: "no such host", Name: "api.example.test", IsNotFound: true} requestErr := &url.Error{Op: "Post", URL: "https://user:password@api.example.test/v1/responses?token=secret", Err: dnsErr} diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index ea693ec9..539053e4 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -1118,7 +1118,7 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string } record.DurationMS = time.Since(startedAt).Milliseconds() record.ErrorCode = errorCode - if !successful { + if !successful && response.StatusCode >= http.StatusOK && response.StatusCode < http.StatusMultipleChoices { failureAttempts.ensureStreamFailureAttempt(credential, upstreamStartedAt, response, errorCode) } attempts := failureAttempts.snapshot() diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index 89ee48b2..54bb06a9 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -3064,6 +3064,17 @@ func TestGatewaySafetyRejectionDoesNotTouchAccountState(t *testing.T) { } } } + logs, total, err := auditRepo.List(ctx, 0, 10) + if err != nil || total != 1 || len(logs) != 1 { + t.Fatalf("audit list = %#v, total=%d, err=%v", logs, total, err) + } + detail, err := auditRepo.Get(ctx, logs[0].ID) + if err != nil { + t.Fatal(err) + } + if detail.AttemptCount != 1 || len(detail.Attempts) != 1 || detail.Attempts[0].Stage != "upstream_response" || detail.Attempts[0].UpstreamStatusCode == nil || *detail.Attempts[0].UpstreamStatusCode != http.StatusForbidden { + t.Fatalf("terminal 403 attempts = %#v", detail.Attempts) + } } func TestGatewayConsoleDPoPRequirementStopsAfterOneAccount(t *testing.T) {