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

Raw Markdown for agents: https://autobot.eidonix.com/p/6ed3fbef-681b-439f-8c5e-788d41193a05.md

Correctness, Contracts & System-Level Consequences — PR #638 (f414393)

Key findings

  1. Major — the tools echo is rebuilt and deep-cloned on every response() call, at least 3× per buffered Responses request. Encoder::response() now calls responses_tools() (encode.rs:306-329), which re-serializes and clone()s every tool schema (encode.rs:42-46); start() calls response() twice (encode.rs:294-300) and the buffered path discards both frames (http.rs:626-641) before building a third at http.rs:582. Bounded only by max_body_bytes (32 MiB).
  2. Major — response.tools now carries a non-OpenAI wire type. Namespaced tools echo as {"type":"namespace", …} (encode.rs:317-322), a Flare extension (docs/api.md:571-572) inside a field the OpenAI Responses schema defines as a discriminated union of OpenAI tool types. The only evidence that would settle it — SDK v2 Pydantic deserialization — is declared unmeasured by the PR body, and tests/server/test_protocols.py was not extended.
  3. Minor — an unreachable!() panic path on request handling (decode.rs:552-556) is guarded only by responses_text_format()'s construction, not by a type.
  4. Minor — residual self-contradictory metadata in the grammar case (decode.rs:559-563 vs 586-591): generation is Lark-constrained while response.text.format says {"type":"text"} — the same defect class #450 item 1 reported.
  5. Minor — seven new HTTP 400 conditions ship with no docs/api.md entry.
  6. Minor — PR-body inaccuracy: "namespaced tool prompts render identically to before" is false for "description": "" (main prepended a bare "\n").

Areas that are sound are listed at the end, including two corrections to the Discovery Dossier.


1. Correctness, safety and platform parity

F3 — unreachable!() panic guarded only by convention — Minor

helios/src/server/protocol/decode.rs:549-563:

    let (has_format, text_format) = if protocol == Protocol::Responses {
        let responses_format = responses_text_format(body)?;
        if let Some(format) = &responses_format {
            options.constraint = match format["type"].as_str().unwrap() {
                "text" => None,
                "json_object" => Some(Constraint::JsonObject),
                "json_schema" => Some(Constraint::Json(format["schema"].clone())),
                _ => unreachable!(),
            };
        }

responses_text_format() validates and constructs format, so today the arm is unreachable — but the invariant is cross-function and unwritten, and the .unwrap() plus unreachable!() sit on the request path. Any future edit to responses_text_format() (adding a format type, changing the echoed shape) turns a client request into a panic. Panics inside request preparation are not protocol errors: they surface as an aborted task/500 rather than the 400 the PR is deliberately adding everywhere else.

Fix: have responses_text_format() return the constraint alongside the echoed value, e.g. Result<Option<(Constraint, Value)>> or a small enum ResponsesFormat::{Text, JsonObject, JsonSchema(Value)} that options() matches exhaustively by type — eliminating both the .unwrap() and the unreachable!().

F8 — inference::Tool gains a public field in a public module — Minor

helios/src/server/inference.rs:57-62:

#[derive(Clone, Debug, PartialEq)]
pub struct Tool {
    pub name: String,
    pub namespace: Option<String>,
    pub namespace_description: Option<String>,

helios/src/lib.rs:30 exposes pub mod server;. The struct has no Default and no #[non_exhaustive], so any downstream struct literal breaks at compile time. Nothing is published yet, so there is no immediate breakage, but it is a source-breaking change on the surface the roadmap says will be published as the in-process Rust SDK (#6). Fix: if the field is not meant to be constructed by SDK users, mark Tool #[non_exhaustive] now (cheap, before publication) or add a constructor that defaults namespace_description: None.

No platform/parity concerns

Nothing in the diff is OS-conditional: no path handling, no Unix-vs-Windows branch, no filesystem or process call. The HashMap used for namespace grouping (encode.rs:308-309) is only ever probed/inserted with &str keys already owned by self.tools; ordering of output is driven by out.push order, not by iteration order, so no hash-order nondeterminism reaches the wire. Race conditions: Encoder is per-request and mutated only by the single task draining delivery, and set_text_format happens at http.rs:371 before encoder.start() at the streaming path — no shared mutable state added.


2. Unintended system-level consequences

F1 — Echo amplification: 3× (4× on failure) full tool-array serialization per Responses request — Major

Encoder::response() is on three frame-construction paths per request, and the Responses start path calls it twice:

helios/src/server/protocol/encode.rs:294-300:

            Protocol::Responses => {
                let response = self.response();
                vec![
                    self.named("response.created", json!({"response":response})),
                    self.named("response.in_progress", json!({"response":self.response()})),
                ]

Each call re-runs responses_tools() (encode.rs:306-329), which deep-clones every declared schema:

helios/src/server/protocol/encode.rs:39-48:

        json!({
            "type": "function",
            "name": tool.name,
            "parameters": if tool.declared_parameters {
                tool.parameters.clone()
            } else {
                Value::Null
            },
            "strict": tool.strict,
        })

and the terminal/failed frames do it again — encode.rs:818 ("tools":self.responses_tools()), encode.rs:827 (let mut response = self.response(); for response.failed), plus response.completed/response.incomplete at encode.rs:725 and 730.

For buffered (non-streaming) Responses requests the two start() frames are built and thrown away — helios/src/server/http.rs:626-641:

        while let Some(event) = delivery.next().await {
            match event {
                Delivery::Complete(body) => {
...
                Delivery::Failed(e, _) => return rejection(&state, protocol, &id, "generation", e),
                _ => {}

— and a third full echo is built at http.rs:582 (let mut response = encoder.response();). A failing buffered request costs four.

Impact: for the workload this endpoint targets (agent clients declaring many JSON-schema tools), every Responses request transiently allocates and serde-serializes the entire tool array 3-4×, on the Tokio worker thread that drives Encoder, and every SSE client receives the identical full tool list twice back-to-back at stream open (response.created and response.in_progress are byte-identical except for status). Magnitude is bounded by max_body_bytes (32 MiB default, helios/src/server/server.rs:141 (not opened)), so this is not unbounded retention, but it is genuine per-request memory amplification and CPU on a path that previously serialized two literal constants. It also scales with concurrency rather than with request rate alone.

Fix (concrete): compute the echo once and store it. Add tools_echo: Value (and keep text_format) to Encoder, fill it in a set_text_format-style setter or lazily on first response() call (the tool set is immutable after Encoder::new), and have response() emit self.tools_echo.clone() — or better, build the created object once in start() and reuse it: let response = self.response(); vec![… created(response.clone()), … in_progress(mark_status(response)) …]. That alone removes two of the three rebuilds; a tools_echo cache removes the third's re-serialization cost.

Failure blast radius, cache/disk I/O, hot-path deltas — no issue found


3. Architecture, contracts and charter compliance

F2 — response.tools echoes a Flare-only wire type; the contract change is unvalidated — Major

helios/src/server/protocol/encode.rs:312-323:

            if let Some(ns) = tool.namespace.as_deref() {
                if let Some(&index) = namespaces.get(ns) {
                    out[index]["tools"].as_array_mut().unwrap().push(entry);
                } else {
                    namespaces.insert(ns, out.len());
                    out.push(json!({
                        "type": "namespace",
                        "name": ns,
                        "description": tool.namespace_description.as_deref().unwrap_or(""),
                        "tools": [entry],
                    }));

Namespaces are a Flare extension, documented at docs/api.md:571-572:

Responses namespaces become unique `namespace__name` names in the model template
and regain their namespace on output; ambiguous names are rejected.

On main the extension was invisible in response.tools because the field was the literal "tools":[]. After this PR, every namespaced request returns {"type":"namespace"} entries inside a field the OpenAI Responses schema defines as a discriminated union of OpenAI tool types (function / custom / web_search / file_search / …). A Pydantic-SDK or gateway client that validates response.tools will reject a payload that main accepted.

The PR body itself concedes the evidence is absent: "Expected but unmeasured against a live server: OpenAI Python SDK v2 Pydantic deserialization of echoed response.tools and response.text." And the in-repo suite that would catch it was not extended — tests/server/test_protocols.py still asserts only tool_choice/parallel_tool_calls/output items (:386-401) and the GET status (:623), with no response.tools or response.text assertion.

Impact: the PR fixes a contract defect (wrong echo) by introducing a different, potentially-incompatible one on the namespaced subset, and merges a client-visible wire-shape change with zero end-to-end coverage. Fix (either): (a) flatten namespaced tools into their namespace__name function/custom entries when echoing, keeping namespace purely a template-side concern — response.tools then stays inside the OpenAI union and round-trip fidelity is preserved by the echoed name; or (b) if the namespace grouping must be echoed, add the assertion to tests/server/test_protocols.py (a shape check and, if available, an SDK deserialization check) and document in docs/api.md:733-738 that response.tools may contain Flare-extension namespace entries.

F6 — Echoed text.format still misreports active structured-output constraints in the grammar case — Minor

helios/src/server/protocol/decode.rs:559-563 and :586-591:

        let has_format = responses_format.is_some();
        (
            has_format,
            responses_format.unwrap_or_else(|| json!({"type": "text"})),
        )
...
    if present(body, "grammar") {
        if has_format {
            return Err("grammar and output format are mutually exclusive".into());
        }
        options.constraint = Some(Constraint::Lark(field(body, "grammar")?.into()));
    }

With grammar plus omitted-or-null text.format, has_format is false, the Lark constraint is installed, and text_format defaults to {"type":"text"}. The client then reads response.text.format.type == "text" — i.e. "no structured constraint" — while generation is grammar-constrained. That is precisely the class of contradiction #450 item 1 was filed about ("emitting self-contradictory metadata and misreporting active structured-output constraints"). docs/api.md:733-738 documents the default but not how it interacts with grammar.

Fix: when grammar is present and text.format is absent/null, echo the grammar as the active format (e.g. {"type":"grammar","syntax":"lark","definition":…} alongside the existing text default, or set text.format to a grammar object) and add one sentence to docs/api.md:733-738. At minimum document the interaction.

Undocumented rejections — F7 — Minor

Seven new HTTP 400 conditions have no entry beyond the generic taxonomy at docs/api.md:242-259, while the PR simultaneously claims to specify these contracts in docs. helios/src/server/protocol/decode.rs:471-501:

    if !text.is_object() {
        return Err("text must be a JSON object".into());
    }
    if !present(text, "format") {
        return Ok(None);
    }
    let format = &text["format"];
    if !format.is_object() {
        return Err("text.format must be a JSON object".into());
    }

Enumerated from the diff: duplicate namespace name (decode.rs:909-911), non-object text (471-473), non-object text.format (478-480), json_schema with absent/non-object-or-boolean schema (485-488), non-string name/description (490-495), non-boolean strict (496-498), unsupported format type (501), plus non-boolean is_error (decode.rs:343), which the new paragraph mentions only as "an optional boolean is_error flag" without stating it is type-checked.

Impact: previously-accepted requests now 400 with no documented rule (notably duplicate namespaces and json_schema.schema shape — on main the latter failed later, inside grammar compilation, with a different error). The charter's rule this PR is implementing ("either implement it according to the spec or reject it, never quietly drop it") is best served by documenting what is rejected. Fix: add 3-4 lines to docs/api.md next to the tools/namespace paragraph (:571-572) and the echo paragraph (:733-738): duplicate namespace names → 400; text/text.format must be objects; json_schema.schema must be an object or boolean; name/description strings; strict/is_error booleans.

Charter/architecture fit — compliant


4. Tests and claim accuracy

F5 — "namespaced tool prompts render identically to before" is inaccurate for "description": "" — Minor

main's loop (read at ref=main, helios/src/server/protocol/decode.rs:846-857) prepended unconditionally whenever the description was a string:

                    let mut t = tool(nested, protocol, Some(namespace))?;
                    if let Some(description) = v["description"].as_str() {
                        t.description = format!("{description}\n{}", t.description);
                    }
                    tools.push(t);

The PR filters empty to None (decode.rs:912-916) and prepends only when non-empty in helios/src/server/request.rs:520-527:

            let base = match tool
                .namespace_description
                .as_deref()
                .filter(|s| !s.is_empty())
            {
                Some(prefix) => format!("{prefix}\n{}", tool.description),
                None => tool.description.clone(),
            };

So for a client sending {"type":"namespace","name":"x","description":"","tools":[…]} the rendered tool description loses main's leading "\n" — a token-visible, prefix-cache-visible change for long-lived agent clients that the PR body explicitly denies ("Non-error tool results and namespaced tool prompts render identically to before").

Dossier correction: the Discovery Dossier (Key finding 2) says "empty or absent namespace description prepended a bare "\n"". Only the empty-string case does; an absent key is Value::Null, as_str() returns None on main, and no prepend happened. The before/after divergence is therefore narrower than the dossier states.

The PR's own round-trip test asserts the right invariant (decode(encode(decode)) == decode and template_inputs equality), not prompt identity with main, so no test catches this. Fix: either restore the "\n" for the empty-string case (preserving prompt identity), or correct the PR body to say prompts change only for explicitly-empty namespace descriptions and note it as intentional.

F4 — the PR body implies a mutual-exclusion rule change that did not happen — Minor

Body: "Mutual exclusion against top-level grammar is checked before defaulting absent or null text.format." On main the gate was if present(body,"grammar") { if !format.is_null() { return Err(…) } } with format = &body["text"]["format"] — i.e. an explicit {"type":"text"} already conflicted with grammar. The new has_format (decode.rs:559, 586-591) preserves that exactly. The sentence describes the new structure accurately but reads as a behaviour change; it is not one. Low impact, worth tightening so reviewers do not hunt for a semantic delta.

Imagined-versus-real test gaps


What is sound (stated plainly)


Open questions

  1. Why is CI failed on f414393 while the body reports 1,805/245/227 passing? Same head, so one of the two describes a different environment or a flake; the body never addresses it.
  2. Should the echo be byte-faithful or only semantically faithful to the request? strict is echoed even when omitted, empty description is dropped on tool entries (encode.rs:50-52) yet echoed as "" on namespace entries (encode.rs:320), and custom format is reconstructed from the stored grammar (encode.rs:25-32). The tests assume semantic equivalence; docs/api.md does not say which.
  3. Must response.tools remain inside the OpenAI union (i.e. flatten namespaces when echoing), or is a documented Flare-extension namespace entry acceptable? This decides F2's fix.
  4. Does the empty-string namespace-description prompt change need to be preserved for prefix-cache stability, or accepted and documented (F5)?

What could not be found