diff --git a/backend/internal/handler/failover_loop.go b/backend/internal/handler/failover_loop.go index 56c39af103..37a2b7c102 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 @@ -76,6 +83,19 @@ func sameAccountRetryDelayFor(failoverErr *service.UpstreamFailoverError, retryC return delay } +// wsSameAccountRetryAllowed preserves the WebSocket retry contract: an OAuth +// 429 deadline or a request-scoped transient failure may use the existing +// retry budget. The caller checks that the current turn can be replayed. +func wsSameAccountRetryAllowed(account *service.Account, failoverErr *service.UpstreamFailoverError, retryCount int) bool { + if account == nil || failoverErr == nil { + return false + } + if (failoverErr.StatusCode != http.StatusTooManyRequests || failoverErr.SameAccountRetryDeadline.IsZero()) && !failoverErr.RequestScopedTransient { + return false + } + return sameAccountRetryAllowed(failoverErr, retryCount, effectiveSameAccountRetryLimit(failoverErr, account)) +} + func sameAccountRetryAllowed(failoverErr *service.UpstreamFailoverError, retryCount, retryLimit int) bool { if failoverErr == nil || !failoverErr.RetryableOnSameAccount { return false @@ -220,13 +240,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 +269,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/failover_loop_test.go b/backend/internal/handler/failover_loop_test.go index d362682cd7..139f14dca4 100644 --- a/backend/internal/handler/failover_loop_test.go +++ b/backend/internal/handler/failover_loop_test.go @@ -1040,3 +1040,31 @@ func TestFailoverClientGone(t *testing.T) { require.False(t, failoverClientGone(nil)) }) } + +func TestWSSameAccountRetryRetainsBoundedRequestScopedCapacityRetry(t *testing.T) { + account := &service.Account{Type: service.AccountTypeAPIKey, Credentials: map[string]any{"pool_mode": true, "pool_mode_retry_count": float64(1)}} + failure := &service.UpstreamFailoverError{ + StatusCode: http.StatusServiceUnavailable, RetryableOnSameAccount: true, RequestScopedTransient: true, + } + t.Run("first attempt may retry", func(t *testing.T) { + require.True(t, wsSameAccountRetryAllowed(account, failure, 0)) + }) + t.Run("configured limit still applies", func(t *testing.T) { + require.False(t, wsSameAccountRetryAllowed(account, failure, 1)) + }) + t.Run("non-transient 503 cannot retry", func(t *testing.T) { + other := *failure + other.RequestScopedTransient = false + require.False(t, wsSameAccountRetryAllowed(account, &other, 0)) + }) + t.Run("explicit zero disables capacity retry", func(t *testing.T) { + disabled := &service.Account{Type: service.AccountTypeAPIKey, Credentials: map[string]any{"pool_mode": true, "pool_mode_retry_count": float64(0)}} + require.False(t, wsSameAccountRetryAllowed(disabled, failure, 0)) + }) + t.Run("OAuth 429 with deadline still retries", func(t *testing.T) { + rateLimit := &service.UpstreamFailoverError{ + StatusCode: http.StatusTooManyRequests, RetryableOnSameAccount: true, SameAccountRetryDeadline: time.Now().Add(time.Minute), + } + require.True(t, wsSameAccountRetryAllowed(account, rateLimit, 0)) + }) +} diff --git a/backend/internal/handler/gemini_mixed_models_test.go b/backend/internal/handler/gemini_mixed_models_test.go index 3f5ed01401..70252639cd 100644 --- a/backend/internal/handler/gemini_mixed_models_test.go +++ b/backend/internal/handler/gemini_mixed_models_test.go @@ -87,11 +87,15 @@ func TestAppendUpstreamGeminiModelsPreservesMetadata(t *testing.T) { // Exercise the real handler's native-upstream branch, including scope fallback. type geminiMixedModelsUpstream struct { service.HTTPUpstream - status int - body string + status int + body string + lastReq *http.Request + calls int } -func (u *geminiMixedModelsUpstream) Do(_ *http.Request, _ string, _ int64, _ int) (*http.Response, error) { +func (u *geminiMixedModelsUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) { + u.lastReq = req + u.calls++ return &http.Response{StatusCode: u.status, Header: http.Header{"Content-Type": {"application/json"}, "X-Request-Id": {"native-id"}}, Body: io.NopCloser(strings.NewReader(u.body))}, nil } func TestGeminiNativeModelsMergesNativeUpstream(t *testing.T) { @@ -240,3 +244,122 @@ func TestGeminiNativeModelsUnmappedAccountKeepsUpstream(t *testing.T) { require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) require.Equal(t, 2, f.upstream.calls) } + +func TestGeminiV1BetaListModels_PaginationQueryForwarding(t *testing.T) { + newHandler := func(upstream *geminiMixedModelsUpstream, allowlist service.GroupModelAllowlist, includeMixedAG bool) (*GatewayHandler, *service.APIKey) { + id := int64(48) + accounts := []service.Account{ + {ID: 1, Platform: service.PlatformGemini, Type: service.AccountTypeAPIKey, Credentials: map[string]any{"api_key": "upstream-key"}}, + } + if includeMixedAG { + accounts = append(accounts, service.Account{ + ID: 2, + Platform: service.PlatformAntigravity, + Extra: map[string]any{"mixed_scheduling": true}, + Credentials: map[string]any{"model_mapping": map[string]any{"gemini-synced-custom": "gemini-3.8-flash-high"}}, + }) + } + repo := &geminiAllowlistAccountRepoStub{gatewayModelsAccountRepoStub: gatewayModelsAccountRepoStub{byGroup: map[int64][]service.Account{id: accounts}}} + h := &GatewayHandler{geminiCompatService: service.NewGeminiMessagesCompatService(repo, nil, nil, nil, nil, nil, upstream, nil, &config.Config{})} + key := &service.APIKey{GroupID: &id, Group: &service.Group{ID: id, Platform: service.PlatformGemini, ModelAllowlist: allowlist}} + return h, key + } + + t.Run("allowlists pageSize and pageToken and drops key and unknown params", func(t *testing.T) { + upstream := &geminiMixedModelsUpstream{ + status: http.StatusOK, + body: `{"models":[{"name":"models/gemini-page-2"}]}`, + } + h, key := newHandler(upstream, service.GroupModelAllowlist{}, true) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models?pageSize=1000&pageToken=abc%2B%2F%3D%3D&key=sk-client-secret&alt=json&foo=bar", nil) + c.Set(string(middleware.ContextKeyAPIKey), key) + + h.GeminiV1BetaListModels(c) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.NotNil(t, upstream.lastReq) + gotQuery := upstream.lastReq.URL.Query() + require.Equal(t, "1000", gotQuery.Get("pageSize")) + require.Equal(t, "abc+/==", gotQuery.Get("pageToken")) + require.Empty(t, gotQuery.Get("key")) + require.Empty(t, gotQuery.Get("alt")) + require.Empty(t, gotQuery.Get("foo")) + require.Len(t, gotQuery, 2) + // 后续分页不重复附加混合分组的 Antigravity 模型。 + require.Contains(t, rec.Body.String(), "models/gemini-page-2") + require.NotContains(t, rec.Body.String(), "models/gemini-synced-custom") + }) + + t.Run("pageSize zero succeeds and omits pageSize upstream", func(t *testing.T) { + upstream := &geminiMixedModelsUpstream{ + status: http.StatusOK, + body: `{"models":[{"name":"models/gemini-page-1"}],"nextPageToken":"tok-2"}`, + } + h, key := newHandler(upstream, service.GroupModelAllowlist{}, true) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models?pageSize=0", nil) + c.Set(string(middleware.ContextKeyAPIKey), key) + + h.GeminiV1BetaListModels(c) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.NotNil(t, upstream.lastReq) + require.Empty(t, upstream.lastReq.URL.RawQuery) + // 首页仍附加混合分组的 Antigravity 模型并保留 nextPageToken。 + require.Contains(t, rec.Body.String(), "models/gemini-synced-custom") + require.Contains(t, rec.Body.String(), `"nextPageToken":"tok-2"`) + }) + + t.Run("invalid pagination params return 400 without hitting upstream", func(t *testing.T) { + for _, target := range []string{ + "/v1beta/models?pageSize=-1", + "/v1beta/models?pageSize=abc", + "/v1beta/models?pageToken=bad%0Atoken", + "/v1beta/models?pageToken=" + strings.Repeat("x", 4097), + } { + upstream := &geminiMixedModelsUpstream{status: http.StatusOK, body: `{"models":[]}`} + h, key := newHandler(upstream, service.GroupModelAllowlist{}, false) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, target, nil) + c.Set(string(middleware.ContextKeyAPIKey), key) + + h.GeminiV1BetaListModels(c) + require.Equal(t, http.StatusBadRequest, rec.Code, target) + require.Zero(t, upstream.calls, target) + } + }) + + t.Run("allowlist dropping all models on a page keeps empty array and nextPageToken", func(t *testing.T) { + upstream := &geminiMixedModelsUpstream{ + status: http.StatusOK, + body: `{"models":[{"name":"models/gemini-blocked"}],"nextPageToken":"tok-2"}`, + } + h, key := newHandler(upstream, service.GroupModelAllowlist{Enabled: true, Models: []string{"gemini-allowed"}}, false) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models?pageSize=1", nil) + c.Set(string(middleware.ContextKeyAPIKey), key) + + h.GeminiV1BetaListModels(c) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.JSONEq(t, `{"models":[],"nextPageToken":"tok-2"}`, rec.Body.String()) + }) + + t.Run("upstream error passes through untouched when allowlist is enabled", func(t *testing.T) { + upstream := &geminiMixedModelsUpstream{ + status: http.StatusBadRequest, + body: `{"error":{"code":400,"message":"Invalid page token","status":"INVALID_ARGUMENT"}}`, + } + h, key := newHandler(upstream, service.GroupModelAllowlist{Enabled: true, Models: []string{"gemini-allowed"}}, false) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models?pageToken=expired", nil) + c.Set(string(middleware.ContextKeyAPIKey), key) + + h.GeminiV1BetaListModels(c) + require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String()) + require.JSONEq(t, upstream.body, rec.Body.String()) + }) +} diff --git a/backend/internal/handler/gemini_v1beta_handler.go b/backend/internal/handler/gemini_v1beta_handler.go index c30807fdfa..dc89567698 100644 --- a/backend/internal/handler/gemini_v1beta_handler.go +++ b/backend/internal/handler/gemini_v1beta_handler.go @@ -48,6 +48,12 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) { return } + listQuery, err := service.ParseGeminiListModelsQuery(c.Query("pageSize"), c.Query("pageToken")) + if err != nil { + googleError(c, http.StatusBadRequest, err.Error()) + return + } + // 分组级模型白名单开启时过滤 models[].name(名字形如 models/xxx)。 filterGeminiModels := func(models []gemini.Model) []gemini.Model { if apiKey.Group == nil || !apiKey.Group.ModelAllowlistEnabled() { @@ -106,7 +112,7 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) { return } - res, err := h.geminiCompatService.ForwardListModels(c.Request.Context(), account) + res, err := h.geminiCompatService.ForwardListModelsWithQuery(c.Request.Context(), account, listQuery) if err != nil { googleError(c, http.StatusBadGateway, err.Error()) return @@ -115,13 +121,14 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) { c.JSON(http.StatusOK, gemini.ModelsListResponse{Models: filterGeminiModels(mergeGeminiModelLists(gemini.DefaultModels(), agModels))}) return } - if res.StatusCode == http.StatusOK && len(agModels) > 0 { + // 仅在首页附加混合分组内的 Antigravity 模型,避免后续分页重复追加。 + if res.StatusCode == http.StatusOK && len(agModels) > 0 && listQuery.PageToken == "" { if merged, ok := appendUpstreamGeminiModels(res.Body, agModels); ok { res.Body = merged } } - if apiKey.Group != nil && apiKey.Group.ModelAllowlistEnabled() { + if res.StatusCode == http.StatusOK && apiKey.Group != nil && apiKey.Group.ModelAllowlistEnabled() { if filtered, dropped, ok := filterUpstreamGeminiModelsBody(res.Body, apiKey.Group.ModelAllowlist); ok && dropped { // 只在确有条目被过滤时替换响应体;全命中或解析失败时保持原始响应, // 统一经 writeUpstreamResponse 写出(保留全部上游响应头)。 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_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 cd1f10eff7..fbbc204dc3 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -432,13 +432,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 @@ -459,12 +460,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_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 7744873201..71fc939e77 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -1112,13 +1112,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 @@ -1155,6 +1156,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 } @@ -1746,13 +1748,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 @@ -1773,12 +1776,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 { @@ -3213,11 +3217,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { var oauth429FailoverState service.OpenAIOAuth429FailoverState wsAttemptMessage := append([]byte(nil), firstMessage...) waitForWSSameAccountRetry := func(account *service.Account, failoverErr *service.UpstreamFailoverError) bool { - if account == nil || failoverErr == nil || failoverErr.StatusCode != http.StatusTooManyRequests || failoverErr.SameAccountRetryDeadline.IsZero() { - return false - } - retryLimit := effectiveSameAccountRetryLimit(failoverErr, account) - if !sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) { + if account == nil || !wsSameAccountRetryAllowed(account, failoverErr, sameAccountRetryCount[account.ID]) { return false } sameAccountRetryCount[account.ID]++ @@ -3262,12 +3262,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/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/billing_service.go b/backend/internal/service/billing_service.go index 11af215814..04951bf7a4 100644 --- a/backend/internal/service/billing_service.go +++ b/backend/internal/service/billing_service.go @@ -1215,7 +1215,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/gateway_service.go b/backend/internal/service/gateway_service.go index a52bd77b17..b2cf71b1ad 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/gemini_models_endpoints.go b/backend/internal/service/gemini_models_endpoints.go index 0364cd1f5a..1893808f2a 100644 --- a/backend/internal/service/gemini_models_endpoints.go +++ b/backend/internal/service/gemini_models_endpoints.go @@ -7,8 +7,10 @@ import ( "fmt" "io" "net/http" + "net/url" "slices" "sort" + "strconv" "strings" "github.com/Wei-Shaw/sub2api/internal/pkg/gemini" @@ -24,6 +26,68 @@ import ( // errGeminiModelsUpstreamStatus 在 Vertex 分页读取遇到非 2xx 时中止分页,原始响应由调用方另行保存。 var errGeminiModelsUpstreamStatus = errors.New("upstream model list returned non-2xx status") +const maxGeminiListModelsPageTokenLen = 4096 + +// GeminiListModelsQuery 表示 GET /v1beta/models 允许透传到 AI Studio 兼容上游的分页查询参数。 +// 仅白名单放行 pageSize 与 pageToken,避免把客户端鉴权用的 ?key= 或其他任意参数透传给上游。 +type GeminiListModelsQuery struct { + PageSize int + PageToken string +} + +// ParseGeminiListModelsQuery 校验并解析客户端传入的 pageSize 与 pageToken 查询参数。 +// pageSize 允许为空或非负整数(0 表示沿用上游默认值);pageToken 作为不透明游标仅拒绝控制字符与超长输入。 +func ParseGeminiListModelsQuery(rawPageSize, rawPageToken string) (GeminiListModelsQuery, error) { + var q GeminiListModelsQuery + if rawPageSize != "" { + n, err := strconv.Atoi(rawPageSize) + if err != nil || n < 0 { + return GeminiListModelsQuery{}, errors.New("pageSize must be a non-negative integer") + } + q.PageSize = n + } + if rawPageToken != "" { + if !isSafeOpaquePageToken(rawPageToken) { + return GeminiListModelsQuery{}, errors.New("invalid pageToken") + } + q.PageToken = rawPageToken + } + return q, nil +} + +func isSafeOpaquePageToken(token string) bool { + if len(token) > maxGeminiListModelsPageTokenLen { + return false + } + for i := 0; i < len(token); i++ { + b := token[i] + if b < 0x20 || b == 0x7f { + return false + } + } + return true +} + +func (q GeminiListModelsQuery) toURLValues() (url.Values, error) { + if q.PageSize < 0 { + return nil, errors.New("pageSize must be a non-negative integer") + } + if q.PageToken != "" && !isSafeOpaquePageToken(q.PageToken) { + return nil, errors.New("invalid pageToken") + } + if q.PageSize == 0 && q.PageToken == "" { + return nil, nil + } + values := url.Values{} + if q.PageSize > 0 { + values.Set("pageSize", strconv.Itoa(q.PageSize)) + } + if q.PageToken != "" { + values.Set("pageToken", q.PageToken) + } + return values, nil +} + // DeclaredModelIDs 在分组内每个可调度 Gemini 账号都有生效的 model_mapping(含 Google One 的默认映射)时, // 返回这些映射键的并集(去重排序,通配符键原样保留)。有账号未配置映射时该账号接受任意模型,返回空, // 模型接口由选中账号的上游应答。 @@ -163,11 +227,21 @@ func modelsEndpointAccountRank(a *Account) int { // AI Studio 兼容账号原样返回上游响应;Vertex 服务账号读取 Google 发布方模型列表后转换格式, // 上游非 2xx 时原样返回该响应;Vertex API Key 账号返回内置列表。 func (s *GeminiMessagesCompatService) ForwardListModels(ctx context.Context, account *Account) (*UpstreamHTTPResult, error) { + return s.ForwardListModelsWithQuery(ctx, account, GeminiListModelsQuery{}) +} + +// ForwardListModelsWithQuery 读取账号上游的模型列表,并将白名单分页查询参数(pageSize、pageToken) +// 透传给 AI Studio 兼容上游;Vertex 账号仍返回聚合后的完整列表或内置列表。 +func (s *GeminiMessagesCompatService) ForwardListModelsWithQuery(ctx context.Context, account *Account, query GeminiListModelsQuery) (*UpstreamHTTPResult, error) { if account == nil { return nil, errors.New("account is nil") } if !account.IsVertexServiceAccount() { - return s.forwardGeminiModelsGET(ctx, account, "/v1beta/models") + queryValues, err := query.toURLValues() + if err != nil { + return nil, err + } + return s.forwardGeminiModelsGET(ctx, account, "/v1beta/models", queryValues) } if account.IsVertexAPIKey() { return geminiModelsJSONResult(http.StatusOK, gemini.FallbackModelsList()) @@ -195,7 +269,7 @@ func (s *GeminiMessagesCompatService) ForwardGetModel(ctx context.Context, accou return nil, errors.New("account is nil") } if !account.IsVertexServiceAccount() { - return s.forwardGeminiModelsGET(ctx, account, "/v1beta/models/"+model) + return s.forwardGeminiModelsGET(ctx, account, "/v1beta/models/"+model, nil) } if account.IsVertexAPIKey() { return geminiModelsJSONResult(http.StatusOK, gemini.FallbackModel(model)) @@ -226,7 +300,8 @@ func (s *GeminiMessagesCompatService) ForwardGetModel(ctx context.Context, accou // forwardGeminiModelsGET 向 AI Studio 兼容上游转发模型接口的 GET 请求。 // path 会被直接拼到上游 base URL 后面,因此按路径护栏逐片段校验,见 upstream_path_guard.go。 -func (s *GeminiMessagesCompatService) forwardGeminiModelsGET(ctx context.Context, account *Account, path string) (*UpstreamHTTPResult, error) { +// query 仅接受白名单过滤后的查询参数,通过结构化 URL 合并写入,避免直接拼接原始查询串。 +func (s *GeminiMessagesCompatService) forwardGeminiModelsGET(ctx context.Context, account *Account, path string, query url.Values) (*UpstreamHTTPResult, error) { sanitizedPath, ok := sanitizedUpstreamPathSuffix(path) if !ok || sanitizedPath == "" { return nil, errors.New("invalid path") @@ -237,7 +312,10 @@ func (s *GeminiMessagesCompatService) forwardGeminiModelsGET(ctx context.Context if err != nil { return nil, err } - fullURL := strings.TrimRight(normalizedBaseURL, "/") + sanitizedPath + fullURL, err := buildGeminiModelsEndpointURL(normalizedBaseURL, sanitizedPath, query) + if err != nil { + return nil, err + } req, err := http.NewRequestWithContext(ctx, http.MethodGet, fullURL, nil) if err != nil { @@ -267,6 +345,28 @@ func (s *GeminiMessagesCompatService) forwardGeminiModelsGET(ctx context.Context return s.doGeminiModelsGET(req, account) } +func buildGeminiModelsEndpointURL(normalizedBaseURL, sanitizedPath string, query url.Values) (string, error) { + u, err := url.Parse(normalizedBaseURL) + if err != nil { + return "", fmt.Errorf("invalid base_url: %w", err) + } + u.Fragment = "" + u.ForceQuery = false + u.Path = strings.TrimRight(u.Path, "/") + sanitizedPath + u.RawPath = "" + if len(query) > 0 { + q := u.Query() + for k, vals := range query { + if len(vals) == 0 { + continue + } + q.Set(k, vals[0]) + } + u.RawQuery = q.Encode() + } + return u.String(), nil +} + // listVertexGeminiModels 读取 Vertex 服务账号在指定区域可用的 Gemini 模型。 // 上游返回非 2xx 时 failure 为该页的原始响应,modelIDs 与 err 均为空。 func (s *GeminiMessagesCompatService) listVertexGeminiModels(ctx context.Context, account *Account, location string) (modelIDs []string, failure *UpstreamHTTPResult, err error) { diff --git a/backend/internal/service/gemini_models_endpoints_test.go b/backend/internal/service/gemini_models_endpoints_test.go index 962f642779..1a511ef9c2 100644 --- a/backend/internal/service/gemini_models_endpoints_test.go +++ b/backend/internal/service/gemini_models_endpoints_test.go @@ -6,6 +6,7 @@ import ( "context" "encoding/json" "net/http" + "strings" "testing" "github.com/Wei-Shaw/sub2api/internal/config" @@ -229,3 +230,108 @@ func TestForwardModels_VertexMultiRegionAccountReadsGlobalList(t *testing.T) { require.Equal(t, http.StatusOK, res.StatusCode) require.Equal(t, globalList, upstream.lastReq.URL.String()) } + +func TestParseGeminiListModelsQuery(t *testing.T) { + q, err := ParseGeminiListModelsQuery("", "") + require.NoError(t, err) + require.Equal(t, GeminiListModelsQuery{}, q) + + q, err = ParseGeminiListModelsQuery("0", "") + require.NoError(t, err) + require.Equal(t, GeminiListModelsQuery{PageSize: 0}, q) + + q, err = ParseGeminiListModelsQuery("1000", "Chttb2RlbHMvZ2VtaW5p+abc/def==") + require.NoError(t, err) + require.Equal(t, GeminiListModelsQuery{PageSize: 1000, PageToken: "Chttb2RlbHMvZ2VtaW5p+abc/def=="}, q) + + q, err = ParseGeminiListModelsQuery("", strings.Repeat("a", maxGeminiListModelsPageTokenLen)) + require.NoError(t, err) + require.Len(t, q.PageToken, maxGeminiListModelsPageTokenLen) + + for _, badSize := range []string{"-1", "abc", "1.5", "10\n", " 10"} { + _, err = ParseGeminiListModelsQuery(badSize, "") + require.Error(t, err, "pageSize=%q", badSize) + } + for _, badToken := range []string{ + "tok\r\n", + "tok\x00", + "tok\x7f", + strings.Repeat("a", maxGeminiListModelsPageTokenLen+1), + } { + _, err = ParseGeminiListModelsQuery("", badToken) + require.Error(t, err, "pageToken len=%d", len(badToken)) + } +} + +func TestForwardListModelsWithQuery_ForwardsPaginationParams(t *testing.T) { + t.Run("forwards pageSize and base64 pageToken with proper encoding", func(t *testing.T) { + upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, `{"models":[{"name":"models/gemini-2.5-pro"}]}`)} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + account := &Account{ID: 261, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "api_key": "sk-pool", + "base_url": "https://relay.example.com/proxy/", + }} + + res, err := svc.ForwardListModelsWithQuery(context.Background(), account, GeminiListModelsQuery{ + PageSize: 1000, + PageToken: "abc+/def==", + }) + require.NoError(t, err) + require.Equal(t, http.StatusOK, res.StatusCode) + require.Equal(t, "https://relay.example.com/proxy/v1beta/models?pageSize=1000&pageToken=abc%2B%2Fdef%3D%3D", upstream.lastReq.URL.String()) + require.Equal(t, "sk-pool", upstream.lastReq.Header.Get("x-goog-api-key")) + }) + + t.Run("merges with existing base_url query params and strips fragment", func(t *testing.T) { + upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, `{"models":[]}`)} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + account := &Account{ID: 262, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "api_key": "sk-pool", + "base_url": "https://relay.example.com/gateway?tenant=alpha#frag", + }} + + res, err := svc.ForwardListModelsWithQuery(context.Background(), account, GeminiListModelsQuery{PageSize: 50}) + require.NoError(t, err) + require.Equal(t, http.StatusOK, res.StatusCode) + require.Equal(t, "https://relay.example.com/gateway/v1beta/models?pageSize=50&tenant=alpha", upstream.lastReq.URL.String()) + }) + + t.Run("pageSize zero omits pageSize and leaves URL clean", func(t *testing.T) { + upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, `{"models":[]}`)} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + account := &Account{ID: 263, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "api_key": "sk-pool", + "base_url": "https://relay.example.com", + }} + + res, err := svc.ForwardListModelsWithQuery(context.Background(), account, GeminiListModelsQuery{PageSize: 0}) + require.NoError(t, err) + require.Equal(t, http.StatusOK, res.StatusCode) + require.Equal(t, "https://relay.example.com/v1beta/models", upstream.lastReq.URL.String()) + }) + + t.Run("rejects invalid direct query before hitting upstream", func(t *testing.T) { + upstream := &httpUpstreamRecorder{} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + account := &Account{ID: 264, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "sk-pool"}} + + _, err := svc.ForwardListModelsWithQuery(context.Background(), account, GeminiListModelsQuery{PageSize: -1}) + require.Error(t, err) + _, err = svc.ForwardListModelsWithQuery(context.Background(), account, GeminiListModelsQuery{PageToken: "bad\n"}) + require.Error(t, err) + require.Empty(t, upstream.requests) + }) + + t.Run("vertex service account ignores AI Studio pagination query", func(t *testing.T) { + upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, `{"publisherModels":[{"name":"publishers/google/models/gemini-2.5-flash"}]}`)} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + + res, err := svc.ForwardListModelsWithQuery(context.Background(), vertexModelSyncTestAccount(nil), GeminiListModelsQuery{ + PageSize: 10, + PageToken: "client-token", + }) + require.NoError(t, err) + require.Equal(t, http.StatusOK, res.StatusCode) + require.Equal(t, "https://us-central1-aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300", upstream.lastReq.URL.String()) + }) +} diff --git a/backend/internal/service/grok_context_length_exceeded_test.go b/backend/internal/service/grok_context_length_exceeded_test.go new file mode 100644 index 0000000000..4ee5058000 --- /dev/null +++ b/backend/internal/service/grok_context_length_exceeded_test.go @@ -0,0 +1,160 @@ +//go:build unit + +package service + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// xAI 对超出上下文窗口的请求回 400,原因只写在顶层 error 字符串里。 +const grokInputTooLargeBody = `{"code":"invalid-argument","error":"Failed to start sampling: [input_too_large] The prompt is too long for this model’s context window (612345 tokens > 500000 tokens)"}` + +const grokInputTooLargeNoCountsBody = `{"code":"invalid-argument","error":"Failed to start sampling: [input_too_large] The prompt is too long for this model’s context window"}` + +const grokGenericInvalidArgumentBody = `{"code":"invalid-argument","error":"Failed to start sampling: invalid tool schema"}` + +func TestDetectGrokContextLengthExceeded(t *testing.T) { + got, ok := detectGrokContextLengthExceeded(http.StatusBadRequest, []byte(grokInputTooLargeBody)) + require.True(t, ok) + require.Equal(t, "The prompt is too long for this model's context window (612345 tokens > 500000 tokens)", got.Message) + require.Equal(t, int64(500000), got.Window) + + got, ok = detectGrokContextLengthExceeded(http.StatusBadRequest, []byte(grokInputTooLargeNoCountsBody)) + require.True(t, ok) + require.Equal(t, "The prompt is too long for this model's context window", got.Message) + require.Zero(t, got.Window) + + nested := `{"error":{"code":"invalid_argument","message":"[input_too_large] prompt exceeds window (12 tokens > 10 tokens)"}}` + got, ok = detectGrokContextLengthExceeded(http.StatusBadRequest, []byte(nested)) + require.True(t, ok) + require.Equal(t, int64(10), got.Window) + + for _, tc := range []struct { + name string + status int + body string + }{ + {name: "generic invalid argument", status: http.StatusBadRequest, body: grokGenericInvalidArgumentBody}, + {name: "context words without the explicit tag", status: http.StatusBadRequest, body: `{"code":"invalid-argument","error":"The prompt is too long for this model’s context window"}`}, + {name: "tag on a non-400", status: http.StatusInternalServerError, body: grokInputTooLargeBody}, + {name: "empty body", status: http.StatusBadRequest, body: ``}, + } { + t.Run(tc.name, func(t *testing.T) { + _, ok := detectGrokContextLengthExceeded(tc.status, []byte(tc.body)) + require.False(t, ok) + }) + } +} + +func TestGrokInputTooLargeDoesNotFailoverOrCoolDown(t *testing.T) { + repo := &grokQuotaAccountRepo{} + svc := &OpenAIGatewayService{accountRepo: repo} + account := &Account{ID: 8241, Platform: PlatformGrok, Type: AccountTypeOAuth} + + require.False(t, svc.shouldFailoverGrokUpstreamError(http.StatusBadRequest, []byte(grokInputTooLargeBody))) + svc.handleGrokAccountUpstreamError(context.Background(), account, http.StatusBadRequest, nil, []byte(grokInputTooLargeBody)) + require.Zero(t, repo.tempUnschedCalls) + require.Zero(t, repo.rateLimitedCalls) + require.Zero(t, repo.updateCalls) +} + +func TestGrokResponsesInputTooLargeKeepsContextLengthExceeded(t *testing.T) { + for _, tc := range []struct { + name string + body string + upstreamWindow string + wantMessage string + wantWindow string + }{ + { + name: "upstream window header wins", + body: grokInputTooLargeBody, + upstreamWindow: "2000000", + wantMessage: "The prompt is too long for this model's context window (612345 tokens > 500000 tokens)", + wantWindow: "2000000", + }, + { + name: "window from the stated limit", + body: grokInputTooLargeBody, + wantMessage: "The prompt is too long for this model's context window (612345 tokens > 500000 tokens)", + wantWindow: "500000", + }, + { + name: "invalid upstream header falls back to the stated limit", + body: grokInputTooLargeBody, + upstreamWindow: "0", + wantMessage: "The prompt is too long for this model's context window (612345 tokens > 500000 tokens)", + wantWindow: "500000", + }, + { + name: "no window anywhere keeps only the code", + body: grokInputTooLargeNoCountsBody, + wantMessage: "The prompt is too long for this model's context window", + wantWindow: "", + }, + } { + t.Run(tc.name, func(t *testing.T) { + repo := &grokQuotaAccountRepo{} + svc := &OpenAIGatewayService{accountRepo: repo} + account := &Account{ID: 8242, Platform: PlatformGrok, Type: AccountTypeOAuth} + c, rec := newOpenAIUpstreamErrorTestContext(t) + resp := newOpenAIUpstreamErrorResponse(http.StatusBadRequest, tc.body) + if tc.upstreamWindow != "" { + resp.Header.Set("x-grok-context-window", tc.upstreamWindow) + } + + _, err := svc.handleErrorResponse(context.Background(), resp, c, account, nil, "grok-4.6") + + require.Error(t, err) + require.Equal(t, http.StatusBadRequest, rec.Code) + require.Contains(t, rec.Header().Get("Content-Type"), "application/json") + body := rec.Body.Bytes() + require.Equal(t, "invalid_request_error", gjson.GetBytes(body, "error.type").String()) + require.Equal(t, "context_length_exceeded", gjson.GetBytes(body, "error.code").String()) + require.Equal(t, tc.wantMessage, gjson.GetBytes(body, "error.message").String()) + require.Equal(t, tc.wantWindow, rec.Header().Get("x-grok-context-window")) + require.Zero(t, repo.tempUnschedCalls) + require.Zero(t, repo.rateLimitedCalls) + }) + } +} + +func TestGrokResponsesGenericInvalidArgumentKeepsShape(t *testing.T) { + gin.SetMode(gin.TestMode) + svc := &OpenAIGatewayService{accountRepo: &grokQuotaAccountRepo{}} + account := &Account{ID: 8243, Platform: PlatformGrok, Type: AccountTypeOAuth} + c, rec := newOpenAIUpstreamErrorTestContext(t) + resp := newOpenAIUpstreamErrorResponse(http.StatusBadRequest, grokGenericInvalidArgumentBody) + resp.Header.Set("x-grok-context-window", "500000") + + _, err := svc.handleErrorResponse(context.Background(), resp, c, account, nil, "grok-4.6") + require.Error(t, err) + + // 与没有这条识别时一样:通用写法、不补上下文窗口头。 + want := httptest.NewRecorder() + wantCtx, _ := gin.CreateTestContext(want) + writeOpenAIUpstreamClientError(wantCtx, http.StatusBadRequest, []byte(grokGenericInvalidArgumentBody), "") + require.Equal(t, http.StatusBadRequest, rec.Code) + require.JSONEq(t, want.Body.String(), rec.Body.String()) + require.NotEqual(t, "context_length_exceeded", gjson.Get(rec.Body.String(), "error.code").String()) + require.Empty(t, rec.Header().Get("x-grok-context-window")) +} + +func TestOpenAIAccountInputTooLargeTagIsNotRemapped(t *testing.T) { + svc := &OpenAIGatewayService{} + c, rec := newOpenAIUpstreamErrorTestContext(t) + resp := newOpenAIUpstreamErrorResponse(http.StatusBadRequest, grokInputTooLargeBody) + + _, err := svc.handleErrorResponse(context.Background(), resp, c, newOpenAIUpstreamErrorTestAccount(), nil, "gpt-5") + require.Error(t, err) + require.Equal(t, http.StatusBadRequest, rec.Code) + require.NotEqual(t, "context_length_exceeded", gjson.Get(rec.Body.String(), "error.code").String()) + require.Empty(t, rec.Header().Get("x-grok-context-window")) +} diff --git a/backend/internal/service/grok_upstream_errors.go b/backend/internal/service/grok_upstream_errors.go index a21837256e..1faa37891d 100644 --- a/backend/internal/service/grok_upstream_errors.go +++ b/backend/internal/service/grok_upstream_errors.go @@ -4,6 +4,8 @@ import ( "context" "encoding/json" "net/http" + "regexp" + "strconv" "strings" "time" @@ -336,3 +338,70 @@ func (s *OpenAIGatewayService) applyGrokForbiddenPolicy(ctx context.Context, acc } return true } + +// grokContextLengthExceededMarker is the reason tag xAI puts in front of its +// context-window refusal, e.g. HTTP 400 +// {"code":"invalid-argument","error":"Failed to start sampling: [input_too_large] The prompt is too long for this model’s context window (612345 tokens > 500000 tokens)"}. +// invalid-argument alone is shared by every malformed request, so only this +// explicit tag is trusted. +const grokContextLengthExceededMarker = "[input_too_large]" + +const grokContextLengthExceededMessage = "The prompt is too long for this model's context window" + +// grokContextWindowHeader carries the model's context window in tokens. Grok +// Build compacts and resends an oversized turn only when this header comes +// with the context_length_exceeded error. +const grokContextWindowHeader = "X-Grok-Context-Window" + +var reGrokContextWindowTokens = regexp.MustCompile(`\((\d+)\s+tokens\s*>\s*(\d+)\s+tokens\)`) + +// grokContextLengthExceeded describes an explicit xAI context-window refusal. +// Window is the limit stated in the upstream message, or 0 when the message +// does not state it. +type grokContextLengthExceeded struct { + Message string + Window int64 +} + +// detectGrokContextLengthExceeded reports whether an xAI 400 is the explicit +// context-window refusal. Token counts are copied only when the same upstream +// message states them; otherwise the refusal is still reported with a message +// that carries no numbers. +func detectGrokContextLengthExceeded(statusCode int, body []byte) (grokContextLengthExceeded, bool) { + if statusCode != http.StatusBadRequest || len(body) == 0 { + return grokContextLengthExceeded{}, false + } + for _, candidate := range grokStructuredErrorMessageCandidates(body) { + if !strings.Contains(strings.ToLower(candidate), grokContextLengthExceededMarker) { + continue + } + result := grokContextLengthExceeded{Message: grokContextLengthExceededMessage} + if m := reGrokContextWindowTokens.FindStringSubmatch(candidate); len(m) == 3 { + actual, errA := strconv.ParseInt(m[1], 10, 64) + limit, errB := strconv.ParseInt(m[2], 10, 64) + if errA == nil && errB == nil && limit > 0 { + result.Message += " (" + strconv.FormatInt(actual, 10) + " tokens > " + strconv.FormatInt(limit, 10) + " tokens)" + result.Window = limit + } + } + return result, true + } + return grokContextLengthExceeded{}, false +} + +// grokContextWindowForClient prefers the upstream's own context-window header +// and falls back to the limit stated in the error. It returns 0 when neither +// is a positive integer, in which case no header is sent. +func grokContextWindowForClient(upstreamHeaders http.Header, statedWindow int64) int64 { + if upstreamHeaders != nil { + if raw := strings.TrimSpace(upstreamHeaders.Get(grokContextWindowHeader)); raw != "" { + if window, err := strconv.ParseInt(raw, 10, 64); err == nil && window > 0 { + return window + } + } + } + if statedWindow > 0 { + return statedWindow + } + return 0 +} diff --git a/backend/internal/service/openai_capacity_shed_test.go b/backend/internal/service/openai_capacity_shed_test.go index e6eca95b36..9b3db1b053 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,81 @@ 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) + }) + } + } +} + +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 分支,只能把致命错误原样转发给客户端。 @@ -603,10 +732,11 @@ func TestOpenAIStreamBareErrorAfterOutputIsRecorded(t *testing.T) { // 依赖其原码解析重试延时)必须原样保留。 func TestSanitizeOpenAICapacityShedErrorCodeForClient(t *testing.T) { cases := []struct { - name string - payload string - wantChanged bool - wantContain string + name string + payload string + wantChanged bool + wantContain string + wantNotContain []string }{ { name: "failed事件嵌套code改写", @@ -633,10 +763,25 @@ func TestSanitizeOpenAICapacityShedErrorCodeForClient(t *testing.T) { wantContain: `"code":"server_error"`, }, { - name: "rate_limit不改写", - payload: `{"type":"response.failed","response":{"error":{"code":"rate_limit_exceeded","message":"try again in 3s"}}}`, - wantChanged: false, - wantContain: `"code":"rate_limit_exceeded"`, + name: "剥离error帧headers中的retry-after并清理空headers", + payload: `{"type":"error","error":{"code":"server_is_overloaded","headers":{"retry-after":"326","retry-after-ms":"326000"},"message":"Our servers are currently overloaded. Please try again later.","type":"service_unavailable_error"},"sequence_number":3}`, + wantChanged: true, + wantContain: `"code":"server_error"`, + wantNotContain: []string{`"retry-after"`, `"retry-after-ms"`, `"headers"`}, + }, + { + name: "上游中转已改写为server_error时仍剥离retry-after与直接重试延时字段", + payload: `{"type":"error","error":{"code":"server_error","headers":{"retry-after":"326","retry-after-ms":"326000","x-request-id":"req_123"},"retry_after":326,"resets_in_seconds":326,"message":"Our servers are currently overloaded. Please try again later.","type":"service_unavailable_error"},"sequence_number":3}`, + wantChanged: true, + wantContain: `"x-request-id":"req_123"`, + wantNotContain: []string{`"retry-after"`, `"retry-after-ms"`, `"retry_after"`, `"resets_in_seconds"`}, + }, + { + name: "rate_limit保留原码与retry-after", + payload: `{"type":"response.failed","response":{"error":{"code":"rate_limit_exceeded","headers":{"retry-after":"30"},"resets_in_seconds":30,"message":"try again in 30s"}}}`, + wantChanged: false, + wantContain: `"retry-after":"30"`, + wantNotContain: nil, }, { name: "普通server_error不改写", @@ -660,6 +805,9 @@ func TestSanitizeOpenAICapacityShedErrorCodeForClient(t *testing.T) { require.NotContains(t, string(out), "server_is_overloaded") require.NotContains(t, string(out), "slow_down") } + for _, forbidden := range tc.wantNotContain { + require.NotContains(t, string(out), forbidden) + } }) } } diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index e0ec5e9232..d3c4e119d5 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -1557,14 +1557,37 @@ func logOpenAICapacityFailoverSuppressed( // 客户端内置的退避重试。 const openAICapacityShedRetryableClientCode = "server_error" +// openAICapacityShedRetryDelayFieldNames 是容量降载事件转发给客户端前需要剥离的 +// 重试延时字段。OpenAI 上游在容量降载事件中常附带 error.headers.retry-after / +// retry-after-ms(例如 326s),客户端(如 Codex CLI)一旦解析到这些字段就会用上游 +// 给出的数分钟等待覆盖客户端内置的毫秒级指数退避,导致客户端长时间挂起在 +// Reconnecting 状态。rate_limit_exceeded 不经过本函数,其配额重置时间不受影响。 +var openAICapacityShedRetryDelayFieldNames = []string{ + "retry_after", + "retry_after_ms", + "resets_at", + "resets_in_seconds", +} + +func isOpenAICapacityShedRetryAfterHeaderKey(key string) bool { + switch strings.ToLower(strings.TrimSpace(key)) { + case "retry-after", "retry-after-ms", "retry_after", "retry_after_ms": + return true + default: + return false + } +} + // sanitizeOpenAICapacityShedErrorCodeForClient 把即将写给下游客户端的 -// error / response.failed 事件中的容量降载错误码改写为客户端可重试的错误码。 +// error / response.failed 事件中的容量降载错误码改写为客户端可重试的错误码, +// 并剥离上游附带的 retry-after 重试延时字段。 // 走到转发这一步说明网关侧 failover 已不可用(流中途)或已用尽;保留原始降载码 -// 只会让客户端就地终止会话。错误消息原样保留;监控与账号状态判定都基于改写前 +// 只会让客户端就地终止会话,而保留数分钟级的 retry-after 则会让客户端跳过内置的 +// 毫秒级退避、长时间卡在重连倒计时。错误消息原样保留;监控与账号状态判定都基于改写前 // 的原始 payload,不受影响。rate_limit 等其他错误码一律不动(客户端依赖 // rate_limit_exceeded 原码解析重试延时)。 func sanitizeOpenAICapacityShedErrorCodeForClient(payload []byte) ([]byte, bool) { - if len(payload) == 0 || !gjson.ValidBytes(payload) || !isOpenAIUpstreamCapacityShedEvent(payload) { + if len(payload) == 0 || !bytes.Contains(payload, []byte(`"error"`)) || !gjson.ValidBytes(payload) || !isOpenAIUpstreamCapacityShedEvent(payload) { return payload, false } updated := payload @@ -1575,15 +1598,61 @@ func sanitizeOpenAICapacityShedErrorCodeForClient(payload []byte) ([]byte, bool) continue } code := strings.ToLower(strings.TrimSpace(gjson.GetBytes(updated, path).String())) - if code != "" && code != "server_is_overloaded" && code != "slow_down" { + if code != "" && code != "server_is_overloaded" && code != "slow_down" && code != openAICapacityShedRetryableClientCode { continue } - next, err := sjson.SetBytes(updated, path, openAICapacityShedRetryableClientCode) - if err != nil { - return payload, false + if code != openAICapacityShedRetryableClientCode { + next, err := sjson.SetBytes(updated, path, openAICapacityShedRetryableClientCode) + if err != nil { + return payload, false + } + updated = next + changed = true + } + headersPath := parent + ".headers" + if headersResult := gjson.GetBytes(updated, headersPath); headersResult.IsObject() { + var removeKeys []string + remainingKeys := 0 + headersResult.ForEach(func(k, _ gjson.Result) bool { + key := k.String() + if isOpenAICapacityShedRetryAfterHeaderKey(key) { + removeKeys = append(removeKeys, key) + } else { + remainingKeys++ + } + return true + }) + if len(removeKeys) > 0 { + if remainingKeys == 0 { + next, err := sjson.DeleteBytes(updated, headersPath) + if err != nil { + return payload, false + } + updated = next + } else { + for _, key := range removeKeys { + next, err := sjson.DeleteBytes(updated, headersPath+"."+key) + if err != nil { + return payload, false + } + updated = next + } + } + changed = true + } + } + for _, field := range openAICapacityShedRetryDelayFieldNames { + fieldPath := parent + "." + field + if !gjson.GetBytes(updated, fieldPath).Exists() { + continue + } + next, err := sjson.DeleteBytes(updated, fieldPath) + if err != nil { + return payload, false + } + updated = next + changed = true } - updated = next - changed = true } return updated, changed } @@ -1934,15 +2003,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 @@ -2047,7 +2121,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..3e2c8f5fcf 100644 --- a/backend/internal/service/openai_gateway_upstream_errors.go +++ b/backend/internal/service/openai_gateway_upstream_errors.go @@ -197,59 +197,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 +348,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) @@ -448,6 +414,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, @@ -775,6 +746,19 @@ func (s *OpenAIGatewayService) handleErrorResponse( // 回真实状态码 + invalid_request_error + 真实 message;/v1/images 还额外透传 // code/param。原生 Responses 是唯一漏掉的一条。 if isOpenAIDeterministicClientError(resp.StatusCode) { + // xAI reports an oversized prompt as a flat invalid-argument body that the + // shared extractor cannot read; keep the explicit reason as the OpenAI code + // and the context window Grok Build needs to compact and resend. + if account != nil && account.Platform == PlatformGrok { + if exceeded, ok := detectGrokContextLengthExceeded(resp.StatusCode, body); ok { + setOpsUpstreamError(c, resp.StatusCode, exceeded.Message, upstreamDetail) + if window := grokContextWindowForClient(resp.Header, exceeded.Window); window > 0 { + c.Header(grokContextWindowHeader, strconv.FormatInt(window, 10)) + } + writeOpenAIContextLengthExceededError(c, resp.StatusCode, exceeded.Message) + return nil, fmt.Errorf("upstream error: %d context_length_exceeded message=%s", resp.StatusCode, exceeded.Message) + } + } writeOpenAIUpstreamClientError(c, resp.StatusCode, body, upstreamMsg) if upstreamMsg == "" { return nil, fmt.Errorf("upstream error: %d", resp.StatusCode) diff --git a/backend/internal/service/openai_images.go b/backend/internal/service/openai_images.go index 327aed6e54..272ad05036 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 "" @@ -302,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") @@ -331,51 +339,106 @@ 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() + v := gjson.GetBytes(body, path) + return v.Exists() && v.Type != gjson.Null }) 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 { + 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) + } + 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 + } + 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 { _, params, err := mime.ParseMediaType(contentType) if err != nil { @@ -529,7 +592,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 +697,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..4e18d6a160 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,137 @@ 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","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=="}}`, + } { + t.Run(invalidBody, func(t *testing.T) { + c, _ := newOpenAIImagesTestContext(t, []byte(invalidBody)) + _, err := newOpenAIImagesTestService(nil).ParseOpenAIImagesRequest(c, []byte(invalidBody)) + 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) { + 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()) + }) + } + + 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_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..b260389bae 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,7 +1928,12 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesOAuth( respBody := s.readUpstreamErrorBody(resp) _ = resp.Body.Close() respBody = s.redactAgentIdentitySensitiveBody(upstreamCtx, account, respBody) - if direct && !requiresCodexDirectImages(upstreamModel) && (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) && endpointUnavailable { return s.forwardOpenAIImagesOAuth(withOpenAIImagesForceResponses(ctx), c, account, parsed, channelMappedModel) } if !agentIdentityTaskRecoveryWasTried(ctx) && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, respBody) { diff --git a/backend/internal/service/openai_responses_input_compat.go b/backend/internal/service/openai_responses_input_compat.go index 29619bc4dd..f7d33fa87c 100644 --- a/backend/internal/service/openai_responses_input_compat.go +++ b/backend/internal/service/openai_responses_input_compat.go @@ -50,8 +50,11 @@ func sanitizeOpenAIResponsesOrphanToolOutputs(reqBody map[string]any, input []an // named function outputs without a preceding function call. Preserve // their native type, namespace and output instead of silently dropping // the request that started the turn. - if callID == "" && strings.TrimSpace(firstNonEmptyString(item["type"])) == "function_call_output" && - strings.TrimSpace(firstNonEmptyString(item["name"])) != "" { + if isStandaloneNamedFunctionCallOutput( + firstNonEmptyString(item["type"]), + callID, + firstNonEmptyString(item["name"]), + ) { normalized = append(normalized, rawItem) continue } diff --git a/backend/internal/service/openai_tool_continuation.go b/backend/internal/service/openai_tool_continuation.go index 3b2356c971..c85e731947 100644 --- a/backend/internal/service/openai_tool_continuation.go +++ b/backend/internal/service/openai_tool_continuation.go @@ -50,6 +50,14 @@ func isCodexToolCallOutputItemType(typ string) bool { } } +// isStandaloneNamedFunctionCallOutput 判断是否为 Codex 注入的带名称、无 call_id 的独立输入(如任务派发 create_thread)。 +// 此类项属于客户端注入的独立上下文而非需要前置工具调用配对的工具结果。 +func isStandaloneNamedFunctionCallOutput(itemType, callID, name string) bool { + return strings.TrimSpace(callID) == "" && + strings.TrimSpace(itemType) == "function_call_output" && + strings.TrimSpace(name) != "" +} + // NeedsToolContinuation 判定请求是否需要工具调用续链处理。 // 满足以下任一信号即视为续链:previous_response_id、input 内包含工具输出/item_reference、 // 或显式声明 tools/tool_choice。 @@ -112,9 +120,13 @@ func AnalyzeToolContinuationSignals(reqBody map[string]any) ToolContinuationSign signals.HasToolCallContext = true } case isCodexToolCallOutputItemType(itemType): - signals.HasFunctionCallOutput = true callID, _ := itemMap["call_id"].(string) callID = strings.TrimSpace(callID) + name, _ := itemMap["name"].(string) + if isStandaloneNamedFunctionCallOutput(itemType, callID, name) { + continue + } + signals.HasFunctionCallOutput = true if callID == "" { signals.HasFunctionCallOutputMissingCallID = true continue @@ -249,8 +261,11 @@ func AnalyzeToolCallOutputContextCoverageBytes(body []byte) ToolCallOutputContex itemType := item.Get("type").String() switch { case isCodexToolCallOutputItemType(itemType): - coverage.HasFunctionCallOutput = true callID := strings.TrimSpace(item.Get("call_id").String()) + if isStandaloneNamedFunctionCallOutput(itemType, callID, item.Get("name").String()) { + return + } + coverage.HasFunctionCallOutput = true if callID == "" { missingCallID = true return diff --git a/backend/internal/service/openai_tool_continuation_test.go b/backend/internal/service/openai_tool_continuation_test.go index 460a659c2e..b8769894b6 100644 --- a/backend/internal/service/openai_tool_continuation_test.go +++ b/backend/internal/service/openai_tool_continuation_test.go @@ -51,6 +51,9 @@ func TestHasFunctionCallOutput(t *testing.T) { "input": []any{map[string]any{"type": typ}}, }), typ) } + require.False(t, HasFunctionCallOutput(map[string]any{ + "input": []any{map[string]any{"type": "function_call_output", "name": "create_thread", "output": "delegated"}}, + })) require.False(t, HasFunctionCallOutput(map[string]any{ "input": "text", })) @@ -100,6 +103,9 @@ func TestHasFunctionCallOutputMissingCallID(t *testing.T) { require.True(t, HasFunctionCallOutputMissingCallID(map[string]any{ "input": []any{map[string]any{"type": "tool_search_output"}}, })) + require.False(t, HasFunctionCallOutputMissingCallID(map[string]any{ + "input": []any{map[string]any{"type": "function_call_output", "name": "create_thread", "output": "delegated"}}, + })) require.False(t, HasFunctionCallOutputMissingCallID(map[string]any{ "input": []any{map[string]any{"type": "tool_search_output", "call_id": "call_1"}}, })) @@ -134,6 +140,10 @@ func TestValidateFunctionCallOutputContextBytesMatchesMapValidation(t *testing.T name: "missing_call_id", body: map[string]any{"input": []any{map[string]any{"type": "function_call_output"}}}, }, + { + name: "named_standalone_delegation_without_call_id", + body: map[string]any{"input": []any{map[string]any{"type": "function_call_output", "name": "create_thread", "output": "delegated"}}}, + }, { name: "call_id_without_reference", body: map[string]any{"input": []any{map[string]any{"type": "function_call_output", "call_id": "call_1"}}}, @@ -263,6 +273,34 @@ func TestAnalyzeToolCallOutputContextCoverageBytes(t *testing.T) { hasOutput: true, coversAllIDs: false, }, + { + name: "standalone_named_delegation_only_does_not_require_replay", + body: map[string]any{"input": []any{ + map[string]any{"type": "function_call_output", "name": "create_thread", "output": "delegated"}, + map[string]any{"type": "message", "role": "user", "content": "summary"}, + }}, + hasOutput: false, + coversAllIDs: false, + }, + { + name: "standalone_named_delegation_with_covered_output", + body: map[string]any{"input": []any{ + map[string]any{"type": "function_call_output", "name": "create_thread", "output": "delegated"}, + map[string]any{"type": "function_call", "call_id": "call_a"}, + map[string]any{"type": "function_call_output", "call_id": "call_a"}, + }}, + hasOutput: true, + coversAllIDs: true, + }, + { + name: "standalone_named_delegation_with_unpaired_output_requires_replay", + body: map[string]any{"input": []any{ + map[string]any{"type": "function_call_output", "name": "create_thread", "output": "delegated"}, + map[string]any{"type": "function_call_output", "call_id": "call_b"}, + }}, + hasOutput: true, + coversAllIDs: false, + }, { name: "mixed_context_and_reference_cover_all", body: map[string]any{"input": []any{ diff --git a/backend/internal/service/openai_upstream_client_error.go b/backend/internal/service/openai_upstream_client_error.go index 431f5a7703..0f11770bc3 100644 --- a/backend/internal/service/openai_upstream_client_error.go +++ b/backend/internal/service/openai_upstream_client_error.go @@ -36,6 +36,19 @@ func isOpenAIDeterministicClientError(statusCode int) bool { // upstreamMsg 由调用方传入,调用方已做过 sanitizeUpstreamErrorMessage 与 // redactAgentIdentitySensitiveBody;这里不重复清洗,也不回落读取原始 body 的 // message,避免绕开那两道脱敏。 +// writeOpenAIContextLengthExceededError writes the OpenAI Responses shape for a +// prompt that does not fit the model's context window, so clients can tell it +// apart from other rejected requests (for example to compact and resend). +func writeOpenAIContextLengthExceededError(c *gin.Context, statusCode int, message string) { + c.JSON(statusCode, gin.H{ + "error": gin.H{ + "type": "invalid_request_error", + "code": "context_length_exceeded", + "message": message, + }, + }) +} + func writeOpenAIUpstreamClientError(c *gin.Context, statusCode int, body []byte, upstreamMsg string) { errorPayload := gin.H{"type": openAIUpstreamClientErrorFallbackType} if errType := strings.TrimSpace(gjson.GetBytes(body, "error.type").String()); errType != "" { diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 317d647f70..2f11610f77 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -202,6 +202,12 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( requestedReasoningEffort *string } ingressSessionOriginalModel := "" + activeTurnMetadata := "" + activeWindowID := "" + if c != nil { + activeTurnMetadata = strings.TrimSpace(c.GetHeader(openAIWSTurnMetadataHeader)) + activeWindowID = strings.TrimSpace(c.GetHeader("x-codex-window-id")) + } applyPayloadMutation := func(current []byte, path string, value any) ([]byte, error) { next, err := sjson.SetBytes(current, path, value) @@ -219,6 +225,8 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( payload[path] = value case "client_metadata." + openAIWSTurnMetadataHeader: setOpenAIWSTurnMetadata(payload, fmt.Sprintf("%v", value)) + case "client_metadata.x-codex-window-id": + setOpenAIWSWindowIDMetadata(payload, fmt.Sprintf("%v", value)) default: return nil, err } @@ -318,8 +326,26 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( nil, ) } - if turnMetadata := strings.TrimSpace(c.GetHeader(openAIWSTurnMetadataHeader)); turnMetadata != "" { - next, setErr := applyPayloadMutation(normalized, "client_metadata."+openAIWSTurnMetadataHeader, turnMetadata) + frameTurnMetadata := strings.TrimSpace(gjson.GetBytes(normalized, "client_metadata."+openAIWSTurnMetadataHeader).String()) + frameWindowID := strings.TrimSpace(gjson.GetBytes(normalized, "client_metadata.x-codex-window-id").String()) + if frameTurnMetadata != "" { + activeTurnMetadata = frameTurnMetadata + if w := strings.TrimSpace(gjson.Get(frameTurnMetadata, "window_id").String()); w != "" { + activeWindowID = w + } + } else if frameWindowID != "" { + activeWindowID = frameWindowID + if activeTurnMetadata != "" && strings.TrimSpace(gjson.Get(activeTurnMetadata, "window_id").String()) != frameWindowID { + activeTurnMetadata = "" + } + } else if activeTurnMetadata != "" { + next, setErr := applyPayloadMutation(normalized, "client_metadata."+openAIWSTurnMetadataHeader, activeTurnMetadata) + if setErr != nil { + return openAIWSClientPayload{}, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", setErr) + } + normalized = next + } else if activeWindowID != "" { + next, setErr := applyPayloadMutation(normalized, "client_metadata.x-codex-window-id", activeWindowID) if setErr != nil { return openAIWSClientPayload{}, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", setErr) } @@ -596,6 +622,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( } defer history.close() historyLost := false + lastBridgeWindowID := "" var bridgeReplayInput []json.RawMessage bridgeReplayInputExists := false bridgeLastResponseID := "" @@ -607,15 +634,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 @@ -627,6 +645,40 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( if c != nil && sessionHash != "" { c.Set(openAIWSIngressSessionHashContextKey, sessionHash) } + boundaryPayload, contextWindowBoundary, boundaryErr := normalizeOpenAIWSContextWindowBoundary( + currentBridgePayload.payloadRaw, + lastBridgeWindowID, + ) + if boundaryErr != nil { + return fmt.Errorf("normalize Codex websocket http bridge context-window boundary: %w", boundaryErr) + } + if contextWindowBoundary.Changed { + if contextWindowBoundary.PreviousResponseIDRemoved { + responsesLite := isOpenAIResponsesLiteWebSocketPayload(boundaryPayload) + if compatBody, compatChanged, compatErr := normalizeOpenAIResponsesWebSocketCompatibilityBodyWithConfig(s.cfg, boundaryPayload, account, responsesLite); compatErr != nil { + return NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", compatErr) + } else if compatChanged { + boundaryPayload = compatBody + } + } + currentBridgePayload.payloadRaw = boundaryPayload + currentBridgePayload.payloadBytes = len(boundaryPayload) + currentBridgePayload.previousResponseID = "" + historyLost = false + bridgeReplayInput = nil + bridgeReplayInputExists = false + bridgeAccountFailoverInput = nil + bridgeAccountFailoverInputExists = false + history.resize(0) + logOpenAIWSModeInfo( + "ingress_ws_http_bridge_context_window_changed account_id=%d turn=%d action=reset_bridge_replay_state previous_window_id=%s current_window_id=%s previous_response_id_removed=%v", + account.ID, + turn, + truncateOpenAIWSLogValue(lastBridgeWindowID, openAIWSIDValueMaxLen), + truncateOpenAIWSLogValue(contextWindowBoundary.WindowID, openAIWSIDValueMaxLen), + contextWindowBoundary.PreviousResponseIDRemoved, + ) + } // 剥离本会话已知失效的加密项,阻断同一失效密文随历史反复触发上游拒绝。 // 历史序列须同步剥离,否则与已剥离的当前 input 项错位,prefix 复用失配。 if invalidDigests := s.sessionInvalidEncryptedContentDigests(groupID, sessionHash); len(invalidDigests) > 0 { @@ -652,6 +704,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 @@ -825,6 +899,9 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( // publishing it by session hash would leak it to independent bridges. turnState = bridgeTurnState } + if contextWindowBoundary.WindowID != "" { + lastBridgeWindowID = contextWindowBoundary.WindowID + } responseID := strings.TrimSpace(result.RequestID) bridgeLastResponseID = "" if result.UpstreamTerminalEvent == "response.completed" || result.UpstreamTerminalEvent == "response.done" { @@ -1604,6 +1681,40 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( } } skipBeforeTurn = false + boundaryPayload, contextWindowBoundary, boundaryErr := normalizeOpenAIWSContextWindowBoundary( + currentPayload, + lastTurnWindowID, + ) + if boundaryErr != nil { + return fmt.Errorf("normalize Codex websocket context-window boundary: %w", boundaryErr) + } + if contextWindowBoundary.Changed { + if contextWindowBoundary.PreviousResponseIDRemoved { + responsesLite := isOpenAIResponsesLiteWebSocketPayload(boundaryPayload) + if compatBody, compatChanged, compatErr := normalizeOpenAIResponsesWebSocketCompatibilityBodyWithConfig(s.cfg, boundaryPayload, account, responsesLite); compatErr != nil { + return NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", compatErr) + } else if compatChanged { + boundaryPayload = compatBody + } + } + currentPayload = boundaryPayload + currentPayloadBytes = len(boundaryPayload) + lastTurnResponseID = "" + lastTurnPayload = nil + lastTurnStrictState = nil + lastTurnReplayInput = nil + lastTurnReplayInputExists = false + lastTurnReplayInputComplete = false + logOpenAIWSModeInfo( + "ingress_ws_context_window_changed account_id=%d turn=%d conn_id=%s action=break_previous_response_chain previous_window_id=%s current_window_id=%s previous_response_id_removed=%v", + account.ID, + turn, + truncateOpenAIWSLogValue(sessionConnID, openAIWSIDValueMaxLen), + truncateOpenAIWSLogValue(lastTurnWindowID, openAIWSIDValueMaxLen), + truncateOpenAIWSLogValue(contextWindowBoundary.WindowID, openAIWSIDValueMaxLen), + contextWindowBoundary.PreviousResponseIDRemoved, + ) + } // 剥离本会话已知失效的加密项,阻断同一失效密文随历史反复触发上游拒绝。 // 历史序列须同步剥离,否则与已剥离的当前 input 项错位,prefix 复用失配。 if invalidDigests := s.sessionInvalidEncryptedContentDigests(groupID, sessionHash); len(invalidDigests) > 0 { @@ -1618,33 +1729,8 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( lastTurnReplayInput, _ = stripOpenAIInvalidEncryptedContentFromReplayItems(lastTurnReplayInput, invalidDigests) } } - boundaryPayload, contextWindowBoundary, boundaryErr := normalizeOpenAIWSContextWindowBoundary( - currentPayload, - lastTurnWindowID, - ) - if boundaryErr != nil { - return fmt.Errorf("normalize Codex websocket context-window boundary: %w", boundaryErr) - } - if contextWindowBoundary.Changed { - currentPayload = boundaryPayload - currentPayloadBytes = len(boundaryPayload) - logOpenAIWSModeInfo( - "ingress_ws_context_window_changed account_id=%d turn=%d conn_id=%s action=break_previous_response_chain previous_window_id=%s current_window_id=%s previous_response_id_removed=%v", - account.ID, - turn, - truncateOpenAIWSLogValue(sessionConnID, openAIWSIDValueMaxLen), - truncateOpenAIWSLogValue(lastTurnWindowID, openAIWSIDValueMaxLen), - truncateOpenAIWSLogValue(contextWindowBoundary.WindowID, openAIWSIDValueMaxLen), - contextWindowBoundary.PreviousResponseIDRemoved, - ) - } currentPreviousResponseID := openAIWSPayloadStringFromRaw(currentPayload, "previous_response_id") expectedPrev := strings.TrimSpace(lastTurnResponseID) - if contextWindowBoundary.Changed { - // A context-window rollover is a new Responses root. Do not infer a - // continuation anchor from the response produced in the old window. - expectedPrev = "" - } toolSignals := ToolContinuationSignals{ HasFunctionCallOutput: openAIWSRawPayloadHasToolCallOutput(currentPayload), } diff --git a/backend/internal/service/openai_ws_forwarder_ingress_test.go b/backend/internal/service/openai_ws_forwarder_ingress_test.go index 915a4edf24..bca0fc3630 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress_test.go +++ b/backend/internal/service/openai_ws_forwarder_ingress_test.go @@ -1024,6 +1024,22 @@ func TestOpenAIWSRawPayloadHasToolCallOutput(t *testing.T) { payload := []byte(`{"input":[{"type":"input_text","text":"hello"}]}`) require.False(t, openAIWSRawPayloadHasToolCallOutput(payload)) }) + + t.Run("standalone_named_delegation_output_ignored", func(t *testing.T) { + t.Parallel() + payload := []byte(`{"input":[{"type":"function_call_output","name":"create_thread","output":"delegated"}]}`) + require.False(t, openAIWSRawPayloadHasToolCallOutput(payload)) + items := []json.RawMessage{ + json.RawMessage(`{"type":"function_call_output","name":"create_thread","output":"delegated"}`), + } + require.False(t, openAIWSRawItemsHasFunctionCallOutput(items)) + pairedItems := []json.RawMessage{ + json.RawMessage(`{"type":"function_call_output","name":"create_thread","output":"delegated"}`), + json.RawMessage(`{"type":"function_call","call_id":"call_1","name":"exec","arguments":"{}"}`), + json.RawMessage(`{"type":"function_call_output","call_id":"call_1","output":"ok"}`), + } + require.True(t, openAIWSRawItemsHaveToolCallContextForOutputs(pairedItems)) + }) } func TestSetOpenAIWSPayloadInputSequence(t *testing.T) { diff --git a/backend/internal/service/openai_ws_forwarder_payload.go b/backend/internal/service/openai_ws_forwarder_payload.go index fc50bc5515..f563f86c77 100644 --- a/backend/internal/service/openai_ws_forwarder_payload.go +++ b/backend/internal/service/openai_ws_forwarder_payload.go @@ -247,6 +247,32 @@ func setOpenAIWSTurnMetadata(payload map[string]any, turnMetadata string) { } } +func setOpenAIWSWindowIDMetadata(payload map[string]any, windowID string) { + if len(payload) == 0 { + return + } + id := strings.TrimSpace(windowID) + if id == "" { + return + } + switch existing := payload["client_metadata"].(type) { + case map[string]any: + existing["x-codex-window-id"] = id + payload["client_metadata"] = existing + case map[string]string: + next := make(map[string]any, len(existing)+1) + for k, v := range existing { + next[k] = v + } + next["x-codex-window-id"] = id + payload["client_metadata"] = next + default: + payload["client_metadata"] = map[string]any{ + "x-codex-window-id": id, + } + } +} + func (s *OpenAIGatewayService) isOpenAIWSStoreRecoveryAllowed(account *Account) bool { if account != nil && account.IsOpenAIWSAllowStoreRecoveryEnabled() { return true @@ -645,9 +671,18 @@ func openAIWSRawItemsHasPrefix(items []json.RawMessage, prefix []json.RawMessage func openAIWSRawItemsHasFunctionCallOutput(items []json.RawMessage) bool { for _, item := range items { - if isCodexToolCallOutputItemType(gjson.GetBytes(item, "type").String()) { - return true + itemType := gjson.GetBytes(item, "type").String() + if !isCodexToolCallOutputItemType(itemType) { + continue } + if isStandaloneNamedFunctionCallOutput( + itemType, + gjson.GetBytes(item, "call_id").String(), + gjson.GetBytes(item, "name").String(), + ) { + continue + } + return true } return false } @@ -667,6 +702,9 @@ func openAIWSRawItemsHaveToolCallContextForOutputs(items []json.RawMessage) bool contextCallIDs[callID] = struct{}{} } case isCodexToolCallOutputItemType(itemType): + if isStandaloneNamedFunctionCallOutput(itemType, callID, gjson.GetBytes(item, "name").String()) { + continue + } if callID == "" { return false } @@ -729,14 +767,21 @@ func openAIWSRawPayloadHasToolCallOutput(payload []byte) bool { } if input.IsArray() { for _, item := range input.Array() { - if isCodexToolCallOutputItemType(item.Get("type").String()) { - return true + itemType := item.Get("type").String() + if !isCodexToolCallOutputItemType(itemType) { + continue } + if isStandaloneNamedFunctionCallOutput(itemType, item.Get("call_id").String(), item.Get("name").String()) { + continue + } + return true } return false } if input.Type == gjson.JSON { - return isCodexToolCallOutputItemType(input.Get("type").String()) + itemType := input.Get("type").String() + return isCodexToolCallOutputItemType(itemType) && + !isStandaloneNamedFunctionCallOutput(itemType, input.Get("call_id").String(), input.Get("name").String()) } return false } 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) + }) } diff --git a/backend/internal/service/openai_ws_http_bridge_resume_test.go b/backend/internal/service/openai_ws_http_bridge_resume_test.go index b18ac294e4..22e550fce4 100644 --- a/backend/internal/service/openai_ws_http_bridge_resume_test.go +++ b/backend/internal/service/openai_ws_http_bridge_resume_test.go @@ -263,3 +263,172 @@ func TestOpenAIWSHTTPBridgeLaterTurn429RetriesCurrentTurnOnReplacementAccount(t require.Equal(t, scopeCodexAccountIdentityValue(&nextAccount, 0, "thread", "client-thread"), gjson.GetBytes(upstream.bodies[2], "client_metadata.thread_id").String()) require.Empty(t, upstream.requests[2].Header.Get(openAIWSTurnStateHeader)) } + +func TestOpenAIWSHTTPBridgeDelegatedSessionCompactionDoesNotReplayOldWindowHistory(t *testing.T) { + gin.SetMode(gin.TestMode) + + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = false + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + cfg.Gateway.OpenAIWS.Enabled = true + cfg.Gateway.OpenAIWS.OAuthEnabled = true + cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true + cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true + cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3 + cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3 + + 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_first\",\"output\":[{\"id\":\"msg_1\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"first-ok\"}]},{\"id\":\"fc_1\",\"type\":\"function_call\",\"call_id\":\"call_1\",\"name\":\"inspect\",\"arguments\":\"{}\"}],\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n", + )), + }, + { + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader( + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_second\",\"output\":[{\"id\":\"msg_2\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"second-ok\"}]}],\"usage\":{\"input_tokens\":2,\"output_tokens\":1}}}\n\n", + )), + }, + { + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader( + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_third\",\"output\":[{\"id\":\"msg_3\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"third-ok\"}]}],\"usage\":{\"input_tokens\":3,\"output_tokens\":1}}}\n\n", + )), + }, + { + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader( + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_fourth\",\"output\":[{\"id\":\"msg_4\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"fourth-ok\"}]}],\"usage\":{\"input_tokens\":4,\"output_tokens\":1}}}\n\n", + )), + }, + }} + svc := &OpenAIGatewayService{ + cfg: cfg, + httpUpstream: upstream, + cache: &stubGatewayCache{}, + openaiWSResolver: NewOpenAIWSProtocolResolver(cfg), + toolCorrector: NewCodexToolCorrector(), + } + account := &Account{ + ID: 131, Name: "bridge-compaction", Platform: PlatformOpenAI, Type: AccountTypeOAuth, + Status: StatusActive, Schedulable: true, Concurrency: 1, + Extra: map[string]any{"openai_oauth_responses_websockets_v2_mode": OpenAIWSIngressModeHTTPBridge}, + Credentials: map[string]any{"chatgpt_account_id": "account-a", "chatgpt_user_id": "user-a"}, + } + + serverErrCh := make(chan error, 1) + wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := websocket.Accept(w, r, nil) + if err != nil { + serverErrCh <- err + return + } + defer func() { _ = conn.CloseNow() }() + + rec := httptest.NewRecorder() + ginCtx, _ := gin.CreateTestContext(rec) + ginCtx.Request = r.Clone(r.Context()) + readCtx, cancel := context.WithTimeout(r.Context(), 3*time.Second) + _, firstMessage, readErr := conn.Read(readCtx) + cancel() + if readErr != nil { + serverErrCh <- readErr + return + } + serverErrCh <- svc.ProxyResponsesWebSocketFromClient(r.Context(), ginCtx, conn, account, "access-token-a", firstMessage, nil) + })) + defer wsServer.Close() + + dialCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + clientConn, _, err := websocket.Dial(dialCtx, "ws"+strings.TrimPrefix(wsServer.URL, "http"), &websocket.DialOptions{ + HTTPHeader: http.Header{ + openAIWSTurnMetadataHeader: []string{`{"window_id":"window-0"}`}, + }, + }) + cancel() + require.NoError(t, err) + defer func() { _ = clientConn.CloseNow() }() + + // Turn 1: delegated session starts in window-0 with create_thread (no call_id). + writeCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + err = clientConn.Write(writeCtx, websocket.MessageText, []byte(`{"type":"response.create","model":"gpt-5.6-sol","input":[{"type":"function_call_output","name":"create_thread","output":"delegated task"},{"role":"user","content":"first-window-msg"}]}`)) + cancel() + require.NoError(t, err) + + readCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + _, completed1, err := clientConn.Read(readCtx) + cancel() + require.NoError(t, err) + require.Equal(t, "resp_first", gjson.GetBytes(completed1, "response.id").String()) + + // Turn 2: normal tool continuation in window-0. + writeCtx, cancel = context.WithTimeout(context.Background(), 3*time.Second) + err = clientConn.Write(writeCtx, websocket.MessageText, []byte(`{"type":"response.create","model":"gpt-5.6-sol","previous_response_id":"resp_first","input":[{"type":"function_call_output","call_id":"call_1","output":"tool-ok"}]}`)) + cancel() + require.NoError(t, err) + + readCtx, cancel = context.WithTimeout(context.Background(), 3*time.Second) + _, completed2, err := clientConn.Read(readCtx) + cancel() + require.NoError(t, err) + require.Equal(t, "resp_second", gjson.GetBytes(completed2, "response.id").String()) + + // Turn 3: context compaction replaces history, omits previous_response_id, + // retains create_thread (without call_id), and rotates window_id to window-1. + writeCtx, cancel = context.WithTimeout(context.Background(), 3*time.Second) + err = clientConn.Write(writeCtx, websocket.MessageText, []byte(`{"type":"response.create","model":"gpt-5.6-sol","client_metadata":{"x-codex-turn-metadata":"{\"window_id\":\"window-1\"}"},"input":[{"type":"function_call_output","name":"create_thread","output":"delegated task"},{"role":"user","content":"compacted-summary"}]}`)) + cancel() + require.NoError(t, err) + + readCtx, cancel = context.WithTimeout(context.Background(), 3*time.Second) + _, completed3, err := clientConn.Read(readCtx) + cancel() + require.NoError(t, err) + require.Equal(t, "resp_third", gjson.GetBytes(completed3, "response.id").String()) + + // Turn 4: follow-up turn in window-1 omitting client_metadata must stay in window-1 + // and stitch only from Turn 3's compacted root. + writeCtx, cancel = context.WithTimeout(context.Background(), 3*time.Second) + err = clientConn.Write(writeCtx, websocket.MessageText, []byte(`{"type":"response.create","model":"gpt-5.6-sol","previous_response_id":"resp_third","input":[{"role":"user","content":"after-compaction"}]}`)) + cancel() + require.NoError(t, err) + + readCtx, cancel = context.WithTimeout(context.Background(), 3*time.Second) + _, completed4, err := clientConn.Read(readCtx) + cancel() + require.NoError(t, err) + require.Equal(t, "resp_fourth", gjson.GetBytes(completed4, "response.id").String()) + _ = clientConn.Close(websocket.StatusNormalClosure, "done") + + select { + case proxyErr := <-serverErrCh: + require.NoError(t, proxyErr) + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for bridge completion") + } + + require.Len(t, upstream.bodies, 4) + // Turn 2 stitched Turn 1 history + call_1 + tool-ok. + require.Contains(t, string(upstream.bodies[1]), "first-window-msg") + require.Contains(t, string(upstream.bodies[1]), "call_1") + + // Turn 3 (compacted window-1) must NOT replay old window-0 history ("first-window-msg" or "call_1"), + // and must preserve frame-level window-1 instead of overwriting it with handshake window-0. + scopedWindow1 := scopeCodexAccountIdentityValue(account, 0, "window", "window-1") + require.NotContains(t, string(upstream.bodies[2]), "first-window-msg") + require.NotContains(t, string(upstream.bodies[2]), "call_1") + require.Contains(t, string(upstream.bodies[2]), "compacted-summary") + require.Equal(t, scopedWindow1, gjson.Get(gjson.GetBytes(upstream.bodies[2], "client_metadata.x-codex-turn-metadata").String(), "window_id").String()) + + // Turn 4 (continuation in window-1) stitches from Turn 3's compacted history and stays on window-1. + require.NotContains(t, string(upstream.bodies[3]), "first-window-msg") + require.NotContains(t, string(upstream.bodies[3]), "call_1") + require.Contains(t, string(upstream.bodies[3]), "compacted-summary") + require.Contains(t, string(upstream.bodies[3]), "after-compaction") + require.Equal(t, scopedWindow1, gjson.Get(gjson.GetBytes(upstream.bodies[3], "client_metadata.x-codex-turn-metadata").String(), "window_id").String()) +} diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index 1cffe0a6dc..16bcff6b5a 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -660,6 +660,9 @@ func (c *openAIWSClientFrameConn) WriteFrame(ctx context.Context, msgType coderw if c.rewriteModelsETag != nil { payload = c.rewriteModelsETag(payload) } + if rewritten, changed := sanitizeOpenAICapacityShedErrorCodeForClient(payload); changed { + payload = rewritten + } } return c.conn.Write(ctx, msgType, payload) } diff --git a/backend/internal/service/openai_ws_v2_passthrough_lifecycle_test.go b/backend/internal/service/openai_ws_v2_passthrough_lifecycle_test.go index 24afbeda09..ecc0d62e24 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_lifecycle_test.go +++ b/backend/internal/service/openai_ws_v2_passthrough_lifecycle_test.go @@ -902,3 +902,35 @@ func TestPassthroughLifecycle_SecondTurnTimeoutIsNotFailoverSafe(t *testing.T) { t.Fatal("second turn first semantic output was left unbounded") } } + +func TestPassthroughLifecycle_CapacityShedSanitizesErrorCodeAndStripsRetryAfter(t *testing.T) { + gin.SetMode(gin.TestMode) + controlCtx, cancelControl := context.WithCancelCause(context.Background()) + defer cancelControl(context.Canceled) + upstream := newStagedPassthroughConn() + upstream.Send(`{"type":"response.created","response":{"id":"resp_overload","model":"gpt-5.1"}}`) + upstream.Send(`{"type":"error","error":{"code":"server_is_overloaded","headers":{"retry-after":"326","retry-after-ms":"326000"},"message":"Our servers are currently overloaded. Please try again later.","type":"service_unavailable_error"},"sequence_number":3}`) + upstream.Send(`{"type":"response.failed","response":{"id":"resp_overload","model":"gpt-5.1","status":"failed","error":{"code":"server_is_overloaded","headers":{"retry-after":"326","retry-after-ms":"326000"},"message":"Our servers are currently overloaded. Please try again later."}},"sequence_number":4}`) + server, _ := startPassthroughLifecycleServer(t, controlCtx, newPassthroughLifecycleService(passthroughLifecycleConfig(), upstream), passthroughLifecycleAccount()) + defer server.Close() + clientConn := dialPassthroughLifecycleClient(t, server) + defer func() { _ = clientConn.CloseNow() }() + + created, err := readPassthroughLifecycleFrame(t, clientConn, 3*time.Second) + require.NoError(t, err) + require.Equal(t, "response.created", gjson.GetBytes(created, "type").String()) + + errFrame, err := readPassthroughLifecycleFrame(t, clientConn, 3*time.Second) + require.NoError(t, err) + require.Equal(t, "error", gjson.GetBytes(errFrame, "type").String()) + require.Equal(t, "server_error", gjson.GetBytes(errFrame, "error.code").String()) + require.False(t, gjson.GetBytes(errFrame, "error.headers").Exists()) + require.NotContains(t, string(errFrame), "retry-after") + + failedFrame, err := readPassthroughLifecycleFrame(t, clientConn, 3*time.Second) + require.NoError(t, err) + require.Equal(t, "response.failed", gjson.GetBytes(failedFrame, "type").String()) + require.Equal(t, "server_error", gjson.GetBytes(failedFrame, "response.error.code").String()) + require.False(t, gjson.GetBytes(failedFrame, "response.error.headers").Exists()) + require.NotContains(t, string(failedFrame), "retry-after") +} diff --git a/backend/internal/service/payment_fulfillment.go b/backend/internal/service/payment_fulfillment.go index 623ee22723..9b9bb1ddcc 100644 --- a/backend/internal/service/payment_fulfillment.go +++ b/backend/internal/service/payment_fulfillment.go @@ -178,17 +178,13 @@ func expectedNotificationProviderKey(registry *payment.Registry, orderPaymentTyp func (s *PaymentService) toPaid(ctx context.Context, o *dbent.PaymentOrder, tradeNo string, paid float64, pk string) error { previousStatus := o.Status now := time.Now() - grace := now.Add(-paymentGraceMinutes * time.Minute) + // A verified success notification means the money has already moved, so + // an expired order is recovered no matter how long ago it expired, the + // same as a cancelled one. Gateways such as EasyPay keep the hosted + // cashier open after our local expiry, so late payments are normal. c, err := s.entClient.PaymentOrder.Update().Where( paymentorder.IDEQ(o.ID), - paymentorder.Or( - paymentorder.StatusEQ(OrderStatusPending), - paymentorder.StatusEQ(OrderStatusCancelled), - paymentorder.And( - paymentorder.StatusEQ(OrderStatusExpired), - paymentorder.UpdatedAtGTE(grace), - ), - ), + paymentorder.StatusIn(OrderStatusPending, OrderStatusCancelled, OrderStatusExpired), ).SetStatus(OrderStatusPaid).SetPayAmount(paid).SetPaymentTradeNo(tradeNo).SetPaidAt(now).ClearFailedAt().ClearFailedReason().Save(ctx) if err != nil { return fmt.Errorf("update to PAID: %w", err) @@ -224,18 +220,6 @@ func (s *PaymentService) alreadyProcessed(ctx context.Context, o *dbent.PaymentO return nil case OrderStatusFailed, OrderStatusPaid, OrderStatusRecharging: return s.executeFulfillment(ctx, o.ID) - case OrderStatusExpired: - slog.Warn("webhook payment success for expired order beyond grace period", - "orderID", o.ID, - "status", cur.Status, - "updatedAt", cur.UpdatedAt, - ) - s.writeAuditLog(ctx, o.ID, "PAYMENT_AFTER_EXPIRY", "system", map[string]any{ - "status": cur.Status, - "updatedAt": cur.UpdatedAt, - "reason": "payment arrived after expiry grace period", - }) - return nil default: return nil } diff --git a/backend/internal/service/payment_fulfillment_test.go b/backend/internal/service/payment_fulfillment_test.go index 0a7d1b8895..037bb360bc 100644 --- a/backend/internal/service/payment_fulfillment_test.go +++ b/backend/internal/service/payment_fulfillment_test.go @@ -1293,3 +1293,46 @@ func TestExecuteSubscriptionFulfillmentDoesNotDuplicateWorkAfterLegacySuccessAud var _ AffiliateRepository = (*paymentFulfillmentAffiliateRepoStub)(nil) var _ SettingRepository = (*paymentFulfillmentSettingRepoStub)(nil) + +// Reproduces a production incident: the order expired locally, the user then +// paid on EasyPay's still-open cashier, and the verified success callback +// arrived six minutes after expiry. It was dropped and never credited. +func TestPaymentNotificationRecoversOrderPaidLongAfterExpiry(t *testing.T) { + ctx := context.Background() + client := newPaymentConfigServiceTestClient(t) + ensurePaymentAuditOrderActionUniqueIndex(t, ctx, client) + expiredAt := time.Now().Add(-6 * time.Minute) + order := createPaymentFulfillmentSubscriptionOrder(t, ctx, client, OrderStatusExpired, expiredAt) + order, err := client.PaymentOrder.UpdateOneID(order.ID). + SetOrderType(payment.OrderTypeBalance). + ClearPlanID(). + ClearSubscriptionGroupID(). + ClearSubscriptionDays(). + ClearPaidAt(). + SetUpdatedAt(expiredAt). + Save(ctx) + require.NoError(t, err) + + credited := 0.0 + userRepo := &mockUserRepo{getByIDUser: &User{ID: order.UserID, Balance: 0}} + userRepo.updateBalanceFn = func(_ context.Context, _ int64, amount float64) error { + credited += amount + return nil + } + redeemService := NewRedeemService(&paymentFulfillmentRedeemRepo{}, userRepo, nil, &paymentFulfillmentRedeemCacheStub{}, nil, client, nil, nil) + svc := &PaymentService{entClient: client, redeemService: redeemService, userRepo: userRepo} + + err = svc.HandlePaymentNotification(ctx, &payment.PaymentNotification{ + TradeNo: "easypay-late-trade", + OrderID: order.OutTradeNo, + Amount: order.PayAmount, + Status: payment.NotificationStatusSuccess, + }, payment.TypeAlipay) + require.NoError(t, err) + + require.InDelta(t, order.Amount, credited, 1e-8, "a verified payment must be credited however late it arrives") + reloaded, err := client.PaymentOrder.Get(ctx, order.ID) + require.NoError(t, err) + require.Equal(t, OrderStatusCompleted, reloaded.Status) + require.Equal(t, "easypay-late-trade", reloaded.PaymentTradeNo) +} diff --git a/backend/internal/service/payment_order_lifecycle.go b/backend/internal/service/payment_order_lifecycle.go index d534bf7b33..5e7e06e918 100644 --- a/backend/internal/service/payment_order_lifecycle.go +++ b/backend/internal/service/payment_order_lifecycle.go @@ -26,8 +26,17 @@ const ( rateLimitModeFixed = "fixed" checkPaidResultAlreadyPaid = "already_paid" checkPaidResultCancelled = "cancelled" + // checkPaidResultQueryFailed means the upstream status is unknown: the + // order may already be paid, so expiry must not close it yet. + checkPaidResultQueryFailed = "query_failed" pendingPaymentReconcileLimit = 20 + + // paymentExpiryQueryRetryWindow bounds how long the expiry job keeps a + // timed-out order pending while the upstream status query keeps failing. + // After it the order expires anyway; a late success webhook still + // recovers it. + paymentExpiryQueryRetryWindow = time.Hour ) type checkPaidOptions struct { @@ -123,8 +132,13 @@ func (s *PaymentService) AdminCancelOrder(ctx context.Context, orderID int64) (s func (s *PaymentService) cancelCore(ctx context.Context, o *dbent.PaymentOrder, fs, op, ad string) (string, error) { if o.PaymentTradeNo != "" || o.PaymentType != "" { - if s.checkPaid(ctx, o) == checkPaidResultAlreadyPaid { + switch s.checkPaid(ctx, o) { + case checkPaidResultAlreadyPaid: return checkPaidResultAlreadyPaid, nil + case checkPaidResultQueryFailed: + if fs == OrderStatusExpired && time.Since(o.ExpiresAt) < paymentExpiryQueryRetryWindow { + return checkPaidResultQueryFailed, nil + } } } c, err := s.entClient.PaymentOrder.Update().Where(paymentorder.IDEQ(o.ID), paymentorder.StatusEQ(OrderStatusPending)).SetStatus(fs).Save(ctx) @@ -163,7 +177,7 @@ func (s *PaymentService) checkPaidWithOptions(ctx context.Context, o *dbent.Paym finishProviderCall() if err != nil { slog.Warn("query upstream failed", "orderID", o.ID, "error", err) - return "" + return checkPaidResultQueryFailed } if resp.Status == payment.ProviderStatusPaid { if !isValidProviderAmount(resp.Amount) { @@ -391,6 +405,10 @@ func (s *PaymentService) ExpireTimedOutOrders(ctx context.Context) (int, error) slog.Info("order was paid during expiry", "orderID", o.ID) continue } + if outcome == checkPaidResultQueryFailed { + slog.Warn("upstream query failed, keeping order pending for the next expiry run", "orderID", o.ID) + continue + } if outcome != "" { n++ } diff --git a/backend/internal/service/payment_order_lifecycle_test.go b/backend/internal/service/payment_order_lifecycle_test.go index c5a5f2fb9c..b58b7b3021 100644 --- a/backend/internal/service/payment_order_lifecycle_test.go +++ b/backend/internal/service/payment_order_lifecycle_test.go @@ -5,6 +5,7 @@ package service import ( "context" "database/sql" + "errors" "testing" "time" @@ -27,6 +28,7 @@ type paymentOrderLifecycleQueryProvider struct { cancelCalls int responses []*payment.QueryOrderResponse resp *payment.QueryOrderResponse + queryErr error } type paymentOrderLifecycleRedeemRepo struct { @@ -59,6 +61,9 @@ func (p *paymentOrderLifecycleQueryProvider) CreatePayment(context.Context, paym func (p *paymentOrderLifecycleQueryProvider) QueryOrder(_ context.Context, tradeNo string) (*payment.QueryOrderResponse, error) { p.lastQueryTradeNo = tradeNo p.queryCalls++ + if p.queryErr != nil { + return nil, p.queryErr + } if len(p.responses) > 0 { resp := p.responses[0] if len(p.responses) > 1 { @@ -864,3 +869,60 @@ func newPaymentOrderLifecycleTestClient(t *testing.T) *dbent.Client { t.Cleanup(func() { _ = client.Close() }) return client } + +// Reproduces a production incident: the upstream status query failed with +// "connection reset by peer" right at expiry, and the order was expired +// without knowing whether it had been paid. +func TestExpireTimedOutOrdersKeepsOrderPendingWhenUpstreamQueryFails(t *testing.T) { + ctx := context.Background() + client := newPaymentOrderLifecycleTestClient(t) + + user, err := client.User.Create(). + SetEmail("expire-query-failed@example.com"). + SetPasswordHash("hash"). + SetUsername("expire-query-failed-user"). + Save(ctx) + require.NoError(t, err) + + createOrder := func(outTradeNo string, expiresAt time.Time) *dbent.PaymentOrder { + order, err := client.PaymentOrder.Create(). + SetUserID(user.ID). + SetUserEmail(user.Email). + SetUserName(user.Username). + SetAmount(100). + SetPayAmount(100). + SetFeeRate(0). + SetRechargeCode("RC-" + outTradeNo). + SetOutTradeNo(outTradeNo). + SetPaymentType(payment.TypeAlipay). + SetPaymentTradeNo(""). + SetOrderType(payment.OrderTypeBalance). + SetStatus(OrderStatusPending). + SetExpiresAt(expiresAt). + SetClientIP("127.0.0.1"). + SetSrcHost("api.example.com"). + Save(ctx) + require.NoError(t, err) + return order + } + justTimedOut := createOrder("sub2_expire_query_failed_recent", time.Now().Add(-time.Minute)) + longTimedOut := createOrder("sub2_expire_query_failed_old", time.Now().Add(-paymentExpiryQueryRetryWindow-time.Minute)) + + registry := payment.NewRegistry() + provider := &paymentOrderLifecycleQueryProvider{queryErr: errors.New("read: connection reset by peer")} + registry.Register(provider) + svc := &PaymentService{entClient: client, registry: registry, providersLoaded: true} + + expired, err := svc.ExpireTimedOutOrders(ctx) + require.NoError(t, err) + require.Equal(t, 1, expired) + require.Zero(t, provider.cancelCalls, "an order whose upstream status is unknown must not be closed upstream") + + reloaded, err := client.PaymentOrder.Get(ctx, justTimedOut.ID) + require.NoError(t, err) + require.Equal(t, OrderStatusPending, reloaded.Status, "a failed upstream query must not expire the order") + + reloaded, err = client.PaymentOrder.Get(ctx, longTimedOut.ID) + require.NoError(t, err) + require.Equal(t, OrderStatusExpired, reloaded.Status, "after the retry window the order expires anyway") +} diff --git a/backend/internal/service/payment_service.go b/backend/internal/service/payment_service.go index 41276d6251..4d69b1c2b0 100644 --- a/backend/internal/service/payment_service.go +++ b/backend/internal/service/payment_service.go @@ -39,8 +39,6 @@ const ( const ( // defaultMaxPendingOrders and defaultOrderTimeoutMin are defined in // payment_config_service.go alongside other payment configuration defaults. - paymentGraceMinutes = 5 - defaultPageSize = 20 maxPageSize = 100 topUsersLimit = 10 diff --git a/backend/internal/service/pricing_service.go b/backend/internal/service/pricing_service.go index 5aa48c3fa7..f7dc44bb6c 100644 --- a/backend/internal/service/pricing_service.go +++ b/backend/internal/service/pricing_service.go @@ -1786,7 +1786,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"} { diff --git a/frontend/src/components/common/DataTable.vue b/frontend/src/components/common/DataTable.vue index 72c0716b9e..2e910c09ac 100644 --- a/frontend/src/components/common/DataTable.vue +++ b/frontend/src/components/common/DataTable.vue @@ -76,7 +76,7 @@ {{ column.label }} -
+
{{ column.formatter ? column.formatter(row[column.key], row) : row[column.key] }} diff --git a/frontend/src/components/user/PlatformUsageBreakdown.vue b/frontend/src/components/user/PlatformUsageBreakdown.vue index 481c5a8bb1..77c98f5932 100644 --- a/frontend/src/components/user/PlatformUsageBreakdown.vue +++ b/frontend/src/components/user/PlatformUsageBreakdown.vue @@ -1,23 +1,30 @@