From 0e2a3b5562cb4f3a80207ae29d126a3bcec4323a Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 24 Sep 2026 15:27:02 +0800 Subject: [PATCH] feat(gateway): take official hosts, output fallback and error shapes from core v0.42.0 - `tw_dialect::official::is_official_host` replaces the three-host list in transport, so DeepSeek, Moonshot, Z.ai and the rest are official too and a relay cannot pass itself off as one through its path or user info. `ANTHROPIC_VERSION` comes from there as well. - The output length written for an upstream that requires one is `fallback_max_output_tokens(model)` (32000 for Claude, 8192 else) instead of a fixed 4096 that cut Claude answers short. - Stream error frames come from `tw_dialect::convert::error_frame`: Responses clients get `response.failed`, Anthropic clients an `error` event of the right type, instead of Chat-shaped frames they skip. - Whole error bodies come from `tw_dialect::convert::error_body` in the caller's format. The Chat body's `type` is now OpenAI's own vocabulary (`rate_limit_error`, `server_error`, ...). - The provider test builds its URL with `tw_dialect::url::upstream_url`. Co-Authored-By: Claude Opus 5.5 --- crates/gateway/src/lifecycle/mod.rs | 22 +-- crates/gateway/src/proxy/generate.rs | 26 ++- crates/gateway/src/proxy/mod.rs | 97 ++++++---- crates/gateway/src/proxy/transport.rs | 37 ++-- crates/server/src/handlers/providers.rs | 10 +- .../tests/gateway_error_shapes.rs | 170 ++++++++++++++++++ 6 files changed, 286 insertions(+), 76 deletions(-) create mode 100644 crates/test-support/tests/gateway_error_shapes.rs diff --git a/crates/gateway/src/lifecycle/mod.rs b/crates/gateway/src/lifecycle/mod.rs index dfc8072f..0d83a5a3 100644 --- a/crates/gateway/src/lifecycle/mod.rs +++ b/crates/gateway/src/lifecycle/mod.rs @@ -204,7 +204,7 @@ pub(crate) fn build_chat_pump( // Headers already went out as 200, so the refusal is said // in the stream — and logged with the upstream's own status, // so a throttled upstream stays 429 on the audit row. - let mut out = shaper.process(&error_frame(client, &e.to_string())); + let mut out = shaper.process(&error_frame(client, e.status_code(), &e.to_string())); out.extend(shaper.finish()); yield Ok::(Bytes::from(out)); if let Some(tx) = done_tx.take() { @@ -271,7 +271,7 @@ pub(crate) fn build_chat_pump( tracing::warn!("{message}"); let tail = match convert.as_mut() { Some(c) => c.fail(&message), - None => error_frame(client, &message), + None => error_frame(client, 502, &message), }; let mut out = shaper.process(&tail); out.extend(shaper.finish()); @@ -404,23 +404,19 @@ fn cut( let mut out = shaper.process(safe); let refusal = match convert { Some(c) => c.fail(&message), - None => error_frame(client, &message), + None => error_frame(client, err.status_code(), &message), }; out.extend(shaper.process(&refusal)); out.extend(shaper.finish()); out } -/// An error in the caller's format, for a stream that was forwarded -/// untouched and so has no converter to write one. -fn error_frame(client: Dialect, message: &str) -> Vec { - let body = tw_dialect::convert::error_body(client, 502, message); - let v: serde_json::Value = serde_json::from_slice(&body).unwrap_or_default(); - match client { - Dialect::Chat => tw_dialect::frame::data(&v), - _ => tw_dialect::frame::named("error", &v), - } - .into_bytes() +/// A standalone error frame in the caller's format, for a stream that has +/// no converter to write one (forwarded as sent, or never opened). `status` +/// is what the error would have been as a response, and picks its class. +fn error_frame(client: Dialect, status: i64, message: &str) -> Vec { + let status = u16::try_from(status).unwrap_or(502); + tw_dialect::convert::error_frame(client, status, message).into_bytes() } impl Surface for ChatCompletionSurface { diff --git a/crates/gateway/src/proxy/generate.rs b/crates/gateway/src/proxy/generate.rs index 10a9c886..bfd4d744 100644 --- a/crates/gateway/src/proxy/generate.rs +++ b/crates/gateway/src/proxy/generate.rs @@ -86,10 +86,6 @@ const RESPONSES: ClientSurface = ClientSurface { caches: false, }; -/// Output length when the caller set none and the upstream insists on -/// one (Anthropic). The value the previous handlers used. -const DEFAULT_MAX_TOKENS: u64 = 4096; - /// POST /v1/chat/completions pub async fn proxy_chat_completion( State(state): State, @@ -179,10 +175,14 @@ impl Outbound { official: bool, ) -> Result { let client = self.surface.dialect; + // Output length when the caller set none and the upstream insists + // on one (Anthropic). There is no per-model output limit on file + // here, so it goes by the upstream model's name. + let default_max_tokens = tw_dialect::official::fallback_max_output_tokens(model); let target = |dialect| Target { dialect, official, - default_max_tokens: DEFAULT_MAX_TOKENS, + default_max_tokens, }; let decode = |v: &Value| { tw_dialect::convert::decode(client, v, self.surface.path, None) @@ -358,12 +358,25 @@ pub(crate) async fn read_whole( // ───────────────────────────────────────────── the pipeline +/// Every error on the way out is in the caller's own format. async fn generate( state: GatewayState, headers: HeaderMap, identity: GatewayRequestIdentity, body: Bytes, surface: ClientSurface, +) -> Result { + run(state, headers, identity, body, surface) + .await + .map_err(|e| e.in_dialect(surface.dialect)) +} + +async fn run( + state: GatewayState, + headers: HeaderMap, + identity: GatewayRequestIdentity, + body: Bytes, + surface: ClientSurface, ) -> Result { let trace_id = resolve_trace_id(&headers); let session_id = resolve_session_id(&headers); @@ -778,9 +791,8 @@ async fn generate( /// part; counting it the same way everywhere keeps one route from /// looking cheaper than another for the same work. pub(crate) fn tokens(u: &tw_dialect::usage::Usage) -> (u32, u32) { - let prompt = u.input + u.cache_read + u.cache_write; ( - u32::try_from(prompt).unwrap_or(u32::MAX), + u32::try_from(u.prompt_total()).unwrap_or(u32::MAX), u32::try_from(u.output).unwrap_or(u32::MAX), ) } diff --git a/crates/gateway/src/proxy/mod.rs b/crates/gateway/src/proxy/mod.rs index 992bffb5..488e7992 100644 --- a/crates/gateway/src/proxy/mod.rs +++ b/crates/gateway/src/proxy/mod.rs @@ -4,7 +4,6 @@ //! see the leaf modules' docs for what lives where. use arc_swap::ArcSwap; -use axum::Json; use axum::response::IntoResponse; use sqlx::PgPool; use std::sync::Arc; @@ -136,12 +135,35 @@ pub(super) fn gateway_error_status(err: &GatewayError) -> i64 { // ---------- Error adapter ---------- -/// Newtype wrapper so we can implement `IntoResponse` for `GatewayError`. -pub struct GatewayErrorResponse(GatewayError); +/// A `GatewayError` on its way to the caller, in the caller's format. +/// +/// The body is the one the caller's own SDK knows how to read: an +/// Anthropic client gets `{"type":"error","error":{…}}`, a Gemini client +/// `{"error":{"code","status",…}}`, Chat and Responses clients OpenAI's +/// `{"error":{"message","type",…}}`. Before, every surface got the Chat +/// shape, and an Anthropic SDK reported a gateway refusal as an +/// unparseable response. +pub struct GatewayErrorResponse { + error: GatewayError, + client: tw_dialect::ir::Dialect, +} impl From for GatewayErrorResponse { - fn from(err: GatewayError) -> Self { - Self(err) + /// In Chat's format until the surface says otherwise + /// ([`GatewayErrorResponse::in_dialect`]). + fn from(error: GatewayError) -> Self { + Self { + error, + client: tw_dialect::ir::Dialect::Chat, + } + } +} + +impl GatewayErrorResponse { + /// Answer in `client`'s format. + pub(crate) fn in_dialect(mut self, client: tw_dialect::ir::Dialect) -> Self { + self.client = client; + self } } @@ -149,36 +171,24 @@ impl IntoResponse for GatewayErrorResponse { fn into_response(self) -> axum::response::Response { use axum::http::{HeaderValue, StatusCode, header}; - let status = - StatusCode::from_u16(self.0.status_code() as u16).unwrap_or(StatusCode::BAD_GATEWAY); - let error_type = match &self.0 { - GatewayError::ProviderError(_) => "provider_error", - GatewayError::ProviderHttpError { .. } => "provider_http_error", - GatewayError::ProviderTimeout(_) => "provider_timeout", - GatewayError::ProviderInvalidResponse(_) => "provider_invalid_response", - GatewayError::TransformError(_) => "transform_error", - GatewayError::NetworkError(_) => "network_error", - GatewayError::UpstreamRateLimited { .. } | GatewayError::LocalRateLimited(_) => { - "rate_limited" - } - GatewayError::UpstreamAuthError => "auth_error", - GatewayError::PolicyBlocked(_) => "policy_blocked", - }; - - let retry_after = self.0.retry_after_secs(); - let body = serde_json::json!({ - "error": { - "message": self.0.to_string(), - "type": error_type, - } - }); - - let mut response = (status, Json(body)).into_response(); + let status = StatusCode::from_u16(self.error.status_code() as u16) + .unwrap_or(StatusCode::BAD_GATEWAY); + let body = + tw_dialect::convert::error_body(self.client, status.as_u16(), &self.error.to_string()); + let mut response = ( + status, + [( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + )], + body, + ) + .into_response(); // Echo the upstream's Retry-After (or our local default) so // well-behaved clients back off the right amount instead of // burning quota with tight 3× retries that all hit the same // open window. - if let Some(secs) = retry_after + if let Some(secs) = self.error.retry_after_secs() && let Ok(v) = HeaderValue::from_str(&secs.to_string()) { response.headers_mut().insert(header::RETRY_AFTER, v); @@ -354,6 +364,31 @@ mod helper_tests { ); } + /// Each client gets the error in the shape its SDK reads. + #[tokio::test] + async fn the_error_body_is_in_the_callers_format() { + use tw_dialect::ir::Dialect; + async fn body(d: Dialect) -> serde_json::Value { + let resp = GatewayErrorResponse::from(GatewayError::LocalRateLimited("rule".into())) + .in_dialect(d) + .into_response(); + assert_eq!(resp.status().as_u16(), 429); + let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap(); + serde_json::from_slice(&bytes).unwrap() + } + let chat = body(Dialect::Chat).await; + assert_eq!(chat["error"]["type"], "rate_limit_error"); + assert_eq!(chat["error"]["message"], "Rate limited: rule"); + let anthropic = body(Dialect::Anthropic).await; + assert_eq!(anthropic["type"], "error"); + assert_eq!(anthropic["error"]["type"], "rate_limit_error"); + let gemini = body(Dialect::Gemini).await; + assert_eq!(gemini["error"]["code"], 429); + assert_eq!(gemini["error"]["status"], "RESOURCE_EXHAUSTED"); + } + #[test] fn retry_after_parser_handles_delta_seconds_and_garbage() { use crate::error::parse_retry_after_seconds; diff --git a/crates/gateway/src/proxy/transport.rs b/crates/gateway/src/proxy/transport.rs index 06b4ab07..968b7109 100644 --- a/crates/gateway/src/proxy/transport.rs +++ b/crates/gateway/src/proxy/transport.rs @@ -16,10 +16,6 @@ pub use crate::bedrock::sigv4::Signer; use crate::call_ctx::CallCtx; use crate::error::GatewayError; -/// Sent to an Anthropic upstream when neither the caller nor the provider -/// row names a version. Without one the API refuses the request. -const ANTHROPIC_VERSION: &str = "2023-06-01"; - /// The HTTP client every upstream call goes through. /// /// **Different from the desktop gateway on purpose.** Desktop sets no @@ -90,20 +86,7 @@ impl Upstream { pub fn is_official(&self) -> bool { match &self.shape { Shape::Bedrock { .. } | Shape::Azure { .. } => true, - Shape::Standard => { - let host = self - .base_url - .split("://") - .nth(1) - .unwrap_or(&self.base_url) - .split(['/', ':']) - .next() - .unwrap_or_default(); - matches!( - host, - "api.openai.com" | "api.anthropic.com" | "generativelanguage.googleapis.com" - ) - } + Shape::Standard => tw_dialect::official::is_official_host(&self.base_url), } } @@ -131,7 +114,8 @@ impl Upstream { for (k, v) in extra { req = req.header(k, v); } - // Anthropic refuses a request without a version header. + // Anthropic refuses a request without a version header. One the + // provider row or the caller set wins. if dialect == tw_dialect::ir::Dialect::Anthropic && !self .headers @@ -139,7 +123,7 @@ impl Upstream { .chain(extra) .any(|(k, _)| k.eq_ignore_ascii_case("anthropic-version")) { - req = req.header("anthropic-version", ANTHROPIC_VERSION); + req = req.header("anthropic-version", tw_dialect::official::ANTHROPIC_VERSION); } if let Some(trace) = &ctx.trace_id { req = req.header("x-trace-id", trace.as_str()); @@ -282,6 +266,19 @@ mod tests { ); } + #[test] + fn only_the_vendors_own_host_counts_as_official() { + assert!(up("https://api.anthropic.com/", Shape::Standard).is_official()); + assert!(up("https://api.deepseek.com/anthropic", Shape::Standard).is_official()); + // A relay cannot dress up as the vendor through its path or user info. + assert!(!up("https://relay.example/api.openai.com", Shape::Standard).is_official()); + assert!(!up("https://api.openai.com@relay.example", Shape::Standard).is_official()); + let azure = Shape::Azure { + api_version: "2024-02-01".into(), + }; + assert!(up("https://x.openai.azure.com", azure).is_official()); + } + #[test] fn azure_addresses_the_model_by_deployment_in_the_url() { let u = up( diff --git a/crates/server/src/handlers/providers.rs b/crates/server/src/handlers/providers.rs index c077b0fb..b254f0ef 100644 --- a/crates/server/src/handlers/providers.rs +++ b/crates/server/src/handlers/providers.rs @@ -609,12 +609,12 @@ pub(crate) async fn run_provider_test( // Provider-specific probe URL. We always hit a cheap, read-only // endpoint that requires auth so a wrong key is detected too. - let url = match req.provider_type.as_str() { - "anthropic" => format!("{}/v1/models", req.base_url.trim_end_matches('/')), - "google" => format!("{}/v1beta/models", req.base_url.trim_end_matches('/')), - // openai / azure / custom — all OpenAI-compatible /v1/models - _ => format!("{}/v1/models", req.base_url.trim_end_matches('/')), + let path = match req.provider_type.as_str() { + "google" => "/v1beta/models", + // anthropic / openai / azure / custom — all answer /v1/models + _ => "/v1/models", }; + let url = tw_dialect::url::upstream_url(&req.base_url, path, None); // `client` is now passed in from `test_provider` — uses the // shared http_client so this endpoint inherits the central diff --git a/crates/test-support/tests/gateway_error_shapes.rs b/crates/test-support/tests/gateway_error_shapes.rs new file mode 100644 index 00000000..1f86af1a --- /dev/null +++ b/crates/test-support/tests/gateway_error_shapes.rs @@ -0,0 +1,170 @@ +//! Errors reach each client in the shape its own SDK reads. +//! +//! An Anthropic SDK looks for `{"type":"error","error":{"type",…}}`, a +//! Responses client dispatches on `response.failed` and skips anything +//! else, a Chat client reads `{"error":{"message","type"}}`. Before, every +//! surface got the Chat shape — for the whole body and in a stream — so +//! an Anthropic or Responses client saw a gateway refusal as a response +//! it could not parse, or as a stream that simply stopped. + +use serde_json::Value; +use think_watch_test_support::prelude::*; + +/// A key allowed on the AI gateway, and `model` routed to an OpenAI +/// upstream that answers every request with a 500. +async fn failing_route(app: &TestApp, model: &str) -> (MockProvider, String) { + let upstream = MockProvider::always_500().await; + let user = fixtures::create_random_user(&app.db).await.unwrap(); + let provider = fixtures::create_provider( + &app.db, + &unique_name("broken"), + "openai", + &upstream.uri(), + None, + ) + .await + .unwrap(); + fixtures::create_model_and_route(&app.db, provider.id, model) + .await + .unwrap(); + app.rebuild_gateway_router().await; + let key = fixtures::create_api_key(&app.db, user.user.id, "e", &["ai_gateway"], None, None) + .await + .unwrap(); + (upstream, key.plaintext) +} + +/// The `data:` payloads of an SSE body, with their event names. +fn frames(body: &str) -> Vec<(Option, Value)> { + body.split("\n\n") + .filter_map(|block| { + let mut event = None; + let mut data = None; + for line in block.lines() { + if let Some(e) = line.strip_prefix("event: ") { + event = Some(e.to_string()); + } else if let Some(d) = line.strip_prefix("data: ") { + data = serde_json::from_str(d).ok(); + } + } + Some((event, data?)) + }) + .collect() +} + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn an_anthropic_client_gets_an_anthropic_error_body() { + let app = TestApp::spawn().await; + let (_upstream, key) = failing_route(&app, "err-shape-a").await; + let gw = app.gateway_client(); + gw.set_bearer(&key); + + let resp = gw + .post( + "/v1/messages", + json!({"model": "err-shape-a", "max_tokens": 16, + "messages": [{"role": "user", "content": "hi"}]}), + ) + .await + .unwrap(); + resp.assert_status(500); + let body: Value = resp.json().unwrap(); + assert_eq!(body["type"], "error", "{body}"); + assert_eq!(body["error"]["type"], "api_error", "{body}"); + assert!(body["error"]["message"].is_string(), "{body}"); +} + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn a_refusal_before_routing_is_in_the_callers_format_too() { + let app = TestApp::spawn().await; + let (_upstream, key) = failing_route(&app, "err-shape-known").await; + let gw = app.gateway_client(); + gw.set_bearer(&key); + + // No route for this model: refused before any upstream is called. + let resp = gw + .post( + "/v1/messages", + json!({"model": "err-shape-nowhere", "max_tokens": 16, + "messages": [{"role": "user", "content": "hi"}]}), + ) + .await + .unwrap(); + assert!(!resp.status.is_success()); + let body: Value = resp.json().unwrap(); + assert_eq!(body["type"], "error", "{body}"); + assert!(body["error"]["type"].is_string(), "{body}"); +} + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn a_chat_client_gets_openais_error_types() { + let app = TestApp::spawn().await; + let (_upstream, key) = failing_route(&app, "err-shape-c").await; + let gw = app.gateway_client(); + gw.set_bearer(&key); + + let resp = gw + .post( + "/v1/chat/completions", + json!({"model": "err-shape-c", "messages": [{"role": "user", "content": "hi"}]}), + ) + .await + .unwrap(); + resp.assert_status(500); + let body: Value = resp.json().unwrap(); + assert_eq!(body["error"]["type"], "server_error", "{body}"); + assert!(body.get("type").is_none(), "{body}"); +} + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn a_responses_stream_that_fails_ends_with_response_failed() { + let app = TestApp::spawn().await; + let (_upstream, key) = failing_route(&app, "err-shape-r").await; + let gw = app.gateway_client(); + gw.set_bearer(&key); + + let resp = gw + .post( + "/v1/responses", + json!({"model": "err-shape-r", "stream": true, "input": "hi"}), + ) + .await + .unwrap(); + let text = resp.text(); + let fs = frames(&text); + let (event, data) = fs.last().unwrap_or_else(|| panic!("no frames in {text}")); + assert_eq!(event.as_deref(), Some("response.failed"), "{text}"); + assert_eq!(data["type"], "response.failed", "{text}"); + assert_eq!(data["response"]["status"], "failed", "{text}"); + assert!(data["response"]["error"]["message"].is_string(), "{text}"); + // The caller's model, like every other frame it receives. + assert_eq!(data["response"]["model"], "err-shape-r", "{text}"); +} + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn an_anthropic_stream_that_fails_ends_with_an_error_event() { + let app = TestApp::spawn().await; + let (_upstream, key) = failing_route(&app, "err-shape-as").await; + let gw = app.gateway_client(); + gw.set_bearer(&key); + + let resp = gw + .post( + "/v1/messages", + json!({"model": "err-shape-as", "max_tokens": 16, "stream": true, + "messages": [{"role": "user", "content": "hi"}]}), + ) + .await + .unwrap(); + let text = resp.text(); + let fs = frames(&text); + let (event, data) = fs.last().unwrap_or_else(|| panic!("no frames in {text}")); + assert_eq!(event.as_deref(), Some("error"), "{text}"); + assert_eq!(data["type"], "error", "{text}"); + assert_eq!(data["error"]["type"], "api_error", "{text}"); +}