Correctness and contracts report · NVIDIA/hyperflare-inference #689

Raw Markdown for agents: https://autobot.eidonix.com/p/ad5f53f4-3cfd-4667-a003-1dfa2cd404ae.md

Correctness, Contracts & System-Level Consequences review — PR #689

PR: NVIDIA/hyperflare-inference#689 · helios/server: preserve typed error codes on HTTP request preparation failures · author jcartu · head 2f72e1b · fixes #446 · +442/−23 in 2 files (helios/src/server/http.rs +86/−23, helios/src/server/runtime/phase_tests.rs +356/−0).

Scope of this review. I read the full diff, all of helios/src/server/http.rs at the PR head, the error/status/code plumbing (helios/src/error.rs, helios/src/server.rs:733-755, helios/src/server/protocol/mod.rs:33-59), every callee reached from the preparation closure (helios/src/server/request.rs, helios/src/server/stops.rs, helios/src/model.rs, helios/src/grammar.rs, helios/src/frontend/), both added test sites, the wire contracts in docs/api.md and docs/core-design.md, issue #446, and the in-repo consumers of error.code. No competing PR touches the same rendering helpers; the decisions endpoints already rendered Protocol::failure from inside spawn_blocking (helios/src/server/protocol/decisions/mod.rs:216-226, :282-292), so #689 generalises an existing pattern rather than inventing one.

Key findings

Verdict: no Blocker. The main path is correct, small and genuinely tested. Three findings, one Major, two Minor.

  1. Major — error.code now encodes internal validation layering, and the change exceeds what #446 asked for. Two adjacent client-input 400s return different code values after this PR ("max_tokens": 0 → invalid_request_error vs "stop": [5 strings] → invalid_request). Issue #446 asks only for context_length_exceeded, unsupported_feature, invalid_grammar, invalid_image; the invalid_request class is a fifth, much broader one.
  2. Minor — the catch-all arm hardcodes HTTP 400 where status(&error) says 500. Internal Frontend/Execution failures reached through prepare_validated_inference (tokenizer, asset, template) are reported to the client as 400. Pre-existing behaviour, but it makes the description's "HTTP status from status(&error)" untrue of that arm.
  3. Minor — docs/api.md now contradicts the wire. It still documents every malformed/unsupported/over-context 400 as invalid_request_error; the typed strings appear nowhere under docs/. One sentence needed; docs/core-design.md already promised typed codes, so this is doc debt rather than a design change.

Everything else in the lens is sound: no HTTP status can change, no concurrency/lock/memory/latency consequence, the x-request-id and failure-log contract is preserved by construction, the Anthropic envelope is untouched, untyped bodies are byte-identical to before, and the two added tests are real behaviour tests. Details and the verified-sound list follow.


1. Major — error.code now depends on internal validation layering, and the change exceeds #446's scope

Severity: Major. helios/src/server/http.rs:124-132; helios/src/server.rs:751.

fn preparation_error(error: Error) -> PreparationError {
    match error {
        Error::Admission(_) => PreparationError::Failure(error),
        Error::Frontend(crate::FrontendError::ImageDecode(_)) => {
            PreparationError::Failure(error.admission_context(AdmissionError::Image))
        }
        other => PreparationError::Http(StatusCode::BAD_REQUEST, other.to_string()),
    }
}

PreparationError::Failure is dispatched to failure_response (helios/src/server/http.rs:286-291), which builds the body via Protocol::failure and therefore calls error_code — where every admission variant maps to a typed string, including the broad Invalid class:

        Error::Admission(AdmissionError::Invalid(_)) => "invalid_request",

Issue #446 asks for exactly four codes (context_length_exceeded, unsupported_feature, invalid_grammar, invalid_image), and yatesdr's confirming comment on #446 lists the same four. AdmissionError::Invalid is a fifth, much larger class of 400s and is not mentioned in the issue.

The concrete inconsistency, both branches reachable from request preparation and both pinned by this PR's own tests:

(a) "max_tokens": 0 keeps the old untyped code. helios/src/server/request.rs:615-616 produces a string error, which impl From<&str> for Error turns into ExecutionError::State (helios/src/error.rs:179-183), so it lands in the other arm:

        if max_new_tokens == 0 || max_new_tokens > i32::MAX as u32 {
            return Err("output limit must be between 1 and 2147483647 tokens".into());
        }

The PR's wire test asserts the old value — helios/src/server/runtime/phase_tests.rs:8744-8757 sends {"max_tokens": 0} and asserts assert_envelope(…, "invalid_request_error", "invalid_request_error").

(b) "stop": [5 strings] now returns the new typed code. helios/src/server/stops.rs:63-72:

pub(super) fn validate_strings(strings: &[String], token_stops: bool, grammar: bool) -> Result<()> {
    if strings.len() > 4
        || strings.iter().any(String::is_empty)
        || strings.iter().map(String::len).sum::<usize>() > 4096
    {
        return Err(Error::admission(
            AdmissionError::Invalid,
            "stop allows at most four nonempty strings totaling at most 4096 UTF-8 bytes",
        ));
    }

and the PR's test asserts the new value — helios/src/server/runtime/phase_tests.rs:8719-8736, assert_envelope("/v1/chat/completions", &body, "invalid_request_error", "invalid_request").

Impact. Two adjacent lines of the same request-validation family now emit different error.code strings for the same class of client mistake. Also in the typed camp: sampling validation (helios/src/model.rs:229-257), and output limits above u32 (helios/src/server/request.rs:609-614). Still in the untyped camp: max_tokens == 0 (request.rs:615-616), top_k/seed type errors (request.rs:710, :724), and token stops (stops.rs:22). A client branching on code == "invalid_request_error" silently stops matching stop/sampling errors while continuing to match max_tokens errors; the code field now encodes which Rust layer raised the error rather than a wire contract. No in-repo consumer branches on these strings (tests/server/test_protocols.py:620 and tests/server/test_decisions.py:218 (not opened) assert only type; test_protocols.py:85 checks model_not_found, unaffected), so nothing breaks in-tree — but the wire contract acquired an accidental dependency on internal structure, which is exactly the class of thing that becomes expensive to change later.

Fix (pick one, do not land neither). (i) Keep AdmissionError::Invalid on the untyped arm — e.g. Error::Admission(AdmissionError::Invalid(_)) => PreparationError::Http(StatusCode::BAD_REQUEST, error.to_string()) — so only #446's four codes change and invalid_request continues to mean "the post-admission/streaming path". Or (ii) type the remaining untyped preparation 400s (give max_tokens == 0, top_k/seed, token stops AdmissionError::Invalid instead of Error::from(&str)) and list all five codes in docs/api.md, so that one class of client error has one code whichever validation layer caught it. Option (i) is the smaller footprint and matches #446's stated scope.


2. Minor — the hardcoded 400 in the catch-all arm blames the client for internal failures

Severity: Minor. helios/src/server/http.rs:130, read against helios/src/server.rs:733-741.

        other => PreparationError::Http(StatusCode::BAD_REQUEST, other.to_string()),

is not the authoritative status mapping. That is status():

fn status(failure: &Error) -> StatusCode {
    match failure {
        Error::Admission(AdmissionError::Capacity(_) | AdmissionError::Unavailable(_)) => {
            StatusCode::SERVICE_UNAVAILABLE
        }
        Error::Admission(_) => StatusCode::BAD_REQUEST,
        _ => StatusCode::INTERNAL_SERVER_ERROR,
    }
}

so Error::Execution(_) and Error::Frontend(Asset|Template|Tokenizer|Input) (helios/src/error.rs:131-143) are 500 by status() but 400 through preparation_error. Reachable internal failures on the preparation path include frontend.encode(...) at helios/src/server/request.rs:178, which returns FrontendError::Tokenizer on a tokenizer runtime failure. Error::Frontend(FrontendError::ImageDecode(_)) is special-cased precisely because it is client-caused, which shows the author was aware the arm mixes client and server causes.

Impact. A tokenizer or template-evaluation failure during preparation is reported as HTTP 400 invalid_request_error, telling the client to fix a request that is fine and hiding an operator-visible fault. This is pre-existing behaviour, not a regression introduced by #689 — and it is also the reason the hardcoded 400 cannot simply be replaced with status(&error): Error::from(&str) maps ordinary validation strings to ExecutionError::State (helios/src/error.rs:174-183), which status() would turn into 500, i.e. it would convert every untyped validation 400 into a 500. So on this path the 400/500 boundary is genuinely not recoverable from the error type, and the PR description's "HTTP status from status(&error)" is not true of the catch-all arm.

Fix. At minimum, comment the arm to record why 400 is hardcoded (untyped validation strings are modelled as ExecutionError::State). If the layering is to be repaired, do it in a follow-up: give validation failures a distinct admission variant so Error::Execution(_) can safely take Http(status(&error), …) here.


3. Minor — docs/api.md now contradicts the wire for typed preparation 400s

Severity: Minor (docs only, but it is the contract a code-branching client reads). docs/api.md:248-259, unchanged by the PR.

Chat Completions, Completions, and Responses errors are
`{"error": {"type", "message", "param": null, "code"}}`; Messages errors are
`{"type": "error", "error": {"type", "message"}}`. Malformed, unsupported, and
over-context requests return HTTP 400 (`invalid_request_error`); a missing or

After this PR an over-context or unsupported-feature request on those same routes returns "code": "context_length_exceeded" / "unsupported_feature" / "invalid_grammar" / "invalid_image" while type stays invalid_request_error (helios/src/server/protocol/mod.rs:33-51 for type, helios/src/server.rs:743-755 for code). The parenthetical is therefore wrong for exactly the cases the PR changes. The typed strings appear nowhere under docs/.

This is doc debt, not a design change: docs/core-design.md:1115-1119 already promised "Failures observed before response headers use the corresponding HTTP error status … Chat and completion errors include type, message, param, and a typed code", and docs/core-design.md:1119-1121 already restricts x-request-id to post-frontend-preparation responses, which #689 preserves. Sibling PR #638 added docs/api.md text for its wire change, so there is an in-repo precedent.

Fix. One sentence in docs/api.md naming the typed 400 codes and stating that type remains invalid_request_error and param remains null. If the reviewer prefers scope discipline over doc completeness, note the gap in the PR body instead of silently leaving api.md wrong.


4. Verified sound — stated plainly, no issues found

These were checked and are correct; I am not inventing findings in them.


5. Tests and claim accuracy

Checked every material claim in the PR description against the diff:

Claim Verdict
Typed codes on all five routes Holds. http.rs:124-132 + server.rs:743-755; asserted phase_tests.rs:8561-8717.
Explicit param: null; Messages without code/param Holds. protocol/mod.rs:44-51, :53-59; asserted phase_tests.rs:8526-8537.
Untyped 400/413/415 keep status and codes Holds. decode_body untouched; asserted phase_tests.rs:8761-8791.
No x-request-id on preparation failures Holds. Only rejection inserts it (http.rs:40); asserted phase_tests.rs:8509-8512.
Zero model-queue admissions Holds, asserted per case.
"context_hint / capacity_hint preserved in error.message" No-op claim. The pre-PR map_err already passed typed admission errors through unchanged and rejection_details (http.rs:60-72) already appended state.context_hint for AdmissionError::Context. Hints worked before and after; only code changed. capacity_hint cannot apply on this path at all. The description presents an unchanged property as a property of the fix.
"HTTP status from status(&error)" True but vacuous for typed failures, and untrue of the catch-all arm, which hardcodes 400 (http.rs:130) — see findings 1 and 2.
"Wraps Frontend(ImageDecode) as AdmissionError::Image, matching request::prepare" Incomplete. Accurate only for ImageDecode. request::prepare (request.rs:30-36) types every non-Admission error as AdmissionError::Invalid; preparation_error flattens all non-Admission, non-ImageDecode errors to HTTP 400 instead. The asymmetry is deliberate (it keeps untyped bodies byte-identical) but is not disclosed, and it means the two paths disagree for Asset/Template/Tokenizer/Input.
AdmissionError::Invalid → invalid_request Client-visible and undeclared as a separate change. Listed as one of five codes in the "claimed result" without noting that it is a fifth, broader class beyond #446 covering ordinary 400s such as bad stop (stops.rs:63-72) and bad sampling (model.rs:229-257).
helios 1,880 passed / 84 ignored; flare 254; flare-cli 245 Unverifiable here. Head 2f72e1b has no CI checks, no review, no labels. .github/workflows/native-serving.yml (not opened) runs exactly the helios command, so CI would cover the new tests once it runs. The same author's same-day PRs report slightly different helios totals (#692: 1,884; #691: 1,821 lib + 62 integration), consistent with per-branch local runs.
Limitations disclosed (no GPU serving, no tests/server/test_protocols.py) Honest and accurate. The Python assertions in reach check only error["type"] (test_protocols.py:620, test_decisions.py:218 (not opened)) and would very likely still pass, but they were not run.

Metrics/observability span check (per the lens directive). This PR changes no rate, latency, or admission metric's sampling span or scope. The permit/ingress guard lifetimes and the extra group-permit acquisition window (http.rs:210-211, :248-263) are byte-for-byte unchanged, so inbound_rate, queue-admission pricing and estimated_seconds inputs are unaffected. Worth noting alongside: preparation failures are still not counted in flare_requests_failed_total and still do not write a failure_log line — identical to before, so not a regression, but the same author's #692 reworks failure accounting in this same file, and these two should be read together.


6. Open questions

  1. Does a maintainer want AdmissionError::Invalid → invalid_request at all? #446 asks for four codes; this adds a fifth, much broader one. Finding 1's fix (i) removes it with a one-line change.
  2. Which typing is the intended contract for FrontendError? request::prepare (request.rs:30-36) types everything non-Admission as Invalid; preparation_error types only ImageDecode. Both are now live on adjacent paths for Asset/Template/Tokenizer/Input.
  3. Should preparation rejections be logged and counted? Not a regression, but #692 suggests the author is already reworking failure accounting in this file; a reviewer may want the two aligned.
  4. Should docs/api.md list the typed 400 codes, mirroring what #638 did for its wire change?

Could not verify: the reported test totals (no CI on head 2f72e1b, no review, single commit), live GPU serving behaviour, and the Python server integration suite (tests/server/test_protocols.py), which was disclosed as unrun.