fix(openai): retain the exhausted window from quota errors

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Zyy
2026-11-24 13:19:41 +08:00
co-authored by Codex
parent a515d54136
commit 98724da968
29 changed files with 497 additions and 177 deletions
@@ -407,6 +407,7 @@ pub struct QuotaState {
evidence: Option<QuotaEvidence>,
observed_at: Option<SystemTime>,
reset_at: Option<SystemTime>,
limit_window_minutes: Option<u16>,
}
impl Default for QuotaState {
@@ -423,6 +424,7 @@ impl QuotaState {
evidence: None,
observed_at: None,
reset_at: None,
limit_window_minutes: None,
}
}
@@ -433,6 +435,7 @@ impl QuotaState {
evidence: None,
observed_at: Some(observed_at),
reset_at: None,
limit_window_minutes: None,
}
}
@@ -443,6 +446,7 @@ impl QuotaState {
evidence: None,
observed_at: Some(observed_at),
reset_at: None,
limit_window_minutes: None,
}
}
@@ -457,6 +461,7 @@ impl QuotaState {
evidence: Some(evidence),
observed_at: Some(observed_at),
reset_at,
limit_window_minutes: None,
}
}
@@ -468,6 +473,7 @@ impl QuotaState {
evidence: Some(QuotaEvidence::CreditsAvailable),
observed_at: Some(observed_at),
reset_at,
limit_window_minutes: None,
}
}
@@ -495,6 +501,7 @@ impl QuotaState {
evidence,
observed_at,
reset_at,
limit_window_minutes: None,
})
} else {
None
@@ -521,6 +528,20 @@ impl QuotaState {
self.reset_at
}
/// 本次上游用量拒绝明确指出的窗口时长
#[must_use]
pub const fn limit_window_minutes(self) -> Option<u16> {
self.limit_window_minutes
}
#[must_use]
pub fn with_limit_window_minutes(mut self, minutes: Option<u16>) -> Self {
if self.evidence == Some(QuotaEvidence::UsageLimitReached) {
self.limit_window_minutes = minutes.filter(|minutes| *minutes > 0);
}
self
}
/// 返回当前已确认的额度耗尽结论
///
/// `reset_at` 只表示何时应重新向 Provider 求证;时间到期本身不是额度恢复证据
@@ -245,7 +245,7 @@ impl AccountGroupStore for PgAccountGroupRepository {
account.next_refresh_at, account.enabled, account.quota_settings, 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,
account.quota_reset_at, account.quota_limit_window_minutes, account.last_error_reason,
account.last_error_message, account.credential_observed_at,
account.created_at, account.updated_at,
settings.max_concurrent_per_account
@@ -110,7 +110,7 @@ pub(crate) async fn load_admin_account_page(
a.credential_revision, a.has_refresh_token, a.access_token_expires_at,
a.next_refresh_at, a.enabled, a.quota_settings, 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_observed_at, 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.quota_limit_window_minutes, 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,
@@ -336,7 +336,7 @@ impl ProviderAccountStore for PgProviderAccountRepository {
.collect::<Vec<_>>();
let rows = sqlx::query(
"select id, credential_revision, plan_type, provider_quota_json, quota_observed_at, \
quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at \
quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, quota_limit_window_minutes \
from provider_accounts \
where id = any($1) and quota_observed_at is not null",
)
@@ -368,40 +368,7 @@ impl ProviderAccountStore for PgProviderAccountRepository {
.map_err(|source| {
CoreStoreError::caused_by(CoreStoreErrorKind::InvalidData, source)
})?;
let access = row
.try_get::<String, _>("quota_access_state")
.ok()
.and_then(|value| QuotaAccessState::parse(&value))
.ok_or_else(|| CoreStoreError::new(CoreStoreErrorKind::InvalidData))?;
let evidence =
row.try_get::<Option<String>, _>("quota_evidence")
.map_err(|source| {
CoreStoreError::caused_by(CoreStoreErrorKind::InvalidData, source)
})?;
let evidence = match evidence {
Some(value) => Some(
QuotaEvidence::parse(&value)
.ok_or_else(|| CoreStoreError::new(CoreStoreErrorKind::InvalidData))?,
),
None => None,
};
let reset_at = row
.try_get::<Option<DateTime<Utc>>, _>("quota_reset_at")
.map_err(|source| {
CoreStoreError::caused_by(CoreStoreErrorKind::InvalidData, source)
})?;
let access_observed_at = row
.try_get::<Option<DateTime<Utc>>, _>("quota_access_observed_at")
.map_err(|source| {
CoreStoreError::caused_by(CoreStoreErrorKind::InvalidData, source)
})?;
let state = QuotaState::from_persisted(
access,
evidence,
access_observed_at.map(Into::into),
reset_at.map(Into::into),
)
.ok_or_else(|| CoreStoreError::new(CoreStoreErrorKind::InvalidData))?;
let state = rows::quota_state_from_row(&row).map_err(core_store_error)?;
Ok(QuotaObservation {
quota_pause: None,
expected_connection: None,
@@ -111,7 +111,7 @@ impl PgProviderAccountRepository {
upstream_account_id, plan_type, authentication_kind, credential_revision, has_refresh_token,
access_token_expires_at, next_refresh_at, enabled, quota_settings, 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_access_observed_at, quota_reset_at, quota_limit_window_minutes,
quota_observed_at, last_error_reason, last_error_message, created_at, updated_at
from provider_accounts
left join (select id as location_proxy_id, enabled as proxy_enabled, max_websocket_connections, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone from outbound_proxies) proxy_location
@@ -209,7 +209,7 @@ impl ProviderAccountRepository for PgProviderAccountRepository {
upstream_account_id, plan_type, authentication_kind, credential_revision, has_refresh_token,
access_token_expires_at, next_refresh_at, enabled, quota_settings, 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_access_observed_at, quota_reset_at, quota_limit_window_minutes,
quota_observed_at, last_error_reason, last_error_message, created_at, updated_at
from provider_accounts
left join (select id as location_proxy_id, enabled as proxy_enabled, max_websocket_connections, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone from outbound_proxies) proxy_location
@@ -619,6 +619,7 @@ impl ProviderAccountAdminRepository for PgProviderAccountRepository {
quota_evidence = null,
quota_access_observed_at = now(),
quota_reset_at = null,
quota_limit_window_minutes = null,
last_error_reason = null,
last_error_message = null,
updated_at = greatest(now(), updated_at)
@@ -795,6 +796,7 @@ pub(crate) async fn upsert_provider_account_in_transaction(
quota_evidence = null,
quota_access_observed_at = null,
quota_reset_at = null,
quota_limit_window_minutes = null,
credential_observed_at = excluded.credential_observed_at,
quota_observed_at = null,
last_error_reason = null,
@@ -877,6 +879,7 @@ pub(crate) async fn rotate_provider_account_in_transaction(
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,
quota_reset_at = case when $11 then null else quota_reset_at end,
quota_limit_window_minutes = case when $11 then null else quota_limit_window_minutes end,
provider_credentials_json = $7,
credential_revision = credential_revision + 1,
has_refresh_token = $8,
@@ -1265,7 +1268,7 @@ impl PgProviderAccountRepository {
upstream_account_id, plan_type, authentication_kind, credential_revision, has_refresh_token,
access_token_expires_at, next_refresh_at, enabled, quota_settings, 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_access_observed_at, quota_reset_at, quota_limit_window_minutes,
quota_observed_at, last_error_reason, last_error_message, created_at, updated_at
from provider_accounts
left join (select id as location_proxy_id, enabled as proxy_enabled, max_websocket_connections, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone from outbound_proxies) proxy_location
@@ -1304,7 +1307,7 @@ where
let result = sqlx::query(
"update provider_accounts
set quota_access_observed_at = $3, quota_access_state = $4,
quota_evidence = $5, quota_reset_at = $6,
quota_evidence = $5, quota_reset_at = $6, quota_limit_window_minutes = $7,
updated_at = greatest(now(), updated_at, $3)
where id = $1 and credential_revision = $2
and (quota_access_observed_at is null or quota_access_observed_at <= $3)",
@@ -1315,6 +1318,7 @@ where
.bind(state.access().as_str())
.bind(state.evidence().map(QuotaEvidence::as_str))
.bind(state.reset_at().map(DateTime::<Utc>::from))
.bind(state.limit_window_minutes().map(i32::from))
.execute(executor)
.await
.map_err(|source| postgres_unavailable("apply provider quota access", source))?;
@@ -1358,6 +1362,10 @@ where
when $7::timestamptz is not null
and (quota_access_observed_at is null or quota_access_observed_at <= $7)
then $8 else quota_reset_at end,
quota_limit_window_minutes = case
when $7::timestamptz is not null
and (quota_access_observed_at is null or quota_access_observed_at <= $7)
then $14 else quota_limit_window_minutes 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)
@@ -1382,6 +1390,7 @@ where
)
.bind(merge_base.is_some())
.bind(merge_base.and_then(|base| base.observed_at).map(DateTime::<Utc>::from))
.bind(state.limit_window_minutes().map(i32::from))
.execute(executor)
.await
.map_err(|source| postgres_unavailable("compare and swap provider quota", source))?;
@@ -330,7 +330,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, quota_settings, 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,
quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, quota_limit_window_minutes,
last_error_reason, last_error_message,
credential_observed_at, quota_observed_at, created_at, updated_at
from provider_accounts
@@ -341,7 +341,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, quota_settings, 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,
quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, quota_limit_window_minutes,
last_error_reason, last_error_message,
credential_observed_at, quota_observed_at, created_at, updated_at
from provider_accounts
@@ -353,7 +353,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, quota_settings, 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,
quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, quota_limit_window_minutes,
last_error_reason, last_error_message,
credential_observed_at, quota_observed_at, created_at, updated_at
from provider_accounts
@@ -581,17 +581,7 @@ pub(crate) fn account_status_facts_from_row(
let credential_state = row
.try_get::<String, _>("credential_state")
.map_err(|source| invalid("invalid credential_state").with_source(source))?;
let quota_access_state = parse_quota_access_state(&get::<String>(row, "quota_access_state")?)?;
let quota_evidence = parse_quota_evidence(get(row, "quota_evidence")?)?;
let quota_access_observed_at = get::<Option<DateTime<Utc>>>(row, "quota_access_observed_at")?;
let quota_reset_at = get::<Option<DateTime<Utc>>>(row, "quota_reset_at")?;
let quota = QuotaState::from_persisted(
quota_access_state,
quota_evidence,
quota_access_observed_at.map(Into::into),
quota_reset_at.map(Into::into),
)
.ok_or_else(|| invalid("invalid persisted quota fact"))?;
let quota = quota_state_from_row(row)?;
Ok(gateway_core::account::AccountStatusFacts {
quota_paused: get(row, "quota_paused")?,
enabled: get(row, "enabled")?,
@@ -604,3 +594,22 @@ pub(crate) fn account_status_facts_from_row(
last_error_message: get(row, "last_error_message")?,
})
}
pub(super) fn quota_state_from_row(row: &sqlx::postgres::PgRow) -> StoreResult<QuotaState> {
let quota_access_state = parse_quota_access_state(&get::<String>(row, "quota_access_state")?)?;
let quota_evidence = parse_quota_evidence(get(row, "quota_evidence")?)?;
let quota_access_observed_at = get::<Option<DateTime<Utc>>>(row, "quota_access_observed_at")?;
let quota_reset_at = get::<Option<DateTime<Utc>>>(row, "quota_reset_at")?;
let minutes = get::<Option<i32>>(row, "quota_limit_window_minutes")?
.map(u16::try_from)
.transpose()
.map_err(|_| invalid("invalid quota limit window"))?;
QuotaState::from_persisted(
quota_access_state,
quota_evidence,
quota_access_observed_at.map(Into::into),
quota_reset_at.map(Into::into),
)
.map(|state| state.with_limit_window_minutes(minutes))
.ok_or_else(|| invalid("invalid persisted quota fact"))
}
@@ -75,7 +75,7 @@ pub(crate) async fn load_account_statuses<'e, E: sqlx::Executor<'e, Database = s
use super::rows::{account_status_facts_from_row, get};
let rows = sqlx::query(
"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,
quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, quota_limit_window_minutes,
last_error_reason, last_error_message
from provider_accounts",
)
@@ -3086,7 +3086,8 @@ async fn quota_exhaustion_survives_rotation_only_for_the_same_upstream_identity(
.apply_quota_access(QuotaAccessChange {
account_id: ProviderAccountId::new("acct_rotation_quota").expect("account ID"),
expected_revision: CredentialRevision::new(1).expect("credential revision"),
state: QuotaState::exhausted(QuotaEvidence::ProviderDenied, observed_at, None),
state: QuotaState::exhausted(QuotaEvidence::UsageLimitReached, observed_at, None)
.with_limit_window_minutes(Some(10080)),
})
.await
.expect("persist quota exhaustion");
@@ -3107,13 +3108,13 @@ async fn quota_exhaustion_survives_rotation_only_for_the_same_upstream_identity(
.await
.expect("rotate exhausted account credential");
let quota_access_state: String =
sqlx::query_scalar("select quota_access_state from provider_accounts where id = $1")
.bind("acct_rotation_quota")
.fetch_one(&database.pool)
.await
.expect("load exhausted account after credential rotation");
assert_eq!(quota_access_state, "exhausted".to_owned());
let current = repository
.get_account(&ProviderAccountId::new("acct_rotation_quota").unwrap())
.await
.unwrap()
.unwrap();
assert!(current.quota().is_exhausted());
assert_eq!(current.quota().limit_window_minutes(), Some(10080));
repository
.rotate_provider_account(RotateProviderAccount {
@@ -232,7 +232,8 @@ async fn snapshot_commit_preserves_newer_quota_failure() {
QuotaEvidence::UsageLimitReached,
now + Duration::from_secs(1),
None,
),
)
.with_limit_window_minutes(Some(10080)),
})
.await
.unwrap();
@@ -253,15 +254,16 @@ async fn snapshot_commit_preserves_newer_quota_failure() {
.unwrap(),
QuotaWriteOutcome::Updated
);
assert!(
repository
.get_account(&id)
.await
.unwrap()
.unwrap()
.quota()
.is_exhausted()
);
let account = repository.get_account(&id).await.unwrap().unwrap();
assert!(account.quota().is_exhausted());
assert_eq!(account.quota().limit_window_minutes(), Some(10080));
let persisted = repository
.get_quotas(std::slice::from_ref(&id))
.await
.unwrap()
.pop()
.unwrap();
assert_eq!(persisted.state, account.quota());
database.close().await;
}
@@ -61,7 +61,27 @@ impl QuotaRecovery {
}
// 旧版从 primary 派生的账号 reset 不能覆盖明确的周窗口耗尽事实
// 真实 usage_limit_reached 错误则可以补充尚未反映到百分比的耗尽窗口
if pending.is_empty() || state.evidence() == Some(QuotaEvidence::UsageLimitReached) {
let error_deadline = state
.reset_at()
.filter(|at| {
state.evidence() == Some(QuotaEvidence::UsageLimitReached)
&& state.observed_at().is_some_and(|denied| *at > denied)
})
.map(DateTime::<Utc>::from);
let hinted = baseline.denied_window(state);
// 错误时间与快照周期不一致时,不能用错误时间替代窗口基线并误判已滚动
let conflicting_reset = hinted
.and_then(CodexQuotaWindow::reset_at)
.zip(error_deadline)
.is_some_and(|(window, error)| (window.timestamp() - error.timestamp()).abs() > 1);
if let Some(window) = hinted {
if !conflicting_reset {
pending.insert(
window.key().to_owned(),
window.reset_at().or(error_deadline),
);
}
} else if pending.is_empty() || state.evidence() == Some(QuotaEvidence::UsageLimitReached) {
for window in windows() {
// 错误与 usage 的秒级 reset 可能相差一秒;只用它识别窗口,
// 后续推进比较始终使用该窗口自己的 reset
@@ -77,15 +97,10 @@ impl QuotaRecovery {
}
}
}
let unmatched = state
.reset_at()
.filter(|reset| {
pending.is_empty()
&& state.evidence() == Some(QuotaEvidence::UsageLimitReached)
&& state.observed_at().is_some_and(|denied| *reset > denied)
})
.map(|reset| UnmatchedQuotaReset {
reset_at: reset.into(),
let unmatched = error_deadline
.filter(|_| pending.is_empty() || conflicting_reset)
.map(|reset_at| UnmatchedQuotaReset {
reset_at,
window_keys: windows().map(|w| w.key().to_owned()).collect(),
});
// 缺少可信的错误边界时保留原有的逐窗口复核
@@ -100,17 +115,31 @@ impl QuotaRecovery {
}
}
fn observe(&mut self, refreshed: &CodexAccountQuotaSnapshot) -> bool {
fn observe(&mut self, refreshed: &CodexAccountQuotaSnapshot, has_window_hint: bool) -> bool {
let windows = || refreshed.windows().iter().filter(|w| w.is_account_wide());
// 拒绝仍有效时,即便被点名的窗口已滚动,也要等待账号放行
if has_window_hint && refreshed.quota().access() != QuotaAccessState::Allowed {
self.candidates.clear();
for window in windows().filter(|w| w.limit_reached()) {
self.pending
.entry(window.key().to_owned())
.or_insert(window.reset_at());
}
return false;
}
let had_baseline = self.unmatched.is_some() || !self.pending.is_empty();
self.unmatched.take_if(|reset| reset.recovered(refreshed));
// 已确认窗口全部到期后,明确放行可以覆盖滞后的百分比
if !self.pending.is_empty()
&& refreshed.quota().access() == QuotaAccessState::Allowed
&& self.pending.values().all(|reset| {
reset.is_some_and(|reset| {
reset.timestamp_micros() > self.exhausted_at_micros
&& SystemTime::from(reset) <= refreshed.observed_at()
})
&& self.pending.iter().all(|(key, reset)| {
let reported = !has_window_hint
|| windows().any(|w| w.key() == key && w.used_percent().is_some());
reported
&& reset.is_some_and(|reset| {
reset.timestamp_micros() > self.exhausted_at_micros
&& SystemTime::from(reset) <= refreshed.observed_at()
})
})
{
self.pending.clear();
@@ -118,9 +147,12 @@ impl QuotaRecovery {
return self.unmatched.is_none();
}
let mut candidates = BTreeMap::new();
for window in refreshed.windows().iter().filter(|w| w.is_account_wide()) {
for window in windows() {
let key = window.key();
if let Some(previous_reset) = self.pending.get(key).copied() {
if has_window_hint && window.used_percent().is_none() {
continue;
}
if window_reset_recovered(window, previous_reset) {
self.pending.remove(key);
continue;
@@ -208,7 +240,8 @@ pub(super) fn reconcile_refresh(
if recovery.pending.is_empty() && recovery.unmatched.is_none() {
recovery = QuotaRecovery::new(state, refreshed);
}
if current.is_exhausted() && recovery.observe(refreshed) {
if current.is_exhausted() && recovery.observe(refreshed, state.limit_window_minutes().is_some())
{
refreshed.recovery = None;
return Ok(QuotaState::allowed(refreshed.observed_at()));
}
@@ -226,7 +259,8 @@ pub(super) fn reconcile_refresh(
.unwrap_or(QuotaEvidence::AccountLimitReached),
state.observed_at().unwrap_or(refreshed.observed_at()),
reset_at,
),
)
.with_limit_window_minutes(state.limit_window_minutes()),
auto_use_credits,
);
if !state.is_exhausted() {
@@ -340,7 +340,11 @@ fn quota_refresh_candidate(
return None;
}
if account.quota().is_exhausted() {
let reset_at = account.quota().reset_at();
let state = account.quota();
let reset_at = state.reset_at().or_else(|| {
let at = SystemTime::from(snapshot?.denied_window(state)?.reset_at()?);
(at > state.observed_at()?).then_some(at)
});
return Some((account, reset_at));
}
// 正常账号首次进入周期候选也要等待宽限期,不能由“无刷新历史”绕过
@@ -74,16 +74,14 @@ impl CodexCredentialQuotaService {
pub(crate) async fn record_confirmed_exhaustion(
&self,
account: &ProviderAccount,
evidence: QuotaEvidence,
reset_at: Option<SystemTime>,
observed_at: SystemTime,
state: QuotaState,
) -> Result<(), CodexCredentialQuotaError> {
let outcome = self
.store
.apply_quota_access(QuotaAccessChange {
account_id: account.id().clone(),
expected_revision: account.revision(),
state: QuotaState::exhausted(evidence, observed_at, reset_at),
state,
})
.await?;
if outcome == QuotaWriteOutcome::Conflict {
@@ -225,7 +223,10 @@ impl CodexCredentialQuotaService {
Some(QuotaEndpointFailure::Exhausted(evidence)) => {
summary.exhausted += 1;
if let Err(write_error) = self
.record_confirmed_exhaustion(&account, evidence, None, observed_at)
.record_confirmed_exhaustion(
&account,
QuotaState::exhausted(evidence, observed_at, None),
)
.await
{
summary.transient += 1;
@@ -422,8 +423,11 @@ impl CodexCredentialQuotaService {
Err(CodexQuotaFetchError::Upstream { account, error }) => {
match classify_quota_endpoint_failure(&error) {
Some(QuotaEndpointFailure::Exhausted(evidence)) => {
self.record_confirmed_exhaustion(&account, evidence, None, observed_at)
.await?;
self.record_confirmed_exhaustion(
&account,
QuotaState::exhausted(evidence, observed_at, None),
)
.await?;
}
Some(QuotaEndpointFailure::AccessTokenRevoked) => {
self.store
@@ -181,6 +181,16 @@ impl CodexAccountQuotaSnapshot {
}
}
pub(super) fn denied_window(&self, state: QuotaState) -> Option<&CodexQuotaWindow> {
let seconds = u64::from(state.limit_window_minutes()?) * 60;
let mut matches = self
.windows
.iter()
.filter(|window| window.is_account_wide() && window.window_seconds() == Some(seconds));
let window = matches.next()?;
matches.next().is_none().then_some(window)
}
#[must_use]
pub const fn account_id(&self) -> &ProviderAccountId {
&self.account_id
@@ -14,7 +14,8 @@ use gateway_core::account::{
AccountCooldownKind, AccountErrorReason, AccountFeedbackStats, AccountModelAccessMode,
AccountQuotaSignals, AccountRuntimeSignals, AccountSchedulingBlocker, AccountSelectionContext,
AccountSelectionPolicy, AccountSelector, AccountStatus, CredentialState,
PreferredAccountSelection, ProviderAccount, ProviderAccountId, QuotaEvidence, RotationStrategy,
PreferredAccountSelection, ProviderAccount, ProviderAccountId, QuotaEvidence, QuotaState,
RotationStrategy,
};
use gateway_core::concurrency::{
CapacityWait, ConcurrencyQueuePolicy, ConcurrencyWaitQueue, QueueRejection, WaitPriority,
@@ -80,6 +81,8 @@ pub enum CodexAccountFailure {
UsageLimitExhausted {
/// 上游返回的窗口绝对重置时刻
reset_at: Option<SystemTime>,
/// 上游明确指出的通用窗口时长
window_minutes: Option<u16>,
},
/// 账号触发临时用量限制
RateLimited {
@@ -1987,21 +1990,29 @@ impl CodexCredentialSelector {
}
CodexAccountFailure::QuotaExhausted => self
.quota
.record_confirmed_exhaustion(account, QuotaEvidence::PaymentRequired, None, now)
.record_confirmed_exhaustion(
account,
QuotaState::exhausted(QuotaEvidence::PaymentRequired, now, None),
)
.await
.map_err(|source| CredentialSelectionError::Store(ErrorSource::new(source))),
CodexAccountFailure::SpendLimitExceeded => self
.quota
.record_confirmed_exhaustion(account, QuotaEvidence::ProviderDenied, None, now)
.record_confirmed_exhaustion(
account,
QuotaState::exhausted(QuotaEvidence::ProviderDenied, now, None),
)
.await
.map_err(|source| CredentialSelectionError::Store(ErrorSource::new(source))),
CodexAccountFailure::UsageLimitExhausted { reset_at } => self
CodexAccountFailure::UsageLimitExhausted {
reset_at,
window_minutes,
} => self
.quota
.record_confirmed_exhaustion(
account,
QuotaEvidence::UsageLimitReached,
reset_at,
now,
QuotaState::exhausted(QuotaEvidence::UsageLimitReached, now, reset_at)
.with_limit_window_minutes(window_minutes),
)
.await
.map_err(|source| CredentialSelectionError::Store(ErrorSource::new(source))),
@@ -1638,11 +1638,7 @@ pub(super) fn map_upstream_failure(
MappedProviderFailure {
error,
websocket_transport_retryable: false,
account_failure: account_failure(
category,
failure.retry_after_seconds,
failure.usage_limit_resets_at,
),
account_failure: account_failure(&failure),
error_message: failure.client_message,
cyber_policy_failure,
model_unsupported: category == CodexFailureCategory::ModelUnsupported,
@@ -1750,24 +1746,19 @@ pub(super) const fn upstream_send_state(phase: CodexUpstreamSendPhase) -> Upstre
}
}
pub(super) fn account_failure(
category: CodexFailureCategory,
retry_after_seconds: Option<u64>,
usage_limit_resets_at: Option<i64>,
) -> Option<CodexAccountFailure> {
match category {
fn account_failure(failure: &CodexUpstreamFailure) -> Option<CodexAccountFailure> {
let retry_after_seconds = failure.retry_after_seconds;
match failure.category() {
CodexFailureCategory::CredentialExpired => Some(CodexAccountFailure::CredentialExpired),
CodexFailureCategory::IdentityVerificationRequired => {
Some(CodexAccountFailure::IdentityVerificationRequired)
}
CodexFailureCategory::Banned => Some(CodexAccountFailure::Banned),
CodexFailureCategory::UsageLimitExhausted => {
let window = failure.account_usage_limit();
Some(CodexAccountFailure::UsageLimitExhausted {
reset_at: usage_limit_resets_at
.and_then(|seconds| u64::try_from(seconds).ok())
.and_then(|seconds| {
SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(seconds))
}),
reset_at: window.reset_at,
window_minutes: window.minutes,
})
}
CodexFailureCategory::RateLimited => Some(CodexAccountFailure::RateLimited {
@@ -4,7 +4,7 @@ use std::collections::BTreeSet;
use std::fmt;
use std::num::NonZeroU32;
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime};
use std::time::{Duration, Instant};
use async_trait::async_trait;
use bytes::Bytes;
@@ -391,7 +391,7 @@ impl CodexClientError {
&upstream.diagnostics,
upstream.client_response.as_deref(),
&upstream.set_cookie_headers,
&[],
&upstream.rate_limit_headers,
upstream.send_phase,
))
}
@@ -3,9 +3,8 @@
pub(crate) mod evidence;
use super::client::CodexClientVisibleUpstreamResponse;
use super::protocol::responses::ResponsesSseFailure;
use super::protocol::responses::{ResponsesSseFailure, UsageLimitWindow, upstream_error_object};
use base64::{Engine as _, engine::general_purpose::STANDARD};
use chrono::{DateTime, Utc};
use reqwest::{StatusCode, header::HeaderMap};
use serde_json::Value;
@@ -78,8 +77,7 @@ pub struct CodexUpstreamFailure {
pub(crate) raw_body: String,
pub(crate) client_response: Option<Box<CodexClientVisibleUpstreamResponse>>,
pub(crate) identity_error_code: Option<String>,
/// 官方 `usage_limit_reached` 错误体携带的窗口重置时间(Unix 秒)
pub(crate) usage_limit_resets_at: Option<i64>,
usage_limit: UsageLimitWindow,
pub(crate) retry_after_seconds: Option<u64>,
/// 上游错误头声明不再重试当前账号
pub(crate) no_more_retry: bool,
@@ -127,9 +125,7 @@ impl CodexUpstreamFailure {
raw_body: body.to_owned(),
client_response: client_response.cloned().map(Box::new),
identity_error_code: diagnostics.identity_error_code.clone(),
usage_limit_resets_at: (category == CodexFailureCategory::UsageLimitExhausted)
.then_some(fields.resets_at)
.flatten(),
usage_limit: fields.usage_limit,
retry_after_seconds,
no_more_retry: gateway_protocol::openai::events::upstream_no_more_retry_from_body(body),
request_id: diagnostics.request_id.clone(),
@@ -159,7 +155,7 @@ impl CodexUpstreamFailure {
error_type: failure.upstream_type.clone(),
message: failure.message.clone(),
client_message: Some(failure.message.clone()),
resets_at: None,
usage_limit: failure.usage_limit,
};
let status = failure
.explicit_status_code
@@ -182,7 +178,7 @@ impl CodexUpstreamFailure {
raw_body: failure.raw_body().to_owned(),
client_response: None,
identity_error_code: diagnostics.identity_error_code.clone(),
usage_limit_resets_at: None,
usage_limit: fields.usage_limit,
retry_after_seconds: failure.retry_after_seconds,
no_more_retry: failure.no_more_retry,
request_id: failure
@@ -197,6 +193,14 @@ impl CodexUpstreamFailure {
}
}
pub(crate) fn account_usage_limit(&self) -> UsageLimitWindow {
self.usage_limit.for_headers(
self.rate_limit_headers
.iter()
.map(|(name, value)| (name.as_str(), value.as_str())),
)
}
/// 返回上游失败分类
#[must_use]
pub const fn category(&self) -> CodexFailureCategory {
@@ -244,7 +248,7 @@ struct ParsedUpstreamError {
error_type: Option<String>,
message: String,
client_message: Option<String>,
resets_at: Option<i64>,
usage_limit: UsageLimitWindow,
}
impl ParsedUpstreamError {
@@ -261,14 +265,10 @@ impl ParsedUpstreamError {
error_type: None,
message: body.to_owned(),
client_message: None,
resets_at: None,
usage_limit: UsageLimitWindow::default(),
};
};
let error = value
.pointer("/response/error")
.or_else(|| value.get("error"))
.or_else(|| value.get("detail"))
.unwrap_or(&value);
let error = upstream_error_object(&value);
let code_value = error.get("code").or_else(|| value.get("code"));
let upstream_fields = gateway_core::upstream::UpstreamFailureFields {
status: None,
@@ -302,17 +302,13 @@ impl ParsedUpstreamError {
.clone()
.or_else(|| error.as_str().and_then(non_empty_owned))
.unwrap_or_else(|| body.to_owned());
let resets_at = error
.get("resets_at")
.and_then(Value::as_i64)
.filter(|seconds| DateTime::<Utc>::from_timestamp(*seconds, 0).is_some());
Self {
upstream_fields,
code,
error_type,
message,
client_message,
resets_at,
usage_limit: UsageLimitWindow::from_payload(&value),
}
}
}
@@ -517,6 +517,55 @@ fn is_tool_execution_event(event_type: &str) -> bool {
)
}
/// 上游用量拒绝标明的时间边界与窗口时长,两者可独立缺失
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub(crate) struct UsageLimitWindow {
pub(crate) reset_at: Option<std::time::SystemTime>,
pub(crate) minutes: Option<u16>,
}
impl UsageLimitWindow {
pub(crate) fn from_payload(value: &Value) -> Self {
let error = upstream_error_object(value);
let reset_at = error
.get("resets_at")
.and_then(Value::as_i64)
.filter(|seconds| *seconds >= 0)
.and_then(|seconds| chrono::DateTime::from_timestamp(seconds, 0))
.map(Into::into);
let mut window = Self {
reset_at,
minutes: error
.get("limit_window_minutes")
.and_then(Value::as_u64)
.and_then(|minutes| u16::try_from(minutes).ok())
.filter(|minutes| *minutes > 0),
};
if let Some(headers) = value.get("headers").and_then(Value::as_object) {
window = window.for_headers(
headers
.iter()
.filter_map(|(key, value)| Some((key.as_str(), value.as_str()?))),
);
}
window
}
pub(crate) fn for_headers<'a>(
mut self,
mut headers: impl Iterator<Item = (&'a str, &'a str)>,
) -> Self {
// 具名桶即使与通用窗口周期相同,也不能当作通用窗口的耗尽证据
if headers.any(|(name, value)| {
name.eq_ignore_ascii_case("x-codex-active-limit")
&& !value.trim().eq_ignore_ascii_case("codex")
}) {
self.minutes = None;
}
self
}
}
/// Codex Responses SSE 失败事件
#[derive(Clone, PartialEq, Eq)]
pub struct ResponsesSseFailure {
@@ -532,6 +581,7 @@ pub struct ResponsesSseFailure {
pub upstream_type: Option<String>,
/// 上游显式状态码;不从业务码或错误类型推导
pub explicit_status_code: Option<u16>,
pub(crate) usage_limit: UsageLimitWindow,
/// 上游显式重试间隔,或从官方限流消息中解析出的重试间隔
pub retry_after_seconds: Option<u64>,
/// 上游 `x-retry-metadata: NO_MORE_RETRY`,与重试间隔独立
@@ -571,6 +621,7 @@ impl ResponsesSseFailure {
upstream_message: failure_message(value),
upstream_type: failure_type(value),
explicit_status_code: failure_explicit_status_code(value),
usage_limit: UsageLimitWindow::from_payload(value),
retry_after_seconds: events::retry_after_seconds_from_value(value),
no_more_retry: events::upstream_no_more_retry(value),
request_id:
@@ -621,6 +672,12 @@ fn failure_explicit_status_code(value: &Value) -> Option<u16> {
.and_then(|status| u16::try_from(status).ok())
}
pub(crate) fn upstream_error_object(value: &Value) -> &Value {
failure_error(value)
.or_else(|| value.get("detail"))
.unwrap_or(value)
}
fn failure_error(value: &Value) -> Option<&Value> {
value
.pointer("/response/error")
@@ -217,6 +217,8 @@ pub struct CodexWebSocketUpstreamError {
pub client_response: Option<Box<CodexClientVisibleUpstreamResponse>>,
/// 上游透传的 `set-cookie` 列表
pub set_cookie_headers: Vec<String>,
/// opening 拒绝携带的额度头
pub(crate) rate_limit_headers: Vec<(String, String)>,
/// 上游诊断元数据
pub diagnostics: CodexUpstreamDiagnostics,
/// 上游拒绝相对业务 payload 的发送阶段
@@ -386,24 +388,4 @@ impl CodexWebSocketExchangeError {
_ => None,
}
}
pub(super) fn upstream(
status_code: u16,
retry_after_seconds: Option<u64>,
body: String,
client_response: Option<Box<CodexClientVisibleUpstreamResponse>>,
set_cookie_headers: Vec<String>,
diagnostics: CodexUpstreamDiagnostics,
send_phase: CodexUpstreamSendPhase,
) -> Self {
Self::Upstream(Box::new(CodexWebSocketUpstreamError {
status_code,
retry_after_seconds,
body,
client_response,
set_cookie_headers,
diagnostics,
send_phase,
}))
}
}
@@ -26,7 +26,7 @@ use crate::{
};
use super::{
error::CodexWebSocketExchangeError,
error::{CodexWebSocketExchangeError, CodexWebSocketUpstreamError},
model::{
CodexWebSocketConnection, CodexWebSocketRequest, ResponseCreateOpening,
WebSocketContinuationRequirement,
@@ -417,11 +417,11 @@ fn websocket_opening_error(
.and_then(|value| value.to_str().ok())
.and_then(gateway_protocol::openai::parse_retry_after_seconds)
.or_else(|| events::retry_after_seconds_from_body(&body));
CodexWebSocketExchangeError::upstream(
CodexWebSocketExchangeError::Upstream(Box::new(CodexWebSocketUpstreamError {
status_code,
retry_after_seconds,
body,
reqwest::StatusCode::from_u16(status_code)
client_response: reqwest::StatusCode::from_u16(status_code)
.ok()
.map(|status| {
Box::new(CodexClientVisibleUpstreamResponse::new(
@@ -431,11 +431,12 @@ fn websocket_opening_error(
raw_body,
))
}),
response_meta::set_cookie_headers(response.headers()),
response_meta::diagnostics(Some(status_code), response.headers())
set_cookie_headers: response_meta::set_cookie_headers(response.headers()),
rate_limit_headers: response_meta::rate_limit_headers(response.headers()),
diagnostics: response_meta::diagnostics(Some(status_code), response.headers())
.with_response_origin(websocket_response_origin(connection)),
CodexUpstreamSendPhase::BeforePayload,
)
send_phase: CodexUpstreamSendPhase::BeforePayload,
}))
}
fn websocket_response_origin(connection: &CodexWebSocketConnection) -> Option<reqwest::Url> {
@@ -1438,6 +1438,7 @@ async fn usage_limit_exhaustion_marks_quota_exhausted_without_usage_probe() {
&account,
CodexAccountFailure::UsageLimitExhausted {
reset_at: Some(SystemTime::now() + Duration::from_secs(30)),
window_minutes: None,
},
None,
)
@@ -122,6 +122,59 @@ async fn exhausted_reset_bypasses_periodic_throttle_and_rechecks_each_pending_wi
assert_eq!(server.received_requests().await.expect("requests").len(), 2);
}
#[tokio::test]
async fn duration_only_denial_schedules_the_weekly_reset_despite_recent_refresh() {
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, "acct_duration_timing").await;
let account = store.account("acct_duration_timing").unwrap();
let server = MockServer::start().await;
let service = quota_service_with_base_url(&store, reqwest::Client::new(), server.uri());
let now = SystemTime::now();
let reset = Utc::now().timestamp() + 120;
let usage = |allowed, used, week_reset| {
json!({"rate_limit": {
"allowed": allowed,
"primary_window": {"used_percent": 45, "limit_window_seconds": 18000, "reset_at": reset + 3600},
"secondary_window": {"used_percent": used, "limit_window_seconds": 604800, "reset_at": week_reset}
}})
};
mount_usage(&server, usage(false, 99, reset)).await;
service.refresh_account(account.id()).await.unwrap();
service.synchronize_at(now).await.unwrap();
let denied = QuotaState::exhausted(QuotaEvidence::UsageLimitReached, SystemTime::now(), None)
.with_limit_window_minutes(Some(10080));
store
.apply_quota_access(QuotaAccessChange {
account_id: account.id().clone(),
expected_revision: account.revision(),
state: denied,
})
.await
.unwrap();
mount_usage(&server, usage(true, 0, reset + 604800)).await;
let at_reset = SystemTime::from(chrono::DateTime::from_timestamp(reset, 0).unwrap());
service
.synchronize_at(at_reset + Duration::from_secs(9))
.await
.unwrap();
assert!(server.received_requests().await.unwrap().is_empty());
let summary = service
.synchronize_at(at_reset + Duration::from_secs(10))
.await
.unwrap();
assert_eq!(summary.updated, 1);
assert_eq!(server.received_requests().await.unwrap().len(), 1);
assert_eq!(
store
.account("acct_duration_timing")
.unwrap()
.quota()
.access(),
QuotaAccessState::Allowed
);
}
#[tokio::test]
async fn periodic_checks_continue_when_reset_is_unknown_or_far_in_the_future() {
for reset in [None, Some(Utc::now().timestamp() + 604_800)] {
@@ -184,6 +184,8 @@ async fn unmatched_usage_limit_reset_requires_a_complete_allowed_observation() {
let missing_percent = json!({"limit_window_seconds": 604_800, "reset_at": now + 86_400});
for (case, error_offset, allowed, weekly_window, recovers) in [
("due", -60, Some(true), weekly(45), true),
("hint_conflict_due", -60, Some(true), weekly(45), true),
("hint_conflict_future", 3600, Some(true), weekly(45), false),
("before_reset", 3600, Some(true), weekly(45), false),
("week_full", -60, Some(true), weekly(100), false),
("week_missing", -60, Some(true), json!(null), false),
@@ -200,6 +202,19 @@ async fn unmatched_usage_limit_reset_requires_a_complete_allowed_observation() {
old["rate_limit"]["secondary_window"]["used_percent"] = json!(45);
let observed_at = at(now - 120);
let account = seed_exhaustion(&store, &id, old, observed_at, Some(error_reset)).await;
if case.starts_with("hint_conflict") {
persist_quota_state(
&store,
&account,
QuotaState::exhausted(
QuotaEvidence::UsageLimitReached,
observed_at,
Some(error_reset),
)
.with_limit_window_minutes(Some(300)),
)
.await;
}
let mut fresh = usage(now, &[Some(18_000), week], allowed);
fresh["rate_limit"]["primary_window"]["used_percent"] = json!(0);
fresh["rate_limit"]["secondary_window"] = weekly_window;
@@ -236,6 +251,47 @@ async fn unmatched_usage_limit_reset_requires_a_complete_allowed_observation() {
}
}
#[tokio::test]
async fn duration_hint_keeps_each_confirmed_window_until_it_is_observed_recovered() {
let store = Arc::new(MemoryAccountStore::default());
let id = "acct_partial_hinted_reset";
create_account(&store, id).await;
let now = Utc::now().timestamp();
let denied_at = SystemTime::now() - Duration::from_secs(120);
let baseline = usage(now, &[Some(-60), Some(-60)], Some(false));
let account = seed_exhaustion(&store, id, baseline, denied_at, None).await;
persist_quota_state(
&store,
&account,
QuotaState::exhausted(QuotaEvidence::UsageLimitReached, denied_at, None)
.with_limit_window_minutes(Some(10080)),
)
.await;
let server = MockServer::start().await;
let service = quota_service_with_base_url(&store, reqwest::Client::new(), server.uri());
for (allowed, role, seconds, recovered) in [
(false, "secondary_window", 604800, false),
(true, "primary_window", 18000, false),
(true, "secondary_window", 604800, true),
] {
server.reset().await;
let fresh = json!({"rate_limit": {"allowed": allowed, (role): {
"limit_window_seconds": seconds, "used_percent": 0, "reset_at": now + seconds
}}});
Mock::given(method("GET"))
.and(path("/api/codex/usage"))
.respond_with(ResponseTemplate::new(200).set_body_json(fresh))
.mount(&server)
.await;
let snapshot = service.refresh_account(account.id()).await.unwrap();
assert_eq!(
snapshot.quota().is_exhausted(),
!recovered,
"{role} allowed={allowed}"
);
}
}
#[tokio::test]
async fn newer_denial_survives_an_unmatched_reset_refresh() {
let now = SystemTime::now();
@@ -1,4 +1,4 @@
//! 失败流的额度观测不能冒充使用,真实输出仍应阻止本轮预热
//! 验证推理失败与真实使用在额度恢复和预热中的不同作用
use super::*;
@@ -204,3 +204,106 @@ async fn disconnected_stream_preserves_quota_facts_without_marking_usage() {
);
assert!(saved.get("_cpr_bucket_last_used_at").is_none());
}
#[tokio::test]
async fn duration_only_usage_limit_tracks_the_window_named_by_the_denial() {
for (minutes, other_minutes, other_used, active_limit, recovers) in [
(300, 10080, 45, "codex", true),
(10080, 300, 45, "", true),
(43200, 10080, 45, "", true),
(10080, 300, 100, "", false),
(10080, 10080, 45, "", false),
(10080, 300, 45, "spark", false),
] {
let store = Arc::new(MemoryAccountStore::default());
let id = "acct_provider_contract";
create_account(&store, id).await;
let account = store.account(id).unwrap();
let now = Utc::now().timestamp();
let usage = |used, reset| {
json!({"rate_limit": {
"allowed": true,
"primary_window": {"used_percent": other_used, "limit_window_seconds": i64::from(other_minutes) * 60, "reset_at": now + 7200},
"secondary_window": {"used_percent": used, "limit_window_seconds": i64::from(minutes) * 60, "reset_at": reset}
}})
};
let observed_at = SystemTime::now() - Duration::from_secs(120);
store
.compare_and_swap_quota(QuotaObservation {
account_id: account.id().clone(),
expected_revision: account.revision(),
quota: OpaqueProviderData::new(usage(99, now - 60).as_object().unwrap().clone()),
observed_at,
state: QuotaState::allowed(observed_at),
quota_pause: None,
expected_connection: None,
plan_type: None,
})
.await
.unwrap();
let server = MockServer::start().await;
let (provider, quota) = provider_and_quota_with_affinity_and_base_url_and_leases(
&store,
Arc::new(MemorySessionAffinity::default()),
server.uri(),
Arc::new(TestLeaseCoordinator::default()),
0,
);
let error = json!({"type": "usage_limit_reached", "code": "usage_limit_reached",
"limit_window_minutes": minutes});
let mut refusal = if minutes == 43200 {
ResponseTemplate::new(200)
.insert_header("content-type", "text/event-stream")
.set_body_string(sse_event(json!({"type": "response.failed",
"response": {"id": "resp_limit", "status": "failed", "error": error}})))
} else {
ResponseTemplate::new(429).set_body_json(json!({"error": error}))
};
if !active_limit.is_empty() {
refusal = refusal.insert_header("x-codex-active-limit", active_limit);
}
Mock::given(method("POST"))
.and(path("/codex/responses"))
.respond_with(refusal)
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/api/codex/usage"))
.respond_with(
ResponseTemplate::new(200).set_body_json(usage(0, now + i64::from(minutes) * 60)),
)
.expect(1)
.mount(&server)
.await;
let mut stream = provider
.execute(
planned_request("openai", http_generate_operation()),
context("req_usage_window", CancellationToken::new()),
)
.await
.unwrap();
let failure = loop {
if let Err(error) = stream.next().await.expect("quota refusal") {
break error;
}
};
assert_eq!(failure.kind(), ProviderErrorKind::QuotaExhausted);
let denied = store.account(id).unwrap().quota();
assert_eq!(denied.evidence(), Some(QuotaEvidence::UsageLimitReached));
assert_eq!(denied.reset_at(), None);
assert_eq!(
denied.limit_window_minutes(),
(active_limit != "spark").then_some(minutes)
);
let summary = quota.synchronize().await.unwrap();
assert_eq!(
summary.updated,
u64::from(recovers),
"{minutes}/{other_minutes} {other_used} {active_limit}"
);
assert_eq!(store.account(id).unwrap().quota().is_exhausted(), !recovers);
}
}
+1
View File
@@ -43,3 +43,4 @@ aeff99fee7cef5a553ae49ffe27a48f49e31ccfb3fbc61a2482c9b109478202d 0041_account_m
223589308df852154004385b13c91a03714114fb9472f00472099bcf2c131cb3 0043_quota_reset_window_weights.sql
23eeb6ef99de2315cf4a198638e9c73b364fb1cb40b7e571a3f15d3e9d15f67c 0044_account_quota_settings.sql
5cfe0227e2a4b26c268bf5b6ef7f93904e02c57d9d2d05cfe2e32db0a7d4e7a2 0045_account_group_policies_and_openai_request_settings.sql
ab779ac6ec710148e7c66d82d0a0abbb13c882ad8598cf786278aab2221ef079 0046_quota_limit_window.sql
@@ -0,0 +1,4 @@
-- 上游明确指出耗尽窗口时,随该次拒绝保留其时长
alter table provider_accounts
add column quota_limit_window_minutes integer
check (quota_limit_window_minutes between 1 and 65535);
+3 -1
View File
@@ -1818,7 +1818,9 @@ OpenAI 授权码交换与令牌刷新请求的连接超时为 30 秒,单次上
`resetAt + 2 分钟` 后复核,未更新则按 30 分钟间隔重试。后台每 30 秒检查条件,实际恢复时间还受
排队、查询耗时和上游传播影响;查询失败也遵守间隔。无可用点数时,到期前仍按原窗口证据恢复;
已确认耗尽的窗口全部到期后,新查询明确 `allowed=true` 可解除限制,即使用量仍为 100%。
若 `usage_limit_reached` 给出的未来重置时间无法对应到任何窗口,且没有窗口明确触顶,按错误给出的时间复核。
若 `usage_limit_reached` 给出 `limit_window_minutes` 且唯一对应一个通用窗口,按该窗口复核,同时保留其他已触顶窗口。
错误未给出 `resets_at` 时,采用该窗口已知的重置时间;具名额度桶的时长不用于识别通用窗口。
若仍无法归属窗口且没有窗口明确触顶,按错误给出的未来重置时间复核。
到期后的查询须明确放行,覆盖此前已知的通用窗口,并且每个通用窗口都有未触顶的使用率。
未知或早于本次拒绝的重置时间仍按窗口证据复核;时间到期本身不会解除限制或将展示用量归零
- 停用的 OpenAI 与 xAI OAuth 账号退出客户端请求调度,仍按各自策略续期 Token、查询额度。
+2 -1
View File
@@ -1026,7 +1026,8 @@ OpenAI Provider 统一解释点数可用性,主动查询、耗尽恢复与失
Store 在账号事务内保存点数放行依据与快照;关闭自动使用时撤销该依据,迟到观测不能绕过开关。
放行条件与默认值见[账号额度 API](api.md#查询与账号字段)。
无可用点数的失败回读保留已确认的拒绝;常规刷新在到期前仍按窗口证据恢复,本次耗尽之后的
已确认窗口 reset 全部到期后可依据新的明确放行观察恢复。无法确认耗尽窗口时,保留拒绝给出的复查时间和
已确认窗口 reset 全部到期后可依据新的明确放行观察恢复。拒绝给出的窗口时长随该次耗尽事实持久化,
OpenAI Provider 将其与通用窗口匹配。无法确认耗尽窗口时,保留拒绝给出的复查时间和
此前已知的通用窗口。查询沿用 credential revision 与观察时间隔离,不允许旧查询撤销较新的失败;恢复条件和后台复核节奏见 [账号额度与状态](api.md#openai-身份额度与状态)
OpenAI 订阅周期属于按需个人信息,不是额度事实。Admin 账号用例通过现有 Provider 管理端口并发读取