diff --git a/backend/internal/handler/failover_loop.go b/backend/internal/handler/failover_loop.go index 56c39af103..428f6be1f4 100644 --- a/backend/internal/handler/failover_loop.go +++ b/backend/internal/handler/failover_loop.go @@ -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), + ) + } } // 加入失败列表 diff --git a/backend/internal/handler/failover_loop_test.go b/backend/internal/handler/failover_loop_test.go index d362682cd7..3180f5c13f 100644 --- a/backend/internal/handler/failover_loop_test.go +++ b/backend/internal/handler/failover_loop_test.go @@ -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, "不健康的账号仍会被各自先遇到它的请求封禁") + }) +} diff --git a/backend/internal/pkg/antigravity/stream_transformer.go b/backend/internal/pkg/antigravity/stream_transformer.go index 5a1cdaa81d..f671309880 100644 --- a/backend/internal/pkg/antigravity/stream_transformer.go +++ b/backend/internal/pkg/antigravity/stream_transformer.go @@ -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 { diff --git a/backend/internal/service/antigravity_gateway_compat_stream.go b/backend/internal/service/antigravity_gateway_compat_stream.go index 4dea4c453c..f9fddf2aad 100644 --- a/backend/internal/service/antigravity_gateway_compat_stream.go +++ b/backend/internal/service/antigravity_gateway_compat_stream.go @@ -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, diff --git a/backend/internal/service/antigravity_gateway_compat_test.go b/backend/internal/service/antigravity_gateway_compat_test.go index bccbe2472f..f60423ba45 100644 --- a/backend/internal/service/antigravity_gateway_compat_test.go +++ b/backend/internal/service/antigravity_gateway_compat_test.go @@ -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 +}