mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-04 15:50:18 +00:00
fix(gateway): stop one bad request from cooling every account it touches
A gemini-3.8-flash request whose tools made the model end with MALFORMED_FUNCTION_CALL produced an empty compat stream on every account. The empty-stream error is retryable on the same account, so after three retries the failover loop temp-unscheduled the account and moved on; the same request then cooled the next account, and the next. One request took three shared Antigravity accounts offline and every customer on those groups got "No available accounts" until the cooldowns expired. Two changes: - The streaming processor records MALFORMED_FUNCTION_CALL. An empty compat stream that ended that way is marked RequestScopedTransient: still retried (model output varies), but it no longer cools the account. Once keepalive has committed the response, the SSE error says malformed_function_call instead of empty_stream. - The failover loop cools at most one account per request. When the same retryable error follows a request to another account, the request is the likely cause; the loop still excludes and switches, and logs gateway.failover_temp_unschedule_skipped. An unhealthy account is still cooled by the next request that reaches it first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ee58c0013c
commit
4ce6281fc0
5 files changed
+191
-8
No files matched your search
@@ -131,6 +131,15 @@ type FailoverState struct {
|
||||
ForceCacheBilling bool
|
||||
hasBoundSession bool
|
||||
|
||||
// tempUnscheduledAccountID is the one account this request has cooled down
|
||||
// after exhausting same-account retries (0 = none yet). A request may cool
|
||||
// at most one account: when the same retryable error follows the request to
|
||||
// the next account, the request is the likely cause, and cooling every
|
||||
// account it touches would take a whole shared pool offline for one bad
|
||||
// request. Accounts that are really unhealthy are still cooled by the
|
||||
// next request that lands on them first.
|
||||
tempUnscheduledAccountID int64
|
||||
|
||||
// profitVetoedAccountIDs 记录被分组利润门终检否决的账号,是 FailedAccountIDs
|
||||
// 的子集。之所以单独维护:HandleSelectionExhausted 的 503 退避分支会清空
|
||||
// FailedAccountIDs,而利润否决在同一请求内的判定不会改变(下游倍率 D 已在
|
||||
@@ -233,9 +242,20 @@ func (s *FailoverState) HandleFailoverError(
|
||||
return FailoverContinue
|
||||
}
|
||||
|
||||
// 同账号重试用尽,执行临时封禁
|
||||
// 同账号重试用尽,执行临时封禁(每个请求最多封禁一个账号)
|
||||
if failoverErr.RetryableOnSameAccount {
|
||||
gatewayService.TempUnscheduleRetryableError(ctx, accountID, failoverErr)
|
||||
if s.tempUnscheduledAccountID == 0 || s.tempUnscheduledAccountID == accountID {
|
||||
if !failoverErr.RequestScopedTransient {
|
||||
s.tempUnscheduledAccountID = accountID
|
||||
}
|
||||
gatewayService.TempUnscheduleRetryableError(ctx, accountID, failoverErr)
|
||||
} else {
|
||||
logger.FromContext(ctx).Warn("gateway.failover_temp_unschedule_skipped",
|
||||
zap.Int64("account_id", accountID),
|
||||
zap.Int64("already_unscheduled_account_id", s.tempUnscheduledAccountID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 加入失败列表
|
||||
|
||||
@@ -1040,3 +1040,59 @@ func TestFailoverClientGone(t *testing.T) {
|
||||
require.False(t, failoverClientGone(nil))
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// HandleFailoverError — 每个请求最多封禁一个账号
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func exhaustSameAccount(fs *FailoverState, mock *mockTempUnscheduler, accountID int64, err *service.UpstreamFailoverError) FailoverAction {
|
||||
var action FailoverAction
|
||||
for i := 0; i <= maxSameAccountRetries; i++ {
|
||||
action = fs.HandleFailoverError(context.Background(), mock, accountID, service.PlatformAntigravity, maxSameAccountRetries, err)
|
||||
}
|
||||
return action
|
||||
}
|
||||
|
||||
func TestHandleFailoverError_TempUnscheduleAtMostOneAccountPerRequest(t *testing.T) {
|
||||
t.Run("同一可重试错误跟随请求_只封禁第一个账号", func(t *testing.T) {
|
||||
mock := &mockTempUnscheduler{}
|
||||
fs := NewFailoverState(10, false)
|
||||
err := newTestFailoverErr(http.StatusBadGateway, true, false)
|
||||
|
||||
for _, id := range []int64{2, 7, 6} {
|
||||
require.Equal(t, FailoverContinue, exhaustSameAccount(fs, mock, id, err))
|
||||
}
|
||||
|
||||
require.Len(t, mock.calls, 1, "一个坏请求不应把它经过的每个账号都封禁")
|
||||
require.Equal(t, int64(2), mock.calls[0].accountID)
|
||||
require.Len(t, fs.FailedAccountIDs, 3, "仍然排除失败账号并继续切换")
|
||||
require.Equal(t, 3, fs.SwitchCount)
|
||||
})
|
||||
|
||||
t.Run("请求级错误不占用封禁名额", func(t *testing.T) {
|
||||
mock := &mockTempUnscheduler{}
|
||||
fs := NewFailoverState(10, false)
|
||||
scoped := &service.UpstreamFailoverError{StatusCode: http.StatusBadGateway, RetryableOnSameAccount: true, RequestScopedTransient: true}
|
||||
plain := newTestFailoverErr(http.StatusBadGateway, true, false)
|
||||
|
||||
exhaustSameAccount(fs, mock, 2, scoped)
|
||||
exhaustSameAccount(fs, mock, 7, plain)
|
||||
exhaustSameAccount(fs, mock, 6, plain)
|
||||
|
||||
// 请求级错误仍交给服务层(服务层自行跳过封禁),且不消耗唯一的封禁名额。
|
||||
require.Len(t, mock.calls, 2)
|
||||
require.Equal(t, int64(2), mock.calls[0].accountID)
|
||||
require.True(t, mock.calls[0].failoverErr.RequestScopedTransient)
|
||||
require.Equal(t, int64(7), mock.calls[1].accountID)
|
||||
})
|
||||
|
||||
t.Run("每个请求独立计数", func(t *testing.T) {
|
||||
mock := &mockTempUnscheduler{}
|
||||
err := newTestFailoverErr(http.StatusBadGateway, true, false)
|
||||
|
||||
exhaustSameAccount(NewFailoverState(10, false), mock, 2, err)
|
||||
exhaustSameAccount(NewFailoverState(10, false), mock, 7, err)
|
||||
|
||||
require.Len(t, mock.calls, 2, "不健康的账号仍会被各自先遇到它的请求封禁")
|
||||
})
|
||||
}
|
||||
@@ -41,6 +41,7 @@ type StreamingProcessor struct {
|
||||
cacheReadTokens int
|
||||
imageOutputTokens int
|
||||
hasContent bool
|
||||
malformedCall bool
|
||||
}
|
||||
|
||||
// NewStreamingProcessor 创建流式响应处理器
|
||||
@@ -143,6 +144,7 @@ func (p *StreamingProcessor) ProcessLine(line string) []byte {
|
||||
if len(geminiResp.Candidates) > 0 {
|
||||
finishReason := geminiResp.Candidates[0].FinishReason
|
||||
if finishReason == "MALFORMED_FUNCTION_CALL" {
|
||||
p.malformedCall = true
|
||||
log.Printf("[Antigravity] MALFORMED_FUNCTION_CALL detected in stream for model %s", p.originalModel)
|
||||
if geminiResp.Candidates[0].Content != nil {
|
||||
if b, err := json.Marshal(geminiResp.Candidates[0].Content); err == nil {
|
||||
@@ -191,6 +193,13 @@ func (p *StreamingProcessor) HasContent() bool {
|
||||
return p.hasContent
|
||||
}
|
||||
|
||||
// SawMalformedFunctionCall reports whether the model ended a candidate with
|
||||
// MALFORMED_FUNCTION_CALL. That outcome depends on the request (its tools and
|
||||
// history), not on the account that served it.
|
||||
func (p *StreamingProcessor) SawMalformedFunctionCall() bool {
|
||||
return p.malformedCall
|
||||
}
|
||||
|
||||
// emitMessageStart 发送 message_start 事件
|
||||
func (p *StreamingProcessor) emitMessageStart(v1Resp *V1InternalResponse) []byte {
|
||||
if p.messageStartSent {
|
||||
|
||||
@@ -170,10 +170,10 @@ func (s *antigravityCompatStreamSession) finish() (*antigravityStreamResult, err
|
||||
s.consumeClaudeEvents(finalEvents)
|
||||
if !s.hasMeaningfulData() && !s.writer.Disconnected() {
|
||||
if s.preContentKeepaliveSent {
|
||||
s.adapter.WriteError(s.writer, "empty_stream")
|
||||
s.adapter.WriteError(s.writer, s.emptyStreamReason())
|
||||
return s.result(false), errors.New("empty Antigravity compatibility stream after keepalive")
|
||||
}
|
||||
return nil, antigravityCompatEmptyStreamError()
|
||||
return nil, s.emptyStreamError()
|
||||
}
|
||||
s.adapter.Finalize(s.writer)
|
||||
return s.result(s.writer.Disconnected()), nil
|
||||
@@ -334,7 +334,7 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveIn
|
||||
writeAntigravityCompatStreamError(c, adapter, writer, "stream_timeout")
|
||||
return session.collectResult(false), fmt.Errorf("pre-content stream timeout")
|
||||
}
|
||||
return nil, antigravityCompatEmptyStreamError()
|
||||
return nil, session.emptyStreamError()
|
||||
}
|
||||
|
||||
for {
|
||||
@@ -392,10 +392,10 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveIn
|
||||
|
||||
func handleAntigravityCompatEmptyStream(c *gin.Context, session *antigravityCompatStreamSession) (*antigravityStreamResult, error) {
|
||||
if session.preContentKeepaliveSent {
|
||||
writeAntigravityCompatStreamError(c, session.adapter, session.writer, "empty_stream")
|
||||
writeAntigravityCompatStreamError(c, session.adapter, session.writer, session.emptyStreamReason())
|
||||
return session.collectResult(false), errors.New("empty Antigravity compatibility stream after keepalive")
|
||||
}
|
||||
return nil, antigravityCompatEmptyStreamError()
|
||||
return nil, session.emptyStreamError()
|
||||
}
|
||||
|
||||
func (s *AntigravityGatewayService) startAntigravityCompatScanner(
|
||||
@@ -492,7 +492,7 @@ func (s *AntigravityGatewayService) handleAntigravityCompatReadError(
|
||||
writeAntigravityCompatStreamError(c, session.adapter, session.writer, "stream_read_error")
|
||||
return session.collectResult(false), fmt.Errorf("stream read error: %w", err)
|
||||
}
|
||||
return nil, antigravityCompatEmptyStreamError()
|
||||
return nil, session.emptyStreamError()
|
||||
}
|
||||
if disconnect, handled := handleStreamReadError(err, session.writer.Disconnected(), prefix); handled {
|
||||
return session.collectResult(disconnect), nil
|
||||
@@ -525,6 +525,38 @@ func antigravityCompatEmptyStreamError() error {
|
||||
}
|
||||
}
|
||||
|
||||
// emptyStreamError builds the failover error for a stream that produced no
|
||||
// meaningful content. When the model ended with MALFORMED_FUNCTION_CALL the
|
||||
// failure belongs to the request: the same tools and history fail on every
|
||||
// account, so the error stays retryable but must not cool the account down.
|
||||
func (s *antigravityCompatStreamSession) emptyStreamError() error {
|
||||
if s.processor == nil || !s.processor.SawMalformedFunctionCall() {
|
||||
return antigravityCompatEmptyStreamError()
|
||||
}
|
||||
return antigravityMalformedFunctionCallFailoverError()
|
||||
}
|
||||
|
||||
// antigravityMalformedFunctionCallFailoverError is the request-scoped variant
|
||||
// of the empty-stream error, shared by every Antigravity stream path.
|
||||
func antigravityMalformedFunctionCallFailoverError() *UpstreamFailoverError {
|
||||
logger.LegacyPrintf("service.antigravity_gateway", "Antigravity stream ended with MALFORMED_FUNCTION_CALL and no content, retrying without cooling the account")
|
||||
return &UpstreamFailoverError{
|
||||
StatusCode: http.StatusBadGateway,
|
||||
ResponseBody: []byte(`{"error":{"type":"malformed_function_call","message":"upstream model returned MALFORMED_FUNCTION_CALL"}}`),
|
||||
RetryableOnSameAccount: true,
|
||||
RequestScopedTransient: true,
|
||||
}
|
||||
}
|
||||
|
||||
// emptyStreamReason is the SSE error reason sent once keepalive bytes have
|
||||
// committed the response and failover is no longer possible.
|
||||
func (s *antigravityCompatStreamSession) emptyStreamReason() string {
|
||||
if s.processor != nil && s.processor.SawMalformedFunctionCall() {
|
||||
return "malformed_function_call"
|
||||
}
|
||||
return "empty_stream"
|
||||
}
|
||||
|
||||
func (s *AntigravityGatewayService) handleChatCompletionsStreamingFromAntigravity(
|
||||
c *gin.Context,
|
||||
resp *http.Response,
|
||||
|
||||
@@ -1256,3 +1256,69 @@ func TestAntigravityCompatEmptyAfterKeepaliveReportsStreamError(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAntigravityCompatMalformedFunctionCallIsRequestScoped(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
malformed := `data: {"response":{"candidates":[{"finishReason":"MALFORMED_FUNCTION_CALL","content":{"role":"model","parts":[{"thoughtSignature":"sig"}]}}]}}` + "\n\n"
|
||||
tests := []struct {
|
||||
name string
|
||||
run func(*AntigravityGatewayService, *gin.Context, *http.Response) (*antigravityStreamResult, error)
|
||||
}{
|
||||
{
|
||||
name: "chat completions",
|
||||
run: func(svc *AntigravityGatewayService, c *gin.Context, resp *http.Response) (*antigravityStreamResult, error) {
|
||||
return svc.handleChatCompletionsStreamingFromAntigravity(c, resp, time.Now(), "gemini-3.8-flash", true)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "responses",
|
||||
run: func(svc *AntigravityGatewayService, c *gin.Context, resp *http.Response) (*antigravityStreamResult, error) {
|
||||
return svc.handleResponsesStreamingFromAntigravity(c, resp, time.Now(), "gemini-3.8-flash")
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, nil)
|
||||
c, recorder := newAntigravityCompatContext(http.MethodPost, "/", nil)
|
||||
resp := &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: io.NopCloser(strings.NewReader(malformed)),
|
||||
}
|
||||
|
||||
result, err := tt.run(svc, c, resp)
|
||||
|
||||
require.Nil(t, result)
|
||||
var failoverErr *UpstreamFailoverError
|
||||
require.ErrorAs(t, err, &failoverErr)
|
||||
require.True(t, failoverErr.RetryableOnSameAccount, "模型输出有随机性,仍允许重试")
|
||||
require.True(t, failoverErr.RequestScopedTransient, "不得因此封禁账号")
|
||||
require.Contains(t, string(failoverErr.ResponseBody), "malformed_function_call")
|
||||
require.Empty(t, recorder.Body.String())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTempUnscheduleRetryableErrorSkipsMalformedFunctionCall(t *testing.T) {
|
||||
repo := &malformedTempUnschedRepo{}
|
||||
svc := &GatewayService{accountRepo: repo}
|
||||
|
||||
svc.TempUnscheduleRetryableError(context.Background(), 6, antigravityMalformedFunctionCallFailoverError())
|
||||
require.Empty(t, repo.ids)
|
||||
|
||||
svc.TempUnscheduleRetryableError(context.Background(), 6, antigravityCompatEmptyStreamError().(*UpstreamFailoverError))
|
||||
require.Equal(t, []int64{6}, repo.ids, "普通空流仍按原逻辑封禁")
|
||||
}
|
||||
|
||||
type malformedTempUnschedRepo struct {
|
||||
AccountRepository
|
||||
ids []int64
|
||||
}
|
||||
|
||||
func (r *malformedTempUnschedRepo) SetTempUnschedulable(_ context.Context, id int64, _ time.Time, _ string) error {
|
||||
r.ids = append(r.ids, id)
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user