Skip to content
9 changes: 9 additions & 0 deletions .github/scripts/prepare-replay-red-fixtures.sh
Original file line number Diff line number Diff line change
Expand Up @@ -178,3 +178,12 @@ if ! git -C "$tree" show "$baseline:$contract" |
fi
done
fi

# The quota tests use the newer request and discovery receipt types. Preserve
# them on the candidate, including all GREEN jobs.
contract=backend/internal/service/openai_agent_message_recovery.go
target=backend/internal/service/openai_agent_quota_failover_test.go
if test -f "$tree/$target" && ! grep -q 'func openAIAgentQuotaFailoverAllowed' "$tree/$contract" &&
test "$(git -C "$tree" hash-object "$contract")" = "$(git -C "$tree" rev-parse "$baseline:$contract")"; then
exclude_absent_fixture "$target" "$contract"
fi
1 change: 1 addition & 0 deletions .github/scripts/prepare-ws-owner-red-fixtures.sh
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ exclude_new_fixture() {
# New service tests require new private proof/diagnostic types. Their own RED
# uses handler tests; every candidate GREEN retains them and all negative cases.
exclude_new_fixture backend/internal/service/openai_ws_owner_conflict_test.go
exclude_new_fixture backend/internal/service/openai_agent_quota_failover_test.go
# Issue892's later matrix also imports the OAuth dial seam and 400/842 test
# helpers absent from these historical overlays. It is not a selected oracle
# here; its own RED and every clean candidate GREEN retain both exact files.
Expand Down
3 changes: 3 additions & 0 deletions backend/internal/handler/failover_loop.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,9 @@ func (s *FailoverState) HandleFailoverError(
// 同账号重试不算切换账号,粘性会话仅在实际切换时强制缓存计费。
retryCount := s.SameAccountRetryCount[accountID]
sameAccountRetry := sameAccountRetryAllowed(failoverErr, retryCount, retryLimit)
if !sameAccountRetry && failoverErr.RequestScopedTransient && failoverErr.Scope == service.GatewayFailureScopeRequest {
return FailoverExhausted
}
if needForceCacheBilling(s.hasBoundSession, failoverErr, sameAccountRetry) {
s.ForceCacheBilling = true
}
Expand Down
13 changes: 13 additions & 0 deletions backend/internal/handler/failover_loop_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -589,6 +589,19 @@ func TestHandleFailoverError_SameAccountRetry(t *testing.T) {
// ---------------------------------------------------------------------------

func TestHandleFailoverError_TempUnschedule(t *testing.T) {
t.Run("exhausted request-local failure preserves the bound account", func(t *testing.T) {
mock := &mockTempUnscheduler{}
state := NewFailoverState(5, true)
err := newTestFailoverErr(502, true, false)
err.Scope = service.GatewayFailureScopeRequest
err.RequestScopedTransient = true
state.SameAccountRetryCount[100] = 1
require.Equal(t, FailoverExhausted, state.HandleFailoverError(context.Background(), mock, 100, "openai", 1, err))
require.Empty(t, mock.calls)
require.Empty(t, state.FailedAccountIDs)
require.Zero(t, state.SwitchCount)
require.False(t, state.ForceCacheBilling)
})
t.Run("非重试错误不调用TempUnschedule", func(t *testing.T) {
mock := &mockTempUnscheduler{}
fs := NewFailoverState(3, false)
Expand Down
2 changes: 1 addition & 1 deletion backend/internal/handler/http2_peer_reset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,7 @@ func TestHTTP2PeerResetHTTP502Control(t *testing.T) {
for len(opsErrorLogQueue) > 0 {
flushOpsErrorLogBatch([]opsErrorLogJob{<-opsErrorLogQueue})
}
require.Equal(t, int32(2), submissions.Load(), "actual HTTP refusal retains existing account failover")
require.Equal(t, int32(4), submissions.Load(), "actual OAuth HTTP refusal uses the bounded same-account retry policy")
require.Equal(t, 502, rec.Code)
require.Len(t, repo.entries, 1)
require.NotNil(t, repo.entries[0].UpstreamStatusCode)
Expand Down
4 changes: 2 additions & 2 deletions backend/internal/handler/moderation_upstream_http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ func TestModerationUpstreamHTTPSelectionAndFailover(t *testing.T) {
writesB.Add(1)
}
if isA && strings.HasPrefix(scenario, "failover") {
w.WriteHeader(503)
_, _ = w.Write([]byte(`{"error":{"message":"fixture overloaded"}}`))
w.WriteHeader(http.StatusTooManyRequests)
_, _ = w.Write([]byte(`{"error":{"type":"usage_limit_reached","message":"fixture account quota exhausted","resets_at":4102444800}}`))
return
}
if stream || accountType == service.AccountTypeOAuth {
Expand Down
4 changes: 4 additions & 0 deletions backend/internal/handler/openai_chat_completions.go
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,10 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
continue
}
}
if failoverErr.RequestScopedTransient && failoverErr.Scope == service.GatewayFailureScopeRequest {
h.handleFailoverExhausted(c, failoverErr, streamStarted)
return
}
h.gatewayService.RecordOpenAIAccountSwitch()
failedAccountIDs[account.ID] = struct{}{}
lastFailoverErr = failoverErr
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
//go:build unit

package handler

import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"

"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/repository"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/Wei-Shaw/sub2api/internal/testutil"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)

func TestEncryptedHistoryQuotaFailoverPreservesContinuation(t *testing.T) {
for _, kind := range []string{service.AccountTypeOAuth, service.AccountTypeAPIKey} {
for _, stream := range []bool{false, true} {
t.Run(fmt.Sprintf("%s/stream=%t", kind, stream), func(t *testing.T) {
clients := issue805Redis(t)
var mu sync.Mutex
var identities []string
var inputs []string
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
t.Error(err)
return
}
mu.Lock()
identities = append(identities, r.Header.Get("Authorization"))
inputs = append(inputs, gjson.GetBytes(body, "input").Raw)
attempt := len(identities)
mu.Unlock()
if attempt > 1 && r.Header.Get("Authorization") == "Bearer fixture-quota-1" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusTooManyRequests)
_, _ = io.WriteString(w, `{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached","resets_at":4102444800}}`)
return
}
output := "[" + issue715Agent + "]"
if attempt > 1 {
output = `[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"existing ledger balance 18"}]}]`
}
response := fmt.Sprintf(`{"id":"resp_quota_%d","status":"completed","model":"gpt-5.1","output":%s,"usage":{"input_tokens":5,"output_tokens":3}}`, attempt, output)
if gjson.GetBytes(body, "stream").Bool() {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = fmt.Fprintf(w, "data: {\"type\":\"response.completed\",\"response\":%s}\n\ndata: [DONE]\n\n", response)
} else {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, response)
}
}))
defer upstream.Close()
target, err := url.Parse(upstream.URL)
require.NoError(t, err)
accounts := issue715Accounts()
for i := range accounts {
accounts[i].Type = kind
accounts[i].Credentials = map[string]any{
"api_key": fmt.Sprintf("fixture-quota-%d", i+1),
"access_token": fmt.Sprintf("fixture-quota-%d", i+1),
"base_url": upstream.URL,
}
}
newNode := func() *OpenAIGatewayHandler {
cfg := &config.Config{RunMode: config.RunModeSimple}
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
transport := &issue842Transport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target}
settings := service.NewSettingService(&issue842Settings{}, cfg)
handler := newOpenAIResponsesFailoverTestHandlerWithSettings(t, transport, repository.NewGatewayCache(clients()), settings, accounts...)
handler.cfg.Security.URLAllowlist.AllowInsecureHTTP = true
issue805Policy(t, handler.cfg, true)
return handler
}
first := issue758Request(t, newNode(), strings.Replace(issue715Body(false, stream), issue715Agent+",", "", 1))
require.Equal(t, http.StatusOK, first.Code, first.Body.String())
issue758CompletedResponse(t, first.Body.String(), stream)
originalOwners := issue805Owners(t, clients())
require.Len(t, originalOwners, 1)
followup := issue715Body(true, stream)
for request := 0; request < 2; request++ {
answer := issue758Request(t, newNode(), followup)
require.Equal(t, http.StatusOK, answer.Code, answer.Body.String())
completed := issue758CompletedResponse(t, answer.Body.String(), stream)
require.Contains(t, completed.Raw, "existing ledger balance 18")
require.NotContains(t, answer.Body.String(), "response.failed")
}
require.Equal(t, originalOwners, issue805Owners(t, clients()), "quota rejection must preserve the completed producer records")
mu.Lock()
defer mu.Unlock()
require.Equal(t, []string{"Bearer fixture-quota-1", "Bearer fixture-quota-1", "Bearer fixture-quota-2", "Bearer fixture-quota-2"}, identities)
for _, input := range inputs[1:] {
require.JSONEq(t, gjson.Get(followup, "input").Raw, input, "quota failover must retain the task and completed tool results")
}
})
}
}
}
14 changes: 13 additions & 1 deletion backend/internal/handler/openai_gateway_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -1383,7 +1383,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
if failoverErr.ShouldReportAccountScheduleFailure() {
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, forwardModel, requireCompact, nil), false, nil, err)
}
if service.OpenAIAgentRecoveryNoReplay(c.Request.Context()) {
if service.OpenAIAgentRecoveryNoReplay(c.Request.Context()) && !failoverErr.QuotaRejectedBeforeExecution {
h.handleFailoverExhausted(c, failoverErr, streamStarted)
return
}
Expand Down Expand Up @@ -1416,6 +1416,10 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
continue
}
}
if failoverErr.RequestScopedTransient && failoverErr.Scope == service.GatewayFailureScopeRequest {
h.handleFailoverExhausted(c, failoverErr, streamStarted)
return
}
h.gatewayService.RecordOpenAIAccountSwitch()
failedAccountIDs[account.ID] = struct{}{}
lastFailoverErr = failoverErr
Expand Down Expand Up @@ -2055,6 +2059,10 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
continue
}
}
if failoverErr.RequestScopedTransient && failoverErr.Scope == service.GatewayFailureScopeRequest {
h.handleAnthropicFailoverExhausted(c, failoverErr, streamStarted)
return
}
h.gatewayService.RecordOpenAIAccountSwitch()
failedAccountIDs[account.ID] = struct{}{}
lastFailoverErr = failoverErr
Expand Down Expand Up @@ -3490,6 +3498,10 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
if ctx.Err() != nil {
return false
}
if failoverErr.RequestScopedTransient && failoverErr.Scope == service.GatewayFailureScopeRequest {
closeOpenAIWSFailoverExhausted(c, wsConn, failoverErr)
return false
}
h.gatewayService.RecordOpenAIAccountSwitch()
failedAccountIDs[account.ID] = struct{}{}
lastFailoverErr = failoverErr
Expand Down
3 changes: 1 addition & 2 deletions backend/internal/handler/openai_issue914_legacy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -290,8 +290,7 @@ func TestIssue914LegacyAccountPoolAndCancellation(t *testing.T) {
require.Empty(t, calls)
} else {
require.GreaterOrEqual(t, status, 400)
require.Contains(t, calls, int64(1))
require.Contains(t, calls, int64(2), "ordinary pre-output failure must be able to select another eligible account")
require.Equal(t, []int64{1, 1, 1, 1}, calls, "legacy history keeps the OAuth account through bounded transient retries")
}
})
}
Expand Down
37 changes: 24 additions & 13 deletions backend/internal/handler/openai_responses_failover_cancel_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,19 +199,30 @@ func TestOpenAIGatewayHandlerResponses_FailoverAbortsWhenClientDisconnected(t *t
require.Equal(t, 520, events[0].UpstreamStatusCode)
}

// TestOpenAIGatewayHandlerResponses_FailoverContinuesForConnectedClient 回归
// 守卫:客户端在线时 failover 行为不变——切换到账号 2,两个账号都 520 后按
// 耗尽返回 502。
// Connected OAuth requests retry transient failures on the original account.
// API-key accounts retain their existing bounded cross-account failover.
func TestOpenAIGatewayHandlerResponses_FailoverContinuesForConnectedClient(t *testing.T) {
gin.SetMode(gin.TestMode)

upstream := &openAIResponsesFailoverCancelUpstream{}
handler := newOpenAIResponsesFailoverTestHandler(t, upstream)
c, rec := newOpenAIResponsesFailoverTestContext(t, nil)

handler.Responses(c)

require.Equal(t, []int64{1, 2}, upstream.calls(), "在线客户端应正常切换账号")
require.Equal(t, http.StatusBadGateway, rec.Code)
require.Equal(t, "upstream_error", gjson.GetBytes(rec.Body.Bytes(), "error.type").String())
for _, tc := range []struct {
kind string
accounts []int64
}{
{service.AccountTypeOAuth, []int64{1, 1, 1, 1}},
{service.AccountTypeAPIKey, []int64{1, 2}},
} {
t.Run(tc.kind, func(t *testing.T) {
accounts := issue715Accounts()
for i := range accounts {
accounts[i].Type = tc.kind
accounts[i].Credentials = map[string]any{"api_key": "fixture-key", "access_token": "fixture-access"}
}
upstream := &openAIResponsesFailoverCancelUpstream{}
handler := newOpenAIResponsesFailoverTestHandler(t, upstream, accounts...)
c, rec := newOpenAIResponsesFailoverTestContext(t, nil)
handler.Responses(c)
require.Equal(t, tc.accounts, upstream.calls())
require.Equal(t, http.StatusBadGateway, rec.Code)
require.Equal(t, "upstream_error", gjson.GetBytes(rec.Body.Bytes(), "error.type").String())
})
}
}
25 changes: 15 additions & 10 deletions backend/internal/service/gateway_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -800,16 +800,18 @@ type GatewayFailureReason string
// trigger account failover. Additive metadata keeps existing composite literals
// source-compatible and preserves their legacy retry-next-account behavior.
type UpstreamFailoverError struct {
StatusCode int
ResponseBody []byte // 上游响应体,用于错误透传规则匹配
ResponseHeaders http.Header // 上游响应头,用于透传 cf-ray/cf-mitigated/content-type 等诊断信息
ForceCacheBilling bool // Antigravity 粘性会话切换时设为 true
RetryableOnSameAccount bool // 临时性错误(如 Google 间歇性 400、空响应),应在同一账号上重试 N 次再切换
SameAccountRetryDelay time.Duration // 同账号重试的最小间隔;零值使用 handler 默认值
SameAccountRetryDeadline time.Time // 同账号重试截止时间;零值表示仅受 retryLimit 限制
SameAccountRetryMax int // 可选的错误级同账号重试上限,低于 handler 默认预算时优先采用
RequestScopedTransient bool // 故障因素与账号无关(如上游按客户端身份/模型容量降载):可同账号重试,但不得据此对账号做临时封禁
SafeToFailoverAfterWrite bool // 仅写出 SSE 注释等非语义字节时,仍可在同一客户端流中切换账号
// QuotaRejectedBeforeExecution is set after any provisional tool receipts are restored.
QuotaRejectedBeforeExecution bool
StatusCode int
ResponseBody []byte // 上游响应体,用于错误透传规则匹配
ResponseHeaders http.Header // 上游响应头,用于透传 cf-ray/cf-mitigated/content-type 等诊断信息
ForceCacheBilling bool // Antigravity 粘性会话切换时设为 true
RetryableOnSameAccount bool // 临时性错误(如 Google 间歇性 400、空响应),应在同一账号上重试 N 次再切换
SameAccountRetryDelay time.Duration // 同账号重试的最小间隔;零值使用 handler 默认值
SameAccountRetryDeadline time.Time // 同账号重试截止时间;零值表示仅受 retryLimit 限制
SameAccountRetryMax int // 可选的错误级同账号重试上限,低于 handler 默认预算时优先采用
RequestScopedTransient bool // 故障因素与账号无关(如上游按客户端身份/模型容量降载):可同账号重试,但不得据此对账号做临时封禁
SafeToFailoverAfterWrite bool // 仅写出 SSE 注释等非语义字节时,仍可在同一客户端流中切换账号
// HeaderTimeoutSubmitted marks a failover caused by an OpenAI response-header
// timeout after the request was written. The upstream may have billed the
// attempt; the successful usage record adds one retry surcharge unit.
Expand Down Expand Up @@ -854,6 +856,9 @@ func (e *UpstreamFailoverError) ShouldReportAccountScheduleFailure() bool {
if e == nil || e.Reason == OpenAIWSModelUnavailableReason || e.Reason == ExcelBPSRateLimitedReason || e.Reason == GrokUnknownForbiddenReason || e.IsExcelBPSImageAdmissionRejection() {
return false
}
if e.RequestScopedTransient && e.Scope == GatewayFailureScopeRequest {
return false
}
return !e.IsCredentialFailure() || e.Scope == GatewayFailureScopeAccount
}

Expand Down
6 changes: 5 additions & 1 deletion backend/internal/service/gateway_upstream_response.go
Original file line number Diff line number Diff line change
Expand Up @@ -1299,11 +1299,15 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http
"message": disconnectMsg,
},
})
return nil, &UpstreamFailoverError{
failoverErr := &UpstreamFailoverError{
StatusCode: http.StatusBadGateway,
ResponseBody: body,
RetryableOnSameAccount: true,
}
if usesOpenAIOAuthRetryAffinity(account) && !classifyUpstreamTransportError(ev.err).Persistent {
failoverErr.preserveOpenAIOAuthBinding()
}
return nil, failoverErr
}
sendErrorEvent("stream_read_error", disconnectMsg)
return &streamingResult{usage: usage, firstTokenMs: firstTokenMs}, fmt.Errorf("stream read error: %w", ev.err)
Expand Down
7 changes: 7 additions & 0 deletions backend/internal/service/openai_access_state_failover_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,13 @@ func TestOpenAIHTTPAccessStateTrustsStructuredCode(t *testing.T) {
}

func TestOpenAIHTTPAuthMessagesUseExistingStatusPolicies(t *testing.T) {
t.Run("revoked credential with echoed concurrency error", func(t *testing.T) {
account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth}
body := []byte(`{"error":{"code":"token_revoked","message":"Token has been revoked"},"input":{"error":{"message":"authentication failed (status=503): Too many concurrent requests"}}}`)
err := (&OpenAIGatewayService{}).newOpenAIHTTPAccountFailoverError(account, http.StatusUnauthorized, nil, body, "", false, false)
require.False(t, err.RequestScopedTransient)
require.False(t, err.RetryableOnSameAccount)
})
t.Run("oauth 401 remains recoverable", func(t *testing.T) {
repo := &openAIAuthPolicyAccountRepo{}
rateLimits := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ func (s *OpenAIGatewayService) handleOpenAIAccountUpstreamError(ctx context.Cont
}
// Apply the same exemption before access-state and custom cooldown fast
// paths, which can otherwise block the credential before the shared handler.
if isOpenAIRequestScoped403(account, statusCode, responseBody) {
if isOpenAIRequestScoped403(account, statusCode, responseBody) || isOpenAIWrappedConcurrency401(account, statusCode, responseBody) {
return false
}
// Capacity shedding describes this request, not account health. Keep the
Expand Down
24 changes: 22 additions & 2 deletions backend/internal/service/openai_agent_message_recovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -724,8 +724,28 @@ func OpenAIAgentToolResultContinuation(ctx context.Context) bool {
return r != nil && (r.owner != nil || r.preservesHistory()) && r.toolResult
}

// Opt-out permits one intact attempt, not automatic cross-account retries or
// input-rewriting retries. Strict mode retains its existing tool-result rule.
// A quota rejection precedes execution. An opted-in full-history request can
// retain its input and use the ordinary account failover budget in that case.
// Account-owned response pointers and ambiguous failures retain their guards.
func openAIAgentQuotaFailoverAllowed(ctx context.Context, status int, body []byte) bool {
request := openAIAgentRecoveryFromContext(ctx)
if request == nil || !request.disableOwnerBinding || request.previousResponseID != "" ||
openAI409HasProviderState(request.replaySource) || request.nativeCompaction ||
request.omittedHistory || request.omitted400History || status != http.StatusTooManyRequests {
return false
}
if !openAIEncryptedJSONUnambiguous(body) {
return false
}
for _, path := range []string{"error.type", "error.code", "response.error.type", "response.error.code"} {
switch gjson.GetBytes(body, path).String() {
case "usage_limit_reached", "insufficient_quota", "quota_exceeded":
return true
}
}
return false
}

func OpenAIAgentRecoveryNoReplay(ctx context.Context) bool {
return OpenAIAgentToolResultContinuation(ctx) || openAIAgentRecoveryPreservesHistory(ctx)
}
Expand Down
Loading
Loading