fix(antigravity): QUOTA_EXHAUSTED 429 立即冷却并切换账号,不再同号退避重试

classifyAntigravity429 已把配额耗尽识别为 antigravity429QuotaExhausted,但
handleSmartRetry 只在 overages 分支用到它;积分不可用或积分重试失败后,因
parseAntigravitySmartRetryInfo 只认 RATE_LIMIT_EXCEEDED,函数返回 Continue,
antigravityRetryLoop 在同一个已耗尽账号上再做 2 次指数退避(1s+2s 和两次
必然失败的上游请求),开启 overages 时还会逐次重复积分重试。

现在该情形按重试用尽时的同一套规则冷却账号(handleError,按 quotaResetDelay
写模型级限流),清理粘性会话并返回 AntigravityAccountSwitchError,与
RATE_LIMIT_EXCEEDED 长延迟分支一致;同时记录 failover 运维事件保留 429 原因。

- 把循环末尾"裸 429 认领 + 冷却"提为 applyAntigravity429Cooldown 共用,
  message-only 的 QUOTA_EXHAUSTED(同属裸 429)仍遵守每请求最多冷却一个账号。
- Claude 路径签名/budget 修正二次重试收到切换信号时转为 failover(新增
  antigravityRetrySwitchToFailover,与 Gemini 路径一致),不再吞掉后返回原始 400。

既有用例 429WithResetDelay_CoolsEveryAccount 断言循环返回 429 响应,改为断言
返回切换信号且每个账号冷却一次,用例本意不变。

Refs #8978
This commit is contained in:
li committed 2026-11-27 19:33:54 +08:00
1 parent 4233cc3d80
commit c2f3bcfe3f
5 files changed
+262 -9

No files matched your search

@@ -112,12 +112,17 @@ func TestAntigravityRetryLoop_Bare429_OtherRequestStillCools(t *testing.T) {
}
// A 429 that says when it resets is Google's statement about the account and is
// applied on every account, as before.
// applied on every account, as before. A QUOTA_EXHAUSTED 429 now cools the account
// and switches away at once (no same-account retries), so the loop returns the
// switch signal instead of the 429 response.
func TestAntigravityRetryLoop_429WithResetDelay_CoolsEveryAccount(t *testing.T) {
setupBare429Test(t)
c := newBare429TestContext()
body := `{"error":{"code":429,"message":"You have exhausted your capacity on this model. Your quota will reset after 2h.","status":"RESOURCE_EXHAUSTED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"QUOTA_EXHAUSTED","metadata":{"quotaResetDelay":"2h0m0s"}}]}}`
require.True(t, runBare429Loop(t, c, bare429Account(13), body))
require.True(t, runBare429Loop(t, c, bare429Account(6), body))
for _, id := range []int64{13, 6} {
out := runQuotaExhaustedLoop(t, c, bare429Account(id), quotaExhaustedAntigravity429Body, nil)
_, ok := IsAntigravityAccountSwitchError(out.err)
require.True(t, ok, "account %d: %v", id, out.err)
require.Equal(t, 1, out.cooled, "account %d is cooled", id)
}
}
@@ -211,6 +211,11 @@ func (s *AntigravityGatewayService) Forward(ctx context.Context, c *gin.Context,
sessionHash: "", // Forward 方法没有 sessionHash,由上层处理粘性会话清除
})
if retryErr != nil {
// 重试命中账号级限流/配额耗尽时,循环返回切换信号:与 Gemini 路径一致转为 failover,
// 不能吞掉后把原始 400 返回给客户端。
if failoverErr := antigravityRetrySwitchToFailover(c, account, retryErr); failoverErr != nil {
return nil, failoverErr
}
appendOpsUpstreamError(c, OpsUpstreamErrorEvent{
ProxyID: opsUpstreamProxyID(account),
ProxyName: opsUpstreamProxyName(account),
@@ -355,6 +360,9 @@ func (s *AntigravityGatewayService) Forward(ctx context.Context, c *gin.Context,
}
}
} else {
if failoverErr := antigravityRetrySwitchToFailover(c, account, retryErr); failoverErr != nil {
return nil, failoverErr
}
logger.LegacyPrintf("service.antigravity_gateway", "Antigravity account %d: budget rectifier retry failed: %v", account.ID, retryErr)
}
}
@@ -130,6 +130,39 @@ func (s *AntigravityGatewayService) handleSmartRetry(p antigravityRetryLoopParam
}
}
// 免费配额耗尽(QUOTA_EXHAUSTED):上游已明确该账号在配额重置前不可用(重置时间通常以小时计),
// 同号指数退避重试只会多打必然失败的请求并白等数秒,积分路径还会被逐次重复尝试。
// 积分未接住时,按重试用尽时的同一套规则冷却账号,并像 RATE_LIMIT_EXCEEDED 长延迟一样立即切换账号。
if resp.StatusCode == http.StatusTooManyRequests &&
category == antigravity429QuotaExhausted &&
p.account.Platform == PlatformAntigravity {
logger.LegacyPrintf("service.antigravity_gateway", "%s status=%d quota_exhausted account=%d body=%s (cool down and switch account, skip same-account retries)",
p.prefix, resp.StatusCode, p.account.ID, truncateForLog(respBody, 200))
// 切换信号到上层只剩 503,在这里保留上游 429 的原因供运维排查。
appendOpsUpstreamError(p.c, OpsUpstreamErrorEvent{
ProxyID: opsUpstreamProxyID(p.account),
ProxyName: opsUpstreamProxyName(p.account),
Platform: p.account.Platform,
AccountID: p.account.ID,
AccountName: p.account.Name,
UpstreamStatusCode: resp.StatusCode,
UpstreamRequestID: resp.Header.Get("x-request-id"),
Kind: "failover",
Message: sanitizeUpstreamErrorMessage(strings.TrimSpace(extractAntigravityErrorMessage(respBody))),
Detail: s.getUpstreamErrorDetail(respBody),
})
s.applyAntigravity429Cooldown(p, resp, respBody)
s.clearStickySession(p.ctx, p.groupID, p.sessionHash)
return &smartRetryResult{
action: smartRetryActionBreakWithResp,
switchError: &AntigravityAccountSwitchError{
OriginalAccountID: p.account.ID,
RateLimitedModel: p.requestedModel,
IsStickySession: p.isStickySession,
},
}
}
// 情况1: retryDelay >= 阈值,限流模型并切换账号
if shouldRateLimitModel {
// 单账号 503 退避重试模式:不设限流、不切换账号,改为原地等待+重试
@@ -646,11 +679,7 @@ urlFallbackLoop:
}
// 重试用尽,标记账户限流(无原因的 429 每个请求最多冷却一个账号)
if isBareAntigravity429(resp.StatusCode, respBody) && !claimBare429Cooldown(p.c, p.account.ID) {
logger.LegacyPrintf("service.antigravity_gateway", "%s status=%d bare_429_cooldown_skipped account=%d (this request already cooled another account; the request is the likely cause)", p.prefix, resp.StatusCode, p.account.ID)
} else {
p.handleError(p.ctx, p.prefix, p.account, resp.StatusCode, resp.Header, respBody, p.requestedModel, p.groupID, p.sessionHash, p.isStickySession)
}
s.applyAntigravity429Cooldown(p, resp, respBody)
logger.LegacyPrintf("service.antigravity_gateway", "%s status=%d rate_limited base_url=%s body=%s", p.prefix, resp.StatusCode, baseURL, truncateForLog(respBody, 200))
resp = &http.Response{
StatusCode: resp.StatusCode,
@@ -904,6 +933,17 @@ func (s *AntigravityGatewayService) setAntigravityModelRateLimits(ctx context.Co
return success
}
// applyAntigravity429Cooldown 对 429/503 的账号执行冷却(p.handleError)。
// 无原因、无重置时间的裸 429 每个请求最多冷却一个账号:它更可能由请求本身触发,
// 不能让同一个请求把它碰到的每个账号都冷却掉。
func (s *AntigravityGatewayService) applyAntigravity429Cooldown(p antigravityRetryLoopParams, resp *http.Response, respBody []byte) {
if isBareAntigravity429(resp.StatusCode, respBody) && !claimBare429Cooldown(p.c, p.account.ID) {
logger.LegacyPrintf("service.antigravity_gateway", "%s status=%d bare_429_cooldown_skipped account=%d (this request already cooled another account; the request is the likely cause)", p.prefix, resp.StatusCode, p.account.ID)
return
}
p.handleError(p.ctx, p.prefix, p.account, resp.StatusCode, resp.Header, respBody, p.requestedModel, p.groupID, p.sessionHash, p.isStickySession)
}
func (s *AntigravityGatewayService) clearStickySession(ctx context.Context, groupID int64, sessionHash string) {
if s == nil || s.cache == nil || strings.TrimSpace(sessionHash) == "" {
return
@@ -16,6 +16,7 @@ import (
"github.com/Wei-Shaw/sub2api/internal/pkg/antigravity"
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/tidwall/gjson"
)
@@ -109,6 +110,30 @@ func IsAntigravityAccountSwitchError(err error) (*AntigravityAccountSwitchError,
return nil, false
}
// antigravityRetrySwitchToFailover 把二次重试(签名/预算修正等)中收到的账号切换信号
// 转为 UpstreamFailoverError,让 Handler 切换账号;不是切换信号时返回 nil。
// 与 Gemini 路径对二次重试切换信号的处理一致。
func antigravityRetrySwitchToFailover(c *gin.Context, account *Account, retryErr error) *UpstreamFailoverError {
switchErr, ok := IsAntigravityAccountSwitchError(retryErr)
if !ok {
return nil
}
appendOpsUpstreamError(c, OpsUpstreamErrorEvent{
ProxyID: opsUpstreamProxyID(account),
ProxyName: opsUpstreamProxyName(account),
Platform: account.Platform,
AccountID: account.ID,
AccountName: account.Name,
UpstreamStatusCode: http.StatusServiceUnavailable,
Kind: "failover",
Message: sanitizeUpstreamErrorMessage(retryErr.Error()),
})
return &UpstreamFailoverError{
StatusCode: http.StatusServiceUnavailable,
ForceCacheBilling: switchErr.IsStickySession,
}
}
// PromptTooLongError 表示上游明确返回 prompt too long
type PromptTooLongError struct {
StatusCode int
@@ -0,0 +1,175 @@
//go:build unit
package service
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
// Google 在 5h/周配额窗口耗尽时返回的 429:带 QUOTA_EXHAUSTED 与 quotaResetDelay。
const quotaExhaustedAntigravity429Body = `{"error":{"code":429,"message":"You have exhausted your capacity on this model. Your quota will reset after 2h.","status":"RESOURCE_EXHAUSTED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"QUOTA_EXHAUSTED","metadata":{"quotaResetDelay":"2h0m0s"}}]}}`
// 只在 message 里写 QUOTA_EXHAUSTED、没有 details 与重置时间:同时属于"裸 429"。
const quotaExhaustedMessageOnly429Body = `{"error":{"status":"RESOURCE_EXHAUSTED","message":"QUOTA_EXHAUSTED"}}`
type quotaLoopOutcome struct {
result *antigravityRetryLoopResult
err error
calls int
cooled int
cooledFor int
}
func runQuotaExhaustedLoop(t *testing.T, c *gin.Context, account *Account, body string, reqBody []byte) quotaLoopOutcome {
t.Helper()
upstream := &fixed429Upstream{body: body}
repo := &stubAntigravityAccountRepo{}
svc := &AntigravityGatewayService{accountRepo: repo}
var out quotaLoopOutcome
if reqBody == nil {
reqBody = []byte(`{"input":"test"}`)
}
out.result, out.err = svc.antigravityRetryLoop(antigravityRetryLoopParams{
prefix: "[test]",
ctx: context.Background(),
account: account,
accessToken: "token",
action: "streamGenerateContent",
body: reqBody,
c: c,
httpUpstream: upstream,
accountRepo: repo,
requestedModel: "gemini-4-argon-high",
handleError: func(ctx context.Context, prefix string, acc *Account, statusCode int, headers http.Header, body []byte, requestedModel string, groupID int64, sessionHash string, isStickySession bool) *handleModelRateLimitResult {
out.cooled++
out.cooledFor = statusCode
return nil
},
})
out.calls = upstream.calls
if out.result != nil && out.result.resp != nil {
_ = out.result.resp.Body.Close()
}
return out
}
// 配额耗尽:只打一次上游,冷却账号并立即返回切换信号,不在同一账号上指数退避重试。
func TestAntigravityRetryLoop_QuotaExhausted_SwitchesWithoutSameAccountRetries(t *testing.T) {
setupBare429Test(t)
c := newBare429TestContext()
out := runQuotaExhaustedLoop(t, c, bare429Account(13), quotaExhaustedAntigravity429Body, nil)
switchErr, ok := IsAntigravityAccountSwitchError(out.err)
require.True(t, ok, "quota exhausted must return an account switch signal, got %v", out.err)
require.Equal(t, int64(13), switchErr.OriginalAccountID)
require.Equal(t, "gemini-4-argon-high", switchErr.RateLimitedModel)
require.Nil(t, out.result)
require.Equal(t, 1, out.calls, "no same-account retries after QUOTA_EXHAUSTED")
require.Equal(t, 1, out.cooled, "the exhausted account is cooled exactly once")
require.Equal(t, http.StatusTooManyRequests, out.cooledFor)
// 切换信号到上层只剩 503,上游 429 的原因必须留在运维事件里。
raw, ok := c.Get(OpsUpstreamErrorsKey)
require.True(t, ok)
events, ok := raw.([]*OpsUpstreamErrorEvent)
require.True(t, ok)
require.Len(t, events, 1)
require.Equal(t, "failover", events[0].Kind)
require.Equal(t, http.StatusTooManyRequests, events[0].UpstreamStatusCode)
require.Contains(t, events[0].Message, "exhausted your capacity")
}
// 只有 message 的 QUOTA_EXHAUSTED 同时是裸 429:立即切换,但仍遵守"一个请求最多冷却一个账号"。
func TestAntigravityRetryLoop_MessageOnlyQuotaExhausted_KeepsBare429Scope(t *testing.T) {
setupBare429Test(t)
c := newBare429TestContext()
first := runQuotaExhaustedLoop(t, c, bare429Account(13), quotaExhaustedMessageOnly429Body, nil)
_, ok := IsAntigravityAccountSwitchError(first.err)
require.True(t, ok)
require.Equal(t, 1, first.calls)
require.Equal(t, 1, first.cooled, "first account is cooled")
second := runQuotaExhaustedLoop(t, c, bare429Account(6), quotaExhaustedMessageOnly429Body, nil)
_, ok = IsAntigravityAccountSwitchError(second.err)
require.True(t, ok, "still switches away immediately")
require.Equal(t, 1, second.calls)
require.Zero(t, second.cooled, "same request on a second account: not cooled (bare 429 scope)")
}
// 开启 overages 且积分重试失败:只额外尝试一次积分请求,随后切换,不再逐次重复积分重试。
func TestAntigravityRetryLoop_QuotaExhausted_CreditsRetryFailed_SwitchesOnce(t *testing.T) {
setupBare429Test(t)
account := bare429Account(21)
account.Type = AccountTypeOAuth
account.Extra = map[string]any{"allow_overages": true}
out := runQuotaExhaustedLoop(t, newBare429TestContext(), account, quotaExhaustedAntigravity429Body,
[]byte(`{"model":"gemini-4-argon-high","request":{}}`))
_, ok := IsAntigravityAccountSwitchError(out.err)
require.True(t, ok, "got %v", out.err)
require.Equal(t, 2, out.calls, "original request + one credits retry, no further same-account attempts")
require.Equal(t, 1, out.cooled)
}
// 不变式:没有配额耗尽关键词的裸 429 仍走默认同号重试,重试用尽后返回 429 响应。
func TestAntigravityRetryLoop_Bare429WithoutQuotaKeyword_StillRetriesSameAccount(t *testing.T) {
setupBare429Test(t)
out := runQuotaExhaustedLoop(t, newBare429TestContext(), bare429Account(31), bareAntigravity429Body, nil)
require.NoError(t, out.err)
require.NotNil(t, out.result)
require.Equal(t, http.StatusTooManyRequests, out.result.resp.StatusCode)
require.Equal(t, antigravityMaxRetries, out.calls)
require.Equal(t, 1, out.cooled)
}
// 不变式:非 Antigravity 平台账号不进入该分支(与 shouldTriggerAntigravitySmartRetry 的平台口径一致)。
func TestHandleSmartRetry_QuotaExhausted_NonAntigravityAccountContinues(t *testing.T) {
account := &Account{ID: 41, Name: "acc-41", Platform: PlatformAnthropic}
respBody := []byte(quotaExhaustedAntigravity429Body)
resp := &http.Response{StatusCode: http.StatusTooManyRequests, Header: http.Header{}, Body: io.NopCloser(bytes.NewReader(respBody))}
cooled := false
params := antigravityRetryLoopParams{
ctx: context.Background(),
prefix: "[test]",
account: account,
handleError: func(ctx context.Context, prefix string, acc *Account, statusCode int, headers http.Header, body []byte, requestedModel string, groupID int64, sessionHash string, isStickySession bool) *handleModelRateLimitResult {
cooled = true
return nil
},
}
result := (&AntigravityGatewayService{}).handleSmartRetry(params, resp, respBody, "https://ag-1.test", 0, []string{"https://ag-1.test"})
require.Equal(t, smartRetryActionContinue, result.action)
require.Nil(t, result.switchError)
require.False(t, cooled)
}
// Claude 路径的二次重试(签名/预算修正)收到切换信号时,转为 failover,而不是吞掉后返回原始 400。
func TestAntigravityRetrySwitchToFailover(t *testing.T) {
c := newBare429TestContext()
account := bare429Account(51)
switchErr := &AntigravityAccountSwitchError{OriginalAccountID: 51, RateLimitedModel: "m", IsStickySession: true}
failover := antigravityRetrySwitchToFailover(c, account, fmt.Errorf("wrapped: %w", switchErr))
require.NotNil(t, failover)
require.Equal(t, http.StatusServiceUnavailable, failover.StatusCode)
require.True(t, failover.ForceCacheBilling)
require.Nil(t, antigravityRetrySwitchToFailover(c, account, errors.New("dial tcp: timeout")))
require.Nil(t, antigravityRetrySwitchToFailover(c, account, nil))
}