Compare commits

..
4 Commits
34 changed files with 828 additions and 297 deletions
@@ -1090,9 +1090,6 @@ impl ProviderQuota {
/// 语义,绝不读取 Provider 私有 JSON
#[must_use]
pub fn representative_used_percent(&self) -> Option<f64> {
if self.limit_reached {
return Some(100.0);
}
self.representative_used_window()
.map(|(_, used_percent)| used_percent)
}
@@ -1111,39 +1108,16 @@ impl ProviderQuota {
})
}
/// 将已确认的账号级额度耗尽事实投影到展示窗口
///
/// Provider 已指出具体触顶窗口时只归一化这些窗口;否则归一化 Dashboard
/// 同样会选择的代表窗口,避免把多个独立额度窗口全部伪造成已用尽
/// 只对 Provider 已明确触顶的窗口展示满额,账号耗尽本身不能定位窗口
pub fn apply_limit_reached_display(&mut self) {
if !self.limit_reached {
return;
}
let reached_windows = self
.windows
.iter()
.enumerate()
.filter_map(|(index, window)| window.limit_reached.then_some(index))
.collect::<Vec<_>>();
if !reached_windows.is_empty() {
for index in reached_windows {
self.windows[index].used_percent = Some(100.0);
if self.limit_reached {
for window in self
.windows
.iter_mut()
.filter(|window| window.limit_reached)
{
window.used_percent = Some(100.0);
}
return;
}
let representative = self
.representative_used_window()
.map(|(index, _)| index)
.or_else(|| {
self.windows
.iter()
.enumerate()
.min_by_key(|(index, window)| (quota_usage_priority(window), *index))
.map(|(index, _)| index)
});
if let Some(index) = representative {
self.windows[index].used_percent = Some(100.0);
self.windows[index].limit_reached = true;
}
}
+10 -11
View File
@@ -148,7 +148,7 @@ fn representative_quota_should_prefer_account_wide_window_over_model_specific_wi
}
#[test]
fn exhausted_quota_should_project_full_usage_to_only_the_representative_window() {
fn account_exhaustion_preserves_measured_and_unknown_window_usage() {
let mut quota = ProviderQuota {
paused_windows: Vec::new(),
upstream: None,
@@ -157,23 +157,22 @@ fn exhausted_quota_should_project_full_usage_to_only_the_representative_window()
observed_at: None,
refresh_token_expires_at: None,
windows: vec![
quota_window("monthly", Some(2_592_000), Some(99.0)),
quota_window("shortTerm", Some(604_800), Some(80.0)),
quota_window("shortTerm", Some(18_000), Some(30.0)),
quota_window("shortTerm", Some(14_400), Some(95.0)),
quota_window("shortTerm", Some(18_000), Some(0.0)),
quota_window("weekly", Some(604_800), Some(16.0)),
quota_window("monthly", Some(2_592_000), None),
],
limit_reached: true,
provider_data: None,
};
assert_eq!(quota.representative_used_percent(), Some(100.0));
quota.apply_limit_reached_display();
assert_eq!(quota.windows[0].used_percent, Some(99.0));
assert_eq!(quota.windows[1].used_percent, Some(80.0));
assert_eq!(quota.windows[2].used_percent, Some(30.0));
assert_eq!(quota.windows[3].used_percent, Some(100.0));
assert!(quota.windows[3].limit_reached);
assert!(quota.limit_reached);
assert_eq!(quota.representative_used_percent(), Some(0.0));
assert_eq!(quota.windows[0].used_percent, Some(0.0));
assert_eq!(quota.windows[1].used_percent, Some(16.0));
assert_eq!(quota.windows[2].used_percent, None);
assert!(quota.windows.iter().all(|window| !window.limit_reached));
}
#[test]
@@ -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;
}
@@ -1,6 +1,6 @@
//! 将耗尽窗口的恢复基准与最新用量分开持久化,允许各窗口分批恢复
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::time::SystemTime;
use chrono::{DateTime, Utc};
@@ -18,25 +18,69 @@ pub(super) struct QuotaRecovery {
// 绑定本次耗尽事实,避免真实推理成功后再次耗尽时复用上次的恢复进度
exhausted_at_micros: i64,
pending: BTreeMap<String, Option<DateTime<Utc>>>,
// 已连续观测到"未触顶"的待解除窗口;第二次确认后解除
// 旧文档没有该
// 字段时反序列化为空集,从当前耗尽事实重新积累证据
#[serde(default, skip_serializing_if = "Option::is_none")]
unmatched: Option<UnmatchedQuotaReset>,
// 上次刷新已观察到未触顶的窗口,下一次仍有证据时解除
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
candidates: BTreeMap<String, ()>,
}
// 拒绝给出了复查时间,但快照无法将它归属到具体窗口
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct UnmatchedQuotaReset {
reset_at: DateTime<Utc>,
window_keys: BTreeSet<String>,
}
impl UnmatchedQuotaReset {
fn recovered(&self, refreshed: &CodexAccountQuotaSnapshot) -> bool {
let windows = refreshed.windows().iter().filter(|w| w.is_account_wide());
SystemTime::from(self.reset_at) <= refreshed.observed_at()
&& refreshed.quota().access() == QuotaAccessState::Allowed
&& windows.clone().next().is_some()
&& windows
.clone()
.all(|w| w.used_percent().is_some() && !w.limit_reached())
&& self
.window_keys
.iter()
.all(|key| windows.clone().any(|w| w.key() == key))
}
}
impl QuotaRecovery {
fn new(state: QuotaState, baseline: &CodexAccountQuotaSnapshot) -> Self {
let windows = || baseline.windows().iter().filter(|w| w.is_account_wide());
let mut pending = BTreeMap::new();
for window in baseline.windows().iter().filter(|w| w.is_account_wide()) {
for window in windows() {
if window.limit_reached() {
pending.insert(window.key().to_owned(), window.reset_at());
}
}
// 旧版从 primary 派生的账号 reset 不能覆盖明确的周窗口耗尽事实
// 真实 usage_limit_reached 错误则可以补充尚未反映到百分比的耗尽窗口
if pending.is_empty() || state.evidence() == Some(QuotaEvidence::UsageLimitReached) {
for window in baseline.windows().iter().filter(|w| w.is_account_wide()) {
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
let matches_error_reset = window.reset_at().zip(state.reset_at()).is_some_and(
@@ -51,47 +95,83 @@ impl QuotaRecovery {
}
}
}
// 上游未指出耗尽窗口时保留所有候选,不能任意把错误归给 primary
if pending.is_empty() {
pending.extend(
baseline
.windows()
.iter()
.filter(|w| w.is_account_wide())
.map(|w| (w.key().to_owned(), w.reset_at())),
);
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(),
});
// 缺少可信的错误边界时保留原有的逐窗口复核
if pending.is_empty() && unmatched.is_none() {
pending.extend(windows().map(|w| (w.key().to_owned(), w.reset_at())));
}
Self {
exhausted_at_micros: exhaustion_time(state),
pending,
unmatched,
candidates: BTreeMap::new(),
}
}
fn observe(&mut self, refreshed: &CodexAccountQuotaSnapshot) -> bool {
let had_baseline = !self.pending.is_empty();
fn observe(&mut self, refreshed: &CodexAccountQuotaSnapshot, has_window_hint: bool) -> bool {
let windows = || refreshed.windows().iter().filter(|w| w.is_account_wide());
let access = refreshed.quota().access();
// 拒绝仍有效时,即便被点名的窗口已滚动,也要等待账号放行
if has_window_hint && 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()
&& access == QuotaAccessState::Allowed
&& 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();
self.candidates.clear();
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 window_reset_recovered(window, previous_reset) {
let Some(previous_reset) = previous_reset else {
// 首次观测到该窗口只锚定 reset 基线,不构成解除证据
if !has_window_hint || window.used_percent().is_some() {
self.pending.insert(key.to_owned(), window.reset_at());
}
continue;
};
let Some(used) = window.used_percent() else {
continue;
};
if window.limit_reached() {
continue;
}
let advanced = window.reset_at().is_some_and(|at| at > previous_reset);
if advanced && used < RESET_RECOVERY_MAX_USED_PERCENT {
self.pending.remove(key);
continue;
}
if previous_reset.is_none() {
// 首次观测到该窗口只锚定 reset 基线,不构成解除证据
self.pending.insert(key.to_owned(), window.reset_at());
continue;
}
// 同一窗口内用量回落(reset 不滚动)时"reset 前进"永远不会
// 成立,滑动窗口的正常用量也长期高于低用量阈值;以上游连续
// 两次观测都报告未触顶为解除证据
// 单次观测无法排除耗尽后
// 立刻拉到的旧快照(reset 未滚动、用量尚未触顶)
let rolled_forward = window
.reset_at()
.is_some_and(|current| Some(current) > previous_reset);
if !rolled_forward && !window.limit_reached() {
// 明确放行时,reset 的位移不影响连续两次未触顶的证据
// 上游未给出放行状态时,只沿用同一窗口内用量回落的确认规则
if access == QuotaAccessState::Allowed
|| (access == QuotaAccessState::Unknown && !advanced)
{
if self.candidates.contains_key(key) {
self.pending.remove(key);
} else {
@@ -103,7 +183,7 @@ impl QuotaRecovery {
}
}
self.candidates = candidates;
had_baseline && self.pending.is_empty()
had_baseline && self.pending.is_empty() && self.unmatched.is_none()
}
}
@@ -111,23 +191,7 @@ fn exhaustion_time(state: QuotaState) -> i64 {
DateTime::<Utc>::from(state.observed_at().unwrap_or(SystemTime::UNIX_EPOCH)).timestamp_micros()
}
fn window_reset_recovered(window: &CodexQuotaWindow, previous: Option<DateTime<Utc>>) -> bool {
// reset 必须前进:防止耗尽后立刻拉到的旧快照(reset 未滚动)误解锁
if !previous
.zip(window.reset_at())
.is_some_and(|(previous, current)| current > previous)
{
return false;
}
// reset 前进说明已进入新窗口,新窗口用量应接近零;高用量说明 reset 基线
// 不可信(例如滑动窗口),保持锁定,等待"同窗口用量回落"的连续观测解除
window
.used_percent()
.is_some_and(|used| used < RESET_RECOVERY_MAX_USED_PERCENT)
}
/// 统一手动刷新和 worker 的恢复规则
/// 到期前仍要求窗口滚动且低用量,或同窗口连续两次未触顶
/// 已记录的耗尽窗口全部到期后,允许新的明确放行观察解除,兼容用量百分比滞后
pub(super) fn reconcile_refresh(
current: QuotaState,
@@ -158,28 +222,19 @@ pub(super) fn reconcile_refresh(
.filter(|recovery| recovery.exhausted_at_micros == exhaustion_time(state))
.cloned()
.unwrap_or_else(|| QuotaRecovery::new(state, previous.unwrap_or(refreshed)));
if recovery.pending.is_empty() {
if recovery.pending.is_empty() && recovery.unmatched.is_none() {
recovery = QuotaRecovery::new(state, refreshed);
}
// 只信任本次耗尽之后的边界,防止再次拒绝后复用已经过期的 reset 反复解封
// 多个耗尽窗口必须全部到期,未知 reset 仍走原有恢复规则
let allowed_after_reset = refreshed.quota().access() == QuotaAccessState::Allowed
&& !recovery.pending.is_empty()
&& recovery.pending.values().all(|reset| {
reset.is_some_and(|reset| {
reset.timestamp_micros() > recovery.exhausted_at_micros
&& SystemTime::from(reset) <= refreshed.observed_at()
})
});
if current.is_exhausted() && (allowed_after_reset || 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()));
}
let reset_at = recovery
.pending
.values()
.filter_map(|reset| *reset)
.min()
.unmatched
.as_ref()
.map(|reset| reset.reset_at)
.or_else(|| recovery.pending.values().filter_map(|reset| *reset).min())
.map(SystemTime::from)
.or(state.reset_at());
let state = refreshed.access_with_credits(
@@ -189,7 +244,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)] {
@@ -22,6 +22,30 @@ fn usage(now: i64, resets: &[Option<i64>], allowed: Option<bool>) -> serde_json:
value
}
async fn seed_exhaustion(
store: &MemoryAccountStore,
id: &str,
usage: serde_json::Value,
observed_at: SystemTime,
reset_at: Option<SystemTime>,
) -> ProviderAccount {
let account = store.account(id).expect("account");
store
.compare_and_swap_quota(QuotaObservation {
quota_pause: None,
expected_connection: None,
plan_type: None,
account_id: account.id().clone(),
expected_revision: account.revision(),
quota: OpaqueProviderData::new(usage.as_object().unwrap().clone()),
observed_at,
state: QuotaState::exhausted(QuotaEvidence::UsageLimitReached, observed_at, reset_at),
})
.await
.expect("persist confirmed exhaustion");
account
}
#[tokio::test]
async fn allowed_refresh_recovers_full_windows_only_after_the_confirmed_resets() {
for (name, resets, failure_offset, allowed, recovered) in [
@@ -57,7 +81,6 @@ async fn allowed_refresh_recovers_full_windows_only_after_the_confirmed_resets()
let store = Arc::new(MemoryAccountStore::default());
let account_id = format!("acct_reset_{name}_{worker}");
create_account(&store, &account_id).await;
let account = store.account(&account_id).expect("account");
let now = Utc::now().timestamp();
let observed_at =
SystemTime::UNIX_EPOCH + Duration::from_secs((now + failure_offset) as u64);
@@ -67,23 +90,8 @@ async fn allowed_refresh_recovers_full_windows_only_after_the_confirmed_resets()
.min()
.map(|offset| SystemTime::UNIX_EPOCH + Duration::from_secs((now + offset) as u64));
let old_usage = usage(now, &resets, Some(false));
store
.compare_and_swap_quota(QuotaObservation {
quota_pause: None,
expected_connection: None,
plan_type: None,
account_id: account.id().clone(),
expected_revision: account.revision(),
quota: OpaqueProviderData::new(old_usage.as_object().expect("usage").clone()),
observed_at,
state: QuotaState::exhausted(
QuotaEvidence::UsageLimitReached,
observed_at,
reset_at,
),
})
.await
.expect("persist confirmed exhaustion before refresh");
let account =
seed_exhaustion(&store, &account_id, old_usage, observed_at, reset_at).await;
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/codex/usage"))
@@ -160,3 +168,166 @@ async fn allowed_refresh_recovers_full_windows_only_after_the_confirmed_resets()
}
}
}
#[tokio::test]
async fn unmatched_usage_limit_reset_requires_a_complete_allowed_observation() {
let now = Utc::now().timestamp();
let at = |seconds: i64| SystemTime::UNIX_EPOCH + Duration::from_secs(seconds as u64);
let week = Some(86_400);
let weekly = |used: i64| {
json!({
"limit_window_seconds": 604_800,
"reset_at": now + 86_400,
"used_percent": used
})
};
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),
("usage_missing", -60, Some(true), missing_percent, false),
("denied", -60, Some(false), weekly(45), false),
("unknown", -60, None, weekly(45), false),
] {
let store = Arc::new(MemoryAccountStore::default());
let id = format!("acct_unmatched_{case}");
create_account(&store, &id).await;
let error_reset = at(now + error_offset);
let mut old = usage(now, &[Some(error_offset - 2), week], Some(true));
old["rate_limit"]["primary_window"]["used_percent"] = json!(99);
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;
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/codex/usage"))
.respond_with(ResponseTemplate::new(200).set_body_json(fresh))
.mount(&server)
.await;
let service = quota_service_with_base_url(&store, reqwest::Client::new(), server.uri());
let summary = service.synchronize().await.unwrap();
assert_eq!(summary.updated, u64::from(recovers), "{case}");
let quota = store.account(&id).unwrap().quota();
assert_eq!(quota.is_exhausted(), !recovers, "{case}");
if !recovers {
assert_eq!(quota.reset_at(), Some(error_reset), "{case}");
// 第二次手动复核从已落库的进度继续,缺失或拒绝的观察仍不可恢复
let refreshed = service.refresh_account(account.id()).await.unwrap();
assert!(refreshed.quota().is_exhausted(), "{case}");
if case == "week_missing" {
server.reset().await;
let mut complete = usage(now, &[Some(18_000), week], Some(true));
complete["rate_limit"]["primary_window"]["used_percent"] = json!(0);
complete["rate_limit"]["secondary_window"] = weekly(45);
Mock::given(method("GET"))
.and(path("/api/codex/usage"))
.respond_with(ResponseTemplate::new(200).set_body_json(complete))
.mount(&server)
.await;
let recovered = service.refresh_account(account.id()).await.unwrap();
assert!(!recovered.quota().is_exhausted());
}
}
}
}
#[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();
let stamp = Utc::now().timestamp();
let mut healthy = usage(stamp, &[Some(18_000), Some(86_400)], Some(true));
healthy["rate_limit"]["primary_window"]["used_percent"] = json!(0);
healthy["rate_limit"]["secondary_window"]["used_percent"] = json!(45);
let reset = now - Duration::from_secs(60);
let store = Arc::new(MemoryAccountStore::default());
let id = "acct_concurrent_quota";
create_account(&store, id).await;
let account = seed_exhaustion(
&store,
id,
healthy.clone(),
now - Duration::from_secs(120),
Some(reset),
)
.await;
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/codex/usage"))
.respond_with(ResponseTemplate::new(200).set_body_json(healthy))
.mount(&server)
.await;
let service = quota_service_with_base_url(&store, reqwest::Client::new(), server.uri());
let (read, resume) = store.hold_next_quota_read();
let next_reset = now + Duration::from_secs(3600);
// 刷新已收到放行回复并读出旧快照,在合并写入前记录新的推理拒绝
let (result, ()) = tokio::join!(service.refresh_account(account.id()), async {
read.await.unwrap();
persist_quota_state(&store, &account, exhausted_quota(Some(next_reset))).await;
resume.send(()).unwrap();
});
result.expect("refresh quota display");
let state = store.account(id).unwrap().quota();
assert!(state.is_exhausted());
assert_eq!(state.reset_at(), Some(next_reset));
}
@@ -564,6 +564,86 @@ async fn an_unknown_slot_establishes_a_baseline_before_it_can_recover() {
}
}
#[tokio::test]
async fn legacy_exhaustion_recovers_after_two_nonfull_observations_despite_reset_drift() {
for (first, second) in [(0, 1), (1, 1), (2, 2), (2, 60), (3600, 7200)] {
let store = Arc::new(MemoryAccountStore::default());
let id = "acct_drifting_reset";
create_account(&store, id).await;
let account = store.account(id).unwrap();
let now = Utc::now().timestamp();
let week = now + 604_800;
let server = MockServer::start().await;
let service = quota_service_with_base_url(&store, reqwest::Client::new(), server.uri());
let mut old = usage((99, now - 60), (15, week));
old["rate_limit"]["allowed"] = json!(true);
mount_usage(&server, old).await;
service.refresh_account(account.id()).await.unwrap();
// 旧版流内拒绝保留最近的用量,但未记录错误 reset,两个窗口都需复核
persist_quota_state(&store, &account, exhausted_quota(None)).await;
for (offset, exhausted) in [(first, true), (second, false)] {
let mut fresh = usage((0, now + 18_000), (16, week + offset));
fresh["rate_limit"]["allowed"] = json!(true);
mount_usage(&server, fresh).await;
let result = service.refresh_account(account.id()).await.unwrap();
assert_eq!(
result.quota().is_exhausted(),
exhausted,
"{first}, {second}, offset={offset}"
);
}
}
}
#[tokio::test]
async fn reset_drift_requires_consecutive_nonfull_evidence_for_the_pending_window() {
let store = Arc::new(MemoryAccountStore::default());
let id = "acct_drift_interrupted";
create_account(&store, id).await;
let account = store.account(id).unwrap();
let week = Utc::now().timestamp() + 604_800;
let server = MockServer::start().await;
let service = quota_service_with_base_url(&store, reqwest::Client::new(), server.uri());
let mut old = usage((0, SHORT_RESET), (100, week));
old["rate_limit"]["allowed"] = json!(false);
mount_usage(&server, old).await;
service.refresh_account(account.id()).await.unwrap();
for (allowed, percent, reached, exhausted) in [
(Some(true), Some(16), false, true),
(Some(true), None, false, true),
(Some(true), Some(16), false, true),
(Some(false), Some(16), false, true),
(Some(true), Some(16), false, true),
(None, Some(16), false, true),
(Some(true), Some(16), false, true),
(Some(true), Some(0), true, true),
(Some(true), Some(16), false, true),
(Some(true), Some(16), false, false),
] {
let mut fresh = usage((0, SHORT_RESET), (16, week + 2));
if let Some(allowed) = allowed {
fresh["rate_limit"]["allowed"] = json!(allowed);
}
let window = fresh["rate_limit"]["secondary_window"]
.as_object_mut()
.unwrap();
window.insert("limit_reached".into(), json!(reached));
if let Some(percent) = percent {
window.insert("used_percent".into(), json!(percent));
} else {
window.remove("used_percent");
}
mount_usage(&server, fresh).await;
let snapshot = service.refresh_account(account.id()).await.unwrap();
assert_eq!(
snapshot.quota().is_exhausted(),
exhausted,
"allowed={allowed:?}, used={percent:?}, reached={reached}"
);
}
}
#[tokio::test]
async fn weekly_usage_falling_back_within_the_same_window_recovers_after_two_observations() {
// 滑动周窗口的用量可以在同一窗口内回落:reset 不滚动、用量从 100% 降到
@@ -8954,6 +8954,14 @@ async fn official_usage_limit_failure_persists_fact_without_fabricating_usage()
account.quota().evidence(),
Some(QuotaEvidence::UsageLimitReached)
);
assert_eq!(
account.quota().reset_at(),
Some(
chrono::DateTime::from_timestamp(reset_at, 0)
.unwrap()
.into()
)
);
let projected = store
.get_quotas(&[account.id().clone()])
.await
@@ -12570,6 +12578,7 @@ async fn quota_continuation_opening_rejection_projects_replay_without_losing_ups
#[tokio::test]
async fn quota_continuation_stream_rejection_only_projects_before_delivery() {
let reset_at = 1_900_000_000;
for use_websocket in [false, true] {
for semantic_output in [false, true] {
for native_continuation in [false, true] {
@@ -12581,7 +12590,10 @@ async fn quota_continuation_stream_rejection_only_projects_before_delivery() {
if semantic_output {
events.push(json!({"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"hello"}));
}
let original = json!({"type":"response.failed","response":{"id":"resp_quota","error":{"code":"usage_limit_reached","message":"You have reached your usage limit."}}});
let original = json!({"type":"response.failed","response":{"id":"resp_quota","error":{
"code":"usage_limit_reached", "message":"You have reached your usage limit.",
"resets_at": reset_at, "limit_window_minutes": 300
}}});
events.push(original.clone());
let (base_url, _http_server, websocket_server) = if use_websocket {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
@@ -12650,6 +12662,12 @@ async fn quota_continuation_stream_rejection_only_projects_before_delivery() {
}
};
assert_eq!(error.kind(), ProviderErrorKind::QuotaExhausted);
let quota = store.account("acct_provider_contract").unwrap().quota();
assert_eq!(
quota.reset_at(),
Some(SystemTime::UNIX_EPOCH + Duration::from_secs(reset_at))
);
assert_eq!(quota.limit_window_minutes(), Some(300));
assert_eq!(error.send_state(), UpstreamSendState::Sent);
assert_eq!(error.replay_is_safe(), !semantic_output);
assert_eq!(
@@ -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);
+8 -3
View File
@@ -1817,9 +1817,14 @@ OpenAI 授权码交换与令牌刷新请求的连接超时为 30 秒,单次上
复核;reset 后前 5 分钟最小查询间隔为 30 秒,之后仍耗尽则改为 5 分钟。正常账号有非零用量或触顶窗口时,仍在
`resetAt + 2 分钟` 后复核,未更新则按 30 分钟间隔重试。后台每 30 秒检查条件,实际恢复时间还受
排队、查询耗时和上游传播影响;查询失败也遵守间隔。无可用点数时,到期前仍按原窗口证据恢复;
本次耗尽之后的已记录窗口 reset 全部到期后,新查询明确 `allowed=true` 可解除限制,即使用量仍为
100%。未知 reset 或再次拒绝后残留的旧 reset 仍走原规则,不复用旧边界解封;时间到期本身不会
解除限制,也不会将展示用量归零
已确认耗尽的窗口全部到期后,新查询明确 `allowed=true` 可解除限制,即使用量仍为 100%。
若 `usage_limit_reached` 给出 `limit_window_minutes` 且唯一对应一个通用窗口,按该窗口复核,同时保留其他已触顶窗口。
错误未给出 `resets_at` 时,采用该窗口已知的重置时间;具名额度桶的时长不用于识别通用窗口。
若仍无法归属窗口且没有窗口明确触顶,按错误给出的未来重置时间复核。
到期后的查询须明确放行,覆盖此前已知的通用窗口,并且每个通用窗口都有未触顶的使用率。
未知或早于本次拒绝的重置时间仍按窗口证据复核,到期本身不会解除限制或将展示用量归零。
上游明确放行时,连续两次查询都有该窗口的使用率且未触顶,即可解除该窗口,即使重置时间持续向后移动
- 账号仍待恢复时,窗口展示最近观测的使用率,缺失时为 `null`。仅将已明确触顶的窗口展示为 100%
- 停用的 OpenAI 与 xAI OAuth 账号退出客户端请求调度,仍按各自策略续期 Token、查询额度。
成功刷新后账号保持停用。无 refresh token 或凭据已进入失效、无效、
封禁状态的账号不参加后台自动续期
+3 -2
View File
@@ -1026,8 +1026,9 @@ OpenAI Provider 统一解释点数可用性,主动查询、耗尽恢复与失
Store 在账号事务内保存点数放行依据与快照;关闭自动使用时撤销该依据,迟到观测不能绕过开关。
放行条件与默认值见[账号额度 API](api.md#查询与账号字段)。
无可用点数的失败回读保留已确认的拒绝;常规刷新在到期前仍按窗口证据恢复,本次耗尽之后的
已记录窗口 reset 全部到期后可依据新的明确放行观察恢复。查询沿用 credential revision 与
观察时间隔离,不允许旧查询撤销较新的失败;恢复条件和后台复核节奏见 [账号额度与状态](api.md#openai-身份额度与状态)
已确认窗口 reset 全部到期后可依据新的明确放行观察恢复。拒绝给出的窗口时长随该次耗尽事实持久化,
OpenAI Provider 将其与通用窗口匹配。无法确认耗尽窗口时,保留拒绝给出的复查时间和
此前已知的通用窗口。查询沿用 credential revision 与观察时间隔离,不允许旧查询撤销较新的失败;恢复条件和后台复核节奏见 [账号额度与状态](api.md#openai-身份额度与状态)
OpenAI 订阅周期属于按需个人信息,不是额度事实。Admin 账号用例通过现有 Provider 管理端口并发读取
个人资料统计与订阅,汇聚为一次只读响应;Provider 继续拥有各自的认证、出站代理与上游协议处理。
+4 -4
View File
@@ -1,7 +1,7 @@
version: 3.54.5
published:
'3':
stable: 3.54.4
rc: 3.54.4
beta: 3.54.4
alpha: 3.54.4
stable: 3.54.5
rc: 3.54.5
beta: 3.54.5
alpha: 3.54.5