diff --git a/backend/crates/gateway-core/src/account/store.rs b/backend/crates/gateway-core/src/account/store.rs index 83f3d6ea1..cef5eec3e 100644 --- a/backend/crates/gateway-core/src/account/store.rs +++ b/backend/crates/gateway-core/src/account/store.rs @@ -160,6 +160,14 @@ pub trait ProviderAccountStore: Send + Sync { .collect()) } + /// 批量返回在各自额度快照之后有成功生成请求完成的账号 + async fn accounts_used_since_quota( + &self, + _snapshots: &[QuotaObservationVersion], + ) -> Result, StoreError> { + Err(StoreError::new(crate::error::StoreErrorKind::InvalidData)) + } + async fn compare_and_swap_quota( &self, observation: QuotaObservation, 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 599cc5d4a..7880ee898 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 @@ -401,6 +401,13 @@ impl ProviderAccountStore for PgProviderAccountRepository { super::quota::versions(self, accounts).await } + async fn accounts_used_since_quota( + &self, + snapshots: &[gateway_core::account::QuotaObservationVersion], + ) -> Result, CoreStoreError> { + super::quota::accounts_used_since_quota(self, snapshots).await + } + async fn apply_quota_access( &self, change: QuotaAccessChange, diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/quota/document.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/quota/document.rs index c5388470a..2c98be266 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/quota/document.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/quota/document.rs @@ -19,6 +19,35 @@ pub(in crate::postgres::provider_accounts) async fn versions( .map_err(crate::core_store_error) } +pub(in crate::postgres::provider_accounts) async fn accounts_used_since_quota( + repository: &PgProviderAccountRepository, + snapshots: &[QuotaObservationVersion], +) -> Result, CoreStoreError> { + let (ids, times): (Vec<_>, Vec<_>) = snapshots + .iter() + .map(|s| (s.account_id.as_str(), DateTime::::from(s.observed_at))) + .unzip(); + // 按账号与完成时间探测共享索引,跨实例及重启复用已记录的请求事实 + let active: Vec = sqlx::query_scalar( + "select s.id from unnest($1::text[], $2::timestamptz[]) as s(id, observed_at) + where exists (select 1 from request_analytics_facts r + where r.provider_account_ref = s.id and r.completed_at > s.observed_at + and r.outcome = 'succeeded' and r.operation = 'generate')", + ) + .bind(ids) + .bind(times) + .fetch_all(&repository.pool) + .await + .map_err(database_error)?; + active + .into_iter() + .map(|id| { + CoreProviderAccountId::new(id) + .map_err(|e| CoreStoreError::caused_by(CoreStoreErrorKind::InvalidData, e)) + }) + .collect() +} + pub(in crate::postgres::provider_accounts) async fn write( repository: &PgProviderAccountRepository, observation: QuotaObservation, diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/quota/mod.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/quota/mod.rs index 46ae44873..69e9ee7e7 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/quota/mod.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/quota/mod.rs @@ -5,6 +5,6 @@ mod forecast; mod history; mod warmup; -pub(super) use document::{versions, write}; +pub(super) use document::{accounts_used_since_quota, versions, write}; pub(super) use forecast::load_history; pub(super) use history::documents; 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 448b333e9..56aedf2b0 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 @@ -2,6 +2,56 @@ use super::*; +#[tokio::test] +async fn quota_activity_uses_successful_generation_completion_after_each_snapshot() { + use gateway_core::account::QuotaObservationVersion; + let Some(database) = TestDatabase::create("quota_generation_activity").await else { + return; + }; + let repo = PgProviderAccountRepository::new(database.pool.clone()); + let start = Utc::now() - TimeDelta::minutes(10); + let mut snapshots = Vec::new(); + for (name, operation, outcome, offset_ms) in [ + ("acct_active", "generate", "succeeded", 500), + ("acct_observed", "generate", "succeeded", 1000), + ("acct_count", "count_tokens", "succeeded", 0), + ("acct_failed", "generate", "failed", 0), + ] { + seed_model_request( + &database.pool, + ModelRequestSeed { + request_id: name, + account_id: name, + provider_kind: "antigravity", + model: "fixture-model", + total_tokens: 5, + cost_amount: "0", + started_at: start, + }, + ) + .await + .unwrap(); + sqlx::query("update model_requests set operation=$2, outcome=$3 where id=$1") + .bind(name) + .bind(operation) + .bind(outcome) + .execute(&database.pool) + .await + .unwrap(); + snapshots.push(QuotaObservationVersion { + account_id: ProviderAccountId::new(name).unwrap(), + credential_revision: CredentialRevision::new(1).unwrap(), + observed_at: (start + TimeDelta::milliseconds(offset_ms)).into(), + }); + } + super::super::drain_analytics(&database.pool).await; + assert_eq!( + repo.accounts_used_since_quota(&snapshots).await.unwrap(), + vec![ProviderAccountId::new("acct_active").unwrap()] + ); + database.close().await; +} + #[tokio::test] async fn scoped_account_list_empty_scope_does_not_use_database() { let pool = sqlx::postgres::PgPoolOptions::new() diff --git a/backend/crates/providers/antigravity/src/credential/quota/service.rs b/backend/crates/providers/antigravity/src/credential/quota/service.rs index fb238e669..0ad90ff8f 100644 --- a/backend/crates/providers/antigravity/src/credential/quota/service.rs +++ b/backend/crates/providers/antigravity/src/credential/quota/service.rs @@ -250,13 +250,13 @@ impl QuotaService { &self, cancel: &CancellationToken, ) -> Result<(), WorkerTaskError> { - let mut accounts = self + let accounts = self .accounts .list_for_provider(&self.kind, false) .await .map_err(|e| WorkerTaskError::safe("读取 Antigravity 账号失败").with_source(e))?; let ids: Vec<_> = accounts.iter().map(|a| a.id().clone()).collect(); - let observations: BTreeMap<_, _> = self + let mut observations: BTreeMap<_, _> = self .accounts .get_quota_versions(&ids) .await @@ -264,37 +264,67 @@ impl QuotaService { .into_iter() .map(|o| (o.account_id.clone(), o)) .collect(); - accounts.retain(|a| { - a.enabled() - && a.authentication_kind() == "oauth" - && observations.get(a.id()).is_none_or(|o| { - o.credential_revision != a.revision() - || o.observed_at.elapsed().unwrap_or_default() >= Duration::from_secs(300) - || (a.quota().is_exhausted() - && a.quota() - .reset_at() - .is_some_and(|reset| reset <= SystemTime::now())) - }) - }); - if accounts.is_empty() { - return Ok(()); + let now = SystemTime::now(); + let interval = Duration::from_secs(300); + let stale_before = now - interval; + let mut due = Vec::new(); + let mut stale = Vec::new(); + for account in accounts + .iter() + .filter(|a| a.enabled() && a.authentication_kind() == "oauth") + { + let snapshot = observations + .remove(account.id()) + .filter(|s| s.credential_revision == account.revision()); + match snapshot { + None => due.push(account.id().clone()), + Some(_) if account.quota().exhaustion_refresh_due(now, interval) => { + due.push(account.id().clone()) + } + Some(s) if !account.quota().is_exhausted() && s.observed_at <= stale_before => { + stale.push(s) + } + Some(_) => {} + } } - accounts.sort_by(|a, b| a.id().cmp(b.id())); - let offset = self.cursor.fetch_add(32, Ordering::Relaxed) % accounts.len(); - accounts.rotate_left(offset); - accounts.truncate(32); - let mut results = stream::iter(accounts).map(|a| async move { tokio::select! { biased; _ = cancel.cancelled() => Ok(()), result = self.refresh(a.id()) => result } }).buffer_unordered(4); - let mut failure = None; + let mut outcome = Ok(()); + if !stale.is_empty() { + // 用量读取失败时,独立执行已选出的首查和耗尽复查 + match self.accounts.accounts_used_since_quota(&stale).await { + Ok(active) => due.extend(active), + Err(e) => { + outcome = + Err(WorkerTaskError::safe("读取 Antigravity 账号使用记录失败") + .with_source(e)) + } + } + } + if due.is_empty() { + return outcome; + } + due.sort_unstable(); + let offset = self.cursor.fetch_add(32, Ordering::Relaxed) % due.len(); + due.rotate_left(offset); + due.truncate(32); + let mut results = stream::iter(due) + .map(|id| async move { + tokio::select! { + biased; + _ = cancel.cancelled() => Ok(()), + result = self.refresh(&id) => result, + } + }) + .buffer_unordered(4); while let Some(result) = results.next().await { if let Err(e) = result && !matches!(e.kind(), Kind::Conflict | Kind::CredentialRefreshRequired) + && outcome.is_ok() { - failure.get_or_insert(e); + outcome = + Err(WorkerTaskError::safe("部分 Antigravity 额度刷新失败").with_source(e)); } } - failure.map_or(Ok(()), |e| { - Err(WorkerTaskError::safe("部分 Antigravity 额度刷新失败").with_source(e)) - }) + outcome } } diff --git a/backend/crates/providers/antigravity/tests/credential/quota/service.rs b/backend/crates/providers/antigravity/tests/credential/quota/service.rs index 9ecd4bd4b..14fdddfef 100644 --- a/backend/crates/providers/antigravity/tests/credential/quota/service.rs +++ b/backend/crates/providers/antigravity/tests/credential/quota/service.rs @@ -15,6 +15,86 @@ async fn upstream(server: &MockServer, remaining: serde_json::Value, delay: Dura Mock::given(path("/v1internal:retrieveUserQuotaSummary")).respond_with(ResponseTemplate::new(200).set_delay(delay).set_body_json(json!({"groups":[{"displayName":"Gemini Models","buckets":[{"bucketId":"gemini-weekly","displayName":"Weekly","window":"weekly","remainingFraction":0.9,"resetTime":"2099-01-01T00:00:00Z"},{"bucketId":"gemini-5h","displayName":"Five hour","window":"5h","remainingFraction":remaining,"resetTime":"2099-01-01T00:00:00Z"}]},{"displayName":"Claude and GPT models","buckets":[{"bucketId":"3p-weekly","displayName":"Weekly","window":"weekly","remainingFraction":0.8,"resetTime":"2099-01-01T00:00:00Z"}]}]}))).mount(server).await; } +#[tokio::test] +async fn background_refresh_requires_new_generation_and_an_aged_snapshot() { + let server = MockServer::start().await; + upstream(&server, json!(0.5), Duration::ZERO).await; + let f = Fixture::new(&server.uri()); + let account = f.store.primary(); + let cancel = CancellationToken::new(); + f.quota.reconcile(&cancel).await.unwrap(); + let initial = account.quota.lock().unwrap().clone().unwrap(); + let queries = || async { + server + .received_requests() + .await + .unwrap() + .into_iter() + .filter(|r| r.url.path() == "/v1internal:retrieveUserQuotaSummary") + .count() + }; + assert_eq!(queries().await, 1); + + *account.last_generation.lock().unwrap() = Some(SystemTime::now()); + f.quota.reconcile(&cancel).await.unwrap(); + assert_eq!(queries().await, 1); + + let old = initial.observed_at - Duration::from_secs(900); + account.quota.lock().unwrap().as_mut().unwrap().observed_at = old; + *account.last_generation.lock().unwrap() = Some(old - Duration::from_secs(1)); + f.quota.read(&initial.account_id).await.unwrap(); + f.quota.reconcile(&cancel).await.unwrap(); + assert_eq!(queries().await, 1); + + *account.last_generation.lock().unwrap() = Some(SystemTime::now()); + f.quota.reconcile(&cancel).await.unwrap(); + f.quota.reconcile(&cancel).await.unwrap(); + assert_eq!(queries().await, 2); + f.quota.refresh(&initial.account_id).await.unwrap(); + assert_eq!(queries().await, 3); +} + +#[tokio::test] +async fn exhausted_quota_is_rechecked_when_due_even_without_generation() { + use gateway_core::account::QuotaEvidence; + let server = MockServer::start().await; + upstream(&server, json!(0.5), Duration::ZERO).await; + let f = Fixture::new(&server.uri()); + let account = f.store.primary(); + let cancel = CancellationToken::new(); + f.quota.reconcile(&cancel).await.unwrap(); + let now = SystemTime::now(); + let old = now - Duration::from_secs(600); + for (observed, reset, due) in [ + (old, Some(now + Duration::from_secs(300)), false), + (old, Some(now), true), + (now, None, false), + (old, None, true), + ] { + { + let mut loaded = account.loaded.lock().unwrap(); + loaded.account = loaded.account.clone().with_account_facts( + true, + CredentialState::Ready, + QuotaState::exhausted(QuotaEvidence::UsageLimitReached, observed, reset), + None, + None, + ); + } + f.quota.reconcile(&cancel).await.unwrap(); + assert_eq!( + account + .loaded + .lock() + .unwrap() + .account + .quota() + .is_exhausted(), + !due + ); + } +} + #[tokio::test] async fn quota_and_catalog_refresh_use_current_global_identity() { let server = MockServer::start().await; @@ -191,6 +271,16 @@ async fn failed_or_stale_refresh_preserves_persisted_quota() { let cancelled = CancellationToken::new(); cancelled.cancel(); f.quota.reconcile(&cancelled).await.unwrap(); + f.quota.reconcile(&CancellationToken::new()).await.unwrap(); + assert_eq!( + f.quota + .read(account.id()) + .await + .unwrap() + .plan_type + .as_deref(), + Some("g1-pro-tier") + ); } #[tokio::test] diff --git a/backend/crates/providers/antigravity/tests/support/mod.rs b/backend/crates/providers/antigravity/tests/support/mod.rs index f084012b4..8c668c5d0 100644 --- a/backend/crates/providers/antigravity/tests/support/mod.rs +++ b/backend/crates/providers/antigravity/tests/support/mod.rs @@ -72,6 +72,7 @@ pub(crate) struct MemoryAccount { pub(crate) catalog: Mutex>, active_leases: Arc, pub(crate) quota: Mutex>, + pub(crate) last_generation: Mutex>, } impl MemoryPorts { @@ -182,6 +183,7 @@ impl Fixture { ))), active_leases: Arc::new(AtomicUsize::new(0)), quota: Mutex::new(None), + last_generation: Mutex::new(None), }, ) }) diff --git a/backend/crates/providers/antigravity/tests/support/ports.rs b/backend/crates/providers/antigravity/tests/support/ports.rs index 91bd7c3a9..8390a658d 100644 --- a/backend/crates/providers/antigravity/tests/support/ports.rs +++ b/backend/crates/providers/antigravity/tests/support/ports.rs @@ -594,6 +594,22 @@ impl ProviderAccountStore for MemoryPorts { *quota = Some(observation); Ok(QuotaWriteOutcome::Updated) } + async fn accounts_used_since_quota( + &self, + snapshots: &[QuotaObservationVersion], + ) -> Result, StoreError> { + Ok(snapshots + .iter() + .filter(|s| { + self.accounts[&s.account_id] + .last_generation + .lock() + .unwrap() + .is_some_and(|at| at > s.observed_at) + }) + .map(|s| s.account_id.clone()) + .collect()) + } async fn touch_quota_observation( &self, _touch: QuotaObservationTouch, diff --git a/docs/architecture.md b/docs/architecture.md index b798154b0..c76307483 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1089,6 +1089,7 @@ OpenAI、xAI、Antigravity 的认证及账号后台操作由各 Provider 通过 OAuth 每轮操作从运行策略读取全局 AGY 选择,由 `profile` 统一解析并冻结出站身份,换码、刷新和身份查询使用同一画像,不读取 Key 覆盖。 `loadCodeAssist` 的付费套餐优先于基础套餐;分组额度和模型额度保存到同一带凭据版本的快照,独立模型耗尽不升级为整个账号耗尽。 原生额度窗口只投影上游模型分组,不归属整号 Token;Admin 按 Provider 声明独立读取部署时区今天及前 6 天的本地用量,展示为“近一周”,不向额度列表补入本地窗口。选号及互联分别读取同一份模型额度事实,失效观测保持未知。 + 账号列表和展开的额度面板读取已保存的快照,点击“刷新额度”时立即查询上游。后台补齐启用账号缺失或凭据版本失效的快照。健康账号仅在距上次观测已满 5 分钟、且有生成请求在该次观测后成功完成时补查。整号耗尽按重置时间复查,缺少重置时间时在耗尽观测满 5 分钟后复查 正常续期后续接同一身份的目录,保留原观测时间并校验新凭据版本与套餐;目录缺失立即尝试重新发现,失败由后台重试 - 账号导入和 OAuth complete(包括重新授权)在凭据提交、Provider 缓存失效与运行快照发布后, 由 Admin 共用流程后台读取一次额度;不等待观测完成才返回管理请求,失败记录告警但不回滚账号事务。