From 7633a6236855ecefbb490a3bb6b456bd74e4ca43 Mon Sep 17 00:00:00 2001 From: Zyy <0x@ainz.cc> Date: Sat, 28 Nov 2026 16:45:21 +0800 Subject: [PATCH] fix(gateway): distinguish local failures from upstream errors (#788) * fix(gateway): distinguish local failures from upstream errors Co-authored-by: Codex * refactor(gateway): distinguish account selection and request limits Co-authored-by: Codex --------- Co-authored-by: Zyy Co-authored-by: Codex --- .../src/use_case/observability/errors.rs | 3 ++ .../tests/use_case/observability/errors.rs | 3 ++ .../crates/gateway-api/src/client_error.rs | 7 ++- .../gateway-api/tests/data_plane/error.rs | 35 +++++++------ .../data_plane/responses/websocket/forward.rs | 9 +--- .../crates/gateway-core/src/concurrency.rs | 4 +- .../gateway-core/src/engine/coordinator.rs | 9 ++-- .../src/engine/execution/failure.rs | 4 +- .../src/engine/execution/service.rs | 19 +++++-- backend/crates/gateway-core/src/error/mod.rs | 50 +++++++++++++------ .../gateway-core/tests/engine/coordinator.rs | 6 ++- .../tests/engine/execution/mod.rs | 21 +++++++- .../gateway-core/tests/error/contract.rs | 5 +- .../runtime/src/callback/error.rs | 4 ++ .../tests/postgres/observability/mod.rs | 5 ++ .../antigravity/src/provider/candidates.rs | 4 +- .../tests/credential/quota/service.rs | 2 +- .../openai/src/provider/observation.rs | 10 ++-- .../openai/tests/provider/contract/mod.rs | 16 +++--- .../provider/contract/session_binding.rs | 4 +- .../providers/xai/src/provider/failure.rs | 14 +++--- .../xai/tests/provider/contract/mod.rs | 2 +- docs/api.md | 6 ++- .../usage-records-table/UsageErrorCell.vue | 2 +- .../components/usage-records-table/errors.ts | 2 + 25 files changed, 155 insertions(+), 91 deletions(-) diff --git a/backend/crates/gateway-admin/src/use_case/observability/errors.rs b/backend/crates/gateway-admin/src/use_case/observability/errors.rs index 12b3a069b..3508f21dd 100644 --- a/backend/crates/gateway-admin/src/use_case/observability/errors.rs +++ b/backend/crates/gateway-admin/src/use_case/observability/errors.rs @@ -109,6 +109,9 @@ impl UsageErrorOrigin { "no_available_provider", "no_eligible_account", "account_capacity_unavailable", + "account_pool_quota_exhausted", + "key_rate_limited", + "key_concurrency_limited", "middleware_capacity_unavailable", "concurrency_queue_full", "concurrency_queue_timeout", diff --git a/backend/crates/gateway-admin/tests/use_case/observability/errors.rs b/backend/crates/gateway-admin/tests/use_case/observability/errors.rs index e5758d55f..7d2a089e0 100644 --- a/backend/crates/gateway-admin/tests/use_case/observability/errors.rs +++ b/backend/crates/gateway-admin/tests/use_case/observability/errors.rs @@ -43,6 +43,9 @@ fn usage_error_origin_recognizes_unambiguous_failure_kinds() { ("no_available_provider", Proxy), ("no_eligible_account", Proxy), ("account_capacity_unavailable", Proxy), + ("account_pool_quota_exhausted", Proxy), + ("key_rate_limited", Proxy), + ("key_concurrency_limited", Proxy), ("middleware_capacity_unavailable", Proxy), ("concurrency_queue_full", Proxy), ("concurrency_queue_timeout", Proxy), diff --git a/backend/crates/gateway-api/src/client_error.rs b/backend/crates/gateway-api/src/client_error.rs index bce2788bc..1f2bf4e91 100644 --- a/backend/crates/gateway-api/src/client_error.rs +++ b/backend/crates/gateway-api/src/client_error.rs @@ -211,12 +211,15 @@ pub const fn gateway_error_contract( "rate_limit_error", "concurrency_queue_timeout", ), - GatewayErrorKind::RateLimited => ( + GatewayErrorKind::RateLimited + | GatewayErrorKind::QuotaExhausted + | GatewayErrorKind::KeyRateLimited + | GatewayErrorKind::KeyConcurrencyLimited => ( StatusCode::TOO_MANY_REQUESTS, "rate_limit_error", "rate_limit_exceeded", ), - GatewayErrorKind::BudgetExhausted => ( + GatewayErrorKind::AccountPoolQuotaExhausted | GatewayErrorKind::BudgetExhausted => ( StatusCode::TOO_MANY_REQUESTS, "usage_limit_reached", "usage_limit_reached", diff --git a/backend/crates/gateway-api/tests/data_plane/error.rs b/backend/crates/gateway-api/tests/data_plane/error.rs index e18283c8a..610de4e3b 100644 --- a/backend/crates/gateway-api/tests/data_plane/error.rs +++ b/backend/crates/gateway-api/tests/data_plane/error.rs @@ -397,7 +397,7 @@ fn local_provider_capacity_exhaustion_should_map_to_service_unavailable() { ); assert_eq!( projected.safe_message(), - "All eligible upstream accounts are temporarily busy." + "The gateway account pool is busy." ); } @@ -429,7 +429,7 @@ fn no_eligible_provider_account_should_preserve_safe_provider_detail() { ); assert_eq!( gateway.safe_message(), - "No upstream provider is available for this request." + "The gateway found no eligible account for this request." ); } @@ -447,7 +447,7 @@ fn provider_infrastructure_failure_should_have_a_distinct_client_contract() { ); assert_eq!( projected.safe_message(), - "Upstream accounts are temporarily inaccessible." + "Gateway account selection is temporarily unavailable." ); } @@ -462,7 +462,7 @@ fn no_eligible_provider_account_should_map_to_service_unavailable() { assert_eq!(projected.kind(), GatewayErrorKind::NoAvailableProvider); assert_eq!( projected.safe_message(), - "No upstream provider is available for this request." + "The gateway found no eligible account for this request." ); } @@ -525,31 +525,30 @@ fn engine_provider_credential_failures_should_not_impersonate_client_auth_failur } #[test] -fn engine_provider_quota_exhaustion_should_use_the_retryable_capacity_contract() { +fn provider_quota_exhaustion_preserves_its_kind_and_retryable_fallback() { let error = EngineError::Provider(ProviderError::new( ProviderErrorKind::QuotaExhausted, UpstreamSendState::Sent, )); + let kind = gateway_error_from_engine(&error).kind(); + assert_eq!(kind.as_str(), "quota_exhausted"); assert_eq!( - gateway_error_from_engine(&error).kind(), - GatewayErrorKind::RateLimited + gateway_error_contract(kind), + ( + StatusCode::TOO_MANY_REQUESTS, + "rate_limit_error", + "rate_limit_exceeded" + ), ); } #[tokio::test] async fn locally_exhausted_account_pool_returns_official_usage_limit_contract() { - let error = EngineError::Provider( - ProviderError::new( - ProviderErrorKind::QuotaExhausted, - UpstreamSendState::NotSent, - ) - .with_client_visible_upstream_error(ClientVisibleUpstreamError::new( - "All eligible accounts have exhausted their quota.", - Some("usage_limit_reached".to_owned()), - Some("usage_limit_reached".to_owned()), - )), - ); + let error = EngineError::Provider(ProviderError::new( + ProviderErrorKind::AccountPoolQuotaExhausted, + UpstreamSendState::NotSent, + )); let response = engine_error_response(&error); assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS); let body: serde_json::Value = diff --git a/backend/crates/gateway-api/tests/data_plane/responses/websocket/forward.rs b/backend/crates/gateway-api/tests/data_plane/responses/websocket/forward.rs index ab717958a..d4936c503 100644 --- a/backend/crates/gateway-api/tests/data_plane/responses/websocket/forward.rs +++ b/backend/crates/gateway-api/tests/data_plane/responses/websocket/forward.rs @@ -745,14 +745,9 @@ 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( - ProviderErrorKind::QuotaExhausted, + ProviderErrorKind::AccountPoolQuotaExhausted, UpstreamSendState::NotSent, - ) - .with_client_visible_upstream_error(ClientVisibleUpstreamError::new( - "All eligible accounts have exhausted their quota.", - Some("usage_limit_reached".to_owned()), - Some("usage_limit_reached".to_owned()), - )); + ); let error = initial_error(EngineError::Provider(provider), Vec::new()).await; assert_eq!(error["status"], 429); assert_eq!(error["error"]["type"], "usage_limit_reached"); diff --git a/backend/crates/gateway-core/src/concurrency.rs b/backend/crates/gateway-core/src/concurrency.rs index 8e8e09204..41cc56eb7 100644 --- a/backend/crates/gateway-core/src/concurrency.rs +++ b/backend/crates/gateway-core/src/concurrency.rs @@ -410,11 +410,11 @@ impl QueueRejection { match self { Self::Full => crate::error::GatewayError::new( crate::error::GatewayErrorKind::ConcurrencyQueueFull, - "Request queue is full.", + "The gateway request queue is full.", ), Self::Timeout => crate::error::GatewayError::new( crate::error::GatewayErrorKind::ConcurrencyQueueTimeout, - "Request queue wait timed out.", + "The request timed out in the gateway queue.", ), } } diff --git a/backend/crates/gateway-core/src/engine/coordinator.rs b/backend/crates/gateway-core/src/engine/coordinator.rs index de3256df1..f90f2eeed 100644 --- a/backend/crates/gateway-core/src/engine/coordinator.rs +++ b/backend/crates/gateway-core/src/engine/coordinator.rs @@ -1064,10 +1064,7 @@ where } } let Some(candidate) = self.plan.candidates().get(self.candidate_index).cloned() else { - let error = GatewayError::new( - GatewayErrorKind::NoAvailableProvider, - "No upstream service is available.", - ); + let error = super::execution::gateway_error_from_engine(&EngineError::EmptyRoutingPlan); self.finish_failure(FailureFinalization { outcome: ExecutionOutcome::Failed, send_state: self.current_send_state(), @@ -1491,6 +1488,7 @@ where ProviderErrorKind::NoEligibleAccount | ProviderErrorKind::AccountCapacityUnavailable | ProviderErrorKind::QuotaExhausted + | ProviderErrorKind::AccountPoolQuotaExhausted | ProviderErrorKind::ConcurrencyQueueFull | ProviderErrorKind::ConcurrencyQueueTimeout ); @@ -2363,7 +2361,8 @@ where } ProviderErrorKind::NoEligibleAccount | ProviderErrorKind::AccountCapacityUnavailable - | ProviderErrorKind::QuotaExhausted => ContinuationAttempt::ReplayAny, + | ProviderErrorKind::QuotaExhausted + | ProviderErrorKind::AccountPoolQuotaExhausted => ContinuationAttempt::ReplayAny, _ => return false, }; self.excluded_accounts.insert(pin.account().clone()); diff --git a/backend/crates/gateway-core/src/engine/execution/failure.rs b/backend/crates/gateway-core/src/engine/execution/failure.rs index 876db1f8a..7ac1f8772 100644 --- a/backend/crates/gateway-core/src/engine/execution/failure.rs +++ b/backend/crates/gateway-core/src/engine/execution/failure.rs @@ -52,7 +52,7 @@ pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> Gatew | crate::validation::RoutingError::NoCapableProviderEndpoint { .. } | crate::validation::RoutingError::EmptyAccountScope => GatewayError::new( GatewayErrorKind::NoAvailableProvider, - "No provider can execute this request.", + "The gateway has no eligible provider for this request.", ), crate::validation::RoutingError::UnsupportedProviderEndpoint { .. } => GatewayError::new( GatewayErrorKind::Unsupported, @@ -77,7 +77,7 @@ pub fn gateway_error_from_engine(error: &EngineError) -> GatewayError { EngineError::EmptyRoutingPlan | EngineError::ProviderNotRegistered { .. } => { GatewayError::new( GatewayErrorKind::NoAvailableProvider, - "No provider is available.", + "The gateway has no available provider for this request.", ) } EngineError::Store(source) => { diff --git a/backend/crates/gateway-core/src/engine/execution/service.rs b/backend/crates/gateway-core/src/engine/execution/service.rs index 7f451f70d..aae81df5a 100644 --- a/backend/crates/gateway-core/src/engine/execution/service.rs +++ b/backend/crates/gateway-core/src/engine/execution/service.rs @@ -1396,11 +1396,20 @@ impl DefaultExecutionService { } ClientAdmissionDecision::Rejected(reason) => { admission.armed = false; - if reason == ClientAdmissionRejection::RateLimited || policy.max_waiting == 0 { - return Err(GatewayError::new( - GatewayErrorKind::RateLimited, - "Request exceeds client API key limits.", - )); + match reason { + ClientAdmissionRejection::RateLimited => { + return Err(GatewayError::new( + GatewayErrorKind::KeyRateLimited, + "The API key's request rate limit was reached.", + )); + } + ClientAdmissionRejection::ConcurrencyLimited if policy.max_waiting == 0 => { + return Err(GatewayError::new( + GatewayErrorKind::KeyConcurrencyLimited, + "The API key's concurrency limit was reached.", + )); + } + ClientAdmissionRejection::ConcurrencyLimited => {} } if waiting.elapsed().is_zero() && let Some(budget) = &self.budget diff --git a/backend/crates/gateway-core/src/error/mod.rs b/backend/crates/gateway-core/src/error/mod.rs index a70830814..b674e57b3 100644 --- a/backend/crates/gateway-core/src/error/mod.rs +++ b/backend/crates/gateway-core/src/error/mod.rs @@ -40,6 +40,8 @@ pub enum ProviderErrorKind { RateLimited, /// Credential 配额耗尽 QuotaExhausted, + /// 本地选号确认当前请求的全部可选账号额度耗尽 + AccountPoolQuotaExhausted, /// 仍有符合条件的账号,但它们暂时没有可调度容量 AccountCapacityUnavailable, ConcurrencyQueueFull, @@ -82,6 +84,7 @@ impl ProviderErrorKind { Self::RequestPolicyDenied => "request_policy_denied", Self::RateLimited => "rate_limited", Self::QuotaExhausted => "quota_exhausted", + Self::AccountPoolQuotaExhausted => "account_pool_quota_exhausted", Self::AccountCapacityUnavailable => "account_capacity_unavailable", Self::ConcurrencyQueueFull => "concurrency_queue_full", Self::ConcurrencyQueueTimeout => "concurrency_queue_timeout", @@ -1266,8 +1269,16 @@ pub enum GatewayErrorKind { ConcurrencyQueueTimeout, /// Provider 的本地账号基础设施不可用 ProviderInfrastructureUnavailable, - /// 上游限流 + /// 请求频率受限 RateLimited, + /// Provider 账号额度耗尽 + QuotaExhausted, + /// 本地可选账号池额度耗尽 + AccountPoolQuotaExhausted, + /// Client Key 每分钟请求数达到上限 + KeyRateLimited, + /// Client Key 并发已满且未启用排队 + KeyConcurrencyLimited, /// 当前客户端 Key 的费用预算耗尽 BudgetExhausted, /// 上游暂不可用 @@ -1301,6 +1312,10 @@ impl GatewayErrorKind { Self::ConcurrencyQueueTimeout => "concurrency_queue_timeout", Self::ProviderInfrastructureUnavailable => "provider_infrastructure_unavailable", Self::RateLimited => "rate_limited", + Self::QuotaExhausted => "quota_exhausted", + Self::AccountPoolQuotaExhausted => "account_pool_quota_exhausted", + Self::KeyRateLimited => "key_rate_limited", + Self::KeyConcurrencyLimited => "key_concurrency_limited", Self::BudgetExhausted => "budget_exhausted", Self::UpstreamUnavailable => "upstream_unavailable", Self::MessageTooBig => "message_too_big", @@ -1425,7 +1440,7 @@ impl GatewayError { ), ProviderErrorKind::SessionPolicyRestricted => Self::new( GatewayErrorKind::InvalidRequest, - "No accounts are available under this conversation's restrictions.", + "Gateway session restrictions exclude all eligible accounts.", ), ProviderErrorKind::ContinuationRecoveryRequired => Self::new( GatewayErrorKind::InvalidRequest, @@ -1443,29 +1458,34 @@ impl GatewayError { || Self::new(GatewayErrorKind::PolicyDenied, "Request blocked by policy."), Self::from, ), - ProviderErrorKind::RateLimited | ProviderErrorKind::QuotaExhausted => Self::new( - GatewayErrorKind::RateLimited, - "Upstream capacity is temporarily unavailable.", + ProviderErrorKind::RateLimited => { + Self::new(GatewayErrorKind::RateLimited, "Request rate limit reached.") + } + ProviderErrorKind::QuotaExhausted => Self::new( + GatewayErrorKind::QuotaExhausted, + "Account quota is exhausted.", ), - ProviderErrorKind::ConcurrencyQueueFull => Self::new( - GatewayErrorKind::ConcurrencyQueueFull, - "Request queue is full.", - ), - ProviderErrorKind::ConcurrencyQueueTimeout => Self::new( - GatewayErrorKind::ConcurrencyQueueTimeout, - "Request queue wait timed out.", + ProviderErrorKind::AccountPoolQuotaExhausted => Self::new( + GatewayErrorKind::AccountPoolQuotaExhausted, + "No eligible gateway account has quota for this request.", ), + ProviderErrorKind::ConcurrencyQueueFull => { + crate::concurrency::QueueRejection::Full.gateway_error() + } + ProviderErrorKind::ConcurrencyQueueTimeout => { + crate::concurrency::QueueRejection::Timeout.gateway_error() + } ProviderErrorKind::AccountCapacityUnavailable => Self::new( GatewayErrorKind::AccountCapacityUnavailable, - "All eligible upstream accounts are temporarily busy.", + "The gateway account pool is busy.", ), ProviderErrorKind::NoEligibleAccount => Self::new( GatewayErrorKind::NoAvailableProvider, - "No upstream provider is available for this request.", + "The gateway found no eligible account for this request.", ), ProviderErrorKind::ProviderInfrastructureUnavailable => Self::new( GatewayErrorKind::ProviderInfrastructureUnavailable, - "Upstream accounts are temporarily inaccessible.", + "Gateway account selection is temporarily unavailable.", ), ProviderErrorKind::Timeout => { Self::new(GatewayErrorKind::Timeout, "Upstream request timed out.") diff --git a/backend/crates/gateway-core/tests/engine/coordinator.rs b/backend/crates/gateway-core/tests/engine/coordinator.rs index 15e19fe7e..530af195d 100644 --- a/backend/crates/gateway-core/tests/engine/coordinator.rs +++ b/backend/crates/gateway-core/tests/engine/coordinator.rs @@ -2840,6 +2840,7 @@ fn native_continuation_exact_retry_keeps_scope_and_account() { fn unavailable_native_continuation_uses_provider_recovery_with_the_configured_account_policy() { for kind in [ ProviderErrorKind::NoEligibleAccount, + ProviderErrorKind::AccountPoolQuotaExhausted, ProviderErrorKind::QuotaExhausted, ] { let Operation::Generate(generate) = generate_operation() else { @@ -5570,9 +5571,9 @@ fn no_eligible_account_before_stream_records_failure_without_fabricating_an_atte GatewayErrorKind::NoAvailableProvider, ), ( - ProviderErrorKind::QuotaExhausted, + ProviderErrorKind::AccountPoolQuotaExhausted, 429, - GatewayErrorKind::RateLimited, + GatewayErrorKind::AccountPoolQuotaExhausted, ), ] { let operation = generate_operation(); @@ -6623,6 +6624,7 @@ fn connection_recovery_keeps_one_account_and_http_transport_until_success() { let cases = [ ProviderErrorKind::NoEligibleAccount, ProviderErrorKind::AccountCapacityUnavailable, + ProviderErrorKind::AccountPoolQuotaExhausted, ProviderErrorKind::QuotaExhausted, ProviderErrorKind::ConcurrencyQueueFull, ProviderErrorKind::ConcurrencyQueueTimeout, diff --git a/backend/crates/gateway-core/tests/engine/execution/mod.rs b/backend/crates/gateway-core/tests/engine/execution/mod.rs index a482ff317..3834fddf6 100644 --- a/backend/crates/gateway-core/tests/engine/execution/mod.rs +++ b/backend/crates/gateway-core/tests/engine/execution/mod.rs @@ -5091,7 +5091,26 @@ fn queue_timeout_and_rpm_rejection_leave_no_new_admission() { .await .err() .unwrap(); - assert_eq!(limited.kind(), GatewayErrorKind::RateLimited); + assert_eq!(limited.kind(), GatewayErrorKind::KeyRateLimited); + assert_eq!(admissions.granted.load(Ordering::SeqCst), 1); + drop(running); + }); +} + +#[test] +fn disabled_key_queue_reports_the_concurrency_limit() { + block_on(async { + let (service, admissions) = queue_service(1, 0, Duration::from_secs(1)); + let running = service + .start(request(&service, ClientTransport::HttpJson)) + .await + .unwrap(); + let rejected = service + .start(request(&service, ClientTransport::HttpJson)) + .await + .err() + .unwrap(); + assert_eq!(rejected.kind(), GatewayErrorKind::KeyConcurrencyLimited); assert_eq!(admissions.granted.load(Ordering::SeqCst), 1); drop(running); }); diff --git a/backend/crates/gateway-core/tests/error/contract.rs b/backend/crates/gateway-core/tests/error/contract.rs index f9bde7af8..d2b2c6dbb 100644 --- a/backend/crates/gateway-core/tests/error/contract.rs +++ b/backend/crates/gateway-core/tests/error/contract.rs @@ -186,10 +186,7 @@ fn gateway_error_should_keep_client_visible_upstream_fields_out_of_safe_diagnost )); let gateway = GatewayError::from_provider(&error); - assert_eq!( - gateway.safe_message(), - "Upstream capacity is temporarily unavailable." - ); + assert_eq!(gateway.safe_message(), "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")); diff --git a/backend/crates/gateway-plugin/runtime/src/callback/error.rs b/backend/crates/gateway-plugin/runtime/src/callback/error.rs index 814884203..7d8c9a745 100644 --- a/backend/crates/gateway-plugin/runtime/src/callback/error.rs +++ b/backend/crates/gateway-plugin/runtime/src/callback/error.rs @@ -24,6 +24,10 @@ pub(super) fn gateway(error: GatewayError) -> PluginFault { | GatewayErrorKind::ConcurrencyQueueFull | GatewayErrorKind::ConcurrencyQueueTimeout | GatewayErrorKind::RateLimited + | GatewayErrorKind::QuotaExhausted + | GatewayErrorKind::AccountPoolQuotaExhausted + | GatewayErrorKind::KeyRateLimited + | GatewayErrorKind::KeyConcurrencyLimited | GatewayErrorKind::BudgetExhausted | GatewayErrorKind::NoAvailableProvider => ErrorCode::Capacity, GatewayErrorKind::Timeout => ErrorCode::Timeout, diff --git a/backend/crates/gateway-store/tests/postgres/observability/mod.rs b/backend/crates/gateway-store/tests/postgres/observability/mod.rs index c6e273f97..b300530e8 100644 --- a/backend/crates/gateway-store/tests/postgres/observability/mod.rs +++ b/backend/crates/gateway-store/tests/postgres/observability/mod.rs @@ -222,6 +222,11 @@ async fn usage_error_origins_preserve_saved_failure_and_connection_boundaries() for (kind, reason, continuation, status, origin) in [ ("internal_error", None, None, None, Proxy), ("internal_error", None, None, Some(503_i32), Upstream), + ("account_pool_quota_exhausted", None, None, None, Proxy), + ("key_rate_limited", None, None, None, Proxy), + ("key_concurrency_limited", None, None, None, Proxy), + ("quota_exhausted", None, None, Some(429), Upstream), + ("rate_limited", None, None, None, Unknown), ("message_too_big", None, None, None, Upstream), ( "continuation_recovery_required", diff --git a/backend/crates/providers/antigravity/src/provider/candidates.rs b/backend/crates/providers/antigravity/src/provider/candidates.rs index 0c0b09261..05bf19756 100644 --- a/backend/crates/providers/antigravity/src/provider/candidates.rs +++ b/backend/crates/providers/antigravity/src/provider/candidates.rs @@ -150,7 +150,9 @@ impl AntigravityProvider { }); } if candidates.is_empty() && model_exhausted { - return Err(unsent(Kind::QuotaExhausted)); + return Err(unsent(Kind::AccountPoolQuotaExhausted).with_diagnostic( + gateway_core::error::ProviderDiagnostic::new("网关可选账号对此模型的额度均已用完"), + )); } let selection = AccountSelectionContext { policy: ctx.account_selection_policy(), diff --git a/backend/crates/providers/antigravity/tests/credential/quota/service.rs b/backend/crates/providers/antigravity/tests/credential/quota/service.rs index 74374257a..589c33110 100644 --- a/backend/crates/providers/antigravity/tests/credential/quota/service.rs +++ b/backend/crates/providers/antigravity/tests/credential/quota/service.rs @@ -459,7 +459,7 @@ async fn peer_model_facts_keep_membership_quota_and_revision_separate() { ), ) .await; - assert!(matches!(result, Err(e) if e.kind() == ProviderErrorKind::QuotaExhausted)); + assert!(matches!(result, Err(e) if e.kind() == ProviderErrorKind::AccountPoolQuotaExhausted)); f.store .primary() .quota diff --git a/backend/crates/providers/openai/src/provider/observation.rs b/backend/crates/providers/openai/src/provider/observation.rs index 614eb6815..82e586de8 100644 --- a/backend/crates/providers/openai/src/provider/observation.rs +++ b/backend/crates/providers/openai/src/provider/observation.rs @@ -855,7 +855,7 @@ fn selection_failure(error: &CredentialSelectionError) -> ProviderError { ) .with_retry_prohibited() .with_client_visible_upstream_error(ClientVisibleUpstreamError::new( - "No account is available for this session after an upstream cyber policy rejection.", + "The gateway found no eligible account for this session after an upstream cyber policy rejection.", Some("cyber_policy".to_owned()), Some("invalid_request_error".to_owned()), )), @@ -864,14 +864,10 @@ fn selection_failure(error: &CredentialSelectionError) -> ProviderError { UpstreamSendState::NotSent, ), CredentialSelectionError::QuotaExhausted => provider_error( - ProviderErrorKind::QuotaExhausted, + ProviderErrorKind::AccountPoolQuotaExhausted, UpstreamSendState::NotSent, ) - .with_client_visible_upstream_error(ClientVisibleUpstreamError::new( - "All eligible accounts have exhausted their quota.", - Some("usage_limit_reached".to_owned()), - Some("usage_limit_reached".to_owned()), - )), + .with_diagnostic(ProviderDiagnostic::new("网关可选账号的额度均已用完")), CredentialSelectionError::AccountSnapshotChanged => provider_error( ProviderErrorKind::ProviderInfrastructureUnavailable, UpstreamSendState::NotSent, diff --git a/backend/crates/providers/openai/tests/provider/contract/mod.rs b/backend/crates/providers/openai/tests/provider/contract/mod.rs index c27ae4c42..271ce2255 100644 --- a/backend/crates/providers/openai/tests/provider/contract/mod.rs +++ b/backend/crates/providers/openai/tests/provider/contract/mod.rs @@ -2503,7 +2503,7 @@ async fn snapshot_retry_rechecks_account_availability_without_sending() { panic!("{change} account must not produce an upstream stream"); }; let expected = if change == "exhausted" { - ProviderErrorKind::QuotaExhausted + ProviderErrorKind::AccountPoolQuotaExhausted } else { ProviderErrorKind::NoEligibleAccount }; @@ -2726,12 +2726,16 @@ async fn exhausted_account_pool_returns_usage_limit_before_http_or_websocket_net else { panic!("exhausted pool must fail before opening an upstream stream"); }; - assert_eq!(error.kind(), ProviderErrorKind::QuotaExhausted); + assert_eq!(error.kind(), ProviderErrorKind::AccountPoolQuotaExhausted); assert_eq!(error.send_state(), UpstreamSendState::NotSent); assert_eq!(error.upstream_status(), None); - let detail = error.client_visible_upstream_error().expect("quota detail"); - assert_eq!(detail.error_type(), Some("usage_limit_reached")); - assert_eq!(detail.code(), Some("usage_limit_reached")); + let gateway = gateway_core::error::GatewayError::from_provider(&error); + assert_eq!(gateway.kind().as_str(), "account_pool_quota_exhausted"); + assert_eq!( + gateway.diagnostic().map(|diagnostic| diagnostic.as_str()), + Some("网关可选账号的额度均已用完") + ); + assert!(error.client_visible_upstream_error().is_none()); } assert!(server.received_requests().await.unwrap().is_empty()); } @@ -2813,7 +2817,7 @@ async fn exhausted_pinned_account_keeps_quota_cause_for_native_continuation_reco else { panic!("native continuation cannot use the other account before recovery"); }; - assert_eq!(error.kind(), ProviderErrorKind::QuotaExhausted); + assert_eq!(error.kind(), ProviderErrorKind::AccountPoolQuotaExhausted); assert_eq!(error.send_state(), UpstreamSendState::NotSent); } diff --git a/backend/crates/providers/openai/tests/provider/contract/session_binding.rs b/backend/crates/providers/openai/tests/provider/contract/session_binding.rs index 64245b942..f58b84d6f 100644 --- a/backend/crates/providers/openai/tests/provider/contract/session_binding.rs +++ b/backend/crates/providers/openai/tests/provider/contract/session_binding.rs @@ -131,7 +131,7 @@ async fn cyber_policy_session_exclusion_has_actionable_non_retryable_error() { assert_eq!(visible.code(), Some("cyber_policy")); assert_eq!( visible.message(), - "No account is available for this session after an upstream cyber policy rejection." + "The gateway found no eligible account for this session after an upstream cyber policy rejection." ); assert_eq!(server.received_requests().await.unwrap().len(), 1); // 可见但不属于固定账号范围的候选不能掩盖会话限制 @@ -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(), - "Request queue wait timed out." + "The request timed out in the gateway queue." ); assert!(error.retry_is_prohibited()); assert_eq!(affinity.binding_count(), 1); diff --git a/backend/crates/providers/xai/src/provider/failure.rs b/backend/crates/providers/xai/src/provider/failure.rs index 3aec71990..32e808d66 100644 --- a/backend/crates/providers/xai/src/provider/failure.rs +++ b/backend/crates/providers/xai/src/provider/failure.rs @@ -425,19 +425,19 @@ fn selection_failure(error: &GrokSessionSelectorError) -> ProviderError { GrokSessionSelectorError::CapacityUnavailable { retry_after } => ( ProviderErrorKind::AccountCapacityUnavailable, *retry_after, - "The available accounts are busy.".to_owned(), + "The gateway account pool is busy.".to_owned(), "account_capacity_busy", ), GrokSessionSelectorError::NoEligibleSession => ( ProviderErrorKind::NoEligibleAccount, None, - "No account is available for the requested model.".to_owned(), + "The gateway found no eligible account for this model.".to_owned(), "no_eligible_account", ), GrokSessionSelectorError::Unavailable(_) => ( ProviderErrorKind::ProviderInfrastructureUnavailable, None, - "Account selection is temporarily unavailable.".to_owned(), + "Gateway account selection is temporarily unavailable.".to_owned(), "account_selector_unavailable", ), GrokSessionSelectorError::PolicyRejected => { @@ -480,20 +480,20 @@ fn selection_failure(error: &GrokSessionSelectorError) -> ProviderError { pub(super) fn cooling_down_message(retry_after: Option) -> String { match retry_after { Some(retry_after) => format!( - "The account is temporarily unavailable after an upstream failure; retry in {} seconds.", + "The gateway is cooling down the account after an upstream failure. Retry in {} seconds.", retry_after.as_secs().saturating_add(1) ), - None => "The account is temporarily unavailable after an upstream failure.".to_owned(), + None => "The gateway is cooling down the account after an upstream failure.".to_owned(), } } pub(super) fn model_cooling_down_message(retry_after: Option) -> String { match retry_after { Some(retry_after) => format!( - "All eligible accounts are temporarily unavailable for this model; retry in {} seconds.", + "A gateway account is cooling down for this model. Retry in {} seconds.", retry_after.as_secs().saturating_add(1) ), - None => "All eligible accounts are temporarily unavailable for this model.".to_owned(), + None => "A gateway account is cooling down for this model.".to_owned(), } } diff --git a/backend/crates/providers/xai/tests/provider/contract/mod.rs b/backend/crates/providers/xai/tests/provider/contract/mod.rs index 1e3683285..0c1bcc5e2 100644 --- a/backend/crates/providers/xai/tests/provider/contract/mod.rs +++ b/backend/crates/providers/xai/tests/provider/contract/mod.rs @@ -2175,7 +2175,7 @@ async fn selection_failures_carry_a_distinguishable_client_error_code() { assert_eq!(transport.calls.load(Ordering::SeqCst), 0); if expected_code == "account_cooling_down" { assert!( - detail.message().contains("retry in 13 seconds."), + detail.message().contains("Retry in 13 seconds."), "{}", detail.message() ); diff --git a/docs/api.md b/docs/api.md index a2bd03c57..148f49940 100644 --- a/docs/api.md +++ b/docs/api.md @@ -3073,8 +3073,10 @@ Dashboard 返回原始 `asOf` 及 `asOfDisplay`,作为当前数据的查询锚 HTTP SSE 请求可能在返回 HTTP 200 后流内失败;WebSocket 已升级时,客户端错误状态码不代表 HTTP 握手状态或 WebSocket 关闭码。 两侧状态码不互相替代,也不覆盖 `logicalOutcome` -请求列表与详情的 `errorKind` 保留网关分类,`websocketCloseCode` 只提取已保存关闭帧的数字码, -与原始上游 `errorCode` 分开。`continuationUnavailableReason` 和 `upstreamConnectionExitReason` +请求列表与详情的 `errorKind` 记录失败原因,使用小写蛇形命名。网关选号时额度耗尽为 `account_pool_quota_exhausted`,Provider 账号额度耗尽为 `quota_exhausted`,请求频率受限为 `rate_limited`。 +Client Key 的频率、并发和费用预算限制分别为 `key_rate_limited`、`key_concurrency_limited` 和 `budget_exhausted`。历史记录保留原分类。 + +`websocketCloseCode` 只提取已保存关闭帧的数字码,与原始上游 `errorCode` 分开。`continuationUnavailableReason` 和 `upstreamConnectionExitReason` 保留已记录的续接及连接退出原因,缺失字段为 `null`,不根据错误文案推断。 `recovered` 表示已关联到后续成功请求,原请求的 `logicalOutcome` 保持不变。 `errorOrigin` 由管理用例统一推导,可取 `proxy`、`upstream`、`connection`、`unknown`。 diff --git a/frontend/src/components/usage-records-table/UsageErrorCell.vue b/frontend/src/components/usage-records-table/UsageErrorCell.vue index a6bdbb6a3..62b389a2c 100644 --- a/frontend/src/components/usage-records-table/UsageErrorCell.vue +++ b/frontend/src/components/usage-records-table/UsageErrorCell.vue @@ -21,7 +21,7 @@ const errorType = computed(() => props.record.errorKind || props.record.errorCod const origin = computed(() => usageErrorOrigin(props.record)) const outcome = computed(() => usageErrorTitle(props.record)) const summary = computed(() => { - const reason = usageErrorReason(code.value) || props.record.errorMessage || code.value + const reason = props.record.errorMessage || usageErrorReason(code.value) || code.value if (reason) return reason return props.record.websocketCloseCode != null diff --git a/frontend/src/components/usage-records-table/errors.ts b/frontend/src/components/usage-records-table/errors.ts index 97b08dc6e..603b9104f 100644 --- a/frontend/src/components/usage-records-table/errors.ts +++ b/frontend/src/components/usage-records-table/errors.ts @@ -59,6 +59,8 @@ export function usageSendStateText(state: string) { export function usageErrorReason(code: string | null): string | undefined { switch (code) { case 'no_available_provider': return t('usage.error.noAvailableProvider') + case 'account_pool_quota_exhausted': + case 'quota_exhausted': return t('accounts.fields.quotaExhausted') case 'rate_limited': case 'rate_limit_exceeded': return t('common.errors.rateLimited') case 'invalid_request': return t('common.errors.invalidParameters')