diff --git a/backend/crates/gateway-admin/src/use_case/credential_mutation.rs b/backend/crates/gateway-admin/src/use_case/credential_mutation.rs index 32ddff010..dee836f75 100644 --- a/backend/crates/gateway-admin/src/use_case/credential_mutation.rs +++ b/backend/crates/gateway-admin/src/use_case/credential_mutation.rs @@ -63,7 +63,10 @@ pub(super) fn observe_account_quotas( continue; } }; - if !account.enabled || &account.provider_kind != provider.provider_kind() { + if &account.provider_kind != provider.provider_kind() + || (!account.enabled + && provider.supports_peer_connection(&account.authentication_kind)) + { continue; } // 后台查询与手动刷新共用认证能力分派,互联协议由 Admin 解释 diff --git a/backend/crates/gateway-admin/src/use_case/peer_link/upstream/service.rs b/backend/crates/gateway-admin/src/use_case/peer_link/upstream/service.rs index f50a75232..f7864085c 100644 --- a/backend/crates/gateway-admin/src/use_case/peer_link/upstream/service.rs +++ b/backend/crates/gateway-admin/src/use_case/peer_link/upstream/service.rs @@ -209,7 +209,7 @@ impl PeerInfoService { if context.cancellation().is_cancelled() { break; } - let accounts = match self.accounts.list_for_provider(provider).await { + let accounts = match self.accounts.list_for_provider(provider, false).await { Ok(accounts) => accounts, Err(error) => { failure.get_or_insert(error); diff --git a/backend/crates/gateway-admin/tests/use_case/credentials/peer.rs b/backend/crates/gateway-admin/tests/use_case/credentials/peer.rs index ceef8061f..e202c07a9 100644 --- a/backend/crates/gateway-admin/tests/use_case/credentials/peer.rs +++ b/backend/crates/gateway-admin/tests/use_case/credentials/peer.rs @@ -26,14 +26,17 @@ use super::super::{ async fn imported_peer_accounts_should_start_observation_without_waiting_for_network() { let events = events(); let provider = FakeProviderAdmin::new("openai", events.clone()); - provider.set_import_account_ids(&["acct_first", "acct_second"]); + provider.set_import_account_ids(&["acct_disabled", "acct_first", "acct_second"]); let mut first = account_record("openai"); first.id = "acct_first".into(); first.authentication_kind = "api_key".into(); let mut second = first.clone(); second.id = "acct_second".into(); let store = FakeAccountStore::with_account(first.clone(), events); - store.set_accounts(vec![first, second]); + let mut disabled = first.clone(); + disabled.id = "acct_disabled".into(); + disabled.enabled = false; + store.set_accounts(vec![disabled, first, second]); let peer = Arc::new(PendingPeer::default()); let services = AdminHarness::new() .provider(provider.clone()) @@ -59,8 +62,8 @@ async fn imported_peer_accounts_should_start_observation_without_waiting_for_net .expect("import must not wait for peer response") .expect("import committed"); peer.wait_for_requests(1).await; - assert_eq!(peer.changed.lock().unwrap().len(), 2); - assert_eq!(result.credential_ids.len(), 2); + assert_eq!(peer.changed.lock().unwrap().len(), 3); + assert_eq!(result.credential_ids.len(), 3); assert!(provider.quota_requests().is_empty()); peer.gate.add_permits(2); peer.wait_for_requests(2).await; @@ -72,11 +75,13 @@ async fn imported_peer_accounts_should_start_observation_without_waiting_for_net } #[tokio::test] -async fn native_import_should_use_provider_quota_when_peer_service_is_available() { +async fn disabled_native_account_should_observe_quota_when_peer_service_is_available() { let events = events(); let provider = FakeProviderAdmin::new("openai", events.clone()); provider.set_import_account_ids(&["acct_test"]); - let store = FakeAccountStore::new("openai", events); + let mut account = account_record("openai"); + account.enabled = false; + let store = FakeAccountStore::with_account(account, events); let peer = Arc::new(PendingPeer::default()); let services = AdminHarness::new() .provider(provider.clone()) diff --git a/backend/crates/gateway-admin/tests/use_case/peer_link/upstream/mod.rs b/backend/crates/gateway-admin/tests/use_case/peer_link/upstream/mod.rs index 426d39b5d..afbac2176 100644 --- a/backend/crates/gateway-admin/tests/use_case/peer_link/upstream/mod.rs +++ b/backend/crates/gateway-admin/tests/use_case/peer_link/upstream/mod.rs @@ -467,6 +467,7 @@ impl ProviderAccountStore for TestAccounts { async fn list_for_provider( &self, provider: &ProviderKind, + include_disabled: bool, ) -> Result, StoreError> { if Some(provider.as_str()) == self.failed_provider { return Err(StoreError::new(StoreErrorKind::Unavailable)); @@ -476,7 +477,9 @@ impl ProviderAccountStore for TestAccounts { .lock() .unwrap() .iter() - .filter(|account| account.provider() == provider) + .filter(|account| { + account.provider() == provider && (include_disabled || account.enabled()) + }) .cloned() .collect()) } diff --git a/backend/crates/gateway-core/src/account/store.rs b/backend/crates/gateway-core/src/account/store.rs index e6eb849c9..83f3d6ea1 100644 --- a/backend/crates/gateway-core/src/account/store.rs +++ b/backend/crates/gateway-core/src/account/store.rs @@ -88,9 +88,11 @@ pub trait ProviderAccountStore: Send + Sync { async fn list_accounts(&self) -> Result, StoreError>; + /// 额度维护可包含停用账号,请求调度只读取已启用账号 async fn list_for_provider( &self, provider: &ProviderKind, + include_disabled: bool, ) -> Result, StoreError>; /// 只读取指定 Provider 冻结范围内的已启用账号,空范围直接返回空池 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 b4d4be6aa..5ee35e92f 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 @@ -112,8 +112,9 @@ impl ProviderAccountStore for PgProviderAccountRepository { async fn list_for_provider( &self, provider: &ProviderKind, + include_disabled: bool, ) -> Result, CoreStoreError> { - self.list_provider_accounts(Some(provider.as_str()), false) + self.list_provider_accounts(Some(provider.as_str()), include_disabled) .await .map_err(core_store_error)? .into_iter() 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 d3a84334b..645c1942c 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/repository.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/repository.rs @@ -854,9 +854,11 @@ pub(crate) async fn rotate_provider_account_in_transaction( profile: &UpdateProviderAccount, replacement_identity: Option<&ProviderAccountIdentity>, update: &ProviderCredentialUpdate, - preserve_name: bool, + reauthorization: bool, ) -> StoreResult { let replace_identity = replacement_identity.is_some(); + // 同身份重新授权会更新账号资料,额度及本周期的预热进度仍属于该身份 + let preserve_quota = !replace_identity && (reauthorization || update.preserve_profile); let upstream_user_id = replacement_identity.map(ProviderAccountIdentity::upstream_user_id); let upstream_account_id = replacement_identity.and_then(ProviderAccountIdentity::upstream_account_id); @@ -866,8 +868,11 @@ 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, - quota_warmup_state = case when $14 then quota_warmup_state else '{}'::jsonb end, quota_warmup_revision = provider_accounts.quota_warmup_revision + 1, 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_warmup_state = case when $18 then quota_warmup_state else '{}'::jsonb end, + quota_warmup_revision = provider_accounts.quota_warmup_revision + 1, + provider_quota_json = case when $18 then provider_quota_json else null end, + quota_paused = case when $18 then quota_paused else false end, + quota_observed_at = case when $18 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, quota_access_observed_at = case when $11 then null else quota_access_observed_at end, @@ -910,8 +915,9 @@ pub(crate) async fn rotate_provider_account_in_transaction( .bind(upstream_account_id) .bind(update.preserve_profile) .bind(update.preserve_credential_state) - .bind(preserve_name) + .bind(reauthorization) .bind(update.preserve_access_token_expiry) + .bind(preserve_quota) .fetch_optional(&mut **transaction) .await .map_err(|error| { @@ -1180,7 +1186,7 @@ pub(super) async fn import_provider_accounts_in_transaction( pub(super) async fn rotate_provider_account_admin_in_transaction( transaction: &mut Transaction<'_, Postgres>, command: RotateProviderAccount, - preserve_name: bool, + reauthorization: bool, ) -> StoreResult { command.scope.validate()?; require_nonempty(ENTITY, "account_id", &command.profile.id)?; @@ -1209,7 +1215,7 @@ pub(super) async fn rotate_provider_account_admin_in_transaction( &command.profile, command.replacement_identity.as_ref(), &command.credential, - preserve_name, + reauthorization, ) .await?; // 凭据 CAS、普通设置和审计共享事务,任何设置失败都回滚凭据更新 diff --git a/backend/crates/gateway-store/tests/postgres/provider_accounts/authorization.rs b/backend/crates/gateway-store/tests/postgres/provider_accounts/authorization.rs index 323b311f2..5e09eca6b 100644 --- a/backend/crates/gateway-store/tests/postgres/provider_accounts/authorization.rs +++ b/backend/crates/gateway-store/tests/postgres/provider_accounts/authorization.rs @@ -1,5 +1,6 @@ //! 验证账号授权回执的并发幂等、事务回滚与过期清理 +use chrono::SubsecRound; use gateway_admin::model::provider_credentials::{ AuthorizationReceiptKey, PreparedCredentialRotationFacts, }; @@ -281,28 +282,21 @@ async fn expired_receipts_are_unreadable_and_reclaimed_without_removing_accounts database.close().await; } -#[tokio::test] -async fn reauthorization_replay_keeps_the_committed_revision_and_later_profile_edits() { - let Some(database) = TestDatabase::create("reauthorization_receipt").await else { - return; - }; - let store = admin_account_store(&database.pool); - let (seed, context) = command(credential("acct_reauthorize", "reauthorize-user")); - let receipt = store.commit_authorization(seed, &context).await.unwrap(); - let id = receipt.result.account_id.clone(); - let command = AuthorizationCommit { - key: AuthorizationReceiptKey::new( - ProviderKind::new("openai").unwrap(), - "reauthorize-flow", - &context, - ) - .unwrap(), +fn reauthorization( + id: &ProviderAccountId, + context: &MutationContext, + flow_id: &str, + replacement_identity: Option, +) -> AuthorizationCommit { + AuthorizationCommit { + key: AuthorizationReceiptKey::new(ProviderKind::new("openai").unwrap(), flow_id, context) + .unwrap(), pending: PendingAuthorizationMutation::new( ProviderKind::new("openai").unwrap(), AuthorizationMutationTarget::Reauthorize { account_id: id.clone(), }, - AuthorizationOwnerBinding::from_context(&context), + AuthorizationOwnerBinding::from_context(context), ), settings: None, credential: AuthorizationCredentialCommit::Reauthorize(Box::new( @@ -310,10 +304,7 @@ async fn reauthorization_replay_keeps_the_committed_revision_and_later_profile_e account_id: id.clone(), provider_kind: ProviderKind::new("openai").unwrap(), expected_credential_revision: gateway_admin::model::Revision::new(1).unwrap(), - replacement_identity: Some(ProviderAccountIdentity::new( - "new-user".into(), - Some("new-workspace".into()), - )), + replacement_identity, name: "remote profile".into(), email: Some("new@example.com".into()), plan_type: Some("plus".into()), @@ -331,7 +322,109 @@ async fn reauthorization_replay_keeps_the_committed_revision_and_later_profile_e next_refresh_at: None, }, )), + } +} + +#[tokio::test] +async fn reauthorization_keeps_disabled_account_quota_only_for_the_same_identity() { + let Some(database) = TestDatabase::create("reauthorization_quota").await else { + return; }; + let store = admin_account_store(&database.pool); + let repository = PgProviderAccountRepository::new(database.pool.clone()); + for (slot, replacement) in [ + ("acct_same", None), + ( + "acct_rebound", + Some(ProviderAccountIdentity::new( + "new-user".into(), + Some("new-workspace".into()), + )), + ), + ] { + let mut input = credential(slot, slot); + input.enabled = false; + let (seed, context) = command(input); + let id = store + .commit_authorization(seed, &context) + .await + .unwrap() + .result + .account_id; + let observed_at = SystemTime::from(Utc::now().round_subsecs(6)); + let reset_at = Utc::now() + TimeDelta::days(2); + let weekly = json!({"rate_limit":{"secondary_window":{ + "used_percent":42, "limit_window_seconds":604800, "reset_at":reset_at.timestamp() + }}}); + let observation = QuotaObservation { + account_id: id.clone(), + expected_revision: CredentialRevision::new(1).unwrap(), + quota: OpaqueProviderData::new(weekly.as_object().unwrap().clone()), + observed_at, + state: QuotaState::allowed(observed_at), + expected_connection: None, + quota_pause: None, + plan_type: None, + }; + assert_eq!( + repository + .compare_and_swap_quota(observation.clone()) + .await + .unwrap(), + QuotaWriteOutcome::Updated + ); + let same_identity = replacement.is_none(); + store + .commit_authorization(reauthorization(&id, &context, slot, replacement), &context) + .await + .unwrap(); + let account = repository.get_account(&id).await.unwrap().unwrap(); + assert!(!account.enabled()); + assert_eq!(account.email(), Some("new@example.com")); + assert_eq!( + repository + .compare_and_swap_quota(observation.clone()) + .await + .unwrap(), + QuotaWriteOutcome::Conflict + ); + let mut snapshots = repository + .get_quotas(std::slice::from_ref(&id)) + .await + .unwrap(); + if same_identity { + let current = snapshots + .pop() + .expect("same quota window after reauthorization"); + assert_eq!(current.expected_revision, account.revision()); + assert_eq!(current.observed_at, observed_at); + assert_eq!(current.quota, observation.quota); + } else { + assert!(snapshots.is_empty()); + assert_eq!(account.quota(), QuotaState::unknown()); + } + } + database.close().await; +} + +#[tokio::test] +async fn reauthorization_replay_keeps_the_committed_revision_and_later_profile_edits() { + let Some(database) = TestDatabase::create("reauthorization_receipt").await else { + return; + }; + let store = admin_account_store(&database.pool); + let (seed, context) = command(credential("acct_reauthorize", "reauthorize-user")); + let receipt = store.commit_authorization(seed, &context).await.unwrap(); + let id = receipt.result.account_id.clone(); + let command = reauthorization( + &id, + &context, + "reauthorize-flow", + Some(ProviderAccountIdentity::new( + "new-user".into(), + Some("new-workspace".into()), + )), + ); let rename = UpdateAccount { account_id: id.to_string(), name: Some("renamed team".to_owned()), diff --git a/backend/crates/gateway-store/tests/postgres/provider_accounts/core_adapter.rs b/backend/crates/gateway-store/tests/postgres/provider_accounts/core_adapter.rs index 8d451b754..448b333e9 100644 --- a/backend/crates/gateway-store/tests/postgres/provider_accounts/core_adapter.rs +++ b/backend/crates/gateway-store/tests/postgres/provider_accounts/core_adapter.rs @@ -62,7 +62,7 @@ async fn scoped_account_list_filters_ids_provider_and_live_enabled_state() { ["acct_scope_a", "acct_scope_z"] ); let full_pool = repository - .list_for_provider(&provider) + .list_for_provider(&provider, false) .await .expect("load full provider pool"); assert_eq!( @@ -72,6 +72,22 @@ async fn scoped_account_list_filters_ids_provider_and_live_enabled_state() { .collect::>(), ["acct_scope_a", "acct_scope_outside", "acct_scope_z"] ); + let maintenance = repository + .list_for_provider(&provider, true) + .await + .expect("load provider accounts for maintenance"); + assert_eq!( + maintenance + .iter() + .map(|account| account.id().as_str()) + .collect::>(), + [ + "acct_scope_a", + "acct_scope_disabled", + "acct_scope_outside", + "acct_scope_z" + ] + ); let all = repository .list_provider_accounts(None, true) .await diff --git a/backend/crates/gateway-store/tests/postgres/proxies.rs b/backend/crates/gateway-store/tests/postgres/proxies.rs index a3e29519a..da9f3b9ef 100644 --- a/backend/crates/gateway-store/tests/postgres/proxies.rs +++ b/backend/crates/gateway-store/tests/postgres/proxies.rs @@ -272,7 +272,7 @@ async fn disabled_proxy_projects_direct_while_preserving_bindings_and_credential projected.push(accounts.get_account(&id).await.unwrap().unwrap()); projected.push(accounts.load_current_credential(&id).await.unwrap().account); let kind = ProviderKind::new(provider).unwrap(); - projected.extend(accounts.list_for_provider(&kind).await.unwrap()); + projected.extend(accounts.list_for_provider(&kind, false).await.unwrap()); let now = SystemTime::now(); projected.extend( accounts diff --git a/backend/crates/providers/openai/src/credential/catalog/refresh.rs b/backend/crates/providers/openai/src/credential/catalog/refresh.rs index 47367420b..27d90e3e9 100644 --- a/backend/crates/providers/openai/src/credential/catalog/refresh.rs +++ b/backend/crates/providers/openai/src/credential/catalog/refresh.rs @@ -243,7 +243,7 @@ impl CodexCredentialCatalogService { } let revision = self.state_revision()?; let now = SystemTime::now(); - let accounts = self.repository.list_for_provider().await?; + let accounts = self.repository.list_for_provider(false).await?; let current: BTreeMap<_, _> = accounts .into_iter() .filter(|a| eligible_catalog_account(a, now)) diff --git a/backend/crates/providers/openai/src/credential/quota/bucket_warmup.rs b/backend/crates/providers/openai/src/credential/quota/bucket_warmup.rs index 9ca0dd98c..8da70d944 100644 --- a/backend/crates/providers/openai/src/credential/quota/bucket_warmup.rs +++ b/backend/crates/providers/openai/src/credential/quota/bucket_warmup.rs @@ -137,7 +137,7 @@ impl CodexCredentialQuotaService { now: DateTime, ) -> Result { let mut summary = CodexWarmupSummary::default(); - for account in self.repository.list_for_provider().await? { + for account in self.repository.list_for_provider(false).await? { if !warmup::warmup_account_is_available(&account) || !account.quota_settings().has_warmup() { diff --git a/backend/crates/providers/openai/src/credential/quota/scheduling.rs b/backend/crates/providers/openai/src/credential/quota/scheduling.rs index f083faa89..489396ed7 100644 --- a/backend/crates/providers/openai/src/credential/quota/scheduling.rs +++ b/backend/crates/providers/openai/src/credential/quota/scheduling.rs @@ -336,7 +336,7 @@ fn quota_refresh_candidate( snapshot: Option<&CodexAccountQuotaSnapshot>, now: SystemTime, ) -> Option<(ProviderAccount, Option)> { - if !eligible_periodic_quota_refresh(&account, now) { + if !access_token_is_current(&account, now) { return None; } if account.quota().is_exhausted() { @@ -428,14 +428,9 @@ fn insert_projection_entry( ); } -fn eligible_periodic_quota_refresh(account: &ProviderAccount, now: SystemTime) -> bool { - account.enabled() && access_token_is_current(account, now) -} - fn eligible_initial_quota_sync(account: &ProviderAccount, now: SystemTime) -> bool { // 首次观察只兜底刚入库、尚无 quota 快照的账号 // 已耗尽等运行时状态必须由 // periodic 路径处理,才能保留同一账号的最小复核间隔 - account.credential_state() == CredentialState::Ready - && eligible_periodic_quota_refresh(account, now) + account.credential_state() == CredentialState::Ready && access_token_is_current(account, now) } diff --git a/backend/crates/providers/openai/src/credential/quota/service.rs b/backend/crates/providers/openai/src/credential/quota/service.rs index a3761d3bb..526089b42 100644 --- a/backend/crates/providers/openai/src/credential/quota/service.rs +++ b/backend/crates/providers/openai/src/credential/quota/service.rs @@ -131,7 +131,7 @@ impl CodexCredentialQuotaService { &self, now: SystemTime, ) -> Result { - let mut accounts = self.repository.list_for_provider().await?; + let mut accounts = self.repository.list_for_provider(true).await?; accounts.retain(|account| { account.authentication_kind() == crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH }); diff --git a/backend/crates/providers/openai/src/credential/quota/warmup.rs b/backend/crates/providers/openai/src/credential/quota/warmup.rs index 23abe5038..caeff8b31 100644 --- a/backend/crates/providers/openai/src/credential/quota/warmup.rs +++ b/backend/crates/providers/openai/src/credential/quota/warmup.rs @@ -121,7 +121,7 @@ impl CodexCredentialQuotaService { &self, model: &str, ) -> Result { - let mut accounts = self.repository.list_for_provider().await?; + let mut accounts = self.repository.list_for_provider(false).await?; accounts.retain(warmup_account_is_available); let mut summary = CodexWarmupSummary::default(); if accounts.is_empty() { diff --git a/backend/crates/providers/openai/src/credential/repository.rs b/backend/crates/providers/openai/src/credential/repository.rs index 8dbe8f7b6..026ddf064 100644 --- a/backend/crates/providers/openai/src/credential/repository.rs +++ b/backend/crates/providers/openai/src/credential/repository.rs @@ -136,12 +136,13 @@ impl CodexCredentialRepository { pub async fn list_for_provider( &self, + include_disabled: bool, ) -> Result, CredentialRepositoryError> { let provider = ProviderKind::new(PROVIDER_NAME).map_err(|source| { CredentialRepositoryError::InvalidCredentialData(Some(ErrorSource::new(source))) })?; self.store - .list_for_provider(&provider) + .list_for_provider(&provider, include_disabled) .await .map_err(Into::into) } diff --git a/backend/crates/providers/openai/src/credential/selector.rs b/backend/crates/providers/openai/src/credential/selector.rs index 3e80b8078..705c9cbfc 100644 --- a/backend/crates/providers/openai/src/credential/selector.rs +++ b/backend/crates/providers/openai/src/credential/selector.rs @@ -594,7 +594,7 @@ impl CodexCredentialSelector { .collect()); } if diagnostic { - return Ok(self.repository.list_for_provider().await?); + return Ok(self.repository.list_for_provider(false).await?); } let account_ids: Vec<_> = attempt .account_scope() diff --git a/backend/crates/providers/openai/tests/credential/quota/initial_sync.rs b/backend/crates/providers/openai/tests/credential/quota/initial_sync.rs index c5aab0413..e4921173f 100644 --- a/backend/crates/providers/openai/tests/credential/quota/initial_sync.rs +++ b/backend/crates/providers/openai/tests/credential/quota/initial_sync.rs @@ -72,9 +72,9 @@ fn local_service( } #[tokio::test] -async fn zero_initial_delay_keeps_immediate_first_observation() { +async fn disabled_account_without_quota_is_observed_when_initial_delay_expires() { let store = Arc::new(MemoryAccountStore::default()); - create_account(&store, "acct_initial_zero").await; + create_account_with_enabled(&store, "acct_initial_zero", false).await; let server = MockServer::start().await; mount_usage(&server, 200).await; let service = local_service(&store, &server, zero_delays()); diff --git a/backend/crates/providers/openai/tests/credential/quota/refresh_timing.rs b/backend/crates/providers/openai/tests/credential/quota/refresh_timing.rs index 44058a4d2..cee70859c 100644 --- a/backend/crates/providers/openai/tests/credential/quota/refresh_timing.rs +++ b/backend/crates/providers/openai/tests/credential/quota/refresh_timing.rs @@ -278,10 +278,10 @@ async fn exhausted_reset_refreshes_quickly_then_backs_off_and_recovers_from_usag } #[tokio::test] -async fn allowed_account_with_expired_window_synchronizes_at_reset_grace() { +async fn disabled_account_with_expired_window_synchronizes_at_reset_grace() { let mut now = SystemTime::now(); let store = Arc::new(MemoryAccountStore::default()); - create_account(&store, "acct_allowed_expired_window").await; + create_account_with_enabled(&store, "acct_allowed_expired_window", false).await; let account = store .account("acct_allowed_expired_window") .expect("account"); diff --git a/backend/crates/providers/openai/tests/support.rs b/backend/crates/providers/openai/tests/support.rs index 73d0515d5..f3e00f102 100644 --- a/backend/crates/providers/openai/tests/support.rs +++ b/backend/crates/providers/openai/tests/support.rs @@ -474,6 +474,7 @@ impl ProviderAccountStore for MemoryAccountStore { async fn list_for_provider( &self, provider: &ProviderKind, + include_disabled: bool, ) -> Result, StoreError> { self.provider_list_reads.fetch_add(1, Ordering::SeqCst); if self.fail_provider_listing.load(Ordering::SeqCst) { @@ -485,13 +486,15 @@ impl ProviderAccountStore for MemoryAccountStore { ), )); } - // 与 Postgres 实现的调度列表语义一致:停用账号不进入常规候选 Ok(self .accounts .lock() .expect("account store lock") .values() - .filter(|stored| stored.account.provider() == provider && stored.account.enabled()) + .filter(|stored| { + stored.account.provider() == provider + && (include_disabled || stored.account.enabled()) + }) .map(|stored| stored.account.clone()) .collect()) } diff --git a/backend/crates/providers/xai/src/credential/quota.rs b/backend/crates/providers/xai/src/credential/quota.rs index 074df75df..0697a4d9d 100644 --- a/backend/crates/providers/xai/src/credential/quota.rs +++ b/backend/crates/providers/xai/src/credential/quota.rs @@ -413,11 +413,10 @@ impl GrokCredentialQuotaService { .load_current(account_id) .await .map_err(map_quota_repository_error)?; - if !loaded.account.enabled() - || loaded - .account - .access_token_expires_at() - .is_none_or(|expires_at| expires_at <= SystemTime::now()) + if loaded + .account + .access_token_expires_at() + .is_none_or(|expires_at| expires_at <= SystemTime::now()) { return Err(GrokQuotaError::AccountUnavailable); } diff --git a/backend/crates/providers/xai/src/credential/repository.rs b/backend/crates/providers/xai/src/credential/repository.rs index f9e017cb4..977edf16a 100644 --- a/backend/crates/providers/xai/src/credential/repository.rs +++ b/backend/crates/providers/xai/src/credential/repository.rs @@ -513,7 +513,7 @@ impl GrokCredentialRepository { })?; let accounts = self .store - .list_for_provider(&provider) + .list_for_provider(&provider, false) .await .map_err(map_store_error)?; let mut loaded = Vec::with_capacity(accounts.len()); @@ -535,7 +535,7 @@ impl GrokCredentialRepository { })?; let accounts = self .store - .list_for_provider(&provider) + .list_for_provider(&provider, false) .await .map_err(map_store_error)?; for account in &accounts { diff --git a/backend/crates/providers/xai/src/provider/workers.rs b/backend/crates/providers/xai/src/provider/workers.rs index 8ca7b76f1..5207e88a4 100644 --- a/backend/crates/providers/xai/src/provider/workers.rs +++ b/backend/crates/providers/xai/src/provider/workers.rs @@ -150,7 +150,7 @@ impl ScheduledTask for XaiQuotaCatalogTask { Box::pin(async move { let accounts = self .accounts - .list_for_provider(&self.provider_kind) + .list_for_provider(&self.provider_kind, true) .await .map_err(|source| WorkerTaskError::safe("账号列表读取失败").with_source(source))?; let mut failures = QuotaCatalogFailure::default(); @@ -243,10 +243,9 @@ impl XaiQuotaCatalogTask { } pub(super) fn eligible_quota_worker_account(account: &ProviderAccount, now: SystemTime) -> bool { - account.enabled() - && account - .access_token_expires_at() - .is_some_and(|expires_at| expires_at > now) + account + .access_token_expires_at() + .is_some_and(|expires_at| expires_at > now) && account .quota() .exhaustion_refresh_due(now, EXHAUSTED_QUOTA_FALLBACK_RECHECK_INTERVAL) diff --git a/backend/crates/providers/xai/tests/admin.rs b/backend/crates/providers/xai/tests/admin.rs index bc6967280..553a80a13 100644 --- a/backend/crates/providers/xai/tests/admin.rs +++ b/backend/crates/providers/xai/tests/admin.rs @@ -219,7 +219,8 @@ async fn xai_quota_catalog_worker_retains_both_failure_stages_and_finishes_the_b for refresh_due in [true, false] { let store = MemoryProviderAccountStore::shared(); for suffix in ["broken_one", "broken_two"] { - let input = create_input(suffix, "synthetic-subject"); + let mut input = create_input(suffix, "synthetic-subject"); + input.enabled = suffix == "broken_one"; let mut account = crate::support::prepare_input(&input).unwrap(); // 模拟历史持久化凭据损坏,额度与目录读取均应保留各自的失败分类 account.credential = gateway_core::account::PlaintextCredential::new(Map::new()); diff --git a/backend/crates/providers/xai/tests/credential/quota.rs b/backend/crates/providers/xai/tests/credential/quota.rs index c0a186376..b555c6344 100644 --- a/backend/crates/providers/xai/tests/credential/quota.rs +++ b/backend/crates/providers/xai/tests/credential/quota.rs @@ -709,21 +709,20 @@ async fn quota_read_rejects_corrupt_provider_document() { } #[tokio::test] -async fn disabled_account_quota_refresh_never_calls_upstream() { +async fn disabled_account_refreshes_quota_without_enabling_scheduling() { let (store, repository) = repository_with_accounts(&[("disabled-quota", "subject-disabled")]).await; + let id = account_id("disabled-quota"); store - .set_enabled(&account_id("disabled-quota"), false) + .set_enabled(&id, false) .await .expect("disable account"); - let transport = QueueBillingTransport::success(br#"{"config":null}"#); - let service = crate::support::grok_quota_service(repository, transport.clone()); + let transport = QueueBillingTransport::success(br#"{"config":{"creditUsagePercent":37.5}}"#); + let service = crate::support::grok_quota_service(repository, transport); - assert!(matches!( - service.refresh_account(&account_id("disabled-quota")).await, - Err(GrokQuotaError::AccountUnavailable) - )); - assert_eq!(transport.calls.load(Ordering::SeqCst), 0); + let snapshot = service.refresh_account(&id).await.expect("refresh quota"); + assert_eq!(snapshot.billing().used_percent(), Some(37.5)); + assert!(!store.account(&id).expect("account").enabled()); } #[tokio::test] diff --git a/backend/crates/providers/xai/tests/support.rs b/backend/crates/providers/xai/tests/support.rs index eb3962837..d0a79ef0c 100644 --- a/backend/crates/providers/xai/tests/support.rs +++ b/backend/crates/providers/xai/tests/support.rs @@ -356,14 +356,17 @@ impl ProviderAccountStore for MemoryProviderAccountStore { async fn list_for_provider( &self, provider: &ProviderKind, + include_disabled: bool, ) -> Result, StoreError> { if self.fail_provider_listing.load(Ordering::SeqCst) { return Err(invalid()); } - // 与 Postgres 实现的调度列表语义一致:停用账号不进入常规候选 Ok(lock(&self.accounts) .values() - .filter(|stored| stored.account.provider() == provider && stored.account.enabled()) + .filter(|stored| { + stored.account.provider() == provider + && (include_disabled || stored.account.enabled()) + }) .map(|stored| stored.account.clone()) .collect()) } diff --git a/docs/api.md b/docs/api.md index 0c9f948ae..76b752957 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1795,7 +1795,8 @@ OpenAI 授权码交换与令牌刷新请求的连接超时为 30 秒,单次上 `refreshToken`。刷新响应中的三个 token 字段均按官方语义独立轮换:返回新值时替换,省略时分别保留 现值。回调地址只承载 `code`/`state`,不以 host/path 形式作为拒绝条件 - OpenAI 重新授权允许登录另一个上游账号。保留本地账号 ID、名称和调度设置,按新授权更新令牌、 - 上游用户与工作区 ID、邮箱和套餐。换号时清除旧账号的额度快照和耗尽状态,新额度由后台重新查询。 + 上游用户与工作区 ID、邮箱和套餐。同一用户和工作区保留最近的额度快照,后台查询成功后按上游窗口更新。 + 用户或工作区变更时清除原身份的额度快照和耗尽状态。 无法识别新用户或新身份已绑定其他记录时,原账号保持不变 - OAuth 账号文件导入和 OAuth complete(包括重新授权)在 credential 提交后后台尝试一次额度观测,不等待 观测完成才返回成功。观测失败只记录告警,不回滚已提交的账号;手工或后台 RT 刷新只更新 token, @@ -1813,8 +1814,8 @@ OpenAI 授权码交换与令牌刷新请求的连接超时为 30 秒,单次上 本次耗尽之后的已记录窗口 reset 全部到期后,新查询明确 `allowed=true` 可解除限制,即使用量仍为 100%。未知 reset 或再次拒绝后残留的旧 reset 仍走原规则,不复用旧边界解封;时间到期本身不会 解除限制,也不会将展示用量归零 -- 账号 `enabled` 控制是否参与请求调度,不控制 OAuth 凭据续期。OpenAI 与 xAI 的停用账号仍按各自刷新 - 策略维护 Token;刷新结果更新凭据状态,但不会启用调度。无 refresh token 或凭据已进入失效、无效、 +- 停用的 OpenAI 与 xAI OAuth 账号退出客户端请求调度,仍按各自策略续期 Token、查询额度。 + 成功刷新后账号保持停用。无 refresh token 或凭据已进入失效、无效、 封禁状态的账号不参加后台自动续期 - `POST /api/admin/accounts/recover` 对停用账号只将 `enabled` 改为 `true`,保留已有额度快照、凭据、错误和 Redis cooldown;启用后仍按这些事实投影状态,不会把已有错误或耗尽改成正常。对已启用账号则执行强制恢复: diff --git a/docs/architecture.md b/docs/architecture.md index 18979a4ec..f1846e26a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -999,8 +999,9 @@ credential 与 quota 是两组独立事实:credential refresh 不等于 quota 团队身份不推断为 Free,订阅查询失败不影响额度观测 普通 Token 续期与刷新退避保留提交时的账号资料及额度快照,显式凭据轮换仍按原子提交合同失效旧观测。 xAI Provider 在缺少可展示上游额度时投影本地 24 小时滚动统计,Admin 按该窗口展示日用量,额度预测使用完整周/月窗口 -- 账号导入和 OAuth complete(包括重新授权)在 credential 提交、Provider 事实失效及快照发布后, +- 账号导入和 OAuth complete(包括重新授权)在凭据提交、Provider 缓存失效与运行快照发布后, 由 Admin 共用流程后台读取一次额度;不等待观测完成才返回管理请求,失败记录告警但不回滚账号事务。 + 同身份重新授权在事务内保留额度观测和按桶预热进度,旧凭据版本的在途观测无法覆盖新版本。 手工和后台 credential refresh 仍不隐式刷新 quota - quota refresh、正常推理返回的 rate-limit headers 和后台健康任务汇入同一额度事实;Provider 使用套餐 事实进行展示、目录 cache 隔离和请求资格检查,不创建套餐专属状态机。