From d07f63ddf8dd57216151d227e21b350ff09bd746 Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 4 Dec 2026 16:30:39 +0800 Subject: [PATCH 1/2] fix(openai): skip same-account overload retries when Retry-After exceeds budget When an OpenAI upstream sheds capacity (`server_is_overloaded` / `slow_down`) and advertises an explicit `Retry-After` longer than the per-retry delay cap (8s, e.g. 315-369s in #9183), replaying a single-credential account every 8s cannot satisfy the upstream window and delays switching to healthy accounts. Switch non-pool accounts immediately on long capacity-shed `Retry-After` hints while keeping short/unspecified blips and pool-mode relays retryable, preserve request-scoped transient semantics (no persistent account cooldown), and log `upstream_retry_after` on retry and switch events. Fixes #9183 Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- backend/internal/handler/failover_loop.go | 17 ++- .../openai_capacity_shed_retry_after_test.go | 91 ++++++++++++ .../handler/openai_chat_completions.go | 10 +- .../handler/openai_gateway_handler.go | 16 +- backend/internal/handler/openai_images.go | 10 +- backend/internal/service/gateway_service.go | 1 + .../service/openai_capacity_shed_test.go | 139 ++++++++++++++++-- .../service/openai_gateway_passthrough.go | 17 ++- .../service/openai_gateway_upstream_errors.go | 69 +++------ 9 files changed, 283 insertions(+), 87 deletions(-) create mode 100644 backend/internal/handler/openai_capacity_shed_retry_after_test.go diff --git a/backend/internal/handler/failover_loop.go b/backend/internal/handler/failover_loop.go index 56c39af103..cd227e1e60 100644 --- a/backend/internal/handler/failover_loop.go +++ b/backend/internal/handler/failover_loop.go @@ -55,6 +55,13 @@ const ( // 语义上等同于「无可用账号」:候选账号都不满足分组的利润约束。 const profitVetoExhaustedMessage = "No available accounts: all candidates rejected by group profit control" +func appendUpstreamRetryAfterField(fields []zap.Field, failoverErr *service.UpstreamFailoverError) []zap.Field { + if failoverErr != nil && failoverErr.UpstreamRetryAfter > 0 { + return append(fields, zap.Duration("upstream_retry_after", failoverErr.UpstreamRetryAfter)) + } + return fields +} + func sameAccountRetryDelayFor(failoverErr *service.UpstreamFailoverError, retryCount int) time.Duration { if failoverErr == nil { return sameAccountRetryDelay @@ -220,13 +227,14 @@ func (s *FailoverState) HandleFailoverError( if sameAccountRetry { s.SameAccountRetryCount[accountID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, s.SameAccountRetryCount[accountID]) - logger.FromContext(ctx).Warn("gateway.failover_same_account_retry", + retryFields := appendUpstreamRetryAfterField([]zap.Field{ zap.Int64("account_id", accountID), zap.Int("upstream_status", failoverErr.StatusCode), zap.Int("same_account_retry_count", s.SameAccountRetryCount[accountID]), zap.Int("same_account_retry_max", retryLimit), zap.Duration("retry_delay", retryDelay), - ) + }, failoverErr) + logger.FromContext(ctx).Warn("gateway.failover_same_account_retry", retryFields...) if !sleepWithContext(ctx, retryDelay) { return FailoverCanceled } @@ -248,12 +256,13 @@ func (s *FailoverState) HandleFailoverError( // 递增切换计数 s.SwitchCount++ - logger.FromContext(ctx).Warn("gateway.failover_switch_account", + switchFields := appendUpstreamRetryAfterField([]zap.Field{ zap.Int64("account_id", accountID), zap.Int("upstream_status", failoverErr.StatusCode), zap.Int("switch_count", s.SwitchCount), zap.Int("max_switches", s.MaxSwitches), - ) + }, failoverErr) + logger.FromContext(ctx).Warn("gateway.failover_switch_account", switchFields...) // Antigravity 平台换号线性递增延时 if platform == service.PlatformAntigravity { diff --git a/backend/internal/handler/openai_capacity_shed_retry_after_test.go b/backend/internal/handler/openai_capacity_shed_retry_after_test.go new file mode 100644 index 0000000000..9db7d8accb --- /dev/null +++ b/backend/internal/handler/openai_capacity_shed_retry_after_test.go @@ -0,0 +1,91 @@ +//go:build unit + +package handler + +import ( + "bytes" + "fmt" + "io" + "net/http" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func capacityShedSSEOverloadResponse(retryAfterSec string) *http.Response { + stream := fmt.Sprintf( + "event: response.created\n"+ + "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_shed\"}}\n\n"+ + "event: error\n"+ + "data: {\"type\":\"error\",\"error\":{\"type\":\"service_unavailable_error\",\"code\":\"server_is_overloaded\",\"message\":\"Our servers are currently overloaded. Please try again later.\",\"headers\":{\"retry-after\":%q}}}\n\n", + retryAfterSec, + ) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(bytes.NewBufferString(stream)), + } +} + +func capacityShedHTTPOverloadResponse(retryAfterMs string) *http.Response { + h := http.Header{"Content-Type": []string{"application/json"}} + if retryAfterMs != "" { + h.Set("Retry-After-Ms", retryAfterMs) + } + return &http.Response{ + StatusCode: http.StatusServiceUnavailable, + Header: h, + Body: io.NopCloser(bytes.NewBufferString( + `{"error":{"type":"service_unavailable_error","code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later."}}`, + )), + } +} + +func TestOpenAIGatewayHandlerResponses_LongOverloadRetryAfterSwitchesImmediately(t *testing.T) { + gin.SetMode(gin.TestMode) + + upstream := newAstraProCapturedUpstream(capacityShedSSEOverloadResponse("315"), astra200()) + handler := newOpenAIResponsesFailoverTestHandler(t, upstream) + c, rec := newAstraProFailoverContext(t, astraProRequestBody) + + handler.Responses(c) + + _, accountIDs, _ := upstream.snapshot() + require.Equal(t, []int64{1, 2}, accountIDs) + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, "completed", gjson.GetBytes(rec.Body.Bytes(), "status").String()) +} + +func TestOpenAIGatewayHandlerResponses_ShortOverloadRetryAfterRetriesSameAccount(t *testing.T) { + gin.SetMode(gin.TestMode) + + upstream := newAstraProCapturedUpstream(capacityShedHTTPOverloadResponse("10"), astra200()) + handler := newOpenAIResponsesFailoverTestHandler(t, upstream) + c, rec := newAstraProFailoverContext(t, astraProRequestBody) + + handler.Responses(c) + + _, accountIDs, _ := upstream.snapshot() + require.Equal(t, []int64{1, 1}, accountIDs) + require.Equal(t, http.StatusOK, rec.Code) +} + +func TestOpenAIGatewayHandlerResponses_AllAccountsLongOverloadFailsFast503(t *testing.T) { + gin.SetMode(gin.TestMode) + + upstream := newAstraProCapturedUpstream( + capacityShedSSEOverloadResponse("315"), + capacityShedSSEOverloadResponse("335"), + ) + handler := newOpenAIResponsesFailoverTestHandler(t, upstream) + c, rec := newAstraProFailoverContext(t, astraProRequestBody) + + handler.Responses(c) + + _, accountIDs, _ := upstream.snapshot() + require.Equal(t, []int64{1, 2}, accountIDs) + require.Equal(t, http.StatusServiceUnavailable, rec.Code) + require.Contains(t, gjson.GetBytes(rec.Body.Bytes(), "error.message").String(), "servers are currently overloaded") +} diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index f8d7deb4dc..6d98f76e72 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -359,13 +359,14 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) { sameAccountRetryCount[account.ID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) - reqLog.Warn("openai_chat_completions.pool_mode_same_account_retry", + retryFields := appendUpstreamRetryAfterField([]zap.Field{ zap.Int64("account_id", account.ID), zap.Int("upstream_status", failoverErr.StatusCode), zap.Int("retry_limit", retryLimit), zap.Int("retry_count", sameAccountRetryCount[account.ID]), zap.Duration("retry_delay", retryDelay), - ) + }, failoverErr) + reqLog.Warn("openai_chat_completions.pool_mode_same_account_retry", retryFields...) select { case <-c.Request.Context().Done(): return @@ -386,12 +387,13 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { h.handleFailoverExhausted(c, failoverErr, streamStarted) return } - reqLog.Warn("openai_chat_completions.upstream_failover_switching", + switchFields := appendUpstreamRetryAfterField([]zap.Field{ zap.Int64("account_id", account.ID), zap.Int("upstream_status", failoverErr.StatusCode), zap.Int("switch_count", switchCount), zap.Int("max_switches", maxAccountSwitches), - ) + }, failoverErr) + reqLog.Warn("openai_chat_completions.upstream_failover_switching", switchFields...) continue } h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, reqModel, false, nil), false, nil, err) diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 280074a180..8c44584ec6 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -981,13 +981,14 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) { sameAccountRetryCount[account.ID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) - reqLog.Warn("openai.pool_mode_same_account_retry", + retryFields := appendUpstreamRetryAfterField([]zap.Field{ zap.Int64("account_id", account.ID), zap.Int("upstream_status", failoverErr.StatusCode), zap.Int("retry_limit", retryLimit), zap.Int("retry_count", sameAccountRetryCount[account.ID]), zap.Duration("retry_delay", retryDelay), - ) + }, failoverErr) + reqLog.Warn("openai.pool_mode_same_account_retry", retryFields...) select { case <-c.Request.Context().Done(): return @@ -1024,6 +1025,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { } else if account.ProxyID != nil { failoverSwitchFields = append(failoverSwitchFields, zap.Int64p("proxy_id", account.ProxyID)) } + failoverSwitchFields = appendUpstreamRetryAfterField(failoverSwitchFields, failoverErr) reqLog.Warn("openai.upstream_failover_switching", failoverSwitchFields...) continue } @@ -1561,13 +1563,14 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) { sameAccountRetryCount[account.ID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) - reqLog.Warn("openai_messages.pool_mode_same_account_retry", + retryFields := appendUpstreamRetryAfterField([]zap.Field{ zap.Int64("account_id", account.ID), zap.Int("upstream_status", failoverErr.StatusCode), zap.Int("retry_limit", retryLimit), zap.Int("retry_count", sameAccountRetryCount[account.ID]), zap.Duration("retry_delay", retryDelay), - ) + }, failoverErr) + reqLog.Warn("openai_messages.pool_mode_same_account_retry", retryFields...) select { case <-c.Request.Context().Done(): return @@ -1588,12 +1591,13 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { h.handleAnthropicFailoverExhausted(c, failoverErr, streamStarted) return } - reqLog.Warn("openai_messages.upstream_failover_switching", + switchFields := appendUpstreamRetryAfterField([]zap.Field{ zap.Int64("account_id", account.ID), zap.Int("upstream_status", failoverErr.StatusCode), zap.Int("switch_count", switchCount), zap.Int("max_switches", maxAccountSwitches), - ) + }, failoverErr) + reqLog.Warn("openai_messages.upstream_failover_switching", switchFields...) continue } if result != nil && result.ClientDisconnect { diff --git a/backend/internal/handler/openai_images.go b/backend/internal/handler/openai_images.go index 3976d13336..7fe6201133 100644 --- a/backend/internal/handler/openai_images.go +++ b/backend/internal/handler/openai_images.go @@ -333,13 +333,14 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) { sameAccountRetryCount[account.ID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) - reqLog.Warn("openai.images.pool_mode_same_account_retry", + retryFields := appendUpstreamRetryAfterField([]zap.Field{ zap.Int64("account_id", account.ID), zap.Int("upstream_status", failoverErr.StatusCode), zap.Int("retry_limit", retryLimit), zap.Int("retry_count", sameAccountRetryCount[account.ID]), zap.Duration("retry_delay", retryDelay), - ) + }, failoverErr) + reqLog.Warn("openai.images.pool_mode_same_account_retry", retryFields...) select { case <-requestCtx.Done(): return @@ -360,12 +361,13 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { h.handleFailoverExhausted(c, failoverErr, streamStarted) return } - reqLog.Warn("openai.images.upstream_failover_switching", + switchFields := appendUpstreamRetryAfterField([]zap.Field{ zap.Int64("account_id", account.ID), zap.Int("upstream_status", failoverErr.StatusCode), zap.Int("switch_count", switchCount), zap.Int("max_switches", maxAccountSwitches), - ) + }, failoverErr) + reqLog.Warn("openai.images.upstream_failover_switching", switchFields...) continue } h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, requestModel, false, result), false, nil, err) diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 819b5ebed9..380158a9a7 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -794,6 +794,7 @@ type UpstreamFailoverError struct { ForceCacheBilling bool // Antigravity 粘性会话切换时设为 true RetryableOnSameAccount bool // 临时性错误(如 Google 间歇性 400、空响应),应在同一账号上重试 N 次再切换 SameAccountRetryDelay time.Duration // 同账号重试的最小间隔;零值使用 handler 默认值 + UpstreamRetryAfter time.Duration // 上游原始 Retry-After 建议时长(未截断),用于决策与可观测日志 SameAccountRetryDeadline time.Time // 同账号重试截止时间;零值表示仅受 retryLimit 限制 SameAccountRetryMax int // 可选的错误级同账号重试上限,低于 handler 默认预算时优先采用 RequestScopedTransient bool // 故障因素与账号无关(如上游按客户端身份/模型容量降载):可同账号重试,但不得据此对账号做临时封禁 diff --git a/backend/internal/service/openai_capacity_shed_test.go b/backend/internal/service/openai_capacity_shed_test.go index e6eca95b36..fc6dba24ae 100644 --- a/backend/internal/service/openai_capacity_shed_test.go +++ b/backend/internal/service/openai_capacity_shed_test.go @@ -112,16 +112,78 @@ func TestOpenAIHTTPCapacityShedIsRequestScopedForOAuthAccounts(t *testing.T) { func TestOpenAICapacityShedHonorsRetryAfter(t *testing.T) { for _, test := range []struct { - name string - headers http.Header - body string - want time.Duration + name string + headers http.Header + body string + callerSameAccount bool + wantDelay time.Duration + wantUpstreamHint time.Duration + wantSameAccountTry bool }{ - {name: "http seconds", headers: http.Header{"Retry-After": []string{"6"}}, want: 6 * time.Second}, - {name: "http milliseconds", headers: http.Header{"Retry-After-Ms": []string{"6000"}}, want: 6 * time.Second}, - {name: "body seconds", body: `{"error":{"headers":{"retry-after":"7"},"message":"Our servers are currently overloaded. Please try again later."}}`, want: 7 * time.Second}, - {name: "body milliseconds", body: `{"response":{"error":{"headers":{"retry-after-ms":"7000"},"message":"Our servers are currently overloaded. Please try again later."}}}`, want: 7 * time.Second}, - {name: "bounded", headers: http.Header{"Retry-After": []string{"60"}}, want: openAIRequestScopedRetryMaxDelay}, + { + name: "missing retry-after keeps same-account retry", + body: `{"error":{"code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later."}}`, + wantDelay: 0, + wantUpstreamHint: 0, + wantSameAccountTry: true, + }, + { + name: "http seconds within budget", + headers: http.Header{"Retry-After": []string{"6"}}, + wantDelay: 6 * time.Second, + wantUpstreamHint: 6 * time.Second, + wantSameAccountTry: true, + }, + { + name: "http milliseconds within budget", + headers: http.Header{"Retry-After-Ms": []string{"6000"}}, + wantDelay: 6 * time.Second, + wantUpstreamHint: 6 * time.Second, + wantSameAccountTry: true, + }, + { + name: "body seconds within budget", + body: `{"error":{"headers":{"retry-after":"7"},"message":"Our servers are currently overloaded. Please try again later."}}`, + wantDelay: 7 * time.Second, + wantUpstreamHint: 7 * time.Second, + wantSameAccountTry: true, + }, + { + name: "body milliseconds within budget", + body: `{"response":{"error":{"headers":{"retry-after-ms":"7000"},"message":"Our servers are currently overloaded. Please try again later."}}}`, + wantDelay: 7 * time.Second, + wantUpstreamHint: 7 * time.Second, + wantSameAccountTry: true, + }, + { + name: "exact max delay boundary still retries same account", + headers: http.Header{"Retry-After": []string{"8"}}, + wantDelay: openAIRequestScopedRetryMaxDelay, + wantUpstreamHint: openAIRequestScopedRetryMaxDelay, + wantSameAccountTry: true, + }, + { + name: "long http retry-after skips non-pool same-account retry", + headers: http.Header{"Retry-After": []string{"60"}}, + wantDelay: openAIRequestScopedRetryMaxDelay, + wantUpstreamHint: 60 * time.Second, + wantSameAccountTry: false, + }, + { + name: "long event retry-after skips non-pool same-account retry", + body: `{"type":"error","error":{"code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later.","headers":{"retry-after":"315"}}}`, + wantDelay: openAIRequestScopedRetryMaxDelay, + wantUpstreamHint: 315 * time.Second, + wantSameAccountTry: false, + }, + { + name: "pool-mode caller retains bounded same-account retry on long hint", + body: `{"type":"error","error":{"code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later.","headers":{"retry-after":"315"}}}`, + callerSameAccount: true, + wantDelay: openAIRequestScopedRetryMaxDelay, + wantUpstreamHint: 315 * time.Second, + wantSameAccountTry: true, + }, } { t.Run(test.name, func(t *testing.T) { failoverErr := newOpenAIUpstreamFailoverError( @@ -129,14 +191,69 @@ func TestOpenAICapacityShedHonorsRetryAfter(t *testing.T) { test.headers, []byte(test.body), "Our servers are currently overloaded. Please try again later.", - false, + test.callerSameAccount, ) require.True(t, failoverErr.RequestScopedTransient) - require.Equal(t, test.want, failoverErr.SameAccountRetryDelay) + require.Equal(t, test.wantDelay, failoverErr.SameAccountRetryDelay) + require.Equal(t, test.wantUpstreamHint, failoverErr.UpstreamRetryAfter) + require.Equal(t, test.wantSameAccountTry, failoverErr.RetryableOnSameAccount) }) } } +func TestOpenAIStreamCapacityShedLongRetryAfterSkipsSameAccountReplay(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, passthrough := range []bool{false, true} { + for _, tc := range []struct { + name string + retryAfter string + poolMode bool + wantSameAccount bool + wantHint time.Duration + }{ + {name: "short_7s_oauth", retryAfter: "7", wantSameAccount: true, wantHint: 7 * time.Second}, + {name: "long_315s_oauth_switches", retryAfter: "315", wantSameAccount: false, wantHint: 315 * time.Second}, + {name: "long_315s_pool_keeps_retry", retryAfter: "315", poolMode: true, wantSameAccount: true, wantHint: 315 * time.Second}, + } { + t.Run(fmt.Sprintf("passthrough=%t/%s", passthrough, tc.name), func(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}}} + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + stream := strings.Join([]string{ + "event: response.created", + `data: {"type":"response.created","response":{"id":"resp_1"}}`, + "", + "event: error", + fmt.Sprintf(`data: {"type":"error","error":{"type":"service_unavailable_error","code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later.","headers":{"retry-after":%q}}}`, tc.retryAfter), + "", + }, "\n") + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{}, + Body: io.NopCloser(strings.NewReader(stream)), + } + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Name: "acc"} + if tc.poolMode { + account.Type = AccountTypeAPIKey + account.Credentials = map[string]any{"pool_mode": true} + } + var err error + if passthrough { + _, err = svc.handleStreamingResponsePassthrough(c.Request.Context(), resp, c, account, time.Now(), "model", "model") + } else { + _, err = svc.handleStreamingResponse(c.Request.Context(), resp, c, account, time.Now(), "model", "model") + } + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.True(t, failoverErr.RequestScopedTransient) + require.Equal(t, tc.wantSameAccount, failoverErr.RetryableOnSameAccount) + require.Equal(t, tc.wantHint, failoverErr.UpstreamRetryAfter) + }) + } + } +} + // 上游降载的真实序列是「event: error → event: response.failed」。error 帧不算 // 客户端输出:若把它当首输出 flush,clientOutputStarted 被固化,随后的 failed // 事件就进不了 pre-output failover 分支,只能把致命错误原样转发给客户端。 diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index c683c5f2e2..ca29a68c6b 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -1922,15 +1922,20 @@ func (s *OpenAIGatewayService) handleOpenAIStreamTerminalAccountSideEffects( } func openAIStreamFailedEventRetryableOnSameAccount(account *Account, payload []byte, message string) bool { + return openAIStreamFailedEventRetryableOnSameAccountWithHeaders(account, nil, payload, message) +} + +func openAIStreamFailedEventRetryableOnSameAccountWithHeaders(account *Account, headers http.Header, payload []byte, message string) bool { if account == nil { return false } - // 容量降载是请求级信号,不是账号级故障:上游只是让本次请求稍后再试。 - // 换账号并不改变被降载的因素(客户端身份、模型容量都与账号无关), - // 只会让单个请求把整池账号逐个消耗掉,最终仍以同一个错误告终。 - // 因此先在同一账号上做有界重试,用尽后才按常规流程切号。 + // 容量降载是请求级信号,不是账号级故障:短时过载先在同一账号上做有界重试; + // 若上游明确建议等待时长超过单次同号重试预算上限,非池模式单凭据账号不再盲目原地重放,直接优先尝试其他可用账号。 if isOpenAIUpstreamCapacityShedEvent(payload) { - return true + upstreamRetryAfter, _ := parseUpstreamRetryAfterDelay(headers, payload) + if openAICapacityShedAllowsSameAccountRetry(upstreamRetryAfter) { + return true + } } if !account.IsPoolMode() { return false @@ -2035,7 +2040,7 @@ func (s *OpenAIGatewayService) newOpenAIStreamFailoverErrorWithModel( "message": message, }, }) - retryableOnSameAccount := openAIStreamFailedEventRetryableOnSameAccount(account, payload, message) + retryableOnSameAccount := openAIStreamFailedEventRetryableOnSameAccountWithHeaders(account, headers, payload, message) // 流终止事件承载在 HTTP 200 内,外层响应头描述的是成功流状态,而不是语义上的 // 429 事件。仅在配额分类时忽略这些头;故障转移错误仍保留它们,使 Retry-After // 和请求 ID 能继续传递给后续处理。 diff --git a/backend/internal/service/openai_gateway_upstream_errors.go b/backend/internal/service/openai_gateway_upstream_errors.go index 503fabe728..9519219ecf 100644 --- a/backend/internal/service/openai_gateway_upstream_errors.go +++ b/backend/internal/service/openai_gateway_upstream_errors.go @@ -7,7 +7,6 @@ import ( "fmt" "io" "net/http" - "strconv" "strings" "time" @@ -197,59 +196,19 @@ func isOpenAIRequestScopedCapacityShed(upstreamMsg string, upstreamBody []byte) const openAIRequestScopedRetryMaxDelay = 8 * time.Second +func openAICapacityShedAllowsSameAccountRetry(upstreamRetryAfter time.Duration) bool { + return upstreamRetryAfter <= 0 || upstreamRetryAfter <= openAIRequestScopedRetryMaxDelay +} + func openAIRequestScopedRetryDelay(responseHeaders http.Header, responseBody []byte) time.Duration { - type retryAfterValue struct { - raw string - milliseconds bool + delay, ok := parseUpstreamRetryAfterDelay(responseHeaders, responseBody) + if !ok || delay <= 0 { + return 0 } - for _, value := range []retryAfterValue{ - {raw: responseHeaders.Get("Retry-After")}, - {raw: responseHeaders.Get("Retry-After-Ms"), milliseconds: true}, - {raw: gjson.GetBytes(responseBody, "error.headers.retry-after").String()}, - {raw: gjson.GetBytes(responseBody, "response.error.headers.retry-after").String()}, - {raw: gjson.GetBytes(responseBody, "error.headers.retry-after-ms").String(), milliseconds: true}, - {raw: gjson.GetBytes(responseBody, "response.error.headers.retry-after-ms").String(), milliseconds: true}, - } { - raw := strings.TrimSpace(value.raw) - if raw == "" { - continue - } - var delay time.Duration - var ok bool - if value.milliseconds { - delay, ok = parseOpenAIRequestScopedRetryDelayMilliseconds(raw) - } else { - delay, ok = parseOpenAIRequestScopedRetryDelay(raw) - } - if !ok || delay <= 0 { - continue - } - if delay > openAIRequestScopedRetryMaxDelay { - return openAIRequestScopedRetryMaxDelay - } - return delay + if delay > openAIRequestScopedRetryMaxDelay { + return openAIRequestScopedRetryMaxDelay } - return 0 -} - -func parseOpenAIRequestScopedRetryDelay(raw string) (time.Duration, bool) { - if seconds, err := strconv.ParseFloat(raw, 64); err == nil && seconds > 0 { - return time.Duration(seconds * float64(time.Second)), true - } - if resetAt, err := http.ParseTime(raw); err == nil { - delay := time.Until(resetAt) - if delay > 0 { - return delay, true - } - } - return 0, false -} - -func parseOpenAIRequestScopedRetryDelayMilliseconds(raw string) (time.Duration, bool) { - if millis, err := strconv.ParseFloat(raw, 64); err == nil && millis > 0 { - return time.Duration(millis * float64(time.Millisecond)), true - } - return 0, false + return delay } func isOpenAIContextWindowError(upstreamMsg string, upstreamBody []byte) bool { @@ -388,12 +347,18 @@ func newOpenAIUpstreamFailoverError( retryableOnSameAccount bool, ) *UpstreamFailoverError { requestScopedCapacity := isOpenAIRequestScopedCapacityShed(upstreamMsg, responseBody) + var upstreamRetryAfter time.Duration + if requestScopedCapacity { + upstreamRetryAfter, _ = parseUpstreamRetryAfterDelay(responseHeaders, responseBody) + } + capacitySameAccountRetry := requestScopedCapacity && openAICapacityShedAllowsSameAccountRetry(upstreamRetryAfter) failoverErr := &UpstreamFailoverError{ StatusCode: statusCode, ResponseBody: responseBody, ResponseHeaders: responseHeaders.Clone(), - RetryableOnSameAccount: retryableOnSameAccount || requestScopedCapacity, + RetryableOnSameAccount: retryableOnSameAccount || capacitySameAccountRetry, RequestScopedTransient: requestScopedCapacity, + UpstreamRetryAfter: upstreamRetryAfter, } if requestScopedCapacity { failoverErr.SameAccountRetryDelay = openAIRequestScopedRetryDelay(responseHeaders, responseBody) From 332f45f858694c28f80314ea53ed7a67b3a3430c Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 4 Dec 2026 17:27:09 +0800 Subject: [PATCH 2/2] fix(openai): guard 429-wrapped capacity shed against long Retry-After window When a capacity-shed event (`slow_down` / `server_is_overloaded`) arrives with a 429 status and an explicit `Retry-After` exceeding the 8s same-account budget, skip opening the 2-minute OAuth 429 retry deadline window as well, and emit `upstream_retry_after` across WebSocket, Embeddings, and AlphaSearch logs. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- backend/internal/handler/openai_alpha_search.go | 10 ++++++---- backend/internal/handler/openai_embeddings.go | 5 +++-- backend/internal/handler/openai_gateway_handler.go | 5 +++-- .../internal/service/openai_capacity_shed_test.go | 12 ++++++++++++ .../service/openai_gateway_upstream_errors.go | 5 +++++ 5 files changed, 29 insertions(+), 8 deletions(-) diff --git a/backend/internal/handler/openai_alpha_search.go b/backend/internal/handler/openai_alpha_search.go index ffd5f3cfcf..c1bb573120 100644 --- a/backend/internal/handler/openai_alpha_search.go +++ b/backend/internal/handler/openai_alpha_search.go @@ -242,13 +242,14 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) { if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) { sameAccountRetryCount[account.ID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) - reqLog.Warn("openai_alpha_search.same_account_retry", + retryFields := appendUpstreamRetryAfterField([]zap.Field{ zap.Int64("account_id", account.ID), zap.Int("upstream_status", failoverErr.StatusCode), zap.Int("retry_limit", retryLimit), zap.Int("retry_count", sameAccountRetryCount[account.ID]), zap.Duration("retry_delay", retryDelay), - ) + }, failoverErr) + reqLog.Warn("openai_alpha_search.same_account_retry", retryFields...) select { case <-c.Request.Context().Done(): return @@ -269,11 +270,12 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) { h.handleFailoverExhausted(c, failoverErr, false) return } - reqLog.Warn("openai_alpha_search.upstream_failover_switching", + switchFields := appendUpstreamRetryAfterField([]zap.Field{ zap.Int64("account_id", account.ID), zap.Int("upstream_status", failoverErr.StatusCode), zap.Int("switch_count", switchCount), - ) + }, failoverErr) + reqLog.Warn("openai_alpha_search.upstream_failover_switching", switchFields...) } } diff --git a/backend/internal/handler/openai_embeddings.go b/backend/internal/handler/openai_embeddings.go index f96f6240b6..e606726682 100644 --- a/backend/internal/handler/openai_embeddings.go +++ b/backend/internal/handler/openai_embeddings.go @@ -247,12 +247,13 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) { return } switchCount++ - reqLog.Warn("openai_embeddings.upstream_failover_switching", + switchFields := appendUpstreamRetryAfterField([]zap.Field{ zap.Int64("account_id", account.ID), zap.Int("upstream_status", failoverErr.StatusCode), zap.Int("switch_count", switchCount), zap.Int("max_switches", maxAccountSwitches), - ) + }, failoverErr) + reqLog.Warn("openai_embeddings.upstream_failover_switching", switchFields...) continue } h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, reqModel, false, result), false, nil, err) diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 8c44584ec6..5dbd315547 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -3081,12 +3081,13 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { closeOpenAIWSFailoverExhausted(c, wsConn, failoverErr) return false } - reqLog.Warn("openai.websocket_upstream_failover_switching", + wsSwitchFields := appendUpstreamRetryAfterField([]zap.Field{ zap.Int64("account_id", account.ID), zap.Int("upstream_status", failoverErr.StatusCode), zap.Int("switch_count", switchCount), zap.Int("max_switches", maxAccountSwitches), - ) + }, failoverErr) + reqLog.Warn("openai.websocket_upstream_failover_switching", wsSwitchFields...) if ctx.Err() != nil { return false } diff --git a/backend/internal/service/openai_capacity_shed_test.go b/backend/internal/service/openai_capacity_shed_test.go index fc6dba24ae..358673ffe1 100644 --- a/backend/internal/service/openai_capacity_shed_test.go +++ b/backend/internal/service/openai_capacity_shed_test.go @@ -254,6 +254,18 @@ func TestOpenAIStreamCapacityShedLongRetryAfterSkipsSameAccountReplay(t *testing } } +func TestOpenAIOAuth429WrappedCapacityShedLongRetryAfterSkipsDeadlineWindow(t *testing.T) { + svc := &OpenAIGatewayService{} + account := &Account{ID: 921, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + payload := []byte(`{"type":"error","error":{"type":"rate_limit_error","code":"slow_down","message":"Our servers are currently overloaded. Please try again later.","headers":{"retry-after":"315"}}}`) + err := svc.newOpenAIAccountFailoverError(account, http.StatusTooManyRequests, nil, payload, "Our servers are currently overloaded. Please try again later.", false, false) + + require.True(t, err.RequestScopedTransient) + require.False(t, err.RetryableOnSameAccount) + require.True(t, err.SameAccountRetryDeadline.IsZero()) + require.Equal(t, 315*time.Second, err.UpstreamRetryAfter) +} + // 上游降载的真实序列是「event: error → event: response.failed」。error 帧不算 // 客户端输出:若把它当首输出 flush,clientOutputStarted 被固化,随后的 failed // 事件就进不了 pre-output failover 分支,只能把致命错误原样转发给客户端。 diff --git a/backend/internal/service/openai_gateway_upstream_errors.go b/backend/internal/service/openai_gateway_upstream_errors.go index 9519219ecf..9d115a6abf 100644 --- a/backend/internal/service/openai_gateway_upstream_errors.go +++ b/backend/internal/service/openai_gateway_upstream_errors.go @@ -413,6 +413,11 @@ func (s *OpenAIGatewayService) newOpenAIAccountFailoverErrorWithClassificationHe retryableOnSameAccount bool, ) *UpstreamFailoverError { oauth429Retry := s.shouldRetryOpenAIOAuth429OnSameAccountWithResponse(account, statusCode, shouldDisable, classificationHeaders, responseBody) + if oauth429Retry && isOpenAIRequestScopedCapacityShed(upstreamMsg, responseBody) { + if upstreamRetryAfter, ok := parseUpstreamRetryAfterDelay(responseHeaders, responseBody); ok && !openAICapacityShedAllowsSameAccountRetry(upstreamRetryAfter) { + oauth429Retry = false + } + } failoverErr := newOpenAIUpstreamFailoverError( statusCode, responseHeaders,