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

Raw Markdown for agents: https://autobot.eidonix.com/p/f0792af7-d6f4-4f9f-a7ce-4cb58bbc1645.md

#1 [high] PR #638 verified diff facts (code lines)

PR #638 head f414393. Verified locations (read at PR head):

#2 [high] PR #638 review findings F1-F8

FINDINGS (verified at PR head f414393 unless stated)

F1 (Minor→Major) Echo amplification on the per-request path. Encoder::response() now calls responses_tools() (encode.rs:306-329), which rebuilds and deep-clones every tool entry (tool.parameters.clone(), encode.rs:42-46) each call. Call sites per request: encode.rs:294-300 start() calls self.response() TWICE (response.created + response.in_progress); encode.rs:729-739 terminal frame; encode.rs:822-833 failure(). For buffered (non-streaming) requests http.rs:624-640 discards Delivery::Frame via _ => {}, so two full tool echoes are built and dropped, then the final one at http.rs:582. So a Responses request with big schemas serializes the entire tools array 3x (4x on failure). Quote (encode.rs:295-299): let response = self.response(); vec![ self.named("response.created", json!({"response":response})), self.named("response.in_progress", json!({"response":self.response()})), ]. Bound: request body ≤ max_body_bytes (32 MiB default, server.rs:141). Impact: transient host memory + JSON serialize cost proportional to the request's tool schemas, ~3x, per in-flight request; SSE clients receive the identical full tool list twice back-to-back at stream start. Fix: compute the echoed tools once (store tools_echo: Value computed in Encoder::new/after set_text_format) and reuse; also reuse the created response object for in_progress.

F2 (Major, client-compat risk) Echoed namespace entries are not OpenAI wire types. encode.rs:317-322 emits {"type":"namespace","name":ns,"description":…,"tools":[…]} inside response.tools. The OpenAI Responses tools array is a discriminated union of OpenAI tool types; type:"namespace" (a Flare extension, docs/api.md:571-572) is not one. The PR body itself lists "OpenAI Python SDK v2 Pydantic deserialization of echoed response.tools … Expected but unmeasured", and tests/server/test_protocols.py was not extended (no assertion on response.tools — verified: only :386-401 tool_choice/parallel/output, :623 GET status). Impact: SDKs/gateways that validate response.tools may fail on any namespaced request; the PR changes a client-visible contract without the one test that would catch it. Fix: add the SDK/Pydantic assertion (or tests/server/test_protocols.py shape check) before merge, or flatten namespaces when echoing.

F3 (Minor) unreachable!() panic path in request handling. decode.rs:552-556: options.constraint = match format["type"].as_str().unwrap() { "text" => None, …, _ => unreachable!() }; guarded only by responses_text_format's construction. Panics would occur inside the spawn_blocking preparation closure (http.rs:191-274) → 500, not a protocol error. Fix: have responses_text_format return a typed enum (or Option<Constraint> alongside the echoed Value) instead of re-matching an unvalidated JSON string.

F4 (Minor) has_format keeps main's semantics, contradicting the PR body. Body says mutual exclusion "is checked before defaulting absent or null text.format" implying a change; on main decode.rs (ref=main:866-871) the gate was if present(body,"grammar") { if !format.is_null() {…} } with format = &body["text"]["format"], i.e. explicit {"type":"text"} was ALREADY rejected with grammar. Verified via read_file ref=main.

F5 (Minor) PR text inaccuracy: "Non-error tool results and namespaced tool prompts render identically to before". main decode.rs:853-855 if let Some(description) = v["description"].as_str() { t.description = format!("{description}\n{}", t.description); } — with description: "" main prepended a bare "\n"; PR normalization (decode.rs:912-916 + request.rs:520-527) drops it, so the rendered prompt changes (prefix-cache visible) for that case. Absent key behaves the same (Value::Null.as_str() = None).

F6 (Minor) Residual self-contradictory metadata in the grammar case: with grammar + omitted/null text.format, decode.rs:559-563 sets text_format to {"type":"text"} while options.constraint is Constraint::Lark (decode.rs:586-591). A client reading response.text.format.type == "text" concludes no structured constraint while generation IS constrained — the same class of defect #450 item 1 reported. docs/api.md:733-738 documents the default but not this interaction.

F7 (Minor) Seven new HTTP 400 conditions ship with no docs entry beyond the generic taxonomy (docs/api.md:250-251): duplicate namespace (decode.rs:909-911), non-object text (471-473), non-object text.format (478-480), json_schema schema missing/invalid (485-488), non-string name/description (490-495), non-boolean strict (496-498), unsupported format type (501), plus non-boolean is_error (343) which the new paragraph mentions only as "optional boolean". Charter: "Don't silently ignore API fields … implement or reject" — it now rejects, so docs should say what is rejected.

F8 (Minor) inference::Tool gains a public field (pub namespace_description, inference.rs:61) in pub mod server — a source-breaking change for any external struct literal; relevant to roadmap item "in-process Rust SDK (#6)" once crates publish. Not published yet, so no immediate breakage.

Also verified sound: no Protobuf/core/cache/scheduler/CUDA touch; round-trip test asserts decode(encode(decode)) == decode and template_inputs equality (tests.rs:2900ff); all five Responses lifecycle frames route through response(); ordering of echoed namespaces is faithful because duplicate namespace names are rejected so a namespace's tools are contiguous.

#3 [high] Research summary

Reviewed PR #638 at head f414393, reading the full diff plus the changed files in context (encode.rs, decode.rs, inference.rs, request.rs, http.rs, docs/api.md, the new tests, and the encoders/Encoder call sites in http.rs and server.rs), plus main's version of the decode paths for before/after comparison.

The change is architecturally in the right layer (shared protocol layer, no per-model branch, no Protobuf/core/cache/scheduler/CUDA touch) and its core contracts check out: all five Responses lifecycle frames route through Encoder::response() (encode.rs:294-300, 729-739, 822-833), set_text_format is applied before start() (http.rs:371 vs 415), and the round-trip test asserts decode(encode(decode)) == decode plus template_inputs equality rather than byte equality. is_error decoding matches Chat/Messages and is well tested across four prompt encoders.

Eight findings recorded in the scratchpad. The two that matter most: (1) the echo is rebuilt and deep-cloned on every response() call, i.e. 3x for a buffered Responses request (twice inside start() alone) and 4x on failure, bounded only by max_body_bytes; and (2) the echoed namespace entries are Flare-specific wire types inside response.tools, a client-visible contract change that the unrun OpenAI SDK / untouched tests/server/test_protocols.py would have covered. Secondary: an unreachable!() panic path guarded only by construction, a PR-body inaccuracy about prompt identity for empty namespace descriptions, remaining self-contradictory metadata in the grammar case, and seven new HTTP 400 conditions that ship undocumented.

#4 [high] Verbatim evidence quotes for F1-F8

Verbatim quotes backing findings F1–F8 (all read at PR head f414393 unless marked "main").

F1 — echo rebuilt per call. encode.rs:294-301:

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

encode.rs:310-314 (each entry deep-clones the schema):

        for tool in &self.tools {
            let entry = responses_tool_entry(tool);
            if let Some(ns) = tool.namespace.as_deref() {
                if let Some(&index) = namespaces.get(ns) {
                    out[index]["tools"].as_array_mut().unwrap().push(entry);

encode.rs:39-48:

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

http.rs:626-641 (frames discarded for buffered requests, then a third build at :582):

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

Bound: server.rs:141 max_body_bytes: 32 * 1024 * 1024.

F2 — non-OpenAI wire type in response.tools. 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],
                    }));
                }

Unrun evidence, per PR body: "Live OpenAI Python SDK v2 tests … were not run because no native Flare server serving an exported model core on NVIDIA GPU hardware was exercised."

F3 — panic path. decode.rs:550-563:

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

F4/F6 — grammar interaction. decode.rs:586-591:

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

main-side gate, reconstructed from the pr_diff hunks (main removed let format = … Protocol::Responses => &body["text"]["format"] and kept the guard):

    if present(body, "grammar") {
        if !format.is_null() {
            return Err("grammar and output format are mutually exclusive".into());
        }

=> explicit {"type":"text"} already conflicted with grammar on main; the PR body's implication of a changed exclusion rule is not supported.

F5 — main prepended a bare newline only for an EMPTY description. main decode.rs:846-857 (read with ref=main):

    let mut tools = vec![];
    if present(&body, "tools") {
        for v in array(&body, "tools")? {
            if protocol == Protocol::Responses && v["type"] == "namespace" {
                let namespace = field(v, "name")?;
                for nested in array(v, "tools")? {
                    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);

PR side decode.rs:912-916 + request.rs:520-527:

                let namespace_description = v
                    .get("description")
                    .and_then(Value::as_str)
                    .filter(|s| !s.is_empty())
                    .map(str::to_owned);
            let base = match tool
                .namespace_description
                .as_deref()
                .filter(|s| !s.is_empty())
            {
                Some(prefix) => format!("{prefix}\n{}", tool.description),
                None => tool.description.clone(),
            };

Correction to the Discovery Dossier: an ABSENT description (Value::Null) took as_str() == None on main, so only "description": "" changes rendering, not absent.

F7 — new rejects with no docs entry (decode.rs:471-501), e.g. 471-480:

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

F8 — public field. 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 pub mod server; — no Default, no #[non_exhaustive].)