fix(openai): align spend limits and WebSocket logging with Codex 0.172

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Zyy
2026-11-24 11:49:02 +08:00
co-authored by Codex
parent 037cbcd605
commit 8075487f57
8 changed files with 125 additions and 21 deletions
+2 -2
View File
@@ -4787,7 +4787,7 @@ dependencies = [
[[package]]
name = "tokio-tungstenite"
version = "0.28.0"
source = "git+https://github.com/openai-oss-forks/tokio-tungstenite?rev=7447c427513cfe685f236e1ac0513c4ea3dd9c0b#7447c427513cfe685f236e1ac0513c4ea3dd9c0b"
source = "git+https://github.com/openai-oss-forks/tokio-tungstenite?rev=7a920470d62138955446b64220c7609e46ad770e#7a920470d62138955446b64220c7609e46ad770e"
dependencies = [
"futures-util",
"log",
@@ -4996,7 +4996,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "tungstenite"
version = "0.27.0"
source = "git+https://github.com/openai-oss-forks/tungstenite-rs?rev=bc589d684755a8c02da0fc7e58d0861cbfc306f1#bc589d684755a8c02da0fc7e58d0861cbfc306f1"
source = "git+https://github.com/openai-oss-forks/tungstenite-rs?rev=e19950ef7828cb311e6d51a6bedcebf0192e055c#e19950ef7828cb311e6d51a6bedcebf0192e055c"
dependencies = [
"bytes",
"data-encoding",
+2 -2
View File
@@ -60,9 +60,9 @@ tokio-util = { version = "0.7.18", features = ["rt"] }
tower-service = "0.3.3"
tower-layer = "0.3.3"
# 官方 fork 支持代理连接和分帧消息的 permessage-deflate,两个提交须配套
tokio-tungstenite = { git = "https://github.com/openai-oss-forks/tokio-tungstenite", rev = "7447c427513cfe685f236e1ac0513c4ea3dd9c0b", features = ["proxy", "rustls-tls-native-roots"] }
tokio-tungstenite = { git = "https://github.com/openai-oss-forks/tokio-tungstenite", rev = "7a920470d62138955446b64220c7609e46ad770e", features = ["proxy", "rustls-tls-native-roots"] }
tracing = "0.1.44"
tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "bc589d684755a8c02da0fc7e58d0861cbfc306f1", features = ["deflate", "proxy"] }
tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "e19950ef7828cb311e6d51a6bedcebf0192e055c", features = ["deflate", "proxy"] }
url = "2.5.8"
uuid = { version = "1.23.3", features = ["v4", "v7"] }
# 静态链接 XZ 解码器,不要求部署环境安装 liblzma。
@@ -74,6 +74,8 @@ pub enum CodexAccountFailure {
Banned,
/// 账号信用额度已耗尽
QuotaExhausted,
/// 当前凭据被上游支出上限拒绝,其他凭据的归属未知
SpendLimitExceeded,
/// 当前用量窗口已耗尽;到重置时间后可自动恢复
UsageLimitExhausted {
/// 上游返回的窗口绝对重置时刻
@@ -1988,6 +1990,11 @@ impl CodexCredentialSelector {
.record_confirmed_exhaustion(account, QuotaEvidence::PaymentRequired, None, now)
.await
.map_err(|source| CredentialSelectionError::Store(ErrorSource::new(source))),
CodexAccountFailure::SpendLimitExceeded => self
.quota
.record_confirmed_exhaustion(account, QuotaEvidence::ProviderDenied, None, now)
.await
.map_err(|source| CredentialSelectionError::Store(ErrorSource::new(source))),
CodexAccountFailure::UsageLimitExhausted { reset_at } => self
.quota
.record_confirmed_exhaustion(
@@ -358,7 +358,11 @@ pub(super) async fn apply_failure(
}
let needs_authoritative_quota_refresh = matches!(
failure.account_failure,
Some(CodexAccountFailure::QuotaExhausted | CodexAccountFailure::UsageLimitExhausted { .. })
Some(
CodexAccountFailure::QuotaExhausted
| CodexAccountFailure::SpendLimitExceeded
| CodexAccountFailure::UsageLimitExhausted { .. }
)
);
if failure.cyber_policy_failure {
context
@@ -1695,6 +1699,9 @@ fn upstream_failure_summary(
CodexFailureCategory::QuotaExhausted => {
(ProviderErrorKind::QuotaExhausted, "上游账号额度已用完")
}
CodexFailureCategory::SpendLimitExceeded => {
(ProviderErrorKind::QuotaExhausted, "已达到上游 API 支出上限")
}
CodexFailureCategory::RateLimited => (ProviderErrorKind::RateLimited, "上游请求频率受限"),
CodexFailureCategory::TurnRateLimited => {
(ProviderErrorKind::RateLimited, "当前对话轮次受到限流")
@@ -1767,6 +1774,7 @@ pub(super) fn account_failure(
retry_after: retry_after_seconds.map(Duration::from_secs),
}),
CodexFailureCategory::QuotaExhausted => Some(CodexAccountFailure::QuotaExhausted),
CodexFailureCategory::SpendLimitExceeded => Some(CodexAccountFailure::SpendLimitExceeded),
CodexFailureCategory::CloudflareChallenge => {
Some(CodexAccountFailure::CloudflareChallenge {
retry_after: retry_after_seconds.map(Duration::from_secs),
@@ -50,6 +50,8 @@ pub enum CodexFailureCategory {
RateLimited,
/// 当前 turn 的限流交给客户端等待,不据此推导账号级冷却
TurnRateLimited,
/// 上游 API 支出已达上限,本次请求终止,作用范围由原始错误码标识
SpendLimitExceeded,
QuotaExhausted,
CloudflareChallenge,
CloudflarePathBlocked,
@@ -467,6 +469,18 @@ fn classify_upstream_failure(
if code == "turn_rate_limit_exceeded" {
return CodexFailureCategory::TurnRateLimited;
}
if matches!(status, None | Some(StatusCode::TOO_MANY_REQUESTS))
&& matches!(
fields.code.as_deref(),
Some(
"api_key_spend_limit_exceeded"
| "project_spend_limit_exceeded"
| "organization_spend_limit_exceeded"
)
)
{
return CodexFailureCategory::SpendLimitExceeded;
}
// 容量拒绝可能带 400/429/503;仅用结构化错误字段识别,不能扫描任意正文
if is_capacity_error(
@@ -9228,27 +9228,62 @@ async fn capacity_http_and_websocket_opening_rejections_use_bounded_business_ret
#[tokio::test]
async fn request_rejections_should_not_retry_or_cool_down_accounts() {
use gateway_core::provider_ports::ProviderCooldownPort as _;
for (use_websocket, (code, expected_kind)) in [false, true].into_iter().flat_map(|websocket| {
[
("flex_unavailable", ProviderErrorKind::Unavailable),
("turn_rate_limit_exceeded", ProviderErrorKind::RateLimited),
]
.map(|case| (websocket, case))
}) {
use provider_openai::credential::ResponsesTransport;
for (use_websocket, (code, error_type, expected_kind)) in
[false, true].into_iter().flat_map(|websocket| {
[
(
"flex_unavailable",
"resource_unavailable",
ProviderErrorKind::Unavailable,
),
(
"turn_rate_limit_exceeded",
"rate_limit_error",
ProviderErrorKind::RateLimited,
),
(
"api_key_spend_limit_exceeded",
"insufficient_quota",
ProviderErrorKind::QuotaExhausted,
),
(
"project_spend_limit_exceeded",
"insufficient_quota",
ProviderErrorKind::QuotaExhausted,
),
(
"organization_spend_limit_exceeded",
"insufficient_quota",
ProviderErrorKind::QuotaExhausted,
),
]
.map(|case| (websocket, case))
})
{
let store = Arc::new(MemoryAccountStore::default());
let account_id = "acct_provider_contract";
create_account(&store, account_id).await;
let cooldowns = Arc::new(MemoryCooldownPort::new());
let server = MockServer::start().await;
let error_type = if code == "turn_rate_limit_exceeded" {
"rate_limit_error"
let spend_limit = expected_kind == ProviderErrorKind::QuotaExhausted;
let endpoint = if spend_limit {
let transport = if use_websocket {
ResponsesTransport::PreferWebsocket
} else {
ResponsesTransport::Http
};
store
.seed_api_key(account_id, server.uri(), transport)
.await;
"/responses"
} else {
"resource_unavailable"
create_account(&store, account_id).await;
"/codex/responses"
};
let body =
json!({"error":{"type":error_type,"code":code,"message":"Retry this request later."}});
Mock::given(method(if use_websocket { "GET" } else { "POST" }))
.and(path("/codex/responses"))
.and(path(endpoint))
.respond_with(
ResponseTemplate::new(429)
.insert_header("retry-after", "300")
@@ -9296,7 +9331,14 @@ async fn request_rejections_should_not_retry_or_cool_down_accounts() {
);
let account = store.account(account_id).unwrap();
assert_eq!(account.credential_state(), CredentialState::Ready);
assert_eq!(account.quota().access(), QuotaAccessState::Unknown);
assert_eq!(
account.quota().access(),
if spend_limit {
QuotaAccessState::Exhausted
} else {
QuotaAccessState::Unknown
}
);
assert!(cooldowns.read(account.id()).await.unwrap().is_none());
}
}
@@ -9576,6 +9618,18 @@ async fn stream_failures_preserve_error_fields_independent_of_retry_classificati
ProviderErrorKind::RateLimited,
false,
),
(
"project_spend_limit_exceeded",
"Project spending limit reached.",
ProviderErrorKind::QuotaExhausted,
false,
),
(
"organization_spend_limit_exceeded",
"Organization spending limit reached.",
ProviderErrorKind::QuotaExhausted,
false,
),
(
"unsupported_parameter",
"Hosted tool 'web_search' requires authorization and metering that are not supported by rustponsesapi.",
@@ -9620,7 +9674,9 @@ async fn stream_failures_preserve_error_fields_independent_of_retry_classificati
"type":"invalid_request_error","code":code,"message":message,"param":"tools"
}});
}
if code == "turn_rate_limit_exceeded" {
if code == "organization_spend_limit_exceeded" {
original = json!({"type":"error","error":{"code":code,"message":message,"headers":{"retry-after":"7"}}});
} else if code == "turn_rate_limit_exceeded" || expected_kind == ProviderErrorKind::QuotaExhausted {
original["response"]["error"]["headers"] = json!({"retry-after": "7"});
}
let expected_status = original["status"]
@@ -9702,10 +9758,13 @@ async fn stream_failures_preserve_error_fields_independent_of_retry_classificati
);
assert_eq!(error.replay_is_safe(), capacity && !semantic_output);
assert_eq!(error.upstream_status(), expected_status);
if code == "turn_rate_limit_exceeded" {
if code == "turn_rate_limit_exceeded" || expected_kind == ProviderErrorKind::QuotaExhausted {
assert!(error.retry_is_prohibited());
assert_eq!(error.retry_after(), Some(Duration::from_secs(7)));
}
if expected_kind == ProviderErrorKind::QuotaExhausted {
assert_eq!(store.account("acct_provider_contract").unwrap().quota().access(), QuotaAccessState::Exhausted);
}
assert_eq!(
error.pre_delivery_retry().is_some(),
capacity && !semantic_output
@@ -12418,6 +12477,7 @@ async fn quota_continuation_opening_rejection_projects_replay_without_losing_ups
for use_websocket in [false, true] {
for (status, code, projects_replay) in [
(429, "usage_limit_reached", true),
(429, "project_spend_limit_exceeded", false),
(402, "insufficient_quota", true),
(429, "quota_exceeded", false),
(429, "rate_limit_exceeded", false),
@@ -469,6 +469,16 @@ fn openai_account_failure_matrix_is_preserved() {
r#"{"error":{"type":"usage_limit_reached","message":"quota window reached"}}"#,
CodexFailureCategory::UsageLimitExhausted,
),
(
429,
r#"{"error":{"type":"project_spend_limit_exceeded"}}"#,
CodexFailureCategory::RateLimited,
),
(
401,
r#"{"error":{"code":"project_spend_limit_exceeded"}}"#,
CodexFailureCategory::CredentialExpired,
),
(
529,
r#"{"error":{"type":"server_error","message":"overloaded"}}"#,
+6 -1
View File
@@ -878,7 +878,12 @@ headers 中移除,避免客户端再次等待旧账号;关联 ID 等其他
#### 额度耗尽与续写
明确额度耗尽触发账号隔离与安全换号,包括 WebSocket 握手返回的 429;不会因其长 `Retry-After` 而转入同账号传输恢复等待
OpenAI Responses 在 HTTP 429、WebSocket 握手 429 或流内错误(无状态码或 429)中返回
`api_key_spend_limit_exceeded`、`project_spend_limit_exceeded` 或 `organization_spend_limit_exceeded` 时,
网关保留原码并终止本次请求,包括原生续写。仅本次选中的上游账号记为额度耗尽,`Retry-After` 不触发重试或临时冷却。
调整上游预算后,可在管理端对已启用的 API Key 账号执行强制恢复
其他明确额度耗尽触发账号隔离与安全换号,包括 WebSocket 握手返回的 429;不会因其长 `Retry-After` 而转入同账号传输恢复等待
Client Key 日周预算超限返回 `429`,`error.type` 为官方额度耗尽类型 `usage_limit_reached`,
`error.code` 分别保留 `key_daily_budget_exceeded` 与 `key_weekly_budget_exceeded`,`Retry-After` 指向预算重置边界。