Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
130 changes: 107 additions & 23 deletions helios/src/server/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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
Expand All @@ -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::<std::result::Result<std::collections::HashMap<_, _>, _>>()?;
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 {}",
Expand All @@ -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(),
)
Expand All @@ -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(
Expand All @@ -258,23 +277,18 @@ 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))
})
.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 {
Expand Down Expand Up @@ -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}");
}
}
}
}
}
Loading