From d07f63ddf8dd57216151d227e21b350ff09bd746 Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 4 Dec 2026 16:30:39 +0800 Subject: [PATCH 1/5] 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 547c35acf54a992f5c385a73720f609c5051e424 Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 4 Dec 2026 16:44:02 +0800 Subject: [PATCH 2/5] fix(openai): support image/mask/markup inputs on unified /v1/images/generations GPT Image 2.6 callers using the unified `/v1/images/generations` protocol pass reference `images` / `image`, `mask`, and `markup` directly on `generations` rather than `/v1/images/edits`. Previously, input-image parsing and Codex OAuth payload construction were gated behind `IsEdits()`, silently dropping image inputs (and skipping image moderation) on `/v1/images/generations`. - Parse, validate, moderate, and forward `images`/`image`, `mask`, and `markup` on `/v1/images/generations` (JSON and multipart) as well as `/v1/images/edits`. - Recognize bare `gpt-image-2.6` and `gpt-image-2.6-*` snapshots consistently in direct routing, Responses-fallback guard, and fallback pricing. - Automatically fall forward from `/backend-api/codex/images/edits` to `/backend-api/codex/images/generations` when upstream returns 404/405. Fixes #9156 Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- backend/internal/service/billing_service.go | 2 +- backend/internal/service/openai_images.go | 118 +++++++++++++----- .../internal/service/openai_images26_test.go | 103 ++++++++++++++- .../internal/service/openai_images_direct.go | 37 ++++-- .../service/openai_images_responses.go | 7 +- backend/internal/service/pricing_service.go | 2 +- 6 files changed, 225 insertions(+), 44 deletions(-) diff --git a/backend/internal/service/billing_service.go b/backend/internal/service/billing_service.go index bd50b1e31b..db34a99025 100644 --- a/backend/internal/service/billing_service.go +++ b/backend/internal/service/billing_service.go @@ -1152,7 +1152,7 @@ func (s *BillingService) initFallbackPricing() { // getFallbackPricing 根据模型系列获取回退价格 func (s *BillingService) getFallbackPricing(model string) *ModelPricing { modelLower := normalizeAntigravityClaudeTierAlias(strings.ToLower(model)) - if modelLower == "gpt-image-2.6-flare" || modelLower == "gpt-image-2.6-sunburst" { + if isGPTImage26Model(modelLower) { p := openAIGPTImage25FallbackPricing return &ModelPricing{ InputPricePerToken: p.InputCostPerToken, CacheReadPricePerToken: p.CacheReadInputTokenCost, diff --git a/backend/internal/service/openai_images.go b/backend/internal/service/openai_images.go index 327aed6e54..7c8aa52cf7 100644 --- a/backend/internal/service/openai_images.go +++ b/backend/internal/service/openai_images.go @@ -193,6 +193,15 @@ func (r *OpenAIImagesRequest) IsEdits() bool { return r != nil && r.Endpoint == openAIImagesEditsEndpoint } +func (r *OpenAIImagesRequest) HasImageInputs() bool { + return r != nil && (len(r.InputImageURLs) > 0 || + len(r.Uploads) > 0 || + strings.TrimSpace(r.MaskImageURL) != "" || + r.MaskUpload != nil || + strings.TrimSpace(r.MarkupImageURL) != "" || + r.MarkupUpload != nil) +} + func (r *OpenAIImagesRequest) StickySessionSeed() string { if r == nil { return "" @@ -331,44 +340,72 @@ func parseOpenAIImagesJSONRequest(body []byte, req *OpenAIImagesRequest) error { } } } - if req.IsEdits() { - images := gjson.GetBytes(body, "images") - if images.Exists() { - if !images.IsArray() { - return fmt.Errorf("invalid images field type") + hasExplicitImagesField := false + if images := gjson.GetBytes(body, "images"); images.Exists() && images.Type != gjson.Null { + hasExplicitImagesField = true + if !images.IsArray() { + return fmt.Errorf("invalid images field type") + } + for _, item := range images.Array() { + imageURL, err := extractOpenAIImagesJSONInputURL(item, "images[]") + if err != nil { + return err } - for _, item := range images.Array() { - if imageURL := strings.TrimSpace(item.Get("image_url").String()); imageURL != "" { - req.InputImageURLs = append(req.InputImageURLs, imageURL) - continue - } - if item.Get("file_id").Exists() { - return fmt.Errorf("images[].file_id is not supported (use images[].image_url instead)") - } + if imageURL != "" { + req.InputImageURLs = append(req.InputImageURLs, imageURL) } } - if maskImageURL := strings.TrimSpace(gjson.GetBytes(body, "mask.image_url").String()); maskImageURL != "" { + } + if singleImage := gjson.GetBytes(body, "image"); singleImage.Exists() && singleImage.Type != gjson.Null { + hasExplicitImagesField = true + switch { + case singleImage.IsArray(): + for _, item := range singleImage.Array() { + imageURL, err := extractOpenAIImagesJSONInputURL(item, "image[]") + if err != nil { + return err + } + if imageURL != "" { + req.InputImageURLs = append(req.InputImageURLs, imageURL) + } + } + default: + imageURL, err := extractOpenAIImagesJSONInputURL(singleImage, "image") + if err != nil { + return err + } + if imageURL != "" { + req.InputImageURLs = append(req.InputImageURLs, imageURL) + } + } + } + if mask := gjson.GetBytes(body, "mask"); mask.Exists() && mask.Type != gjson.Null { + maskImageURL, err := extractOpenAIImagesJSONInputURL(mask, "mask") + if err != nil { + return err + } + if maskImageURL != "" { req.MaskImageURL = maskImageURL req.HasMask = true } - if gjson.GetBytes(body, "mask.file_id").Exists() { - return fmt.Errorf("mask.file_id is not supported (use mask.image_url instead)") + } + if markup := gjson.GetBytes(body, "markup"); markup.Exists() && markup.Type != gjson.Null { + if !markup.IsObject() { + return fmt.Errorf("invalid markup field type") } - if markup := gjson.GetBytes(body, "markup"); markup.Exists() && markup.Type != gjson.Null { - if !markup.IsObject() { - return fmt.Errorf("invalid markup field type") - } - if markup.Get("file_id").Exists() { - return fmt.Errorf("markup.file_id is not supported (use markup.image_url instead)") - } - req.MarkupImageURL = strings.TrimSpace(markup.Get("image_url").String()) - if req.MarkupImageURL == "" { - return fmt.Errorf("markup.image_url is required") - } + if markup.Get("file_id").Exists() { + return fmt.Errorf("markup.file_id is not supported (use markup.image_url instead)") } - if len(req.InputImageURLs) == 0 { - return fmt.Errorf("images[].image_url is required") + req.MarkupImageURL = strings.TrimSpace(markup.Get("image_url").String()) + if req.MarkupImageURL == "" { + req.MarkupImageURL = strings.TrimSpace(markup.Get("url").String()) } + if req.MarkupImageURL == "" { + return fmt.Errorf("markup.image_url is required") + } + } + if (req.IsEdits() || hasExplicitImagesField || req.MaskImageURL != "" || req.MarkupImageURL != "") && len(req.InputImageURLs) == 0 { + return fmt.Errorf("images[].image_url is required") } req.HasNativeOptions = hasOpenAINativeImageOptions(func(path string) bool { return gjson.GetBytes(body, path).Exists() @@ -376,6 +413,25 @@ func parseOpenAIImagesJSONRequest(body []byte, req *OpenAIImagesRequest) error { return nil } +func extractOpenAIImagesJSONInputURL(value gjson.Result, field string) (string, error) { + if !value.Exists() || value.Type == gjson.Null { + return "", nil + } + if value.Type == gjson.String { + return strings.TrimSpace(value.String()), nil + } + if !value.IsObject() { + return "", fmt.Errorf("invalid %s field type", field) + } + if value.Get("file_id").Exists() { + return "", fmt.Errorf("%s.file_id is not supported (use %s.image_url instead)", field, field) + } + if imageURL := strings.TrimSpace(value.Get("image_url").String()); imageURL != "" { + return imageURL, nil + } + return strings.TrimSpace(value.Get("url").String()), nil +} + func parseOpenAIImagesMultipartRequest(body []byte, contentType string, req *OpenAIImagesRequest) error { _, params, err := mime.ParseMediaType(contentType) if err != nil { @@ -529,7 +585,7 @@ func parseOpenAIImagesMultipartRequest(body []byte, contentType string, req *Ope } } - if len(req.Uploads) == 0 && req.IsEdits() { + if len(req.Uploads) == 0 && (req.IsEdits() || req.MaskUpload != nil || req.MarkupUpload != nil) { return fmt.Errorf("image file is required") } return nil @@ -634,7 +690,7 @@ func classifyOpenAIImagesCapability(req *OpenAIImagesRequest) OpenAIImagesCapabi if req.Stream || req.N != 1 || req.HasMask || req.HasNativeOptions { return OpenAIImagesCapabilityNative } - if req.IsEdits() && !req.Multipart { + if (req.IsEdits() && !req.Multipart) || (!req.IsEdits() && req.HasImageInputs()) { return OpenAIImagesCapabilityNative } if req.ResponseFormat != "" && req.ResponseFormat != "b64_json" { diff --git a/backend/internal/service/openai_images26_test.go b/backend/internal/service/openai_images26_test.go index 4961fa58ea..c546eee18c 100644 --- a/backend/internal/service/openai_images26_test.go +++ b/backend/internal/service/openai_images26_test.go @@ -290,7 +290,7 @@ func TestGPTImage26InvalidNativeOptions(t *testing.T) { func TestGPTImage26BillingWithoutDynamicPricing(t *testing.T) { svc := &BillingService{} - for _, model := range []string{"gpt-image-2.6-flare", "gpt-image-2.6-sunburst"} { + for _, model := range []string{"gpt-image-2.6", "gpt-image-2.6-flare", "gpt-image-2.6-sunburst", "gpt-image-2.6-flare-2026-11-06"} { p, err := svc.GetModelPricing(model) require.NoError(t, err) require.Equal(t, 5e-6, p.InputPricePerToken) @@ -301,3 +301,104 @@ func TestGPTImage26BillingWithoutDynamicPricing(t *testing.T) { require.Zero(t, p.OutputPricePerToken) } } + +func TestGPTImage26UnifiedGenerationsWithImageInputs(t *testing.T) { + for _, model := range []string{"gpt-image-2.6", "gpt-image-2.6-flare", "gpt-image-2.6-sunburst", "gpt-image-2.6-flare-2026-11-06"} { + for _, multipartInput := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/multipart=%t", model, multipartInput), func(t *testing.T) { + body := []byte(fmt.Sprintf(`{"model":%q,"prompt":"combine and edit","complexity":"high","quality":"high","size":"1024x1024","images":[{"image_url":"data:image/png;base64,aW1nMQ=="},{"url":"https://example.com/ref2.png"}],"mask":{"image_url":"data:image/png;base64,bWFzaw=="},"markup":{"image_url":"data:image/png;base64,bWFya3Vw"}}`, model)) + contentType := "application/json" + if multipartInput { + var buf bytes.Buffer + writer := multipart.NewWriter(&buf) + for key, value := range map[string]string{ + "model": model, "prompt": "combine and edit", "complexity": "high", "quality": "high", "size": "1024x1024", + } { + require.NoError(t, writer.WriteField(key, value)) + } + for _, partSpec := range []struct{ field, content string }{ + {"image[]", "img1"}, + {"image[]", "img2"}, + {"mask", "mask"}, + {"markup", "markup"}, + } { + header := textproto.MIMEHeader{} + header.Set("Content-Disposition", fmt.Sprintf(`form-data; name=%q; filename="in.png"`, partSpec.field)) + header.Set("Content-Type", "image/png") + part, err := writer.CreatePart(header) + require.NoError(t, err) + _, err = part.Write([]byte(partSpec.content)) + require.NoError(t, err) + } + require.NoError(t, writer.Close()) + body, contentType = buf.Bytes(), writer.FormDataContentType() + } + + c, _ := newOpenAIImagesTestContext(t, body) + c.Request.Header.Set("Content-Type", contentType) + upstream := &httpUpstreamRecorder{resp: openAIImagesJSONResponse()} + svc := newOpenAIImagesTestService(upstream) + + parsed, err := svc.ParseOpenAIImagesRequest(c, body) + require.NoError(t, err) + require.Equal(t, OpenAIImagesCapabilityNative, parsed.RequiredCapability) + require.Len(t, gjson.GetBytes(parsed.ModerationBody(), "images").Array(), 4) + + result, err := svc.ForwardImages(context.Background(), c, directImagesTestAccount(), body, parsed, "") + require.NoError(t, err) + require.Equal(t, "/backend-api/codex/images/generations", result.UpstreamEndpoint) + require.Len(t, gjson.GetBytes(upstream.lastBody, "images").Array(), 2) + require.NotEmpty(t, gjson.GetBytes(upstream.lastBody, "mask.image_url").String()) + require.NotEmpty(t, gjson.GetBytes(upstream.lastBody, "markup.image_url").String()) + require.Equal(t, "high", gjson.GetBytes(upstream.lastBody, "complexity").String()) + }) + } + } + + for _, invalidBody := range []string{ + `{"model":"gpt-image-2.6-flare","prompt":"edit","images":[]}`, + `{"model":"gpt-image-2.6-flare","prompt":"edit","images":"bad"}`, + `{"model":"gpt-image-2.6-flare","prompt":"edit","images":[{"file_id":"file-1"}]}`, + `{"model":"gpt-image-2.6-flare","prompt":"edit","mask":{"image_url":"data:image/png;base64,AA=="}}`, + `{"model":"gpt-image-2.6-flare","prompt":"edit","markup":{"image_url":"data:image/png;base64,AA=="}}`, + } { + t.Run(invalidBody, func(t *testing.T) { + c, _ := newOpenAIImagesTestContext(t, []byte(invalidBody)) + _, err := newOpenAIImagesTestService(nil).ParseOpenAIImagesRequest(c, []byte(invalidBody)) + require.Error(t, err) + }) + } +} + +func TestGPTImage26EditsFallsForwardToUnifiedGenerationsWhenEditsUnavailable(t *testing.T) { + for _, status := range []int{http.StatusNotFound, http.StatusMethodNotAllowed} { + t.Run(fmt.Sprint(status), func(t *testing.T) { + var paths []string + var lastPayload []byte + upstream := &codexModelsHTTPUpstreamStub{do: func(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) { + paths = append(paths, req.URL.Path) + lastPayload, _ = io.ReadAll(req.Body) + if len(paths) == 1 { + return &http.Response{ + StatusCode: status, + Header: http.Header{}, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"edits endpoint retired"}}`)), + }, nil + } + return openAIImagesJSONResponse(), nil + }} + body := []byte(`{"model":"gpt-image-2.6-flare","prompt":"edit","complexity":"low","images":[{"image_url":"data:image/png;base64,AA=="}],"markup":{"image_url":"data:image/png;base64,bWFya3Vw"}}`) + c, _ := newOpenAIImagesTestContext(t, body) + c.Request.URL.Path = openAIImagesEditsEndpoint + svc := newOpenAIImagesTestService(upstream) + parsed, err := svc.ParseOpenAIImagesRequest(c, body) + require.NoError(t, err) + result, err := svc.ForwardImages(context.Background(), c, directImagesTestAccount(), body, parsed, "") + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, []string{"/backend-api/codex/images/edits", "/backend-api/codex/images/generations"}, paths) + require.Len(t, gjson.GetBytes(lastPayload, "images").Array(), 1) + require.Equal(t, "data:image/png;base64,bWFya3Vw", gjson.GetBytes(lastPayload, "markup.image_url").String()) + }) + } +} diff --git a/backend/internal/service/openai_images_direct.go b/backend/internal/service/openai_images_direct.go index b930091579..5a83013cf8 100644 --- a/backend/internal/service/openai_images_direct.go +++ b/backend/internal/service/openai_images_direct.go @@ -14,6 +14,7 @@ import ( ) type openAIImagesForceResponsesContextKey struct{} +type openAIImagesForceUnifiedGenerationsContextKey struct{} func withOpenAIImagesForceResponses(ctx context.Context) context.Context { return context.WithValue(ctx, openAIImagesForceResponsesContextKey{}, true) @@ -27,11 +28,30 @@ func isOpenAIImagesForceResponses(ctx context.Context) bool { return forced } +func withOpenAIImagesForceUnifiedGenerations(ctx context.Context) context.Context { + return context.WithValue(ctx, openAIImagesForceUnifiedGenerationsContextKey{}, true) +} + +func isOpenAIImagesForceUnifiedGenerations(ctx context.Context) bool { + if ctx == nil { + return false + } + forced, _ := ctx.Value(openAIImagesForceUnifiedGenerationsContextKey{}).(bool) + return forced +} + +func isGPTImage26Model(model string) bool { + normalized := strings.ToLower(strings.TrimSpace(model)) + return normalized == "gpt-image-2.6" || strings.HasPrefix(normalized, "gpt-image-2.6-") +} + // 显式列出已接入的模型,不把未来模型或未知快照自动送到直调端点。 func usesCodexDirectImages(model string) bool { + if isGPTImage26Model(model) { + return true + } switch strings.TrimSpace(model) { case "gpt-image-1.5", "gpt-image-2", - "gpt-image-2.6-flare", "gpt-image-2.6-sunburst", "gpt-image-2.5-flare", "gpt-image-2.5-sunburst", "gpt-image-2.5-flare-2026-09-08", "gpt-image-2.5-sunburst-2026-09-08": return true @@ -43,16 +63,15 @@ func usesCodexDirectImages(model string) bool { // Codex Responses binds image_generation to an internal model and cannot // preserve the requested 2.6 model. Do not fall back to that bridge for 2.6. func requiresCodexDirectImages(model string) bool { - switch strings.TrimSpace(model) { - case "gpt-image-2.6-flare", "gpt-image-2.6-sunburst": - return true - default: - return false - } + return isGPTImage26Model(model) } // 正式转发与后台测试共用同一份端点选择和请求构造。 func buildOpenAIImagesOAuthPayload(parsed *OpenAIImagesRequest, model string) ([]byte, string, error) { + return buildOpenAIImagesOAuthPayloadForContext(context.Background(), parsed, model) +} + +func buildOpenAIImagesOAuthPayloadForContext(ctx context.Context, parsed *OpenAIImagesRequest, model string) ([]byte, string, error) { if parsed == nil { return nil, "", fmt.Errorf("parsed images request is required") } @@ -109,8 +128,10 @@ func buildOpenAIImagesOAuthPayload(parsed *OpenAIImagesRequest, model string) ([ } endpoint := "/images/generations" - if parsed.IsEdits() { + if parsed.IsEdits() && !isOpenAIImagesForceUnifiedGenerations(ctx) { endpoint = "/images/edits" + } + if parsed.IsEdits() || parsed.HasImageInputs() { images := make([]map[string]string, 0, len(parsed.InputImageURLs)+len(parsed.Uploads)) for _, imageURL := range parsed.InputImageURLs { if imageURL = strings.TrimSpace(imageURL); imageURL != "" { diff --git a/backend/internal/service/openai_images_responses.go b/backend/internal/service/openai_images_responses.go index 54541b2981..e6caffef38 100644 --- a/backend/internal/service/openai_images_responses.go +++ b/backend/internal/service/openai_images_responses.go @@ -408,7 +408,7 @@ func buildOpenAIImagesResponsesRequest(parsed *OpenAIImagesRequest, toolModel st req, _ = sjson.SetRawBytes(req, "input", input) action := "generate" - if parsed.IsEdits() { + if parsed.IsEdits() || len(inputImages) > 0 { action = "edit" } tool := []byte(`{"type":"image_generation","action":"","model":""}`) @@ -1872,7 +1872,7 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesOAuth( var responsesBody []byte var targetURL string if direct { - responsesBody, targetURL, err = buildOpenAIImagesOAuthPayload(parsed, upstreamModel) + responsesBody, targetURL, err = buildOpenAIImagesOAuthPayloadForContext(ctx, parsed, upstreamModel) } else { responsesBody, err = buildOpenAIImagesResponsesRequest(parsed, upstreamModel) targetURL = chatgptCodexURL @@ -1928,6 +1928,9 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesOAuth( respBody := s.readUpstreamErrorBody(resp) _ = resp.Body.Close() respBody = s.redactAgentIdentitySensitiveBody(upstreamCtx, account, respBody) + if direct && parsed.IsEdits() && !isOpenAIImagesForceUnifiedGenerations(ctx) && (resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusMethodNotAllowed) { + return s.forwardOpenAIImagesOAuth(withOpenAIImagesForceUnifiedGenerations(ctx), c, account, parsed, channelMappedModel) + } if direct && !requiresCodexDirectImages(upstreamModel) && (resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusMethodNotAllowed) { return s.forwardOpenAIImagesOAuth(withOpenAIImagesForceResponses(ctx), c, account, parsed, channelMappedModel) } diff --git a/backend/internal/service/pricing_service.go b/backend/internal/service/pricing_service.go index c08db8aceb..106904df18 100644 --- a/backend/internal/service/pricing_service.go +++ b/backend/internal/service/pricing_service.go @@ -1773,7 +1773,7 @@ func (s *PricingService) matchOpenAIModel(model string) *LiteLLMModelPricing { // Remote price mirrors can lag new releases. Never bill GPT Image 2.5 / 2.6 // using the older image model's rates when its entry is absent. - if model == "gpt-image-2.6-flare" || model == "gpt-image-2.6-sunburst" { + if isGPTImage26Model(model) { return openAIGPTImage25FallbackPricing } for _, imageModel := range []string{"gpt-image-2.5-flare", "gpt-image-2.5-sunburst"} { From 332f45f858694c28f80314ea53ed7a67b3a3430c Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 4 Dec 2026 17:27:09 +0800 Subject: [PATCH 3/5] 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, From c3f1b4bc75bd1e87cafe501989436dace6e72f95 Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 4 Dec 2026 17:31:39 +0800 Subject: [PATCH 4/5] fix(openai): tighten null/empty image field checks and model_not_found 404 guard - Ignore explicit JSON `null` values on `mask` and native image options so prompt-only requests with null placeholders stay on basic capability. - Reject empty objects/strings inside `images[]`, `image`, and `mask` instead of silently dropping malformed image entries. - Skip same-account `/images/edits` -> `/images/generations` retry when a 404 is explicitly `model_not_found` so account failover runs without an extra round-trip. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- backend/internal/service/openai_images.go | 15 ++++++--- .../internal/service/openai_images26_test.go | 33 +++++++++++++++++++ .../service/openai_images_responses.go | 6 ++-- 3 files changed, 48 insertions(+), 6 deletions(-) diff --git a/backend/internal/service/openai_images.go b/backend/internal/service/openai_images.go index 7c8aa52cf7..272ad05036 100644 --- a/backend/internal/service/openai_images.go +++ b/backend/internal/service/openai_images.go @@ -311,7 +311,6 @@ func parseOpenAIImagesJSONRequest(body []byte, req *OpenAIImagesRequest) error { req.Moderation = strings.TrimSpace(gjson.GetBytes(body, "moderation").String()) req.InputFidelity = strings.TrimSpace(gjson.GetBytes(body, "input_fidelity").String()) req.Style = strings.TrimSpace(gjson.GetBytes(body, "style").String()) - req.HasMask = gjson.GetBytes(body, "mask").Exists() if outputCompression := gjson.GetBytes(body, "output_compression"); outputCompression.Exists() { if outputCompression.Type != gjson.Number { return fmt.Errorf("invalid output_compression field type") @@ -408,7 +407,8 @@ func parseOpenAIImagesJSONRequest(body []byte, req *OpenAIImagesRequest) error { return fmt.Errorf("images[].image_url is required") } req.HasNativeOptions = hasOpenAINativeImageOptions(func(path string) bool { - return gjson.GetBytes(body, path).Exists() + v := gjson.GetBytes(body, path) + return v.Exists() && v.Type != gjson.Null }) return nil } @@ -418,7 +418,11 @@ func extractOpenAIImagesJSONInputURL(value gjson.Result, field string) (string, return "", nil } if value.Type == gjson.String { - return strings.TrimSpace(value.String()), nil + trimmed := strings.TrimSpace(value.String()) + if trimmed == "" { + return "", fmt.Errorf("%s.image_url is required", field) + } + return trimmed, nil } if !value.IsObject() { return "", fmt.Errorf("invalid %s field type", field) @@ -429,7 +433,10 @@ func extractOpenAIImagesJSONInputURL(value gjson.Result, field string) (string, if imageURL := strings.TrimSpace(value.Get("image_url").String()); imageURL != "" { return imageURL, nil } - return strings.TrimSpace(value.Get("url").String()), nil + if imageURL := strings.TrimSpace(value.Get("url").String()); imageURL != "" { + return imageURL, nil + } + return "", fmt.Errorf("%s.image_url is required", field) } func parseOpenAIImagesMultipartRequest(body []byte, contentType string, req *OpenAIImagesRequest) error { diff --git a/backend/internal/service/openai_images26_test.go b/backend/internal/service/openai_images26_test.go index c546eee18c..4e18d6a160 100644 --- a/backend/internal/service/openai_images26_test.go +++ b/backend/internal/service/openai_images26_test.go @@ -359,6 +359,10 @@ func TestGPTImage26UnifiedGenerationsWithImageInputs(t *testing.T) { `{"model":"gpt-image-2.6-flare","prompt":"edit","images":[]}`, `{"model":"gpt-image-2.6-flare","prompt":"edit","images":"bad"}`, `{"model":"gpt-image-2.6-flare","prompt":"edit","images":[{"file_id":"file-1"}]}`, + `{"model":"gpt-image-2.6-flare","prompt":"edit","images":[{"image_url":"data:image/png;base64,AA=="},{}]}`, + `{"model":"gpt-image-2.6-flare","prompt":"edit","images":["data:image/png;base64,AA==",""]}`, + `{"model":"gpt-image-2.6-flare","prompt":"edit","images":[{"image_url":"data:image/png;base64,AA=="}],"mask":{}}`, + `{"model":"gpt-image-2.6-flare","prompt":"edit","images":[{"image_url":"data:image/png;base64,AA=="}],"mask":""}`, `{"model":"gpt-image-2.6-flare","prompt":"edit","mask":{"image_url":"data:image/png;base64,AA=="}}`, `{"model":"gpt-image-2.6-flare","prompt":"edit","markup":{"image_url":"data:image/png;base64,AA=="}}`, } { @@ -368,6 +372,14 @@ func TestGPTImage26UnifiedGenerationsWithImageInputs(t *testing.T) { require.Error(t, err) }) } + + nullOptionalBody := []byte(`{"prompt":"draw a cat","images":null,"mask":null,"markup":null}`) + cNull, _ := newOpenAIImagesTestContext(t, nullOptionalBody) + parsedNull, err := newOpenAIImagesTestService(nil).ParseOpenAIImagesRequest(cNull, nullOptionalBody) + require.NoError(t, err) + require.False(t, parsedNull.HasMask) + require.False(t, parsedNull.HasImageInputs()) + require.Equal(t, OpenAIImagesCapabilityBasic, parsedNull.RequiredCapability) } func TestGPTImage26EditsFallsForwardToUnifiedGenerationsWhenEditsUnavailable(t *testing.T) { @@ -401,4 +413,25 @@ func TestGPTImage26EditsFallsForwardToUnifiedGenerationsWhenEditsUnavailable(t * require.Equal(t, "data:image/png;base64,bWFya3Vw", gjson.GetBytes(lastPayload, "markup.image_url").String()) }) } + + t.Run("model_not_found_404_does_not_retry_generations_on_same_account", func(t *testing.T) { + var paths []string + upstream := &codexModelsHTTPUpstreamStub{do: func(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) { + paths = append(paths, req.URL.Path) + return &http.Response{ + StatusCode: http.StatusNotFound, + Header: http.Header{}, + Body: io.NopCloser(strings.NewReader(`{"error":{"code":"model_not_found","message":"The model 'gpt-image-2.6-flare' does not exist"}}`)), + }, nil + }} + body := []byte(`{"model":"gpt-image-2.6-flare","prompt":"edit","images":[{"image_url":"data:image/png;base64,AA=="}]}`) + c, _ := newOpenAIImagesTestContext(t, body) + c.Request.URL.Path = openAIImagesEditsEndpoint + svc := newOpenAIImagesTestService(upstream) + parsed, err := svc.ParseOpenAIImagesRequest(c, body) + require.NoError(t, err) + _, err = svc.ForwardImages(context.Background(), c, directImagesTestAccount(), body, parsed, "") + require.Error(t, err) + require.Equal(t, []string{"/backend-api/codex/images/edits"}, paths) + }) } diff --git a/backend/internal/service/openai_images_responses.go b/backend/internal/service/openai_images_responses.go index e6caffef38..b260389bae 100644 --- a/backend/internal/service/openai_images_responses.go +++ b/backend/internal/service/openai_images_responses.go @@ -1928,10 +1928,12 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesOAuth( respBody := s.readUpstreamErrorBody(resp) _ = resp.Body.Close() respBody = s.redactAgentIdentitySensitiveBody(upstreamCtx, account, respBody) - if direct && parsed.IsEdits() && !isOpenAIImagesForceUnifiedGenerations(ctx) && (resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusMethodNotAllowed) { + endpointUnavailable := resp.StatusCode == http.StatusMethodNotAllowed || + (resp.StatusCode == http.StatusNotFound && !isOpenAICompatibleModelNotFoundBody(respBody)) + if direct && parsed.IsEdits() && !isOpenAIImagesForceUnifiedGenerations(ctx) && endpointUnavailable { return s.forwardOpenAIImagesOAuth(withOpenAIImagesForceUnifiedGenerations(ctx), c, account, parsed, channelMappedModel) } - if direct && !requiresCodexDirectImages(upstreamModel) && (resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusMethodNotAllowed) { + if direct && !requiresCodexDirectImages(upstreamModel) && endpointUnavailable { return s.forwardOpenAIImagesOAuth(withOpenAIImagesForceResponses(ctx), c, account, parsed, channelMappedModel) } if !agentIdentityTaskRecoveryWasTried(ctx) && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, respBody) { From 4e694a37457da2bd9bffdf54191b16dc33c90d3e Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 4 Dec 2026 18:24:50 +0800 Subject: [PATCH 5/5] fix(openai-ws): reconcile HTTP bridge parent check with history limit and sticky continuations Follow-up to #8302 (f7ec8b3ce). Placing the unresolved `previous_response_id` 1008 rejection at the top of the HTTP bridge turn loop ran before `hooks.BeforeTurn` and before the `historyLost` 1013 (`StatusTryAgainLater`) check from #9203, and rejected valid turn-1 sticky API-key continuations (`store != false` bound in `stateStore`) as well as Grok HTTP bridge turns. Move the 1008 check after `BeforeTurn` and `historyLost`, allow turn-1 API-key continuations bound to the selected account when `store != false`, and preserve Grok HTTP bridge handling while keeping all #8302 unresolved-parent cases closed with 1008. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../service/openai_ws_forwarder_ingress.go | 31 +++++--- .../service/openai_ws_http_bridge_p2_test.go | 73 +++++++++++++++++++ 2 files changed, 95 insertions(+), 9 deletions(-) diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 317d647f70..37bbe215c5 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -607,15 +607,6 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( return err } } - // HTTP cannot resolve an opaque parent; only this connection's replay can. - if parent := currentBridgePayload.previousResponseID; parent != "" && - (parent != bridgeLastResponseID || !bridgeReplayInputExists || len(bridgeReplayInput) == 0) { - return NewOpenAIWSClientCloseError( - coderws.StatusPolicyViolation, - "previous_response_id cannot be resolved on this connection; resend full input without previous_response_id", - nil, - ) - } if hooks != nil && hooks.BeforeTurn != nil { if err := hooks.BeforeTurn(turn); err != nil { return err @@ -652,6 +643,28 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( if needsBridgeReplay && historyLost { return NewResponsesWSBridgeHistoryCloseError() } + // HTTP cannot resolve an opaque parent unless this connection holds its + // replay chain, the platform handles continuations natively on HTTP bridge, + // or turn 1 sticky-routed to the API-key account bound to that response ID. + if parent := currentBridgePayload.previousResponseID; parent != "" { + resolvedInConnection := parent == bridgeLastResponseID && bridgeReplayInputExists && len(bridgeReplayInput) > 0 + resolvedBoundAPIKey := turn == 1 && + account != nil && + account.IsOpenAIApiKey() && + !s.isOpenAIWSStoreDisabledInRequestRaw(currentBridgePayload.payloadRaw, account) && + stateStore != nil && + func() bool { + boundAccountID, getErr := stateStore.GetResponseAccount(ctx, groupID, parent) + return getErr == nil && boundAccountID == account.ID + }() + if !resolvedInConnection && !resolvedBoundAPIKey && (account == nil || account.Platform != PlatformGrok) { + return NewOpenAIWSClientCloseError( + coderws.StatusPolicyViolation, + "previous_response_id cannot be resolved on this connection; resend full input without previous_response_id", + nil, + ) + } + } if !needsBridgeReplay { // A self-contained request replaces the previous replay chain. bridgeReplayInput, bridgeAccountFailoverInput = nil, nil diff --git a/backend/internal/service/openai_ws_http_bridge_p2_test.go b/backend/internal/service/openai_ws_http_bridge_p2_test.go index c0ed7e58b6..f2861432d0 100644 --- a/backend/internal/service/openai_ws_http_bridge_p2_test.go +++ b/backend/internal/service/openai_ws_http_bridge_p2_test.go @@ -114,4 +114,77 @@ func TestOpenAIWSHTTPBridgeRejectsUnresolvedPreviousResponseID(t *testing.T) { require.Len(t, upstream.bodies, priorTurns, "never POST a delta whose parent cannot be reconstructed") }) } + + t.Run("bound_apikey_cross_connection_turn1_allowed_but_store_false_rejected", func(t *testing.T) { + upstream := &httpUpstreamRecorder{ + responses: []*http.Response{ + { + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader("data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_next\",\"output\":[]}}\n\n")), + }, + }, + } + cfg := &config.Config{} + cfg.Gateway.OpenAIWS.Enabled = true + cfg.Gateway.OpenAIWS.APIKeyEnabled = true + cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true + cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true + cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3 + cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3 + svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: upstream, cache: &stubGatewayCache{}, openaiWSResolver: NewOpenAIWSProtocolResolver(cfg)} + account := &Account{ + ID: 9006, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{"openai_apikey_responses_websockets_v2_mode": OpenAIWSIngressModeHTTPBridge}, + Status: StatusActive, Schedulable: true, Concurrency: 1, + } + require.NoError(t, svc.getOpenAIWSStateStore().BindResponseAccount(context.Background(), 0, "resp_bound", account.ID, time.Hour)) + + runTurn1 := func(frame string) (int, coderws.StatusCode) { + wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := coderws.Accept(w, r, nil) + if err != nil { + return + } + defer func() { _ = conn.CloseNow() }() + readCtx, cancel := context.WithTimeout(r.Context(), 3*time.Second) + _, firstMessage, err := conn.Read(readCtx) + cancel() + if err != nil { + return + } + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = r.Clone(r.Context()) + proxyErr := svc.ProxyResponsesWebSocketFromClient(r.Context(), c, conn, account, "sk-test", firstMessage, nil) + var closeErr *OpenAIWSClientCloseError + if errors.As(proxyErr, &closeErr) { + _ = conn.Close(closeErr.StatusCode(), closeErr.Reason()) + } + })) + defer wsServer.Close() + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + client, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(wsServer.URL, "http"), nil) + require.NoError(t, err) + defer func() { _ = client.CloseNow() }() + require.NoError(t, client.Write(ctx, coderws.MessageText, []byte(frame))) + _, event, readErr := client.Read(ctx) + if readErr != nil { + return len(upstream.bodies), coderws.CloseStatus(readErr) + } + require.Equal(t, "response.completed", gjson.GetBytes(event, "type").String()) + _ = client.Close(coderws.StatusNormalClosure, "done") + return len(upstream.bodies), coderws.StatusNormalClosure + } + + posts, status := runTurn1(`{"type":"response.create","model":"gpt-6.1-sol","store":false,"previous_response_id":"resp_bound","input":[{"role":"user","content":"delta"}]}`) + require.Equal(t, coderws.StatusPolicyViolation, status) + require.Zero(t, posts) + + posts, status = runTurn1(`{"type":"response.create","model":"gpt-6.1-sol","previous_response_id":"resp_bound","input":[{"role":"user","content":"delta"}]}`) + require.Equal(t, coderws.StatusNormalClosure, status) + require.Equal(t, 1, posts) + }) }