From 76ddf1e782b88c32cf1272037e4c4f204ad6ab01 Mon Sep 17 00:00:00 2001 From: pood1e Date: Wed, 2 Dec 2026 17:38:11 -0800 Subject: [PATCH 1/3] fix(ratelimit): keep pool-mode accounts off model and transport cooldowns Pool mode promises that upstream errors leave local account state alone and are retried on the same account. Two paths still marked it: - HandleUpstreamModelNotFound put a 30-minute model rate limit on the account for a 404 model_not_found, although HandleUpstreamError and HandleTempUnschedulable already skip pool-mode accounts without custom error codes. The OpenAI fast path calls it first, so the skip never applied there. - tempUnscheduleOpenAITransportError marked the account unschedulable after a transport error. A pool-mode upstream that restarts briefly answers 404 for its models and refuses connections; the account then stayed blocked for up to 30 minutes after the upstream recovered. Custom error codes still opt a pool-mode account into the model rate limit. Co-Authored-By: Claude Opus 5.5 --- .../openai_upstream_transport_error.go | 3 +- ...ai_upstream_transport_error_handle_test.go | 19 +++++++++ backend/internal/service/ratelimit_service.go | 6 ++- .../ratelimit_service_model_not_found_test.go | 40 +++++++++++++++++++ 4 files changed, 66 insertions(+), 2 deletions(-) diff --git a/backend/internal/service/openai_upstream_transport_error.go b/backend/internal/service/openai_upstream_transport_error.go index fcb142e2fd..1f7240357e 100644 --- a/backend/internal/service/openai_upstream_transport_error.go +++ b/backend/internal/service/openai_upstream_transport_error.go @@ -158,7 +158,8 @@ func (s *OpenAIGatewayService) handleOpenAIUpstreamTransportError(ctx context.Co // - "openai.account_temp_unscheduled_transport_failed" — DB write attempted // but returned an error. func (s *OpenAIGatewayService) tempUnscheduleOpenAITransportError(ctx context.Context, account *Account, safeErr string, cooldown time.Duration) { - if s == nil || account == nil { + // A pool-mode upstream retries on the same account instead of marking it. + if s == nil || account == nil || account.IsPoolMode() { return } if s.cfg != nil && s.cfg.Gateway.DisableOpenAITransportErrorCooldown { 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..40b0ecfb94 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,25 @@ func TestTempUnscheduleOpenAITransportError_NilAccountRepo_InMemoryBlockOnly(t * "in-memory block must apply even when accountRepo is nil") } +func TestTempUnscheduleOpenAITransportError_PoolModeSkipsCooldown(t *testing.T) { + repo := &openaiTransportAccountRepoStub{} + svc := &OpenAIGatewayService{accountRepo: repo, cfg: &config.Config{}} + account := &Account{ + ID: 8542, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{"pool_mode": true}, + } + + svc.tempUnscheduleOpenAITransportError(context.Background(), account, "connection refused", openAITransportReachabilityCooldown) + + require.Empty(t, repo.tempUnschedCalls) + require.Nil(t, account.TempUnschedulableUntil) + require.False(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..2aefb37065 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -2637,11 +2637,15 @@ 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 keeps it off local state like any other +// upstream error, unless it configures custom error codes. 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 } + if account.IsPoolMode() && !account.IsCustomErrorCodesEnabled() { + return false + } if !account.ShouldHandleErrorCode(statusCode) { return false } 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..f34b3251ac 100644 --- a/backend/internal/service/ratelimit_service_model_not_found_test.go +++ b/backend/internal/service/ratelimit_service_model_not_found_test.go @@ -548,3 +548,43 @@ func TestRateLimitService_HandleUpstreamError_ModelNotFoundImageModelStillCoolsD require.Len(t, repo.modelRateLimitCalls, 1, "守卫只作用于 codex plan-gated 分支") require.Equal(t, upstreamModelNotFoundReason, repo.modelRateLimitCalls[0].reason) } + +func TestRateLimitService_HandleUpstreamModelNotFound_PoolModeSkipsModelRateLimit(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.False(t, handled) + require.Zero(t, repo.tempCalls) + require.Empty(t, repo.modelRateLimitCalls) +} + +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) +} From 4b43302f59aa5d6ae8e554469cbd7ebb4b4d0d65 Mon Sep 17 00:00:00 2001 From: shaw Date: Thu, 3 Dec 2026 15:39:05 +0800 Subject: [PATCH 2/3] fix(ratelimit): keep pool-mode model-not-found failover and proxy-auth cooldown A pool-mode account hitting a deterministic model-not-found must still fail the current attempt over (404 is not in the generic failover set), only the 30-minute model cooldown is skipped. Rejected proxy credentials are a local configuration fault, so only reachability failures skip the transport cooldown for pool-mode accounts. --- .../openai_upstream_transport_error.go | 11 ++-- ...ai_upstream_transport_error_handle_test.go | 35 ++++++++++--- backend/internal/service/ratelimit_service.go | 12 +++-- .../ratelimit_service_model_not_found_test.go | 50 ++++++++++++++++++- 4 files changed, 92 insertions(+), 16 deletions(-) diff --git a/backend/internal/service/openai_upstream_transport_error.go b/backend/internal/service/openai_upstream_transport_error.go index 1f7240357e..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) } @@ -158,8 +164,7 @@ func (s *OpenAIGatewayService) handleOpenAIUpstreamTransportError(ctx context.Co // - "openai.account_temp_unscheduled_transport_failed" — DB write attempted // but returned an error. func (s *OpenAIGatewayService) tempUnscheduleOpenAITransportError(ctx context.Context, account *Account, safeErr string, cooldown time.Duration) { - // A pool-mode upstream retries on the same account instead of marking it. - if s == nil || account == nil || account.IsPoolMode() { + if s == nil || account == nil { return } if s.cfg != nil && s.cfg.Gateway.DisableOpenAITransportErrorCooldown { 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 40b0ecfb94..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,25 +326,48 @@ func TestTempUnscheduleOpenAITransportError_NilAccountRepo_InMemoryBlockOnly(t * "in-memory block must apply even when accountRepo is nil") } -func TestTempUnscheduleOpenAITransportError_PoolModeSkipsCooldown(t *testing.T) { - repo := &openaiTransportAccountRepoStub{} - svc := &OpenAIGatewayService{accountRepo: repo, cfg: &config.Config{}} - account := &Account{ - ID: 8542, +func openAITransportPoolModeAccount(id int64) *Account { + return &Account{ + ID: id, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true, Credentials: map[string]any{"pool_mode": true}, } +} - svc.tempUnscheduleOpenAITransportError(context.Background(), account, "connection refused", openAITransportReachabilityCooldown) +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 2aefb37065..6a03306193 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -2637,15 +2637,13 @@ 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. A pool-mode account keeps it off local state like any other -// upstream error, unless it configures custom error codes. +// 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 } - if account.IsPoolMode() && !account.IsCustomErrorCodesEnabled() { - return false - } if !account.ShouldHandleErrorCode(statusCode) { return false } @@ -2668,6 +2666,10 @@ func (s *RateLimitService) HandleUpstreamModelNotFound(ctx context.Context, acco if shouldSkipCodexPlanGatedImageModelCooldown(ctx, reason, requestedModel, modelKey) { return true } + if account.IsPoolMode() && !account.IsCustomErrorCodesEnabled() { + 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 f34b3251ac..ca79fa4eb2 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" ) @@ -549,7 +550,7 @@ func TestRateLimitService_HandleUpstreamError_ModelNotFoundImageModelStillCoolsD require.Equal(t, upstreamModelNotFoundReason, repo.modelRateLimitCalls[0].reason) } -func TestRateLimitService_HandleUpstreamModelNotFound_PoolModeSkipsModelRateLimit(t *testing.T) { +func TestRateLimitService_HandleUpstreamModelNotFound_PoolModeFailsOverWithoutModelRateLimit(t *testing.T) { repo := &modelNotFoundAccountRepoStub{} svc := &RateLimitService{accountRepo: repo} account := openAIModelNotFoundTempAccount() @@ -563,11 +564,56 @@ func TestRateLimitService_HandleUpstreamModelNotFound_PoolModeSkipsModelRateLimi []byte(`{"error":{"code":"model_not_found","message":"model not found"}}`), ) - require.False(t, handled) + 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_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} From 2ecf932f878f116db50bf525afb12892311a4616 Mon Sep 17 00:00:00 2001 From: shaw Date: Thu, 3 Dec 2026 16:04:47 +0800 Subject: [PATCH 3/3] fix(ratelimit): honor explicit temp-unschedulable rules on pool-mode model-not-found Pool mode only skips the default model cooldown; a rule the admin configured still applies, mirroring the pool-mode branch of HandleUpstreamError. --- backend/internal/service/ratelimit_service.go | 8 +++++++ .../ratelimit_service_model_not_found_test.go | 21 ++++++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go index 6a03306193..c7fa4bb70a 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -2667,6 +2667,14 @@ func (s *RateLimitService) HandleUpstreamModelNotFound(ctx context.Context, acco 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 } 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 ca79fa4eb2..ce21e1356a 100644 --- a/backend/internal/service/ratelimit_service_model_not_found_test.go +++ b/backend/internal/service/ratelimit_service_model_not_found_test.go @@ -554,7 +554,7 @@ func TestRateLimitService_HandleUpstreamModelNotFound_PoolModeFailsOverWithoutMo repo := &modelNotFoundAccountRepoStub{} svc := &RateLimitService{accountRepo: repo} account := openAIModelNotFoundTempAccount() - account.Credentials["pool_mode"] = true + account.Credentials = map[string]any{"pool_mode": true} handled := svc.HandleUpstreamModelNotFound( context.Background(), @@ -569,6 +569,25 @@ func TestRateLimitService_HandleUpstreamModelNotFound_PoolModeFailsOverWithoutMo 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}