Code correctness report · NVIDIA/hyperflare-inference #685

Raw Markdown for agents: https://autobot.eidonix.com/p/ce181177-928b-4d44-a225-8db10cd965f5.md

Deep Code Correctness, Invariants & Hot-Path Performance Audit — PR #685 @ 826a427

Scope/partitioning: 7 files, ~871 net changed lines, single crate (helios). Below the >12-file / >900-line multi-crate threshold, so audited directly (no sub-agents).

Verdict: the PR's core streaming invariants are correct. I found one Major hot-path defect (O(N²) delta coalescing, newly reachable because of this PR) and one Minor cross-protocol inconsistency (Anthropic Messages renders a truncated DSSM call as a completed zero-input tool_use block). The remaining mechanical checks pass; details of what I verified and why it is sound are at the end.


Finding 1 — Major (hot path): per-fragment publishing turns Accumulator::apply into O(N²) coalescing on the Chat wire

Diff site: helios/src/output/dsml.rs:173-193 (new publish on every argument-text action) and helios/src/output/dsml.rs:53-62 (Call::publish). Callee: helios/src/server/output.rs:113-141.

// helios/src/output/dsml.rs:53-62
fn publish(&mut self, index: usize, events: &mut Vec<Event>) {
    if self.literal.is_some() || self.published_argument_bytes == self.arguments.len() {
        return;
    }
    events.push(Event::ToolArguments {
        index,
        text: self.arguments[self.published_argument_bytes..].to_owned(),
    });
    self.published_argument_bytes = self.arguments.len();
}
// helios/src/server/output.rs:113-141
Event::ToolArguments { index, text } => {
    let call = self.calls.get_mut(index).filter(|call| !call.ended)
        .ok_or("tool arguments require an open call")?;
    if call.arguments.len().saturating_add(text.len()) > 8 * 1024 * 1024 { ... }
    call.arguments.push_str(&text);
    if let Some(previous) = deltas.last_mut()
        .and_then(|v| v.get_mut("tool_calls"))
        .and_then(Value::as_array_mut)
        .and_then(|calls| (calls.len() == 1).then(|| &mut calls[0]))
        .filter(|call| call["index"].as_u64() == Some(index as u64))
    {
        let args = previous["function"]["arguments"]
            .as_str().unwrap_or("").to_owned()   // <-- full copy of accumulated text
            + &text;
        previous["function"]["arguments"] = Value::String(args);
    } else { ... }
}

Why this PR makes it a hot-path defect. Before the PR, DsmlOutput::apply emitted exactly one ToolArguments carrying the whole argument object at ToolCallArgumentsEnd (pr_diff removed block: Event::ToolArguments { index, text: call.arguments }). The coalescing branch in Accumulator::apply therefore ran at most once per call — harmless. Now Call::publish pushes a fragment for every ToolCallArgumentsText action, i.e. once per decoded chunk/token of argument text. Each fragment hits the coalescing branch, and each hit does args.to_owned() + &text, a full copy of everything accumulated so far.

Concrete counterexample (matches the PR's own measurement). A write call with a 2.2 KB argument produced 566 frames (PR description). With ~566 fragments and average accumulated length ~1.1 KB:

This is quadratic in the number of published fragments and bounded only by the 8 MiB argument cap, so a single large tool call regresses from O(total bytes) to O(N²) on the hot per-token path. Note the PR description also confirms a multi-kilobyte write argument is the motivating real workload.

Fix (local, keeps the coalescing optimization): make the merge amortized O(1) instead of re-copying — e.g. push a fresh delta value and let the serializer concatenate, or track the index of the last tool-call delta and mutate a Vec<Value>-free buffer; simplest correct form:

if let Some(previous) = /* ...same navigation... */ {
    let slot = &mut previous["function"]["arguments"];
    match slot {
        Value::String(s) => s.push_str(&text),   // in-place, amortized O(1)
        _ => *slot = Value::String(text.to_string()),
    }
} else { /* push new delta */ }

serde_json::Value::String derefs to String, so push_str amortizes to O(1) per fragment and the whole call becomes O(total bytes). (Alternative: have Call::publish coalesce fragments up to a size threshold — but the Accumulator fix also protects the other streaming parsers and is strictly better.)


Finding 2 — Minor (cross-protocol inconsistency / silent wrong behavior): a truncated call becomes a completed zero-argument tool_use block on the Messages wire

Diff site: helios/src/server/protocol/encode.rs:679-707 (new drops_unfinished_call / discard_abandoned gating) with no corresponding Messages handling, contrasted against helios/src/server/protocol/encode.rs:470-491 (Responses is_abandoned → status: "incomplete"). Callee: helios/src/server/protocol/encode.rs:390-404 (anthropic_block), helios/src/server/output.rs:1735-1762.

// helios/src/server/output.rs:1735-1748
pub fn finish(&mut self, cause: Termination) -> Result<Vec<Change>> {
    let mut changes = vec![];
    if drops_unfinished_call(cause)
        && self.open.is_some()
        && matches!(self.blocks.last(), Some(Block::Tool { .. }))
    {
        let last = self.blocks.len() - 1;
        changes.push(Change::End(last));      // Messages -> content_block_stop
        self.abandoned = Some(last);
        self.open = None;
    }
    self.close(&mut changes)?;
    Ok(changes)
}
// helios/src/server/protocol/encode.rs:408-414  (Change::Start, Messages)
(Protocol::Messages, Change::Start(i)) => {
    let block = self.anthropic_block(i, false);   // arguments "" -> input json!({})
    frames.push(self.named("content_block_start",
        json!({"index":i,"content_block":block})));
}
// helios/src/server/protocol/encode.rs:396-403
Block::Tool { id, name, arguments, .. } => { json!({"type":"tool_use","id":id,"name":name,
    "input": if complete { serde_json::from_str::<Value>(arguments).unwrap_or(json!({})) }
             else { json!({}) }}) }

Why it is a defect. ResponseOutput::finish emits Change::End(last) for the abandoned block on all protocols; only Responses consults is_abandoned (encode.rs:471) to downgrade the item to status:"incomplete". For Protocol::Messages the same Change::End is turned into a plain content_block_stop (encode.rs:424-429), and the block itself was announced earlier as content_block_start with input: {}. The block is then popped by discard_abandoned() (encode.rs:702), so self.response()["content"] is empty (encode.rs:833), but the streaming client has already received:

  1. content_block_start with {"type":"tool_use","id":"...","name":"write","input":{}}
  2. any number of input_json_delta fragments (encode.rs:416-423)
  3. content_block_stop — the Anthropic terminal frame for a valid, complete tool_use block

Anthropic clients treat content_block_stop as "this tool_use is complete" and execute it with the accumulated partial-JSON merge; here the merged input is {} (no complete flag ever reaches anthropic_block on the End path, and no partial_json terminator is sent). Contrast the Responses path, which the PR explicitly fixed to report incomplete and to skip the custom-input frames (encode.rs:488-514). So for Messages a UserStop/OutputLimit/Cancelled truncation silently yields an executable write call with empty arguments — the precise class of bug the PR set out to eliminate on Chat/Responses.

The PR description acknowledges only the Responses and Chat contracts; the Messages wire is left with a "completed empty call" semantics that is not documented in docs/api.md either.

Concrete counterexample. Protocol::Messages, DSML parser, stream "<|DSML|tool_calls><|DSML|invoke name=\"write\"><|DSML|parameter name=\"path\" string=\"true\">a.txt", terminated with Termination::UserStop. Emitted: content_block_start {tool_use, input:{}}, content_block_delta {input_json_delta, partial_json:"{\"path\": \"a.txt\""}, content_block_stop. A Messages client merging the deltas issues write({"path": "a.txt"}); a client using the announced input issues write({}). The PR's own test an_announced_call_is_omitted_when_the_response_truncates (helios/src/server/protocol/tests.rs:3842-3930) asserts only that a content_block_stop exists for Messages and never checks that the block is distinguishable from a completed one — so the matrix does not catch this asymmetry.

Fix. Give Messages the same abandonment signal Responses got: either (a) suppress Change::Start/Delta for tool blocks whose arguments are known-incomplete, or (b) tag the content_block_stop path with self.outputs[0].is_abandoned(i) and emit the block's content_block_start-announced input only after completion — at minimum, do not emit a content_block_stop for a block that will be discarded, and extend helios/src/server/protocol/tests.rs to assert response()["content"] and the absence of a terminal content_block_stop for the abandoned Messages block (the current assertion at tests.rs:3921-3928 requires the stop frame, which locks in the wrong behavior).


Verified-clean checks (no defect found)

  1. Call::publish prefix invariant (dsml.rs:53-62). published_argument_bytes only ever advances to arguments.len() inside publish, and close_literal (dsml.rs:65-78) can only rewrite in place the slice starting at literal while literal.is_some() blocks publish. I traced every mutation of arguments: LabelToolCallArguments (dsml.rs:165 push_str, sets literal = Some(len) for KeyValueSeparator), ToolCallArgumentsText (dsml.rs:180/189 push_str then check_size then publish), and ToolCallArgumentsEnd (dsml.rs:200 push_str(closing_text)). Hence published_argument_bytes ≤ literal_start always, so live = arguments[published..] never contains a byte that close_literal can replace — the "no published byte is replaced" claim holds. The string="false" path is safe because LabelToolCallArguments(ArgumentSeparator) calls close_literal() before appending the separator (dsml.rs:162-165), and ToolCallArgumentsEnd calls it before closing_text (dsml.rs:199-200); in both cases publish is then invoked with literal == None, so the retained text ships exactly once.

  2. End-before-begin ordering (dsml.rs:145-206). ToolBegin is now pushed at ToolNameEnd guarded by !repeated; ToolEnd at ToolCallArgumentsEnd also !repeated; self.calls is incremented exactly once, after the end event, so Event::ToolBegin{index} / ToolArguments{index} / ToolEnd{index} stay consistently indexed. A repeated ToolCallArgumentsEnd action falls through to _ => {} and cannot double-publish. ToolCallArgumentsEnd takes the call (self.call.take()), so check_size at dsml.rs:218-220 cannot see a stale call.

  3. check_size moved before/after publication (dsml.rs:191-192 vs docs/api.md:571-575). check_size runs before publish on the text path, so the fragment that crosses the 1 MiB bound is never published and the call can never complete (self.call stays Some, so a later ToolCallArgumentsEnd re-checks). The documented "bound is enforced on the append that crosses it, after the call name and earlier fragments were published and are not retracted" is accurate. name.len().saturating_add(arguments.len()) at dsml.rs:43 cannot overflow.

  4. drops_unfinished_call(cause) == cause != Termination::Eos (output.rs:479-481). Termination (helios/src/output.rs:51-58) has exactly five variants — Eos, OutputLimit, UserStop, Cancelled, ExecutionError. No variant is semantically an outlier that a != test misclassifies: only Eos means "the model finished naturally", so the predicate is total and non-degenerate (not always-true/always-false). Cross-checked against the parser's own Eos handling: DsmlOutput::finish (dsml.rs:376-395) errors on Eos inside an announced call and clears self.call for Cancelled|ExecutionError, so Accumulator::finish's "incomplete emitted tool call" error (output.rs:163-168) remains reachable only on the genuinely-illegal path — the pre-PR contract is preserved exactly as claimed.

  5. Abandoned-index bookkeeping (output.rs:1735-1762, encode.rs:687-707). finish only marks abandoned when self.open.is_some() and the last block is a Block::Tool; ToolBegin (output.rs:1811-1822) calls close first and always pushes at blocks.len(), so an open tool block is always last → last == self.open and Change::End(last) matches; discard_abandoned then pops exactly that block and its calls entry, so has_tools() (output.rs:1710-1712) afterwards reflects only completed calls and the Required | Named check at encode.rs:708-712 fails correctly (verified by the new test at tests.rs:4194-4231). The abandoned |= truncated + incomplete_item = None reset at encode.rs:698-707 correctly scopes the marker to the discarded item so a later completed item is not mislabeled incomplete; self.incomplete_item = Some(*i) before change(change) is required because item() reads it (encode.rs:340).

  6. Custom-tool truncation (encode.rs:470-517). abandoned && custom skips serde_json::from_str and grammar.validate, and item(i, false) yields input: "" with status: "incomplete"; the !abandoned guard suppresses custom_tool_call_input.delta/.done. Confirmed against item() (encode.rs:366-379). No partial input leaks.

  7. Strict-tool parking unchanged (encode.rs:571-631). Event::ToolBegin for a strict tool still continues into pending_strict_calls[index] before any ResponseOutput/Accumulator mutation, and arguments are re-emitted only after strict_validators[..].validate(&arguments) succeeds — so no frame precedes schema acceptance. This matches the PR claim.

  8. Test-side consistency. helios/tests/deepseek_output.rs:501-516 and :581-595 were correctly weakened from "no events published" to "no ToolEnd reported" (parsed.ended == 0), which is the only property that still holds now that ToolBegin/ToolArguments publish early; the rejection assertions at :514 still pin the error text. helios/tests/deepseek_requests.rs:684-693 similarly concatenates fragments instead of requiring one whole-argument event. Both are correct adaptations, not weakened coverage of the new contract.

No numerical/median/comparator defects apply: the diff introduces no rate, median, EMA, eviction-priority or comparator logic; the only new arithmetic is self.blocks.len() - 1 (guarded by self.open.is_some(), so the vec is non-empty) and the existing saturating_add size checks. No integer overflow or 1e305-style NaN path exists in the changed code.

Not reported (out of scope per instructions): documentation wording, the PR-description's open questions to #364's author/reviewer, and CI-bookkeeping.