perf(gateway): 单 antigravity 账号分组判定改为按需求值

三个入口(Gemini 原生、/v1/messages 的 Gemini 分支与 Claude 路径)
每个请求都会查询分组的 antigravity:forced 快照桶。纯 Gemini/Anthropic
分组的该桶恒为空,空快照按未命中处理,于是每个请求都回源 PG 并重新
发布快照,而判定结果只被 antigravity 账号的 503 原地重试与模型限流
预检查读取。

入口改为挂载延迟判定:antigravity 账号首次需要时才查询快照,同一请求
内只查一次;显式设置的 SingleAccountRetry 标记仍优先。其他平台的请求
不再触发该查询。
This commit is contained in:
feeeei committed 2026-10-20 23:49:34 +08:00
1 parent 8f2cbb53d9
commit d5dbb5c36b
9 files changed
+388 -33

No files matched your search

+6 -12
View File
@@ -339,12 +339,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
if platform == service.PlatformGemini {
fs := NewFailoverState(h.maxAccountSwitchesGemini, hasBoundSession)
// 单账号分组提前设置 SingleAccountRetry 标记,让 Service 层首次 503 就不设模型限流标记。
// 避免单账号分组收到 503 (MODEL_CAPACITY_EXHAUSTED) 时设 29s 限流,导致后续请求连续快速失败。
if h.gatewayService.IsSingleAntigravityAccountGroup(c.Request.Context(), apiKey.GroupID) {
ctx := service.WithSingleAccountRetry(c.Request.Context(), true, h.metadataBridgeEnabled())
c.Request = c.Request.WithContext(ctx)
}
// 单账号分组首次 503 就不设模型限流标记,避免设 29s 限流导致后续请求连续快速失败;
// 是否单账号分组在 antigravity 账号遇到 503 或模型限流预检查时才判定。
c.Request = c.Request.WithContext(h.gatewayService.WithSingleAntigravityAccountGroupProbe(c.Request.Context(), apiKey.GroupID))
for {
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), apiKey.GroupID, sessionKey, reqModel, fs.FailedAccountIDs, "", int64(0)) // Gemini 不使用会话限制
@@ -639,12 +636,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
}
fallbackUsed := false
// 单账号分组提前设置 SingleAccountRetry 标记,让 Service 层首次 503 就不设模型限流标记。
// 避免单账号分组收到 503 (MODEL_CAPACITY_EXHAUSTED) 时设 29s 限流,导致后续请求连续快速失败。
if h.gatewayService.IsSingleAntigravityAccountGroup(c.Request.Context(), currentAPIKey.GroupID) {
ctx := service.WithSingleAccountRetry(c.Request.Context(), true, h.metadataBridgeEnabled())
c.Request = c.Request.WithContext(ctx)
}
// 单账号分组首次 503 就不设模型限流标记,避免设 29s 限流导致后续请求连续快速失败;
// 是否单账号分组在 antigravity 账号遇到 503 或模型限流预检查时才判定。
c.Request = c.Request.WithContext(h.gatewayService.WithSingleAntigravityAccountGroupProbe(c.Request.Context(), currentAPIKey.GroupID))
// 会话槽失败释放:failover 链上每个选中的 Anthropic OAuth 账号都注册过同一会话
// (checkAndRegisterSession)。若请求最终失败(转发失败/客户端中断/换号耗尽),
@@ -158,8 +158,12 @@ func (f *fakeConcurrencyCache) CleanupStaleProcessSlots(context.Context, string)
func newTestGatewayHandler(t *testing.T, group *service.Group, accounts []*service.Account) (*GatewayHandler, func()) {
t.Helper()
return newTestGatewayHandlerWithSchedulerCache(t, group, &fakeSchedulerCache{accounts: accounts})
}
func newTestGatewayHandlerWithSchedulerCache(t *testing.T, group *service.Group, schedulerCache service.SchedulerCache) (*GatewayHandler, func()) {
t.Helper()
schedulerCache := &fakeSchedulerCache{accounts: accounts}
schedulerSnapshot := service.NewSchedulerSnapshotService(schedulerCache, nil, nil, nil, nil)
gwSvc := service.NewGatewayService(
@@ -34,11 +34,12 @@ func (u *clientCancelUpstream) Do(req *http.Request, _ string, _ int64, _ int) (
}
type geminiClientCancelFixture struct {
handler *GatewayHandler
group *service.Group
apiKey *service.APIKey
upstream *clientCancelUpstream
ctx context.Context
handler *GatewayHandler
group *service.Group
apiKey *service.APIKey
upstream *clientCancelUpstream
schedulerCache *bucketRecordingSchedulerCache
ctx context.Context
}
func newGeminiClientCancelFixture(t *testing.T) *geminiClientCancelFixture {
@@ -57,7 +58,8 @@ func newGeminiClientCancelFixture(t *testing.T) *geminiClientCancelFixture {
Priority: 1,
AccountGroups: []service.AccountGroup{{AccountID: accountID, GroupID: groupID}},
}
h, cleanup := newTestGatewayHandler(t, group, []*service.Account{account})
schedulerCache := &bucketRecordingSchedulerCache{fakeSchedulerCache: &fakeSchedulerCache{accounts: []*service.Account{account}}}
h, cleanup := newTestGatewayHandlerWithSchedulerCache(t, group, schedulerCache)
t.Cleanup(cleanup)
ctx, cancel := context.WithCancel(context.Background())
@@ -69,7 +71,7 @@ func newGeminiClientCancelFixture(t *testing.T) *geminiClientCancelFixture {
ID: 9202, UserID: 9203, GroupID: &groupID, Group: group, Status: service.StatusActive,
User: &service.User{ID: 9203, Concurrency: 10, Balance: 100},
}
return &geminiClientCancelFixture{handler: h, group: group, apiKey: apiKey, upstream: upstream, ctx: ctx}
return &geminiClientCancelFixture{handler: h, group: group, apiKey: apiKey, upstream: upstream, schedulerCache: schedulerCache, ctx: ctx}
}
// serve 经 ops 错误日志中间件执行请求,返回响应与 ops 队列中的条目数。
@@ -546,12 +546,9 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
}
fs := NewFailoverState(maxAccountSwitches, hasBoundSession)
// 单账号分组提前设置 SingleAccountRetry 标记,让 Service 层首次 503 就不设模型限流标记。
// 避免单账号分组收到 503 (MODEL_CAPACITY_EXHAUSTED) 时设 29s 限流,导致后续请求连续快速失败。
if h.gatewayService.IsSingleAntigravityAccountGroup(c.Request.Context(), apiKey.GroupID) {
ctx := service.WithSingleAccountRetry(c.Request.Context(), true, h.metadataBridgeEnabled())
c.Request = c.Request.WithContext(ctx)
}
// 单账号分组首次 503 就不设模型限流标记,避免设 29s 限流导致后续请求连续快速失败;
// 是否单账号分组在 antigravity 账号遇到 503 或模型限流预检查时才判定。
c.Request = c.Request.WithContext(h.gatewayService.WithSingleAntigravityAccountGroupProbe(c.Request.Context(), apiKey.GroupID))
for {
excludedAccountIDs := fs.FailedAccountIDs
@@ -0,0 +1,120 @@
//go:build unit
package handler
import (
"bytes"
"context"
"net/http/httptest"
"sync"
"testing"
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
// bucketRecordingSchedulerCache 记录读取过的快照桶平台。
type bucketRecordingSchedulerCache struct {
*fakeSchedulerCache
mu sync.Mutex
platforms []string
}
func (c *bucketRecordingSchedulerCache) GetSnapshot(ctx context.Context, bucket service.SchedulerBucket) ([]*service.Account, bool, error) {
c.mu.Lock()
c.platforms = append(c.platforms, bucket.Platform)
c.mu.Unlock()
return c.fakeSchedulerCache.GetSnapshot(ctx, bucket)
}
func (c *bucketRecordingSchedulerCache) readPlatforms() []string {
c.mu.Lock()
defer c.mu.Unlock()
return append([]string(nil), c.platforms...)
}
// 非 antigravity 账号的请求不读取单 antigravity 账号分组判定,选号之外不查询 antigravity 快照桶。
func TestGeminiGroupRequestsDoNotReadAntigravityBucket(t *testing.T) {
gin.SetMode(gin.TestMode)
tests := []struct {
name string
route string
path string
body string
call func(h *GatewayHandler) func(*gin.Context)
}{
{
name: "gemini native",
route: "/v1beta/models/*modelAction",
path: "/v1beta/models/gemini-2.5-flash:generateContent",
body: `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`,
call: func(h *GatewayHandler) func(*gin.Context) { return h.GeminiV1BetaModels },
},
{
name: "messages on gemini group",
route: "/v1/messages",
path: "/v1/messages",
body: `{"model":"gemini-2.5-flash","max_tokens":16,"messages":[{"role":"user","content":"hi"}]}`,
call: func(h *GatewayHandler) func(*gin.Context) { return h.Messages },
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := newGeminiClientCancelFixture(t)
f.serve(t, tt.route, tt.path, tt.body, tt.call(f.handler))
require.Equal(t, int32(1), f.upstream.calls.Load(), "请求应完成选号并到达上游")
platforms := f.schedulerCache.readPlatforms()
require.NotEmpty(t, platforms)
require.NotContains(t, platforms, service.PlatformAntigravity)
})
}
}
func TestMessagesAnthropicGroupDoesNotReadAntigravityBucket(t *testing.T) {
gin.SetMode(gin.TestMode)
groupID := int64(9400)
accountID := int64(9401)
group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive}
account := &service.Account{
ID: accountID,
Platform: service.PlatformAnthropic,
Type: service.AccountTypeAPIKey,
Credentials: map[string]any{"api_key": "test-key", "intercept_warmup_requests": true},
Status: service.StatusActive,
Schedulable: true,
Concurrency: 1,
Priority: 1,
AccountGroups: []service.AccountGroup{{AccountID: accountID, GroupID: groupID}},
}
schedulerCache := &bucketRecordingSchedulerCache{fakeSchedulerCache: &fakeSchedulerCache{accounts: []*service.Account{account}}}
h, cleanup := newTestGatewayHandlerWithSchedulerCache(t, group, schedulerCache)
t.Cleanup(cleanup)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
body := `{"model":"claude-sonnet-4-5","max_tokens":256,"messages":[{"role":"user","content":[{"type":"text","text":"Warmup"}]}]}`
req := httptest.NewRequest("POST", "/v1/messages", bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
c.Request = req.WithContext(context.WithValue(req.Context(), ctxkey.Group, group))
apiKey := &service.APIKey{
ID: 9402, UserID: 9403, GroupID: &groupID, Group: group, Status: service.StatusActive,
User: &service.User{ID: 9403, Concurrency: 10, Balance: 100},
}
c.Set(string(middleware.ContextKeyAPIKey), apiKey)
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.UserID, Concurrency: 10})
h.Messages(c)
require.Equal(t, 200, rec.Code)
selected, ok := c.Get(opsAccountIDKey)
require.True(t, ok)
require.Equal(t, accountID, selected)
platforms := schedulerCache.readPlatforms()
require.NotEmpty(t, platforms)
require.NotContains(t, platforms, service.PlatformAntigravity)
}
@@ -850,10 +850,12 @@ func sleepAntigravityBackoffWithContext(ctx context.Context, attempt int) bool {
}
}
// isSingleAccountRetry 检查 context 中是否设置了单账号退避重试标记
// isSingleAccountRetry 检查是否处于单账号退避重试模式:显式标记优先,否则使用请求挂载的延迟判定。
func isSingleAccountRetry(ctx context.Context) bool {
v, _ := SingleAccountRetryFromContext(ctx)
return v
if v, ok := SingleAccountRetryFromContext(ctx); ok {
return v
}
return singleAccountRetryProbeResult(ctx)
}
// setModelRateLimitByModelName 使用官方模型 ID 设置模型级限流
+16 -4
View File
@@ -1122,10 +1122,22 @@ func (s *GatewayService) listSchedulableAccounts(ctx context.Context, groupID *i
return accounts, useMixed, nil
}
// IsSingleAntigravityAccountGroup 检查指定分组是否只有一个 antigravity 平台的可调度账号。
// 用于 Handler 层在首次请求时提前设置 SingleAccountRetry context,
// 避免单账号分组收到 503 时错误地设置模型限流标记导致后续请求连续快速失败。
func (s *GatewayService) IsSingleAntigravityAccountGroup(ctx context.Context, groupID *int64) bool {
// WithSingleAntigravityAccountGroupProbe 为请求挂载「分组是否只有一个 antigravity 可调度账号」的延迟判定。
// 只有 antigravity 账号遇到 503 或模型限流预检查时才会查询;其他平台的请求不读取该判定。
func (s *GatewayService) WithSingleAntigravityAccountGroupProbe(ctx context.Context, groupID *int64) context.Context {
var probeGroupID *int64
if groupID != nil {
id := *groupID
probeGroupID = &id
}
return WithSingleAccountRetryProbe(ctx, func(probeCtx context.Context) bool {
return s.isSingleAntigravityAccountGroup(probeCtx, probeGroupID)
})
}
// isSingleAntigravityAccountGroup 检查指定分组是否只有一个 antigravity 平台的可调度账号。
// 单账号分组收到 503 时原地重试而不设置模型限流,避免后续请求连续快速失败。
func (s *GatewayService) isSingleAntigravityAccountGroup(ctx context.Context, groupID *int64) bool {
accounts, _, err := s.listSchedulableAccounts(ctx, groupID, PlatformAntigravity, true)
if err != nil {
return false
@@ -2,6 +2,7 @@ package service
import (
"context"
"sync"
"sync/atomic"
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
@@ -11,6 +12,15 @@ type requestMetadataContextKey struct{}
var requestMetadataKey = requestMetadataContextKey{}
type singleAccountRetryProbeContextKey struct{}
// singleAccountRetryProbe 在首次需要时判定是否进入单账号退避重试模式,同一请求内至多判定一次。
type singleAccountRetryProbe struct {
once sync.Once
check func(ctx context.Context) bool
result bool
}
type RequestMetadata struct {
IsMaxTokensOneHaikuRequest *bool
ThinkingEnabled *bool
@@ -107,6 +117,29 @@ func WithSingleAccountRetry(ctx context.Context, value bool, bridgeOldKeys bool)
})
}
// WithSingleAccountRetryProbe 挂载单账号退避重试的延迟判定;显式设置的 SingleAccountRetry 标记优先于它。
func WithSingleAccountRetryProbe(ctx context.Context, check func(ctx context.Context) bool) context.Context {
if ctx == nil || check == nil {
return ctx
}
return context.WithValue(ctx, singleAccountRetryProbeContextKey{}, &singleAccountRetryProbe{check: check})
}
func singleAccountRetryProbeResult(ctx context.Context) bool {
if ctx == nil {
return false
}
probe, _ := ctx.Value(singleAccountRetryProbeContextKey{}).(*singleAccountRetryProbe)
if probe == nil {
return false
}
// 判定结果在整个请求内复用,不能因调用时 ctx 已取消而被记成 false。
probe.once.Do(func() {
probe.result = probe.check(context.WithoutCancel(ctx))
})
return probe.result
}
func WithAccountSwitchCount(ctx context.Context, value int, bridgeOldKeys bool) context.Context {
return updateRequestMetadata(ctx, bridgeOldKeys, func(md *RequestMetadata) {
v := value
@@ -0,0 +1,191 @@
//go:build unit
package service
import (
"context"
"net/http"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
"github.com/stretchr/testify/require"
)
func TestIsSingleAccountRetry_ProbeEvaluatedLazilyOnce(t *testing.T) {
calls := 0
ctx := WithSingleAccountRetryProbe(context.Background(), func(context.Context) bool {
calls++
return true
})
require.Zero(t, calls, "挂载时不应判定")
require.True(t, isSingleAccountRetry(ctx))
require.True(t, isSingleAccountRetry(ctx))
require.Equal(t, 1, calls, "同一请求内只判定一次")
}
func TestIsSingleAccountRetry_ProbeFalse(t *testing.T) {
ctx := WithSingleAccountRetryProbe(context.Background(), func(context.Context) bool { return false })
require.False(t, isSingleAccountRetry(ctx))
}
func TestIsSingleAccountRetry_ExplicitFlagOverridesProbe(t *testing.T) {
calls := 0
probe := func(context.Context) bool {
calls++
return false
}
ctx := WithSingleAccountRetryProbe(context.Background(), probe)
ctx = WithSingleAccountRetry(ctx, true, false)
require.True(t, isSingleAccountRetry(ctx))
legacy := context.WithValue(WithSingleAccountRetryProbe(context.Background(), probe), ctxkey.SingleAccountRetry, true)
require.True(t, isSingleAccountRetry(legacy))
explicitFalse := WithSingleAccountRetry(WithSingleAccountRetryProbe(context.Background(), func(context.Context) bool {
calls++
return true
}), false, false)
require.False(t, isSingleAccountRetry(explicitFalse))
require.Zero(t, calls, "显式标记存在时不应触发判定")
}
func TestIsSingleAccountRetry_ProbeIgnoresCanceledContext(t *testing.T) {
ctx, cancel := context.WithCancel(WithSingleAccountRetryProbe(context.Background(), func(probeCtx context.Context) bool {
return probeCtx.Err() == nil
}))
cancel()
require.True(t, isSingleAccountRetry(ctx))
}
func TestIsSingleAccountRetry_ProbeSurvivesMetadataUpdates(t *testing.T) {
ctx := WithSingleAccountRetryProbe(context.Background(), func(context.Context) bool { return true })
ctx = WithAccountSwitchCount(ctx, 1, false)
ctx = WithThinkingEnabled(ctx, true, false)
require.True(t, isSingleAccountRetry(ctx))
}
// groupRecordingAccountRepo 记录单平台分组查询的分组与平台。
type groupRecordingAccountRepo struct {
*mockAccountRepoForPlatform
groupIDs []int64
platforms []string
}
func (r *groupRecordingAccountRepo) ListSchedulableByGroupIDAndPlatform(ctx context.Context, groupID int64, platform string) ([]Account, error) {
r.groupIDs = append(r.groupIDs, groupID)
r.platforms = append(r.platforms, platform)
return r.mockAccountRepoForPlatform.ListSchedulableByGroupIDAndPlatform(ctx, groupID, platform)
}
func newSingleAntigravityProbeTestService(accounts ...Account) (*GatewayService, *groupRecordingAccountRepo) {
repo := &groupRecordingAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{accounts: accounts}}
return &GatewayService{accountRepo: repo}, repo
}
func probeTestAccount(id int64, platform string) Account {
return Account{ID: id, Platform: platform, Status: StatusActive, Schedulable: true}
}
func TestWithSingleAntigravityAccountGroupProbe_QueriesOnlyWhenRead(t *testing.T) {
svc, repo := newSingleAntigravityProbeTestService(probeTestAccount(1, PlatformAntigravity))
groupID := int64(42)
ctx := svc.WithSingleAntigravityAccountGroupProbe(context.Background(), &groupID)
require.Empty(t, repo.groupIDs, "挂载时不应查询账号")
require.True(t, isSingleAccountRetry(ctx))
require.True(t, isSingleAccountRetry(ctx))
require.Equal(t, []int64{42}, repo.groupIDs)
require.Equal(t, []string{PlatformAntigravity}, repo.platforms)
}
func TestWithSingleAntigravityAccountGroupProbe_UsesGroupAtMountTime(t *testing.T) {
svc, repo := newSingleAntigravityProbeTestService(probeTestAccount(1, PlatformAntigravity))
groupID := int64(42)
ctx := svc.WithSingleAntigravityAccountGroupProbe(context.Background(), &groupID)
groupID = 99
require.True(t, isSingleAccountRetry(ctx))
require.Equal(t, []int64{42}, repo.groupIDs)
}
func TestWithSingleAntigravityAccountGroupProbe_CountsOnlyAntigravityAccounts(t *testing.T) {
groupID := int64(42)
tests := []struct {
name string
accounts []Account
want bool
}{
{name: "no antigravity accounts", accounts: []Account{probeTestAccount(1, PlatformGemini)}, want: false},
{name: "single antigravity account", accounts: []Account{probeTestAccount(1, PlatformAntigravity), probeTestAccount(2, PlatformGemini)}, want: true},
{name: "two antigravity accounts", accounts: []Account{probeTestAccount(1, PlatformAntigravity), probeTestAccount(2, PlatformAntigravity)}, want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
svc, _ := newSingleAntigravityProbeTestService(tt.accounts...)
ctx := svc.WithSingleAntigravityAccountGroupProbe(context.Background(), &groupID)
require.Equal(t, tt.want, isSingleAccountRetry(ctx))
})
}
}
func runRateLimitedPreCheckWithProbe(t *testing.T, single bool) (*antigravityRetryLoopResult, *recordingOKUpstream, error) {
t.Helper()
upstream := &recordingOKUpstream{}
account := &Account{
ID: 30,
Type: AccountTypeOAuth,
Platform: PlatformAntigravity,
Schedulable: true,
Status: StatusActive,
Concurrency: 1,
Extra: map[string]any{
modelRateLimitsKey: map[string]any{
"claude-sonnet-4-5": map[string]any{
"rate_limit_reset_at": time.Now().Add(30 * time.Second).Format(time.RFC3339),
},
},
},
}
ctx := WithSingleAccountRetryProbe(context.Background(), func(context.Context) bool { return single })
svc := &AntigravityGatewayService{}
result, err := svc.antigravityRetryLoop(antigravityRetryLoopParams{
ctx: ctx,
prefix: "[test]",
account: account,
accessToken: "token",
action: "generateContent",
body: []byte(`{"input":"test"}`),
httpUpstream: upstream,
requestedModel: "claude-sonnet-4-5",
handleError: func(ctx context.Context, prefix string, account *Account, statusCode int, headers http.Header, body []byte, requestedModel string, groupID int64, sessionHash string, isStickySession bool) *handleModelRateLimitResult {
return nil
},
})
return result, upstream, err
}
func TestAntigravityRetryLoop_PreCheck_ProbeSingleAccount_SkipsRateLimit(t *testing.T) {
result, upstream, err := runRateLimitedPreCheckWithProbe(t, true)
require.NoError(t, err)
require.NotNil(t, result)
require.NotNil(t, result.resp)
require.Equal(t, http.StatusOK, result.resp.StatusCode)
require.Equal(t, 1, upstream.calls)
}
func TestAntigravityRetryLoop_PreCheck_ProbeMultiAccount_SwitchesOnRateLimit(t *testing.T) {
result, upstream, err := runRateLimitedPreCheckWithProbe(t, false)
require.Nil(t, result)
var switchErr *AntigravityAccountSwitchError
require.ErrorAs(t, err, &switchErr)
require.Equal(t, "claude-sonnet-4-5", switchErr.RateLimitedModel)
require.Zero(t, upstream.calls)
}