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

Raw Markdown for agents: https://autobot.eidonix.com/p/a77380f1-4c86-4854-b85b-44d079df6e5e.md

Correctness, Contracts & System-Level Consequences review — PR #638 @ 7ba8c66

Scope of this lens: every changed file opened at head 7ba8c66, plus their direct callers (http::generate, Encoder::start/response/failure, decode::options, decode::responses_messages, Request::validate, request::template_inputs, server::admit_http), the docs contracts they touch (docs/api.md), and all five new tests. Findings from the Discovery Dossier that the rebase resolved (per-response responses_tools rebuild, non-single-pass responses_text_format, duplicated TML fixture, missing namespace docs) are withdrawn and not repeated here.

Key findings

  1. Major (contract, self-inconsistency in the newly fixed field): response.tools now echoes namespaced tools unflattened ({"type":"namespace","name":"db","tools":[{"type":"function","name":"query"}]}), while response.tool_choice for a named pick still echoes the flattened db__query — a name that appears nowhere in response.tools (encode.rs:819-822 vs encode.rs:39-42/60-70). Caveat stated honestly: the flattened model-facing name is pre-existing and documented (docs/api.md:548-550); #638 does not create it, but it fixes one half of the pair and leaves the response object internally inconsistent, and the PR's own new test bakes the flattened form in (tests.rs:3279-3282).
  2. Minor (charter #417 silent field drop): text.verbosity is accepted by the new text validation and silently discarded — responses_text_format() inspects only format, and no reject() list includes verbosity (decode.rs:466-506, decode.rs:782-806). The response then claims "text":{"format":{"type":"text"}} with no verbosity, i.e. a config the request did not make — the same class of defect the PR exists to fix.
  3. Minor (docs/claim accuracy): the new text.format HTTP 400 rejections and the prompt-rendering change are undocumented in docs/api.md; §747-752 documents only the happy-path echo. The prompt change is disclosed in the PR body but nowhere in the repo.
  4. Minor (allocations, bounded, not a hot path): responses_tools is deep-copied 4–5× per request by the json! literal at encode.rs:828 (start + clone, completed/incomplete, failed, buffered Complete). Bounded by max_body_bytes (32 MiB default), never per token delta, no lock/queue/IO involvement — avoidable, not a blocker.
  5. Test/claim accuracy: all five new tests are Rust CPU tests; tests/server/test_protocols.py still asserts nothing about response.tools, text.format or is_error, so the PR's headline served-SDK claim is unmeasured (the body admits it), and no CI result exists for this head.
  6. Sound, no finding: is_error decoding is exactly parity with Chat and Messages; duplicate-namespace rejection and empty-wrapper omission are correct; no protobuf/core-format/per-model/flag/scheduler change; no concurrency, admission, or failure-propagation change.

1. Correctness, safety, platform parity

1.1 is_error decoding — correct, exact parity (no finding)

helios/src/server/protocol/decode.rs:337-345:

"function_call_output" | "custom_tool_call_output" => (
    Role::Tool,
    vec![Part::ToolResult {
        id: Some(field(&item, "call_id")?.into()),
        name: None,
        content: plain_parts(&item["output"], Protocol::Responses)?,
        is_error: flag(&item, "is_error", false)?,
    }],
),

This is the same helper and default Chat uses (decode.rs:197) and Messages uses (decode.rs:254); flag rejects non-booleans, so true/false/null/omitted all behave as the PR body states. Multimodal output continues through plain_parts, unchanged. This half of the fix is right and needs no change.

1.2 Namespace decode: duplicate rejection and empty wrappers — correct (no finding)

helios/src/server/protocol/decode.rs:900-916 rejects duplicate namespaces (if !namespaces.insert(namespace) { return Err(...) }), normalizes empty/absent descriptions to None (:907-911), and an empty "tools": [] wrapper yields zero Tool entries and therefore no response.tools entry, consistent with docs/api.md:579-582. No stale-state or ordering hazard: all of this is per-request local state inside decode(), no shared mutable state, no lock.

1.3 Platform parity — nothing changed (no finding)

No filesystem, path, threading, cfg(target_os), signal, or process-boundary code is touched; the diff is confined to helios/src/server/{http,inference,request,protocol/*,runtime/phase_tests}.rs and docs/api.md. Unix/Windows parity is unchanged because the change is pure in-memory JSON transformation.

1.4 Finding — text.verbosity accepted and silently dropped (Minor)

decode.rs:466-506 (opening and the text-only case):

fn responses_text_format(body: &Value) -> Result<Option<(Option<Constraint>, Value)>> {
    if !present(body, "text") { return Ok(None); }
    let text = &body["text"];
    if !text.is_object() { return Err("text must be a JSON object".into()); }
    if !present(text, "format") { return Ok(None); }
    let format = &text["format"];
    ...
    match field(format, "type")? {
        "text" => Ok(Some((None, json!({"type": "text"})))),

Nothing in this function, and no reject() list in decode() (decode.rs:782-806 covers previous_response_id, conversation, background, store, logit_bias, guided_json), mentions verbosity. A repo-wide search_code verbosity returns only docs/clients/codex-models.json:16-17 ("support_verbosity": false) and two unittest.main(..., verbosity=2) lines — no reader in helios/src. So {"text":{"verbosity":"low"}} is accepted, has no effect on the prompt, and the echoed object is rebuilt from scratch so the field disappears from the reply.

Impact: the charter rule "Don't silently ignore API fields … implement it according to the spec or reject it. Never accept it and quietly drop it (#417)" is violated by the very function introduced to stop that class of bug; a client that sets verbosity believes it changed decoding and receives a response object that disclaims it. Fix: in responses_text_format(), either return Err(unsupported("text.verbosity is not supported")) when present(text, "verbosity"), or echo the accepted value. Add a rejection case next to the existing text cases in protocol/tests.rs (the responses_text_format_validation_echo_and_grammar_exclusion test at tests.rs:3476).

2. Unintended system-level consequences

2.1 No contention, HOL blocking, or unbounded retention (no finding)

Every new field is per-Encoder/per-Decoded request state: responses_tools: Value (encode.rs:156, built once at :175-179, initialised :216), text_format: Option<Value> (encode.rs:217, set once by http.rs:371 before encoder.start()), namespace_description: Option<String> (inference.rs, one per tool). No mutex, channel, queue, task, or shared cache is added or reordered; the scheduler, prefix cache, checkpoint hints and CUDA-graph path are untouched. Lifetimes end with the request, so there is no cross-request retention to grow under load.

2.2 Finding — per-envelope deep copies of the tools array (Minor)

helios/src/server/protocol/encode.rs:824-828:

let text_format = self
    .text_format
    .clone()
    .unwrap_or_else(|| json!({"type": "text"}));
json!({"id":self.id,...,"tool_choice":tool_choice,"tools":self.responses_tools,"text":{"format":text_format}})

Because "tools": self.responses_tools sits inside a json! literal, serde_json::to_value takes it by value through Serialize, i.e. a fresh deep copy of the entire tool array (schemas included) each call. Responses call sites: encode.rs:325 (start, and that value is cloned again at :327-328), encode.rs:736 (finish), encode.rs:837 (failure), plus http.rs:582 for buffered Delivery::Complete — 4 copies per successful request, 5 on a post-start failure. Bounds: request body limit max_body_bytes 32 MiB default, capped at 256 MiB (server.rs:141, :276), so worst case is tens of MB per in-flight request; never per SSE token delta (chunk()/item() do not call response()); no I/O or lock inside. Impact: avoidable CPU/allocator pressure only on very large tool sets; not a correctness or scaling hazard. Fix: store Arc<Value> (or emit a small Value::Object once and Arc::clone it into each envelope), and let start() build the frame bodies without the extra :327-328 clone. Severity Minor — this is a cleanup, not a reason to hold the PR.

2.3 Partial-failure / blast-radius — unchanged (no finding)

Encoder::failure() (encode.rs:832-840) mutates only its own freshly built response object (response["status"]="failed"), so a failed response can no longer disagree with a peer, and the new echo fields are read-only copies of request state — one failing request cannot poison another. Cancellation paths (Delivery::Complete at http.rs:582) use the same immutable snapshot.

3. Architecture, contracts & charter compliance

3.1 Finding — tools/tool_choice self-inconsistency for namespaced tools (Major, with the caveat below)

New tools echo, helios/src/server/protocol/encode.rs:39-48 and :60-70:

json!({
    "type": "function",
    "name": tool.name,
...
if let Some(ns) = tool.namespace.as_deref() {
    ...
        out.push(json!({
            "type": "namespace",
            "name": ns,
            "description": tool.namespace_description.as_deref().unwrap_or(""),
            "tools": [entry],
        }));

Existing tool_choice echo, helios/src/server/protocol/encode.rs:819-822:

ToolChoice::Named(name) => json!({
    "type": if self.tool(name).is_some_and(|tool| tool.custom) { "custom" } else { "function" },
    "name": name,
}),

name here can only be the flattened form: decode stores it verbatim (decode.rs:855-860, ToolChoice::Named(field(v, "name")?.into())) and Request::validate requires it to equal Tool::native_name():

if let ToolChoice::Named(name) = &self.tool_choice {
    if !names.contains(name) { return Err(format!("selected tool {name:?} is not declared in tools").into()); }
}

(helios/src/server/inference.rs:193-197, with native_name() = format!("{ns}__{}", self.name) at inference.rs:84-89.) So a namespaced request can return response.tools = [{"type":"namespace","name":"db","tools":[{"type":"function","name":"query"}]}] together with response.tool_choice = {"type":"function","name":"db__query"} — the selected name is unresolvable inside the response's own tools array, which is precisely the cross-field consistency the PR sets out to establish ("clients … read tools … to confirm active tool declarations"). The new test asserts the flattened echo rather than resolving it against tools: protocol/tests.rs:3279-3282 feeds json!({"type": "function", "name": "db__query"}) as both input and expected echo.

Caveat for adjudication (recorded honestly): on main response.tools was hardcoded [], so the flattened tool_choice was equally unresolvable; the mismatch is not introduced by the flattening rule, and docs/api.md:548-550 ("namespaced tools use namespace__name") documents the model-facing name. The regression is therefore about degree — #638 makes tools truthful and thereby exposes the inconsistency — and it is fixable in three lines. If reviewers prefer, grade it Minor-with-follow-up rather than a merge blocker.

Impact: any validating client (the stated audience) cannot resolve tool_choice against response.tools; an OpenAI-shaped client that sends its own {"type":"function","name":"query"} plus a namespace reference still gets a name it never sent, so echo fidelity for namespaced selections is imperfect in both directions. Fix: in the ToolChoice::Named arm, look the tool up (self.tool(name)) and emit the namespaced shape when tool.namespace.is_some() — e.g. {"type":"function","name":"query","namespace":"db"} (or the nested namespace object form) — keeping the flattened form for standalone tools so existing clients are unaffected. Add an assertion in tests.rs:3126/3476 that every echoed tool_choice name resolves inside the echoed tools. Update docs/api.md:747-752.

3.2 Findly overstated echo fidelity — always-emitted strict and null parameters (Minor)

encode.rs:42-47 always emits "strict": tool.strict and "parameters": null when the client declared no schema. Well-formed, and Request::validate rejects strict without a declared schema (inference.rs:183-187), so no contradictory pair is possible — but the echo is semantic, not byte-faithful, and docs/api.md:747-752 ("echo the request's declared tools") reads stronger than what is emitted. Fix (docs only): say that strict and parameters are normalized on echo, and that empty tool descriptions are omitted while namespace entries always carry "description": "" (encode.rs:50-52 vs :68).

3.3 Finding — new text.format rejections and the prompt-rendering change are undocumented (Minor)

docs/api.md:747-752 documents only:

Response objects in buffered responses and SSE lifecycle events echo the
request's declared `tools` and `text.format` (defaulting to `{"type":"text"}`
when `text.format` is omitted or `null`). `function_call_output` and
`custom_tool_call_output` items honor an optional boolean `is_error` flag

Undocumented, though newly enforced/admitted: non-object text/text.format (decode.rs:471-480), text.format.schema absent or not object/boolean (:487-491), invalid optional name/description (:493-498), non-boolean strict (:499-501), unsupported format types (:504), grammar combined with an explicit text.format (mutual exclusion) — and a non-boolean is_error 400. Separately, the prompt-rendering change for empty namespace descriptions (prepend now .filter(|s| !s.is_empty()) in request::template_inputs) is disclosed in the PR body only. docs/api.md:579-582 covers namespace naming/echo but says nothing about prompt rendering. Impact: the API spec is the contract users and agent clients read; a 400 with no documented cause is a support burden, and a silent prompt change is invisible to anyone reading the docs. Fix: add the rejection list next to :747-752 and one sentence at :579-582 about namespace descriptions being prepended to tool descriptions only when non-empty.

3.4 Charter / layering compliance — strong (no finding)

No protobuf, core format, captured-graph op contract, cache layout, scheduler, route table (server.rs:585) or per-model branch is touched; all logic lives in the shared protocol layer plus request::template_inputs, which is exactly the "solve it in the right layer" rule. No new flag, alias, or magic default. No performance claim is made, so the #210 benchmark gate does not apply. The change is squarely a #417-style "implement or reject" fix.

4. Tests & claim accuracy

4.1 Finding — headline served-SDK contract has zero served-path coverage, and no CI for this head (Major for the evidence section)

New coverage is entirely Rust CPU: protocol/tests.rs:3126 (echo/round-trip), :3476 (text.format validation), :3677 (is_error decode), decode.rs:2277 (is_error across prompt encoders), http.rs:706-720 (get_responses_returns_bad_request_with_http_json_and_sse_guidance), runtime/phase_tests.rs:4703 (http::generate lifecycle echo). tests/server/test_protocols.py — the served-SDK suite — contains no assertion on response.tools, response.text.format, or is_error; its tool mentions only pass tools in requests. The body itself lists SDK deserialisation as "Expected but unmeasured against a live server", and the only evidence offered is local aarch64 CPU runs (1,816 helios / 245 flare / 227 flare-cli, no Python suite). No CI result for head 7ba8c66 appears in the PR. Impact: the claim "clients read tools and text.format from returned response objects" is the PR's whole purpose and is untested where it matters; an SDK-shaped regression (e.g. finding 3.1/3.2) would ship undetected. Fix: add one Responses test in tests/server/test_protocols.py that sends tools + text.format and asserts the echoed tools/text.format plus is_error: true round-trip; attach a CI run link for this head.

4.2 Claim accuracy vs the diff — accurate except as noted

Verified statement-by-statement: precompute in Encoder::new (encode.rs:175-179, init :216), single response built and cloned in start() (:324-330), single-pass responses_text_format (decode.rs:466-506) consumed once in options() (decode.rs:552-558), text_format: None at construction (encode.rs:217) with {"type":"text"} materialised once (:824-827), is_error via flag(...) (decode.rs:343), duplicate-namespace 400 (decode.rs:904-906), GET guidance text and route (http.rs, docs/api.md:230-232). The "1,816 helios passed" style counts are local and unverified by CI; the only overstated prose is "echo the request's declared tools" (§3.2) and the claim that echoing makes active tool declarations confirmable for namespaced selections (§3.1).


Open questions

  1. Does the 12:28Z Changes Requested review's blocker (red CI on the previous head) count as satisfied by the #624 rebase alone, given no CI result exists for 7ba8c66 and no Python suite was run locally?
  2. Should the namespaced tool_choice echo be de-flattened in this PR (finding 3.1), or documented as the intentional model-facing name and deferred?
  3. Should the text.format/is_error rejection list and the namespace prompt-rendering rule be added to docs/api.md before merge (findings 3.3/3.2)?
  4. Should tests/server/test_protocols.py gain the three assertions above, since the served-SDK contract is the point of the change?

What could not be found