🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(ai-gateway): attribute errors by origin and measure gateway overhead (#18919)
Tobias Wochinger5832994c9a0e
diff --git a/ai-gateway/README.md b/ai-gateway/README.mdindex 6040c4a1b9..260c952561 100644--- a/ai-gateway/README.md+++ b/ai-gateway/README.md@@ -197,7 +197,7 @@ generation routes listed above, when the body is uncompressed JSON of at most 5The span fields are declared empty on the `http.server` span and recorded afterresolution; child spans do not repeat them. JSON log lines emitted inside therequest after they are recorded repeat them as top-level keys, like `request_id`.-They are never metric attributes.+Apart from the bounded `gateway.provider`, they are never metric attributes.Each inference request phase has a child span of the server span so a waterfallhas no unattributed wall time:@@ -223,17 +223,36 @@ Client spans measure the HTTP send through response headers;streaming execution and inference-telemetry delivery are tracked separately.A small Axum middleware records `http.server.request.duration` through the-OpenTelemetry SDK, with method, matched route, and HTTP status as its only-dimensions. The histogram's count supplies request volume and error rates,-including responses rejected before provider execution. Metrics are independent-of trace sampling. Health probes are excluded.--Gateway-specific metrics include `gateway.active` (model_catalog/resolution/execution),-`gateway.phase.duration` (execution/provider.first_byte), `gateway.executions`,-`gateway.admission.rejected`, and `gateway.telemetry.records`. Durations use seconds;-first-byte timing measures provider bytes arriving at the gateway, not first-token-delivery to the caller. Metric attributes contain bounded categories, not tenant-or request identifiers.+OpenTelemetry SDK, with method, matched route, HTTP status, `error.origin`,+`error.reason`, and `gateway.provider` as its dimensions. The histogram's count+supplies request volume and error rates, including responses rejected before+provider execution. Metrics are independent of trace sampling. Health probes are+excluded.++`error.origin` names who caused a failed response: `none`, `client`,+`gateway`, `control_plane`, `provider_transport`, or `provider` (an error status+relayed unchanged, with `error.reason` `provider_rate_limited`, `provider_auth`,+`provider_4xx`, or `provider_5xx`). The server span carries the same origin and+reason (as `error.type`); it has an error status only for 5xx.++Gateway-specific metrics:++- `gateway.overhead.duration` (`http.route`, `gateway.provider`): time to response+ headers minus the caller's upload and the provider's wait; recorded only for+ requests that reached the provider.+- `http.server.request.body.size` (`http.route`, `gateway.provider`) and+ `http.server.response.body.size` (`gateway.provider`), in bytes: the buffered+ request body, and the bytes relayed from the provider, including truncated or+ cancelled streams.+- `gateway.active`, `gateway.admission.capacity`, and `gateway.active.peak`+ (`phase`): in-flight, configured, and most-held-since-last-export slots for+ model_catalog/resolution/execution.+- `gateway.phase.duration` (execution/provider.first_byte), `gateway.executions`,+ `gateway.admission.rejected`, and `gateway.telemetry.records`.++Durations use seconds; first-byte timing measures provider bytes arriving at the+gateway, not first-token delivery to the caller. Metric attributes contain+bounded categories, not tenant or request identifiers.Trace export uses a 512-span queue, batches of up to 64, and a one-second interval.Metrics export every 30 seconds. Export calls use a three-second timeout; failuresdiff --git a/ai-gateway/src/capture/facts.rs b/ai-gateway/src/capture/facts.rsindex 2e57e62ecd..6dfd26a347 100644--- a/ai-gateway/src/capture/facts.rs+++ b/ai-gateway/src/capture/facts.rs@@ -20,6 +20,11 @@ impl RelayOutcome {Self::TransportError => "transport_error",}}++ /// A cancellation is the caller hanging up, so it is not a failure.+ pub(crate) fn is_failure(self) -> bool {+ matches!(self, Self::Timeout | Self::TransportError)+ }}#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]diff --git a/ai-gateway/src/capture/mod.rs b/ai-gateway/src/capture/mod.rsindex 0c7e189fdb..612eaead07 100644--- a/ai-gateway/src/capture/mod.rs+++ b/ai-gateway/src/capture/mod.rs@@ -233,6 +233,7 @@ impl ExecutionCapture {pub(crate) fn finish(&mut self, outcome: RelayOutcome) {let span = self.span.clone();let _entered = span.enter();+ crate::observability::execution_failed(outcome);let Some(protocol) = self.protocol.take() else {return;};diff --git a/ai-gateway/src/correlation.rs b/ai-gateway/src/correlation.rsindex 27dc35d864..956c54115e 100644--- a/ai-gateway/src/correlation.rs+++ b/ai-gateway/src/correlation.rs@@ -9,7 +9,10 @@ use axum::{response::Response,};-use crate::resolution::{OrganizationId, ProjectId, ProviderConnection, ResolvedRequestContext};+use crate::{+ observability::RequestObservation,+ resolution::{OrganizationId, ProjectId, ProviderConnection, ResolvedRequestContext},+};pub(crate) const REQUEST_ID_HEADER: HeaderName = HeaderName::from_static("langfuse-request-id");const TRACE_ID_HEADER: HeaderName = HeaderName::from_static("langfuse-trace-id");@@ -67,6 +70,7 @@ pub(crate) struct RequestCorrelation {upstream: Option<UpstreamTarget>,/// The request's `http.server` span, which outlives the phase spans.server_span: tracing::Span,+ observation: RequestObservation,}impl Default for RequestCorrelation {@@ -78,6 +82,7 @@ impl Default for RequestCorrelation {tenant: None,upstream: None,server_span: tracing::Span::none(),+ observation: RequestObservation::default(),}}}@@ -115,6 +120,11 @@ impl RequestCorrelation {self.client_id.as_deref()}+ /// Error origin and phase timings for the response metric.+ pub(crate) fn observation(&self) -> &RequestObservation {+ &self.observation+ }+pub(crate) fn record_generation(&mut self, ids: GenerationIds) {self.generation = Some(ids);}@@ -196,6 +206,9 @@ pub(crate) async fn assign_request_id(mut request: Request, next: Next) -> Respospan.record("gateway.client.request.id", client_id);}correlation.server_span = span;+ if let Some(observation) = request.extensions().get::<RequestObservation>() {+ correlation.observation = observation.clone();+ }#[expect(clippy::expect_used, reason = "the gateway-generated UUID is ASCII")]let value = HeaderValue::from_str(correlation.id()).expect("a UUID is a valid header value");request.extensions_mut().insert(correlation);diff --git a/ai-gateway/src/http.rs b/ai-gateway/src/http.rsindex 648ed9de98..90f5d5e738 100644--- a/ai-gateway/src/http.rs+++ b/ai-gateway/src/http.rs@@ -1,4 +1,4 @@-use std::{ops::Range, sync::Arc};+use std::{ops::Range, sync::Arc, time::Instant};use axum::{Json, Router,@@ -16,7 +16,11 @@ use tracing::Instrument;use crate::{correlation::{RequestCorrelation, assign_request_id},- inference::{InferenceService, RequestBodyPermit, RequestPreparationError},+ inference::{+ InferenceService, RequestBodyPermit, RequestPreparationError, provider_origin,+ resolution_origin,+ },+ observability::{ErrorOrigin, Wait},providers::{ProviderError, RequestBody, Route},resolution::{ApiFormat, ResolutionError},server::GatewayLifecycleState,@@ -112,6 +116,9 @@ async fn handle_inference(.extensions_mut().remove::<RequestCorrelation>().unwrap_or_default();+ correlation+ .observation()+ .record_provider(route.api_format().provider().as_str());let result = match prepare_request(&state, request.headers(), route.api_format()) {Ok((inference, gateway_key)) => {relay(&inference, &gateway_key, request, route, &mut correlation).await@@ -130,6 +137,9 @@ async fn handle_models(.extensions_mut().remove::<RequestCorrelation>().unwrap_or_default();+ correlation+ .observation()+ .record_provider(api_format.provider().as_str());let result = match prepare_request(&state, request.headers(), api_format) {Ok((inference, gateway_key)) => {models(&inference, &gateway_key, api_format, &correlation).await@@ -161,7 +171,11 @@ fn finish_response() -> Response {let mut response = match result {Ok(response) => response,- Err(error) => error.into_native_response(api_format, correlation.id()),+ Err(error) => {+ let (origin, reason) = error.origin();+ correlation.observation().record_error(origin, reason);+ error.into_native_response(api_format, correlation)+ }};correlation.apply_generation_headers(response.headers_mut());correlation.apply_resolution_headers(response.headers_mut());@@ -197,13 +211,19 @@ async fn relay(.try_reserve_request_body().map_err(InferenceHttpError::from)?;let (parts, body) = request.into_parts();- let (bytes, body_permit) = read_request_body(+ let started = Instant::now();+ let read = read_request_body(body,&parts.headers,inference.max_request_bytes(),body_permit,)- .await?;+ .await;+ correlation+ .observation()+ .record_wait(Wait::RequestBody, started.elapsed());+ let (bytes, body_permit) = read?;+ correlation.observation().record_request_bytes(bytes.len());let request_body = request_body_and_model(bytes)?;let (permit, context) = inference.resolve_and_admit(@@ -464,6 +484,7 @@ impl InferenceHttpError {R::Forbidden => "forbidden",R::ModelNotAllowed => "model_not_allowed",R::NoRoute => "no_route",+ R::Busy => "capacity",R::Timeout => "timeout",R::Unavailable => "unavailable",R::Configuration => "configuration",@@ -548,7 +569,7 @@ impl InferenceHttpError {"invalid_model",),Self::Unavailable- | Self::Resolution(R::Unavailable | R::Configuration)+ | Self::Resolution(R::Unavailable | R::Configuration | R::Busy)| Self::Provider(ProviderError::Configuration | ProviderError::Busy) => (StatusCode::SERVICE_UNAVAILABLE,"Gateway temporarily unavailable",@@ -571,13 +592,34 @@ impl InferenceHttpError {}}- fn into_native_response(self, api_format: ApiFormat, request_id: &str) -> Response {+ fn origin(&self) -> (ErrorOrigin, &'static str) {+ match self {+ Self::Unavailable => (ErrorOrigin::Gateway, "unavailable"),+ Self::Credential => (ErrorOrigin::Client, "invalid_credential"),+ Self::AmbiguousCredential => (ErrorOrigin::Client, "ambiguous_credential"),+ Self::TooLarge => (ErrorOrigin::Client, "body_too_large"),+ Self::RequestTimeout => (ErrorOrigin::Client, "body_timeout"),+ Self::UnsupportedEncoding => (ErrorOrigin::Client, "unsupported_content_encoding"),+ Self::InvalidBody => (ErrorOrigin::Client, "invalid_body"),+ Self::Resolution(error) => resolution_origin(*error),+ Self::Provider(error) => provider_origin(*error),+ }+ }++ fn into_native_response(+ self,+ api_format: ApiFormat,+ correlation: &RequestCorrelation,+ ) -> Response {let (phase, reason) = self.category();+ let (origin, _) = self.origin();let (status, message, kind, code) = self.classify();+ // Caller mistakes are routine; only failures that need an operator warn.if status.is_server_error() {tracing::warn!(phase,reason,+ error.origin = origin.as_str(),status = status.as_u16(),"gateway request rejected");@@ -585,10 +627,12 @@ impl InferenceHttpError {tracing::debug!(phase,reason,+ error.origin = origin.as_str(),status = status.as_u16(),"gateway request rejected");}+ let request_id = correlation.id();match api_format {ApiFormat::OpenAiResponses | ApiFormat::OpenAiChatCompletions => (status,diff --git a/ai-gateway/src/inference.rs b/ai-gateway/src/inference.rsindex eb951a689c..3162477d4f 100644--- a/ai-gateway/src/inference.rs+++ b/ai-gateway/src/inference.rs@@ -11,6 +11,7 @@ use tracing::Instrument;use crate::{config::{GatewayConfig, RequestLimits},correlation::RequestCorrelation,+ observability::ErrorOrigin,providers::{ProviderError, ProviderTransport, RequestBody, RequestPermit, Route},resolution::{ApiFormat, ControlPlaneClient, ControlPlaneConfig, ResolutionError, ResolvedRequestContext,@@ -33,6 +34,44 @@ pub(crate) enum RequestPreparationError {Provider(ProviderError),}+impl RequestPreparationError {+ pub(crate) fn origin(&self) -> (ErrorOrigin, &'static str) {+ match *self {+ Self::Resolution(error) => resolution_origin(error),+ Self::Provider(error) => provider_origin(error),+ }+ }+}++/// `error.origin` and `error.reason` for a failed resolution or catalog fetch.+pub(crate) fn resolution_origin(error: ResolutionError) -> (ErrorOrigin, &'static str) {+ use ResolutionError as R;+ match error {+ R::Configuration => (ErrorOrigin::Gateway, "configuration"),+ R::Busy => (ErrorOrigin::Gateway, "capacity"),+ R::InvalidCredential | R::Authentication => (ErrorOrigin::Client, "authentication"),+ R::InvalidRequest => (ErrorOrigin::Client, "invalid_request"),+ R::Forbidden => (ErrorOrigin::Client, "forbidden"),+ R::ModelNotAllowed => (ErrorOrigin::Client, "model_not_allowed"),+ R::NoRoute => (ErrorOrigin::Client, "no_route"),+ R::Unavailable => (ErrorOrigin::ControlPlane, "unavailable"),+ R::Timeout => (ErrorOrigin::ControlPlane, "timeout"),+ R::Transport => (ErrorOrigin::ControlPlane, "transport"),+ R::InvalidResponse => (ErrorOrigin::ControlPlane, "invalid_response"),+ R::ResponseTooLarge => (ErrorOrigin::ControlPlane, "response_too_large"),+ }+}++/// `error.origin` and `error.reason` for a provider request that produced no response.+pub(crate) fn provider_origin(error: ProviderError) -> (ErrorOrigin, &'static str) {+ match error {+ ProviderError::Configuration => (ErrorOrigin::Gateway, "configuration"),+ ProviderError::Busy => (ErrorOrigin::Gateway, "capacity"),+ ProviderError::Timeout => (ErrorOrigin::ProviderTransport, "timeout"),+ ProviderError::Transport => (ErrorOrigin::ProviderTransport, "transport"),+ }+}+/// One request-body slot plus the body bytes reserved so far from the shared budget./// It is held with the execution and released once the response ends.pub(crate) struct RequestBodyPermit {@@ -45,7 +84,7 @@ impl RequestBodyPermit {/// Grow the reservation to `total` body bytes without waiting.////// # Errors- /// Returns [`ResolutionError::Unavailable`] when the shared budget cannot cover `total`.+ /// Returns [`ResolutionError::Busy`] when the shared budget cannot cover `total`.pub(crate) fn try_reserve_bytes(&mut self, total: usize) -> Result<(), ResolutionError> {let Some(missing) = total.checked_sub(self.bytes.num_permits())@@ -62,7 +101,7 @@ impl RequestBodyPermit {}).ok_or_else(|| {crate::observability::rejected("request_bytes");- ResolutionError::Unavailable+ ResolutionError::Busy})?;self.bytes.merge(reserved);Ok(())@@ -88,6 +127,8 @@ impl InferenceService {}let telemetry =crate::telemetry::Telemetry::new(&control_plane, config.telemetry_buffer_bytes)?;+ crate::observability::record_capacity("model_catalog", max_concurrent_resolutions);+ crate::observability::record_capacity("resolution", max_concurrent_resolutions);Ok(Self {control_plane: ControlPlaneClient::new(control_plane)?,provider: ProviderTransport::new(config.max_active_requests, config.execution_limits)@@ -111,7 +152,7 @@ impl InferenceService {fn try_reserve_resolution(&self) -> Result<SemaphorePermit<'_>, ResolutionError> {self.resolution_capacity.try_acquire().map_err(|_| {crate::observability::rejected("resolution");- ResolutionError::Unavailable+ ResolutionError::Busy})}@@ -122,7 +163,7 @@ impl InferenceService {.try_acquire_owned().map_err(|_| {crate::observability::rejected("request_body");- RequestPreparationError::Resolution(ResolutionError::Unavailable)+ RequestPreparationError::Resolution(ResolutionError::Busy)})?;let bytes = Arc::clone(&self.request_bytes_capacity).try_acquire_many_owned(0)@@ -157,7 +198,7 @@ impl InferenceService {) -> Result<Vec<u8>, ResolutionError> {let _permit = self.model_catalog_capacity.try_acquire().map_err(|_| {crate::observability::rejected("model_catalog");- ResolutionError::Unavailable+ ResolutionError::Busy})?;let _active = crate::observability::Active::new("model_catalog");let body = self@@ -180,13 +221,16 @@ impl InferenceService {let span = tracing::info_span!("resolution",otel.kind = "internal",- gateway.outcome = tracing::field::Empty+ gateway.outcome = tracing::field::Empty,+ otel.status_code = tracing::field::Empty,+ error.type = tracing::field::Empty);async {let prepared = self.prepare(gateway_key, api_format, model, correlation).await;- tracing::Span::current().record(+ let span = tracing::Span::current();+ span.record("gateway.outcome",match &prepared {Ok(_) => "admitted",@@ -194,6 +238,15 @@ impl InferenceService {Err(RequestPreparationError::Provider(_)) => "busy",},);+ // Caller-caused failures (bad key, forbidden model) stay unset so+ // Datadog error rates track gateway and control-plane faults only.+ if let Err(error) = &prepared+ && let (origin, reason) = error.origin()+ && origin.is_ours()+ {+ span.record("otel.status_code", "ERROR");+ span.record("error.type", reason);+ }prepared}.instrument(span)diff --git a/ai-gateway/src/observability/http.rs b/ai-gateway/src/observability/http.rsindex 67c116281a..5f5399952f 100644--- a/ai-gateway/src/observability/http.rs+++ b/ai-gateway/src/observability/http.rs@@ -4,7 +4,7 @@ use axum::{Router,body::Body,extract::MatchedPath,- http::{HeaderMap, Request},+ http::{HeaderMap, Request, StatusCode},middleware::{self, Next},response::Response,};@@ -13,15 +13,17 @@ use tower_http::trace::TraceLayer;use tracing::Span;use tracing_opentelemetry::OpenTelemetrySpanExt;+use super::request::{ErrorOrigin, RequestObservation, Summary};+/// Instrument application routes; mount health probes outside this router.pub fn instrument(router: Router) -> Router {router- .layer(middleware::from_fn(record_http_duration))+ .layer(middleware::from_fn(observe_request)).layer(TraceLayer::new_for_http().make_span_with(|request: &Request<Body>| {let (method, route) = request_labels(request);- let span = tracing::info_span!(parent: None, "http.server", otel.name = %format_args!("{method} {route}"), otel.kind = "server", http.request.method = method, http.route = route, http.request.body.size = tracing::field::Empty, http.response.status_code = tracing::field::Empty, otel.status_code = tracing::field::Empty, gateway.request.id = tracing::field::Empty, gateway.client.request.id = tracing::field::Empty, langfuse.organization.id = tracing::field::Empty, langfuse.project.id = tracing::field::Empty, gateway.provider = tracing::field::Empty, gateway.provider.connection.id = tracing::field::Empty, gateway.provider.connection.name = tracing::field::Empty, gateway.upstream.model = tracing::field::Empty, provider_request_id = tracing::field::Empty, gateway.outcome = tracing::field::Empty, gateway.first_byte_ms = tracing::field::Empty);+ let span = tracing::info_span!(parent: None, "http.server", otel.name = %format_args!("{method} {route}"), otel.kind = "server", http.request.method = method, http.route = route, http.request.body.size = tracing::field::Empty, http.response.status_code = tracing::field::Empty, otel.status_code = tracing::field::Empty, otel.status_description = tracing::field::Empty, error.type = tracing::field::Empty, error.origin = tracing::field::Empty, gateway.request.id = tracing::field::Empty, gateway.client.request.id = tracing::field::Empty, langfuse.organization.id = tracing::field::Empty, langfuse.project.id = tracing::field::Empty, gateway.provider = tracing::field::Empty, gateway.provider.connection.id = tracing::field::Empty, gateway.provider.connection.name = tracing::field::Empty, gateway.upstream.model = tracing::field::Empty, provider_request_id = tracing::field::Empty, gateway.outcome = tracing::field::Empty, gateway.first_byte_ms = tracing::field::Empty);// Operational tracing has no caller or ambient trace context.let _ = span.set_parent(Context::new());span@@ -51,15 +53,67 @@ pub fn instrument(router: Router) -> Router {)}-async fn record_http_duration(request: Request<Body>, next: Next) -> Response {+async fn observe_request(mut request: Request<Body>, next: Next) -> Response {let (method, route) = request_labels(&request);let (method, route) = (method.to_owned(), route.to_owned());+ let observation = RequestObservation::default();+ request.extensions_mut().insert(observation.clone());let start = Instant::now();let response = next.run(request).await;- super::metrics::http_response(start.elapsed(), method, route, response.status().as_u16());+ let elapsed = start.elapsed();+ let status = response.status();+ let summary = observation.summary();+ let (origin, reason) = summary.error.unwrap_or_else(|| fallback_error(status));+ record_span_error(origin, reason, status);+ super::metrics::http_response(+ elapsed,+ &super::metrics::HttpResponse {+ method: &method,+ route: &route,+ status: status.as_u16(),+ origin,+ reason,+ provider: summary.provider,+ },+ );+ record_overhead(&route, &summary, elapsed);+ if let Some(bytes) = summary.request_bytes {+ super::metrics::request_body_size(&route, summary.provider, bytes);+ }response}+/// Classifies responses the handler did not, such as router 404/405.+fn fallback_error(status: StatusCode) -> (ErrorOrigin, &'static str) {+ match status.as_u16() {+ 400..=499 => (ErrorOrigin::Client, "unhandled"),+ 500.. => (ErrorOrigin::Gateway, "unhandled"),+ _ => (ErrorOrigin::None, "none"),+ }+}++fn record_span_error(origin: ErrorOrigin, reason: &'static str, status: StatusCode) {+ if origin == ErrorOrigin::None {+ return;+ }+ let span = Span::current();+ span.record("error.origin", origin.as_str());+ span.record("error.type", reason);+ if status.is_server_error() {+ span.record("otel.status_description", reason);+ }+}++/// Overhead is only defined for requests that waited on a provider.+fn record_overhead(route: &str, summary: &Summary, elapsed: Duration) {+ if let Some(provider_headers) = summary.provider_headers {+ let total = elapsed+ .saturating_sub(summary.request_body.unwrap_or_default())+ .saturating_sub(provider_headers);+ super::metrics::overhead(route, summary.provider, total);+ }+}+fn request_labels(request: &Request<Body>) -> (&str, &str) {let route = request.extensions()diff --git a/ai-gateway/src/observability/http/tests.rs b/ai-gateway/src/observability/http/tests.rsindex 79ab5832ab..d905df4d7f 100644--- a/ai-gateway/src/observability/http/tests.rs+++ b/ai-gateway/src/observability/http/tests.rs@@ -238,6 +238,135 @@ async fn provider_http_errors_are_traced_without_changing_the_response() {}}+/// Datadog splits gateway faults from relayed provider errors by the server span's+/// `error.origin`; only 5xx responses mark the span as an error.+#[tokio::test]+async fn failed_responses_name_their_origin_on_the_server_span() {+ for (provider_status, capacity, origin, reason) in [+ (429, 1, "provider", "provider_rate_limited"),+ (401, 1, "provider", "provider_auth"),+ (500, 1, "provider", "provider_5xx"),+ (200, 0, "gateway", "capacity"),+ ] {+ let web = FakeServer::start(|_| async { resolution_response("provider-secret") }).await;+ let provider = FakeServer::start(move |_| async move {+ Response::builder()+ .status(provider_status)+ .body(Body::from("native error"))+ .unwrap()+ })+ .await;+ let service = InferenceService::for_test(+ web.control_plane(),+ ProviderTransport::for_test(provider.url.clone(), ProviderLimits::default()),+ capacity,+ );+ let recording = Recording::start();+ let lifecycle = GatewayLifecycleState::default();+ let app = instrument(crate::http::router(Some(service), lifecycle.clone()));+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let mut serving = Box::pin(crate::server::serve(+ listener,+ app.clone(),+ lifecycle,+ std::future::pending(),+ Duration::from_secs(1),+ ));+ assert!(futures_util::poll!(serving.as_mut()).is_pending());+ let response = app.oneshot(generation_request()).await.unwrap();+ let status = response.status();+ axum::body::to_bytes(response.into_body(), 4096)+ .await+ .unwrap();+ let spans = recording.exporter.get_finished_spans().unwrap();+ let server = spans+ .iter()+ .find(|span| span.span_kind == SpanKind::Server)+ .unwrap();+ assert_attribute(server, "error.origin", origin);+ assert_attribute(server, "error.type", reason);+ assert_eq!(+ matches!(server.status, opentelemetry::trace::Status::Error { .. }),+ status.is_server_error(),+ "{reason}"+ );+ if capacity == 0 {+ assert_eq!(status, 503);+ assert_eq!(web.calls() + provider.calls(), 0);+ } else {+ assert_eq!(status.as_u16(), provider_status);+ }+ }+}++/// Token counting captures no generation, yet a body that breaks after the+/// headers must still fail the server span.+#[tokio::test]+async fn late_body_failures_fail_the_server_span_without_a_generation() {+ let web = FakeServer::start(|_| async {+ crate::test_support::resolution_response_for(+ crate::resolution::ApiFormat::AnthropicMessages,+ "provider-secret",+ )+ })+ .await;+ let provider = FakeServer::start(|_| async {+ let chunks = futures_util::StreamExt::chain(+ futures_util::stream::iter([Ok::<_, io::Error>(Bytes::from_static(+ b"{\"input_tokens\"",+ ))]),+ futures_util::stream::once(async {+ tokio::time::sleep(Duration::from_millis(50)).await;+ Err(io::Error::other("provider reset"))+ }),+ );+ Response::new(Body::from_stream(chunks))+ })+ .await;+ let service = InferenceService::for_test(+ web.control_plane(),+ ProviderTransport::for_test(provider.url.clone(), ProviderLimits::default()),+ 1,+ );+ let recording = Recording::start();+ let lifecycle = GatewayLifecycleState::default();+ let app = instrument(crate::http::router(Some(service), lifecycle.clone()));+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let mut serving = Box::pin(crate::server::serve(+ listener,+ app.clone(),+ lifecycle,+ std::future::pending(),+ Duration::from_secs(1),+ ));+ assert!(futures_util::poll!(serving.as_mut()).is_pending());+ let request = HttpRequest::post("/anthropic/v1/messages/count_tokens")+ .header("x-api-key", "gateway-secret")+ .header("content-type", "application/json")+ .body(Body::from(+ r#"{"model":"Production key:test-model","messages":[]}"#,+ ))+ .unwrap();+ let response = app.oneshot(request).await.unwrap();+ assert_eq!(response.status(), 200);+ assert!(+ axum::body::to_bytes(response.into_body(), 4096)+ .await+ .is_err()+ );+ let spans = recording.exporter.get_finished_spans().unwrap();+ let server = spans+ .iter()+ .find(|span| span.span_kind == SpanKind::Server)+ .unwrap();+ assert_attribute(server, "error.origin", "provider_transport");+ assert_attribute(server, "error.type", "transport_error");+ assert!(matches!(+ server.status,+ opentelemetry::trace::Status::Error { .. }+ ));+}+#[tokio::test]async fn generation_context_is_isolated_from_operational_spans_and_outbound_headers() {opentelemetry::global::set_text_map_propagator(diff --git a/ai-gateway/src/observability/metrics.rs b/ai-gateway/src/observability/metrics.rsindex f8762b5b10..9c5841e727 100644--- a/ai-gateway/src/observability/metrics.rs+++ b/ai-gateway/src/observability/metrics.rs@@ -1,15 +1,26 @@-use std::sync::LazyLock;+use std::{+ sync::{+ LazyLock,+ atomic::{AtomicU64, Ordering},+ },+ time::Duration,+};-use crate::capture::RelayOutcome;+use crate::capture::{InferenceFacts, RelayOutcome};use opentelemetry::trace::TraceContextExt;use opentelemetry::{KeyValue, global,- metrics::{Counter, Histogram, UpDownCounter},+ metrics::{Counter, Histogram, ObservableGauge, UpDownCounter},};use tracing_opentelemetry::OpenTelemetrySpanExt;+use super::request::ErrorOrigin;+struct Metrics {http_duration: Histogram<f64>,+ overhead: Histogram<f64>,+ request_size: Histogram<u64>,+ response_size: Histogram<u64>,active: UpDownCounter<i64>,phases: Histogram<f64>,rejections: Counter<u64>,@@ -19,6 +30,10 @@ struct Metrics {static METRICS: LazyLock<Metrics> = LazyLock::new(|| {let meter = global::meter("ai-gateway");+ // Chat payloads are kilobytes; long contexts and images reach tens of MiB.+ let bytes: Vec<f64> = [10, 12, 14, 16, 18, 20, 22, 24, 26]+ .map(|power| f64::from(1u32 << power))+ .to_vec();let seconds = vec![0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 600.0,];@@ -30,6 +45,25 @@ static METRICS: LazyLock<Metrics> = LazyLock::new(|| {0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, 7.5, 10.0,]).build(),+ // Gateway work is expected in the sub-millisecond to tens of milliseconds range.+ overhead: meter+ .f64_histogram("gateway.overhead.duration")+ .with_unit("s")+ .with_boundaries(vec![+ 0.0001, 0.00025, 0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5,+ 1.0, 2.5, 5.0,+ ])+ .build(),+ request_size: meter+ .u64_histogram("http.server.request.body.size")+ .with_unit("By")+ .with_boundaries(bytes.clone())+ .build(),+ response_size: meter+ .u64_histogram("http.server.response.body.size")+ .with_unit("By")+ .with_boundaries(bytes)+ .build(),active: meter.i64_up_down_counter("gateway.active").build(),phases: meter.f64_histogram("gateway.phase.duration")@@ -42,27 +76,125 @@ static METRICS: LazyLock<Metrics> = LazyLock::new(|| {}});-pub(super) fn http_response(- duration: std::time::Duration,- method: String,- route: String,- status: u16,-) {+pub(super) struct HttpResponse<'a> {+ pub method: &'a str,+ pub route: &'a str,+ pub status: u16,+ pub origin: ErrorOrigin,+ pub reason: &'static str,+ pub provider: &'static str,+}++pub(super) fn http_response(duration: Duration, response: &HttpResponse<'_>) {METRICS.http_duration.record(duration.as_secs_f64(),&[- KeyValue::new("http.request.method", method),- KeyValue::new("http.route", route),- KeyValue::new("http.response.status_code", i64::from(status)),+ KeyValue::new("http.request.method", response.method.to_owned()),+ KeyValue::new("http.route", response.route.to_owned()),+ KeyValue::new("http.response.status_code", i64::from(response.status)),+ KeyValue::new("error.origin", response.origin.as_str()),+ KeyValue::new("error.reason", response.reason),+ KeyValue::new("gateway.provider", response.provider),+ ],+ );+}++pub(super) fn overhead(route: &str, provider: &'static str, duration: Duration) {+ METRICS.overhead.record(+ duration.as_secs_f64(),+ &[+ KeyValue::new("http.route", route.to_owned()),+ KeyValue::new("gateway.provider", provider),+ ],+ );+}++/// Buffered request bytes, recorded for requests whose body was read in full.+pub(super) fn request_body_size(route: &str, provider: &'static str, bytes: u64) {+ METRICS.request_size.record(+ bytes,+ &[+ KeyValue::new("http.route", route.to_owned()),+ KeyValue::new("gateway.provider", provider),],);}+/// Bytes relayed from the provider, including truncated and cancelled streams.+pub(crate) fn response_body_size(provider: &'static str, bytes: u64) {+ METRICS+ .response_size+ .record(bytes, &[KeyValue::new("gateway.provider", provider)]);+}++/// In-use, high-water, and configured slots of one admission semaphore.+struct Slots {+ phase: &'static str,+ in_use: AtomicU64,+ peak: AtomicU64,+ capacity: AtomicU64,+}++impl Slots {+ const fn new(phase: &'static str) -> Self {+ Self {+ phase,+ in_use: AtomicU64::new(0),+ peak: AtomicU64::new(0),+ capacity: AtomicU64::new(0),+ }+ }++ fn acquire(&self) {+ let in_use = self.in_use.fetch_add(1, Ordering::Relaxed) + 1;+ self.peak.fetch_max(in_use, Ordering::Relaxed);+ }++ fn release(&self) {+ self.in_use.fetch_sub(1, Ordering::Relaxed);+ }++ /// The highest in-use count since the previous read. The next interval starts+ /// from the slots still held, so a long request is not reported as idle.+ fn take_peak(&self) -> u64 {+ let peak = self+ .peak+ .swap(self.in_use.load(Ordering::Relaxed), Ordering::Relaxed);+ self.peak+ .fetch_max(self.in_use.load(Ordering::Relaxed), Ordering::Relaxed);+ peak+ }+}++static SLOTS: [Slots; 3] = [+ Slots::new("model_catalog"),+ Slots::new("resolution"),+ Slots::new("execution"),+];++fn slots(phase: &str) -> Option<&'static Slots> {+ SLOTS.iter().find(|slots| slots.phase == phase)+}++/// Report a semaphore's configured size for `gateway.admission.capacity`. The+/// gateway runs one inference service per process, so the latest value wins.+pub(crate) fn record_capacity(phase: &'static str, capacity: usize) {+ if let Some(slots) = slots(phase) {+ slots.capacity.store(+ u64::try_from(capacity).unwrap_or(u64::MAX),+ Ordering::Relaxed,+ );+ }+}+pub(crate) struct Active(&'static str);impl Active {pub(crate) fn new(phase: &'static str) -> Self {METRICS.active.add(1, &[KeyValue::new("phase", phase)]);+ if let Some(slots) = slots(phase) {+ slots.acquire();+ }Self(phase)}}@@ -70,10 +202,13 @@ impl Active {impl Drop for Active {fn drop(&mut self) {METRICS.active.add(-1, &[KeyValue::new("phase", self.0)]);+ if let Some(slots) = slots(self.0) {+ slots.release();+ }}}-pub(crate) fn phase_finished(phase: &'static str, duration: std::time::Duration) {+pub(crate) fn phase_finished(phase: &'static str, duration: Duration) {METRICS.phases.record(duration.as_secs_f64(), &[KeyValue::new("phase", phase)]);@@ -93,7 +228,7 @@ pub(crate) fn delivery(outcome: &'static str, reason: &'static str, records: u64);}-pub(crate) fn execution_finished(facts: &crate::capture::InferenceFacts) {+pub(crate) fn execution_finished(facts: &InferenceFacts) {let outcome = match facts.outcome {RelayOutcome::Eof => "complete",RelayOutcome::Cancelled => "cancelled",@@ -111,22 +246,91 @@ pub(crate) fn execution_finished(facts: &crate::capture::InferenceFacts) {);phase_finished("provider.first_byte",- std::time::Duration::from_millis(u64::try_from(first_byte_ms).unwrap_or(u64::MAX)),+ Duration::from_millis(u64::try_from(first_byte_ms).unwrap_or(u64::MAX)),);}phase_finished("execution",- std::time::Duration::from_millis(u64::try_from(facts.duration_ms).unwrap_or(u64::MAX)),+ Duration::from_millis(u64::try_from(facts.duration_ms).unwrap_or(u64::MAX)),);let context = tracing::Span::current().context();let context_span = context.span();let ids = context_span.span_context();tracing::info!(trace_id = %ids.trace_id(), span_id = %ids.span_id(), outcome, duration_ms = facts.duration_ms, "gateway execution finished");- if matches!(- facts.outcome,- RelayOutcome::Timeout | RelayOutcome::TransportError- ) {- tracing::Span::current().record("otel.status_code", "ERROR");- tracing::warn!(trace_id = %ids.trace_id(), span_id = %ids.span_id(), phase = "provider", outcome, "gateway stream failed");+}++/// Marks the server span failed when the provider body breaks after headers were+/// sent. Runs for every route, including those that capture no generation.+pub(crate) fn execution_failed(outcome: RelayOutcome) {+ if !outcome.is_failure() {+ return;+ }+ let outcome = outcome.as_str();+ let span = tracing::Span::current();+ span.record("otel.status_code", "ERROR");+ span.record("otel.status_description", outcome);+ span.record("error.type", outcome);+ span.record("error.origin", ErrorOrigin::ProviderTransport.as_str());+ let context = span.context();+ let context_span = context.span();+ let ids = context_span.span_context();+ tracing::warn!(trace_id = %ids.trace_id(), span_id = %ids.span_id(), phase = "provider", outcome, error.origin = ErrorOrigin::ProviderTransport.as_str(), "gateway stream failed");+}++/// Keeps the admission callbacks registered for the life of the meter provider.+pub(super) struct AdmissionInstruments {+ _capacity: ObservableGauge<u64>,+ _peak: ObservableGauge<u64>,+}++/// Free slots are `gateway.admission.capacity - gateway.active`. The 30-second+/// average of `gateway.active` hides bursts, so `gateway.active.peak` reports the+/// most slots held at once since the previous export.+pub(super) fn register_admission() -> AdmissionInstruments {+ let meter = global::meter("ai-gateway");+ let capacity = meter+ .u64_observable_gauge("gateway.admission.capacity")+ .with_callback(|observer| {+ for slots in &SLOTS {+ let capacity = slots.capacity.load(Ordering::Relaxed);+ if capacity > 0 {+ observer.observe(capacity, &[KeyValue::new("phase", slots.phase)]);+ }+ }+ })+ .build();+ // The SDK reads observable instruments once per collection, which is once+ // per export with the single periodic reader.+ let peak = meter+ .u64_observable_gauge("gateway.active.peak")+ .with_callback(|observer| {+ for slots in &SLOTS {+ observer.observe(slots.take_peak(), &[KeyValue::new("phase", slots.phase)]);+ }+ })+ .build();+ AdmissionInstruments {+ _capacity: capacity,+ _peak: peak,+ }+}++#[cfg(test)]+mod tests {+ use super::Slots;++ #[test]+ fn peak_reports_the_interval_burst_then_restarts_from_held_slots() {+ let slots = Slots::new("execution");+ for _ in 0..3 {+ slots.acquire();+ }+ slots.release();+ slots.release();+ assert_eq!(slots.take_peak(), 3, "a burst between exports is kept");+ assert_eq!(slots.take_peak(), 1, "a slot still held stays visible");+ slots.release();+ assert_eq!(slots.take_peak(), 1);+ assert_eq!(slots.take_peak(), 0);}}diff --git a/ai-gateway/src/observability/mod.rs b/ai-gateway/src/observability/mod.rsindex 6bae23dde1..a4189edccf 100644--- a/ai-gateway/src/observability/mod.rs+++ b/ai-gateway/src/observability/mod.rs@@ -2,10 +2,15 @@ mod client;mod http;mod logs;mod metrics;+mod request;pub(crate) use client::instrument_client;pub use http::instrument;-pub(crate) use metrics::{Active, delivery, execution_finished, rejected};+pub(crate) use metrics::{+ Active, delivery, execution_failed, execution_finished, record_capacity, rejected,+ response_body_size,+};+pub(crate) use request::{ErrorOrigin, RequestObservation, Wait, provider_status_reason};use crate::config::{GatewayConfig, LogFormat};use opentelemetry::{KeyValue, global, trace::TracerProvider};@@ -23,6 +28,7 @@ use tracing_subscriber::{EnvFilter, Layer, filter::filter_fn, prelude::*};pub struct Observability {traces: SdkTracerProvider,metrics: Option<SdkMeterProvider>,+ _admission: Option<metrics::AdmissionInstruments>,}/// Sanitized startup failures; supplied values and exporter errors are never retained.@@ -50,20 +56,7 @@ pub enum ObservabilityError {/// Returns an [`ObservabilityError`] for invalid settings, exporter construction, or an/// already installed tracing subscriber.pub fn init(config: &GatewayConfig) -> Result<Observability, ObservabilityError> {- let service = setting("OTEL_SERVICE_NAME")?.unwrap_or_else(|| "ai-gateway".into());- let resource = Resource::builder()- .with_service_name(service)- .with_attributes([- KeyValue::new(- "deployment.environment.name",- setting("DD_ENV")?.unwrap_or_else(|| "development".into()),- ),- KeyValue::new(- "service.version",- setting("BUILD_ID")?.unwrap_or_else(|| env!("CARGO_PKG_VERSION").into()),- ),- ])- .build();+ let resource = resource()?;let ratio = sampling_ratio(setting("OTEL_TRACES_SAMPLER_ARG")?.as_deref())?;let mut traces = SdkTracerProvider::builder().with_resource(resource.clone())@@ -114,9 +107,10 @@ pub fn init(config: &GatewayConfig) -> Result<Observability, ObservabilityError>};let traces = traces.build();global::set_text_map_propagator(TraceContextPropagator::new());- if let Some(metrics) = &metrics {- global::set_meter_provider(metrics.clone());- }+ let admission = metrics.as_ref().map(|provider| {+ global::set_meter_provider(provider.clone());+ metrics::register_admission()+ });let log_filter = EnvFilter::try_new(format!("warn,ai_gateway={}", config.log_level)).map_err(|_| ObservabilityError::LogFilter)?;let logger = match config.log_format {@@ -147,7 +141,46 @@ pub fn init(config: &GatewayConfig) -> Result<Observability, ObservabilityError>.with(logs::CorrelationSpans).try_init().map_err(|_| ObservabilityError::Logging)?;- Ok(Observability { traces, metrics })+ log_panics();+ Ok(Observability {+ traces,+ metrics,+ _admission: admission,+ })+}++fn resource() -> Result<Resource, ObservabilityError> {+ let service = setting("OTEL_SERVICE_NAME")?.unwrap_or_else(|| "ai-gateway".into());+ Ok(Resource::builder()+ .with_service_name(service)+ .with_attributes([+ KeyValue::new(+ "deployment.environment.name",+ setting("DD_ENV")?.unwrap_or_else(|| "development".into()),+ ),+ KeyValue::new(+ "service.version",+ setting("BUILD_ID")?.unwrap_or_else(|| env!("CARGO_PKG_VERSION").into()),+ ),+ ])+ .build())+}++/// A panicking request task drops its connection without a response, metric, or+/// log. Report the location only: panic payloads can carry request data.+fn log_panics() {+ let previous = std::panic::take_hook();+ std::panic::set_hook(Box::new(move |info| {+ let location = info+ .location()+ .map(|location| format!("{}:{}", location.file(), location.line()));+ tracing::error!(+ location = location.as_deref().unwrap_or("unknown"),+ error.origin = ErrorOrigin::Gateway.as_str(),+ "gateway panicked"+ );+ previous(info);+ }));}impl Observability {diff --git a/ai-gateway/src/observability/request.rs b/ai-gateway/src/observability/request.rsnew file mode 100644index 0000000000..3bcb7c3462--- /dev/null+++ b/ai-gateway/src/observability/request.rs@@ -0,0 +1,124 @@+//! Per-request facts shared between the HTTP middleware and the request handler, so+//! the response metric can name who caused an error and how much of the wait was+//! the gateway's own work.+use std::{+ sync::{Arc, Mutex, PoisonError},+ time::Duration,+};++/// Who caused a failed response. `none` marks a success. Dashboards fold+/// `provider` responses with `error.reason=provider_4xx` into caller errors.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum ErrorOrigin {+ None,+ /// The caller's request or credential was rejected.+ Client,+ /// The gateway itself: capacity, draining, configuration, or a bug.+ Gateway,+ /// Web resolution or the model catalog failed.+ ControlPlane,+ /// The provider was unreachable or missed a deadline.+ ProviderTransport,+ /// The provider answered with an error status, relayed unchanged.+ Provider,+}++impl ErrorOrigin {+ pub(crate) fn as_str(self) -> &'static str {+ match self {+ Self::None => "none",+ Self::Client => "client",+ Self::Gateway => "gateway",+ Self::ControlPlane => "control_plane",+ Self::ProviderTransport => "provider_transport",+ Self::Provider => "provider",+ }+ }++ /// Errors attributed to Langfuse rather than the caller or the provider.+ pub(crate) fn is_ours(self) -> bool {+ matches!(self, Self::Gateway | Self::ControlPlane)+ }+}++/// Bounded `error.reason` for a provider error status relayed to the caller.+/// Provider 401/403 usually means the stored provider credential is broken, so+/// it is kept apart from other 4xx rather than counted as a caller error.+pub(crate) fn provider_status_reason(status: u16) -> &'static str {+ match status {+ 429 => "provider_rate_limited",+ 401 | 403 => "provider_auth",+ 400..=499 => "provider_4xx",+ _ => "provider_5xx",+ }+}++/// Time spent waiting on the caller or the provider, which is never gateway overhead.+#[derive(Clone, Copy)]+pub(crate) enum Wait {+ /// Buffering the caller's upload.+ RequestBody,+ /// The provider send through response headers.+ ProviderHeaders,+}++#[derive(Debug, Default)]+struct State {+ error: Option<(ErrorOrigin, &'static str)>,+ provider: Option<&'static str>,+ request_body: Option<Duration>,+ provider_headers: Option<Duration>,+ request_bytes: Option<u64>,+}++/// Cheap to clone; the middleware and the handler hold the same state.+#[derive(Clone, Debug, Default)]+pub(crate) struct RequestObservation(Arc<Mutex<State>>);++pub(super) struct Summary {+ pub error: Option<(ErrorOrigin, &'static str)>,+ pub provider: &'static str,+ pub request_body: Option<Duration>,+ pub provider_headers: Option<Duration>,+ pub request_bytes: Option<u64>,+}++impl RequestObservation {+ fn with_state<R>(&self, update: impl FnOnce(&mut State) -> R) -> R {+ update(&mut self.0.lock().unwrap_or_else(PoisonError::into_inner))+ }++ /// The first recorded error wins: it is the one closest to the cause.+ pub(crate) fn record_error(&self, origin: ErrorOrigin, reason: &'static str) {+ self.with_state(|state| {+ state.error.get_or_insert((origin, reason));+ });+ }++ pub(crate) fn record_provider(&self, provider: &'static str) {+ self.with_state(|state| state.provider = Some(provider));+ }++ pub(crate) fn record_wait(&self, wait: Wait, duration: Duration) {+ self.with_state(|state| match wait {+ Wait::RequestBody => state.request_body = Some(duration),+ Wait::ProviderHeaders => state.provider_headers = Some(duration),+ });+ }++ pub(crate) fn record_request_bytes(&self, bytes: usize) {+ self.with_state(|state| {+ state.request_bytes = Some(u64::try_from(bytes).unwrap_or(u64::MAX));+ });+ }++ pub(super) fn summary(&self) -> Summary {+ self.with_state(|state| Summary {+ error: state.error,+ provider: state.provider.unwrap_or("none"),+ request_body: state.request_body,+ provider_headers: state.provider_headers,+ request_bytes: state.request_bytes,+ })+ }+}diff --git a/ai-gateway/src/providers/mod.rs b/ai-gateway/src/providers/mod.rsindex 4b1aa145c8..a8cdbf9f11 100644--- a/ai-gateway/src/providers/mod.rs+++ b/ai-gateway/src/providers/mod.rs@@ -5,7 +5,7 @@ use std::{ops::Range, sync::Arc, time::Duration};use axum::{body::{Body, Bytes},- http::{HeaderMap, HeaderName, HeaderValue, Response, header},+ http::{HeaderMap, HeaderName, HeaderValue, Response, StatusCode, header},};use reqwest::Client;use reqwest_middleware::ClientWithMiddleware;@@ -20,6 +20,7 @@ use crate::{capture::{ExecutionCapture, RelayOutcome},config::ExecutionLimits,correlation::{RequestCorrelation, UpstreamTarget},+ observability::{ErrorOrigin, RequestObservation, Wait, provider_status_reason},resolution::{ApiFormat, Provider, ProviderCredential, ResolvedRequestContext},transport,};@@ -145,6 +146,7 @@ impl ProviderTransport {.pool_max_idle_per_host(16).build().map_err(|_| ProviderError::Configuration)?;+ crate::observability::record_capacity("execution", limits.active);Ok(Self {client: crate::observability::instrument_client(client, "provider.headers"),capacity: Arc::new(Semaphore::new(limits.active)),@@ -256,6 +258,7 @@ impl ProviderTransport {.header(header::ACCEPT_ENCODING, "identity").header(credential_name, credential);upstream = upstream.body(body);+ let started = Instant::now();// A stream, or a call that does not generate, that goes quiet before its// headers is stalled. A non-streamed generation sends nothing until the whole// response is generated.@@ -278,6 +281,8 @@ impl ProviderTransport {}})});+ let observation = correlation.observation();+ observation.record_wait(Wait::ProviderHeaders, started.elapsed());let response = match response {Ok(response) => response,Err(error) => {@@ -292,12 +297,15 @@ impl ProviderTransport {if let Some(request_id) = transport::provider_request_id(response.headers(), api_format) {tracing::Span::current().record("provider_request_id", request_id);}- capture.record_response(response.status().as_u16(), response.headers());+ let status = response.status();+ capture.record_response(status.as_u16(), response.headers());+ record_provider_status(observation, status);let mut downstream = Response::new(Body::empty());- *downstream.status_mut() = response.status();+ *downstream.status_mut() = status;*downstream.headers_mut() = transport::response_headers(response.headers(), api_format);*downstream.body_mut() = transport::relay(response,+ api_format.provider().as_str(),permit.deadline,self.limits.execution.stall_timeout,(permit, context, reservation),@@ -326,6 +334,29 @@ impl ProviderTransport {}}+/// Provider error statuses are relayed unchanged, so the handler's rejection log+/// and error classification never see them.+fn record_provider_status(observation: &RequestObservation, status: StatusCode) {+ if !(status.is_client_error() || status.is_server_error()) {+ return;+ }+ let reason = provider_status_reason(status.as_u16());+ observation.record_error(ErrorOrigin::Provider, reason);+ if status.is_server_error() {+ tracing::warn!(+ reason,+ status = status.as_u16(),+ "provider returned an error status"+ );+ } else {+ tracing::info!(+ reason,+ status = status.as_u16(),+ "provider returned an error status"+ );+ }+}+#[expect(clippy::needless_pass_by_value,reason = "ownership releases the caller body when rewriting returns, before the upstream wait"diff --git a/ai-gateway/src/resolution/contracts.rs b/ai-gateway/src/resolution/contracts.rsindex d40f677a99..9b16879d8d 100644--- a/ai-gateway/src/resolution/contracts.rs+++ b/ai-gateway/src/resolution/contracts.rs@@ -25,6 +25,13 @@ impl ApiFormat {Self::AnthropicMessages => "anthropic.messages",}}++ pub fn provider(self) -> Provider {+ match self {+ Self::OpenAiResponses | Self::OpenAiChatCompletions => Provider::OpenAi,+ Self::AnthropicMessages => Provider::Anthropic,+ }+ }}#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]diff --git a/ai-gateway/src/resolution/mod.rs b/ai-gateway/src/resolution/mod.rsindex 80963f03c9..9659b46cb2 100644--- a/ai-gateway/src/resolution/mod.rs+++ b/ai-gateway/src/resolution/mod.rs@@ -256,6 +256,14 @@ async fn read_response(match response.status().as_u16() {200 => {}400 => return Err(ResolutionError::InvalidRequest),+ // Web rejected the gateway's own signature: a service-key mismatch, not the caller.+ 401 if response+ .headers()+ .get(ERROR_CODE_HEADER)+ .is_some_and(|value| value == "invalid_gateway_authorization") =>+ {+ return Err(ResolutionError::Configuration);+ }401 => return Err(ResolutionError::Authentication),403 if response.headers()@@ -310,6 +318,9 @@ pub enum ResolutionError {ModelNotAllowed,#[error("no eligible connection")]NoRoute,+ /// The gateway's own resolution or catalog capacity is exhausted.+ #[error("gateway at capacity")]+ Busy,#[error("resolution unavailable")]Unavailable,#[error("resolution deadline exceeded")]diff --git a/ai-gateway/src/resolution/tests.rs b/ai-gateway/src/resolution/tests.rsindex 3d22a4c227..e9dc39250e 100644--- a/ai-gateway/src/resolution/tests.rs+++ b/ai-gateway/src/resolution/tests.rs@@ -303,6 +303,37 @@ async fn model_policy_rejections_are_distinct_from_other_forbidden_responses() {assert!(!format!("{error:?} {error}").contains("private-upstream-error"));}+/// A rejected gateway signature means the service keys disagree, which is the+/// gateway's fault, not the caller's.+#[tokio::test]+async fn rejected_gateway_signatures_are_configuration_errors() {+ let web = FakeWeb::start(|_| async {+ Response::builder()+ .status(StatusCode::UNAUTHORIZED)+ .header(+ "langfuse-gateway-error-code",+ "invalid_gateway_authorization",+ )+ .body(Body::empty())+ .unwrap()+ })+ .await;++ let error = web+ .control_plane()+ .resolve_at(+ GATEWAY_KEY,+ ApiFormat::OpenAiResponses,+ "primary:gpt-4.1",+ NOW_TIME,+ REQUEST_ID,+ )+ .await+ .unwrap_err();++ assert!(matches!(error, ResolutionError::Configuration));+}+#[tokio::test]async fn never_follows_redirects_with_credentials() {let destination =diff --git a/ai-gateway/src/telemetry/worker.rs b/ai-gateway/src/telemetry/worker.rsindex 753bf6465b..ef2dc65339 100644--- a/ai-gateway/src/telemetry/worker.rs+++ b/ai-gateway/src/telemetry/worker.rs@@ -94,7 +94,9 @@ impl Uploads {"telemetry.batch",otel.kind = "internal",gateway.telemetry.records = i64::try_from(flush.items.len()).unwrap_or(i64::MAX),- gateway.telemetry.attempts = tracing::field::Empty+ gateway.telemetry.attempts = tracing::field::Empty,+ otel.status_code = tracing::field::Empty,+ error.type = tracing::field::Empty);for item in &flush.items {if item.link.is_valid() {@@ -188,6 +190,9 @@ impl Receipt {fn settle_failed(mut self, reason: &'static str) {self.settled = true;+ let current = tracing::Span::current();+ current.record("otel.status_code", "ERROR");+ current.record("error.type", reason);if self.stats.record_failed(self.records, reason) {let context = tracing::Span::current().context();let span = context.span();diff --git a/ai-gateway/src/transport/mod.rs b/ai-gateway/src/transport/mod.rsindex 0fbd5cc235..c243839656 100644--- a/ai-gateway/src/transport/mod.rs+++ b/ai-gateway/src/transport/mod.rs@@ -142,6 +142,7 @@ pub(crate) fn identity_encoding(headers: &HeaderMap) -> bool {pub(crate) fn relay<T: Send + 'static>(upstream: reqwest::Response,+ provider: &'static str,deadline: Instant,stall_timeout: Duration,owner: T,@@ -157,6 +158,7 @@ pub(crate) fn relay<T: Send + 'static>(}})}),+ provider,deadline,stall_timeout,owner,@@ -168,6 +170,7 @@ pub(crate) fn relay<T: Send + 'static>(/// in either direction: no upstream chunk, or a downstream that stopped reading.fn relay_stream<S, T>(upstream: S,+ provider: &'static str,deadline: Instant,stall_timeout: Duration,owner: T,@@ -184,12 +187,14 @@ where"provider.stream",otel.kind = "internal",otel.status_code = tracing::field::Empty,+ error.type = tracing::field::Empty,http.response.body.size = tracing::field::Empty,gateway.chunks = tracing::field::Empty,gateway.outcome = tracing::field::Empty,);let resources = Arc::new(StreamResources {relay: Mutex::new(Some(Relay {+ provider,owner,capture,span,@@ -264,6 +269,7 @@ where/// Everything the winning finalizer releases at once: admission and trusted/// context, the capture, and the stream span, which ends when it is dropped here.struct Relay<T> {+ provider: &'static str,owner: T,capture: Option<ExecutionCapture>,span: tracing::Span,@@ -289,23 +295,23 @@ impl<T> StreamResources<T> {let taken = relay.take();// Only the winning finalizer publishes the body failure. In// particular, a deadline racing downstream EOF cannot change it later.- if taken.is_some()- && matches!(- outcome,- RelayOutcome::Timeout | RelayOutcome::TransportError- )- {+ if taken.is_some() && outcome.is_failure() {self.failed.store(true, Ordering::Release);}(taken, outcome)};if let Some(Relay {+ provider,owner,capture,span,}) = relay{self.record_outcome(&span, outcome);+ crate::observability::response_body_size(+ provider,+ u64::try_from(self.bytes.load(Ordering::Relaxed)).unwrap_or(u64::MAX),+ );drop(span);drop(owner);if let Some(mut capture) = capture {@@ -323,11 +329,9 @@ impl<T> StreamResources<T> {);span.record("gateway.chunks", count(self.chunks.load(Ordering::Relaxed)));span.record("gateway.outcome", outcome.as_str());- if matches!(- outcome,- RelayOutcome::Timeout | RelayOutcome::TransportError- ) {+ if outcome.is_failure() {span.record("otel.status_code", "ERROR");+ span.record("error.type", outcome.as_str());}}@@ -400,6 +404,7 @@ mod tests {for first in [RelayOutcome::Eof, RelayOutcome::Timeout] {let resources = StreamResources {relay: Mutex::new(Some(Relay {+ provider: "test",owner: (),capture: None,span: tracing::Span::none(),@@ -425,6 +430,7 @@ mod tests {fn a_panic_while_updating_the_capture_fails_the_relay() {let resources = StreamResources {relay: Mutex::new(Some(Relay {+ provider: "test",owner: (),capture: None,span: tracing::Span::none(),@@ -472,6 +478,7 @@ mod tests {Ok(Bytes::from_static(b"partial")),Err(ProviderError::Transport),]),+ "test",Instant::now() + Duration::from_secs(1),Duration::from_secs(10),Owner(released.clone()),@@ -513,6 +520,7 @@ mod tests {let released = Arc::new(Notify::new());let body = relay_stream(upstream,+ "test",Instant::now() + Duration::from_secs(10),Duration::from_secs(10),Owner(released.clone()),@@ -532,6 +540,7 @@ mod tests {let bytes = Bytes::from_static(b"event: response.output_text.delta\ndata: hello\n\n");let body = relay_stream(stream::iter([Ok(bytes.clone()), Err(ProviderError::Transport)]),+ "test",Instant::now() + Duration::from_secs(1),Duration::from_secs(10),Owner(released.clone()),@@ -552,6 +561,7 @@ mod tests {let released = Arc::new(Notify::new());let body = relay_stream(stream::once(async { Ok(Bytes::from_static(b"final bytes")) }),+ "test",Instant::now() + Duration::from_millis(30),Duration::from_secs(10),Owner(released.clone()),@@ -569,6 +579,7 @@ mod tests {let started = Instant::now();let body = relay_stream(stream::once(async { Ok(Bytes::from_static(b"first")) }).chain(stream::pending()),+ "test",started + Duration::from_secs(3600),Duration::from_secs(120),Owner(released.clone()),@@ -593,6 +604,7 @@ mod tests {});let _body = relay_stream(upstream,+ "test",started + Duration::from_secs(3600),Duration::from_secs(120),Owner(released.clone()),diff --git a/ai-gateway/tests/observability.rs b/ai-gateway/tests/observability.rsindex eb35182887..233249f876 100644--- a/ai-gateway/tests/observability.rs+++ b/ai-gateway/tests/observability.rs@@ -355,7 +355,19 @@ fn assert_http_metrics(metrics: &[ResourceMetrics]) {)}).collect();- assert_eq!(attributes.len(), 3);+ assert_eq!(attributes.len(), 6);+ // An unconfigured gateway answers 503 itself; dashboards must not blame Web or the provider.+ for (key, value) in [+ ("error.origin", "gateway"),+ ("error.reason", "unavailable"),+ ("gateway.provider", "openai"),+ ] {+ assert_eq!(+ attributes[key],+ &AttributeValue::StringValue(value.into()),+ "{key}"+ );+ }assert_eq!(attributes["http.request.method"],&AttributeValue::StringValue("POST".into())diff --git a/web/src/features/ai-gateway/server/auth/gatewayRequestSignatureVerifier.servertest.ts b/web/src/features/ai-gateway/server/auth/gatewayRequestSignatureVerifier.servertest.tsindex 4727ab68ff..00ae671487 100644--- a/web/src/features/ai-gateway/server/auth/gatewayRequestSignatureVerifier.servertest.ts+++ b/web/src/features/ai-gateway/server/auth/gatewayRequestSignatureVerifier.servertest.ts@@ -209,6 +209,10 @@ describe("withGatewayResolveSignatureVerification", () => {);expect(res.status).toHaveBeenCalledWith(401);+ expect(res.setHeader).toHaveBeenCalledWith(+ "langfuse-gateway-error-code",+ "invalid_gateway_authorization",+ );expect(handler).not.toHaveBeenCalled();});diff --git a/web/src/features/ai-gateway/server/auth/gatewayRequestSignatureVerifier.ts b/web/src/features/ai-gateway/server/auth/gatewayRequestSignatureVerifier.tsindex c1f764ca90..854b1740c6 100644--- a/web/src/features/ai-gateway/server/auth/gatewayRequestSignatureVerifier.ts+++ b/web/src/features/ai-gateway/server/auth/gatewayRequestSignatureVerifier.ts@@ -78,7 +78,12 @@ function verifyGatewayRequestSignatureAndHashApiKey(input: {serviceKeys,)) {- throw new GatewayControlPlaneError("Invalid gateway authorization", 401);+ // Coded so the gateway can tell a service-key mismatch from a rejected caller key.+ throw new GatewayControlPlaneError(+ "Invalid gateway authorization",+ 401,+ "invalid_gateway_authorization",+ );}return createShaHash(input.virtualSecretKey, env.SALT);@@ -156,6 +161,9 @@ export function withGatewayModelsSignatureVerification(});} catch (error) {if (error instanceof GatewayControlPlaneError) {+ if (error.code) {+ res.setHeader("langfuse-gateway-error-code", error.code);+ }return res.status(error.status).json({ error: error.message });}return res.status(500).json({ error: "Internal server error" });@@ -214,6 +222,9 @@ function withGatewayControlPlaneAuth<);} catch (error) {if (error instanceof GatewayControlPlaneError) {+ if (error.code) {+ res.setHeader("langfuse-gateway-error-code", error.code);+ }return res.status(error.status).json({ error: error.message });}return res.status(500).json({ error: "Internal server error" });diff --git a/web/src/features/ai-gateway/server/gatewayControlPlaneError.ts b/web/src/features/ai-gateway/server/gatewayControlPlaneError.tsindex 9aa19357aa..abf519c54c 100644--- a/web/src/features/ai-gateway/server/gatewayControlPlaneError.ts+++ b/web/src/features/ai-gateway/server/gatewayControlPlaneError.ts@@ -2,7 +2,7 @@ export class GatewayControlPlaneError extends Error {constructor(message: string,readonly status: 400 | 401 | 403 | 404 | 503,- readonly code?: "model_not_allowed",+ readonly code?: "model_not_allowed" | "invalid_gateway_authorization",) {super(message);}