From e3befd862a83610ffa511b9394880e98a310a2c6 Mon Sep 17 00:00:00 2001 From: Zyy <0x@ainz.cc> Date: Wed, 11 Nov 2026 01:24:37 +0800 Subject: [PATCH] feat(accounts): pause scheduling at general quota window limits (#670) * feat(accounts): pause scheduling at general quota window limits Co-authored-by: Codex * fix(store): preserve quota pauses across proxy changes Co-authored-by: Codex * fix(openai): retry quota merges against the observed snapshot Co-authored-by: Codex --------- Co-authored-by: Zyy Co-authored-by: Codex --- .../gateway-admin/src/model/accounts.rs | 14 + .../gateway-admin/src/model/observability.rs | 3 +- .../src/model/provider_credentials.rs | 3 +- .../crates/gateway-admin/src/ports/store.rs | 1 + .../src/use_case/accounts/mod.rs | 50 +++- .../src/use_case/peer_link/projection.rs | 3 +- .../use_case/peer_link/upstream/projection.rs | 1 + .../use_case/peer_link/upstream/refresh.rs | 1 + backend/crates/gateway-admin/tests/main.rs | 4 + .../tests/model/provider_credentials.rs | 2 + .../tests/model/quota_forecast.rs | 1 + .../tests/use_case/account_groups.rs | 1 + .../tests/use_case/accounts/mod.rs | 12 + .../gateway-admin/tests/use_case/mod.rs | 1 + .../gateway-admin/tests/use_case/proxies.rs | 1 + .../src/admin/accounts/presenter.rs | 7 +- .../gateway-api/src/admin/accounts/wire.rs | 11 +- .../src/admin/observability/presenter.rs | 1 + .../src/admin/observability/wire.rs | 1 + .../tests/admin/accounts/handlers.rs | 10 + .../crates/gateway-api/tests/admin/errors.rs | 3 + backend/crates/gateway-api/tests/admin/mod.rs | 6 + .../tests/admin/observability/response.rs | 1 + .../gateway-api/tests/openai/peer_link/mod.rs | 4 + .../crates/gateway-core/src/account/mod.rs | 2 + .../crates/gateway-core/src/account/model.rs | 34 ++- .../gateway-core/src/account/quota_limits.rs | 68 +++++ .../runtime/tests/generation/data.rs | 3 + .../src/postgres/account_groups.rs | 3 +- .../postgres/observability/admin_adapter.rs | 5 +- .../provider_accounts/admin_adapter.rs | 6 + .../provider_accounts/admin_queries.rs | 11 +- .../provider_accounts/core_adapter.rs | 3 +- .../src/postgres/provider_accounts/mapping.rs | 2 + .../src/postgres/provider_accounts/quota.rs | 30 +-- .../postgres/provider_accounts/repository.rs | 89 ++++--- .../src/postgres/provider_accounts/rows.rs | 18 +- .../src/postgres/provider_accounts/runtime.rs | 3 +- .../gateway-store/src/postgres/proxies.rs | 12 +- .../tests/postgres/provider_accounts/mod.rs | 54 +++- .../tests/postgres/provider_accounts/quota.rs | 80 ++++++ .../postgres/provider_accounts/timestamps.rs | 1 + .../gateway-store/tests/postgres/proxies.rs | 40 +++ .../crates/providers/openai/src/admin/mod.rs | 23 +- .../providers/openai/src/admin/quota.rs | 3 +- .../openai/src/credential/quota/mod.rs | 7 +- .../openai/src/credential/quota/passive.rs | 155 ++++++----- .../openai/src/credential/quota/scheduling.rs | 15 ++ .../openai/src/credential/quota/service.rs | 250 +++++++++--------- .../openai/src/credential/quota/snapshot.rs | 62 +++++ .../openai/src/credential/selector.rs | 23 +- .../providers/openai/tests/admin/mod.rs | 7 + .../providers/openai/tests/admin/peer_info.rs | 1 + .../openai/tests/credential/contract/mod.rs | 1 + .../openai/tests/credential/quota/mod.rs | 121 +++++++++ .../tests/credential/quota/reset_recovery.rs | 1 + .../tests/credential/quota/scheduling.rs | 1 + .../openai/tests/credential/quota/slots.rs | 1 + .../openai/tests/credential/quota/snapshot.rs | 6 + .../openai/tests/credential/quota/warmup.rs | 2 + .../openai/tests/provider/contract/mod.rs | 106 ++++++++ .../crates/providers/openai/tests/support.rs | 54 +++- backend/crates/providers/xai/src/admin.rs | 1 + .../xai/src/credential/repository.rs | 1 + backend/crates/providers/xai/tests/admin.rs | 3 + .../providers/xai/tests/credential/quota.rs | 1 + .../providers/xai/tests/credential/refresh.rs | 1 + .../xai/tests/credential/selector.rs | 1 + backend/migrations/.frozen-sha256 | 1 + .../migrations/0044_account_quota_limits.sql | 3 + docs/api.md | 12 +- docs/architecture.md | 8 +- frontend/src/api/modules/accounts/index.ts | 1 + .../src/api/modules/accounts/management.ts | 2 + frontend/src/api/modules/accounts/quota.ts | 9 + frontend/src/api/modules/accounts/types.ts | 6 +- frontend/src/api/modules/dashboard.ts | 1 + frontend/src/i18n/locales/en/accounts.json | 12 + frontend/src/i18n/locales/en/dashboard.json | 4 +- .../src/i18n/locales/zh-Hans/accounts.json | 12 + .../src/i18n/locales/zh-Hans/dashboard.json | 4 +- .../src/i18n/locales/zh-Hant/accounts.json | 12 + .../src/i18n/locales/zh-Hant/dashboard.json | 4 +- .../components/AccountConnectionTestModal.vue | 1 + .../components/AccountOverviewCards.vue | 2 +- .../components/account-quota-panel/Entry.vue | 2 +- .../account-quota-panel/QuotaActionButton.vue | 22 ++ .../account-quota-panel/QuotaLimits.vue | 90 +++++++ .../account-quota-panel/ResetCredits.vue | 8 +- .../components/account-quota-panel/index.vue | 31 ++- .../components/account-status-badge/index.vue | 23 +- .../account-status-badge/presenter.ts | 82 ++++-- .../accounts/composables/useAccountsQuery.ts | 1 + frontend/src/views/accounts/constants.ts | 3 + frontend/src/views/accounts/index.vue | 1 + .../components/AccountOverviewCard.vue | 16 +- .../src/views/theme/fixtures/dashboard.ts | 4 + 97 files changed, 1464 insertions(+), 366 deletions(-) create mode 100644 backend/crates/gateway-core/src/account/quota_limits.rs create mode 100644 backend/migrations/0044_account_quota_limits.sql create mode 100644 frontend/src/views/accounts/components/account-quota-panel/QuotaActionButton.vue create mode 100644 frontend/src/views/accounts/components/account-quota-panel/QuotaLimits.vue diff --git a/backend/crates/gateway-admin/src/model/accounts.rs b/backend/crates/gateway-admin/src/model/accounts.rs index 6bdeff9ce..c77ea263b 100644 --- a/backend/crates/gateway-admin/src/model/accounts.rs +++ b/backend/crates/gateway-admin/src/model/accounts.rs @@ -21,6 +21,7 @@ pub use gateway_core::account::{ /// 账号可用的管理操作 #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct ProviderAccountCapabilities { + pub quota_limits_supported: bool, pub quota_credits: bool, pub quota: bool, pub quota_refresh: bool, @@ -111,6 +112,8 @@ pub enum AccountGroupFilter { /// 账号公共存储投影;Provider 专属字段不进入此结构 #[derive(Debug, Clone, PartialEq, Eq)] pub struct AccountRecord { + pub quota_paused: bool, + pub quota_limits: gateway_core::account::AccountQuotaLimits, pub auto_use_quota_credits: bool, pub id: String, pub provider_kind: ProviderKind, @@ -251,6 +254,7 @@ pub struct AccountUpdateResult { /// 仅修改显式字段的批量账号设置命令 #[derive(Debug, Clone, PartialEq, Eq)] pub struct BatchUpdateAccounts { + pub quota_limits: Option, pub auto_use_quota_credits: Option, pub account_ids: Vec, pub enabled: Option, @@ -261,6 +265,16 @@ pub struct BatchUpdateAccounts { pub outbound_proxy: Option, } +/// 已按拟提交策略重算的账号暂停结果,以快照版本防止旧判断覆盖新观测 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PreparedQuotaPause { + pub observed_at: Option>, + pub revision: Revision, + pub paused: bool, +} + +pub type PreparedQuotaPauses = std::collections::BTreeMap; + /// 批量账号更新结果 #[derive(Debug, Clone, PartialEq, Eq)] pub struct AccountsUpdateResult { diff --git a/backend/crates/gateway-admin/src/model/observability.rs b/backend/crates/gateway-admin/src/model/observability.rs index 4b86d698d..96ef18ac3 100644 --- a/backend/crates/gateway-admin/src/model/observability.rs +++ b/backend/crates/gateway-admin/src/model/observability.rs @@ -690,11 +690,12 @@ pub struct RequestMetricPoint { pub costs: Vec, } -/// 账号池的统一五态统计 +/// 账号池的状态统计 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct AccountPoolMetrics { pub total: u64, pub normal: u64, + pub quota_paused: u64, pub quota_exhausted: u64, pub rate_limited: u64, pub disabled: u64, diff --git a/backend/crates/gateway-admin/src/model/provider_credentials.rs b/backend/crates/gateway-admin/src/model/provider_credentials.rs index 9fb987e1d..e84287864 100644 --- a/backend/crates/gateway-admin/src/model/provider_credentials.rs +++ b/backend/crates/gateway-admin/src/model/provider_credentials.rs @@ -845,6 +845,7 @@ pub struct ProviderQuotaReadRequest<'a> { /// Provider 已解析的 quota 结果及其不透明差异字段 #[derive(Debug, Default, Clone, PartialEq)] pub struct ProviderQuota { + pub paused_windows: Vec, pub upstream: Option, /// 上游额度响应明确提供的套餐,可用于补全账号展示 pub plan_type: Option, @@ -852,7 +853,7 @@ pub struct ProviderQuota { pub refresh_token_expires_at: Option>, pub windows: Vec, pub credits: Option, - /// 展示用快照级触顶事实(顶层或任一窗口触顶);不参与账号五态派生 + /// 展示用快照级触顶事实(顶层或任一窗口触顶);不参与账号状态派生 pub limit_reached: bool, pub provider_data: Option, } diff --git a/backend/crates/gateway-admin/src/ports/store.rs b/backend/crates/gateway-admin/src/ports/store.rs index 60375bfe3..18c079dbb 100644 --- a/backend/crates/gateway-admin/src/ports/store.rs +++ b/backend/crates/gateway-admin/src/ports/store.rs @@ -255,6 +255,7 @@ pub trait AccountStore: async fn batch_update_accounts( &self, command: BatchUpdateAccounts, + pauses: crate::model::accounts::PreparedQuotaPauses, context: &MutationContext, ) -> AdminStoreResult; diff --git a/backend/crates/gateway-admin/src/use_case/accounts/mod.rs b/backend/crates/gateway-admin/src/use_case/accounts/mod.rs index 7827b6d49..c49d1a679 100644 --- a/backend/crates/gateway-admin/src/use_case/accounts/mod.rs +++ b/backend/crates/gateway-admin/src/use_case/accounts/mod.rs @@ -759,6 +759,7 @@ impl AccountsService for DefaultAccountsService { self.accounts .batch_update_accounts( BatchUpdateAccounts { + quota_limits: None, auto_use_quota_credits: None, account_ids: vec![account_id.to_string()], enabled: Some(true), @@ -768,6 +769,7 @@ impl AccountsService for DefaultAccountsService { group_ids: None, outbound_proxy: None, }, + Default::default(), context, ) .await @@ -841,8 +843,52 @@ impl AccountsService for DefaultAccountsService { Vec, ), >::new(); + let mut pauses = BTreeMap::new(); for account_id in &account_ids { - let (item, provider) = self.provider_for_account(account_id).await?; + let (mut item, provider) = self.provider_for_account(account_id).await?; + if let Some(limits) = &command.quota_limits { + if !provider + .account_capabilities(account_id, &item.account.authentication_kind) + .quota_limits_supported + { + return Err(AdminError::invalid("该账号不支持通用额度窗口上限")); + } + let new_keys = limits + .keys() + .filter(|key| !item.account.quota_limits.contains(key)) + .map(str::to_owned) + .collect::>(); + if !limits.is_empty() { + item.account.quota_limits = limits.clone(); + let quota = provider + .read_quotas(&[ProviderQuotaReadRequest { + account: &item.account, + rolling_usage: None, + }]) + .await + .into_iter() + .next() + .ok_or_else(|| AdminError::invalid("缺少账号额度观测结果"))? + .map_err(|error| map_provider_error(error, "provider quota"))?; + if new_keys.iter().any(|key| { + !quota.windows.iter().any(|window| { + window.key == *key + && window.local_usage_attribution + == QuotaLocalUsageAttribution::AccountWide + }) + }) { + return Err(AdminError::invalid("只能设置已观测的通用额度窗口")); + } + pauses.insert( + item.account.id.clone(), + crate::model::accounts::PreparedQuotaPause { + revision: item.account.credential_revision, + observed_at: quota.observed_at, + paused: !quota.paused_windows.is_empty(), + }, + ); + } + } if command.auto_use_quota_credits.is_some() && !provider .account_capabilities(account_id, &item.account.authentication_kind) @@ -864,7 +910,7 @@ impl AccountsService for DefaultAccountsService { let enabled = command.enabled; let result = self .accounts - .batch_update_accounts(command, context) + .batch_update_accounts(command, pauses, context) .await .map_err(|error| map_store_error(error, "provider accounts"))?; for (provider, provider_ids, _) in providers.values() { diff --git a/backend/crates/gateway-admin/src/use_case/peer_link/projection.rs b/backend/crates/gateway-admin/src/use_case/peer_link/projection.rs index b30d26e7c..4e28da684 100644 --- a/backend/crates/gateway-admin/src/use_case/peer_link/projection.rs +++ b/backend/crates/gateway-admin/src/use_case/peer_link/projection.rs @@ -38,7 +38,7 @@ pub(super) fn pool_summary( for account in accounts { match status(account, runtime, now) { AccountStatus::Normal => summary.ready += 1, - AccountStatus::RateLimited => summary.cooldown += 1, + AccountStatus::QuotaPaused | AccountStatus::RateLimited => summary.cooldown += 1, AccountStatus::QuotaExhausted => summary.exhausted += 1, AccountStatus::Disabled => summary.disabled += 1, AccountStatus::Error => summary.error += 1, @@ -271,6 +271,7 @@ fn status( ) -> AccountStatus { resolve_account_status( &AccountStatusFacts { + quota_paused: account.quota_paused, enabled: account.enabled, credential_state: account.credential_state, access_token_expires_at: account.access_token_expires_at.map(Into::into), diff --git a/backend/crates/gateway-admin/src/use_case/peer_link/upstream/projection.rs b/backend/crates/gateway-admin/src/use_case/peer_link/upstream/projection.rs index 9fdf76499..d22cde3f8 100644 --- a/backend/crates/gateway-admin/src/use_case/peer_link/upstream/projection.rs +++ b/backend/crates/gateway-admin/src/use_case/peer_link/upstream/projection.rs @@ -214,6 +214,7 @@ impl PeerInfoService { } } ProviderQuota { + paused_windows: Vec::new(), upstream: Some(info), plan_type: None, observed_at, diff --git a/backend/crates/gateway-admin/src/use_case/peer_link/upstream/refresh.rs b/backend/crates/gateway-admin/src/use_case/peer_link/upstream/refresh.rs index 5648fcd05..46a3dace2 100644 --- a/backend/crates/gateway-admin/src/use_case/peer_link/upstream/refresh.rs +++ b/backend/crates/gateway-admin/src/use_case/peer_link/upstream/refresh.rs @@ -170,6 +170,7 @@ impl PeerInfoService { .and_then(|peer| quota::observe(&peer, started_at, now)) .unwrap_or(QuotaState::unknown()); let observation = QuotaObservation { + quota_pause: None, expected_connection: Some(connection.clone()), account_id: id.clone(), expected_revision: connection.credential_revision, diff --git a/backend/crates/gateway-admin/tests/main.rs b/backend/crates/gateway-admin/tests/main.rs index 2ebb9dfc2..c35611535 100644 --- a/backend/crates/gateway-admin/tests/main.rs +++ b/backend/crates/gateway-admin/tests/main.rs @@ -106,6 +106,7 @@ fn provider_document_debug_should_not_expose_opaque_material() { #[test] fn representative_quota_should_prefer_short_window_and_highest_usage() { let quota = ProviderQuota { + paused_windows: Vec::new(), upstream: None, credits: None, plan_type: None, @@ -129,6 +130,7 @@ fn representative_quota_should_prefer_account_wide_window_over_model_specific_wi let mut model_specific = quota_window("shortTerm", Some(18_000), Some(64.0)); model_specific.local_usage_attribution = QuotaLocalUsageAttribution::Unavailable; let quota = ProviderQuota { + paused_windows: Vec::new(), upstream: None, credits: None, plan_type: None, @@ -148,6 +150,7 @@ fn representative_quota_should_prefer_account_wide_window_over_model_specific_wi #[test] fn exhausted_quota_should_project_full_usage_to_only_the_representative_window() { let mut quota = ProviderQuota { + paused_windows: Vec::new(), upstream: None, credits: None, plan_type: None, @@ -178,6 +181,7 @@ fn exhausted_quota_should_preserve_the_provider_identified_reached_window() { let mut reached = quota_window("monthly", Some(2_592_000), Some(98.0)); reached.limit_reached = true; let mut quota = ProviderQuota { + paused_windows: Vec::new(), upstream: None, credits: None, plan_type: None, diff --git a/backend/crates/gateway-admin/tests/model/provider_credentials.rs b/backend/crates/gateway-admin/tests/model/provider_credentials.rs index 031d4fb5a..9edb5fd43 100644 --- a/backend/crates/gateway-admin/tests/model/provider_credentials.rs +++ b/backend/crates/gateway-admin/tests/model/provider_credentials.rs @@ -116,6 +116,7 @@ fn selected_usage_window(quota: &ProviderQuota) -> Option<(&str, AccountUsagePer fn usage_quota(windows: Vec) -> ProviderQuota { ProviderQuota { + paused_windows: Vec::new(), upstream: None, credits: None, plan_type: None, @@ -168,6 +169,7 @@ fn usage_window(key: &str, group: &str, seconds: u64) -> ProviderQuotaWindow { #[test] fn dashboard_quota_should_preserve_unknown_and_actual_window_facts() { let mut quota = ProviderQuota { + paused_windows: Vec::new(), upstream: None, credits: None, plan_type: None, diff --git a/backend/crates/gateway-admin/tests/model/quota_forecast.rs b/backend/crates/gateway-admin/tests/model/quota_forecast.rs index 6284af338..86c646058 100644 --- a/backend/crates/gateway-admin/tests/model/quota_forecast.rs +++ b/backend/crates/gateway-admin/tests/model/quota_forecast.rs @@ -59,6 +59,7 @@ fn window(key: &str, days: u64) -> ProviderQuotaWindow { fn quota(windows: Vec) -> ProviderQuota { ProviderQuota { + paused_windows: Vec::new(), upstream: None, credits: None, plan_type: None, diff --git a/backend/crates/gateway-admin/tests/use_case/account_groups.rs b/backend/crates/gateway-admin/tests/use_case/account_groups.rs index dd2d3ef65..087894176 100644 --- a/backend/crates/gateway-admin/tests/use_case/account_groups.rs +++ b/backend/crates/gateway-admin/tests/use_case/account_groups.rs @@ -377,6 +377,7 @@ fn member(account_id: &str, total_slots: u64) -> AccountGroupMemberFact { group_id: group_id(), account_id: account_id.to_owned(), status: AccountStatusFacts { + quota_paused: false, enabled: true, credential_state: CredentialState::Ready, access_token_expires_at: None, diff --git a/backend/crates/gateway-admin/tests/use_case/accounts/mod.rs b/backend/crates/gateway-admin/tests/use_case/accounts/mod.rs index e615c1317..b57e655f4 100644 --- a/backend/crates/gateway-admin/tests/use_case/accounts/mod.rs +++ b/backend/crates/gateway-admin/tests/use_case/accounts/mod.rs @@ -714,6 +714,7 @@ impl FakeAccountStore { fn page_item(account: AccountRecord) -> AccountPageItem { let facts = AccountStatusFacts { + quota_paused: false, enabled: account.enabled, credential_state: account.credential_state, access_token_expires_at: account.access_token_expires_at.map(Into::into), @@ -788,6 +789,7 @@ impl AccountStore for FakeAccountStore { summary: AccountSummary { total, normal: 1, + quota_paused: 0, quota_exhausted: 0, rate_limited: 0, disabled: 0, @@ -1082,6 +1084,7 @@ impl AccountStore for FakeAccountStore { async fn batch_update_accounts( &self, command: BatchUpdateAccounts, + _: gateway_admin::model::accounts::PreparedQuotaPauses, context: &MutationContext, ) -> AdminStoreResult { self.record("store.batch_update_accounts"); @@ -1910,6 +1913,7 @@ async fn accounts_batch_update_should_commit_once_and_notify_each_provider() { .batch_update( &context("batch-update-request"), BatchUpdateAccounts { + quota_limits: None, auto_use_quota_credits: None, model_access: Default::default(), outbound_proxy: None, @@ -2078,6 +2082,7 @@ async fn accounts_list_should_degrade_quota_failure_to_empty_window_without_drop let events = events(); let openai = FakeProviderAdmin::new("openai", events.clone()); openai.set_quota(ProviderQuota { + paused_windows: Vec::new(), upstream: None, credits: None, plan_type: None, @@ -2238,6 +2243,7 @@ async fn accounts_list_should_map_unknown_credential_to_error_not_normal() { async fn accounts_list_should_not_derive_rate_limited_from_provider_quota_view() { let provider = FakeProviderAdmin::new("openai", events()); provider.set_quota(ProviderQuota { + paused_windows: Vec::new(), upstream: None, credits: None, plan_type: None, @@ -2289,6 +2295,7 @@ async fn accounts_list_should_not_derive_rate_limited_from_provider_quota_view() async fn accounts_list_should_not_derive_exhaustion_from_provider_quota_view() { let provider = FakeProviderAdmin::new("openai", events()); provider.set_quota(ProviderQuota { + paused_windows: Vec::new(), upstream: None, credits: None, plan_type: None, @@ -2895,6 +2902,7 @@ async fn accounts_list_should_attach_local_usage_to_quota_windows() { let provider = FakeProviderAdmin::new("openai", events()); let reset_at = Utc::now() + TimeDelta::hours(1); provider.set_quota(ProviderQuota { + paused_windows: Vec::new(), upstream: None, credits: None, plan_type: None, @@ -3059,6 +3067,7 @@ async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_w let provider = FakeProviderAdmin::new("openai", events()); let reset_at = Utc::now() + TimeDelta::days(7); provider.set_quota(ProviderQuota { + paused_windows: Vec::new(), upstream: None, credits: None, plan_type: None, @@ -3364,6 +3373,7 @@ pub(super) fn document() -> ProviderDocument { fn empty_quota() -> ProviderQuota { ProviderQuota { + paused_windows: Vec::new(), upstream: None, credits: None, plan_type: None, @@ -3401,6 +3411,8 @@ fn quota_local_usage(account_id: &str, total_tokens: u64) -> AccountUsage { pub(super) fn account_record(kind: &str) -> AccountRecord { let now = Utc::now(); AccountRecord { + quota_paused: false, + quota_limits: Default::default(), auto_use_quota_credits: false, outbound_proxy_id: None, outbound_proxy_enabled: true, diff --git a/backend/crates/gateway-admin/tests/use_case/mod.rs b/backend/crates/gateway-admin/tests/use_case/mod.rs index 39cf5e5b8..1243e7faa 100644 --- a/backend/crates/gateway-admin/tests/use_case/mod.rs +++ b/backend/crates/gateway-admin/tests/use_case/mod.rs @@ -644,6 +644,7 @@ impl AccountStore for UnavailableStore { async fn batch_update_accounts( &self, _: BatchUpdateAccounts, + _: gateway_admin::model::accounts::PreparedQuotaPauses, _: &MutationContext, ) -> AdminStoreResult { Err(unavailable("account batch update")) diff --git a/backend/crates/gateway-admin/tests/use_case/proxies.rs b/backend/crates/gateway-admin/tests/use_case/proxies.rs index 6dc76e8f9..e95dbc707 100644 --- a/backend/crates/gateway-admin/tests/use_case/proxies.rs +++ b/backend/crates/gateway-admin/tests/use_case/proxies.rs @@ -281,6 +281,7 @@ async fn linked_accounts_share_plan_resolution_and_only_read_cached_quota() { ] { let provider = FakeProviderAdmin::new("openai", events()); provider.set_quota(ProviderQuota { + paused_windows: Vec::new(), upstream: None, credits: None, plan_type: cached.map(str::to_owned), diff --git a/backend/crates/gateway-api/src/admin/accounts/presenter.rs b/backend/crates/gateway-api/src/admin/accounts/presenter.rs index d6b764877..454ae1107 100644 --- a/backend/crates/gateway-api/src/admin/accounts/presenter.rs +++ b/backend/crates/gateway-api/src/admin/accounts/presenter.rs @@ -25,6 +25,7 @@ pub(super) fn account_page_data( summary: AccountSummaryView { total: result.summary.total, normal: result.summary.normal, + quota_paused: result.summary.quota_paused, quota_exhausted: result.summary.quota_exhausted, rate_limited: result.summary.rate_limited, disabled: result.summary.disabled, @@ -116,6 +117,7 @@ pub(super) fn account_view( let (mut quota, refresh_token_expires_at) = account_quota_view(quota, cooldown, now, time); quota.protection_rules = protection_rules; AccountView { + quota_limits: account.quota_limits, auto_use_quota_credits: account.auto_use_quota_credits, upstream, capabilities: capabilities.into(), @@ -272,6 +274,7 @@ pub(super) fn account_quota_view( let recovery_probe_required = cooldown.is_some_and(|value| value.kind.requires_probe()); ( AccountQuotaView { + paused_windows: quota.paused_windows, refreshed_at: quota.observed_at.map(|value| time.rfc3339(&value)), refreshed_at_relative: quota .observed_at @@ -306,7 +309,7 @@ pub(crate) fn quota_window_view( limit_id, limit_name, role, - local_usage_attribution: _, + local_usage_attribution, window_seconds, used_percent, reset_at, @@ -318,6 +321,8 @@ pub(crate) fn quota_window_view( .as_ref() .map_or_else(|| label.clone(), |name| format!("{name} · {label}")); AccountQuotaWindowView { + account_wide: local_usage_attribution + == gateway_admin::model::provider_credentials::QuotaLocalUsageAttribution::AccountWide, source_account_id: upstream.as_ref().and_then(|value| value.account_id.clone()), amount: upstream .as_ref() diff --git a/backend/crates/gateway-api/src/admin/accounts/wire.rs b/backend/crates/gateway-api/src/admin/accounts/wire.rs index e86c0ca90..cd9e2ae05 100644 --- a/backend/crates/gateway-api/src/admin/accounts/wire.rs +++ b/backend/crates/gateway-api/src/admin/accounts/wire.rs @@ -61,6 +61,7 @@ pub struct ListQuery { #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct BatchUpdateAccountsRequest { + pub quota_limits: Option, pub auto_use_quota_credits: Option, pub outbound_proxy_id: Option, pub outbound_proxy_url: Option, @@ -118,7 +119,8 @@ impl BatchUpdateAccountsRequest { .map(parse_concurrency_limit) .transpose()?; self.weight.map(parse_account_weight).transpose()?; - if self.auto_use_quota_credits.is_none() + if self.quota_limits.is_none() + && self.auto_use_quota_credits.is_none() && self.enabled.is_none() && self.concurrency_limit.is_none() && self.weight.is_none() @@ -135,6 +137,7 @@ impl BatchUpdateAccountsRequest { pub(super) fn into_command(self) -> Result { self.validate()?; Ok(BatchUpdateAccounts { + quota_limits: self.quota_limits, auto_use_quota_credits: self.auto_use_quota_credits, outbound_proxy: proxy_selection(self.outbound_proxy_id, self.outbound_proxy_url)?, account_ids: self.account_ids, @@ -259,6 +262,7 @@ pub struct AccountPageData { pub struct AccountSummaryView { pub total: u64, pub normal: u64, + pub quota_paused: u64, pub quota_exhausted: u64, pub rate_limited: u64, pub disabled: u64, @@ -269,6 +273,7 @@ pub struct AccountSummaryView { #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct AccountView { + pub quota_limits: gateway_core::account::AccountQuotaLimits, pub auto_use_quota_credits: bool, pub upstream: Option, pub capabilities: AccountCapabilitiesView, @@ -322,6 +327,7 @@ pub struct AccountCapacityView { #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct AccountCapabilitiesView { + pub quota_limits_supported: bool, pub quota_credits: bool, pub quota: bool, pub quota_refresh: bool, @@ -341,6 +347,7 @@ impl From for Accou subscription: value.subscription, avatar: value.avatar, reset_credits: value.reset_credits, + quota_limits_supported: value.quota_limits_supported, quota_credits: value.quota_credits, consume_reset_credit: value.consume_reset_credit, } @@ -392,6 +399,7 @@ pub use crate::admin::account_groups::AccountGroupRefView; #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct AccountQuotaView { + pub paused_windows: Vec, pub refreshed_at: Option, pub refreshed_at_relative: Option, pub refreshed_at_display: String, @@ -419,6 +427,7 @@ pub struct AccountQuotaCreditsView { #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct AccountQuotaWindowView { + pub account_wide: bool, #[serde(skip_serializing_if = "Option::is_none")] pub source_account_id: Option, pub amount: Option, diff --git a/backend/crates/gateway-api/src/admin/observability/presenter.rs b/backend/crates/gateway-api/src/admin/observability/presenter.rs index 546d0382d..841e69d69 100644 --- a/backend/crates/gateway-api/src/admin/observability/presenter.rs +++ b/backend/crates/gateway-api/src/admin/observability/presenter.rs @@ -1042,6 +1042,7 @@ pub(crate) fn dashboard_view( pool_summary: DashboardPoolSummaryView { total: provider_accounts.total, normal: provider_accounts.normal, + quota_paused: provider_accounts.quota_paused, quota_exhausted: provider_accounts.quota_exhausted, rate_limited: provider_accounts.rate_limited, disabled: provider_accounts.disabled, diff --git a/backend/crates/gateway-api/src/admin/observability/wire.rs b/backend/crates/gateway-api/src/admin/observability/wire.rs index 5997e1e5a..24a993887 100644 --- a/backend/crates/gateway-api/src/admin/observability/wire.rs +++ b/backend/crates/gateway-api/src/admin/observability/wire.rs @@ -460,6 +460,7 @@ pub struct DashboardAccountUsageView { pub struct DashboardPoolSummaryView { pub total: u64, pub normal: u64, + pub quota_paused: u64, pub quota_exhausted: u64, pub rate_limited: u64, pub disabled: u64, diff --git a/backend/crates/gateway-api/tests/admin/accounts/handlers.rs b/backend/crates/gateway-api/tests/admin/accounts/handlers.rs index 4afef432f..69e383688 100644 --- a/backend/crates/gateway-api/tests/admin/accounts/handlers.rs +++ b/backend/crates/gateway-api/tests/admin/accounts/handlers.rs @@ -16,6 +16,7 @@ async fn peer_refresh_uses_the_account_quota_endpoint_and_requires_admin() { fixture.auth.insert_session("valid-session"); *fixture.account.lock().unwrap() = Some(account_page_item( AccountStatusFacts { + quota_paused: false, enabled: true, credential_state: CredentialState::Ready, access_token_expires_at: None, @@ -73,6 +74,7 @@ async fn account_model_reads_and_refreshes_preserve_provider_observation_time() let observed_at: DateTime = "2026-09-12T08:00:00Z".parse().unwrap(); *fixture.account.lock().unwrap() = Some(account_page_item( AccountStatusFacts { + quota_paused: false, enabled: true, credential_state: CredentialState::Ready, access_token_expires_at: None, @@ -161,6 +163,7 @@ async fn account_proxy_binding_is_distinct_from_the_redacted_endpoint() { ] { let now = Utc::now(); let facts = AccountStatusFacts { + quota_paused: false, enabled: true, credential_state: CredentialState::Ready, access_token_expires_at: None, @@ -239,6 +242,7 @@ async fn account_cooldown_returns_an_instant_and_server_formatted_recovery() { let now = Utc::now(); let until = seconds.map(|seconds| now + Duration::seconds(seconds)); let facts = AccountStatusFacts { + quota_paused: false, enabled: true, credential_state: CredentialState::Ready, access_token_expires_at: None, @@ -323,6 +327,7 @@ async fn account_quota_refresh_time_uses_server_clock_and_deployment_timezone() let now = Utc::now(); *fixture.account.lock().unwrap() = Some(account_page_item( AccountStatusFacts { + quota_paused: false, enabled: true, credential_state: CredentialState::Ready, access_token_expires_at: None, @@ -356,6 +361,7 @@ async fn account_quota_refresh_time_uses_server_clock_and_deployment_timezone() ), ] { *fixture.provider_quota.lock().unwrap() = Some(ProviderQuota { + paused_windows: Vec::new(), upstream: None, plan_type: None, observed_at, @@ -406,6 +412,8 @@ fn account_page_item( AccountPageItem { protection_rules: Vec::new(), account: AccountRecord { + quota_paused: false, + quota_limits: Default::default(), auto_use_quota_credits: false, outbound_proxy_id: None, outbound_proxy_enabled: true, @@ -458,6 +466,7 @@ async fn account_usage_preserves_periods_cache_counts_and_missing_values() { fixture.auth.insert_session("valid-session"); let now = Utc::now(); let facts = AccountStatusFacts { + quota_paused: false, enabled: true, credential_state: CredentialState::Ready, access_token_expires_at: None, @@ -741,6 +750,7 @@ async fn concurrency_details_require_admin_validate_paging_and_report_lease_time fixture.auth.insert_session("valid-session"); *fixture.account.lock().unwrap() = Some(account_page_item( gateway_core::account::AccountStatusFacts { + quota_paused: false, enabled: true, credential_state: gateway_core::account::CredentialState::Ready, access_token_expires_at: None, diff --git a/backend/crates/gateway-api/tests/admin/errors.rs b/backend/crates/gateway-api/tests/admin/errors.rs index e09b629f9..f94be4ba1 100644 --- a/backend/crates/gateway-api/tests/admin/errors.rs +++ b/backend/crates/gateway-api/tests/admin/errors.rs @@ -563,6 +563,7 @@ mod provider { fn account(provider: &str) -> AccountPageItem { let now = Utc::now(); let facts = AccountStatusFacts { + quota_paused: false, enabled: true, credential_state: CredentialState::Ready, access_token_expires_at: None, @@ -578,6 +579,8 @@ mod provider { total_slots: None, }, account: AccountRecord { + quota_paused: false, + quota_limits: Default::default(), auto_use_quota_credits: false, outbound_proxy_id: None, outbound_proxy_enabled: true, diff --git a/backend/crates/gateway-api/tests/admin/mod.rs b/backend/crates/gateway-api/tests/admin/mod.rs index 52d5dc73d..738de559b 100644 --- a/backend/crates/gateway-api/tests/admin/mod.rs +++ b/backend/crates/gateway-api/tests/admin/mod.rs @@ -891,6 +891,7 @@ impl AccountGroupStore for MemoryAccountGroupStore { group_id: group_id(PRIMARY_GROUP_ID), account_id: "acct_group_ready".to_owned(), status: AccountStatusFacts { + quota_paused: false, enabled: true, credential_state: CredentialState::Ready, access_token_expires_at: None, @@ -906,6 +907,7 @@ impl AccountGroupStore for MemoryAccountGroupStore { group_id: group_id(PRIMARY_GROUP_ID), account_id: "acct_group_disabled".to_owned(), status: AccountStatusFacts { + quota_paused: false, enabled: false, credential_state: CredentialState::Ready, access_token_expires_at: None, @@ -1228,6 +1230,9 @@ impl AccountStore for UnusedStore { summary: gateway_admin::model::accounts::AccountSummary { total: 1, normal: u64::from(status == gateway_core::account::AccountStatus::Normal), + quota_paused: u64::from( + status == gateway_core::account::AccountStatus::QuotaPaused, + ), quota_exhausted: u64::from( status == gateway_core::account::AccountStatus::QuotaExhausted, ), @@ -1392,6 +1397,7 @@ impl AccountStore for UnusedStore { async fn batch_update_accounts( &self, _: BatchUpdateAccounts, + _: gateway_admin::model::accounts::PreparedQuotaPauses, _: &MutationContext, ) -> AdminStoreResult { Err(unavailable("account batch update")) diff --git a/backend/crates/gateway-api/tests/admin/observability/response.rs b/backend/crates/gateway-api/tests/admin/observability/response.rs index 3a68f06e8..f7821b09c 100644 --- a/backend/crates/gateway-api/tests/admin/observability/response.rs +++ b/backend/crates/gateway-api/tests/admin/observability/response.rs @@ -142,6 +142,7 @@ async fn dashboard_summary_should_include_quota_exhaustion_in_unavailable_headli provider_accounts: AccountPoolMetrics { total: 1002, normal: 943, + quota_paused: 0, quota_exhausted: 52, rate_limited: 0, disabled: 3, diff --git a/backend/crates/gateway-api/tests/openai/peer_link/mod.rs b/backend/crates/gateway-api/tests/openai/peer_link/mod.rs index 60a8c58df..6874d289f 100644 --- a/backend/crates/gateway-api/tests/openai/peer_link/mod.rs +++ b/backend/crates/gateway-api/tests/openai/peer_link/mod.rs @@ -81,6 +81,7 @@ async fn fixture(sharing: ClientPeerSharing, plaintext: &str) -> (AdminTestFixtu *fixture.client_key.lock().unwrap() = Some(key); let provider = ProviderKind::new("openai").unwrap(); let facts = AccountStatusFacts { + quota_paused: false, enabled: true, credential_state: CredentialState::Ready, access_token_expires_at: None, @@ -97,6 +98,8 @@ async fn fixture(sharing: ClientPeerSharing, plaintext: &str) -> (AdminTestFixtu }, projection: resolve_account_status(&facts, now.into()), account: AccountRecord { + quota_paused: false, + quota_limits: Default::default(), auto_use_quota_credits: false, id: "acct_private_sentinel".into(), provider_kind: provider, @@ -129,6 +132,7 @@ async fn fixture(sharing: ClientPeerSharing, plaintext: &str) -> (AdminTestFixtu }, }); *fixture.provider_quota.lock().unwrap() = Some(ProviderQuota { + paused_windows: Vec::new(), upstream: None, plan_type: Some("pro".into()), observed_at: Some(now), diff --git a/backend/crates/gateway-core/src/account/mod.rs b/backend/crates/gateway-core/src/account/mod.rs index 0e7e4a44b..761878920 100644 --- a/backend/crates/gateway-core/src/account/mod.rs +++ b/backend/crates/gateway-core/src/account/mod.rs @@ -13,6 +13,8 @@ pub use model_access::{ AccountModelAccess, AccountModelAccessMode, InvalidAccountModelAccess, MAX_ACCOUNT_ACCESS_MODELS, }; +mod quota_limits; +pub use quota_limits::{AccountQuotaLimits, QuotaMergeBase, QuotaPauseDecision}; mod proxy; pub use proxy::{InvalidOutboundProxy, OutboundProxy}; pub mod scope; diff --git a/backend/crates/gateway-core/src/account/model.rs b/backend/crates/gateway-core/src/account/model.rs index d91b31552..07c4469d2 100644 --- a/backend/crates/gateway-core/src/account/model.rs +++ b/backend/crates/gateway-core/src/account/model.rs @@ -557,10 +557,11 @@ impl QuotaState { } } -/// 对外唯一的五态账号状态 +/// 对外唯一的账号状态 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum AccountStatus { Normal, + QuotaPaused, QuotaExhausted, RateLimited, Disabled, @@ -572,6 +573,7 @@ impl AccountStatus { pub const fn as_str(self) -> &'static str { match self { Self::Normal => "normal", + Self::QuotaPaused => "quota_paused", Self::QuotaExhausted => "quota_exhausted", Self::RateLimited => "rate_limited", Self::Disabled => "disabled", @@ -583,6 +585,7 @@ impl AccountStatus { pub fn parse(value: &str) -> Option { match value { "normal" => Some(Self::Normal), + "quota_paused" => Some(Self::QuotaPaused), "quota_exhausted" => Some(Self::QuotaExhausted), "rate_limited" => Some(Self::RateLimited), "disabled" => Some(Self::Disabled), @@ -710,6 +713,7 @@ impl From for AccountCooldown { /// 唯一状态解析器的完整输入事实 #[derive(Debug, Clone, PartialEq, Eq)] pub struct AccountStatusFacts { + pub quota_paused: bool, pub enabled: bool, pub credential_state: CredentialState, pub access_token_expires_at: Option, @@ -766,6 +770,9 @@ pub fn resolve_account_status( cooldown: facts.cooldown, }; } + if facts.quota_paused { + return status_projection(AccountStatus::QuotaPaused); + } status_projection(AccountStatus::Normal) } @@ -821,6 +828,8 @@ pub struct ProviderAccount { enabled: bool, concurrency_limit: Option, weight: AccountWeight, + quota_limits: super::AccountQuotaLimits, + quota_paused: bool, auto_use_quota_credits: bool, model_access: super::AccountModelAccess, credential_state: CredentialState, @@ -860,6 +869,8 @@ impl ProviderAccount { enabled: true, concurrency_limit: None, weight: AccountWeight::DEFAULT, + quota_limits: super::AccountQuotaLimits::disabled(), + quota_paused: false, auto_use_quota_credits: false, model_access: super::AccountModelAccess::all(), credential_state: CredentialState::Unknown, @@ -874,6 +885,24 @@ impl ProviderAccount { } } + #[must_use] + pub fn with_quota_limits(mut self, limits: super::AccountQuotaLimits, paused: bool) -> Self { + // 只有限额账号需要在取得租约前检测额度窗口的并发更新 + self.quota_paused = paused; + self.quota_limits = limits; + self + } + + #[must_use] + pub const fn quota_limits(&self) -> &super::AccountQuotaLimits { + &self.quota_limits + } + + #[must_use] + pub const fn quota_paused(&self) -> bool { + self.quota_paused + } + #[must_use] pub const fn with_auto_use_quota_credits(mut self, enabled: bool) -> Self { self.auto_use_quota_credits = enabled; @@ -1101,6 +1130,7 @@ impl ProviderAccount { ) -> AccountStatusProjection { resolve_account_status( &AccountStatusFacts { + quota_paused: self.quota_paused, enabled: self.enabled, credential_state: self.credential_state, access_token_expires_at: self.access_token_expires_at, @@ -1430,6 +1460,8 @@ pub struct QuotaObservationVersion { /// Provider quota 的一次完整观察结果 #[derive(Clone, PartialEq)] pub struct QuotaObservation { + /// 本地阈值决策与观测一起写入,策略已变时拒绝旧结论 + pub quota_pause: Option, /// 网络查询可额外校验请求出口与启用状态,避免连接变化后的迟到写入 pub expected_connection: Option, pub account_id: ProviderAccountId, diff --git a/backend/crates/gateway-core/src/account/quota_limits.rs b/backend/crates/gateway-core/src/account/quota_limits.rs new file mode 100644 index 000000000..f623073e2 --- /dev/null +++ b/backend/crates/gateway-core/src/account/quota_limits.rs @@ -0,0 +1,68 @@ +//! 管理员按账号通用窗口设置的已用比例上限 + +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(try_from = "BTreeMap")] +pub struct AccountQuotaLimits(BTreeMap); + +impl AccountQuotaLimits { + #[must_use] + pub const fn disabled() -> Self { + Self(BTreeMap::new()) + } + + #[must_use] + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + #[must_use] + pub fn contains(&self, key: &str) -> bool { + self.0.contains_key(key) + } + + pub fn keys(&self) -> impl Iterator { + self.0.keys().map(String::as_str) + } + + #[must_use] + pub fn reached(&self, key: &str, used: Option) -> bool { + self.0 + .get(key) + .zip(used) + .is_some_and(|(&limit, used)| used >= f64::from(limit)) + } +} + +impl TryFrom> for AccountQuotaLimits { + type Error = &'static str; + + fn try_from(limits: BTreeMap) -> Result { + if limits.iter().any(|(key, limit)| { + key.is_empty() + || key.len() > 256 + || key.chars().any(char::is_control) + || !(1..=100).contains(limit) + }) { + return Err("额度窗口标识无效或上限不在 1~100 范围内"); + } + Ok(Self(limits)) + } +} + +/// 合并时读到的快照版本,时间为空表示当时尚无快照 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct QuotaMergeBase { + pub observed_at: Option, +} + +/// 此次判断依据的策略,以及是否有通用窗口触发暂停 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct QuotaPauseDecision { + /// 独立观测无需合并,依赖旧快照的判断必须随写入校验版本 + pub merge_base: Option, + pub limits: AccountQuotaLimits, + pub paused: bool, +} diff --git a/backend/crates/gateway-plugin/runtime/tests/generation/data.rs b/backend/crates/gateway-plugin/runtime/tests/generation/data.rs index fdb17ef51..1ef0cf8f3 100644 --- a/backend/crates/gateway-plugin/runtime/tests/generation/data.rs +++ b/backend/crates/gateway-plugin/runtime/tests/generation/data.rs @@ -32,6 +32,8 @@ struct Facts { fn account() -> AccountRecord { let at = "2026-01-01T00:00:00Z".parse().unwrap(); AccountRecord { + quota_paused: false, + quota_limits: Default::default(), auto_use_quota_credits: false, outbound_proxy_id: None, outbound_proxy_enabled: true, @@ -132,6 +134,7 @@ impl PluginAccountAccess for Facts { self.reads.fetch_add(1, Ordering::SeqCst); assert_eq!(account.as_str(), "acct_facts"); Ok(ProviderQuota { + paused_windows: Vec::new(), upstream: None, credits: Some(ProviderQuotaCredits { has_credits: true, diff --git a/backend/crates/gateway-store/src/postgres/account_groups.rs b/backend/crates/gateway-store/src/postgres/account_groups.rs index 9be510c6a..6adda74ef 100644 --- a/backend/crates/gateway-store/src/postgres/account_groups.rs +++ b/backend/crates/gateway-store/src/postgres/account_groups.rs @@ -242,7 +242,7 @@ impl AccountGroupStore for PgAccountGroupRepository { account.upstream_user_id, account.upstream_account_id, account.plan_type, account.authentication_kind, account.credential_revision, account.outbound_proxy_id, account.outbound_proxy_url, account.has_refresh_token, account.access_token_expires_at, - account.next_refresh_at, account.enabled, account.auto_use_quota_credits, account.concurrency_limit, + account.next_refresh_at, account.enabled, account.quota_limits, account.quota_paused, account.auto_use_quota_credits, account.concurrency_limit, account.quota_observed_at, account.weight, account.model_access_json, account.credential_state, account.quota_access_state, account.quota_evidence, account.quota_access_observed_at, account.quota_reset_at, account.last_error_reason, @@ -284,6 +284,7 @@ impl AccountGroupStore for PgAccountGroupRepository { group_id, account_id: account.id, status: AccountStatusFacts { + quota_paused: account.quota_paused, enabled: account.enabled, credential_state: account.credential_state, access_token_expires_at: account.access_token_expires_at.map(Into::into), diff --git a/backend/crates/gateway-store/src/postgres/observability/admin_adapter.rs b/backend/crates/gateway-store/src/postgres/observability/admin_adapter.rs index 42343a6c2..8181c7e18 100644 --- a/backend/crates/gateway-store/src/postgres/observability/admin_adapter.rs +++ b/backend/crates/gateway-store/src/postgres/observability/admin_adapter.rs @@ -41,7 +41,7 @@ impl PgObservabilityRepository { self } - /// 从账号事实和当前冷却一次性派生 Dashboard 五态;不在 SQL 中复制状态机 + /// 从账号事实和当前冷却一次性派生 Dashboard 状态;不在 SQL 中复制状态机 async fn account_status_snapshot( &self, observed_at: DateTime, @@ -69,6 +69,9 @@ impl PgObservabilityRepository { metrics.normal = metrics.normal.saturating_add(1); normal_accounts.push(account); } + gateway_core::account::AccountStatus::QuotaPaused => { + metrics.quota_paused = metrics.quota_paused.saturating_add(1); + } gateway_core::account::AccountStatus::QuotaExhausted => { metrics.quota_exhausted = metrics.quota_exhausted.saturating_add(1); } diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/admin_adapter.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/admin_adapter.rs index 908a92de2..22440b4d0 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/admin_adapter.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/admin_adapter.rs @@ -664,6 +664,8 @@ impl AccountStore for PgAdminAccountStore { .accounts .batch_update_provider_accounts_admin(BatchUpdateProviderAccountsAdmin { account_ids: vec![command.account_id.clone()], + pauses: Default::default(), + quota_limits: None, auto_use_quota_credits: None, name: command.name, notes: command.notes, @@ -726,6 +728,7 @@ impl AccountStore for PgAdminAccountStore { async fn batch_update_accounts( &self, command: BatchUpdateAccounts, + pauses: gateway_admin::model::accounts::PreparedQuotaPauses, context: &MutationContext, ) -> AdminStoreResult { let account_ids = command @@ -748,6 +751,7 @@ impl AccountStore for PgAdminAccountStore { }; let mut changed_fields = Vec::new(); for (changed, field) in [ + (command.quota_limits.is_some(), "quota_limits"), ( command.auto_use_quota_credits.is_some(), "auto_use_quota_credits", @@ -771,6 +775,8 @@ impl AccountStore for PgAdminAccountStore { .accounts .batch_update_provider_accounts_admin(BatchUpdateProviderAccountsAdmin { account_ids: command.account_ids, + pauses, + quota_limits: command.quota_limits, auto_use_quota_credits: command.auto_use_quota_credits, name: None, notes: None, diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/admin_queries.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/admin_queries.rs index 3f1a17e2e..a26c9e70f 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/admin_queries.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/admin_queries.rs @@ -57,12 +57,14 @@ pub(crate) async fn load_admin_account_page( or a.access_token_expires_at <= $2 then 'error' when a.quota_access_state = 'exhausted' then 'quota_exhausted' when a.id = any($1::text[]) then 'rate_limited' + when a.quota_paused then 'quota_paused' else 'normal' end as admin_status from provider_accounts a ), global_summary as ( select count(*)::bigint as summary_total, + count(*) filter (where admin_status = 'quota_paused')::bigint as summary_quota_paused, count(*) filter (where admin_status = 'normal')::bigint as summary_normal, count(*) filter (where admin_status = 'quota_exhausted')::bigint as summary_quota_exhausted, @@ -106,13 +108,13 @@ pub(crate) async fn load_admin_account_page( select coalesce(p.enabled, true) as outbound_proxy_enabled, coalesce(p.max_websocket_connections, 0) as outbound_proxy_max_websocket_connections, p.auto_location, p.detected_location_json, p.location_country, p.location_region, p.location_city, p.location_timezone, a.outbound_proxy_id, a.outbound_proxy_url, a.id, a.provider_kind, a.name, a.notes, a.email, a.upstream_user_id, a.upstream_account_id, a.plan_type, a.authentication_kind, a.credential_revision, a.has_refresh_token, a.access_token_expires_at, - a.next_refresh_at, a.enabled, a.auto_use_quota_credits, a.concurrency_limit, a.weight, a.model_access_json, + a.next_refresh_at, a.enabled, a.quota_limits, a.quota_paused, a.auto_use_quota_credits, a.concurrency_limit, a.weight, a.model_access_json, a.credential_state, a.quota_access_state, a.quota_evidence, - a.quota_access_observed_at, a.quota_reset_at, a.last_error_reason, + a.quota_observed_at, a.quota_access_observed_at, a.quota_reset_at, a.last_error_reason, a.last_error_message, a.credential_observed_at, a.created_at, a.updated_at, filtered_total.filtered_total, global_summary.summary_total, global_summary.summary_normal, - global_summary.summary_quota_exhausted, global_summary.summary_rate_limited, + global_summary.summary_quota_paused, global_summary.summary_quota_exhausted, global_summary.summary_rate_limited, global_summary.summary_disabled, global_summary.summary_error, settings.config_revision, settings.max_concurrent_per_account from filtered_total @@ -185,6 +187,7 @@ pub(crate) async fn load_admin_account_page( let summary = AccountSummary { total: unsigned_metadata(metadata, "summary_total")?, normal: unsigned_metadata(metadata, "summary_normal")?, + quota_paused: unsigned_metadata(metadata, "summary_quota_paused")?, quota_exhausted: unsigned_metadata(metadata, "summary_quota_exhausted")?, rate_limited: unsigned_metadata(metadata, "summary_rate_limited")?, disabled: unsigned_metadata(metadata, "summary_disabled")?, @@ -249,7 +252,7 @@ fn admin_account_order(sort: Option) -> String { let expression = match sort.field { AdminAccountSortField::Email => "a.email", AdminAccountSortField::Status => { - "case filtered.admin_status when 'normal' then 0 when 'rate_limited' then 1 when 'quota_exhausted' then 2 when 'error' then 3 else 4 end" + "case filtered.admin_status when 'normal' then 0 when 'rate_limited' then 1 when 'quota_exhausted' then 2 when 'quota_paused' then 3 when 'error' then 4 else 5 end" } AdminAccountSortField::PlanType => "a.plan_type", AdminAccountSortField::Usage => "usage.total_tokens", diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/core_adapter.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/core_adapter.rs index a6be45e8d..dd22faefc 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/core_adapter.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/core_adapter.rs @@ -203,7 +203,7 @@ impl ProviderAccountStore for PgProviderAccountRepository { set name = case when $14 then name else $3 end, email = case when $14 then email else $4 end, plan_type = case when $14 then plan_type else $5 end, - provider_quota_json = case when $14 then provider_quota_json else null end, + provider_quota_json = case when $14 then provider_quota_json else null end, quota_paused = case when $14 then quota_paused else false end, quota_observed_at = case when $14 then quota_observed_at else null end, provider_credentials_json = $6, credential_revision = credential_revision + 1, @@ -338,6 +338,7 @@ impl ProviderAccountStore for PgProviderAccountRepository { ) .ok_or_else(|| CoreStoreError::new(CoreStoreErrorKind::InvalidData))?; Ok(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: row.try_get("plan_type").map_err(|source| { CoreStoreError::caused_by(CoreStoreErrorKind::InvalidData, source) diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/mapping.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/mapping.rs index 932c0b389..2d182a621 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/mapping.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/mapping.rs @@ -10,6 +10,8 @@ pub(crate) fn admin_account_record( summary: ProviderAccountSummary, ) -> AdminStoreResult { Ok(AccountRecord { + quota_paused: summary.quota_paused, + quota_limits: summary.quota_limits, auto_use_quota_credits: summary.auto_use_quota_credits, outbound_proxy_id: summary.outbound_proxy_id, outbound_proxy_enabled: summary.outbound_proxy_enabled, diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/quota.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/quota.rs index b0ddbf9ba..51a6b8e71 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/quota.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/quota.rs @@ -25,13 +25,13 @@ pub(super) async fn write( ) -> Result { let quota = JsonObject::try_from_value( "provider_quota_json", - serde_json::Value::Object(observation.quota.into_inner()), + serde_json::Value::Object(observation.quota.clone().into_inner()), QUOTA_MAX_BYTES, ) .map_err(crate::core_store_error)?; let revision = Revision::new(observation.expected_revision.get()).map_err(crate::core_store_error)?; - let updated = if let Some(expected) = observation.expected_connection { + let updated = if let Some(ref expected) = observation.expected_connection { if expected.account_id != observation.account_id || expected.credential_revision != observation.expected_revision { @@ -57,34 +57,30 @@ pub(super) async fn write( .map_err(crate::core_store_error)? .summary, )?; - if !account.enabled() || UpstreamConnection::for_account(&account) != expected { + if !account.enabled() || UpstreamConnection::for_account(&account) != *expected { return Ok(QuotaWriteOutcome::Conflict); } let updated = super::repository::write_quota( &mut *transaction, observation.account_id.as_str(), revision, + &observation, quota, - observation.observed_at.into(), - observation.state, - observation.plan_type.as_deref(), ) .await .map_err(crate::core_store_error)?; transaction.commit().await.map_err(database_error)?; updated } else { - repository - .compare_and_swap_provider_quota( - observation.account_id.as_str(), - revision, - quota, - observation.observed_at.into(), - observation.state, - observation.plan_type.as_deref(), - ) - .await - .map_err(crate::core_store_error)? + super::repository::write_quota( + &repository.pool, + observation.account_id.as_str(), + revision, + &observation, + quota, + ) + .await + .map_err(crate::core_store_error)? }; Ok(if updated { QuotaWriteOutcome::Updated diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/repository.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/repository.rs index c2847e247..140770ca0 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/repository.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/repository.rs @@ -27,15 +27,6 @@ pub trait ProviderAccountRepository: Send + Sync { update: ProviderAccountStateUpdate, ) -> StoreResult; async fn set_provider_account_enabled(&self, id: &str, enabled: bool) -> StoreResult; - async fn compare_and_swap_provider_quota( - &self, - account_id: &str, - expected_revision: Revision, - quota: JsonObject, - observed_at: DateTime, - state: QuotaState, - plan_type: Option<&str>, - ) -> StoreResult; async fn touch_provider_quota_observation( &self, account_id: &str, @@ -117,7 +108,7 @@ impl PgProviderAccountRepository { let mut query = sqlx::QueryBuilder::::new( "select coalesce(proxy_enabled, true) as outbound_proxy_enabled, coalesce(max_websocket_connections, 0) as outbound_proxy_max_websocket_connections, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_id, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id, upstream_account_id, plan_type, authentication_kind, credential_revision, has_refresh_token, - access_token_expires_at, next_refresh_at, enabled, auto_use_quota_credits, concurrency_limit, weight, model_access_json, credential_state, + access_token_expires_at, next_refresh_at, enabled, quota_limits, quota_paused, auto_use_quota_credits, concurrency_limit, weight, model_access_json, credential_state, credential_observed_at, quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, quota_observed_at, last_error_reason, last_error_message, created_at, updated_at @@ -198,7 +189,7 @@ impl ProviderAccountRepository for PgProviderAccountRepository { let rows = sqlx::query( "select coalesce(proxy_enabled, true) as outbound_proxy_enabled, coalesce(max_websocket_connections, 0) as outbound_proxy_max_websocket_connections, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_id, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id, upstream_account_id, plan_type, authentication_kind, credential_revision, has_refresh_token, - access_token_expires_at, next_refresh_at, enabled, auto_use_quota_credits, concurrency_limit, weight, model_access_json, credential_state, + access_token_expires_at, next_refresh_at, enabled, quota_limits, quota_paused, auto_use_quota_credits, concurrency_limit, weight, model_access_json, credential_state, credential_observed_at, quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, quota_observed_at, last_error_reason, last_error_message, created_at, updated_at @@ -318,7 +309,7 @@ impl ProviderAccountRepository for PgProviderAccountRepository { } let next = sqlx::query_scalar::<_, i64>( "update provider_accounts - set provider_quota_json = case when $7 then provider_quota_json else null end, + set provider_quota_json = case when $7 then provider_quota_json else null end, quota_paused = case when $7 then quota_paused else false end, quota_observed_at = case when $7 then quota_observed_at else null end, provider_credentials_json = $3, credential_revision = credential_revision + 1, @@ -391,27 +382,6 @@ impl ProviderAccountRepository for PgProviderAccountRepository { Ok(result.rows_affected() == 1) } - async fn compare_and_swap_provider_quota( - &self, - account_id: &str, - expected_revision: Revision, - quota: JsonObject, - observed_at: DateTime, - state: QuotaState, - plan_type: Option<&str>, - ) -> StoreResult { - write_quota( - &self.pool, - account_id, - expected_revision, - quota, - observed_at, - state, - plan_type, - ) - .await - } - async fn apply_provider_quota_access( &self, account_id: &str, @@ -543,6 +513,22 @@ impl ProviderAccountAdminRepository for PgProviderAccountRepository { })?; let result = async { let revision = bump_config_revision_in_transaction(&mut transaction).await?; + if let Some(limits) = &command.quota_limits { + for id in &command.account_ids { + let pause = command.pauses.get(id); + if !limits.is_empty() && pause.is_none() { + return Err(invalid("缺少账号额度暂停结论")); + } + let updated = sqlx::query("update provider_accounts set quota_limits = $2, quota_paused = $3 + where id = $1 and ($4::bigint is null or (credential_revision = $4 and quota_observed_at is not distinct from $5))") + .bind(id).bind(sqlx::types::Json(limits)).bind(pause.is_some_and(|p| p.paused)) + .bind(pause.map(|p| to_i64(p.revision.get())).transpose()?).bind(pause.and_then(|p| p.observed_at)) + .execute(&mut *transaction).await.map_err(|source| postgres_unavailable("set account quota limits", source))?; + if updated.rows_affected() == 0 { + return Err(StoreError::Conflict { source: None, entity: ENTITY, id: id.clone(), kind: ConflictKind::StaleRevision }); + } + } + } update_provider_accounts_scheduling_in_transaction( &mut transaction, &command.account_ids, @@ -609,7 +595,7 @@ impl ProviderAccountAdminRepository for PgProviderAccountRepository { when access_token_expires_at <= now() then null else access_token_expires_at end, - provider_quota_json = null, + provider_quota_json = null, quota_paused = false, quota_observed_at = null, quota_access_state = 'allowed', quota_evidence = null, @@ -786,7 +772,7 @@ pub(crate) async fn upsert_provider_account_in_transaction( next_refresh_at = excluded.next_refresh_at, enabled = excluded.enabled, credential_state = excluded.credential_state, - provider_quota_json = null, + provider_quota_json = null, quota_paused = false, quota_access_state = 'unknown', quota_evidence = null, quota_access_observed_at = null, @@ -862,7 +848,7 @@ pub(crate) async fn rotate_provider_account_in_transaction( set name = case when $14 or $16 then name else $4 end, email = case when $14 then email else $5 end, plan_type = case when $14 then plan_type else $6 end, - provider_quota_json = case when $14 then provider_quota_json else null end, + provider_quota_json = case when $14 then provider_quota_json else null end, quota_paused = case when $14 then quota_paused else false end, quota_observed_at = case when $14 then quota_observed_at else null end, quota_access_state = case when $11 then 'unknown' else quota_access_state end, quota_evidence = case when $11 then null else quota_evidence end, @@ -951,8 +937,10 @@ pub(crate) async fn update_provider_accounts_scheduling_in_transaction( let updated = sqlx::query_scalar::<_, String>( "update provider_accounts set enabled = coalesce($2, enabled), concurrency_limit = case when $9 then $3 else concurrency_limit end, weight = coalesce($4, weight), updated_at = greatest(now(), updated_at), - provider_quota_json = case when $5 and outbound_proxy_url is distinct from $6 then null else provider_quota_json end, - quota_observed_at = case when $5 and outbound_proxy_url is distinct from $6 then null else quota_observed_at end, + (provider_quota_json, quota_observed_at) = ( + select provider_quota_json, quota_observed_at + where quota_paused or not $5 or outbound_proxy_url is not distinct from $6 + ), outbound_proxy_url = case when $5 then $6 else outbound_proxy_url end, outbound_proxy_id = case when $5 then $7 else outbound_proxy_id end, model_access_json = coalesce($8, model_access_json) @@ -1250,7 +1238,7 @@ impl PgProviderAccountRepository { let rows = sqlx::query( "select coalesce(proxy_enabled, true) as outbound_proxy_enabled, coalesce(max_websocket_connections, 0) as outbound_proxy_max_websocket_connections, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_id, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id, upstream_account_id, plan_type, authentication_kind, credential_revision, has_refresh_token, - access_token_expires_at, next_refresh_at, enabled, auto_use_quota_credits, concurrency_limit, weight, model_access_json, credential_state, + access_token_expires_at, next_refresh_at, enabled, quota_limits, quota_paused, auto_use_quota_credits, concurrency_limit, weight, model_access_json, credential_state, credential_observed_at, quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, quota_observed_at, last_error_reason, last_error_message, created_at, updated_at @@ -1312,20 +1300,22 @@ pub(super) async fn write_quota<'e, E>( executor: E, account_id: &str, expected_revision: Revision, + observation: &gateway_core::account::QuotaObservation, quota: JsonObject, - observed_at: DateTime, - state: QuotaState, - plan_type: Option<&str>, ) -> StoreResult where E: sqlx::Executor<'e, Database = Postgres>, { require_nonempty(ENTITY, "account_id", account_id)?; validate_object_size("provider_quota_json", "a, QUOTA_MAX_BYTES)?; + let state = observation.state; + let observed_at = DateTime::::from(observation.observed_at); let access_observed_at = state.observed_at().map(DateTime::::from); + let merge_base = observation.quota_pause.as_ref().and_then(|d| d.merge_base); let result = sqlx::query( "update provider_accounts set provider_quota_json = $3, quota_observed_at = $4, + quota_paused = $10, plan_type = coalesce($9, plan_type), quota_access_state = case when $7::timestamptz is not null @@ -1345,7 +1335,9 @@ where then $8 else quota_reset_at end, updated_at = greatest(now(), updated_at, $4, $7) where id = $1 and credential_revision = $2 - and (quota_observed_at is null or quota_observed_at <= $4)", + and (quota_observed_at is null or quota_observed_at <= $4) + and ($11::jsonb is null or (quota_limits = $11 and quota_observed_at is distinct from $4)) + and (not $12 or quota_observed_at is not distinct from $13)", ) .bind(account_id) .bind(to_i64(expected_revision.get())?) @@ -1355,7 +1347,16 @@ where .bind(state.evidence().map(QuotaEvidence::as_str)) .bind(access_observed_at) .bind(state.reset_at().map(DateTime::::from)) - .bind(plan_type) + .bind(observation.plan_type.as_deref()) + .bind(observation.quota_pause.as_ref().is_some_and(|d| d.paused)) + .bind( + observation + .quota_pause + .as_ref() + .map(|d| sqlx::types::Json(&d.limits)), + ) + .bind(merge_base.is_some()) + .bind(merge_base.and_then(|base| base.observed_at).map(DateTime::::from)) .execute(executor) .await .map_err(|source| postgres_unavailable("compare and swap provider quota", source))?; diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/rows.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/rows.rs index 1fdfc5240..2a7a6260f 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/rows.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/rows.rs @@ -51,6 +51,8 @@ pub(crate) fn parse_error_reason(value: Option) -> StoreResult, pub outbound_proxy_enabled: bool, @@ -250,6 +252,8 @@ impl fmt::Debug for RotateProviderAccount { #[derive(Debug, Clone)] pub struct BatchUpdateProviderAccountsAdmin { + pub pauses: gateway_admin::model::accounts::PreparedQuotaPauses, + pub quota_limits: Option, pub auto_use_quota_credits: Option, pub outbound_proxy: Option, pub account_ids: Vec, @@ -324,7 +328,7 @@ impl ProviderAccountStateUpdate { pub(crate) const ACCOUNT_SELECT: &str = "select coalesce(proxy_enabled, true) as outbound_proxy_enabled, coalesce(max_websocket_connections, 0) as outbound_proxy_max_websocket_connections, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_id, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id, upstream_account_id, plan_type, authentication_kind, provider_credentials_json, credential_revision, - has_refresh_token, access_token_expires_at, next_refresh_at, enabled, auto_use_quota_credits, concurrency_limit, weight, model_access_json, credential_state, + has_refresh_token, access_token_expires_at, next_refresh_at, enabled, quota_limits, quota_paused, auto_use_quota_credits, concurrency_limit, weight, model_access_json, credential_state, quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, last_error_reason, last_error_message, credential_observed_at, quota_observed_at, created_at, updated_at @@ -335,7 +339,7 @@ pub(crate) const ACCOUNT_SELECT: &str = "select coalesce(proxy_enabled, true) as pub(crate) const ACCOUNT_SELECT_BY_IDS: &str = "select coalesce(proxy_enabled, true) as outbound_proxy_enabled, coalesce(max_websocket_connections, 0) as outbound_proxy_max_websocket_connections, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_id, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id, upstream_account_id, plan_type, authentication_kind, provider_credentials_json, credential_revision, - has_refresh_token, access_token_expires_at, next_refresh_at, enabled, auto_use_quota_credits, concurrency_limit, weight, model_access_json, credential_state, + has_refresh_token, access_token_expires_at, next_refresh_at, enabled, quota_limits, quota_paused, auto_use_quota_credits, concurrency_limit, weight, model_access_json, credential_state, quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, last_error_reason, last_error_message, credential_observed_at, quota_observed_at, created_at, updated_at @@ -347,7 +351,7 @@ pub(crate) const ACCOUNT_SELECT_BY_IDS: &str = "select coalesce(proxy_enabled, t pub(crate) const REFRESH_CANDIDATES_SELECT: &str = "select coalesce(proxy_enabled, true) as outbound_proxy_enabled, coalesce(max_websocket_connections, 0) as outbound_proxy_max_websocket_connections, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_id, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id, upstream_account_id, plan_type, authentication_kind, provider_credentials_json, credential_revision, - has_refresh_token, access_token_expires_at, next_refresh_at, enabled, auto_use_quota_credits, concurrency_limit, weight, model_access_json, credential_state, + has_refresh_token, access_token_expires_at, next_refresh_at, enabled, quota_limits, quota_paused, auto_use_quota_credits, concurrency_limit, weight, model_access_json, credential_state, quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, last_error_reason, last_error_message, credential_observed_at, quota_observed_at, created_at, updated_at @@ -417,6 +421,7 @@ pub(crate) fn core_account_from_summary( ) .with_scheduling(summary.concurrency_limit, summary.weight) .with_model_access(summary.model_access) + .with_quota_limits(summary.quota_limits, summary.quota_paused) .with_auto_use_quota_credits(summary.auto_use_quota_credits) .with_outbound_proxy( summary @@ -473,6 +478,12 @@ pub(crate) fn account_summary_from_row( .and_then(AccountWeight::new) .ok_or_else(|| invalid("invalid weight"))?; Ok(ProviderAccountSummary { + quota_paused: status.quota_paused, + quota_limits: get::>( + &row, + "quota_limits", + )? + .0, auto_use_quota_credits: get(&row, "auto_use_quota_credits")?, outbound_proxy_id: get(&row, "outbound_proxy_id")?, outbound_proxy_enabled: get(&row, "outbound_proxy_enabled")?, @@ -581,6 +592,7 @@ pub(crate) fn account_status_facts_from_row( ) .ok_or_else(|| invalid("invalid persisted quota fact"))?; Ok(gateway_core::account::AccountStatusFacts { + quota_paused: get(row, "quota_paused")?, enabled: get(row, "enabled")?, credential_state: parse_credential_state(&credential_state)?, access_token_expires_at: get::>>(row, "access_token_expires_at")? diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/runtime.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/runtime.rs index 16fc4de03..d1915da50 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/runtime.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/runtime.rs @@ -20,6 +20,7 @@ pub(crate) fn account_status_projection( ) -> AccountStatusProjection { resolve_account_status( &AccountStatusFacts { + quota_paused: account.quota_paused, enabled: account.enabled, credential_state: account.credential_state, access_token_expires_at: account.access_token_expires_at.map(Into::into), @@ -73,7 +74,7 @@ pub(crate) async fn load_account_statuses<'e, E: sqlx::Executor<'e, Database = s ) -> crate::StoreResult> { use super::rows::{account_status_facts_from_row, get}; let rows = sqlx::query( - "select id, enabled, concurrency_limit, credential_revision, quota_observed_at, credential_state, access_token_expires_at, + "select id, enabled, quota_paused, concurrency_limit, credential_revision, quota_observed_at, credential_state, access_token_expires_at, quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, last_error_reason, last_error_message from provider_accounts", diff --git a/backend/crates/gateway-store/src/postgres/proxies.rs b/backend/crates/gateway-store/src/postgres/proxies.rs index e49491c10..3396a6347 100644 --- a/backend/crates/gateway-store/src/postgres/proxies.rs +++ b/backend/crates/gateway-store/src/postgres/proxies.rs @@ -424,7 +424,8 @@ impl ProxyStore for PgProxyRepository { // 在同一条更新中校验绑定,避免旧弹窗清除账号后来选择的其他代理 let updated = sqlx::query( "update provider_accounts - set outbound_proxy_id = null, outbound_proxy_url = null, provider_quota_json = null, quota_observed_at = null, + set outbound_proxy_id = null, outbound_proxy_url = null, + (provider_quota_json, quota_observed_at) = (select provider_quota_json, quota_observed_at where quota_paused), updated_at = greatest(now(), updated_at) where id = $1 and outbound_proxy_id = $2", ) @@ -801,7 +802,11 @@ impl ProxyStore for PgProxyRepository { .await .map_err(store_error)?; } - sqlx::query("update provider_accounts a set outbound_proxy_url = p.proxy_url, provider_quota_json = null, quota_observed_at = null, updated_at = case when a.outbound_proxy_url is distinct from p.proxy_url or a.provider_quota_json is not null then greatest(now(), a.updated_at) else a.updated_at end from outbound_proxies p where p.id = $1 and a.outbound_proxy_id = p.id and (a.outbound_proxy_url is distinct from p.proxy_url or $2)") + sqlx::query("update provider_accounts a set outbound_proxy_url = p.proxy_url, + (provider_quota_json, quota_observed_at) = (select a.provider_quota_json, a.quota_observed_at where a.quota_paused), + updated_at = case when a.outbound_proxy_url is distinct from p.proxy_url or a.provider_quota_json is not null + then greatest(now(), a.updated_at) else a.updated_at end + from outbound_proxies p where p.id = $1 and a.outbound_proxy_id = p.id and (a.outbound_proxy_url is distinct from p.proxy_url or $2)") .bind(&command.id).bind(enabled_changed).execute(&mut *transaction).await.map_err(|source| store_error(unavailable(source)))?; audit( &mut transaction, @@ -865,7 +870,8 @@ impl ProxyStore for PgProxyRepository { return Err(store_error(error)); } let account_ids: Vec = sqlx::query_scalar( - "update provider_accounts set outbound_proxy_id = null, outbound_proxy_url = null, provider_quota_json = null, quota_observed_at = null, + "update provider_accounts set outbound_proxy_id = null, outbound_proxy_url = null, + (provider_quota_json, quota_observed_at) = (select provider_quota_json, quota_observed_at where quota_paused), updated_at = greatest(now(), updated_at) where outbound_proxy_id = $1 returning id", ) .bind(id) diff --git a/backend/crates/gateway-store/tests/postgres/provider_accounts/mod.rs b/backend/crates/gateway-store/tests/postgres/provider_accounts/mod.rs index b43d439fe..718d89fde 100644 --- a/backend/crates/gateway-store/tests/postgres/provider_accounts/mod.rs +++ b/backend/crates/gateway-store/tests/postgres/provider_accounts/mod.rs @@ -207,6 +207,7 @@ async fn core_quota_batch_reads_only_observed_accounts_in_one_contract_call() { let observed_at = SystemTime::now(); let outcome = repository .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: ProviderAccountId::new(id).expect("account id"), @@ -284,6 +285,7 @@ async fn quota_observation_touch_preserves_quota_state_and_advances_account_upda assert_eq!( repository .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account_id.clone(), @@ -384,6 +386,7 @@ async fn delayed_provider_observations_cannot_overwrite_newer_state_or_quota() { .expect("older observation time"); let quota = |marker: &str, observed_at| QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: Some(if marker == "newer" { "pro" } else { "plus" }.to_owned()), account_id: account_id.clone(), @@ -490,6 +493,7 @@ async fn profile_changes_survive_inflight_background_and_manual_token_refresh() let config_revision = current_revision(&database.pool).await; let observed_at = SystemTime::now(); let observation = QuotaObservation { + quota_pause: None, expected_connection: None, account_id: id.clone(), expected_revision: original.revision(), @@ -555,6 +559,7 @@ async fn profile_changes_survive_inflight_background_and_manual_token_refresh() saved_quota ); let stale = QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: Some("free".to_owned()), ..observation @@ -595,6 +600,7 @@ async fn profile_changes_survive_inflight_background_and_manual_token_refresh() let observed_at = SystemTime::now(); repository .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, account_id: id.clone(), expected_revision: refreshed.revision(), @@ -829,6 +835,7 @@ async fn terminal_admin_list_filters_and_sorts_before_pagination_with_retained_u assert_eq!( usage_page.summary.total, usage_page.summary.normal + + usage_page.summary.quota_paused + usage_page.summary.quota_exhausted + usage_page.summary.rate_limited + usage_page.summary.disabled @@ -954,6 +961,34 @@ async fn terminal_admin_list_filters_and_sorts_before_pagination_with_retained_u assert_eq!(error_accounts.items.len(), 2); assert_eq!(error_accounts.items[0].account.id, "acct_beta"); assert_eq!(error_accounts.items[1].account.id, "acct_invalid"); + // 上游耗尽优先展示,不重复计入本地额度暂停 + sqlx::query("update provider_accounts set quota_paused = true where id in ('acct_alpha', 'acct_charlie')") + .execute(&database.pool).await.unwrap(); + let paused = store + .list_accounts( + AccountListQuery { + page: 1, + page_size: PageSize::new(1).unwrap(), + provider_kind: None, + group_filter: None, + search: None, + status: Some(AccountStatus::QuotaPaused), + sort: None, + }, + Default::default(), + ) + .await + .unwrap(); + assert_eq!(paused.total, 1); + assert_eq!(paused.items[0].account.id, "acct_alpha"); + assert_eq!( + paused.items[0].projection.status, + AccountStatus::QuotaPaused + ); + assert_eq!(paused.summary.quota_paused, 1); + assert_eq!(paused.summary.normal, 0); + assert_eq!(paused.summary.quota_exhausted, 2); + database.close().await; } @@ -1540,6 +1575,7 @@ async fn account_notes_round_trip_and_survive_import_and_scheduling_updates() { store .batch_update_accounts( BatchUpdateAccounts { + quota_limits: None, auto_use_quota_credits: None, account_ids: vec!["acct_notes".to_owned()], enabled: Some(false), @@ -1549,6 +1585,7 @@ async fn account_notes_round_trip_and_survive_import_and_scheduling_updates() { model_access: None, outbound_proxy: None, }, + Default::default(), &context, ) .await @@ -1711,6 +1748,7 @@ async fn account_enable_preserves_facts_and_explicit_recovery_clears_them() { let observed_at = SystemTime::now(); repository .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: ProviderAccountId::new("acct_recovery").expect("account ID"), @@ -1779,6 +1817,7 @@ async fn account_enable_preserves_facts_and_explicit_recovery_clears_them() { let enabled = store .batch_update_accounts( BatchUpdateAccounts { + quota_limits: None, auto_use_quota_credits: None, account_ids: vec!["acct_recovery".to_owned()], enabled: Some(true), @@ -1788,6 +1827,7 @@ async fn account_enable_preserves_facts_and_explicit_recovery_clears_them() { group_ids: None, outbound_proxy: None, }, + Default::default(), &MutationContext { actor: MutationActor::System, request_id: "request_account_enable".to_owned(), @@ -1904,6 +1944,7 @@ async fn terminal_batch_update_replaces_state_and_groups_once_or_rolls_back_ever let result = store .batch_update_accounts( BatchUpdateAccounts { + quota_limits: None, auto_use_quota_credits: None, model_access: Default::default(), outbound_proxy: None, @@ -1913,6 +1954,7 @@ async fn terminal_batch_update_replaces_state_and_groups_once_or_rolls_back_ever weight: Some(gateway_core::account::AccountWeight::new(25).expect("weight")), group_ids: Some(vec![AccountGroupId::new(GROUP_ID).expect("group ID")]), }, + Default::default(), &context, ) .await @@ -1942,6 +1984,7 @@ async fn terminal_batch_update_replaces_state_and_groups_once_or_rolls_back_ever store .batch_update_accounts( BatchUpdateAccounts { + quota_limits: None, auto_use_quota_credits: None, model_access: Default::default(), outbound_proxy: None, @@ -1954,6 +1997,7 @@ async fn terminal_batch_update_replaces_state_and_groups_once_or_rolls_back_ever .expect("missing group ID"), ]), }, + Default::default(), &context, ) .await @@ -2682,6 +2726,8 @@ async fn provider_account_admin_mutations_are_scoped_audited_and_atomic() { let revision = repository .batch_update_provider_accounts_admin(BatchUpdateProviderAccountsAdmin { + pauses: Default::default(), + quota_limits: None, auto_use_quota_credits: None, name: None, notes: None, @@ -3720,6 +3766,7 @@ async fn model_access_only_batch_update_preserves_other_settings_and_survives_re .expect("policy"); let store = admin_account_store(&database.pool); let command = BatchUpdateAccounts { + quota_limits: None, auto_use_quota_credits: None, account_ids: vec![input.id.clone()], enabled: None, @@ -3734,7 +3781,7 @@ async fn model_access_only_batch_update_preserves_other_settings_and_survives_re request_id: "request_model_access".to_owned(), }; store - .batch_update_accounts(command.clone(), &context) + .batch_update_accounts(command.clone(), Default::default(), &context) .await .expect("update policy only"); let loaded = repository @@ -3772,6 +3819,7 @@ async fn model_access_only_batch_update_preserves_other_settings_and_survives_re model_access: Some(AccountModelAccess::all()), ..command }, + Default::default(), &context, ) .await @@ -3864,6 +3912,7 @@ async fn disabling_quota_credits_revokes_credit_only_access_even_with_a_late_obs let set_policy = async |enabled| { let command = BatchUpdateAccounts { account_ids: vec![input.id.clone()], + quota_limits: None, auto_use_quota_credits: Some(enabled), enabled: None, concurrency_limit: None, @@ -3873,12 +3922,13 @@ async fn disabling_quota_credits_revokes_credit_only_access_even_with_a_late_obs outbound_proxy: None, }; admin - .batch_update_accounts(command, &context) + .batch_update_accounts(command, Default::default(), &context) .await .unwrap(); }; let observe = async |state: QuotaState| { let observation = QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: id.clone(), diff --git a/backend/crates/gateway-store/tests/postgres/provider_accounts/quota.rs b/backend/crates/gateway-store/tests/postgres/provider_accounts/quota.rs index 79db7c4b2..1699fc8f4 100644 --- a/backend/crates/gateway-store/tests/postgres/provider_accounts/quota.rs +++ b/backend/crates/gateway-store/tests/postgres/provider_accounts/quota.rs @@ -17,6 +17,7 @@ async fn connection_changes_reject_in_flight_quota_writes() { let id = ProviderAccountId::new("acct_peer").unwrap(); let current = repository.get_account(&id).await.unwrap().unwrap(); let observation = QuotaObservation { + quota_pause: None, expected_connection: Some(UpstreamConnection::for_account(¤t)), account_id: id.clone(), expected_revision: current.revision(), @@ -66,6 +67,7 @@ async fn large_quota_uses_shared_snapshot_and_cannot_reappear_after_revocation() let current = repository.get_account(&id).await.unwrap().unwrap(); let now = SystemTime::now(); let observation = QuotaObservation { + quota_pause: None, expected_connection: Some(UpstreamConnection::for_account(¤t)), account_id: id.clone(), expected_revision: current.revision(), @@ -133,6 +135,81 @@ async fn large_quota_uses_shared_snapshot_and_cannot_reappear_after_revocation() database.close().await; } +#[tokio::test] +async fn quota_merge_can_only_replace_the_snapshot_it_read() { + use gateway_core::account::{QuotaMergeBase, QuotaPauseDecision}; + let Some(database) = TestDatabase::create("quota_merge_base").await else { + return; + }; + let repository = PgProviderAccountRepository::new(database.pool.clone()); + let id = ProviderAccountId::new("acct_merge").unwrap(); + repository + .insert_provider_account(account(id.as_str(), "fixture")) + .await + .unwrap(); + let limits = json!({"codex:18000s": 95}); + sqlx::query("update provider_accounts set quota_limits = $2 where id = $1") + .bind(id.as_str()) + .bind(&limits) + .execute(&database.pool) + .await + .unwrap(); + let limits: gateway_core::account::AccountQuotaLimits = serde_json::from_value(limits).unwrap(); + let start = SystemTime::UNIX_EPOCH + Duration::from_secs(1_800_000_000); + let later = start + Duration::from_secs(1); + let observed = |base, observed_at, paused| QuotaObservation { + quota_pause: Some(QuotaPauseDecision { + limits: limits.clone(), + paused, + merge_base: Some(QuotaMergeBase { observed_at: base }), + }), + expected_connection: None, + account_id: id.clone(), + expected_revision: CredentialRevision::new(1).unwrap(), + quota: OpaqueProviderData::new(Default::default()), + observed_at, + plan_type: None, + state: QuotaState::unknown(), + }; + let write = |base, at, paused| repository.compare_and_swap_quota(observed(base, at, paused)); + assert_eq!( + write(None, start, true).await.unwrap(), + QuotaWriteOutcome::Updated + ); + for (base, at) in [ + (None, later), + (Some(start - Duration::from_secs(1)), later), + // PostgreSQL 时间精度为微秒,同一版本不能代表两份不同的快照 + (Some(start), start + Duration::from_nanos(1)), + ] { + assert_eq!( + write(base, at, false).await.unwrap(), + QuotaWriteOutcome::Conflict + ); + } + assert!( + repository + .get_account(&id) + .await + .unwrap() + .unwrap() + .quota_paused() + ); + assert_eq!( + write(Some(start), later, false).await.unwrap(), + QuotaWriteOutcome::Updated + ); + assert!( + !repository + .get_account(&id) + .await + .unwrap() + .unwrap() + .quota_paused() + ); + database.close().await; +} + #[tokio::test] async fn snapshot_commit_preserves_newer_quota_failure() { let Some(database) = TestDatabase::create("quota_connection_evidence").await else { @@ -159,6 +236,7 @@ async fn snapshot_commit_preserves_newer_quota_failure() { .await .unwrap(); let observation = QuotaObservation { + quota_pause: None, expected_connection: Some(UpstreamConnection::for_account(¤t)), account_id: id.clone(), expected_revision: current.revision(), @@ -227,6 +305,7 @@ async fn managed_proxy_changes_clear_snapshots_and_reject_old_connections() { for change in ["url", "disabled"] { let current = repository.get_account(&id).await.unwrap().unwrap(); let observation = QuotaObservation { + quota_pause: None, expected_connection: Some(UpstreamConnection::for_account(¤t)), account_id: id.clone(), expected_revision: current.revision(), @@ -294,6 +373,7 @@ async fn managed_proxy_changes_clear_snapshots_and_reject_old_connections() { // 模拟代理更新持有账号锁,额度查询已经开始但必须等待提交的交错 let current = repository.get_account(&id).await.unwrap().unwrap(); let observation = QuotaObservation { + quota_pause: None, expected_connection: Some(UpstreamConnection::for_account(¤t)), account_id: id.clone(), expected_revision: current.revision(), diff --git a/backend/crates/gateway-store/tests/postgres/provider_accounts/timestamps.rs b/backend/crates/gateway-store/tests/postgres/provider_accounts/timestamps.rs index 65e3f74df..0b03fc704 100644 --- a/backend/crates/gateway-store/tests/postgres/provider_accounts/timestamps.rs +++ b/backend/crates/gateway-store/tests/postgres/provider_accounts/timestamps.rs @@ -21,6 +21,7 @@ async fn cross_kind_observations_preserve_time_bounds_and_stale_observation_fenc let revision = CredentialRevision::new(1).expect("revision"); let quota_at = SystemTime::from(anchor - TimeDelta::milliseconds(400)); let observation = QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account_id.clone(), diff --git a/backend/crates/gateway-store/tests/postgres/proxies.rs b/backend/crates/gateway-store/tests/postgres/proxies.rs index 404895d7b..85059cbd4 100644 --- a/backend/crates/gateway-store/tests/postgres/proxies.rs +++ b/backend/crates/gateway-store/tests/postgres/proxies.rs @@ -355,6 +355,7 @@ async fn disabled_proxy_projects_direct_while_preserving_bindings_and_credential let error = admin .batch_update_accounts( BatchUpdateAccounts { + quota_limits: None, auto_use_quota_credits: None, account_ids: vec![ "acct_enabled_openai".to_owned(), @@ -367,6 +368,7 @@ async fn disabled_proxy_projects_direct_while_preserving_bindings_and_credential group_ids: None, outbound_proxy: Some(AccountProxySelection::Saved(saved.id.clone())), }, + Default::default(), &context(), ) .await @@ -409,6 +411,22 @@ fn update(account_id: &str, selection: AccountProxySelection) -> UpdateAccount { } } +async fn seed_paused_quota(database: &TestDatabase, id: &str) { + let window = serde_json::json!({ + "rate_limit": {"primary_window": {"limit_window_seconds": 18000, "used_percent": 99}} + }); + sqlx::query( + "update provider_accounts set quota_limits = $2, quota_paused = true, + provider_quota_json = $3, quota_observed_at = now(), updated_at = now() where id = $1", + ) + .bind(id) + .bind(serde_json::json!({"codex:18000s": 99})) + .bind(window) + .execute(&database.pool) + .await + .unwrap(); +} + #[tokio::test] async fn proxy_account_removal_preserves_settings_and_rejects_changed_bindings() { let Some(database) = TestDatabase::create("proxy_account_remove").await else { @@ -455,6 +473,7 @@ async fn proxy_account_removal_preserves_settings_and_rejects_changed_bindings() .execute(&database.pool) .await .unwrap(); + seed_paused_quota(&database, "acct_remove").await; let account_id = ProviderAccountId::new("acct_remove").unwrap(); let snapshot = "select to_jsonb(a) - 'updated_at' - 'outbound_proxy_id' - 'outbound_proxy_url' from provider_accounts a where id = 'acct_remove'"; @@ -995,6 +1014,22 @@ async fn managed_proxies_persist_bind_update_all_accounts_and_protect_stale_test .await .is_err() ); + seed_paused_quota(&database, "acct_one").await; + let paused_evidence = || async { + use gateway_core::account::ProviderAccountStore; + let id = ProviderAccountId::new("acct_one").unwrap(); + assert!( + accounts + .get_account(&id) + .await + .unwrap() + .unwrap() + .quota_paused() + ); + let observation = accounts.get_quotas(&[id]).await.unwrap().pop().unwrap(); + (observation.observed_at, observation.quota) + }; + let original_evidence = paused_evidence().await; let selection = AccountProxySelection::Saved(created.id.clone()); admin .update_account(update("acct_one", selection.clone()), &context) @@ -1004,6 +1039,7 @@ async fn managed_proxies_persist_bind_update_all_accounts_and_protect_stale_test sqlx::query_as::<_, (String, Option, Option, i64)>("select id, outbound_proxy_id, outbound_proxy_url, credential_revision from provider_accounts order by id") .fetch_all(&database.pool).await.unwrap() }; + assert_eq!(paused_evidence().await, original_evidence); let untested = read().await; assert_eq!(untested[0].1.as_deref(), Some(created.id.as_str())); assert_eq!(untested[0].2.as_deref(), Some(old_proxy.expose_url())); @@ -1086,6 +1122,7 @@ async fn managed_proxies_persist_bind_update_all_accounts_and_protect_stale_test .record; assert!(edited.last_test.is_none()); assert!(edited.last_test_at.is_none()); + assert_eq!(paused_evidence().await, original_evidence); assert!( read() .await @@ -1144,6 +1181,7 @@ async fn managed_proxies_persist_bind_update_all_accounts_and_protect_stale_test .all(|row| row.1.is_none() && row.2.is_none() && row.3 == 1) ); assert!(store.get(&created.id).await.is_err()); + assert_eq!(paused_evidence().await, original_evidence); let audits: Vec = sqlx::query_scalar("select to_jsonb(a) from admin_audit_events a") .fetch_all(&database.pool) @@ -1181,6 +1219,7 @@ async fn legacy_urls_join_one_catalog_entry_and_invalid_batch_rolls_back() { admin .batch_update_accounts( BatchUpdateAccounts { + quota_limits: None, auto_use_quota_credits: None, model_access: Default::default(), account_ids: vec!["acct_one".to_owned(), "acct_missing".to_owned()], @@ -1192,6 +1231,7 @@ async fn legacy_urls_join_one_catalog_entry_and_invalid_batch_rolls_back() { OutboundProxy::parse("http://127.0.0.1:9090").unwrap() )), }, + Default::default(), &context() ) .await diff --git a/backend/crates/providers/openai/src/admin/mod.rs b/backend/crates/providers/openai/src/admin/mod.rs index 05f8e5af3..edee20a5b 100644 --- a/backend/crates/providers/openai/src/admin/mod.rs +++ b/backend/crates/providers/openai/src/admin/mod.rs @@ -205,6 +205,7 @@ impl ProviderAdmin for OpenAiAdminProvider { ) -> gateway_admin::model::accounts::ProviderAccountCapabilities { let oauth = authentication_kind == crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH; gateway_admin::model::accounts::ProviderAccountCapabilities { + quota_limits_supported: oauth, quota_credits: oauth, quota: oauth, quota_refresh: oauth, @@ -738,7 +739,7 @@ impl ProviderAdmin for OpenAiAdminProvider { if refresh { return Err(provider_admin_error(ProviderAdminErrorKind::Unsupported)); } - return Ok(project_quota(None, false)); + return Ok(empty_quota()); } let snapshot = if refresh { let snapshot = Some( @@ -755,7 +756,11 @@ impl ProviderAdmin for OpenAiAdminProvider { .await .map_err(map_quota_error)? }; - Ok(project_quota(snapshot, account.quota().is_exhausted())) + Ok(project_quota( + snapshot, + account.quota().is_exhausted(), + account.quota_limits(), + )) } async fn read_quotas( @@ -1223,6 +1228,7 @@ fn account_matches_record(account: &ProviderAccount, record: &AccountRecord) -> fn empty_quota() -> ProviderQuota { ProviderQuota { + paused_windows: Vec::new(), upstream: None, credits: None, plan_type: None, @@ -1237,15 +1243,19 @@ fn empty_quota() -> ProviderQuota { fn project_quota( snapshot: Option, limit_reached: bool, + limits: &gateway_core::account::AccountQuotaLimits, ) -> ProviderQuota { let mut quota = snapshot - .map(project_quota_snapshot) + .map(|s| project_quota_snapshot(s, limits)) .unwrap_or_else(empty_quota); quota.limit_reached = limit_reached; quota } -fn project_quota_snapshot(snapshot: CodexAccountQuotaSnapshot) -> ProviderQuota { +fn project_quota_snapshot( + snapshot: CodexAccountQuotaSnapshot, + limits: &gateway_core::account::AccountQuotaLimits, +) -> ProviderQuota { let mut provider_data = Map::new(); provider_data.insert( "remaining_percent".to_owned(), @@ -1287,6 +1297,11 @@ fn project_quota_snapshot(snapshot: CodexAccountQuotaSnapshot) -> ProviderQuota // 在窗口全部过期后继续维持限流 let limit_reached = quota_windows_limit_reached(&windows); ProviderQuota { + paused_windows: snapshot + .limit_usage() + .filter(|(key, used)| limits.reached(key, Some(*used))) + .map(|(key, _)| key.to_owned()) + .collect(), upstream: None, plan_type: snapshot.plan_type().map(str::to_owned), observed_at: Some(DateTime::::from(snapshot.observed_at())), diff --git a/backend/crates/providers/openai/src/admin/quota.rs b/backend/crates/providers/openai/src/admin/quota.rs index a43b8f0a0..2e0ed8375 100644 --- a/backend/crates/providers/openai/src/admin/quota.rs +++ b/backend/crates/providers/openai/src/admin/quota.rs @@ -52,7 +52,7 @@ impl OpenAiAdminProvider { let snapshot = if request.account.authentication_kind == crate::credential::CODEX_AUTHENTICATION_KIND_API_KEY { - return Ok(project_quota(None, false)); + return Ok(empty_quota()); } else { observations .as_ref() @@ -68,6 +68,7 @@ impl OpenAiAdminProvider { Ok(project_quota( snapshot, request.account.quota.is_exhausted(), + &request.account.quota_limits, )) }) .collect() diff --git a/backend/crates/providers/openai/src/credential/quota/mod.rs b/backend/crates/providers/openai/src/credential/quota/mod.rs index ea3afbbfe..673ebee2f 100644 --- a/backend/crates/providers/openai/src/credential/quota/mod.rs +++ b/backend/crates/providers/openai/src/credential/quota/mod.rs @@ -31,8 +31,8 @@ use futures::StreamExt as _; use gateway_core::account::{ AccountErrorReason, AccountQuotaSignals, CredentialRevision, CredentialState, OpaqueProviderData, ProviderAccount, ProviderAccountId, ProviderAccountStore, - QuotaAccessChange, QuotaAccessState, QuotaEvidence, QuotaObservation, QuotaObservationTouch, - QuotaState, QuotaWriteOutcome, + QuotaAccessChange, QuotaAccessState, QuotaEvidence, QuotaMergeBase, QuotaObservation, + QuotaObservationTouch, QuotaState, QuotaWriteOutcome, }; use gateway_core::provider_ports::{ ProviderCooldown, ProviderCooldownPort, ProviderRuntimePolicyPort, @@ -68,6 +68,9 @@ use snapshot::{ scheduling_signals_from_snapshot, }; +// 同一份上游观测只重做本地合并,高并发时不无限争抢写入 +const QUOTA_MERGE_ATTEMPTS: usize = 3; +const LIMIT_EVIDENCE_FIELD: &str = "_cpr_quota_limit_evidence"; const DEFAULT_RATE_LIMIT_COOLDOWN: Duration = Duration::from_secs(60); pub(crate) const QUOTA_SCHEDULING_TTL: Duration = Duration::from_secs(10 * 60); const QUOTA_HYDRATION_FAILURE_TTL: Duration = Duration::from_secs(5); diff --git a/backend/crates/providers/openai/src/credential/quota/passive.rs b/backend/crates/providers/openai/src/credential/quota/passive.rs index 1d58e8240..f68443fdf 100644 --- a/backend/crates/providers/openai/src/credential/quota/passive.rs +++ b/backend/crates/providers/openai/src/credential/quota/passive.rs @@ -33,19 +33,6 @@ impl CodexCredentialQuotaService { .values() .any(|details| passive_rate_limit_snapshot(details).is_some()) }); - let existing = self - .store - .get_quotas(std::slice::from_ref(account.id())) - .await? - .into_iter() - .find(|observation| { - observation.account_id == *account.id() - && observation.expected_revision == account.revision() - }); - let existing_state = existing.as_ref().map(|observation| observation.state); - let existing = existing - .map(|observation| observation.quota.into_inner()) - .unwrap_or_default(); // 只用本次响应明确携带的套餐更新账号,不能把合并前的旧快照重新当作新证据 let observed_plan = rate_limits .iter() @@ -56,65 +43,97 @@ impl CodexCredentialQuotaService { }) }) .next(); - let plan_type = observed_account_plan(account.plan_type(), observed_plan); - if !has_quota_facts && existing_state.is_none() { - return Ok(false); - } - let prior = existing_state.unwrap_or_else(|| account.quota()); - let (quota, updated_default) = merge_passive_quota(existing, rate_limits); + // 重读发生冲突的快照时仍用响应到达时间,不能把迟到的用量当成新证据 let observed_at = SystemTime::now(); - let snapshot = parse_account_quota_snapshot( - account.id().clone(), - account.revision(), - observed_at, - &Value::Object(quota.clone()), - )?; - let credit_access = prior.evidence() == Some(QuotaEvidence::CreditsAvailable); - let fresh_credits = rate_limits.iter().any(|limits| limits.credits.is_some()); - // 具名桶和元数据不改变套餐结论;点数不能再用时,仍须撤销原先仅凭点数的放行 - let subscription = if !updated_default - || (snapshot.quota().access() == QuotaAccessState::Unknown - && (credit_access || prior.is_exhausted())) - { - if credit_access { - QuotaState::exhausted( - QuotaEvidence::AccountLimitReached, - observed_at, - prior.reset_at(), - ) - } else { - prior + for _ in 0..QUOTA_MERGE_ATTEMPTS { + let existing = self + .store + .get_quotas(std::slice::from_ref(account.id())) + .await? + .into_iter() + .find(|observation| { + observation.account_id == *account.id() + && observation.expected_revision == account.revision() + }); + let merge_base = QuotaMergeBase { + observed_at: existing.as_ref().map(|obs| obs.observed_at), + }; + if merge_base.observed_at.is_some_and(|at| at >= observed_at) { + return Ok(false); } - } else if snapshot.quota().is_exhausted() { - snapshot.quota() - } else { - QuotaState::allowed(observed_at) - }; - // 套餐刚耗尽时不能拿合并快照里的旧余额作为首次放行依据 - let state = snapshot.access_with_credits( - subscription, - account.auto_use_quota_credits() - && (credit_access || (updated_default && fresh_credits)), - ); - let outcome = self - .store - .compare_and_swap_quota(QuotaObservation { - expected_connection: None, - plan_type, - account_id: account.id().clone(), - expected_revision: account.revision(), - quota: OpaqueProviderData::new(quota), + let previous = if account.quota_limits().is_empty() { + None + } else { + existing.as_ref().and_then(quota_snapshot_from_observation) + }; + let existing_state = existing.as_ref().map(|observation| observation.state); + let existing = existing + .map(|observation| observation.quota.into_inner()) + .unwrap_or_default(); + let plan_type = observed_account_plan(account.plan_type(), observed_plan); + if !has_quota_facts && existing_state.is_none() { + return Ok(false); + } + let prior = existing_state.unwrap_or_else(|| account.quota()); + let (mut quota, updated_default) = merge_passive_quota(existing, rate_limits); + let mut snapshot = parse_account_quota_snapshot( + account.id().clone(), + account.revision(), observed_at, - state, - }) - .await?; - if outcome == QuotaWriteOutcome::Conflict { - return Ok(false); + &Value::Object(quota.clone()), + )?; + snapshot.retain_limit_evidence(account.quota_limits(), previous.as_ref(), &mut quota); + let credit_access = prior.evidence() == Some(QuotaEvidence::CreditsAvailable); + let fresh_credits = rate_limits.iter().any(|limits| limits.credits.is_some()); + // 具名桶和元数据不改变套餐结论;点数不能再用时,仍须撤销原先仅凭点数的放行 + let subscription = if !updated_default + || (snapshot.quota().access() == QuotaAccessState::Unknown + && (credit_access || prior.is_exhausted())) + { + if credit_access { + QuotaState::exhausted( + QuotaEvidence::AccountLimitReached, + observed_at, + prior.reset_at(), + ) + } else { + prior + } + } else if snapshot.quota().is_exhausted() { + snapshot.quota() + } else { + QuotaState::allowed(observed_at) + }; + // 套餐刚耗尽时不能拿合并快照里的旧余额作为首次放行依据 + let state = snapshot.access_with_credits( + subscription, + account.auto_use_quota_credits() + && (credit_access || (updated_default && fresh_credits)), + ); + let outcome = self + .store + .compare_and_swap_quota(QuotaObservation { + quota_pause: Some( + snapshot.pause_decision(account.quota_limits(), Some(merge_base)), + ), + expected_connection: None, + plan_type, + account_id: account.id().clone(), + expected_revision: account.revision(), + quota: OpaqueProviderData::new(quota), + observed_at, + state, + }) + .await?; + if outcome == QuotaWriteOutcome::Conflict { + continue; + } + if has_quota_facts { + self.scheduling.observe(&snapshot); + } + return Ok(true); } - if has_quota_facts { - self.scheduling.observe(&snapshot); - } - Ok(true) + Ok(false) } } diff --git a/backend/crates/providers/openai/src/credential/quota/scheduling.rs b/backend/crates/providers/openai/src/credential/quota/scheduling.rs index 2651242f3..484a71474 100644 --- a/backend/crates/providers/openai/src/credential/quota/scheduling.rs +++ b/backend/crates/providers/openai/src/credential/quota/scheduling.rs @@ -345,6 +345,21 @@ fn quota_refresh_candidate( } // 正常账号首次进入周期候选也要等待宽限期,不能由“无刷新历史”绕过 let snapshot = snapshot?; + if account.quota_paused() { + let reset_at = snapshot + .windows() + .iter() + .filter(|window| { + window.is_account_wide() + && account + .quota_limits() + .reached(window.key(), window.used_percent()) + }) + .filter_map(CodexQuotaWindow::reset_at) + .map(SystemTime::from) + .min(); + return Some((account, reset_at)); + } let expired_window_reset = snapshot .windows() .iter() diff --git a/backend/crates/providers/openai/src/credential/quota/service.rs b/backend/crates/providers/openai/src/credential/quota/service.rs index 0ef46f329..650554d91 100644 --- a/backend/crates/providers/openai/src/credential/quota/service.rs +++ b/backend/crates/providers/openai/src/credential/quota/service.rs @@ -211,10 +211,24 @@ impl CodexCredentialQuotaService { Ok(FetchedCodexQuota { account, value }) => { // 单账号解析或落库失败只影响该账号;其余账号继续同步 match self - .apply_fetched_quota(&account, &value, observed_at, &mut summary) + .persist_fetched_quota( + &account, + &value, + observed_at, + QuotaRefreshAuthority::ObserveAccess, + ) .await { - Ok(()) => { + Ok(snapshot) => { + if snapshot.quota().is_exhausted() { + summary.exhausted += 1; + } else { + summary.updated += 1; + } + pending_initial.remove(account.id()); + } + Err(CodexCredentialQuotaError::RevisionConflict) => { + summary.stale += 1; pending_initial.remove(account.id()); } Err(error) => { @@ -276,65 +290,6 @@ impl CodexCredentialQuotaService { &self.runtime_policy } - /// 解析并 revision-fenced 落库单账号的 Provider quota JSON - async fn apply_fetched_quota( - &self, - account: &ProviderAccount, - value: &Value, - observed_at: SystemTime, - summary: &mut CodexQuotaSyncSummary, - ) -> Result<(), CodexCredentialQuotaError> { - let mut object = normalize_quota_window_placeholders( - value - .as_object() - .cloned() - .ok_or(CodexCredentialQuotaError::InvalidCredentialData)?, - ); - object.remove(RECOVERY_FIELD); - let mut snapshot = parse_account_quota_snapshot( - account.id().clone(), - account.revision(), - observed_at, - &Value::Object(object.clone()), - )?; - let previous = if account.quota().is_exhausted() { - self.read_snapshot_for(account).await? - } else { - None - }; - let state = reconcile_refresh( - account.quota(), - account.auto_use_quota_credits(), - &mut snapshot, - previous.as_ref(), - &mut object, - )?; - let snapshot = snapshot.with_quota_state(state); - let outcome = self - .store - .compare_and_swap_quota(QuotaObservation { - expected_connection: None, - plan_type: observed_account_plan(account.plan_type(), snapshot.plan_type()), - account_id: account.id().clone(), - expected_revision: account.revision(), - quota: OpaqueProviderData::new(object), - observed_at, - state, - }) - .await?; - if outcome == QuotaWriteOutcome::Conflict { - summary.stale += 1; - return Ok(()); - } - self.scheduling.observe(&snapshot); - if snapshot.quota().is_exhausted() { - summary.exhausted += 1; - } else { - summary.updated += 1; - } - Ok(()) - } - /// 真实 429 的单一事实入口:写入 Redis 临时限流冷却(`until = now + retry_after`) /// 凭据与额度主窗口(额度重置时间)都不改变——临时限流是独立维度, /// 到期由 Redis key 过期自动解除,不污染配额耗尽状态 @@ -379,20 +334,32 @@ impl CodexCredentialQuotaService { &self, account: &ProviderAccount, ) -> Result, CodexCredentialQuotaError> { + Ok(self.read_snapshot_with_base(account).await?.1) + } + + async fn read_snapshot_with_base( + &self, + account: &ProviderAccount, + ) -> Result<(QuotaMergeBase, Option), CodexCredentialQuotaError> + { if account.provider().as_str() != "openai" { return Err(CodexCredentialQuotaError::NotFound); } let account_id = account.id(); - let Some(observation) = self + let observation = self .store .get_quotas(std::slice::from_ref(account_id)) .await? .into_iter() - .next() - else { - return Ok(None); + .next(); + let base = QuotaMergeBase { + observed_at: observation.as_ref().map(|obs| obs.observed_at), }; - self.project_observation(account_id, account.revision(), &observation) + let snapshot = match observation { + Some(obs) => self.project_observation(account_id, account.revision(), &obs)?, + None => None, + }; + Ok((base, snapshot)) } /// 单账号与目录批量读取共用 revision 校验、窗口解释及调度信号更新 @@ -485,81 +452,106 @@ impl CodexCredentialQuotaService { }); } }; - let mut object = normalize_quota_window_placeholders( - value - .as_object() - .cloned() - .ok_or(CodexCredentialQuotaError::InvalidCredentialData)?, - ); - object.remove(RECOVERY_FIELD); - let mut snapshot = parse_account_quota_snapshot( - account.id().clone(), - account.revision(), - observed_at, - &Value::Object(object.clone()), - )?; - let previous = if account.quota().is_exhausted() { - self.read_snapshot_for(&account).await? - } else { - None - }; - // 失败后回读只允许明确可用的点数恢复访问,套餐 allowed 仍可能滞后 - let observe_access = matches!(authority, QuotaRefreshAuthority::ObserveAccess) - || (account.auto_use_quota_credits() && snapshot.credits_usable()); - if account.quota().is_exhausted() && !observe_access { + self.persist_fetched_quota(&account, &value, observed_at, authority) + .await + } + + async fn persist_fetched_quota( + &self, + account: &ProviderAccount, + value: &Value, + observed_at: SystemTime, + authority: QuotaRefreshAuthority, + ) -> Result { + for _ in 0..QUOTA_MERGE_ATTEMPTS { + let mut object = normalize_quota_window_placeholders( + value + .as_object() + .cloned() + .ok_or(CodexCredentialQuotaError::InvalidCredentialData)?, + ); + object.remove(RECOVERY_FIELD); + object.remove(LIMIT_EVIDENCE_FIELD); + let mut snapshot = parse_account_quota_snapshot( + account.id().clone(), + account.revision(), + observed_at, + &Value::Object(object.clone()), + )?; + let (merge_base, previous) = + if account.quota().is_exhausted() || !account.quota_limits().is_empty() { + let (base, snapshot) = self.read_snapshot_with_base(account).await?; + if base.observed_at.is_some_and(|at| at >= observed_at) { + return Err(CodexCredentialQuotaError::RevisionConflict); + } + (Some(base), snapshot) + } else { + (None, None) + }; + // 失败后回读只允许明确可用的点数恢复访问,套餐 allowed 仍可能滞后 + let observe_access = matches!(authority, QuotaRefreshAuthority::ObserveAccess) + || (account.auto_use_quota_credits() && snapshot.credits_usable()); + if account.quota().is_exhausted() && !observe_access { + if self + .store + .touch_quota_observation(QuotaObservationTouch { + account_id: account.id().clone(), + expected_revision: account.revision(), + observed_at, + }) + .await? + == QuotaWriteOutcome::Conflict + { + return Err(CodexCredentialQuotaError::RevisionConflict); + } + return Ok(match previous { + Some(previous) => { + let previous = previous.with_observed_at(observed_at); + self.scheduling.observe(&previous); + previous + } + None => snapshot + .with_quota_state(account.quota()) + .with_observed_at(observed_at), + }); + } + snapshot.retain_limit_evidence(account.quota_limits(), previous.as_ref(), &mut object); + let state = if matches!(authority, QuotaRefreshAuthority::PreserveAccess) { + snapshot.access_with_credits(account.quota(), account.auto_use_quota_credits()) + } else { + reconcile_refresh( + account.quota(), + account.auto_use_quota_credits(), + &mut snapshot, + previous.as_ref().filter(|_| account.quota().is_exhausted()), + &mut object, + )? + }; + let snapshot = snapshot.with_quota_state(state); if self .store - .touch_quota_observation(QuotaObservationTouch { + .compare_and_swap_quota(QuotaObservation { + quota_pause: Some(snapshot.pause_decision(account.quota_limits(), merge_base)), + expected_connection: None, + plan_type: observed_account_plan(account.plan_type(), snapshot.plan_type()), account_id: account.id().clone(), expected_revision: account.revision(), + quota: OpaqueProviderData::new(object), observed_at, + state, }) .await? == QuotaWriteOutcome::Conflict { + if merge_base.is_some() { + continue; + } return Err(CodexCredentialQuotaError::RevisionConflict); } - return Ok(match previous { - Some(previous) => { - let previous = previous.with_observed_at(observed_at); - self.scheduling.observe(&previous); - previous - } - None => snapshot - .with_quota_state(account.quota()) - .with_observed_at(observed_at), - }); + self.scheduling.observe(&snapshot); + return Ok(snapshot); } - let state = if matches!(authority, QuotaRefreshAuthority::PreserveAccess) { - snapshot.access_with_credits(account.quota(), account.auto_use_quota_credits()) - } else { - reconcile_refresh( - account.quota(), - account.auto_use_quota_credits(), - &mut snapshot, - previous.as_ref(), - &mut object, - )? - }; - let snapshot = snapshot.with_quota_state(state); - if self - .store - .compare_and_swap_quota(QuotaObservation { - expected_connection: None, - plan_type: observed_account_plan(account.plan_type(), snapshot.plan_type()), - account_id: account.id().clone(), - expected_revision: account.revision(), - quota: OpaqueProviderData::new(object), - observed_at, - state, - }) - .await? - == QuotaWriteOutcome::Conflict - { - return Err(CodexCredentialQuotaError::RevisionConflict); - } - self.scheduling.observe(&snapshot); - Ok(snapshot) + Err(CodexCredentialQuotaError::RevisionConflict) } async fn persist_credential_failure( diff --git a/backend/crates/providers/openai/src/credential/quota/snapshot.rs b/backend/crates/providers/openai/src/credential/quota/snapshot.rs index f4cb1ef4c..007b8fe8d 100644 --- a/backend/crates/providers/openai/src/credential/quota/snapshot.rs +++ b/backend/crates/providers/openai/src/credential/quota/snapshot.rs @@ -3,6 +3,7 @@ //! Provider raw quota JSON 的唯一解析者:产出 [`CodexAccountQuotaSnapshot`] //! 供服务编排层消费;`limit_reached` 是快照级事实,不能只从子窗口反推 +use std::collections::BTreeMap; use std::time::{Duration, SystemTime}; use chrono::{DateTime, Utc}; @@ -120,10 +121,65 @@ pub struct CodexAccountQuotaSnapshot { fact: CodexQuotaFact, quota: QuotaState, windows: Vec, + unconfirmed_limits: BTreeMap, pub(super) recovery: Option, } impl CodexAccountQuotaSnapshot { + pub(super) fn pause_decision( + &self, + limits: &gateway_core::account::AccountQuotaLimits, + merge_base: Option, + ) -> gateway_core::account::QuotaPauseDecision { + gateway_core::account::QuotaPauseDecision { + merge_base, + limits: limits.clone(), + paused: self + .limit_usage() + .any(|(key, used)| limits.reached(key, Some(used))), + } + } + + pub(crate) fn limit_usage(&self) -> impl Iterator { + self.windows + .iter() + .filter(|w| w.is_account_wide()) + .filter_map(|w| Some((w.key(), w.used_percent()?))) + .chain( + self.unconfirmed_limits + .iter() + .map(|(key, &used)| (key.as_str(), used)), + ) + } + + /// 迟到的在途响应或不完整的刷新不能清除已确认的上限,只有对应窗口的新比例才能覆盖它 + pub(super) fn retain_limit_evidence( + &mut self, + limits: &gateway_core::account::AccountQuotaLimits, + previous: Option<&Self>, + document: &mut Map, + ) { + self.unconfirmed_limits = previous + .into_iter() + .flat_map(Self::limit_usage) + .filter(|(key, used)| { + limits.reached(key, Some(*used)) + && !self.windows.iter().any(|w| { + w.is_account_wide() && w.key() == *key && w.used_percent().is_some() + }) + }) + .map(|(key, used)| (key.to_owned(), used)) + .collect(); + if self.unconfirmed_limits.is_empty() { + document.remove(super::LIMIT_EVIDENCE_FIELD); + } else { + document.insert( + super::LIMIT_EVIDENCE_FIELD.into(), + serde_json::json!(self.unconfirmed_limits), + ); + } + } + #[must_use] pub const fn account_id(&self) -> &ProviderAccountId { &self.account_id @@ -381,6 +437,12 @@ pub(crate) fn parse_account_quota_snapshot( fact, quota, windows, + unconfirmed_limits: object + .get(super::LIMIT_EVIDENCE_FIELD) + .map(|v| serde_json::from_value(v.clone())) + .transpose() + .map_err(|_| CodexCredentialQuotaError::InvalidCredentialData)? + .unwrap_or_default(), recovery, }) } diff --git a/backend/crates/providers/openai/src/credential/selector.rs b/backend/crates/providers/openai/src/credential/selector.rs index 43eb91e65..c1aa52fcb 100644 --- a/backend/crates/providers/openai/src/credential/selector.rs +++ b/backend/crates/providers/openai/src/credential/selector.rs @@ -1064,6 +1064,20 @@ impl CodexCredentialSelector { .prepare_cyber_policy_scope(cyber_policy_session_key) .await; let mut excluded = request.attempt.excluded_accounts().clone(); + if !diagnostic { + for candidate in &candidates { + if candidate.account.quota_paused() { + if follow_only + && binding.as_ref().is_some_and(|binding| { + binding.account_id() == candidate.account.id() + }) + { + return Err(CredentialSelectionError::PolicyFiltered); + } + excluded.insert(candidate.account.id().clone()); + } + } + } if let Some(state) = cyber_policy_scope .as_ref() .and_then(|scope| scope.state.as_ref()) @@ -1320,6 +1334,10 @@ impl CodexCredentialSelector { } Err(error) => return Err(error.into()), }; + if !diagnostic && account.quota_paused() { + refresh_candidates = true; + continue 'capacity; + } // 凭据重读和插件选号都可能挂起,取得租约前再次让位于新队首 if !waiting.can_try(account.id()) { busy_accounts.insert(account.id().clone()); @@ -2056,7 +2074,8 @@ fn affinity_selection_for_bound_account( .status { AccountStatus::Normal => AffinitySelection::preferred(account_id), - AccountStatus::QuotaExhausted + AccountStatus::QuotaPaused + | AccountStatus::QuotaExhausted | AccountStatus::RateLimited | AccountStatus::Disabled | AccountStatus::Error => { @@ -2075,7 +2094,7 @@ fn affinity_unavailable_reason( .status { AccountStatus::QuotaExhausted => AffinityEscapeReason::QuotaExhausted, - AccountStatus::RateLimited => AffinityEscapeReason::Cooldown, + AccountStatus::RateLimited | AccountStatus::QuotaPaused => AffinityEscapeReason::Cooldown, AccountStatus::Normal => AffinityEscapeReason::SelectionInvariant, AccountStatus::Disabled | AccountStatus::Error => AffinityEscapeReason::HardUnavailable, } diff --git a/backend/crates/providers/openai/tests/admin/mod.rs b/backend/crates/providers/openai/tests/admin/mod.rs index c7e355c95..4fbaeb440 100644 --- a/backend/crates/providers/openai/tests/admin/mod.rs +++ b/backend/crates/providers/openai/tests/admin/mod.rs @@ -1101,6 +1101,7 @@ async fn openai_admin_batch_quota_isolates_stale_and_invalid_observations() { }; store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, account_id: account.id().clone(), expected_revision: account.revision(), @@ -1451,6 +1452,7 @@ async fn openai_admin_projects_free_plan_from_cached_quota_when_account_claims_o let observed_at = SystemTime::now(); store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account.id().clone(), @@ -1567,6 +1569,7 @@ async fn openai_admin_provider_projects_official_codex_quota_and_independent_buc let observed_at = SystemTime::now(); store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account.id().clone(), @@ -1670,6 +1673,7 @@ async fn openai_admin_keeps_confirmed_exhaustion_separate_from_raw_usage_display let observed_at = SystemTime::now(); store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account.id().clone(), @@ -1782,6 +1786,7 @@ async fn openai_admin_preserves_expired_window_usage_and_exhaustion_attribution( }; store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account.id().clone(), @@ -2184,6 +2189,8 @@ fn provider_ports_with_catalog( fn account_record(account: &ProviderAccount) -> AccountRecord { let now = Utc::now(); AccountRecord { + quota_paused: false, + quota_limits: Default::default(), auto_use_quota_credits: false, outbound_proxy_id: None, outbound_proxy_enabled: true, diff --git a/backend/crates/providers/openai/tests/admin/peer_info.rs b/backend/crates/providers/openai/tests/admin/peer_info.rs index e87ef95ad..3f0331b75 100644 --- a/backend/crates/providers/openai/tests/admin/peer_info.rs +++ b/backend/crates/providers/openai/tests/admin/peer_info.rs @@ -1259,6 +1259,7 @@ async fn cold_lists_bound_full_snapshot_batches_and_reuse_every_hydrated_summary document["usage"]["data"]["windows"][0]["used"] = json!(index.to_string()); store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: Some(connection), account_id: id.clone(), expected_revision: account.revision(), diff --git a/backend/crates/providers/openai/tests/credential/contract/mod.rs b/backend/crates/providers/openai/tests/credential/contract/mod.rs index 02bc79f24..64b5a97de 100644 --- a/backend/crates/providers/openai/tests/credential/contract/mod.rs +++ b/backend/crates/providers/openai/tests/credential/contract/mod.rs @@ -1624,6 +1624,7 @@ fn native_continuation_surfaces_the_original_accounts_quota_signal_to_the_coordi }); let observed_at = SystemTime::now(); let outcome = block_on(store.compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: original.id().clone(), diff --git a/backend/crates/providers/openai/tests/credential/quota/mod.rs b/backend/crates/providers/openai/tests/credential/quota/mod.rs index 500aaf1b6..3a07eccbc 100644 --- a/backend/crates/providers/openai/tests/credential/quota/mod.rs +++ b/backend/crates/providers/openai/tests/credential/quota/mod.rs @@ -623,6 +623,127 @@ async fn initial_quota_worker_synchronizes_account_plan() { ); } +#[tokio::test] +async fn concurrent_named_usage_preserves_newly_paused_general_window() { + let store = Arc::new(MemoryAccountStore::default()); + let id = "acct_concurrent_threshold"; + create_account(&store, id).await; + store.set_quota_limits( + id, + serde_json::from_value(json!({"codex:18000s": 95})).unwrap(), + ); + let account = store.account(id).unwrap(); + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/api/codex/usage")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "rate_limit": {"primary_window": {"limit_window_seconds": 18000, "used_percent": 96}} + }))) + .expect(1) + .mount(&server) + .await; + let service = quota_service_with_base_url( + &store, + reqwest::Client::builder().no_proxy().build().unwrap(), + server.uri(), + ); + let named = [ + ( + "x-codex-bengalfox-primary-used-percent".to_owned(), + "13".to_owned(), + ), + ( + "x-codex-bengalfox-primary-window-minutes".to_owned(), + "300".to_owned(), + ), + ]; + // 刷新先发起,两次读取都看到空快照,但刷新先写入达限结论 + let (read, commit_refresh) = store.hold_next_quota_read(); + let mut refresh = std::pin::pin!(service.refresh_account(account.id())); + tokio::select! { + result = &mut refresh => panic!("refresh finished before merge: {result:?}"), + ready = read => ready.unwrap(), + } + let (read, commit_passive) = store.hold_next_quota_read(); + let mut passive = std::pin::pin!(service.synchronize_passive_headers(&account, &named)); + tokio::select! { + result = &mut passive => panic!("passive write finished before merge: {result:?}"), + ready = read => ready.unwrap(), + } + commit_refresh.send(()).unwrap(); + refresh.await.unwrap(); + assert!(store.account(id).unwrap().quota_paused()); + commit_passive.send(()).unwrap(); + assert!(passive.await.unwrap()); + + assert!(store.account(id).unwrap().quota_paused()); + let snapshot = service.read_account(account.id()).await.unwrap().unwrap(); + for (source, percent) in [("codex", 96.0), ("codex_bengalfox", 13.0)] { + assert!( + snapshot + .windows() + .iter() + .any(|w| w.source() == source && w.used_percent() == Some(percent)) + ); + } +} + +#[tokio::test] +async fn missing_window_keeps_its_confirmed_limit_across_refresh_and_restart() { + let store = Arc::new(MemoryAccountStore::default()); + let id = "acct_partial_threshold"; + create_account(&store, id).await; + store.set_quota_limits( + id, + serde_json::from_value(json!({"codex:604800s":95})).unwrap(), + ); + let server = MockServer::start().await; + let service = quota_service_with_base_url( + &store, + reqwest::Client::builder().no_proxy().build().unwrap(), + server.uri(), + ); + for (rate, blocked) in [ + ( + json!({"secondary_window":{"limit_window_seconds":604800,"used_percent":95}}), + true, + ), + ( + json!({"primary_window":{"limit_window_seconds":18000,"used_percent":8}}), + true, + ), + ( + json!({"secondary_window":{"limit_window_seconds":604800,"used_percent":0}}), + false, + ), + ] { + server.reset().await; + Mock::given(method("GET")) + .and(path("/api/codex/usage")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"rate_limit":rate}))) + .mount(&server) + .await; + if blocked { + service + .refresh_account(store.account(id).unwrap().id()) + .await + .unwrap(); + } else { + let result = service.synchronize_at(SystemTime::now()).await.unwrap(); + assert_eq!(result.updated, 1); + } + let account = store.account(id).unwrap(); + let restarted = quota_service(&store); + restarted + .prepare_scheduling(std::slice::from_ref(&account)) + .await; + assert_eq!( + account.status_projection(SystemTime::now(), None).status == AccountStatus::QuotaPaused, + blocked + ); + } +} + #[tokio::test] async fn quota_refresh_persists_explicit_provider_denial() { let store = Arc::new(MemoryAccountStore::default()); diff --git a/backend/crates/providers/openai/tests/credential/quota/reset_recovery.rs b/backend/crates/providers/openai/tests/credential/quota/reset_recovery.rs index c85a3dc9e..8d749d9a5 100644 --- a/backend/crates/providers/openai/tests/credential/quota/reset_recovery.rs +++ b/backend/crates/providers/openai/tests/credential/quota/reset_recovery.rs @@ -69,6 +69,7 @@ async fn allowed_refresh_recovers_full_windows_only_after_the_confirmed_resets() let old_usage = usage(now, &resets, Some(false)); store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account.id().clone(), diff --git a/backend/crates/providers/openai/tests/credential/quota/scheduling.rs b/backend/crates/providers/openai/tests/credential/quota/scheduling.rs index 1025c9b74..0e53d15d5 100644 --- a/backend/crates/providers/openai/tests/credential/quota/scheduling.rs +++ b/backend/crates/providers/openai/tests/credential/quota/scheduling.rs @@ -25,6 +25,7 @@ async fn persist_snapshot( let account = store.account(id).expect("created account"); store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account.id().clone(), diff --git a/backend/crates/providers/openai/tests/credential/quota/slots.rs b/backend/crates/providers/openai/tests/credential/quota/slots.rs index e438c15da..05656231a 100644 --- a/backend/crates/providers/openai/tests/credential/quota/slots.rs +++ b/backend/crates/providers/openai/tests/credential/quota/slots.rs @@ -495,6 +495,7 @@ async fn stored_weekly_exhaustion_ignores_the_old_primary_only_account_reset() { old["rate_limit"]["allowed"] = json!(false); store .compare_and_swap_quota(gateway_core::account::QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account.id().clone(), diff --git a/backend/crates/providers/openai/tests/credential/quota/snapshot.rs b/backend/crates/providers/openai/tests/credential/quota/snapshot.rs index de17733d0..abd500350 100644 --- a/backend/crates/providers/openai/tests/credential/quota/snapshot.rs +++ b/backend/crates/providers/openai/tests/credential/quota/snapshot.rs @@ -187,6 +187,7 @@ async fn persisted_provider_quota_projects_dynamic_windows_without_network_io() }); let outcome = store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account.id().clone(), @@ -234,6 +235,7 @@ async fn expired_window_remains_the_last_observation_until_refresh() { }); store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account.id().clone(), @@ -274,6 +276,7 @@ async fn persisted_access_fact_survives_limit_without_percent_or_reset() { }); store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account.id().clone(), @@ -325,6 +328,7 @@ async fn persisted_codex_alias_keeps_the_top_level_rate_limit_canonical() { }); let outcome = store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account.id().clone(), @@ -384,6 +388,7 @@ async fn persisted_quota_orders_core_window_before_additional_limit() { }); store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account.id().clone(), @@ -450,6 +455,7 @@ async fn code_review_limit_projects_as_one_snapshot_per_limit_id() { }); store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account.id().clone(), diff --git a/backend/crates/providers/openai/tests/credential/quota/warmup.rs b/backend/crates/providers/openai/tests/credential/quota/warmup.rs index 6a296fdce..ae5c8a57e 100644 --- a/backend/crates/providers/openai/tests/credential/quota/warmup.rs +++ b/backend/crates/providers/openai/tests/credential/quota/warmup.rs @@ -29,6 +29,7 @@ async fn seed_quota( assert_eq!( store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account.id().clone(), @@ -128,6 +129,7 @@ async fn warmup_skips_exhausted_account_windows_without_refreshing_quota() { }}}); store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account.id().clone(), diff --git a/backend/crates/providers/openai/tests/provider/contract/mod.rs b/backend/crates/providers/openai/tests/provider/contract/mod.rs index 9329c21ee..69885e78a 100644 --- a/backend/crates/providers/openai/tests/provider/contract/mod.rs +++ b/backend/crates/providers/openai/tests/provider/contract/mod.rs @@ -6138,6 +6138,109 @@ async fn websocket_metadata_close_requests_bounded_retry_without_claiming_replay ); } +#[tokio::test] +async fn general_quota_limits_filter_new_requests_until_every_window_recovers() { + let store = Arc::new(MemoryAccountStore::default()); + let limited = "acct_provider_contract"; + let backup = "acct_scope_new"; + create_account(&store, limited).await; + create_account(&store, backup).await; + store.set_quota_limits( + limited, + serde_json::from_value(json!({"codex:18000s":99, "codex:604800s":95})).unwrap(), + ); + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/codex/responses")) + .respond_with( + ResponseTemplate::new(200) + .insert_header("content-type", "text/event-stream") + .set_body_string(CAPTURE_COMPLETED_SSE), + ) + .mount(&server) + .await; + let leases = Arc::new(TestLeaseCoordinator::default()); + let (provider, quota) = provider_and_quota_with_affinity_and_base_url_and_leases( + &store, + Arc::new(MemorySessionAffinity::default()), + server.uri(), + leases.clone(), + 0, + ); + for (index, (short, weekly, blocked)) in + [(99.0, 96.0, true), (0.0, 95.0, true), (98.99, 94.99, false)] + .into_iter() + .enumerate() + { + let account = store.account(limited).unwrap(); + let usage = Mock::given(method("GET")) + .and(path("/api/codex/usage")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "rate_limit": {"primary_window":{"limit_window_seconds":18000,"used_percent":short},"secondary_window":{"limit_window_seconds":604800,"used_percent":weekly}}, + "code_review_rate_limit":{"primary_window":{"limit_window_seconds":18000,"used_percent":100}} + }))) + .mount_as_scoped(&server).await; + quota.refresh_account(account.id()).await.unwrap(); + drop(usage); + let request = planned_request("openai", http_generate_operation()); + let pinned = pinned_continuation_context( + &format!("req_pin_{index}"), + limited, + "client-previous", + "upstream-previous", + 1, + ContinuationAttempt::Native, + ); + let before = leases.requests.lock().unwrap().len(); + let result = provider.clone().execute(request, pinned).await; + if blocked { + let Err(error) = result else { + panic!("a paused owner cannot serve native continuation") + }; + assert_eq!(error.send_state(), UpstreamSendState::NotSent); + assert_eq!(leases.requests.lock().unwrap().len(), before); + drop( + provider + .clone() + .execute( + planned_request("openai", http_generate_operation()), + context(&format!("req_fallback_{index}"), CancellationToken::new()), + ) + .await + .unwrap(), + ); + assert_eq!( + leases + .requests + .lock() + .unwrap() + .last() + .unwrap() + .account_id() + .as_str(), + backup + ); + } else { + drop( + result.expect( + "recovered general quota can serve the owner despite a full named bucket", + ), + ); + assert_eq!( + leases + .requests + .lock() + .unwrap() + .last() + .unwrap() + .account_id() + .as_str(), + limited + ); + } + } +} + #[tokio::test] async fn disabled_account_is_excluded_from_normal_scheduling() { let store = Arc::new(MemoryAccountStore::default()); @@ -7559,6 +7662,7 @@ async fn affinity_quota_switch_should_clear_old_turn_state_without_a_provider_st let observed_at = SystemTime::now(); store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: first_account.id().clone(), @@ -8567,6 +8671,7 @@ async fn official_usage_limit_failure_persists_fact_without_fabricating_usage() let observed_at = SystemTime::now(); store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account.id().clone(), @@ -10170,6 +10275,7 @@ async fn quota_limited_account_diagnostic_uses_upstream() { let observed_at = SystemTime::now(); store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account.id().clone(), diff --git a/backend/crates/providers/openai/tests/support.rs b/backend/crates/providers/openai/tests/support.rs index 4c70d6387..81bac8c66 100644 --- a/backend/crates/providers/openai/tests/support.rs +++ b/backend/crates/providers/openai/tests/support.rs @@ -32,6 +32,7 @@ use provider_openai::credential::{ ImportCodexOAuthCredential, }; use secrecy::SecretString; +use tokio::sync::oneshot; #[derive(Clone)] struct StoredAccount { @@ -55,6 +56,7 @@ pub(crate) struct MemoryAccountStore { account_reads: AtomicUsize, provider_list_reads: AtomicUsize, quota_reads: AtomicUsize, + next_quota_read: Mutex, oneshot::Receiver<()>)>>, largest_quota_read: AtomicUsize, fail_provider_listing: AtomicBool, pending_account_reads: bool, @@ -167,6 +169,18 @@ impl MemoryAccountStore { .map(|stored| stored.account.clone()) } + pub(crate) fn set_quota_limits( + &self, + id: &str, + limits: gateway_core::account::AccountQuotaLimits, + ) { + let mut accounts = self.accounts.lock().unwrap(); + let stored = accounts + .get_mut(&ProviderAccountId::new(id).unwrap()) + .unwrap(); + stored.account = stored.account.clone().with_quota_limits(limits, false); + } + pub(crate) fn enable_quota_credits(&self, id: &str) { let mut accounts = self.accounts.lock().unwrap(); let stored = accounts @@ -222,6 +236,13 @@ impl MemoryAccountStore { self.largest_quota_read.load(Ordering::SeqCst) } + pub(crate) fn hold_next_quota_read(&self) -> (oneshot::Receiver<()>, oneshot::Sender<()>) { + let (read, ready) = oneshot::channel(); + let (release, held) = oneshot::channel(); + *self.next_quota_read.lock().unwrap() = Some((read, held)); + (ready, release) + } + pub(crate) fn quota_reads(&self) -> usize { self.quota_reads.load(Ordering::SeqCst) } @@ -507,11 +528,19 @@ impl ProviderAccountStore for MemoryAccountStore { self.quota_reads.fetch_add(1, Ordering::SeqCst); self.largest_quota_read .fetch_max(accounts.len(), Ordering::SeqCst); - let stored = self.accounts.lock().expect("account store lock"); - Ok(accounts - .iter() - .filter_map(|account| stored.get(account)?.quota.clone()) - .collect()) + let result = { + let stored = self.accounts.lock().expect("account store lock"); + accounts + .iter() + .filter_map(|account| stored.get(account)?.quota.clone()) + .collect() + }; + let held = self.next_quota_read.lock().unwrap().take(); + if let Some((read, held)) = held { + read.send(()).unwrap(); + held.await.expect("release quota read"); + } + Ok(result) } async fn get_quota_versions( @@ -553,6 +582,16 @@ impl ProviderAccountStore for MemoryAccountStore { { return Ok(QuotaWriteOutcome::Conflict); } + let current_version = stored.quota.as_ref().map(|quota| quota.observed_at); + if observation.quota_pause.as_ref().is_some_and(|decision| { + &decision.limits != stored.account.quota_limits() + || current_version == Some(observation.observed_at) + || decision + .merge_base + .is_some_and(|base| base.observed_at != current_version) + }) { + return Ok(QuotaWriteOutcome::Conflict); + } if stored .quota .as_ref() @@ -580,8 +619,10 @@ impl ProviderAccountStore for MemoryAccountStore { Some(plan_type.clone()), )); } + let paused = observation.quota_pause.as_ref().is_some_and(|v| v.paused); stored.quota = Some(observation); - stored.account = rebuild_account(&stored.account, replacement); + stored.account = rebuild_account(&stored.account, replacement) + .with_quota_limits(stored.account.quota_limits().clone(), paused); Ok(QuotaWriteOutcome::Updated) } @@ -789,6 +830,7 @@ fn rebuild_account(current: &ProviderAccount, rebuild: AccountRebuild) -> Provid rebuild.last_error_message, ) .with_scheduling(current.concurrency_limit(), current.weight()) + .with_quota_limits(current.quota_limits().clone(), current.quota_paused()) .with_auto_use_quota_credits(current.auto_use_quota_credits()) .with_refresh_schedule(rebuild.has_refresh_token, rebuild.next_refresh_at) .with_outbound_proxy(current.outbound_proxy().cloned()) diff --git a/backend/crates/providers/xai/src/admin.rs b/backend/crates/providers/xai/src/admin.rs index 005b15979..94741fd22 100644 --- a/backend/crates/providers/xai/src/admin.rs +++ b/backend/crates/providers/xai/src/admin.rs @@ -1258,6 +1258,7 @@ fn project_quota( } }; ProviderQuota { + paused_windows: Vec::new(), upstream: None, credits: None, plan_type: billing diff --git a/backend/crates/providers/xai/src/credential/repository.rs b/backend/crates/providers/xai/src/credential/repository.rs index c8bcd2f75..f9e017cb4 100644 --- a/backend/crates/providers/xai/src/credential/repository.rs +++ b/backend/crates/providers/xai/src/credential/repository.rs @@ -567,6 +567,7 @@ impl GrokCredentialRepository { let outcome = self .store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id, diff --git a/backend/crates/providers/xai/tests/admin.rs b/backend/crates/providers/xai/tests/admin.rs index 903897eca..67c7dd0c3 100644 --- a/backend/crates/providers/xai/tests/admin.rs +++ b/backend/crates/providers/xai/tests/admin.rs @@ -568,6 +568,7 @@ async fn xai_admin_provider_projects_cached_quota_models_and_canonical_export() ); store .compare_and_swap_quota(gateway_core::account::QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account.id().clone(), @@ -768,6 +769,8 @@ fn provider_ports_with_catalog( fn account_record(account: &ProviderAccount) -> AccountRecord { let now = Utc::now(); AccountRecord { + quota_paused: false, + quota_limits: Default::default(), auto_use_quota_credits: false, outbound_proxy_id: None, outbound_proxy_enabled: true, diff --git a/backend/crates/providers/xai/tests/credential/quota.rs b/backend/crates/providers/xai/tests/credential/quota.rs index 8185a26b6..4381a53a3 100644 --- a/backend/crates/providers/xai/tests/credential/quota.rs +++ b/backend/crates/providers/xai/tests/credential/quota.rs @@ -645,6 +645,7 @@ async fn quota_read_rejects_corrupt_provider_document() { document.insert("config".to_owned(), serde_json::json!([])); store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: account_id("corrupt"), diff --git a/backend/crates/providers/xai/tests/credential/refresh.rs b/backend/crates/providers/xai/tests/credential/refresh.rs index 4fb835420..34ae4aa07 100644 --- a/backend/crates/providers/xai/tests/credential/refresh.rs +++ b/backend/crates/providers/xai/tests/credential/refresh.rs @@ -323,6 +323,7 @@ async fn seed_quota_snapshot( ) -> QuotaObservation { let account = store.account(id).unwrap(); let quota = QuotaObservation { + quota_pause: None, account_id: id.clone(), expected_revision: account.revision(), expected_connection: None, diff --git a/backend/crates/providers/xai/tests/credential/selector.rs b/backend/crates/providers/xai/tests/credential/selector.rs index 36713c757..276f967b0 100644 --- a/backend/crates/providers/xai/tests/credential/selector.rs +++ b/backend/crates/providers/xai/tests/credential/selector.rs @@ -266,6 +266,7 @@ impl SelectorFixture { let outcome = self .store .compare_and_swap_quota(QuotaObservation { + quota_pause: None, expected_connection: None, plan_type: None, account_id: id.clone(), diff --git a/backend/migrations/.frozen-sha256 b/backend/migrations/.frozen-sha256 index 078095b3a..b85253aca 100644 --- a/backend/migrations/.frozen-sha256 +++ b/backend/migrations/.frozen-sha256 @@ -41,3 +41,4 @@ a6b4e81d38e5d70776a75eba22749354573ebcb186160ff9eb45fd91157b3e0d 0039_queue_tim 3451931b9296d9db9cd580e15c9256c4576936ce6580d52600c4e85e959d7c36 0041_explicit_budget_windows.sql 3685caa890f06d1537ddf5bfe8e139c481575340d5d852886d8d200282aadd4a 0042_reset_credit_weekly_trigger.sql ea4761e79b249d7eaa8722727cc2a42bcb5b361a56f20090eb2469b0036242f5 0043_peer_routing_id.sql +d5be4b04199856ef9825e600d5e51a904f6a5ba16c3213d8a7ae158825ff6878 0044_account_quota_limits.sql diff --git a/backend/migrations/0044_account_quota_limits.sql b/backend/migrations/0044_account_quota_limits.sql new file mode 100644 index 000000000..803a6a18b --- /dev/null +++ b/backend/migrations/0044_account_quota_limits.sql @@ -0,0 +1,3 @@ +alter table provider_accounts + add column quota_limits jsonb not null default '{}'::jsonb, + add column quota_paused boolean not null default false; diff --git a/docs/api.md b/docs/api.md index 66ef9bfdb..c951c4d42 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1214,7 +1214,7 @@ config 返回 `{ name, plaintextKey }`,仅读取服务端会话绑定的当前 - `provider`: `openai` 或 `xai`,省略或空值表示不过滤 - `groupId`: 分组 ID、`ungrouped`,或省略以不过滤 -- `status`: `normal`、`quota_exhausted`、`rate_limited`、`disabled`、`error` +- `status`: `normal`、`quota_paused`、`quota_exhausted`、`rate_limited`、`disabled`、`error` - `sortBy`: `email`、`status`、`planType`、`usage`、`lastUsedAt`、`expiresAt` - `sortDirection`: `asc`、`desc` @@ -1248,6 +1248,16 @@ config 返回 `{ name, plaintextKey }`,仅读取服务端会话绑定的当前 未要求探测时,该字段表示冷却结束时间。`protectionRules` 返回触发时的规则快照 `[{ id, name }]`, 没有保护原因时为空数组,修改或删除当前规则不改写此快照。错误保护与上游限流独立恢复,解除保护不保证其他限制已经解除 +OpenAI OAuth 账号的 `capabilities.quotaLimitsSupported` 为真。通过 `POST /api/admin/accounts/batch-update` +提交 `{"accountIds":["acct_1"],"quotaLimits":{"codex:18000s":99,"codex:604800s":95}}`。 +键取自该账号 `quota.windows` 中 `accountWide: true` 的窗口 `key`,值是 1~100 的整数使用率。 +提交的映射替换全部窗口上限;省略字段保留原配置,空对象关闭全部上限。账号视图以 `quotaLimits` 返回配置 + +任一已设限通用窗口的实际使用率达到或超过上限,该账号暂停接收新请求,在途请求继续。账号状态为 `quota_paused`,可按此状态筛选;停用、凭据错误、上游额度耗尽和限流优先显示。 +`quota.pausedWindows` 列出触发窗口的键,已知重置时间见对应窗口的 `resetAtDisplay`。 +重置时间到达或暂时缺少用量均不证明恢复;所有触发窗口的观测都低于上限或相应配置解除后恢复调度。 +专属额度桶不参与判断,此策略不改变账号启用状态和上游额度状态 + `quota.credits` 返回上游点数信息,缺失时为 `null`;包含 `hasCredits`、`unlimited` 和 `balance`。 余额是保留上游精度的十进制字符串,未知为 `null`,零为 `"0"`,与重置卡库存独立 diff --git a/docs/architecture.md b/docs/architecture.md index eea10f967..c84d19b52 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1010,7 +1010,7 @@ PostgreSQL 周期对账才是正确性基础 | Windows 安装包临时直链 | Host 进程内短缓存 | 按需解析、严格校验、到期前丢弃;不写 PostgreSQL/Redis,也不代理包字节 | 账号对外状态不是独立列,而是 PostgreSQL credential/quota 事实与 Redis cooldown 的统一投影: -`normal`、`quota_exhausted`、`rate_limited`、`disabled`、`error`。只有明确上游证据才能恢复或终态化账号, +`normal`、`quota_paused`、`quota_exhausted`、`rate_limited`、`disabled`、`error`。只有明确上游证据才能恢复或终态化账号, 本地时钟和不确定响应不能伪造事实 错误保护与上游限流分别保存恢复事实并聚合冷却投影,探测恢复由 Admin 负责,详见[Worker 与账号冻结](#worker-与账号冻结) @@ -1046,6 +1046,10 @@ OpenAI 响应头的额度窗口按头名前缀归属,普通 Responses 的 `x-c 仅在图片生成和编辑端点,若 `x-codex-active-limit` 指向具名计量项且没有该项的独立额度头, 通用窗口才归入该计量项。Provider 按计量项独立保存,具名额度不改变账号级套餐访问结论 +账号调度上限属于管理员策略。OpenAI Provider 只将通用桶的实际使用率用于上限判断, +与有时效的 Smart 排序信号和上游额度耗尽事实分开。选号、等待后重选和管理端投影共用窗口身份及比较规则; +合并写入前核对所读快照的版本,版本冲突时按原观测时间重新合并。部分观测缺少已触发窗口时保留该窗口的最后证据。已暂停账号切换出口时保留原生额度快照和观测时间,后台额度任务继续复核 + OpenAI Provider 统一解释点数可用性,主动查询、耗尽恢复与失败回读复用同一规则。 Store 在账号事务内保存点数放行依据与快照;关闭自动使用时撤销该依据,迟到观测不能绕过开关。 放行条件与默认值见[账号额度 API](api.md#查询与账号字段)。 @@ -1101,7 +1105,7 @@ OAuth 额度解析属于 Provider,CPR 发现、解析与投影属于 Admin; 共享端按 Core 的预算规则从本地账本生成明确的访问状态,与本地准入共用口径;金额字段只供接入端展示。 接入端 Admin 的独立额度模块解释默认公开的访问状态,展示、调度投影与同步共用,不要求公开账号池额度;未知或过期事实保留已有状态,Provider 不新增 CPR 错误码分类。 通用额度写入按凭据版本和查询开始时间提交快照,并独立保护访问事实的观察时间;网络查询可附带连接校验,在同一事务核对出口与启用状态。 -账号重新授权或出口变更使旧快照及互联识别记录失效,正常 token 续期保留额度;授权撤销提交不含共享内容的观测和时间屏障,阻止更早响应重新发布旧内容。 +互联账号重新授权或出口变更使旧快照及互联识别记录失效,正常 token 续期保留额度;授权撤销提交不含共享内容的观测和时间屏障,阻止更早响应重新发布旧内容。 互联解析只提交有效且明确的预算访问事实,额度同步不改变凭据或独立冷却 Admin 按连接身份及额度观察时间缓存管理摘要与调度投影,解析和投影在锁外完成。 diff --git a/frontend/src/api/modules/accounts/index.ts b/frontend/src/api/modules/accounts/index.ts index 5608692d3..2bd63b8c7 100644 --- a/frontend/src/api/modules/accounts/index.ts +++ b/frontend/src/api/modules/accounts/index.ts @@ -72,6 +72,7 @@ export type { } from './personal-info' export { + getAccountQuota, getAccountQuotaForecast, refreshAccountQuota, } from './quota' diff --git a/frontend/src/api/modules/accounts/management.ts b/frontend/src/api/modules/accounts/management.ts index 8923754e1..3439a3656 100644 --- a/frontend/src/api/modules/accounts/management.ts +++ b/frontend/src/api/modules/accounts/management.ts @@ -12,6 +12,7 @@ export interface AccountPageMeta { export interface AccountSummary { total: number normal: number + quotaPaused: number quotaExhausted: number rateLimited: number disabled: number @@ -66,6 +67,7 @@ interface AccountUpdateParam { } interface AccountBatchUpdateParam { + quotaLimits?: Record autoUseQuotaCredits?: boolean outboundProxyUrl?: string outboundProxyId?: string diff --git a/frontend/src/api/modules/accounts/quota.ts b/frontend/src/api/modules/accounts/quota.ts index 0b739e422..f5555c675 100644 --- a/frontend/src/api/modules/accounts/quota.ts +++ b/frontend/src/api/modules/accounts/quota.ts @@ -45,6 +45,15 @@ export function getAccountQuotaForecast(data: AccountIdParam, options: RequestOp }) } +export function getAccountQuota(data: AccountIdParam, options: RequestOptions = {}) { + return request({ + url: '/api/admin/accounts/quota', + method: 'GET', + params: data, + ...options, + }) +} + export function refreshAccountQuota(data: AccountIdParam, options: RequestOptions = {}) { return request({ url: '/api/admin/accounts/quota/refresh', diff --git a/frontend/src/api/modules/accounts/types.ts b/frontend/src/api/modules/accounts/types.ts index bd91fc6d4..0fa8ba05a 100644 --- a/frontend/src/api/modules/accounts/types.ts +++ b/frontend/src/api/modules/accounts/types.ts @@ -2,7 +2,7 @@ import type { RelativeTimeView } from '../../types/time' import type { AccountGroupRef } from '../groups' export type AccountStatus - = 'normal' | 'quota_exhausted' | 'rate_limited' | 'disabled' | 'error' + = 'normal' | 'quota_paused' | 'quota_exhausted' | 'rate_limited' | 'disabled' | 'error' export type AccountErrorReason = 'account_unverified' @@ -12,6 +12,7 @@ export type AccountErrorReason | 'account_banned' export interface AccountQuotaWindow { + accountWide: boolean sourceAccountId?: string | null amount?: { usedDisplay: string, remainingDisplay: string, totalDisplay: string } | null observedAtDisplay?: string | null @@ -51,6 +52,7 @@ export interface AccountQuota { rateLimitedUntil: string | null rateLimitRecoveryDisplay: string | null rateLimitReason: 'upstream_rate_limit' | 'error_protection' | null + pausedWindows: string[] protectionRules: AccountProtectionRule[] recoveryProbeRequired: boolean windows: AccountQuotaWindow[] @@ -138,6 +140,7 @@ export interface AccountModelAccess { } export interface Account { + quotaLimits: Record autoUseQuotaCredits: boolean upstream: AccountUpstream | null capabilities: AccountCapabilities @@ -200,6 +203,7 @@ export interface AccountUpstream { } export interface AccountCapabilities { + quotaLimitsSupported: boolean quotaCredits: boolean quota: boolean quotaRefresh: boolean diff --git a/frontend/src/api/modules/dashboard.ts b/frontend/src/api/modules/dashboard.ts index 3fd9bc1ea..d6724b2fc 100644 --- a/frontend/src/api/modules/dashboard.ts +++ b/frontend/src/api/modules/dashboard.ts @@ -166,6 +166,7 @@ export interface DashboardAccountUsage { export interface DashboardPoolSummary { total: number normal: number + quotaPaused: number quotaExhausted: number rateLimited: number disabled: number diff --git a/frontend/src/i18n/locales/en/accounts.json b/frontend/src/i18n/locales/en/accounts.json index baba66223..999a9b42b 100644 --- a/frontend/src/i18n/locales/en/accounts.json +++ b/frontend/src/i18n/locales/en/accounts.json @@ -1,5 +1,17 @@ { "accounts": { + "quotaLimits": { + "badge": "Quota paused", + "title": "General quota scheduling limits", + "reached": "Scheduling limit reached: {windows}", + "expectedReset": "Expected reset", + "windowReset": "{window} reset", + "recovery": "Wait for usage to reset or adjust the window limit.", + "help": "Pause at any window limit. Resume when all are below their limits.", + "unlimited": "No limit", + "empty": "No general quota windows observed", + "invalid": "Enter a whole number from 1 to 100 or leave blank for no limit" + }, "quota": { "general": "General quota", "usageInThisWindow": "Usage in this window: {localUsageDisplay}", diff --git a/frontend/src/i18n/locales/en/dashboard.json b/frontend/src/i18n/locales/en/dashboard.json index 7c768a587..58329949f 100644 --- a/frontend/src/i18n/locales/en/dashboard.json +++ b/frontend/src/i18n/locales/en/dashboard.json @@ -14,12 +14,12 @@ }, "accountPool": { "empty": "No account pool data", - "quotaExhausted": "Quota exhausted", + "quotaLimited": "Quota limited", "rateLimited": "Rate limited", "pending": "Pending", "issueCountsEmpty": "Disabled: — · Errors: —", "availableDescription": "Account is currently available", - "exhaustedDescription": "Account quota has been exhausted", + "limitedQuotaDescription": "Quota exhausted or scheduling limit reached", "limitedDescription": "Account requests are temporarily restricted", "issueCounts": "Disabled: {disabled} · Errors: {error}", "title": "Account status", diff --git a/frontend/src/i18n/locales/zh-Hans/accounts.json b/frontend/src/i18n/locales/zh-Hans/accounts.json index 35f340bba..00c2e8494 100644 --- a/frontend/src/i18n/locales/zh-Hans/accounts.json +++ b/frontend/src/i18n/locales/zh-Hans/accounts.json @@ -1,5 +1,17 @@ { "accounts": { + "quotaLimits": { + "badge": "额度暂停", + "title": "通用额度调度上限", + "reached": "{windows}已达调度上限", + "expectedReset": "预计重置", + "windowReset": "{window}预计重置", + "recovery": "等待额度恢复,或调整窗口上限", + "help": "任一窗口达限即暂停调度,均低于上限后恢复", + "unlimited": "不限制", + "empty": "没有已观测的通用额度窗口", + "invalid": "请输入 1~100 的整数,留空表示不限制" + }, "quota": { "general": "通用额度", "usageInThisWindow": "窗口消耗:{localUsageDisplay}", diff --git a/frontend/src/i18n/locales/zh-Hans/dashboard.json b/frontend/src/i18n/locales/zh-Hans/dashboard.json index 10070646d..d8f71fd02 100644 --- a/frontend/src/i18n/locales/zh-Hans/dashboard.json +++ b/frontend/src/i18n/locales/zh-Hans/dashboard.json @@ -14,12 +14,12 @@ }, "accountPool": { "empty": "暂无账号池观测", - "quotaExhausted": "配额耗尽", + "quotaLimited": "额度受限", "rateLimited": "限流中", "pending": "待处理", "issueCountsEmpty": "停用 — · 错误 —", "availableDescription": "账号当前可用", - "exhaustedDescription": "账号额度已耗尽", + "limitedQuotaDescription": "额度耗尽或达到调度上限", "limitedDescription": "账号请求暂时受限", "issueCounts": "停用 {disabled} · 错误 {error}", "title": "账号状态", diff --git a/frontend/src/i18n/locales/zh-Hant/accounts.json b/frontend/src/i18n/locales/zh-Hant/accounts.json index 1e84d007b..211acca35 100644 --- a/frontend/src/i18n/locales/zh-Hant/accounts.json +++ b/frontend/src/i18n/locales/zh-Hant/accounts.json @@ -1,5 +1,17 @@ { "accounts": { + "quotaLimits": { + "badge": "額度暫停", + "title": "通用額度調度上限", + "reached": "{windows}已達調度上限", + "expectedReset": "預計重置", + "windowReset": "{window}預計重置", + "recovery": "等待額度恢復,或調整視窗上限", + "help": "任一視窗達限即暫停調度,均低於上限後恢復", + "unlimited": "不限制", + "empty": "沒有已觀測的通用額度視窗", + "invalid": "請輸入 1~100 的整數,留空表示不限制" + }, "quota": { "general": "通用額度", "usageInThisWindow": "窗口消耗:{localUsageDisplay}", diff --git a/frontend/src/i18n/locales/zh-Hant/dashboard.json b/frontend/src/i18n/locales/zh-Hant/dashboard.json index e6ae9ed50..2ae438355 100644 --- a/frontend/src/i18n/locales/zh-Hant/dashboard.json +++ b/frontend/src/i18n/locales/zh-Hant/dashboard.json @@ -14,12 +14,12 @@ }, "accountPool": { "empty": "暫無賬號池觀測", - "quotaExhausted": "配額耗盡", + "quotaLimited": "額度受限", "rateLimited": "限流中", "pending": "待處理", "issueCountsEmpty": "停用 — · 錯誤 —", "availableDescription": "賬號當前可用", - "exhaustedDescription": "賬號額度已耗盡", + "limitedQuotaDescription": "額度耗盡或達到調度上限", "limitedDescription": "賬號請求暫時受限", "issueCounts": "停用 {disabled} · 錯誤 {error}", "title": "賬號狀態", diff --git a/frontend/src/views/accounts/components/AccountConnectionTestModal.vue b/frontend/src/views/accounts/components/AccountConnectionTestModal.vue index dbfcd33c7..24618add6 100644 --- a/frontend/src/views/accounts/components/AccountConnectionTestModal.vue +++ b/frontend/src/views/accounts/components/AccountConnectionTestModal.vue @@ -60,6 +60,7 @@ function connectionLogClass(tone: string) { > [ }, { label: t('accounts.overview.quotaLimited'), - value: formatInteger((props.summary.quotaExhausted ?? 0) + (props.summary.rateLimited ?? 0)), + value: formatInteger(props.summary.quotaPaused + (props.summary.quotaExhausted ?? 0) + (props.summary.rateLimited ?? 0)), caption: t('accounts.overview.waitingForQuota'), tone: 'warning', icon: Gauge, diff --git a/frontend/src/views/accounts/components/account-quota-panel/Entry.vue b/frontend/src/views/accounts/components/account-quota-panel/Entry.vue index 2aaaeffef..efc307234 100644 --- a/frontend/src/views/accounts/components/account-quota-panel/Entry.vue +++ b/frontend/src/views/accounts/components/account-quota-panel/Entry.vue @@ -63,7 +63,7 @@ const items = computed(() => props.windows.map((window) => { class="grid min-w-0 gap-3" :class="grouped ? 'grid-cols-2' : 'grid-cols-1'" > -
+