PR #685: fix(frontend): stream DeepSeek tool-call arguments

Raw Markdown for agents: https://autobot.eidonix.com/api/v1/cases/91494b52-270b-424c-ac0b-f5344388ea0e

Opened by a workflow run, Dec 2, 2026 1:07 PM EST. decide malicious: all_clear (100%): No malicious content found

explore

Author: peperunas (FIRST_TIME_CONTRIBUTOR; one previous PR #519, closed unmerged; Discord: peperunas) Motivation: Flare's DeepSeek (DSML) parser collected a tool call's whole argument object and only released it to the client when the closing tag arrived, so a multi-kilobyte write argument left the SSE stream silent for the entire generation — indistinguishable from a hung model. The pull request publishes the call name as soon as the header completes and streams argument fragments as the model writes them. Scale: +662 / −72 lines in 13 files Proposal:

Full report · Notes

Value Proposition

Value Proposition — PR #685 "fix(frontend): stream DeepSeek tool-call arguments"

Charter alignment — mostly yes. The vision targets "coding agents, and heavy tool use"; a DSML call that leaves function.arguments silent for a multi-kilobyte write value is exactly that workload's failure mode, and the fix changes when the parser publishes rather than swallowing an error (#397). No shared-layer per-model branch is added: DsmlOutput is the only parser changed semantically, and drops_unfinished_call is a Termination predicate, not a dialect flag (#267, #334). The description carries the four expected parts and is candid that the tagged dialects still buffer, were not exercised live, and that flare/flare-cli were not built.

Novelty — genuinely additive. Nothing on main streams DSML argument fragments; open #577 and #575 touch other dialects. Not obsolete, not superseded by any open PR.

Fit risk — no demand trail. "What gets merged" wants a maintainer request, roadmap item, reproducible bug, or measured issue. No issue asks for streaming tool arguments; docs/api.md:540-541 on main documented the buffering as the contract. Evidence is served-workload measurement (566 frames / 2196 bytes, hash-equal to non-streaming), but self-reported, single model, author's own endpoint, with no CI on head 2f0ed9d and test counts that shifted in the body (1783/18 → 1787/16) while the commit stayed the same.

Cost — a second, undisclosed behaviour change rides along. Behind the DSML-only win, Accumulator::finish(cause)/ResponseOutput::finish(cause) drop announced-but-unfinished calls for every termination except Eos — all tool parsers, all three wire protocols — turning main's server_error "incomplete emitted tool call" into success. That inverts the deliberate user_stop_cannot_retract_an_already_emitted_partial_tool_call test (renamed, one clause of the body) and reverses #364's reviewed "check the 1 MiB bound before emitting any tool event" ordering, now documented as tripping after publication. Clients that received content_block_start/output_item.added for a dropped call never get its closing event. #670 rewrote the same docs/api.md parser section after the branch point, so a rebase is required.

Verdict: Worth it with changes. The streaming fix is root-cause, small-footprint, and serves the target workload. It should not carry a universal, unstated truncation-semantics reversal: split that into its own PR with a filed rationale, or drop it and keep main's error. Re-negotiate the #364 bound with @voipmonitor and @yatesdr, rebase over #670, get CI green, and state the truncation change in the body as the reversal it is.

Full report Decide Value: yes (99%): This change is worth reviewing: it provides value to the project in line with its charter.

Classify intake

Selected: triage:review, performance, area:api, model:deepseek-v4, model:deepseek-v4.1

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

Applied: +triage:review, +performance, +area:api, +model:deepseek-v4, +model:deepseek-v4.1

Subtraction and simplicity

Subtraction/Simplicity review of PR #685 (fix(frontend): stream DeepSeek tool-call arguments). The production change itself is lean — DsmlOutput::publish is six lines, the Event::ToolBegin move is a net deletion, and no new flag, knob, env var, trait, enum variant or per-model branch is added — but four subtraction items and one dead line are worth fixing.

  1. One rule spelled twice (high): the new drops_unfinished_call(cause) { cause != Termination::Eos } (helios/src/server/output.rs:476-480) is logically identical to the existing four-arm matches! in TaggedTools::eos_decision (helios/src/output/tagged.rs:247-255), since Termination has exactly those five variants (helios/src/output.rs:51-58). Move the predicate beside the enum and use it there; the copy's pub(crate) is also unnecessary since both uses are in the same module.
  2. finish(cause) sweep (high): the new mandatory cause argument on Accumulator::finish (output.rs:163) and ResponseOutput::finish (output.rs:1730) has exactly one production caller (helios/src/server/protocol/encode.rs:675,677); every other call site is a test passing Termination::Eos, and eight of thirteen changed files exist only for that sweep (argument_tags.rs, chatml.rs, gemma_call.rs (not opened), minimax_xml.rs, pipeline.rs, xtml.rs, runtime_core/protobuf.rs, server/runtime/phase_tests.rs). An explicit drop_unfinished_call(&mut self) called from Encoder::finish removes the threading and the churn; counterweight: ModelOutput::finish(cause) already exists in the same layer (helios/src/output.rs:92,97).
  3. Same-named duplicate tests (medium): a_truncated_second_call_keeps_the_completed_first_call and a_header_only_call_is_omitted_when_the_response_truncates each exist twice, in helios/src/output/dsml.rs:940,963 and helios/src/server/protocol/tests.rs:3894,3964; the parser copies (~46 lines) are subsumed by the wire copies.
  4. docs/api.md:547-551 restates the finish-reason mapping already specified at docs/api.md:580-589, and docs/api.md:550-551 argues for the design instead of specifying behaviour (AGENTS.md:52-60).
  5. call.check_size()? at dsml.rs:191 duplicates the loop-tail check at dsml.rs:218-220 with no mutation between them; delete line 191 (the one at dsml.rs:201 must stay, that arm takes the call).

Open: whether the finish(cause) shape is deliberate consistency with the parser trait; whether the truncation semantics change (documented at docs/api.md:570-572 for the 1 MiB bound, and the dropped-call rule) needs a maintainer decision (#364, #333); and whether the flaky-engram test claim holds, which no CI run corroborates.

Full report · Notes

Correctness and contracts

PR #685 (stream DeepSeek tool-call arguments) has a sound core mechanism but four serious problems elsewhere in the diff.

Blockers/major

Verified clean: no lock/queue contention, no memory amplification (dsml.rs:57-60 slices), string="false" deferred correctly, strict parking untouched (encode.rs:564-621), abort path unaffected.

Open: whether dropping the partial call is deliberate; whether the missing stream close is acceptable to contract owners; why counts changed at an unchanged head (no CI at all); whether flare/flare-cli build.

Full report · Notes

Final review

Recommendation: Changes Requested

The core streaming mechanism in DsmlOutput (Call::publish with published_argument_bytes and literal deferral for string="false" values) is small, clean, and directly addresses the stalled-stream UX for multi-kilobyte DeepSeek tool calls while keeping strict-tool parking intact. However, this PR cannot merge as-is: it breaks four existing integration tests in helios/tests/ that were skipped because only --lib was run, leaves already-announced Messages/Responses tool blocks permanently unclosed (content_block_stop / response.output_item.done never emitted) when a call is truncated, and reverses reviewed pre-publication and retraction invariants without maintainer sign-off or explicit before/after disclosure in the PR description.

Merge Risk

Level: High

Walkthrough

Pre-merge Checks

Blockers

  1. Four existing integration tests in helios/tests/ fail on head 2f0ed9d

    • helios/tests/deepseek_output.rs:476-512 (empty_and_duplicate_top_level_parameter_names_are_rejected), helios/tests/deepseek_output.rs:568-593, 596-619, 622-635 (parse_literal_parameters, called by tool_call_size_includes_retained_strings_and_closing_brace_in_either_order and literal_nesting_includes_the_enclosing_argument_object), and helios/tests/deepseek_requests.rs:652-687 (added_non_special_dsml_token_produces_tool_calls).
    • Verified behavior/impact: Because the PR only ran cargo test ... --lib, all integration tests in helios/tests/ were skipped, whereas CI (.github/workflows/native-serving.yml:63 (not opened),68) runs cargo test --locked --release --manifest-path helios/Cargo.toml (not opened) --features runtime-core,server:
      1. deepseek_output.rs:511 asserts assert!(published.is_empty()) when feeding char-by-char input with empty or duplicate parameter names; DsmlOutput::apply (dsml.rs:145-156) now emits Event::ToolBegin at ToolNameEnd before parameters are parsed, so published is non-empty and the assertion panics.
      2. deepseek_output.rs:576 asserts assert!(output.push(Input::Text(&header))?.is_empty()) on "{open}<|DSML|{s}invoke name=\"lookup\">", which now emits Event::ToolBegin and panics immediately (and :581 asserts .is_empty() across multi-parameter string="false" pushes even though the next parameter's ArgumentSeparator closes the previous literal and publishes on the next parameter key, breaking both tool_call_size_includes_retained_strings_and_closing_brace_in_either_order and literal_nesting_includes_the_enclosing_argument_object).
      3. deepseek_requests.rs:683-684 feeds "Berlin" one byte-token at a time via the zero-merge byte-level BPE fixture (:37-53) and evaluates serde_json::from_str::<Value>(text).unwrap() on each individual Event::ToolArguments event; the first fragment is "{\"location\": \"B", so .unwrap() panics.
    • Fix: Run the full helios release test suite (without --lib), plus flare and flare-cli per docs/design-review.md:180-185. Update deepseek_requests.rs:683-684 to concatenate Event::ToolArguments fragments (matching lines 875-882 in the same file), and update deepseek_output.rs:511, 568-593 once maintainers sign off on the relaxed pre-publication contract (see Should Fix #1).
  2. Truncating an announced tool call leaves Messages and Responses SSE streams with unclosed blocks/items

    • helios/src/server/output.rs:1720-1742, helios/src/server/protocol/encode.rs:409-415, 424-429, 430-434, 470-517, 677-684, 730-745, helios/src/server/http.rs:526-573.
    • Verified behavior/impact: When Event::ToolBegin arrives, Encoder::change immediately yields content_block_start (Messages, encode.rs:411-414) or response.output_item.added (Responses, encode.rs:431-434) over SSE (http.rs:571-573), followed by input_json_delta / response.function_call_arguments.delta frames. When OutputLimit, UserStop, Cancelled, or ExecutionError then triggers Encoder::finish, ResponseOutput::finish(cause) (output.rs:1730-1742) pops self.blocks and self.calls and sets self.open = None before calling self.close(&mut changes)?, returning an empty Vec<Change>. Encoder::finish therefore emits message_delta + message_stop (Messages) without content_block_stop, and response.incomplete/response.completed (Responses) with "output": [] without response.output_item.done (affecting both function tools and custom tools at encode.rs:366-386). On main, this path returned Err("incomplete emitted tool call") and emitted a terminal error frame (error / response.failed); converting it to a "successful" terminal stream without closing the opened block violates both SSE grammars. The new truncation tests (helios/src/server/protocol/tests.rs:3809-3891, 3964-4001) only assert !finished.is_empty() and encoder.response(), so they do not detect the missing close frames.
    • Fix: Emit the terminal per-block close frame before omitting the unfinished tool block from the final buffered body (e.g., an explicit Change::Abort(i) or closing before popping): emit content_block_stop { index: i } for Messages, and response.output_item.done with status: "incomplete" for Responses (bypassing the custom-tool JSON/grammar validation at encode.rs:475-485 for aborted calls so truncated custom-tool JSON does not turn an omission into a parse error). Add stream-framing assertions to protocol/tests.rs:3809-4001 (following messages_stream_reconstructs_ordered_buffered_blocks at :1098-1152 and :1195-1200) verifying every content_block_start has a matching content_block_stop and every response.output_item.added has a matching response.output_item.done.

Should Fix

  1. Obtain explicit maintainer sign-off and document the contract reversals in the PR description (AGENTS.md:88-93, 182-187, 204-207)
    • helios/src/server/output.rs:163-173, 1265-1274, helios/src/output/dsml.rs:191-205, docs/api.md:540-555, 570-572.
    • Streaming DSML calls before </|DSML|invoke> inherently reverses three previously tested guarantees:
      1. #364 (authored by @voipmonitor, reviewed by @yatesdr): the 1 MiB call-size check previously ran before emitting any tool event (docs/api.md:560 on main, helios/tests/deepseek_output.rs:596-619), whereas now earlier fragments are published before the oversized append fails (docs/api.md:570-572).
      2. validate_arguments (dsml.rs:202, 398-426) runs at ToolCallArgumentsEnd, so duplicate or empty parameter names now stream ToolBegin and partial ToolArguments before returning a delivery error (http.rs:575-579), breaking deepseek_output.rs:511.
      3. Truncating an already-announced call (OutputLimit, UserStop, Cancelled, ExecutionError) previously returned Err("incomplete emitted tool call") (server_error) as asserted by user_stop_cannot_retract_an_already_emitted_partial_tool_call (server/output.rs:1257-1271 on main), whereas now Accumulator::finish / ResponseOutput::finish succeed with a cause-derived finish_reason ("length", "stop", or "tool_calls" when an earlier call completed, encode.rs:690-696) while dropping the partial call from encoder.response() — meaning streaming Chat clients receive a tool_calls[0] header/fragment delta that the final buffered message omits.
    • Fix: Request explicit sign-off from @voipmonitor and @yatesdr on (a) relaxing #364's pre-publication 1 MiB and key-validation guarantees for streamed DSML calls, and (b) whether truncated streamed calls should omit-and-succeed vs error (and how Chat/Messages/Responses streaming vs buffered parity is defined). Update the PR description to state these before/after behavioral reversals explicitly, and rebase onto main so docs/api.md:543-547 accurately reflects #670's TAGGED_JSON parser (which buffers JSON objects rather than parameter syntax).

Subtract / Simplify

  1. Avoid the 8-file mechanical finish(Termination::Eos) sweep (AGENTS.md:188-193)
    • helios/src/server/output.rs:163-173, 1730-1742, helios/src/server/protocol/encode.rs:674-677, plus 21 one-token test edits across argument_tags.rs, chatml.rs, gemma_call.rs, minimax_xml.rs, pipeline.rs, xtml.rs, runtime_core/protobuf.rs, and server/runtime/phase_tests.rs.
    • Encoder::finish (encode.rs:675, 677) is the sole production caller that owns cause. Keeping Accumulator::finish(&self) and ResponseOutput::finish(&mut self) parameter-free and adding an explicit drop_unfinished_call / abort_unfinished_call method called from Encoder::finish (and test helper Presentation::finish) when cause.omits_unfinished_call() reverts all 8 unrelated files to zero diff and keeps finish() a pure invariant check.
  2. Unify drops_unfinished_call with TaggedTools::eos_decision
    • helios/src/server/output.rs:478-480 vs helios/src/output/tagged.rs:247-255 and helios/src/output.rs:51-58.
    • Termination has exactly five variants (Eos, OutputLimit, UserStop, Cancelled, ExecutionError), so cause != Termination::Eos (server/output.rs:479) and matches!(cause, Cancelled | ExecutionError | UserStop | OutputLimit) (tagged.rs:248-254) express the exact same policy in two modules with opposite polarities. Move the method onto Termination in helios/src/output.rs:58 (e.g., pub(crate) fn omits_unfinished_call(self) -> bool { self != Self::Eos }), use it in both tagged.rs:248 and server/output.rs, and delete server/output.rs:476-480 (which is currently unnecessarily pub(crate) for same-file callers).
  3. Delete the redundant call.check_size()? at helios/src/output/dsml.rs:191
    • helios/src/output/dsml.rs:191-192 vs helios/src/output/dsml.rs:218-220.
    • apply() writes into a local events Vec owned by push() (:359) or finish() (:387) that is discarded whenever apply() returns Err. call.publish (:192) does not mutate call.name or call.arguments, so :218-220 checks identical state and discards events on overflow identically. Delete :191 (keep :201 in ToolCallArgumentsEnd, where self.call.take() at :196 bypasses :218).
  4. Deduplicate docs/api.md finish-reason text
    • docs/api.md:547-551 duplicates the normative finish-reason mapping already defined at docs/api.md:580-589, and line 550-551 ("A client that received fragments of such a call has already seen a call that cannot complete") omits the concrete wire framing behavior clients must handle. Keep only the omission rule at :547-549, cross-reference :580-589 for finish reasons, and state the exact terminal SSE event behavior once Blocker #2 is fixed.

Nits

Dropped on verification

Full report

Classify triage

Selected: triage:review

Threshold: 65%

Triage

Apply labels

No label changes Decision to Test: no (100%): Testing will not add significant value as the code stands today. The code is either not yet ready to merge, or adequate testing has already been done to validate the contents of the code, or the available hardware is not suitable to test with. decide malicious: all_clear (100%): No malicious content found

explore

Author: peperunas (FIRST_TIME_CONTRIBUTOR; prior PR #519 closed unmerged; Discord: peperunas) Motivation: DeepSeek tool calls arrive silently: the DSML parser holds the whole call until the closing tag, so a multi-kilobyte write argument leaves the client stream blank for the entire generation, which looks like a hang. The PR publishes the call name as soon as the header completes and streams argument fragments as the model writes them. Scale: +662 / −72 lines in 13 files Proposal:

Full report · Notes

Classify intake

Selected: triage:review, bug, performance, enhancement, area:api, model:deepseek-v4, model:deepseek-v4.1

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

Applied: +bug, +enhancement

Subtraction and simplicity

The core streaming change in #685 is lean — Call::publish is ~10 lines, one new field, no new event variant, no flag or wrapper, and ToolCallArgumentsEnd is a net −9-line simplification of an old 3-event extend. Removability is concentrated in two high-value places.

  1. The finish(cause) parameter sweep (high). Accumulator::finish and ResponseOutput::finish gained a Termination argument (output.rs:163, :1730) whose only job is one boolean, drops_unfinished_call(cause) = cause != Eos (output.rs:476-480). It costs 21 mechanically edited call sites across 8 files that change nothing else (+21/−21: argument_tags.rs, chatml.rs, gemma_call.rs, minimax_xml.rs (not opened), pipeline.rs, xtml.rs, protobuf.rs, phase_tests.rs), ~8 more in output.rs tests, and 6 in dsml.rs, while the decision is made at exactly one place: encode.rs:674-677. Replace with finish() unchanged plus one drop_unfinished(&mut self) called from Encoder::finish when cause != Termination::Eos; the helper disappears entirely.

  2. Two duplicated tests, under identical names (high). a_truncated_second_call_keeps_the_completed_first_call exists at dsml.rs:940 and protocol/tests.rs:3894; a_header_only_call_is_omitted_when_the_response_truncates at dsml.rs:963 and protocol/tests.rs:3964. Keep the protocol-level copies (they assert the user-visible buffered body and finish_reason across three protocols); the dsml copies repeat what dsml.rs:793 and :917 already assert. Also rejection_tests::end_of_sequence_inside_an_announced_call_is_an_error (dsml.rs:1003-1011) restates existing integration coverage.

  3. Duplicate size check (medium). dsml.rs:191 call.check_size()? was added immediately before publish, but the pre-existing post-match check at dsml.rs:218-220 already runs on the same iteration over the same state. Delete line 191.

  4. Docs overreach (medium). docs/api.md:544-548 justifies the tagged parsers (untouched by this PR, and the justification is already false for TAGGED_JSON), and :551-552 ("A client that received fragments of such a call has already seen a call that cannot complete") is commentary that describes the unresolved missing-stop-frame gap.

Open: whether the automated review's "Subtract/Simplify: 4" items are these; whether the dsml-level duplicates were deliberate layering; minimax_xml.rs (not opened) and phase_tests.rs diffs were inferred mechanical (+1/−1, +2/−2) rather than read.

Full report · Notes

Correctness and contracts

PR #685 at head 80c87b3 streams DSML tool-call fragments correctly at the parser layer, but the surrounding contract work is not safe to merge: it trades a silent-generation complaint for unclosed protocol blocks, broken integration tests, and a silently weakened error guarantee.

Findings, most important first:

  1. Blocker — an announced-but-dropped call leaves a Messages/Responses block unclosed. ResponseOutput::finish pops the block and clears open before close(), the only producer of Change::End (helios/src/server/output.rs:1730-1742), yet Encoder::finish still sends message_delta/message_stop and response.incomplete/response.completed (helios/src/server/protocol/encode.rs:730-745), so content_block_start/response.output_item.added never get their stop/done, and stop_reason contradicts the stream.
  2. Blocker — four existing integration tests fail on merge; CI runs the whole helios target (.github/workflows/native-serving.yml:63 (not opened),68) and the author's --lib evidence cannot see them (helios/tests/deepseek_output.rs:511,576,581, helios/tests/deepseek_requests.rs:684).
  3. Blocker — drops_unfinished_call(cause) -> cause != Termination::Eos (helios/src/server/output.rs:476-480) turns Err("incomplete emitted tool call") into success for UserStop, Cancelled and ExecutionError, with finish reason stop/end_turn, documented as contract (docs/api.md:547-551) and pinned by an inverted test (output.rs:1265-1274) — a weakened guarantee with no maintainer decision (AGENTS.md:182-187, 201-207).
  4. Major — the 1 MiB bound is now enforced after publication (docs/api.md:568-572, helios/src/output/dsml.rs:189-192), reversing #364's pre-publication invariant and compounding finding 1 on overflow.
  5. Minor — docs/api.md:543-547 describes tagged parsers as schema-building, already false for TAGGED_JSON (#670).

Sound: fragment bytes concatenate exactly to stored arguments, string="false" withholding, strict parking, per-request state only, no new contention/amplification, TTFT sampling unchanged.

Full report · Notes

Re-review

Recommendation: Changes Requested

The core streaming mechanism in DsmlOutput (Call::publish with published_argument_bytes and string="false" literal deferral) is minimal, byte-exact, and directly solves stalled streaming for large DeepSeek tool calls without adding per-model runtime branches or hurting concurrency/TTFT. However, the PR at 80c87b3 breaks four existing integration tests in helios/tests/ that CI runs unconditionally, introduces a streaming SSE framing violation on Messages and Responses when an announced tool call is truncated, and reverses the reviewed Err("incomplete emitted tool call") contract on UserStop/Cancelled/ExecutionError without maintainer sign-off.

Merge Risk

Level: High

Walkthrough

Pre-merge Checks

Blockers

  1. Four existing integration tests in helios/tests/ fail under CI (.github/workflows/native-serving.yml:63 (not opened), 68):

    • CI runs cargo test --locked --release --manifest-path helios/Cargo.toml (not opened) --target-dir flare-cli/target --features runtime-core,server (without --lib), and this PR modifies no files in helios/tests/.
    • helios/tests/deepseek_output.rs:576, 581 (parse_literal_parameters, used by tool_call_size_includes_retained_strings_and_closing_brace_in_either_order at :596-619 and literal_nesting_includes_the_enclosing_argument_object at :622-635): asserts output.push(Input::Text(&header))?.is_empty() and output.push(Input::Text(&parameter))?.is_empty(). ToolNameEnd now emits Event::ToolBegin (helios/src/output/dsml.rs:145-156) and parameter key text emits Event::ToolArguments (dsml.rs:191-192), failing both assertions.
    • helios/tests/deepseek_output.rs:510-511 (empty_and_duplicate_top_level_parameter_names_are_rejected): asserts published.is_empty() after duplicate/empty key rejection, but Event::ToolBegin and early argument fragments are now emitted before validate_arguments runs at ToolCallArgumentsEnd (dsml.rs:151-155, 192, 202).
    • helios/tests/deepseek_requests.rs:683-684 (added_non_special_dsml_token_produces_tool_calls): runs serde_json::from_str::<Value>(text).unwrap() on a single Event::ToolArguments event, which panics now that individual events carry partial JSON fragments.
    • Fix: Update these four integration tests to match incremental DSML emission (collect/verify streamed ToolBegin and concatenated ToolArguments, verify no ToolEnd is emitted on rejected/oversized calls) and verify with the full CI test commands across helios, flare, and flare-cli (docs/design-review.md:180-185).
  2. Truncating an announced tool call leaves Messages and Responses SSE blocks/items permanently unclosed (helios/src/server/output.rs:1730-1742, helios/src/server/protocol/encode.rs:409-517, 730-745):

    • ResponseOutput::apply emits Change::Start(i) on Event::ToolBegin (output.rs:1792-1802), which sends content_block_start on Messages (encode.rs:409-415) and response.output_item.added on Responses (encode.rs:430-434).
    • On non-EOS termination, ResponseOutput::finish (output.rs:1730-1742) pops self.blocks, pops self.calls, and sets self.open = None before calling self.close(&mut changes) (output.rs:1720-1729), which is the sole producer of Change::End(i) — and Change::End(i) is the sole producer of content_block_stop (encode.rs:424-429) and response.output_item.done (encode.rs:470-517).
    • Encoder::finish (encode.rs:730-745) then unconditionally sends message_delta/message_stop (with stop_reason: "end_turn" / "max_tokens" / "stop_sequence") or response.incomplete/response.completed (whose response.output omits the announced item) without ever closing the open tool block/item. This breaks strict SSE parsers/SDK assemblers for both function tools and Responses custom tools (encode.rs:458-460).
    • The new tests in helios/src/server/protocol/tests.rs:3810-4001 miss this because they assert only encoder.response() and !finished.is_empty(), never the emitted frame sequence.
    • Fix: Do not emit terminal message_stop / response.completed / response.incomplete frames while a previously announced block/item is unclosed. Either preserve Err("incomplete emitted tool call") (so http.rs:575-579 terminates the stream with encoder.failure(&e)), or — for causes where omission from the final body is approved (e.g., OutputLimit) — emit a valid closing frame (content_block_stop on Messages; on Responses, response.output_item.done with status: "incomplete", skipping the complete-JSON custom-tool validation at encode.rs:475-485) before omitting the incomplete item from the final response. Add frame-sequence assertions to helios/src/server/protocol/tests.rs:3810-4001.
  3. Unapproved reversal of Err("incomplete emitted tool call") for UserStop, Cancelled, and ExecutionError (helios/src/server/output.rs:163-173, 476-480, 1265-1274, 1730-1742, docs/api.md:547-551):

    • drops_unfinished_call(cause) (output.rs:478-480) returns true for every Termination except Eos, silently omitting an already-announced incomplete tool call across all parsers and all three wire protocols instead of returning Err("incomplete emitted tool call").
    • While production HTTP execution errors still travel via GenerationEvent::Error(e) → encoder.failure(&e) (helios/src/server/http.rs:562-579, helios/src/server/runtime.rs:321-329, 2053-2070, 2351-2373), UserStop (matched stop string mid-call) and Cancelled do flow through Encoder::finish — and direct callers of Accumulator/ResponseOutput/Encoder::finish with ExecutionError also now succeed with finish_reason: "stop" / end_turn / completed and no tool_calls after already streaming partial tool frames.
    • The PR renames and inverts the regression test that pinned this invariant (user_stop_cannot_retract_an_already_emitted_partial_tool_call → user_stop_omits_an_already_emitted_partial_tool_call, output.rs:1265-1274) and rewrites docs/api.md:547-551 without an explicit maintainer design decision, contravening AGENTS.md:182-187, 201-207 ("Do not ... suppress errors ... Apply these criteria to documentation and test changes that would weaken the rules as well as code").
    • Fix: Narrow unfinished-call omission to Termination::OutputLimit (consistent with main's docs/api.md:542-543 contract for output-limit truncation) and keep Err("incomplete emitted tool call") plus user_stop_cannot_retract_an_already_emitted_partial_tool_call for UserStop/Cancelled/ExecutionError, or obtain explicit maintainer sign-off before changing that contract.

Should Fix

  1. docs/api.md:543-547 is already factually inaccurate against main (#670 TAGGED_JSON):

    • docs/api.md:543-547 claims that "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."
    • On main, #670 added TAGGED_JSON (helios/src/output/tagged_json.rs:12-66 on main, docs/api.md:610-619 on main), which sets TRIM_NEWLINES = false and JSON_BODY = true, parses the model's {"name": ..., "arguments": ...} JSON object directly without parameter syntax or schema coercion, and re-serializes object["arguments"].to_string().
    • Additionally, docs/api.md:550-551 ("A client that received fragments of such a call has already seen a call that cannot complete.") is commentary rather than wire specification.
    • Fix: Rebase onto main, replace lines 543-547 with a concise, dialect-accurate sentence (e.g., "The other tool parsers publish a call only when its envelope is complete, so their argument events do not imply incremental generation."), and replace lines 550-551 with the concrete wire-framing contract resolved in Blocker #2.
  2. Disclose and obtain maintainer sign-off on relaxing #364's pre-publication 1 MiB bound (docs/api.md:569-572, helios/src/output/dsml.rs:145-156, 189-192):

    • #364 intentionally enforced the 1 MiB combined name+arguments limit before emitting the first tool event (docs/api.md:560 on main: "Helios rejects a larger call before publishing it.").
    • Incremental streaming inherently relaxes this: Event::ToolBegin and earlier Event::ToolArguments fragments are emitted before a later append crosses 1 MiB (dsml.rs:191 still rejects the crossing fragment before publish at :192, and http.rs:575-579 terminates the stream with an error frame).
    • Fix: Call out this #364 contract relaxation explicitly in the PR description and get maintainer sign-off (@voipmonitor / @yatesdr) per AGENTS.md:201-207.

Subtract / Simplify

  1. Eliminate finish(cause) churn across 8 unrelated files (helios/src/server/output.rs:163-173, 476-480, 1730-1742, helios/src/server/protocol/encode.rs:674-677):

    • Adding cause: Termination to Accumulator::finish and ResponseOutput::finish produces mechanical +21/-21 edits across 8 otherwise-untouched files (helios/src/output/{argument_tags,chatml,gemma_call,minimax_xml,pipeline,xtml}.rs, helios/src/runtime_core/protobuf.rs, helios/src/server/runtime/phase_tests.rs) plus 15 test call sites in dsml.rs and output.rs, for a single production caller (encode.rs:674-677).
    • Simplification: Keep Accumulator::finish(&mut self) and ResponseOutput::finish(&mut self) zero-argument, delete drops_unfinished_call, and invoke an explicit truncation method (e.g. drop_unfinished / finish_truncated) only from encode.rs:674-677 for the approved truncation cause(s). This removes 8 files from the PR diff.
  2. Deduplicate new unit test structure in helios/src/output/dsml.rs:940-1032:

    • rejection_tests (dsml.rs:988-1032) duplicates streaming_tests's fixture/imports (dsml.rs:750-763) solely to pass OutputStart::Content, and end_of_sequence_inside_an_announced_call_is_an_error (dsml.rs:1003-1011) overlaps helios/tests/deepseek_output.rs:387-421 (incomplete_calls_do_not_finish_on_eos_and_can_be_cancelled_or_truncated) plus dsml.rs:793.
    • a_truncated_second_call_keeps_the_completed_first_call (dsml.rs:940-960) and a_header_only_call_is_omitted_when_the_response_truncates (dsml.rs:963-984) reuse the exact names of helios/src/server/protocol/tests.rs:3894-3961, 3964-4001; their Accumulator truncation assertions repeat protocol/tests.rs.
    • Simplification: Merge rejection_tests into streaming_tests (keeping a_rejected_argument_object_fails_after_its_fragments_are_published), remove end_of_sequence_inside_an_announced_call_is_an_error, and keep dsml.rs focused on DsmlOutput event assertions under distinct names rather than repeating Accumulator truncation checks.

Nits

  1. ResponseOutput::finish does not check ended: false (helios/src/server/output.rs:1733): Accumulator::finish (:165) checks !call.ended and ResponseOutput::close (:1722) checks Block::Tool { ended: false, .. }, whereas ResponseOutput::finish (:1733) matches Some(Block::Tool { .. }). Currently unreachable because Event::ToolEnd immediately calls close() (:1842-1843), but matching Some(Block::Tool { ended: false, .. }) makes the invariant self-contained.
  2. Extend the end-to-end DSML wire test to Messages and Responses (helios/src/server/protocol/tests.rs:4004-4073): dsml_arguments_reach_the_chat_wire_while_the_call_is_open currently exercises OutputPipeline → Encoder only for Protocol::Chat; covering Protocol::Messages and Protocol::Responses as well would pin incremental input_json_delta and response.function_call_arguments.delta delivery end-to-end.

Dropped on verification

Full report Decision to Test: no (100%): Testing will not add significant value as the code stands today. The code is either not yet ready to merge, or adequate testing has already been done to validate the contents of the code, or the available hardware is not suitable to test with.

Classify triage

Selected: triage:review

Threshold: 65%

Triage

Apply labels

No label changes decide malicious: all_clear (100%): No malicious content found

explore

Author: peperunas (FIRST_TIME_CONTRIBUTOR; prior PR #519 closed unmerged; Discord: peperunas) Motivation: DeepSeek tool calls arrive all at once when the closing tag is parsed, so a multi-kilobyte write argument leaves the stream silent long enough that clients render a stall or a hung model. The PR makes the DSML parser announce the call at name completion and publish argument fragments as the model writes them. Scale: +722 / −80 in 15 files Proposal:

Full report · Notes

Classify intake

Selected: triage:review, bug, performance, enhancement, area:api, model:deepseek-v4, model:deepseek-v4.1

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

No label changes

Subtraction and simplicity

Lens: Subtraction, Simplicity & Conventions. The diff at head b9864ab (15 files, +722/−80, still labelled triage:review, labels include enhancement/performance) is mostly lean; the streaming core is load-bearing. Four concrete cuts, one convention violation.

  1. Accumulator::finish(cause) threads one boolean through 9 files: helios/src/server/output.rs:163-173, whose cause is used only via drops_unfinished_call (output.rs:478-480, cause != Eos). Restore finish(&self) as on main and add discard_unfinished_call(&mut self); revert ~21 finish(Termination::Eos) sites (argument_tags.rs:212,287,334,435,490; chatml.rs:418,650,833,1097; dsml.rs:456,500,567,631,699,789; gemma_call.rs:265 (not opened); minimax_xml.rs:346 (not opened); pipeline.rs:345,492,580,685,738; xtml.rs:464,508; protobuf.rs:1160). AGENTS.md:188-193.
  2. Abandoned-block machinery is over-built: output.rs:1745-1755 two public methods + abandoned field (:1703) for one Vec::pop pair; the index + 1 == self.blocks.len() guard (:1751) is unreachable and matches!(blocks.last(), Some(Block::Tool{..})) (:1735) cannot fail when open.is_some(). Collapse to discard_abandoned(&mut self), one trailing call at encode.rs:687-689.
  3. Truncation matrices expressed twice each: protocol/tests.rs:3979-4017 duplicates :3809-3907; dsml.rs:962-984 duplicates :917-937. Fold by parameterising the pre-cut; their cause lists are already skewed (:3912-3916 lacks ExecutionError, :3982-3986 lacks Cancelled).
  4. docs/api.md:543-547's "because" clause is false against main (TAGGED_JSON, #670) and blocks any rebase; delete it plus the non-normative :550-551 sentence.
  5. helios/tests/deepseek_output.rs:515 was rewritten to accept the new behaviour; AGENTS.md:182-187, 201-207 require withdrawing the accommodation.

Open: whether any maintainer authorised dropping the non-EOS Err("incomplete emitted tool call"); review status of b9864ab; no CI on any hash.

Full report · Notes

Correctness and contracts

Review of PR #685 at head b9864ab, correctness/contracts/system-consequences lens (static reading; nothing executed, no CI on the branch).

  1. BLOCKER — truncated custom/grammar tool call now fails the whole Responses request: Encoder::finish renders the abandoned block's Change::End through the custom branch, which serde_json::from_strs partial JSON with ? (encode.rs:475-483, from :677-689); http.rs:575-580 emits an error frame, no response.completed, and drop_abandoned never runs. Untested (new tests use function tool lookup only).
  2. MAJOR — for UserStop/Cancelled/ExecutionError the abandoned item's response.output_item.done says status:"completed" with partial arguments (encode.rs:339-346, :381, :486, :513-516; only OutputLimit sets incomplete_item at :680-683), then vanishes from response.completed.
  3. BLOCKER (authority) — announce at ToolNameEnd and publish per fragment now precede validate_arguments/1 MiB check_size (dsml.rs:145-156, :191-206 vs main:171-194); rejected/oversized calls reach the client and the pinning tests were rewritten (deepseek_output.rs:514-515, :572-601; output.rs:1264-1274). AGENTS.md:182-187/201-207 require sign-off; none on record, and it reverses #364's publish-after-check property.
  4. MAJOR (docs) — api.md:547-549's unconditional "omitted for every termination other than EOS" is contradicted by the required/named tool_choice error at encode.rs:690-694, which still ends in an error frame.
  5. MAJOR (docs) — api.md:543-547 ("tagged parsers build arguments from parameter syntax … rather than copying the model's text") is false against main's merged tagged_json.rs:17-49,57; this PR edits those exact lines.
  6. MAJOR (claim) — "ExecutionError included" is unreachable in production: only UserStop/Eos/OutputLimit reach Encoder::finish (http.rs:534-540); errors take http.rs:562→576. Test counts (1787/16, 113, 96) are stale for this head.
  7. CLEAN: per-request state only (no new locks/queues/shared state), fragment copies bounded by the 1 MiB limit, TTFT sampling excludes tool deltas (latency.rs:114-142), and the earlier Messages/Responses unclosed-block framing bug is genuinely fixed.

Open: whether a truncated custom tool is reachable in served configs; the prior reviews' "Should fix"/"Subtract" items; #347's body unreadable.

Full report · Notes

Re-review

Recommendation: Changes Requested

The incremental DSML streaming core (DsmlOutput::apply + Call::publish with published_argument_bytes and string="false" literal deferral) is clean, byte-exact, and avoids per-model shared-layer branches, concurrency hazards, or TTFT regressions, and b9864ab fixes the four previously broken helios/tests/ integration tests and the Messages closing-frame order. However, the new Change::End-before-drop path in b9864ab introduces a concrete regression that fails Responses requests (both streaming and non-streaming) whenever a custom tool call is truncated, and the PR still reverses reviewed pre-publication (#364) and non-EOS incomplete-call error contracts across code, tests, and docs without explicit maintainer sign-off (AGENTS.md:182-187, 201-207).

Merge Risk

Level: High

Walkthrough

Pre-merge Checks

Blockers

  1. Truncated custom tool calls on Responses now fail the entire request instead of being omitted (helios/src/server/protocol/encode.rs:470-485, 502-505, 677-689; helios/src/server/output.rs:1731-1744).

    • Verified behavior & impact: When a custom tool call (tool.custom == true) is truncated by OutputLimit or UserStop, ResponseOutput::finish(cause) emits Change::End(last) before drop_abandoned pops the block. Encoder::finish renders that Change::End through Encoder::change (encode.rs:685), which executes serde_json::from_str(arguments)? (:476-477), checks value.get("input").is_some_and(Value::is_string) (:478-480), runs grammar.validate(...) (:481-483), and checks item["input"].is_string() (:503-505). Because an abandoned call's arguments are empty or partial JSON by construction, Encoder::finish returns Err("invalid custom tool arguments: ..."), drop_abandoned never runs, streaming Responses requests fail with response.failed (helios/src/server/http.rs:575-580), and non-streaming Responses requests return an HTTP error (http.rs:639). This is a direct regression against main, where DsmlOutput buffered and discarded incomplete calls so both streaming and buffered Responses requests succeeded cleanly as incomplete/completed.
    • Fix: Pass whether Change::End(i) is closing an abandoned block into Encoder::change (or check abandoned == Some(i)), skip custom-tool JSON/grammar validation and response.custom_tool_call_input.{delta,done} emission for abandoned blocks, and emit only the closing response.output_item.done with "status": "incomplete" before discarding the block. Add a Responses protocol test covering a truncated custom tool call for both streaming frames and buffered response().
  2. Reversal of reviewed pre-publication, size-bound, and non-EOS error invariants without maintainer sign-off (helios/src/output/dsml.rs:145-156, 191-206; helios/src/server/output.rs:163-173, 478-480, 1265-1274; helios/tests/deepseek_output.rs:514-515; docs/api.md:547-551, 568-572).

    • Verified behavior & impact: Streaming DSML arguments before ToolCallArgumentsEnd inherently publishes ToolBegin and ToolArguments fragments before validate_arguments and before subsequent appends cross #364's 1 MiB bound (main docs/api.md:560 and helios/tests/deepseek_output.rs:511 pinned "nothing published before validation/size check"; b9864ab weakens :515 to assert_eq!(parsed.ended, 0)). Separately, drops_unfinished_call replaces main's non-EOS Err("incomplete emitted tool call") (pinned by main helios/src/server/output.rs:1257-1271, user_stop_cannot_retract_an_already_emitted_partial_tool_call, rewritten here to assert omission) across all tool parsers and wire protocols. Under AGENTS.md:182-187, 201-207, weakening existing validation/error guarantees — including via accompanying doc and test rewrites — requires an explicit maintainer design decision on record before merging.
    • Fix: Obtain explicit maintainer sign-off (e.g., from @yatesdr / @voipmonitor, who reviewed/authored #364 and the retraction semantics) recorded on this PR confirming (a) post-publication validation/1 MiB enforcement for streaming DSML calls and (b) non-EOS unfinished-call omission across protocols.

Should Fix

  1. Responses response.output_item.done reports status: "completed" with partial JSON arguments for non-OutputLimit truncated calls (helios/src/server/protocol/encode.rs:339-346, 381, 486, 509, 513-516, 680-685).

    • self.incomplete_item = Some(i) is set only when cause == Termination::OutputLimit (encode.rs:680-684). On UserStop (or Cancelled), Change::End renders self.item(i, true) with "status": "completed" and partial JSON in both response.function_call_arguments.done and response.output_item.done, right before drop_abandoned deletes that item from response.completed's output.
    • Fix: Set self.incomplete_item = Some(i) whenever abandoned == Some(i) (not only on OutputLimit), clear self.incomplete_item = None after the for change in changes loop, and extend the Responses truncation test to assert status == "incomplete" for all non-EOS causes.
  2. docs/api.md:547-550 states an unconditional truncation-omission rule contradicted by tool_choice: Required | Named (helios/src/server/protocol/encode.rs:690-694).

    • docs/api.md:547-550 claims an announced call cut off before completion is omitted and the response reports that termination's finish reason for every non-EOS termination. However, after drop_abandoned, if no completed tool call remains and tool_choice is Required or Named(_), encode.rs:690-694 returns Err("required tool choice was not satisfied: ..."), ending the request in an error frame / HTTP error.
    • Fix: Qualify docs/api.md:547-550 to note that tool_choice: "required" or a named tool still errors when omitting the truncated call leaves no completed tool call (and add a test pinning the intended behavior).
  3. docs/api.md:543-547 is factually false against main after #670 (TAGGED_JSON).

    • docs/api.md:543-547 states that all tagged tool parsers buffer "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." On main, TAGGED_JSON (helios/src/output/tagged_json.rs:14-49, 57, JSON_BODY = true, TRIM_NEWLINES = false) parses the model's JSON object directly without parameter syntax, schema coercion, or newline trimming.
    • Fix: Delete the over-generalized "because ... trimmed." clause so line 543-544 states simply: "The tagged tool parsers publish a call only when its envelope is complete." (The per-dialect details are already documented at docs/api.md:601-638 on main.)

Subtract / Simplify

  1. Restore Accumulator::finish(&self) and remove 8 files of mechanical test churn (helios/src/server/output.rs:163-173; helios/src/server/protocol/encode.rs:674-676; 8 test-only files).

    • Accumulator::finish(&mut self, cause: Termination) uses cause only to evaluate drops_unfinished_call(cause), forcing ~25 call sites across argument_tags.rs, chatml.rs, gemma_call.rs, minimax_xml.rs, pipeline.rs, xtml.rs, runtime_core/protobuf.rs, server/runtime/phase_tests.rs, dsml.rs, and server/output.rs to pass Termination::Eos.
    • Simplification: Keep Accumulator::finish(&self) -> Result<()> unchanged from main, add pub(crate) fn discard_unfinished_call(&mut self) (4 lines), and call it before finish() at the single production site (encode.rs:674-676, plus Presentation::finish at output.rs:501-505). This deletes 8 entire files from the diff.
  2. Collapse take_abandoned + drop_abandoned(index) into discard_abandoned(&mut self) (helios/src/server/output.rs:1745-1755; helios/src/server/protocol/encode.rs:678, 687-689).

    • ResponseOutput::finish always sets self.abandoned = Some(self.blocks.len() - 1) and rendering changes never mutates self.blocks, so round-tripping index: usize out through take_abandoned and back into drop_abandoned with the unreachable if index + 1 == self.blocks.len() guard adds surface area without value. Replace take_abandoned/drop_abandoned(index) with a read accessor is_abandoned(&self, index: usize) -> bool (needed for Blocker #1 / Should Fix #1) plus a single pub fn discard_abandoned(&mut self) that pops blocks and calls when self.abandoned.take().is_some().
  3. Fold the duplicated header-only vs mid-argument truncation matrix tests (helios/src/server/protocol/tests.rs:3809-3907, 3979-4017; helios/src/output/dsml.rs:917-937, 962-984).

    • Both pairs repeat the same loop/assertion body differing only in whether argument fragments were pushed, and protocol/tests.rs:3982-3986 already drifted by omitting Termination::Cancelled and the closing-frame assertions (:3861-3876). Parameterizing each pair over empty vs non-empty fragments removes ~70 lines and keeps one authoritative cause list.

Nits

Dropped on verification

Full report

Classify triage

Selected: (none)

Threshold: 65%

Triage

Apply labels

No label changes Decision to Test: no (100%): Testing will not add significant value as the code stands today. The code is either not yet ready to merge, or adequate testing has already been done to validate the contents of the code, or the available hardware is not suitable to test with. decide malicious: all_clear (100%): No malicious content found

explore

Author: peperunas (FIRST_TIME_CONTRIBUTOR; prior PR #519 closed unmerged; Discord: peperunas) Motivation: DeepSeek tool calls were handed to the client in one burst only after the call's closing tag, so a multi-kilobyte write argument left the stream silent and agents could not tell a working request from a hung one. The PR instead announces the call when its name completes and publishes argument bytes as the model writes them, and it also drops a call that a truncated generation never finished instead of failing the request. Scale: +871 / −66 lines in 7 files Proposal:

Full report · Notes

Classify intake

Selected: performance, enhancement, area:api, model:deepseek-v4, model:deepseek-v4.1

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

No label changes

Subtraction and simplicity

Subtraction & Simplicity audit — PR #685 @ 826a427a

Verdict: the production diff is small (≈90 changed lines across dsml.rs, output.rs, encode.rs) and mostly justified, but it is not lean: the same "was this call truncated?" fact is encoded three times in three files, dsml.rs keeps a hand-maintained ordering that a one-line helper change makes unrepresentable, and +738 of the +871 added lines are tests in which the same five-element termination matrix and the same DSML envelope fixture are hand-copied between files, including a duplicated test name. Everything below is verified at head unless labelled main.


1. Subtraction — one fact, three carriers ("abandoned")

The PR introduces a third representation of one boolean. All three live simultaneously on the truncation path:

So the encoder asks is_abandoned (:694), remembers the answer in a local, then sets and immediately clears incomplete_item. The comment at :703-704 admits why: "The buffered response is rendered after this returns, so the marking outlives the change that set it unless the item is gone." That is a description of a leaked intermediate, not of a contract.

Concrete simplification: let the change carry the outcome. Change::End(usize) → Change::End(usize, Outcome) (Complete / Incomplete / Abandoned) is a one-variant addition to a 3-variant private enum (output.rs:1697-1701). Then:

That is ~25 lines removed and one invalid state (incomplete_item set for a block that no longer exists — exactly what :705-707 exists to paper over) made unrepresentable.

Bug the collapse exposes (worth fixing in the same edit): incomplete_item is a single Option on the Encoder, but the loop at :688 runs per choice and self.outputs is Vec<ResponseOutput> (:140, (0..choices) at :196). Clearing incomplete_item at :705-707 for choice k also clears the marking set for choice j < k, and a later choice's item(i, …) renders status completed for the earlier choice's truncated block. The field being per-encoder and per-choice simultaneously is the invalid state; making the outcome travel with the change removes it.

2. Simplicity — publish should own check_size

helios/src/output/dsml.rs now calls the same two functions in the same order at three sites:

publish (:53-62) already mutates self and already early-returns, so the invariant "enforce the 1 MiB bound, then publish whatever is now storable" belongs inside it:

fn publish(&mut self, index: usize, events: &mut Vec<Event>) -> Result<()> {
    self.check_size()?;
    if self.literal.is_some() || self.published_argument_bytes == self.arguments.len() {
        return Ok(());
    }
    ...
}

Three call sites become one call each, and the ordering documented at docs/api.md:573-576 ("enforced on the append that crosses it, after the call name and earlier argument fragments were published") becomes structural rather than a comment three readers must keep in sync. This is exactly the post-publication bound the PR is asking maintainers to bless — making it a single line is what the review question at the end of the body should be resting on.

3. Simplicity — custom is computed twice to be un-combined once

helios/src/server/protocol/encode.rs:471-491:

let abandoned = self.outputs[0].is_abandoned(i);
let custom = matches!(&self.outputs[0].blocks[i], Block::Tool { name, .. } if self.tool(name).is_some_and(|tool| tool.custom));
if !abandoned && let Block::Tool { name, arguments, .. } = &self.outputs[0].blocks[i] && custom
{ /* parse + grammar */ }
…
let complete = !(abandoned && custom);
let item = self.item(i, complete);

custom is matched out of blocks[i] at :472, then matched again at :474-476 only to reach arguments, and the two booleans are recombined at :490. One match yields both, and the whole guard becomes the match arm:

match (&self.outputs[0].blocks[i], abandoned) {
    (Block::Tool { name, arguments, .. }, false) if self.tool(name).is_some_and(|t| t.custom) => { /* parse + grammar */ }
    _ => {}
}

The let-chains version also hides that abandoned && custom is the only combination where complete is false — with the tuple match that is visible in the arm pattern instead of in a !(a && c) expression.

4. Simplicity — blocks.last() where self.open is the answer

helios/src/server/output.rs:1737-1745:

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));
    self.abandoned = Some(last);
    self.open = None;
}

self.open is the index of the last block by construction (:1821 self.open = Some(i); where i == self.blocks.len(), and every close sets it to None). The blocks.last() test and the len() - 1 re-derivation are a second, weaker way to ask the same question — and they disagree in the case that matters: a Block::Tool at last that is already ended with self.open == Some(text_block). Use let Some(last) = self.open.filter(|&i| matches!(self.blocks[i], Block::Tool { .. })) and both the is_some() check and the subtraction go away.

5. Duplication in the tests — the bulk of the diff

a. The termination matrix is spelled out five times, differently each time. [OutputLimit, UserStop, ExecutionError] at dsml.rs:928-933 and :961-965; [OutputLimit, UserStop, Cancelled, ExecutionError] at protocol/tests.rs:3849-3854; [OutputLimit, UserStop, Cancelled] at :3965-3969; [OutputLimit, UserStop] at :4103. The PR body claims the tests "hold the truncation matrix as one table per property" — there is no table; there are five hand-written literals. Static const CAUSES: [Termination; 4] (or one helper for_each_truncation(f)) makes the claim true and the matrix greppable in one place.

b. The same test name exists twice. a_truncated_second_call_keeps_the_completed_first_call at dsml.rs:956 and protocol/tests.rs:3960. The dsml.rs copy drives parser + Accumulator + discard_unfinished_call by hand; the tests.rs copy drives the encoder for all three protocols. Only the encoder copy is needed once item 1 lands — the parser-level one re-tests Accumulator internals that the encoder test already covers end-to-end.

c. The DSML envelope fixture is built three different ways: dsml.rs:765-767 (envelope), protocol/tests.rs:4056 (inline literal let wire = "…"), helios/tests/deepseek_output.rs:166-175 (block). Three copies of a markup dialect that is already in helios/tests/support/.

d. for event in push { parsed.event(event) } boilerplate, four times: deepseek_output.rs:503-506, :581-582, :588-589, :593-594. A fn feed(&mut self, out: &mut OutputPipeline, text: &str) -> Result<()> on Parsed removes all four — and would have let the old assertions stay (see note below).

Note on that rewrite: the change at deepseek_output.rs:515 (assert!(published.is_empty()) → assert_eq!(parsed.ended, 0, "a rejected call reported an end")) and at :581-595 (empty-push assertions dropped) is the one place where simplification was used to weaken a test rather than to remove a line. Parsed cannot distinguish "no ToolBegin was published" from "a ToolBegin was published", so routing events through it was the only way to keep the new behaviour green. If the requirement is that a rejected call publishes nothing usable, Parsed needs a began: usize counter and the assertion should be assert_eq!((parsed.began, parsed.ended), (0, 0)). That keeps the original strength at the same line count.

6. Docs

docs/api.md:540-559 newly restates the cause→finish-reason mapping (:549-550 "a response that completes reports the termination's finish reason; only an output-limit termination reports the output limit") that the same file already states at :584-590. Two places to edit for one rule. Keep the truncation sentence at :547-552 and delete the redundant clause; also :554 has a missing wrap — …error event for streams. A client that received fragments… exceeds the paragraph width every other line in the file respects.


Explicitly not a finding

drops_unfinished_call (helios/src/server/output.rs:477-481, cause != Termination::Eos) is a one-line function, but it names a policy decision that three call sites (encode.rs:682, encode.rs, output.rs:1737) share and that the PR is asking maintainers about. That is a legitimate name, not a wrapper to inline.

Lean-ness summary

area added verdict
dsml.rs production (~25 lines) justified, 2 simplifications (#2) + 1 subtraction (#3-adjacent)
output.rs production (~35 lines) 3 representations of one fact (#1), last() misuse (#4)
encode.rs production (~45 lines) #1, #3
tests.rs +423, dsml.rs tests +303 matrix duplicated 5×, one duplicate test name, fixture triplicated (#5)
docs/api.md +29 restates :584-590 (#6)

Fixing #1 and #2 removes ~25 production lines and closes a real cross-choice status bug; folding the test matrices removes another ~40; nothing else in the diff is speculative generality or dead code.

Full report · Notes

Gates and contracts

Contracts, Charter & Verification Gates Audit — PR #685

Head audited: 826a427a (pr_files: 7 files, +871/−66). Read-only audit: nothing was executed and no GitHub check-run API is available here; every statement below is from the diff at head, main, and the governance docs.

Verdict: one hard-gate violation family (Gate 1 + Charter), in two concrete parts. Gates 2, 3 and 4 pass.


Gate 1 — Signed core-format / wire / captured-graph / public-contract boundaries

Mechanical prongs: PASS. No protobuf, no core-format or captured-graph enum, no new graph operation family, no wire kind, no new configuration switch or environment variable. The changed files are docs/api.md, helios/src/output/dsml.rs, helios/src/server/output.rs, helios/src/server/protocol/{encode,tests}.rs, and two helios/tests/ files. Event/Termination on main (helios/src/output.rs:54,61) already carry ToolBegin/ToolArguments/ToolEnd; the PR re-times their emission and adds no variant. docs/core-design.md / docs/scheduling-theory.md (not opened) / docs/scheduling-runtime-design.md (not opened) / docs/core-format-design.md (not opened) are untouched, and the one core-design invariant in this area — "The output encoder holds the call until it has validated the complete arguments; a truncated strict call does not publish partial arguments" (docs/core-design.md:1731-1732, :1697 at head) — is preserved, since strict calls keep the pending_strict_calls parking path (helios/src/server/protocol/encode.rs:577-631).

Normative-doc prong: PASS. The contradicted normative document is updated inside the PR: docs/api.md:580-582 on main ("The model parsers buffer tool envelopes until they are complete, so argument events do not imply incremental generation of an unfinished call") becomes docs/api.md:540-559 and :561-578 at head. The earlier round's factual defect is also genuinely repaired: the false "because they build its arguments from parameter syntax …" clause is gone (docs/api.md:545-547), so nothing in the changed prose is false against main's TAGGED_JSON (helios/src/output/tagged_json.rs:14-66).

BLOCKER 1 — the PR reverses two reviewed normative invariants before obtaining the maintainer decision it asks for (AGENTS.md:182-187, 201-207)

Both reversals are real, and both were previously attested as contracts by the people the PR addresses:

  1. #364's pre-publication 1 MiB / key-validation bound. main states "Helios rejects a larger call before publishing it" (docs/api.md:600); #364's reviewer recorded the property explicitly — "The size check now runs after the final value is quoted and the closing text appended, before any event is published" (read_item(364), yatesdr review, 2026-11-18 23:54). At head, helios/src/output/dsml.rs:151-155 publishes Event::ToolBegin at ToolNameEnd and :191-192 publishes fragments per text append, so check_size (:191) and validate_arguments (:202) now run after publication; docs/api.md:574-576 documents exactly that ("enforced on the append that crosses it, after the call name and earlier argument fragments were published and are not retracted").
  2. The non-EOS incomplete-call error. main returns Err("incomplete emitted tool call") at Accumulator::finish (helios/src/server/output.rs:165) and ResponseOutput::close (:1728), pinned by user_stop_cannot_retract_an_already_emitted_partial_tool_call (renamed and inverted at helios/src/server/output.rs:1269-1278). Head adds drops_unfinished_call(cause) = cause != Eos (helios/src/server/output.rs:479-481), calls it from Encoder::finish (encode.rs:681-686) and ResponseOutput::finish (output.rs:1735-1748) so UserStop/Cancelled/ExecutionError now succeed, and rewrites the rule at docs/api.md:547-554. main's documented rule was scoped to the output limit ("Truncated tool envelopes are omitted and the response reports its output limit", docs/api.md:582-583); the PR generalises it to every non-EOS cause across all parsers and all three protocols, while the streaming benefit is DSML-only.

AGENTS.md is unambiguous that this is a prior decision, not a review-time one: "Resolve conflicts through an explicit maintainer decision on the design before implementing a change to that invariant" (AGENTS.md:204-207), and the criteria apply "to documentation and test changes that would weaken the rules as well as code" (:201-207). The PR body does disclose both reversals and asks @voipmonitor and @yatesdr to accept them — that is honest disclosure, but it is not the recorded decision the rule requires, and pr_comments shows no human comment or review in the entire thread (three Autobot reviews, plus the author's two pings). The change is therefore implemented ahead of its authorisation.

Mitigating context to weigh, not a waiver: omission at OutputLimit was accepted precedent in #102, and docs/api.md:552-554 does disclose the tool_choice: required/named exception that encode.rs:708-711 implements. That narrows the delta to UserStop/Cancelled/ExecutionError — but the delta is still unratified.

BLOCKER 2 — an existing guarantee assertion was deleted to make the suite pass (AGENTS.md:182-187, 201-207)

helios/tests/deepseek_output.rs:515: main's assert!(published.is_empty()) after a duplicate/empty-parameter rejection is replaced by assert_eq!(parsed.ended, 0, "a rejected call reported an end"), and parse_literal_parameters (:576-592) likewise stops asserting that nothing is published, routing the events into Parsed instead. The check that a rejected call published nothing — precisely the #364 property in Blocker 1 — is removed rather than the behavior being justified. This is the case AGENTS.md names verbatim: "Do not remove validation, suppress errors, … to obtain passing checks", applied to test changes. It needs the same maintainer decision as Blocker 1, or the assertion should stay and the behaviour change should wait.

These two are one governance finding: the wire-visible contract reversals and the test weakening that accompanies them must either be approved on the record by the #364 owner/reviewer or be dropped from this PR.


Gate 2 — Vendored upstream dependencies & cross-PR conflicts: PASS


Gate 3 — Mandatory verification evidence: PASS (one Info note)


Gate 4 — Material scope / claim contradictions: PASS (two Info notes)

No unrelated standalone tooling, no bundled refactor, no scope expansion; 871 lines are dominated by tests (protocol/tests.rs +423, dsml.rs streaming/rejection tests +303).


Recommendation

Changes requested on Gate 1 alone. Everything mechanical about this PR is clean: no proto, core-format, captured-graph, wire-kind, vendored-file, dependency or scope violation, and the Layer-1 evidence is disclosed with a branch-point baseline. What blocks it is authority: it reverses two invariants that are documented in main and were attested by #364's author and reviewer — #364's publish-after-check bound and the non-EOS incomplete emitted tool call error — and deletes the assertion that pinned the first (helios/tests/deepseek_output.rs:515), all before the maintainer decision the body itself requests exists. Either obtain and record that decision from @voipmonitor/@yatesdr (making the doc rewrite and test change legitimate), or split the truncation/validation-ordering change out and land the DSML streaming re-timing on its own.

Full report

Code correctness

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.

Full report · Notes Merge Risk: medium_high (100%): Medium or high merge risk (core runtime/scheduler/GPU/CUDA/VMM/RoCE/multi-rank/contracts/ABI, large multi-crate changes, or Blocker/Major findings) — route to Super Agent.

Re-review

Recommendation: Changes Requested

Commit 826a427 resolves every technical, protocol, documentation, and test-churn issue from Round 3: truncated Responses custom tool calls now close cleanly as incomplete with empty input instead of failing the request, abandoned function calls report status: "incomplete" across all non-EOS causes, docs/api.md accurately documents tool_choice: required/named failures and TAGGED_JSON-compatible tagged-parser behavior, and restoring Accumulator::finish(&self) shrank the diff from 15 files to 7. Direct verification found zero remaining code bugs or hot-path defects. The sole remaining blocker is the unresolved Round 3 governance gate (AGENTS.md:182-187, 201-207): the PR reverses #364's pre-publication 1 MiB / validation bound and main's non-EOS Err("incomplete emitted tool call") contract (along with their pinning tests and docs), and while the PR description now transparently asks @voipmonitor and @yatesdr to approve both changes, no maintainer decision is recorded on the PR yet. Once a maintainer signs off on both contract changes in the thread, no further code changes are required to merge.

Merge Risk

Level: Medium

Walkthrough

Pre-merge Checks

Blockers

  1. Explicit maintainer sign-off still required for the two contract reversals and their accompanying test/doc rewrites (AGENTS.md:182-187, 201-207; helios/src/output/dsml.rs:151-155, 191-205; helios/src/server/output.rs:479-481, 1269-1278, 1735-1748; helios/tests/deepseek_output.rs:515; docs/api.md:547-555, 574-576).
    • Verified behavior & impact: Both reversals remain active on 826a427 and still have zero human maintainer comments or approvals in the PR thread:
      1. #364's pre-publication 1 MiB and key-validation guarantee (docs/api.md:600 on main, explicitly verified in @yatesdr's #364 review and pinned by assert!(published.is_empty()) at helios/tests/deepseek_output.rs:511 on main) is reversed so ToolBegin and early ToolArguments fragments publish before validate_arguments and before a subsequent append crosses 1 MiB, with deepseek_output.rs:515 weakened to assert_eq!(parsed.ended, 0, ...).
      2. main's non-EOS Err("incomplete emitted tool call") guarantee (helios/src/server/output.rs:165, 1728 and user_stop_cannot_retract_an_already_emitted_partial_tool_call) is replaced by silent omission via drops_unfinished_call(cause) = cause != Termination::Eos (output.rs:479-481), renaming and inverting that regression test at output.rs:1269-1278.
    • Under AGENTS.md:182-187, 201-207, relaxing existing error/validation guarantees — including via accompanying test and doc updates — requires an explicit maintainer design decision on record before merging.
    • Fix: Obtain an explicit maintainer comment on this PR from @voipmonitor / @yatesdr (or a repository maintainer) approving (a) post-publication validation and 1 MiB enforcement for streamed DSML calls and (b) non-EOS unfinished-call omission (vs restricting omission to OutputLimit or keeping the error). If approved as-is, no further code changes are needed.

Should Fix

None.

Subtract / Simplify

  1. Have Call::publish own self.check_size()? (helios/src/output/dsml.rs:53-62, 191-192, 201-203): Changing Call::publish to return Result<()> and call self.check_size()? before emitting makes the check-before-publish ordering structural in one place instead of repeating the two-line pair at :191-192 and :201-203 (keeping :218-220 for non-publishing actions like ToolName and LabelToolCallArguments).
  2. Simplify the custom match in Encoder::change and self.open check in ResponseOutput::finish (helios/src/server/protocol/encode.rs:471-478; helios/src/server/output.rs:1737-1745):
    • In encode.rs:471-478, matching &self.outputs[0].blocks[i] once avoids matching Block::Tool twice to compute custom and then extract arguments.
    • In output.rs:1737-1741, if drops_unfinished_call(cause) && let Some(last) = self.open && matches!(self.blocks[last], Block::Tool { ended: false, .. }) uses self.open directly instead of re-deriving self.blocks.len() - 1 via self.blocks.last().
  3. Disambiguate the remaining duplicate test name (helios/src/output/dsml.rs:956 vs helios/src/server/protocol/tests.rs:3960): a_truncated_second_call_keeps_the_completed_first_call still exists verbatim in both files; prefixing the parser-layer test (e.g., dsml_truncated_second_call_keeps_the_completed_first_call) keeps cargo test <name> unambiguous.

Nits

Dropped on verification

Full report

Classify triage

Selected: triage:design-review

Threshold: 65%

Triage

Apply labels

Applied: +triage:design-review, -triage:review decide malicious: all_clear (100%): No malicious content found

explore

Author: peperunas (FIRST_TIME_CONTRIBUTOR; prior PR #519 closed unmerged; Discord: peperunas) Motivation: DeepSeek tool calls used to arrive only once the whole argument object was parsed, so a multi-kilobyte write argument left the client's stream silent for the entire generation and an agent loop could not tell a working model from a hung one. The parser now announces the call when its name completes and streams argument bytes as the model writes them. Scale: +869 / −59 lines in 7 files (head dfe38d4c; was +662/−72 in 13 files at first submission) Proposal:

Full report · Notes

Classify intake

Selected: triage:design-review, performance, enhancement, area:api, model:deepseek-v4, model:deepseek-v4.1

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

No label changes

Gates and contracts

Contracts, Charter & Verification Gates audit — PR #685 @ dfe38d4c

Audit scope: the four hard gates only. Read-only static reading at head dfe38d4c05af3005a7d55d12e70003b29789f932 (pr_files, pr_diff, read_file, read_item(364), pr_comments, main refs). Nothing was executed. Prior rounds' verification evidence (## Case File History, five Autobot reviews, pr_comments) was checked before judging Gate 3.

Head shape: 7 files, +869/−59 — docs/api.md (+30/−12), helios/src/output/dsml.rs (+304/−14), helios/src/server/output.rs (+46/−13), helios/src/server/protocol/encode.rs (+35/−12), helios/src/server/protocol/tests.rs (+428/−0), helios/tests/deepseek_output.rs (+15/−6), helios/tests/deepseek_requests.rs (+11/−2).

Verdict: one Gate 1 blocker (authority prong), in one family with two parts. Gates 2, 3 and 4 pass. No vendored-file, dependency-pin, mandatory-verification or material-scope gate is violated.


Gate 1 — Core-format / wire / public-contract boundaries

Mechanical prongs: PASS

BLOCKER 1 — two previously attested invariants are reversed, and the test that pinned one was weakened, before the maintainer decision the PR itself requests exists (AGENTS.md:182-187, 201-207; docs/design-review.md:135-146)

Both reversals are real, both are disclosed in the description, and both were asked about in the thread — but neither has an answer, and pr_comments shows zero human comments or reviews in the entire thread (three Autobot reviews, plus the author's pings at 2026-12-05 12:10 and 12:22 asking @voipmonitor/@yatesdr to accept them).

  1. #364's pre-publication 1 MiB / key-validation bound.
    • main states the guarantee normatively: docs/api.md:600 — "Helios rejects a larger call before publishing it." Its author @voipmonitor shipped it for exactly that reason (read_item(364) body: "checks the UTF-8 byte count of the name plus the complete argument object before emitting the first tool event"), and its reviewer @yatesdr attested the property on the record (read_item(364), review 2026-11-18 23:54: "The size check now runs after the final value is quoted and the closing text appended, before any event is published").
    • At head the order is inverted: Event::ToolBegin is pushed at ToolNameEnd (dsml.rs:147-158) and fragments are published per argument-text action (dsml.rs:175-193), so validate_arguments (dsml.rs:202) and the 1 MiB check_size inside publish (dsml.rs:53-54 → :42-47) run after publication. This is documented honestly at docs/api.md:573-577 ("enforced on the append that crosses it, after the call name and earlier argument fragments were published and are not retracted").
  2. main's non-EOS Err("incomplete emitted tool call").
    • Accumulator::finish still errors (helios/src/server/output.rs:163-168) and ResponseOutput::close still errors at Eos (output.rs:1728), but the new drops_unfinished_call(cause) = cause != Termination::Eos (output.rs:477-481) is applied from Encoder::finish on Chat (encode.rs:681-686) and from ResponseOutput::finish (output.rs:1735-1748) for Messages/Responses, so UserStop/Cancelled/ExecutionError now succeed with the termination's finish reason while the announced call is omitted. docs/api.md:580-583 on main scoped omission to the output limit ("Truncated tool envelopes are omitted and the response reports its output limit"); head generalises it to every non-EOS cause across all parsers and all three wire protocols (docs/api.md:546-550).
  3. A pinning assertion was deleted to make the suite green. main helios/tests/deepseek_output.rs:511 asserts assert!(published.is_empty()) after a duplicate/empty-parameter rejection — precisely the #364 property. Head replaces it with assert_eq!(parsed.ended, 0, "a rejected call reported an end") (:515) and drops the is_empty() push assertions in parse_literal_parameters (main:576, 581 → head :579-595, routing events into Parsed instead). That is the case AGENTS.md names verbatim.

AGENTS.md:201-207 is explicit that this is a prior decision, not a review-time one: "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." docs/design-review.md:143-146 adds: "Reject changes that bypass validation, conceal unsupported behavior, weaken … contracts … Do not make a violating contribution acceptable by weakening its governing rule." Updating the contradicted doc (docs/api.md:540-577) is required work but is not authorization; honest disclosure in the description is likewise not the recorded decision.

Mitigating context, weighed but not a waiver: omission at OutputLimit was already accepted in #102, and docs/api.md:552-554 correctly discloses the required/named exception implemented at encode.rs:708-712 (pinned by helios/src/server/protocol/tests.rs:4200-4235). That narrows the delta to UserStop/Cancelled/ExecutionError — and Cancelled is genuinely reachable in production (helios/src/server/runtime.rs:326 → finish_cancelled, plus the tool-limit remap at encode.rs:673 and http.rs:527) — but the delta is still unratified.

What closes it: a maintainer comment on this PR (@voipmonitor / @yatesdr, or any repository maintainer) approving (a) post-publication validation and post-publication 1 MiB enforcement for streamed DSML calls and (b) non-EOS omission of an announced-but-unfinished call for all parsers and protocols — including the accompanying doc rewrite and the weakened deepseek_output.rs:515 assertion. If the answer is no to either, the corresponding code must change rather than the rule. triage:design-review (applied after the last review) is consistent with triage classifying this as exactly that decision.


Gate 2 — Vendored upstream dependencies & cross-PR conflicts: PASS

Gate 3 — Mandatory verification evidence & failing tests: PASS

Gate 4 — Material scope / claim contradictions: PASS, two Info notes

No unrelated standalone tooling, no bundled refactor, no scope expansion; the +869 lines are dominated by tests (protocol/tests.rs +428, dsml.rs tests +303) that all target the changed behavior. No claimed test or benchmark is absent from the diff.

Deliverable verdict

One hard gate violated: Gate 1, authority prong — AGENTS.md:182-187 and :201-207 (weakened guarantee, weakened pinning test, invariant changed before the required maintainer decision), with docs/design-review.md:143-146. Gates 2, 3 and 4: no blockers.

If the maintainer decision lands in the thread accepting both reversals, no further code change is needed for this lens; if it lands against either, the corresponding code, doc sentence and test assertion must revert rather than the rule.

Full report · Notes

Subtraction and simplicity

Subtraction & Simplicity audit — PR #685 (dfe38d4)

Verdict: the production diff is lean, and the streaming core is genuinely minimal. Call::publish (helios/src/output/dsml.rs:49-64) is 15 lines and does the whole feature; Event::ToolBegin at ToolNameEnd is 6 added lines (dsml.rs:153-157); the DSML ToolCallArgumentsEnd arm shrank on net (dsml.rs:195-205). No flag, config knob, trait, per-model branch or speculative abstraction is added anywhere in the diff. Everything worth flagging sits in the truncation bookkeeping split across two modules and in test scaffolding — which is where +428 (protocol/tests.rs) and +304 (output/dsml.rs) came from.

Citations are at head dfe38d4; nothing was executed, all statements are static reading of the diff and files.

1. Encoder adds a second, mark-then-clear copy of "this item is abandoned" — HIGH

helios/src/server/protocol/encode.rs:687-707:

let mut abandoned = false;
for change in self.outputs[index].finish(cause)? {
    if self.protocol == Protocol::Responses
        && let Change::End(i) = &change
    {
        let truncated = self.outputs[index].is_abandoned(*i);
        if truncated || cause == Termination::OutputLimit {
            self.incomplete_item = Some(*i);
        }
        abandoned |= truncated;
    }
    frames.extend(self.change(change)?);
}
self.outputs[index].discard_abandoned();
// The buffered response is rendered after this returns, so the marking
// outlives the change that set it unless the item is gone.
if abandoned {
    self.incomplete_item = None;
}

Two facts are tracked for the same block: incomplete_item (read later by item() at encode.rs:340-341 when the buffered body is rendered) and the local abandoned, which exists only to undo the first. The undo only exists because one field serves two renders, and abandoned |= plus the post-loop unset is treating a symptom of that: the restore is skipped for every end in the call, not just the last. change() already receives the index, so the abandoned flag can be passed down into item(i, complete) / change(change, abandoned) and incomplete_item left carrying only the OutputLimit case it carried before this PR (which is all encode.rs:695's || adds). That deletes abandoned, truncated, the trailing if abandoned and its three-line comment: ~8 lines and one piece of hidden state.

2. ResponseOutput.abandoned + is_abandoned + discard_abandoned is a channel where a return value would do — MEDIUM/HIGH

helios/src/server/output.rs:1735-1761:

pub fn finish(&mut self, cause: Termination) -> Result<Vec<Change>> {
    let mut changes = vec![];
    if drops_unfinished_call(cause)
        && let Some(index) = self.open
        && matches!(self.blocks[index], Block::Tool { ended: false, .. })
    {
        changes.push(Change::End(index));
        self.abandoned = Some(index);
        self.open = None;
    }
    self.close(&mut changes)?;
    Ok(changes)
}
pub fn is_abandoned(&self, index: usize) -> bool { self.abandoned == Some(index) }
pub fn discard_abandoned(&mut self) {
    if self.abandoned.take().is_some() {
        self.blocks.pop();
        self.calls.pop();
    }
}

The index is already fully known inside finish; storing it in a field so the caller can re-read it through is_abandoned (called twice: encode.rs:471 and encode.rs:694) makes a three-method protocol for one value. finish returning (Vec<Change>, Option<usize>) and the caller holding it in a local across the loop removes abandoned, is_abandoned, and discard_abandoned's field entirely. Two concrete defects of the same design: (a) discard_abandoned discards the index it just took and pops positionally — correct only because an abandoned block is always last; let Some(index) = self.abandoned.take() + self.blocks.remove(index) / self.calls.remove(...) is the same line count and states the invariant instead of depending on it; (b) self.open = None; here duplicates the identical line close() executes three lines later (output.rs:1726-1731).

3. The 1 MiB check now runs twice per published fragment — MEDIUM

helios/src/output/dsml.rs:53-54:

fn publish(&mut self, index: usize, events: &mut Vec<Event>) -> Result<()> {
    self.check_size()?;

and helios/src/output/dsml.rs:218-220, at the end of every action in apply:

if let Some(call) = &self.call {
    call.check_size()?;
}

publish is reached only from the ToolCallArgumentsText arm (dsml.rs:193), whose every path has already run the loop-level check on the previous action and will run it again on this one — so the same inequality is evaluated three times per fragment. Round 4 deliberately moved the check into publish; the loop-level call could then be narrowed to actions that do not publish, or dropped for the text action. check_size is cheap, so this is a legibility item, not perf — but as written a reader has to work out which of two identical guards produces which error ordering (dsml.rs:202 validate precedes :203 publish).

4. custom tracked by a mutable flag, then re-derived anyway — LOW

encode.rs:472-476:

let mut custom = false;
if let Block::Tool { name, arguments, .. } = &self.outputs[0].blocks[i]
    && self.tool(name).is_some_and(|tool| tool.custom)
{
    custom = true;

is one expression as matches!: matches!(self.outputs[0].blocks[i], Block::Tool { name, .. } if self.tool(name).is_some_and(|t| t.custom)), leaving arguments bound only inside the if !abandoned body. Five lines to one, no let mut.

5. Test scaffolding duplicates the helper it sits beside — LOW/MEDIUM

helios/src/server/protocol/tests.rs:56-74 re-lists all ten Encoder::new arguments verbatim from encoder_with_parallel (tests.rs:36-53), differing only in tools[0].custom = true; calling encoder_with_parallel(Protocol::Responses, tool_choice, true) and setting encoder.tools[0].custom = true removes ~14 duplicated lines. Same shape in dsml.rs: streaming_tests::config() (dsml.rs:757-763) and rejection_tests::parser() (dsml.rs:987-995) are the same OutputConfig differing only in start, and the two adjacent mods re-import the same five names (dsml.rs:751-755 vs :988-991); one config(start: OutputStart) in a shared #[cfg(test)] mod removes the pair.

6. Trailing blank line at EOF — NIT

helios/tests/deepseek_output.rs:834 — the diff's final hunk adds an empty line after the closing brace, leaving the file ending }\n\n.

Checked and already lean (do not re-raise)

Bottom line: nothing blocks on simplicity grounds. Items 1 and 2 are the ones I would insist on — together they are ~20 lines of two-way bookkeeping (incomplete_item ↔ abandoned) that a single value passed down the change() path replaces, and discard_abandoned currently pops positionally while holding the index that says where to pop.

Full report · Notes