From 4695d846a7640327552752cc92e5bb3782dc0598 Mon Sep 17 00:00:00 2001 From: Joshua Cartu Date: Wed, 2 Dec 2026 20:55:34 +0100 Subject: [PATCH] helios/server: preserve typed error codes on HTTP request preparation failures In the Helios HTTP generation handler (`helios/src/server/http.rs`), request preparation runs on a blocking worker before scheduler admission. Previously, the preparation closure returned `Result<_, (StatusCode, String)>`, flattening typed `Error::Admission` failures from protocol decoding (`protocol::decode`), custom tool grammar compilation (`GrammarCompiler::compile_text`), strict tool schema validation (`request::compile_strict_validators`), and inference preparation (`request::prepare_validated_inference`, via `rejection_details`) into plain `(StatusCode, String)` pairs. The handler then rendered those pairs through `http::error` and `Protocol::error`, which always sets `error.code` to the status-derived category (`"invalid_request_error"` for HTTP 400) rather than the typed code returned by `error_code(&error)`. Preserving typed `Error::Admission` variants across the `spawn_blocking` boundary and rendering them through the same `Protocol::failure` plus `rejection_details` path used by `rejection` aligns preparation rejections with post-admission rejections, while keeping `AdmissionError::Invalid` on the `http::error` path so general invalid-request 400s uniformly emit `"invalid_request_error"`. Before this change, `http::generate` converted all errors inside its `spawn_blocking` task into `(StatusCode, String)` and returned `http::error(protocol, status, message)`. In `prepare_validated_inference`, non-`Admission` errors were previously wrapped into `AdmissionError::Invalid` solely so `rejection_details` would compute HTTP 400 (hints apply only to `Context` and `Capacity`), and then flattened by `http::error` to `"invalid_request_error"`. With this change: - Added `PreparationError` (`Http(StatusCode, String)` and `Failure(Error)`) and `preparation_error(Error) -> PreparationError` in `helios/src/server/http.rs`. `Error::Admission(AdmissionError::Invalid(_))` and non-`Admission` errors map to `PreparationError::Http(StatusCode::BAD_REQUEST, message)`, keeping general 400 validation errors uniformly on `"invalid_request_error"`. All other `Error::Admission(_)` variants (`Context`, `Feature`, `Grammar`, `Image`, `Capacity`, `Unavailable`) remain intact as `PreparationError::Failure`. - Extracted `failure_response(&HttpState, Protocol, Error) -> Response` from `rejection` so both typed preparation failures and post-submission rejections render via `Protocol::failure(&failure)` and apply `rejection_details` (`status(&failure)` and `context_hint` / `capacity_hint` message suffixes), while only post-submission `rejection` attaches `x-request-id` and writes `failure_log`. - Updated `http::generate` to route `protocol::decode`, `GrammarCompiler::compile_text`, `Request::generation_count`, `request::compile_strict_validators`, and `request::prepare_validated_inference` through `preparation_error`, dispatching `PreparationError::Failure` to `failure_response` and `PreparationError::Http` to `http::error`. - Documented the typed HTTP 400 `error.code` values (`context_length_exceeded`, `unsupported_feature`, `invalid_grammar`, `invalid_image`) for Chat Completions, Completions, and Responses in `docs/api.md`. - Added unit test `preparation_error_preserves_typed_admission_errors_and_keeps_untyped_bad_requests` in `helios/src/server/http.rs` and HTTP-wire test `http_preparation_failures_preserve_typed_error_codes_and_protocol_envelopes` in `helios/src/server/runtime/phase_tests.rs`. Resulting behavior: Typed request-preparation failures on Chat Completions (`/v1/chat/completions`), Completions (`/v1/completions`), and Responses (`/v1/responses`) return their typed `error.code` (`context_length_exceeded`, `unsupported_feature`, `invalid_grammar`, `invalid_image`), `error.type` (`invalid_request_error`), explicit `error.param: null`, and `status(&error)` with `context_hint` / `capacity_hint` preserved in `error.message` for both `stream: false` and `stream: true` requests. Anthropic Messages (`/v1/messages` and `/v1/messages/count_tokens`) keeps its `{"type": "error", "error": {"type", "message"}}` envelope without `code` or `param` fields and preserves `context_hint`. General HTTP validation errors (invalid JSON, missing required fields, `AdmissionError::Invalid` such as more than four stop sequences, untyped preparation checks such as `max_tokens: 0`, unsupported `Content-Encoding`, and oversized bodies) retain their HTTP status and `invalid_request_error` or `request_too_large` codes. Evidence and limitations: - `cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server` (with prepared template fixtures supplied via `FLARE_TEST_TEMPLATE_DIR`): 1,880 passed, 0 failed, 84 ignored (1,818 passed, 47 ignored in `flare-helios --lib`; 62 passed, 37 ignored across integration test targets; ignored tests require GPU hardware or local checkpoint snapshots). The unit test verifies `preparation_error` across `Context`, `Feature`, `Grammar`, `Image`, `Capacity`, `Unavailable`, `Invalid`, and untyped errors; the HTTP-wire test exercises `http::generate` end-to-end across all four protocols and `/v1/messages/count_tokens` for `context_length_exceeded`, `unsupported_feature`, `invalid_grammar` (output schema, strict tool schema, and custom tool grammar paths), `invalid_image`, general 400 validation (`stop` count > 4 and `max_tokens: 0`), and HTTP 400/413/415 rejections while asserting explicit `param: null` presence, absent `x-request-id`, and zero model-queue admissions. - `cargo test --locked --release --manifest-path flare/Cargo.toml`: 254 passed, 0 failed, 4 ignored (246 passed, 4 ignored in `flare --lib`; 7 passed in `packed_canonical_download`; 1 passed in `reference_workflows`). - `cargo test --locked --release --manifest-path flare-cli/Cargo.toml`: 245 passed, 0 failed, 3 ignored (219 passed, 3 ignored in `flare-cli --bin`; 9 passed in `cache_commands`; 6 passed in `cli`; 4 passed in `inspect`; 7 passed in `unverified_payload`). - Live GPU serving and the Python server integration tests (`tests/server/test_protocols.py`) were not run because no GPU serving instance was executed in this environment. Signed-off-by: Joshua Cartu Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=2e5b --- docs/api.md | 9 +- helios/src/server/http.rs | 130 +++++++-- helios/src/server/runtime/phase_tests.rs | 327 +++++++++++++++++++++++ 3 files changed, 440 insertions(+), 26 deletions(-) diff --git a/docs/api.md b/docs/api.md index 2942b388e..6a3c8b466 100644 --- a/docs/api.md +++ b/docs/api.md @@ -254,9 +254,12 @@ over `max_body_bytes` returns 413 (`request_too_large`); an unknown `Content-Encoding` returns 415; exhausted HTTP admission slots return 429 (`rate_limit_error`); and a full model request queue, paused admission, or an unavailable runtime return 503. Execution and output-validation failures -return 500. 5xx errors use `server_error`, or `api_error` on Messages. -Responses for requests that reach model submission carry an `x-request-id` -header. +return 500. 5xx errors use `server_error`, or `api_error` on Messages. On Chat +Completions, Completions, and Responses, typed HTTP 400 rejections set +`error.code` to `context_length_exceeded`, `unsupported_feature`, +`invalid_grammar`, or `invalid_image` while keeping `error.type` as +`invalid_request_error`. Responses for requests that reach model submission +carry an `x-request-id` header. Streaming requests return HTTP 200 and SSE headers after frontend validation and bounded enqueue, without waiting for GPU admission or prefill. Admission failures diff --git a/helios/src/server/http.rs b/helios/src/server/http.rs index 5a9e3bf16..75946b8c1 100644 --- a/helios/src/server/http.rs +++ b/helios/src/server/http.rs @@ -23,6 +23,12 @@ pub(super) async fn no_websocket() -> Response { "GET /v1/responses and WebSocket transport are not supported; use POST /v1/responses with HTTP JSON or SSE", ) } +fn failure_response(state: &HttpState, protocol: Protocol, failure: Error) -> Response { + let mut body = protocol.failure(&failure); + let (status, message) = rejection_details(state, failure); + body["error"]["message"] = message.into(); + (status, Json(body)).into_response() +} fn rejection( state: &HttpState, protocol: Protocol, @@ -31,10 +37,7 @@ fn rejection( failure: Error, ) -> Response { if state.log_to_stderr { log_failure(id, stage, &failure); } - let mut body = protocol.failure(&failure); - let (status, message) = rejection_details(state, failure); - body["error"]["message"] = message.into(); - with_request_id((status, Json(body)).into_response(), id) + with_request_id(failure_response(state, protocol, failure), id) } fn with_request_id(mut response: Response, id: &str) -> Response { response @@ -113,6 +116,21 @@ pub(super) fn decode_body( ) }) } +enum PreparationError { + Http(StatusCode, String), + Failure(Error), +} + +fn preparation_error(error: Error) -> PreparationError { + match error { + Error::Admission(AdmissionError::Invalid(_)) => { + PreparationError::Http(StatusCode::BAD_REQUEST, error.to_string()) + } + Error::Admission(_) => PreparationError::Failure(error), + other => PreparationError::Http(StatusCode::BAD_REQUEST, other.to_string()), + } +} + enum Delivery { Frame(Frame), Complete(Value), @@ -191,9 +209,9 @@ pub(super) async fn generate( let preparation = tokio::task::spawn_blocking(move || { let _permit = permit; let _ingress = preparation_ingress; - let body = decode_body(&bytes, &encoding, prepare_state.max_body_bytes)?; - let mut decoded = protocol::decode(protocol, body, count) - .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?; + let body = decode_body(&bytes, &encoding, prepare_state.max_body_bytes) + .map_err(|(status, message)| PreparationError::Http(status, message))?; + let mut decoded = protocol::decode(protocol, body, count).map_err(preparation_error)?; if protocol != Protocol::Completions { decoded.request.options.thinking_budget = decoded.request.options.thinking_budget.or(prepare_state @@ -210,16 +228,16 @@ pub(super) async fn generate( .grammar .compile_text(&grammar.syntax, &grammar.source) .map(|compiled| (tool.native_name(), compiled)) - .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string())) + .map_err(preparation_error) }) }) .collect::, _>>()?; let size = decoded .request .generation_count() - .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?; + .map_err(preparation_error)?; if size > prepare_state.ingress_capacity { - return Err(( + return Err(PreparationError::Http( StatusCode::BAD_REQUEST, format!( "generation group of {size} exceeds capacity {}", @@ -234,7 +252,7 @@ pub(super) async fn generate( .clone() .try_acquire_many_owned((size - 1) as u32) .map_err(|_| { - ( + PreparationError::Http( StatusCode::TOO_MANY_REQUESTS, "native generation admission is full".into(), ) @@ -243,8 +261,9 @@ pub(super) async fn generate( } else { None }; - let strict_validators = request::compile_strict_validators(&prepare_state.grammar, &decoded.request) - .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?; + let strict_validators = + request::compile_strict_validators(&prepare_state.grammar, &decoded.request) + .map_err(preparation_error)?; let mut prepared = Vec::with_capacity(size); for index in 0..size { prepared.push( @@ -258,15 +277,7 @@ pub(super) async fn generate( count, prepare_state.model.input_store(), ) - .map_err(|e| { - rejection_details( - &prepare_state, - match e { - Error::Admission(_) => e, - _ => e.admission_context(AdmissionError::Invalid), - }, - ) - })?, + .map_err(preparation_error)?, ); } Ok((decoded, prepared, extra, tool_grammars, strict_validators)) @@ -274,7 +285,10 @@ pub(super) async fn generate( .await; let (decoded, prepared, extra, tool_grammars, strict_validators) = match preparation { Ok(Ok(v)) => v, - Ok(Err((status, message))) => return error(protocol, status, message), + Ok(Err(PreparationError::Http(status, message))) => return error(protocol, status, message), + Ok(Err(PreparationError::Failure(failure))) => { + return failure_response(&state, protocol, failure); + } Err(e) => return error(protocol, StatusCode::INTERNAL_SERVER_ERROR, e), }; if count { @@ -721,4 +735,74 @@ mod tests { }) ); } + + #[test] + fn preparation_error_preserves_typed_admission_errors_and_keeps_untyped_bad_requests() { + for (input, expected_code, expected_status) in [ + ( + Error::admission(AdmissionError::Context, "prompt too long"), + "context_length_exceeded", + StatusCode::BAD_REQUEST, + ), + ( + Error::admission(AdmissionError::Feature, "unsupported"), + "unsupported_feature", + StatusCode::BAD_REQUEST, + ), + ( + Error::admission(AdmissionError::Grammar, "bad grammar"), + "invalid_grammar", + StatusCode::BAD_REQUEST, + ), + ( + Error::admission(AdmissionError::Image, "bad image"), + "invalid_image", + StatusCode::BAD_REQUEST, + ), + ( + Error::admission(AdmissionError::Capacity, "capacity full"), + "capacity_exhausted", + StatusCode::SERVICE_UNAVAILABLE, + ), + ( + Error::admission(AdmissionError::Unavailable, "runtime paused"), + "server_unavailable", + StatusCode::SERVICE_UNAVAILABLE, + ), + ] { + match preparation_error(input) { + PreparationError::Failure(failure) => { + assert_eq!(error_code(&failure), expected_code); + assert_eq!(status(&failure), expected_status); + } + PreparationError::Http(status, message) => { + panic!( + "expected typed failure for {expected_code}, got HTTP {status}: {message}" + ); + } + } + } + for (input, expected_message) in [ + ( + Error::admission(AdmissionError::Invalid, "bad stop"), + "bad stop", + ), + ( + Error::from("messages must be an array"), + "messages must be an array", + ), + ] { + match preparation_error(input) { + PreparationError::Http(status, message) => { + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(message, expected_message); + let body = Protocol::Chat.error(status, &message); + assert_eq!(body["error"]["code"], "invalid_request_error"); + } + PreparationError::Failure(failure) => { + panic!("expected HTTP 400 invalid_request_error, got typed failure: {failure}"); + } + } + } + } } diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 703c0a8a2..de6996b65 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -8434,3 +8434,330 @@ fn forced_reasoning_close_readmission_anchors_first_output_wait_with_and_without assert_eq!(readmitted_acc.arrival_ns, arrival_ns); assert_eq!(readmitted_acc.first_output_wait_ns, carried_last_output); } + +#[tokio::test] +async fn http_preparation_failures_preserve_typed_error_codes_and_protocol_envelopes() { + use crate::frontend::images::{ImageLimits, ImageProcessor, ImageSettings}; + use axum::http::StatusCode; + use serde_json::{Value, json}; + + let make_state = |with_images: bool, context_hint: &str| { + let mut fixture = Fixture::with_template( + b"{% mark %}{% for m in messages %}{% if m.content is string %}{{ m.content }}{% else %}{% for p in m.content %}{% if p.type == 'text' %}{{ p.text }}{% else %}a{% endif %}{% endfor %}{% endif %}{% endfor %}", + &[""], + &[], + ); + fixture.config.limits.max_sequence_tokens = 8; + let (sender, receiver) = mpsc::sync_channel(4); + let mut state = http_state_for(fixture, sender, None, &[]); + { + let s = Arc::get_mut(&mut state).unwrap(); + s.images = with_images.then(|| { + Arc::new( + ImageProcessor::load(ImageSettings::Deepseek4 {}, ImageLimits::default()) + .unwrap(), + ) + }); + s.max_body_bytes = 4096; + s.context_hint = context_hint.to_owned(); + } + (state, receiver) + }; + + async fn send_raw( + state: Arc, + path: &str, + encoding: Option<&str>, + payload: String, + ) -> (axum::http::StatusCode, serde_json::Value) { + let ingress = Arc::new(state.ingress_slots.clone().acquire_owned().await.unwrap()); + let mut builder = axum::http::Request::builder() + .method("POST") + .uri(path) + .header("content-type", "application/json"); + if path.starts_with("/v1/messages") { + builder = builder.header("anthropic-version", "2023-06-01"); + } + if let Some(encoding) = encoding { + builder = builder.header("content-encoding", encoding); + } + let request = builder.body(axum::body::Body::from(payload)).unwrap(); + let response = super::super::http::generate( + axum::extract::State(state), + axum::Extension(ingress), + request, + ) + .await; + let status = response.status(); + assert!( + response.headers().get("x-request-id").is_none(), + "{path} preparation failure should not set x-request-id" + ); + let bytes = axum::body::to_bytes(response.into_body(), 16384) + .await + .unwrap(); + let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + (status, body) + } + + let assert_envelope = |path: &str, body: &Value, expected_type: &str, expected_code: &str| { + assert_eq!(body["error"]["type"], expected_type, "{path}: {body}"); + assert!( + body["error"]["message"].as_str().is_some_and(|m| !m.is_empty()), + "{path}: {body}" + ); + if path.starts_with("/v1/messages") { + assert_eq!(body["type"], "error", "{path}: {body}"); + assert!(body["error"].get("code").is_none(), "{path}: {body}"); + assert!(body["error"].get("param").is_none(), "{path}: {body}"); + } else { + assert_eq!(body["error"]["code"], expected_code, "{path}: {body}"); + assert_eq!( + body["error"].get("param"), + Some(&Value::Null), + "{path}: {body}" + ); + } + }; + + // 1. context_length_exceeded across all protocols (including count_tokens and stream=true), + // preserving context_hint in the rendered message. + for stream in [false, true] { + for (path, payload) in [ + ( + "/v1/chat/completions", + json!({"messages": [{"role": "user", "content": "a"}], "max_tokens": 32, "stream": stream}), + ), + ( + "/v1/completions", + json!({"prompt": "a", "max_tokens": 32, "stream": stream}), + ), + ( + "/v1/responses", + json!({"input": "a", "max_output_tokens": 32, "stream": stream}), + ), + ( + "/v1/messages", + json!({"messages": [{"role": "user", "content": "a"}], "max_tokens": 32, "stream": stream}), + ), + ] { + let (state, receiver) = make_state(false, "increase --max-context"); + let (status, body) = send_raw(state, path, None, payload.to_string()).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{path} stream={stream}"); + assert_envelope(path, &body, "invalid_request_error", "context_length_exceeded"); + assert!( + body["error"]["message"] + .as_str() + .unwrap() + .contains("increase --max-context"), + "{path}: {body}" + ); + assert!(receiver.try_recv().is_err(), "{path}"); + } + } + { + let (state, receiver) = make_state(false, "increase --max-context"); + let (status, body) = send_raw( + state, + "/v1/messages/count_tokens", + None, + json!({"messages": [{"role": "user", "content": "a a a a a a a a a a"}]}).to_string(), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_envelope( + "/v1/messages/count_tokens", + &body, + "invalid_request_error", + "context_length_exceeded", + ); + assert!( + body["error"]["message"] + .as_str() + .unwrap() + .contains("increase --max-context"), + "{body}" + ); + assert!(receiver.try_recv().is_err()); + } + + // 2. unsupported_feature from both protocol::decode and prepare_validated_inference + // (image input on a text-only runtime). + for (path, payload) in [ + ( + "/v1/chat/completions", + json!({"messages": [{"role": "user", "content": "a"}], "logit_bias": {"0": 1}}), + ), + ( + "/v1/completions", + json!({"prompt": "a", "suffix": "b"}), + ), + ( + "/v1/responses", + json!({"input": "a", "store": true}), + ), + ( + "/v1/messages", + json!({"messages": [{"role": "user", "content": "a"}], "max_tokens": 4, "logprobs": true}), + ), + ( + "/v1/chat/completions", + json!({"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}}]}]}), + ), + ( + "/v1/responses", + json!({"input": [{"role": "user", "content": [{"type": "input_image", "image_url": "data:image/png;base64,AA=="}]}]}), + ), + ( + "/v1/messages", + json!({"messages": [{"role": "user", "content": [{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "AA=="}}]}], "max_tokens": 4}), + ), + ] { + let (state, receiver) = make_state(false, ""); + let (status, body) = send_raw(state, path, None, payload.to_string()).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{path}: {body}"); + assert_envelope(path, &body, "invalid_request_error", "unsupported_feature"); + assert!(receiver.try_recv().is_err(), "{path}"); + } + + // 3. invalid_grammar across response/output schema compilation, strict tool schema validation, + // and custom tool grammar compilation. + let invalid_schema = json!({"type": "not-a-valid-json-schema-type"}); + for (path, payload) in [ + ( + "/v1/chat/completions", + json!({ + "messages": [{"role": "user", "content": "a"}], + "response_format": {"type": "json_schema", "json_schema": {"name": "bad", "schema": invalid_schema}} + }), + ), + ( + "/v1/completions", + json!({ + "prompt": "a", + "response_format": {"type": "json_schema", "schema": invalid_schema} + }), + ), + ( + "/v1/responses", + json!({ + "input": "a", + "text": {"format": {"type": "json_schema", "schema": invalid_schema}} + }), + ), + ( + "/v1/messages", + json!({ + "messages": [{"role": "user", "content": "a"}], + "max_tokens": 4, + "output_config": {"format": {"type": "json_schema", "schema": invalid_schema}} + }), + ), + // compile_strict_validators path (strict tool schema without additionalProperties: false) + ( + "/v1/chat/completions", + json!({ + "messages": [{"role": "user", "content": "a"}], + "tools": [{"type": "function", "function": {"name": "lookup", "strict": true, "parameters": {"type": "object"}}}] + }), + ), + // compile_text path (invalid regex custom tool grammar on Responses) + ( + "/v1/responses", + json!({ + "input": "a", + "tools": [{"type": "custom", "name": "sql", "format": {"type": "grammar", "syntax": "regex", "definition": "["}}] + }), + ), + ] { + let (state, receiver) = make_state(false, ""); + let (status, body) = send_raw(state, path, None, payload.to_string()).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{path}: {body}"); + assert_envelope(path, &body, "invalid_request_error", "invalid_grammar"); + assert!(receiver.try_recv().is_err(), "{path}"); + } + + // 4. invalid_image on a vision-enabled runtime (invalid base64 and corrupt PNG bytes). + for (path, payload) in [ + ( + "/v1/chat/completions", + json!({"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "data:image/png;base64,not-valid-base64!!!"}}]}]}), + ), + ( + "/v1/responses", + json!({"input": [{"role": "user", "content": [{"type": "input_image", "image_url": "data:image/png;base64,AAAA"}]}]}), + ), + ( + "/v1/messages", + json!({"messages": [{"role": "user", "content": [{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "AAAA"}}]}], "max_tokens": 4}), + ), + ] { + let (state, receiver) = make_state(true, ""); + let (status, body) = send_raw(state, path, None, payload.to_string()).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{path}: {body}"); + assert_envelope(path, &body, "invalid_request_error", "invalid_image"); + assert!(receiver.try_recv().is_err(), "{path}"); + } + + // 4b. General invalid-request 400s (both AdmissionError::Invalid and untyped checks) + // emit HTTP 400 with invalid_request_error. + for payload in [ + json!({ + "messages": [{"role": "user", "content": "a"}], + "stop": ["a", "b", "c", "d", "e"] + }), + json!({ + "messages": [{"role": "user", "content": "a"}], + "max_tokens": 0 + }), + ] { + let (state, receiver) = make_state(false, ""); + let (status, body) = send_raw( + state, + "/v1/chat/completions", + None, + payload.to_string(), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); + assert_envelope( + "/v1/chat/completions", + &body, + "invalid_request_error", + "invalid_request_error", + ); + assert!(receiver.try_recv().is_err()); + } + + // 5. Non-typed HTTP validation errors return their status-derived error codes. + for path in [ + "/v1/chat/completions", + "/v1/completions", + "/v1/responses", + "/v1/messages", + ] { + let (state, receiver) = make_state(false, ""); + let (status, body) = send_raw(state, path, None, "{".into()).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{path}: {body}"); + assert_envelope(path, &body, "invalid_request_error", "invalid_request_error"); + assert!(receiver.try_recv().is_err(), "{path}"); + + let (state, receiver) = make_state(false, ""); + let (status, body) = send_raw(state, path, None, "{}".into()).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{path}: {body}"); + assert_envelope(path, &body, "invalid_request_error", "invalid_request_error"); + assert!(receiver.try_recv().is_err(), "{path}"); + + let (state, receiver) = make_state(false, ""); + let (status, body) = send_raw(state, path, Some("unknown"), "{}".into()).await; + assert_eq!(status, StatusCode::UNSUPPORTED_MEDIA_TYPE, "{path}: {body}"); + assert_envelope(path, &body, "invalid_request_error", "invalid_request_error"); + assert!(receiver.try_recv().is_err(), "{path}"); + + let (state, receiver) = make_state(false, ""); + let (status, body) = send_raw(state, path, None, "x".repeat(4200)).await; + assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE, "{path}: {body}"); + assert_envelope(path, &body, "request_too_large", "request_too_large"); + assert!(receiver.try_recv().is_err(), "{path}"); + } +}