From 531ca9984da2bbc0f9fccb3894c49297ffa21f1d Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 8 Nov 2026 20:42:45 +0800 Subject: [PATCH 1/4] =?UTF-8?q?feat:=20=E6=94=AF=E6=8C=81=20OAuth=20?= =?UTF-8?q?=E8=B4=A6=E5=8F=B7=E9=81=87=E5=88=B0=20429=20=E5=90=8E=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E5=85=B3=E9=97=AD=E8=B0=83=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../admin/account_auto_config_429_test.go | 67 ++++++++ backend/internal/repository/account_repo.go | 7 +- .../openai_oauth_reauth_account_repo_test.go | 2 +- ...auth_reauth_scheduling_integration_test.go | 53 ++++++ backend/internal/service/oauth_auto_config.go | 46 ++--- .../service/oauth_auto_config_429_test.go | 81 +++++++++ .../openai_account_runtime_block_fastpath.go | 11 +- .../service/openai_disable_scheduling_429.go | 55 ++++++ .../service/openai_excel_bps_ratelimit.go | 1 + backend/internal/service/ratelimit_service.go | 4 + ...mit_service_disable_scheduling_429_test.go | 161 ++++++++++++++++++ frontend/src/api/admin/autoConfig.ts | 1 + frontend/src/constants/newFeatureNotices.ts | 1 + frontend/src/i18n/locales/en/autoConfig.ts | 4 + frontend/src/i18n/locales/zh/autoConfig.ts | 4 + frontend/src/views/admin/AutoConfigView.vue | 13 +- .../admin/__tests__/AutoConfigView.spec.ts | 77 ++++++++- 17 files changed, 556 insertions(+), 32 deletions(-) create mode 100644 backend/internal/handler/admin/account_auto_config_429_test.go create mode 100644 backend/internal/repository/openai_oauth_reauth_scheduling_integration_test.go create mode 100644 backend/internal/service/oauth_auto_config_429_test.go create mode 100644 backend/internal/service/openai_disable_scheduling_429.go create mode 100644 backend/internal/service/ratelimit_service_disable_scheduling_429_test.go diff --git a/backend/internal/handler/admin/account_auto_config_429_test.go b/backend/internal/handler/admin/account_auto_config_429_test.go new file mode 100644 index 000000000000..b431a529f249 --- /dev/null +++ b/backend/internal/handler/admin/account_auto_config_429_test.go @@ -0,0 +1,67 @@ +//go:build unit + +package admin + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestAutoConfigDisableScheduling429SaveAndLegacyClient(t *testing.T) { + gin.SetMode(gin.TestMode) + original := service.DefaultOAuthAutoConfig() + raw, err := json.Marshal(original) + require.NoError(t, err) + repo := &opsHandlerWritableSettings{raw: string(raw)} + cfg := &config.Config{} + cfg.Runtime.Role = config.RuntimeRoleGateway + svc := service.ProvideAccountOpsService(repo, opsHandlerQueue{}, nil, nil, modelBillingHandlerGroups{}, cfg, nil, nil, nil, nil, nil) + svc.Stop() + handler := NewAccountOpsHandler(svc, nil) + router := gin.New() + router.PUT("/config", handler.SaveAutoConfig) + router.GET("/config", handler.GetAutoConfig) + for _, tc := range []struct { + name string + body string + status int + disable bool + rotateTOTP bool + }{ + {"enable both", `{"openai_disable_scheduling_on_429":true,"openai_totp_rotate_on_429":true}`, http.StatusOK, true, true}, + {"old client omits flags", `{"priority":6}`, http.StatusOK, true, true}, + {"disable rotation independently", `{"openai_totp_rotate_on_429":false}`, http.StatusOK, true, false}, + {"reject non boolean", `{"openai_disable_scheduling_on_429":"true"}`, http.StatusBadRequest, true, false}, + {"explicit opt out", `{"openai_disable_scheduling_on_429":false}`, http.StatusOK, false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + before := repo.raw + written := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodPut, "/config", strings.NewReader(tc.body)) + request.Header.Set("Content-Type", "application/json") + router.ServeHTTP(written, request) + require.Equal(t, tc.status, written.Code, written.Body.String()) + if tc.status != http.StatusOK { + require.Equal(t, before, repo.raw, "invalid values must not change stored settings") + } + read := httptest.NewRecorder() + router.ServeHTTP(read, httptest.NewRequest(http.MethodGet, "/config", nil)) + require.Equal(t, http.StatusOK, read.Code) + var payload struct { + Data service.OAuthAutoConfig `json:"data"` + } + require.NoError(t, json.Unmarshal(read.Body.Bytes(), &payload)) + require.Equal(t, tc.disable, payload.Data.OpenAIDisableSchedulingOn429) + require.Equal(t, tc.rotateTOTP, payload.Data.OpenAITOTPRotateOn429) + require.Equal(t, original.ExcelBPS, payload.Data.ExcelBPS) + }) + } +} diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index ea50537f5c80..7544335dd180 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -1178,8 +1178,9 @@ func (r *accountRepository) UpdateCredentials(ctx context.Context, id int64, cre // account still has the credential snapshot captured before protocol login. // Re-authentication may take several minutes; the expected-value guard keeps a // concurrent manual edit or token refresh from being overwritten by a stale -// callback. Successful swaps also restore the account's active/schedulable -// state and clear transient scheduling quarantine. +// callback. Successful swaps also restore the account's active state and clear +// transient scheduling quarantine. Admission and 429 scheduling policies retain +// the existing scheduling switch. func (r *accountRepository) ApplyOpenAIOAuthReauth( ctx context.Context, taskID int64, @@ -1226,7 +1227,7 @@ func (r *accountRepository) ApplyOpenAIOAuthReauth( expires_at = COALESCE($14::timestamptz, a.expires_at), status = $5, error_message = '', - schedulable = CASE WHEN a.extra ? 'openai_two_fa_admission' THEN a.schedulable ELSE TRUE END, + schedulable = CASE WHEN a.extra ? 'openai_two_fa_admission' OR a.extra @> '{"openai_disable_scheduling_on_429":true}'::jsonb THEN a.schedulable ELSE TRUE END, rate_limited_at = NULL, rate_limit_reset_at = NULL, overload_until = NULL, diff --git a/backend/internal/repository/openai_oauth_reauth_account_repo_test.go b/backend/internal/repository/openai_oauth_reauth_account_repo_test.go index 91a34d823e0b..39884e76fc0c 100644 --- a/backend/internal/repository/openai_oauth_reauth_account_repo_test.go +++ b/backend/internal/repository/openai_oauth_reauth_account_repo_test.go @@ -39,7 +39,7 @@ func TestAccountRepositoryApplyOpenAIOAuthReauthIsAtomic(t *testing.T) { require.Contains(t, query, "task.worker_id = $10") require.Contains(t, query, "expires_at = COALESCE($14::timestamptz, a.expires_at)") require.Contains(t, query, "status = $5") - require.Contains(t, query, "schedulable = CASE WHEN a.extra ? 'openai_two_fa_admission' THEN a.schedulable ELSE TRUE END") + require.Contains(t, query, `schedulable = CASE WHEN a.extra ? 'openai_two_fa_admission' OR a.extra @> '{"openai_disable_scheduling_on_429":true}'::jsonb THEN a.schedulable ELSE TRUE END`) require.Contains(t, query, "rate_limited_at = NULL") require.Contains(t, query, "rate_limit_reset_at = NULL") require.Contains(t, query, "overload_until = NULL") diff --git a/backend/internal/repository/openai_oauth_reauth_scheduling_integration_test.go b/backend/internal/repository/openai_oauth_reauth_scheduling_integration_test.go new file mode 100644 index 000000000000..70ea7aa56d5f --- /dev/null +++ b/backend/internal/repository/openai_oauth_reauth_scheduling_integration_test.go @@ -0,0 +1,53 @@ +//go:build integration + +package repository + +import ( + "context" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestOpenAIReauthPreserves429SchedulingPolicy(t *testing.T) { + for _, tc := range []struct { + name string + extra map[string]any + before bool + want bool + }{ + {name: "legacy paused account", want: true}, + {name: "opted out", extra: map[string]any{service.OpenAIDisableSchedulingOn429ExtraKey: false}, want: true}, + {name: "429 paused account", extra: map[string]any{service.OpenAIDisableSchedulingOn429ExtraKey: true}}, + {name: "opted in active account", extra: map[string]any{service.OpenAIDisableSchedulingOn429ExtraKey: true}, before: true, want: true}, + {name: "string flag is not enabled", extra: map[string]any{service.OpenAIDisableSchedulingOn429ExtraKey: "true"}, want: true}, + {name: "admission still preserved", extra: map[string]any{service.OpenAITwoFAAdmissionExtraKey: map[string]any{"state": "pending"}}}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + tx := testEntTx(t) + repo := newAccountRepositoryWithSQL(tx.Client(), tx, nil) + old := map[string]any{"access_token": "old", "refresh_token": "old-rt"} + a := mustCreateAccount(t, tx.Client(), &service.Account{ + Name: "reauth-scheduling", Platform: service.PlatformOpenAI, + Type: service.AccountTypeOAuth, Credentials: old, Extra: tc.extra, + }) + require.NoError(t, tx.Client().Account.UpdateOneID(a.ID).SetSchedulable(tc.before).Exec(ctx)) + var taskID int64 + require.NoError(t, tx.QueryRowContext(ctx, `INSERT INTO openai_oauth_reauth_tasks + (account_id,status,stage,expected_credentials_hash,worker_id) + VALUES ($1,$2,$3,'synthetic-hash','worker') RETURNING id`, + a.ID, service.OpenAIOAuthReauthStatusCallbackProcessing, service.OpenAIOAuthReauthStageApplyingCredentials).Scan(&taskID)) + + applied, err := repo.ApplyOpenAIOAuthReauth(ctx, taskID, "worker", a.ID, old, + map[string]any{"access_token": "new", "refresh_token": "new-rt"}, nil) + require.NoError(t, err) + require.True(t, applied) + current, err := repo.GetByID(ctx, a.ID) + require.NoError(t, err) + require.Equal(t, tc.want, current.Schedulable) + require.Equal(t, "new", current.Credentials["access_token"], "preserving the scheduling switch must not block credential replacement") + }) + } +} diff --git a/backend/internal/service/oauth_auto_config.go b/backend/internal/service/oauth_auto_config.go index 1800842f8092..f582626cf9fe 100644 --- a/backend/internal/service/oauth_auto_config.go +++ b/backend/internal/service/oauth_auto_config.go @@ -18,28 +18,29 @@ const AutoConfigConcurrencyExtraKey = "auto_config_concurrency" // Initial account fields, BPS defaults, model billing and concurrency upgrades are independent. type OAuthAutoConfig struct { - OpenAITwoFAAdmission OpenAITwoFAAdmissionConfig `json:"openai_two_fa_admission"` - OpenAITOTPRotateOn429 bool `json:"openai_totp_rotate_on_429"` - QualityRule *OAuthInitialQualityRule `json:"quality_rule,omitempty"` - ModelMappings []OAuthModelMappingRule `json:"model_mappings"` - SelectedModels []string `json:"selected_models"` - ModelBilling ModelBillingConfig `json:"model_billing"` - ExcelBPS ExcelBPSDefaults `json:"excel_bps"` - UpdatedAt time.Time `json:"updated_at"` - Enabled bool `json:"enabled"` - Platform string `json:"platform"` - Priority int `json:"priority"` - LoadFactor int `json:"load_factor"` - Concurrency int `json:"concurrency"` - GroupIDs []int64 `json:"group_ids"` - UpgradeEnabled bool `json:"upgrade_enabled"` - UpgradeGroupIDs []int64 `json:"upgrade_group_ids"` - SuccessesPerStep int `json:"successes_per_step"` - UpgradeStep int `json:"upgrade_step"` - MaxConcurrency int `json:"max_concurrency"` - CooldownSeconds int `json:"cooldown_seconds"` - CostMultiplier float64 `json:"cost_multiplier"` - Revision string `json:"revision"` + OpenAITwoFAAdmission OpenAITwoFAAdmissionConfig `json:"openai_two_fa_admission"` + OpenAITOTPRotateOn429 bool `json:"openai_totp_rotate_on_429"` + OpenAIDisableSchedulingOn429 bool `json:"openai_disable_scheduling_on_429"` + QualityRule *OAuthInitialQualityRule `json:"quality_rule,omitempty"` + ModelMappings []OAuthModelMappingRule `json:"model_mappings"` + SelectedModels []string `json:"selected_models"` + ModelBilling ModelBillingConfig `json:"model_billing"` + ExcelBPS ExcelBPSDefaults `json:"excel_bps"` + UpdatedAt time.Time `json:"updated_at"` + Enabled bool `json:"enabled"` + Platform string `json:"platform"` + Priority int `json:"priority"` + LoadFactor int `json:"load_factor"` + Concurrency int `json:"concurrency"` + GroupIDs []int64 `json:"group_ids"` + UpgradeEnabled bool `json:"upgrade_enabled"` + UpgradeGroupIDs []int64 `json:"upgrade_group_ids"` + SuccessesPerStep int `json:"successes_per_step"` + UpgradeStep int `json:"upgrade_step"` + MaxConcurrency int `json:"max_concurrency"` + CooldownSeconds int `json:"cooldown_seconds"` + CostMultiplier float64 `json:"cost_multiplier"` + Revision string `json:"revision"` } func DefaultOAuthAutoConfig() OAuthAutoConfig { @@ -195,6 +196,7 @@ func (s *adminServiceImpl) ApplyOAuthAutoConfig(ctx context.Context, input *Crea input.Extra[AccountCostMultiplierExtraKey] = c.CostMultiplier if input.Platform == PlatformOpenAI { input.Extra[OpenAITOTPRotateOn429ExtraKey] = c.OpenAITOTPRotateOn429 + input.Extra[OpenAIDisableSchedulingOn429ExtraKey] = c.OpenAIDisableSchedulingOn429 } return nil } diff --git a/backend/internal/service/oauth_auto_config_429_test.go b/backend/internal/service/oauth_auto_config_429_test.go new file mode 100644 index 000000000000..6e0dbd6f5984 --- /dev/null +++ b/backend/internal/service/oauth_auto_config_429_test.go @@ -0,0 +1,81 @@ +package service + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestOAuthAutoConfigDisableSchedulingOn429Scope(t *testing.T) { + for _, tc := range []struct { + name, platform, kind, templatePlatform string + enabled, disable, observer bool + want any + }{ + {name: "new OpenAI OAuth", enabled: true, disable: true, want: true}, + {name: "unchecked overrides import", enabled: true, want: false}, + {name: "initialization disabled", disable: true}, + {name: "API key", enabled: true, disable: true, kind: AccountTypeAPIKey}, + {name: "another platform", enabled: true, disable: true, platform: PlatformAnthropic}, + {name: "matching non-OpenAI platform", enabled: true, disable: true, platform: PlatformAnthropic, templatePlatform: PlatformAnthropic}, + {name: "observer preserves explicit configuration", enabled: true, disable: true, observer: true}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := DefaultOAuthAutoConfig() + cfg.Enabled, cfg.OpenAIDisableSchedulingOn429, cfg.GroupIDs = tc.enabled, tc.disable, []int64{2} + if tc.templatePlatform != "" { + cfg.Platform = tc.templatePlatform + } + raw, err := json.Marshal(cfg) + require.NoError(t, err) + svc := &adminServiceImpl{ + settingService: NewSettingService(&accountOpsSettingsStub{raw: string(raw)}, nil), + groupRepo: autoConfigGroups{group: &Group{ID: 2, Platform: cfg.Platform, Status: StatusActive}}, + } + original := map[string]any{"keep": "unchanged"} + if tc.want != nil { + original[OpenAIDisableSchedulingOn429ExtraKey] = !tc.disable + } + input := &CreateAccountInput{Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{25}, Extra: original} + if tc.platform != "" { + input.Platform = tc.platform + } + if tc.kind != "" { + input.Type = tc.kind + } + ctx := t.Context() + if tc.observer { + ctx = WithObserverScope(ctx, []int64{25}) + } + require.NoError(t, svc.ApplyOAuthAutoConfig(ctx, input)) + require.Equal(t, tc.want, input.Extra[OpenAIDisableSchedulingOn429ExtraKey]) + require.Equal(t, "unchanged", input.Extra["keep"]) + if tc.want != nil { + require.Equal(t, !tc.disable, original[OpenAIDisableSchedulingOn429ExtraKey], "template must not mutate the imported map") + } else { + require.NotContains(t, original, OpenAIDisableSchedulingOn429ExtraKey) + } + }) + } +} + +func TestOAuthAutoConfigDisableSchedulingOn429LegacyAndRoundTrip(t *testing.T) { + repo := &accountOpsSettingsStub{raw: `{"enabled":false,"platform":"openai"}`} + cfg, err := GetOAuthAutoConfig(t.Context(), repo) + require.NoError(t, err) + require.False(t, cfg.OpenAIDisableSchedulingOn429, "old settings must not opt in") + svc := NewAccountOpsService(repo, nil, nil) + svc.autoGroups = autoConfigGroups{} + for _, rotate := range []bool{false, true} { + for _, disable := range []bool{false, true} { + cfg.OpenAITOTPRotateOn429, cfg.OpenAIDisableSchedulingOn429 = rotate, disable + _, err = svc.SaveOAuthAutoConfig(t.Context(), cfg) + require.NoError(t, err) + loaded, err := GetOAuthAutoConfig(t.Context(), repo) + require.NoError(t, err) + require.Equal(t, disable, loaded.OpenAIDisableSchedulingOn429) + require.Equal(t, rotate, loaded.OpenAITOTPRotateOn429, "the two policies are independent") + } + } +} diff --git a/backend/internal/service/openai_account_runtime_block_fastpath.go b/backend/internal/service/openai_account_runtime_block_fastpath.go index 4bfe43ff0b70..31f6aee5ead7 100644 --- a/backend/internal/service/openai_account_runtime_block_fastpath.go +++ b/backend/internal/service/openai_account_runtime_block_fastpath.go @@ -92,7 +92,14 @@ func isOpenAIAccount(account *Account) bool { // handleOpenAIAccountUpstreamError expects canonicalModel to be the model used // for scheduling after applying account mapping exactly once. -func (s *OpenAIGatewayService) handleOpenAIAccountUpstreamError(ctx context.Context, account *Account, statusCode int, headers http.Header, responseBody []byte, canonicalModel ...string) bool { +func (s *OpenAIGatewayService) handleOpenAIAccountUpstreamError(ctx context.Context, account *Account, statusCode int, headers http.Header, responseBody []byte, canonicalModel ...string) (shouldDisable bool) { + if s != nil { + var disabledOn429 bool + ctx, disabledOn429 = s.rateLimitService.maybeDisableOpenAISchedulingOn429(ctx, account, statusCode) + if disabledOn429 { + defer func() { shouldDisable = true }() + } + } if isOpenAIUpstreamSessionBlocked(responseBody) { return false } @@ -206,7 +213,7 @@ func (s *OpenAIGatewayService) handleOpenAIAccountUpstreamError(ctx context.Cont if s.rateLimitService == nil { return false } - shouldDisable := s.rateLimitService.handleUpstreamErrorAfterStreakReset(stateCtx, account, statusCode, headers, responseBody) + shouldDisable = s.rateLimitService.handleUpstreamErrorAfterStreakReset(stateCtx, account, statusCode, headers, responseBody) tempModel := tempUnschedulableModel(stateCtx, nil) modelTempMatched := tempModel != "" && tempUnschedRulesApply(account, statusCode, responseBody, tempModel) && len(matchTempUnschedulableRules(account, statusCode, responseBody)) > 0 diff --git a/backend/internal/service/openai_disable_scheduling_429.go b/backend/internal/service/openai_disable_scheduling_429.go new file mode 100644 index 000000000000..eadfb3b6780f --- /dev/null +++ b/backend/internal/service/openai_disable_scheduling_429.go @@ -0,0 +1,55 @@ +package service + +import ( + "context" + "log/slog" + "net/http" + "time" +) + +const OpenAIDisableSchedulingOn429ExtraKey = "openai_disable_scheduling_on_429" + +func openAIDisableSchedulingOn429Enabled(account *Account) bool { + // Managed connection projections retain the owning account's ID and policy, + // so their 429s close that account's switch. Spark shadows have their own + // scheduling identity and quota and must not close the primary account. + if account == nil || account.ID <= 0 || account.Platform != PlatformOpenAI || account.Type != AccountTypeOAuth || + account.IsShadow() { + return false + } + enabled, _ := account.Extra[OpenAIDisableSchedulingOn429ExtraKey].(bool) + return enabled +} + +type openAIDisableScheduling429ObservedKey struct{} + +type openAIDisableScheduling429Observation struct { + accountID int64 + disabled bool +} + +// Persist the normal scheduling switch, rather than a temporary cooldown. A +// successful test or an elapsed 429 window must not reopen the account. The +// context marker shares the result across gateway and common error handlers. +func (s *RateLimitService) maybeDisableOpenAISchedulingOn429(ctx context.Context, account *Account, status int) (context.Context, bool) { + if s == nil || s.accountRepo == nil || status != http.StatusTooManyRequests || !openAIDisableSchedulingOn429Enabled(account) { + return ctx, false + } + if observed, ok := ctx.Value(openAIDisableScheduling429ObservedKey{}).(openAIDisableScheduling429Observation); ok && observed.accountID == account.ID { + return ctx, observed.disabled + } + stateCtx, cancel := openAIAccountStateContext(ctx) + defer cancel() + err := s.accountRepo.SetSchedulable(stateCtx, account.ID, false) + if err != nil { + // Never log an upstream response, request body or credential here. + slog.Warn("openai_429_disable_scheduling_failed", "account_id", account.ID) + } else { + // SetSchedulable refreshes the shared scheduler snapshot; bridge stale + // in-flight candidates immediately and stop same-account 429 retries. + s.notifyAccountSchedulingBlocked(account, time.Time{}, "openai_429_scheduling_disabled") + slog.Info("openai_429_scheduling_disabled", "account_id", account.ID) + } + ctx = context.WithValue(ctx, openAIDisableScheduling429ObservedKey{}, openAIDisableScheduling429Observation{accountID: account.ID, disabled: err == nil}) + return ctx, err == nil +} diff --git a/backend/internal/service/openai_excel_bps_ratelimit.go b/backend/internal/service/openai_excel_bps_ratelimit.go index 3ce392ad9223..c6ee28191ade 100644 --- a/backend/internal/service/openai_excel_bps_ratelimit.go +++ b/backend/internal/service/openai_excel_bps_ratelimit.go @@ -51,6 +51,7 @@ func (s *OpenAIGatewayService) coolDownExcelBPS(ctx context.Context, account *Ac if s == nil || account == nil { return } + ctx, _ = s.rateLimitService.maybeDisableOpenAISchedulingOn429(ctx, account, http.StatusTooManyRequests) ctx = s.rateLimitService.maybeRotateOpenAITOTPOn429(ctx, account, http.StatusTooManyRequests) if account.AuthConnectionID != "" { s.handleOpenAIAccountUpstreamError(ctx, account, http.StatusTooManyRequests, http.Header{"Retry-After": []string{retryAfter}}, nil) diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go index 4fbb3bcfc73a..0aa5d55b3753 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -357,6 +357,10 @@ func (s *RateLimitService) HandleUpstreamError(ctx context.Context, account *Acc // handleUpstreamErrorAfterStreakReset keeps account policy handling shared with // the OpenAI gateway, which resets the streak before its early-return policies. func (s *RateLimitService) handleUpstreamErrorAfterStreakReset(ctx context.Context, account *Account, statusCode int, headers http.Header, responseBody []byte, requestedModel ...string) (shouldDisable bool) { + ctx, disabledOn429 := s.maybeDisableOpenAISchedulingOn429(ctx, account, statusCode) + if disabledOn429 { + defer func() { shouldDisable = true }() + } ctx = s.maybeRotateOpenAITOTPOn429(ctx, account, statusCode) // An edge refusal must not reach account-specific rules, linked-account // mutation or quota handlers, even when administrators configured a broad 403. diff --git a/backend/internal/service/ratelimit_service_disable_scheduling_429_test.go b/backend/internal/service/ratelimit_service_disable_scheduling_429_test.go new file mode 100644 index 000000000000..0fde4632f344 --- /dev/null +++ b/backend/internal/service/ratelimit_service_disable_scheduling_429_test.go @@ -0,0 +1,161 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "net/http" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +type scheduling429Repo struct { + rateLimitAccountRepoStub + ids []int64 + values []bool + err error + ctxErr error +} + +func (r *scheduling429Repo) SetSchedulable(ctx context.Context, id int64, enabled bool) error { + r.ids = append(r.ids, id) + r.values = append(r.values, enabled) + r.ctxErr = ctx.Err() + return r.err +} + +func scheduling429Account() *Account { + return &Account{ID: 42, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Schedulable: true, + Extra: map[string]any{OpenAIDisableSchedulingOn429ExtraKey: true}} +} + +func TestRateLimitDisableSchedulingOn429ScopeAndObservation(t *testing.T) { + for _, tc := range []struct { + name string + status int + mutate func(*Account) + want bool + }{ + {"enabled without saved credentials", 429, func(*Account) {}, true}, + {"managed connection keeps owner identity", 429, func(a *Account) { a.AuthConnectionID = "connection" }, true}, + {"SIWC", 429, func(a *Account) { a.Extra[OpenAISIWCEnabledKey] = true }, true}, + {"PAT", 429, func(a *Account) { a.Credentials = map[string]any{"auth_mode": "personal_access_token"} }, true}, + {"agent identity", 429, func(a *Account) { a.Credentials = map[string]any{"auth_mode": OpenAIAuthModeAgentIdentity} }, true}, + {"another error", 503, func(*Account) {}, false}, + {"not opted in", 429, func(a *Account) { a.Extra = nil }, false}, + {"explicit false", 429, func(a *Account) { a.Extra[OpenAIDisableSchedulingOn429ExtraKey] = false }, false}, + {"string opt-in rejected", 429, func(a *Account) { a.Extra[OpenAIDisableSchedulingOn429ExtraKey] = "true" }, false}, + {"another platform", 429, func(a *Account) { a.Platform = PlatformAnthropic }, false}, + {"API key", 429, func(a *Account) { a.Type = AccountTypeAPIKey }, false}, + {"Spark shadow", 429, func(a *Account) { id := int64(99); a.ParentAccountID = &id }, false}, + {"unsaved account", 429, func(a *Account) { a.ID = 0 }, false}, + } { + t.Run(tc.name, func(t *testing.T) { + repo, blocker := &scheduling429Repo{}, &runtimeBlockRecorder{} + svc := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + svc.SetAccountRuntimeBlocker(blocker) + account := scheduling429Account() + tc.mutate(account) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + ctx, disabled := svc.maybeDisableOpenAISchedulingOn429(ctx, account, tc.status) + _, repeated := svc.maybeDisableOpenAISchedulingOn429(ctx, account, tc.status) + require.Equal(t, tc.want, disabled) + require.Equal(t, disabled, repeated) + if tc.want { + require.Equal(t, []int64{42}, repo.ids, "one write for this error; never mutate another owner") + require.Equal(t, []bool{false}, repo.values) + require.NoError(t, repo.ctxErr, "request cancellation must not cancel the scheduling change") + require.Equal(t, []string{"openai_429_scheduling_disabled"}, blocker.reasons) + require.True(t, account.Schedulable, "do not mutate a shared request snapshot") + } else { + require.Empty(t, repo.ids) + require.Empty(t, blocker.accounts) + } + }) + } +} + +func TestRateLimitDisableSchedulingOn429PreservesOtherPolicies(t *testing.T) { + for _, fail := range []bool{false, true} { + t.Run(map[bool]string{false: "saved", true: "write failed"}[fail], func(t *testing.T) { + repo, rotation := &scheduling429Repo{}, &totp429Recorder{} + if fail { + repo.err = errors.New("database unavailable") + } + rates := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + rates.openAITOTP429Rotator = rotation + account := scheduling429Account() + account.Extra[OpenAITOTPRotateOn429ExtraKey] = true + disabled := rates.HandleUpstreamError(t.Context(), account, 429, http.Header{}, nil) + require.Equal(t, !fail, disabled) + require.Equal(t, []int64{42}, repo.ids) + require.Equal(t, []int64{42}, rotation.accounts, "automatic rotation remains independent") + require.Equal(t, 1, repo.rateLimitedCalls, "scheduling persistence must not skip ordinary 429 cooldown") + }) + } +} + +func TestOpenAIGatewayDisableSchedulingOn429Paths(t *testing.T) { + for _, path := range []string{"native", "image", "bps", "managed", "managed-bps", "siwc", "websocket-error"} { + t.Run(path, func(t *testing.T) { + repo, rotation := &scheduling429Repo{}, &totp429Recorder{} + rates := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + rates.openAITOTP429Rotator = rotation + gateway := &OpenAIGatewayService{rateLimitService: rates} + rates.SetAccountRuntimeBlocker(gateway) + account := scheduling429Account() + if path == "managed" || path == "managed-bps" { + account.AuthConnectionID = "connection" + } + if path == "siwc" { + account.Extra[OpenAISIWCEnabledKey] = true + } + switch path { + case "bps", "managed-bps": + gateway.coolDownExcelBPS(t.Context(), account, "5") + case "image": + disabled := gateway.handleOpenAIAccountUpstreamError(t.Context(), account, 429, http.Header{}, []byte(`{"error":{"message":"Rate limit reached for gpt-image-2-codex (for limit gpt-image)"}}`)) + require.True(t, disabled) + case "websocket-error": + require.True(t, gateway.handleOpenAIWSFailureAccountSideEffects(t.Context(), account, "gpt-5.5", http.Header{}, []byte(`{"type":"error","error":{"type":"rate_limit_error","code":"rate_limit_exceeded","message":"Rate limit reached"}}`))) + default: + disabled := gateway.handleOpenAIAccountUpstreamError(t.Context(), account, 429, http.Header{}, nil) + require.True(t, disabled) + } + require.Equal(t, []int64{42}, repo.ids, "gateway and common paths must share one durable scheduling change") + require.Equal(t, []bool{false}, repo.values) + require.Empty(t, rotation.accounts, "scheduling policy needs no 2FA opt-in or credentials") + require.True(t, gateway.isOpenAIAccountRuntimeBlocked(account)) + require.False(t, gateway.shouldRetryOpenAIOAuth429OnSameAccount(account, 429, false), "the same-account retry window must not reopen a disabled account") + }) + } +} + +type scheduling429RecoveryRepo struct { + rateLimitClearRepoStub + writes []bool +} + +func (r *scheduling429RecoveryRepo) SetSchedulable(_ context.Context, _ int64, enabled bool) error { + r.writes = append(r.writes, enabled) + return nil +} + +func TestRateLimitDisableSchedulingOn429SurvivesSuccessfulTestRecovery(t *testing.T) { + account := scheduling429Account() + account.Schedulable = false + resetAt := time.Now().Add(-time.Minute) + account.RateLimitResetAt = &resetAt + repo := &scheduling429RecoveryRepo{rateLimitClearRepoStub: rateLimitClearRepoStub{getByIDAccount: account}} + rates := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + result, err := rates.RecoverAccountAfterSuccessfulTest(t.Context(), account.ID) + require.NoError(t, err) + require.True(t, result.ClearedRateLimit) + require.Empty(t, repo.writes, "recovering quota state must not re-enable the persistent scheduling switch") + require.False(t, account.Schedulable) +} diff --git a/frontend/src/api/admin/autoConfig.ts b/frontend/src/api/admin/autoConfig.ts index 9dff8a3f9f67..459176389784 100644 --- a/frontend/src/api/admin/autoConfig.ts +++ b/frontend/src/api/admin/autoConfig.ts @@ -10,6 +10,7 @@ export type OAuthInitialQualityRule = Pick

{{ t('autoConfig.initial') }}

{{ t('autoConfig.initialHint') }}

- +

{{ t('autoConfig.loadHint') }}

@@ -54,6 +54,13 @@

{{ t('autoConfig.totp429.hint') }}

+
+
+ + +
+

{{ t('autoConfig.disableScheduling429.hint') }}

+
{{ t('autoConfig.groups') }}

{{ t('autoConfig.noGroups') }}

{{ t('autoConfig.quality.title') }} @@ -158,7 +165,7 @@ function unavailableModelBillingGroups(rule: ModelBillingRule) { async function load() { const v = generation; loading.value = true; error.value = '' - try { const [config, available] = await Promise.all([getAutoConfig(), getAll()]); if (validGeneration(v)) { draft.value = { ...config, openai_totp_rotate_on_429: config.openai_totp_rotate_on_429 ?? false, openai_two_fa_admission: config.openai_two_fa_admission ?? defaultOpenAITwoFAAdmissionConfig(), cost_multiplier: config.cost_multiplier ?? 0.07, model_mappings: config.model_mappings ?? defaultOAuthModelMappings(config.platform), model_billing: modelBillingPayload(config.model_billing ?? defaultModelBillingConfig()), excel_bps: config.excel_bps ?? defaultExcelBPSDefaults() }; selectedQualityRule.value = config.quality_rule ? 'saved' : ''; groups.value = available.filter(g => g.status === 'active') } } + try { const [config, available] = await Promise.all([getAutoConfig(), getAll()]); if (validGeneration(v)) { draft.value = { ...config, openai_totp_rotate_on_429: config.openai_totp_rotate_on_429 ?? false, openai_disable_scheduling_on_429: config.openai_disable_scheduling_on_429 ?? false, openai_two_fa_admission: config.openai_two_fa_admission ?? defaultOpenAITwoFAAdmissionConfig(), cost_multiplier: config.cost_multiplier ?? 0.07, model_mappings: config.model_mappings ?? defaultOAuthModelMappings(config.platform), model_billing: modelBillingPayload(config.model_billing ?? defaultModelBillingConfig()), excel_bps: config.excel_bps ?? defaultExcelBPSDefaults() }; selectedQualityRule.value = config.quality_rule ? 'saved' : ''; groups.value = available.filter(g => g.status === 'active') } } catch { if (validGeneration(v)) error.value = t('autoConfig.loadFailed') } finally { if (validGeneration(v)) loading.value = false } } @@ -176,7 +183,7 @@ async function save() { const costMultiplier = c.cost_multiplier ?? 0.07 if (c.enabled && !c.group_ids.length || c.upgrade_enabled && !c.upgrade_group_ids.length || !Number.isFinite(costMultiplier) || costMultiplier < 0 || costMultiplier > 1000000 || [...initialFields, ...upgradeFields].some(f => !Number.isInteger(c[f.key]) || c[f.key] < ('min' in f ? f.min : 1) || c[f.key] > ('max' in f ? f.max : 10000))) { error.value = t('autoConfig.invalid'); return } const v = generation; saving.value = true; error.value = ''; notice.value = '' - try { const { runtime_blocked: _blocked, ...payload } = c; const result = await saveAutoConfig({ ...payload, cost_multiplier: costMultiplier, model_mappings: oauthModelMappingsPayload(c.model_mappings), model_billing: modelBillingPayload(c.model_billing), excel_bps: excelBPSDefaultsPayload(c.excel_bps) }); if (validGeneration(v)) { draft.value = { ...result, openai_totp_rotate_on_429: result.openai_totp_rotate_on_429 ?? false, openai_two_fa_admission: result.openai_two_fa_admission ?? defaultOpenAITwoFAAdmissionConfig(), cost_multiplier: result.cost_multiplier ?? 0.07, model_mappings: result.model_mappings ?? defaultOAuthModelMappings(result.platform), model_billing: modelBillingPayload(result.model_billing ?? defaultModelBillingConfig()), excel_bps: result.excel_bps ?? defaultExcelBPSDefaults() }; selectedQualityRule.value = result.quality_rule ? 'saved' : ''; notice.value = t('autoConfig.saved'); historyRefreshKey.value++ } } + try { const { runtime_blocked: _blocked, ...payload } = c; const result = await saveAutoConfig({ ...payload, cost_multiplier: costMultiplier, model_mappings: oauthModelMappingsPayload(c.model_mappings), model_billing: modelBillingPayload(c.model_billing), excel_bps: excelBPSDefaultsPayload(c.excel_bps) }); if (validGeneration(v)) { draft.value = { ...result, openai_totp_rotate_on_429: result.openai_totp_rotate_on_429 ?? false, openai_disable_scheduling_on_429: result.openai_disable_scheduling_on_429 ?? false, openai_two_fa_admission: result.openai_two_fa_admission ?? defaultOpenAITwoFAAdmissionConfig(), cost_multiplier: result.cost_multiplier ?? 0.07, model_mappings: result.model_mappings ?? defaultOAuthModelMappings(result.platform), model_billing: modelBillingPayload(result.model_billing ?? defaultModelBillingConfig()), excel_bps: result.excel_bps ?? defaultExcelBPSDefaults() }; selectedQualityRule.value = result.quality_rule ? 'saved' : ''; notice.value = t('autoConfig.saved'); historyRefreshKey.value++ } } catch { if (validGeneration(v)) error.value = t('autoConfig.saveFailed') } finally { if (validGeneration(v)) saving.value = false } } diff --git a/frontend/src/views/admin/__tests__/AutoConfigView.spec.ts b/frontend/src/views/admin/__tests__/AutoConfigView.spec.ts index 417093e79df5..510eda1aba15 100644 --- a/frontend/src/views/admin/__tests__/AutoConfigView.spec.ts +++ b/frontend/src/views/admin/__tests__/AutoConfigView.spec.ts @@ -25,7 +25,7 @@ vi.mock('@/api/client', () => ({ apiClient: { get: vi.fn(), put: vi.fn() } })) vi.mock('@/api/admin/autoConfig', async importOriginal => ({ ...await importOriginal(), getAutoConfig: vi.fn(), saveAutoConfig: vi.fn() })) vi.mock('@/api/admin/accountQuality', () => ({ listQualityPlans: vi.fn() })) vi.mock('@/api/admin/groups', () => ({ getAll: vi.fn(), list: vi.fn() })) -const config: AutoConfig = { openai_totp_rotate_on_429: false, openai_two_fa_admission: defaultOpenAITwoFAAdmissionConfig(), model_billing: defaultModelBillingConfig(), model_mappings: defaultOAuthModelMappings('openai'), excel_bps: defaultExcelBPSDefaults(), enabled: false, platform: 'openai', priority: 50, load_factor: 1, concurrency: 3, cost_multiplier: 0.07, group_ids: [], upgrade_enabled: false, upgrade_group_ids: [], successes_per_step: 20, upgrade_step: 1, max_concurrency: 100, cooldown_seconds: 60, revision: '' } +const config: AutoConfig = { openai_totp_rotate_on_429: false, openai_disable_scheduling_on_429: false, openai_two_fa_admission: defaultOpenAITwoFAAdmissionConfig(), model_billing: defaultModelBillingConfig(), model_mappings: defaultOAuthModelMappings('openai'), excel_bps: defaultExcelBPSDefaults(), enabled: false, platform: 'openai', priority: 50, load_factor: 1, concurrency: 3, cost_multiplier: 0.07, group_ids: [], upgrade_enabled: false, upgrade_group_ids: [], successes_per_step: 20, upgrade_step: 1, max_concurrency: 100, cooldown_seconds: 60, revision: '' } beforeEach(() => { localStorage.clear(); setActivePinia(createPinia()) vi.resetAllMocks(); vi.mocked(listQualityPlans).mockResolvedValue([]); state.auth = reactive({ user: { id: 1, role: 'admin' } }) @@ -87,6 +87,81 @@ describe('AutoConfigView', () => { expect(saveAutoConfig).toHaveBeenCalledWith(config) w.unmount() }) + it('shows the scheduling notice after the 2FA notice was dismissed and remembers its own dismissal', async () => { + const id = NEW_FEATURE_NOTICES.oauthInitialDisableScheduling429 + const oldId = NEW_FEATURE_NOTICES.oauthInitialTOTPRotation429 + useNewFeatureNoticeStore().dismiss(1, oldId) + const w = mount(AutoConfigView); await flushPromises() + const schedulingNotice = (view: typeof w) => view.findAllComponents(NewFeatureBadge).find(badge => badge.props('noticeId') === id)! + const rotationNotice = (view: typeof w) => view.findAllComponents(NewFeatureBadge).find(badge => badge.props('noticeId') === oldId)! + const other = mount(NewFeatureBadge, { props: { noticeId: id, userId: 1 } }) + expect(schedulingNotice(w).find('[data-testid="new-feature-badge"]').exists()).toBe(true) + expect(rotationNotice(w).find('[data-testid="new-feature-badge"]').exists()).toBe(false) + await schedulingNotice(w).get('[data-testid="new-feature-badge"]').trigger('click') + expect(schedulingNotice(w).find('[data-testid="new-feature-badge"]').exists()).toBe(false) + expect(other.find('[data-testid="new-feature-badge"]').exists()).toBe(false) + expect(w.get('[data-testid="disable-scheduling-on-429"]').element.checked).toBe(false) + w.unmount(); other.unmount() + setActivePinia(createPinia()) + const reloaded = mount(AutoConfigView); await flushPromises() + expect(schedulingNotice(reloaded).find('[data-testid="new-feature-badge"]').exists()).toBe(false) + expect(rotationNotice(reloaded).find('[data-testid="new-feature-badge"]').exists()).toBe(false) + expect(reloaded.get('[data-testid="initial-model-selection"]').find('[data-testid="new-feature-badge"]').exists()).toBe(true) + const future = mount(NewFeatureBadge, { props: { noticeId: 'future-scheduling-announcement-test', userId: 1 } }) + expect(future.find('[data-testid="new-feature-badge"]').exists()).toBe(true) + reloaded.unmount(); future.unmount() + }) + it.each([ + { disable: true, rotate: false }, + { disable: false, rotate: true }, + { disable: true, rotate: true }, + { disable: false, rotate: false } + ])('saves scheduling and 2FA independently (disable=$disable, rotate=$rotate)', async ({ disable, rotate }) => { + const w = mount(AutoConfigView); await flushPromises() + const checkbox = '[data-testid="disable-scheduling-on-429"]' + expect(w.get(checkbox).element.checked).toBe(false) + expect(w.get(checkbox).element.closest('section')).toBe(w.get('[data-testid="initial-enabled"]').element.closest('section')) + await w.get('[data-testid="initial-enabled"]').setValue(true) + await w.get('[data-testid="initial-group-5"]').setValue(true) + await w.get(checkbox).setValue(disable) + await w.get('[data-testid="totp-rotate-on-429"]').setValue(rotate) + await w.get('form').trigger('submit'); await flushPromises() + const saved = { ...config, enabled: true, group_ids: [5], openai_disable_scheduling_on_429: disable, openai_totp_rotate_on_429: rotate } + expect(saveAutoConfig).toHaveBeenCalledWith(saved) + expect(w.get(checkbox).element.checked).toBe(disable) + w.unmount() + vi.mocked(getAutoConfig).mockResolvedValueOnce(saved) + const reloaded = mount(AutoConfigView); await flushPromises() + expect(reloaded.get(checkbox).element.checked).toBe(disable) + expect(reloaded.get('[data-testid="totp-rotate-on-429"]').element.checked).toBe(rotate) + reloaded.unmount() + }) + it('resets both OpenAI 429 options when changing platforms', async () => { + vi.mocked(getAutoConfig).mockResolvedValueOnce({ ...config, openai_disable_scheduling_on_429: true, openai_totp_rotate_on_429: true }) + const w = mount(AutoConfigView); await flushPromises() + const scheduling = '[data-testid="disable-scheduling-on-429"]', rotation = '[data-testid="totp-rotate-on-429"]' + await w.get('[data-testid="platform"]').setValue('anthropic') + expect(w.find(scheduling).exists()).toBe(false) + expect(w.find(rotation).exists()).toBe(false) + await w.get('form').trigger('submit'); await flushPromises() + expect(saveAutoConfig).toHaveBeenLastCalledWith({ ...config, platform: 'anthropic', selected_models: null, quality_rule: null, model_mappings: [] }) + await w.get('[data-testid="platform"]').setValue('openai') + expect(w.get(scheduling).element.checked).toBe(false) + expect(w.get(rotation).element.checked).toBe(false) + w.unmount() + }) + it('keeps automatic scheduling shutdown off when loading or saving legacy settings', async () => { + const { openai_disable_scheduling_on_429: _scheduling, ...legacy } = config + vi.mocked(getAutoConfig).mockResolvedValueOnce(legacy) + vi.mocked(saveAutoConfig).mockResolvedValueOnce(legacy) + const w = mount(AutoConfigView); await flushPromises() + const checkbox = '[data-testid="disable-scheduling-on-429"]' + expect(w.get(checkbox).element.checked).toBe(false) + await w.get('form').trigger('submit'); await flushPromises() + expect(saveAutoConfig).toHaveBeenCalledWith(config) + expect(w.get(checkbox).element.checked).toBe(false) + w.unmount() + }) it('starts with the Luna 10x rule disabled and saves model billing independently', async () => { const w = mount(AutoConfigView); await flushPromises() expect(w.get('[data-testid="model-billing-enabled"]').element.checked).toBe(false) From 0c09f39227030d096e8f2387db46d2dac4e9675a Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 8 Nov 2026 20:56:52 +0800 Subject: [PATCH 2/4] =?UTF-8?q?test:=20=E4=BF=AE=E5=A4=8D=20OAuth=20?= =?UTF-8?q?=E9=87=8D=E7=99=BB=E8=B0=83=E5=BA=A6=E5=9B=9E=E5=BD=92=E7=9A=84?= =?UTF-8?q?=E4=BA=8B=E5=8A=A1=E6=9F=A5=E8=AF=A2=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...penai_oauth_reauth_scheduling_integration_test.go | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/backend/internal/repository/openai_oauth_reauth_scheduling_integration_test.go b/backend/internal/repository/openai_oauth_reauth_scheduling_integration_test.go index 70ea7aa56d5f..8e1800ab87df 100644 --- a/backend/internal/repository/openai_oauth_reauth_scheduling_integration_test.go +++ b/backend/internal/repository/openai_oauth_reauth_scheduling_integration_test.go @@ -34,11 +34,17 @@ func TestOpenAIReauthPreserves429SchedulingPolicy(t *testing.T) { Type: service.AccountTypeOAuth, Credentials: old, Extra: tc.extra, }) require.NoError(t, tx.Client().Account.UpdateOneID(a.ID).SetSchedulable(tc.before).Exec(ctx)) - var taskID int64 - require.NoError(t, tx.QueryRowContext(ctx, `INSERT INTO openai_oauth_reauth_tasks + rows, err := tx.Client().QueryContext(ctx, `INSERT INTO openai_oauth_reauth_tasks (account_id,status,stage,expected_credentials_hash,worker_id) VALUES ($1,$2,$3,'synthetic-hash','worker') RETURNING id`, - a.ID, service.OpenAIOAuthReauthStatusCallbackProcessing, service.OpenAIOAuthReauthStageApplyingCredentials).Scan(&taskID)) + a.ID, service.OpenAIOAuthReauthStatusCallbackProcessing, service.OpenAIOAuthReauthStageApplyingCredentials) + require.NoError(t, err) + t.Cleanup(func() { _ = rows.Close() }) + require.True(t, rows.Next(), "the callback task must be created in the account transaction") + var taskID int64 + require.NoError(t, rows.Scan(&taskID)) + require.NoError(t, rows.Err()) + require.NoError(t, rows.Close()) applied, err := repo.ApplyOpenAIOAuthReauth(ctx, taskID, "worker", a.ID, old, map[string]any{"access_token": "new", "refresh_token": "new-rt"}, nil) From 1b458856adbb8660bb432b12ba6d057827235eb9 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 8 Nov 2026 21:41:39 +0800 Subject: [PATCH 3/4] =?UTF-8?q?test:=20=E8=A1=A5=E9=BD=90429=E5=81=9C?= =?UTF-8?q?=E8=B0=83=E9=80=89=E9=A1=B9=E7=9A=84=E7=9C=9F=E5=AE=9E=E9=A1=B5?= =?UTF-8?q?=E9=9D=A2=E4=BA=A4=E4=BA=92=E4=B8=8E=E6=88=AA=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../oauth-initial-model-selection-browser.mjs | 37 ++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/.github/scripts/oauth-initial-model-selection-browser.mjs b/.github/scripts/oauth-initial-model-selection-browser.mjs index e0bcf69b9fd9..8d24b484389f 100644 --- a/.github/scripts/oauth-initial-model-selection-browser.mjs +++ b/.github/scripts/oauth-initial-model-selection-browser.mjs @@ -94,8 +94,20 @@ try { const scope = page.getByTestId('initial-model-selection') const initialSection = page.getByTestId('initial-enabled').locator('xpath=ancestor::section') const rotation = page.getByTestId('totp-rotate-on-429') + const disableScheduling = page.getByTestId('disable-scheduling-on-429') assert.equal(await rotation.isChecked(), false) + assert.equal(await disableScheduling.isChecked(), false) await initialSection.screenshot({ path: path.join(output, '429-off-desktop-zh.png') }) + // The scheduling policy is independent of credential rotation. Exercise the + // real checkbox, API payload and reloaded page; do not infer this from labels. + await disableScheduling.check() + await save() + assert.equal(saved.openai_disable_scheduling_on_429, true) + assert.equal(saved.openai_totp_rotate_on_429, false) + await page.reload({ waitUntil: 'networkidle' }) + assert.equal(await disableScheduling.isChecked(), true) + assert.equal(await rotation.isChecked(), false) + await initialSection.screenshot({ path: path.join(output, 'scheduling429-only-desktop-zh.png') }) assert.equal(await page.getByTestId('model-selection-enabled').isChecked(), false) await scope.screenshot({ path: path.join(output, 'unset-desktop-zh.png') }) await page.getByTestId('model-selection-enabled').check() @@ -104,6 +116,7 @@ try { await save() assert(saved.selected_models.includes('gpt-6.1-sol')); assert(!saved.selected_models.includes('gpt-6-luna')) assert.equal(saved.openai_totp_rotate_on_429, true) + assert.equal(saved.openai_disable_scheduling_on_429, true) await initialSection.screenshot({ path: path.join(output, '429-and-selection-desktop-zh.png') }) await scope.screenshot({ path: path.join(output, 'excluded-luna-desktop-zh.png') }) await page.setViewportSize({ width: 390, height: 1000 }) @@ -112,8 +125,17 @@ try { assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)) await page.reload({ waitUntil: 'networkidle' }) assert.equal(await rotation.isChecked(), true) + assert.equal(await disableScheduling.isChecked(), true) assert.equal(await scope.locator('[data-model="gpt-6-luna"]').isChecked(), false) await initialSection.screenshot({ path: path.join(output, '429-reloaded-mobile-zh.png') }) + await disableScheduling.uncheck() + await save() + assert.equal(saved.openai_disable_scheduling_on_429, false) + assert.equal(saved.openai_totp_rotate_on_429, true) + await page.reload({ waitUntil: 'networkidle' }) + assert.equal(await disableScheduling.isChecked(), false) + assert.equal(await rotation.isChecked(), true) + await disableScheduling.check() await page.getByTestId('model-selection-none').click() await page.getByTestId('model-selection-empty').waitFor() await save(); assert.deepEqual(saved.selected_models, []) @@ -121,6 +143,7 @@ try { await page.getByTestId('model-selection-enabled').uncheck(); await save(); assert.equal(saved.selected_models, null) await page.getByTestId('platform').selectOption('anthropic') assert.equal(await rotation.count(), 0) + assert.equal(await disableScheduling.count(), 0) await page.getByTestId('initial-group-6').check() await page.getByTestId('model-selection-enabled').check() assert.equal(await scope.locator('[data-model="gpt-6-luna"]').count(), 0) @@ -129,11 +152,23 @@ try { await page.getByTestId('model-selection-add').click(); await save() assert(saved.selected_models.includes('custom-model')) assert.equal(saved.openai_totp_rotate_on_429, false) + assert.equal(saved.openai_disable_scheduling_on_429, false) await page.setViewportSize({ width: 1280, height: 1000 }) await open('?lang=en') await scope.screenshot({ path: path.join(output, 'anthropic-custom-desktop-en.png') }) + await page.getByTestId('platform').selectOption('openai') + await page.getByTestId('initial-group-5').check() + assert.equal(await disableScheduling.isChecked(), false) + await disableScheduling.check() + await save() + assert.equal(saved.openai_disable_scheduling_on_429, true) + assert.equal(saved.openai_totp_rotate_on_429, false) + await initialSection.screenshot({ path: path.join(output, 'scheduling429-only-desktop-en.png') }) + await page.setViewportSize({ width: 390, height: 1000 }) + await initialSection.screenshot({ path: path.join(output, 'scheduling429-only-mobile-en.png') }) + assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)) assert.deepEqual(errors, []); assert.deepEqual(external, []) - await fs.writeFile(path.join(output, 'verification.json'), JSON.stringify({ head, baselineSHA, synthetic: true, actualPage: 'AutoConfigView.vue', actualComponent: 'OAuthInitialModelSelection.vue', cssRoot: frontend, checks: ['old template before screenshot', 'unset', 'select catalog and exclude Luna', 'save and reload', 'empty explicitly denies all', 'turn off null', '429 opt-in and model selection save/reload together', '429 desktop/mobile screenshots', 'platform switch clears both options', 'custom exact name', 'desktop and mobile', 'no horizontal overflow', 'zh and en', 'no external requests'], requests, saves, errors, external }, null, 2)) + await fs.writeFile(path.join(output, 'verification.json'), JSON.stringify({ head, baselineSHA, synthetic: true, actualPage: 'AutoConfigView.vue', actualComponent: 'OAuthInitialModelSelection.vue', cssRoot: frontend, checks: ['old template before screenshot', 'unset', 'select catalog and exclude Luna', 'save and reload', 'empty explicitly denies all', 'turn off null', '429 scheduling policy independent of rotation; both save/reload together', '429 scheduling opt-out preserves rotation after reload', '429 desktop/mobile screenshots', 'platform switch clears both 429 policies', 'custom exact name', 'desktop and mobile', 'no horizontal overflow', 'zh and en', 'no external requests'], requests, saves, errors, external }, null, 2)) } catch (error) { await fs.writeFile(path.join(output, 'failure.json'), JSON.stringify({ head, error: String(error), errors, external, requests }, null, 2)); throw error } finally { await browser.close(); await server.close(); await fs.rm(baselinePath, { force: true }) } From b847b1c7fe3e15085fabf6c46dd01b581827f8ca Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 8 Nov 2026 21:44:37 +0800 Subject: [PATCH 4/4] =?UTF-8?q?fix:=20=E6=8C=89=E6=AF=8D=E8=B4=A6=E5=8F=B7?= =?UTF-8?q?=E7=AD=96=E7=95=A5=E5=A4=84=E7=90=86=E9=99=84=E5=B1=9EAPIKey?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5429=E5=81=9C=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/openai_disable_scheduling_429.go | 32 +++++-- ...mit_service_disable_scheduling_429_test.go | 84 +++++++++++++++++-- 2 files changed, 102 insertions(+), 14 deletions(-) diff --git a/backend/internal/service/openai_disable_scheduling_429.go b/backend/internal/service/openai_disable_scheduling_429.go index eadfb3b6780f..5d279db99794 100644 --- a/backend/internal/service/openai_disable_scheduling_429.go +++ b/backend/internal/service/openai_disable_scheduling_429.go @@ -10,9 +10,7 @@ import ( const OpenAIDisableSchedulingOn429ExtraKey = "openai_disable_scheduling_on_429" func openAIDisableSchedulingOn429Enabled(account *Account) bool { - // Managed connection projections retain the owning account's ID and policy, - // so their 429s close that account's switch. Spark shadows have their own - // scheduling identity and quota and must not close the primary account. + // Evaluate the persisted owner, not a managed connection's projected type. if account == nil || account.ID <= 0 || account.Platform != PlatformOpenAI || account.Type != AccountTypeOAuth || account.IsShadow() { return false @@ -32,7 +30,8 @@ type openAIDisableScheduling429Observation struct { // successful test or an elapsed 429 window must not reopen the account. The // context marker shares the result across gateway and common error handlers. func (s *RateLimitService) maybeDisableOpenAISchedulingOn429(ctx context.Context, account *Account, status int) (context.Context, bool) { - if s == nil || s.accountRepo == nil || status != http.StatusTooManyRequests || !openAIDisableSchedulingOn429Enabled(account) { + if s == nil || s.accountRepo == nil || status != http.StatusTooManyRequests || account == nil || + account.ID <= 0 || account.Platform != PlatformOpenAI || account.IsShadow() { return ctx, false } if observed, ok := ctx.Value(openAIDisableScheduling429ObservedKey{}).(openAIDisableScheduling429Observation); ok && observed.accountID == account.ID { @@ -40,14 +39,35 @@ func (s *RateLimitService) maybeDisableOpenAISchedulingOn429(ctx context.Context } stateCtx, cancel := openAIAccountStateContext(ctx) defer cancel() - err := s.accountRepo.SetSchedulable(stateCtx, account.ID, false) + // A projected api_key connection can belong to an OAuth account. Conversely, + // a projected OAuth type/Extra must not opt an API Key owner into this policy. + // Resolve the owning account authoritatively, retaining one observation even + // on failure so the common handler does not repeat the read for this error. + ctx = context.WithValue(ctx, openAIDisableScheduling429ObservedKey{}, openAIDisableScheduling429Observation{accountID: account.ID}) + owner := account + if account.AuthConnectionID != "" { + if !account.HasManagedOpenAIConnections() { + slog.Warn("openai_429_disable_scheduling_owner_unverified", "account_id", account.ID) + return ctx, false + } + var err error + owner, err = s.accountRepo.GetByID(stateCtx, account.ID) + if err != nil || owner == nil || owner.ID != account.ID { + slog.Warn("openai_429_disable_scheduling_owner_read_failed", "account_id", account.ID) + return ctx, false + } + } + if !openAIDisableSchedulingOn429Enabled(owner) { + return ctx, false + } + err := s.accountRepo.SetSchedulable(stateCtx, owner.ID, false) if err != nil { // Never log an upstream response, request body or credential here. slog.Warn("openai_429_disable_scheduling_failed", "account_id", account.ID) } else { // SetSchedulable refreshes the shared scheduler snapshot; bridge stale // in-flight candidates immediately and stop same-account 429 retries. - s.notifyAccountSchedulingBlocked(account, time.Time{}, "openai_429_scheduling_disabled") + s.notifyAccountSchedulingBlocked(owner, time.Time{}, "openai_429_scheduling_disabled") slog.Info("openai_429_scheduling_disabled", "account_id", account.ID) } ctx = context.WithValue(ctx, openAIDisableScheduling429ObservedKey{}, openAIDisableScheduling429Observation{accountID: account.ID, disabled: err == nil}) diff --git a/backend/internal/service/ratelimit_service_disable_scheduling_429_test.go b/backend/internal/service/ratelimit_service_disable_scheduling_429_test.go index 0fde4632f344..2f9379ad0e6e 100644 --- a/backend/internal/service/ratelimit_service_disable_scheduling_429_test.go +++ b/backend/internal/service/ratelimit_service_disable_scheduling_429_test.go @@ -15,10 +15,20 @@ import ( type scheduling429Repo struct { rateLimitAccountRepoStub - ids []int64 - values []bool - err error - ctxErr error + ids []int64 + values []bool + err error + ctxErr error + owner *Account + getErr error + reads []int64 + readCtxErr error +} + +func (r *scheduling429Repo) GetByID(ctx context.Context, id int64) (*Account, error) { + r.reads = append(r.reads, id) + r.readCtxErr = ctx.Err() + return r.owner, r.getErr } func (r *scheduling429Repo) SetSchedulable(ctx context.Context, id int64, enabled bool) error { @@ -41,7 +51,8 @@ func TestRateLimitDisableSchedulingOn429ScopeAndObservation(t *testing.T) { want bool }{ {"enabled without saved credentials", 429, func(*Account) {}, true}, - {"managed connection keeps owner identity", 429, func(a *Account) { a.AuthConnectionID = "connection" }, true}, + {"managed connection keeps owner identity", 429, func(a *Account) { a.AuthConnectionID = "connection"; a.Extra["openai_connections_managed"] = true }, true}, + {"unverified connection marker", 429, func(a *Account) { a.AuthConnectionID = "connection" }, false}, {"SIWC", 429, func(a *Account) { a.Extra[OpenAISIWCEnabledKey] = true }, true}, {"PAT", 429, func(a *Account) { a.Credentials = map[string]any{"auth_mode": "personal_access_token"} }, true}, {"agent identity", 429, func(a *Account) { a.Credentials = map[string]any{"auth_mode": OpenAIAuthModeAgentIdentity} }, true}, @@ -55,7 +66,7 @@ func TestRateLimitDisableSchedulingOn429ScopeAndObservation(t *testing.T) { {"unsaved account", 429, func(a *Account) { a.ID = 0 }, false}, } { t.Run(tc.name, func(t *testing.T) { - repo, blocker := &scheduling429Repo{}, &runtimeBlockRecorder{} + repo, blocker := &scheduling429Repo{owner: scheduling429Account()}, &runtimeBlockRecorder{} svc := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) svc.SetAccountRuntimeBlocker(blocker) account := scheduling429Account() @@ -83,7 +94,7 @@ func TestRateLimitDisableSchedulingOn429ScopeAndObservation(t *testing.T) { func TestRateLimitDisableSchedulingOn429PreservesOtherPolicies(t *testing.T) { for _, fail := range []bool{false, true} { t.Run(map[bool]string{false: "saved", true: "write failed"}[fail], func(t *testing.T) { - repo, rotation := &scheduling429Repo{}, &totp429Recorder{} + repo, rotation := &scheduling429Repo{owner: scheduling429Account()}, &totp429Recorder{} if fail { repo.err = errors.New("database unavailable") } @@ -103,7 +114,7 @@ func TestRateLimitDisableSchedulingOn429PreservesOtherPolicies(t *testing.T) { func TestOpenAIGatewayDisableSchedulingOn429Paths(t *testing.T) { for _, path := range []string{"native", "image", "bps", "managed", "managed-bps", "siwc", "websocket-error"} { t.Run(path, func(t *testing.T) { - repo, rotation := &scheduling429Repo{}, &totp429Recorder{} + repo, rotation := &scheduling429Repo{owner: scheduling429Account()}, &totp429Recorder{} rates := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) rates.openAITOTP429Rotator = rotation gateway := &OpenAIGatewayService{rateLimitService: rates} @@ -111,6 +122,7 @@ func TestOpenAIGatewayDisableSchedulingOn429Paths(t *testing.T) { account := scheduling429Account() if path == "managed" || path == "managed-bps" { account.AuthConnectionID = "connection" + account.Extra["openai_connections_managed"] = true } if path == "siwc" { account.Extra[OpenAISIWCEnabledKey] = true @@ -136,6 +148,62 @@ func TestOpenAIGatewayDisableSchedulingOn429Paths(t *testing.T) { } } +func TestRateLimitDisableSchedulingOn429UsesAuthoritativeManagedOwner(t *testing.T) { + for _, tc := range []struct { + name string + owner *Account + readErr error + writeErr error + projectedType string + projectedOptIn bool + want bool + }{ + {name: "historical API Key connection under OAuth owner", owner: scheduling429Account(), projectedType: AccountTypeAPIKey, want: true}, + {name: "OAuth projection with stale opt out", owner: scheduling429Account(), want: true}, + {name: "API Key owner cannot opt in through projection", owner: &Account{ID: 42, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Extra: map[string]any{OpenAIDisableSchedulingOn429ExtraKey: true}}, projectedOptIn: true}, + {name: "OAuth owner opted out since selection", owner: &Account{ID: 42, Platform: PlatformOpenAI, Type: AccountTypeOAuth}, projectedOptIn: true}, + {name: "owner lookup failure", readErr: errors.New("fixture unavailable"), projectedOptIn: true}, + {name: "owner missing", projectedOptIn: true}, + {name: "owner identity mismatch", owner: &Account{ID: 99, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Extra: map[string]any{OpenAIDisableSchedulingOn429ExtraKey: true}}, projectedOptIn: true}, + {name: "scheduling persistence failure", owner: scheduling429Account(), writeErr: errors.New("fixture write failure"), projectedOptIn: true}, + } { + t.Run(tc.name, func(t *testing.T) { + repo := &scheduling429Repo{owner: tc.owner, getErr: tc.readErr, err: tc.writeErr} + blocker := &runtimeBlockRecorder{} + svc := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + svc.SetAccountRuntimeBlocker(blocker) + projection := scheduling429Account() + projection.AuthConnectionID = "synthetic-connection" + projection.Extra["openai_connections_managed"] = true + projection.Extra[OpenAIDisableSchedulingOn429ExtraKey] = tc.projectedOptIn + if tc.projectedType != "" { + projection.Type = tc.projectedType + } + ctx, cancel := context.WithCancel(t.Context()) + cancel() + ctx, disabled := svc.maybeDisableOpenAISchedulingOn429(ctx, projection, 429) + _, repeated := svc.maybeDisableOpenAISchedulingOn429(ctx, projection, 429) + require.Equal(t, tc.want, disabled) + require.Equal(t, disabled, repeated) + require.Equal(t, []int64{42}, repo.reads, "read the mother account once; never infer policy from the projection") + require.NoError(t, repo.readCtxErr, "cancelled upstream requests still allow the bounded owner lookup") + if tc.want || tc.writeErr != nil { + require.Equal(t, []int64{42}, repo.ids) + require.Equal(t, []bool{false}, repo.values) + require.NoError(t, repo.ctxErr) + } else { + require.Empty(t, repo.ids) + } + if tc.want { + require.Equal(t, []string{"openai_429_scheduling_disabled"}, blocker.reasons) + } else { + require.Empty(t, blocker.accounts) + } + require.True(t, projection.Schedulable, "do not mutate shared request snapshots") + }) + } +} + type scheduling429RecoveryRepo struct { rateLimitClearRepoStub writes []bool