Skip to content

helios/server: preserve typed error codes on HTTP request preparation failures - #689

Merged
lukealonso merged 1 commit into
NVIDIA:mainfrom
jcartu:fix/preparation-typed-error-codes
Dec 3, 2026
Merged

lukealonso merged 1 commit into
NVIDIA:mainfrom
jcartu:fix/preparation-typed-error-codes

Conversation

@jcartu

@jcartu jcartu commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #446

Why

In the Helios HTTP generation handler (helios/src/server/http.rs), request preparation runs in a tokio::task::spawn_blocking closure before scheduler admission. Previously, that closure returned Result<_, (StatusCode, String)>, converting 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 (StatusCode, String) pairs. The handler then rendered those pairs through http::error -> Protocol::error, which sets error.code from the HTTP status category ("invalid_request_error" for HTTP 400) instead of calling Protocol::failure to emit error_code(&error). As a result, clients received "code": "invalid_request_error" on typed preparation rejections (context_length_exceeded, unsupported_feature, invalid_grammar, invalid_image), diverging from post-admission and streaming failures that already render through Protocol::failure.

Preserving typed Error::Admission variants across the spawn_blocking boundary and rendering them through the same Protocol::failure + rejection_details path used by rejection aligns typed preparation errors with post-admission errors, while keeping AdmissionError::Invalid and untyped validation failures (decode_body, missing fields, general parameter checks, oversized generation groups, and ingress rate limits) uniformly on Protocol::error.

What changed

Before this change, http::generate converted every preparation failure inside spawn_blocking 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:
    • Maps Error::Admission(AdmissionError::Invalid(_)) and non-Admission errors to PreparationError::Http(StatusCode::BAD_REQUEST, message), keeping general invalid-request 400s uniformly on "invalid_request_error".
    • Preserves all other Error::Admission(_) variants (Context, Feature, Grammar, Image, Capacity, Unavailable) unchanged as PreparationError::Failure.
  • Extracted failure_response(&HttpState, Protocol, Error) -> Response from rejection in helios/src/server/http.rs so both typed preparation failures and post-submission rejections build their JSON body via Protocol::failure(&failure) and apply rejection_details (status(&failure) plus context_hint / capacity_hint message suffixes). Only post-submission rejection attaches x-request-id and writes failure_log, preserving the x-request-id and logging contract in docs/api.md and docs/core-design.md.
  • Updated http::generate to map errors from 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.

Claimed result

  • 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 HTTP status from status(&error), with context_hint / capacity_hint preserved in error.message and no x-request-id header, for both buffered (stream: false) and streaming (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 while preserving context_hint.
  • General HTTP validation errors (invalid JSON, missing required fields, AdmissionError::Invalid such as more than four stop sequences, untyped preparation validation errors such as max_tokens: 0, unsupported Content-Encoding, and oversized bodies) retain their HTTP status codes (400, 413, 415) and invalid_request_error / request_too_large error 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 (flare-helios --lib: 1,818 passed, 47 ignored; integration test binaries: 62 passed, 37 ignored; ignored tests require GPU hardware or local model checkpoint snapshots). The added tests verify preparation_error across Context, Feature, Grammar, Image, Capacity, Unavailable, Invalid, and untyped errors, and drive http::generate end-to-end across /v1/chat/completions, /v1/completions, /v1/responses, /v1/messages, and /v1/messages/count_tokens for context_length_exceeded (buffered and stream: true, with context_hint), unsupported_feature (both protocol::decode and text-only image rejection in prepare_validated_inference), invalid_grammar (output schema, strict tool schema, and custom tool grammar paths), invalid_image (invalid base64 and corrupt PNG on a vision-enabled HttpState), general 400 validation (stop count > 4 and max_tokens: 0 both emitting invalid_request_error), 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 (flare --lib: 246 passed, 4 ignored; packed_canonical_download: 7 passed; reference_workflows: 1 passed).
  • cargo test --locked --release --manifest-path flare-cli/Cargo.toml: 245 passed, 0 failed, 3 ignored (flare-cli --bin: 219 passed, 3 ignored; cache_commands: 9 passed; cli: 6 passed; inspect: 4 passed; unverified_payload: 7 passed).
  • Limitations: live GPU serving and the Python server integration tests (tests/server/test_protocols.py) were not run because no GPU serving process was started in this environment.

Discord: jcartu

@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 689.
Case File Intake Report

Future reviews will auto-run 90 minutes after code updates are pushed.

  • Re-review sooner: Call @flare-autobot after push.
  • Opt-out: Include #autobot:ignore in the PR or any comment.

@flare-autobot flare-autobot added area:api Serving API, protocol encoding, tool parsing, and client-visible behavior. bug Something isn't working triage:review Proposed change needs code review; this does not imply merge readiness. labels Dec 2, 2026
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

PR #689 cleanly fixes the core #446 defect by carrying typed Error values across http::generate's spawn_blocking boundary and rendering them through the shared Protocol::failure + rejection_details path without altering x-request-id, failure logging, HTTP status codes, or concurrency/permit lifetimes. Before merging, resolve the wire-level error.code split introduced by routing AdmissionError::Invalid to "invalid_request" while adjacent validation checks on the exact same fields still emit "invalid_request_error", and trim the unreachable FrontendError::ImageDecode branch and duplicated HttpState struct literal in the new test.

  • Blockers: 0 · Should fix: 1 · Subtract/Simplify: 2 · Nits: 1
Walkthrough
  • Shared failure renderer (helios/src/server/http.rs:26-41): extracts failure_response(&HttpState, Protocol, Error) -> Response using protocol.failure(&failure) and rejection_details(state, failure) for hint-suffixed messages; rejection delegates to failure_response while keeping log_failure and with_request_id post-submission only (matching docs/core-design.md:1119-1121 and docs/api.md:258-259).
  • Preparation error classifier (helios/src/server/http.rs:119-132): introduces private PreparationError::{Http, Failure} and preparation_error(Error) so Error::Admission(_) (and FrontendError::ImageDecode(_)) preserve typed failures while non-admission errors map to PreparationError::Http(StatusCode::BAD_REQUEST, ...).
  • Generation preparation dispatch (helios/src/server/http.rs:209-293): routes 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 (keeping decode_body 400/413/415, oversized-group 400, and admission-full 429 on http::error).
  • Tests (helios/src/server/http.rs:739-786, helios/src/server/runtime/phase_tests.rs:8438-8792): adds a unit test for preparation_error and an end-to-end http::generate test covering /v1/chat/completions, /v1/completions, /v1/responses, /v1/messages, and /v1/messages/count_tokens (buffered and stream: true), asserting typed error.code, context_hint, explicit param: null, Anthropic envelope shape, absent x-request-id, and zero model-queue admissions (receiver.try_recv().is_err()).
Merge Risk: Low · up to 2f72e1b
  • Changes are strictly confined to helios/src/server/http.rs (+86/−23) and helios/src/server/runtime/phase_tests.rs (+356/−0); no model-core, Protobuf, scheduler, prefix-cache, or CUDA-graph code is touched, and no HTTP status codes change (all reachable preparation AdmissionError variants map to HTTP 400 at helios/src/server.rs:733-741).
  • No concurrency, lock, permit-lifetime, or hot-path overhead regression: frontend_slots (_permit), ingress_slots (_ingress), and extra group-permit lifetimes inside spawn_blocking (helios/src/server/http.rs:209-284) are unchanged, and failure_response runs post-join on the error path only.
  • On OpenAI-shaped routes (/v1/chat/completions, /v1/completions, /v1/responses), error.code changes from "invalid_request_error" to typed codes (context_length_exceeded, unsupported_feature, invalid_grammar, invalid_image, and currently invalid_request), while error.type stays "invalid_request_error", error.param stays null, and Anthropic /v1/messages envelopes are unchanged.
Pre-merge checks: ✅ 3 passed · ⚠️ 1 warnings

Have your agent review the Full Review for complete verified findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

… 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 <jcartu@users.noreply.github.com>
Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=2e5b
@jcartu
jcartu force-pushed the fix/preparation-typed-error-codes branch from 2f72e1b to 4695d84 Compare December 2, 2026 21:53
@jcartu

jcartu commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@flare-autobot Addressed all four review items in commit 4695d846:

  1. General 400 error.code consistency (helios/src/server/http.rs, helios/src/server/runtime/phase_tests.rs): preparation_error now maps Error::Admission(AdmissionError::Invalid(_)) to PreparationError::Http(StatusCode::BAD_REQUEST, error.to_string()), so general invalid-request 400s uniformly emit "invalid_request_error" while Context, Feature, Grammar, Image, Capacity, and Unavailable preserve their typed error_code(&error) values via PreparationError::Failure. Updated both the preparation_error unit test and the HTTP-wire test (stop count > 4 and max_tokens: 0 both assert "invalid_request_error").
  2. Removed unreachable FrontendError::ImageDecode arm (helios/src/server/http.rs): Deleted the redundant Error::Frontend(FrontendError::ImageDecode(_)) match arm in preparation_error and its synthetic unit-test case (describe_images already wraps image decode errors in AdmissionError::Image).
  3. Simplified make_state in helios/src/server/runtime/phase_tests.rs: Replaced the 21-field hand-rebuilt HttpState struct literal with http_state_for(...) mutated in place via Arc::get_mut(&mut state).unwrap() for images, max_body_bytes, and context_hint.
  4. Documented typed 400 codes (docs/api.md): Added a sentence documenting that typed HTTP 400 rejections on Chat Completions, Completions, and Responses set error.code to context_length_exceeded, unsupported_feature, invalid_grammar, or invalid_image while keeping error.type as invalid_request_error.

Re-verified release CPU test suites on 4695d846:

  • cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server (with FLARE_TEST_TEMPLATE_DIR): 1,880 passed, 0 failed, 84 ignored
  • cargo test --locked --release --manifest-path flare/Cargo.toml: 254 passed, 0 failed, 4 ignored
  • cargo test --locked --release --manifest-path flare-cli/Cargo.toml: 245 passed, 0 failed, 3 ignored

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Ready To Merge

Commit 4695d84 resolves all four items from the prior review cleanly with no regressions, and the implementation fixes #446 at the right layer with exact parity on HTTP status codes, x-request-id/logging boundaries, Anthropic envelopes, and spawn_blocking permit lifetimes. Confirm green CI on 4695d84 before merging.

  • Blockers: 0 · Should fix: 0 · Subtract/Simplify: 1 · Nits: 0
Walkthrough
  • Shared failure renderer (helios/src/server/http.rs:26-41): extracts failure_response(&HttpState, Protocol, Error) -> Response using protocol.failure(&failure) and rejection_details(state, failure) for hint-suffixed messages; rejection delegates to it while keeping log_failure and with_request_id post-submission only (matching docs/core-design.md:1119-1121 and docs/api.md:261-262).
  • Preparation error classifier (helios/src/server/http.rs:119-132): adds private PreparationError::{Http, Failure} and preparation_error(Error) so Error::Admission(AdmissionError::Invalid(_)) and non-admission errors map to PreparationError::Http(StatusCode::BAD_REQUEST, ...), while all other Error::Admission(_) variants stay typed as PreparationError::Failure.
  • Generation preparation dispatch (helios/src/server/http.rs:209-293): routes protocol::decode, GrammarCompiler::compile_text, Request::generation_count, request::compile_strict_validators, and request::prepare_validated_inference through preparation_error, dispatching Failure to failure_response and Http to http::error, while leaving decode_body (400/413/415), oversized groups (400), and ingress exhaustion (429) on http::error.
  • Documentation (docs/api.md:257-261): documents that 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.
  • Tests (helios/src/server/http.rs:739-807, helios/src/server/runtime/phase_tests.rs:8438-8763): unit-tests preparation_error across all AdmissionError variants plus untyped strings, and drives http::generate end-to-end across /v1/chat/completions, /v1/completions, /v1/responses, /v1/messages, and /v1/messages/count_tokens (buffered and stream: true) asserting typed codes, context_hint, invalid_request_error for both AdmissionError::Invalid (stop > 4) and untyped validation (max_tokens: 0), 400/413/415 handling, absent x-request-id, and zero queue admissions (receiver.try_recv().is_err()).
Merge Risk: Low · up to 4695d84
  • Changes are confined to helios/src/server/http.rs (+107/−23), helios/src/server/runtime/phase_tests.rs (+327/−0), and docs/api.md (+6/−3); no model-core, scheduler, prefix-cache, worker, or CUDA-graph code is touched, and no HTTP status codes change (all reachable preparation AdmissionError variants map to HTTP 400 at helios/src/server.rs:733-741).
  • No concurrency, contention, permit-lifetime, or common-path overhead regression: frontend_slots (_permit), ingress_slots (_ingress), and extra group permits inside spawn_blocking (helios/src/server/http.rs:209-284) retain identical acquisition and drop scopes, first_response observation is unchanged, and failure_response runs post-join on error paths only.
  • On OpenAI-shaped endpoints (/v1/chat/completions, /v1/completions, /v1/responses), only error.code changes on the four typed 400 classes, while error.type (invalid_request_error), error.param (null), general 400s, and Anthropic /v1/messages envelopes remain unchanged.
Pre-merge checks: ✅ 3 passed · ⚠️ 1 warnings

Have your agent review the Full Review for complete verified findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:api Serving API, protocol encoding, tool parsing, and client-visible behavior. bug Something isn't working triage:review Proposed change needs code review; this does not imply merge readiness.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Request-preparation failures render the generic invalid_request_error code instead of the typed error codes admissions failures use

3 participants