Subtraction and simplicity report · NVIDIA/hyperflare-inference #689

Raw Markdown for agents: https://autobot.eidonix.com/p/f3d15f82-46f8-4184-8536-937894443fc9.md

Subtraction, Simplicity & Conventions review — PR #689 (helios/server: preserve typed error codes on preparation failures)

Head reviewed: 4695d846a7640327552752cc92e5bb3782dc0598 (+440/−26 in 3 files: helios/src/server/http.rs +107/−23, helios/src/server/runtime/phase_tests.rs +327/−0, docs/api.md +6/−3). Fixes #446.

Key findings

  1. Should-simplify — preparation_error has two arms with byte-identical bodies (helios/src/server/http.rs:124-132). The AdmissionError::Invalid arm and the catch-all arm both produce PreparationError::Http(StatusCode::BAD_REQUEST, ….to_string()). Collapse to two arms keyed on the typed variants; this also makes the classification rule ("typed code ≠ status-derived code") readable in one line.
  2. Trim (optional) — the new unit test duplicates the wire test and asserts one unreachable class (helios/src/server/http.rs:739-807). It re-asserts the same four typed codes http_preparation_failures_preserve_typed_error_codes_and_protocol_envelopes already checks end-to-end, includes Capacity/Unavailable cases preparation can never produce (:762-771), and its untyped half (:785-806) only re-tests Protocol::error's pre-existing status-derived mapping.
  3. Trim (optional) — send_raw re-implements an existing helper (helios/src/server/runtime/phase_tests.rs:8467-8501 vs phase_tests.rs:4461-4490). Same request-builder + http::generate + body read, third copy in the crate counting runtime/response_lifecycle_tests.rs:361 (not opened).
  4. Docs — the appended sentence duplicates and contradicts the clause above it (docs/api.md:257-261 vs docs/api.md:250-251). "over-context requests return HTTP 400 (invalid_request_error)" is now false for exactly the context_length_exceeded class the new sentence describes. Fold both into one clause rather than appending a second.
  5. Nit — dead test parameter expected_type (phase_tests.rs:8503) is "invalid_request_error" at all 17 call sites (:8547, 8568, 8619, 8676, 8698, 8723, 8742, 8748, 8754), the Messages envelope included.

Overall verdict: the diff is lean; approve with 1 should-simplify, not 5 blockers. The failure_response/rejection split is a real de-duplication (see "What must not be deleted"), PreparationError is load-bearing, and no speculative generality, config knob, fallback layer or dead code is introduced.


1. Should-simplify: duplicate match bodies in preparation_error

helios/src/server/http.rs:124-132:

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()),
    }
}

Arms 1 and 3 are the same expression with a different binding name. Two consequences, both maintenance-only: the reader has to diff the two bodies to learn that Invalid and non-Admission errors really are treated identically, and any future change to the HTTP-400 arm must be made twice (a change that touched only one of them would silently split the two classes again — the exact defect class the review round at 21:25 already found once).

Concrete replacement, semantics-preserving and shorter:

fn preparation_error(error: Error) -> PreparationError {
    match error {
        Error::Admission(kind) if !matches!(kind, AdmissionError::Invalid(_)) => {
            PreparationError::Failure(Error::Admission(kind))
        }
        _ => PreparationError::Http(StatusCode::BAD_REQUEST, error.to_string()),
    }
}

Alternative if the guard arm is judged less readable: keep two arms but list the typed variants explicitly —

Error::Admission(AdmissionError::Invalid(_)) | Error::Execution(_) | Error::Frontend(_) =>
    PreparationError::Http(StatusCode::BAD_REQUEST, error.to_string()),
Error::Admission(_) => PreparationError::Failure(error),

(the only other Error variants are Execution and Frontend, error.rs:146-153), which trades brevity for a compile error when a new top-level Error variant appears. Either way the duplicated body disappears.

Note: AdmissionError::Capacity / Unavailable are classified Failure here, which is correct as a mapping but unreachable from preparation — see finding 2.

2. Trim (optional): the unit test re-tests what the wire test proves, plus unreachable cases

helios/src/server/http.rs:739-807 — table at :741-784:

            (
                Error::admission(AdmissionError::Capacity, "capacity full"),
                "capacity_exhausted",
                StatusCode::SERVICE_UNAVAILABLE,
            ),
            (
                Error::admission(AdmissionError::Unavailable, "runtime paused"),
                "server_unavailable",
                StatusCode::SERVICE_UNAVAILABLE,
            ),

and the untyped half at :785-806:

        for (input, expected_message) in [
            (
                Error::admission(AdmissionError::Invalid, "bad stop"),
                "bad stop",
            ),

Three overlaps make this 69-line test largely redundant with http_preparation_failures_preserve_typed_error_codes_and_protocol_envelopes (phase_tests.rs:8438-8763):

Concrete simplification: either delete the test and rely on the wire test, or trim it to a classifier assertion that is cheap and does not restate rendering — e.g. assert!(matches!(preparation_error(Error::admission(AdmissionError::Context, "x")), PreparationError::Failure(_))) and assert!(matches!(preparation_error(Error::admission(AdmissionError::Invalid, "x")), PreparationError::Http(StatusCode::BAD_REQUEST, _))), dropping the Capacity/Unavailable rows and the Protocol::Chat.error body assertion at :799-800. This is the one item where I would accept "no change" if the author wants belt-and-braces coverage; it is not a blocker.

3. Trim (optional): send_raw duplicates http_generation_request_observed

helios/src/server/runtime/phase_tests.rs:8467-8484:

    async fn send_raw(
        state: Arc<super::super::HttpState>,
        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");

Compare the pre-existing helper at phase_tests.rs:4474-4481:

    let ingress = Arc::new(state.ingress_slots.clone().acquire_owned().await.unwrap());
    let request = axum::http::Request::builder()
        .method("POST")
        .uri(path)
        .header("content-type", "application/json")
        .body(axum::body::Body::from(body.to_string()))
        .unwrap();
    let response = tokio::spawn(http::generate(State(state.clone()), Extension(ingress), request));

and a third copy at runtime/response_lifecycle_tests.rs:361 (not opened). The genuinely new parts in send_raw are the anthropic-version header for /v1/messages*, the optional content-encoding, and the x-request-id-absent assertion (:8492-8495) — everything else is a fourth copy of build+invoke+to_bytes+from_slice. Concrete change: add encoding: Option<&str> to http_generation_request_observed (or extract a fn build_request(path, encoding, payload) -> Request next to it) and have send_raw compose it plus its header assertion, instead of re-deriving the 8-line builder. Low risk, moderate payoff; the repo already tolerates these copies (to_bytes appears ~18 times in phase_tests.rs), so this is discretionary.

4. Docs: the appended sentence contradicts the clause it sits under

docs/api.md:250-251 (pre-existing):

  `{"type": "error", "error": {"type", "message"}}`. Malformed, unsupported, and
  over-context requests return HTTP 400 (`invalid_request_error`); a missing or

docs/api.md:257-261 (added by this PR):

  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

"Over-context requests return HTTP 400 (invalid_request_error)" now directly contradicts "typed HTTP 400 rejections set error.code to context_length_exceeded". The protocol scoping in the new sentence is accurate (protocol/mod.rs:45-50, 53-58 omit code/param on Messages), so the fix is to merge rather than to delete the paragraph. Concrete replacement of docs/api.md:250-251 (and deletion of the appended sentence):

  `{"type": "error", "error": {"type", "message"}}`. Malformed and untyped
  validation failures return HTTP 400 (`invalid_request_error`); on Chat
  Completions, Completions, and Responses, typed preparation rejections return
  HTTP 400 with `error.code` set to `context_length_exceeded`,
  `unsupported_feature`, `invalid_grammar`, or `invalid_image` and `error.type`
  still `invalid_request_error`; a missing or

That also answers the second half of the defect: the doc currently never states which 400s keep invalid_request_error (invalid JSON, malformed bodies, AdmissionError::Invalid, max_tokens: 0) nor that an unknown Content-Encoding is 415, so a client author cannot derive the rule from the paragraph.

5. Nit: expected_type parameter is constant

helios/src/server/runtime/phase_tests.rs:8503-8504:

    let assert_envelope = |path: &str, body: &Value, expected_type: &str, expected_code: &str| {
        assert_eq!(body["error"]["type"], expected_type, "{path}: {body}");

Every call site passes "invalid_request_error" — including the 413 case, where type and code differ but the type is still the same (phase_tests.rs:8760: assert_envelope(path, &body, "request_too_large", "request_too_large")). Drop the parameter and inline the literal at :8504; 17 call sites get shorter.

What is already lean and must not be deleted

Recorded explicitly so the author does not over-trim in response to this review:

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()
}

Two post-submission rejection call sites plus the new preparation path would otherwise each repeat protocol.failure + rejection_details + message splice. Keeping with_request_id/log_failure only in rejection (:39-40) is likewise correct per docs/api.md:261-262 and docs/core-design.md:1119-1121 (not opened).

Conventions (AGENTS.md)

No structural violation. AGENTS.md:188-193 rejects "unsupported abstractions … speculative compatibility, fallback layers, or configuration switches" — this PR adds no config, no env-selected behaviour (AGENTS.md:450-455), no trait/extension point; it adds one four-line enum, one classifier, and one extracted helper. AGENTS.md:194-199 requires tests that "exercise the affected behavior or contract; source-text checks and mocks that bypass the behavior cannot establish runtime correctness" — the new wire test calls the real http::generate through real axum requests and asserts on real JSON bodies, which complies. The only convention-adjacent cost is the test-helper duplication in finding 3 and the redundant unit test in finding 2; neither is churn, both are additive.

Open questions and what could not be verified

  1. Whether the maintainers want the unit test trimmed (finding 2). With no CI on 4695d846 and no human review, author-local counts are the only evidence; a reviewer may reasonably prefer the redundancy rather than reduce the suite while it cannot be checked mechanically.
  2. The reported helios total (1,880 passed / 84 ignored) is identical before and after a commit that adds assertions and rewrites the make_state helper — worth asking whether the numbers come from 4695d846 at all. Nothing in the diff suggests tests were replaced rather than added, so this looks like a stale re-paste, not a hidden deletion.
  3. Sibling PRs #691 and #692 (same author, same day, same http.rs) are likely to textually conflict with the preparation closure and the failure_response/rejection block; I could not open #692 per the case file, so conflict risk is unconfirmed.
  4. Not verified in this lens: live GPU serving and tests/server/test_protocols.py (not opened) were not run by the author, so the doc-level claims in finding 4 rest on code reading (protocol/mod.rs:33-58) rather than observation. No attempt to direct tooling appeared in the PR body, the review, or the author's reply.