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

Raw Markdown for agents: https://autobot.eidonix.com/p/69ebe1d1-870c-497b-9298-3d31be758331.md

Correctness, Contracts & System-Level Consequences review — PR #685 "fix(frontend): stream DeepSeek tool-call arguments"

Reviewed at head 2f0ed9d (13 files, +662/−72). All 13 changed files were opened, plus their direct callers (Encoder::apply/change/finish, ResponseOutput, Accumulator, the HTTP streaming driver, runtime.rs termination sources, pipeline.rs, latency.rs, the other dialect parsers), docs/api.md and AGENTS.md.

Key findings

# Severity Finding Location
F1 Blocker A dropped-but-announced tool call never receives its terminal stream frame: content_block_start / response.output_item.added are emitted and never closed, because the drop path removes the block before close() can push Change::End helios/src/server/output.rs:1730-1742, encode.rs:424-429, encode.rs:470-517
F2 Major drops_unfinished_call(cause) = cause != Eos changes truncation from server_error to success for every dialect and all three protocols, inverting a deliberately named pre-existing test, with no maintainer sign-off output.rs:476-480, output.rs:163-173, encode.rs:666-688, diff hunk server/output.rs:~1262-1274
F3 Major Two documented invariants are reversed in docs/api.md without being presented as reversals: the universal "parsers buffer tool envelopes" contract, and #364's check-size-before-first-tool-event property docs/api.md:540-555, docs/api.md:570-572, dsml.rs:191-192
F4 Major validate_arguments now runs after fragments are published, so a rejected argument object leaves an announced call open forever and puts invalid partial JSON on the wire — a path that published nothing on main dsml.rs:194-206, dsml.rs:398-426
F5 Major Chat streams an index/id/name delta for a call the final message no longer contains — an orphan tool_calls[] entry assembled by any index-keyed client output.rs:111, output.rs:163-173
F6 Blocker-adjacent (test gap) The new truncation tests assert only the final buffered body and the finish reason — exactly the fields that stay correct while F1 is broken — so no test in the PR can fail on the missing terminal frame protocol/tests.rs:3809-3891, :3963-4001
F7 Minor Per-fragment SSE frame amplification on the per-token path (~566 frames for 2196 bytes, one json! per fragment) with no coalescing, unmeasured against main; plus a finish_reason observability shift encode.rs:625-653, encode.rs:690-696
F8 Minor Every mechanical claim in the description checks out, but the two reversals are framed as means rather than as behaviour changes, and the reported test counts differ between snapshots of the body at an unchanged head PR body

1. Correctness, safety & platform parity

F1 — Blocker: an announced call loses its terminal stream event (Messages, Responses, and Chat)

ResponseOutput::finish removes the block and clears open before calling close():

    pub fn finish(&mut self, cause: Termination) -> Result<Vec<Change>> {
        if drops_unfinished_call(cause)
            && self.open.is_some()
            && matches!(self.blocks.last(), Some(Block::Tool { .. }))
        {
            self.blocks.pop();
            self.calls.pop();
            self.open = None;
        }
        let mut changes = vec![];
        self.close(&mut changes)?;
        Ok(changes)
    }

— helios/src/server/output.rs:1730-1742 (verbatim).

close() is the only producer of Change::End, and it is a no-op once open is None:

    fn close(&mut self, changes: &mut Vec<Change>) -> Result<()> {
        if let Some(index) = self.open {
            if let Block::Tool { ended: false, .. } = &self.blocks[index] {
                return Err("incomplete emitted tool call".into());
            }
            self.open = None;
            changes.push(Change::End(index));
        }
        Ok(())
    }

— output.rs:1720-1729 (verbatim).

Change::End(i) is the sole trigger for the two terminal per-block frames:

            (Protocol::Messages, Change::End(i)) => {
                if let Block::Reasoning(text) = &self.outputs[0].blocks[i] {
                    frames.push(self.named("content_block_delta",json!({"index":i,"delta":{"type":"signature_delta","signature":thinking_signature(text)}})));
                }
                frames.push(self.named("content_block_stop", json!({"index":i})));
            }

— helios/src/server/protocol/encode.rs:424-429;

                frames.push(self.named(
                    "response.output_item.done",
                    json!({"output_index":i,"item":item}),
                ));

— encode.rs:513-516.

Meanwhile the opening frames were already sent from Change::Start (encode.rs:409-415 content_block_start, encode.rs:430-434 response.output_item.added), which the PR's own test confirms (protocol/tests.rs:3830-3846: assert_eq!(opening.len(), 1), content_block_start, response.output_item.added).

Impact. On OutputLimit, UserStop, Cancelled or ExecutionError inside an announced call, a Messages streaming client receives content_block_start with no content_block_stop before message_delta/message_stop, and a Responses client receives response.output_item.added with no response.output_item.done. Both grammars require the close (Anthropic: every content block opened must be stopped; OpenAI Responses: every output_item.added is closed by output_item.done). Block-accumulating SDK clients (anthropic streaming helpers, OpenAI Responses SDK) keep the announced item_id pending forever. Note the comparison honestly: main also left the block open, but it failed the request (Err("incomplete emitted tool call"), still asserted at output.rs:1648-1652 with finish(Termination::Eos)), so the client got an explicit error rather than a silently malformed but "successful" stream. The change converts a loud failure into an unannounced protocol-grammar violation.

Note also the Responses incomplete status wiring does not cover this: incomplete_item is only set for Termination::OutputLimit on a surviving Change::End (encode.rs:678-682), and the dropped block is removed from outputs anyway.

Fix. Emit the terminal change for the dropped block before removing it — push Change::End(index) (Responses: with item(i, true) carrying status: "incomplete" via encode.rs:339-346) so content_block_stop / response.output_item.done is still sent, then drop the block from the buffered body. A dedicated Change::Abort(i) mapping to the same terminal frames with status:"incomplete" is the cleaner form.

F2 — Major: universal truncation reversal, cross-dialect, no sign-off

/// Whether a termination cause drops a tool call that was announced but never
/// completed, instead of reporting it as an incomplete call.
pub(crate) fn drops_unfinished_call(cause: Termination) -> bool {
    cause != Termination::Eos
}

— output.rs:476-480 (verbatim, from the diff hunk).

Consumed by Accumulator::finish (output.rs:163-173) and ResponseOutput::finish (output.rs:1730-1742), both driven by Encoder::finish with the same cause (encode.rs:666: let cause = if self.tool_limit_reached { Termination::Cancelled } else { cause };, then encode.rs:674-677). Because the predicate keys only on Termination, it applies to every tool dialect — DSML, the tagged Qwen/GLM/MiniMax/Gemma parsers, XTML, TML, recipient — and to Chat, Messages and Responses alike, although only DSML gained streaming in this PR.

The diff inverts a test whose name recorded the previous rule as deliberate:

-    fn user_stop_cannot_retract_an_already_emitted_partial_tool_call() {
...
-        assert_eq!(
-            presentation.finish(Termination::UserStop).unwrap_err().to_string(),
-            "incomplete emitted tool call"
-        );
+    fn user_stop_omits_an_already_emitted_partial_tool_call() {
+        presentation.finish(Termination::UserStop).unwrap();
+        assert!(presentation.message().get("tool_calls").is_none());

— pr_diff hunk helios/src/server/output.rs around line 1262.

Impact. Every request that truncates inside an emitted tool call changes wire class from server_error to success with a cause-derived finish reason (encode.rs:690-696: "length" for OutputLimit, "stop" otherwise unless completed tools exist). This is a service-wide observable change: dashboards and retry logic keyed on server_error for this class go to zero, and a client that retried a truncated agent turn no longer will. Charter/"What gets merged" requires a maintainer request, roadmap item, reproducible bug or measured issue, and AGENTS.md requires an explicit maintainer decision to relax a guarantee; neither is recorded (no issue, no review, no label).

Fix. Scope the drop to the case streaming creates (DSML-announced calls), keeping the existing error for the buffering dialects where nothing was retracted, or obtain explicit sign-off and record it in the description.

F4 — Major: validation failure leaves an announced call open and streams invalid JSON

                OutputAction::ToolCallArgumentsEnd { closing_text } if !repeated => {
                    let mut call = self.call.take()...;
                    call.close_literal();
                    call.arguments.push_str(closing_text);
                    call.check_size()?;
                    validate_arguments(&call.arguments)?;
                    call.publish(self.calls, events);
                    events.push(Event::ToolEnd { index: self.calls });
                    self.calls += 1;
                }

— helios/src/output/dsml.rs:194-205.

validate_arguments (dsml.rs:398-426) rejects duplicate/empty keys and malformed JSON. On that error the ? returns before Event::ToolEnd, so ResponseOutput.open stays Some(i) and the Chat accumulator keeps ended: false; the request then fails (delivery error) and finish() never runs, so no terminal change is produced for a call that already announced itself. On main all three events were emitted after validate_arguments passed, so this path published nothing.

Impact. The new test documents the outcome — server_error arriving after mid-argument JSON deltas — so streaming clients receive function.arguments / input_json_delta bytes that are syntactically invalid, then an error frame with no content_block_stop/output_item.done. This is a new partial-JSON exposure on an error path, and the PR description does not mention it.

Fix. Validate before publishing, or on the error path close the announced call (same Change::End fix as F1) and document the partial-JSON-then-error sequence.

F5 — Major: Chat streamed an index the final message drops

Accumulator::finish pops the announced call:

    pub(crate) fn finish(&mut self, cause: Termination) -> Result<()> {
        if drops_unfinished_call(cause)
            && self.calls.last().is_some_and(|call| !call.ended)
        {
            self.calls.pop();
        }

— output.rs:163-168.

But the stream already published that call's header: deltas.push(json!({"tool_calls":[{"index":index,"id":id,"type":"function","function":{"name":name,"arguments":""}}]})); (output.rs:111), followed by argument deltas (output.rs:113-130), and Chat chunk emission (encode.rs:626-629). The final message() is built from the popped accumulator, so it has no tool_calls (output.rs:179-181), and the test asserts exactly that (protocol/tests.rs:3864-3867).

Impact. An index-keyed Chat client (the standard OpenAI streaming assembly) has a tool_calls[] entry with an id and name that the assistant message never contains. That is a client-visible inconsistency, not a crash, but it violates the invariant that the SSE-assembled message equals the buffered message (output.rs test reconstruct(&deltas) == output.message() at Eos).

Fix. Make the drop observable: a final delta on that index marking it aborted (or simply keep the header-only call with empty arguments), and derive the drop decision from the parser's announcement rather than from the raw cause.

Areas verified sound (no issue)


2. Unintended system-level consequences

F7 — Minor: per-fragment SSE frame amplification on the per-token path, unmeasured

Each event produced by a fragment goes through one chats[index].apply(...) delta → one chunk(...) frame per delta and one change(...) frame per change (encode.rs:625-653). There is no coalescing of consecutive argument fragments at the encoder; the only merge is inside Accumulator::apply for deltas produced in the same call (output.rs:123-140), which does not merge across generation steps.

Impact. For a large write argument the PR converts one frame into hundreds: the author measured 566 frames for 2196 bytes (~4 bytes/frame), i.e. roughly an order of magnitude more SSE writes and json! allocations for tool-heavy responses. On a local single-user engine this is not a throughput hazard, but it is the dominant new cost of the change on agent workloads and it is not measured against main — the charter (#210) asks for served-workload A/B evidence, and the only datum is frame count on the author's own endpoint, not latency/tokens-per-second. A trivial mitigation (flush fragments on a small byte or time threshold, or on the next token boundary) would recover most of the benefit for write-shaped payloads.

Failure propagation is improved, not worsened: a stalled-forward stream was the reported failure mode, and streaming shortens the window in which a client watchdog can fire. No new poison-peer or partial-failure blast radius: a failing encoder still fails only its own request.

Observability / metric-span check

The PR changes what the finish-reason classification reports without changing any sampled rate or admission estimate. Verified span: encode.rs:690-696 computes reason from cause and has_tools() for the whole request, after Accumulator::finish has already popped the dropped call, so:

        let reason = if cause == Termination::OutputLimit {
            "length"
        } else if cause != Termination::UserStop && self.outputs[index].has_tools() {
            "tool_calls"
        } else {
            "stop"
        };

— encode.rs:690-696 (verbatim).

Consequence: a Cancelled request (scheduler preemption/cancellation, runtime.rs emits Cancelled with reason: "stop") that previously surfaced as server_error now reports finish_reason: "stop"; a Cancelled request with a completed call reports "tool_calls". Operators lose the discriminator between "model finished" and "we cancelled it" for this class, which is the opposite direction from #679 (which wants output-layer stream failures counted rather than absorbed). No config flag, default, env var or protobuf contract changes (runtime_core/protobuf.rs is a one-line test call-site), so the shift is silent.


3. Architecture, contracts & charter compliance

F3 — Major: two documented contracts reversed without being named as reversals

(a) The universal buffering contract is deleted. main's docs/api.md said (removed lines 540-541):

The model parsers buffer tool envelopes until
they are complete, so argument events do not imply incremental generation of an
unfinished call.

The PR replaces it with a per-parser description ending:

An announced call cut off before completion is omitted from a
buffered response for every termination other than natural end-of-sequence, and
the response reports that termination's finish reason; only an output-limit
termination reports the output limit. A client that received fragments of such a
call has already seen a call that cannot complete.

— docs/api.md:540-555.

The second sentence is honest, but the change silently removes (i) the guarantee that argument events never imply incremental generation, and (ii) the guarantee that a truncated tool envelope reports the output limit — now UserStop/Cancelled/ExecutionError report their own reason, which is wire-visible for all clients on all dialects.

(b) #364's pre-publication size bound is reversed. docs/api.md:570-572 now reads:

The bound is enforced on the append that crosses it, after the
call name and earlier argument fragments were published and are not retracted,
so an oversized call never completes and cannot appear in a buffered body.

main said Helios rejects a larger call before publishing it. #364 (voipmonitor, reviewed by yatesdr) deliberately moved the 1 MiB check ahead of the first tool event; dsml.rs:191-192 now checks on the append that crosses the bound and publishes the earlier bytes:

                    call.check_size()?;
                    call.publish(self.calls, events);

Impact. This is a reversed invariant of a reviewed, merged change by a priority contributor, made by a first-time contributor, with no rebase, no sign-off request and no mention in the description. Per the charter's review standards and AGENTS.md, the reversal needs an explicit maintainer decision.

Fix. Either keep the pre-publication bound (validate before publishing, which also fixes F4), or state the reversal explicitly and request sign-off from voipmonitor/yatesdr.

Contract/owner sign-off check. No AGENTS.md-required owner sign-off exists for either the tool-call streaming contract change or the truncation-semantics change; the PR has no labels, no reviews and no comments. The change is not wrong-layer: the streaming decision lives in the DSML parser, the shared predicate lives in the shared output layer keyed on Termination (not on a model). That part complies.

Fit risk restated. The change is closest to "reproducible bug" but the bug was never filed; no maintainer request, roadmap item or issue asks for streaming tool arguments. Charter tension: the PR makes the streaming guarantee explicitly dialect-dependent (DSML streams, tagged parsers do not, docs/api.md:540-555), which a reviewer could read as two behaviours behind one Event contract.


4. Tests & claim accuracy

F6 — Blocker-adjacent: the truncation tests cannot fail on the F1 defect

            let finished = encoder.finish(0, cause, 4, 0, None).unwrap();
            assert!(!finished.is_empty(), "{protocol:?} reports its finish");
            let response = encoder.response();
            match protocol {
                ...
                Protocol::Messages => {
                    assert!(response["content"].as_array().unwrap().is_empty(), "{cause:?}");

— protocol/tests.rs:3859-3876.

and

            assert!(encoder.finish(0, cause, 1, 0, None).is_ok(), "{cause:?}");
            let response = encoder.response();
            ...
                Protocol::Responses => {
                    assert!(response["output"].as_array().unwrap().is_empty(), "{cause:?}")
                }

— protocol/tests.rs:3984-3996.

The assertions are precisely the fields that remain correct while content_block_stop / response.output_item.done are missing: finished.is_ok() / !is_empty() (the finish chunk is always pushed at encode.rs:704-710) and the final body shape. Neither test inspects the event names in finished, and neither test reconstructs the stream.

The repo already has the right idioms and the PR does not use them:

Fix. Add to both truncation tests: every content_block_start index must be matched by a content_block_stop, and every output_item.added item_id by an output_item.done; plus for Chat, the SSE-assembled message equals encoder.response()["choices"][0]["message"].

Also absent: no test asserts the new behavior under actual streaming concurrency (chunked HTTP with a slow writer), and no test covers the F4 error path's terminal frames. The PR's single end-to-end-ish test is the DSML→OutputPipeline→Chat round-trip, which is the right shape but Chat-only.

F8 — Minor: description accuracy

Checked claim by claim against the diff; every mechanical statement holds:

The two claims that are inaccurate by omission are F2 and F3: the description never says that a server_error becomes a success, nor that #364's pre-publication bound is reversed. It also does not mention F1 (the missing terminal frame) or F4 (partial JSON before a rejection) at all.


Open questions / could not find

  1. Is dropping the partial call a deliberate product decision? No issue, comment, review or roadmap item records the intent, and the deleted test name (user_stop_cannot_retract_...) shows the earlier rule was considered. This needs a maintainer answer, not a code answer.
  2. Is the missing content_block_stop/output_item.done acceptable to the Messages/Responses contract owners? docs/api.md now says the call "cannot complete" but the streaming grammar for that case is not spelled out anywhere I could find.
  3. Did anyone ask for DSML streaming? No demand trail exists (no issue, 👍, duplicate report, or consumer filing the symptom); #347's body could not be retrieved by the reading tool, so it may list the symptom.
  4. Does any consumer depend on server_error for a truncated tool call (monitoring alerts, client retry)? Not documented and not measurable from the repo.
  5. Are the self-reported flaky engram failures truly pre-existing on main? No CI run corroborates, and the counts shifted between snapshots of the body.
  6. Do flare and flare-cli still build against the changed finish(cause) signatures? The author did not build them; Accumulator::finish is pub(crate) and ResponseOutput::finish is consumed only at encode.rs:677, so the risk is low, but this is inference rather than a build.
  7. Rebase status. The branch point 1fbcc3c predates #670 and #660 on main, and #670 touched eight of these 13 files including a rewrite of the same docs/api.md parser section, so the docs/api.md resolution is not mechanical — and that resolution is exactly where F3's contract text lives.