Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend/internal/handler/failover_loop.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
4 changes: 3 additions & 1 deletion backend/internal/handler/openai_chat_completions.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 + "]"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -319,6 +320,7 @@ type grokCredentialHandlerUpstream struct {
failAccountID int64
rateLimitIDs map[int64]bool
failureStatus map[int64]int
failureBody map[int64]string
cancelRequest context.CancelFunc
}

Expand All @@ -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 {
Expand All @@ -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 {
Expand All @@ -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"}},
Expand Down Expand Up @@ -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")
Expand Down
28 changes: 24 additions & 4 deletions backend/internal/handler/openai_gateway_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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
Expand Down Expand Up @@ -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",
Expand All @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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",
Expand All @@ -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 {
Expand All @@ -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
Expand Down Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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{
{
Expand Down Expand Up @@ -110,7 +114,7 @@ func newOpenAIResponsesFailoverTestHandlerWithUsage(t *testing.T, upstream servi
cache,
cfg,
nil,
nil,
concurrency,
service.NewBillingService(cfg, nil),
nil,
nil,
Expand All @@ -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,
Expand Down
Loading
Loading