From f528844ff92edf2ffb5d6fd5f9c52d9e6f56d362 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 30 Oct 2026 03:48:29 +0100 Subject: [PATCH] fix: read the recoverable tool-call cases instead of failing the response Four shapes that ended in response.failed (or 502 tool_call_parse_failed) are now calls, each logged on stderr as "tool call accepted beyond the template form (closers supplied: N, arguments repaired: M, ...)": * left out: a followed by ends the value and the call, but only when no followed by ends the value (upstream d7113273, #4427/#4077). A streamed response delivers such a call when the generation ends, not at its : only the end can tell it from quoted inside a value. * left out: the call is whole when the next follows its , or when its ends a generation that stopped by itself (finish stop). A generation cut by the token limit never gets this. * A call inside the reasoning (no ): a normal stop whose text ends on whole calls of declared tools, the first at the start of a line outside a code fence and inline code, is reasoning (completed) followed by those calls (upstream 805ebe17/d7113273, #804). The calls' markup was already streamed as reasoning deltas; the final reasoning item ends before it. * Damaged array/object arguments of a parameter declared array or object (not a union with string): a trailing or doubled comma, single quotes, Python True/False/None, extra closing brackets, and an array written as a JSON string of itself are read as written (upstream _Lenient, A4). Nothing is invented or dropped; open brackets and bare strings are not repaired here. Undeclared tool names: upstream returns the call as text and counts it. That is NOT adopted. Text without a call ends an agent's turn as if it were the answer, while a failed response is retried by the client (docs/e2e-run.md records a session that survived one such failure), and native_tools_sdet / backend_worker_http pin the refusal. An undeclared tool is still an error; it is never run and never published. API: tool_output::{Options, Notes, Parsed, parse_with, calls_at_end}, Incremental::{with_options, finish_after, notes}; parse_complete and Incremental::new keep their strict default reading. Documented in docs/api-contract.md ("Tool-call parsing") and docs/tool-call-corpus.md. Corpus: 24 of 41 specimens read as upstream expects (13 before this commit). New unit tests cover each shape whole and streamed; strata-control lib 334 passed, native_tools_sdet 14 passed, existing tests unchanged. Co-Authored-By: Claude Sonnet 5.5 --- control-plane/src/responses.rs | 112 +++++- control-plane/src/tool_output.rs | 600 +++++++++++++++++++++++++++-- control-plane/tests/tool_corpus.rs | 25 +- docs/api-contract.md | 60 ++- docs/tool-call-corpus.md | 120 +++--- 5 files changed, 797 insertions(+), 120 deletions(-) diff --git a/control-plane/src/responses.rs b/control-plane/src/responses.rs index 1db455e3..cc1f68ac 100644 --- a/control-plane/src/responses.rs +++ b/control-plane/src/responses.rs @@ -1442,8 +1442,9 @@ pub async fn create( let tokenizer_for_decode = tokenizer.clone(); let thinking = reasoning_enabled(&request, tokenizer.family()); let finish = done.finish; + let flat_tools = flat_tools(&request); let output = match tokio::task::spawn_blocking(move || { - decode_generation(tokenizer_for_decode.as_ref(), &output_ids, thinking, finish) + decode_generation_with(tokenizer_for_decode.as_ref(), &output_ids, thinking, finish, &flat_tools) }) .await { @@ -1482,7 +1483,7 @@ pub async fn create( output.answer ) }); - let (items, reasoning_tokens) = match decoded_items(&request, output, &id) { + let (items, reasoning_tokens) = match decoded_items(&request, output, &id, finish != Finish::Length) { Ok(items) => items, Err(message) => { log_generation_failure(&message); @@ -1546,10 +1547,21 @@ pub async fn create( } } +#[cfg(test)] fn parse_output_items( request: &CreateRequest, output: String, id: &str, +) -> Result, String> { + parse_output_items_after(request, output, id, false) +} + +/// `natural_stop`: the generation ended by itself and not at the token limit, so a call that ends the text on `` is whole. +fn parse_output_items_after( + request: &CreateRequest, + output: String, + id: &str, + natural_stop: bool, ) -> Result, String> { if request.tools.is_empty() { return Ok(vec![OutputItem::Text { @@ -1557,7 +1569,10 @@ fn parse_output_items( }]); } let catalog = Catalog::new(&request.tools)?; - let mut items = tool_output::parse_complete(&output, &catalog.flat)? + let parsed = tool_output::parse_with(&output, &catalog.flat, tool_output::Options { natural_stop })?; + log_tool_notes(&parsed.notes); + let mut items = parsed + .segments .into_iter() .enumerate() .map(|(index, segment)| match segment { @@ -1577,6 +1592,18 @@ fn parse_output_items( Ok(items) } +/// The request's tool declarations in the form the parser reads; none when the request declares no tools. +fn flat_tools(request: &CreateRequest) -> Vec { + Catalog::new(&request.tools).map(|catalog| catalog.flat).unwrap_or_default() +} + +/// A tool call that was accepted although the template form was not followed is never silent: it is logged here. +fn log_tool_notes(notes: &tool_output::Notes) { + if !notes.is_empty() { + crate::elog!("tool call accepted beyond the template form ({notes})"); + } +} + fn reasoning_effort(request: &CreateRequest) -> Result { let Some(value) = &request.reasoning else { return Ok(Effort::XHigh); @@ -1628,11 +1655,23 @@ struct DecodedGeneration { reasoning_tokens: u64, } +#[cfg(test)] fn decode_generation( tokenizer: &dyn TextCodec, ids: &[u32], reasoning: bool, finish: Finish, +) -> Result { + decode_generation_with(tokenizer, ids, reasoning, finish, &[]) +} + +/// `tools`: the flat declarations of the request, to tell a call the reasoning ends on from one it only quotes. +fn decode_generation_with( + tokenizer: &dyn TextCodec, + ids: &[u32], + reasoning: bool, + finish: Finish, + tools: &[Value], ) -> Result { let bytes = decode_all(tokenizer, ids)?; if !reasoning { @@ -1646,6 +1685,28 @@ fn decode_generation( let boundary = bytes.windows(marker.len()).position(|part| part == marker); let Some(boundary) = boundary else { if finish != Finish::Length { + // The model stopped by itself without closing its reasoning. If the text ends on whole tool calls of declared + // tools, the reasoning is what comes before them and they are the answer; otherwise the turn is malformed. + // (The calls were already streamed as reasoning text; the reasoning item here ends before them.) + let text = String::from_utf8_lossy(&bytes); + if let Some(at) = tool_output::calls_at_end(&text, tools) { + crate::elog!("tool call accepted beyond the template form (written inside the reasoning, no )"); + let mut consumed = 0; + let mut reasoning_tokens = 0; + let mut decoder = tokenizer.decoder(); + for id in ids { + if consumed >= at { + break; + } + consumed += decoder.push(*id)?.len(); + reasoning_tokens += 1; + } + return Ok(DecodedGeneration { + answer: text[at..].to_owned(), + reasoning: Some((text[..at].to_owned(), true)), + reasoning_tokens, + }); + } return Err("reasoning ended without ".into()); } return Ok(DecodedGeneration { @@ -1680,6 +1741,7 @@ fn decoded_items( request: &CreateRequest, decoded: DecodedGeneration, id: &str, + natural_stop: bool, ) -> Result<(Vec, u64), String> { let mut items = Vec::new(); let mut reasoning_incomplete = false; @@ -1691,7 +1753,7 @@ fn decoded_items( reasoning_incomplete = !complete; } if !reasoning_incomplete { - items.extend(parse_output_items(request, decoded.answer, id)?); + items.extend(parse_output_items_after(request, decoded.answer, id, natural_stop)?); } Ok((items, decoded.reasoning_tokens)) } @@ -2497,8 +2559,9 @@ fn stream_live_buffered( if !delta.is_empty() && !send_stream_event(&sender, &mut sequence, "response.reasoning_text.delta", json!({"response_id":id,"item_id":reasoning_id,"output_index":0,"content_index":0,"delta":delta})).await { return; } } let post_decode = crate::stage_trace::span("post_decode"); + let flat_tools = flat_tools(&request); let decoded = tokio::task::spawn_blocking(move || { - decode_generation(tokenizer.as_ref(), &tokens, thinking, done.finish) + decode_generation_with(tokenizer.as_ref(), &tokens, thinking, done.finish, &flat_tools) }) .await .map_err(|e| e.to_string()) @@ -2506,7 +2569,7 @@ fn stream_live_buffered( drop(post_decode); let post_assemble = crate::stage_trace::span("post_assemble"); let assembled = decoded - .and_then(|output| decoded_items(&request, output, &id)) + .and_then(|output| decoded_items(&request, output, &id, done.finish != Finish::Length)) .and_then(|(items, reasoning_tokens)| { ResponseTrace::build_with_terminal( &request, @@ -2810,9 +2873,10 @@ fn stream_live_tools( if let Some(value) = done.filter(|value| value.finish != Finish::Cancel) { let remaining = drain_utf8(&mut pending_bytes, true); let parsed = parser.feed(&remaining).and_then(|mut segments| { - segments.extend(parser.finish()?); + segments.extend(parser.finish_after(value.finish != Finish::Length)?); Ok(segments) }); + log_tool_notes(parser.notes()); match parsed { Ok(segments) => { for segment in segments { @@ -5282,6 +5346,40 @@ mod tests { fs::remove_dir_all(root).unwrap(); } + #[test] + fn a_stop_without_think_close_that_ends_on_a_declared_call_is_reasoning_then_the_call() { + let (tokenizer, root) = test_tokenizer(); + let tools = [json!({"name":"lookup","parameters":{"properties":{"city":{"type":"string"}}}})]; + let call = " + + +Oslo + + +"; + let ids = tokenizer.encode(&format!("Plan: look it up. + +{call}"), false).unwrap(); + // the same tokens without a call stay the old failure; a token-limit stop never takes the calls + let err = decode_generation_with(tokenizer.as_ref(), &tokenizer.encode("No call here", false).unwrap(), true, Finish::Stop, &tools); + assert_eq!(err.err().as_deref(), Some("reasoning ended without ")); + let decoded = decode_generation_with(tokenizer.as_ref(), &ids, true, Finish::Stop, &tools).unwrap(); + assert_eq!(decoded.reasoning, Some(("Plan: look it up. + +".into(), true))); + assert_eq!(decoded.answer, call); + assert!(decoded.reasoning_tokens > 0 && decoded.reasoning_tokens < ids.len() as u64); + let undeclared = decode_generation_with(tokenizer.as_ref(), &ids, true, Finish::Stop, &[]); + assert!(undeclared.is_err()); + let limited = decode_generation_with(tokenizer.as_ref(), &ids, true, Finish::Length, &tools).unwrap(); + assert_eq!(limited.reasoning.as_ref().map(|r| r.1), Some(false)); + let request = make_request(json!({"tools":[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}]})); + let (items, _) = decoded_items(&request, decoded, "resp_x_1", true).unwrap(); + assert!(matches!(items[0], OutputItem::Reasoning { complete: true, .. })); + assert!(matches!(&items[1], OutputItem::FunctionCall { name, .. } if name == "lookup")); + fs::remove_dir_all(root).unwrap(); + } + #[test] fn reasoning_effort_uses_pinned_template_and_validates_options() { let default = make_request(json!({})); diff --git a/control-plane/src/tool_output.rs b/control-plane/src/tool_output.rs index 03634166..2158304a 100644 --- a/control-plane/src/tool_output.rs +++ b/control-plane/src/tool_output.rs @@ -1,5 +1,9 @@ //! Complete Qwen tool-call parsing for the pinned Strata chat-template format. -//! A call is publishable only after its function and outer call delimiters close. +//! A call is publishable only after its function and outer call delimiters close. Three delimiters may be missing where +//! something else shows that the call is whole: the `` after a `` that ends the generation or is +//! followed by the next call's opener, and the `` before a `` that follows the last `` +//! (see `docs/api-contract.md`, "Tool-call parsing"). A call for a tool the request did not declare is an error: it is +//! neither run nor shown as text. use serde_json::{Map, Value, json}; @@ -9,8 +13,52 @@ pub enum Segment { Call { name: String, arguments: Value }, } +/// How a text is read. `Options::default()` is the strict reading of the template form. +#[derive(Clone, Copy, Debug, Default)] +pub struct Options { + /// The generation ended on its own and not at the token limit: a call whose text ends on `` is whole. + pub natural_stop: bool, +} + +/// What was accepted although the template form was not followed. The caller logs it; nothing is silent. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Notes { + /// Calls whose `` or `` was left out and which the next token or the end of the generation confirmed. + pub closers_supplied: usize, + /// Array or object arguments that were damaged JSON (or JSON written inside a JSON string) and were read as written. + pub repaired_arguments: usize, +} + +impl Notes { + pub fn is_empty(&self) -> bool { + *self == Notes::default() + } + + fn absorb(&mut self, other: &Notes) { + self.closers_supplied += other.closers_supplied; + self.repaired_arguments += other.repaired_arguments; + } +} + +impl std::fmt::Display for Notes { + fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + out, + "closers supplied: {}, arguments repaired: {}", + self.closers_supplied, self.repaired_arguments + ) + } +} + +pub struct Parsed { + pub segments: Vec, + pub notes: Notes, +} + pub struct Incremental<'a> { tools: &'a [Value], + options: Options, + notes: Notes, buffer: String, in_call: bool, after_call: bool, @@ -21,8 +69,14 @@ pub struct Incremental<'a> { impl<'a> Incremental<'a> { pub fn new(tools: &'a [Value]) -> Self { + Self::with_options(tools, Options::default()) + } + + pub fn with_options(tools: &'a [Value], options: Options) -> Self { Self { tools, + options, + notes: Notes::default(), buffer: String::new(), in_call: false, after_call: false, @@ -30,6 +84,11 @@ impl<'a> Incremental<'a> { } } + /// What was accepted although the template form was not followed, so far. + pub fn notes(&self) -> &Notes { + &self.notes + } + pub fn feed(&mut self, delta: &str) -> Result, String> { self.buffer.push_str(delta); let mut out = Vec::new(); @@ -48,22 +107,24 @@ impl<'a> Incremental<'a> { let mut completed = None; while let Some(relative) = self.buffer[search..].find("") { let end = search + relative + "".len(); - let candidate = format!("{}", &self.buffer[..end]); - if let Ok(mut parsed) = parse_complete(&candidate, self.tools) - && parsed.len() == 1 - && matches!(parsed[0], Segment::Call { .. }) + let mut found = Notes::default(); + // A `` left out is not accepted while streaming: the `` found may be text inside + // a value, and only the end of the generation can tell (see `finish_after`). + if let Ok((call, consumed)) = + parse_call(&self.buffer[..end], self.tools, self.options, false, &mut found) { - completed = Some((end, parsed.remove(0))); + completed = Some((consumed, call, found)); break; } search = end; } - let Some((end, call)) = completed else { + let Some((consumed, call, found)) = completed else { self.tried = search; break; }; out.push(call); - self.buffer.drain(..end); + self.notes.absorb(&found); + self.buffer.drain(..consumed); self.tried = 0; self.in_call = false; self.after_call = true; @@ -90,9 +151,25 @@ impl<'a> Incremental<'a> { Ok(out) } - pub fn finish(mut self) -> Result, String> { + /// End of the generation, which stopped at the token limit or was otherwise not a natural stop. + pub fn finish(&mut self) -> Result, String> { + self.finish_after(false) + } + + /// End of the generation. With `natural_stop` a call whose text ends on `` is whole. + pub fn finish_after(&mut self, natural_stop: bool) -> Result, String> { if self.in_call { - return Err("generation ended inside a tool call".into()); + let text = format!("{}", self.buffer); + let options = Options { natural_stop, ..self.options }; + return match parse_with(&text, self.tools, options) { + Ok(parsed) => { + self.in_call = false; + self.buffer.clear(); + self.notes.absorb(&parsed.notes); + Ok(parsed.segments) + } + Err(_) => Err("generation ended inside a tool call".into()), + }; } if self.after_call || self.buffer.is_empty() { Ok(Vec::new()) @@ -109,14 +186,20 @@ fn held_tag_prefix(text: &str, tag: &str) -> usize { .unwrap_or(0) } -pub fn parse_complete(mut text: &str, tools: &[Value]) -> Result, String> { +pub fn parse_complete(text: &str, tools: &[Value]) -> Result, String> { + Ok(parse_with(text, tools, Options::default())?.segments) +} + +/// The whole text of a generation as text and calls, with what was accepted beyond the strict template form. +pub fn parse_with(mut text: &str, tools: &[Value], options: Options) -> Result { let mut segments = Vec::new(); + let mut notes = Notes::default(); while let Some(start) = text.find("") { let prefix = text[..start].trim_end_matches('\n'); if !prefix.is_empty() { segments.push(Segment::Text(prefix.to_owned())); } - let (call, consumed) = parse_call(&text[start + "".len()..], tools)?; + let (call, consumed) = parse_call(&text[start + "".len()..], tools, options, true, &mut notes)?; segments.push(call); text = &text[start + "".len() + consumed..]; text = text.trim_start_matches('\n'); @@ -124,10 +207,64 @@ pub fn parse_complete(mut text: &str, tools: &[Value]) -> Result, S if !text.is_empty() { segments.push(Segment::Text(text.to_owned())); } - Ok(segments) + Ok(Parsed { segments, notes }) } -fn parse_call(text: &str, tools: &[Value]) -> Result<(Segment, usize), String> { +/// A generation that stopped by itself without ever closing its reasoning (``) and ended on tool calls: the offset +/// where the calls start. The calls count only when every one of them is a whole call of a declared tool, they are the last +/// thing in the text (whitespace aside), and the first one stands at the start of a line outside a code fence and outside +/// inline code, so a call the reasoning only quotes is not one. +pub fn calls_at_end(text: &str, tools: &[Value]) -> Option { + let options = Options { natural_stop: true }; + let mut from = 0; + while let Some(relative) = text[from..].find("") { + let at = from + relative; + if stands_outside_code(&text[..at]) + && let Ok(parsed) = parse_with(&text[at..], tools, options) + && !parsed.segments.is_empty() + && parsed.segments.iter().all(|segment| matches!(segment, Segment::Call { .. })) + { + return Some(at); + } + from = at + 1; + } + None +} + +/// Whether the next character, after `before`, starts a line outside a code fence and outside inline code (backticks are +/// counted per paragraph). +fn stands_outside_code(before: &str) -> bool { + let mut fence: Option = None; + let mut ticks = 0usize; + let mut lines = before.split('\n').collect::>(); + let current = lines.pop().unwrap_or(""); + for line in lines { + let start = line.trim_start(); + if let Some(mark) = fence { + if start.starts_with(&mark.to_string().repeat(3)) { + fence = None; + } + } else if (start.starts_with("```") || start.starts_with("~~~")) && !start[3..].contains(&start[..3]) { + fence = start.chars().next(); + } else if start.is_empty() { + ticks = 0; + } else { + ticks += line.matches('`').count(); + } + } + fence.is_none() && current.trim().is_empty() && ticks % 2 == 0 +} + +/// The next call, and how much of `text` (which starts after ``) it used. `closes_call`: a `` followed by +/// `` may end a call whose `` was left out (only when no `` that is followed by +/// `` ends the value; see `find_parameter_end`). +fn parse_call( + text: &str, + tools: &[Value], + options: Options, + closes_call: bool, + notes: &mut Notes, +) -> Result<(Segment, usize), String> { let mut offset = text.len() - text.trim_start().len(); let rest = &text[offset..]; let rest = rest @@ -148,31 +285,30 @@ fn parse_call(text: &str, tools: &[Value]) -> Result<(Segment, usize), String> { // would only retry into the same call until the turn dies. let patch_shell = if tool.is_none() && name == "apply_patch" { patch_shell(tools) } else { None }; if tool.is_none() && patch_shell.is_none() { + // Fail closed: an undeclared tool is never run, and its text is not shown as an answer either (an agent would + // take that for the end of its turn). The client sees a failed response and retries. return Err(format!("undeclared function in tool call: {name}")); } offset += "") { offset += "".len(); offset += after.len() - after.trim_start().len(); - if !text[offset..].starts_with("") { + let tail = &text[offset..]; + if tail.starts_with("") { + offset += "".len(); + } else if starts_next_call(tail) || (options.natural_stop && tail.is_empty()) { + // The wrapper's closer was left out and the next call's opener, or the end of a generation that stopped by + // itself, shows that the call is whole. + found.closers_supplied += 1; + } else { return Err("tool call is missing ".to_owned()); } - offset += "".len(); - if let Some(shell) = &patch_shell { - let (name, arguments) = shell.rewrite(&arguments); - return Ok((Segment::Call { name, arguments }, offset)); - } - return Ok(( - Segment::Call { - name: name.to_owned(), - arguments: Value::Object(arguments), - }, - offset, - )); + break; } let after = rest .strip_prefix(" Result<(Segment, usize), String> { return Err("tool parameter name is empty".to_owned()); } offset += " Result<(Segment, usize), String> { .and_then(|value| value.get("properties")) .and_then(|value| value.get(parameter)) .and_then(|value| value.get("type")); - let parsed = parameter_value(value, declared); + let parsed = parameter_value(value, declared, &mut found); if arguments.insert(parameter.to_owned(), parsed).is_some() { return Err(format!("duplicate tool parameter: {parameter}")); } offset += value_end + "".len(); + if call_closed { + // `` and then ``: the `` was left out. + offset += text[offset..].len() - text[offset..].trim_start().len(); + offset += "".len(); + found.closers_supplied += 1; + break; + } } + notes.absorb(&found); + if let Some(shell) = &patch_shell { + let (name, arguments) = shell.rewrite(&arguments); + return Ok((Segment::Call { name, arguments }, offset)); + } + Ok(( + Segment::Call { + name: name.to_owned(), + arguments: Value::Object(arguments), + }, + offset, + )) +} + +/// Whether `tail` starts the next call: `` and then ``. +fn starts_next_call(tail: &str) -> bool { + let Some(rest) = tail.strip_prefix("") else { + return false; + }; + let Some(rest) = rest.trim_start().strip_prefix("') else { + return false; + }; + let name = rest[..end].trim(); + !name.is_empty() && !name.contains(|c: char| c == '<' || c.is_whitespace()) } /// How to run a shell command through the shell tool the agent declared. @@ -239,12 +409,64 @@ impl PatchShell { } } -fn parameter_value(raw: &str, declared: Option<&Value>) -> Value { +/// Which JSON types a parameter's declared `type` allows. +#[derive(Clone, Copy)] +struct Kinds { + string: bool, + array: bool, + object: bool, +} + +impl Kinds { + fn of(declared: Option<&Value>) -> Self { + let has = |wanted: &str| match declared { + Some(Value::String(kind)) => kind == wanted, + Some(Value::Array(kinds)) => kinds.iter().any(|kind| kind == wanted), + _ => false, + }; + Self { string: has("string"), array: has("array"), object: has("object") } + } + + /// An array or object parameter that cannot be a string, so a damaged value is not simply text. + fn structured(self) -> bool { + !self.string && (self.array || self.object) + } + + fn fits(self, value: &Value) -> bool { + (self.array && value.is_array()) || (self.object && value.is_object()) + } +} + +fn parameter_value(raw: &str, declared: Option<&Value>, found: &mut Notes) -> Value { let text = || Value::String(raw.to_owned()); if declared.is_some_and(|kind| kind == "string") { return text(); } - let parsed = serde_json::from_str(raw).unwrap_or_else(|_| text()); + let kinds = Kinds::of(declared); + let parsed = match serde_json::from_str::(raw) { + Ok(parsed) => parsed, + Err(_) => { + // A slightly damaged array or object (a trailing comma, single quotes, Python's True/None) is read as written. + if kinds.structured() + && let Some(value) = repair_json(raw).filter(|value| kinds.fits(value)) + { + found.repaired_arguments += 1; + return value; + } + text() + } + }; + if kinds.structured() + && let Value::String(inner) = &parsed + && matches!(inner.trim_start().chars().next(), Some('[' | '{')) + { + // An array or object written as a JSON string of itself. + let value = serde_json::from_str::(inner).ok().or_else(|| repair_json(inner)); + if let Some(value) = value.filter(|value| kinds.fits(value)) { + found.repaired_arguments += 1; + return value; + } + } if let Some(types) = declared.and_then(Value::as_array) && types.iter().any(|kind| kind == "string") { @@ -267,21 +489,190 @@ fn parameter_value(raw: &str, declared: Option<&Value>) -> Value { parsed } -/// Where a parameter value in `text` (which starts at the value) ends: the first `` that is followed, after -/// whitespace, by the next ``. The same text inside a value (a file that documents the call -/// format) is part of the value, and so is a close that belongs to a call the value itself quotes (upstream #4078): a -/// `` counts only when the quoted openers (`` followed by ``) before it -/// are no more than the `` closers before it. A value that reopens its own parameter (`` -/// of the same name) still ends at the first close: that text is indistinguishable from a parameter written twice, which is -/// refused (`duplicate tool parameter`) rather than merged into one argument. -fn find_parameter_end(text: &str) -> Option { +/// A reader for the mechanical slips a model makes inside an array or object argument: a trailing or doubled comma, single +/// quotes, Python's `True`/`False`/`None`, and extra closing brackets at the end. It is only asked about text that is not valid +/// JSON. It never guesses a value and never drops or invents one: a string cut short, an unknown word, brackets left open, +/// a bare string where a member belongs, a missing colon: anything else is not repaired. +fn repair_json(raw: &str) -> Option { + let text = raw.trim(); + if !text.starts_with(['[', '{']) || text.len() > 1 << 20 { + return None; + } + let mut reader = Lenient { chars: text.chars().collect(), at: 0 }; + let value = reader.value(0).ok()?; + let rest: String = reader.chars[reader.at..].iter().collect(); + rest.trim_matches(|c: char| "]}) \t\r\n".contains(c)).is_empty().then_some(value) +} + +struct Lenient { + chars: Vec, + at: usize, +} + +impl Lenient { + fn peek(&mut self) -> Option { + while self.chars.get(self.at).is_some_and(|c| matches!(c, ' ' | '\t' | '\r' | '\n')) { + self.at += 1; + } + self.chars.get(self.at).copied() + } + + fn string(&mut self) -> Result { + let quote = self.chars[self.at]; + self.at += 1; + let mut out = String::new(); + while let Some(&c) = self.chars.get(self.at) { + self.at += 1; + if c == quote { + return Ok(out); + } + if c != '\\' { + out.push(c); + continue; + } + let escape = *self.chars.get(self.at).ok_or(())?; + self.at += 1; + out.push(match escape { + '"' | '\'' | '\\' | '/' => escape, + 'b' => '\u{8}', + 'f' => '\u{c}', + 'n' => '\n', + 'r' => '\r', + 't' => '\t', + 'u' => { + let mut unit = self.hex4()?; + if (0xd800..0xdc00).contains(&unit) { + // a surrogate pair: 😀 + if self.chars.get(self.at) != Some(&'\\') || self.chars.get(self.at + 1) != Some(&'u') { + return Err(()); + } + self.at += 2; + let low = self.hex4()?; + if !(0xdc00..0xe000).contains(&low) { + return Err(()); + } + unit = 0x10000 + ((unit - 0xd800) << 10) + (low - 0xdc00); + } + char::from_u32(unit).ok_or(())? + } + _ => return Err(()), + }); + } + Err(()) + } + + fn hex4(&mut self) -> Result { + let digits: String = self.chars.get(self.at..self.at + 4).ok_or(())?.iter().collect(); + self.at += 4; + u32::from_str_radix(&digits, 16).map_err(|_| ()) + } + + fn value(&mut self, depth: usize) -> Result { + if depth > 64 { + return Err(()); + } + match self.peek().ok_or(())? { + '{' => self.object(depth + 1), + '[' => self.array(depth + 1), + '"' | '\'' => self.string().map(Value::String), + _ => { + let start = self.at; + while self + .chars + .get(self.at) + .is_some_and(|c| !c.is_whitespace() && !matches!(c, ',' | ']' | '}' | ':')) + { + self.at += 1; + } + let word: String = self.chars[start..self.at].iter().collect(); + match word.as_str() { + "true" | "True" => Ok(Value::Bool(true)), + "false" | "False" => Ok(Value::Bool(false)), + "null" | "None" => Ok(Value::Null), + _ => serde_json::from_str::(&word).ok().filter(Value::is_number).ok_or(()), + } + } + } + } + + fn object(&mut self, depth: usize) -> Result { + self.at += 1; + let mut members = Map::new(); + loop { + match self.peek() { + Some('}') => { + self.at += 1; + return Ok(Value::Object(members)); + } + Some(',') => { + self.at += 1; + continue; + } + Some('"' | '\'') => {} + _ => return Err(()), + } + let key = self.string()?; + if self.peek() != Some(':') { + return Err(()); + } + self.at += 1; + let value = self.value(depth)?; + members.insert(key, value); + } + } + + fn array(&mut self, depth: usize) -> Result { + self.at += 1; + let mut items = Vec::new(); + loop { + match self.peek() { + Some(']') => { + self.at += 1; + return Ok(Value::Array(items)); + } + Some(',') => { + self.at += 1; + continue; + } + None => return Err(()), + Some(_) => {} + } + items.push(self.value(depth)?); + if !matches!(self.peek(), Some(',' | ']')) { + return Err(()); + } + } + } +} + +/// Where a parameter value in `text` (which starts at the value) ends, and whether the call's `` was left out. +/// The value ends at the first `` that is followed, after whitespace, by the next ``. The same text inside a value (a file that documents the call format) is part of the value, and so is a close +/// that belongs to a call the value itself quotes (upstream #4078): a `` counts only when the quoted openers +/// (`` followed by ``) before it are no more than the `` closers before +/// it. (A value that reopens its own parameter, `` of the same name, still ends at the first close: +/// it is indistinguishable from a parameter written twice, which is refused as `duplicate tool parameter`, not merged.) +/// Only when no such close exists, and `closes_call` is set, a `` followed by `` ends the value and the +/// call (the `` was left out). +fn find_parameter_end(text: &str, closes_call: bool) -> Option<(usize, bool)> { + scan_parameter_end(text, false).map(|at| (at, false)).or_else(|| { + closes_call + .then(|| scan_parameter_end(text, true).map(|at| (at, true))) + .flatten() + }) +} + +fn scan_parameter_end(text: &str, call_close: bool) -> Option { let mut balance = QuoteBalance::new(text); let mut search = 0; while let Some(relative) = text[search..].find("") { let at = search + relative; if balance.opened_before(at) <= balance.closed_before(at) { let after = text[at + "".len()..].trim_start(); - if after.starts_with("") { + if after.starts_with("") + || (call_close && after.starts_with("")) + { return Some(at); } } @@ -411,6 +802,133 @@ mod tests { assert!(parse_complete(output, &exec).unwrap_err().contains("undeclared function in tool call: nope")); } + fn calls_of(segments: Vec) -> Vec<(String, Value)> { + segments + .into_iter() + .filter_map(|segment| match segment { + Segment::Call { name, arguments } => Some((name, arguments)), + Segment::Text(_) => None, + }) + .collect() + } + + fn stream(tools: &[Value], text: &str, size: usize, natural_stop: bool) -> Result<(Vec, Notes), String> { + let mut parser = Incremental::new(tools); + let mut out = Vec::new(); + let chars: Vec<(usize, char)> = text.char_indices().collect(); + for chunk in chars.chunks(size) { + let from = chunk[0].0; + let to = chunk.last().map_or(from, |(at, c)| at + c.len_utf8()); + out.extend(parser.feed(&text[from..to])?); + } + out.extend(parser.finish_after(natural_stop)?); + Ok((out, parser.notes().clone())) + } + + #[test] + fn a_call_without_function_close_is_read_when_the_wrapper_closes_it() { + let tools = [json!({"name":"write","parameters":{"properties":{"path":{"type":"string"},"content":{"type":"string"}}}})]; + let text = "\n\n\nout.txt\n\n\nhello\n\n"; + let want = vec![("write".to_owned(), json!({"path":"out.txt","content":"hello"}))]; + let parsed = parse_with(text, &tools, Options::default()).unwrap(); + assert_eq!(calls_of(parsed.segments), want); + assert_eq!(parsed.notes.closers_supplied, 1); + for size in [1, 7, text.len()] { + let (segments, notes) = stream(&tools, text, size, true).unwrap(); + assert_eq!(calls_of(segments), want, "pieces of {size}"); + assert_eq!(notes.closers_supplied, 1); + } + // two such calls, then a well-formed one + let two = format!("{text}\n{text}\nz"); + assert_eq!(calls_of(parse_complete(&two, &tools).unwrap()).len(), 3); + } + + #[test] + fn a_value_that_quotes_a_malformed_tail_is_not_cut_when_the_real_close_exists() { + // `\n` inside the value is only a candidate end: a real `` follows + let tools = [json!({"name":"write","parameters":{"properties":{"content":{"type":"string"}}}})]; + let content = "a call that lost its closer ends like\n\n\nand that is all"; + let text = format!("\n\n\n{content}\n\n\n"); + let want = vec![("write".to_owned(), json!({"content": content}))]; + assert_eq!(calls_of(parse_complete(&text, &tools).unwrap()), want); + for size in [1, 5, text.len()] { + let (segments, _) = stream(&tools, &text, size, true).unwrap(); + assert_eq!(calls_of(segments), want, "pieces of {size}"); + } + } + + #[test] + fn a_missing_wrapper_close_is_confirmed_only_by_the_next_call_or_a_natural_end() { + let tools = [json!({"name":"read","parameters":{"properties":{"path":{"type":"string"}}}})]; + let open = "\n\n\na.txt\n\n"; + let whole = format!("{open}\n"); + let want = vec![("read".to_owned(), json!({"path":"a.txt"}))]; + assert_eq!(calls_of(parse_complete(&whole, &tools).unwrap()), want); + // ends on ``: whole only when the generation stopped by itself + assert!(parse_complete(open, &tools).is_err()); + assert!(parse_with(open, &tools, Options { natural_stop: false }).is_err()); + assert_eq!(calls_of(parse_with(open, &tools, Options { natural_stop: true }).unwrap().segments), want); + assert!(stream(&tools, open, 3, false).is_err()); + assert_eq!(calls_of(stream(&tools, open, 3, true).unwrap().0), want); + // prose after `` does not confirm it + let prose = format!("{open}\nand then I will"); + assert!(parse_with(&prose, &tools, Options { natural_stop: true }).is_err()); + // the next call's opener does + let next = format!("{open}\n\n\n\nb.txt\n\n\n"); + let both = vec![want[0].clone(), ("read".to_owned(), json!({"path":"b.txt"}))]; + assert_eq!(calls_of(parse_complete(&next, &tools).unwrap()), both); + for size in [1, 4, next.len()] { + assert_eq!(calls_of(stream(&tools, &next, size, false).unwrap().0), both, "pieces of {size}"); + } + } + + #[test] + fn damaged_array_arguments_are_read_as_written_but_never_completed_or_pruned() { + let tools = [json!({"name":"todo","parameters":{"properties":{"todos":{"type":"array"},"note":{"type":"string"},"any":{"type":["string","array"]}}}})]; + let read = |value: &str, parameter: &str| { + let text = format!("\n{value}\n"); + let parsed = parse_with(&text, &tools, Options::default()).unwrap(); + let repaired = parsed.notes.repaired_arguments; + (calls_of(parsed.segments).remove(0).1[parameter].clone(), repaired) + }; + for (value, want) in [ + ("[{'a': 1, 'b': True},]", json!([{"a": 1, "b": true}])), + ("[1,, 2,]", json!([1, 2])), + ("[{\"a\": None}]]", json!([{"a": null}])), + ("\"[{\\\"a\\\": 1}]\"", json!([{"a": 1}])), + ("\"[1, 2,]\"", json!([1, 2])), + ] { + assert_eq!(read(value, "todos"), (want, 1), "{value}"); + } + // valid JSON is not a repair + assert_eq!(read("[1, 2]", "todos"), (json!([1, 2]), 0)); + // not repaired, still the text the model wrote: brackets left open, a bare string, a missing colon, an unknown word + for value in ["[{\"a\": 1},", "[{\"a\": 1, \"b\"}]", "[{\"a\" 1}]", "[nope]", "[\"unterminated]"] { + assert_eq!(read(value, "todos"), (json!(value), 0), "{value}"); + } + // string parameters and unions with a string are untouched + assert_eq!(read("[1, 2,]", "note"), (json!("[1, 2,]"), 0)); + assert_eq!(read("[1, 2,]", "any"), (json!("[1, 2,]"), 0)); + } + + #[test] + fn calls_the_reasoning_ends_on_are_calls_and_calls_it_quotes_are_not() { + let tools = [json!({"name":"read","parameters":{"properties":{"path":{"type":"string"}}}})]; + let call = "\n\n\na.txt\n\n\n"; + let at = |text: &str| calls_at_end(text, &tools); + assert_eq!(at(&format!("Plan.\n\n{call}")), Some(7)); + assert_eq!(at(&format!("{call}\n{call}")), Some(0)); + // the call is not the last thing, is in a fence or in inline code, is mid-line, or names an undeclared tool + assert_eq!(at(&format!("{call}\nthen more thinking")), None); + assert_eq!(at(&format!("```\n{call}\n```")), None); + assert_eq!(at(&format!("a `quote {call}")), None); + assert_eq!(at(&format!("so I write {call}")), None); + assert_eq!(at(&call.replace("read", "format_disk")), None); + // a quoted call earlier does not hide the real one at the end + let after_quote = format!("```\n{call}\n```\nNow for real:\n{call}"); + assert_eq!(at(&after_quote), Some(after_quote.len() - call.len())); + } + #[test] fn parses_typed_values_and_preserves_text_around_calls() { let tools = [ diff --git a/control-plane/tests/tool_corpus.rs b/control-plane/tests/tool_corpus.rs index 9df3d634..257e47ac 100644 --- a/control-plane/tests/tool_corpus.rs +++ b/control-plane/tests/tool_corpus.rs @@ -13,7 +13,7 @@ use serde_json::{Value, json}; use std::collections::BTreeMap; -use strata_control::tool_output::{Incremental, Segment, parse_complete}; +use strata_control::tool_output::{Incremental, Options, Segment, calls_at_end, parse_complete, parse_with}; struct Specimen { name: String, @@ -69,7 +69,7 @@ struct Seen { reasoning: String, } -/// What `responses.rs::decode_generation` does with the bytes of a reasoning request (kept in step with it by hand). +/// What `responses.rs::decode_generation_with` does with the bytes of a reasoning request (kept in step with it by hand). fn split_reasoning(spec: &Specimen) -> Result<(String, String), String> { if !spec.thinking { return Ok((String::new(), spec.text.clone())); @@ -82,7 +82,10 @@ fn split_reasoning(spec: &Specimen) -> Result<(String, String), String> { .to_owned(), )), None if spec.length => Ok((spec.text.clone(), String::new())), - None => Err("reasoning ended without ".into()), + None => match calls_at_end(&spec.text, &spec.tools) { + Some(at) => Ok((spec.text[..at].to_owned(), spec.text[at..].to_owned())), + None => Err("reasoning ended without ".into()), + }, } } @@ -104,7 +107,8 @@ fn seen(reasoning: String, segments: Vec) -> Seen { fn whole(spec: &Specimen) -> Result { let (reasoning, answer) = split_reasoning(spec)?; - Ok(seen(reasoning, parse_complete(&answer, &spec.tools)?)) + let options = Options { natural_stop: !spec.length }; + Ok(seen(reasoning, parse_with(&answer, &spec.tools, options)?.segments)) } fn streamed(spec: &Specimen, cuts: &[usize]) -> Result { @@ -115,7 +119,7 @@ fn streamed(spec: &Specimen, cuts: &[usize]) -> Result { segments.extend(parser.feed(&spec.text[from..to])?); from = to; } - segments.extend(parser.finish()?); + segments.extend(parser.finish_after(!spec.length)?); Ok(seen(String::new(), segments)) } @@ -185,23 +189,12 @@ fn verdict(spec: &Specimen) -> Option { /// Specimens this parser does not read as upstream does. Keep `docs/tool-call-corpus.md` in step. const KNOWN_FAILURES: &[&str] = &[ "4427-todos-stray-items", - "4427-todos-single-quotes", "4427-todos-trailing-comma-and-open-bracket", "4078-reopened-parameter", - "4427-todos-json-string-of-an-array", - "4427-one-line-in-thinking", "4077-stray-think-line", "4077-stray-think-in-a-fence", "4077-stray-think-after-a-backtick", "4077-quoted-think-stays-reasoning", - "qwen-call-in-the-thinking", - "qwen-three-calls-in-the-thinking", - "qwen-function-close-left-out", - "qwen-function-close-left-out-in-thinking", - "qwen-wrapper-close-left-out", - "qwen-wrapper-close-left-out-in-thinking", - "qwen-wrapper-close-left-out-two-calls", - "qwen-wrapper-close-left-out-two-calls-in-thinking", "qwen-undeclared-name-is-text", "qwen-cut-inside-a-value", "qwen-cut-inside-the-opener", diff --git a/docs/api-contract.md b/docs/api-contract.md index 6ac4e678..c97d43f2 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -594,9 +594,10 @@ and tool streaming retain their incremental behavior. Disconnect during reasoning cancels the worker generation. The first Qwen `` marker separates reasoning from answer text, even -when split over tokens. A normal stop without that marker fails; a token-budget -stop while thinking returns an incomplete reasoning item and no invented final -answer. `usage.output_tokens_details.reasoning_tokens` counts original emitted +when split over tokens. A normal stop without that marker fails, unless the +text ends on whole tool calls of declared tools (see "Tool-call parsing"); a +token-budget stop while thinking returns an incomplete reasoning item and no +invented final answer. `usage.output_tokens_details.reasoning_tokens` counts original emitted tokens up to and including the closing-marker token; if one token straddles the boundary it is assigned to reasoning. Truncated thinking counts all its tokens. EOS tokens remain in total output usage, not reasoning usage. @@ -828,10 +829,59 @@ and the stream ends with `response.failed`. Forced choice rejects a wrong first call before publishing it; required choice with zero calls fails at completion. Under none, no callable item is published. Earlier valid text/calls cannot be retracted. Reasoning/structured -paths keep their existing buffering behavior. The runtime does not truncate, -repair or retry tool calls; these policies do not implement constrained sampling +paths keep their existing buffering behavior. The runtime does not truncate +or retry tool calls and repairs them only as listed under "Tool-call parsing"; these policies do not implement constrained sampling or parallel GPU requests. +## Tool-call parsing + +The Qwen model writes a call as ``, ``, one `` ... `` per argument, +``, ``. `control-plane/src/tool_output.rs` reads it; a call is published only after it is whole, and an +argument value is the exact text between its tags. The specimens that pin this are listed in +[tool-call-corpus.md](tool-call-corpus.md). This section is what a client can observe. + +**Quoted calls inside a string argument stay inside it.** A `write` whose `content` documents or tests the call format +(a quoted whole call, a heredoc that prints one) is delivered with its `content` exact, in a streamed and a buffered response +alike. Before this change the argument was cut at the first quoted close and the rest +was published as plain text without an error. A value ends at the first `` that is followed by the next +`` and that does not belong to a call the value itself quotes (the quoted `` +openers before it, each followed by ``, must not outnumber the `` closers before it). +A call whose value opens a quoted call and never closes it is treated as unterminated, and is an error, not cut at the first +plausible close. Known limits: a value that quotes only the tail of a call (`` with no opener) still ends there; and a +value that reopens its own parameter (`` inside `content`) is still a parameter written twice, +which is refused as `duplicate tool parameter` and not merged into one argument. + +**Accepted although a delimiter is missing.** Each of these used to fail the response (`response.failed` or 502 +`tool_call_parse_failed`) and is now a call. Each is logged on the server's stderr as +`tool call accepted beyond the template form (closers supplied: N, arguments repaired: M)`; nothing else changes in the response. + +* `` left out: `` followed by `` ends the value and the call, but only when no `` + followed by `` ends the value (so a value that quotes `` and has a real + close later is read whole). A streamed response delivers such a call when the generation ends, not when its `` + arrives, because only the end of the generation can tell the two readings apart. +* `` left out: the call is whole when the next `` follows its ``, or when its + `` is the end of a generation that stopped by itself (finish `stop`). A generation cut by the token limit (finish + `length`) never gets this; it stays an error. +* A call inside the reasoning: a generation that stops by itself without `` and whose text ends on whole calls of declared + tools is read as reasoning followed by those calls, when the first call stands at the start of a line outside a code fence and + outside inline code and nothing but whitespace or further calls follows. The reasoning item is the text before the calls + and is `completed`. The calls' text has already been streamed as `response.reasoning_text.delta` (a stream cannot take it + back), so the deltas of that response contain the call markup that the final reasoning item and its `done` events do not. Without + such calls the old failure (`reasoning ended without `) stands; so does a `` that follows the calls. +* A slightly damaged array or object argument: for a parameter declared `array` or `object` (and not a union with `string`), + a trailing or doubled comma, single quotes, Python's `True`/`False`/`None`, extra closing brackets at the end, and an + array or object written as a JSON string of itself are read as written. Nothing is invented or dropped: brackets left open, + a bare string where a member belongs, a missing colon, an unknown word and a string cut short are not repaired and are + delivered as before (a string, which the argument schema then rejects). String parameters are never touched. + +**Not accepted (unchanged): a call for an undeclared tool** is an error, `undeclared function in tool call: NAME`, as a failed +response; it is never run and never published as text. Upstream Strata returns it as plain text and counts it. The choice here +is deliberate: text without a call ends an agent's turn as if it were the answer, while a failed response is retried by the client +(a recorded session survived one such failure that way, `docs/e2e-run.md`). The exception stays that an undeclared `apply_patch` is +run through the declared shell tool. Also unchanged: a call cut by the token limit, a duplicate parameter, prose that names the +`` tag, and a call that quotes a code fence are not recovered (they stay failures or are read as before); see the table in +[tool-call-corpus.md](tool-call-corpus.md). + ## Active generation deadline An operator can opt into `engine.generation_timeout_s` / diff --git a/docs/tool-call-corpus.md b/docs/tool-call-corpus.md index 7516d6da..81a5bf30 100644 --- a/docs/tool-call-corpus.md +++ b/docs/tool-call-corpus.md @@ -30,67 +30,68 @@ Origin of the question: upstream issue #4078 (a string argument that quotes a to | --- | --- | | main (before) | 11 | | after 2 | 13 | +| after 3 | 24 | ## Specimens `ok`: the calls, the answer text and the reasoning text are what upstream expects, whole and in every streamed cut. A reason is the first difference found at the final stage shown. `recover` marks specimens upstream reads only with `tool_call_recovery` on. -| specimen | what it is | recover | main (before) | after 2 | first difference at the last stage | -| --- | --- | --- | --- | --- | --- | -| `4427-todos-valid` | #4427 first example (the Harness todo_write call) | | ok | ok | | -| `4427-todos-stray-items` | #4427 second example: `"status": "pending", "in_progress", "pending": false` | | FAIL | FAIL | whole: calls: got todo_write want todo_write | -| `4427-todos-single-quotes` | #4427 shape: Python quotes | | FAIL | FAIL | whole: calls: got todo_write want todo_write | -| `4427-todos-trailing-comma-and-open-bracket` | #4427 shape: a cut array | | FAIL | FAIL | whole: calls: got todo_write want todo_write | -| `4427-todos-json-string-of-an-array` | #4427 shape: the array written as a JSON string | | FAIL | FAIL | whole: calls: got todo_write want todo_write | -| `4427-todos-not-json-stays-text` | #4427: text that is no array stays the text it is | | ok | ok | | -| `4427-one-line` | #4427: the tags on one line | | ok | ok | | -| `4427-one-line-in-thinking` | #4427: written inside the thinking, the turn ends on it | | FAIL | FAIL | whole: error: reasoning ended without | -| `4078-nested-call` | #4078: a value holding a whole call | | FAIL | ok | | -| `4078-reopened-parameter` | #4078: a value that reopens its own parameter | | FAIL | FAIL | whole: error: duplicate tool parameter: content | -| `4078-heredoc` | #4078: a heredoc that prints a quoted call | | FAIL | ok | | -| `4078-call-format-in-a-file` | #210: a file that documents the format | | ok | ok | | -| `4077-stray-think-line` | #4077: the model quoted the closing tag at a line start | | FAIL | FAIL | whole: content differs | -| `4077-stray-think-in-a-fence` | #4077: the quote sat in a code fence, so the fence closes in the 'answer' | | FAIL | FAIL | whole: content differs | -| `4077-stray-think-after-a-backtick` | #4077: an open backtick | | FAIL | FAIL | whole: content differs | -| `4077-quoted-think-stays-reasoning` | #537: a closing tag after a backtick is still reasoning (control) | | FAIL | FAIL | whole: content differs | -| `4077-closer-in-the-answer-text-is-kept-mid-line` | a closing tag inside a sentence of the answer is text (control) | | ok | ok | | -| `4077-no-second-closer-is-the-normal-case` | control | | ok | ok | | -| `qwen-one-call` | the template's own form | | ok | ok | | -| `qwen-int-argument` | a declared integer | | ok | ok | | -| `qwen-after-thinking` | the normal agent turn | | ok | ok | | -| `qwen-call-in-the-thinking` | #804: the turn ends inside the thinking, on the call | | FAIL | FAIL | whole: error: reasoning ended without | -| `qwen-three-calls` | parallel calls, one wrapper each | | ok | ok | | -| `qwen-calls-with-prose-between` | prose between calls | | ok | ok | | -| `qwen-three-calls-in-the-thinking` | #804: two calls at the end of the thinking | | FAIL | FAIL | whole: error: reasoning ended without | -| `qwen-function-close-left-out` | #4427 shape: no (PR #3960's Coder-L slip) | | FAIL | FAIL | whole: error: tool parameter is incomplete | -| `qwen-function-close-left-out-in-thinking` | the same inside the thinking | | FAIL | FAIL | whole: error: reasoning ended without | -| `qwen-wrapper-close-left-out` | the output ends on (the server always streams) | | FAIL | FAIL | whole: error: tool call is missing | -| `qwen-wrapper-close-left-out-in-thinking` | the same inside the thinking | | FAIL | FAIL | whole: error: reasoning ended without | -| `qwen-wrapper-close-left-out-two-calls` | a following opener confirms the missing closer | | FAIL | FAIL | whole: error: tool call is missing | -| `qwen-wrapper-close-left-out-two-calls-in-thinking` | the same inside the thinking | | FAIL | FAIL | whole: error: reasoning ended without | -| `qwen-undeclared-name-is-text` | by design: a call for a tool the request did not declare comes back as text (and is counted) | | FAIL | FAIL | whole: error: undeclared function in tool call: format_disk | -| `qwen-cut-inside-a-value` | an unterminated tag: the output stopped at the token limit; no call | | FAIL | FAIL | whole: error: tool parameter is incomplete | -| `qwen-cut-inside-the-opener` | cut inside the name | | FAIL | FAIL | whole: error: tool call function name is incomplete | -| `qwen-cut-after-function-close-on-length` | a turn cut by the token limit is not a natural stop: no call | | FAIL | FAIL | whole: error: tool call is missing | -| `qwen-quoted-in-a-fence` | #1058: a call in a code fence is a quote | | FAIL | FAIL | whole: calls: got read want | -| `qwen-prose-names-the-format` | prose that names the tag | | FAIL | FAIL | whole: error: tool call needs | -| `drift-parameter-as-opener` | corpus 300dfba2 (x11) | yes | FAIL | FAIL | whole: error: tool call needs | -| `drift-json-in-the-wrapper` | corpus 5e847539 (x6) | yes | FAIL | FAIL | whole: error: tool call needs | -| `drift-bare-function` | corpus 395efd4c / 6e71eed4 (x5 each) | yes | FAIL | FAIL | whole: calls: got want write | -| `drift-batch-in-one-wrapper` | corpus 0912870b / 51b155c9 | yes | FAIL | FAIL | whole: error: tool call is missing | +| specimen | what it is | recover | main (before) | after 2 | after 3 | first difference at the last stage | +| --- | --- | --- | --- | --- | --- | --- | +| `4427-todos-valid` | #4427 first example (the Harness todo_write call) | | ok | ok | ok | | +| `4427-todos-stray-items` | #4427 second example: `"status": "pending", "in_progress", "pending": false` | | FAIL | FAIL | FAIL | whole: calls: got todo_write want todo_write | +| `4427-todos-single-quotes` | #4427 shape: Python quotes | | FAIL | FAIL | ok | | +| `4427-todos-trailing-comma-and-open-bracket` | #4427 shape: a cut array | | FAIL | FAIL | FAIL | whole: calls: got todo_write want todo_write | +| `4427-todos-json-string-of-an-array` | #4427 shape: the array written as a JSON string | | FAIL | FAIL | ok | | +| `4427-todos-not-json-stays-text` | #4427: text that is no array stays the text it is | | ok | ok | ok | | +| `4427-one-line` | #4427: the tags on one line | | ok | ok | ok | | +| `4427-one-line-in-thinking` | #4427: written inside the thinking, the turn ends on it | | FAIL | FAIL | ok | | +| `4078-nested-call` | #4078: a value holding a whole call | | FAIL | ok | ok | | +| `4078-reopened-parameter` | #4078: a value that reopens its own parameter | | FAIL | FAIL | FAIL | whole: error: duplicate tool parameter: content | +| `4078-heredoc` | #4078: a heredoc that prints a quoted call | | FAIL | ok | ok | | +| `4078-call-format-in-a-file` | #210: a file that documents the format | | ok | ok | ok | | +| `4077-stray-think-line` | #4077: the model quoted the closing tag at a line start | | FAIL | FAIL | FAIL | whole: content differs | +| `4077-stray-think-in-a-fence` | #4077: the quote sat in a code fence, so the fence closes in the 'answer' | | FAIL | FAIL | FAIL | whole: content differs | +| `4077-stray-think-after-a-backtick` | #4077: an open backtick | | FAIL | FAIL | FAIL | whole: content differs | +| `4077-quoted-think-stays-reasoning` | #537: a closing tag after a backtick is still reasoning (control) | | FAIL | FAIL | FAIL | whole: content differs | +| `4077-closer-in-the-answer-text-is-kept-mid-line` | a closing tag inside a sentence of the answer is text (control) | | ok | ok | ok | | +| `4077-no-second-closer-is-the-normal-case` | control | | ok | ok | ok | | +| `qwen-one-call` | the template's own form | | ok | ok | ok | | +| `qwen-int-argument` | a declared integer | | ok | ok | ok | | +| `qwen-after-thinking` | the normal agent turn | | ok | ok | ok | | +| `qwen-call-in-the-thinking` | #804: the turn ends inside the thinking, on the call | | FAIL | FAIL | ok | | +| `qwen-three-calls` | parallel calls, one wrapper each | | ok | ok | ok | | +| `qwen-calls-with-prose-between` | prose between calls | | ok | ok | ok | | +| `qwen-three-calls-in-the-thinking` | #804: two calls at the end of the thinking | | FAIL | FAIL | ok | | +| `qwen-function-close-left-out` | #4427 shape: no (PR #3960's Coder-L slip) | | FAIL | FAIL | ok | | +| `qwen-function-close-left-out-in-thinking` | the same inside the thinking | | FAIL | FAIL | ok | | +| `qwen-wrapper-close-left-out` | the output ends on (the server always streams) | | FAIL | FAIL | ok | | +| `qwen-wrapper-close-left-out-in-thinking` | the same inside the thinking | | FAIL | FAIL | ok | | +| `qwen-wrapper-close-left-out-two-calls` | a following opener confirms the missing closer | | FAIL | FAIL | ok | | +| `qwen-wrapper-close-left-out-two-calls-in-thinking` | the same inside the thinking | | FAIL | FAIL | ok | | +| `qwen-undeclared-name-is-text` | by design: a call for a tool the request did not declare comes back as text (and is counted) | | FAIL | FAIL | FAIL | whole: error: undeclared function in tool call: format_disk | +| `qwen-cut-inside-a-value` | an unterminated tag: the output stopped at the token limit; no call | | FAIL | FAIL | FAIL | whole: error: tool parameter is incomplete | +| `qwen-cut-inside-the-opener` | cut inside the name | | FAIL | FAIL | FAIL | whole: error: tool call function name is incomplete | +| `qwen-cut-after-function-close-on-length` | a turn cut by the token limit is not a natural stop: no call | | FAIL | FAIL | FAIL | whole: error: tool call is missing | +| `qwen-quoted-in-a-fence` | #1058: a call in a code fence is a quote | | FAIL | FAIL | FAIL | whole: calls: got read want | +| `qwen-prose-names-the-format` | prose that names the tag | | FAIL | FAIL | FAIL | whole: error: tool call needs | +| `drift-parameter-as-opener` | corpus 300dfba2 (x11) | yes | FAIL | FAIL | FAIL | whole: error: tool call needs | +| `drift-json-in-the-wrapper` | corpus 5e847539 (x6) | yes | FAIL | FAIL | FAIL | whole: error: tool call needs | +| `drift-bare-function` | corpus 395efd4c / 6e71eed4 (x5 each) | yes | FAIL | FAIL | FAIL | whole: calls: got want write | +| `drift-batch-in-one-wrapper` | corpus 0912870b / 51b155c9 | yes | FAIL | FAIL | FAIL | whole: error: tool call is missing | ## Quoted-call value shapes (`serve/test_quoted_call_values.py`) Six string-argument shapes, each read whole and streamed in pieces of 1, 7 and everything; the argument must come back exact and no text may leak. -| shape | main (before) | after 2 | -| --- | --- | --- | -| quoted call | FAIL | ok | -| quoted call at the end | FAIL | ok | -| heredoc | FAIL | ok | -| repeated parameter | FAIL | FAIL | -| unclosed opener in prose | ok | ok | -| unclosed opener in code | ok | ok | +| shape | main (before) | after 2 | after 3 | +| --- | --- | --- | --- | +| quoted call | FAIL | ok | ok | +| quoted call at the end | FAIL | ok | ok | +| heredoc | FAIL | ok | ok | +| repeated parameter | FAIL | FAIL | FAIL | +| unclosed opener in prose | ok | ok | ok | +| unclosed opener in code | ok | ok | ok | ## What each stage changed @@ -106,3 +107,20 @@ Six string-argument shapes, each read whole and streamed in pieces of 1, 7 and e written twice, which `native_tools_sdet::unknown_incomplete_duplicate_or_late_invalid_call_refuses_entire_output` requires to be refused; reading it as one value would merge two arguments of a malformed call into a corrupt one without an error. It stays an error (`duplicate tool parameter`). +* **after 3 (recoverable cases).** A call whose `` was left out (`` then ``), whose `` + was left out (next call's opener, or the end of a generation that stopped by itself), a call the reasoning ends on instead of + ``, and a damaged array argument (trailing or doubled comma, single quotes, Python literals, extra closers, an array in a + JSON string) are now calls; each is logged. See `docs/api-contract.md`, "Tool-call parsing", for what a client sees. + +## Specimens that stay unread, and why + +| specimen(s) | why this parser reads them differently | +| --- | --- | +| `qwen-undeclared-name-is-text` | Deliberate. A call for an undeclared tool is an error (failed response), never text and never a call. Upstream returns the markup as text and counts it; text ends an agent's turn as if it were the answer, a failed response is retried. Pinned by `an_invalid_tool_call_never_becomes_a_successful_function_call` and `other_undeclared_functions_still_fail`. | +| `4078-reopened-parameter` (and the `repeated parameter` value shape) | Deliberate. `` inside a `content` value is the same bytes as a parameter written twice. `native_tools_sdet::unknown_incomplete_duplicate_or_late_invalid_call_refuses_entire_output` requires that to be refused, and merging the two into one argument would hide a malformed call. It stays an error (`duplicate tool parameter`); upstream reads it as text. | +| `qwen-cut-inside-a-value`, `qwen-cut-inside-the-opener`, `qwen-cut-after-function-close-on-length` | A generation cut by the token limit inside a call is an error here (`generation ended inside a tool call`), where upstream returns the text with an incomplete status. Never a published call, so nothing is run. Pinned by `unfinished_live_tool_call_fails_without_publishing_arguments`; changing it is a separate decision. | +| `4427-todos-stray-items`, `4427-todos-trailing-comma-and-open-bracket` | The repairs that drop a bare string from an object or close brackets the model left open decide what the model meant, so they are not on by default; with `tool_call_recovery` on they are read (step 4). | +| `4077-stray-think-line`, `-in-a-fence`, `-after-a-backtick`, `4077-quoted-think-stays-reasoning` | Not a tool-call matter: the reasoning ends at the first literal ``, even one the model quoted in backticks or wrote twice. A second `` stays in the answer text. Unchanged; a reasoning-boundary decision. | +| `qwen-quoted-in-a-fence` | A call written inside a Markdown code fence of the answer is run. Upstream treats it as a quote. Not changed here: it alters which well-formed calls run. Worth a decision. | +| `qwen-prose-names-the-format` | `` followed by something other than `