fix(openai): preserve quota observation timestamps

Keep header and stream quota facts tied to their collection time so delayed responses cannot replace a newer refresh. Filter stale observations again on merge conflicts and retain timestamps through failure and warmup paths.

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Zyy
2026-12-01 15:27:03 +08:00
co-authored by Codex
parent b4bb97d1dc
commit e0b0ab14da
21 changed files with 504 additions and 105 deletions
@@ -1,60 +1,30 @@
//! 推理响应携带的额度观察合并与 Provider 快照规范化
use super::*;
use crate::transport::CodexRateLimitObservation;
impl CodexCredentialQuotaService {
/// 把正常推理响应携带的限流事实合并进 Provider 原始 quota JSON
pub async fn synchronize_passive_headers(
&self,
account: &ProviderAccount,
headers: &[(String, String)],
) -> Result<bool, CodexCredentialQuotaError> {
let Some(rate_limits) = parse_rate_limit_headers(headers) else {
return Ok(false);
};
self.synchronize_passive_rate_limits(account, std::slice::from_ref(&rate_limits))
.await
}
/// 把成功推理响应中采集的结构化限流观察合并后单次落库
pub async fn synchronize_passive_rate_limits(
&self,
account: &ProviderAccount,
rate_limits: &[ParsedRateLimits],
observations: &[CodexRateLimitObservation],
) -> Result<bool, CodexCredentialQuotaError> {
self.synchronize_passive_rate_limits_with_usage(account, rate_limits, true)
self.synchronize_passive_rate_limits_with_usage(account, observations, true)
.await
}
pub(crate) async fn synchronize_passive_rate_limits_with_usage(
&self,
account: &ProviderAccount,
rate_limits: &[ParsedRateLimits],
observations: &[CodexRateLimitObservation],
request_used_quota: bool,
) -> Result<bool, CodexCredentialQuotaError> {
if account.authentication_kind() != crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH
|| rate_limits.is_empty()
|| observations.is_empty()
{
return Ok(false);
}
let has_quota_facts = rate_limits.iter().any(|observation| {
observation
.limits
.values()
.any(|details| passive_rate_limit_snapshot(details).is_some())
});
// 只用本次响应明确携带的套餐更新账号,不能把合并前的旧快照重新当作新证据
let observed_plan = rate_limits
.iter()
.rev()
.filter_map(|observation| {
observation.plan_type.as_deref().filter(|plan| {
!plan.trim().is_empty() && !plan.trim().eq_ignore_ascii_case("unknown")
})
})
.next();
// 重读发生冲突的快照时仍用响应到达时间,不能把迟到的用量当成新证据
let observed_at = SystemTime::now();
for _ in 0..QUOTA_MERGE_ATTEMPTS {
let existing = self
.store
@@ -68,9 +38,36 @@ impl CodexCredentialQuotaService {
let merge_base = QuotaMergeBase {
observed_at: existing.as_ref().map(|obs| obs.observed_at),
};
if merge_base.observed_at.is_some_and(|at| at >= observed_at) {
// 每条事实按采集时间过滤,后来的具名桶事件不能替旧的通用额度续期
// 冲突重读也重新筛选,流结束和落库重试都不产生新的上游观测
let fresh: Vec<_> = observations
.iter()
.filter(|observation| {
merge_base
.observed_at
.is_none_or(|at| observation.observed_at > at)
})
.collect();
let Some(observed_at) = fresh
.iter()
.map(|observation| observation.observed_at)
.max()
else {
return Ok(false);
}
};
let has_quota_facts = fresh.iter().any(|observation| {
observation
.rate_limits
.limits
.values()
.any(|details| passive_rate_limit_snapshot(details).is_some())
});
// 套餐也只取本轮新事实,不能把旧响应里的套餐重新写回账号
let observed_plan = fresh.iter().rev().find_map(|observation| {
observation.rate_limits.plan_type.as_deref().filter(|plan| {
!plan.trim().is_empty() && !plan.trim().eq_ignore_ascii_case("unknown")
})
});
let previous = if account.quota_settings().is_empty() {
None
} else {
@@ -87,8 +84,12 @@ impl CodexCredentialQuotaService {
let prior = existing_state.unwrap_or_else(|| account.quota());
let (mut quota, updated_default) = merge_passive_quota(
existing,
rate_limits,
request_used_quota.then_some(observed_at),
fresh.iter().map(|observation| {
(
&observation.rate_limits,
request_used_quota.then_some(observation.observed_at),
)
}),
);
let mut snapshot = parse_account_quota_snapshot(
account.id().clone(),
@@ -98,7 +99,9 @@ impl CodexCredentialQuotaService {
)?;
snapshot.retain_limit_evidence(account.quota_settings(), previous.as_ref(), &mut quota);
let credit_access = prior.evidence() == Some(QuotaEvidence::CreditsAvailable);
let fresh_credits = rate_limits.iter().any(|limits| limits.credits.is_some());
let fresh_credits = fresh
.iter()
.any(|observation| observation.rate_limits.credits.is_some());
// 具名桶和元数据不改变套餐结论;点数不能再用时,仍须撤销原先仅凭点数的放行
let subscription = if !updated_default
|| (snapshot.quota().access() == QuotaAccessState::Unknown
@@ -156,21 +159,20 @@ pub(crate) fn observed_quota_window(
key: &str,
) -> Option<CodexQuotaWindow> {
// 只解释本次响应,不借用当前快照补全旧观测或把具名桶镜像当作账号额度
let (quota, _) = merge_passive_quota(Map::new(), std::slice::from_ref(parsed), None);
let (quota, _) = merge_passive_quota(Map::new(), std::iter::once((parsed, None)));
snapshot::quota_windows(&quota)
.ok()?
.into_iter()
.find(|window| window.key() == key)
}
fn merge_passive_quota(
fn merge_passive_quota<'a>(
mut quota: Map<String, Value>,
observations: &[ParsedRateLimits],
used_at: Option<SystemTime>,
observations: impl IntoIterator<Item = (&'a ParsedRateLimits, Option<SystemTime>)>,
) -> (Map<String, Value>, bool) {
let mut updated_default = false;
let mut snapshots = RateLimitSnapshotsByLimitId::take_from_document(&mut quota);
for rate_limits in observations {
for (rate_limits, used_at) in observations {
let default_is_named_alias = default_limit_is_named_alias(rate_limits);
let mut resolved_limit_ids = BTreeMap::new();
for (wire_limit_id, details) in &rate_limits.limits {
@@ -1,6 +1,7 @@
//! 账号额度窗口预热与完成事件校验
use super::*;
use crate::transport::CodexRateLimitObservation;
enum WarmupDecision<'a> {
Ready,
@@ -263,30 +264,38 @@ impl CodexCredentialQuotaService {
.await
.map_err(|_| "request_rejected")?;
let terminal = consume_warmup_sse(&mut response).await;
let mut observations = response
.diagnostics
.headers_observed_at
.and_then(|observed_at| {
parse_rate_limit_headers(&response.rate_limit_headers).map(|rate_limits| {
CodexRateLimitObservation {
rate_limits,
observed_at,
}
})
})
.into_iter()
.collect::<Vec<_>>();
let rate_limit_updates = match response.rate_limit_updates.as_ref() {
Some(updates) => std::mem::take(&mut *updates.lock().await),
None => Vec::new(),
};
Ok::<_, &'static str>((terminal, response.rate_limit_headers, rate_limit_updates))
observations.extend(rate_limit_updates);
Ok::<_, &'static str>((terminal, observations))
})
.await;
match attempt {
Ok(Ok((terminal, headers, rate_limit_updates))) => {
Ok(Ok((terminal, observations))) => {
match terminal {
Ok(()) => {
// 被动额度同步会把成功请求的窗口事实标为可用,失败流不能复用该结论
if !headers.is_empty()
&& let Err(error) =
self.synchronize_passive_headers(account, &headers).await
{
tracing::warn!(account_id = %account.id(), error = %error, "OpenAI warmup rate-limit header sync failed");
}
if !rate_limit_updates.is_empty()
if !observations.is_empty()
&& let Err(error) = self
.synchronize_passive_rate_limits(account, &rate_limit_updates)
.synchronize_passive_rate_limits(account, &observations)
.await
{
tracing::warn!(account_id = %account.id(), error = %error, "OpenAI warmup rate-limit event sync failed");
tracing::warn!(account_id = %account.id(), error = %error, "OpenAI warmup rate-limit sync failed");
}
summary.warmed_up += 1;
tracing::info!(
@@ -730,6 +730,7 @@ pub(super) fn cold_json_response_stream(request: ColdJsonResponse) -> EventStrea
&request.quota,
&active_account,
&response.rate_limit_headers,
response.diagnostics.headers_observed_at,
image_endpoint,
true,
)
@@ -1015,7 +1016,7 @@ pub(super) fn cold_response_stream(response: ColdResponse) -> EventStream {
}
let failure_rate_limit_headers = response.rate_limit_headers.clone();
let mut passive_quota_observation =
OpenAiPassiveQuotaObservation::new(response.rate_limit_headers);
OpenAiPassiveQuotaObservation::new(response.rate_limit_headers, response.diagnostics.headers_observed_at);
let rate_limit_updates = response.rate_limit_updates;
let response_metadata_updates = response.response_metadata_updates;
// 同协议保留原始帧;canonical 解析只提取计费、续接和状态事实
@@ -51,6 +51,7 @@ pub(super) struct MappedProviderFailure {
pub(super) set_cookie_headers: Vec<String>,
pub(super) response_origin: Option<Url>,
pub(super) rate_limit_headers: Vec<(String, String)>,
pub(super) headers_observed_at: Option<std::time::SystemTime>,
pub(super) observation: Option<ProviderResponseObservation>,
pub(super) capture_response_cookies: bool,
}
@@ -67,6 +68,7 @@ impl MappedProviderFailure {
set_cookie_headers: Vec::new(),
response_origin: None,
rate_limit_headers: Vec::new(),
headers_observed_at: None,
observation: None,
capture_response_cookies: false,
}
@@ -342,6 +344,7 @@ pub(super) async fn apply_failure(
context.quota,
account,
&failure.rate_limit_headers,
failure.headers_observed_at,
context.image_endpoint,
false,
)
@@ -1624,6 +1627,7 @@ pub(super) fn map_upstream_failure(
set_cookie_headers: failure.set_cookie_headers,
response_origin: failure.response_origin,
rate_limit_headers: failure.rate_limit_headers,
headers_observed_at: failure.headers_observed_at,
observation,
capture_response_cookies: !matches!(
category,
@@ -46,9 +46,7 @@ use gateway_core::task::{
WorkerRunnable, WorkerSchedule, WorkerTaskError,
};
use gateway_core::upstream::{UpstreamSendState, UpstreamTransport};
use gateway_protocol::openai::events::{
ParsedRateLimits, parse_rate_limit_headers, rate_limits_to_header_pairs,
};
use gateway_protocol::openai::events::{parse_rate_limit_headers, rate_limits_to_header_pairs};
use gateway_protocol::openai::{CodexGuardianRole, OPENAI_PROTOCOL, codex_guardian_role};
use reqwest::{Client, header::HeaderValue};
use secrecy::{ExposeSecret, SecretString};
@@ -1,6 +1,7 @@
//! OpenAI 请求、响应与 transport 观测事实归一化
use super::*;
use crate::transport::CodexRateLimitObservation;
pub(super) fn endpoint_requested_model(
payload: &gateway_core::operation::RawJsonPayload,
@@ -39,21 +40,34 @@ pub(super) struct OpenAiResponseObservationState {
}
pub(super) struct OpenAiPassiveQuotaObservation {
rate_limits: Vec<ParsedRateLimits>,
rate_limits: Vec<CodexRateLimitObservation>,
}
impl OpenAiPassiveQuotaObservation {
pub(super) fn new(headers: Vec<(String, String)>) -> Self {
pub(super) fn new(
headers: Vec<(String, String)>,
observed_at: Option<std::time::SystemTime>,
) -> Self {
Self {
rate_limits: parse_rate_limit_headers(&headers).into_iter().collect(),
rate_limits: observed_at
.and_then(|observed_at| {
parse_rate_limit_headers(&headers).map(|rate_limits| {
CodexRateLimitObservation {
rate_limits,
observed_at,
}
})
})
.into_iter()
.collect(),
}
}
pub(super) fn observe(&mut self, updates: &[ParsedRateLimits]) {
pub(super) fn observe(&mut self, updates: &[CodexRateLimitObservation]) {
self.rate_limits.extend_from_slice(updates);
}
pub(super) fn rate_limits(&self) -> &[ParsedRateLimits] {
pub(super) fn rate_limits(&self) -> &[CodexRateLimitObservation] {
&self.rate_limits
}
}
@@ -493,17 +507,19 @@ pub(super) fn insert_first_timing(target: &mut Option<u64>, started_at: Instant)
pub(super) async fn take_rate_limit_updates(
updates: Option<&CodexRateLimitUpdates>,
) -> Vec<ParsedRateLimits> {
) -> Vec<CodexRateLimitObservation> {
let Some(updates) = updates else {
return Vec::new();
};
std::mem::take(&mut *updates.lock().await)
}
pub(super) fn rate_limit_update_headers(updates: &[ParsedRateLimits]) -> Vec<(String, String)> {
pub(super) fn rate_limit_update_headers(
updates: &[CodexRateLimitObservation],
) -> Vec<(String, String)> {
updates
.iter()
.flat_map(rate_limits_to_header_pairs)
.flat_map(|observation| rate_limits_to_header_pairs(&observation.rate_limits))
.collect()
}
@@ -532,7 +548,7 @@ pub(super) fn terminal_response_is_incomplete(events: &[ProviderEvent]) -> bool
pub(super) async fn synchronize_passive_quota(
quota: &CodexCredentialQuotaService,
account: &ProviderAccount,
rate_limits: &[ParsedRateLimits],
rate_limits: &[CodexRateLimitObservation],
request_used_quota: bool,
) {
if rate_limits.is_empty() {
@@ -554,9 +570,13 @@ pub(super) async fn synchronize_passive_quota_headers(
quota: &CodexCredentialQuotaService,
account: &ProviderAccount,
headers: &[(String, String)],
observed_at: Option<std::time::SystemTime>,
image_endpoint: bool,
request_used_quota: bool,
) {
let Some(observed_at) = observed_at else {
return;
};
let parsed = if image_endpoint {
gateway_protocol::openai::events::parse_image_rate_limit_headers(headers)
} else {
@@ -566,7 +586,10 @@ pub(super) async fn synchronize_passive_quota_headers(
synchronize_passive_quota(
quota,
account,
std::slice::from_ref(&rate_limits),
&[CodexRateLimitObservation {
rate_limits,
observed_at,
}],
request_used_quota,
)
.await;
@@ -944,7 +944,10 @@ async fn append_http_sse_rate_limit_updates(
let Some(rate_limits) = events::parse_rate_limits_event_raw(&event.data) else {
continue;
};
observations.push(rate_limits);
observations.push(crate::transport::CodexRateLimitObservation {
rate_limits,
observed_at: std::time::SystemTime::now(),
});
}
}
if !observations.is_empty() {
@@ -85,6 +85,7 @@ pub struct CodexUpstreamFailure {
pub(crate) response_origin: Option<url::Url>,
pub(crate) set_cookie_headers: Vec<String>,
pub(crate) rate_limit_headers: Vec<(String, String)>,
pub(crate) headers_observed_at: Option<std::time::SystemTime>,
pub(crate) send_phase: CodexUpstreamSendPhase,
category: CodexFailureCategory,
}
@@ -132,6 +133,7 @@ impl CodexUpstreamFailure {
response_origin: diagnostics.response_origin.clone(),
set_cookie_headers: set_cookie_headers.to_vec(),
rate_limit_headers: rate_limit_headers.to_vec(),
headers_observed_at: diagnostics.headers_observed_at,
send_phase,
category,
}
@@ -188,6 +190,7 @@ impl CodexUpstreamFailure {
response_origin: diagnostics.response_origin.clone(),
set_cookie_headers: set_cookie_headers.to_vec(),
rate_limit_headers: rate_limit_headers.to_vec(),
headers_observed_at: diagnostics.headers_observed_at,
send_phase,
category,
}
@@ -321,6 +324,8 @@ enum UpstreamFailureSource {
#[derive(Clone, Default, PartialEq, Eq)]
pub struct CodexUpstreamDiagnostics {
/// 响应头的采集时间,不随正文消费或连接复用推进
pub headers_observed_at: Option<std::time::SystemTime>,
pub status_code: Option<u16>,
pub request_id: Option<String>,
pub identity_authorization_error: Option<String>,
@@ -381,6 +386,7 @@ impl CodexUpstreamDiagnostics {
pub fn from_headers(status_code: Option<u16>, headers: &HeaderMap) -> Self {
Self {
headers_observed_at: Some(std::time::SystemTime::now()),
status_code,
request_id: first_header(headers, UPSTREAM_REQUEST_ID_HEADERS),
identity_authorization_error: header_value(
@@ -60,7 +60,7 @@ pub use self::{
CodexRateLimitResetCredit, CodexRateLimitResetCredits,
CodexRateLimitResetCreditsConsumeResult, MAX_CODEX_RESET_CREDITS_BODY_BYTES,
},
response_meta::CodexResponseMetadata,
response_meta::{CodexRateLimitObservation, CodexResponseMetadata},
usage::MAX_CODEX_USAGE_BODY_BYTES,
websocket::{
CodexWebSocketPool, CodexWebSocketPoolConfig, CodexWebSocketPoolKey, WebSocketPoolDecision,
@@ -1,13 +1,22 @@
//! 上游响应元数据提取辅助
use std::fmt;
use std::{fmt, time::SystemTime};
use bytes::Bytes;
use gateway_protocol::openai::events::{is_codex_quota_header_name, is_rate_limit_header_name};
use gateway_protocol::openai::events::{
ParsedRateLimits, is_codex_quota_header_name, is_rate_limit_header_name,
};
use reqwest::header::{HeaderMap, SET_COOKIE};
use super::diagnostics::CodexUpstreamDiagnostics;
/// 额度事实与采集时间一起跨越流缓冲和持久化等待
#[derive(Debug, Clone)]
pub struct CodexRateLimitObservation {
pub rate_limits: ParsedRateLimits,
pub observed_at: SystemTime,
}
/// Codex Responses 上游响应元数据
#[derive(Clone, Default, PartialEq, Eq)]
pub struct CodexResponseMetadata {
@@ -8,12 +8,12 @@ use std::{pin::Pin, sync::Arc};
use bytes::Bytes;
use futures::Stream;
use gateway_protocol::openai::events::ParsedRateLimits;
use tokio::sync::Mutex;
use uuid::Uuid;
use crate::transport::{
diagnostics::CodexUpstreamDiagnostics, response_meta::CodexResponseMetadata,
diagnostics::CodexUpstreamDiagnostics,
response_meta::{CodexRateLimitObservation, CodexResponseMetadata},
};
use super::error::CodexWebSocketExchangeError;
@@ -54,7 +54,7 @@ pub struct CodexWebSocketStreamingExchange {
pub type CodexWebSocketTextStream =
Pin<Box<dyn Stream<Item = Result<Bytes, CodexWebSocketExchangeError>> + Send + 'static>>;
/// live 流中的结构化限流动态更新
pub type CodexWebSocketRateLimitUpdates = Arc<Mutex<Vec<ParsedRateLimits>>>;
pub type CodexWebSocketRateLimitUpdates = Arc<Mutex<Vec<CodexRateLimitObservation>>>;
/// 单次响应的动态 metadata,与连接池保存的握手快照隔离
#[derive(Debug, Default)]
pub struct CodexWebSocketResponseMetadataUpdate {
@@ -365,7 +365,11 @@ async fn forward_websocket_response_stream(state: WebSocketStreamForwardState) {
}
let terminal = match reduced.action {
ExchangeAction::RateLimits(rate_limits) => {
rate_limit_updates.lock().await.push(rate_limits);
let observation = crate::transport::CodexRateLimitObservation {
rate_limits,
observed_at: std::time::SystemTime::now(),
};
rate_limit_updates.lock().await.push(observation);
continue;
}
ExchangeAction::Forward { terminal } => terminal,
@@ -84,7 +84,7 @@ async fn observe_request(
let observation = parse_rate_limits_event(&event).unwrap();
assert!(
service
.synchronize_passive_rate_limits(&account, &[observation])
.synchronize_passive_rate_limits(&account, &rate_limit_observations(&[observation]))
.await
.unwrap()
);
@@ -257,7 +257,10 @@ async fn passive_exhaustion_requires_fresh_credits_and_revokes_access_when_spent
wire["type"] = json!("codex.rate_limits");
let update = parse_rate_limits_event(&wire).expect("rate limit event");
service
.synchronize_passive_rate_limits(&store.account(id).unwrap(), &[update])
.synchronize_passive_rate_limits(
&store.account(id).unwrap(),
&rate_limit_observations(&[update]),
)
.await
.unwrap();
assert_eq!(
@@ -239,7 +239,10 @@ async fn successful_inference_at_the_subscription_limit_stops_further_scheduling
assert!(
service
.synchronize_passive_headers(&account, &headers)
.synchronize_passive_rate_limits(
&account,
&crate::support::quota_header_observations(&headers, SystemTime::now())
)
.await
.expect("passive quota")
);
@@ -287,7 +290,10 @@ async fn passive_quota_updates_keep_core_and_model_specific_buckets_independent(
),
];
service
.synchronize_passive_headers(&account, &initial_headers)
.synchronize_passive_rate_limits(
&account,
&crate::support::quota_header_observations(&initial_headers, SystemTime::now()),
)
.await
.expect("initial passive quota");
@@ -322,7 +328,10 @@ async fn passive_quota_updates_keep_core_and_model_specific_buckets_independent(
),
];
service
.synchronize_passive_headers(&account, &spark_headers)
.synchronize_passive_rate_limits(
&account,
&crate::support::quota_header_observations(&spark_headers, SystemTime::now()),
)
.await
.expect("Spark passive quota");
@@ -354,7 +363,10 @@ async fn passive_quota_updates_keep_core_and_model_specific_buckets_independent(
),
];
service
.synchronize_passive_headers(&account, &core_headers)
.synchronize_passive_rate_limits(
&account,
&crate::support::quota_header_observations(&core_headers, SystemTime::now()),
)
.await
.expect("core passive quota");
@@ -425,7 +437,10 @@ async fn websocket_additional_rate_limit_resolves_by_name_without_touching_core(
),
];
service
.synchronize_passive_headers(&account, &initial_headers)
.synchronize_passive_rate_limits(
&account,
&crate::support::quota_header_observations(&initial_headers, SystemTime::now()),
)
.await
.expect("initial quota metadata");
@@ -458,7 +473,10 @@ async fn websocket_additional_rate_limit_resolves_by_name_without_touching_core(
});
let observation = parse_rate_limits_event(&event).expect("WebSocket rate-limit event");
service
.synchronize_passive_rate_limits(&account, std::slice::from_ref(&observation))
.synchronize_passive_rate_limits(
&account,
&rate_limit_observations(std::slice::from_ref(&observation)),
)
.await
.expect("WebSocket passive quota");
@@ -582,7 +600,7 @@ async fn passive_quota_observation_preserves_account_egress() {
.unwrap();
quota_service(&store)
.synchronize_passive_rate_limits(&account, &[observation])
.synchronize_passive_rate_limits(&account, &rate_limit_observations(&[observation]))
.await
.unwrap();
@@ -599,12 +617,15 @@ async fn passive_plan_observations_update_account_without_replaying_stale_plan()
let original = store.account("acct_passive_plan").unwrap();
let service = quota_service(&store);
service
.synchronize_passive_headers(
.synchronize_passive_rate_limits(
&original,
&[
("x-codex-plan-type".to_owned(), "plus".to_owned()),
("x-codex-primary-used-percent".to_owned(), "5".to_owned()),
],
&crate::support::quota_header_observations(
&[
("x-codex-plan-type".to_owned(), "plus".to_owned()),
("x-codex-primary-used-percent".to_owned(), "5".to_owned()),
],
SystemTime::now(),
),
)
.await
.unwrap();
@@ -618,7 +639,7 @@ async fn passive_plan_observations_update_account_without_replaying_stale_plan()
"rate_limits": {"primary": {"used_percent": 5, "window_minutes": 300, "reset_at": 1900000000}}
})).unwrap();
service
.synchronize_passive_rate_limits(&original, &[upgrade])
.synchronize_passive_rate_limits(&original, &rate_limit_observations(&[upgrade]))
.await
.unwrap();
assert_eq!(
@@ -626,9 +647,12 @@ async fn passive_plan_observations_update_account_without_replaying_stale_plan()
Some("pro")
);
service
.synchronize_passive_headers(
.synchronize_passive_rate_limits(
&original,
&[("x-codex-primary-used-percent".to_owned(), "6".to_owned())],
&crate::support::quota_header_observations(
&[("x-codex-primary-used-percent".to_owned(), "6".to_owned())],
SystemTime::now(),
),
)
.await
.unwrap();
@@ -644,9 +668,12 @@ async fn passive_plan_observations_update_account_without_replaying_stale_plan()
persist_quota_state(&store, &original, state).await;
// 仅有套餐的新观察不能清除既有额度耗尽结论
service
.synchronize_passive_headers(
.synchronize_passive_rate_limits(
&original,
&[("x-codex-plan-type".to_owned(), "plus".to_owned())],
&crate::support::quota_header_observations(
&[("x-codex-plan-type".to_owned(), "plus".to_owned())],
SystemTime::now(),
),
)
.await
.unwrap();
@@ -692,6 +719,95 @@ async fn initial_quota_worker_synchronizes_account_plan() {
);
}
#[tokio::test]
async fn passive_merge_conflict_discards_only_observations_older_than_refresh() {
use gateway_protocol::openai::events::parse_rate_limit_headers;
use provider_openai::transport::CodexRateLimitObservation;
let store = Arc::new(MemoryAccountStore::default());
let id = "acct_quota_order";
create_account(&store, id).await;
let account = store.account(id).unwrap();
let service = quota_service(&store);
let newest = SystemTime::now();
let refreshed_at = newest - Duration::from_secs(1);
let observations = [
CodexRateLimitObservation {
rate_limits: parse_rate_limits_event(&json!({
"type": "codex.rate_limits", "plan_type": "plus",
"credits": {"has_credits": true, "balance": "42"},
"rate_limits": {"primary": {"used_percent": 95, "window_minutes": 10080}}
}))
.unwrap(),
observed_at: newest - Duration::from_secs(2),
},
CodexRateLimitObservation {
rate_limits: parse_rate_limit_headers(&[
(
"x-codex-bengalfox-primary-used-percent".to_owned(),
"13".to_owned(),
),
(
"x-codex-bengalfox-primary-window-minutes".to_owned(),
"300".to_owned(),
),
])
.unwrap(),
observed_at: newest,
},
];
let (read, commit) = store.hold_next_quota_read();
let mut passive =
std::pin::pin!(service.synchronize_passive_rate_limits(&account, &observations));
tokio::select! {
result = &mut passive => panic!("write finished before refresh: {result:?}"),
ready = read => ready.unwrap(),
}
service
.synchronize_passive_rate_limits(
&account,
&crate::support::quota_header_observations(
&[
("x-codex-primary-used-percent".to_owned(), "0".to_owned()),
(
"x-codex-primary-window-minutes".to_owned(),
"10080".to_owned(),
),
("x-codex-plan-type".to_owned(), "pro".to_owned()),
],
refreshed_at,
),
)
.await
.unwrap();
let refreshed_usage =
store.quota_json(id).unwrap()["_cpr_bucket_last_used_at"]["codex"].clone();
commit.send(()).unwrap();
assert!(passive.await.unwrap());
let snapshot = service.read_account(account.id()).await.unwrap().unwrap();
assert_eq!(snapshot.observed_at(), newest);
for (source, percent) in [("codex", 0.0), ("codex_bengalfox", 13.0)] {
assert!(
snapshot
.windows()
.iter()
.any(|window| window.source() == source && window.used_percent() == Some(percent))
);
}
assert_eq!(store.account(id).unwrap().plan_type(), Some("pro"));
assert!(snapshot.credits().is_none());
assert_eq!(
store.quota_json(id).unwrap()["_cpr_bucket_last_used_at"]["codex"],
refreshed_usage
);
assert!(
!service
.synchronize_passive_rate_limits(&account, &observations)
.await
.unwrap()
);
}
#[tokio::test]
async fn concurrent_named_usage_preserves_newly_paused_general_window() {
let store = Arc::new(MemoryAccountStore::default());
@@ -735,7 +851,9 @@ async fn concurrent_named_usage_preserves_newly_paused_general_window() {
ready = read => ready.unwrap(),
}
let (read, commit_passive) = store.hold_next_quota_read();
let mut passive = std::pin::pin!(service.synchronize_passive_headers(&account, &named));
let observations = crate::support::quota_header_observations(&named, SystemTime::now());
let mut passive =
std::pin::pin!(service.synchronize_passive_rate_limits(&account, &observations));
tokio::select! {
result = &mut passive => panic!("passive write finished before merge: {result:?}"),
ready = read => ready.unwrap(),
@@ -1050,7 +1168,7 @@ async fn passive_credit_updates_replace_balance_without_changing_quota_access()
}))
.unwrap();
service
.synchronize_passive_rate_limits(&account, &[initial])
.synchronize_passive_rate_limits(&account, &rate_limit_observations(&[initial]))
.await
.unwrap();
for (wire, expected) in [
@@ -1064,7 +1182,7 @@ async fn passive_credit_updates_replace_balance_without_changing_quota_access()
parse_rate_limits_event(&json!({"type": "codex.rate_limits", "credits": wire}))
.unwrap();
service
.synchronize_passive_rate_limits(&account, &[update])
.synchronize_passive_rate_limits(&account, &rate_limit_observations(&[update]))
.await
.unwrap();
let snapshot = service.read_account(account.id()).await.unwrap().unwrap();
@@ -1073,3 +1191,18 @@ async fn passive_credit_updates_replace_balance_without_changing_quota_access()
assert_eq!(snapshot.quota().access(), QuotaAccessState::Allowed);
}
}
fn rate_limit_observations(
limits: &[gateway_protocol::openai::events::ParsedRateLimits],
) -> Vec<provider_openai::transport::CodexRateLimitObservation> {
limits
.iter()
.cloned()
.map(
|rate_limits| provider_openai::transport::CodexRateLimitObservation {
rate_limits,
observed_at: SystemTime::now(),
},
)
.collect()
}
@@ -242,7 +242,10 @@ async fn fresh_reset_observation_should_clear_previous_scheduling_signals() {
];
assert!(
service
.synchronize_passive_headers(&account, &headers)
.synchronize_passive_rate_limits(
&account,
&crate::support::quota_header_observations(&headers, SystemTime::now())
)
.await
.expect("reset observation")
);
@@ -2972,7 +2972,10 @@ async fn image_quota_headers_keep_the_codex_weekly_window_and_access_state() {
]
.map(|(name, value)| (name.to_owned(), value.to_owned()));
quota
.synchronize_passive_headers(&account, &core_headers)
.synchronize_passive_rate_limits(
&account,
&crate::support::quota_header_observations(&core_headers, SystemTime::now()),
)
.await
.expect("initial weekly quota");
let initial = quota.read_account(account.id()).await.unwrap().unwrap();
@@ -3037,7 +3040,10 @@ async fn image_quota_headers_keep_the_codex_weekly_window_and_access_state() {
assert_eq!(store.account(account_id).unwrap().quota(), initial.quota());
quota
.synchronize_passive_headers(&account, &core_headers)
.synchronize_passive_rate_limits(
&account,
&crate::support::quota_header_observations(&core_headers, SystemTime::now()),
)
.await
.expect("next Codex quota observation");
let refreshed = quota.read_account(account.id()).await.unwrap().unwrap();
@@ -2,6 +2,189 @@
use super::*;
#[tokio::test]
async fn inflight_quota_observations_preserve_a_newer_refresh() {
for websocket in [false, true] {
for headers in [false, true] {
for ending in ["completed", "failed", "disconnect"] {
let store = Arc::new(MemoryAccountStore::default());
let id = "acct_provider_contract";
create_account(&store, id).await;
let reset_at = Utc::now().timestamp() + 604800;
let (base_url, release, server) =
paused_quota_stream(websocket, headers, ending, reset_at - 3600).await;
let provider = provider_with_base_url(&store, base_url);
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object(
"openai",
json!({"model": "gpt-5.4", "input": "hello"})
.as_object()
.unwrap()
.clone(),
)
.unwrap()
.with_context(Map::from_iter([(
"use_websocket".to_owned(),
json!(websocket),
)])),
));
let mut stream = provider
.execute(
planned_request("openai", operation),
context("req_quota_order", CancellationToken::new()),
)
.await
.unwrap();
// 已消费首个业务事件,保证此前额度头或事件已被采集,流仍未结束
timeout(Duration::from_secs(5), async {
while let Some(event) = stream.next().await {
if event
.unwrap()
.wire_event()
.is_some_and(|wire| wire.event_type() == Some("response.created"))
{
return;
}
}
panic!("stream ended before refresh");
})
.await
.unwrap();
let usage_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/codex/usage"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"rate_limit": {
"allowed": true, "primary_window": {
"used_percent": 0, "limit_window_seconds": 604800, "reset_at": reset_at
}
}})))
.expect(1).mount(&usage_server).await;
let (_, quota) = provider_and_quota_with_affinity_and_base_url_and_leases(
&store,
Arc::new(MemorySessionAffinity::default()),
usage_server.uri(),
Arc::new(TestLeaseCoordinator::default()),
0,
);
let account_id = ProviderAccountId::new(id).unwrap();
quota.refresh_account(&account_id).await.unwrap();
let refreshed = store.quota_json(id).unwrap();
let refreshed_at = quota
.read_account(&account_id)
.await
.unwrap()
.unwrap()
.observed_at();
release.send(()).unwrap();
let mut failed = false;
timeout(Duration::from_secs(5), async {
while let Some(event) = stream.next().await {
failed |= event.is_err();
}
})
.await
.unwrap();
server.await.unwrap();
assert_eq!(
failed,
ending != "completed",
"{websocket}/{headers}/{ending}"
);
assert_eq!(
store.quota_json(id).unwrap(),
refreshed,
"{websocket}/{headers}/{ending}"
);
assert_eq!(
quota
.read_account(&account_id)
.await
.unwrap()
.unwrap()
.observed_at(),
refreshed_at
);
}
}
}
}
async fn paused_quota_stream(
websocket: bool,
headers: bool,
ending: &'static str,
reset_at: i64,
) -> (String, oneshot::Sender<()>, tokio::task::JoinHandle<()>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let base_url = format!("http://{}", listener.local_addr().unwrap());
let (release, released) = oneshot::channel();
let task = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
let quota_headers = [
("x-codex-primary-used-percent", "95".to_owned()),
("x-codex-primary-window-minutes", "10080".to_owned()),
("x-codex-primary-reset-at", reset_at.to_string()),
];
let mut initial = Vec::new();
if !headers {
initial.push(json!({"type": "codex.rate_limits", "rate_limits": {
"primary": {"used_percent": 95, "window_minutes": 10080, "reset_at": reset_at}
}}));
}
initial.push(json!({"type": "response.created", "response": {"id": "resp_quota_usage", "model": "gpt-5.4"}}));
let terminal = if ending == "completed" {
json!({"type": "response.completed", "response": {"id": "resp_quota_usage", "model": "gpt-5.4", "status": "completed", "output": [], "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2}}})
} else {
json!({"type": "response.failed", "response": {"error": {"code": "server_error", "message": "failed"}}})
};
if websocket {
let mut socket =
crate::transport::accept_codex_test_websocket_with(socket, |_, response| {
if headers {
for (name, value) in &quota_headers {
response.headers_mut().insert(*name, value.parse().unwrap());
}
}
})
.await;
socket.next().await.unwrap().unwrap();
for event in initial {
socket
.send(Message::Text(event.to_string().into()))
.await
.unwrap();
}
released.await.unwrap();
if ending != "disconnect" {
socket
.send(Message::Text(terminal.to_string().into()))
.await
.unwrap();
}
} else {
read_http_request(&mut socket).await;
let mut response = "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ntransfer-encoding: chunked\r\n".to_owned();
if headers {
for (name, value) in &quota_headers {
response.push_str(&format!("{name}: {value}\r\n"));
}
}
response.push_str("\r\n");
socket.write_all(response.as_bytes()).await.unwrap();
for event in initial {
write_http_chunk(&mut socket, &sse_event(event)).await;
}
released.await.unwrap();
if ending != "disconnect" {
write_http_chunk(&mut socket, &sse_event(terminal)).await;
socket.write_all(b"0\r\n\r\n").await.unwrap();
}
}
});
(base_url, release, task)
}
#[tokio::test]
async fn stream_quota_facts_skip_warmup_only_after_usage() {
for ending in ["failed", "error", "eof", "malformed", "completed"] {
@@ -34,6 +34,17 @@ use provider_openai::credential::{
use secrecy::SecretString;
use tokio::sync::oneshot;
pub(crate) fn quota_header_observations(
headers: &[(String, String)],
observed_at: SystemTime,
) -> [provider_openai::transport::CodexRateLimitObservation; 1] {
[provider_openai::transport::CodexRateLimitObservation {
rate_limits: gateway_protocol::openai::events::parse_rate_limit_headers(headers)
.expect("quota headers"),
observed_at,
}]
}
#[derive(Clone)]
struct StoredAccount {
account: ProviderAccount,
@@ -282,7 +282,7 @@ async fn collect_backend_response(
}
if let Some(updates) = rate_limit_updates {
for update in updates.lock().await.iter() {
rate_limit_headers.extend(rate_limits_to_header_pairs(update));
rate_limit_headers.extend(rate_limits_to_header_pairs(&update.rate_limits));
}
}
if let Some(update) = response_metadata_updates {
+2 -1
View File
@@ -1146,7 +1146,8 @@ OpenAI 响应头的额度窗口按头名前缀归属,普通 Responses 的 `x-c
额度桶设置属于管理员策略,按通用窗口保存上限与可选预热模型。OpenAI Provider 只将通用桶的实际使用率用于上限判断,
与有时效的 Smart 排序信号和上游额度耗尽事实分开。选号、等待后重选和管理端投影共用窗口身份及比较规则;
合并写入前核对所读快照的版本,版本冲突时按原观测时间重新合并。部分观测缺少已触发窗口时保留该窗口的最后证据。已暂停账号切换出口时保留原生额度快照和观测时间,后台额度任务继续复核
响应头和流内额度事件在采集时固定观测时间,流结束与写入重试不推进该时间;合并时逐条排除不晚于已保存快照的事实,避免在途旧请求覆盖刷新后的额度。
合并写入前核对所读快照的版本,版本冲突时按原观测时间重新筛选和合并。部分观测缺少已触发窗口时保留该窗口的最后证据。已暂停账号切换出口时保留原生额度快照和观测时间,后台额度任务继续复核
按桶预热由 OpenAI Provider 解释重置时间、五分钟延迟和本轮使用证据,与 Cron 共用已有预热 worker 和单账号发送逻辑。
请求使用时间按额度来源保留在 Provider 额度正文,未产生实际输出的失败响应只更新额度事实;刷新 `/usage` 保留本地使用证据。