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

Raw Markdown for agents: https://autobot.eidonix.com/p/509ccfd3-3319-4fae-85ae-bf16d007d31e.md

#1 [high] F1 Blocker: announced call loses its terminal stream event (Messages/Responses/Chat)

helios/src/server/output.rs:1730-1742 (PR head):

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

The block is removed and open cleared, so close() (output.rs:1720-1729, the only producer of Change::End) produces nothing. Change::End is the sole trigger for the terminal per-block frames:

Impact: on OutputLimit / UserStop / Cancelled / ExecutionError a streaming client receives content_block_start (or response.output_item.added) with no matching content_block_stop (or .done). Anthropic's streaming grammar requires every started content block to be stopped before message_delta/message_stop; OpenAI's Responses grammar requires every output_item.added to be closed by output_item.done. Block-accumulating SDK clients keep the block pending; the announced item_id never completes. The final buffered body also omits the announced item while the stream announced it.

Concrete fix: when dropping, still emit the terminal change for that block before removing it, e.g. push Change::End(i) for the popped index (or a dedicated Change::Abort(i) mapping to content_block_stop / output_item.done with status: "incomplete"), then drop the block from the accumulated body. Same for Chat streaming (encode.rs:627-629 emits an id+name delta that the final message no longer contains).

Note main behaviour for comparison: main returned Err("incomplete emitted tool call") from close() (see the surviving assertion at output.rs:1648-1652), so main also left the block open — but main failed the request instead of continuing. The new code makes a silent, unannounced protocol-grammar violation the normal outcome, which is a worse client failure mode than either a clean stop or an error.

#2 [high] F2 Major: universal truncation change reverses a tested invariant for all parsers, no sign-off

helios/src/server/output.rs:476-480 (new):

/// 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
}

Consumed by Accumulator::finish (output.rs:163-173) and ResponseOutput::finish (output.rs:1730-1742), both driven by Encoder::finish (encode.rs:674-677). Because the predicate keys only on Termination, it applies to every tool dialect (DSML, tagged Qwen/GLM/MiniMax/Gemma, XTML, TML, recipient) and to Chat, Messages and Responses alike — even though only DSML gained streaming.

The previously deliberate behaviour is inverted in the diff (server/output.rs:~1265):

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

The old test name records that retraction was forbidden.

Impact: every request that truncates inside an emitted call (output limit, stop string, user stop, cancellation, execution error) changes from a server_error to a success with that cause's finish reason. That is a service-wide observability shift (error rates drop for a class of requests — relevant to #679) and a behaviour change for clients whose retry/monitoring keys on the error. AGENTS.md:182-186 requires "Do not remove validation, suppress errors ... to obtain passing checks"; the change also has no maintainer request (see #418's "zero leaked partial calls" evidence, which this reinterprets).

Concrete fix: scope the drop to the case the streaming fix creates — DSML-announced calls — and/or require explicit maintainer sign-off for the cross-dialect change; at minimum keep the old error for causes that never streamed (the tagged parsers still buffer, so on those dialects nothing was retracted and the error was correct).

#3 [high] F3 Major: two documented invariants reversed in docs/api.md without sign-off

docs/api.md:540-555 (PR head) now states:

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.

Compare the deleted main text (diff, docs/api.md -540..-541):

The model parsers buffer tool envelopes until
they are complete, so argument events do not imply incremental generation of an
unfinished call. Truncated tool envelopes are omitted and the response reports
its output limit.

Two contract facts the PR does not surface as reversals: (a) the documented universal buffering contract is gone (only DSML now streams); (b) truncation no longer reports the output limit for UserStop/Cancelled/ExecutionError but that cause's reason, which is a wire-visible change for all clients.

docs/api.md:570-572 (PR head) replaces "Helios rejects a larger call before publishing it" with:

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.

That directly reverses #364's reviewed property (1 MiB check moved ahead of the first tool event). Code: dsml.rs:191-192 call.check_size()?; call.publish(self.calls, events); publishes before the next append's check trips, and dsml.rs:194-205 runs validate_arguments after the fragments of the same call were already published.

Charter/AGENTS.md:182-186 ("Reject weakened guarantees... Do not remove validation, suppress errors, ... relax ... bounds") applies to both reversals. They need a maintainer decision, which the PR neither requests nor records.

#4 [high] F4 Major: validation failure now leaves an announced call open forever and streams invalid JSON

helios/src/output/dsml.rs:194-205 (PR head), ToolCallArgumentsEnd:

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

validate_arguments (dsml.rs:398-426) rejects duplicate/empty keys and malformed JSON. On that error the ? returns before ToolEnd, so the encoder keeps an open call: ResponseOutput.open stays Some(i) (encode.rs → output.rs:1778-1803) and Chat's Accumulator keeps ended: false. The request then fails (http.rs:575-578 Delivery::Failed), and no finish() runs, so the Change::End never arrives.

This is exactly what the new test asserts — dsml.rs (a_rejected_argument_object_fails_after_its_fragments_are_published) and protocol/tests.rs:3849-3891 — a server_error arriving after mid-argument JSON deltas. For non-streaming requests the body becomes an error; for streaming, clients got function.arguments/input_json_delta up to the invalid byte then an error frame with no content_block_stop. Main published nothing on this path (all three events were emitted only after validate_arguments passed), so this is a new partial-JSON exposure and it is not mentioned in the PR description.

Also worth noting on the same path: Call::publish is a no-op while literal.is_some() (dsml.rs:53-62), so a very large string="false" parameter (e.g. a number array) buffers entirely and publishes in one burst at close_literal, i.e. no streaming for non-string arguments — the opposite of the PR's claim for write-style payloads only.

Concrete fix: keep the fragments but close the announced call on error, or publish only bytes that have already passed a validation that cannot fail later (i.e. re-validate per parameter), and document the partial-JSON-then-error outcome.

#6 [high] F6 Blocker-adjacent: test gap — truncation tests never assert the streamed terminal frames

harness: helios/src/server/protocol/tests.rs:3809-3891 an_announced_call_publishes_fragments_and_truncation_omits_it loops over for cause in [OutputLimit, UserStop, Cancelled, ExecutionError] and asserts only finished is non-empty, the final body omits the call, and the finish reason. It never inspects the content of finished (the terminal frames). So the missing content_block_stop / response.output_item.done (F1) is invisible to the suite: for Messages it asserts response["content"] is empty and for Responses response["output"] is empty, both of which are precisely the conditions under which Change::End was suppressed.

Same gap in protocol/tests.rs:3963-4001 a_header_only_call_is_omitted_when_the_response_truncates: asserts only finish(...).is_ok() and the final body shape.

Missing tests that would catch it, and which the repo already has an idiom for:

Also unrun: the PR body reports counts that changed between the packet and the live body (1783/18 vs 1787/16; output:: 111 vs 113), so the numbers cannot be tied to head 2f0ed9d; no CI check exists on the head commit. The self-reported failures include six FLARE_TEST_TEMPLATE_DIR cases and ten to twelve engram failures; the output:: and server::protocol suites are the ones that matter and the template failure is claimed to be pre-existing, which is plausible but unverified here.

#9 [high] Research summary

Reviewed PR #685 (stream DeepSeek tool-call arguments) for correctness, contracts and system-level consequences. All 13 changed files plus their direct callers were inspected in context: helios/src/output/dsml.rs (apply/publish/close_literal/finish/validate_arguments), helios/src/server/output.rs (Accumulator, ResponseOutput, Decoder, drops_unfinished_call), helios/src/server/protocol/encode.rs (apply, change, finish, strict parking), helios/src/server/http.rs (streaming driver), helios/src/server/runtime.rs (termination causes), pipeline.rs, latency.rs, the other dialects, docs/api.md and AGENTS.md.

The mechanism itself is sound: the DSML streaming fix is confined to dsml.rs, the publish cursor is correct, string="false" literals are correctly withheld, strict parking is untouched, and no lock/queue/shared-state or memory-amplification hazard is introduced (fragments are slices of the already-buffered argument string; total copying stays O(bytes)).

The serious problems are elsewhere. The biggest is a protocol-grammar violation I verified in code: when a termination other than Eos drops an announced call, ResponseOutput::finish pops the block and clears open without emitting Change::End, which is the only producer of content_block_stop (encode.rs:424-429) and response.output_item.done (encode.rs:470-517) — while Change::Start already sent content_block_start / output_item.added. The PR's own new test confirms the opening frame is emitted but never asserts a matching close, so the gap is untested. Second, drops_unfinished_call(cause) = cause != Eos is a universal, cross-dialect behavioural reversal (a request error becomes a success with a different finish reason) that inverts an existing deliberately-named test and has no maintainer sign-off. Third, validate_arguments now runs after fragments are published, so a duplicate-key rejection leaves an announced call open forever and exposes invalid partial JSON on the wire — a path that previously published nothing. Fourth, docs/api.md deletes the documented "parsers buffer tool envelopes" contract and rewrites the 1 MiB sentence into an explicit post-publication bound, reversing #364's reviewed invariant. I also recorded a Chat-specific orphan-delta asymmetry, per-token SSE frame amplification (~566 frames for 2196 bytes, no coalescing, unmeasured), the cancellation→"stop" observability shift, and an audit showing every PR-body claim is mechanically accurate while the two reversals are framed as incidental. Details, verbatim quotes and file:line citations are in the scratchpad (entries 1-8).

#10 [high] Consolidated finding list with severities, locations and fixes

Ranked for adjudication. All verified by opening the files at PR head 2f0ed9d.

F1 — Blocker. Announced call never gets its terminal stream frame. helios/src/server/output.rs:1730-1742 pops blocks, calls and clears open without pushing Change::End; close() at output.rs:1720-1729 is the only Change::End producer. Change::End is the sole trigger for content_block_stop (encode.rs:424-429) and response.output_item.done (encode.rs:470-517), while Change::Start already emitted content_block_start (encode.rs:406-415) / response.output_item.added (encode.rs:430-451). Impact: every truncated streaming request on Messages/Responses leaves a permanently open content block; Anthropic and OpenAI streaming grammars both require the close. Fix: emit the close (with status:"incomplete" for Responses) before dropping the block.

F2 — Major. Universal truncation reversal without sign-off. output.rs:476-480 drops_unfinished_call(cause) -> cause != Termination::Eos, consumed at output.rs:163-173 and output.rs:1730-1742, driven from encode.rs:674-677. Applies to all dialects and all three protocols although only DSML streams. Inverts the pre-existing test at diff hunk server/output.rs:~1262-1274 (user_stop_cannot_retract_... → user_stop_omits_...). Impact: server_error becomes success for a whole class of requests. Fix: scope to announced (DSML) calls, or obtain an explicit maintainer decision per AGENTS.md:182-186 / :201-207.

F3 — Major. Two documented invariants reversed in docs/api.md without naming them. docs/api.md:540-555 deletes "The model parsers buffer tool envelopes until they are complete..." (main); docs/api.md:570-572 replaces "Helios rejects a larger call before publishing it" with a post-publication bound, reversing #364. Code confirms: dsml.rs:191-192 publishes before the next append's check_size. Fix: call the reversals out in the description and get sign-off, or keep the pre-publication bound.

F4 — Major. Validation failure leaves an announced call open and streams invalid JSON. dsml.rs:194-206: validate_arguments (dsml.rs:398-426) runs after publish and its ? returns before ToolEnd, so ResponseOutput.open stays Some (output.rs:1778-1803) and the Accumulator call stays ended: false; http.rs:575-578 then emits Delivery::Failed and no finish() runs. Previously nothing was published on this path. Fix: close the call on the error path, or validate before publishing.

F5 — Major. Chat streamed an index the final message drops. output.rs:163-173 pops the call; the id+name delta was already sent at output.rs:111, and encode.rs:787 builds the final message from the popped accumulator. Output-index orphan for Chat. Fix: mark the streamed call as aborted rather than silently dropping it.

F6 — Blocker-adjacent (test gap). Truncation tests never assert terminal frames. protocol/tests.rs:3809-3891 and :3963-4001 assert only finish(...) being Ok/non-empty plus the final body shape — exactly the fields that stay correct while F1 is broken. The repo already has the right idiom at protocol/tests.rs:1098-1151 (json!(blocks) == expected["content"]) and :1195-1200 (.done items == response["output"]). Fix: add those two invariants to the truncation cases.

F7 — Minor/Major. Frame amplification and observability shift. ~566 SSE frames for 2196 bytes, one json! frame per parser fragment on the per-token path (encode.rs:625-653), no coalescing (contrast the merge at output.rs:123-140); unmeasured against main. Separately, runtime.rs:320-329 + encode.rs:690-696 make a cancelled/parked request report finish_reason:"stop", reducing error-rate visibility (adjacent to #679).

F8 — Minor. Description framing. Every mechanical claim checks out (dsml.rs:145-156, :53-62, encode.rs:564-621), test counts disagree with the packet while the head is unchanged, and F2/F3 are framed as means rather than as reversals.

#5 [medium] F5 Major: Chat streamed delta keeps an index the final message drops

helios/src/server/output.rs:163-173, Accumulator::finish:

        if drops_unfinished_call(cause)
            && self.calls.last().is_some_and(|call| !call.ended)
        {
            self.calls.pop();
        }
        if self.calls.iter().any(|call| !call.ended) {
            return Err("incomplete emitted tool call".into());
        }

The pop is singular and only inspects the last call, while the predicate that decides "drop" is global to the cause rather than structural. Accumulator enforces index == self.calls.len() (output.rs:94-100), so only the last call can be unfinished — the guard is fine — but the same is not true on the wire: the Chat stream already published {"index":N,"id":...,"function":{"name":...,"arguments":""}} (output.rs:111) for that popped call, so the streaming deltas reference a tool_calls[] entry that the final message no longer contains. Encoder::response() for Chat reads the popped accumulator (encode.rs:787), so a client that assembled the call by index gets an orphan.

Contrast with ResponseOutput::finish (output.rs:1730-1742), which has the same pop but also self.open = None — the diverging handling is what produces F1 (no terminal change) on Messages/Responses while Chat silently loses only the buffered copy.

Concrete fix: make the drop path symmetric and observable — emit the closing stream event for the announced call and mark it finished in the streamed deltas (e.g. a final Chat chunk with finish_reason on that index and an input_json_delta-free content_block_stop/output_item.done with status:"incomplete"), and derive the "may drop" decision from the parser's announcement rather than the raw cause.

#7 [medium] F7 Minor-Major: per-token SSE frame amplification and cancellation observability shift; no concurrency/memory hazard

Verified in helios/src/server/output.rs (Decoder::finish, 341-401) and helios/src/server/http.rs:518-560:

No lock/mutex, queue, allocation-amplification or cross-request coupling is introduced: the change is per-request, in the streaming task's own Encoder/Accumulator/ResponseOutput; there is no shared state, no new buffer (the fragments are slices of the already-buffered arguments string, dsml.rs:57-60 self.arguments[self.published_argument_bytes..].to_owned() — one copy per fragment, replacing one copy at the end). Memory is unchanged in the worst case and the per-fragment copies are O(total argument bytes) overall, not O(n²).

One real cost: fragment granularity is per ToolCallArgumentsText action, i.e. roughly per token; each fragment is turned into an SSE frame by encode.rs:625-653 → Frame::sse(). The PR measured 566 frames for 2196 bytes (~4 bytes/frame), i.e. ~3.8x the non-streaming frame count for tool-heavy responses and one SSE write per fragment. No coalescing exists (contrast Event::ToolArguments merging inside Accumulator::apply, output.rs:123-140, which merges only when the previous delta was for the same index and had exactly one entry). For a large write argument this multiplies SSE frames and json! allocations on the per-token hot path; on a chatty agent workload that is the dominant cost of the change and is not measured (no A/B on frame count/latency vs main beyond the one request).

#8 [medium] F8: PR description accuracy audit — claims check out, framing understates reversals

PR description claims vs code, checked one by one:

  1. "the call's name is announced when its header completes" — correct: dsml.rs:145-156 pushes Event::ToolBegin at ToolNameEnd.
  2. "published fragments concatenate to exactly the stored arguments" — correct for validated calls; tested at every UTF-8 split (dsml.rs published_fragments_reconstruct_the_stored_arguments_at_every_split).
  3. "no published byte is replaced, string="false" stays private while close_literal may rewrite it" — correct: dsml.rs:53-62 no-op while literal.is_some(); close_literal (dsml.rs:65-78) only rewrites under literal. Note the cost: a large non-string parameter does not stream at all; the description says label bytes "travel with the next text fragment" but the whole literal is withheld, which the description does not state (it only says a value "stays private while close_literal may still rewrite it").
  4. "Accumulator::finish(cause) and ResponseOutput::finish(cause) now drop an announced-but-unfinished call ... holds for every cause except natural end-of-sequence, ExecutionError included" — accurate and admirably explicit, but it is described as a means, never as a user-visible reversal from server_error to success for all dialects (see F2).
  5. "Strict tools keep the existing parking path" — correct: encode.rs:564-621 untouched; pending_strict_calls still suppresses frames (continue at 588 and 598). Note encode.rs:667-671 still returns an error for a pending strict call at Eos, so strict + truncation keeps the old error, which is consistent.
  6. "docs/api.md now states which parsers publish fragments, what those fragments concatenate to, and how a truncated call ends" — correct (docs/api.md:540-555), but the same edit deletes the sentence that documented the previous universal contract, and it rewrites the 1 MiB sentence into an explicit post-publication bound (docs/api.md:570-572), reversing #364 without naming it.
  7. "the output:: suite reports 111/113 passed and server::protocol 94/96" — the two live numbers differ from the packet's snapshot while the head commit did not change, so the description was edited after opening; counts cannot be attributed to 2f0ed9d with confidence.
  8. Evidence limits are stated honestly (single model pino/chat DeepSeek-V4.1-Flash-1017, tagged dialects unexercised live, flare/flare-cli unbuilt). That satisfies AGENTS.md:103-112 partially, but per AGENTS.md:165-169 the change also needs "a demonstrated defect" — no issue exists for this, only the author's own observation — and per AGENTS.md:182-186 a weakened guarantee needs an explicit maintainer decision, which the description does not request.