From 646dd395cad7c909f3cd1f6f9c87d19b707ae7ca Mon Sep 17 00:00:00 2001 From: Entropy-Enthalpy <55441397+Entropy-Enthalpy@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:30:22 +0800 Subject: [PATCH 1/7] fix: recover quota refusals and preserve OAuth retry affinity --- backend/internal/handler/failover_loop.go | 3 + .../internal/handler/failover_loop_test.go | 13 +++ .../handler/openai_chat_completions.go | 4 + ...i_encrypted_history_quota_failover_test.go | 106 ++++++++++++++++++ .../handler/openai_gateway_handler.go | 14 ++- .../openai_responses_failover_cancel_test.go | 37 +++--- backend/internal/service/gateway_service.go | 3 + .../service/gateway_upstream_response.go | 6 +- .../openai_access_state_failover_test.go | 7 ++ .../openai_account_runtime_block_fastpath.go | 2 +- .../service/openai_agent_message_delivery.go | 24 ++++ .../service/openai_agent_message_recovery.go | 29 ++++- .../openai_agent_quota_failover_test.go | 71 ++++++++++++ .../service/openai_gateway_forward.go | 9 +- .../service/openai_gateway_passthrough.go | 10 ++ .../service/openai_gateway_service_test.go | 5 +- .../service/openai_gateway_upstream_errors.go | 55 ++++++++- .../service/openai_oauth_passthrough_test.go | 30 ++++- .../openai_upstream_transport_error.go | 12 +- backend/internal/service/ratelimit_service.go | 3 + 20 files changed, 412 insertions(+), 31 deletions(-) create mode 100644 backend/internal/handler/openai_encrypted_history_quota_failover_test.go create mode 100644 backend/internal/service/openai_agent_quota_failover_test.go diff --git a/backend/internal/handler/failover_loop.go b/backend/internal/handler/failover_loop.go index 154fc3c663d9..ebcbd9004991 100644 --- a/backend/internal/handler/failover_loop.go +++ b/backend/internal/handler/failover_loop.go @@ -211,6 +211,9 @@ func (s *FailoverState) HandleFailoverError( // 同账号重试不算切换账号,粘性会话仅在实际切换时强制缓存计费。 retryCount := s.SameAccountRetryCount[accountID] sameAccountRetry := sameAccountRetryAllowed(failoverErr, retryCount, retryLimit) + if !sameAccountRetry && failoverErr.RequestScopedTransient && failoverErr.Scope == service.GatewayFailureScopeRequest { + return FailoverExhausted + } if needForceCacheBilling(s.hasBoundSession, failoverErr, sameAccountRetry) { s.ForceCacheBilling = true } diff --git a/backend/internal/handler/failover_loop_test.go b/backend/internal/handler/failover_loop_test.go index d362682cd7af..b32719081659 100644 --- a/backend/internal/handler/failover_loop_test.go +++ b/backend/internal/handler/failover_loop_test.go @@ -589,6 +589,19 @@ func TestHandleFailoverError_SameAccountRetry(t *testing.T) { // --------------------------------------------------------------------------- func TestHandleFailoverError_TempUnschedule(t *testing.T) { + t.Run("exhausted request-local failure preserves the bound account", func(t *testing.T) { + mock := &mockTempUnscheduler{} + state := NewFailoverState(5, true) + err := newTestFailoverErr(502, true, false) + err.Scope = service.GatewayFailureScopeRequest + err.RequestScopedTransient = true + state.SameAccountRetryCount[100] = 1 + require.Equal(t, FailoverExhausted, state.HandleFailoverError(context.Background(), mock, 100, "openai", 1, err)) + require.Empty(t, mock.calls) + require.Empty(t, state.FailedAccountIDs) + require.Zero(t, state.SwitchCount) + require.False(t, state.ForceCacheBilling) + }) t.Run("非重试错误不调用TempUnschedule", func(t *testing.T) { mock := &mockTempUnscheduler{} fs := NewFailoverState(3, false) diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index ee4615784929..771565d7cd4e 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -420,6 +420,10 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { continue } } + if failoverErr.RequestScopedTransient && failoverErr.Scope == service.GatewayFailureScopeRequest { + h.handleFailoverExhausted(c, failoverErr, streamStarted) + return + } h.gatewayService.RecordOpenAIAccountSwitch() failedAccountIDs[account.ID] = struct{}{} lastFailoverErr = failoverErr diff --git a/backend/internal/handler/openai_encrypted_history_quota_failover_test.go b/backend/internal/handler/openai_encrypted_history_quota_failover_test.go new file mode 100644 index 000000000000..409f7304e00d --- /dev/null +++ b/backend/internal/handler/openai_encrypted_history_quota_failover_test.go @@ -0,0 +1,106 @@ +//go:build unit + +package handler + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/repository" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/Wei-Shaw/sub2api/internal/testutil" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestEncryptedHistoryQuotaFailoverPreservesContinuation(t *testing.T) { + for _, kind := range []string{service.AccountTypeOAuth, service.AccountTypeAPIKey} { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/stream=%t", kind, stream), func(t *testing.T) { + clients := issue805Redis(t) + var mu sync.Mutex + var identities []string + var inputs []string + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + if err != nil { + t.Error(err) + return + } + mu.Lock() + identities = append(identities, r.Header.Get("Authorization")) + inputs = append(inputs, gjson.GetBytes(body, "input").Raw) + attempt := len(identities) + mu.Unlock() + if attempt > 1 && r.Header.Get("Authorization") == "Bearer fixture-quota-1" { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusTooManyRequests) + _, _ = io.WriteString(w, `{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached","resets_at":4102444800}}`) + return + } + output := "[" + issue715Agent + "]" + if attempt > 1 { + output = `[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"existing ledger balance 18"}]}]` + } + response := fmt.Sprintf(`{"id":"resp_quota_%d","status":"completed","model":"gpt-5.1","output":%s,"usage":{"input_tokens":5,"output_tokens":3}}`, attempt, output) + if gjson.GetBytes(body, "stream").Bool() { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprintf(w, "data: {\"type\":\"response.completed\",\"response\":%s}\n\ndata: [DONE]\n\n", response) + } else { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, response) + } + })) + defer upstream.Close() + target, err := url.Parse(upstream.URL) + require.NoError(t, err) + accounts := issue715Accounts() + for i := range accounts { + accounts[i].Type = kind + accounts[i].Credentials = map[string]any{ + "api_key": fmt.Sprintf("fixture-quota-%d", i+1), + "access_token": fmt.Sprintf("fixture-quota-%d", i+1), + "base_url": upstream.URL, + } + } + newNode := func() *OpenAIGatewayHandler { + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + transport := &issue842Transport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target} + settings := service.NewSettingService(&issue842Settings{}, cfg) + handler := newOpenAIResponsesFailoverTestHandlerWithSettings(t, transport, repository.NewGatewayCache(clients()), settings, accounts...) + handler.cfg.Security.URLAllowlist.AllowInsecureHTTP = true + issue805Policy(t, handler.cfg, true) + return handler + } + first := issue758Request(t, newNode(), strings.Replace(issue715Body(false, stream), issue715Agent+",", "", 1)) + require.Equal(t, http.StatusOK, first.Code, first.Body.String()) + issue758CompletedResponse(t, first.Body.String(), stream) + originalOwners := issue805Owners(t, clients()) + require.Len(t, originalOwners, 1) + followup := issue715Body(true, stream) + for request := 0; request < 2; request++ { + answer := issue758Request(t, newNode(), followup) + require.Equal(t, http.StatusOK, answer.Code, answer.Body.String()) + completed := issue758CompletedResponse(t, answer.Body.String(), stream) + require.Contains(t, completed.Raw, "existing ledger balance 18") + require.NotContains(t, answer.Body.String(), "response.failed") + } + require.Equal(t, originalOwners, issue805Owners(t, clients()), "quota rejection must preserve the completed producer records") + mu.Lock() + defer mu.Unlock() + require.Equal(t, []string{"Bearer fixture-quota-1", "Bearer fixture-quota-1", "Bearer fixture-quota-2", "Bearer fixture-quota-2"}, identities) + for _, input := range inputs[1:] { + require.JSONEq(t, gjson.Get(followup, "input").Raw, input, "quota failover must retain the task and completed tool results") + } + }) + } + } +} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 89978538a81d..85da01323cf5 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -1383,7 +1383,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { if failoverErr.ShouldReportAccountScheduleFailure() { h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, forwardModel, requireCompact, nil), false, nil, err) } - if service.OpenAIAgentRecoveryNoReplay(c.Request.Context()) { + if service.OpenAIAgentRecoveryNoReplay(c.Request.Context(), failoverErr) { h.handleFailoverExhausted(c, failoverErr, streamStarted) return } @@ -1416,6 +1416,10 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { continue } } + if failoverErr.RequestScopedTransient && failoverErr.Scope == service.GatewayFailureScopeRequest { + h.handleFailoverExhausted(c, failoverErr, streamStarted) + return + } h.gatewayService.RecordOpenAIAccountSwitch() failedAccountIDs[account.ID] = struct{}{} lastFailoverErr = failoverErr @@ -2055,6 +2059,10 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { continue } } + if failoverErr.RequestScopedTransient && failoverErr.Scope == service.GatewayFailureScopeRequest { + h.handleAnthropicFailoverExhausted(c, failoverErr, streamStarted) + return + } h.gatewayService.RecordOpenAIAccountSwitch() failedAccountIDs[account.ID] = struct{}{} lastFailoverErr = failoverErr @@ -3490,6 +3498,10 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { if ctx.Err() != nil { return false } + if failoverErr.RequestScopedTransient && failoverErr.Scope == service.GatewayFailureScopeRequest { + closeOpenAIWSFailoverExhausted(c, wsConn, failoverErr) + return false + } h.gatewayService.RecordOpenAIAccountSwitch() failedAccountIDs[account.ID] = struct{}{} lastFailoverErr = failoverErr diff --git a/backend/internal/handler/openai_responses_failover_cancel_test.go b/backend/internal/handler/openai_responses_failover_cancel_test.go index 40f39b1ab5ce..de3fddd6c7f4 100644 --- a/backend/internal/handler/openai_responses_failover_cancel_test.go +++ b/backend/internal/handler/openai_responses_failover_cancel_test.go @@ -199,19 +199,30 @@ func TestOpenAIGatewayHandlerResponses_FailoverAbortsWhenClientDisconnected(t *t require.Equal(t, 520, events[0].UpstreamStatusCode) } -// TestOpenAIGatewayHandlerResponses_FailoverContinuesForConnectedClient 回归 -// 守卫:客户端在线时 failover 行为不变——切换到账号 2,两个账号都 520 后按 -// 耗尽返回 502。 +// Connected OAuth requests retry transient failures on the original account. +// API-key accounts retain their existing bounded cross-account failover. func TestOpenAIGatewayHandlerResponses_FailoverContinuesForConnectedClient(t *testing.T) { gin.SetMode(gin.TestMode) - - upstream := &openAIResponsesFailoverCancelUpstream{} - handler := newOpenAIResponsesFailoverTestHandler(t, upstream) - c, rec := newOpenAIResponsesFailoverTestContext(t, nil) - - handler.Responses(c) - - require.Equal(t, []int64{1, 2}, upstream.calls(), "在线客户端应正常切换账号") - require.Equal(t, http.StatusBadGateway, rec.Code) - require.Equal(t, "upstream_error", gjson.GetBytes(rec.Body.Bytes(), "error.type").String()) + for _, tc := range []struct { + kind string + accounts []int64 + }{ + {service.AccountTypeOAuth, []int64{1, 1, 1, 1}}, + {service.AccountTypeAPIKey, []int64{1, 2}}, + } { + t.Run(tc.kind, func(t *testing.T) { + accounts := issue715Accounts() + for i := range accounts { + accounts[i].Type = tc.kind + accounts[i].Credentials = map[string]any{"api_key": "fixture-key", "access_token": "fixture-access"} + } + upstream := &openAIResponsesFailoverCancelUpstream{} + handler := newOpenAIResponsesFailoverTestHandler(t, upstream, accounts...) + c, rec := newOpenAIResponsesFailoverTestContext(t, nil) + handler.Responses(c) + require.Equal(t, tc.accounts, upstream.calls()) + require.Equal(t, http.StatusBadGateway, rec.Code) + require.Equal(t, "upstream_error", gjson.GetBytes(rec.Body.Bytes(), "error.type").String()) + }) + } } diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 357db7921ffb..0b6a51464841 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -854,6 +854,9 @@ func (e *UpstreamFailoverError) ShouldReportAccountScheduleFailure() bool { if e == nil || e.Reason == OpenAIWSModelUnavailableReason || e.Reason == ExcelBPSRateLimitedReason || e.Reason == GrokUnknownForbiddenReason || e.IsExcelBPSImageAdmissionRejection() { return false } + if e.RequestScopedTransient && e.Scope == GatewayFailureScopeRequest { + return false + } return !e.IsCredentialFailure() || e.Scope == GatewayFailureScopeAccount } diff --git a/backend/internal/service/gateway_upstream_response.go b/backend/internal/service/gateway_upstream_response.go index c1e4f054f655..f0835040b3a9 100644 --- a/backend/internal/service/gateway_upstream_response.go +++ b/backend/internal/service/gateway_upstream_response.go @@ -1299,11 +1299,15 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http "message": disconnectMsg, }, }) - return nil, &UpstreamFailoverError{ + failoverErr := &UpstreamFailoverError{ StatusCode: http.StatusBadGateway, ResponseBody: body, RetryableOnSameAccount: true, } + if isOpenAIOAuthAccount(account) && !classifyUpstreamTransportError(ev.err).Persistent { + failoverErr.preserveOpenAIOAuthBinding() + } + return nil, failoverErr } sendErrorEvent("stream_read_error", disconnectMsg) return &streamingResult{usage: usage, firstTokenMs: firstTokenMs}, fmt.Errorf("stream read error: %w", ev.err) diff --git a/backend/internal/service/openai_access_state_failover_test.go b/backend/internal/service/openai_access_state_failover_test.go index 92254d92e52d..6c1c0ba206fc 100644 --- a/backend/internal/service/openai_access_state_failover_test.go +++ b/backend/internal/service/openai_access_state_failover_test.go @@ -155,6 +155,13 @@ func TestOpenAIHTTPAccessStateTrustsStructuredCode(t *testing.T) { } func TestOpenAIHTTPAuthMessagesUseExistingStatusPolicies(t *testing.T) { + t.Run("revoked credential with echoed concurrency error", func(t *testing.T) { + account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth} + body := []byte(`{"error":{"code":"token_revoked","message":"Token has been revoked"},"input":{"error":{"message":"authentication failed (status=503): Too many concurrent requests"}}}`) + err := (&OpenAIGatewayService{}).newOpenAIAccountFailoverError(account, http.StatusUnauthorized, nil, body, "", false, false) + require.False(t, err.RequestScopedTransient) + require.False(t, err.RetryableOnSameAccount) + }) t.Run("oauth 401 remains recoverable", func(t *testing.T) { repo := &openAIAuthPolicyAccountRepo{} rateLimits := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) diff --git a/backend/internal/service/openai_account_runtime_block_fastpath.go b/backend/internal/service/openai_account_runtime_block_fastpath.go index 70a4da4a4494..733b439d319f 100644 --- a/backend/internal/service/openai_account_runtime_block_fastpath.go +++ b/backend/internal/service/openai_account_runtime_block_fastpath.go @@ -105,7 +105,7 @@ func (s *OpenAIGatewayService) handleOpenAIAccountUpstreamError(ctx context.Cont } // Apply the same exemption before access-state and custom cooldown fast // paths, which can otherwise block the credential before the shared handler. - if isOpenAIRequestScoped403(account, statusCode, responseBody) { + if isOpenAIRequestScoped403(account, statusCode, responseBody) || isOpenAIWrappedConcurrency401(account, statusCode, responseBody) { return false } // Capacity shedding describes this request, not account health. Keep the diff --git a/backend/internal/service/openai_agent_message_delivery.go b/backend/internal/service/openai_agent_message_delivery.go index 926138e07105..6188f3d90f83 100644 --- a/backend/internal/service/openai_agent_message_delivery.go +++ b/backend/internal/service/openai_agent_message_delivery.go @@ -185,6 +185,30 @@ func (d *openAIAgentRecoveryDelivery) reserve(items [][32]byte) error { return nil } +// A rejected HTTP request has produced no output. Restore only the discovery +// receipts reserved by this attempt, so the next account can consume them. +func (d *openAIAgentRecoveryDelivery) rejectBeforeExecution() error { + if len(d.keys) != 0 || len(d.epochs) != 0 || len(d.tools) != 0 { + return openAIAgentRecoveryError("owner_conflict") + } + for key, pending := range d.discoveryBindings { + original, ok := d.request.toolProofs[key] + if !ok { + return openAIAgentRecoveryError("owner_conflict") + } + restored, err := d.service.compareAndSwapToolProof(d.ctx, key, pending.raw, original.raw) + if err != nil { + return openAIAgentRecoveryError("store_unavailable") + } + if !restored { + return openAIAgentRecoveryError("owner_conflict") + } + delete(d.discoveryBindings, key) + } + d.finish(false) + return nil +} + func (d *openAIAgentRecoveryDelivery) finish(completed bool) { d.once.Do(func() { final := make(map[[32]byte]bool) diff --git a/backend/internal/service/openai_agent_message_recovery.go b/backend/internal/service/openai_agent_message_recovery.go index b486a2e5ca79..5a5c31f839f0 100644 --- a/backend/internal/service/openai_agent_message_recovery.go +++ b/backend/internal/service/openai_agent_message_recovery.go @@ -724,9 +724,32 @@ func OpenAIAgentToolResultContinuation(ctx context.Context) bool { return r != nil && (r.owner != nil || r.preservesHistory()) && r.toolResult } -// Opt-out permits one intact attempt, not automatic cross-account retries or -// input-rewriting retries. Strict mode retains its existing tool-result rule. -func OpenAIAgentRecoveryNoReplay(ctx context.Context) bool { +// A quota rejection precedes execution. An opted-in full-history request can +// retain its input and use the ordinary account failover budget in that case. +// Account-owned response pointers and ambiguous failures retain their guards. +func openAIAgentQuotaFailoverAllowed(ctx context.Context, status int, body []byte) bool { + request := openAIAgentRecoveryFromContext(ctx) + if request == nil || !request.disableOwnerBinding || request.previousResponseID != "" || + openAI409HasProviderState(request.replaySource) || request.nativeCompaction || + request.omittedHistory || request.omitted400History || status != http.StatusTooManyRequests { + return false + } + if !openAIEncryptedJSONUnambiguous(body) { + return false + } + for _, path := range []string{"error.type", "error.code", "response.error.type", "response.error.code"} { + switch gjson.GetBytes(body, path).String() { + case "usage_limit_reached", "insufficient_quota", "quota_exceeded": + return true + } + } + return false +} + +func OpenAIAgentRecoveryNoReplay(ctx context.Context, failure *UpstreamFailoverError) bool { + if failure != nil && openAIAgentQuotaFailoverAllowed(ctx, failure.StatusCode, failure.ResponseBody) { + return false + } return OpenAIAgentToolResultContinuation(ctx) || openAIAgentRecoveryPreservesHistory(ctx) } diff --git a/backend/internal/service/openai_agent_quota_failover_test.go b/backend/internal/service/openai_agent_quota_failover_test.go new file mode 100644 index 000000000000..3b4ceac84c61 --- /dev/null +++ b/backend/internal/service/openai_agent_quota_failover_test.go @@ -0,0 +1,71 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestAgentQuotaFailoverRetainsOtherReplayRestrictions(t *testing.T) { + quota := []byte(`{"error":{"type":"usage_limit_reached","resets_at":4102444800}}`) + for _, tc := range []struct { + name string + request openAIAgentRecoveryRequest + status int + body []byte + allowed bool + }{ + {"quota", openAIAgentRecoveryRequest{disableOwnerBinding: true}, 429, quota, true}, + {"strict", openAIAgentRecoveryRequest{}, 429, quota, false}, + {"pointer", openAIAgentRecoveryRequest{disableOwnerBinding: true, previousResponseID: "resp_owned"}, 429, quota, false}, + {"conversation", openAIAgentRecoveryRequest{disableOwnerBinding: true, replaySource: []byte(`{"conversation":"conv_owned"}`)}, 429, quota, false}, + {"compaction", openAIAgentRecoveryRequest{disableOwnerBinding: true, nativeCompaction: true}, 429, quota, false}, + {"rewritten_history", openAIAgentRecoveryRequest{disableOwnerBinding: true, omittedHistory: true}, 429, quota, false}, + {"ambiguous_server_error", openAIAgentRecoveryRequest{disableOwnerBinding: true}, 520, quota, false}, + {"ordinary_rate_limit", openAIAgentRecoveryRequest{disableOwnerBinding: true}, 429, []byte(`{"error":{"code":"rate_limit_exceeded","resets_at":4102444800}}`), false}, + {"echoed_input", openAIAgentRecoveryRequest{disableOwnerBinding: true}, 429, []byte(`{"error":{"type":"server_error"},"input":{"error":{"type":"usage_limit_reached"}}}`), false}, + {"truncated", openAIAgentRecoveryRequest{disableOwnerBinding: true}, 429, []byte(`{"error":{"type":"usage_limit_reached"}`), false}, + {"duplicate_error", openAIAgentRecoveryRequest{disableOwnerBinding: true}, 429, []byte(`{"error":{"type":"usage_limit_reached"},"error":{"type":"server_error"}}`), false}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := context.WithValue(context.Background(), openAIAgentRecoveryContextKey{}, &tc.request) + require.Equal(t, tc.allowed, openAIAgentQuotaFailoverAllowed(ctx, tc.status, tc.body)) + }) + } +} + +func TestAgentQuotaRejectionReleasesOnlyItsDiscoveryReceipt(t *testing.T) { + for _, changed := range []bool{false, true} { + t.Run(map[bool]string{false: "own_receipt", true: "concurrent_receipt"}[changed], func(t *testing.T) { + svc := &OpenAIGatewayService{} + proof := openAIToolProof{Version: 1, Call: "completed-discovery-call", Producer: "original-producer"} + raw, err := json.Marshal(proof) + require.NoError(t, err) + request := &openAIAgentRecoveryRequest{toolProofs: map[string]openAIToolProofSnapshot{ + "discovery": {raw: string(raw), proof: proof, discoveryDigest: "same-result"}, + }} + svc.agentMessageRecovery.toolProofs = map[string]openAIToolLocalRecord{ + "discovery": {raw: string(raw), until: time.Now().Add(time.Hour)}, + } + delivery := newOpenAIAgentRecoveryDelivery(svc, context.Background(), request, openAIAgentRecoveryBinding{}) + require.NoError(t, delivery.bindDiscoveryResults()) + if changed { + svc.agentMessageRecovery.toolProofs["discovery"] = openAIToolLocalRecord{raw: "concurrent-record", until: time.Now().Add(time.Hour)} + require.Error(t, delivery.rejectBeforeExecution()) + delivery.finish(false) + require.Equal(t, "concurrent-record", svc.agentMessageRecovery.toolProofs["discovery"].raw) + return + } + require.NoError(t, delivery.rejectBeforeExecution()) + delivery.finish(false) + require.Equal(t, string(raw), svc.agentMessageRecovery.toolProofs["discovery"].raw) + next := newOpenAIAgentRecoveryDelivery(svc, context.Background(), request, openAIAgentRecoveryBinding{}) + require.NoError(t, next.bindDiscoveryResults(), "the same result can be submitted after a definitive rejection") + }) + } +} diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index d419de374ec7..5a861a0e4716 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -1586,9 +1586,16 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco // text. Do not borrow field/compact/failover retry budgets here. return s.handleErrorResponse(ctx, resp, c, account, body, resolveOpenAIErrorSchedulingModel(billingModel, upstreamModel)) } - if openAIAgentRecoveryPreservesHistory(ctx) { + if openAIAgentRecoveryPreservesHistory(ctx) && !openAIAgentQuotaFailoverAllowed(ctx, resp.StatusCode, respBody) { return s.handleErrorResponse(ctx, resp, c, account, body, resolveOpenAIErrorSchedulingModel(billingModel, upstreamModel)) } + if openAIAgentQuotaFailoverAllowed(ctx, resp.StatusCode, respBody) { + if recovery := openAIAgentRecoveryFromContext(ctx); recovery.delivery != nil { + if err := recovery.delivery.rejectBeforeExecution(); err != nil { + return nil, err + } + } + } if retryBody, reason, changed, retryErr := normalizeOpenAIResponsesRejectedFieldRetryBody(resp.StatusCode, body, respBody); retryErr != nil { return nil, fmt.Errorf("normalize rejected Responses field retry body: %w", retryErr) } else if !isControlledExperiment(ctx) && changed && rejectedFieldRetryState.Allow(retryBody) { diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index e8df76c13bcb..42b747af5351 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -915,6 +915,9 @@ func shouldFailoverOpenAIPassthroughResponse(account *Account, statusCode int, r if account != nil && account.IsOpenAICompatible() && isUpstreamModelNotFoundError(statusCode, responseBody) { return true } + if isOpenAIWrappedConcurrency401(account, statusCode, responseBody) || (isOpenAIOAuthAccount(account) && isOpenAIOAuthTransientServerStatus(statusCode)) { + return true + } if account != nil && account.IsPoolMode() && account.IsPoolModeRetryableStatus(statusCode) { return true } @@ -2048,6 +2051,13 @@ func (s *OpenAIGatewayService) newOpenAIStreamFailoverErrorWithModel( classificationHeaders = nil } failoverErr := s.newOpenAIAccountFailoverErrorWithClassificationHeaders(account, statusCode, headers, classificationHeaders, payload, message, shouldDisable, retryableOnSameAccount) + // A nil frame with this message is generated locally on a pre-output disconnect. + // Generic provider SSE errors also map to 502; that alone does not identify a disconnect. + if !shouldDisable && isOpenAIOAuthAccount(account) && failoverErr.Scope == "" && + ((len(payload) == 0 && strings.HasPrefix(message, "OpenAI stream disconnected before completion")) || + (statusCode == http.StatusServiceUnavailable && failoverErr.RequestScopedTransient)) { + failoverErr.preserveOpenAIOAuthBinding() + } failoverErr = failoverErr.WithGrokForbiddenPolicy(account) if len(payload) > 0 && account != nil { failoverErr.StreamFailedFrame = &OpenAIStreamFailedFrame{Platform: account.Platform, Payload: payload, Message: message} diff --git a/backend/internal/service/openai_gateway_service_test.go b/backend/internal/service/openai_gateway_service_test.go index 866c250ef27f..4559a4bfc843 100644 --- a/backend/internal/service/openai_gateway_service_test.go +++ b/backend/internal/service/openai_gateway_service_test.go @@ -1690,11 +1690,14 @@ func TestOpenAIStreamingReadErrorBeforeOutputReturnsFailover(t *testing.T) { Header: http.Header{"X-Request-Id": []string{"rid-disconnect"}}, } - _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI, Name: "acc"}, time.Now(), "model", "model") + _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Name: "acc"}, time.Now(), "model", "model") require.Error(t, err) var failoverErr *UpstreamFailoverError require.ErrorAs(t, err, &failoverErr) require.Equal(t, http.StatusBadGateway, failoverErr.StatusCode) + require.True(t, failoverErr.RetryableOnSameAccount) + require.True(t, failoverErr.RequestScopedTransient) + require.Equal(t, GatewayFailureScopeRequest, failoverErr.Scope) require.False(t, c.Writer.Written()) require.Empty(t, rec.Body.String()) } diff --git a/backend/internal/service/openai_gateway_upstream_errors.go b/backend/internal/service/openai_gateway_upstream_errors.go index f0839d43e42b..ed45eed02090 100644 --- a/backend/internal/service/openai_gateway_upstream_errors.go +++ b/backend/internal/service/openai_gateway_upstream_errors.go @@ -180,6 +180,38 @@ func isOpenAIRequestScopedCapacityShed(upstreamMsg string, upstreamBody []byte) return isOpenAICapacityShedMessage(upstreamMsg) || isOpenAICapacityShedMessage(string(upstreamBody)) } +func isOpenAIOAuthTransientServerStatus(status int) bool { + switch status { + case 500, 502, 503, 504, 520, 521, 522, 523, 524: + return true + } + return false +} + +// Some relays wrap their own 503 concurrency rejection in an HTTP 401. +// Only the provider's error field can establish that the credential is healthy. +func isOpenAIWrappedConcurrency401(account *Account, status int, body []byte) bool { + if !isOpenAIOAuthAccount(account) || status != http.StatusUnauthorized { + return false + } + providerError := gjson.GetBytes(body, "error") + if providerError.Get("code").String() != "" || providerError.Get("message").Type != gjson.String { + return false + } + message := strings.ToLower(strings.TrimSpace(providerError.Get("message").String())) + const prefix = "authentication failed (status=503):" + inner, wrapped := strings.CutPrefix(message, prefix) + if !wrapped { + return false + } + inner = strings.TrimSpace(inner) + if gjson.Valid(inner) { + reason := gjson.Get(inner, "error") + return reason.Type == gjson.String && strings.EqualFold(strings.TrimSpace(reason.String()), "too many concurrent requests") + } + return inner == "too many concurrent requests" +} + // OpenAIUpstreamCapacityCode preserves transient capacity across relay hops. // model_capacity_exhausted already denotes persisted quota in selection errors. const OpenAIUpstreamCapacityCode = "upstream_capacity_exhausted" @@ -441,7 +473,25 @@ func (s *OpenAIGatewayService) newOpenAIAccountFailoverError( shouldDisable bool, retryableOnSameAccount bool, ) *UpstreamFailoverError { - return s.newOpenAIAccountFailoverErrorWithClassificationHeaders(account, statusCode, responseHeaders, responseHeaders, responseBody, upstreamMsg, shouldDisable, retryableOnSameAccount) + failoverErr := s.newOpenAIAccountFailoverErrorWithClassificationHeaders(account, statusCode, responseHeaders, responseHeaders, responseBody, upstreamMsg, shouldDisable, retryableOnSameAccount) + if shouldDisable || !isOpenAIOAuthAccount(account) || failoverErr.Scope != "" { + return failoverErr + } + if isOpenAIWrappedConcurrency401(account, statusCode, responseBody) { + failoverErr.Reason = OpenAIUpstreamCapacityCode + failoverErr.ClientStatusCode = http.StatusServiceUnavailable + failoverErr.ClientMessage = openAICapacityShedClientMessage(upstreamMsg, responseBody) + } else if !isOpenAIOAuthTransientServerStatus(statusCode) && !(statusCode == 529 && failoverErr.RequestScopedTransient) { + return failoverErr + } + failoverErr.preserveOpenAIOAuthBinding() + return failoverErr +} + +func (e *UpstreamFailoverError) preserveOpenAIOAuthBinding() { + e.Scope = GatewayFailureScopeRequest + e.RequestScopedTransient = true + e.RetryableOnSameAccount = true } func (s *OpenAIGatewayService) newOpenAIAccountFailoverErrorWithClassificationHeaders( @@ -544,7 +594,8 @@ func (e *UpstreamFailoverError) IsOpenAIRequestBodyTooLarge() bool { // IsOpenAICapacityShed reports whether typed client fields were derived from a // recognized provider overload rather than supplied by an unrelated failure. func (e *UpstreamFailoverError) IsOpenAICapacityShed() bool { - return e != nil && e.RequestScopedTransient && isOpenAIRequestScopedCapacityResponse(e.StatusCode, e.ResponseHeaders, e.ResponseBody) + return e != nil && e.RequestScopedTransient && (e.Reason == OpenAIUpstreamCapacityCode || + isOpenAIRequestScopedCapacityResponse(e.StatusCode, e.ResponseHeaders, e.ResponseBody)) } func marshalOpenAIUpstreamJSON(v any) ([]byte, error) { diff --git a/backend/internal/service/openai_oauth_passthrough_test.go b/backend/internal/service/openai_oauth_passthrough_test.go index 8842ec8acc16..c9c6ff38f864 100644 --- a/backend/internal/service/openai_oauth_passthrough_test.go +++ b/backend/internal/service/openai_oauth_passthrough_test.go @@ -1564,8 +1564,21 @@ func TestOpenAIGatewayService_OpenAIPassthrough_RetryableStatusesTriggerFailover statusCode int body string expectFailover bool + keepBinding bool assertRepo func(t *testing.T, repo *openAIPassthroughFailoverRepo, start time.Time) }{ + { + name: "oauth_concurrency_wrapped_in_401", + accountType: AccountTypeOAuth, + statusCode: http.StatusUnauthorized, + body: `{"error":{"type":"authentication_error","message":"authentication failed (status=503): {\"error\":\"Too many concurrent requests\"}"}}`, + expectFailover: true, + keepBinding: true, + assertRepo: func(t *testing.T, repo *openAIPassthroughFailoverRepo, _ time.Time) { + require.Empty(t, repo.rateLimitCalls) + require.Empty(t, repo.overloadCalls) + }, + }, { name: "oauth_429_rate_limit", accountType: AccountTypeOAuth, @@ -1598,7 +1611,8 @@ func TestOpenAIGatewayService_OpenAIPassthrough_RetryableStatusesTriggerFailover accountType: AccountTypeOAuth, statusCode: http.StatusBadGateway, body: `{"error":{"message":"bad gateway","type":"server_error"}}`, - expectFailover: false, + expectFailover: true, + keepBinding: true, assertRepo: func(t *testing.T, repo *openAIPassthroughFailoverRepo, _ time.Time) { require.Empty(t, repo.rateLimitCalls) require.Empty(t, repo.overloadCalls) @@ -1609,7 +1623,8 @@ func TestOpenAIGatewayService_OpenAIPassthrough_RetryableStatusesTriggerFailover accountType: AccountTypeOAuth, statusCode: http.StatusServiceUnavailable, body: `{"error":{"message":"service unavailable","type":"server_error"}}`, - expectFailover: false, + expectFailover: true, + keepBinding: true, assertRepo: func(t *testing.T, repo *openAIPassthroughFailoverRepo, _ time.Time) { require.Empty(t, repo.rateLimitCalls) require.Empty(t, repo.overloadCalls) @@ -1620,7 +1635,8 @@ func TestOpenAIGatewayService_OpenAIPassthrough_RetryableStatusesTriggerFailover accountType: AccountTypeOAuth, statusCode: http.StatusGatewayTimeout, body: `{"error":{"message":"gateway timeout","type":"server_error"}}`, - expectFailover: false, + expectFailover: true, + keepBinding: true, assertRepo: func(t *testing.T, repo *openAIPassthroughFailoverRepo, _ time.Time) { require.Empty(t, repo.rateLimitCalls) require.Empty(t, repo.overloadCalls) @@ -1694,6 +1710,14 @@ func TestOpenAIGatewayService_OpenAIPassthrough_RetryableStatusesTriggerFailover if tc.expectFailover { require.ErrorAs(t, err, &failoverErr) require.Equal(t, tc.statusCode, failoverErr.StatusCode) + require.Equal(t, tc.keepBinding, failoverErr.Scope == GatewayFailureScopeRequest && failoverErr.RequestScopedTransient) + if tc.keepBinding { + require.True(t, failoverErr.RetryableOnSameAccount) + if tc.statusCode == http.StatusUnauthorized { + require.True(t, failoverErr.IsOpenAICapacityShed()) + require.Equal(t, http.StatusServiceUnavailable, failoverErr.ClientStatusCode) + } + } require.False(t, c.Writer.Written(), "retryable passthrough 错误应返回 failover 错误给上层换号,而不是直接向客户端写响应") } else { require.False(t, errors.As(err, &failoverErr)) diff --git a/backend/internal/service/openai_upstream_transport_error.go b/backend/internal/service/openai_upstream_transport_error.go index b2ff98ba903d..93a18f5ae827 100644 --- a/backend/internal/service/openai_upstream_transport_error.go +++ b/backend/internal/service/openai_upstream_transport_error.go @@ -172,14 +172,16 @@ func (s *OpenAIGatewayService) handleOpenAIUpstreamTransportError(ctx context.Co return err } - if classifyUpstreamTransportError(err).Persistent { - s.tempUnscheduleOpenAITransportError(ctx, account, safeErr) - } - - return &UpstreamFailoverError{ + failoverErr := &UpstreamFailoverError{ StatusCode: http.StatusBadGateway, ResponseBody: openAITransportFailoverBody, } + if classifyUpstreamTransportError(err).Persistent { + s.tempUnscheduleOpenAITransportError(ctx, account, safeErr) + } else if isOpenAIOAuthAccount(account) { + failoverErr.preserveOpenAIOAuthBinding() + } + return failoverErr } // tempUnscheduleOpenAITransportError marks an account temporarily unschedulable diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go index 9810d369ab01..80aa95bc04c8 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -391,6 +391,9 @@ func (s *RateLimitService) HandleUpstreamError(ctx context.Context, account *Acc // handleUpstreamErrorAfterStreakReset keeps account policy handling shared with // the OpenAI gateway, which resets the streak before its early-return policies. func (s *RateLimitService) handleUpstreamErrorAfterStreakReset(ctx context.Context, account *Account, statusCode int, headers http.Header, responseBody []byte, requestedModel ...string) (shouldDisable bool) { + if isOpenAIWrappedConcurrency401(account, statusCode, responseBody) { + return false + } ctx, disabledOn429 := s.maybeDisableOpenAISchedulingOn429(ctx, account, statusCode, headers) if disabledOn429 { defer func() { shouldDisable = true }() From 9962b7f83476ccee1f250523814ca39045dc20f8 Mon Sep 17 00:00:00 2001 From: Entropy-Enthalpy <55441397+Entropy-Enthalpy@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:49:11 +0800 Subject: [PATCH 2/7] fix: recover quota refusals and preserve OAuth retry affinity --- .../service/openai_access_state_failover_test.go | 2 +- .../service/openai_gateway_cc_pipeline.go | 2 +- .../internal/service/openai_gateway_forward.go | 4 ++-- .../service/openai_gateway_passthrough.go | 2 +- .../service/openai_gateway_upstream_errors.go | 16 +++++++++++++++- .../service/openai_images_tool_cooldown_test.go | 2 ++ 6 files changed, 22 insertions(+), 6 deletions(-) diff --git a/backend/internal/service/openai_access_state_failover_test.go b/backend/internal/service/openai_access_state_failover_test.go index 6c1c0ba206fc..5a24703f3ee8 100644 --- a/backend/internal/service/openai_access_state_failover_test.go +++ b/backend/internal/service/openai_access_state_failover_test.go @@ -158,7 +158,7 @@ func TestOpenAIHTTPAuthMessagesUseExistingStatusPolicies(t *testing.T) { t.Run("revoked credential with echoed concurrency error", func(t *testing.T) { account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth} body := []byte(`{"error":{"code":"token_revoked","message":"Token has been revoked"},"input":{"error":{"message":"authentication failed (status=503): Too many concurrent requests"}}}`) - err := (&OpenAIGatewayService{}).newOpenAIAccountFailoverError(account, http.StatusUnauthorized, nil, body, "", false, false) + err := (&OpenAIGatewayService{}).newOpenAIHTTPAccountFailoverError(account, http.StatusUnauthorized, nil, body, "", false, false) require.False(t, err.RequestScopedTransient) require.False(t, err.RetryableOnSameAccount) }) diff --git a/backend/internal/service/openai_gateway_cc_pipeline.go b/backend/internal/service/openai_gateway_cc_pipeline.go index 293100c10399..19383086feeb 100644 --- a/backend/internal/service/openai_gateway_cc_pipeline.go +++ b/backend/internal/service/openai_gateway_cc_pipeline.go @@ -184,7 +184,7 @@ func (s *OpenAIGatewayService) failoverOpenAIUpstreamHTTPError( if account.Platform != PlatformGrok && !tempUnscheduled { shouldDisable = s.handleOpenAIAccountUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, upstreamModel) } - return s.newOpenAIAccountFailoverError( + return s.newOpenAIHTTPAccountFailoverError( account, resp.StatusCode, resp.Header, diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 5a861a0e4716..b9a024cccccb 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -1646,7 +1646,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco }) shouldDisable := s.handleFailoverSideEffects(ctx, resp, account, respBody, upstreamModel) - return nil, s.newOpenAIAccountFailoverError( + return nil, s.newOpenAIHTTPAccountFailoverError( account, resp.StatusCode, resp.Header, @@ -1756,7 +1756,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco Message: signal.message, }) shouldDisable := s.handleFailoverSideEffects(ctx, compactResp, account, compactBody, upstreamModel) - return nil, s.newOpenAIAccountFailoverError( + return nil, s.newOpenAIHTTPAccountFailoverError( account, compactResp.StatusCode, compactResp.Header, compactBody, signal.message, shouldDisable, !shouldDisable && account.IsPoolMode() && (account.IsPoolModeRetryableStatus(compactResp.StatusCode) || isOpenAITransientProcessingError(compactResp.StatusCode, signal.message, compactBody)), ) diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index 42b747af5351..22e2fd87dc5e 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -1055,7 +1055,7 @@ func (s *OpenAIGatewayService) handleFailoverErrorResponsePassthrough( Detail: upstreamDetail, UpstreamResponseBody: upstreamDetail, }) - return s.newOpenAIAccountFailoverError( + return s.newOpenAIHTTPAccountFailoverError( account, resp.StatusCode, resp.Header, diff --git a/backend/internal/service/openai_gateway_upstream_errors.go b/backend/internal/service/openai_gateway_upstream_errors.go index ed45eed02090..0eca0e57c33c 100644 --- a/backend/internal/service/openai_gateway_upstream_errors.go +++ b/backend/internal/service/openai_gateway_upstream_errors.go @@ -473,7 +473,21 @@ func (s *OpenAIGatewayService) newOpenAIAccountFailoverError( shouldDisable bool, retryableOnSameAccount bool, ) *UpstreamFailoverError { - failoverErr := s.newOpenAIAccountFailoverErrorWithClassificationHeaders(account, statusCode, responseHeaders, responseHeaders, responseBody, upstreamMsg, shouldDisable, retryableOnSameAccount) + return s.newOpenAIAccountFailoverErrorWithClassificationHeaders(account, statusCode, responseHeaders, responseHeaders, responseBody, upstreamMsg, shouldDisable, retryableOnSameAccount) +} + +// Only raw text-response HTTP failures participate in the OAuth affinity +// policy. Synthetic capability errors retain their caller's retry decision. +func (s *OpenAIGatewayService) newOpenAIHTTPAccountFailoverError( + account *Account, + statusCode int, + responseHeaders http.Header, + responseBody []byte, + upstreamMsg string, + shouldDisable bool, + retryableOnSameAccount bool, +) *UpstreamFailoverError { + failoverErr := s.newOpenAIAccountFailoverError(account, statusCode, responseHeaders, responseBody, upstreamMsg, shouldDisable, retryableOnSameAccount) if shouldDisable || !isOpenAIOAuthAccount(account) || failoverErr.Scope != "" { return failoverErr } diff --git a/backend/internal/service/openai_images_tool_cooldown_test.go b/backend/internal/service/openai_images_tool_cooldown_test.go index 0f38c200d782..75d0d44bbaa0 100644 --- a/backend/internal/service/openai_images_tool_cooldown_test.go +++ b/backend/internal/service/openai_images_tool_cooldown_test.go @@ -106,6 +106,8 @@ func TestHandleOpenAIImagesOAuthResponseError_TextFallbackDoesNotCoolAccount(t * // 换号行为必须原样保留:本 PR 只撤销账号状态写入,不动 failover。 var failover *UpstreamFailoverError require.True(t, errors.As(err, &failover), "仍应触发换号,got %T", err) + require.False(t, failover.RetryableOnSameAccount, "synthetic missing image capability must select another account") + require.False(t, failover.RequestScopedTransient) } // 对照不变式:上游 error 帧点名该状态时仍然冷却,否则等于把功能整个废掉。 From 517f524e6c808583711d7bbf0acd016b1c2781d8 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 22 Nov 2026 16:39:22 +0800 Subject: [PATCH 3/7] =?UTF-8?q?fix:=20=E4=BF=9D=E7=95=99=E9=87=8D=E6=94=BE?= =?UTF-8?q?=E4=BF=9D=E6=8A=A4=E6=8E=A5=E5=8F=A3=E5=B9=B6=E9=99=90=E5=AE=9A?= =?UTF-8?q?=E9=A2=9D=E5=BA=A6=E5=9B=9E=E6=89=A7=E7=9A=84=E6=9D=A5=E6=BA=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../scripts/prepare-replay-red-fixtures.sh | 9 +++++++ .../scripts/prepare-ws-owner-red-fixtures.sh | 1 + .../handler/openai_gateway_handler.go | 2 +- backend/internal/service/gateway_service.go | 22 +++++++++-------- .../service/openai_agent_message_delivery.go | 24 ------------------- .../service/openai_agent_message_recovery.go | 5 +--- .../service/openai_gateway_forward.go | 21 +++++++++------- .../service/openai_tool_provenance.go | 24 +++++++++++++++++++ 8 files changed, 60 insertions(+), 48 deletions(-) diff --git a/.github/scripts/prepare-replay-red-fixtures.sh b/.github/scripts/prepare-replay-red-fixtures.sh index bf893bb07308..811985cdf013 100644 --- a/.github/scripts/prepare-replay-red-fixtures.sh +++ b/.github/scripts/prepare-replay-red-fixtures.sh @@ -178,3 +178,12 @@ if ! git -C "$tree" show "$baseline:$contract" | fi done fi + +# The quota tests use the newer request and discovery receipt types. Preserve +# them on the candidate, including all GREEN jobs. +contract=backend/internal/service/openai_agent_message_recovery.go +target=backend/internal/service/openai_agent_quota_failover_test.go +if test -f "$tree/$target" && ! grep -q 'func openAIAgentQuotaFailoverAllowed' "$tree/$contract" && + test "$(git -C "$tree" hash-object "$contract")" = "$(git -C "$tree" rev-parse "$baseline:$contract")"; then + exclude_absent_fixture "$target" "$contract" +fi diff --git a/.github/scripts/prepare-ws-owner-red-fixtures.sh b/.github/scripts/prepare-ws-owner-red-fixtures.sh index 581bd4f2da5a..fa00e80d5b65 100644 --- a/.github/scripts/prepare-ws-owner-red-fixtures.sh +++ b/.github/scripts/prepare-ws-owner-red-fixtures.sh @@ -65,6 +65,7 @@ exclude_new_fixture() { # New service tests require new private proof/diagnostic types. Their own RED # uses handler tests; every candidate GREEN retains them and all negative cases. exclude_new_fixture backend/internal/service/openai_ws_owner_conflict_test.go +exclude_new_fixture backend/internal/service/openai_agent_quota_failover_test.go # Issue892's later matrix also imports the OAuth dial seam and 400/842 test # helpers absent from these historical overlays. It is not a selected oracle # here; its own RED and every clean candidate GREEN retain both exact files. diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 85da01323cf5..1b52840de901 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -1383,7 +1383,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { if failoverErr.ShouldReportAccountScheduleFailure() { h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, forwardModel, requireCompact, nil), false, nil, err) } - if service.OpenAIAgentRecoveryNoReplay(c.Request.Context(), failoverErr) { + if service.OpenAIAgentRecoveryNoReplay(c.Request.Context()) && !failoverErr.QuotaRejectedBeforeExecution { h.handleFailoverExhausted(c, failoverErr, streamStarted) return } diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 0b6a51464841..4bbdc0ad7f4e 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -800,16 +800,18 @@ type GatewayFailureReason string // trigger account failover. Additive metadata keeps existing composite literals // source-compatible and preserves their legacy retry-next-account behavior. type UpstreamFailoverError struct { - StatusCode int - ResponseBody []byte // 上游响应体,用于错误透传规则匹配 - ResponseHeaders http.Header // 上游响应头,用于透传 cf-ray/cf-mitigated/content-type 等诊断信息 - ForceCacheBilling bool // Antigravity 粘性会话切换时设为 true - RetryableOnSameAccount bool // 临时性错误(如 Google 间歇性 400、空响应),应在同一账号上重试 N 次再切换 - SameAccountRetryDelay time.Duration // 同账号重试的最小间隔;零值使用 handler 默认值 - SameAccountRetryDeadline time.Time // 同账号重试截止时间;零值表示仅受 retryLimit 限制 - SameAccountRetryMax int // 可选的错误级同账号重试上限,低于 handler 默认预算时优先采用 - RequestScopedTransient bool // 故障因素与账号无关(如上游按客户端身份/模型容量降载):可同账号重试,但不得据此对账号做临时封禁 - SafeToFailoverAfterWrite bool // 仅写出 SSE 注释等非语义字节时,仍可在同一客户端流中切换账号 + // QuotaRejectedBeforeExecution is set after any provisional tool receipts are restored. + QuotaRejectedBeforeExecution bool + StatusCode int + ResponseBody []byte // 上游响应体,用于错误透传规则匹配 + ResponseHeaders http.Header // 上游响应头,用于透传 cf-ray/cf-mitigated/content-type 等诊断信息 + ForceCacheBilling bool // Antigravity 粘性会话切换时设为 true + RetryableOnSameAccount bool // 临时性错误(如 Google 间歇性 400、空响应),应在同一账号上重试 N 次再切换 + SameAccountRetryDelay time.Duration // 同账号重试的最小间隔;零值使用 handler 默认值 + SameAccountRetryDeadline time.Time // 同账号重试截止时间;零值表示仅受 retryLimit 限制 + SameAccountRetryMax int // 可选的错误级同账号重试上限,低于 handler 默认预算时优先采用 + RequestScopedTransient bool // 故障因素与账号无关(如上游按客户端身份/模型容量降载):可同账号重试,但不得据此对账号做临时封禁 + SafeToFailoverAfterWrite bool // 仅写出 SSE 注释等非语义字节时,仍可在同一客户端流中切换账号 // HeaderTimeoutSubmitted marks a failover caused by an OpenAI response-header // timeout after the request was written. The upstream may have billed the // attempt; the successful usage record adds one retry surcharge unit. diff --git a/backend/internal/service/openai_agent_message_delivery.go b/backend/internal/service/openai_agent_message_delivery.go index 6188f3d90f83..926138e07105 100644 --- a/backend/internal/service/openai_agent_message_delivery.go +++ b/backend/internal/service/openai_agent_message_delivery.go @@ -185,30 +185,6 @@ func (d *openAIAgentRecoveryDelivery) reserve(items [][32]byte) error { return nil } -// A rejected HTTP request has produced no output. Restore only the discovery -// receipts reserved by this attempt, so the next account can consume them. -func (d *openAIAgentRecoveryDelivery) rejectBeforeExecution() error { - if len(d.keys) != 0 || len(d.epochs) != 0 || len(d.tools) != 0 { - return openAIAgentRecoveryError("owner_conflict") - } - for key, pending := range d.discoveryBindings { - original, ok := d.request.toolProofs[key] - if !ok { - return openAIAgentRecoveryError("owner_conflict") - } - restored, err := d.service.compareAndSwapToolProof(d.ctx, key, pending.raw, original.raw) - if err != nil { - return openAIAgentRecoveryError("store_unavailable") - } - if !restored { - return openAIAgentRecoveryError("owner_conflict") - } - delete(d.discoveryBindings, key) - } - d.finish(false) - return nil -} - func (d *openAIAgentRecoveryDelivery) finish(completed bool) { d.once.Do(func() { final := make(map[[32]byte]bool) diff --git a/backend/internal/service/openai_agent_message_recovery.go b/backend/internal/service/openai_agent_message_recovery.go index 5a5c31f839f0..7667b3c6aa0d 100644 --- a/backend/internal/service/openai_agent_message_recovery.go +++ b/backend/internal/service/openai_agent_message_recovery.go @@ -746,10 +746,7 @@ func openAIAgentQuotaFailoverAllowed(ctx context.Context, status int, body []byt return false } -func OpenAIAgentRecoveryNoReplay(ctx context.Context, failure *UpstreamFailoverError) bool { - if failure != nil && openAIAgentQuotaFailoverAllowed(ctx, failure.StatusCode, failure.ResponseBody) { - return false - } +func OpenAIAgentRecoveryNoReplay(ctx context.Context) bool { return OpenAIAgentToolResultContinuation(ctx) || openAIAgentRecoveryPreservesHistory(ctx) } diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index b9a024cccccb..6cd425d7e61e 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -1586,16 +1586,10 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco // text. Do not borrow field/compact/failover retry budgets here. return s.handleErrorResponse(ctx, resp, c, account, body, resolveOpenAIErrorSchedulingModel(billingModel, upstreamModel)) } - if openAIAgentRecoveryPreservesHistory(ctx) && !openAIAgentQuotaFailoverAllowed(ctx, resp.StatusCode, respBody) { + quotaRejected := openAIAgentQuotaFailoverAllowed(ctx, resp.StatusCode, respBody) + if openAIAgentRecoveryPreservesHistory(ctx) && !quotaRejected { return s.handleErrorResponse(ctx, resp, c, account, body, resolveOpenAIErrorSchedulingModel(billingModel, upstreamModel)) } - if openAIAgentQuotaFailoverAllowed(ctx, resp.StatusCode, respBody) { - if recovery := openAIAgentRecoveryFromContext(ctx); recovery.delivery != nil { - if err := recovery.delivery.rejectBeforeExecution(); err != nil { - return nil, err - } - } - } if retryBody, reason, changed, retryErr := normalizeOpenAIResponsesRejectedFieldRetryBody(resp.StatusCode, body, respBody); retryErr != nil { return nil, fmt.Errorf("normalize rejected Responses field retry body: %w", retryErr) } else if !isControlledExperiment(ctx) && changed && rejectedFieldRetryState.Allow(retryBody) { @@ -1645,8 +1639,15 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco Detail: upstreamDetail, }) + if quotaRejected { + if recovery := openAIAgentRecoveryFromContext(ctx); recovery.delivery != nil { + if err := recovery.delivery.rejectBeforeExecution(); err != nil { + return nil, err + } + } + } shouldDisable := s.handleFailoverSideEffects(ctx, resp, account, respBody, upstreamModel) - return nil, s.newOpenAIHTTPAccountFailoverError( + failover := s.newOpenAIHTTPAccountFailoverError( account, resp.StatusCode, resp.Header, @@ -1655,6 +1656,8 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco shouldDisable, !shouldDisable && account.IsPoolMode() && (account.IsPoolModeRetryableStatus(resp.StatusCode) || isOpenAITransientProcessingError(resp.StatusCode, upstreamMsg, respBody)), ) + failover.QuotaRejectedBeforeExecution = quotaRejected + return nil, failover } return s.handleErrorResponse(ctx, resp, c, account, body, resolveOpenAIErrorSchedulingModel(billingModel, upstreamModel)) } diff --git a/backend/internal/service/openai_tool_provenance.go b/backend/internal/service/openai_tool_provenance.go index ba2f5ff86efc..274424ff1e83 100644 --- a/backend/internal/service/openai_tool_provenance.go +++ b/backend/internal/service/openai_tool_provenance.go @@ -688,6 +688,30 @@ func (s *OpenAIGatewayService) compareAndSwapToolProof(ctx context.Context, key, return true, nil } +// A rejected HTTP request has produced no output. Restore only the discovery +// receipts reserved by this attempt, so the next account can consume them. +func (d *openAIAgentRecoveryDelivery) rejectBeforeExecution() error { + if len(d.keys) != 0 || len(d.epochs) != 0 || len(d.tools) != 0 { + return openAIAgentRecoveryError("owner_conflict") + } + for key, pending := range d.discoveryBindings { + original, ok := d.request.toolProofs[key] + if !ok { + return openAIAgentRecoveryError("owner_conflict") + } + restored, err := d.service.compareAndSwapToolProof(d.ctx, key, pending.raw, original.raw) + if err != nil { + return openAIAgentRecoveryError("store_unavailable") + } + if !restored { + return openAIAgentRecoveryError("owner_conflict") + } + delete(d.discoveryBindings, key) + } + d.finish(false) + return nil +} + func (d *openAIAgentRecoveryDelivery) bindDiscoveryResults() error { for key, snapshot := range d.request.toolProofs { if snapshot.discoveryDigest == "" || snapshot.proof.Discovery != nil { From d71cc2ab1dc1ac41c05ad6f3cb40aacd14fb7d73 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 22 Nov 2026 17:01:17 +0800 Subject: [PATCH 4/7] =?UTF-8?q?fix:=20=E5=B0=86=E4=B8=B4=E6=97=B6=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E7=9A=84=E5=90=8C=E8=B4=A6=E5=8F=B7=E9=87=8D=E8=AF=95?= =?UTF-8?q?=E9=99=90=E5=AE=9A=E4=BA=8E=E6=99=AE=E9=80=9A=20OAuth?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/service/gateway_upstream_response.go | 2 +- .../internal/service/openai_gateway_passthrough.go | 4 ++-- .../service/openai_gateway_upstream_errors.go | 11 +++++++++-- .../service/openai_upstream_transport_error.go | 2 +- 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/backend/internal/service/gateway_upstream_response.go b/backend/internal/service/gateway_upstream_response.go index f0835040b3a9..a657bc3a6b76 100644 --- a/backend/internal/service/gateway_upstream_response.go +++ b/backend/internal/service/gateway_upstream_response.go @@ -1304,7 +1304,7 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http ResponseBody: body, RetryableOnSameAccount: true, } - if isOpenAIOAuthAccount(account) && !classifyUpstreamTransportError(ev.err).Persistent { + if usesOpenAIOAuthRetryAffinity(account) && !classifyUpstreamTransportError(ev.err).Persistent { failoverErr.preserveOpenAIOAuthBinding() } return nil, failoverErr diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index 22e2fd87dc5e..b2e8a8d937bd 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -915,7 +915,7 @@ func shouldFailoverOpenAIPassthroughResponse(account *Account, statusCode int, r if account != nil && account.IsOpenAICompatible() && isUpstreamModelNotFoundError(statusCode, responseBody) { return true } - if isOpenAIWrappedConcurrency401(account, statusCode, responseBody) || (isOpenAIOAuthAccount(account) && isOpenAIOAuthTransientServerStatus(statusCode)) { + if isOpenAIWrappedConcurrency401(account, statusCode, responseBody) || (usesOpenAIOAuthRetryAffinity(account) && isOpenAIOAuthTransientServerStatus(statusCode)) { return true } if account != nil && account.IsPoolMode() && account.IsPoolModeRetryableStatus(statusCode) { @@ -2053,7 +2053,7 @@ func (s *OpenAIGatewayService) newOpenAIStreamFailoverErrorWithModel( failoverErr := s.newOpenAIAccountFailoverErrorWithClassificationHeaders(account, statusCode, headers, classificationHeaders, payload, message, shouldDisable, retryableOnSameAccount) // A nil frame with this message is generated locally on a pre-output disconnect. // Generic provider SSE errors also map to 502; that alone does not identify a disconnect. - if !shouldDisable && isOpenAIOAuthAccount(account) && failoverErr.Scope == "" && + if !shouldDisable && usesOpenAIOAuthRetryAffinity(account) && failoverErr.Scope == "" && ((len(payload) == 0 && strings.HasPrefix(message, "OpenAI stream disconnected before completion")) || (statusCode == http.StatusServiceUnavailable && failoverErr.RequestScopedTransient)) { failoverErr.preserveOpenAIOAuthBinding() diff --git a/backend/internal/service/openai_gateway_upstream_errors.go b/backend/internal/service/openai_gateway_upstream_errors.go index 0eca0e57c33c..cc4dab75e0fe 100644 --- a/backend/internal/service/openai_gateway_upstream_errors.go +++ b/backend/internal/service/openai_gateway_upstream_errors.go @@ -180,6 +180,13 @@ func isOpenAIRequestScopedCapacityShed(upstreamMsg string, upstreamBody []byte) return isOpenAICapacityShedMessage(upstreamMsg) || isOpenAICapacityShedMessage(string(upstreamBody)) } +// Specialized upstreams have their own failover and cooldown contracts. +func usesOpenAIOAuthRetryAffinity(account *Account) bool { + return account != nil && account.IsOpenAIOAuth() && !account.IsExcelOAuth() && + !account.IsExcelBPSEnabled() && !account.IsSIWCEnabled() && !account.IsCopilotSDKEnabled() && + !account.HasManagedOpenAIConnections() && account.AuthConnectionID == "" && !accountHasPrismBrowser(account) +} + func isOpenAIOAuthTransientServerStatus(status int) bool { switch status { case 500, 502, 503, 504, 520, 521, 522, 523, 524: @@ -191,7 +198,7 @@ func isOpenAIOAuthTransientServerStatus(status int) bool { // Some relays wrap their own 503 concurrency rejection in an HTTP 401. // Only the provider's error field can establish that the credential is healthy. func isOpenAIWrappedConcurrency401(account *Account, status int, body []byte) bool { - if !isOpenAIOAuthAccount(account) || status != http.StatusUnauthorized { + if !usesOpenAIOAuthRetryAffinity(account) || status != http.StatusUnauthorized { return false } providerError := gjson.GetBytes(body, "error") @@ -488,7 +495,7 @@ func (s *OpenAIGatewayService) newOpenAIHTTPAccountFailoverError( retryableOnSameAccount bool, ) *UpstreamFailoverError { failoverErr := s.newOpenAIAccountFailoverError(account, statusCode, responseHeaders, responseBody, upstreamMsg, shouldDisable, retryableOnSameAccount) - if shouldDisable || !isOpenAIOAuthAccount(account) || failoverErr.Scope != "" { + if shouldDisable || !usesOpenAIOAuthRetryAffinity(account) || failoverErr.Scope != "" { return failoverErr } if isOpenAIWrappedConcurrency401(account, statusCode, responseBody) { diff --git a/backend/internal/service/openai_upstream_transport_error.go b/backend/internal/service/openai_upstream_transport_error.go index 93a18f5ae827..5bc46bbbfc13 100644 --- a/backend/internal/service/openai_upstream_transport_error.go +++ b/backend/internal/service/openai_upstream_transport_error.go @@ -178,7 +178,7 @@ func (s *OpenAIGatewayService) handleOpenAIUpstreamTransportError(ctx context.Co } if classifyUpstreamTransportError(err).Persistent { s.tempUnscheduleOpenAITransportError(ctx, account, safeErr) - } else if isOpenAIOAuthAccount(account) { + } else if usesOpenAIOAuthRetryAffinity(account) { failoverErr.preserveOpenAIOAuthBinding() } return failoverErr From af6765599ce2491332bd09afa732e34880f8861e Mon Sep 17 00:00:00 2001 From: Entropy-Enthalpy <55441397+Entropy-Enthalpy@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:08:45 +0800 Subject: [PATCH 5/7] test: assert bounded OAuth affinity for legacy continuations --- backend/internal/handler/openai_issue914_legacy_test.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/backend/internal/handler/openai_issue914_legacy_test.go b/backend/internal/handler/openai_issue914_legacy_test.go index f04617118cc1..918a46aece67 100644 --- a/backend/internal/handler/openai_issue914_legacy_test.go +++ b/backend/internal/handler/openai_issue914_legacy_test.go @@ -290,8 +290,7 @@ func TestIssue914LegacyAccountPoolAndCancellation(t *testing.T) { require.Empty(t, calls) } else { require.GreaterOrEqual(t, status, 400) - require.Contains(t, calls, int64(1)) - require.Contains(t, calls, int64(2), "ordinary pre-output failure must be able to select another eligible account") + require.Equal(t, []int64{1, 1, 1, 1}, calls, "legacy history keeps the OAuth account through bounded transient retries") } }) } From 803ae3a281798e553a17d34ca3e7699d55fb7354 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 22 Nov 2026 17:40:27 +0800 Subject: [PATCH 6/7] =?UTF-8?q?fix:=20=E7=AE=80=E5=8C=96=20OAuth=20?= =?UTF-8?q?=E8=BF=87=E8=BD=BD=E7=8A=B6=E6=80=81=E7=9A=84=E6=9D=A1=E4=BB=B6?= =?UTF-8?q?=E5=88=A4=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/service/openai_gateway_upstream_errors.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/internal/service/openai_gateway_upstream_errors.go b/backend/internal/service/openai_gateway_upstream_errors.go index cc4dab75e0fe..b4a59db10e7c 100644 --- a/backend/internal/service/openai_gateway_upstream_errors.go +++ b/backend/internal/service/openai_gateway_upstream_errors.go @@ -502,7 +502,7 @@ func (s *OpenAIGatewayService) newOpenAIHTTPAccountFailoverError( failoverErr.Reason = OpenAIUpstreamCapacityCode failoverErr.ClientStatusCode = http.StatusServiceUnavailable failoverErr.ClientMessage = openAICapacityShedClientMessage(upstreamMsg, responseBody) - } else if !isOpenAIOAuthTransientServerStatus(statusCode) && !(statusCode == 529 && failoverErr.RequestScopedTransient) { + } else if !isOpenAIOAuthTransientServerStatus(statusCode) && (statusCode != 529 || !failoverErr.RequestScopedTransient) { return failoverErr } failoverErr.preserveOpenAIOAuthBinding() From 7da8c4a863b9b54caec4c2c9ecc4dbbdecbe9513 Mon Sep 17 00:00:00 2001 From: Entropy-Enthalpy <55441397+Entropy-Enthalpy@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:18:53 +0800 Subject: [PATCH 7/7] test: align HTTP retry and moderation failover scenarios --- backend/internal/handler/http2_peer_reset_test.go | 2 +- backend/internal/handler/moderation_upstream_http_test.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/internal/handler/http2_peer_reset_test.go b/backend/internal/handler/http2_peer_reset_test.go index 229498d9cbcf..921c7464409a 100644 --- a/backend/internal/handler/http2_peer_reset_test.go +++ b/backend/internal/handler/http2_peer_reset_test.go @@ -428,7 +428,7 @@ func TestHTTP2PeerResetHTTP502Control(t *testing.T) { for len(opsErrorLogQueue) > 0 { flushOpsErrorLogBatch([]opsErrorLogJob{<-opsErrorLogQueue}) } - require.Equal(t, int32(2), submissions.Load(), "actual HTTP refusal retains existing account failover") + require.Equal(t, int32(4), submissions.Load(), "actual OAuth HTTP refusal uses the bounded same-account retry policy") require.Equal(t, 502, rec.Code) require.Len(t, repo.entries, 1) require.NotNil(t, repo.entries[0].UpstreamStatusCode) diff --git a/backend/internal/handler/moderation_upstream_http_test.go b/backend/internal/handler/moderation_upstream_http_test.go index d4f97fbe68c1..e75fbfd02d46 100644 --- a/backend/internal/handler/moderation_upstream_http_test.go +++ b/backend/internal/handler/moderation_upstream_http_test.go @@ -44,8 +44,8 @@ func TestModerationUpstreamHTTPSelectionAndFailover(t *testing.T) { writesB.Add(1) } if isA && strings.HasPrefix(scenario, "failover") { - w.WriteHeader(503) - _, _ = w.Write([]byte(`{"error":{"message":"fixture overloaded"}}`)) + w.WriteHeader(http.StatusTooManyRequests) + _, _ = w.Write([]byte(`{"error":{"type":"usage_limit_reached","message":"fixture account quota exhausted","resets_at":4102444800}}`)) return } if stream || accountType == service.AccountTypeOAuth {