diff --git a/backend/internal/handler/failover_loop.go b/backend/internal/handler/failover_loop.go index ebcbd9004991..f4592e35a320 100644 --- a/backend/internal/handler/failover_loop.go +++ b/backend/internal/handler/failover_loop.go @@ -211,7 +211,7 @@ func (s *FailoverState) HandleFailoverError( // 同账号重试不算切换账号,粘性会话仅在实际切换时强制缓存计费。 retryCount := s.SameAccountRetryCount[accountID] sameAccountRetry := sameAccountRetryAllowed(failoverErr, retryCount, retryLimit) - if !sameAccountRetry && failoverErr.RequestScopedTransient && failoverErr.Scope == service.GatewayFailureScopeRequest { + if !sameAccountRetry && failoverErr.SameAccountRetryOnly() { return FailoverExhausted } if needForceCacheBilling(s.hasBoundSession, failoverErr, sameAccountRetry) { diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index 771565d7cd4e..404fd950bce8 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -403,6 +403,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { if failoverErr.RetryableOnSameAccount { retryLimit := effectiveSameAccountRetryLimit(failoverErr, account) if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) { + c.Request = c.Request.WithContext(service.WithOpenAISameAccountRetry(c.Request.Context(), account.ID, failoverErr)) sameAccountRetryCount[account.ID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) reqLog.Warn("openai_chat_completions.pool_mode_same_account_retry", @@ -420,10 +421,11 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { continue } } - if failoverErr.RequestScopedTransient && failoverErr.Scope == service.GatewayFailureScopeRequest { + if failoverErr.SameAccountRetryOnly() { h.handleFailoverExhausted(c, failoverErr, streamStarted) return } + c.Request = c.Request.WithContext(service.WithOpenAISameAccountRetry(c.Request.Context(), 0, nil)) h.gatewayService.RecordOpenAIAccountSwitch() failedAccountIDs[account.ID] = struct{}{} lastFailoverErr = failoverErr diff --git a/backend/internal/handler/openai_encrypted_history_quota_failover_test.go b/backend/internal/handler/openai_encrypted_history_quota_failover_test.go index 409f7304e00d..919ed91a7747 100644 --- a/backend/internal/handler/openai_encrypted_history_quota_failover_test.go +++ b/backend/internal/handler/openai_encrypted_history_quota_failover_test.go @@ -21,9 +21,17 @@ import ( ) func TestEncryptedHistoryQuotaFailoverPreservesContinuation(t *testing.T) { - for _, kind := range []string{service.AccountTypeOAuth, service.AccountTypeAPIKey} { + for _, tc := range []struct{ kind, quotaCode string }{ + {service.AccountTypeOAuth, "usage_limit_reached"}, + {service.AccountTypeOAuth, "insufficient_quota"}, + {service.AccountTypeOAuth, "quota_exceeded"}, + {service.AccountTypeAPIKey, "usage_limit_reached"}, + {service.AccountTypeAPIKey, "insufficient_quota"}, + {service.AccountTypeAPIKey, "quota_exceeded"}, + } { + kind := tc.kind for _, stream := range []bool{false, true} { - t.Run(fmt.Sprintf("%s/stream=%t", kind, stream), func(t *testing.T) { + t.Run(fmt.Sprintf("%s/%s/stream=%t", kind, tc.quotaCode, stream), func(t *testing.T) { clients := issue805Redis(t) var mu sync.Mutex var identities []string @@ -42,7 +50,7 @@ func TestEncryptedHistoryQuotaFailoverPreservesContinuation(t *testing.T) { if attempt > 1 && r.Header.Get("Authorization") == "Bearer fixture-quota-1" { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusTooManyRequests) - _, _ = io.WriteString(w, `{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached","resets_at":4102444800}}`) + _, _ = fmt.Fprintf(w, `{"error":{"type":%q,"code":%q,"message":"The usage limit has been reached"}}`, tc.quotaCode, tc.quotaCode) return } output := "[" + issue715Agent + "]" diff --git a/backend/internal/handler/openai_gateway_credential_failover_loop_test.go b/backend/internal/handler/openai_gateway_credential_failover_loop_test.go index 6451b44ea13c..e342feb0c1f4 100644 --- a/backend/internal/handler/openai_gateway_credential_failover_loop_test.go +++ b/backend/internal/handler/openai_gateway_credential_failover_loop_test.go @@ -7,6 +7,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "io" "net/http" "net/http/httptest" @@ -319,6 +320,7 @@ type grokCredentialHandlerUpstream struct { failAccountID int64 rateLimitIDs map[int64]bool failureStatus map[int64]int + failureBody map[int64]string cancelRequest context.CancelFunc } @@ -334,6 +336,7 @@ func (u *grokCredentialHandlerUpstream) Do(req *http.Request, _ string, accountI failAccountID := u.failAccountID rateLimited := u.rateLimitIDs[accountID] failureStatus := u.failureStatus[accountID] + failureBody := u.failureBody[accountID] cancelRequest := u.cancelRequest u.mu.Unlock() if rateLimited { @@ -347,10 +350,13 @@ func (u *grokCredentialHandlerUpstream) Do(req *http.Request, _ string, accountI }, nil } if failureStatus > 0 { + if failureBody == "" { + failureBody = `{"error":{"message":"upstream unavailable"}}` + } return &http.Response{ StatusCode: failureStatus, Header: http.Header{"Content-Type": []string{"application/json"}}, - Body: io.NopCloser(bytes.NewBufferString(`{"error":{"message":"upstream unavailable"}}`)), + Body: io.NopCloser(bytes.NewBufferString(failureBody)), }, nil } if accountID == failAccountID { @@ -364,6 +370,13 @@ func (u *grokCredentialHandlerUpstream) Do(req *http.Request, _ string, accountI }, nil } if bytes.Contains(requestBody, []byte(`"stream":true`)) { + if strings.Contains(req.URL.Path, "/chat/completions") { + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader("data: {\"id\":\"chatcmpl_healthy\",\"object\":\"chat.completion.chunk\",\"model\":\"grok-4.5\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"ok\"},\"finish_reason\":null}]}\n\ndata: {\"id\":\"chatcmpl_healthy\",\"object\":\"chat.completion.chunk\",\"model\":\"grok-4.5\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n")), + }, nil + } return &http.Response{ StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, @@ -743,6 +756,59 @@ func TestGrokOAuthCredentialFailoverAcrossHTTPHandlers(t *testing.T) { } } +func TestGrokUnknown403ChatHasOneBackup(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, stream := range []bool{false, true} { + for _, scenario := range []string{"backup_success", "backup_failure", "content_rejection", "explicit_cooldown", "pause_enabled"} { + t.Run(fmt.Sprintf("%s/stream=%t", scenario, stream), func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "all_429") + defer cleanup() + upstream.rateLimitIDs = nil + upstream.failureStatus = map[int64]int{801: http.StatusForbidden} + upstream.failureBody = map[int64]string{801: `{"code":"permission-denied","error":"Access to the chat endpoint is denied"}`} + for i := range repo.accounts { + repo.accounts[i].Extra["grok_skip_forbidden_pause"] = scenario != "pause_enabled" + } + if scenario == "backup_failure" { + upstream.failureStatus[802] = http.StatusBadGateway + } + if scenario == "content_rejection" { + upstream.failureBody[801] = `{"error":{"code":"content_policy","message":"request rejected"}}` + } + if scenario == "explicit_cooldown" { + repo.accounts[0].Credentials["temp_unschedulable_enabled"] = true + repo.accounts[0].Credentials["temp_unschedulable_rules"] = []any{map[string]any{ + "error_code": 403, "keywords": []any{"chat endpoint"}, "duration_minutes": 7, + }} + } + recorder := httptest.NewRecorder() + body := fmt.Sprintf(`{"model":"grok","messages":[{"role":"user","content":"hello"}],"stop":["END"],"stream":%t}`, stream) + req := httptest.NewRequest(http.MethodPost, "/openai/v1/chat/completions", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(recorder, req) + if scenario == "content_rejection" { + require.Equal(t, []int64{801}, upstream.accountHits()) + } else { + require.Equal(t, []int64{801, 802}, upstream.accountHits(), "a failed backup must never visit C") + } + if scenario == "backup_success" || scenario == "explicit_cooldown" || scenario == "pause_enabled" { + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Contains(t, recorder.Body.String(), "ok") + } + if scenario == "explicit_cooldown" || scenario == "pause_enabled" { + require.Contains(t, repo.setTempIDs, int64(801)) + } else if scenario == "backup_failure" { + require.Equal(t, []int64{802}, repo.setTempIDs, "only the backup returning 502 receives a cooldown") + require.Empty(t, repo.errorIDs()) + } else { + require.Empty(t, repo.setTempIDs, "request-level refusals must not cool an account") + require.Empty(t, repo.errorIDs()) + } + }) + } + } +} + func TestGrokOAuthMissingSelectedRowRetriesHealthyAccountWithoutMutation(t *testing.T) { gin.SetMode(gin.TestMode) _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "missing_row") diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 1b52840de901..11ed6767b560 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -1399,6 +1399,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { if failoverErr.RetryableOnSameAccount { retryLimit := effectiveSameAccountRetryLimit(failoverErr, account) if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) { + c.Request = c.Request.WithContext(service.WithOpenAISameAccountRetry(c.Request.Context(), account.ID, failoverErr)) sameAccountRetryCount[account.ID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) reqLog.Warn("openai.pool_mode_same_account_retry", @@ -1416,10 +1417,11 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { continue } } - if failoverErr.RequestScopedTransient && failoverErr.Scope == service.GatewayFailureScopeRequest { + if failoverErr.SameAccountRetryOnly() { h.handleFailoverExhausted(c, failoverErr, streamStarted) return } + c.Request = c.Request.WithContext(service.WithOpenAISameAccountRetry(c.Request.Context(), 0, nil)) h.gatewayService.RecordOpenAIAccountSwitch() failedAccountIDs[account.ID] = struct{}{} lastFailoverErr = failoverErr @@ -2042,6 +2044,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { if failoverErr.RetryableOnSameAccount { retryLimit := effectiveSameAccountRetryLimit(failoverErr, account) if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) { + c.Request = c.Request.WithContext(service.WithOpenAISameAccountRetry(c.Request.Context(), account.ID, failoverErr)) sameAccountRetryCount[account.ID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) reqLog.Warn("openai_messages.pool_mode_same_account_retry", @@ -2059,10 +2062,11 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { continue } } - if failoverErr.RequestScopedTransient && failoverErr.Scope == service.GatewayFailureScopeRequest { + if failoverErr.SameAccountRetryOnly() { h.handleAnthropicFailoverExhausted(c, failoverErr, streamStarted) return } + c.Request = c.Request.WithContext(service.WithOpenAISameAccountRetry(c.Request.Context(), 0, nil)) h.gatewayService.RecordOpenAIAccountSwitch() failedAccountIDs[account.ID] = struct{}{} lastFailoverErr = failoverErr @@ -2876,6 +2880,13 @@ func (h *OpenAIGatewayHandler) acquireOpenAIAccountSlot( ctx = service.ContextWithSelectionPriorityRequest(ctx, selection) c.Request = c.Request.WithContext(service.ContextWithSelectionPriorityRequest(c.Request.Context(), selection)) checkLatency := func(release func()) bool { + if !service.OpenAISameAccountRetryAdmissible(ctx, selection.Account.ID) { + if release != nil { + release() + } + writeError(http.StatusServiceUnavailable, "api_error", "", "Same-account retry is no longer available") + return false + } if denied := h.gatewayService.CheckPriorityLatencySelection(ctx, selection); denied != nil { if release != nil { release() @@ -3461,6 +3472,8 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { if !sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) { return false } + ctx = service.WithOpenAISameAccountRetry(ctx, account.ID, failoverErr) + c.Request = c.Request.WithContext(ctx) sameAccountRetryCount[account.ID]++ retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID]) reqLog.Warn("openai.websocket.same_account_retry", @@ -3473,7 +3486,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { case <-ctx.Done(): return false case <-time.After(retryDelay): - return service.OpenAIWSIngressCanFailover(ctx, c) + return service.OpenAISameAccountRetryAdmissible(ctx, account.ID) && service.OpenAIWSIngressCanFailover(ctx, c) } } handleWSFailover := func(account *service.Account, failoverErr *service.UpstreamFailoverError) bool { @@ -3498,10 +3511,12 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { if ctx.Err() != nil { return false } - if failoverErr.RequestScopedTransient && failoverErr.Scope == service.GatewayFailureScopeRequest { + if failoverErr.SameAccountRetryOnly() { closeOpenAIWSFailoverExhausted(c, wsConn, failoverErr) return false } + ctx = service.WithOpenAISameAccountRetry(ctx, 0, nil) + c.Request = c.Request.WithContext(ctx) h.gatewayService.RecordOpenAIAccountSwitch() failedAccountIDs[account.ID] = struct{}{} lastFailoverErr = failoverErr @@ -4385,6 +4400,11 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { currentAccountRelease = accountRelease } wsFirstMessage = wsAttemptMessage + if !service.OpenAISameAccountRetryAdmissible(ctx, account.ID) { + releaseTurnSlots() + closeOpenAIWSFailoverExhausted(c, wsConn, failoverErr) + return + } continue } if handleWSFailover(account, failoverErr) { diff --git a/backend/internal/handler/openai_responses_failover_cancel_test.go b/backend/internal/handler/openai_responses_failover_cancel_test.go index de3fddd6c7f4..5fba37af45b0 100644 --- a/backend/internal/handler/openai_responses_failover_cancel_test.go +++ b/backend/internal/handler/openai_responses_failover_cancel_test.go @@ -65,6 +65,10 @@ func newOpenAIResponsesFailoverTestHandlerWithSettings(t *testing.T, upstream se } func newOpenAIResponsesFailoverTestHandlerWithUsage(t *testing.T, upstream service.HTTPUpstream, cache service.GatewayCache, settings *service.SettingService, usage service.UsageLogRepository, fixtureAccounts ...service.Account) *OpenAIGatewayHandler { + return newOpenAIResponsesFailoverTestHandlerWithConcurrency(t, upstream, cache, settings, usage, nil, fixtureAccounts...) +} + +func newOpenAIResponsesFailoverTestHandlerWithConcurrency(t *testing.T, upstream service.HTTPUpstream, cache service.GatewayCache, settings *service.SettingService, usage service.UsageLogRepository, concurrency *service.ConcurrencyService, fixtureAccounts ...service.Account) *OpenAIGatewayHandler { t.Helper() accounts := []service.Account{ { @@ -110,7 +114,7 @@ func newOpenAIResponsesFailoverTestHandlerWithUsage(t *testing.T, upstream servi cache, cfg, nil, - nil, + concurrency, service.NewBillingService(cfg, nil), nil, nil, @@ -126,7 +130,10 @@ func newOpenAIResponsesFailoverTestHandlerWithUsage(t *testing.T, upstream servi ) billingService := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) t.Cleanup(billingService.Stop) - concurrencyService := service.NewConcurrencyService(nil) + concurrencyService := concurrency + if concurrencyService == nil { + concurrencyService = service.NewConcurrencyService(nil) + } handler := NewOpenAIGatewayHandler( gatewayService, concurrencyService, diff --git a/backend/internal/handler/openai_retry_owner_test.go b/backend/internal/handler/openai_retry_owner_test.go new file mode 100644 index 000000000000..d71a22d50c18 --- /dev/null +++ b/backend/internal/handler/openai_retry_owner_test.go @@ -0,0 +1,215 @@ +//go:build unit + +package handler + +import ( + "context" + "fmt" + "io" + "net/http" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +type retryOwnerBindings struct { + service.GatewayCache + owners map[string]int64 +} + +func (b *retryOwnerBindings) GetSessionAccountID(_ context.Context, _ int64, key string) (int64, error) { + if owner := b.owners[key]; owner > 0 { + return owner, nil + } + return 0, service.ErrStickySessionNotFound +} + +func (b *retryOwnerBindings) SetSessionAccountID(_ context.Context, _ int64, key string, owner int64, _ time.Duration) error { + b.owners[key] = owner + return nil +} + +func (b *retryOwnerBindings) RefreshSessionTTL(context.Context, int64, string, time.Duration) error { + return nil +} + +func (b *retryOwnerBindings) DeleteSessionAccountID(_ context.Context, _ int64, key string) error { + delete(b.owners, key) + return nil +} + +// The first attempt releases its real ConcurrencyService slot before another +// request occupies A. A barrier exposes the busy state to retry selection. +type retryOwnerSlots struct { + concurrencyCacheMock + mu sync.Mutex + released []int64 + acquired []int64 + busy bool + busySeen chan struct{} + busyOnce sync.Once +} + +func (s *retryOwnerSlots) AcquireAccountSlot(_ context.Context, id int64, _ int, _ string) (bool, error) { + s.mu.Lock() + busy := id == 1 && s.busy + if !busy { + s.acquired = append(s.acquired, id) + } + s.mu.Unlock() + if busy { + s.busyOnce.Do(func() { close(s.busySeen) }) + } + return !busy, nil +} + +func (s *retryOwnerSlots) ReleaseAccountSlot(_ context.Context, id int64, _ string) error { + s.mu.Lock() + defer s.mu.Unlock() + s.released = append(s.released, id) + if len(s.released) == 1 { + s.busy = true + } + return nil +} + +type retryOwnerUpstream struct { + service.HTTPUpstream + mu sync.Mutex + ids []int64 + exhaust bool + quota string +} + +func (u *retryOwnerUpstream) Do(req *http.Request, _ string, id int64, _ int) (*http.Response, error) { + u.mu.Lock() + u.ids = append(u.ids, id) + first := len(u.ids) == 1 + fail := first || u.exhaust + u.mu.Unlock() + if first && u.quota != "" { + frame := fmt.Sprintf("data: {\"type\":\"response.failed\",\"response\":{\"id\":\"resp_quota\",\"status\":\"failed\",\"error\":{\"code\":%q,\"type\":%q,\"message\":\"Quota exhausted\"}}}\n\n", u.quota, u.quota) + return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(frame))}, nil + } + if fail { + return &http.Response{StatusCode: 503, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"type":"server_error","message":"temporarily unavailable"}}`))}, nil + } + body, _ := io.ReadAll(req.Body) + response := `{"id":"resp_retry","object":"response","status":"completed","model":"gpt-5.1","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":1,"output_tokens":1}}` + contentType := "application/json" + if gjson.GetBytes(body, "stream").Bool() { + contentType = "text/event-stream" + response = "data: {\"type\":\"response.output_text.delta\",\"output_index\":0,\"content_index\":0,\"delta\":\"ok\"}\n\ndata: {\"type\":\"response.completed\",\"response\":" + response + "}\n\ndata: [DONE]\n\n" + } + return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{contentType}}, Body: io.NopCloser(strings.NewReader(response))}, nil +} + +func TestSSEQuotaWithoutResetUsesBoundedAccountFailover(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, kind := range []string{service.AccountTypeOAuth, service.AccountTypeAPIKey} { + for _, code := range []string{"insufficient_quota", "quota_exceeded", "usage_limit_reached"} { + for _, passthrough := range []bool{false, true} { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/%s/passthrough=%t/stream=%t", kind, code, passthrough, stream), func(t *testing.T) { + accounts := issue715Accounts() + for i := range accounts { + accounts[i].Type = kind + accounts[i].Credentials["api_key"] = "fixture-key" + accounts[i].Credentials["pool_mode"] = true + accounts[i].Extra = map[string]any{"openai_passthrough": passthrough} + } + upstream := &retryOwnerUpstream{quota: code} + h := newOpenAIResponsesFailoverTestHandler(t, upstream, accounts...) + c, rec := newOpenAIResponsesFailoverTestContext(t, nil) + body := fmt.Sprintf(`{"model":"gpt-5.1","input":"hello","stream":%t}`, stream) + c.Request.Body = io.NopCloser(strings.NewReader(body)) + c.Request.ContentLength = int64(len(body)) + h.Responses(c) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.Equal(t, []int64{1, 2}, upstream.ids, "semantic quota must not retry A within the transient window") + require.Contains(t, rec.Body.String(), "ok") + }) + } + } + } + } +} + +func TestOAuthRetryOwnerBusyAfterSlotRelease(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, scenario := range []string{"busy_timeout", "recovered", "exhausted", "canceled"} { + for _, maxSwitches := range []int{0, 2} { + t.Run(fmt.Sprintf("%s/switches=%d", scenario, maxSwitches), func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + slots := &retryOwnerSlots{busySeen: make(chan struct{})} + bindings := &retryOwnerBindings{owners: map[string]int64{}} + upstream := &retryOwnerUpstream{exhaust: scenario == "exhausted"} + accounts := issue715Accounts() + for i := range accounts { + accounts[i].Concurrency = 1 + accounts[i].Priority = i * 1000 + } + h := newOpenAIResponsesFailoverTestHandlerWithConcurrency(t, upstream, bindings, nil, nil, service.NewConcurrencyService(slots), accounts...) + h.maxAccountSwitches = maxSwitches + h.cfg.Gateway.OpenAIScheduler.StickyEscapeEnabled = true + h.cfg.Gateway.Scheduling.StickySessionWaitTimeout = 500 * time.Millisecond + h.cfg.Gateway.OpenAIWS.LBTopK = 1 + workerDone := make(chan struct{}) + if scenario != "busy_timeout" { + go func() { + defer close(workerDone) + select { + case <-ctx.Done(): + return + case <-slots.busySeen: + } + if scenario == "canceled" { + cancel() + } else { + slots.mu.Lock() + slots.busy = false + slots.mu.Unlock() + } + }() + } else { + close(workerDone) + } + c, rec := newOpenAIResponsesFailoverTestContext(t, ctx) + body := `{"model":"gpt-5.1","input":"hello","stream":false,"prompt_cache_key":"retry-owner"}` + c.Request.Body = io.NopCloser(strings.NewReader(body)) + c.Request.ContentLength = int64(len(body)) + h.Responses(c) + select { + case <-slots.busySeen: + default: + t.Fatal("retry never observed the released owner's occupied slot") + } + <-workerDone + want := []int64{1} + if scenario == "recovered" { + want = []int64{1, 1} + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + } else if scenario == "exhausted" { + want = []int64{1, 1, 1, 1} + require.Equal(t, http.StatusBadGateway, rec.Code, rec.Body.String()) + } + require.Equal(t, want, upstream.ids, "B must receive zero sends, including with no switch budget") + slots.mu.Lock() + acquired := append([]int64(nil), slots.acquired...) + released := append([]int64(nil), slots.released...) + slots.mu.Unlock() + require.Equal(t, acquired, released, "every actual attempt releases its slot") + session := h.gatewayService.GenerateSessionHash(c, []byte(body)) + require.NotEmpty(t, session) + require.Equal(t, int64(1), bindings.owners["openai:"+session], "the session binding must still belong to A") + }) + } + } +} diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 4bbdc0ad7f4e..8e29f5bd5abd 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -837,6 +837,12 @@ func (e *UpstreamFailoverError) ShouldRetryNextAccount() bool { return e != nil && e.NextAccountAction != NextAccountStop } +// SameAccountRetryOnly separates retry affinity from account-health scope. +// An ambiguous Grok 403 is request-scoped too, but has its own one-backup budget. +func (e *UpstreamFailoverError) SameAccountRetryOnly() bool { + return e != nil && e.RequestScopedTransient && e.Scope == GatewayFailureScopeRequest && e.Reason != GrokUnknownForbiddenReason +} + func (e *UpstreamFailoverError) IsCredentialFailure() bool { return e != nil && e.Stage == GatewayFailureStageAccountAuth } diff --git a/backend/internal/service/openai_account_runtime_block_fastpath.go b/backend/internal/service/openai_account_runtime_block_fastpath.go index 733b439d319f..cab30ad3fb89 100644 --- a/backend/internal/service/openai_account_runtime_block_fastpath.go +++ b/backend/internal/service/openai_account_runtime_block_fastpath.go @@ -7,6 +7,8 @@ import ( "strings" "sync" "time" + + "github.com/tidwall/gjson" ) const ( @@ -35,10 +37,25 @@ const ( openAIOAuth429Quota5h openAIOAuth429Quota7d openAIOAuth429QuotaReset + openAIOAuth429QuotaExhausted ) -// classifyOpenAIOAuth429 区分账号配额耗尽信号与普通瞬时 429。只有窗口达到 -// 100% 或响应体明确给出 reset 时间时,才视为配额限流信号。 +// isOpenAIQuotaExhaustedResponse recognizes explicit quota codes even when the +// provider omits a reset time. Use the same evidence for retry and replay proof. +func isOpenAIQuotaExhaustedResponse(body []byte) bool { + if !openAIEncryptedJSONUnambiguous(body) { + return false + } + for _, path := range []string{"error.type", "error.code", "response.error.type", "response.error.code"} { + switch gjson.GetBytes(body, path).String() { + case "usage_limit_reached", "insufficient_quota", "quota_exceeded": + return true + } + } + return false +} + +// classifyOpenAIOAuth429 distinguishes exhausted quota from transient throttling. func classifyOpenAIOAuth429(headers http.Header, responseBody []byte) (openAIOAuth429Disposition, *time.Time) { if snapshot := ParseCodexRateLimitHeaders(headers); snapshot != nil { if normalized := snapshot.Normalize(); normalized != nil { @@ -67,6 +84,9 @@ func classifyOpenAIOAuth429(headers http.Header, responseBody []byte) (openAIOAu resetAt := time.Unix(*resetUnix, 0) return openAIOAuth429QuotaReset, &resetAt } + if isOpenAIQuotaExhaustedResponse(responseBody) { + return openAIOAuth429QuotaExhausted, nil + } return openAIOAuth429Transient, nil } @@ -106,6 +126,9 @@ func (s *OpenAIGatewayService) handleOpenAIAccountUpstreamError(ctx context.Cont // Apply the same exemption before access-state and custom cooldown fast // paths, which can otherwise block the credential before the shared handler. if isOpenAIRequestScoped403(account, statusCode, responseBody) || isOpenAIWrappedConcurrency401(account, statusCode, responseBody) { + if s != nil && s.rateLimitService != nil { + s.rateLimitService.resetOpenAIIPUnauthorizedStreak(account) + } return false } // Capacity shedding describes this request, not account health. Keep the diff --git a/backend/internal/service/openai_account_runtime_block_fastpath_test.go b/backend/internal/service/openai_account_runtime_block_fastpath_test.go index dc966253d14f..d08d39bf518e 100644 --- a/backend/internal/service/openai_account_runtime_block_fastpath_test.go +++ b/backend/internal/service/openai_account_runtime_block_fastpath_test.go @@ -22,6 +22,25 @@ type oauth429RateLimitRepo struct { lastModelRateLimitedUntil time.Time } +func TestExplicitQuotaWithoutResetCoolsInsteadOfRetrying(t *testing.T) { + for _, code := range []string{"insufficient_quota", "quota_exceeded", "usage_limit_reached"} { + t.Run(code, func(t *testing.T) { + repo := &oauth429RateLimitRepo{} + rateLimits := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + svc := &OpenAIGatewayService{rateLimitService: rateLimits} + rateLimits.SetAccountRuntimeBlocker(svc) + account := &Account{ID: 42, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + body := []byte(`{"error":{"type":"` + code + `"}}`) + svc.handleOpenAIAccountUpstreamError(context.Background(), account, 429, nil, body) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + require.Equal(t, 1, repo.setRateLimitedCalls) + require.False(t, svc.ShouldRetryOpenAIOAuth429(account, nil, body)) + _, started := svc.openaiOAuth429RetryStartedAt.Load(account.ID) + require.False(t, started) + }) + } +} + func (r *oauth429RateLimitRepo) SetRateLimited(_ context.Context, _ int64, until time.Time) error { r.setRateLimitedCalls++ r.lastRateLimitedUntil = until diff --git a/backend/internal/service/openai_account_scheduler.go b/backend/internal/service/openai_account_scheduler.go index ab3cee1a8129..e5f4ed1514be 100644 --- a/backend/internal/service/openai_account_scheduler.go +++ b/backend/internal/service/openai_account_scheduler.go @@ -560,7 +560,7 @@ func (s *defaultOpenAIAccountScheduler) Select( if err := s.checkOpenAIAgentRecoveryCooldown(ctx, req, recovery); err != nil { return nil, decision, err } - if req.StrictSessionAffinity { + if req.StrictSessionAffinity && openAISameAccountRetryFromContext(ctx).accountID <= 0 { return s.selectStrictSessionAccount(ctx, req) } @@ -576,6 +576,59 @@ func (s *defaultOpenAIAccountScheduler) Select( req = prepared } + if retry := openAISameAccountRetryFromContext(ctx); retry.accountID > 0 { + unavailable := fmt.Errorf("%w: same-account retry owner unavailable", ErrNoAvailableAccounts) + if !OpenAISameAccountRetryAdmissible(ctx, retry.accountID) || + (recovery.ownerBindingRequired() && recovery.owner.accountID != retry.accountID) || + (pointerOwner > 0 && pointerOwner != retry.accountID) || + (req.GuardianParentAccountID > 0 && req.GuardianParentAccountID != retry.accountID) { + return nil, decision, unavailable + } + if previous := strings.TrimSpace(req.PreviousResponseID); previous != "" { + owner, readErr := s.service.getOpenAIWSStateStore().GetResponseAccount(ctx, derefGroupID(req.GroupID), previous) + if readErr != nil || owner != retry.accountID { + return nil, decision, unavailable + } + } + // Retry affinity is an owner constraint, independent of weighted sticky, + // priority rebalancing and capacity escape. Reuse all normal admission + // checks and the bounded owner WaitPlan; never fall through to the pool. + if req.StrictSessionAffinity { + snapshot := openAIStickyBindingSnapshotFromContext(ctx, req.GroupID, req.SessionHash) + if snapshot == nil || !snapshot.known || snapshot.accountID != retry.accountID || req.StickyAccountID != retry.accountID { + return nil, decision, strictSessionUnavailable("retry owner no longer holds the session") + } + selection, decision, err = s.selectStrictSessionAccount(ctx, req) + } else { + req.StickyAccountID = retry.accountID + req.StickyWeighted = false + req.PreserveStickyBinding = true + req.DisableStickyEscape = true + req.StrictSessionAffinity = true + selection, _, err = s.selectBySessionHash(ctx, req) + } + if err != nil { + return nil, decision, err + } + if selection == nil || selection.Account == nil { + return nil, decision, unavailable + } + if selection.WaitPlan != nil && !retry.deadline.IsZero() { + remaining := time.Until(retry.deadline) + if remaining <= 0 { + return nil, decision, unavailable + } + if selection.WaitPlan.Timeout <= 0 || remaining < selection.WaitPlan.Timeout { + selection.WaitPlan.Timeout = remaining + } + } + decision.Layer = openAIAccountScheduleLayerSessionSticky + decision.StickySessionHit = true + decision.SelectedAccountID = selection.Account.ID + decision.SelectedAccountType = selection.Account.Type + return selection, decision, nil + } + previousResponseID := strings.TrimSpace(req.PreviousResponseID) // Even a nominally movable provider continuation must not be reassigned just // because its owner is stopped. Resolve ownership without acquiring a slot. @@ -796,7 +849,7 @@ func (s *defaultOpenAIAccountScheduler) selectBySessionHash( req OpenAIAccountScheduleRequest, ) (*AccountSelectionResult, bool, error) { sessionHash := strings.TrimSpace(req.SessionHash) - if sessionHash == "" || s == nil || s.service == nil || (s.service.cache == nil && req.StickyAccountID <= 0) { + if (sessionHash == "" && openAISameAccountRetryFromContext(ctx).accountID <= 0) || s == nil || s.service == nil || (s.service.cache == nil && req.StickyAccountID <= 0) { return nil, false, nil } @@ -2947,7 +3000,7 @@ func (s *OpenAIGatewayService) selectAccountWithSchedulerOnce( stickyAccountID, stickyReadErr = s.getStickySessionAccountID(ctx, groupID, sessionHash) } ctx = withOpenAIStickyBindingSnapshot(ctx, groupID, sessionHash, stickyAccountID, stickyReadErr == nil || errors.Is(stickyReadErr, ErrStickySessionNotFound)) - scheduler := s.getOpenAIAccountScheduler(ctx, platform == PlatformQwen || s.strictOpenAISessionAffinity(groupID, platform, requiredImageCapability) || openAIAgentRecoveryBound(ctx) || (platform == PlatformOpenAI && requiredImageCapability == "" && useUpstreamTokenCost && priorityApplies(priority, OpenAIAccountScheduleRequest{GroupID: groupID, RequestedModel: requestedModel, HistoryModel: observation.model}))) + scheduler := s.getOpenAIAccountScheduler(ctx, openAISameAccountRetryFromContext(ctx).accountID > 0 || platform == PlatformQwen || s.strictOpenAISessionAffinity(groupID, platform, requiredImageCapability) || openAIAgentRecoveryBound(ctx) || (platform == PlatformOpenAI && requiredImageCapability == "" && useUpstreamTokenCost && priorityApplies(priority, OpenAIAccountScheduleRequest{GroupID: groupID, RequestedModel: requestedModel, HistoryModel: observation.model}))) if scheduler == nil { decision.Layer = openAIAccountScheduleLayerLoadBalance if selection, hit, err := s.selectLegacyAccountByPreviousResponse(ctx, groupID, previousResponseID, sessionHash, requestedModel, excludedIDs, requiredTransport, requiredCapability, requiredImageCapability, requireCompact, platform); err != nil { diff --git a/backend/internal/service/openai_agent_message_recovery.go b/backend/internal/service/openai_agent_message_recovery.go index 7667b3c6aa0d..05c58b85b6bd 100644 --- a/backend/internal/service/openai_agent_message_recovery.go +++ b/backend/internal/service/openai_agent_message_recovery.go @@ -734,16 +734,7 @@ func openAIAgentQuotaFailoverAllowed(ctx context.Context, status int, body []byt request.omittedHistory || request.omitted400History || status != http.StatusTooManyRequests { return false } - if !openAIEncryptedJSONUnambiguous(body) { - return false - } - for _, path := range []string{"error.type", "error.code", "response.error.type", "response.error.code"} { - switch gjson.GetBytes(body, path).String() { - case "usage_limit_reached", "insufficient_quota", "quota_exceeded": - return true - } - } - return false + return isOpenAIQuotaExhaustedResponse(body) } func OpenAIAgentRecoveryNoReplay(ctx context.Context) bool { diff --git a/backend/internal/service/openai_agent_quota_failover_test.go b/backend/internal/service/openai_agent_quota_failover_test.go index 3b4ceac84c61..42414b2c1918 100644 --- a/backend/internal/service/openai_agent_quota_failover_test.go +++ b/backend/internal/service/openai_agent_quota_failover_test.go @@ -5,12 +5,70 @@ package service import ( "context" "encoding/json" + "io" + "net/http" + "strings" "testing" "time" "github.com/stretchr/testify/require" ) +func TestExplicitQuotaWithoutResetSkipsTransientRetryWindow(t *testing.T) { + for _, code := range []string{"insufficient_quota", "quota_exceeded", "usage_limit_reached", "rate_limit_exceeded"} { + t.Run(code, func(t *testing.T) { + body := []byte(`{"error":{"code":"` + code + `"}}`) + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + svc := &OpenAIGatewayService{} + disposition, reset := classifyOpenAIOAuth429(nil, body) + require.Nil(t, reset) + transient := code == "rate_limit_exceeded" + require.Equal(t, transient, disposition == openAIOAuth429Transient) + require.Equal(t, transient, svc.ShouldRetryOpenAIOAuth429(account, nil, body)) + failure := svc.newOpenAIHTTPAccountFailoverError(account, 429, nil, body, "", false, true) + require.Equal(t, transient, failure.RetryableOnSameAccount, "pool retry must not override explicit quota") + require.Equal(t, transient, !failure.SameAccountRetryDeadline.IsZero()) + _, started := svc.openaiOAuth429RetryStartedAt.Load(account.ID) + require.Equal(t, transient, started, "quota must not open a two-minute retry window") + }) + } +} + +type quotaBodyErrorReader struct { + io.Reader +} + +func (r quotaBodyErrorReader) Read(p []byte) (int, error) { + n, err := r.Reader.Read(p) + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + return n, err +} + +func TestQuotaHTTPBodyIntegrity(t *testing.T) { + quota := `{"error":{"code":"insufficient_quota"}}` + limit := int(openAIUpstreamErrorBodyReadLimit) + for _, tc := range []struct { + name string + reader io.Reader + complete bool + }{ + {"complete", strings.NewReader(quota), true}, + {"complete_json_then_read_error", quotaBodyErrorReader{strings.NewReader(quota)}, false}, + {"exact_limit", strings.NewReader(quota + strings.Repeat(" ", limit-len(quota))), true}, + {"tail_after_limit", strings.NewReader(quota + strings.Repeat(" ", limit-len(quota)) + "x"), false}, + } { + t.Run(tc.name, func(t *testing.T) { + svc := &OpenAIGatewayService{} + body, complete := svc.readUpstreamErrorBodyWithIntegrity(&http.Response{Body: io.NopCloser(tc.reader)}) + require.Equal(t, tc.complete, complete) + require.LessOrEqual(t, len(body), limit) + require.True(t, isOpenAIQuotaExhaustedResponse(body), "a valid JSON prefix alone cannot establish completeness") + }) + } +} + func TestAgentQuotaFailoverRetainsOtherReplayRestrictions(t *testing.T) { quota := []byte(`{"error":{"type":"usage_limit_reached","resets_at":4102444800}}`) for _, tc := range []struct { diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 6cd425d7e61e..5f28debd0e6f 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -1543,7 +1543,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco // Handle error response if resp.StatusCode >= 400 { - respBody := s.readUpstreamErrorBody(resp) + respBody, errorBodyComplete := s.readUpstreamErrorBodyWithIntegrity(resp) _ = resp.Body.Close() resp.Body = io.NopCloser(bytes.NewReader(respBody)) @@ -1586,7 +1586,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco // text. Do not borrow field/compact/failover retry budgets here. return s.handleErrorResponse(ctx, resp, c, account, body, resolveOpenAIErrorSchedulingModel(billingModel, upstreamModel)) } - quotaRejected := openAIAgentQuotaFailoverAllowed(ctx, resp.StatusCode, respBody) + quotaRejected := errorBodyComplete && openAIAgentQuotaFailoverAllowed(ctx, resp.StatusCode, respBody) if openAIAgentRecoveryPreservesHistory(ctx) && !quotaRejected { return s.handleErrorResponse(ctx, resp, c, account, body, resolveOpenAIErrorSchedulingModel(billingModel, upstreamModel)) } diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index b2e8a8d937bd..4b81769abdf3 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -895,6 +895,9 @@ func stripOpenAILegacyResponsesBeta(headers http.Header) { } func shouldFailoverOpenAIPassthroughResponse(account *Account, statusCode int, responseBody []byte) bool { + if isOpenAIUpstreamSessionBlocked(responseBody) { + return false + } if isSIWCEligibilityRejection(account, statusCode, responseBody) { return false } @@ -1603,6 +1606,11 @@ func openAIStreamFailedEventSemanticStatus(payload []byte, message string) int { } } switch { + // Bare errors can precede a successful terminal. Only a terminal refusal + // with a recognized provider code grants the new quota failover behavior. + case gjson.GetBytes(payload, "type").String() == "response.failed" && + (code == "usage_limit_reached" || code == "insufficient_quota" || code == "quota_exceeded"): + return http.StatusTooManyRequests case strings.Contains(combined, "rate_limit"): return http.StatusTooManyRequests case strings.Contains(errType, "invalid_request"): @@ -2054,7 +2062,8 @@ func (s *OpenAIGatewayService) newOpenAIStreamFailoverErrorWithModel( // A nil frame with this message is generated locally on a pre-output disconnect. // Generic provider SSE errors also map to 502; that alone does not identify a disconnect. if !shouldDisable && usesOpenAIOAuthRetryAffinity(account) && failoverErr.Scope == "" && - ((len(payload) == 0 && strings.HasPrefix(message, "OpenAI stream disconnected before completion")) || + ((len(payload) == 0 && (strings.HasPrefix(message, "OpenAI stream disconnected before completion") || + message == "OpenAI stream ended before a terminal event")) || (statusCode == http.StatusServiceUnavailable && failoverErr.RequestScopedTransient)) { failoverErr.preserveOpenAIOAuthBinding() } diff --git a/backend/internal/service/openai_gateway_upstream_errors.go b/backend/internal/service/openai_gateway_upstream_errors.go index b4a59db10e7c..82ac1face7d1 100644 --- a/backend/internal/service/openai_gateway_upstream_errors.go +++ b/backend/internal/service/openai_gateway_upstream_errors.go @@ -533,6 +533,10 @@ func (s *OpenAIGatewayService) newOpenAIAccountFailoverErrorWithClassificationHe upstreamMsg, retryableOnSameAccount || oauth429Retry, ) + if statusCode == http.StatusTooManyRequests && isOpenAIQuotaExhaustedResponse(responseBody) { + // Exhausted quota cannot recover within a pool-mode retry budget either. + failoverErr.RetryableOnSameAccount = false + } if shouldDisable && account != nil && account.Platform == PlatformOpenAI && failoverErr.RequestScopedTransient { // A configured model cooldown takes precedence over capacity-shed replay. failoverErr.RetryableOnSameAccount = false @@ -642,15 +646,27 @@ func openAIUpstreamErrorBodyReadLimitForConfig(cfg *config.Config) int64 { } func (s *OpenAIGatewayService) readUpstreamErrorBody(resp *http.Response) []byte { + body, _ := s.readUpstreamErrorBodyWithIntegrity(resp) + return body +} + +// A syntactically complete prefix is not proof of a complete HTTP rejection. +// Keep bounded diagnostics, but grant replay proof only after an error-free EOF. +func (s *OpenAIGatewayService) readUpstreamErrorBodyWithIntegrity(resp *http.Response) ([]byte, bool) { if resp == nil || resp.Body == nil { - return nil + return nil, false } cfg := (*config.Config)(nil) if s != nil { cfg = s.cfg } - body, _ := io.ReadAll(io.LimitReader(resp.Body, openAIUpstreamErrorBodyReadLimitForConfig(cfg))) - return body + limit := openAIUpstreamErrorBodyReadLimitForConfig(cfg) + body, err := io.ReadAll(io.LimitReader(resp.Body, limit+1)) + complete := err == nil && int64(len(body)) <= limit + if int64(len(body)) > limit { + body = body[:limit] + } + return body, complete } // opsUpstreamErrorDetail returns the trimmed upstream error body for an ops diff --git a/backend/internal/service/openai_ip_unauthorized_streak_test.go b/backend/internal/service/openai_ip_unauthorized_streak_test.go index 574073b06bc5..e5cd9ed24d2d 100644 --- a/backend/internal/service/openai_ip_unauthorized_streak_test.go +++ b/backend/internal/service/openai_ip_unauthorized_streak_test.go @@ -205,6 +205,7 @@ func TestOpenAIIPUnauthorizedGatewayEarlyReturnsBreakStreak(t *testing.T) { {"ordinary_400_control", 400, "{\"error\":{\"message\":\"Invalid parameter\"}}"}, {"context_window_400", 400, "{\"error\":{\"code\":\"context_length_exceeded\",\"message\":\"maximum context length exceeded\"}}"}, {"capacity_shed_503", 503, "{\"error\":{\"code\":\"server_is_overloaded\",\"message\":\"The server is overloaded\"}}"}, + {"wrapped_concurrency_401", 401, `{"error":{"type":"authentication_error","message":"authentication failed (status=503): Too many concurrent requests"}}`}, } { t.Run(tc.name, func(t *testing.T) { repo := &ipUnauthorizedAccountRepo{} @@ -225,6 +226,18 @@ func TestOpenAIIPUnauthorizedGatewayEarlyReturnsBreakStreak(t *testing.T) { } } +func TestOpenAIIPUnauthorizedGatewayRevokedTokenStillDisables(t *testing.T) { + repo := &ipUnauthorizedAccountRepo{} + rateLimits := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + gateway := &OpenAIGatewayService{rateLimitService: rateLimits} + rateLimits.SetAccountRuntimeBlocker(gateway) + account := &Account{ID: 10, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"refresh_token": "fixture-refresh"}} + body := []byte(`{"error":{"code":"token_revoked","message":"Token revoked"}}`) + require.True(t, gateway.handleOpenAIAccountUpstreamError(context.Background(), account, 401, nil, body)) + require.Equal(t, 1, repo.setErrorCalls) + require.True(t, gateway.isOpenAIAccountRuntimeBlocked(account)) +} + func TestOpenAIIPUnauthorizedOtherAccountTypesUnchanged(t *testing.T) { for _, tc := range []struct { name, platform, accountType string diff --git a/backend/internal/service/openai_oauth_eof_affinity_test.go b/backend/internal/service/openai_oauth_eof_affinity_test.go new file mode 100644 index 000000000000..77d4e9b8df9f --- /dev/null +++ b/backend/internal/service/openai_oauth_eof_affinity_test.go @@ -0,0 +1,74 @@ +//go:build unit + +package service + +import ( + "errors" + "fmt" + "io" + "net/http" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +func TestOAuthNormalEOFBeforeOutputPreservesAccount(t *testing.T) { + for _, passthrough := range []bool{false, true} { + for _, pool := range []bool{false, true} { + for _, prefix := range []string{"", "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_metadata\"}}\n\n"} { + t.Run(fmt.Sprintf("passthrough=%t/pool=%t/metadata=%t", passthrough, pool, prefix != ""), func(t *testing.T) { + c, rec := newOpenAIUpstreamErrorTestContext(t) + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"pool_mode": pool}} + svc := &OpenAIGatewayService{cfg: &config.Config{}} + resp := &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(prefix))} + var err error + if passthrough { + _, err = svc.handleStreamingResponsePassthrough(c.Request.Context(), resp, c, account, time.Now(), "gpt-5.1", "gpt-5.1") + } else { + _, err = svc.handleStreamingResponse(c.Request.Context(), resp, c, account, time.Now(), "gpt-5.1", "gpt-5.1") + } + var failure *UpstreamFailoverError + require.ErrorAs(t, err, &failure) + require.True(t, failure.SameAccountRetryOnly()) + require.True(t, failure.RetryableOnSameAccount) + require.False(t, failure.QuotaRejectedBeforeExecution) + require.Empty(t, rec.Body.String(), "pre-output EOF cannot publish buffered metadata") + }) + } + } + } +} + +func TestOAuthNormalEOFAfterOutputCannotReplay(t *testing.T) { + for _, passthrough := range []bool{false, true} { + t.Run(fmt.Sprint(passthrough), func(t *testing.T) { + c, rec := newOpenAIUpstreamErrorTestContext(t) + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + svc := &OpenAIGatewayService{cfg: &config.Config{}} + resp := &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader("data: {\"type\":\"response.output_text.delta\",\"delta\":\"partial\",\"output_index\":0}\n\n"))} + var err error + if passthrough { + _, err = svc.handleStreamingResponsePassthrough(c.Request.Context(), resp, c, account, time.Now(), "gpt-5.1", "gpt-5.1") + } else { + _, err = svc.handleStreamingResponse(c.Request.Context(), resp, c, account, time.Now(), "gpt-5.1", "gpt-5.1") + } + require.Error(t, err) + var failure *UpstreamFailoverError + require.False(t, errors.As(err, &failure)) + require.Contains(t, rec.Body.String(), "partial") + }) + } +} + +func TestSSEQuotaTerminalDoesNotGrantHTTPRejectionProof(t *testing.T) { + c, _ := newOpenAIUpstreamErrorTestContext(t) + svc := &OpenAIGatewayService{cfg: &config.Config{}} + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"pool_mode": true}} + payload := []byte(`{"type":"response.failed","response":{"status":"failed","error":{"code":"insufficient_quota","message":"Quota exhausted"}}}`) + failure := svc.newOpenAIStreamFailoverError(c, account, true, "fixture-sse-quota", payload, "Quota exhausted") + require.False(t, failure.QuotaRejectedBeforeExecution, "HTTP200 terminal events do not grant the HTTP429 history-replay exception") + require.False(t, failure.RetryableOnSameAccount, "explicit quota must not enter a transient retry window through SSE") +} diff --git a/backend/internal/service/openai_same_account_retry.go b/backend/internal/service/openai_same_account_retry.go new file mode 100644 index 000000000000..0dd2fb6db651 --- /dev/null +++ b/backend/internal/service/openai_same_account_retry.go @@ -0,0 +1,40 @@ +package service + +import ( + "context" + "time" +) + +type openAISameAccountRetryKey struct{} + +type openAISameAccountRetry struct { + accountID int64 + deadline time.Time +} + +// WithOpenAISameAccountRetry pins the actual sender for a same-account retry. +// Passing nil clears the constraint when an ordinary counted switch is allowed. +func WithOpenAISameAccountRetry(ctx context.Context, accountID int64, failure *UpstreamFailoverError) context.Context { + retry := openAISameAccountRetry{} + if failure != nil && failure.RetryableOnSameAccount { + retry.accountID = accountID + retry.deadline = failure.SameAccountRetryDeadline + } + return context.WithValue(ctx, openAISameAccountRetryKey{}, retry) +} + +func openAISameAccountRetryFromContext(ctx context.Context) openAISameAccountRetry { + if ctx == nil { + return openAISameAccountRetry{} + } + retry, _ := ctx.Value(openAISameAccountRetryKey{}).(openAISameAccountRetry) + return retry +} + +// OpenAISameAccountRetryAdmissible is rechecked after slot waits so an expired +// retry cannot send, and a changed selection cannot escape its actual owner. +func OpenAISameAccountRetryAdmissible(ctx context.Context, accountID int64) bool { + retry := openAISameAccountRetryFromContext(ctx) + return (ctx == nil || ctx.Err() == nil) && (retry.accountID <= 0 || + (retry.accountID == accountID && (retry.deadline.IsZero() || time.Now().Before(retry.deadline)))) +} diff --git a/backend/internal/service/openai_same_account_retry_test.go b/backend/internal/service/openai_same_account_retry_test.go new file mode 100644 index 000000000000..2ab50a21a7b0 --- /dev/null +++ b/backend/internal/service/openai_same_account_retry_test.go @@ -0,0 +1,101 @@ +package service + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +func TestStrictSameAccountRetryRequiresCurrentBinding(t *testing.T) { + for _, owner := range []int64{947101, 947102, 0} { + t.Run(fmt.Sprint(owner), func(t *testing.T) { + f := newStrictSessionFixture() + f.cache.sessionBindings["openai:rebind-session"] = owner + ctx := WithOpenAISameAccountRetry(context.Background(), 947101, &UpstreamFailoverError{RetryableOnSameAccount: true}) + selected, _, err := f.scheduler.Select(ctx, f.request) + if owner == 947101 { + require.NoError(t, err) + require.Equal(t, owner, selected.Account.ID) + } else { + require.Error(t, err) + require.Nil(t, selected) + } + require.Equal(t, owner, f.cache.sessionBindings["openai:rebind-session"]) + }) + } +} + +func TestSameAccountRetrySchedulerCannotEscape(t *testing.T) { + for _, advanced := range []string{"false", "true"} { + for _, weighted := range []string{"false", "true"} { + for _, scenario := range []string{"busy", "recovered", "excluded", "disabled", "wrong_group", "no_session", "expired", "canceled"} { + t.Run(fmt.Sprintf("advanced=%s/weighted=%s/%s", advanced, weighted, scenario), func(t *testing.T) { + groupID := int64(10103) + accounts := []Account{ + {ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, Concurrency: 1, GroupIDs: []int64{groupID}}, + {ID: 2, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, Concurrency: 1, GroupIDs: []int64{groupID}}, + } + cache := &schedulerTestGatewayCache{sessionBindings: map[string]int64{"openai:retry-session": 1}} + cfg := &config.Config{} + cfg.Gateway.OpenAIScheduler.StickyEscapeEnabled = true + cfg.Gateway.Scheduling.StickySessionWaitTimeout = time.Second + var acquired []int64 + acquires := map[int64]bool{1: false, 2: true} + var excluded map[int64]struct{} + session := "retry-session" + failure := &UpstreamFailoverError{RetryableOnSameAccount: true, SameAccountRetryDeadline: time.Now().Add(time.Second)} + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + switch scenario { + case "recovered": + acquires[1] = true + case "excluded": + excluded = map[int64]struct{}{1: {}} + case "disabled": + accounts[0].Schedulable = false + case "wrong_group": + accounts[0].GroupIDs = []int64{999} + case "no_session": + session = "" + case "expired": + failure.SameAccountRetryDeadline = time.Now().Add(-time.Second) + case "canceled": + cancel() + } + svc := &OpenAIGatewayService{ + accountRepo: schedulerTestOpenAIAccountRepo{accounts: accounts}, + cache: cache, + cfg: cfg, + rateLimitService: newOpenAIAdvancedSchedulerRateLimitService(advanced, weighted), + concurrencyService: NewConcurrencyService(schedulerTestConcurrencyCache{ + acquireResults: acquires, acquiredIDs: &acquired, + }), + } + ctx = WithOpenAISameAccountRetry(ctx, 1, failure) + selection, _, err := svc.SelectAccountWithScheduler(ctx, &groupID, "", session, "gpt-5.1", excluded, OpenAIUpstreamTransportAny, false) + if scenario == "busy" || scenario == "no_session" || scenario == "recovered" { + require.NoError(t, err) + require.Equal(t, int64(1), selection.Account.ID) + if scenario == "recovered" { + require.True(t, selection.Acquired) + selection.ReleaseFunc() + } else { + require.NotNil(t, selection.WaitPlan) + require.Positive(t, selection.WaitPlan.Timeout) + require.LessOrEqual(t, selection.WaitPlan.Timeout, time.Second) + } + } else { + require.Error(t, err) + require.Nil(t, selection) + } + require.NotContains(t, acquired, int64(2), "B is healthy but cannot replace the retry owner") + require.Equal(t, int64(1), cache.sessionBindings["openai:retry-session"]) + }) + } + } + } +} diff --git a/backend/internal/service/openai_upstream_session_error_test.go b/backend/internal/service/openai_upstream_session_error_test.go index 328b2a14a17f..301692d1f048 100644 --- a/backend/internal/service/openai_upstream_session_error_test.go +++ b/backend/internal/service/openai_upstream_session_error_test.go @@ -95,6 +95,26 @@ func TestUpstreamSessionBlockedIsTerminalAndPreservesClientGuidance(t *testing.T } } +func TestOAuthPassthroughSessionBlockedNeverEntersAffinityRetry(t *testing.T) { + gin.SetMode(gin.TestMode) + c, rec := newOpenAIUpstreamErrorTestContext(t) + upstream := &httpUpstreamRecorder{resp: newOpenAIUpstreamErrorResponse(http.StatusBadGateway, upstreamSessionBlockedBody)} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + account := &Account{ + ID: 551, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, + Credentials: map[string]any{"access_token": "fixture-access", "chatgpt_account_id": "fixture-account"}, + Extra: map[string]any{"openai_passthrough": true}, + } + require.False(t, shouldFailoverOpenAIPassthroughResponse(account, 502, []byte(upstreamSessionBlockedBody))) + _, err := svc.Forward(context.Background(), c, account, []byte(`{"model":"gpt-5.1","input":"synthetic","stream":false}`)) + require.Error(t, err) + var failover *UpstreamFailoverError + require.False(t, errors.As(err, &failover)) + require.Equal(t, http.StatusBadGateway, rec.Code) + require.True(t, IsResponseCommitted(c)) + require.Len(t, upstream.requests, 1) +} + func TestUpstreamSessionBlockedRequiresExactErrorCode(t *testing.T) { for _, body := range []string{ `{"error":{"code":"cyber_policy","message":"blocked"}}`,