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:
- total bytes copied ≈ Σᵢ 1 100·i ≈ 566²/2 · 1.1 KB ≈ 176 MB of memcpy per tool call, plus 566 heap reallocations of the growing
String; - at the documented 8 MiB argument ceiling (
helios/src/server/output.rs:119) with ~2 000 fragments, copied bytes ≈ (2 000²/2)·4 KB ≈ 8 GB for one call, on the request's streaming path, per choice.
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:
content_block_startwith{"type":"tool_use","id":"...","name":"write","input":{}}- any number of
input_json_deltafragments (encode.rs:416-423) 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)
-
Call::publishprefix invariant (dsml.rs:53-62).published_argument_bytesonly ever advances toarguments.len()insidepublish, andclose_literal(dsml.rs:65-78) can only rewrite in place the slice starting atliteralwhileliteral.is_some()blockspublish. I traced every mutation ofarguments:LabelToolCallArguments(dsml.rs:165push_str, setsliteral = Some(len)forKeyValueSeparator),ToolCallArgumentsText(dsml.rs:180/189push_strthencheck_sizethenpublish), andToolCallArgumentsEnd(dsml.rs:200push_str(closing_text)). Hencepublished_argument_bytes ≤ literal_startalways, solive = arguments[published..]never contains a byte thatclose_literalcan replace — the "no published byte is replaced" claim holds. Thestring="false"path is safe becauseLabelToolCallArguments(ArgumentSeparator)callsclose_literal()before appending the separator (dsml.rs:162-165), andToolCallArgumentsEndcalls it beforeclosing_text(dsml.rs:199-200); in both casespublishis then invoked withliteral == None, so the retained text ships exactly once. -
End-before-begin ordering (dsml.rs:145-206).
ToolBeginis now pushed atToolNameEndguarded by!repeated;ToolEndatToolCallArgumentsEndalso!repeated;self.callsis incremented exactly once, after the end event, soEvent::ToolBegin{index}/ToolArguments{index}/ToolEnd{index}stay consistently indexed. A repeatedToolCallArgumentsEndaction falls through to_ => {}and cannot double-publish.ToolCallArgumentsEndtakes the call (self.call.take()), socheck_sizeat dsml.rs:218-220 cannot see a stale call. -
check_sizemoved before/after publication (dsml.rs:191-192 vs docs/api.md:571-575).check_sizeruns beforepublishon the text path, so the fragment that crosses the 1 MiB bound is never published and the call can never complete (self.callstaysSome, so a laterToolCallArgumentsEndre-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. -
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: onlyEosmeans "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 onEosinside an announced call and clearsself.callforCancelled|ExecutionError, soAccumulator::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. -
Abandoned-index bookkeeping (output.rs:1735-1762, encode.rs:687-707).
finishonly marksabandonedwhenself.open.is_some()and the last block is aBlock::Tool;ToolBegin(output.rs:1811-1822) callsclosefirst and always pushes atblocks.len(), so an open tool block is always last →last == self.openandChange::End(last)matches;discard_abandonedthen pops exactly that block and itscallsentry, sohas_tools()(output.rs:1710-1712) afterwards reflects only completed calls and theRequired | Namedcheck at encode.rs:708-712 fails correctly (verified by the new test at tests.rs:4194-4231). Theabandoned |= truncated+incomplete_item = Nonereset at encode.rs:698-707 correctly scopes the marker to the discarded item so a later completed item is not mislabeledincomplete;self.incomplete_item = Some(*i)beforechange(change)is required becauseitem()reads it (encode.rs:340). -
Custom-tool truncation (encode.rs:470-517).
abandoned && customskipsserde_json::from_strandgrammar.validate, anditem(i, false)yieldsinput: ""withstatus: "incomplete"; the!abandonedguard suppressescustom_tool_call_input.delta/.done. Confirmed againstitem()(encode.rs:366-379). No partial input leaks. -
Strict-tool parking unchanged (encode.rs:571-631).
Event::ToolBeginfor a strict tool stillcontinues intopending_strict_calls[index]before anyResponseOutput/Accumulatormutation, and arguments are re-emitted only afterstrict_validators[..].validate(&arguments)succeeds — so no frame precedes schema acceptance. This matches the PR claim. -
Test-side consistency.
helios/tests/deepseek_output.rs:501-516and:581-595were correctly weakened from "no events published" to "noToolEndreported" (parsed.ended == 0), which is the only property that still holds now thatToolBegin/ToolArgumentspublish early; the rejection assertions at :514 still pin the error text.helios/tests/deepseek_requests.rs:684-693similarly 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.