From dea1a06d100f58d5922a0c51eead41e5ed3f37ec Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Tue, 10 Nov 2026 23:29:59 +0800 Subject: [PATCH 1/5] feat: guard OAuth 429 scheduling and add API Key fallback handling --- .../admin/account_auto_config_429_test.go | 51 ++++ .../admin/account_auto_config_handler.go | 5 +- .../repository/account_apikey_fallback.go | 34 +++ ...ccount_apikey_fallback_integration_test.go | 117 ++++++++ .../account_apikey_fallback_test.go | 47 +++ .../repository/ops_repo_window_stats.go | 5 +- backend/internal/service/account_ops.go | 66 +++-- backend/internal/service/oauth_auto_config.go | 80 ++++-- .../service/oauth_auto_config_429_test.go | 10 + .../openai_account_runtime_block_fastpath.go | 2 +- .../service/openai_apikey_fallback.go | 269 ++++++++++++++++++ .../openai_apikey_fallback_eligibility.go | 46 +++ ...openai_apikey_fallback_eligibility_test.go | 59 ++++ .../service/openai_apikey_fallback_test.go | 204 +++++++++++++ .../service/openai_disable_scheduling_429.go | 144 +++++++++- ...enai_disable_scheduling_429_weekly_test.go | 244 ++++++++++++++++ backend/internal/service/openai_excel_bps.go | 12 +- .../service/openai_excel_bps_images.go | 2 +- .../service/openai_excel_bps_ratelimit.go | 11 +- backend/internal/service/ops_port.go | 9 +- backend/internal/service/ratelimit_service.go | 2 +- ...mit_service_disable_scheduling_429_test.go | 10 +- backend/internal/service/wire.go | 1 + frontend/src/api/admin/autoConfig.ts | 4 + .../operations/OpenAIAPIKeyFallbackCard.vue | 98 +++++++ frontend/src/constants/newFeatureNotices.ts | 1 + frontend/src/i18n/locales/en/autoConfig.ts | 40 ++- frontend/src/i18n/locales/zh/autoConfig.ts | 40 ++- frontend/src/utils/openaiAPIKeyFallback.ts | 38 +++ frontend/src/views/admin/AutoConfigView.vue | 34 ++- .../admin/__tests__/AutoConfigView.spec.ts | 237 ++++++++++++++- .../__tests__/OAuthDegradationActions.spec.ts | 1 + 32 files changed, 1826 insertions(+), 97 deletions(-) create mode 100644 backend/internal/repository/account_apikey_fallback.go create mode 100644 backend/internal/repository/account_apikey_fallback_integration_test.go create mode 100644 backend/internal/repository/account_apikey_fallback_test.go create mode 100644 backend/internal/service/openai_apikey_fallback.go create mode 100644 backend/internal/service/openai_apikey_fallback_eligibility.go create mode 100644 backend/internal/service/openai_apikey_fallback_eligibility_test.go create mode 100644 backend/internal/service/openai_apikey_fallback_test.go create mode 100644 backend/internal/service/openai_disable_scheduling_429_weekly_test.go create mode 100644 frontend/src/components/admin/operations/OpenAIAPIKeyFallbackCard.vue create mode 100644 frontend/src/utils/openaiAPIKeyFallback.ts diff --git a/backend/internal/handler/admin/account_auto_config_429_test.go b/backend/internal/handler/admin/account_auto_config_429_test.go index b431a529f249..df4707b501c8 100644 --- a/backend/internal/handler/admin/account_auto_config_429_test.go +++ b/backend/internal/handler/admin/account_auto_config_429_test.go @@ -65,3 +65,54 @@ func TestAutoConfigDisableScheduling429SaveAndLegacyClient(t *testing.T) { }) } } + +func TestAutoConfigWeekly429ThresholdSaveValidationAndLegacyClient(t *testing.T) { + gin.SetMode(gin.TestMode) + // An old stored template still receives the safe weekly threshold default. + repo := &opsHandlerWritableSettings{raw: `{"enabled":false,"platform":"openai","openai_disable_scheduling_on_429":true}`} + 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, body string + status int + threshold float64 + }{ + {"legacy default", `{"priority":6}`, http.StatusOK, 98}, + {"fractional value", `{"openai_disable_scheduling_on_429_7d_threshold_percent":97.5}`, http.StatusOK, 97.5}, + {"legacy client preserves saved value", `{"priority":7}`, http.StatusOK, 97.5}, + {"negative", `{"openai_disable_scheduling_on_429_7d_threshold_percent":-1}`, http.StatusBadRequest, 97.5}, + {"over 100", `{"openai_disable_scheduling_on_429_7d_threshold_percent":100.01}`, http.StatusBadRequest, 97.5}, + {"string", `{"openai_disable_scheduling_on_429_7d_threshold_percent":"98"}`, http.StatusBadRequest, 97.5}, + {"null", `{"openai_disable_scheduling_on_429_7d_threshold_percent":null}`, http.StatusBadRequest, 97.5}, + {"boolean", `{"openai_disable_scheduling_on_429_7d_threshold_percent":true}`, http.StatusBadRequest, 97.5}, + {"zero", `{"openai_disable_scheduling_on_429_7d_threshold_percent":0}`, http.StatusOK, 0}, + {"100", `{"openai_disable_scheduling_on_429_7d_threshold_percent":100}`, http.StatusOK, 100}, + } { + 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) + } + 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.threshold, payload.Data.OpenAIDisableSchedulingOn4297dThresholdPercent) + require.True(t, payload.Data.OpenAIDisableSchedulingOn429) + }) + } +} diff --git a/backend/internal/handler/admin/account_auto_config_handler.go b/backend/internal/handler/admin/account_auto_config_handler.go index 530feac31822..d0b125771738 100644 --- a/backend/internal/handler/admin/account_auto_config_handler.go +++ b/backend/internal/handler/admin/account_auto_config_handler.go @@ -16,8 +16,9 @@ func (h *AccountOpsHandler) GetAutoConfig(c *gin.Context) { } response.Success(c, struct { service.OAuthAutoConfig - RuntimeBlocked bool `json:"runtime_blocked"` - }{cfg, h.svc.AutoConfigBlocked()}) + RuntimeBlocked bool `json:"runtime_blocked"` + OpenAIAPIKeyFallbackStatus service.OpenAIAPIKeyFallbackStatus `json:"openai_apikey_fallback_status"` + }{cfg, h.svc.AutoConfigBlocked(), h.svc.OpenAIAPIKeyFallbackStatus()}) } func (h *AccountOpsHandler) SaveAutoConfig(c *gin.Context) { // Preserve fields unknown to older clients, including the BPS template. diff --git a/backend/internal/repository/account_apikey_fallback.go b/backend/internal/repository/account_apikey_fallback.go new file mode 100644 index 000000000000..304e592a9079 --- /dev/null +++ b/backend/internal/repository/account_apikey_fallback.go @@ -0,0 +1,34 @@ +package repository + +import ( + "context" + + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" + "github.com/Wei-Shaw/sub2api/internal/service" +) + +// EnableOpenAIAPIKeyFallback changes only the scheduling switch. Both account +// eligibility and the saved config revision/selection are checked in this write. +// Error state, credentials, cooldowns and scheduled tasks remain intact. +func (r *accountRepository) EnableOpenAIAPIKeyFallback(ctx context.Context, id int64, revision string) (bool, error) { + result, err := r.sql.ExecContext(ctx, `UPDATE accounts SET schedulable=TRUE,updated_at=NOW() + WHERE id=$1 AND deleted_at IS NULL AND platform='openai' AND type='apikey' + AND status='active' AND parent_account_id IS NULL AND schedulable=FALSE + AND (expires_at IS NULL OR expires_at>NOW()) + AND EXISTS (SELECT 1 FROM settings WHERE key=$2 AND value::jsonb->>'revision'=$3 + AND value::jsonb->'openai_apikey_fallback'->>'enabled'='true' + AND value::jsonb->'openai_apikey_fallback'->'account_ids' @> jsonb_build_array($1::bigint))`, + id, service.SettingKeyOAuthAutoConfig, revision) + if err != nil { + return false, err + } + changed, err := result.RowsAffected() + if err != nil || changed == 0 { + return false, err + } + if err := enqueueSchedulerOutbox(ctx, r.sql, service.SchedulerOutboxEventAccountChanged, &id, nil, nil); err != nil { + logger.LegacyPrintf("repository.account", "[SchedulerOutbox] enqueue API Key fallback change failed: account=%d", id) + } + r.syncSchedulerAccountSnapshot(ctx, id) + return true, nil +} diff --git a/backend/internal/repository/account_apikey_fallback_integration_test.go b/backend/internal/repository/account_apikey_fallback_integration_test.go new file mode 100644 index 000000000000..97b8a2bda726 --- /dev/null +++ b/backend/internal/repository/account_apikey_fallback_integration_test.go @@ -0,0 +1,117 @@ +//go:build integration + +package repository + +import ( + "context" + "encoding/json" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestAPIKeyFallbackChecksSavedPolicyAndAccountEligibility(t *testing.T) { + for _, tc := range []struct { + name string + stale, disabled, unselected bool + errorAccount, expired, oauth bool + otherPlatform, shadow, wantOpen bool + }{ + {name: "selected active API key", wantOpen: true}, + {name: "stale revision", stale: true}, + {name: "feature disabled", disabled: true}, + {name: "selection removed", unselected: true}, + {name: "account in error", errorAccount: true}, + {name: "expired account", expired: true}, + {name: "OAuth account", oauth: true}, + {name: "another platform", otherPlatform: true}, + {name: "shadow account", shadow: true}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + tx := testEntTx(t) + client := tx.Client() + repo := newAccountRepositoryWithSQL(client, tx, nil) + account := &service.Account{ + Name: "apikey-fallback-policy", Platform: service.PlatformOpenAI, + Type: service.AccountTypeAPIKey, Status: service.StatusActive, + Credentials: map[string]any{"api_key": "fixture-only", "keep": "credential"}, + Extra: map[string]any{"keep": "metadata"}, ErrorMessage: "retained diagnostic", + } + if tc.errorAccount { + account.Status = service.StatusError + } + if tc.oauth { + account.Type = service.AccountTypeOAuth + } + if tc.otherPlatform { + account.Platform = service.PlatformAnthropic + } + if tc.shadow { + parent := mustCreateAccount(t, client, &service.Account{Name: "fallback-parent"}) + account.ParentAccountID = &parent.ID + } + account = mustCreateAccount(t, client, account) + now := time.Now().UTC().Truncate(time.Microsecond) + future := now.Add(time.Hour) + expires := now.Add(2 * time.Hour) + if tc.expired { + expires = now.Add(-time.Hour) + } + require.NoError(t, client.Account.UpdateOneID(account.ID). + SetSchedulable(false).SetExpiresAt(expires). + SetRateLimitedAt(now).SetRateLimitResetAt(future). + SetOverloadUntil(future).SetTempUnschedulableUntil(future). + Exec(ctx)) + before, err := client.Account.Get(ctx, account.ID) + require.NoError(t, err) + cfg := service.DefaultOAuthAutoConfig() + cfg.Revision = "current-fallback-revision" + cfg.OpenAIAPIKeyFallback.Enabled = !tc.disabled + cfg.OpenAIAPIKeyFallback.AccountIDs = []int64{account.ID} + if tc.unselected { + cfg.OpenAIAPIKeyFallback.AccountIDs = []int64{account.ID + 1} + } + raw, err := json.Marshal(cfg) + require.NoError(t, err) + _, err = tx.ExecContext(ctx, `INSERT INTO settings(key,value) VALUES($1,$2) + ON CONFLICT(key) DO UPDATE SET value=EXCLUDED.value`, service.SettingKeyOAuthAutoConfig, string(raw)) + require.NoError(t, err) + revision := cfg.Revision + if tc.stale { + revision = "outdated-fallback-revision" + } + changed, err := repo.EnableOpenAIAPIKeyFallback(ctx, account.ID, revision) + require.NoError(t, err) + require.Equal(t, tc.wantOpen, changed) + if tc.wantOpen { + changed, err = repo.EnableOpenAIAPIKeyFallback(ctx, account.ID, revision) + require.NoError(t, err) + require.False(t, changed, "repeated evaluation must be idempotent") + } + after, err := client.Account.Get(ctx, account.ID) + require.NoError(t, err) + require.Equal(t, tc.wantOpen, after.Schedulable) + require.Equal(t, before.Status, after.Status) + require.Equal(t, before.Credentials, after.Credentials) + require.Equal(t, before.Extra, after.Extra) + require.Equal(t, before.ErrorMessage, after.ErrorMessage) + require.Equal(t, before.ExpiresAt, after.ExpiresAt) + require.Equal(t, before.RateLimitedAt, after.RateLimitedAt) + require.Equal(t, before.RateLimitResetAt, after.RateLimitResetAt) + require.Equal(t, before.OverloadUntil, after.OverloadUntil) + require.Equal(t, before.TempUnschedulableUntil, after.TempUnschedulableUntil) + var events int + require.NoError(t, scanSingleRow(ctx, tx, + `SELECT COUNT(*) FROM scheduler_outbox WHERE event_type=$1 AND account_id=$2`, + []any{service.SchedulerOutboxEventAccountChanged, account.ID}, &events)) + wantEvents := 0 + if tc.wantOpen { + wantEvents = 1 + } + require.Equal(t, wantEvents, events) + }) + } +} diff --git a/backend/internal/repository/account_apikey_fallback_test.go b/backend/internal/repository/account_apikey_fallback_test.go new file mode 100644 index 000000000000..54d16ca320c3 --- /dev/null +++ b/backend/internal/repository/account_apikey_fallback_test.go @@ -0,0 +1,47 @@ +package repository + +import ( + "context" + "errors" + "testing" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestAPIKeyFallbackChangedRowsControlSchedulingPublication(t *testing.T) { + for _, tc := range []struct { + name string + changed int64 + err error + }{ + {name: "stale configuration or ineligible account"}, + {name: "eligible selected account", changed: 1}, + {name: "write failure", err: errors.New("write failed")}, + } { + t.Run(tc.name, func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer db.Close() + expect := mock.ExpectExec("UPDATE accounts SET schedulable=TRUE,updated_at=NOW\\(\\)").WithArgs(int64(10), service.SettingKeyOAuthAutoConfig, "revision") + if tc.err != nil { + expect.WillReturnError(tc.err) + } else { + expect.WillReturnResult(sqlmock.NewResult(0, tc.changed)) + } + if tc.changed > 0 { + mock.ExpectExec("INSERT INTO scheduler_outbox").WillReturnResult(sqlmock.NewResult(1, 1)) + } + repo := &accountRepository{sql: db} + changed, err := repo.EnableOpenAIAPIKeyFallback(context.Background(), 10, "revision") + require.Equal(t, tc.changed > 0, changed) + if tc.err != nil { + require.Error(t, err) + } else { + require.NoError(t, err) + } + require.NoError(t, mock.ExpectationsWereMet()) + }) + } +} diff --git a/backend/internal/repository/ops_repo_window_stats.go b/backend/internal/repository/ops_repo_window_stats.go index 8221c4735631..eacbcdd2a5ac 100644 --- a/backend/internal/repository/ops_repo_window_stats.go +++ b/backend/internal/repository/ops_repo_window_stats.go @@ -34,7 +34,7 @@ func (r *opsRepository) GetWindowStats(ctx context.Context, filter *service.OpsD return nil, err } - errorTotal, _, _, _, _, _, err := r.queryErrorCounts(ctx, filter, start, end) + errorTotal, _, errorSLA, _, _, _, err := r.queryErrorCounts(ctx, filter, start, end) if err != nil { return nil, err } @@ -46,5 +46,8 @@ func (r *opsRepository) GetWindowStats(ctx context.Context, filter *service.OpsD SuccessCount: successCount, ErrorCountTotal: errorTotal, TokenConsumed: tokenConsumed, + ErrorCountSLA: errorSLA, + RequestCountSLA: successCount + errorSLA, + SLA: safeDivideFloat64(float64(successCount), float64(successCount+errorSLA)), }, nil } diff --git a/backend/internal/service/account_ops.go b/backend/internal/service/account_ops.go index 131599e9c16d..4e03aba93307 100644 --- a/backend/internal/service/account_ops.go +++ b/backend/internal/service/account_ops.go @@ -101,34 +101,37 @@ type AccountOpsService struct { newAPIGroupReader interface { GetBinding(context.Context, int64) (*NewAPIAccountBinding, error) } - newAPIGroupCache sync.Map - accounts AccountRepository - usageCache *UsageCache - encryptor SecretEncryptor - fixedKey bool - timezone *time.Location - robotClient *http.Client - robotMu sync.Mutex - robotLast map[string]time.Time - degradationCursor int64 - autoSeen map[int64]bool - autoConfigMu sync.Mutex - autoGroups GroupRepository - autoAccounts AccountConcurrencyRepository - autoConfig atomic.Value - autoBlocked atomic.Bool - autoResults chan AccountConcurrencyResult - settings SettingRepository - repo AccountOpsRepository - email accountOpsEmailSender - config atomic.Value - queue chan AccountOpsEvent - cancel context.CancelFunc - wg sync.WaitGroup - lifecycle sync.Mutex - settingsMu sync.Mutex - dropped atomic.Uint64 - failures atomic.Uint64 + newAPIGroupCache sync.Map + accounts AccountRepository + usageCache *UsageCache + encryptor SecretEncryptor + fixedKey bool + timezone *time.Location + robotClient *http.Client + robotMu sync.Mutex + robotLast map[string]time.Time + degradationCursor int64 + autoSeen map[int64]bool + autoConfigMu sync.Mutex + autoGroups GroupRepository + autoAccounts AccountConcurrencyRepository + autoConfig atomic.Value + autoBlocked atomic.Bool + fallbackSharedJobs atomic.Bool + fallbackSLAReader atomic.Value + fallbackStatus atomic.Value + autoResults chan AccountConcurrencyResult + settings SettingRepository + repo AccountOpsRepository + email accountOpsEmailSender + config atomic.Value + queue chan AccountOpsEvent + cancel context.CancelFunc + wg sync.WaitGroup + lifecycle sync.Mutex + settingsMu sync.Mutex + dropped atomic.Uint64 + failures atomic.Uint64 } func NewAccountOpsService(settings SettingRepository, repo AccountOpsRepository, email accountOpsEmailSender) *AccountOpsService { @@ -206,11 +209,15 @@ func (s *AccountOpsService) start(runSharedJobs bool) { } ctx, cancel := context.WithCancel(context.Background()) s.cancel = cancel + s.fallbackSharedJobs.Store(runSharedJobs) s.wg.Add(2) go s.runAutoConfig(ctx) go func() { defer s.wg.Done() s.refreshConfig(ctx, runSharedJobs) + if runSharedJobs { + s.evaluateOpenAIAPIKeyFallback(ctx) + } ticker := time.NewTicker(15 * time.Second) defer ticker.Stop() for { @@ -228,6 +235,9 @@ func (s *AccountOpsService) start(runSharedJobs bool) { s.failures.Add(1) } case <-ticker.C: + if runSharedJobs { + s.evaluateOpenAIAPIKeyFallback(ctx) + } if s.refreshConfig(ctx, runSharedJobs) && runSharedJobs { s.scanBalances(ctx) s.deliver(ctx) diff --git a/backend/internal/service/oauth_auto_config.go b/backend/internal/service/oauth_auto_config.go index beb4587fbbfe..4102eb3b3466 100644 --- a/backend/internal/service/oauth_auto_config.go +++ b/backend/internal/service/oauth_auto_config.go @@ -1,11 +1,13 @@ package service import ( + "bytes" "context" "encoding/json" "errors" "fmt" "maps" + "math" "slices" "time" @@ -18,39 +20,59 @@ const AutoConfigConcurrencyExtraKey = "auto_config_concurrency" // Initial account fields, BPS defaults, model billing and concurrency upgrades are independent. type OAuthAutoConfig struct { - DegradationAction OAuthDegradationConfig `json:"degradation_action"` - OpenAITwoFAAdmission OpenAITwoFAAdmissionConfig `json:"openai_two_fa_admission"` - OpenAITOTPRotateOn429 bool `json:"openai_totp_rotate_on_429"` - OpenAIDisableSchedulingOn429 bool `json:"openai_disable_scheduling_on_429"` - OpenAIWSMode *string `json:"openai_ws_mode,omitempty"` - OpenAIWSSSEAcceleration *bool `json:"openai_ws_sse_acceleration,omitempty"` - 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"` + OpenAIAPIKeyFallback OpenAIAPIKeyFallbackConfig `json:"openai_apikey_fallback"` + DegradationAction OAuthDegradationConfig `json:"degradation_action"` + OpenAITwoFAAdmission OpenAITwoFAAdmissionConfig `json:"openai_two_fa_admission"` + OpenAITOTPRotateOn429 bool `json:"openai_totp_rotate_on_429"` + OpenAIDisableSchedulingOn429 bool `json:"openai_disable_scheduling_on_429"` + OpenAIDisableSchedulingOn4297dThresholdPercent float64 `json:"openai_disable_scheduling_on_429_7d_threshold_percent"` + OpenAIWSMode *string `json:"openai_ws_mode,omitempty"` + OpenAIWSSSEAcceleration *bool `json:"openai_ws_sse_acceleration,omitempty"` + 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 (c *OAuthAutoConfig) UnmarshalJSON(data []byte) error { + type configJSON OAuthAutoConfig + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + if raw, exists := fields[OpenAIDisableSchedulingOn4297dThresholdExtraKey]; exists && bytes.Equal(bytes.TrimSpace(raw), []byte("null")) { + return errors.New("7d scheduling threshold must be a number") + } + return json.Unmarshal(data, (*configJSON)(c)) } func DefaultOAuthAutoConfig() OAuthAutoConfig { wsMode, wsSSEAcceleration := OpenAIWSIngressModeCtxPool, false - return OAuthAutoConfig{DegradationAction: DefaultOAuthDegradationConfig(), OpenAIWSMode: &wsMode, OpenAIWSSSEAcceleration: &wsSSEAcceleration, OpenAITwoFAAdmission: DefaultOpenAITwoFAAdmissionConfig(), ModelMappings: defaultOAuthModelMappings(PlatformOpenAI), ModelBilling: DefaultModelBillingConfig(), ExcelBPS: DefaultExcelBPSDefaults(), Platform: PlatformOpenAI, Priority: 50, LoadFactor: 1, Concurrency: 3, CostMultiplier: 0.07, GroupIDs: []int64{}, UpgradeGroupIDs: []int64{}, SuccessesPerStep: 20, UpgradeStep: 1, MaxConcurrency: 100, CooldownSeconds: 60} + return OAuthAutoConfig{OpenAIAPIKeyFallback: DefaultOpenAIAPIKeyFallbackConfig(), OpenAIDisableSchedulingOn4297dThresholdPercent: DefaultOpenAIDisableSchedulingOn4297dThresholdPercent, DegradationAction: DefaultOAuthDegradationConfig(), OpenAIWSMode: &wsMode, OpenAIWSSSEAcceleration: &wsSSEAcceleration, OpenAITwoFAAdmission: DefaultOpenAITwoFAAdmissionConfig(), ModelMappings: defaultOAuthModelMappings(PlatformOpenAI), ModelBilling: DefaultModelBillingConfig(), ExcelBPS: DefaultExcelBPSDefaults(), Platform: PlatformOpenAI, Priority: 50, LoadFactor: 1, Concurrency: 3, CostMultiplier: 0.07, GroupIDs: []int64{}, UpgradeGroupIDs: []int64{}, SuccessesPerStep: 20, UpgradeStep: 1, MaxConcurrency: 100, CooldownSeconds: 60} } func ValidateOAuthAutoConfig(c OAuthAutoConfig) error { + if err := c.OpenAIAPIKeyFallback.Validate(); err != nil { + return err + } + if threshold := c.OpenAIDisableSchedulingOn4297dThresholdPercent; math.IsNaN(threshold) || math.IsInf(threshold, 0) || threshold < 0 || threshold > 100 { + return infraerrors.BadRequest("AUTO_CONFIG_INVALID", "7d scheduling threshold must be a finite number between 0 and 100") + } if err := c.DegradationAction.Validate(); err != nil { return err } @@ -210,6 +232,7 @@ func (s *adminServiceImpl) ApplyOAuthAutoConfig(ctx context.Context, input *Crea if input.Platform == PlatformOpenAI { input.Extra[OpenAITOTPRotateOn429ExtraKey] = c.OpenAITOTPRotateOn429 input.Extra[OpenAIDisableSchedulingOn429ExtraKey] = c.OpenAIDisableSchedulingOn429 + input.Extra[OpenAIDisableSchedulingOn4297dThresholdExtraKey] = c.OpenAIDisableSchedulingOn4297dThresholdPercent applyOAuthInitialWS(input.Extra, c) } return nil @@ -227,6 +250,9 @@ func (s *AccountOpsService) SaveOAuthAutoConfig(ctx context.Context, c OAuthAuto if err := ValidateOAuthAutoConfig(c); err != nil { return c, err } + if err := s.validateOpenAIAPIKeyFallbackAccounts(ctx, c.OpenAIAPIKeyFallback); err != nil { + return c, err + } if c.QualityRule != nil { // Keep only the normalized configuration, never source runtime metadata. plan, err := c.QualityRule.plan(c.Platform) diff --git a/backend/internal/service/oauth_auto_config_429_test.go b/backend/internal/service/oauth_auto_config_429_test.go index 5f371253c819..d45e9b799b2c 100644 --- a/backend/internal/service/oauth_auto_config_429_test.go +++ b/backend/internal/service/oauth_auto_config_429_test.go @@ -24,6 +24,7 @@ func TestOAuthAutoConfigDisableSchedulingOn429Scope(t *testing.T) { t.Run(tc.name, func(t *testing.T) { cfg := DefaultOAuthAutoConfig() cfg.Enabled, cfg.OpenAIDisableSchedulingOn429, cfg.GroupIDs = tc.enabled, tc.disable, []int64{2} + cfg.OpenAIDisableSchedulingOn4297dThresholdPercent = 97.5 if tc.templatePlatform != "" { cfg.Platform = tc.templatePlatform } @@ -50,6 +51,12 @@ func TestOAuthAutoConfigDisableSchedulingOn429Scope(t *testing.T) { } require.NoError(t, svc.ApplyOAuthAutoConfig(ctx, input)) require.Equal(t, tc.want, input.Extra[OpenAIDisableSchedulingOn429ExtraKey]) + if tc.want != nil { + require.Equal(t, 97.5, input.Extra[OpenAIDisableSchedulingOn4297dThresholdExtraKey]) + } else { + require.NotContains(t, input.Extra, OpenAIDisableSchedulingOn4297dThresholdExtraKey) + } + require.NotContains(t, original, OpenAIDisableSchedulingOn4297dThresholdExtraKey) 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") @@ -65,6 +72,8 @@ func TestOAuthAutoConfigDisableSchedulingOn429LegacyAndRoundTrip(t *testing.T) { cfg, err := GetOAuthAutoConfig(t.Context(), repo) require.NoError(t, err) require.False(t, cfg.OpenAIDisableSchedulingOn429, "old settings must not opt in") + require.Equal(t, 98.0, cfg.OpenAIDisableSchedulingOn4297dThresholdPercent) + cfg.OpenAIDisableSchedulingOn4297dThresholdPercent = 97.5 svc := NewAccountOpsService(repo, nil, nil) svc.autoGroups = autoConfigGroups{} for _, rotate := range []bool{false, true} { @@ -75,6 +84,7 @@ func TestOAuthAutoConfigDisableSchedulingOn429LegacyAndRoundTrip(t *testing.T) { loaded, err := GetOAuthAutoConfig(t.Context(), repo) require.NoError(t, err) require.Equal(t, disable, loaded.OpenAIDisableSchedulingOn429) + require.Equal(t, 97.5, loaded.OpenAIDisableSchedulingOn4297dThresholdPercent) 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 31f6aee5ead7..da881b84eeb5 100644 --- a/backend/internal/service/openai_account_runtime_block_fastpath.go +++ b/backend/internal/service/openai_account_runtime_block_fastpath.go @@ -95,7 +95,7 @@ func isOpenAIAccount(account *Account) 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) + ctx, disabledOn429 = s.rateLimitService.maybeDisableOpenAISchedulingOn429(ctx, account, statusCode, headers) if disabledOn429 { defer func() { shouldDisable = true }() } diff --git a/backend/internal/service/openai_apikey_fallback.go b/backend/internal/service/openai_apikey_fallback.go new file mode 100644 index 000000000000..27ef6b600193 --- /dev/null +++ b/backend/internal/service/openai_apikey_fallback.go @@ -0,0 +1,269 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "log/slog" + "math" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +type OpenAIAPIKeyFallbackConfig struct { + Enabled bool `json:"enabled"` + AccountIDs []int64 `json:"account_ids"` + Metric string `json:"metric"` + Threshold float64 `json:"threshold"` + WindowMinutes int `json:"window_minutes"` +} + +func (c *OpenAIAPIKeyFallbackConfig) UnmarshalJSON(data []byte) error { + type configJSON OpenAIAPIKeyFallbackConfig + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + for _, key := range []string{"metric", "threshold", "window_minutes"} { + if raw, ok := fields[key]; ok && string(raw) == "null" { + return errors.New("fallback metric, threshold and window cannot be null") + } + } + return json.Unmarshal(data, (*configJSON)(c)) +} + +func DefaultOpenAIAPIKeyFallbackConfig() OpenAIAPIKeyFallbackConfig { + return OpenAIAPIKeyFallbackConfig{AccountIDs: []int64{}, Metric: "sla", Threshold: 95, WindowMinutes: 5} +} + +func (c OpenAIAPIKeyFallbackConfig) Validate() error { + bad := func(message string) error { return infraerrors.BadRequest("OPENAI_APIKEY_FALLBACK_INVALID", message) } + if c.Metric != "sla" && c.Metric != "health_score" { + return bad("select sla or health_score") + } + if math.IsNaN(c.Threshold) || math.IsInf(c.Threshold, 0) || c.Threshold < 0 || c.Threshold > 100 { + return bad("OpenAI fallback threshold must be a finite number between 0 and 100") + } + if c.WindowMinutes < 1 || c.WindowMinutes > 1440 { + return bad("OpenAI fallback window must be between 1 and 1440 minutes") + } + if len(c.AccountIDs) > 100 || c.Enabled && len(c.AccountIDs) == 0 { + return bad("select between 1 and 100 fallback accounts before enabling") + } + seen := make(map[int64]bool, len(c.AccountIDs)) + for _, id := range c.AccountIDs { + if id <= 0 || seen[id] { + return bad("fallback account IDs must be positive and unique") + } + seen[id] = true + } + return nil +} + +type OpenAIAPIKeyFallbackStatus struct { + LastCheckedAt *time.Time `json:"last_checked_at,omitempty"` + OAuthAccountCount int `json:"oauth_account_count"` + OAuthAvailableCount int `json:"oauth_available_count"` + Metric string `json:"metric"` + MetricValue *float64 `json:"metric_value,omitempty"` + Samples int64 `json:"samples"` + WindowMinutes int `json:"window_minutes"` + LastMetricCheckedAt *time.Time `json:"last_metric_checked_at,omitempty"` + LastTriggerReason string `json:"last_trigger_reason,omitempty"` + LastEnabledAt *time.Time `json:"last_enabled_at,omitempty"` + LastErrorCategory string `json:"last_error_category,omitempty"` +} + +type openAIAPIKeyFallbackSLAReader interface { + GetOpenAIAPIKeyFallbackMetric(context.Context, string, time.Time, time.Time) (*OpenAIAPIKeyFallbackObservation, error) +} +type OpenAIAPIKeyFallbackObservation struct { + Value float64 + Samples int64 +} + +type openAIAPIKeyFallbackReader struct { + reader openAIAPIKeyFallbackSLAReader + settings *SettingService +} + +// The write rechecks the selected account's platform, type, status and disabled +// switch atomically, rather than trusting an earlier inventory snapshot. +type OpenAIAPIKeyFallbackRepository interface { + EnableOpenAIAPIKeyFallback(context.Context, int64, string) (bool, error) +} + +func (s *AccountOpsService) setOpenAIAPIKeyFallbackSLAReader(reader openAIAPIKeyFallbackSLAReader, settings *SettingService) { + if s == nil { + return + } + s.fallbackSLAReader.Store(openAIAPIKeyFallbackReader{reader: reader, settings: settings}) + // Ops is constructed after AccountOps. Complete the full node's first SLA + // check as soon as its reader exists, without waiting for request traffic. + if s.fallbackSharedJobs.Load() { + s.evaluateOpenAIAPIKeyFallback(context.Background()) + } +} + +func (s *AccountOpsService) OpenAIAPIKeyFallbackStatus() OpenAIAPIKeyFallbackStatus { + if s != nil { + if status, ok := s.fallbackStatus.Load().(OpenAIAPIKeyFallbackStatus); ok { + return status + } + } + return OpenAIAPIKeyFallbackStatus{} +} + +func validOpenAIAPIKeyFallbackAccount(account *Account) bool { + return account != nil && account.ID > 0 && account.Platform == PlatformOpenAI && + account.Type == AccountTypeAPIKey && account.IsActive() && !account.IsShadow() && + (account.ExpiresAt == nil || account.ExpiresAt.After(time.Now())) +} + +func (s *AccountOpsService) validateOpenAIAPIKeyFallbackAccounts(ctx context.Context, c OpenAIAPIKeyFallbackConfig) error { + // Stale selections must not prevent an administrator from turning this off. + if !c.Enabled { + return nil + } + if s.accounts == nil { + return infraerrors.ServiceUnavailable("OPENAI_APIKEY_FALLBACK_UNAVAILABLE", "account repository unavailable") + } + accounts, err := s.accounts.GetByIDs(ctx, c.AccountIDs) + if err != nil { + return err + } + valid := make(map[int64]bool, len(accounts)) + for _, account := range accounts { + if validOpenAIAPIKeyFallbackAccount(account) { + valid[account.ID] = true + } + } + for _, id := range c.AccountIDs { + if !valid[id] { + return infraerrors.BadRequest("OPENAI_APIKEY_FALLBACK_ACCOUNT_INVALID", "select active, unexpired OpenAI API Key accounts without a shadow parent") + } + } + return nil +} + +func (s *AccountOpsService) evaluateOpenAIAPIKeyFallback(ctx context.Context) { + if s == nil || !s.fallbackSharedJobs.Load() { + return + } + // Serialize evaluation with local configuration saves, including disable. + s.autoConfigMu.Lock() + defer s.autoConfigMu.Unlock() + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + cfg, err := s.GetOAuthAutoConfig(ctx) + if err != nil || !cfg.OpenAIAPIKeyFallback.Enabled { + return + } + c := cfg.OpenAIAPIKeyFallback + now := time.Now().UTC() + previous := s.OpenAIAPIKeyFallbackStatus() + state := OpenAIAPIKeyFallbackStatus{LastCheckedAt: &now, LastTriggerReason: previous.LastTriggerReason, LastEnabledAt: previous.LastEnabledAt} + defer func() { s.fallbackStatus.Store(state) }() + if s.accounts == nil { + state.LastErrorCategory = "accounts_unavailable" + return + } + accounts, accountErr := s.accounts.ListAllWithFilters(ctx, PlatformOpenAI, AccountTypeOAuth, "", "", 0, "") + if accountErr != nil { + state.LastErrorCategory = "accounts_unavailable" + } + dependency, _ := s.fallbackSLAReader.Load().(openAIAPIKeyFallbackReader) + for i := range accounts { + account := &accounts[i] + if account.Platform != PlatformOpenAI || account.Type != AccountTypeOAuth || account.IsShadow() { + continue + } + state.OAuthAccountCount++ + if openAIAPIKeyFallbackOAuthAvailable(ctx, account, dependency.settings, now) { + state.OAuthAvailableCount++ + } + } + reason := "" + if accountErr == nil && state.OAuthAccountCount > 0 && state.OAuthAvailableCount == 0 { + reason = "oauth_unavailable" + } + state.Metric, state.WindowMinutes = c.Metric, c.WindowMinutes + if previous.Metric == c.Metric && previous.WindowMinutes == c.WindowMinutes { + state.MetricValue, state.Samples, state.LastMetricCheckedAt = previous.MetricValue, previous.Samples, previous.LastMetricCheckedAt + } + // A known empty OAuth pool is sufficient on its own. A slow/unavailable + // monitoring query must not consume the write deadline for that condition. + if reason == "" { + if dependency, ok := s.fallbackSLAReader.Load().(openAIAPIKeyFallbackReader); ok && dependency.reader != nil && + (state.LastMetricCheckedAt == nil || now.Sub(*state.LastMetricCheckedAt) >= time.Minute) { + state.LastMetricCheckedAt, state.MetricValue, state.Samples = &now, nil, 0 + observation, readErr := dependency.reader.GetOpenAIAPIKeyFallbackMetric(ctx, c.Metric, now.Add(-time.Duration(c.WindowMinutes)*time.Minute), now) + if readErr != nil { + state.LastErrorCategory = "metric_unavailable" + } else if observation != nil && observation.Samples > 0 && !math.IsNaN(observation.Value) && !math.IsInf(observation.Value, 0) && observation.Value >= 0 && observation.Value <= 100 { + state.MetricValue, state.Samples = &observation.Value, observation.Samples + } + } + if state.MetricValue != nil && state.Samples > 0 && *state.MetricValue < c.Threshold { + reason = "metric_below_threshold" + } + } + if reason == "" { + return + } + state.LastTriggerReason = reason + writer, ok := s.accounts.(OpenAIAPIKeyFallbackRepository) + if !ok { + state.LastErrorCategory = "account_enable_failed" + return + } + // Read selected accounts independently: an OAuth inventory read failure does + // not invalidate a separately observed low SLA, and only chosen IDs may open. + targets, err := s.accounts.GetByIDs(ctx, c.AccountIDs) + if err != nil { + state.LastErrorCategory = "accounts_unavailable" + return + } + selected := make(map[int64]bool, len(c.AccountIDs)) + for _, id := range c.AccountIDs { + selected[id] = true + } + for _, account := range targets { + if !validOpenAIAPIKeyFallbackAccount(account) || !selected[account.ID] || account.Schedulable { + continue + } + changed, err := writer.EnableOpenAIAPIKeyFallback(ctx, account.ID, cfg.Revision) + if err != nil { + state.LastErrorCategory = "account_enable_failed" + continue + } + if !changed { + continue + } + state.LastEnabledAt = &now + slog.Info("openai_apikey_fallback_enabled", "account_id", account.ID, "reason", reason) + } +} + +func (s *OpsService) GetOpenAIAPIKeyFallbackMetric(ctx context.Context, metric string, start, end time.Time) (*OpenAIAPIKeyFallbackObservation, error) { + if err := s.RequireMonitoringEnabled(ctx); err != nil { + return nil, err + } + if s.opsRepo == nil { + return nil, infraerrors.ServiceUnavailable("OPS_REPO_UNAVAILABLE", "Ops repository not available") + } + filter := &OpsDashboardFilter{StartTime: start, EndTime: end, Platform: PlatformOpenAI} + if metric == "health_score" { + overview, err := s.GetDashboardOverview(ctx, filter) + if err != nil || overview == nil { + return nil, err + } + return &OpenAIAPIKeyFallbackObservation{Value: float64(overview.HealthScore), Samples: overview.RequestCountSLA}, nil + } + stats, err := s.opsRepo.GetWindowStats(ctx, filter) + if err != nil || stats == nil { + return nil, err + } + return &OpenAIAPIKeyFallbackObservation{Value: stats.SLA * 100, Samples: stats.RequestCountSLA}, nil +} diff --git a/backend/internal/service/openai_apikey_fallback_eligibility.go b/backend/internal/service/openai_apikey_fallback_eligibility.go new file mode 100644 index 000000000000..3ff8007b9bda --- /dev/null +++ b/backend/internal/service/openai_apikey_fallback_eligibility.go @@ -0,0 +1,46 @@ +package service + +import ( + "context" + "time" +) + +// Inspect the same persisted account and quota signals used by scheduling without +// enqueueing quota resets, changing account state or making provider requests. +func openAIAPIKeyFallbackOAuthAvailable(ctx context.Context, account *Account, settings *SettingService, now time.Time) bool { + if account == nil || account.Platform != PlatformOpenAI || account.Type != AccountTypeOAuth || account.IsShadow() || !account.IsSchedulable() { + return false + } + var schedulingThresholds map[string]int + if settings != nil { + ctx = withOpenAIQuotaAutoPauseSettings(ctx, settings.GetOpenAIQuotaAutoPauseSettings(ctx)) + schedulingThresholds = settings.GetAccountSchedulingThresholds(ctx) + } + if EvaluateAccountSchedulingThreshold(account, schedulingThresholds, now).ShouldPause { + return false + } + // Imported quota observations for a different identity cannot establish this + // account's exhaustion. The existing threshold evaluator has the same guard. + if !openAICodexSnapshotIdentityTrusted(account) { + return true + } + used5h, has5h := resolveOpenAIQuotaUtilization(account.Extra, "5h", now) + used7d, has7d := resolveOpenAIQuotaUtilization(account.Extra, "7d", now) + pause5h, pause7d := resolveOpenAIQuotaAutoPauseThresholds(ctx, account) + reached5h := !resolveAccountExtraBool(account.Extra, "auto_pause_5h_disabled") && pause5h > 0 && has5h && used5h >= pause5h + reached7d := !resolveAccountExtraBool(account.Extra, "auto_pause_7d_disabled") && pause7d > 0 && has7d && used7d >= pause7d + if config := ResolveOpenAIAutoResetCreditConfig(account); config.Enabled { + if config.Threshold5h > 0 && has5h && used5h >= config.Threshold5h || config.Threshold7d > 0 && has7d && used7d >= config.Threshold7d { + return false + } + if reached5h && config.Threshold5h == 0 || reached7d && config.Threshold7d == 0 { + return false + } + if reached5h || reached7d { + state := openAIAutoResetStateFromExtra(account.Extra) + return state != nil && state.Status == OpenAIAutoResetStatusAvailable && state.AvailableCount > 0 && !openAIAutoResetStateStale(state, now) + } + return true + } + return !reached5h && !reached7d +} diff --git a/backend/internal/service/openai_apikey_fallback_eligibility_test.go b/backend/internal/service/openai_apikey_fallback_eligibility_test.go new file mode 100644 index 000000000000..0c1b14658aef --- /dev/null +++ b/backend/internal/service/openai_apikey_fallback_eligibility_test.go @@ -0,0 +1,59 @@ +//go:build unit + +package service + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestOpenAIAPIKeyFallbackOAuthAvailability(t *testing.T) { + now := time.Now() + future, past := now.Add(time.Hour), now.Add(-time.Hour) + for _, tc := range []struct { + name string + mutate func(*Account) + want bool + }{ + {name: "active without quota evidence", want: true}, + {name: "error", mutate: func(a *Account) { a.Status = StatusError }}, + {name: "inactive", mutate: func(a *Account) { a.Status = StatusDisabled }}, + {name: "manual pause", mutate: func(a *Account) { a.Schedulable = false }}, + {name: "performance pause", mutate: func(a *Account) { a.PerformancePaused = true }}, + {name: "expiry", mutate: func(a *Account) { a.AutoPauseOnExpired = true; a.ExpiresAt = &past }}, + {name: "overload", mutate: func(a *Account) { a.OverloadUntil = &future }}, + {name: "rate limited", mutate: func(a *Account) { a.RateLimitResetAt = &future }}, + {name: "temporary cooldown", mutate: func(a *Account) { a.TempUnschedulableUntil = &future }}, + {name: "elapsed cooldown", mutate: func(a *Account) { a.TempUnschedulableUntil = &past }, want: true}, + {name: "API key", mutate: func(a *Account) { a.Type = AccountTypeAPIKey }}, + {name: "shadow", mutate: func(a *Account) { id := int64(2); a.ParentAccountID = &id }}, + {name: "weekly 100 percent alone is not a scheduling block", mutate: func(a *Account) { a.Extra["codex_7d_used_percent"] = 100.0 }, want: true}, + {name: "five hour 100 percent alone is not a scheduling block", mutate: func(a *Account) { a.Extra["codex_5h_used_percent"] = 100.0 }, want: true}, + {name: "weekly window reset", mutate: func(a *Account) { + a.Extra["codex_7d_used_percent"] = 100.0 + a.Extra["codex_7d_reset_at"] = past.Format(time.RFC3339Nano) + }, want: true}, + {name: "available quota", mutate: func(a *Account) { a.Extra["codex_7d_used_percent"] = 50.0 }, want: true}, + {name: "configured weekly auto pause", mutate: func(a *Account) { a.Extra["codex_7d_used_percent"] = 95.0; a.Extra["auto_pause_7d_threshold"] = 0.9 }}, + {name: "disabled weekly auto pause", mutate: func(a *Account) { + a.Extra["codex_7d_used_percent"] = 95.0 + a.Extra["auto_pause_7d_threshold"] = 0.9 + a.Extra["auto_pause_7d_disabled"] = true + }, want: true}, + {name: "account scheduling threshold", mutate: func(a *Account) { + a.Extra["codex_7d_used_percent"] = 95.0 + a.Extra["codex_7d_reset_at"] = future.Format(time.RFC3339Nano) + a.Credentials = map[string]any{accountSchedulingThresholdCredentialKey: 90} + }}, + } { + t.Run(tc.name, func(t *testing.T) { + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, Extra: map[string]any{"codex_usage_updated_at": now.Format(time.RFC3339Nano)}} + if tc.mutate != nil { + tc.mutate(account) + } + require.Equal(t, tc.want, openAIAPIKeyFallbackOAuthAvailable(t.Context(), account, nil, now)) + }) + } +} diff --git a/backend/internal/service/openai_apikey_fallback_test.go b/backend/internal/service/openai_apikey_fallback_test.go new file mode 100644 index 000000000000..a2e52323041b --- /dev/null +++ b/backend/internal/service/openai_apikey_fallback_test.go @@ -0,0 +1,204 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "math" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +type apiKeyFallbackAccounts struct { + AccountRepository + oauth []Account + targets []*Account + listErr, writeErr error + enabled []int64 + revision string +} + +func (r *apiKeyFallbackAccounts) ListAllWithFilters(_ context.Context, platform, kind, status, search string, groupID int64, privacy string) ([]Account, error) { + if platform != PlatformOpenAI || kind != AccountTypeOAuth || status != "" { + return nil, errors.New("incorrect OAuth inventory scope") + } + return r.oauth, r.listErr +} +func (r *apiKeyFallbackAccounts) GetByIDs(context.Context, []int64) ([]*Account, error) { + return r.targets, nil +} +func (r *apiKeyFallbackAccounts) EnableOpenAIAPIKeyFallback(_ context.Context, id int64, revision string) (bool, error) { + if r.writeErr != nil { + return false, r.writeErr + } + r.enabled = append(r.enabled, id) + r.revision = revision + for _, a := range r.targets { + if a.ID == id { + a.Schedulable = true + } + } + return true, nil +} + +type apiKeyFallbackMetrics struct { + value float64 + samples int64 + err error + calls int + metric string + window time.Duration +} + +func (r *apiKeyFallbackMetrics) GetOpenAIAPIKeyFallbackMetric(_ context.Context, metric string, start, end time.Time) (*OpenAIAPIKeyFallbackObservation, error) { + r.calls++ + r.metric = metric + r.window = end.Sub(start) + return &OpenAIAPIKeyFallbackObservation{Value: r.value, Samples: r.samples}, r.err +} +func apiKeyFallbackFixture(t *testing.T, accounts *apiKeyFallbackAccounts, metric *apiKeyFallbackMetrics) *AccountOpsService { + t.Helper() + cfg := DefaultOAuthAutoConfig() + cfg.Revision = "fallback-revision" + cfg.OpenAIAPIKeyFallback.Enabled, cfg.OpenAIAPIKeyFallback.AccountIDs = true, []int64{10} + raw, err := json.Marshal(cfg) + require.NoError(t, err) + svc := NewAccountOpsService(&accountOpsSettingsStub{raw: string(raw)}, nil, nil) + svc.accounts = accounts + svc.fallbackSharedJobs.Store(true) + svc.fallbackSLAReader.Store(openAIAPIKeyFallbackReader{reader: metric}) + return svc +} +func TestOpenAIAPIKeyFallbackIndependentTriggersAndNoSampleGuard(t *testing.T) { + until := time.Now().Add(time.Hour) + for _, tc := range []struct { + name string + oauth []Account + metric apiKeyFallbackMetrics + want bool + }{ + {name: "all OAuth manually paused", oauth: []Account{{Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive}}, want: true}, + {name: "all OAuth are error", oauth: []Account{{Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusError}}, want: true}, + {name: "all OAuth rate limited", oauth: []Account{{Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, RateLimitResetAt: &until}}, want: true}, + {name: "one available OAuth", oauth: []Account{{Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true}}}, + {name: "no OAuth is not an outage"}, + {name: "no OAuth but poor SLA", metric: apiKeyFallbackMetrics{value: 94, samples: 100}, want: true}, + {name: "no samples", metric: apiKeyFallbackMetrics{value: 0, samples: 0}}, + {name: "equal SLA threshold", metric: apiKeyFallbackMetrics{value: 95, samples: 100}}, + {name: "metric failure", metric: apiKeyFallbackMetrics{value: 0, samples: 100, err: errors.New("unavailable")}}, + {name: "metric failure does not block OAuth trigger", oauth: []Account{{Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusError}}, metric: apiKeyFallbackMetrics{err: errors.New("unavailable")}, want: true}, + } { + t.Run(tc.name, func(t *testing.T) { + account := &Account{ID: 10, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, RateLimitResetAt: &until, ErrorMessage: "keep", Credentials: map[string]any{"keep": "unchanged"}} + repo := &apiKeyFallbackAccounts{oauth: tc.oauth, targets: []*Account{account}} + svc := apiKeyFallbackFixture(t, repo, &tc.metric) + svc.evaluateOpenAIAPIKeyFallback(t.Context()) + require.Equal(t, tc.want, account.Schedulable) + if tc.want { + require.Equal(t, []int64{10}, repo.enabled) + require.Equal(t, "fallback-revision", repo.revision) + } + require.Equal(t, &until, account.RateLimitResetAt) + require.Equal(t, "keep", account.ErrorMessage) + require.Equal(t, map[string]any{"keep": "unchanged"}, account.Credentials) + }) + } +} +func TestOpenAIAPIKeyFallbackTargetsAndFullNodeBoundary(t *testing.T) { + parent := int64(1) + past := time.Now().Add(-time.Hour) + for _, tc := range []struct { + name string + target Account + gateway bool + }{ + {name: "unselected", target: Account{ID: 11, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive}}, + {name: "error", target: Account{ID: 10, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusError}}, + {name: "expired", target: Account{ID: 10, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, ExpiresAt: &past}}, + {name: "inactive", target: Account{ID: 10, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusDisabled}}, + {name: "shadow", target: Account{ID: 10, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, ParentAccountID: &parent}}, + {name: "other platform", target: Account{ID: 10, Platform: PlatformAnthropic, Type: AccountTypeAPIKey, Status: StatusActive}}, + {name: "OAuth target", target: Account{ID: 10, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive}}, + {name: "gateway", target: Account{ID: 10, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive}, gateway: true}, + } { + t.Run(tc.name, func(t *testing.T) { + repo := &apiKeyFallbackAccounts{targets: []*Account{&tc.target}} + metric := &apiKeyFallbackMetrics{value: 90, samples: 10} + svc := apiKeyFallbackFixture(t, repo, metric) + if tc.gateway { + svc.fallbackSharedJobs.Store(false) + } + svc.evaluateOpenAIAPIKeyFallback(t.Context()) + require.Empty(t, repo.enabled) + }) + } +} +func TestOpenAIAPIKeyFallbackCachesMetricsAndNeverClosesAfterRecovery(t *testing.T) { + a := &Account{ID: 10, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive} + repo := &apiKeyFallbackAccounts{targets: []*Account{a}} + metric := &apiKeyFallbackMetrics{value: 90, samples: 100} + svc := apiKeyFallbackFixture(t, repo, metric) + svc.evaluateOpenAIAPIKeyFallback(t.Context()) + svc.evaluateOpenAIAPIKeyFallback(t.Context()) + require.Equal(t, 1, metric.calls) + require.Equal(t, 5*time.Minute, metric.window) + require.Equal(t, []int64{10}, repo.enabled) + state := svc.OpenAIAPIKeyFallbackStatus() + old := time.Now().Add(-2 * time.Minute) + state.LastMetricCheckedAt = &old + svc.fallbackStatus.Store(state) + metric.value = 100 + svc.evaluateOpenAIAPIKeyFallback(t.Context()) + require.True(t, a.Schedulable) + require.Equal(t, []int64{10}, repo.enabled) +} +func TestOpenAIAPIKeyFallbackConfiguration(t *testing.T) { + cfg, err := GetOAuthAutoConfig(t.Context(), &accountOpsSettingsStub{raw: `{"platform":"openai"}`}) + require.NoError(t, err) + require.Equal(t, DefaultOpenAIAPIKeyFallbackConfig(), cfg.OpenAIAPIKeyFallback) + for _, mutate := range []func(*OpenAIAPIKeyFallbackConfig){ + func(c *OpenAIAPIKeyFallbackConfig) { c.Metric = "other" }, + func(c *OpenAIAPIKeyFallbackConfig) { c.Threshold = math.NaN() }, + func(c *OpenAIAPIKeyFallbackConfig) { c.Threshold = 101 }, + func(c *OpenAIAPIKeyFallbackConfig) { c.WindowMinutes = 0 }, + func(c *OpenAIAPIKeyFallbackConfig) { c.WindowMinutes = 1441 }, + func(c *OpenAIAPIKeyFallbackConfig) { c.AccountIDs = []int64{10, 10} }, + func(c *OpenAIAPIKeyFallbackConfig) { c.Enabled = true }, + } { + c := DefaultOpenAIAPIKeyFallbackConfig() + mutate(&c) + require.Error(t, c.Validate()) + } + c := DefaultOpenAIAPIKeyFallbackConfig() + c.Metric = "health_score" + c.WindowMinutes = 1440 + require.NoError(t, c.Validate()) + repo := &apiKeyFallbackAccounts{targets: []*Account{{ID: 10, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive}}} + svc := apiKeyFallbackFixture(t, repo, &apiKeyFallbackMetrics{}) + c.Enabled, c.AccountIDs = true, []int64{10} + require.Error(t, svc.validateOpenAIAPIKeyFallbackAccounts(t.Context(), c)) + c.Enabled = false + require.NoError(t, svc.validateOpenAIAPIKeyFallbackAccounts(t.Context(), c)) +} + +func TestOpenAIAPIKeyFallbackHealthMetricAndConfiguredWindow(t *testing.T) { + repo := &apiKeyFallbackAccounts{targets: []*Account{{ID: 10, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive}}} + metric := &apiKeyFallbackMetrics{value: 70, samples: 100} + svc := apiKeyFallbackFixture(t, repo, metric) + cfg, err := svc.GetOAuthAutoConfig(t.Context()) + require.NoError(t, err) + cfg.OpenAIAPIKeyFallback.Metric, cfg.OpenAIAPIKeyFallback.Threshold, cfg.OpenAIAPIKeyFallback.WindowMinutes = "health_score", 80, 30 + raw, err := json.Marshal(cfg) + require.NoError(t, err) + svc.settings.(*accountOpsSettingsStub).raw = string(raw) + svc.evaluateOpenAIAPIKeyFallback(t.Context()) + require.Equal(t, "health_score", metric.metric) + require.Equal(t, 30*time.Minute, metric.window) + require.Equal(t, []int64{10}, repo.enabled) + state := svc.OpenAIAPIKeyFallbackStatus() + require.Equal(t, "health_score", state.Metric) + require.Equal(t, "metric_below_threshold", state.LastTriggerReason) + require.Equal(t, 70.0, *state.MetricValue) +} diff --git a/backend/internal/service/openai_disable_scheduling_429.go b/backend/internal/service/openai_disable_scheduling_429.go index 5d279db99794..ab9d5251a4ac 100644 --- a/backend/internal/service/openai_disable_scheduling_429.go +++ b/backend/internal/service/openai_disable_scheduling_429.go @@ -2,12 +2,145 @@ package service import ( "context" + "fmt" "log/slog" + "math" "net/http" + "strconv" "time" ) -const OpenAIDisableSchedulingOn429ExtraKey = "openai_disable_scheduling_on_429" +const ( + OpenAIDisableSchedulingOn429ExtraKey = "openai_disable_scheduling_on_429" + OpenAIDisableSchedulingOn4297dThresholdExtraKey = "openai_disable_scheduling_on_429_7d_threshold_percent" + DefaultOpenAIDisableSchedulingOn4297dThresholdPercent = 98.0 +) + +func openAI429WeeklyThreshold(account *Account) (float64, bool) { + if _, exists := account.Extra[OpenAIDisableSchedulingOn4297dThresholdExtraKey]; !exists { + return DefaultOpenAIDisableSchedulingOn4297dThresholdPercent, true + } + threshold, ok := resolveAccountExtraNumber(account.Extra, OpenAIDisableSchedulingOn4297dThresholdExtraKey) + return threshold, ok && validOpenAI429Percent(threshold) +} + +func validOpenAI429Percent(value float64) bool { + return !math.IsNaN(value) && !math.IsInf(value, 0) && value >= 0 && value <= 100 +} + +// Read this response directly: persistence happens later and may be throttled. +// A present but invalid/low weekly observation must never fall back to an older +// high snapshot. The five-hour window does not participate in this policy. +func openAI429WeeklyHeaderUsage(headers http.Header) (used float64, present, valid bool) { + hasObservation := false + for _, window := range []string{"primary", "secondary"} { + for _, field := range []string{"used-percent", "window-minutes", "reset-after-seconds"} { + _, exists := headers[http.CanonicalHeaderKey("x-codex-"+window+"-"+field)] + hasObservation = hasObservation || exists + } + } + if !hasObservation { + return 0, false, false + } + snapshot := ParseCodexRateLimitHeaders(headers) + if snapshot == nil { + return 0, true, false + } + // A permanent pause must not rely on Normalize's legacy primary=7d + // assumption. Require exactly one explicitly identified weekly window. + prefix := "" + for _, window := range []string{"primary", "secondary"} { + if key := "x-codex-" + window + "-window-minutes"; len(headers.Values(key)) > 0 { + minutes, err := strconv.Atoi(headers.Get(key)) + if err != nil || minutes <= 0 { + return 0, true, false + } + if minutes == 7*24*60 { + if prefix != "" { + return 0, true, false + } + prefix = "x-codex-" + window + "-" + } + } + } + if prefix == "" { + return 0, true, false + } + weekly := snapshot.PrimaryUsedPercent + if prefix == "x-codex-secondary-" { + weekly = snapshot.SecondaryUsedPercent + } + if weekly == nil || !validOpenAI429Percent(*weekly) { + return 0, true, false + } + if key := prefix + "reset-after-seconds"; len(headers.Values(key)) > 0 { + seconds, err := strconv.ParseInt(headers.Get(key), 10, 64) + if err != nil || seconds <= 0 || seconds > int64((7*24*time.Hour)/time.Second) { + return 0, true, false + } + } + return *weekly, true, true +} + +func openAI429WeeklyUsage(account *Account, headers http.Header, now time.Time) (float64, bool) { + if used, present, valid := openAI429WeeklyHeaderUsage(headers); present { + return used, valid + } + if !openAICodexSnapshotIdentityTrusted(account) { + return 0, false + } + extra := account.Extra + if _, exists := extra["codex_7d_window_minutes"]; exists { + minutes, ok := resolveAccountExtraNumber(extra, "codex_7d_window_minutes") + if !ok || minutes != 7*24*60 { + return 0, false + } + } + used, ok := resolveAccountExtraNumber(extra, "codex_7d_used_percent") + if !ok || !validOpenAI429Percent(used) { + return 0, false + } + observed := codexUpdatesTime(extra) + if versions, exists := extra[CodexUsageFieldVersionsKey]; exists { + fields, ok := versions.(map[string]any) + if !ok { + return 0, false + } + stamp, err := strconv.ParseInt(fmt.Sprint(fields["codex_7d_used_percent"]), 10, 64) + if err != nil || stamp <= 0 { + return 0, false + } + observed = time.Unix(0, stamp) + } + // Permanent pauses require a known, recent observation, unlike temporary + // scheduling guards that may retain legacy snapshots without timestamps. + if observed.IsZero() || observed.After(now) || now.Sub(observed) >= openAICodexAutoPauseStaleAfter { + return 0, false + } + if raw, exists := extra["codex_7d_reset_at"]; exists { + reset, err := parseTime(fmt.Sprint(raw)) + if err != nil || !reset.After(now) { + return 0, false + } + } else if raw, exists := extra["codex_7d_reset_after_seconds"]; exists { + seconds, err := strconv.ParseInt(fmt.Sprint(raw), 10, 64) + if err != nil || seconds <= 0 || seconds > int64((7*24*time.Hour)/time.Second) { + return 0, false + } + resetObserved := codexUpdatesTime(extra) + if fields, ok := extra[CodexUsageFieldVersionsKey].(map[string]any); ok { + stamp, err := strconv.ParseInt(fmt.Sprint(fields["codex_7d_reset_after_seconds"]), 10, 64) + if err != nil || stamp <= 0 { + return 0, false + } + resetObserved = time.Unix(0, stamp) + } + if resetObserved.IsZero() || resetObserved.After(now) || !resetObserved.Add(time.Duration(seconds)*time.Second).After(now) { + return 0, false + } + } + return used, true +} func openAIDisableSchedulingOn429Enabled(account *Account) bool { // Evaluate the persisted owner, not a managed connection's projected type. @@ -29,7 +162,7 @@ type openAIDisableScheduling429Observation struct { // 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) { +func (s *RateLimitService) maybeDisableOpenAISchedulingOn429(ctx context.Context, account *Account, status int, headers http.Header) (context.Context, bool) { if s == nil || s.accountRepo == nil || status != http.StatusTooManyRequests || account == nil || account.ID <= 0 || account.Platform != PlatformOpenAI || account.IsShadow() { return ctx, false @@ -60,6 +193,11 @@ func (s *RateLimitService) maybeDisableOpenAISchedulingOn429(ctx context.Context if !openAIDisableSchedulingOn429Enabled(owner) { return ctx, false } + threshold, thresholdValid := openAI429WeeklyThreshold(owner) + used, usageValid := openAI429WeeklyUsage(owner, headers, time.Now()) + if !thresholdValid || !usageValid || used <= threshold { + return ctx, false + } err := s.accountRepo.SetSchedulable(stateCtx, owner.ID, false) if err != nil { // Never log an upstream response, request body or credential here. @@ -68,7 +206,7 @@ func (s *RateLimitService) maybeDisableOpenAISchedulingOn429(ctx context.Context // SetSchedulable refreshes the shared scheduler snapshot; bridge stale // in-flight candidates immediately and stop same-account 429 retries. s.notifyAccountSchedulingBlocked(owner, time.Time{}, "openai_429_scheduling_disabled") - slog.Info("openai_429_scheduling_disabled", "account_id", account.ID) + slog.Info("openai_429_scheduling_disabled", "account_id", account.ID, "weekly_used_percent", used, "threshold_percent", threshold) } ctx = context.WithValue(ctx, openAIDisableScheduling429ObservedKey{}, openAIDisableScheduling429Observation{accountID: account.ID, disabled: err == nil}) return ctx, err == nil diff --git a/backend/internal/service/openai_disable_scheduling_429_weekly_test.go b/backend/internal/service/openai_disable_scheduling_429_weekly_test.go new file mode 100644 index 000000000000..591b81ca8a74 --- /dev/null +++ b/backend/internal/service/openai_disable_scheduling_429_weekly_test.go @@ -0,0 +1,244 @@ +//go:build unit + +package service + +import ( + "encoding/json" + "math" + "net/http" + "strconv" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +func weekly429Headers(weekly, fiveHour string, reverse bool) http.Header { + headers := http.Header{} + week, short := "primary", "secondary" + if reverse { + week, short = short, week + } + headers.Set("x-codex-"+week+"-window-minutes", "10080") + headers.Set("x-codex-"+short+"-window-minutes", "300") + if weekly != "" { + headers.Set("x-codex-"+week+"-used-percent", weekly) + } + if fiveHour != "" { + headers.Set("x-codex-"+short+"-used-percent", fiveHour) + } + return headers +} + +func TestDisableScheduling429RequiresWeeklyUsageStrictlyAboveThreshold(t *testing.T) { + for _, tc := range []struct { + name string + mutate func(*Account) + headers http.Header + want bool + }{ + {name: "legacy account defaults to 98", want: true}, + {name: "exactly 98 does not disable", mutate: func(a *Account) { a.Extra["codex_7d_used_percent"] = 98.0 }}, + {name: "fraction above default", mutate: func(a *Account) { a.Extra["codex_7d_used_percent"] = 98.01 }, want: true}, + {name: "custom fractional threshold", mutate: func(a *Account) { a.Extra[OpenAIDisableSchedulingOn4297dThresholdExtraKey] = 99.5 }}, + {name: "custom lower threshold", mutate: func(a *Account) { a.Extra[OpenAIDisableSchedulingOn4297dThresholdExtraKey] = 97.5 }, want: true}, + {name: "zero is a valid configured threshold", mutate: func(a *Account) { a.Extra[OpenAIDisableSchedulingOn4297dThresholdExtraKey] = 0.0 }, want: true}, + {name: "100 never exceeded by valid usage", mutate: func(a *Account) { a.Extra[OpenAIDisableSchedulingOn4297dThresholdExtraKey] = 100.0 }, headers: weekly429Headers("100", "100", false)}, + {name: "five hour exhaustion alone", mutate: func(a *Account) { a.Extra["codex_7d_used_percent"] = 20.0; a.Extra["codex_5h_used_percent"] = 100.0 }}, + {name: "missing weekly usage", mutate: func(a *Account) { delete(a.Extra, "codex_7d_used_percent"); a.Extra["codex_5h_used_percent"] = 100.0 }}, + {name: "cached short window mislabeled as weekly", mutate: func(a *Account) { a.Extra["codex_7d_window_minutes"] = 300 }}, + {name: "missing timestamp", mutate: func(a *Account) { delete(a.Extra, "codex_usage_updated_at") }}, + {name: "invalid timestamp", mutate: func(a *Account) { a.Extra["codex_usage_updated_at"] = "invalid" }}, + {name: "future observation", mutate: func(a *Account) { + a.Extra["codex_usage_updated_at"] = time.Now().Add(time.Hour).Format(time.RFC3339Nano) + }}, + {name: "stale snapshot", mutate: func(a *Account) { + a.Extra["codex_usage_updated_at"] = time.Now().Add(-3 * time.Hour).Format(time.RFC3339Nano) + }}, + {name: "stale weekly field with fresh five hour update", mutate: func(a *Account) { + a.Extra[CodexUsageFieldVersionsKey] = map[string]any{"codex_7d_used_percent": strconv.FormatInt(time.Now().Add(-3*time.Hour).UnixNano(), 10)} + }}, + {name: "unknown weekly field version", mutate: func(a *Account) { a.Extra[CodexUsageFieldVersionsKey] = map[string]any{} }}, + {name: "already reset", mutate: func(a *Account) { a.Extra["codex_7d_reset_at"] = time.Now().Add(-time.Minute).Format(time.RFC3339Nano) }}, + {name: "invalid reset", mutate: func(a *Account) { a.Extra["codex_7d_reset_at"] = "invalid" }}, + {name: "relative reset already passed", mutate: func(a *Account) { a.Extra["codex_7d_reset_after_seconds"] = 1 }}, + {name: "identity mismatch", mutate: func(a *Account) { + a.Credentials = map[string]any{"chatgpt_account_id": "owner"} + a.Extra["chatgpt_account_id"] = "other" + }}, + {name: "new low header overrides old high snapshot", headers: weekly429Headers("20", "100", false)}, + {name: "new high header overrides old low snapshot", mutate: func(a *Account) { a.Extra["codex_7d_used_percent"] = 20.0 }, headers: weekly429Headers("99", "20", false), want: true}, + {name: "latest equality overrides old high", headers: weekly429Headers("98", "100", false)}, + {name: "reversed windows do not confuse five hour quota", headers: weekly429Headers("20", "100", true)}, + {name: "reversed weekly quota", headers: weekly429Headers("99", "20", true), want: true}, + {name: "five hour header alone cannot confirm cached weekly exhaustion", headers: weekly429Headers("", "100", false)}, + {name: "new header validates otherwise stale snapshot", mutate: func(a *Account) { a.Extra["codex_usage_updated_at"] = "invalid" }, headers: weekly429Headers("99", "20", false), want: true}, + {name: "invalid current weekly header blocks fallback", headers: weekly429Headers("invalid", "100", false)}, + {name: "negative current weekly usage", headers: weekly429Headers("-1", "100", false)}, + {name: "over 100 current weekly usage", headers: weekly429Headers("101", "100", false)}, + {name: "NaN current weekly usage", headers: weekly429Headers("NaN", "100", false)}, + {name: "infinite current weekly usage", headers: weekly429Headers("+Inf", "100", false)}, + {name: "current reset already elapsed", headers: func() http.Header { + h := weekly429Headers("99", "100", false) + h.Set("x-codex-primary-reset-after-seconds", "0") + return h + }()}, + {name: "empty current reset", headers: func() http.Header { + h := weekly429Headers("99", "100", false) + h.Set("x-codex-primary-reset-after-seconds", "") + return h + }()}, + {name: "reset-only response cannot reuse cached high usage", headers: func() http.Header { h := http.Header{}; h.Set("x-codex-primary-reset-after-seconds", "0"); return h }()}, + {name: "weekly reset and window without usage cannot reuse cached high", headers: func() http.Header { + h := http.Header{} + h.Set("x-codex-primary-reset-after-seconds", "0") + h.Set("x-codex-primary-window-minutes", "10080") + return h + }()}, + {name: "weekly window alone cannot reuse cached high", headers: func() http.Header { h := http.Header{}; h.Set("x-codex-primary-window-minutes", "10080"); return h }()}, + {name: "short window alone cannot reuse cached high", headers: func() http.Header { h := http.Header{}; h.Set("x-codex-primary-window-minutes", "300"); return h }()}, + {name: "empty window cannot reuse cached high", headers: func() http.Header { h := http.Header{}; h.Set("x-codex-primary-window-minutes", ""); return h }()}, + {name: "empty weekly window invalidates current high usage", headers: func() http.Header { + h := weekly429Headers("99", "100", false) + h.Set("x-codex-primary-window-minutes", "") + return h + }()}, + {name: "nil header values still invalidate observation", headers: http.Header{http.CanonicalHeaderKey("x-codex-primary-window-minutes"): nil}}, + {name: "invalid current reset", headers: func() http.Header { + h := weekly429Headers("99", "100", false) + h.Set("x-codex-primary-reset-after-seconds", "invalid") + return h + }()}, + {name: "two short windows cannot invent weekly quota", headers: func() http.Header { + h := weekly429Headers("99", "100", false) + h.Set("x-codex-primary-window-minutes", "60") + return h + }()}, + {name: "legacy unclassified primary may be five hour", headers: func() http.Header { h := http.Header{}; h.Set("x-codex-primary-used-percent", "100"); return h }()}, + {name: "two weekly windows are ambiguous", headers: func() http.Header { + h := weekly429Headers("99", "100", false) + h.Set("x-codex-secondary-window-minutes", "10080") + return h + }()}, + {name: "empty current weekly header", headers: func() http.Header { + h := weekly429Headers("99", "100", false) + h.Set("x-codex-primary-used-percent", "") + return h + }()}, + {name: "invalid current window", headers: func() http.Header { + h := weekly429Headers("99", "100", false) + h.Set("x-codex-primary-window-minutes", "invalid") + return h + }()}, + } { + t.Run(tc.name, func(t *testing.T) { + account := scheduling429Account() + if tc.mutate != nil { + tc.mutate(account) + } + repo, blocker := &scheduling429Repo{}, &runtimeBlockRecorder{} + rates := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + rates.SetAccountRuntimeBlocker(blocker) + ctx, disabled := rates.maybeDisableOpenAISchedulingOn429(t.Context(), account, http.StatusTooManyRequests, tc.headers) + _, repeated := rates.maybeDisableOpenAISchedulingOn429(ctx, account, http.StatusTooManyRequests, tc.headers) + require.Equal(t, tc.want, disabled) + require.Equal(t, disabled, repeated) + if tc.want { + require.Equal(t, []int64{account.ID}, repo.ids) + require.Equal(t, []bool{false}, repo.values) + } else { + require.Empty(t, repo.ids) + require.Empty(t, blocker.accounts) + } + }) + } +} + +func TestDisableScheduling429RejectsInvalidStoredThresholdsAndUsage(t *testing.T) { + for _, key := range []string{OpenAIDisableSchedulingOn4297dThresholdExtraKey, "codex_7d_used_percent"} { + for _, invalid := range []any{nil, "invalid", -1.0, 101.0, math.NaN(), math.Inf(1), true} { + account := scheduling429Account() + account.Extra[key] = invalid + repo := &scheduling429Repo{} + rates := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + _, disabled := rates.maybeDisableOpenAISchedulingOn429(t.Context(), account, 429, nil) + require.False(t, disabled, "key=%s invalid=%v", key, invalid) + require.Empty(t, repo.ids) + } + } +} + +func TestManaged429WeeklyPolicyUsesOwnerThresholdAndSnapshot(t *testing.T) { + for _, used := range []float64{20, 99} { + owner := scheduling429Account() + owner.Extra["codex_7d_used_percent"] = used + projection := scheduling429Account() + projection.AuthConnectionID = "connection" + projection.Extra["openai_connections_managed"] = true + projection.Extra[OpenAIDisableSchedulingOn4297dThresholdExtraKey] = 0.0 + repo := &scheduling429Repo{owner: owner} + rates := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + _, disabled := rates.maybeDisableOpenAISchedulingOn429(t.Context(), projection, 429, nil) + require.Equal(t, used > 98, disabled) + require.Equal(t, []int64{owner.ID}, repo.reads) + } +} + +func TestWeekly429ThresholdConfigValidation(t *testing.T) { + for _, threshold := range []float64{0, 98, 98.5, 100} { + cfg := DefaultOAuthAutoConfig() + cfg.OpenAIDisableSchedulingOn4297dThresholdPercent = threshold + require.NoError(t, ValidateOAuthAutoConfig(cfg)) + } + for _, threshold := range []float64{-1, 100.01, math.NaN(), math.Inf(1)} { + cfg := DefaultOAuthAutoConfig() + cfg.OpenAIDisableSchedulingOn4297dThresholdPercent = threshold + require.Error(t, ValidateOAuthAutoConfig(cfg)) + } + for _, raw := range []string{`{"openai_disable_scheduling_on_429_7d_threshold_percent":null}`, `{"openai_disable_scheduling_on_429_7d_threshold_percent":"98"}`} { + cfg := DefaultOAuthAutoConfig() + require.Error(t, json.Unmarshal([]byte(raw), &cfg)) + } +} + +func TestWeekly429ThresholdAppliesBeforeGatewayAndBPSPersistence(t *testing.T) { + for _, bps := range []bool{false, true} { + for _, high := range []bool{false, true} { + account := scheduling429Account() + weekly := "20" + if high { + weekly = "99" + account.Extra["codex_7d_used_percent"] = 20.0 + } + headers := weekly429Headers(weekly, "100", false) + repo := &scheduling429Repo{} + rates := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + gateway := &OpenAIGatewayService{rateLimitService: rates} + rates.SetAccountRuntimeBlocker(gateway) + if bps { + gateway.coolDownExcelBPS(t.Context(), account, "5", headers) + } else { + gateway.handleOpenAIAccountUpstreamError(t.Context(), account, 429, headers, nil) + } + if high { + require.Equal(t, []int64{account.ID}, repo.ids) + } else { + require.Empty(t, repo.ids) + } + } + } +} + +func TestWeekly429ThresholdDoesNotGateTOTPRotation(t *testing.T) { + account := scheduling429Account() + account.Extra["codex_7d_used_percent"] = 20.0 + account.Extra[OpenAITOTPRotateOn429ExtraKey] = true + repo, rotation := &scheduling429Repo{}, &totp429Recorder{} + rates := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + rates.openAITOTP429Rotator = rotation + rates.HandleUpstreamError(t.Context(), account, 429, nil, nil) + require.Empty(t, repo.ids) + require.Equal(t, []int64{account.ID}, rotation.accounts) + require.Equal(t, 1, repo.rateLimitedCalls) +} diff --git a/backend/internal/service/openai_excel_bps.go b/backend/internal/service/openai_excel_bps.go index 69b8f0c05d6b..6ada7e8d7ecd 100644 --- a/backend/internal/service/openai_excel_bps.go +++ b/backend/internal/service/openai_excel_bps.go @@ -269,9 +269,9 @@ func (s *OpenAIGatewayService) forwardExcelBPS(ctx context.Context, c *gin.Conte } // No output exists yet, so the handler may replay the request on another // account within its switch budget unless the client is already gone. - failoverRateLimited := func(retryAfter string) (*OpenAIForwardResult, error) { + failoverRateLimited := func(retryAfter string, responseHeaders ...http.Header) (*OpenAIForwardResult, error) { if !isQualityObservation(ctx) { - s.coolDownExcelBPS(ctx, account, retryAfter) + s.coolDownExcelBPS(ctx, account, retryAfter, responseHeaders...) } if isExcelBPSClientCancellation(c, ctx.Err()) { return clientCanceled() @@ -676,7 +676,7 @@ func (s *OpenAIGatewayService) forwardExcelBPS(ctx context.Context, c *gin.Conte Message: upstreamMessage, Detail: upstreamDetail, UpstreamResponseBody: upstreamDetail, }) if resp.StatusCode == http.StatusTooManyRequests { - return failoverRateLimited(resp.Header.Get("Retry-After")) + return failoverRateLimited(resp.Header.Get("Retry-After"), resp.Header) } if resp.StatusCode == http.StatusUnauthorized { s.handleExcelBPSUnauthorized(ctx, account, resp.StatusCode, resp.Header, raw, token) @@ -748,7 +748,7 @@ func (s *OpenAIGatewayService) forwardExcelBPS(ctx context.Context, c *gin.Conte observeBPSTestResponse(repairCtx, repairResp, model, token, gjson.GetBytes(raw, "error.code").String()) if repairResp.StatusCode == http.StatusTooManyRequests { // Output was already accepted: cool the route, never replay the request. - s.coolDownExcelBPS(repairCtx, account, repairResp.Header.Get("Retry-After")) + s.coolDownExcelBPS(repairCtx, account, repairResp.Header.Get("Retry-After"), repairResp.Header) } s.handleExcelBPSUnauthorized(repairCtx, account, repairResp.StatusCode, repairResp.Header, raw, token) if isExcelBPSModelPermissionError(repairResp.StatusCode, gjson.GetBytes(raw, "error.code").String()) && !isQualityObservation(repairCtx) { @@ -792,7 +792,7 @@ func (s *OpenAIGatewayService) forwardExcelBPS(ctx context.Context, c *gin.Conte observeBPSTestResponse(repairCtx, repaired, model, token, gjson.GetBytes(raw, "error.code").String()) _ = repaired.Body.Close() if repaired.StatusCode == http.StatusTooManyRequests { - s.coolDownExcelBPS(repairCtx, account, repaired.Header.Get("Retry-After")) + s.coolDownExcelBPS(repairCtx, account, repaired.Header.Get("Retry-After"), repaired.Header) } s.handleExcelBPSUnauthorized(repairCtx, account, repaired.StatusCode, repaired.Header, raw, token) if isExcelBPSModelPermissionError(repaired.StatusCode, gjson.GetBytes(raw, "error.code").String()) && !isQualityObservation(repairCtx) { @@ -896,7 +896,7 @@ func (s *OpenAIGatewayService) forwardExcelBPS(ctx context.Context, c *gin.Conte IntendedStatus: upstreamFailure.Status, CountTowardsSLA: true, NonStream: !stream, }) if upstreamFailure.Status == http.StatusTooManyRequests && !isQualityObservation(ctx) { - s.coolDownExcelBPS(ctx, account, resp.Header.Get("Retry-After")) + s.coolDownExcelBPS(ctx, account, resp.Header.Get("Retry-After"), resp.Header) } } } diff --git a/backend/internal/service/openai_excel_bps_images.go b/backend/internal/service/openai_excel_bps_images.go index fba4a3c4359b..90574a03aeb6 100644 --- a/backend/internal/service/openai_excel_bps_images.go +++ b/backend/internal/service/openai_excel_bps_images.go @@ -301,7 +301,7 @@ func (s *OpenAIGatewayService) forwardExcelBPSImages(ctx context.Context, c *gin event.Kind = "failover" appendOpsUpstreamError(c, event) if !isQualityObservation(ctx) { - s.coolDownExcelBPS(ctx, account, resp.Header.Get("Retry-After")) + s.coolDownExcelBPS(ctx, account, resp.Header.Get("Retry-After"), resp.Header) } // The next account may use Codex, so the endpoint is recorded only // for final BPS outcomes; the image path never clears it. diff --git a/backend/internal/service/openai_excel_bps_ratelimit.go b/backend/internal/service/openai_excel_bps_ratelimit.go index c6ee28191ade..a1f52594c54a 100644 --- a/backend/internal/service/openai_excel_bps_ratelimit.go +++ b/backend/internal/service/openai_excel_bps_ratelimit.go @@ -47,14 +47,19 @@ func newExcelBPSRateLimitedFailoverError(retryAfter string) *UpstreamFailoverErr // coolDownExcelBPS skips the account for BPS requests until the upstream // Retry-After, or the configured 429 fallback when none is given. A shorter // cooldown never replaces a longer one. -func (s *OpenAIGatewayService) coolDownExcelBPS(ctx context.Context, account *Account, retryAfter string) { +func (s *OpenAIGatewayService) coolDownExcelBPS(ctx context.Context, account *Account, retryAfter string, responseHeaders ...http.Header) { if s == nil || account == nil { return } - ctx, _ = s.rateLimitService.maybeDisableOpenAISchedulingOn429(ctx, account, http.StatusTooManyRequests) + headers := http.Header{} + if len(responseHeaders) > 0 && responseHeaders[0] != nil { + headers = responseHeaders[0].Clone() + } + headers.Set("Retry-After", retryAfter) + ctx, _ = s.rateLimitService.maybeDisableOpenAISchedulingOn429(ctx, account, http.StatusTooManyRequests, headers) ctx = s.rateLimitService.maybeRotateOpenAITOTPOn429(ctx, account, http.StatusTooManyRequests) if account.AuthConnectionID != "" { - s.handleOpenAIAccountUpstreamError(ctx, account, http.StatusTooManyRequests, http.Header{"Retry-After": []string{retryAfter}}, nil) + s.handleOpenAIAccountUpstreamError(ctx, account, http.StatusTooManyRequests, headers, nil) return } cooldown, ok := excelBPSRetryAfter(retryAfter, time.Now()) diff --git a/backend/internal/service/ops_port.go b/backend/internal/service/ops_port.go index 32f8db5f0922..a6cdba5d7c83 100644 --- a/backend/internal/service/ops_port.go +++ b/backend/internal/service/ops_port.go @@ -309,7 +309,10 @@ type OpsWindowStats struct { StartTime time.Time `json:"start_time"` EndTime time.Time `json:"end_time"` - SuccessCount int64 `json:"success_count"` - ErrorCountTotal int64 `json:"error_count_total"` - TokenConsumed int64 `json:"token_consumed"` + SuccessCount int64 `json:"success_count"` + ErrorCountTotal int64 `json:"error_count_total"` + TokenConsumed int64 `json:"token_consumed"` + ErrorCountSLA int64 `json:"error_count_sla"` + RequestCountSLA int64 `json:"request_count_sla"` + SLA float64 `json:"sla"` } diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go index 0aa5d55b3753..1c27aa2ff6eb 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -357,7 +357,7 @@ 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) + ctx, disabledOn429 := s.maybeDisableOpenAISchedulingOn429(ctx, account, statusCode, headers) if disabledOn429 { defer func() { shouldDisable = true }() } 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 2f9379ad0e6e..1aedb049b866 100644 --- a/backend/internal/service/ratelimit_service_disable_scheduling_429_test.go +++ b/backend/internal/service/ratelimit_service_disable_scheduling_429_test.go @@ -40,7 +40,7 @@ func (r *scheduling429Repo) SetSchedulable(ctx context.Context, id int64, enable func scheduling429Account() *Account { return &Account{ID: 42, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Schedulable: true, - Extra: map[string]any{OpenAIDisableSchedulingOn429ExtraKey: true}} + Extra: map[string]any{OpenAIDisableSchedulingOn429ExtraKey: true, "codex_7d_used_percent": 99.0, "codex_usage_updated_at": time.Now().Add(-time.Minute).UTC().Format(time.RFC3339Nano)}} } func TestRateLimitDisableSchedulingOn429ScopeAndObservation(t *testing.T) { @@ -73,8 +73,8 @@ func TestRateLimitDisableSchedulingOn429ScopeAndObservation(t *testing.T) { 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) + ctx, disabled := svc.maybeDisableOpenAISchedulingOn429(ctx, account, tc.status, nil) + _, repeated := svc.maybeDisableOpenAISchedulingOn429(ctx, account, tc.status, nil) require.Equal(t, tc.want, disabled) require.Equal(t, disabled, repeated) if tc.want { @@ -181,8 +181,8 @@ func TestRateLimitDisableSchedulingOn429UsesAuthoritativeManagedOwner(t *testing } ctx, cancel := context.WithCancel(t.Context()) cancel() - ctx, disabled := svc.maybeDisableOpenAISchedulingOn429(ctx, projection, 429) - _, repeated := svc.maybeDisableOpenAISchedulingOn429(ctx, projection, 429) + ctx, disabled := svc.maybeDisableOpenAISchedulingOn429(ctx, projection, 429, nil) + _, repeated := svc.maybeDisableOpenAISchedulingOn429(ctx, projection, 429, nil) 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") diff --git a/backend/internal/service/wire.go b/backend/internal/service/wire.go index 352a089baef0..1de808872b94 100644 --- a/backend/internal/service/wire.go +++ b/backend/internal/service/wire.go @@ -914,6 +914,7 @@ func ProvideOpsService( svc.authCacheInvalidationWorker = authCacheInvalidationWorker svc.apiKeyService = apiKeyService svc.StartRuntimeSettingsRefresh(context.Background()) + accountOps.setOpenAIAPIKeyFallbackSLAReader(svc, settingService) svc.StartAIOpsController(context.Background()) return svc } diff --git a/frontend/src/api/admin/autoConfig.ts b/frontend/src/api/admin/autoConfig.ts index 09fc4e8865d3..a44255176286 100644 --- a/frontend/src/api/admin/autoConfig.ts +++ b/frontend/src/api/admin/autoConfig.ts @@ -7,12 +7,16 @@ import type { ModelBillingConfig } from '@/utils/modelBilling' import type { ExcelBPSDefaults } from '@/utils/excelBPSDefaults' import type { OAuthModelMappingRule } from '@/utils/oauthModelMappings' import type { OpenAIWSMode } from '@/utils/openaiWsMode' +import type { OpenAIAPIKeyFallbackConfig, OpenAIAPIKeyFallbackStatus } from '@/utils/openaiAPIKeyFallback' export type OAuthInitialQualityRule = Pick export interface AutoConfig { degradation_action?: import('@/utils/oauthDegradation').OAuthDegradationConfig openai_two_fa_admission?: OpenAITwoFAAdmissionConfig openai_totp_rotate_on_429?: boolean openai_disable_scheduling_on_429?: boolean + openai_disable_scheduling_on_429_7d_threshold_percent?: number + openai_apikey_fallback?: OpenAIAPIKeyFallbackConfig + openai_apikey_fallback_status?: OpenAIAPIKeyFallbackStatus openai_ws_mode?: OpenAIWSMode openai_ws_sse_acceleration?: boolean quality_rule?: OAuthInitialQualityRule | null diff --git a/frontend/src/components/admin/operations/OpenAIAPIKeyFallbackCard.vue b/frontend/src/components/admin/operations/OpenAIAPIKeyFallbackCard.vue new file mode 100644 index 000000000000..fb09c85ef361 --- /dev/null +++ b/frontend/src/components/admin/operations/OpenAIAPIKeyFallbackCard.vue @@ -0,0 +1,98 @@ + + + diff --git a/frontend/src/constants/newFeatureNotices.ts b/frontend/src/constants/newFeatureNotices.ts index 57dc6608cd96..837d6a076d36 100644 --- a/frontend/src/constants/newFeatureNotices.ts +++ b/frontend/src/constants/newFeatureNotices.ts @@ -5,6 +5,7 @@ */ export const NEW_FEATURE_NOTICES = { oauthDegradationActions: 'oauth-degradation-actions-initial-announcement', + openaiAPIKeyFallback: 'openai-apikey-fallback-initial-announcement', dashboardAccountConcurrency: 'dashboard-account-concurrency-initial-announcement', qualityRetestRest: 'quality-retest-rest-initial-announcement', qualityOAuth401Cleanup: 'quality-oauth-401-cleanup-initial-announcement', diff --git a/frontend/src/i18n/locales/en/autoConfig.ts b/frontend/src/i18n/locales/en/autoConfig.ts index c7ab84f53c12..4b367f89a39b 100644 --- a/frontend/src/i18n/locales/en/autoConfig.ts +++ b/frontend/src/i18n/locales/en/autoConfig.ts @@ -1,4 +1,38 @@ export default { + apikeyFallback: { + title: 'Fallback handling', + hint: 'Independent of initial configuration. Automatically enable scheduling for selected API Key accounts when all OpenAI OAuth accounts are unavailable, or when the chosen OpenAI metric falls below your threshold within the selected window. Either condition can trigger fallback.', + metric: 'Metric', + metrics: { sla: 'OpenAI SLA', health_score: 'OpenAI health score' }, + threshold: 'Enable fallback below this threshold', + scoreUnit: 'points', + window: 'Data window (minutes)', + minutes: 'minutes', + accounts: 'Fallback OpenAI API Key accounts (up to 100)', + reloadAccounts: 'Refresh accounts', + schedulingOn: 'Scheduling enabled', + schedulingOff: 'Scheduling disabled', + noAccounts: 'No active OpenAI API Key accounts are available.', + accountsFailed: 'Could not load the complete account list. Selections are preserved. Refresh the list before enabling this rule; you can still turn it off.', + retainedIds: 'Preserved account IDs:', + unavailableHint: 'Selected accounts are unavailable and remain selected. Deselect them before enabling this rule; you can still turn it off.', + unavailableAccount: 'Missing, ineligible or inactive account', + chooseAccounts: 'Select at least one available OpenAI API Key account.', + invalid: 'Choose a valid metric, a threshold from 0 to 100, an integer window from 1 to 1440 minutes, and up to 100 distinct valid accounts.', + recoveryHint: 'Metrics use the same definitions as operations monitoring and include OpenAI only. No metric trigger runs without valid samples. This rule only enables accounts: disable fallback accounts manually after recovery. Turning off the rule also leaves already enabled accounts running.', + status: 'Latest check', + refreshStatus: 'Refresh status', + statusFailed: 'Could not refresh status. The previous check is still shown.', + notChecked: 'No check yet. Background checks run after you save and enable the rule.', + lastChecked: 'Checked at:', + lastMetricChecked: 'Metric measured at:', + oauthAvailable: 'Available OAuth accounts:', + samples: 'Valid samples:', + lastTrigger: 'Last trigger:', + lastEnabled: 'Last enabled at:', + reasons: { oauth_unavailable: 'All OAuth accounts unavailable', metric_below_threshold: 'Selected metric below threshold' }, + errors: { accounts_unavailable: 'Could not read account state.', metric_unavailable: 'Could not read the monitored metric.', account_enable_failed: 'Some fallback accounts could not be enabled. Check their state.' } + }, degradation: { "title": "Degradation actions", "hint": "Independent policy for all OAuth accounts. Uses the same rolling window and complete, conclusive quality probe rounds as Account performance. Applies when the failed-probe percentage meets or exceeds the threshold, not the percentage of all customer requests. A performance pause monitor is not required.", @@ -136,8 +170,10 @@ export default { hint: 'Enable for new OpenAI OAuth accounts through initial configuration. After a 429, use the email, password and current 2FA saved in Credential Operations to rotate the secret and store it encrypted. At most one rotation task per account per hour; incomplete credentials or an unresolved rotation prevent automatic rotation.' }, disableScheduling429: { - label: 'Automatically disable scheduling after a 429', - hint: 'Enable for new OpenAI OAuth accounts through initial configuration. An upstream 429 turns off the account scheduling switch, which you can manually re-enable. Can be enabled together with automatic 2FA rotation.' + label: 'Disable scheduling on a 429 when 7-day usage exceeds the threshold', + hint: 'Enable for new OpenAI OAuth accounts through initial configuration. Disable scheduling only when an upstream 429 occurs and 7-day usage exceeds the chosen threshold, which defaults to 98%. The 5-hour window does not count. Without valid 7-day usage, this rule does not disable scheduling. You can manually re-enable scheduling and use this together with automatic 2FA rotation.', + threshold: '7-day usage threshold', + invalidThreshold: 'The 7-day usage threshold must be a valid number from 0 to 100.' }, "noGroups": "No active matching groups. Create one in group management first.", "loadHint": "Lower priority values run first. Load factor controls scheduling frequency independently of concurrency limits and billing multipliers.", diff --git a/frontend/src/i18n/locales/zh/autoConfig.ts b/frontend/src/i18n/locales/zh/autoConfig.ts index ab0dc7582047..e403261b8853 100644 --- a/frontend/src/i18n/locales/zh/autoConfig.ts +++ b/frontend/src/i18n/locales/zh/autoConfig.ts @@ -1,4 +1,38 @@ export default { + apikeyFallback: { + title: '兜底处置', + hint: '独立于首次配置。OpenAI OAuth 账号全部不可调度,或选定周期内的 OpenAI 指标低于所填阈值时,自动开启勾选 API Key 账号的调度;两项条件满足任意一项即可。', + metric: '监控指标', + metrics: { sla: 'OpenAI SLA', health_score: 'OpenAI 健康状况分数' }, + threshold: '低于此阈值时开启', + scoreUnit: '分', + window: '数据周期(分钟)', + minutes: '分钟', + accounts: '兜底 OpenAI API Key 账号(最多 100 个)', + reloadAccounts: '刷新账号列表', + schedulingOn: '调度已开启', + schedulingOff: '调度已关闭', + noAccounts: '暂无启用状态的 OpenAI API Key 账号。', + accountsFailed: '未能取得完整账号列表,已保留选择。请刷新列表后再启用;仍可关闭此规则。', + retainedIds: '保留的账号 ID:', + unavailableHint: '已选账号不可用,已保留选择。请取消勾选后再启用;仍可关闭此规则。', + unavailableAccount: '账号不存在、不符合条件或已停用', + chooseAccounts: '请至少勾选一个可用的 OpenAI API Key 账号。', + invalid: '请选择有效指标、0~100 的阈值、1~1440 的整数分钟周期,以及最多 100 个不同的有效账号。', + recoveryHint: '指标与运维监控使用相同口径,仅统计 OpenAI;没有有效样本时不触发指标条件。规则只自动开启账号,恢复后需手动关闭兜底账号;停用本规则也不会关闭已开启的账号。', + status: '最近检查', + refreshStatus: '刷新状态', + statusFailed: '状态刷新失败,仍显示上一次检查结果。', + notChecked: '尚无检查结果;保存并启用后由后台检查。', + lastChecked: '检查时间:', + lastMetricChecked: '指标统计时间:', + oauthAvailable: '可调度 OAuth:', + samples: '有效样本:', + lastTrigger: '最近触发原因:', + lastEnabled: '最近开启时间:', + reasons: { oauth_unavailable: 'OAuth 账号全部不可调度', metric_below_threshold: '所选指标低于阈值' }, + errors: { accounts_unavailable: '账号状态读取失败。', metric_unavailable: '监控指标读取失败。', account_enable_failed: '部分兜底账号开启失败,请检查账号状态。' } + }, degradation: { "title": "降智后处置", "hint": "独立适用于所有 OAuth 账号。使用账号性能相同的统一滚动窗口:仅统计完整、可明确判定的质量探针轮次,探针失败比例达到或超过阈值时处置;不是全部请求的降智率。无需开启账号性能停调监控。", @@ -136,8 +170,10 @@ export default { hint: '随首次配置为新 OpenAI OAuth 账号启用。遇到 429 时,使用凭证运营已保存的邮箱、密码和当前 2FA 更换密钥,新密钥加密保存。同一账号 1 小时内最多自动创建一次更换任务;凭据不完整或更换结果待确认时不自动更换。' }, disableScheduling429: { - label: '429 后自动关闭调度', - hint: '随首次配置为新 OpenAI OAuth 账号启用。收到上游 429 时关闭账号调度开关,可手动重新开启;可与自动更换 2FA 同时启用。' + label: '429 且 7 天额度超阈值后关闭调度', + hint: '随首次配置为新 OpenAI OAuth 账号启用。仅在收到上游 429 且 7 天额度使用率超过所填阈值时关闭调度,默认 98%;5 小时用量不参与判断,无有效 7 天用量时不关闭。可手动重新开启,也可与自动更换 2FA 同时启用。', + threshold: '7 天额度使用率阈值', + invalidThreshold: '7 天额度使用率阈值必须是 0~100 之间的有效数值。' }, "noGroups": "暂无符合条件的启用分组,请先在分组管理中创建。", "loadHint": "优先级数值越小越优先;负载因子影响调度频率,与实际并发上限、计费倍率独立。", diff --git a/frontend/src/utils/openaiAPIKeyFallback.ts b/frontend/src/utils/openaiAPIKeyFallback.ts new file mode 100644 index 000000000000..5ef6b8790690 --- /dev/null +++ b/frontend/src/utils/openaiAPIKeyFallback.ts @@ -0,0 +1,38 @@ +export interface OpenAIAPIKeyFallbackConfig { + enabled: boolean + account_ids: number[] + metric: 'sla' | 'health_score' + threshold: number + window_minutes: number +} + +export interface OpenAIAPIKeyFallbackStatus { + last_checked_at?: string + last_metric_checked_at?: string + oauth_account_count: number + oauth_available_count: number + metric: 'sla' | 'health_score' + metric_value?: number | null + samples: number + window_minutes: number + last_trigger_reason?: 'oauth_unavailable' | 'metric_below_threshold' + last_enabled_at?: string + last_error_category?: 'accounts_unavailable' | 'metric_unavailable' | 'account_enable_failed' +} + +export function defaultOpenAIAPIKeyFallbackConfig(): OpenAIAPIKeyFallbackConfig { + return { enabled: false, account_ids: [], metric: 'sla', threshold: 95, window_minutes: 5 } +} + +export function openaiAPIKeyFallbackPayload(value?: Partial | null): OpenAIAPIKeyFallbackConfig { + return { ...defaultOpenAIAPIKeyFallbackConfig(), ...value, account_ids: [...(value?.account_ids ?? [])] } +} + +export function openaiAPIKeyFallbackError(value: OpenAIAPIKeyFallbackConfig): string | null { + if (!['sla', 'health_score'].includes(value.metric) || !Number.isFinite(value.threshold) || value.threshold < 0 || value.threshold > 100 || + !Number.isInteger(value.window_minutes) || value.window_minutes < 1 || value.window_minutes > 1440 || + value.account_ids.length > 100 || new Set(value.account_ids).size !== value.account_ids.length || + value.account_ids.some(id => !Number.isSafeInteger(id) || id <= 0)) return 'autoConfig.apikeyFallback.invalid' + if (value.enabled && !value.account_ids.length) return 'autoConfig.apikeyFallback.chooseAccounts' + return null +} diff --git a/frontend/src/views/admin/AutoConfigView.vue b/frontend/src/views/admin/AutoConfigView.vue index 30d57bfe451b..5f693c6d6538 100644 --- a/frontend/src/views/admin/AutoConfigView.vue +++ b/frontend/src/views/admin/AutoConfigView.vue @@ -9,7 +9,10 @@
-
+
+
+
+
@@ -45,7 +48,7 @@

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

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

- +

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

@@ -61,6 +64,10 @@

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

+
@@ -130,6 +137,8 @@ import NewFeatureBadge from '@/components/common/NewFeatureBadge.vue' import { NEW_FEATURE_NOTICES } from '@/constants/newFeatureNotices' import SmartOpsNav from '@/components/admin/operations/SmartOpsNav.vue' import OAuthDegradationCard from '@/components/admin/operations/OAuthDegradationCard.vue' +import OpenAIAPIKeyFallbackCard from '@/components/admin/operations/OpenAIAPIKeyFallbackCard.vue' +import { openaiAPIKeyFallbackPayload, openaiAPIKeyFallbackError, type OpenAIAPIKeyFallbackConfig, type OpenAIAPIKeyFallbackStatus } from '@/utils/openaiAPIKeyFallback' import { oauthDegradationPayload, oauthDegradationError, type OAuthDegradationConfig } from '@/utils/oauthDegradation' import BPSDefaultsCard from '@/components/admin/operations/BPSDefaultsCard.vue' import OpenAITwoFAAdmissionCard from '@/components/admin/operations/OpenAITwoFAAdmissionCard.vue' @@ -147,9 +156,12 @@ import type { ScheduledTestPlan } from '@/types' import type { Group } from '@/types' import { defaultModelBillingConfig, modelBillingConfigError, modelBillingPayload, type ModelBillingConfig, type ModelBillingRule } from '@/utils/modelBilling' const { t } = useI18n(), auth = useAuthStore() -const draft = ref<(AutoConfig & { degradation_action: OAuthDegradationConfig; openai_ws_mode: OpenAIWSMode; openai_ws_sse_acceleration: boolean; openai_two_fa_admission: OpenAITwoFAAdmissionConfig; excel_bps: ExcelBPSDefaults; model_billing: ModelBillingConfig; model_mappings: OAuthModelMappingRule[] }) | null>(null), groups = ref([]) +const DEFAULT_DISABLE_SCHEDULING_429_7D_THRESHOLD_PERCENT = 98 +const draft = ref<(AutoConfig & { openai_apikey_fallback: OpenAIAPIKeyFallbackConfig; openai_disable_scheduling_on_429_7d_threshold_percent: number; degradation_action: OAuthDegradationConfig; openai_ws_mode: OpenAIWSMode; openai_ws_sse_acceleration: boolean; openai_two_fa_admission: OpenAITwoFAAdmissionConfig; excel_bps: ExcelBPSDefaults; model_billing: ModelBillingConfig; model_mappings: OAuthModelMappingRule[] }) | null>(null), groups = ref([]) const modelBillingGroups = ref([]), modelBillingGroupsLoading = ref(true), modelBillingGroupsFailed = ref(false) const loading = ref(false), saving = ref(false), error = ref(''), notice = ref('') +const fallbackCard = ref | null>(null) +const fallbackStatus = ref(null), fallbackStatusLoading = ref(false), fallbackStatusFailed = ref(false) const qualityPlans = ref([]), selectedQualityRule = ref(''), qualityLoadFailed = ref(false) const availableQualityPlans = computed(() => qualityPlans.value.filter(p => p.pelican_config?.quality && p.pelican_config.quality.action !== 'openai_two_fa_admission' && (draft.value?.platform === 'openai' || p.pelican_config.question_kind !== 'state_probe'))) function qualityActionLabel(plan: ScheduledTestPlan) { @@ -195,13 +207,21 @@ 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, degradation_action: oauthDegradationPayload(config.degradation_action), openai_ws_mode: config.openai_ws_mode ?? OPENAI_WS_MODE_CTX_POOL, openai_ws_sse_acceleration: config.openai_ws_sse_acceleration ?? false, 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') } } + try { const [config, available] = await Promise.all([getAutoConfig(), getAll()]); if (validGeneration(v)) { draft.value = { ...config, degradation_action: oauthDegradationPayload(config.degradation_action), openai_apikey_fallback: openaiAPIKeyFallbackPayload(config.openai_apikey_fallback), openai_ws_mode: config.openai_ws_mode ?? OPENAI_WS_MODE_CTX_POOL, openai_ws_sse_acceleration: config.openai_ws_sse_acceleration ?? false, 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_disable_scheduling_on_429_7d_threshold_percent: config.openai_disable_scheduling_on_429_7d_threshold_percent ?? DEFAULT_DISABLE_SCHEDULING_429_7D_THRESHOLD_PERCENT, 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() }; fallbackStatus.value = config.openai_apikey_fallback_status ?? null; 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 } } +async function refreshFallbackStatus() { + const v = generation; fallbackStatusLoading.value = true; fallbackStatusFailed.value = false + try { const config = await getAutoConfig(); if (validGeneration(v)) fallbackStatus.value = config.openai_apikey_fallback_status ?? null } + catch { if (validGeneration(v)) fallbackStatusFailed.value = true } + finally { if (validGeneration(v)) fallbackStatusLoading.value = false } +} async function save() { if (!draft.value || saving.value) return const c = draft.value + const fallbackError = openaiAPIKeyFallbackError(c.openai_apikey_fallback) ?? fallbackCard.value?.validationError() + if (fallbackError) { error.value = t(fallbackError); return } if (oauthDegradationError(c.degradation_action)) { error.value = t('autoConfig.degradation.invalid'); return } const admissionError = openaiTwoFAAdmissionError(c.openai_two_fa_admission) if (admissionError || c.openai_two_fa_admission.enabled && !groups.value.some(g => g.id === c.openai_two_fa_admission.isolation_group_id && g.platform === 'openai' && g.status === 'active')) { error.value = t(admissionError ?? 'autoConfig.admission.invalid'); return } @@ -211,14 +231,16 @@ async function save() { if (bpsError) { error.value = t(bpsError); return } const mappingError = oauthModelMappingsError(c.model_mappings) if (mappingError) { error.value = t(mappingError); return } + const shutdownThreshold = c.openai_disable_scheduling_on_429_7d_threshold_percent + if (!Number.isFinite(shutdownThreshold) || shutdownThreshold < 0 || shutdownThreshold > 100) { error.value = t('autoConfig.disableScheduling429.invalidThreshold'); return } 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, degradation_action: oauthDegradationPayload(result.degradation_action), openai_ws_mode: result.openai_ws_mode ?? OPENAI_WS_MODE_CTX_POOL, openai_ws_sse_acceleration: result.openai_ws_sse_acceleration ?? false, 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++ } } + try { const { runtime_blocked: _blocked, openai_apikey_fallback_status: _fallbackStatus, ...payload } = c; const result = await saveAutoConfig({ ...payload, cost_multiplier: costMultiplier, openai_apikey_fallback: openaiAPIKeyFallbackPayload(c.openai_apikey_fallback), model_mappings: oauthModelMappingsPayload(c.model_mappings), model_billing: modelBillingPayload(c.model_billing), excel_bps: excelBPSDefaultsPayload(c.excel_bps) }); if (validGeneration(v)) { draft.value = { ...result, degradation_action: oauthDegradationPayload(result.degradation_action), openai_apikey_fallback: openaiAPIKeyFallbackPayload(result.openai_apikey_fallback), openai_ws_mode: result.openai_ws_mode ?? OPENAI_WS_MODE_CTX_POOL, openai_ws_sse_acceleration: result.openai_ws_sse_acceleration ?? false, 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_disable_scheduling_on_429_7d_threshold_percent: result.openai_disable_scheduling_on_429_7d_threshold_percent ?? DEFAULT_DISABLE_SCHEDULING_429_7D_THRESHOLD_PERCENT, 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() }; if (result.openai_apikey_fallback_status) fallbackStatus.value = result.openai_apikey_fallback_status; 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 } } -watch(() => auth.user ? auth.user.id + ':' + auth.user.role : '', () => { generation++; draft.value = null; groups.value = []; modelBillingGroups.value = []; modelBillingGroupsFailed.value = false; modelBillingGroupsLoading.value = true; qualityPlans.value = []; selectedQualityRule.value = ''; qualityLoadFailed.value = false; error.value = notice.value = ''; loading.value = saving.value = false }, { flush: 'sync' }) +watch(() => auth.user ? auth.user.id + ':' + auth.user.role : '', () => { generation++; draft.value = null; fallbackStatus.value = null; fallbackStatusLoading.value = fallbackStatusFailed.value = false; groups.value = []; modelBillingGroups.value = []; modelBillingGroupsFailed.value = false; modelBillingGroupsLoading.value = true; qualityPlans.value = []; selectedQualityRule.value = ''; qualityLoadFailed.value = false; error.value = notice.value = ''; loading.value = saving.value = false }, { flush: 'sync' }) onMounted(() => { void load(); void loadQualityPlans(); void loadModelBillingGroups() }) onBeforeUnmount(() => { alive = false; generation++ }) diff --git a/frontend/src/views/admin/__tests__/AutoConfigView.spec.ts b/frontend/src/views/admin/__tests__/AutoConfigView.spec.ts index 439381e5b3f1..728a6f44dacc 100644 --- a/frontend/src/views/admin/__tests__/AutoConfigView.spec.ts +++ b/frontend/src/views/admin/__tests__/AutoConfigView.spec.ts @@ -9,12 +9,14 @@ import { useNewFeatureNoticeStore } from '@/stores/newFeatureNotices' import { getAutoConfig, saveAutoConfig, type AutoConfig } from '@/api/admin/autoConfig' import { listQualityPlans } from '@/api/admin/accountQuality' import { getAll, list as listGroups } from '@/api/admin/groups' +import { list as listAccounts } from '@/api/admin/accounts' import type { Group } from '@/types' import { defaultModelBillingConfig } from '@/utils/modelBilling' import { defaultExcelBPSDefaults } from '@/utils/excelBPSDefaults' import { defaultOAuthModelMappings } from '@/utils/oauthModelMappings' import { defaultOAuthDegradationConfig } from '@/utils/oauthDegradation' import { defaultOpenAITwoFAAdmissionConfig } from '@/utils/openaiTwoFAAdmission' +import { defaultOpenAIAPIKeyFallbackConfig, type OpenAIAPIKeyFallbackStatus } from '@/utils/openaiAPIKeyFallback' vi.mock('@/components/account/ModelWhitelistSelector.vue', () => ({ default: { props: ['modelValue'], template: '
{{ modelValue.join(", ") }}
' } })) const state = vi.hoisted(() => ({ auth: null as any })) vi.mock('@/stores/auth', () => ({ useAuthStore: () => state.auth })) @@ -26,15 +28,167 @@ 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 = { degradation_action: defaultOAuthDegradationConfig(), openai_ws_mode: 'ctx_pool', openai_ws_sse_acceleration: false, 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: '' } +vi.mock('@/api/admin/accounts', () => ({ list: vi.fn() })) +const config: AutoConfig = { openai_apikey_fallback: defaultOpenAIAPIKeyFallbackConfig(), degradation_action: defaultOAuthDegradationConfig(), openai_ws_mode: 'ctx_pool', openai_ws_sse_acceleration: false, openai_totp_rotate_on_429: false, openai_disable_scheduling_on_429: false, openai_disable_scheduling_on_429_7d_threshold_percent: 98, 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' } }) + vi.resetAllMocks(); vi.mocked(listAccounts).mockResolvedValue({ items: [], page: 1, page_size: 100, pages: 0, total: 0 }); vi.mocked(listQualityPlans).mockResolvedValue([]); state.auth = reactive({ user: { id: 1, role: 'admin' } }) vi.mocked(listGroups).mockImplementation(async () => ({ items: await getAll(), page: 1, page_size: 100, pages: 1, total: 2 }) as any) vi.mocked(getAutoConfig).mockResolvedValue(structuredClone(config)); vi.mocked(saveAutoConfig).mockImplementation(async c => c) vi.mocked(getAll).mockResolvedValue([{ id: 5, name: 'OpenAI test', platform: 'openai', status: 'active' }, { id: 6, name: 'Anthropic test', platform: 'anthropic', status: 'active' }] as Group[]) }) describe('AutoConfigView', () => { + it('places fallback handling beside degradation handling and saves its controls independently of initial configuration', async () => { + vi.mocked(listAccounts).mockResolvedValueOnce({ items: [{ id: 71, name: 'Fallback fixture', platform: 'openai', type: 'apikey', status: 'active', schedulable: false, parent_account_id: null }] as any, page: 1, page_size: 100, pages: 1, total: 1 }) + const w = mount(AutoConfigView); await flushPromises() + const panels = w.get('[data-testid="oauth-handling-panels"]') + expect(panels.classes()).toContain('lg:grid-cols-2') + expect(panels.find('[data-testid="degradation-action"]').exists()).toBe(true) + expect(panels.find('[data-testid="apikey-fallback"]').exists()).toBe(true) + expect(w.get('[data-testid="apikey-fallback-enabled"]').element.checked).toBe(false) + expect(w.get('[data-testid="apikey-fallback-threshold"]').element.value).toBe('95') + expect(w.get('[data-testid="apikey-fallback-window"]').element.value).toBe('5') + await w.get('[data-testid="platform"]').setValue('anthropic') + await w.get('[data-testid="apikey-fallback-enabled"]').setValue(true) + await w.get('[data-testid="apikey-fallback-account-71"]').setValue(true) + await w.get('[data-testid="apikey-fallback-metric"]').setValue('health_score') + await w.get('[data-testid="apikey-fallback-threshold"]').setValue('82.5') + await w.get('[data-testid="apikey-fallback-window"]').setValue('1440') + await w.get('form').trigger('submit'); await flushPromises() + const saved: AutoConfig = { ...config, platform: 'anthropic', selected_models: null, quality_rule: null, model_mappings: [], openai_apikey_fallback: { enabled: true, account_ids: [71], metric: 'health_score', threshold: 82.5, window_minutes: 1440 } } + expect(saveAutoConfig).toHaveBeenCalledWith(saved) + expect(w.get('[data-testid="initial-enabled"]').element.checked).toBe(false) + w.unmount() + vi.mocked(getAutoConfig).mockResolvedValueOnce(saved) + vi.mocked(listAccounts).mockResolvedValueOnce({ items: [{ id: 71, name: 'Fallback fixture', platform: 'openai', type: 'apikey', status: 'active', schedulable: false }] as any, page: 1, page_size: 100, pages: 1, total: 1 }) + const reloaded = mount(AutoConfigView); await flushPromises() + expect(reloaded.get('[data-testid="apikey-fallback-metric"]').element.value).toBe('health_score') + expect(reloaded.get('[data-testid="apikey-fallback-threshold"]').element.value).toBe('82.5') + expect(reloaded.get('[data-testid="apikey-fallback-window"]').element.value).toBe('1440') + expect(reloaded.get('[data-testid="apikey-fallback-account-71"]').element.checked).toBe(true) + reloaded.unmount() + }) + it('loads all fallback account pages and excludes OAuth, other platforms, inactive accounts, shadows and expired or invalid expiry timestamps', async () => { + vi.mocked(getAutoConfig).mockResolvedValueOnce({ ...config, openai_apikey_fallback: { ...defaultOpenAIAPIKeyFallbackConfig(), account_ids: [77] } }) + vi.mocked(listAccounts).mockResolvedValueOnce({ items: [ + { id: 71, name: 'First key', platform: 'openai', type: 'apikey', status: 'active', schedulable: false }, + { id: 72, name: 'OAuth fixture', platform: 'openai', type: 'oauth', status: 'active' }, + { id: 73, name: 'Shadow fixture', platform: 'openai', type: 'apikey', status: 'active', parent_account_id: 71 } + ] as any, page: 1, page_size: 100, pages: 2, total: 9 }) + vi.mocked(listAccounts).mockResolvedValueOnce({ items: [ + { id: 74, name: 'Other platform', platform: 'anthropic', type: 'apikey', status: 'active' }, + { id: 75, name: 'Inactive fixture', platform: 'openai', type: 'apikey', status: 'inactive' }, + { id: 76, name: 'Second key', platform: 'openai', type: 'apikey', status: 'active', schedulable: true, expires_at: Date.now() / 1000 + 3600 }, + { id: 77, name: 'Expired key', platform: 'openai', type: 'apikey', status: 'active', schedulable: false, expires_at: 1 }, + { id: 78, name: 'Invalid expiry', platform: 'openai', type: 'apikey', status: 'active', schedulable: false, expires_at: 'invalid' }, + { id: 79, name: 'Non-finite expiry', platform: 'openai', type: 'apikey', status: 'active', schedulable: false, expires_at: Number.POSITIVE_INFINITY } + ] as any, page: 2, page_size: 100, pages: 2, total: 9 }) + const w = mount(AutoConfigView); await flushPromises() + expect(listAccounts).toHaveBeenNthCalledWith(1, 1, 100, { platform: 'openai', type: 'apikey', status: 'active', lite: '1', sort_by: 'id', sort_order: 'asc' }) + expect(listAccounts).toHaveBeenNthCalledWith(2, 2, 100, { platform: 'openai', type: 'apikey', status: 'active', lite: '1', sort_by: 'id', sort_order: 'asc' }) + expect(w.findAll('[data-testid^="apikey-fallback-account-"]').map(input => input.attributes('data-testid'))).toEqual(['apikey-fallback-account-71', 'apikey-fallback-account-76']) + expect(w.get('[data-testid="apikey-fallback-unavailable-77"]').element.checked).toBe(true) + w.unmount() + }) + it('preserves unavailable selected account IDs, blocks enabling them and still allows the rule to be disabled', async () => { + vi.mocked(getAutoConfig).mockResolvedValueOnce({ ...config, openai_apikey_fallback: { ...defaultOpenAIAPIKeyFallbackConfig(), enabled: true, account_ids: [999] } }) + const w = mount(AutoConfigView); await flushPromises() + expect(w.get('[data-testid="apikey-fallback-unavailable-999"]').element.checked).toBe(true) + await w.get('form').trigger('submit'); await flushPromises() + expect(saveAutoConfig).not.toHaveBeenCalled() + expect(w.get('[role="alert"]').text()).toContain('autoConfig.apikeyFallback.unavailableHint') + await w.get('[data-testid="apikey-fallback-enabled"]').setValue(false) + await w.get('form').trigger('submit'); await flushPromises() + expect(saveAutoConfig).toHaveBeenCalledWith({ ...config, openai_apikey_fallback: { ...defaultOpenAIAPIKeyFallbackConfig(), account_ids: [999] } }) + expect(w.get('[data-testid="apikey-fallback-unavailable-999"]').element.checked).toBe(true) + w.unmount() + }) + it('keeps selections on an incomplete account response and can retry before enabling fallback', async () => { + vi.mocked(getAutoConfig).mockResolvedValueOnce({ ...config, openai_apikey_fallback: { ...defaultOpenAIAPIKeyFallbackConfig(), enabled: true, account_ids: [71] } }) + vi.mocked(listAccounts).mockResolvedValueOnce({ items: [], page: 1, page_size: 100, pages: 2, total: 1 }) + const w = mount(AutoConfigView); await flushPromises() + expect(w.get('[data-testid="apikey-fallback-accounts-error"]').text()).toContain('autoConfig.apikeyFallback.accountsFailed') + expect(w.get('[data-testid="apikey-fallback-retained-ids"]').text()).toContain('#71') + await w.get('form').trigger('submit'); await flushPromises() + expect(saveAutoConfig).not.toHaveBeenCalled() + vi.mocked(listAccounts).mockResolvedValueOnce({ items: [{ id: 71, name: 'Fallback fixture', platform: 'openai', type: 'apikey', status: 'active', schedulable: false }] as any, page: 1, page_size: 100, pages: 1, total: 1 }) + await w.get('[data-testid="apikey-fallback-reload-accounts"]').trigger('click'); await flushPromises() + expect(w.get('[data-testid="apikey-fallback-account-71"]').element.checked).toBe(true) + await w.get('form').trigger('submit'); await flushPromises() + expect(saveAutoConfig).toHaveBeenCalled() + w.unmount() + }) + it.each([ + { metric: 'sla', threshold: -1, window_minutes: 5 }, + { metric: 'health_score', threshold: 100.1, window_minutes: 5 }, + { metric: 'sla', threshold: Number.NaN, window_minutes: 5 }, + { metric: 'sla', threshold: 95, window_minutes: 0 }, + { metric: 'sla', threshold: 95, window_minutes: 1441 }, + { metric: 'sla', threshold: 95, window_minutes: 1.5 } + ] as const)('rejects invalid fallback metric controls $metric / $threshold / $window_minutes', async controls => { + vi.mocked(getAutoConfig).mockResolvedValueOnce({ ...config, openai_apikey_fallback: { ...defaultOpenAIAPIKeyFallbackConfig(), ...controls } }) + const w = mount(AutoConfigView); await flushPromises() + await w.get('form').trigger('submit'); await flushPromises() + expect(saveAutoConfig).not.toHaveBeenCalled() + expect(w.get('[role="alert"]').text()).toContain('autoConfig.apikeyFallback.invalid') + w.unmount() + }) + it('defaults legacy fallback settings to off and requires a target before enabling', async () => { + const { openai_apikey_fallback: _fallback, ...legacy } = config + vi.mocked(getAutoConfig).mockResolvedValueOnce(legacy) + const w = mount(AutoConfigView); await flushPromises() + expect(w.get('[data-testid="apikey-fallback-enabled"]').element.checked).toBe(false) + await w.get('[data-testid="apikey-fallback-enabled"]').setValue(true) + await w.get('form').trigger('submit'); await flushPromises() + expect(saveAutoConfig).not.toHaveBeenCalled() + expect(w.get('[role="alert"]').text()).toContain('autoConfig.apikeyFallback.chooseAccounts') + await w.get('[data-testid="apikey-fallback-enabled"]').setValue(false) + await w.get('form').trigger('submit'); await flushPromises() + expect(saveAutoConfig).toHaveBeenCalledWith(config) + w.unmount() + }) + it('refreshes read-only fallback status without overwriting the draft or including status in saves', async () => { + const status: OpenAIAPIKeyFallbackStatus = { last_checked_at: '2026-11-10T15:00:00Z', last_metric_checked_at: '2026-11-10T14:59:30Z', oauth_account_count: 5, oauth_available_count: 0, metric: 'sla', metric_value: 91, samples: 100, window_minutes: 5, last_trigger_reason: 'metric_below_threshold', last_enabled_at: '2026-11-10T14:59:00Z' } + vi.mocked(getAutoConfig).mockResolvedValueOnce({ ...config, openai_apikey_fallback_status: status }) + const w = mount(AutoConfigView); await flushPromises() + expect(w.get('[data-testid="apikey-fallback-status"]').text()).toContain('91.00%') + expect(w.get('[data-testid="apikey-fallback-metric-checked-at"]').text()).toContain('2026-11-10T14:59:30Z') + expect(w.get('[data-testid="apikey-fallback-metric-checked-at"]').text()).toContain('autoConfig.apikeyFallback.lastMetricChecked') + await w.get('[data-testid="apikey-fallback-threshold"]').setValue('88') + vi.mocked(getAutoConfig).mockResolvedValueOnce({ ...config, openai_apikey_fallback_status: { ...status, last_checked_at: '2026-11-10T15:00:15Z', metric: 'health_score', metric_value: 86, samples: 50, window_minutes: 15 } }) + await w.get('[data-testid="apikey-fallback-refresh-status"]').trigger('click'); await flushPromises() + expect(w.get('[data-testid="apikey-fallback-status"]').text()).toContain('86.00') + expect(w.get('[data-testid="apikey-fallback-status"]').text()).toContain('autoConfig.apikeyFallback.metrics.health_score') + expect(w.get('[data-testid="apikey-fallback-status"]').text()).toContain('86.00autoConfig.apikeyFallback.scoreUnit') + expect(w.get('[data-testid="apikey-fallback-status"]').text()).not.toContain('86.00%') + expect(w.get('[data-testid="apikey-fallback-metric"]').element.value).toBe('sla') + expect(w.get('[data-testid="apikey-fallback-metric-checked-at"]').text()).toContain('2026-11-10T14:59:30Z') + expect(w.get('[data-testid="apikey-fallback-threshold"]').element.value).toBe('88') + await w.get('form').trigger('submit'); await flushPromises() + expect(saveAutoConfig).toHaveBeenCalledWith({ ...config, openai_apikey_fallback: { ...defaultOpenAIAPIKeyFallbackConfig(), threshold: 88 } }) + expect(vi.mocked(saveAutoConfig).mock.lastCall![0]).not.toHaveProperty('openai_apikey_fallback_status') + w.unmount() + }) + it('registers an independent fallback notice and preserves its dismissal across remounts', async () => { + const oldId = NEW_FEATURE_NOTICES.oauthDegradationActions, id = NEW_FEATURE_NOTICES.openaiAPIKeyFallback + useNewFeatureNoticeStore().dismiss(1, oldId) + const w = mount(AutoConfigView); await flushPromises() + const badge = w.get('[data-testid="apikey-fallback"] [data-testid="new-feature-badge"]') + const second = mount(NewFeatureBadge, { props: { noticeId: id, userId: 1 } }) + await badge.trigger('click') + expect(second.find('[data-testid="new-feature-badge"]').exists()).toBe(false) + expect(w.get('[data-testid="apikey-fallback-enabled"]').element.checked).toBe(false) + expect(saveAutoConfig).not.toHaveBeenCalled() + w.unmount(); second.unmount(); setActivePinia(createPinia()) + const reloaded = mount(AutoConfigView); await flushPromises() + expect(reloaded.find('[data-testid="apikey-fallback"] [data-testid="new-feature-badge"]').exists()).toBe(false) + expect(useNewFeatureNoticeStore().isDismissed(1, oldId)).toBe(true) + const future = mount(NewFeatureBadge, { props: { noticeId: 'future-fallback-test', userId: 1 } }) + expect(future.find('[data-testid="new-feature-badge"]').exists()).toBe(true) + const otherAdmin = mount(NewFeatureBadge, { props: { noticeId: id, userId: 2 } }) + expect(otherAdmin.find('[data-testid="new-feature-badge"]').exists()).toBe(true) + reloaded.unmount(); future.unmount(); otherAdmin.unmount() + }) it('preserves degradation actions when saving WS settings and preserves WS settings when saving degradation actions', async () => { const degradation = { ...defaultOAuthDegradationConfig(), enabled: true, threshold_percent: 42, limit_concurrency: false, limit_models: false, limit_groups: true, group_ids: [5] } const initial: AutoConfig = { ...config, openai_ws_mode: 'off', degradation_action: degradation } @@ -221,6 +375,8 @@ describe('AutoConfigView', () => { 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 threshold = '[data-testid="disable-scheduling-on-429-7d-threshold"]' + expect(w.get(threshold).element.closest('fieldset')).toBe(schedulingNotice(w).element.closest('fieldset')) 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) @@ -228,6 +384,7 @@ describe('AutoConfigView', () => { 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) + expect(w.get(threshold).element.value).toBe('98') w.unmount(); other.unmount() setActivePinia(createPinia()) const reloaded = mount(AutoConfigView); await flushPromises() @@ -263,22 +420,25 @@ describe('AutoConfigView', () => { 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 }) + it('resets both OpenAI 429 options and their weekly threshold when changing platforms', async () => { + vi.mocked(getAutoConfig).mockResolvedValueOnce({ ...config, openai_disable_scheduling_on_429: true, openai_totp_rotate_on_429: true, openai_disable_scheduling_on_429_7d_threshold_percent: 97.5 }) const w = mount(AutoConfigView); await flushPromises() - const scheduling = '[data-testid="disable-scheduling-on-429"]', rotation = '[data-testid="totp-rotate-on-429"]' + const scheduling = '[data-testid="disable-scheduling-on-429"]', rotation = '[data-testid="totp-rotate-on-429"]', threshold = '[data-testid="disable-scheduling-on-429-7d-threshold"]' await w.get('[data-testid="platform"]').setValue('anthropic') expect(w.find(scheduling).exists()).toBe(false) expect(w.find(rotation).exists()).toBe(false) + expect(w.find(threshold).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) + expect(w.get(threshold).element.value).toBe('98') + expect(w.get(threshold).element.disabled).toBe(true) w.unmount() }) it('keeps automatic scheduling shutdown off when loading or saving legacy settings', async () => { - const { openai_disable_scheduling_on_429: _scheduling, ...legacy } = config + const { openai_disable_scheduling_on_429: _scheduling, openai_disable_scheduling_on_429_7d_threshold_percent: _threshold, ...legacy } = config vi.mocked(getAutoConfig).mockResolvedValueOnce(legacy) vi.mocked(saveAutoConfig).mockResolvedValueOnce(legacy) const w = mount(AutoConfigView); await flushPromises() @@ -289,6 +449,71 @@ describe('AutoConfigView', () => { expect(w.get(checkbox).element.checked).toBe(false) w.unmount() }) + it('defaults the weekly shutdown threshold to 98 and enables editing only with the switch', async () => { + const w = mount(AutoConfigView); await flushPromises() + const threshold = '[data-testid="disable-scheduling-on-429-7d-threshold"]' + expect(w.get(threshold).element.value).toBe('98') + expect(w.get(threshold).element.disabled).toBe(true) + expect(w.get(threshold).attributes()).toEqual(expect.objectContaining({ min: '0', max: '100', step: 'any', required: '' })) + await w.get('[data-testid="disable-scheduling-on-429"]').setValue(true) + expect(w.get(threshold).element.disabled).toBe(false) + await w.get(threshold).setValue('97.25') + await w.get('[data-testid="disable-scheduling-on-429"]').setValue(false) + expect(w.get(threshold).element.disabled).toBe(true) + await w.get('form').trigger('submit'); await flushPromises() + expect(saveAutoConfig).toHaveBeenCalledWith({ ...config, openai_disable_scheduling_on_429_7d_threshold_percent: 97.25 }) + w.unmount() + }) + it.each([0, 97.5, 98, 100])('saves and reloads weekly shutdown threshold %s independently of 2FA', async threshold => { + const w = mount(AutoConfigView); await flushPromises() + const input = '[data-testid="disable-scheduling-on-429-7d-threshold"]' + await w.get('[data-testid="disable-scheduling-on-429"]').setValue(true) + await w.get('[data-testid="totp-rotate-on-429"]').setValue(true) + await w.get(input).setValue(threshold) + await w.get('form').trigger('submit'); await flushPromises() + const saved = { ...config, openai_disable_scheduling_on_429: true, openai_totp_rotate_on_429: true, openai_disable_scheduling_on_429_7d_threshold_percent: threshold } + expect(saveAutoConfig).toHaveBeenCalledWith(saved) + expect(w.get(input).element.value).toBe(String(threshold)) + w.unmount() + vi.mocked(getAutoConfig).mockResolvedValueOnce(saved) + const reloaded = mount(AutoConfigView); await flushPromises() + expect(reloaded.get(input).element.value).toBe(String(threshold)) + expect(reloaded.get('[data-testid="disable-scheduling-on-429"]').element.checked).toBe(true) + expect(reloaded.get('[data-testid="totp-rotate-on-429"]').element.checked).toBe(true) + reloaded.unmount() + }) + it('uses 98 for existing opt-in settings without a weekly threshold on load and save', async () => { + const { openai_disable_scheduling_on_429_7d_threshold_percent: _threshold, ...withoutThreshold } = config + const legacy = { ...withoutThreshold, openai_disable_scheduling_on_429: true } + vi.mocked(getAutoConfig).mockResolvedValueOnce(legacy) + vi.mocked(saveAutoConfig).mockResolvedValueOnce(legacy) + const w = mount(AutoConfigView); await flushPromises() + const input = '[data-testid="disable-scheduling-on-429-7d-threshold"]' + expect(w.get(input).element.value).toBe('98') + expect(w.get(input).element.disabled).toBe(false) + await w.get('form').trigger('submit'); await flushPromises() + expect(saveAutoConfig).toHaveBeenCalledWith({ ...config, openai_disable_scheduling_on_429: true }) + expect(w.get(input).element.value).toBe('98') + expect(w.get('[data-testid="disable-scheduling-on-429"]').element.checked).toBe(true) + w.unmount() + }) + it.each([-1, 100.01, ''])('rejects invalid weekly shutdown threshold input %s', async threshold => { + const w = mount(AutoConfigView); await flushPromises() + await w.get('[data-testid="disable-scheduling-on-429"]').setValue(true) + await w.get('[data-testid="disable-scheduling-on-429-7d-threshold"]').setValue(threshold) + await w.get('form').trigger('submit'); await flushPromises() + expect(saveAutoConfig).not.toHaveBeenCalled() + expect(w.get('[role="alert"]').text()).toContain('autoConfig.disableScheduling429.invalidThreshold') + w.unmount() + }) + it.each([Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY])('rejects a non-finite loaded weekly shutdown threshold (%s)', async threshold => { + vi.mocked(getAutoConfig).mockResolvedValueOnce({ ...config, openai_disable_scheduling_on_429_7d_threshold_percent: threshold }) + const w = mount(AutoConfigView); await flushPromises() + await w.get('form').trigger('submit'); await flushPromises() + expect(saveAutoConfig).not.toHaveBeenCalled() + expect(w.get('[role="alert"]').text()).toContain('autoConfig.disableScheduling429.invalidThreshold') + 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) diff --git a/frontend/src/views/admin/__tests__/OAuthDegradationActions.spec.ts b/frontend/src/views/admin/__tests__/OAuthDegradationActions.spec.ts index ca178285ac5d..613266ab90fa 100644 --- a/frontend/src/views/admin/__tests__/OAuthDegradationActions.spec.ts +++ b/frontend/src/views/admin/__tests__/OAuthDegradationActions.spec.ts @@ -19,6 +19,7 @@ vi.mock('@/api/client', () => ({ apiClient: { get: vi.fn(), put: vi.fn() } })) vi.mock('@/api/admin/autoConfig', () => ({ getAutoConfig: vi.fn(), saveAutoConfig: vi.fn(), getModelBillingGroups: vi.fn(async () => []) })) vi.mock('@/api/admin/groups', () => ({ getAll: vi.fn(async () => []) })) vi.mock('@/api/admin/accountQuality', () => ({ listQualityPlans: vi.fn(async () => []) })) +vi.mock('@/api/admin/accounts', () => ({ list: vi.fn(async () => ({ items: [], page: 1, page_size: 100, pages: 0, total: 0 })) })) const baseline = { enabled:false,platform:'openai',priority:50,load_factor:1,concurrency:3,group_ids:[],upgrade_enabled:false,upgrade_group_ids:[],successes_per_step:20,upgrade_step:1,max_concurrency:100,cooldown_seconds:60,revision:'fixture' } beforeEach(() => { localStorage.clear(); setActivePinia(createPinia()); vi.clearAllMocks() From f2009d24ce6b5c4c3f4acf6508cd493207c68a08 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Tue, 10 Nov 2026 23:38:00 +0800 Subject: [PATCH 2/5] fix(ci): mock fallback account reads in auto-config browser fixtures --- .github/scripts/model-billing-groups-browser.mjs | 5 +++++ .github/scripts/oauth-degradation-browser.mjs | 12 +++++++++++- .../oauth-initial-model-selection-browser.mjs | 12 +++++++++++- .github/scripts/oauth-initial-ws-preview.mjs | 13 ++++++++++++- .github/scripts/oauth-initial-ws-screenshot.mjs | 9 +++++++++ 5 files changed, 48 insertions(+), 3 deletions(-) diff --git a/.github/scripts/model-billing-groups-browser.mjs b/.github/scripts/model-billing-groups-browser.mjs index f1db40af37d0..838afe0ab4e3 100644 --- a/.github/scripts/model-billing-groups-browser.mjs +++ b/.github/scripts/model-billing-groups-browser.mjs @@ -83,6 +83,10 @@ try { const page=Number(url.searchParams.get('page')) if(page===2&&failSecondPage)return route.fulfill({status:503,json:{code:503,message:'synthetic page failure'}}) data={items:[groups[page-1]],total:2,page,page_size:100,pages:2} + } else if(url.pathname==='/api/v1/admin/accounts'){ + assert.equal(route.request().method(),'GET') + for(const [key,value] of Object.entries({platform:'openai',type:'apikey',status:'active',lite:'1'}))assert.equal(url.searchParams.get(key),value) + data={items:[],total:0,page:1,page_size:100,pages:0} } else if(url.pathname==='/api/v1/admin/account-quality-plans')data=[] else if(url.pathname==='/api/v1/admin/account-ops/auto-config/events')data={items:[],has_more:false} else throw new Error('Unexpected synthetic API: '+url.pathname) @@ -104,6 +108,7 @@ try { assert.equal(await page.getByTestId('model-billing-group-0-5').isChecked(),true) assert.equal(await page.getByTestId('model-billing-group-1-6').isChecked(),true) assert(requests.some(r=>r.path==='/api/v1/admin/groups'&&r.page==='2')) + assert(requests.some(r=>r.path==='/api/v1/admin/accounts'&&r.method==='GET')) await page.getByTestId('model-billing').screenshot({path:path.join(output,'selected-groups-desktop-zh.png')}) await page.setViewportSize({width:390,height:1000}) await page.getByTestId('model-billing').screenshot({path:path.join(output,'selected-groups-mobile-zh.png')}) diff --git a/.github/scripts/oauth-degradation-browser.mjs b/.github/scripts/oauth-degradation-browser.mjs index 737bec5a179d..44ef6e2370fb 100644 --- a/.github/scripts/oauth-degradation-browser.mjs +++ b/.github/scripts/oauth-degradation-browser.mjs @@ -27,8 +27,9 @@ const {default:Page}=new URLSearchParams(location.search).has('baseline')?await import {i18n,loadLocaleMessages} from '/src/i18n/index.ts'; import {defaultExcelBPSDefaults} from '/src/utils/excelBPSDefaults.ts'; import {defaultOpenAITwoFAAdmissionConfig} from '/src/utils/openaiTwoFAAdmission.ts'; +import {defaultOpenAIAPIKeyFallbackConfig} from '/src/utils/openaiAPIKeyFallback.ts'; import '/src/style.css'; -window.fixture={enabled:true,platform:'openai',priority:50,load_factor:1,concurrency:3,cost_multiplier:0.07,group_ids:[5],upgrade_enabled:false,upgrade_group_ids:[],successes_per_step:20,upgrade_step:1,max_concurrency:100,cooldown_seconds:60,revision:'synthetic',excel_bps:defaultExcelBPSDefaults(),openai_two_fa_admission:defaultOpenAITwoFAAdmissionConfig(),model_mappings:[],model_billing:{enabled:false,rules:[]},selected_models:null}; +window.fixture={enabled:true,platform:'openai',priority:50,load_factor:1,concurrency:3,cost_multiplier:0.07,group_ids:[5],upgrade_enabled:false,upgrade_group_ids:[],successes_per_step:20,upgrade_step:1,max_concurrency:100,cooldown_seconds:60,revision:'synthetic',excel_bps:defaultExcelBPSDefaults(),openai_two_fa_admission:defaultOpenAITwoFAAdmissionConfig(),openai_apikey_fallback:defaultOpenAIAPIKeyFallbackConfig(),openai_disable_scheduling_on_429_7d_threshold_percent:98,model_mappings:[],model_billing:{enabled:false,rules:[]},selected_models:null}; const lang=new URLSearchParams(location.search).get('lang')||'zh';await loadLocaleMessages(lang);i18n.global.locale.value=lang; createApp(Page).use(i18n).use(createPinia()).mount('#app');` process.chdir(frontend) // Tailwind/PostCSS resolve the actual frontend config. @@ -72,6 +73,11 @@ try { if (route.request().method() === 'PUT') { saved = route.request().postDataJSON(); saves.push(structuredClone(saved)) } data = saved ?? await route.request().frame().evaluate(() => window.fixture) } else if (url.pathname === '/api/v1/admin/groups/all') data = groups + else if (url.pathname === '/api/v1/admin/accounts') { + assert.equal(route.request().method(), 'GET') + assert.deepEqual(Object.fromEntries(url.searchParams), { page: '1', page_size: '100', platform: 'openai', type: 'apikey', status: 'active', lite: '1', sort_by: 'id', sort_order: 'asc' }) + data = { items: [], page: 1, page_size: 100, pages: 1, total: 0 } + } else if (url.pathname === '/api/v1/admin/groups') data = { items: groups, page: 1, page_size: 100, pages: 1, total: 2 } else if (url.pathname === '/api/v1/admin/account-quality-plans') data = [] else if (url.pathname === '/api/v1/admin/account-ops/auto-config/events') data = { items: [], has_more: false } @@ -90,6 +96,10 @@ try { assert.equal(await page.getByTestId('degradation-action').count(), 0) await page.screenshot({ path: path.join(output, 'before-zh.png'), fullPage: true }) await open() + await page.getByTestId('apikey-fallback-loading').waitFor({ state: 'detached' }) + assert.equal(await page.getByTestId('apikey-fallback-accounts-error').count(), 0) + assert.equal(await page.getByTestId('apikey-fallback-enabled').isChecked(), false) + assert(requests.some(request => request.path === '/api/v1/admin/accounts' && request.method === 'GET')) const card=page.getByTestId('degradation-action') const annotate=()=>page.addStyleTag({content:'[data-testid=degradation-action]::before{content:"CI fixture · 虚构数据 · 非生产";display:block;color:#92400e;font-size:12px}'}) assert.equal(await page.getByTestId('degradation-enabled').isChecked(),false) diff --git a/.github/scripts/oauth-initial-model-selection-browser.mjs b/.github/scripts/oauth-initial-model-selection-browser.mjs index 8d24b484389f..27a372b4f58c 100644 --- a/.github/scripts/oauth-initial-model-selection-browser.mjs +++ b/.github/scripts/oauth-initial-model-selection-browser.mjs @@ -27,8 +27,9 @@ const {default:Page}=new URLSearchParams(location.search).has('baseline')?await import {i18n,loadLocaleMessages} from '/src/i18n/index.ts'; import {defaultExcelBPSDefaults} from '/src/utils/excelBPSDefaults.ts'; import {defaultOpenAITwoFAAdmissionConfig} from '/src/utils/openaiTwoFAAdmission.ts'; +import {defaultOpenAIAPIKeyFallbackConfig} from '/src/utils/openaiAPIKeyFallback.ts'; import '/src/style.css'; -window.fixture={enabled:true,platform:'openai',priority:50,load_factor:1,concurrency:3,cost_multiplier:0.07,group_ids:[5],upgrade_enabled:false,upgrade_group_ids:[],successes_per_step:20,upgrade_step:1,max_concurrency:100,cooldown_seconds:60,revision:'synthetic',excel_bps:defaultExcelBPSDefaults(),openai_two_fa_admission:defaultOpenAITwoFAAdmissionConfig(),model_mappings:[],model_billing:{enabled:false,rules:[]},selected_models:null}; +window.fixture={enabled:true,platform:'openai',priority:50,load_factor:1,concurrency:3,cost_multiplier:0.07,group_ids:[5],upgrade_enabled:false,upgrade_group_ids:[],successes_per_step:20,upgrade_step:1,max_concurrency:100,cooldown_seconds:60,revision:'synthetic',excel_bps:defaultExcelBPSDefaults(),openai_two_fa_admission:defaultOpenAITwoFAAdmissionConfig(),openai_apikey_fallback:defaultOpenAIAPIKeyFallbackConfig(),openai_disable_scheduling_on_429_7d_threshold_percent:98,model_mappings:[],model_billing:{enabled:false,rules:[]},selected_models:null}; const lang=new URLSearchParams(location.search).get('lang')||'zh';await loadLocaleMessages(lang);i18n.global.locale.value=lang; createApp(Page).use(i18n).use(createPinia()).mount('#app');` process.chdir(frontend) // Tailwind/PostCSS resolve the actual frontend config. @@ -73,6 +74,11 @@ try { if (route.request().method() === 'PUT') { saved = route.request().postDataJSON(); saves.push(structuredClone(saved)) } data = saved ?? await route.request().frame().evaluate(() => window.fixture) } else if (url.pathname === '/api/v1/admin/groups/all') data = groups + else if (url.pathname === '/api/v1/admin/accounts') { + assert.equal(route.request().method(), 'GET') + assert.deepEqual(Object.fromEntries(url.searchParams), { page: '1', page_size: '100', platform: 'openai', type: 'apikey', status: 'active', lite: '1', sort_by: 'id', sort_order: 'asc' }) + data = { items: [], page: 1, page_size: 100, pages: 1, total: 0 } + } else if (url.pathname === '/api/v1/admin/groups') data = { items: groups, page: 1, page_size: 100, pages: 1, total: 2 } else if (url.pathname === '/api/v1/admin/account-quality-plans') data = [] else if (url.pathname === '/api/v1/admin/account-ops/auto-config/events') data = { items: [], has_more: false } @@ -91,6 +97,10 @@ try { assert.equal(await page.getByTestId('initial-model-selection').count(), 0) await page.getByTestId('initial-enabled').locator('xpath=ancestor::section').screenshot({ path: path.join(output, 'before-initial-template-zh.png') }) await open() + await page.getByTestId('apikey-fallback-loading').waitFor({ state: 'detached' }) + assert.equal(await page.getByTestId('apikey-fallback-accounts-error').count(), 0) + assert.equal(await page.getByTestId('apikey-fallback-enabled').isChecked(), false) + assert(requests.some(request => request.path === '/api/v1/admin/accounts' && request.method === 'GET')) 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') diff --git a/.github/scripts/oauth-initial-ws-preview.mjs b/.github/scripts/oauth-initial-ws-preview.mjs index 75afda4889bd..78e1c6b4be0a 100644 --- a/.github/scripts/oauth-initial-ws-preview.mjs +++ b/.github/scripts/oauth-initial-ws-preview.mjs @@ -35,17 +35,23 @@ import {i18n,loadLocaleMessages} from '/src/i18n/index.ts'; import {apiClient} from '/src/api/client.ts'; import {defaultExcelBPSDefaults} from '/src/utils/excelBPSDefaults.ts'; import {defaultOpenAITwoFAAdmissionConfig} from '/src/utils/openaiTwoFAAdmission.ts'; +import {defaultOpenAIAPIKeyFallbackConfig} from '/src/utils/openaiAPIKeyFallback.ts'; import {defaultModelBillingConfig} from '/src/utils/modelBilling.ts'; import {defaultOAuthModelMappings} from '/src/utils/oauthModelMappings.ts'; import View from '/src/views/admin/AutoConfigView.vue'; import '/src/style.css'; const locale=new URL(location.href).searchParams.get('locale')||'zh'; await loadLocaleMessages(locale);i18n.global.locale.value=locale; -let config={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:'synthetic-preview',openai_totp_rotate_on_429:false,openai_disable_scheduling_on_429:false,openai_two_fa_admission:defaultOpenAITwoFAAdmissionConfig(),excel_bps:defaultExcelBPSDefaults(),model_billing:defaultModelBillingConfig(),model_mappings:defaultOAuthModelMappings('openai')}; +let config={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:'synthetic-preview',openai_totp_rotate_on_429:false,openai_disable_scheduling_on_429:false,openai_two_fa_admission:defaultOpenAITwoFAAdmissionConfig(),openai_apikey_fallback:defaultOpenAIAPIKeyFallbackConfig(),openai_disable_scheduling_on_429_7d_threshold_percent:98,excel_bps:defaultExcelBPSDefaults(),model_billing:defaultModelBillingConfig(),model_mappings:defaultOAuthModelMappings('openai')}; const groups=[{id:5,name:'OpenAI Demo',platform:'openai',status:'active'},{id:6,name:'Anthropic Demo',platform:'anthropic',status:'active'}]; window.__previewRequests=[]; apiClient.defaults.adapter=async request=>{let data;window.__previewRequests.push({method:request.method,url:request.url});switch(request.url){ case '/admin/account-ops/auto-config':if(request.method==='put'){config=typeof request.data==='string'?JSON.parse(request.data):request.data;window.__saved=structuredClone(config)}data=structuredClone(config);break; +case '/admin/accounts':{ +const expected={page:1,page_size:100,platform:'openai',type:'apikey',status:'active',lite:'1',sort_by:'id',sort_order:'asc'}; +if(request.method!=='get'||Object.keys(request.params||{}).length!==Object.keys(expected).length||Object.entries(expected).some(([key,value])=>request.params[key]!==value))throw Error('Unexpected preview account query'); +data={items:[],page:1,page_size:100,pages:1,total:0};break; +} case '/admin/groups/all':data=groups;break; case '/admin/groups':data={items:groups,page:1,pages:1,page_size:100,total:groups.length};break; case '/admin/account-quality-plans':data=[];break; @@ -101,6 +107,11 @@ window.preview=mount(View,{attachTo:'#preview',global:{plugins:[createPinia(),i1 server.moduleGraph.invalidateAll() await page.reload({ waitUntil: 'networkidle' }) await page.getByTestId('initial-ws-mode-select').waitFor({ timeout: 60000 }) + await page.getByTestId('apikey-fallback').waitFor() + await page.getByTestId('apikey-fallback-loading').waitFor({ state: 'detached' }) + if (await page.getByTestId('apikey-fallback-accounts-error').count()) throw Error('Fallback account fixture failed to load') + if (await page.getByTestId('apikey-fallback-enabled').isChecked()) throw Error('Fallback must remain disabled in the WS fixture') + if (!await page.evaluate(() => window.__previewRequests.some(request => request.method === 'get' && request.url === '/admin/accounts'))) throw Error('Missing fallback account request') await capture('after-defaults.png') await page.getByTestId('initial-enabled').check() await page.getByTestId('initial-group-5').check() diff --git a/.github/scripts/oauth-initial-ws-screenshot.mjs b/.github/scripts/oauth-initial-ws-screenshot.mjs index 2cf359cc6792..2f904dc6c128 100644 --- a/.github/scripts/oauth-initial-ws-screenshot.mjs +++ b/.github/scripts/oauth-initial-ws-screenshot.mjs @@ -44,6 +44,11 @@ try { if(request.method==='put'){state.config=JSON.parse(request.data);state.writes.push(structuredClone(state.config));localStorage.setItem('fixture-oauth-ws',JSON.stringify(state.config))} data=structuredClone(state.config); }else if(path==='/admin/account-ops/auto-config/events')data={items:[],has_more:false}; + else if(path==='/admin/accounts'&&request.method==='get'){ + const params=request.params||{}; + if(params.platform!=='openai'||params.type!=='apikey'||params.status!=='active'||params.lite!=='1')throw Error('Unexpected fallback account filters'); + data={items:[],total:0,page:1,page_size:100,pages:1}; + } else if(path==='/admin/groups/all')data=groups; else if(path==='/admin/groups')data={items:groups,total:1,page:1,page_size:100,pages:1}; else if(path==='/admin/account-quality-plans')data=[]; @@ -79,6 +84,10 @@ try { await screenshot('before.png') manifest.results.push({ mode, ws_controls_present: false }) } else { + await page.getByTestId('apikey-fallback-loading').waitFor({state:'detached'}) + assert.equal(await page.getByTestId('apikey-fallback-accounts-error').count(), 0) + assert.equal(await page.getByTestId('apikey-fallback-enabled').isChecked(), false) + assert.equal(await page.evaluate(() => window.__oauthWSFixture.requests.some(request => request.method==='get'&&request.path==='/admin/accounts')), true) const select = () => page.getByTestId('initial-ws-mode-select') const acceleration = () => page.getByTestId('initial-ws-sse-acceleration-enabled') assert.equal(await select().inputValue(), 'ctx_pool') From 83c673578ae95d382d4a743d0d559066cc576f78 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Tue, 10 Nov 2026 23:39:39 +0800 Subject: [PATCH 3/5] fix(ci): check cleanup and type assertion results in fallback tests --- backend/internal/repository/account_apikey_fallback_test.go | 2 +- backend/internal/service/openai_apikey_fallback_test.go | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/backend/internal/repository/account_apikey_fallback_test.go b/backend/internal/repository/account_apikey_fallback_test.go index 54d16ca320c3..f9421fd2c13a 100644 --- a/backend/internal/repository/account_apikey_fallback_test.go +++ b/backend/internal/repository/account_apikey_fallback_test.go @@ -23,7 +23,7 @@ func TestAPIKeyFallbackChangedRowsControlSchedulingPublication(t *testing.T) { t.Run(tc.name, func(t *testing.T) { db, mock, err := sqlmock.New() require.NoError(t, err) - defer db.Close() + defer func() { _ = db.Close() }() expect := mock.ExpectExec("UPDATE accounts SET schedulable=TRUE,updated_at=NOW\\(\\)").WithArgs(int64(10), service.SettingKeyOAuthAutoConfig, "revision") if tc.err != nil { expect.WillReturnError(tc.err) diff --git a/backend/internal/service/openai_apikey_fallback_test.go b/backend/internal/service/openai_apikey_fallback_test.go index a2e52323041b..4c54629e5d8a 100644 --- a/backend/internal/service/openai_apikey_fallback_test.go +++ b/backend/internal/service/openai_apikey_fallback_test.go @@ -192,7 +192,9 @@ func TestOpenAIAPIKeyFallbackHealthMetricAndConfiguredWindow(t *testing.T) { cfg.OpenAIAPIKeyFallback.Metric, cfg.OpenAIAPIKeyFallback.Threshold, cfg.OpenAIAPIKeyFallback.WindowMinutes = "health_score", 80, 30 raw, err := json.Marshal(cfg) require.NoError(t, err) - svc.settings.(*accountOpsSettingsStub).raw = string(raw) + settings, ok := svc.settings.(*accountOpsSettingsStub) + require.True(t, ok) + settings.raw = string(raw) svc.evaluateOpenAIAPIKeyFallback(t.Context()) require.Equal(t, "health_score", metric.metric) require.Equal(t, 30*time.Minute, metric.window) From 7f65ab146ea79f2f941a76b9ad61ecd1f78922c5 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Tue, 10 Nov 2026 23:59:09 +0800 Subject: [PATCH 4/5] fix(ci): include browser timezone in fallback account fixtures --- .github/scripts/oauth-degradation-browser.mjs | 4 ++-- .github/scripts/oauth-initial-model-selection-browser.mjs | 4 ++-- .github/scripts/oauth-initial-ws-preview.mjs | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/scripts/oauth-degradation-browser.mjs b/.github/scripts/oauth-degradation-browser.mjs index 44ef6e2370fb..59305945752e 100644 --- a/.github/scripts/oauth-degradation-browser.mjs +++ b/.github/scripts/oauth-degradation-browser.mjs @@ -62,7 +62,7 @@ const errors = [], external = [], saves = [], requests = [] let saved const groups = [{ id: 5, name: 'OpenAI 示例组', platform: 'openai', status: 'active' }, { id: 6, name: 'Anthropic 示例组', platform: 'anthropic', status: 'active' }] try { - const context = await browser.newContext({ viewport: { width: 1280, height: 1000 } }) + const context = await browser.newContext({ viewport: { width: 1280, height: 1000 }, timezoneId: 'UTC' }) await context.route('**/*', async route => { const url = new URL(route.request().url()) if (url.origin !== 'http://127.0.0.1:4183') { external.push(url.origin); return route.abort() } @@ -75,7 +75,7 @@ try { } else if (url.pathname === '/api/v1/admin/groups/all') data = groups else if (url.pathname === '/api/v1/admin/accounts') { assert.equal(route.request().method(), 'GET') - assert.deepEqual(Object.fromEntries(url.searchParams), { page: '1', page_size: '100', platform: 'openai', type: 'apikey', status: 'active', lite: '1', sort_by: 'id', sort_order: 'asc' }) + assert.deepEqual(Object.fromEntries(url.searchParams), { page: '1', page_size: '100', platform: 'openai', type: 'apikey', status: 'active', lite: '1', sort_by: 'id', sort_order: 'asc', timezone: 'UTC' }) data = { items: [], page: 1, page_size: 100, pages: 1, total: 0 } } else if (url.pathname === '/api/v1/admin/groups') data = { items: groups, page: 1, page_size: 100, pages: 1, total: 2 } diff --git a/.github/scripts/oauth-initial-model-selection-browser.mjs b/.github/scripts/oauth-initial-model-selection-browser.mjs index 27a372b4f58c..f103888d984d 100644 --- a/.github/scripts/oauth-initial-model-selection-browser.mjs +++ b/.github/scripts/oauth-initial-model-selection-browser.mjs @@ -63,7 +63,7 @@ const errors = [], external = [], saves = [], requests = [] let saved const groups = [{ id: 5, name: 'OpenAI 示例组', platform: 'openai', status: 'active' }, { id: 6, name: 'Anthropic 示例组', platform: 'anthropic', status: 'active' }] try { - const context = await browser.newContext({ viewport: { width: 1280, height: 1000 } }) + const context = await browser.newContext({ viewport: { width: 1280, height: 1000 }, timezoneId: 'UTC' }) await context.route('**/*', async route => { const url = new URL(route.request().url()) if (url.origin !== 'http://127.0.0.1:4183') { external.push(url.origin); return route.abort() } @@ -76,7 +76,7 @@ try { } else if (url.pathname === '/api/v1/admin/groups/all') data = groups else if (url.pathname === '/api/v1/admin/accounts') { assert.equal(route.request().method(), 'GET') - assert.deepEqual(Object.fromEntries(url.searchParams), { page: '1', page_size: '100', platform: 'openai', type: 'apikey', status: 'active', lite: '1', sort_by: 'id', sort_order: 'asc' }) + assert.deepEqual(Object.fromEntries(url.searchParams), { page: '1', page_size: '100', platform: 'openai', type: 'apikey', status: 'active', lite: '1', sort_by: 'id', sort_order: 'asc', timezone: 'UTC' }) data = { items: [], page: 1, page_size: 100, pages: 1, total: 0 } } else if (url.pathname === '/api/v1/admin/groups') data = { items: groups, page: 1, page_size: 100, pages: 1, total: 2 } diff --git a/.github/scripts/oauth-initial-ws-preview.mjs b/.github/scripts/oauth-initial-ws-preview.mjs index 78e1c6b4be0a..78865c817ed6 100644 --- a/.github/scripts/oauth-initial-ws-preview.mjs +++ b/.github/scripts/oauth-initial-ws-preview.mjs @@ -48,7 +48,7 @@ window.__previewRequests=[]; apiClient.defaults.adapter=async request=>{let data;window.__previewRequests.push({method:request.method,url:request.url});switch(request.url){ case '/admin/account-ops/auto-config':if(request.method==='put'){config=typeof request.data==='string'?JSON.parse(request.data):request.data;window.__saved=structuredClone(config)}data=structuredClone(config);break; case '/admin/accounts':{ -const expected={page:1,page_size:100,platform:'openai',type:'apikey',status:'active',lite:'1',sort_by:'id',sort_order:'asc'}; +const expected={page:1,page_size:100,platform:'openai',type:'apikey',status:'active',lite:'1',sort_by:'id',sort_order:'asc',timezone:'UTC'}; if(request.method!=='get'||Object.keys(request.params||{}).length!==Object.keys(expected).length||Object.entries(expected).some(([key,value])=>request.params[key]!==value))throw Error('Unexpected preview account query'); data={items:[],page:1,page_size:100,pages:1,total:0};break; } @@ -81,7 +81,7 @@ window.preview=mount(View,{attachTo:'#preview',global:{plugins:[createPinia(),i1 }) await server.listen() browser = process.env.SUB2API_CDP_ENDPOINT ? await chromium.connectOverCDP(process.env.SUB2API_CDP_ENDPOINT) : await chromium.launch({ headless: true }) - context = await browser.newContext({ viewport: { width: 1180, height: 1000 }, locale: 'zh-CN' }) + context = await browser.newContext({ viewport: { width: 1180, height: 1000 }, locale: 'zh-CN', timezoneId: 'UTC' }) const page = await context.newPage() page.on('pageerror', error => { errors.push(error.message); console.error(error.message) }) page.on('console', message => { From 0c7c3210fd7b5d69b8d9518f053547a0cbbdfb06 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Wed, 11 Nov 2026 00:01:13 +0800 Subject: [PATCH 5/5] fix(test): use Spark quota dimension for fallback shadow fixture --- .../repository/account_apikey_fallback_integration_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/backend/internal/repository/account_apikey_fallback_integration_test.go b/backend/internal/repository/account_apikey_fallback_integration_test.go index 97b8a2bda726..08b09e734403 100644 --- a/backend/internal/repository/account_apikey_fallback_integration_test.go +++ b/backend/internal/repository/account_apikey_fallback_integration_test.go @@ -52,6 +52,7 @@ func TestAPIKeyFallbackChecksSavedPolicyAndAccountEligibility(t *testing.T) { if tc.shadow { parent := mustCreateAccount(t, client, &service.Account{Name: "fallback-parent"}) account.ParentAccountID = &parent.ID + account.QuotaDimension = service.QuotaDimensionSpark } account = mustCreateAccount(t, client, account) now := time.Now().UTC().Truncate(time.Microsecond)