Adds Options::recovery to tool_output and an opt-in setting, `tool_call_recovery` (config key) / STRATA_TOOL_CALL_RECOVERY=1 (environment, wins over the file; 0/false turns it off; anything else stops the start). It is off unless set, is read once at start, logs "tool_call_recovery is ON (experimental)" at start, and logs every call it accepts. It is NOT part of the default contract and has not passed a quality gate (docs/api-contract.md, "Tool-call recovery (experimental)"). With it on, a call for a DECLARED tool written next to the template form is read as the call (upstream 3fcb2106, #3441): * <parameter=NAME> where <function=NAME> belongs; <=NAME>, <function:NAME>, <function =NAME> or <NAME> after <tool_call>; * {"name": ..., "arguments": {...}} inside <tool_call>, also in a Markdown fence, arguments possibly a JSON string; * a bare <function=NAME> ... </function> at the start of a line outside a code fence and inline code (a stray </tool_call> after it is dropped); the Markdown state is tracked over the text that has left the stream buffer, so streamed and whole readings agree; * a second call in the same <tool_call>; * for array/object arguments, brackets left open at the end and a bare string where an object member belongs (dropped). An undeclared name stays an error in every form. Streaming: a batch is delivered when its </tool_call> arrives, a bare call when the text after it shows it is over or at the end. With the option off the reading is byte for byte the step-3 reading. The corpus test now reads every specimen twice (off and on) and lists the failures of each; every streamed cut agrees with the whole reading in both. Recovery rate on the 41 Qwen specimens: off 24/41 (58.5 %), on 30/41 (73.2 %); the 6 specimens that need recovery: off 0/6, on 6/6. That is code reach on upstream's failure corpus, not a rate for real sessions. strata-control lib 339 passed (new: 3 recovery tests, 1 config test), corpus and the quoted-value shapes pass with the option on and off. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
430 lines
16 KiB
Rust
430 lines
16 KiB
Rust
//! The upstream tool-call corpus (49 specimens) and the quoted-call value shapes, run against `tool_output`.
|
|
//!
|
|
//! The specimens are a port of `serve/test_tool_corpus.py` and `serve/test_quoted_call_values.py` of the Strata upstream
|
|
//! (MIT licence, Copyright (c) 2026 Niko1221 and the Strata contributors; see `tests/fixtures/tool_corpus/NOTICE.md`).
|
|
//!
|
|
//! Each specimen is read whole (`parse_complete`, the path of every request that reasons) and, when the request does not
|
|
//! reason, streamed (`Incremental`, fed in pieces of 1, 3 and 7 characters and cut in two at every character boundary).
|
|
//! The outcome must be the same for every cut, and it is compared with what upstream expects a client to get.
|
|
//!
|
|
//! Every specimen is read twice: with the default options and with the experimental `tool_call_recovery` on (`Options::recovery`).
|
|
//! `KNOWN_FAILURES` lists the specimens this parser does not read as upstream does by default,
|
|
//! `KNOWN_FAILURES_WITH_RECOVERY` the ones it still does not read with recovery on. The test is strict both ways: a
|
|
//! specimen that fails and is not listed fails the test, and so does a listed specimen that now passes (remove it from the
|
|
//! list and update `docs/tool-call-corpus.md`). Set `TOOL_CORPUS_TABLE=1` and run with `--nocapture` to print the table.
|
|
|
|
use serde_json::{Value, json};
|
|
use strata_control::tool_output::{Incremental, Options, Segment, calls_at_end, parse_complete, parse_with};
|
|
|
|
struct Specimen {
|
|
name: String,
|
|
source: String,
|
|
parser: String,
|
|
text: String,
|
|
thinking: bool,
|
|
recover: bool,
|
|
length: bool,
|
|
tools: Vec<Value>,
|
|
calls: Vec<(String, Value)>,
|
|
content: Option<String>,
|
|
reasoning: String,
|
|
}
|
|
|
|
fn specimens() -> Vec<Specimen> {
|
|
let doc: Value =
|
|
serde_json::from_str(include_str!("fixtures/tool_corpus/specimens.json")).unwrap();
|
|
doc["specimens"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.map(|s| Specimen {
|
|
name: s["name"].as_str().unwrap().to_owned(),
|
|
source: s["source"].as_str().unwrap().to_owned(),
|
|
parser: s["parser"].as_str().unwrap().to_owned(),
|
|
text: s["text"].as_str().unwrap().to_owned(),
|
|
thinking: s["thinking"].as_bool().unwrap(),
|
|
recover: s["recover"].as_bool().unwrap(),
|
|
length: s["finish"] == "length",
|
|
tools: s["tools"].as_array().unwrap().clone(),
|
|
calls: s["calls"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.map(|c| {
|
|
(
|
|
c["name"].as_str().unwrap().to_owned(),
|
|
c["arguments"].clone(),
|
|
)
|
|
})
|
|
.collect(),
|
|
content: s["content"].as_str().map(str::to_owned),
|
|
reasoning: s["reasoning"].as_str().unwrap().to_owned(),
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
#[derive(Debug, PartialEq)]
|
|
struct Seen {
|
|
calls: Vec<(String, Value)>,
|
|
content: String,
|
|
reasoning: String,
|
|
}
|
|
|
|
/// 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, recovery: bool) -> Result<(String, String), String> {
|
|
if !spec.thinking {
|
|
return Ok((String::new(), spec.text.clone()));
|
|
}
|
|
match spec.text.find("</think>") {
|
|
Some(at) => Ok((
|
|
spec.text[..at].to_owned(),
|
|
spec.text[at + "</think>".len()..]
|
|
.trim_start_matches('\n')
|
|
.to_owned(),
|
|
)),
|
|
None if spec.length => Ok((spec.text.clone(), String::new())),
|
|
None => match calls_at_end(&spec.text, &spec.tools, Options { natural_stop: false, recovery }) {
|
|
Some(at) => Ok((spec.text[..at].to_owned(), spec.text[at..].to_owned())),
|
|
None => Err("reasoning ended without </think>".into()),
|
|
},
|
|
}
|
|
}
|
|
|
|
fn seen(reasoning: String, segments: Vec<Segment>) -> Seen {
|
|
let mut calls = Vec::new();
|
|
let mut content = String::new();
|
|
for segment in segments {
|
|
match segment {
|
|
Segment::Text(text) => content.push_str(&text),
|
|
Segment::Call { name, arguments } => calls.push((name, arguments)),
|
|
}
|
|
}
|
|
Seen {
|
|
calls,
|
|
content,
|
|
reasoning,
|
|
}
|
|
}
|
|
|
|
fn whole(spec: &Specimen, recovery: bool) -> Result<Seen, String> {
|
|
let (reasoning, answer) = split_reasoning(spec, recovery)?;
|
|
let options = Options { natural_stop: !spec.length, recovery };
|
|
Ok(seen(reasoning, parse_with(&answer, &spec.tools, options)?.segments))
|
|
}
|
|
|
|
fn streamed(spec: &Specimen, cuts: &[usize], recovery: bool) -> Result<Seen, String> {
|
|
let mut parser = Incremental::with_options(&spec.tools, Options { natural_stop: false, recovery });
|
|
let mut segments = Vec::new();
|
|
let mut from = 0;
|
|
for &to in cuts.iter().chain(std::iter::once(&spec.text.len())) {
|
|
segments.extend(parser.feed(&spec.text[from..to])?);
|
|
from = to;
|
|
}
|
|
segments.extend(parser.finish_after(!spec.length)?);
|
|
Ok(seen(String::new(), segments))
|
|
}
|
|
|
|
fn boundaries(text: &str) -> Vec<usize> {
|
|
text.char_indices().map(|(at, _)| at).skip(1).collect()
|
|
}
|
|
|
|
/// `None`: matches upstream's expectation. `Some(why)`: the first difference.
|
|
fn compare(spec: &Specimen, got: &Result<Seen, String>) -> Option<String> {
|
|
let got = match got {
|
|
Ok(got) => got,
|
|
Err(error) => return Some(format!("error: {error}")),
|
|
};
|
|
if got.calls != spec.calls {
|
|
return Some(format!(
|
|
"calls: got {} want {}",
|
|
got.calls
|
|
.iter()
|
|
.map(|c| c.0.as_str())
|
|
.collect::<Vec<_>>()
|
|
.join("+"),
|
|
spec.calls
|
|
.iter()
|
|
.map(|c| c.0.as_str())
|
|
.collect::<Vec<_>>()
|
|
.join("+")
|
|
));
|
|
}
|
|
if let Some(content) = &spec.content
|
|
&& got.content.trim() != content.trim()
|
|
{
|
|
return Some("content differs".into());
|
|
}
|
|
if spec.thinking && got.reasoning.trim() != spec.reasoning.trim() {
|
|
return Some("reasoning differs".into());
|
|
}
|
|
None
|
|
}
|
|
|
|
/// The first difference over every way of reading the specimen, or `None` when all of them match.
|
|
fn verdict(spec: &Specimen, recovery: bool) -> Option<String> {
|
|
if let Some(why) = compare(spec, &whole(spec, recovery)) {
|
|
return Some(format!("whole: {why}"));
|
|
}
|
|
if spec.thinking {
|
|
return None; // a reasoning request is never parsed incrementally
|
|
}
|
|
for size in [1usize, 3, 7] {
|
|
let cuts: Vec<usize> = boundaries(&spec.text)
|
|
.into_iter()
|
|
.enumerate()
|
|
.filter(|(index, _)| (index + 1) % size == 0)
|
|
.map(|(_, at)| at)
|
|
.collect();
|
|
if let Some(why) = compare(spec, &streamed(spec, &cuts, recovery)) {
|
|
return Some(format!("pieces of {size}: {why}"));
|
|
}
|
|
}
|
|
for at in boundaries(&spec.text) {
|
|
if let Some(why) = compare(spec, &streamed(spec, &[at], recovery)) {
|
|
return Some(format!("cut at {at}: {why}"));
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
/// 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-trailing-comma-and-open-bracket",
|
|
"4078-reopened-parameter",
|
|
"4077-stray-think-line",
|
|
"4077-stray-think-in-a-fence",
|
|
"4077-stray-think-after-a-backtick",
|
|
"4077-quoted-think-stays-reasoning",
|
|
"qwen-undeclared-name-is-text",
|
|
"qwen-cut-inside-a-value",
|
|
"qwen-cut-inside-the-opener",
|
|
"qwen-cut-after-function-close-on-length",
|
|
"qwen-quoted-in-a-fence",
|
|
"qwen-prose-names-the-format",
|
|
"drift-parameter-as-opener",
|
|
"drift-json-in-the-wrapper",
|
|
"drift-bare-function",
|
|
"drift-batch-in-one-wrapper",
|
|
];
|
|
|
|
/// Specimens this parser still does not read as upstream does with `tool_call_recovery` on.
|
|
const KNOWN_FAILURES_WITH_RECOVERY: &[&str] = &[
|
|
"4078-reopened-parameter",
|
|
"4077-stray-think-line",
|
|
"4077-stray-think-in-a-fence",
|
|
"4077-stray-think-after-a-backtick",
|
|
"4077-quoted-think-stays-reasoning",
|
|
"qwen-undeclared-name-is-text",
|
|
"qwen-cut-inside-a-value",
|
|
"qwen-cut-inside-the-opener",
|
|
"qwen-cut-after-function-close-on-length",
|
|
"qwen-quoted-in-a-fence",
|
|
"qwen-prose-names-the-format",
|
|
];
|
|
|
|
fn check_listed(
|
|
spec: &Specimen,
|
|
result: &Option<String>,
|
|
list: &[&str],
|
|
which: &str,
|
|
unexpected: &mut Vec<String>,
|
|
) {
|
|
let known = list.contains(&spec.name.as_str());
|
|
match (result, known) {
|
|
(Some(why), false) => unexpected.push(format!("{} fails ({which}): {why}", spec.name)),
|
|
(None, true) => unexpected.push(format!("{} passes ({which}) but is listed as a known failure", spec.name)),
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn every_qwen_specimen_is_read_as_listed() {
|
|
let table = std::env::var_os("TOOL_CORPUS_TABLE").is_some();
|
|
let mut unexpected = Vec::new();
|
|
let (mut passed_off, mut passed_on) = (0, 0);
|
|
for spec in specimens() {
|
|
if spec.parser != "qwen" {
|
|
continue; // DSML: no parser in this repository
|
|
}
|
|
let off = verdict(&spec, false);
|
|
let on = verdict(&spec, true);
|
|
if table {
|
|
println!(
|
|
"TABLE | {} | {} | recover={} | {} | {}",
|
|
spec.name,
|
|
spec.source,
|
|
spec.recover,
|
|
off.as_deref().unwrap_or("ok"),
|
|
on.as_deref().unwrap_or("ok")
|
|
);
|
|
}
|
|
passed_off += off.is_none() as usize;
|
|
passed_on += on.is_none() as usize;
|
|
check_listed(&spec, &off, KNOWN_FAILURES, "recovery off", &mut unexpected);
|
|
check_listed(&spec, &on, KNOWN_FAILURES_WITH_RECOVERY, "recovery on", &mut unexpected);
|
|
}
|
|
if table {
|
|
println!("TABLE passed: recovery off {passed_off}, recovery on {passed_on}");
|
|
}
|
|
assert!(unexpected.is_empty(), "{}", unexpected.join("\n"));
|
|
}
|
|
|
|
#[test]
|
|
fn the_corpus_is_the_ported_one() {
|
|
let all = specimens();
|
|
assert_eq!(all.len(), 49);
|
|
assert_eq!(all.iter().filter(|s| s.parser == "qwen").count(), 41);
|
|
assert!(all.iter().all(|s| !s.source.is_empty()));
|
|
}
|
|
|
|
// ---- serve/test_quoted_call_values.py -----------------------------------------------------------------------------
|
|
|
|
fn write_tool() -> Vec<Value> {
|
|
vec![
|
|
json!({"name":"write","parameters":{"properties":{"path":{"type":"string"},"content":{"type":"string"}}}}),
|
|
]
|
|
}
|
|
|
|
fn quoted() -> String {
|
|
"<tool_call>\n<function=write>\n<parameter=path>\nx.txt\n</parameter>\n</function>\n</tool_call>".to_owned()
|
|
}
|
|
|
|
fn quoted_values() -> Vec<(&'static str, String)> {
|
|
let q = quoted();
|
|
vec![
|
|
(
|
|
"quoted call",
|
|
format!("example transcript:\n{q}\nafter block"),
|
|
),
|
|
(
|
|
"quoted call at the end",
|
|
format!("example transcript:\n{q}"),
|
|
),
|
|
("heredoc", format!("python3 - <<'PY'\nprint('''{q}''')\nPY")),
|
|
(
|
|
"repeated parameter",
|
|
"head part\n</parameter>\n<parameter=content>\ntail part".to_owned(),
|
|
),
|
|
(
|
|
"unclosed opener in prose",
|
|
"A call starts with `<function=NAME>` and its parameters follow.".to_owned(),
|
|
),
|
|
(
|
|
"unclosed opener in code",
|
|
"opener = \"<function=\"\n".to_owned(),
|
|
),
|
|
]
|
|
}
|
|
|
|
fn call_text(value: &str) -> String {
|
|
format!(
|
|
"<tool_call>\n<function=write>\n<parameter=path>\nprobe.txt\n</parameter>\n<parameter=content>\n{value}\n</parameter>\n</function>\n</tool_call>"
|
|
)
|
|
}
|
|
|
|
fn only_call(segments: Vec<Segment>) -> Result<Value, String> {
|
|
let mut calls = segments.into_iter().filter_map(|s| match s {
|
|
Segment::Call { arguments, .. } => Some(arguments),
|
|
Segment::Text(text) if text.trim().is_empty() => None,
|
|
Segment::Text(text) => Some(json!({"unexpected text": text})),
|
|
});
|
|
let first = calls.next().ok_or("no call")?;
|
|
match calls.next() {
|
|
None => Ok(first),
|
|
Some(extra) => Err(format!("more than one segment: {extra}")),
|
|
}
|
|
}
|
|
|
|
/// Every value shape, whole and streamed in pieces of 1, 7 and everything: the argument is exact and no text leaks out.
|
|
fn quoted_value_failures(recovery: bool) -> Vec<(&'static str, String)> {
|
|
let tools = write_tool();
|
|
let mut failures = Vec::new();
|
|
for (label, value) in quoted_values() {
|
|
let text = call_text(&value);
|
|
let want = json!({"path":"probe.txt","content":value});
|
|
let options = Options { natural_stop: true, recovery };
|
|
match parse_with(&text, &tools, options)
|
|
.map(|parsed| parsed.segments)
|
|
.and_then(only_call)
|
|
{
|
|
Ok(got) if got == want => {}
|
|
Ok(got) => failures.push((label, format!("whole: got {got}"))),
|
|
Err(error) => failures.push((label, format!("whole: {error}"))),
|
|
}
|
|
let chars: Vec<(usize, char)> = text.char_indices().collect();
|
|
for size in [1usize, 7, chars.len()] {
|
|
let mut parser = Incremental::with_options(&tools, options);
|
|
let mut segments = Vec::new();
|
|
let mut failed = None;
|
|
for chunk in chars.chunks(size) {
|
|
let from = chunk[0].0;
|
|
let to = chunk.last().map_or(from, |(at, c)| at + c.len_utf8());
|
|
match parser.feed(&text[from..to]) {
|
|
Ok(out) => segments.extend(out),
|
|
Err(error) => failed = Some(error),
|
|
}
|
|
}
|
|
match parser.finish_after(true) {
|
|
Ok(out) => segments.extend(out),
|
|
Err(error) => failed = Some(error),
|
|
}
|
|
let got = match failed {
|
|
Some(error) => Err(error),
|
|
None => only_call(segments),
|
|
};
|
|
match got {
|
|
Ok(got) if got == want => {}
|
|
Ok(got) => failures.push((label, format!("streamed/{size}: got {got}"))),
|
|
Err(error) => failures.push((label, format!("streamed/{size}: {error}"))),
|
|
}
|
|
}
|
|
}
|
|
failures
|
|
}
|
|
|
|
/// Value shapes that are not yet read exactly (strict both ways, like `KNOWN_FAILURES`).
|
|
const KNOWN_QUOTED_FAILURES: &[&str] = &["repeated parameter"];
|
|
|
|
#[test]
|
|
fn quoted_call_values_stay_exact() {
|
|
for recovery in [false, true] {
|
|
let failures = quoted_value_failures(recovery);
|
|
if std::env::var_os("TOOL_CORPUS_TABLE").is_some() {
|
|
for (label, why) in &failures {
|
|
println!("QUOTED | {label} | {why} | recovery={recovery}");
|
|
}
|
|
}
|
|
let mut unexpected: Vec<String> = failures
|
|
.iter()
|
|
.filter(|(label, _)| !KNOWN_QUOTED_FAILURES.contains(label))
|
|
.map(|(label, why)| format!("{label} (recovery {recovery}): {why}"))
|
|
.collect();
|
|
for label in KNOWN_QUOTED_FAILURES {
|
|
if !failures.iter().any(|(failed, _)| failed == label) {
|
|
unexpected.push(format!("{label} passes (recovery {recovery}) but is listed as a known failure"));
|
|
}
|
|
}
|
|
assert!(unexpected.is_empty(), "{}", unexpected.join("\n"));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn prose_between_two_calls_still_ends_the_first() {
|
|
let tools = write_tool();
|
|
let text = format!(
|
|
"{}\nnow the second:\n{}",
|
|
call_text("one"),
|
|
call_text("two")
|
|
);
|
|
let segments = parse_complete(&text, &tools).unwrap();
|
|
let contents: Vec<&str> = segments
|
|
.iter()
|
|
.filter_map(|s| match s {
|
|
Segment::Call { arguments, .. } => arguments["content"].as_str(),
|
|
_ => None,
|
|
})
|
|
.collect();
|
|
assert_eq!(contents, ["one", "two"]);
|
|
}
|