From dd38123ee7af32634c581482170693b4800a1832 Mon Sep 17 00:00:00 2001 From: Giulio De Pasquale Date: Thu, 3 Dec 2026 16:11:21 +0000 Subject: [PATCH 1/5] fix(frontend): stream DeepSeek tool-call arguments A DeepSeek tool call now reaches the client as the model writes it: the call's name is announced when its header completes, and its argument text is published fragment by fragment instead of arriving whole when the invoke tag closes. The pinned `deepseek-recipe` parser already releases each argument label and text fragment as it decodes input, but `DsmlOutput` collected them and emitted the begin, arguments and end events together at `ToolCallArgumentsEnd`. A client therefore received nothing between the tool name and the finished argument object: a multi-kilobyte `write` argument left the stream silent for the whole generation, which a client renders as a stalled response and an agent loop cannot tell apart from a hung model. The encoder and both block emitters already open a tool call on `Event::ToolBegin` and forward each `Event::ToolArguments` fragment, so the defect was confined to when the parser published them. `DsmlOutput::apply` now emits `Event::ToolBegin` at `ToolNameEnd`, publishes the argument bytes appended by each argument-text action and the rest at `ToolCallArgumentsEnd`, so label bytes travel with the next text fragment or that end, and emits `Event::ToolEnd` after `validate_arguments` accepts the object. A `string="false"` value stays private while `close_literal` may still rewrite it, so no published byte is replaced, and the published fragments concatenate to exactly the stored arguments. Strict tools keep the existing parking path, so they still emit no frame before the compiled schema accepts their arguments. A call announced before its arguments are complete must not fail the request when the generation is cut short. `Accumulator::finish` keeps its pre-PR `&self` shape and its error for an unfinished call at natural end-of-sequence; the drop of an announced but unfinished Chat call moves to `discard_unfinished_call`, which `Encoder::finish` calls under `drops_unfinished_call(cause)`. On the Responses wire, `ResponseOutput` reports the block it closed for a truncated call through `is_abandoned(index)` while the encoder renders its closing frame, and `discard_abandoned()` removes it afterwards. An abandoned item reports status `incomplete` for every termination that drops it, not only for the output limit, and a custom tool call among them skips the JSON parse and grammar validation over arguments that never arrived and closes with an empty input instead of failing the request. `docs/api.md` states which parsers publish fragments, what those fragments concatenate to, how a truncated call ends, and that a `required` or named tool choice still fails when omitting the call leaves no completed call. Two contracts `main` guarantees change here, and both follow from publishing before the envelope closes: a non-EOS truncation omits the announced call where `main` raised `incomplete emitted tool call`, and streamed fragments are published before `validate_arguments` and before the 1 MiB parser bound that #364 introduced. @voipmonitor and @yatesdr, as #364's author and reviewer: do you accept the omission rather than the error for a non-EOS truncated call, and post-publication validation and size enforcement for streamed calls? If either answer is no, say which behavior you want and this pull request changes instead of leaving the rule reversed. Clients receive the tool name as soon as the call opens and argument text as the model writes it, and it works against the served backend: a live request that previously returned two frames for a 2.2 KB `write` argument now returns 566. The fragments a client assembles equal the arguments of the completed call byte for byte, reasoning, content and tool-call ordering are unchanged, and a call cut off by an output limit, a stop string or a cancellation now ends as an incomplete item rather than a failed request. The Qwen function-tag, GLM argument-tag, MiniMax XML and Gemma call parsers still buffer because their arguments are synthesized from parameter syntax, so this pull request streams only the DSML dialect. A chat-completions request with `stream: true`, one `write` tool and `tool_choice: "required"` returned 566 argument frames totalling 2196 bytes, and their concatenation hashed identically to the same request's non-streaming arguments; the tagged dialects were not exercised against a served model. Tests: `helios/src/server/protocol/tests.rs` drives a truncated custom call and a truncated function call on all three wire protocols and every termination cause, including the custom call's empty input, its missing input frames and the forced tool choice that must still fail, and it holds the truncation matrix as one table per property. In `helios/src/output/dsml.rs` the streaming tests assert the published prefix while an envelope is open, concatenation against the stored arguments at every UTF-8 split, a rewritten literal, end-of-sequence and schema rejection after fragments, and the folded truncation rows. On `75764de2`, `cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --no-fail-fast` runs all fifteen targets and reports 1848 passed, 20 failed and 84 ignored, against 1846 passed and 21 failed for the same command at `b9864ab8`; all 20 failures exist at both heads, eleven of them engram tests that fail against this host's 8 MiB `RLIMIT_MEMLOCK` (`register Engram staging: Cannot allocate memory`) and pass when run alone, nine needing `FLARE_TEST_TEMPLATE_DIR` from `tests/frontend/prepare_templates.py`, and the `message_boundaries` suite failing the same 3 tests at both heads. The `deepseek_output` and `deepseek_requests` integration suites pass 15 each. `cargo build --locked --release --manifest-path flare/Cargo.toml` and the same for `flare-cli/Cargo.toml` both succeed, and their suites report 254 and 245 passed with no failure. Two probes drive the review's symptoms directly: at `b9864ab8` a truncated custom call fails with `custom tool input does not match its grammar` and a `UserStop` truncation reports status `completed`; at `75764de2` both succeed with status `incomplete`. Design-Signed-Off-By: pi coding agent; design-review=2e5b Signed-off-by: Giulio De Pasquale --- docs/api.md | 38 ++- helios/src/output/dsml.rs | 316 +++++++++++++++++++- helios/src/server/output.rs | 60 +++- helios/src/server/protocol/encode.rs | 63 ++-- helios/src/server/protocol/tests.rs | 423 +++++++++++++++++++++++++++ helios/tests/deepseek_output.rs | 21 +- helios/tests/deepseek_requests.rs | 13 +- 7 files changed, 868 insertions(+), 66 deletions(-) diff --git a/docs/api.md b/docs/api.md index ab3176c96..c9f6495fa 100644 --- a/docs/api.md +++ b/docs/api.md @@ -537,19 +537,30 @@ and the call index). This format stays within the 40-character OpenAI Chat Completions maximum and the `[a-zA-Z0-9_-]+` character set accepted across Chat Completions, Responses, and Messages, keeping synthesized identifiers distinct across calls, choices, requests, server restarts, and hosts. Tool arguments are -JSON objects, bounded to 8 MiB. The model parsers buffer tool envelopes until -they are complete, so argument events do not imply incremental generation of an -unfinished call. Truncated tool envelopes are omitted and the response reports -its output limit. At natural completion, tagged tool parsers accept a non-strict -call whose inner arguments are structurally complete and self-delimited when -only its closing wrapper tag is omitted; undecided openers, bare headers -without a closing argument delimiter, unclosed arguments, trailing text, and -unclosed strict calls remain errors. +JSON objects, bounded to 8 MiB. A DeepSeek DSML call is announced once its name +is complete, and its argument text is published while the model writes it, so +concatenating the argument fragments of a call reproduces its stored arguments +byte for byte. The tagged tool parsers publish a call only when its envelope is +complete. An announced call cut off before completion is omitted from a +buffered response for every termination other than natural end-of-sequence, and +a response that completes reports the termination's finish reason; only an +output-limit termination reports the output limit. The closing frame of such an +item reports status `incomplete`, and a truncated custom call's item carries an +empty input because its arguments never formed. When the omitted call leaves no +completed call, a `required` or named `tool_choice` fails the response instead, +producing HTTP 500 for buffered requests or a terminal error event for streams. A client that received fragments of such a call has already seen a +call that cannot complete. At natural completion, tagged tool parsers accept a +non-strict call whose inner arguments are structurally complete and +self-delimited when only its closing wrapper tag is omitted; undecided openers, +bare headers without a closing argument delimiter, unclosed arguments, trailing +text, and unclosed strict calls remain errors. DeepSeek reasoning and both DSML tool syntaxes use the pinned official `deepseek-recipe` state machine. Helios adapts its actions into the same neutral -events, validates nonempty tool names and JSON objects with nonempty, unique -argument names, and publishes each call when its arguments complete. A parameter +events and validates nonempty tool names and JSON objects with nonempty, unique +argument names. A call ends after its argument object validates. A +`string="false"` value stays private until the parser decides whether to retain +it as text, so published fragments never change. A parameter tag that closes before its string attribute is discarded, so the following well-formed parameter is parsed normally. A parameter marked `string="false"` keeps its JSON type if its text decodes as one value @@ -557,8 +568,11 @@ inside the argument object. If decoding fails, Helios retains the original text as a JSON string. This includes valid JSON exceeding 126 levels of array or object nesting within the parameter. The combined size of the UTF-8 tool name and complete JSON argument object is limited to 1 MiB, including escapes -and delimiters. Helios rejects a larger call before publishing it. Closing the -outer calls block ends parsed output and discards subsequent generated text. +and delimiters. The bound is enforced on the append that crosses it, after the +call name and earlier argument fragments were published and are not retracted, +so an oversized call never completes and cannot appear in a buffered body. +Closing the outer calls block ends parsed output and discards subsequent +generated text. The official parser owns markup recognition, including its tolerance of omitted or partial tags. Structured answers become verbatim when ordinary answer content begins, preserving scalar JSON, Lark output, and markup inside string values. diff --git a/helios/src/output/dsml.rs b/helios/src/output/dsml.rs index 5393a6258..a4de4468b 100644 --- a/helios/src/output/dsml.rs +++ b/helios/src/output/dsml.rs @@ -35,6 +35,7 @@ struct Call { literal: Option, literal_quoted: bool, literal_escaped: bool, + published_argument_bytes: usize, } impl Call { @@ -45,6 +46,21 @@ impl Call { Ok(()) } + /// Publishes argument bytes appended since the previous call. + /// + /// A value whose `string="false"` text may still be rewritten stays private + /// until `close_literal` decides, so published text never changes afterwards. + fn publish(&mut self, index: usize, events: &mut Vec) { + 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(); + } + /// Retain the model's text when it cannot be decoded as a value in the argument object. fn close_literal(&mut self) { let Some(start) = self.literal.take() else { @@ -132,6 +148,11 @@ impl DsmlOutput { if call.name.is_empty() { return Err("tool function name is empty".into()); } + events.push(Event::ToolBegin { + index: self.calls, + name: call.name.clone(), + id: None, + }); } OutputAction::LabelToolCallArguments(label) if !repeated => { let call = self @@ -167,6 +188,8 @@ impl DsmlOutput { } call.arguments.push_str(source); } + call.check_size()?; + call.publish(self.calls, events); } OutputAction::ToolCallArgumentsEnd { closing_text } if !repeated => { let mut call = self @@ -177,19 +200,8 @@ impl DsmlOutput { call.arguments.push_str(closing_text); call.check_size()?; validate_arguments(&call.arguments)?; - let index = self.calls; - events.extend([ - Event::ToolBegin { - index, - name: call.name, - id: None, - }, - Event::ToolArguments { - index, - text: call.arguments, - }, - Event::ToolEnd { index }, - ]); + call.publish(self.calls, events); + events.push(Event::ToolEnd { index: self.calls }); self.calls += 1; } OutputAction::Label(label) if !repeated => { @@ -733,3 +745,281 @@ mod retained_literal_tests { check::(); } } + +#[cfg(test)] +mod streaming_tests { + use super::*; + use crate::output::tagged::{OutputConfig, OutputStart}; + use crate::output::{Input, ModelOutput, Termination}; + use crate::server::output::Accumulator; + use serde_json::json; + + fn config() -> OutputConfig { + OutputConfig { + structured: false, + start: OutputStart::Reasoning, + tools: vec![json!({"type":"function", "function":{"name":"write"}})], + } + } + + fn envelope(parameters: &str) -> String { + format!("thought<|DSML|tool_calls>\n<|DSML|invoke name=\"write\">\n{parameters}\n") + } + + fn string_parameter(name: &str, value: &str) -> String { + format!( + "<|DSML|parameter name=\"{name}\" string=\"true\">{value}\n" + ) + } + + fn arguments(events: &[Event]) -> String { + events + .iter() + .filter_map(|event| match event { + Event::ToolArguments { text, .. } => Some(text.as_str()), + _ => None, + }) + .collect() + } + + fn finish_arguments(parser: &mut DsmlOutput, output: &mut Accumulator) { + output + .apply(parser.finish(Termination::Eos).unwrap()) + .unwrap(); + output.finish().unwrap(); + } + + #[test] + fn a_call_opens_and_publishes_arguments_before_its_envelope_closes() { + let content = "x".repeat(64); + let text = envelope(&format!( + "{}{}", + string_parameter("path", "a.txt"), + string_parameter("content", &content) + )); + let expected = format!("{{\"path\": \"a.txt\", \"content\": \"{content}\"}}"); + let envelope_close = text.find("").unwrap(); + let mut parser = DsmlOutput::::new(config()); + let mut output = Accumulator::new("stream".into()); + let mut published = String::new(); + let mut began = false; + let mut ended = false; + for (at, character) in text.char_indices() { + let before_close = at < envelope_close; + for event in parser.push(Input::Text(&character.to_string())).unwrap() { + if before_close { + assert!( + !matches!(event, Event::ToolEnd { .. }), + "the call ended before its envelope closed" + ); + match &event { + Event::ToolBegin { index, name, .. } => { + assert_eq!((*index, name.as_str()), (0, "write")); + assert!(published.is_empty(), "arguments preceded the call header"); + began = true; + } + Event::ToolArguments { text, .. } => published.push_str(text), + _ => {} + } + } else if matches!(event, Event::ToolEnd { .. }) { + ended = true; + } + output.apply(vec![event]).unwrap(); + } + } + assert!(began, "the call was announced only when its envelope closed"); + assert!( + expected.starts_with(&published), + "published fragments are not a prefix of the arguments: {published}" + ); + assert!(ended, "the completed call never ended"); + finish_arguments(&mut parser, &mut output); + let stored = output.message()["tool_calls"][0]["function"]["arguments"] + .as_str() + .unwrap() + .to_owned(); + assert_eq!(stored, expected); + } + + #[test] + fn published_fragments_reconstruct_the_stored_arguments_at_every_split() { + let content = "é".repeat(24); + let text = envelope(&format!( + "{}{}{}", + string_parameter("path", "a.txt"), + string_parameter("content", &content), + "<|DSML|parameter name=\"count\" string=\"false\">42\n" + )); + let expected = format!("{{\"path\": \"a.txt\", \"content\": \"{content}\", \"count\": 42}}"); + let invoke_close = text.find("").unwrap(); + for split in text + .char_indices() + .map(|(at, _)| at) + .chain([text.len(), invoke_close]) + { + let mut parser = DsmlOutput::::new(config()); + let mut output = Accumulator::new("split".into()); + let mut events = parser.push(Input::Text(&text[..split])).unwrap(); + events.extend(parser.push(Input::Text(&text[split..])).unwrap()); + let fragments = arguments(&events); + let begins = events + .iter() + .filter(|event| matches!(event, Event::ToolBegin { .. })) + .count(); + let ends = events + .iter() + .filter(|event| matches!(event, Event::ToolEnd { .. })) + .count(); + output.apply(events).unwrap(); + finish_arguments(&mut parser, &mut output); + let stored = output.message()["tool_calls"][0]["function"]["arguments"] + .as_str() + .unwrap() + .to_owned(); + assert_eq!((begins, ends), (1, 1), "split {split}"); + assert_eq!(fragments, expected, "split {split}"); + assert_eq!(stored, expected, "split {split}"); + } + // A push that stops before the invoke close already published a prefix. + let mut parser = DsmlOutput::::new(config()); + let published = arguments(&parser.push(Input::Text(&text[..invoke_close])).unwrap()); + assert!(!published.is_empty(), "nothing was published before the envelope closed"); + assert!(expected.starts_with(&published), "{published}"); + } + + #[test] + fn a_rewritten_literal_value_publishes_only_its_final_text() { + let text = envelope(&format!( + "{}{}{}", + string_parameter("label", "a \"b\""), + "<|DSML|parameter name=\"v\" string=\"false\">3 apples\n", + string_parameter("tail", "x") + )); + let tail = text.find("<|DSML|parameter name=\"tail\"").unwrap(); + let cut = tail + text[tail..].find('>').unwrap() + 1; + let mut parser = DsmlOutput::::new(config()); + let mut events = parser.push(Input::Text(&text[..cut])).unwrap(); + let published = arguments(&events); + assert!( + published.contains("\"v\": \"3 apples\""), + "the retained value was not published when the next parameter opened: {published}" + ); + assert!(!published.contains("\"v\": 3 apples"), "{published}"); + assert!(!events.iter().any(|event| matches!(event, Event::ToolEnd { .. }))); + events.extend(parser.push(Input::Text(&text[cut..])).unwrap()); + assert_eq!( + serde_json::from_str::(&arguments(&events)).unwrap(), + json!({"label": "a \"b\"", "v": "3 apples", "tail": "x"}) + ); + } + + #[test] + fn a_truncated_announced_call_is_omitted_from_the_stored_message() { + for (parameters, cut_at, publishes) in [ + ( + string_parameter("content", &"x".repeat(32)), + "", + true, + ), + (String::new(), ">\n", false), + ] { + let text = envelope(¶meters); + let cut = text.find(cut_at).unwrap(); + for cause in [ + Termination::OutputLimit, + Termination::UserStop, + Termination::ExecutionError, + ] { + let mut parser = DsmlOutput::::new(config()); + let mut output = Accumulator::new("truncated".into()); + let events = parser.push(Input::Text(&text[..cut])).unwrap(); + assert!( + events.iter().any(|event| matches!(event, Event::ToolBegin { index: 0, name, .. } if name == "write")), + "the call name was never announced" + ); + assert_eq!(!arguments(&events).is_empty(), publishes, "{cut_at}"); + assert!( + !events + .iter() + .any(|event| matches!(event, Event::ToolEnd { .. })) + ); + output.apply(events).unwrap(); + output.apply(parser.finish(cause).unwrap()).unwrap(); + output.discard_unfinished_call(); + output.finish().unwrap(); + assert!(output.message().get("tool_calls").is_none(), "{cause:?}"); + } + } + } + + #[test] + fn a_truncated_second_call_keeps_the_completed_first_call() { + let text = "thought<|DSML|tool_calls>\n<|DSML|invoke name=\"write\"><|DSML|parameter name=\"path\" string=\"true\">a.txt\n<|DSML|invoke name=\"write\"><|DSML|parameter name=\"path\" string=\"true\">b"; + for cause in [ + Termination::OutputLimit, + Termination::UserStop, + Termination::ExecutionError, + ] { + let mut parser = DsmlOutput::::new(config()); + let mut output = Accumulator::new("two_calls".into()); + output.apply(parser.push(Input::Text(text)).unwrap()).unwrap(); + output + .apply(parser.finish(cause).unwrap()) + .unwrap(); + output.discard_unfinished_call(); + output.finish().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\"}"); + } + } +} + +#[cfg(test)] +mod rejection_tests { + use super::*; + use crate::output::tagged::{OutputConfig, OutputStart}; + use crate::output::{Input, ModelOutput, Termination}; + use serde_json::json; + + fn parser() -> DsmlOutput { + DsmlOutput::new(OutputConfig { + structured: false, + start: OutputStart::Content, + tools: vec![json!({"type":"function", "function":{"name":"write"}})], + }) + } + + #[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()); + } + + #[test] + fn a_rejected_argument_object_fails_after_its_fragments_are_published() { + let text = "<|DSML|tool_calls><|DSML|invoke name=\"write\"><|DSML|parameter name=\"q\" string=\"true\">a<|DSML|parameter name=\"q\" string=\"true\">b"; + let first_value = text.find("").unwrap() + "".len(); + let mut parser = parser(); + let events = parser.push(Input::Text(&text[..first_value])).unwrap(); + assert!( + events + .iter() + .any(|event| matches!(event, Event::ToolBegin { index: 0, name, .. } if name == "write")), + "the call name was never announced" + ); + assert!( + events.iter().any(|event| matches!(event, Event::ToolArguments { text, .. } if !text.is_empty())), + "no argument fragment was published before the rejection" + ); + let err = parser.push(Input::Text(&text[first_value..])).unwrap_err(); + assert!(err.to_string().contains("unique"), "{err}"); + } +} diff --git a/helios/src/server/output.rs b/helios/src/server/output.rs index 62a83c7ab..2a5e3d7f8 100644 --- a/helios/src/server/output.rs +++ b/helios/src/server/output.rs @@ -166,6 +166,12 @@ impl Accumulator { } Ok(()) } + /// Forget the last call when it was announced but never completed. + pub(crate) fn discard_unfinished_call(&mut self) { + if self.calls.last().is_some_and(|call| !call.ended) { + self.calls.pop(); + } + } pub(crate) fn message(&self) -> Value { let mut message = json!({"role":"assistant","content":if self.content.is_empty(){Value::Null}else{Value::String(self.content.clone())}}); if !self.reasoning.is_empty() { @@ -468,6 +474,12 @@ impl Drop for Decoder<'_, P> { } } +/// 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 +} + #[cfg(test)] struct Presentation<'a, P: ModelOutput> { decoder: Decoder<'a, P>, @@ -489,6 +501,9 @@ impl<'a, P: ModelOutput> Presentation<'a, P> { } fn finish(&mut self, cause: Termination) -> Result> { let deltas = self.output.apply(self.decoder.finish(cause)?)?; + if drops_unfinished_call(cause) { + self.output.discard_unfinished_call(); + } self.output.finish()?; Ok(deltas) } @@ -1251,20 +1266,15 @@ pub(crate) mod tests { ); } #[test] - fn user_stop_cannot_retract_an_already_emitted_partial_tool_call() { + fn user_stop_omits_an_already_emitted_partial_tool_call() { let frontend = frontend(&["x"]); let observed = Arc::new(Mutex::new(Vec::new())); let mut presentation = Presentation::::new(&frontend, &[98], observed, "partial".into()); let deltas = presentation.push(98).unwrap(); assert_eq!(deltas[0]["tool_calls"][0]["function"]["name"], "partial"); - assert_eq!( - presentation - .finish(Termination::UserStop) - .unwrap_err() - .to_string(), - "incomplete emitted tool call" - ); + presentation.finish(Termination::UserStop).unwrap(); + assert!(presentation.message().get("tool_calls").is_none()); } #[test] fn decoding_sources_cannot_be_mixed_in_either_order() { @@ -1370,7 +1380,7 @@ pub(crate) mod tests { .unwrap(); out.apply(Event::ToolEnd { index: 0 }, &resp_req_id) .unwrap(); - out.finish().unwrap(); + out.finish(Termination::Eos).unwrap(); let Block::Tool { id, .. } = &out.blocks[0] else { panic!("expected tool block"); }; @@ -1423,7 +1433,7 @@ pub(crate) mod tests { out.apply(Event::ToolEnd { index }, &scope).unwrap(); } acc.finish().unwrap(); - out.finish().unwrap(); + out.finish(Termination::Eos).unwrap(); let acc_calls = acc.message()["tool_calls"].as_array().unwrap().clone(); assert_eq!(acc_calls.len(), 128); assert_eq!(out.blocks.len(), 128); @@ -1639,7 +1649,7 @@ pub(crate) mod tests { let blocks_before = unclosed.blocks.clone(); let calls_before = unclosed.calls.clone(); - let err = unclosed.finish().unwrap_err(); + let err = unclosed.finish(Termination::Eos).unwrap_err(); assert_eq!(err.to_string(), "incomplete emitted tool call"); assert_eq!(unclosed.open, Some(0)); assert_eq!(unclosed.blocks, blocks_before); @@ -1667,7 +1677,7 @@ pub(crate) mod tests { .apply(Event::ToolEnd { index: 0 }, req_id) .unwrap(); assert_eq!(unclosed.open, None); - assert!(unclosed.finish().unwrap().is_empty()); + assert!(unclosed.finish(Termination::Eos).unwrap().is_empty()); } } @@ -1694,6 +1704,7 @@ pub(super) struct ResponseOutput { pub blocks: Vec, open: Option, calls: Vec, + abandoned: Option, } impl ResponseOutput { pub fn has_tools(&self) -> bool { @@ -1721,11 +1732,34 @@ impl ResponseOutput { } Ok(()) } - pub fn finish(&mut self) -> Result> { + pub fn finish(&mut self, cause: Termination) -> Result> { 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)); + self.abandoned = Some(last); + self.open = None; + } self.close(&mut changes)?; Ok(changes) } + /// Whether `finish` closed the tool block at `index` to send its closing + /// frame for a call that never completed. The block stays present until + /// `discard_abandoned`. + pub fn is_abandoned(&self, index: usize) -> bool { + self.abandoned == Some(index) + } + /// Remove the block `finish` closed for a truncated call, once its + /// closing frame has been rendered. + pub fn discard_abandoned(&mut self) { + if self.abandoned.take().is_some() { + self.blocks.pop(); + self.calls.pop(); + } + } pub fn apply(&mut self, event: Event, request_id: &str) -> Result> { let mut changes = vec![]; match event { diff --git a/helios/src/server/protocol/encode.rs b/helios/src/server/protocol/encode.rs index 848f9c920..f1b077218 100644 --- a/helios/src/server/protocol/encode.rs +++ b/helios/src/server/protocol/encode.rs @@ -10,7 +10,7 @@ use crate::{ output::{Event, Termination}, server::{ inference::{Tool, ToolChoice}, - output::{Accumulator, Block, Change, ResponseOutput}, + output::{Accumulator, Block, Change, ResponseOutput, drops_unfinished_call}, }, }; use serde_json::{Value, json}; @@ -468,22 +468,27 @@ impl Encoder { frames.push(self.named(name, data)); } (Protocol::Responses, Change::End(i)) => { - if let Block::Tool { - name, arguments, .. - } = &self.outputs[0].blocks[i] + 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 { - if self.tool(name).is_some_and(|tool| tool.custom) { - let value: Value = serde_json::from_str(arguments) - .map_err(|e| format!("invalid custom tool arguments: {e}"))?; - if !value.get("input").is_some_and(Value::is_string) { - return Err("custom tool input must be text".into()); - } - if let Some(grammar) = self.tool_grammars.get(name) { - grammar.validate(value["input"].as_str().unwrap())?; - } + let value: Value = serde_json::from_str(arguments) + .map_err(|e| format!("invalid custom tool arguments: {e}"))?; + if !value.get("input").is_some_and(Value::is_string) { + return Err("custom tool input must be text".into()); + } + if let Some(grammar) = self.tool_grammars.get(name) { + grammar.validate(value["input"].as_str().unwrap())?; } } - let item = self.item(i, true); + // A truncated custom call has no complete input, so its item + // reports an empty string instead of the partial arguments. + let complete = !(abandoned && custom); + let item = self.item(i, complete); match &self.outputs[0].blocks[i] { Block::Text(text) | Block::Reasoning(text) => { let name = if matches!(&self.outputs[0].blocks[i], Block::Text(_)) { @@ -503,8 +508,10 @@ impl Encoder { if !item["input"].is_string() { return Err("custom tool input must be text".into()); } - frames.push(self.named("response.custom_tool_call_input.delta",json!({"item_id":self.item_id(i),"output_index":i,"delta":item["input"]}))); - frames.push(self.named("response.custom_tool_call_input.done",json!({"item_id":self.item_id(i),"output_index":i,"input":item["input"]}))); + if !abandoned { + frames.push(self.named("response.custom_tool_call_input.delta",json!({"item_id":self.item_id(i),"output_index":i,"delta":item["input"]}))); + frames.push(self.named("response.custom_tool_call_input.done",json!({"item_id":self.item_id(i),"output_index":i,"input":item["input"]}))); + } } else { frames.push(self.named("response.function_call_arguments.done",json!({"item_id":self.item_id(i),"output_index":i,"arguments":item["arguments"]}))); } @@ -672,16 +679,32 @@ impl Encoder { let stop = if self.tool_limit_reached { None } else { stop }; let mut frames = vec![]; if self.protocol == Protocol::Chat { + if drops_unfinished_call(cause) { + self.chats[index].discard_unfinished_call(); + } self.chats[index].finish()?; } - for change in self.outputs[index].finish()? { - if self.protocol == Protocol::Responses && cause == Termination::OutputLimit { - if let Change::End(i) = change { - self.incomplete_item = Some(i); + let mut abandoned = false; + for change in self.outputs[index].finish(cause)? { + if self.protocol == Protocol::Responses + && let Change::End(i) = &change + { + // An abandoned block is incomplete whatever ended it. Any other + // block is incomplete only when the output limit cut it short. + 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; + } if matches!(self.tool_choice, ToolChoice::Required | ToolChoice::Named(_)) && !self.outputs[index].has_tools() { diff --git a/helios/src/server/protocol/tests.rs b/helios/src/server/protocol/tests.rs index e8159a1d8..5ba7b42b9 100644 --- a/helios/src/server/protocol/tests.rs +++ b/helios/src/server/protocol/tests.rs @@ -51,6 +51,40 @@ fn encoder_with_parallel(protocol: Protocol, tool_choice: ToolChoice, parallel: json!({}), ) } +/// A Responses encoder whose only tool takes free-form text and validates it +/// against a grammar. +fn custom_tool_encoder(tool_choice: ToolChoice) -> Encoder { + let mut tools = tools(); + tools[0].custom = true; + let mut encoder = Encoder::new( + Protocol::Responses, + "test".into(), + "model".into(), + 1, + 1, + vec![PromptUsage { + tokens: 17, + image_tokens: 0, + }], + tools, + tool_choice, + true, + true, + json!({}), + ); + let compiler = crate::grammar::GrammarCompiler::new( + &crate::grammar::tests::byte_tokenizer(), + 320, + &[256, 257], + &[], + ) + .unwrap(); + encoder.set_tool_grammars(std::collections::HashMap::from([( + "lookup".to_owned(), + compiler.compile_text("regex", "SELECT [a-z]+").unwrap(), + )])); + encoder +} fn events() -> Vec { vec![ Event::Reasoning("考え".into()), @@ -3805,3 +3839,392 @@ fn responses_tool_outputs_decode_is_error_and_match_chat_and_messages() { } } } + +#[test] +fn an_announced_call_is_omitted_when_the_response_truncates() { + for protocol in [Protocol::Chat, Protocol::Messages, Protocol::Responses] { + for cause in [ + Termination::OutputLimit, + Termination::UserStop, + Termination::Cancelled, + Termination::ExecutionError, + ] { + for fragment in [Some(r#"{"query":"par"#), None] { + let mut encoder = encoder(protocol); + let _ = encoder.start(); + let opening = encoder + .apply( + 0, + vec![Event::ToolBegin { + index: 0, + name: "lookup".into(), + id: Some("call_1".into()), + }], + ) + .unwrap(); + assert_eq!(opening.len(), 1, "{protocol:?} opens a call with one frame"); + match protocol { + Protocol::Chat => assert_eq!( + opening[0].data["choices"][0]["delta"]["tool_calls"][0]["function"]["name"], + "lookup" + ), + Protocol::Messages => { + assert_eq!(opening[0].event.as_deref(), Some("content_block_start")); + assert_eq!(opening[0].data["content_block"]["input"], json!({})); + } + Protocol::Responses => { + assert_eq!( + opening[0].event.as_deref(), + Some("response.output_item.added") + ); + assert_eq!(opening[0].data["item"]["arguments"], ""); + } + _ => unreachable!(), + } + if let Some(text) = fragment { + let fragments = encoder + .apply( + 0, + vec![Event::ToolArguments { + index: 0, + text: text.into(), + }], + ) + .unwrap(); + assert_eq!( + fragments.len(), + 1, + "{protocol:?} publishes one fragment frame" + ); + } + let finished = encoder.finish(0, cause, 4, 0, None).unwrap(); + assert!(!finished.is_empty(), "{protocol:?} reports its finish"); + match protocol { + Protocol::Chat => {} + Protocol::Messages => assert!( + finished + .iter() + .any(|frame| frame.event.as_deref() == Some("content_block_stop")), + "{cause:?} left the announced block open" + ), + Protocol::Responses => assert!( + finished.iter().any( + |frame| frame.event.as_deref() == Some("response.output_item.done") + ), + "{cause:?} left the announced item open" + ), + _ => unreachable!(), + } + let response = encoder.response(); + match protocol { + Protocol::Chat => { + assert!( + response["choices"][0]["message"] + .get("tool_calls") + .is_none(), + "{cause:?}" + ); + let reason = if cause == Termination::OutputLimit { + "length" + } else { + "stop" + }; + assert_eq!(response["choices"][0]["finish_reason"], reason, "{cause:?}"); + } + Protocol::Messages => { + assert!( + response["content"].as_array().unwrap().is_empty(), + "{cause:?}" + ); + if cause == Termination::OutputLimit { + assert_eq!(response["stop_reason"], "max_tokens"); + } + } + Protocol::Responses => { + assert!( + response["output"].as_array().unwrap().is_empty(), + "{cause:?}" + ); + if cause == Termination::OutputLimit { + assert_eq!(response["status"], "incomplete"); + } + } + _ => unreachable!(), + } + } + } + } +} + +#[test] +fn a_truncated_second_call_keeps_the_completed_first_call() { + for protocol in [Protocol::Chat, Protocol::Messages, Protocol::Responses] { + for cause in [ + Termination::OutputLimit, + Termination::UserStop, + Termination::Cancelled, + ] { + let mut encoder = encoder(protocol); + let _ = encoder.start(); + encoder + .apply( + 0, + vec![ + Event::ToolBegin { + index: 0, + name: "lookup".into(), + id: Some("call_1".into()), + }, + Event::ToolArguments { + index: 0, + text: r#"{"query":"one"}"#.into(), + }, + Event::ToolEnd { index: 0 }, + Event::ToolBegin { + index: 1, + name: "lookup".into(), + id: Some("call_2".into()), + }, + Event::ToolArguments { + index: 1, + text: r#"{"query":"tw"#.into(), + }, + ], + ) + .unwrap(); + encoder.finish(0, cause, 4, 0, None).unwrap(); + let response = encoder.response(); + match protocol { + Protocol::Chat => { + let calls = response["choices"][0]["message"]["tool_calls"] + .as_array() + .unwrap(); + assert_eq!(calls.len(), 1, "{cause:?}"); + assert_eq!(calls[0]["function"]["arguments"], r#"{"query":"one"}"#); + let reason = match cause { + Termination::OutputLimit => "length", + Termination::UserStop => "stop", + _ => "tool_calls", + }; + assert_eq!(response["choices"][0]["finish_reason"], reason, "{cause:?}"); + } + Protocol::Messages => { + let content = response["content"].as_array().unwrap(); + assert_eq!(content.len(), 1, "{cause:?}"); + assert_eq!(content[0]["type"], "tool_use"); + assert_eq!(content[0]["input"], json!({"query": "one"})); + } + Protocol::Responses => { + let output = response["output"].as_array().unwrap(); + assert_eq!(output.len(), 1, "{cause:?}"); + assert_eq!(output[0]["type"], "function_call"); + assert_eq!(output[0]["arguments"], r#"{"query":"one"}"#); + } + _ => unreachable!(), + } + } + } +} + +#[test] +fn dsml_arguments_reach_the_chat_wire_while_the_call_is_open() { + use crate::{ + model::contract::{ToolParser, ToolParserKind}, + output::{ + Input as OutputInput, OutputConfig, OutputPipeline, + tagged::{self, OutputStart}, + }, + }; + let mut syntax = crate::model::testing::metadata().frontend; + syntax.reasoning = None; + syntax.tools = Some(ToolParser { + kind: ToolParserKind::Dsml, + wrapping_newlines: 0, + tag_separator: String::new(), + }); + let mut parser = OutputPipeline::new(OutputConfig { + syntax, + control_tokens: vec![], + content: tagged::OutputConfig { + structured: false, + start: OutputStart::Content, + tools: vec![json!({"type":"function","function":{"name":"lookup"}})], + }, + }); + let mut encoder = encoder(Protocol::Chat); + let _ = encoder.start(); + let wire = "<|DSML|tool_calls><|DSML|invoke name=\"lookup\"><|DSML|parameter name=\"q\" string=\"true\">ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + let envelope_close = wire.find("").unwrap(); + let mut fragments = String::new(); + let mut arguments_before_close = 0; + let mut named = false; + for (at, character) in wire.char_indices() { + let piece = &wire[at..at + character.len_utf8()]; + for frame in encoder.apply(0, parser.push(OutputInput::Text(piece)).unwrap()).unwrap() { + for call in frame.data["choices"][0]["delta"]["tool_calls"] + .as_array() + .into_iter() + .flatten() + { + if call["function"]["name"].as_str() == Some("lookup") { + named = true; + } + if let Some(arguments) = call["function"]["arguments"].as_str() + && !arguments.is_empty() + { + fragments.push_str(arguments); + if at < envelope_close { + arguments_before_close += 1; + } + } + } + } + } + let tail = parser.finish(Termination::Eos).unwrap(); + encoder.apply(0, tail).unwrap(); + encoder.finish(0, Termination::Eos, 8, 0, None).unwrap(); + assert!(named, "the call name never reached the wire"); + assert!( + arguments_before_close > 2, + "only {arguments_before_close} argument frames arrived before the envelope closed" + ); + let expected = r#"{"q": "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"}"#; + assert_eq!(fragments, expected); + let stored = encoder.response()["choices"][0]["message"]["tool_calls"][0]["function"] + ["arguments"] + .as_str() + .unwrap() + .to_owned(); + assert_eq!(stored, expected); +} + +#[test] +fn a_truncated_custom_call_closes_incomplete_without_failing_the_request() { + for cause in [Termination::OutputLimit, Termination::UserStop] { + // The first partial parses but fails the grammar; the second does not + // parse at all. + for partial in [r#"{"input":"nope"}"#, r#"{"input":"#] { + let mut encoder = custom_tool_encoder(ToolChoice::Auto); + let _ = encoder.start(); + let opening = encoder + .apply( + 0, + vec![ + Event::ToolBegin { + index: 0, + name: "lookup".into(), + id: Some("call_1".into()), + }, + Event::ToolArguments { + index: 0, + text: partial.into(), + }, + ], + ) + .unwrap(); + assert_eq!(opening.len(), 1, "{cause:?} {partial:?}"); + let frames = encoder.finish(0, cause, 3, 0, None).unwrap(); + let done: Vec<_> = frames + .iter() + .filter(|frame| frame.event.as_deref() == Some("response.output_item.done")) + .collect(); + assert_eq!(done.len(), 1, "{cause:?} {partial:?}"); + assert_eq!(done[0].data["item"]["type"], "custom_tool_call"); + assert_eq!(done[0].data["item"]["status"], "incomplete"); + assert_eq!(done[0].data["item"]["input"], ""); + assert!( + !frames.iter().any(|frame| frame + .event + .as_deref() + .is_some_and(|name| name.starts_with("response.custom_tool_call_input"))), + "{cause:?} {partial:?}" + ); + assert_eq!(encoder.response()["output"], json!([]), "{cause:?} {partial:?}"); + } + } +} + +#[test] +fn an_abandoned_function_call_reports_incomplete() { + for cause in [Termination::UserStop, Termination::Cancelled] { + let mut encoder = encoder(Protocol::Responses); + let _ = encoder.start(); + let streamed = encoder + .apply( + 0, + vec![ + Event::ToolBegin { + index: 0, + name: "lookup".into(), + id: Some("call_1".into()), + }, + Event::ToolArguments { + index: 0, + text: r#"{"query":"par"#.into(), + }, + ], + ) + .unwrap(); + assert!( + streamed + .iter() + .any(|frame| frame.event.as_deref() + == Some("response.function_call_arguments.delta")), + "{cause:?}" + ); + let frames = encoder.finish(0, cause, 2, 0, None).unwrap(); + let done: Vec<_> = frames + .iter() + .filter(|frame| frame.event.as_deref() == Some("response.output_item.done")) + .collect(); + assert_eq!(done.len(), 1, "{cause:?}"); + assert_eq!(done[0].data["item"]["type"], "function_call"); + assert_eq!(done[0].data["item"]["status"], "incomplete"); + assert_eq!(done[0].data["item"]["arguments"], r#"{"query":"par"#); + assert!( + frames + .iter() + .any(|frame| frame.event.as_deref() + == Some("response.function_call_arguments.done")), + "{cause:?}" + ); + assert_eq!(encoder.response()["output"], json!([]), "{cause:?}"); + } +} + +#[test] +fn a_truncated_call_does_not_satisfy_a_required_tool_choice() { + for choice in [ToolChoice::Required, ToolChoice::Named("lookup".into())] { + for mut encoder in [ + custom_tool_encoder(choice.clone()), + encoder_with_choice(Protocol::Responses, choice.clone()), + ] { + let _ = encoder.start(); + encoder + .apply( + 0, + vec![ + Event::ToolBegin { + index: 0, + name: "lookup".into(), + id: Some("call_1".into()), + }, + Event::ToolArguments { + index: 0, + text: r#"{"query":"par"#.into(), + }, + ], + ) + .unwrap(); + let error = encoder + .finish(0, Termination::UserStop, 2, 0, None) + .unwrap_err(); + assert!( + error + .to_string() + .contains("did not produce a completed tool call"), + "{choice:?}: {error}" + ); + } + } +} diff --git a/helios/tests/deepseek_output.rs b/helios/tests/deepseek_output.rs index a34cf8713..28a2bac63 100644 --- a/helios/tests/deepseek_output.rs +++ b/helios/tests/deepseek_output.rs @@ -496,11 +496,15 @@ fn empty_and_duplicate_top_level_parameter_names_are_rejected() { .collect(), ] { let mut output = pipeline(spaced, OutputStart::Content, false); - let mut published = vec![]; + let mut parsed = Parsed::default(); let mut error = None; for chunk in chunks { match output.push(Input::Text(chunk)) { - Ok(events) => published.extend(events), + Ok(events) => { + for event in events { + parsed.event(event); + } + } Err(failure) => { error = Some(failure); break; @@ -508,7 +512,7 @@ fn empty_and_duplicate_top_level_parameter_names_are_rejected() { } } assert!(error.unwrap().to_string().contains("nonempty and unique")); - assert!(published.is_empty()); + assert_eq!(parsed.ended, 0, "a rejected call reported an end"); } } let nested = parameter("object", "{\"x\":1,\"x\":2}"); @@ -572,16 +576,20 @@ fn parse_literal_parameters( let (open, _, close) = block(spaced); let s = if spaced { " " } else { "" }; let mut output = pipeline(spaced, OutputStart::Content, false); + let mut parsed = Parsed::default(); let header = format!("{open}<|DSML|{s}invoke name=\"lookup\">"); - assert!(output.push(Input::Text(&header))?.is_empty()); + for event in output.push(Input::Text(&header))? { + parsed.event(event); + } for (name, value) in parameters { let parameter = format!( "<|DSML|{s}parameter name=\"{name}\" string=\"false\">{value}" ); - assert!(output.push(Input::Text(¶meter))?.is_empty()); + for event in output.push(Input::Text(¶meter))? { + parsed.event(event); + } } let end = format!("{close}"); - let mut parsed = Parsed::default(); for event in output.push(Input::Text(&end))? { parsed.event(event); } @@ -822,3 +830,4 @@ fn deepseek_tool_markup_uses_special_dsml_token() { assert_eq!(parsed.ended, 1); } } + diff --git a/helios/tests/deepseek_requests.rs b/helios/tests/deepseek_requests.rs index ddcec058c..0963c3d74 100644 --- a/helios/tests/deepseek_requests.rs +++ b/helios/tests/deepseek_requests.rs @@ -680,8 +680,17 @@ fn added_non_special_dsml_token_produces_tool_calls() { events.extend(output.finish(flare_helios::output::Termination::Eos).unwrap()); assert!(events.iter().any(|event| matches!(event, flare_helios::output::Event::ToolBegin { name, .. } if name == "get_weather"))); - assert!(events.iter().any(|event| matches!(event, - flare_helios::output::Event::ToolArguments { text, .. } if serde_json::from_str::(text).unwrap() == json!({"location":"Berlin"})))); + let arguments: String = events + .iter() + .filter_map(|event| match event { + flare_helios::output::Event::ToolArguments { text, .. } => Some(text.as_str()), + _ => None, + }) + .collect(); + assert_eq!( + serde_json::from_str::(&arguments).unwrap(), + json!({"location": "Berlin"}) + ); assert!(events.iter().any(|event| matches!(event, flare_helios::output::Event::ToolEnd { .. }))); } } From 826a427a6198ae8eb249673dbaf42d57bc4307ab Mon Sep 17 00:00:00 2001 From: Giulio De Pasquale Date: Sat, 5 Dec 2026 11:33:40 +0000 Subject: [PATCH 2/5] docs(api): scope fragment publication to function calls A custom tool call publishes no argument fragment while the model writes, and the text a client assembles is the item's input rather than the stored argument object, so the fragment-identity sentence held only for function calls. Design-Signed-Off-By: pi coding agent; design-review=2e5b Signed-off-by: Giulio De Pasquale --- docs/api.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/api.md b/docs/api.md index c9f6495fa..6edf26b28 100644 --- a/docs/api.md +++ b/docs/api.md @@ -538,9 +538,12 @@ Completions maximum and the `[a-zA-Z0-9_-]+` character set accepted across Chat Completions, Responses, and Messages, keeping synthesized identifiers distinct across calls, choices, requests, server restarts, and hosts. Tool arguments are JSON objects, bounded to 8 MiB. A DeepSeek DSML call is announced once its name -is complete, and its argument text is published while the model writes it, so -concatenating the argument fragments of a call reproduces its stored arguments -byte for byte. The tagged tool parsers publish a call only when its envelope is +is complete, and a function call's argument text is published while the model +writes it, so concatenating the argument fragments of a function call +reproduces its stored arguments byte for byte. A custom tool call publishes its +input once its arguments are accepted, because the client's text is the input +inside the argument object rather than the object itself. The tagged tool +parsers publish a call only when its envelope is complete. An announced call cut off before completion is omitted from a buffered response for every termination other than natural end-of-sequence, and a response that completes reports the termination's finish reason; only an From c28c3c3ffa328a12fcd1abfd8e6f86cd432b40eb Mon Sep 17 00:00:00 2001 From: Giulio De Pasquale Date: Sat, 5 Dec 2026 12:09:44 +0000 Subject: [PATCH 3/5] docs(api): scope the truncated item's status to Responses Only a Responses item carries a status: a truncated Messages block ends with content_block_stop and reports the truncation through message_delta, and a Chat call has no per-call closing frame. Design-Signed-Off-By: pi coding agent; design-review=2e5b Signed-off-by: Giulio De Pasquale --- docs/api.md | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/docs/api.md b/docs/api.md index 6edf26b28..8920e09d5 100644 --- a/docs/api.md +++ b/docs/api.md @@ -543,16 +543,17 @@ writes it, so concatenating the argument fragments of a function call reproduces its stored arguments byte for byte. A custom tool call publishes its input once its arguments are accepted, because the client's text is the input inside the argument object rather than the object itself. The tagged tool -parsers publish a call only when its envelope is -complete. An announced call cut off before completion is omitted from a -buffered response for every termination other than natural end-of-sequence, and -a response that completes reports the termination's finish reason; only an -output-limit termination reports the output limit. The closing frame of such an -item reports status `incomplete`, and a truncated custom call's item carries an -empty input because its arguments never formed. When the omitted call leaves no -completed call, a `required` or named `tool_choice` fails the response instead, -producing HTTP 500 for buffered requests or a terminal error event for streams. A client that received fragments of such a call has already seen a -call that cannot complete. At natural completion, tagged tool parsers accept a +parsers publish a call only when its envelope is complete. An announced call cut +off before completion is omitted from a buffered response for every termination +other than natural end-of-sequence, and a response that completes reports the +termination's finish reason; only an output-limit termination reports the +output limit. On the Responses wire the closing frame of such an item reports +status `incomplete`, and a truncated custom call's item carries an empty input +because its arguments never formed. When the omitted call leaves no completed +call, a `required` or named `tool_choice` fails the response instead, producing +HTTP 500 for buffered requests or a terminal error event for streams. A client +that received fragments of such a call has already seen a call that cannot +complete. At natural completion, tagged tool parsers accept a non-strict call whose inner arguments are structurally complete and self-delimited when only its closing wrapper tag is omitted; undecided openers, bare headers without a closing argument delimiter, unclosed arguments, trailing From dfe38d4c05af3005a7d55d12e70003b29789f932 Mon Sep 17 00:00:00 2001 From: Giulio De Pasquale Date: Sat, 5 Dec 2026 12:17:26 +0000 Subject: [PATCH 4/5] refactor(helios): simplify DSML publication and truncated-call output Design-Signed-Off-By: pi coding agent; design-review=2e5b Signed-off-by: Giulio De Pasquale --- helios/src/output/dsml.rs | 14 +++++++------- helios/src/server/output.rs | 9 ++++----- helios/src/server/protocol/encode.rs | 26 +++++++++++++------------- helios/src/server/protocol/tests.rs | 7 ++++++- 4 files changed, 30 insertions(+), 26 deletions(-) diff --git a/helios/src/output/dsml.rs b/helios/src/output/dsml.rs index a4de4468b..c926c4d86 100644 --- a/helios/src/output/dsml.rs +++ b/helios/src/output/dsml.rs @@ -50,15 +50,17 @@ impl Call { /// /// A value whose `string="false"` text may still be rewritten stays private /// until `close_literal` decides, so published text never changes afterwards. - fn publish(&mut self, index: usize, events: &mut Vec) { + fn publish(&mut self, index: usize, events: &mut Vec) -> Result<()> { + self.check_size()?; if self.literal.is_some() || self.published_argument_bytes == self.arguments.len() { - return; + return Ok(()); } events.push(Event::ToolArguments { index, text: self.arguments[self.published_argument_bytes..].to_owned(), }); self.published_argument_bytes = self.arguments.len(); + Ok(()) } /// Retain the model's text when it cannot be decoded as a value in the argument object. @@ -188,8 +190,7 @@ impl DsmlOutput { } call.arguments.push_str(source); } - call.check_size()?; - call.publish(self.calls, events); + call.publish(self.calls, events)?; } OutputAction::ToolCallArgumentsEnd { closing_text } if !repeated => { let mut call = self @@ -198,9 +199,8 @@ impl DsmlOutput { .ok_or("DeepSeek tool arguments have no call")?; call.close_literal(); call.arguments.push_str(closing_text); - call.check_size()?; validate_arguments(&call.arguments)?; - call.publish(self.calls, events); + call.publish(self.calls, events)?; events.push(Event::ToolEnd { index: self.calls }); self.calls += 1; } @@ -953,7 +953,7 @@ mod streaming_tests { } #[test] - fn a_truncated_second_call_keeps_the_completed_first_call() { + fn dsml_truncated_second_call_keeps_the_completed_first_call() { let text = "thought<|DSML|tool_calls>\n<|DSML|invoke name=\"write\"><|DSML|parameter name=\"path\" string=\"true\">a.txt\n<|DSML|invoke name=\"write\"><|DSML|parameter name=\"path\" string=\"true\">b"; for cause in [ Termination::OutputLimit, diff --git a/helios/src/server/output.rs b/helios/src/server/output.rs index 2a5e3d7f8..301c58ec1 100644 --- a/helios/src/server/output.rs +++ b/helios/src/server/output.rs @@ -1735,12 +1735,11 @@ impl ResponseOutput { pub fn finish(&mut self, cause: Termination) -> Result> { let mut changes = vec![]; if drops_unfinished_call(cause) - && self.open.is_some() - && matches!(self.blocks.last(), Some(Block::Tool { .. })) + && let Some(index) = self.open + && matches!(self.blocks[index], Block::Tool { ended: false, .. }) { - let last = self.blocks.len() - 1; - changes.push(Change::End(last)); - self.abandoned = Some(last); + changes.push(Change::End(index)); + self.abandoned = Some(index); self.open = None; } self.close(&mut changes)?; diff --git a/helios/src/server/protocol/encode.rs b/helios/src/server/protocol/encode.rs index f1b077218..126b44e67 100644 --- a/helios/src/server/protocol/encode.rs +++ b/helios/src/server/protocol/encode.rs @@ -469,20 +469,20 @@ impl Encoder { } (Protocol::Responses, Change::End(i)) => { 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 + let mut custom = false; + if let Block::Tool { name, arguments, .. } = &self.outputs[0].blocks[i] + && self.tool(name).is_some_and(|tool| tool.custom) { - let value: Value = serde_json::from_str(arguments) - .map_err(|e| format!("invalid custom tool arguments: {e}"))?; - if !value.get("input").is_some_and(Value::is_string) { - return Err("custom tool input must be text".into()); - } - if let Some(grammar) = self.tool_grammars.get(name) { - grammar.validate(value["input"].as_str().unwrap())?; + custom = true; + if !abandoned { + let value: Value = serde_json::from_str(arguments) + .map_err(|e| format!("invalid custom tool arguments: {e}"))?; + if !value.get("input").is_some_and(Value::is_string) { + return Err("custom tool input must be text".into()); + } + if let Some(grammar) = self.tool_grammars.get(name) { + grammar.validate(value["input"].as_str().unwrap())?; + } } } // A truncated custom call has no complete input, so its item diff --git a/helios/src/server/protocol/tests.rs b/helios/src/server/protocol/tests.rs index 5ba7b42b9..d734c5ad8 100644 --- a/helios/src/server/protocol/tests.rs +++ b/helios/src/server/protocol/tests.rs @@ -4100,7 +4100,12 @@ fn dsml_arguments_reach_the_chat_wire_while_the_call_is_open() { #[test] fn a_truncated_custom_call_closes_incomplete_without_failing_the_request() { - for cause in [Termination::OutputLimit, Termination::UserStop] { + for cause in [ + Termination::OutputLimit, + Termination::UserStop, + Termination::Cancelled, + Termination::ExecutionError, + ] { // The first partial parses but fails the grammar; the second does not // parse at all. for partial in [r#"{"input":"nope"}"#, r#"{"input":"#] { From b97312c929763cbee8360098cc68fba8f21d3c94 Mon Sep 17 00:00:00 2001 From: Giulio De Pasquale Date: Sat, 5 Dec 2026 12:54:49 +0000 Subject: [PATCH 5/5] style: drop a trailing blank line from deepseek_output.rs Design-Signed-Off-By: pi coding agent; design-review=2e5b Signed-off-by: Giulio De Pasquale --- helios/tests/deepseek_output.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/helios/tests/deepseek_output.rs b/helios/tests/deepseek_output.rs index 28a2bac63..2099457ca 100644 --- a/helios/tests/deepseek_output.rs +++ b/helios/tests/deepseek_output.rs @@ -830,4 +830,3 @@ fn deepseek_tool_markup_uses_special_dsml_token() { assert_eq!(parsed.ended, 1); } } -