diff --git a/backend/internal/service/openai_upstream_transport_error.go b/backend/internal/service/openai_upstream_transport_error.go index fcb142e2fd..287f257ec0 100644 --- a/backend/internal/service/openai_upstream_transport_error.go +++ b/backend/internal/service/openai_upstream_transport_error.go @@ -135,7 +135,13 @@ func (s *OpenAIGatewayService) handleOpenAIUpstreamTransportError(ctx context.Co switch classifyUpstreamTransportError(err) { case upstreamTransportReachability: - s.tempUnscheduleOpenAITransportError(ctx, account, safeErr, openAITransportReachabilityCooldown) + // A pool-mode upstream (e.g. a self-hosted cluster restarting) is expected + // to come back on its own, so reachability failures only fail the attempt + // over instead of cooling the whole pool account down. Rejected proxy + // credentials are a local configuration fault and still cool down below. + if !account.IsPoolMode() { + s.tempUnscheduleOpenAITransportError(ctx, account, safeErr, openAITransportReachabilityCooldown) + } case upstreamTransportProxyAuth: s.tempUnscheduleOpenAITransportError(ctx, account, safeErr, openAITransportProxyAuthCooldown) } diff --git a/backend/internal/service/openai_upstream_transport_error_handle_test.go b/backend/internal/service/openai_upstream_transport_error_handle_test.go index cb9f84a58f..cdbcdd5ecb 100644 --- a/backend/internal/service/openai_upstream_transport_error_handle_test.go +++ b/backend/internal/service/openai_upstream_transport_error_handle_test.go @@ -326,6 +326,48 @@ func TestTempUnscheduleOpenAITransportError_NilAccountRepo_InMemoryBlockOnly(t * "in-memory block must apply even when accountRepo is nil") } +func openAITransportPoolModeAccount(id int64) *Account { + return &Account{ + ID: id, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{"pool_mode": true}, + } +} + +func TestHandleOpenAIUpstreamTransportError_PoolModeReachabilityFailsOverWithoutCooldown(t *testing.T) { + repo := &openaiTransportAccountRepoStub{} + svc := &OpenAIGatewayService{accountRepo: repo, cfg: &config.Config{}} + account := openAITransportPoolModeAccount(8542) + c, _ := newOpenAITransportErrTestContext() + transportErr := &url.Error{ + Op: "Post", + URL: "https://pool.example.test/v1/responses", + Err: &net.OpError{Op: "dial", Net: "tcp", Err: syscall.ECONNREFUSED}, + } + + var failover *UpstreamFailoverError + require.ErrorAs(t, svc.handleOpenAIUpstreamTransportError(context.Background(), c, account, transportErr, false), &failover) + require.Empty(t, repo.tempUnschedCalls) + require.Nil(t, account.TempUnschedulableUntil) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestHandleOpenAIUpstreamTransportError_PoolModeProxyAuthStillCoolsDown(t *testing.T) { + repo := &openaiTransportAccountRepoStub{} + svc := &OpenAIGatewayService{accountRepo: repo, cfg: &config.Config{}} + account := openAITransportPoolModeAccount(8543) + c, _ := newOpenAITransportErrTestContext() + + var failover *UpstreamFailoverError + require.ErrorAs(t, svc.handleOpenAIUpstreamTransportError(context.Background(), c, account, + errors.New(`Post "https://pool.example.test/v1/responses": socks connect tcp 10.0.0.1:1080->pool.example.test:443: username/password authentication failed`), false), &failover) + require.Len(t, repo.tempUnschedCalls, 1, "rejected proxy credentials are a local fault and must still cool the account down") + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + // context.DeadlineExceeded is NOT special-cased — a slow upstream is worth failing over. func TestHandleOpenAIUpstreamTransportError_DeadlineExceeded_StillFailsOver(t *testing.T) { repo := &openaiTransportAccountRepoStub{} diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go index c3cacf7603..c7fa4bb70a 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -2637,7 +2637,9 @@ const tempUnschedMessageMaxBytes = 2048 // to fail the current attempt over to another account; the scheduler skips the // (account, model) pair via IsSchedulableForModelWithContext until the // cooldown expires, instead of re-selecting an account that can never serve -// the model. +// the model. A pool-mode account (without custom error codes) still fails the +// current attempt over, but no cooldown is written: the pool may serve the model +// again as soon as its members recover, so local state must not lock it out. func (s *RateLimitService) HandleUpstreamModelNotFound(ctx context.Context, account *Account, requestedModel string, statusCode int, responseBody []byte) bool { if s == nil || account == nil || s.accountRepo == nil { return false @@ -2664,6 +2666,18 @@ func (s *RateLimitService) HandleUpstreamModelNotFound(ctx context.Context, acco if shouldSkipCodexPlanGatedImageModelCooldown(ctx, reason, requestedModel, modelKey) { return true } + if account.IsPoolMode() && !account.IsCustomErrorCodesEnabled() { + // Pool mode only skips the default cooldown. A temporary-unschedulable + // rule the admin configured explicitly still applies, matching the + // pool-mode branch of HandleUpstreamError. + ruleCtx := withTempUnschedulableModel(ctx, []string{requestedModel}) + if tempUnschedRulesApply(account, statusCode, responseBody, tempUnschedulableModel(ruleCtx, nil)) && + s.tryTempUnschedulable(ruleCtx, account, statusCode, responseBody) { + return true + } + slog.Info("upstream_model_not_found_pool_mode_cooldown_skipped", "account_id", account.ID, "model", modelKey, "reason", reason) + return true + } resetAt := time.Now().Add(cooldown) if err := s.accountRepo.SetModelRateLimit(ctx, account.ID, modelKey, resetAt, reason); err != nil { slog.Warn("upstream_model_not_found_set_model_rate_limit_failed", "account_id", account.ID, "model", modelKey, "reason", reason, "error", err) diff --git a/backend/internal/service/ratelimit_service_model_not_found_test.go b/backend/internal/service/ratelimit_service_model_not_found_test.go index 9e2baa3b09..ce21e1356a 100644 --- a/backend/internal/service/ratelimit_service_model_not_found_test.go +++ b/backend/internal/service/ratelimit_service_model_not_found_test.go @@ -10,6 +10,7 @@ import ( "testing" "time" + "github.com/Wei-Shaw/sub2api/internal/config" "github.com/stretchr/testify/require" ) @@ -548,3 +549,107 @@ func TestRateLimitService_HandleUpstreamError_ModelNotFoundImageModelStillCoolsD require.Len(t, repo.modelRateLimitCalls, 1, "守卫只作用于 codex plan-gated 分支") require.Equal(t, upstreamModelNotFoundReason, repo.modelRateLimitCalls[0].reason) } + +func TestRateLimitService_HandleUpstreamModelNotFound_PoolModeFailsOverWithoutModelRateLimit(t *testing.T) { + repo := &modelNotFoundAccountRepoStub{} + svc := &RateLimitService{accountRepo: repo} + account := openAIModelNotFoundTempAccount() + account.Credentials = map[string]any{"pool_mode": true} + + handled := svc.HandleUpstreamModelNotFound( + context.Background(), + account, + "gpt-5.4", + http.StatusNotFound, + []byte(`{"error":{"code":"model_not_found","message":"model not found"}}`), + ) + + require.True(t, handled, "a pool-mode model-not-found must still fail the attempt over") + require.Zero(t, repo.tempCalls) + require.Empty(t, repo.modelRateLimitCalls) +} + +func TestRateLimitService_HandleUpstreamModelNotFound_PoolModeHonorsExplicitTempUnschedRule(t *testing.T) { + repo := &modelNotFoundAccountRepoStub{} + svc := &RateLimitService{accountRepo: repo} + account := openAIModelNotFoundTempAccount() + account.Credentials["pool_mode"] = true + + handled := svc.HandleUpstreamModelNotFound( + context.Background(), + account, + "gpt-5.4", + http.StatusNotFound, + []byte(`{"error":{"code":"model_not_found","message":"model not found"}}`), + ) + + require.True(t, handled) + require.Len(t, repo.modelRateLimitCalls, 1, "an admin-configured rule still applies in pool mode") + require.NotEqual(t, upstreamModelNotFoundReason, repo.modelRateLimitCalls[0].reason, "the default 30-minute cooldown must not be written") +} + +func TestRateLimitService_HandleUpstreamModelNotFound_PoolMode401FailsOverWithoutModelRateLimit(t *testing.T) { + repo := &modelNotFoundAccountRepoStub{} + svc := &RateLimitService{accountRepo: repo} + account := openAIModelNotFoundTempAccount() + account.Credentials["pool_mode"] = true + + handled := svc.HandleUpstreamModelNotFound( + context.Background(), + account, + "gpt-5.4", + http.StatusUnauthorized, + []byte(`{"error":{"code":"model_not_found","message":"The model gpt-5.4 does not exist"}}`), + ) + + require.True(t, handled) + require.Zero(t, repo.tempCalls) + require.Empty(t, repo.modelRateLimitCalls) +} + +func TestOpenAIAccountUpstreamError_PoolModeModelNotFoundStillFailsOver(t *testing.T) { + repo := &oauth429RateLimitRepo{} + rateLimits := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + svc := &OpenAIGatewayService{rateLimitService: rateLimits} + rateLimits.SetAccountRuntimeBlocker(svc) + account := &Account{ + ID: 8544, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{"pool_mode": true}, + } + + shouldFailover := svc.handleOpenAIAccountUpstreamError( + context.Background(), account, http.StatusNotFound, http.Header{}, + []byte(`{"error":{"code":"model_not_found","message":"model not found"}}`), + "gpt-5.4", + ) + + require.True(t, shouldFailover, "the pool account cannot serve this model now; the request must move to another account") + require.Zero(t, repo.setModelRateLimitCalls) + require.Zero(t, repo.setRateLimitedCalls) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestRateLimitService_HandleUpstreamModelNotFound_PoolModeCustomCodesUseModelRateLimit(t *testing.T) { + repo := &modelNotFoundAccountRepoStub{} + svc := &RateLimitService{accountRepo: repo} + account := openAIModelNotFoundTempAccount() + account.Credentials["pool_mode"] = true + account.Credentials["custom_error_codes_enabled"] = true + account.Credentials["custom_error_codes"] = []any{float64(http.StatusNotFound)} + + handled := svc.HandleUpstreamModelNotFound( + context.Background(), + account, + "gpt-5.4", + http.StatusNotFound, + []byte(`{"error":{"code":"model_not_found","message":"model not found"}}`), + ) + + require.True(t, handled) + require.Len(t, repo.modelRateLimitCalls, 1) + require.Equal(t, upstreamModelNotFoundReason, repo.modelRateLimitCalls[0].reason) +}