Merge pull request #9236 from r266-tech/codex/antigravity-retry-after

fix(antigravity): honor Retry-After for upstream 429s
This commit is contained in:
Wesley Liddick authored and GitHub committed 2026-12-04 15:20:47 +08:00
commit 484625a239
7 files changed
+271 -85

No files matched your search

@@ -3,6 +3,7 @@ package service
import (
"context"
"net/http"
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
"github.com/gin-gonic/gin"
@@ -19,14 +20,38 @@ const antigravityBare429CooledAccountKey = "antigravity_bare429_cooled_account_i
// 1.8 MB request got it on four accounts in a row while those accounts kept
// serving other requests). A 429 that names a reason or a reset time is
// Google's statement about the account and is not bare.
func isBareAntigravity429(statusCode int, body []byte) bool {
func isBareAntigravity429(statusCode int, headers http.Header, body []byte) bool {
if statusCode != http.StatusTooManyRequests {
return false
}
if gjson.GetBytes(body, "error.details").Exists() {
return false
}
return ParseGeminiRateLimitResetTime(body) == nil
return ParseGeminiRateLimitResetTime(body) == nil && antigravity429RetryAt(statusCode, headers, nil).IsZero()
}
// antigravity429RetryAt uses an explicit Retry-After and a later reset from
// the response body when present. A response without a usable header follows
// the existing body-only retry rules.
func antigravity429RetryAt(statusCode int, headers http.Header, body []byte) time.Time {
if statusCode != http.StatusTooManyRequests {
return time.Time{}
}
now := time.Now()
retryAt := parseRetryAfterResetTime(headers, now)
if retryAt == nil || !retryAt.After(now) {
return time.Time{}
}
if bodyReset := ParseGeminiRateLimitResetTime(body); bodyReset != nil {
if bodyDeadline := time.Unix(*bodyReset, 0); bodyDeadline.After(*retryAt) {
return bodyDeadline
}
}
// Model cooldowns are stored at second precision. Preserve the full delay.
if retryAt.Nanosecond() != 0 {
return retryAt.Truncate(time.Second).Add(time.Second)
}
return *retryAt
}
// claimBare429Cooldown reports whether this request may cool accountID for a
@@ -59,7 +84,7 @@ func (s *AntigravityGatewayService) handleUpstreamErrorAfterRetryLoop(
requestedModel string,
groupID int64, sessionHash string, isStickySession bool,
) *handleModelRateLimitResult {
if isBareAntigravity429(statusCode, body) && !claimBare429Cooldown(c, account.ID) {
if isBareAntigravity429(statusCode, headers, body) && !claimBare429Cooldown(c, account.ID) {
logger.LegacyPrintf("service.antigravity_gateway", "%s status=%d bare_429_cooldown_skipped account=%d (after retry loop)", prefix, statusCode, account.ID)
return nil
}
@@ -127,10 +127,7 @@ func (s *AntigravityGatewayService) Forward(ctx context.Context, c *gin.Context,
if err != nil {
// 检查是否是账号切换信号,转换为 UpstreamFailoverError 让 Handler 切换账号
if switchErr, ok := IsAntigravityAccountSwitchError(err); ok {
return nil, &UpstreamFailoverError{
StatusCode: http.StatusServiceUnavailable,
ForceCacheBilling: switchErr.IsStickySession,
}
return nil, switchErr.failoverError()
}
// 区分客户端取消和真正的上游失败,返回更准确的错误消息
if c.Request.Context().Err() != nil {
@@ -420,10 +420,7 @@ func antigravityCompatProxyURL(account *Account) string {
func (s *AntigravityGatewayService) handleAntigravityCompatTransportError(c *gin.Context, err error) error {
if switchErr, ok := IsAntigravityAccountSwitchError(err); ok {
return &UpstreamFailoverError{
StatusCode: http.StatusServiceUnavailable,
ForceCacheBilling: switchErr.IsStickySession,
}
return switchErr.failoverError()
}
if c.Request.Context().Err() != nil {
return s.writeAntigravityCompatError(c, antigravityStatusClientClosed, "client_disconnected", "Client disconnected before upstream response")
@@ -178,10 +178,7 @@ func (s *AntigravityGatewayService) ForwardGemini(ctx context.Context, c *gin.Co
if err != nil {
// 检查是否是账号切换信号,转换为 UpstreamFailoverError 让 Handler 切换账号
if switchErr, ok := IsAntigravityAccountSwitchError(err); ok {
return nil, &UpstreamFailoverError{
StatusCode: http.StatusServiceUnavailable,
ForceCacheBilling: switchErr.IsStickySession,
}
return nil, switchErr.failoverError()
}
// 区分客户端取消和真正的上游失败,返回更准确的错误消息
if c.Request.Context().Err() != nil {
@@ -307,21 +304,8 @@ func (s *AntigravityGatewayService) ForwardGemini(ctx context.Context, c *gin.Co
}
}
} else {
if switchErr, ok := IsAntigravityAccountSwitchError(retryErr); ok {
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 nil, &UpstreamFailoverError{
StatusCode: http.StatusServiceUnavailable,
ForceCacheBilling: switchErr.IsStickySession,
}
if failover := antigravityRetrySwitchToFailover(c, account, retryErr); failover != nil {
return nil, failover
}
appendOpsUpstreamError(c, OpsUpstreamErrorEvent{
ProxyID: opsUpstreamProxyID(account),
@@ -101,8 +101,16 @@ type smartRetryResult struct {
// handleSmartRetry 处理 OAuth 账号的智能重试逻辑
// 将 429/503 限流处理逻辑抽取为独立函数,减少 antigravityRetryLoop 的复杂度
func (s *AntigravityGatewayService) handleSmartRetry(p antigravityRetryLoopParams, resp *http.Response, respBody []byte, baseURL string, urlIdx int, availableURLs []string) *smartRetryResult {
retryAfter := time.Duration(0)
if p.account.Platform == PlatformAntigravity {
retryAfter = time.Until(antigravity429RetryAt(resp.StatusCode, resp.Header, respBody))
}
if retryAfter >= antigravityRateLimitThreshold {
return s.cooldownAndSwitchAntigravity429(p, resp, respBody, true)
}
// "Resource has been exhausted" 是 URL 级别限流,切换 URL(仅 429)
if resp.StatusCode == http.StatusTooManyRequests && isURLLevelRateLimit(respBody) && urlIdx < len(availableURLs)-1 {
if resp.StatusCode == http.StatusTooManyRequests && retryAfter <= 0 && isURLLevelRateLimit(respBody) && urlIdx < len(availableURLs)-1 {
logger.LegacyPrintf("service.antigravity_gateway", "%s URL fallback (429): %s -> %s", p.prefix, baseURL, availableURLs[urlIdx+1])
return &smartRetryResult{action: smartRetryActionContinueURL}
}
@@ -118,6 +126,7 @@ func (s *AntigravityGatewayService) handleSmartRetry(p antigravityRetryLoopParam
// AI Credits 超量请求:
// 仅在上游明确返回免费配额耗尽时才允许切换到 credits。
if resp.StatusCode == http.StatusTooManyRequests &&
retryAfter <= 0 &&
category == antigravity429QuotaExhausted &&
p.account.IsOveragesEnabled() &&
!p.account.isCreditsExhausted() {
@@ -136,31 +145,7 @@ func (s *AntigravityGatewayService) handleSmartRetry(p antigravityRetryLoopParam
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,
},
}
return s.cooldownAndSwitchAntigravity429(p, resp, respBody, false)
}
// 情况1: retryDelay >= 阈值,限流模型并切换账号
@@ -228,6 +213,9 @@ func (s *AntigravityGatewayService) handleSmartRetry(p antigravityRetryLoopParam
}
}
if retryAfter > waitDuration {
waitDuration = retryAfter
}
for attempt := 1; attempt <= maxAttempts; attempt++ {
log.Printf("%s status=%d oauth_smart_retry attempt=%d/%d delay=%v model=%s account=%d",
p.prefix, resp.StatusCode, attempt, maxAttempts, waitDuration, modelName, p.account.ID)
@@ -283,6 +271,9 @@ func (s *AntigravityGatewayService) handleSmartRetry(p antigravityRetryLoopParam
lastRetryBody, _ = io.ReadAll(io.LimitReader(retryResp.Body, 8<<10))
_ = retryResp.Body.Close()
}
if !antigravity429RetryAt(retryResp.StatusCode, retryResp.Header, nil).IsZero() {
return s.cooldownAndSwitchAntigravity429(p, retryResp, lastRetryBody, true)
}
// Honor updated reset information even on the final attempt: it also
// determines the cooldown below. A long delay requests model limiting
@@ -366,6 +357,49 @@ func (s *AntigravityGatewayService) handleSmartRetry(p antigravityRetryLoopParam
return &smartRetryResult{action: smartRetryActionContinue}
}
func (s *AntigravityGatewayService) cooldownAndSwitchAntigravity429(
p antigravityRetryLoopParams, resp *http.Response, respBody []byte, explicitRetryAfter bool,
) *smartRetryResult {
reason := "quota_exhausted"
switchErr := &AntigravityAccountSwitchError{
OriginalAccountID: p.account.ID,
RateLimitedModel: p.requestedModel,
IsStickySession: p.isStickySession,
}
if explicitRetryAfter {
reason = "retry_after"
// Keep the actual 429 so selection exhaustion never treats it as a
// capacity 503 and retries the single account before its deadline.
switchErr.upstream429 = &UpstreamFailoverError{
StatusCode: resp.StatusCode,
ResponseBody: respBody,
ResponseHeaders: resp.Header.Clone(),
ForceCacheBilling: p.isStickySession,
}
}
logger.LegacyPrintf("service.antigravity_gateway", "%s status=%d %s account=%d body=%s (cool down and switch account, skip same-account retries)",
p.prefix, resp.StatusCode, reason, p.account.ID, truncateForLog(respBody, 200))
// Preserve the upstream 429 in the diagnostic event when the caller switches accounts.
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: switchErr,
}
}
// handleSingleAccountRetryInPlace 单账号 503 退避重试的原地重试逻辑。
//
// 在多账号场景下,收到 503 + 长 retryDelay(≥ 7s)时会设置模型限流 + 切换账号;
@@ -459,6 +493,9 @@ func (s *AntigravityGatewayService) handleSingleAccountRetryInPlace(
lastRetryResp = retryResp
lastRetryBody, _ = io.ReadAll(io.LimitReader(retryResp.Body, 8<<10))
_ = retryResp.Body.Close()
if !antigravity429RetryAt(retryResp.StatusCode, retryResp.Header, nil).IsZero() {
return s.cooldownAndSwitchAntigravity429(p, retryResp, lastRetryBody, true)
}
// 解析新的重试信息,更新下次等待时间
if attempt < antigravitySingleAccountSmartRetryMaxAttempts && lastRetryBody != nil {
@@ -595,7 +632,7 @@ urlFallbackLoop:
}
if attempt < antigravityMaxRetries {
logger.LegacyPrintf("service.antigravity_gateway", "%s status=request_failed retry=%d/%d error=%v", p.prefix, attempt, antigravityMaxRetries, err)
if !sleepAntigravityBackoffWithContext(p.ctx, attempt) {
if !sleepAntigravityBackoffWithContext(p.ctx, attempt, 0) {
logger.LegacyPrintf("service.antigravity_gateway", "%s status=context_canceled_during_backoff", p.prefix)
return nil, p.ctx.Err()
}
@@ -671,7 +708,11 @@ urlFallbackLoop:
Detail: getUpstreamDetail(respBody),
})
logger.LegacyPrintf("service.antigravity_gateway", "%s status=%d retry=%d/%d body=%s", p.prefix, resp.StatusCode, attempt, antigravityMaxRetries, truncateForLog(respBody, 200))
if !sleepAntigravityBackoffWithContext(p.ctx, attempt) {
minimumDelay := time.Duration(0)
if p.account.Platform == PlatformAntigravity {
minimumDelay = time.Until(antigravity429RetryAt(resp.StatusCode, resp.Header, respBody))
}
if !sleepAntigravityBackoffWithContext(p.ctx, attempt, minimumDelay) {
logger.LegacyPrintf("service.antigravity_gateway", "%s status=context_canceled_during_backoff", p.prefix)
return nil, p.ctx.Err()
}
@@ -708,7 +749,7 @@ urlFallbackLoop:
Detail: getUpstreamDetail(respBody),
})
logger.LegacyPrintf("service.antigravity_gateway", "%s status=%d retry=%d/%d body=%s", p.prefix, resp.StatusCode, attempt, antigravityMaxRetries, truncateForLog(respBody, 500))
if !sleepAntigravityBackoffWithContext(p.ctx, attempt) {
if !sleepAntigravityBackoffWithContext(p.ctx, attempt, 0) {
logger.LegacyPrintf("service.antigravity_gateway", "%s status=context_canceled_during_backoff", p.prefix)
return nil, p.ctx.Err()
}
@@ -862,7 +903,7 @@ func tempUnscheduleEmptyResponse(ctx context.Context, repo AccountRepository, ac
// sleepAntigravityBackoffWithContext 带 context 取消检查的退避等待
// 返回 true 表示正常完成等待,false 表示 context 已取消
func sleepAntigravityBackoffWithContext(ctx context.Context, attempt int) bool {
func sleepAntigravityBackoffWithContext(ctx context.Context, attempt int, minimumDelay time.Duration) bool {
delay := antigravityRetryBaseDelay * time.Duration(1<<uint(attempt-1))
if delay > antigravityRetryMaxDelay {
delay = antigravityRetryMaxDelay
@@ -872,8 +913,8 @@ func sleepAntigravityBackoffWithContext(ctx context.Context, attempt int) bool {
r := mathrand.New(mathrand.NewSource(time.Now().UnixNano()))
jitter := time.Duration(float64(delay) * 0.2 * (r.Float64()*2 - 1))
sleepFor := delay + jitter
if sleepFor < 0 {
sleepFor = 0
if sleepFor < minimumDelay {
sleepFor = minimumDelay
}
timer := time.NewTimer(sleepFor)
@@ -937,7 +978,7 @@ func (s *AntigravityGatewayService) setAntigravityModelRateLimits(ctx context.Co
// 无原因、无重置时间的裸 429 每个请求最多冷却一个账号:它更可能由请求本身触发,
// 不能让同一个请求把它碰到的每个账号都冷却掉。
func (s *AntigravityGatewayService) applyAntigravity429Cooldown(p antigravityRetryLoopParams, resp *http.Response, respBody []byte) {
if isBareAntigravity429(resp.StatusCode, respBody) && !claimBare429Cooldown(p.c, p.account.ID) {
if isBareAntigravity429(resp.StatusCode, resp.Header, 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
}
@@ -1135,6 +1176,7 @@ type handleModelRateLimitParams struct {
prefix string
account *Account
statusCode int
retryAt time.Time
body []byte
cache GatewayCache
groupID int64
@@ -1176,7 +1218,7 @@ func (s *AntigravityGatewayService) handleModelRateLimit(p *handleModelRateLimit
}
// RATE_LIMIT_EXCEEDED: < antigravityRateLimitThreshold: 等待后重试
if info.RetryDelay < antigravityRateLimitThreshold {
if info.RetryDelay < antigravityRateLimitThreshold && p.retryAt.IsZero() {
logger.LegacyPrintf("service.antigravity_gateway", "%s status=%d model_rate_limit_wait model=%s wait=%v",
p.prefix, p.statusCode, info.ModelName, info.RetryDelay)
return &handleModelRateLimitResult{
@@ -1202,6 +1244,9 @@ func (s *AntigravityGatewayService) handleModelRateLimit(p *handleModelRateLimit
// setModelRateLimitAndClearSession 设置模型限流并清除粘性会话
func (s *AntigravityGatewayService) setModelRateLimitAndClearSession(p *handleModelRateLimitParams, info *antigravitySmartRetryInfo) {
resetAt := time.Now().Add(info.RetryDelay)
if p.retryAt.After(resetAt) {
resetAt = p.retryAt
}
logger.LegacyPrintf("service.antigravity_gateway", "%s status=%d model_rate_limited model=%s account=%d reset_in=%v",
p.prefix, p.statusCode, info.ModelName, p.account.ID, info.RetryDelay)
@@ -1251,12 +1296,17 @@ func (s *AntigravityGatewayService) handleUpstreamError(
if !account.ShouldHandleErrorCode(statusCode) {
return nil
}
retryAt := time.Time{}
if account.Platform == PlatformAntigravity {
retryAt = antigravity429RetryAt(statusCode, headers, body)
}
// 模型级限流处理(优先)
result := s.handleModelRateLimit(&handleModelRateLimitParams{
ctx: ctx,
prefix: prefix,
account: account,
statusCode: statusCode,
retryAt: retryAt,
body: body,
cache: s.cache,
groupID: groupID,
@@ -1279,8 +1329,14 @@ func (s *AntigravityGatewayService) handleUpstreamError(
logger.LegacyPrintf("service.antigravity_gateway", "[Antigravity-Debug] 429 response body: %s", truncateString(string(body), maxBytes))
}
resetAt := ParseGeminiRateLimitResetTime(body)
defaultDur := s.getDefaultRateLimitDuration()
resetAt := retryAt
if resetAt.IsZero() {
if bodyReset := ParseGeminiRateLimitResetTime(body); bodyReset != nil {
resetAt = time.Unix(*bodyReset, 0)
} else {
resetAt = time.Now().Add(s.getDefaultRateLimitDuration())
}
}
// 尝试解析模型 key 并设置模型级限流
//
@@ -1294,21 +1350,19 @@ func (s *AntigravityGatewayService) handleUpstreamError(
modelKey = resolveAntigravityModelKey(requestedModel)
}
if modelKey != "" {
ra := s.resolveResetTime(resetAt, defaultDur)
if !s.setAntigravityModelRateLimits(ctx, s.accountRepo, account, modelKey, prefix, statusCode, ra, false) {
if !s.setAntigravityModelRateLimits(ctx, s.accountRepo, account, modelKey, prefix, statusCode, resetAt, false) {
logger.LegacyPrintf("service.antigravity_gateway", "%s status=429 model_rate_limit_set_failed model=%s", prefix, modelKey)
} else {
logger.LegacyPrintf("service.antigravity_gateway", "%s status=429 model_rate_limited model=%s account=%d reset_at=%v reset_in=%v",
prefix, modelKey, account.ID, ra.Format("15:04:05"), time.Until(ra).Truncate(time.Second))
prefix, modelKey, account.ID, resetAt.Format("15:04:05"), time.Until(resetAt).Truncate(time.Second))
}
return nil
}
// 无法解析模型 key,兜底为账号级限流
ra := s.resolveResetTime(resetAt, defaultDur)
logger.LegacyPrintf("service.antigravity_gateway", "%s status=429 rate_limited account=%d reset_at=%v reset_in=%v (fallback)",
prefix, account.ID, ra.Format("15:04:05"), time.Until(ra).Truncate(time.Second))
if err := s.accountRepo.SetRateLimited(ctx, account.ID, ra); err != nil {
prefix, account.ID, resetAt.Format("15:04:05"), time.Until(resetAt).Truncate(time.Second))
if err := s.accountRepo.SetRateLimited(ctx, account.ID, resetAt); err != nil {
logger.LegacyPrintf("service.antigravity_gateway", "%s status=429 rate_limit_set_failed account=%d error=%v", prefix, account.ID, err)
}
return nil
@@ -1335,11 +1389,3 @@ func (s *AntigravityGatewayService) getDefaultRateLimitDuration() time.Duration
}
return defaultDur
}
// resolveResetTime 根据解析的重置时间或默认时长计算重置时间点
func (s *AntigravityGatewayService) resolveResetTime(resetAt *int64, defaultDur time.Duration) time.Time {
if resetAt != nil {
return time.Unix(*resetAt, 0)
}
return time.Now().Add(defaultDur)
}
@@ -94,6 +94,7 @@ type AntigravityAccountSwitchError struct {
OriginalAccountID int64
RateLimitedModel string
IsStickySession bool // 是否为粘性会话切换(决定是否缓存计费)
upstream429 *UpstreamFailoverError
}
func (e *AntigravityAccountSwitchError) Error() string {
@@ -101,6 +102,16 @@ func (e *AntigravityAccountSwitchError) Error() string {
e.OriginalAccountID, e.RateLimitedModel)
}
func (e *AntigravityAccountSwitchError) failoverError() *UpstreamFailoverError {
if e.upstream429 != nil {
return e.upstream429
}
return &UpstreamFailoverError{
StatusCode: http.StatusServiceUnavailable,
ForceCacheBilling: e.IsStickySession,
}
}
// IsAntigravityAccountSwitchError 检查错误是否为账号切换信号
func IsAntigravityAccountSwitchError(err error) (*AntigravityAccountSwitchError, bool) {
var switchErr *AntigravityAccountSwitchError
@@ -118,20 +129,18 @@ func antigravityRetrySwitchToFailover(c *gin.Context, account *Account, retryErr
if !ok {
return nil
}
failover := switchErr.failoverError()
appendOpsUpstreamError(c, OpsUpstreamErrorEvent{
ProxyID: opsUpstreamProxyID(account),
ProxyName: opsUpstreamProxyName(account),
Platform: account.Platform,
AccountID: account.ID,
AccountName: account.Name,
UpstreamStatusCode: http.StatusServiceUnavailable,
UpstreamStatusCode: failover.StatusCode,
Kind: "failover",
Message: sanitizeUpstreamErrorMessage(retryErr.Error()),
})
return &UpstreamFailoverError{
StatusCode: http.StatusServiceUnavailable,
ForceCacheBilling: switchErr.IsStickySession,
}
return failover
}
// PromptTooLongError 表示上游明确返回 prompt too long
@@ -272,6 +281,9 @@ func (s *AntigravityGatewayService) handleAntigravityModelRateLimitBeforePolicy(
rateLimitDuration = antigravityDefaultRateLimitDuration
}
resetAt := time.Now().Add(rateLimitDuration)
if retryAt := antigravity429RetryAt(statusCode, headers, respBody); retryAt.After(resetAt) {
resetAt = retryAt
}
if !s.setAntigravityModelRateLimits(p.ctx, p.accountRepo, p.account, modelName, p.prefix, statusCode, resetAt, false) {
return false
}
@@ -10,11 +10,106 @@ import (
"net/http"
"strings"
"testing"
"testing/synctest"
"time"
"github.com/stretchr/testify/require"
)
func TestAntigravityRetryLoop_ExplicitRetryAfter(t *testing.T) {
setupBare429Test(t)
t.Setenv(antigravityFallbackSecondsEnv, "60")
tests := []struct {
name string
retryAfter string
body string
wantCooldown time.Duration
wantRetryWait time.Duration
}{
{
name: "delta-seconds", retryAfter: "120",
body: bareAntigravity429Body, wantCooldown: 120 * time.Second,
},
{
name: "http-date",
body: bareAntigravity429Body, wantCooldown: 120 * time.Second,
},
{
name: "later-body-reset", retryAfter: "3",
body: string(buildGeminiRateLimitBody("180s")), wantCooldown: 180 * time.Second,
},
{
name: "short-delay", retryAfter: "3",
body: bareAntigravity429Body, wantRetryWait: 3 * time.Second,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
start := time.Now()
retryAfter := test.retryAfter
if retryAfter == "" {
retryAfter = start.Add(test.wantCooldown).UTC().Format(http.TimeFormat)
}
upstream := &queuedHTTPUpstreamStub{
responses: []*http.Response{{
StatusCode: http.StatusTooManyRequests,
Header: http.Header{"Retry-After": []string{retryAfter}},
Body: io.NopCloser(strings.NewReader(test.body)),
}},
}
var attempts []time.Time
upstream.onCall = func(_ *http.Request, _ *queuedHTTPUpstreamStub) {
attempts = append(attempts, time.Now())
}
if test.wantRetryWait > 0 {
upstream.responses = append(upstream.responses, &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader("ok")),
})
}
repo := &stubAntigravityAccountRepo{}
svc := &AntigravityGatewayService{accountRepo: repo}
account := bare429Account(13)
account.Type = AccountTypeOAuth
c := newBare429TestContext()
require.True(t, claimBare429Cooldown(c, 7))
result, err := svc.antigravityRetryLoop(antigravityRetryLoopParams{
ctx: context.Background(), prefix: "[test]", account: account,
accessToken: "synthetic-test-token", action: "generateContent", body: []byte(`{"input":"test"}`),
httpUpstream: upstream, accountRepo: repo, handleError: svc.handleUpstreamError,
requestedModel: "claude-sonnet-4-5", isStickySession: true, c: c,
})
if test.wantRetryWait > 0 {
require.NoError(t, err)
require.NotNil(t, result.resp)
defer func() { _ = result.resp.Body.Close() }()
require.Equal(t, http.StatusOK, result.resp.StatusCode)
require.Len(t, attempts, 2)
require.Equal(t, test.wantRetryWait, attempts[1].Sub(attempts[0]))
require.Empty(t, repo.modelRateLimitCalls)
return
}
require.Len(t, attempts, 1, "a long Retry-After must not be retried in place")
require.Nil(t, result)
switchErr, ok := IsAntigravityAccountSwitchError(err)
require.True(t, ok, "unexpected error: %v", err)
failover := switchErr.failoverError()
require.Equal(t, http.StatusTooManyRequests, failover.StatusCode)
require.Equal(t, retryAfter, failover.ResponseHeaders.Get("Retry-After"))
require.Equal(t, test.body, string(failover.ResponseBody))
require.True(t, failover.ForceCacheBilling)
require.Len(t, repo.modelRateLimitCalls, 1)
require.Equal(t, "claude-sonnet-4-5", repo.modelRateLimitCalls[0].modelKey)
require.Equal(t, test.wantCooldown, repo.modelRateLimitCalls[0].resetAt.Sub(start))
})
})
}
}
func TestHandleSmartRetry_LastRetryInfoControlsCooldown(t *testing.T) {
for _, delay := range []time.Duration{5 * time.Second, 60 * time.Second} {
t.Run(delay.String(), func(t *testing.T) {
@@ -48,3 +143,33 @@ func TestHandleSmartRetry_LastRetryInfoControlsCooldown(t *testing.T) {
})
}
}
func TestHandleSmartRetry_FinalRetryAfterControlsCooldown(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
first := []byte(`{"error":{"status":"RESOURCE_EXHAUSTED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"RATE_LIMIT_EXCEEDED","metadata":{"model":"claude-sonnet-4-5"}},{"@type":"type.googleapis.com/google.rpc.RetryInfo","retryDelay":"1s"}]}}`)
upstream := &queuedHTTPUpstreamStub{
responses: []*http.Response{{
StatusCode: http.StatusTooManyRequests,
Header: http.Header{"Retry-After": []string{"120"}},
Body: io.NopCloser(strings.NewReader(bareAntigravity429Body)),
}},
}
repo := &stubAntigravityAccountRepo{}
svc := &AntigravityGatewayService{accountRepo: repo}
params := antigravityRetryLoopParams{
ctx: context.Background(), prefix: "[test]", account: bare429Account(13),
accessToken: "synthetic-test-token", action: "generateContent", body: []byte(`{"input":"test"}`),
httpUpstream: upstream, accountRepo: repo, handleError: svc.handleUpstreamError,
requestedModel: "claude-sonnet-4-5",
}
resp := &http.Response{StatusCode: http.StatusTooManyRequests, Body: io.NopCloser(bytes.NewReader(first))}
defer func() { _ = resp.Body.Close() }()
start := time.Now()
result := svc.handleSmartRetry(params, resp, first, "https://ag-1.test", 0, []string{"https://ag-1.test"})
require.Equal(t, 1, upstream.callCount)
require.NotNil(t, result.switchError)
require.Equal(t, http.StatusTooManyRequests, result.switchError.failoverError().StatusCode)
require.Len(t, repo.modelRateLimitCalls, 1)
require.Equal(t, start.Add(121*time.Second), repo.modelRateLimitCalls[0].resetAt)
})
}