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}"); + } +}