PR #685 — Correctness, Contracts & System-Level Consequences review
PR: https://github.com/NVIDIA/hyperflare-inference/pull/685 · head 80c87b3 · author peperunas · 13 files, +662/−72.
Key findings
- Blocker — truncation leaves a Messages/Responses content block permanently open.
ResponseOutput::finishpops the announced tool block and clearsopenbeforeclose(), which is the only source ofChange::End;Encoder::finishthen emits the terminal frames anyway. A client receivescontent_block_start/response.output_item.added, theninput_json_delta/response.function_call_arguments.deltaframes, thenmessage_stop/response.completedwith nocontent_block_stop/output_item.done, and astop_reasonthat contradicts the stream. - Blocker — four existing integration tests fail on merge; the PR's own evidence structurally cannot see them. CI runs the whole
heliostest target (.github/workflows/native-serving.yml:63(not opened) Linux,:68Windows, no--lib); the body reportscargo test … --libonly, and nohelios/tests/file is touched. - Blocker (charter) — a request-level error becomes a successful empty response.
drops_unfinished_call(cause) -> cause != Termination::Eosconverts the signed-offErr("incomplete emitted tool call")into silent omission for UserStop, Cancelled and ExecutionError, rewrites the test that pinned it, and documents it as contract — code, test and docs weakened with no maintainer decision on record (AGENTS.md:182-187,201-207). - Major — the 1 MiB argument bound is now enforced after publication, reversing the #364 pre-publication invariant and making an oversized DSML call a client-visible partial
tool_usefollowed by a failure, which compounds finding 1. - Minor — the doc paragraph this PR rewrites for per-parser behaviour is already false on
mainforTAGGED_JSON(#670): it claims tagged parsers "coerce to declared types" from "declared schemas", buttagged_json.rs(not opened) re-serializes the model's own arguments object. - Sound areas (stated plainly, no issue invented): fragment bytes concatenate byte-for-byte to the stored arguments;
string="false"values stay private untilclose_literaldecides (dsml.rs:53-78); the strict-tool parking path is genuinely unchanged; all added state is per-request with no shared lock, no extra copies beyond O(n) per call, and no TTFT/metric-span shift (latency.rs:116-142samples only text/thinking/content/reasoning deltas).
Area 1 — Correctness, Safety & Platform Parity
F1. Blocker — dropped call never gets its closing frame (Messages and Responses SSE)
helios/src/server/output.rs:1730-1742:
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)
}
close() (helios/src/server/output.rs:1720-1729) is the only place Change::End is produced:
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));
}
With self.open = None, close() emits nothing for the popped block. But the block was already announced and its fragments already streamed to the client: Change::Start produces content_block_start (helios/src/server/protocol/encode.rs:409-415) and response.output_item.added (encode.rs:430-434); Change::End is the sole producer of content_block_stop (encode.rs:424-428) and of response.function_call_arguments.done + response.output_item.done (encode.rs:470-516). Encoder::finish then terminates the stream unconditionally (helios/src/server/protocol/encode.rs:730-745):
Protocol::Messages => {
let response = self.response();
frames.push(self.named("message_delta",json!({"delta":{"stop_reason":response["stop_reason"],"stop_sequence":response["stop_sequence"]},"usage":self.usage_value()})));
frames.push(self.named("message_stop", json!({})));
}
Protocol::Responses => {
let response = self.response();
frames.push(self.named(
if reason == "length" {
"response.incomplete"
} else {
"response.completed"
},
Concrete impact: from the first frame in which a streamed DSML call is truncated (output limit, stop sequence, cancellation, execution error), Anthropic SDK clients receive an unterminated tool_use block — their SSE assemblers raise on missing content_block_stop, and streaming Responses clients get a response.completed whose output array (encode.rs:828) does not contain the item they were told was added. The reason is contradictory too: response["stop_reason"] is end_turn (encode.rs:810: "stop_reason":self.reasons[0].map(|r|if r=="length"{"max_tokens"}else if r=="tool_calls"{"tool_use"}else if self.stop.is_some(){"stop_sequence"}else{"end_turn"})) while the stream just opened a tool_use block.
Why CI does not catch it: the PR's three new protocol tests (helios/src/server/protocol/tests.rs:3810, :3894, :4004) assert only the buffered encoder.response() body, never the frame sequence returned by finish, and the chat-message counterpart asserts presentation.message().get("tool_calls").is_none() (helios/src/server/output.rs:1265-1274) — the body, not the stream.
Concrete fix: do not delete the block from blocks. Keep it, mark it dropped (or reuse incomplete_item), and have finish() still push Change::End(index) so content_block_stop / output_item.done are sent; then filter the dropped index out of Encoder::response()'s block iterators (encode.rs:810, encode.rs:828) and out of text(). Add a test that asserts the full frame list for a truncated announced call, not just response().
F2. Minor — the two drop predicates disagree
Accumulator::finish drops only when the last call is unfinished (helios/src/server/output.rs:164-168: if drops_unfinished_call(cause) && self.calls.last().is_some_and(|call| !call.ended)), while ResponseOutput::finish drops on block kind alone, without checking ended (output.rs:1731-1738, quoted above). Today the DSML flow closes an ended tool block before finish, so this is not reachable; but the asymmetry means any future ordering change can silently delete the arguments of a completed call from a success body. Mirror the ended: false guard in ResponseOutput::finish and share one predicate, since the PR's own doc comment claims "one predicate" (output.rs:476-477) while two different conditions are actually used.
F3. Sound — per-fragment publication is byte-exact and bounded
Call::publish (helios/src/output/dsml.rs:53-62) only emits the appended suffix, and refuses to publish while a string="false" literal is open:
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();
}
close_literal can only rewrite self.arguments[start..] where start = literal, and publish is blocked for exactly that span, so no published byte is ever replaced; the withheld literal is flushed by the next publish after close_literal (dsml.rs:163, :199, :203). Accumulator-side size checks remain in force (helios/src/server/output.rs:119-121, 8 MiB). deltas is re-created per push (output.rs:113-141), so the "merge into previous delta" branch appends within one push only — no quadratic growth across a generation.
F4. Sound — no contention, memory amplification, or metric-span change
All new state is per-request (DsmlOutput, Accumulator, ResponseOutput, Encoder constructed per streamed request in helios/src/server/http.rs:451-600). The parser's 1 MiB bound (dsml.rs:22, :42-47) and the response's 8 MiB bound (output.rs:119-121) are unchanged. On the metric/rate span check requested for this lens: stream_text (helios/src/server/latency.rs:116-142) counts only text/thinking/content/reasoning deltas, so publishing hundreds of ToolArguments frames does not move TTFT/first-frame metrics; token attribution (output.rs:319-336) ignores tool events, so reasoning-token accounting is unchanged. The only metric-facing shift is in distribution, not sampling: finish reasons that used to be Err become stop/end_turn/completed (see F5), so error-rate and finish_reason=="tool_calls" dashboards will under-count failures after this lands.
Area 2 — Unintended System-Level Consequences
F5. Blocker (charter) — universal drop turns errors into success, and the docs enshrine it
helios/src/server/output.rs:476-480:
/// 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
}
applied in Accumulator::finish (output.rs:163-173):
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();
}
if self.calls.iter().any(|call| !call.ended) {
return Err("incomplete emitted tool call".into());
}
ExecutionError is the sharpest path: Decoder::finish already aborts and drops parser state before returning (helios/src/server/output.rs:341-348; helios/src/output/dsml.rs:382-386 clears pending and call), so the ToolBegin already streamed is the client's only trace, and the request now completes with an empty body instead of failing. On Chat the finish reason becomes stop (encode.rs:690-696: else if cause != Termination::UserStop && self.outputs[index].has_tools() { "tool_calls" } else { "stop" }), on Messages end_turn (encode.rs:810), on Responses completed (encode.rs:828). An agent loop can no longer distinguish "model produced no output" from "execution failed mid-call". Mitigation to note: with tool_choice: required|named the guard at encode.rs:685-688 still errors, so the loss is confined to auto/none.
The PR also inverts the test that pinned the invariant (helios/src/server/output.rs:1265-1274):
fn user_stop_omits_an_already_emitted_partial_tool_call() {
...
presentation.finish(Termination::UserStop).unwrap();
assert!(presentation.message().get("tool_calls").is_none());
and rewrites the public contract to match (docs/api.md:547-551): "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; … A client that received fragments of such a call has already seen a call that cannot complete."
AGENTS.md:182-187 — "Reject weakened guarantees. … Do not remove validation, suppress errors, silently substitute execution paths…" — and AGENTS.md:201-207 — "A feature request, passing tests, or a performance gain does not waive an architectural invariant. Resolve conflicts through an explicit maintainer decision on the design before implementing a change to that invariant… Apply these criteria to documentation and test changes that would weaken the rules as well as code." Code, test and documentation are all changed; no maintainer decision exists in the tracker (no issue, no PR referencing streaming tool arguments, zero human comments on #685).
Concrete fix: narrow the predicate to cause == Termination::OutputLimit (the only omission main already performed) and keep Err("incomplete emitted tool call") for UserStop/Cancelled/ExecutionError; or, if drop-on-truncate is genuinely wanted, emit an explicit machine-readable truncation signal in the terminal frame and obtain maintainer sign-off on the design before touching the invariant.
F6. Major — the 1 MiB bound now fires after publication (#364 reversal)
docs/api.md:568-572 (added by this PR):
The combined size of the UTF-8 tool
name and complete JSON argument object is limited to 1 MiB, including escapes
and delimiters. 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.
Matching code, helios/src/output/dsml.rs:189-192:
call.arguments.push_str(source);
}
call.check_size()?;
call.publish(self.calls, events);
The error propagates as a request failure; the frames already handed to the client (up to ~1 MiB of input_json_delta) are never retracted and, per F1, the tool block they opened is never closed. So an oversized argument now produces a client-visible dead tool_use followed by a failure frame, where main published nothing until the whole envelope validated. This is exactly the pre-publication bound #364 established; the PR reverses it without calling that out in the description (the body only says the fragments "are not retracted" for the string="false" case). Concrete fix: enforce check_size before appending/publishing the fragment that crosses the bound (reserve-and-check, then append+publish together), so no fragment is published for a call that cannot complete.
F7. Minor — ordering/interaction: a completed call beside a truncated one keeps its args
ResponseOutput::finish pops only the last block and one calls index, and Accumulator::finish pops only calls.last(); earlier completed calls survive, which is correct. Worth pinning with a frame-level test rather than a body-level one (the PR's only multi-call coverage is helios/src/server/protocol/tests.rs:4004-ish body assertions).
Area 3 — Architecture, Contracts & Charter Compliance
- Wire contracts changed without opt-in. Findings F1 (unterminated blocks on Messages/Responses) and F5 (error→success,
stop_reasonshift) change what both the Anthropic Messages and Responses SSE streams mean. Neither is behind a flag, anddocs/api.mdis edited to describe the new behaviour rather than to flag it as a decision (docs/api.md:547-551). PerAGENTS.md:201-207this needs an explicit maintainer decision on the design first; none is on record. - Right layer, right shape. The parser change itself is well placed:
DsmlOutput::applyemitsEvent::ToolBeginatToolNameEnd(helios/src/output/dsml.rs:145-156) andEvent::ToolEndonly aftervalidate_arguments(dsml.rs:202-204), keeping schema/JSON validation in the parser and framing in the encoder — no per-model branch leaks into Helios's shared layers, matching the charter's "model-agnostic runtime" rule. - Claim accuracy —
docs/api.md:543-547is stale againstmain:
The tagged tool parsers publish a call only when its envelope is
complete, because they build its arguments from parameter syntax and the
declared schemas rather than copying the model's text: values are coerced to
declared types, strict container parameters are parsed, and wrapping newlines
are trimmed.
TAGGED_JSON (#670, merged 2026-12-02 after this PR branched) does neither: helios/src/output/tagged_json.rs:14-49 (not opened) parses the model's own {"name":…,"arguments":…} object and re-serializes object["arguments"].to_string(), with JSON_BODY = true (tagged_json.rs:57 (not opened)) and no schema coercion. The rebase obligation is semantic, not a textual conflict: the paragraph must be rewritten to cover TAGGED_JSON, and the same sentence's claim that tagged calls are published "only when its envelope is complete" is what #670's parser now contradicts.
- Doc overreach on strict tools (hedged).
docs/api.md:540-542says unconditionally "A DeepSeek DSML call is announced once its name is complete, and its argument text is published while the model writes it", while the PR body says "Strict tools keep the existing parking path, so they still emit no frame before the compiled schema accepts their arguments." If the parking happens downstream of the parser'sToolBegin(thepending_strict_callsmachinery atencode.rs:667-671), the doc sentence is false forstrict: trueDSML tools. At minimum the doc should say "non-strict". - No served-workload A/B evidence in-repo. The body's headline proof ("two frames … now 566", "566 argument frames totalling 2196 bytes … hashed identically") comes from the author's own deployment (
llm.giugl.io/pino/chat) and is not reproducible from the tree; there is no benchmark artifact. The root cause analysis, however, is correct and verifiable in the diff:Encoderand both block emitters already opened onEvent::ToolBeginand forwardedEvent::ToolArguments(unchanged in this PR — the onlyencode.rsdiff isfinish(cause)threading), so the defect really was confined to publication timing.
Area 4 — Tests & Claim Accuracy
F8. Blocker — four existing integration tests fail; the reported evidence cannot see them
CI invokes the whole target (cargo test --locked --release --manifest-path helios/Cargo.toml (not opened) --target-dir flare-cli/target --features runtime-core,server) at .github/workflows/native-serving.yml:63 (not opened) (Linux) and :68 (Windows) — no --lib — and the PR changes no helios/tests/ file. The body's evidence is --lib only, and the output:: / server::protocol suites it cites are unit suites.
Statically verified failures against the new behaviour:
helios/tests/deepseek_output.rs:576-581, shared helperparse_literal_parameters(drivestool_call_size_includes_retained_strings_and_closing_brace_in_either_orderat:595-619andliteral_nesting_includes_the_enclosing_argument_objectat:621-635):
let header = format!("{open}<|DSML|{s}invoke name=\"lookup\">");
assert!(output.push(Input::Text(&header))?.is_empty());
...
assert!(output.push(Input::Text(¶meter))?.is_empty());
The header push now yields Event::ToolBegin (helios/src/output/dsml.rs:151-155), and non-string parameters now yield Event::ToolArguments (dsml.rs:189-192).
helios/tests/deepseek_output.rs:509-511,empty_and_duplicate_top_level_parameter_names_are_rejected:
assert!(error.unwrap().to_string().contains("nonempty and unique"));
assert!(published.is_empty());
validate_arguments (dsml.rs:202) now runs after ToolBegin (dsml.rs:151) and after per-fragment publish (dsml.rs:192), so published is non-empty — the PR's own new test asserts the opposite (a_rejected_argument_object_fails_after_its_fragments_are_published, dsml.rs:1015+).
helios/tests/deepseek_requests.rs:683-684,added_non_special_dsml_token_produces_tool_calls:
flare_helios::output::Event::ToolArguments { text, .. }
if serde_json::from_str::<Value>(text).unwrap() == json!({"location":"Berlin"})));
A single fragment is now partial JSON ({"location": , "Berlin", }), so the unwrap() panics.
Impact: both Linux and Windows CI jobs fail on merge (no platform divergence in the defect itself). Fix: update the assertions to the streaming contract (exactly one ToolBegin on the header push; each parameter push yields empty or fragments; drop published.is_empty(); concatenate fragments before serde_json::from_str), and add the whole-target command to the PR evidence. Note other helios/tests DSML sites already accumulate (deepseek_requests.rs:875-882, :920-924) and pass.
F9. Major — test-count evidence does not match head, and the new tests assert the wrong surface
The reported totals shifted across a content-identical force-push (2f0ed9d → 80c87b3d, same parent, same subject, byte-identical docs/api.md:540-572 and output.rs:1265-1274): 1783 passed/18 failed → 1787/16, output:: 111→113, server::protocol 94→96. That reads as a PR-body edit rather than a new run, so the published numbers cannot be attributed to the merged head with confidence. Independently, the ten "engram failures under parallel execution" are reported without a CI link, and six failures need FLARE_TEST_TEMPLATE_DIR — i.e. the green portion of the evidence is a non-CI invocation.
Coverage gap (see F1): the three new protocol tests at helios/src/server/protocol/tests.rs:3810, :3894, :4004 assert encoder.response() only; the DSML pipeline test reproduces stored arguments from >2 pre-close frames but never checks the emitted Change::Start/Change::End pairing. Fix: assert the full Frame list for an announced call, its truncation, and a completed call next to a truncated one.
Open questions / not found
- Whether the automated review's "Should fix: 1" and "Subtract/Simplify: 4" items overlap F4/F6/F7 — the full review page was unreachable from this environment; only the posted summary (2 blockers, 1 should-fix, 4 subtract, 2 nits, Merge Risk High) is quotable.
- Whether a maintainer decision exists elsewhere authorising the
Err("incomplete emitted tool call")removal; nothing in the tracker, and no human comment or review on #685. - Whether voipmonitor (whose #364 pre-publication bound this reverses) or yatesdr (author of the
UserStop/Cancelled paths) considers either invariant blocking — no human engagement as of 2026-12-02 18:31. - #347's body remains unreadable (the reading tool rejected its arguments), so whether that umbrella lists the silent-tool-call symptom is unconfirmed.
- Not exercised: the
flareandflare-clicrates (perdocs/design-review.md:180-185(not opened) they should be built for an affected change; the body states their Helios calls are unchanged), and the tagged dialects against a served model.