Subtraction and simplicity report · NVIDIA/hyperflare-inference #685

Raw Markdown for agents: https://autobot.eidonix.com/p/55626d63-9bce-4702-902b-710924c1149c.md

Subtraction, Simplicity & Conventions — PR #685 (fix(frontend): stream DeepSeek tool-call arguments)

Key findings

  1. High — finish(cause) is a mode-flag parameter threaded through ~35 call sites to carry one boolean. drops_unfinished_call(cause) (helios/src/server/output.rs:476-480) is cause != Termination::Eos; it is consulted at exactly two lines (output.rs:164, :1731), while the new cause argument ripples across 8 files that change nothing else (21 lines, +21/−21), ~8 more test sites in output.rs, and 6 in dsml.rs. The one production decision point is Encoder::finish (helios/src/server/protocol/encode.rs:674-677). Collapse to finish() unchanged plus one explicit drop_unfinished(&mut self); the helper and all churn disappear.
  2. High — two new tests exist twice under identical names in two files. a_truncated_second_call_keeps_the_completed_first_call (helios/src/output/dsml.rs:940, helios/src/server/protocol/tests.rs:3894) and a_header_only_call_is_omitted_when_the_response_truncates (dsml.rs:963, protocol/tests.rs:3964). Keep one per name.
  3. Medium — a duplicated 1 MiB size check. dsml.rs:191 (call.check_size()? added by this PR) re-validates exactly the state the pre-existing dsml.rs:218-220 check validates on the same loop iteration.
  4. Medium — the docs/api.md hunk carries two sentences that are not this PR's subject: a cross-dialect justification for parsers the PR does not touch (and which is already stale on main), and an editorial line restating an unresolved framing gap.
  5. The substantive streaming change is lean and I would not dress this up as a style problem. See "What is already lean" below — say so plainly, because three of the four items above are test/doc/API-plumbing, not the mechanism.

1. (High) finish(cause) — a boolean disguised as a parameter, paid for by 8 otherwise-untouched files

The new helper, complete:

helios/src/server/output.rs:476-480

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

Its two consumers:

helios/src/server/output.rs:163-173

    pub(crate) fn finish(&mut self, cause: Termination) -> Result<()> {
        if drops_unfinished_call(cause)
            && self.calls.last().is_some_and(|call| !call.ended)
        {
            self.calls.pop();
        }
        if self.calls.iter().any(|call| !call.ended) {
            return Err("incomplete emitted tool call".into());
        }
        Ok(())
    }

helios/src/server/output.rs:1730-1742

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

The RFC 2119-flavoured smell: the parameter is never used as a termination cause by either function; it is immediately reduced to a bool, and the second match arm (Eos) behaves exactly as the pre-PR function did. In production the argument has exactly one value, and it comes from one place:

helios/src/server/protocol/encode.rs:674-677 (the whole functional diff of encode.rs, +2/−2)

        if self.protocol == Protocol::Chat {
            self.chats[index].finish(cause)?;
        }
        for change in self.outputs[index].finish(cause)? {

Cost, measured from the diff:

Concretely, replace with: keep Accumulator::finish(&mut self) -> Result<()> and ResponseOutput::finish(&mut self) -> Result<Vec<Change>> exactly as on main, add one explicit method to each, and make the drop visible at its single decision point:

// output.rs, on both Accumulator and ResponseOutput
pub(crate) fn drop_unfinished(&mut self) {
    // body of the `if drops_unfinished_call(cause) && ...` block above, minus the cause test
}
// encode.rs:673-677
        if cause != Termination::Eos {
            if self.protocol == Protocol::Chat {
                self.chats[index].drop_unfinished();
            }
            self.outputs[index].drop_unfinished();
        }
        if self.protocol == Protocol::Chat {
            self.chats[index].finish()?;
        }
        for change in self.outputs[index].finish()? {

This deletes drops_unfinished_call (5 lines), the cause parameter on two public-ish signatures, and 21 cross-crate edit lines in files that have no other business in this PR, while adding ~6 lines at the point where the semantics actually live. Behaviour is identical in every branch, including the existing Chat guard at encode.rs:674 (Answers drop_unfinished on a non-Chat accumulator is never called because self.chats is only indexed for Chat) and the strict-tool parking path at encode.rs:667-671, which is untouched.

Note for the correctness lens (do not duplicate, but the two interact): if #685's universal non-Eos drop is judged wrong and the Err("incomplete emitted tool call") branch is restored for UserStop/Cancelled/ExecutionError, this suggestion becomes trivially correct — the API returns to a zero-argument finish(). This simplification is strictly better under either correctness outcome, which is why it is worth making regardless.


2. (High) Duplicated tests — the same two scenarios are asserted twice under the same names

test name helios/src/output/dsml.rs helios/src/server/protocol/tests.rs
a_truncated_second_call_keeps_the_completed_first_call :940-960 :3894-3961
a_header_only_call_is_omitted_when_the_response_truncates :963-984 :3964-4001

Both dsml copies loop the same non-Eos causes and assert on output.message():

helios/src/output/dsml.rs:953-959

            output.finish(cause).unwrap();
            let message = output.message();
            assert_eq!(message["reasoning_content"], "thought", "{cause:?}");
            let calls = message["tool_calls"].as_array().unwrap();
            assert_eq!(calls.len(), 1, "{cause:?}");
            assert_eq!(calls[0]["function"]["arguments"], "{\"path\": \"a.txt\"}");

The protocol copies assert strictly more on the same state — buffered body and finish_reason and all three protocols (protocol/tests.rs:3931-3958, :3986-3998). The only thing the dsml copies add is "the parser produced these events", which the earlier, genuinely distinct dsml tests already cover: a_call_opens_and_publishes_arguments_before_its_envelope_closes (dsml.rs:793-842) and a_truncated_call_keeps_its_published_fragments_and_omits_the_stored_call (dsml.rs:917-937).

Concretely: delete dsml.rs:939-984 (the two duplicate #[test] fns, ~46 lines). The truncation contract keeps its strongest assertion, in the file where the client-visible consequence is decided.

Related, smaller: rejection_tests::end_of_sequence_inside_an_announced_call_is_an_error re-asserts what an existing integration test already loops:

helios/src/output/dsml.rs:1003-1011

    #[test]
    fn end_of_sequence_inside_an_announced_call_is_an_error() {
        let mut parser = parser();
        let events = parser.push(Input::Text(
            "<|DSML|tool_calls><|DSML|invoke name=\"write\"><|DSML|parameter name=\"q\" string=\"true\">par",
        )).unwrap();
        assert!(events.iter().any(|event| matches!(event, Event::ToolBegin { .. })));
        assert!(events.iter().any(|event| matches!(event, Event::ToolArguments { .. })));
        assert!(parser.finish(Termination::Eos).is_err());
    }

The Eos-is-Err half is already exercised by helios/tests/deepseek_output.rs:387-421 (incomplete_calls_do_not_finish_on_eos_and_can_be_cancelled_or_truncated, which asserts Eos -> is_err() and OutputLimit/UserStop/Cancelled/ExecutionError -> Ok), and the two event assertions by dsml.rs:793. Also note rejection_tests::parser() (dsml.rs:994-1000) duplicates streaming_tests::config() (dsml.rs:757-763) except for start: OutputStart::Content vs Reasoning — merging the two modules into one streaming_tests with a fn parser(start: OutputStart) deletes the second fixture and its import block (dsml.rs:990-992). Keep a_rejected_argument_object_fails_after_its_fragments_are_published (dsml.rs:1013-1031); that one is genuinely new behaviour.


3. (Medium) The added check_size duplicates the pre-existing one on the same iteration

Both checks, in the same for segment loop body:

helios/src/output/dsml.rs:188-193 (the call.check_size()? line is added by this PR)

                        call.arguments.push_str(source);
                    }
                    call.check_size()?;
                    call.publish(self.calls, events);
                }

helios/src/output/dsml.rs:218-220 (pre-existing, unchanged)

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

For a ToolCallArgumentsText action the second check re-validates exactly the state the first just validated; nothing appends between them (publish only reads arguments). Two identical guards 27 lines apart in the same iteration is the kind of "defence in depth" that rots: the next reader cannot tell which one is load-bearing, and docs/api.md:571-573 — added by this PR — describes only one of the two behaviours ("The bound is enforced on the append that crosses it, after the call name and earlier argument fragments were published and are not retracted").

Concretely: delete call.check_size()?; at dsml.rs:191. The post-match :218-220 check is strictly more general — it also bounds growth from LabelToolCallArguments (:157-172) and ToolName (:138-143) — and it runs on the same iteration. No validation is weakened (AGENTS.md:182-187 "Do not remove validation" is satisfied: every append is still bounded; only the duplicate goes). Keeping :191 instead is not viable as a pure dedup, because deleting :218-220 would leave label-driven growth unbounded.


4. (Medium) docs/api.md grows two sentences that do not belong to this change

docs/api.md:544-548 and :551-552 (head line numbers; the added paragraph spans :541-552)

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

Two removals:

  1. :544-548 explains parsers this PR does not modify (pr_files touches no tagged-parser source), and the explanation is already untrue on main: TAGGED_JSON parses the model's own {"name":…,"arguments":…} object and re-serializes it (helios/src/output/tagged_json.rs:14-57 (not opened), JSON_BODY = true at :57), coercing nothing. The sentence it replaced on main said the same thing in one neutral clause: "The model parsers buffer tool envelopes until they are complete, so argument events do not imply incremental generation of an unfinished call." Replace 5 lines of dialect theory with that clause, inverted for the one dialect that changed: "The tagged tool parsers publish a call only when its envelope is complete, so their argument events do not imply incremental generation."
  2. :551-552 — "A client that received fragments of such a call has already seen a call that cannot complete." — is commentary, not contract, and it is precisely the place where the missing content_block_stop / response.output_item.done for the dropped call should be documented instead (correctness lens owns that defect; this lens owns the fact that the sentence should not stay as-is).

That shrinks the docs hunk from ~12 added lines to ~4 and keeps the specification honest about which parsers this PR changed.


What is already lean (state plainly — do not manufacture churn)

Suggested order of action

  1. §1 (finish(cause) → finish() + drop_unfinished) — removes 8 files from the diff and ~20 lines.
  2. §2 (delete the two duplicate dsml tests and the rejection_tests overlap) — removes ~60 lines.
  3. §3 (delete dsml.rs:191) — one line, removes a genuine duplicate guard.
  4. §4 (trim docs/api.md:544-548, :551-552) — 7 lines.

Together these take roughly 90 lines and 8 files out of a +662/−72 change without touching the behaviour under review.

Open questions / what I could not confirm