fix(errors): clarify account selection and upstream failures

Report WebSocket transport constraints separately from exhausted account quota, including mixed account pools. Clarify routing, concurrency, authentication, permission, transport and protocol failure messages while preserving upstream error details.

Update HTTP and WebSocket regression coverage and document the client error contract. Validate 2,620 tests, workspace Clippy, formatting and architecture checks.

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Zyy
2026-12-03 10:28:00 +08:00
co-authored by Codex
parent e4f6e1d4e3
commit f2d95cc3fa
10 changed files with 241 additions and 88 deletions
@@ -396,16 +396,16 @@ fn local_provider_capacity_exhaustion_should_map_to_service_unavailable() {
);
assert_eq!(
projected.safe_message(),
"The gateway account pool is busy."
"No eligible account currently has capacity for this request."
);
}
#[test]
fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
#[tokio::test]
async fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
let detail = ClientVisibleUpstreamError::new(
"no account is eligible for the requested model",
Some("no_eligible_account".to_owned()),
Some("account_unavailable_error".to_owned()),
"This request requires an upstream WebSocket.",
Some("websocket_account_unavailable".to_owned()),
None,
);
let error = EngineError::Provider(
ProviderError::new(
@@ -419,17 +419,24 @@ fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
assert_eq!(gateway.kind(), GatewayErrorKind::NoAvailableProvider);
assert_eq!(
gateway.client_message(),
"no account is eligible for the requested model"
"This request requires an upstream WebSocket."
);
assert_eq!(gateway.client_error_code(), Some("no_eligible_account"));
assert_eq!(
gateway.client_error_type(),
Some("account_unavailable_error")
gateway.client_error_code(),
Some("websocket_account_unavailable")
);
assert_eq!(gateway.client_error_type(), None);
assert_eq!(
gateway.safe_message(),
"The gateway found no eligible account for this request."
);
let response = engine_error_response(&error);
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
let body: serde_json::Value =
serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap()).unwrap();
assert_eq!(body["error"]["type"], "server_error");
assert_eq!(body["error"]["code"], "websocket_account_unavailable");
assert_eq!(body["error"]["message"], gateway.client_message());
}
#[test]
@@ -508,6 +515,7 @@ fn engine_provider_unsupported_capability_should_remain_unsupported() {
#[test]
fn engine_provider_credential_failures_should_not_impersonate_client_auth_failures() {
let mut messages = std::collections::HashSet::new();
for kind in [
ProviderErrorKind::Unauthorized,
ProviderErrorKind::PermissionDenied,
@@ -516,11 +524,19 @@ fn engine_provider_credential_failures_should_not_impersonate_client_auth_failur
let mapped = gateway_error_from_engine(&error);
assert_eq!(mapped.kind(), GatewayErrorKind::UpstreamUnavailable);
assert_eq!(
mapped.safe_message(),
"The upstream account cannot access the service."
assert!(
mapped
.safe_message()
.to_lowercase()
.contains("upstream account")
);
messages.insert(mapped.safe_message().to_owned());
}
assert_eq!(
messages.len(),
2,
"authentication and permission failures must be distinguishable"
);
}
#[test]
@@ -577,19 +593,29 @@ fn engine_provider_timeout_and_cancellation_should_remain_distinct() {
}
#[test]
fn engine_provider_runtime_failures_should_collapse_to_safe_unavailability() {
fn engine_provider_runtime_failures_preserve_the_cause_without_exposing_internal_details() {
let mut messages = std::collections::HashSet::new();
for kind in [
ProviderErrorKind::Transport,
ProviderErrorKind::Protocol,
ProviderErrorKind::Unavailable,
ProviderErrorKind::ProcessTerminated,
] {
let error = EngineError::Provider(ProviderError::new(kind, UpstreamSendState::Ambiguous));
let error = EngineError::Provider(
ProviderError::new(kind, UpstreamSendState::Ambiguous)
.with_source(std::io::Error::other("PRIVATE_ENDPOINT_AND_CREDENTIAL")),
);
let projected = gateway_error_from_engine(&error);
assert_eq!(projected.kind(), GatewayErrorKind::UpstreamUnavailable);
assert_eq!(projected.safe_message(), "Upstream service is unavailable.");
assert!(!projected.client_message().contains("PRIVATE_"));
messages.insert(projected.client_message().to_owned());
}
assert_eq!(
messages.len(),
4,
"different failure causes must remain distinguishable"
);
}
#[test]
@@ -417,7 +417,7 @@ async fn provider_failure_facts_survive_without_a_complete_http_response() {
assert!(error["headers"].get("x-ms-request-id").is_none());
assert_eq!(
error["error"]["message"],
"Upstream service is unavailable."
"Communication with the upstream service failed."
);
}
@@ -796,13 +796,38 @@ async fn initial_continuation_recovery_delivers_the_official_client_replay_signa
}
#[tokio::test]
async fn locally_exhausted_account_pool_sends_one_official_usage_limit_error() {
let provider = ProviderError::new(
async fn account_selection_errors_distinguish_quota_from_websocket_requirements() {
let exhausted = ProviderError::new(
ProviderErrorKind::AccountPoolQuotaExhausted,
UpstreamSendState::NotSent,
);
let error = initial_error(EngineError::Provider(provider), Vec::new()).await;
assert_eq!(error["status"], 429);
assert_eq!(error["error"]["type"], "usage_limit_reached");
assert_eq!(error["error"]["code"], "usage_limit_reached");
let incompatible = ProviderError::new(
ProviderErrorKind::NoEligibleAccount,
UpstreamSendState::NotSent,
)
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
"This request requires an upstream WebSocket.",
Some("websocket_account_unavailable".to_owned()),
None,
));
for (provider, status, kind, code) in [
(exhausted, 429, "usage_limit_reached", "usage_limit_reached"),
(
incompatible,
503,
"server_error",
"websocket_account_unavailable",
),
] {
let error = initial_error(EngineError::Provider(provider), Vec::new()).await;
assert_eq!(error["status"], status);
assert_eq!(error["error"]["type"], kind);
assert_eq!(error["error"]["code"], code);
if status == 503 {
assert_eq!(
error["error"]["message"],
"This request requires an upstream WebSocket."
);
}
}
}
@@ -48,11 +48,17 @@ pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> Gatew
"Mapped model unavailable for this API key. Check the model mapping."
},
),
crate::validation::RoutingError::NoCapableProvider { .. }
| crate::validation::RoutingError::NoCapableProviderEndpoint { .. }
| crate::validation::RoutingError::EmptyAccountScope => GatewayError::new(
crate::validation::RoutingError::NoCapableProvider { .. } => GatewayError::new(
GatewayErrorKind::NoAvailableProvider,
"The gateway has no eligible provider for this request.",
"The gateway cannot select a provider for this model and the requested capabilities.",
),
crate::validation::RoutingError::NoCapableProviderEndpoint { .. } => GatewayError::new(
GatewayErrorKind::NoAvailableProvider,
"No eligible provider is available for the requested API endpoint.",
),
crate::validation::RoutingError::EmptyAccountScope => GatewayError::new(
GatewayErrorKind::NoAvailableProvider,
"This API key has no accounts in its scope. Add accounts or check its enabled account groups.",
),
crate::validation::RoutingError::UnsupportedProviderEndpoint { .. } => GatewayError::new(
GatewayErrorKind::Unsupported,
+31 -14
View File
@@ -1436,14 +1436,14 @@ impl GatewayError {
pub(crate) const fn concurrency_queue_full() -> Self {
Self::new(
GatewayErrorKind::ConcurrencyQueueFull,
"The gateway request queue is full.",
"The gateway concurrency queue is full.",
)
}
pub(crate) const fn concurrency_queue_timeout() -> Self {
Self::new(
GatewayErrorKind::ConcurrencyQueueTimeout,
"The request timed out in the gateway queue.",
"Timed out waiting for available concurrency in the gateway.",
)
}
@@ -1516,20 +1516,25 @@ impl GatewayError {
GatewayErrorKind::Unsupported,
"Requested capability is unsupported.",
),
ProviderErrorKind::Unauthorized | ProviderErrorKind::PermissionDenied => Self::new(
ProviderErrorKind::Unauthorized => Self::new(
GatewayErrorKind::UpstreamUnavailable,
"The upstream account cannot access the service.",
"Upstream account authentication failed.",
),
ProviderErrorKind::PermissionDenied => Self::new(
GatewayErrorKind::UpstreamUnavailable,
"The upstream account does not have permission for this request.",
),
ProviderErrorKind::RequestPolicyDenied => error.denied_group_feature.map_or_else(
|| Self::new(GatewayErrorKind::PolicyDenied, "Request blocked by policy."),
Self::from,
),
ProviderErrorKind::RateLimited => {
Self::new(GatewayErrorKind::RateLimited, "Request rate limit reached.")
}
ProviderErrorKind::RateLimited => Self::new(
GatewayErrorKind::RateLimited,
"Upstream request rate limit reached.",
),
ProviderErrorKind::QuotaExhausted => Self::new(
GatewayErrorKind::QuotaExhausted,
"Account quota is exhausted.",
"Upstream account quota is exhausted.",
),
ProviderErrorKind::AccountPoolQuotaExhausted => Self::new(
GatewayErrorKind::AccountPoolQuotaExhausted,
@@ -1539,7 +1544,7 @@ impl GatewayError {
ProviderErrorKind::ConcurrencyQueueTimeout => Self::concurrency_queue_timeout(),
ProviderErrorKind::AccountCapacityUnavailable => Self::new(
GatewayErrorKind::AccountCapacityUnavailable,
"The gateway account pool is busy.",
"No eligible account currently has capacity for this request.",
),
ProviderErrorKind::NoEligibleAccount => Self::new(
GatewayErrorKind::NoAvailableProvider,
@@ -1559,11 +1564,23 @@ impl GatewayError {
ProviderErrorKind::Cancelled => {
Self::new(GatewayErrorKind::Cancelled, "Request was cancelled.")
}
ProviderErrorKind::Transport
| ProviderErrorKind::Protocol
| ProviderErrorKind::Unavailable
| ProviderErrorKind::UpstreamCapacityUnavailable
| ProviderErrorKind::ProcessTerminated => Self::new(
ProviderErrorKind::Transport => Self::new(
GatewayErrorKind::UpstreamUnavailable,
"Communication with the upstream service failed.",
),
ProviderErrorKind::Protocol => Self::new(
GatewayErrorKind::UpstreamUnavailable,
"Upstream protocol handling failed.",
),
ProviderErrorKind::ProcessTerminated => Self::new(
GatewayErrorKind::UpstreamUnavailable,
"The gateway stopped before the request completed.",
),
ProviderErrorKind::UpstreamCapacityUnavailable => Self::new(
GatewayErrorKind::UpstreamUnavailable,
"The upstream service has no capacity for this request.",
),
ProviderErrorKind::Unavailable => Self::new(
GatewayErrorKind::UpstreamUnavailable,
"Upstream service is unavailable.",
),
@@ -186,7 +186,10 @@ fn gateway_error_should_keep_client_visible_upstream_fields_out_of_safe_diagnost
));
let gateway = GatewayError::from_provider(&error);
assert_eq!(gateway.safe_message(), "Account quota is exhausted.");
assert_eq!(
gateway.safe_message(),
"Upstream account quota is exhausted."
);
assert_eq!(gateway.client_message(), message);
assert_eq!(gateway.client_error_code(), Some("quota_exhausted"));
assert_eq!(gateway.client_error_type(), Some("rate_limit_error"));
@@ -564,6 +564,7 @@ impl CodexCredentialSelector {
err,
CredentialSelectionError::CapacityUnavailable { .. }
| CredentialSelectionError::NoEligibleCredential
| CredentialSelectionError::WebSocketUnavailable { .. }
| CredentialSelectionError::QuotaExhausted
)
},
@@ -939,6 +940,7 @@ impl CodexCredentialSelector {
_ => None,
};
let mut catalog_rejected = 0_usize;
let mut websocket_rejected = false;
let mut native_accounts = BTreeSet::new();
for account in accounts {
let adapter = if let Some(model) = adapter_model.as_ref() {
@@ -1043,14 +1045,22 @@ impl CodexCredentialSelector {
(account.revision(), runtime.authentication.api_protocol()),
);
}
if (request.requires_websocket
&& runtime.transport == super::ResponsesTransport::Http)
|| required_protocol.is_some_and(|protocol| {
runtime.authentication.api_protocol() != protocol
})
if required_protocol
.is_some_and(|protocol| runtime.authentication.api_protocol() != protocol)
{
continue;
}
if request.requires_websocket
&& runtime.transport == super::ResponsesTransport::Http
{
// 仅记录基础状态正常的 HTTP 账号,失效或已耗尽账号不能掩盖真实额度失败
websocket_rejected |= (diagnostic
|| account.status_projection(SystemTime::now(), None).status
== AccountStatus::Normal)
&& !request.attempt.excluded_accounts().contains(account.id())
&& !request.attempt.excludes_proxy(account.outbound_proxy());
continue;
}
}
eligible.push(account);
}
@@ -1475,7 +1485,7 @@ impl CodexCredentialSelector {
Err(CredentialSelectionError::CapacityUnavailable {
retry_after: shortest_retry,
})
} else if quota_exhausted {
} else if quota_exhausted && !websocket_rejected {
Err(CredentialSelectionError::QuotaExhausted)
} else if cyber_policy_scope
.as_ref()
@@ -1496,6 +1506,8 @@ impl CodexCredentialSelector {
{
// 仅明确的会话策略排除使用此分类,空池、传输和容量失败保持原分类
Err(CredentialSelectionError::SessionPolicyRestricted)
} else if websocket_rejected {
Err(CredentialSelectionError::WebSocketUnavailable { quota_exhausted })
} else {
Err(CredentialSelectionError::NoEligibleCredential)
};
@@ -2465,6 +2477,10 @@ pub enum CredentialSelectionError {
IneligibleSessionAccountTimeout(&'static str),
#[error("no eligible Codex account")]
NoEligibleCredential,
#[error(
"no available WebSocket account; compatible account quota exhausted: {quota_exhausted}"
)]
WebSocketUnavailable { quota_exhausted: bool },
#[error("upstream safety policy temporarily excludes accounts for this session")]
SessionPolicyRestricted,
#[error("all eligible Codex accounts have exhausted their quota")]
@@ -886,6 +886,27 @@ fn selection_failure(error: &CredentialSelectionError) -> ProviderError {
ProviderErrorKind::NoEligibleAccount,
UpstreamSendState::NotSent,
),
CredentialSelectionError::WebSocketUnavailable { quota_exhausted } => provider_error(
ProviderErrorKind::NoEligibleAccount,
UpstreamSendState::NotSent,
)
.with_diagnostic(
ProviderDiagnostic::new(if *quota_exhausted {
"WebSocket 账号额度耗尽,HTTP/SSE 账号不符合本次传输要求"
} else {
"请求需要上游 WebSocket,HTTP/SSE 账号不符合本次传输要求"
})
.with_classification("account_selection", "websocket_account_unavailable"),
)
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
if *quota_exhausted {
"WebSocket-compatible accounts have exhausted their quota; HTTP/SSE-only accounts cannot serve this request. Enable WebSocket on an available account or use HTTP/SSE in the client."
} else {
"This request requires an upstream WebSocket, but no compatible account is available. Enable WebSocket on an available account or use HTTP/SSE in the client."
},
Some("websocket_account_unavailable".to_owned()),
None,
)),
CredentialSelectionError::QuotaExhausted => provider_error(
ProviderErrorKind::AccountPoolQuotaExhausted,
UpstreamSendState::NotSent,
@@ -154,7 +154,7 @@ async fn account_client_preparation_keeps_ca_read_cause_without_exposing_path()
assert!(diagnostic.as_str().contains("OS cause:"));
assert!(!diagnostic.as_str().contains("PRIVATE_"));
let gateway = gateway_core::error::GatewayError::from_provider(&snapshot);
assert_eq!(gateway.safe_message(), "Upstream service is unavailable.");
assert_eq!(gateway.safe_message(), "Upstream protocol handling failed.");
assert_eq!(gateway.diagnostic(), Some(diagnostic));
}
@@ -13475,43 +13475,78 @@ async fn oauth_http_transport_rejects_websocket_only_warmup_without_sending() {
}
#[tokio::test]
async fn oauth_http_transport_rejects_downstream_websocket_chain_without_sending() {
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, "acct_provider_contract").await;
store.set_oauth_transport(
"acct_provider_contract",
provider_openai::credential::ResponsesTransport::Http,
);
let upstream = MockServer::start().await;
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object(
"openai",
json!({"model":"gpt-5.4", "input":"hello", "store":false, "stream":true})
.as_object()
.unwrap()
.clone(),
)
.unwrap()
.with_context(Map::from_iter([
("use_websocket".to_owned(), json!(true)),
(
"downstream_websocket_connection_id".to_owned(),
json!("client-connection"),
),
])),
));
let result = provider_with_base_url(&store, upstream.uri())
.execute(
planned_request("openai", operation),
context("req_oauth_http_ws_chain", CancellationToken::new()),
)
.await;
let Err(error) = result else {
panic!("connection-local chain needs an upstream WebSocket")
};
assert_eq!(error.kind(), ProviderErrorKind::NoEligibleAccount);
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
assert!(upstream.received_requests().await.unwrap().is_empty());
async fn websocket_selection_distinguishes_http_only_accounts_from_exhausted_quota() {
for (http_enabled, http_exhausted, with_exhausted_ws) in [
(true, false, false),
(true, false, true),
(true, true, true),
(false, false, true),
] {
let store = Arc::new(MemoryAccountStore::default());
create_account_with_enabled(&store, "acct_provider_contract", http_enabled).await;
store.set_oauth_transport(
"acct_provider_contract",
provider_openai::credential::ResponsesTransport::Http,
);
if http_exhausted {
exhaust_account_quota(&store, "acct_provider_contract").await;
}
if with_exhausted_ws {
create_account(&store, "acct_scope_new").await;
exhaust_account_quota(&store, "acct_scope_new").await;
}
let upstream = MockServer::start().await;
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object(
"openai",
json!({"model":"gpt-5.4", "input":"hello", "store":false, "stream":true})
.as_object()
.unwrap()
.clone(),
)
.unwrap()
.with_context(Map::from_iter([
("use_websocket".to_owned(), json!(true)),
(
"downstream_websocket_connection_id".to_owned(),
json!("client-connection"),
),
])),
));
let result = provider_with_base_url(&store, upstream.uri())
.execute(
planned_request("openai", operation),
context("req_oauth_http_ws_chain", CancellationToken::new()),
)
.await;
let Err(error) = result else {
panic!("connection-local chain needs an upstream WebSocket")
};
if http_enabled && !http_exhausted {
assert_eq!(error.kind(), ProviderErrorKind::NoEligibleAccount);
let gateway = gateway_core::error::GatewayError::from_provider(&error);
assert_eq!(
gateway.client_error_code(),
Some("websocket_account_unavailable")
);
assert!(gateway.client_message().contains("HTTP/SSE"));
assert_eq!(
gateway.client_message().contains("exhausted their quota"),
with_exhausted_ws
);
assert_eq!(
gateway
.diagnostic()
.and_then(gateway_core::error::ProviderDiagnostic::code),
Some("websocket_account_unavailable")
);
} else {
assert_eq!(error.kind(), ProviderErrorKind::AccountPoolQuotaExhausted);
assert!(error.client_visible_upstream_error().is_none());
}
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
assert!(upstream.received_requests().await.unwrap().is_empty());
}
}
#[tokio::test]
@@ -855,7 +855,7 @@ async fn child_queue_timeout_does_not_rebind_or_allow_provider_fallback() {
assert_eq!(error.kind(), ProviderErrorKind::ConcurrencyQueueTimeout);
assert_eq!(
gateway_core::error::GatewayError::from_provider(&error).client_message(),
"The request timed out in the gateway queue."
"Timed out waiting for available concurrency in the gateway."
);
assert!(error.retry_is_prohibited());
assert_eq!(affinity.binding_count(), 1);
+5 -1
View File
@@ -700,6 +700,9 @@ OAuth 账号默认 `prefer_websocket`,客户端使用 HTTP/SSE 时仍可能选
可将账号上游传输方式设为 `http`,固定使用 HTTP/SSE。Responses API Key 账号默认使用 HTTP/SSE,
也可配置 `prefer_websocket`;Messages API Key 账号只支持 `http`。
OpenAI 的协议预热、依赖 WS 的非持久化新链和连接内续接要求账号支持上游 WS。
`503 websocket_account_unavailable` 表示无法选出可用的 WS 账号,而授权范围内仍有基础状态正常的
HTTP/SSE 账号被传输要求排除;可将账号上游传输改为 WS,或将客户端改为 HTTP/SSE。
若兼容 WS 的账号均已耗尽额度,提示同时保留该原因,不将混合原因简化为整个账号池额度耗尽。
HTTP 入站的 Codex 压缩请求未显式指定 `use_websocket: true` 且不依赖 WS 时,保留上游 HTTP/SSE;
压缩根据 turn metadata 中的 `request_kind: compaction` 或输入中的 `compaction_trigger` 识别。
WS 入站的压缩沿用常规传输策略。
@@ -947,7 +950,8 @@ Client Key 日周预算超限返回 `429`,`error.type` 为官方额度耗尽
OpenAI 选号阶段确认本次可选账号全部额度耗尽时,HTTP 返回 `429`,WebSocket 错误帧返回
`status: 429`,两者的 `error.type` 与 `error.code` 均为 `usage_limit_reached`,提示客户端停止
本轮自动重试,等待额度恢复或补充可用账号。空账号池、认证失效和临时容量不足不按额度耗尽处理;
本轮自动重试,等待额度恢复或补充可用账号。空账号池、认证失效、临时容量不足,以及仍有正常账号因
HTTP/SSE 配置无法承接 WS 请求的混合原因,不按整个账号池额度耗尽处理;
仍有其他可用 Provider 或可安全恢复的续写时,网关先按现有路由规则尝试恢复
带 `previous_response_id` 的 OpenAI 原生续写仍绑定原账号。若该账号明确拒绝请求且额度已耗尽,