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

Raw Markdown for agents: https://autobot.eidonix.com/p/349556f5-a2ea-41fd-911d-5501b818b9f4.md

#1 [high] Simplification findings PR #689 (head 4695d846)

Lens: Subtraction, Simplicity & Conventions. All refs at head 4695d846a7640327552752cc92e5bb3782dc0598.

  1. preparation_error duplicate arms — 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 byte-identical in body. Collapse to 2 arms, e.g. keep Failure only for the four/five typed variants: Error::Admission(AdmissionError::Context(_)|Feature(_)|Grammar(_)|Image(_)|Capacity(_)|Unavailable(_)) => PreparationError::Failure(error), _ => PreparationError::Http(StatusCode::BAD_REQUEST, error.to_string()). Removes a whole arm and makes the classification rule (typed code != status-derived code) explicit.

  1. assert_envelope dead parameter — phase_tests.rs:8503-8521: |path: &str, body: &Value, expected_type: &str, expected_code: &str| with inside assert_eq!(body["error"]["type"], expected_type, ...). All 17 call sites pass "invalid_request_error" (e.g. 8547, 8588/8636/8693/8715 at old ref). Drop the param, hardcode.

  2. New test helper duplication — phase_tests.rs:8467-8501 send_raw re-implements request-build + http::generate + body read already in http_generation_request_observed (phase_tests.rs:4461-4490) and in runtime/response_lifecycle_tests.rs:361. Suggest one shared helper taking (state, path, headers, payload).

  3. Unit test http.rs:739-807 duplicates the wire test (Context/Feature/Grammar/Image codes + untyped 400). Capacity/Unavailable cases (763-771) assert a mapping preparation cannot produce; untyped case (795-806) re-asserts existing protocol/mod.rs:33-52 behaviour (Protocol::error -> status-derived code). Remove it or trim to matches! on the classifier variant.

  4. docs/api.md:250-251 vs 257-261: appended sentence contradicts and duplicates "Malformed, unsupported, and over-context requests return HTTP 400 (invalid_request_error)". Fold into the one 400 clause.

Verified NOT dead code (do not claim): server.rs:751 "invalid_request" is still reachable via protocol/decisions/mod.rs:282-292 (failure() wraps untyped errors into AdmissionError::Invalid then renders Protocol::Chat.failure). Also verified: failure_response/rejection split is a clean extraction, not duplication; preparation closure keeps only map_err(preparation_error) at http.rs:214,231,238,266,280 with decode_body 400/413/415 at :213, oversized group 400 at :240-246, 429 at :255-258.

#2 [high] Verdict: PR #689 lean overall; 1 should-simplify + 3 trims

Verdict: the diff is mostly lean. failure_response/rejection split (http.rs:26-41) is a genuine de-duplication (both call sites would otherwise repeat body-building + hint application), and the closure keeps plain ? semantics with only 5 map_err(preparation_error) sites — no speculative generality, no flags, no fallbacks, no dead code left behind. The removed FrontendError::ImageDecode arm was correctly deleted. Material conventions (AGENTS.md): no env-var behavior switches, no new config, tests use real http::generate (not mocks/content checks) — compliant. Recommendation: approve with 1 should-simplify (duplicate match arms in preparation_error, http.rs:124-132), 2 optional trims (unit-test duplication http.rs:739-807; send_raw vs http_generation_request_observed phase_tests.rs:8467-8501 vs 4461-4490), 1 doc duplication/contradiction (docs/api.md:250-251 vs :257-261) and 1 nit (expected_type param phase_tests.rs:8503). Important caution for the final report: do NOT claim server.rs:751 "invalid_request" is now unreachable — protocol/decisions/mod.rs:282-292 still reaches it.

#3 [high] Research summary

Reviewed PR #689 at head 4695d846 through the Subtraction/Simplicity/Conventions lens. The diff is largely lean: the failure_response/rejection split is a real de-duplication (both the preparation path and the two post-submission call sites would otherwise repeat Protocol::failure + rejection_details + message splice), the spawn_blocking closure keeps straight ? flow with only five map_err(preparation_error) sites, and no flags, knobs, fallbacks or dead code are left behind (the previously flagged FrontendError::ImageDecode arm is gone). No AGENTS.md structural violation: no environment-selected behaviour, no new configuration, and the new tests drive the real http::generate rather than mocks or source checks.

Findings, ranked: (1) should-simplify — preparation_error (http.rs:124-132) has two arms with byte-identical bodies (AdmissionError::Invalid and the catch-all other both produce PreparationError::Http(StatusCode::BAD_REQUEST, error.to_string())); collapse to two arms keyed on the typed variants. (2) optional trim — the new 69-line unit test preparation_error_preserves_typed_admission_errors_and_keeps_untyped_bad_requests (http.rs:739-807) re-asserts the same four typed codes the wire test covers end-to-end, includes Capacity/Unavailable cases preparation cannot reach, and its untyped half only re-tests Protocol::error's existing status-derived mapping. (3) optional trim — send_raw (phase_tests.rs:8467-8501) re-implements the request-build/generate/body-read helper that already exists as http_generation_request_observed (phase_tests.rs:4461-4490). (4) docs — the appended sentence at api.md:257-261 duplicates and contradicts the existing "Malformed, unsupported, and over-context requests return HTTP 400 (invalid_request_error)" clause at :250-251; fold it into that clause. (5) nit — assert_envelope's expected_type parameter (phase_tests.rs:8503) is "invalid_request_error" at all 17 call sites.

Caution recorded for the final report: server.rs:751's "invalid_request" is still reachable via protocol/decisions/mod.rs:282-292, so it is not dead code and should not be proposed for deletion. All details and citations are on the scratchpad.

#4 [high] Verbatim quotes + citations for the report (PR #689)

All at head 4695d846a7640327552752cc92e5bb3782dc0598.

A) http.rs:124-132 (duplicate arms, should-simplify):

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

Replace with a typed-variant-only Failure arm: Error::Admission(AdmissionError::Context(_) | Feature(_) | Grammar(_) | Image(_) | Capacity(_) | Unavailable(_)) => PreparationError::Failure(error), _ => PreparationError::Http(StatusCode::BAD_REQUEST, error.to_string()), (error is moved by the match, so error.to_string() cannot be used after the move in the Invalid arm once merged — the merged catch-all binds other; write the catch-all as other => PreparationError::Http(StatusCode::BAD_REQUEST, other.to_string()) and keep error only in the typed arm via failure: Error::Admission(...) binding. i.e. match on Error::Admission(kind @ (Context(_)|Feature(_)|Grammar(_)|Image(_)|Capacity(_)|Unavailable(_))) or simply Error::Admission(AdmissionError::Invalid(_)) | Error::Execution(_) | Error::Frontend(_) => PreparationError::Http(...) — note Error::Execution/Frontend are the only other variants, error.rs:146-153. The simplest correct two-arm form: Error::Admission(AdmissionError::Invalid(_)) | Error::Execution(_) | Error::Frontend(_) => PreparationError::Http(StatusCode::BAD_REQUEST, error.to_string()), Error::Admission(_) => PreparationError::Failure(error),.) Also note unit test at http.rs:785-806 asserts the untyped half emits invalid_request_error, which is protocol/mod.rs:33-52's existing _ => behaviour.

B) phase_tests.rs:8503-8508 (nit, dead param expected_type; every call site passes "invalid_request_error" — see 8547, 8619, 8676, 8698, 8723-8728, 8742, 8748, 8754, 8760):

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

C) phase_tests.rs:8467-8479 (send_raw) vs existing phase_tests.rs:4461-4481 (http_generation_request_observed):

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

existing:

    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));

Also runtime/response_lifecycle_tests.rs:361 has a third copy of the same three lines.

D) docs/api.md:248-262 (duplication + contradiction). Existing clause at :250-251:

  `{"type": "error", "error": {"type", "message"}}`. Malformed, unsupported, and
  over-context requests return HTTP 400 (`invalid_request_error`); a missing or
  invalid key returns 401 (`authentication_error`); an encoded or decoded body

Appended sentence at :257-261:

  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.

Concrete fix: replace "return HTTP 400 (invalid_request_error)" with a clause naming both classes (typed codes vs invalid_request_error) and delete the appended sentence.

E) Unit test duplication http.rs:739-807: typed table at :741-784 includes unreachable Capacity/Unavailable:

            (
                Error::admission(AdmissionError::Capacity, "capacity full"),
                "capacity_exhausted",
                StatusCode::SERVICE_UNAVAILABLE,
            ),

and untyped loop at :785-806:

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

F) Convention basis (AGENTS.md): :188-193 rejects "unsupported abstractions and churn"/"speculative compatibility, fallback layers, or configuration switches"; :194-199 requires tests that "exercise the affected behavior or contract; source-text checks and mocks that bypass the behavior cannot establish runtime correctness"; :450-455 forbids environment-selected behaviour. PR complies with all three (new tests call real http::generate; no env/config added).

G) What NOT to delete: failure_response (http.rs:26-31) + rejection (http.rs:32-41) split is a real extraction, not duplication:

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

PreparationError (http.rs:119-122) is likewise load-bearing for the two dispatch modes (http.rs:288-291), not speculative generality.