mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-24 16:00:49 +00:00
fix(quota): confirm recovery despite drifting reset times
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -20,9 +20,7 @@ pub(super) struct QuotaRecovery {
|
||||
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, ()>,
|
||||
}
|
||||
@@ -117,8 +115,9 @@ impl QuotaRecovery {
|
||||
|
||||
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 && refreshed.quota().access() != QuotaAccessState::Allowed {
|
||||
if has_window_hint && access != QuotaAccessState::Allowed {
|
||||
self.candidates.clear();
|
||||
for window in windows().filter(|w| w.limit_reached()) {
|
||||
self.pending
|
||||
@@ -131,7 +130,7 @@ impl QuotaRecovery {
|
||||
self.unmatched.take_if(|reset| reset.recovered(refreshed));
|
||||
// 已确认窗口全部到期后,明确放行可以覆盖滞后的百分比
|
||||
if !self.pending.is_empty()
|
||||
&& refreshed.quota().access() == QuotaAccessState::Allowed
|
||||
&& 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());
|
||||
@@ -150,27 +149,29 @@ impl QuotaRecovery {
|
||||
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() {
|
||||
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;
|
||||
}
|
||||
if window_reset_recovered(window, previous_reset) {
|
||||
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 {
|
||||
@@ -190,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,
|
||||
|
||||
@@ -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!(
|
||||
|
||||
+3
-1
@@ -1822,7 +1822,9 @@ OpenAI 授权码交换与令牌刷新请求的连接超时为 30 秒,单次上
|
||||
错误未给出 `resets_at` 时,采用该窗口已知的重置时间;具名额度桶的时长不用于识别通用窗口。
|
||||
若仍无法归属窗口且没有窗口明确触顶,按错误给出的未来重置时间复核。
|
||||
到期后的查询须明确放行,覆盖此前已知的通用窗口,并且每个通用窗口都有未触顶的使用率。
|
||||
未知或早于本次拒绝的重置时间仍按窗口证据复核;时间到期本身不会解除限制或将展示用量归零
|
||||
未知或早于本次拒绝的重置时间仍按窗口证据复核,到期本身不会解除限制或将展示用量归零。
|
||||
上游明确放行时,连续两次查询都有该窗口的使用率且未触顶,即可解除该窗口,即使重置时间持续向后移动
|
||||
- 账号仍待恢复时,窗口展示最近观测的使用率,缺失时为 `null`。仅将已明确触顶的窗口展示为 100%
|
||||
- 停用的 OpenAI 与 xAI OAuth 账号退出客户端请求调度,仍按各自策略续期 Token、查询额度。
|
||||
成功刷新后账号保持停用。无 refresh token 或凭据已进入失效、无效、
|
||||
封禁状态的账号不参加后台自动续期
|
||||
|
||||
Reference in New Issue
Block a user