okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

waveringanaserve tests: bring back the DeepSeek V4.1 cases upstream cut with the enginecded60248

main
21.5 KiB288 linesraw
1"""A corpus of model outputs for the tool-call and reasoning parser (#4427, #4078, #4077).
2
3Each specimen is the text a model wrote, the tools the request declared, and what a client must get: the calls (name and
4arguments), the answer text, the reasoning text.  The sources are named in each entry: the reporters' own examples in
5the issues, the Qwen3.8-Flash-Next form (`<tool_call><function=NAME><parameter=P>`), the drift shapes of the 1,462-turn
6corpus the recovery switch was written for, and DeepSeek-V4.1's DSML form.
7
8Every specimen is read whole, one byte at a time, in pieces of 3 and 7 bytes, and cut in two at every byte; with
9streaming of the arguments on and off.  All of them must give the same events, and the streamed arguments of a call
10must be its final arguments.
11
12    python -m unittest serve.test_tool_corpus -v
13"""
14from __future__ import annotations
15
16import json
17import sys
18import unittest
19from pathlib import Path
20
21sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
22from serve.dsml import DsmlOutputParser  # noqa: E402
23from serve.frontend import OutputParser  # noqa: E402
24
25
26def tool(name, **props):
27    return {"name": name, "parameters": {"type": "object", "properties": props}}
28
29
30S, I, A, O = {"type": "string"}, {"type": "integer"}, {"type": "array"}, {"type": "object"}
31TOOLS = [tool("todo_write", todos=A), tool("run_command", command=S, timeout=I), tool("write_file", path=S, content=S),
32         tool("read", path=S), tool("bash", command=S), tool("edit", path=S, edits=A, options=O)]
33
34
35def qwen(name, **params):
36    """The call as Qwen3.8-Flash-Next writes it (the chat template's own form)."""
37    body = "".join(f"<parameter={k}>\n{v}\n</parameter>\n" for k, v in params.items())
38    return f"<tool_call>\n<function={name}>\n{body}</function>\n</tool_call>"
39
40
41def dsml(*calls):
42    """DeepSeek-V4.1's DSML block: calls are (name, [(parameter, value, is_string)])."""
43    out = ["<|DSML| calls>\n"]
44    for name, params in calls:
45        out.append(f'<|DSML| invoke name="{name}">\n')
46        for k, v, is_str in params:
47            out.append(f'<|DSML| parameter name="{k}" string="{str(is_str).lower()}">{v}</|DSML| parameter>\n')
48        out.append("</|DSML| invoke>\n")
49    return "".join(out) + "</|DSML| calls>"
50
51
52NESTED = qwen("read", path="nested.txt")
53HEREDOC = f"python3 - <<'PY'\ntext = '''{NESTED}'''\nprint('tail that must not be lost')\nPY"
54REOPEN = "first line\n</parameter>\n<parameter=content>\nlast line"
55TODO_OK = ('[{"content": "Generate lorem ipsum page texture atlas (PIL) + inspect", "status": "in_progress"}, '
56           '{"content": "Blender script: book geometry + materials", "status": "pending"}]')
57TODO_STRAY = ('[{"content": "Init git repo with LFS", "status": "in_progress", "pending": false, "completed": false}, '
58              '{"content": "Write Blender build script", "status": "pending", "in_progress", "pending": false, '
59              '"completed": false}]')
60TODO_STRAY_WANT = [{"content": "Init git repo with LFS", "status": "in_progress", "pending": False, "completed": False},
61                   {"content": "Write Blender build script", "status": "pending", "pending": False, "completed": False}]
62STRAY_VALUE = "reasoning sample:\n</think>\nanswer sample"
63
64# name: dict(text, calls, content, reasoning, thinking, recover, finish, tools, unread, notes, source)
65CORPUS = {}
66
67
68def add(name, text, calls=(), content="", reasoning="", thinking=False, recover=False, finish="stop", tools=None,
69        unread=0, notes=0, source="", parser="qwen", stream_only=False, announced=False):
70    assert name not in CORPUS, name
71    CORPUS[name] = dict(text=text, calls=[tuple(c) for c in calls], content=content, reasoning=reasoning,
72                        thinking=thinking, recover=recover, finish=finish, tools=tools or TOOLS, unread=unread,
73                        notes=notes, source=source, parser=parser, stream_only=stream_only, announced=announced)
74
75
76# ---- the reporters' examples ------------------------------------------------------------------------------------
77add("4427-todos-valid", qwen("todo_write", todos=TODO_OK), [("todo_write", {"todos": json.loads(TODO_OK)})],
78    source="#4427 FraYoshi, first example (the Harness todo_write call)")
79add("4427-todos-stray-items", "Old tree project files are present but the task is fresh.\n\n" + qwen("todo_write", todos=TODO_STRAY),
80    [("todo_write", {"todos": TODO_STRAY_WANT})], content="Old tree project files are present but the task is fresh.",
81    notes=1, source="#4427 FraYoshi, second example: `\"status\": \"pending\", \"in_progress\", \"pending\": false`")
82add("4427-todos-single-quotes", qwen("todo_write", todos="[{'content': 'a', 'status': 'pending'}]"),
83    [("todo_write", {"todos": [{"content": "a", "status": "pending"}]})], notes=1, source="#4427 shape: Python quotes")
84add("4427-todos-trailing-comma-and-open-bracket", qwen("todo_write", todos='[{"content": "a", "status": "pending"},'),
85    [("todo_write", {"todos": [{"content": "a", "status": "pending"}]})], notes=1, source="#4427 shape: a cut array")
86add("4427-todos-json-string-of-an-array", qwen("todo_write", todos=json.dumps(TODO_OK)),
87    [("todo_write", {"todos": json.loads(TODO_OK)})], source="#4427 shape: the array written as a JSON string")
88add("4427-todos-not-json-stays-text", qwen("todo_write", todos="buy milk"), [("todo_write", {"todos": "buy milk"})],
89    source="#4427: text that is no array stays the text it is")
90add("4427-one-line", "Let me run ls and read the images.\n\n<tool_call> <function=run_command> <parameter=command> "
91    "ls -la /home/user/imap-attachments/ 2>&1 | head -30 </parameter> </function> </tool_call>",
92    [("run_command", {"command": " ls -la /home/user/imap-attachments/ 2>&1 | head -30 "})],
93    content="Let me run ls and read the images.", source="#4427 miscdebris: the tags on one line")
94add("4427-one-line-in-thinking", "Let me run ls and read the images.\n\n<tool_call> <function=run_command> <parameter=command> "
95    "ls -la 2>&1 | head -30 </parameter> </function> </tool_call>", [("run_command", {"command": " ls -la 2>&1 | head -30 "})],
96    reasoning="Let me run ls and read the images.\n\n", thinking=True,
97    source="#4427 miscdebris: written inside the thinking, the turn ends on it")
98add("4078-nested-call", qwen("write_file", path="fixture.txt", content="first line\n" + NESTED + "\nlast line"),
99    [("write_file", {"path": "fixture.txt", "content": "first line\n" + NESTED + "\nlast line"})],
100    source="#4078 LispEngineer / ackalker: a value holding a whole call")
101add("4078-reopened-parameter", qwen("write_file", path="fixture.txt", content=REOPEN),
102    [("write_file", {"path": "fixture.txt", "content": REOPEN})], source="#4078: a value that reopens its own parameter")
103add("4078-heredoc", qwen("bash", command=HEREDOC), [("bash", {"command": HEREDOC})],
104    source="#4078 Tsury: a heredoc that prints a quoted call")
105add("4078-call-format-in-a-file", qwen("write_file", path="DOC.md", content="Close a call with </function> and then </tool_call>.\nlike this."),
106    [("write_file", {"path": "DOC.md", "content": "Close a call with </function> and then </tool_call>.\nlike this."})],
107    source="#210: a file that documents the format")
108CLOSE_DOC = ("# Tool calls\n\nThe closing tags, in order:\n\n</parameter>\n</function>\n</tool_call>\n\nNothing may follow the last one.")
109add("4701-closing-tags-in-a-file", "I will save the doc.\n\n" + qwen("write_file", path="TOOLS.md", content=CLOSE_DOC),
110    [("write_file", {"path": "TOOLS.md", "content": CLOSE_DOC})], content="I will save the doc.", source="#4701, #5040: streamed arguments too")
111add("4701-closing-tags-in-a-file-recover", qwen("write_file", path="TOOLS.md", content=CLOSE_DOC),
112    [("write_file", {"path": "TOOLS.md", "content": CLOSE_DOC})], recover=True, source="#4701, recover on")
113add("4701-text-after-a-whole-call", qwen("read", path="a.txt") + "\n\nThat is the read.", [("read", {"path": "a.txt"})],
114    content="That is the read.", source="#4701: with no later close, the first one is the end")
115add("4701-two-calls-with-text-between", qwen("read", path="a.txt") + "\n\nAnd the next:\n" + qwen("read", path="b.txt"),
116    [("read", {"path": "a.txt"}), ("read", {"path": "b.txt"})], content="And the next:", source="#4701: a later call is not a later close")
117add("4077-stray-think-line", "The user wants a file with a literal.\n" + STRAY_VALUE + "\nSo I write it.\n</think>\n\n" +
118    qwen("write_file", path="out.txt", content=STRAY_VALUE),
119    [("write_file", {"path": "out.txt", "content": STRAY_VALUE})], thinking=True,
120    reasoning="The user wants a file with a literal.\nreasoning sample:\n",
121    content="answer sample\nSo I write it.", source="#4077 Tsury: the model quoted the closing tag at a line start")
122add("4077-stray-think-in-a-fence", "Content:\n```\n" + STRAY_VALUE + "\n```\nNow call it.\n</think>\n\n" +
123    qwen("write_file", path="out.txt", content=STRAY_VALUE),
124    [("write_file", {"path": "out.txt", "content": STRAY_VALUE})], thinking=True,
125    reasoning="Content:\n```\nreasoning sample:\n", content="answer sample\n```\nNow call it.",
126    source="#4077: the quote sat in a code fence, so the fence closes in the 'answer'")
127add("4077-stray-think-after-a-backtick", "The text is `" + STRAY_VALUE + "`. Call it.\n</think>\n\n" +
128    qwen("write_file", path="out.txt", content=STRAY_VALUE),
129    [("write_file", {"path": "out.txt", "content": STRAY_VALUE})], thinking=True,
130    reasoning="The text is `reasoning sample:\n", content="answer sample`. Call it.", source="#4077: an open backtick")
131add("4077-quoted-think-stays-reasoning", "I will not write `</think>` yet, I keep thinking.\nDone thinking.\n</think>\n\nThe answer.",
132    thinking=True, reasoning="I will not write `</think>` yet, I keep thinking.\nDone thinking.\n", content="The answer.",
133    source="#537: a closing tag after a backtick is still reasoning (control)")
134add("4077-closer-in-the-answer-text-is-kept-mid-line", "Reasoning.\n</think>\n\nWrite </think> to end the thinking.",
135    thinking=True, reasoning="Reasoning.\n", content="Write </think> to end the thinking.",
136    source="a closing tag inside a sentence of the answer is text (control)")
137add("4077-no-second-closer-is-the-normal-case", "Reasoning.\n</think>\n\n" + qwen("read", path="a.txt"),
138    [("read", {"path": "a.txt"})], thinking=True, reasoning="Reasoning.\n", source="control")
139
140# ---- the Qwen3.8-Flash-Next form and its slips ------------------------------------------------------------------
141add("qwen-one-call", "I will read it.\n\n" + qwen("read", path="a.txt"), [("read", {"path": "a.txt"})],
142    content="I will read it.", source="the template's own form")
143add("qwen-int-argument", qwen("run_command", command="make -j8", timeout="30"),
144    [("run_command", {"command": "make -j8", "timeout": 30})], source="a declared integer")
145add("qwen-after-thinking", "Plan: read the file.\n</think>\n\n" + qwen("read", path="a.txt"), [("read", {"path": "a.txt"})],
146    thinking=True, reasoning="Plan: read the file.\n", source="the normal agent turn")
147add("qwen-call-in-the-thinking", "Plan: read the file.\n\n" + qwen("read", path="a.txt"), [("read", {"path": "a.txt"})],
148    thinking=True, reasoning="Plan: read the file.\n\n", source="#804: the turn ends inside the thinking, on the call")
149add("qwen-three-calls", "Reading all three.\n\n" + "\n".join(qwen("read", path=f"{n}.txt") for n in "abc"),
150    [("read", {"path": "a.txt"}), ("read", {"path": "b.txt"}), ("read", {"path": "c.txt"})], content="Reading all three.",
151    source="parallel calls, one wrapper each")
152add("qwen-calls-with-prose-between", qwen("read", path="a.txt") + "\nand now the other one:\n" + qwen("read", path="b.txt"),
153    [("read", {"path": "a.txt"}), ("read", {"path": "b.txt"})], content="and now the other one:", source="prose between calls")
154add("qwen-three-calls-in-the-thinking", "Plan.\n\n" + "\n".join(qwen("read", path=f"{n}.txt") for n in "ab"),
155    [("read", {"path": "a.txt"}), ("read", {"path": "b.txt"})], thinking=True, reasoning="Plan.\n\n\n",
156    source="#804: two calls at the end of the thinking")
157add("qwen-function-close-left-out", "<tool_call>\n<function=write_file>\n<parameter=path>\nout.txt\n</parameter>\n"
158    "<parameter=content>\nhello\n</parameter>\n</tool_call>", [("write_file", {"path": "out.txt", "content": "hello"})],
159    source="#4427 shape: no </function> (PR #3960's Coder-L slip)")
160add("qwen-function-close-left-out-in-thinking", "Writing.\n\n<tool_call>\n<function=write_file>\n<parameter=path>\nout.txt\n"
161    "</parameter>\n<parameter=content>\nhello\n</parameter>\n</tool_call>", [("write_file", {"path": "out.txt", "content": "hello"})],
162    thinking=True, reasoning="Writing.\n\n", source="the same inside the thinking")
163add("qwen-wrapper-close-left-out", "<tool_call>\n<function=read>\n<parameter=path>\na.txt\n</parameter>\n</function>",
164    [("read", {"path": "a.txt"})], stream_only=True, source="the output ends on </function> (the server always streams)")
165add("qwen-wrapper-close-left-out-in-thinking", "Plan.\n\n<tool_call>\n<function=read>\n<parameter=path>\na.txt\n</parameter>\n</function>",
166    [("read", {"path": "a.txt"})], thinking=True, reasoning="Plan.\n\n", source="the same inside the thinking")
167add("qwen-wrapper-close-left-out-two-calls", qwen("read", path="a.txt").replace("\n</tool_call>", "") + "\n" + qwen("read", path="b.txt"),
168    [("read", {"path": "a.txt"}), ("read", {"path": "b.txt"})], source="a following opener confirms the missing closer")
169add("qwen-wrapper-close-left-out-two-calls-in-thinking", "Plan.\n\n" + qwen("read", path="a.txt").replace("\n</tool_call>", "") +
170    "\n" + qwen("read", path="b.txt"), [("read", {"path": "a.txt"}), ("read", {"path": "b.txt"})], thinking=True,
171    reasoning="Plan.\n\n\n", source="the same inside the thinking")
172add("qwen-undeclared-name-is-text", qwen("format_disk", target="/"), content=qwen("format_disk", target="/"), unread=1,
173    source="by design: a call for a tool the request did not declare comes back as text (and is counted)")
174add("qwen-cut-inside-a-value", "<tool_call>\n<function=write_file>\n<parameter=path>\nout.txt\n</parameter>\n<parameter=content>\nhal",
175    content="<tool_call>\n<function=write_file>\n<parameter=path>\nout.txt\n</parameter>\n<parameter=content>\nhal",
176    finish="length", announced=True, source="an unterminated tag: the output stopped at the token limit; no call")
177add("qwen-cut-inside-the-opener", "Now.\n\n<tool_call>\n<function=writ", content="Now.\n\n<tool_call>\n<function=writ",
178    finish="length", source="cut inside the name")
179add("qwen-cut-after-function-close-on-length", "<tool_call>\n<function=read>\n<parameter=path>\na.txt\n</parameter>\n</function>",
180    finish="length", content="<tool_call>\n<function=read>\n<parameter=path>\na.txt\n</parameter>\n</function>",
181    source="a turn cut by the token limit is not a natural stop: no call")
182add("qwen-quoted-in-a-fence", "Example:\n```\n" + qwen("read", path="a.txt") + "\n```", content="Example:\n```\n" + qwen("read", path="a.txt") + "\n```",
183    source="#1058: a call in a code fence is a quote")
184add("qwen-prose-names-the-format", "Calls are written as <tool_call> blocks.", content="Calls are written as <tool_call> blocks.",
185    source="prose that names the tag")
186
187# ---- the drift shapes (tool_call_recovery on; the corpus of 1,462 agent turns) ----------------------------------
188PW = "<parameter=path>\na.md\n</parameter>\n<parameter=content>\nhi\n</parameter>\n</function>"
189WRITE_TOOLS = [tool("write", path=S, content=S)]
190add("drift-parameter-as-opener", f"<tool_call>\n<parameter=write>\n{PW}\n</tool_call>", [("write", {"path": "a.md", "content": "hi"})],
191    recover=True, tools=WRITE_TOOLS, source="corpus 300dfba2 (x11)")
192add("drift-json-in-the-wrapper", '<tool_call>\n{"name": "write", "arguments": {"path": "a.md", "content": "hi"}}\n</tool_call>',
193    [("write", {"path": "a.md", "content": "hi"})], recover=True, tools=WRITE_TOOLS, source="corpus 5e847539 (x6)")
194add("drift-bare-function", f"Writing it now.\n\n<function=write>\n{PW}", [("write", {"path": "a.md", "content": "hi"})],
195    content="Writing it now.", recover=True, tools=WRITE_TOOLS, source="corpus 395efd4c / 6e71eed4 (x5 each)")
196add("drift-batch-in-one-wrapper", f"<tool_call>\n<function=write>\n{PW}\n<function=write>\n{PW.replace('a.md', 'b.md')}\n</tool_call>",
197    [("write", {"path": "a.md", "content": "hi"}), ("write", {"path": "b.md", "content": "hi"})], recover=True,
198    tools=WRITE_TOOLS, source="corpus 0912870b / 51b155c9")
199
200# ---- DeepSeek-V4.1 (DSML) ---------------------------------------------------------------------------------------
201add("dsml-one-call", dsml(("write_file", [("path", "out.txt", True), ("content", "hello\nworld", True)])),
202    [("write_file", {"path": "out.txt", "content": "hello\nworld"})], parser="dsml", source="the model's own template")
203add("dsml-after-thinking", "Plan.</think>\n\n" + dsml(("read", [("path", "a.txt", True)])), [("read", {"path": "a.txt"})],
204    thinking=True, reasoning="Plan.", parser="dsml", source="a thinking turn")
205add("dsml-typed-arguments", dsml(("run_command", [("command", "make", True), ("timeout", "30", False)]),
206                                 ("todo_write", [("todos", TODO_OK, False)])),
207    [("run_command", {"command": "make", "timeout": 30}), ("todo_write", {"todos": json.loads(TODO_OK)})], parser="dsml",
208    source="string=\"false\" values are JSON")
209add("dsml-damaged-array", dsml(("todo_write", [("todos", TODO_STRAY, False)])), [("todo_write", {"todos": TODO_STRAY_WANT})],
210    notes=1, parser="dsml", source="#4427 shape inside DSML")
211add("dsml-several-calls-and-text", "Reading both.\n\n" + dsml(("read", [("path", "a.txt", True)]), ("read", [("path", "b.txt", True)])),
212    [("read", {"path": "a.txt"}), ("read", {"path": "b.txt"})], content="Reading both.", parser="dsml", source="a batch")
213add("dsml-value-holds-a-qwen-call", dsml(("write_file", [("path", "x.txt", True), ("content", NESTED, True)])),
214    [("write_file", {"path": "x.txt", "content": NESTED})], parser="dsml", source="#4078 shape in DSML")
215add("dsml-stray-think", "Quote:\n</think>\nmore thinking.\n</think>\n\n" + dsml(("read", [("path", "a.txt", True)])),
216    [("read", {"path": "a.txt"})], thinking=True, reasoning="Quote:\n", content="more thinking.", parser="dsml",
217    source="#4077 shape in DSML")
218add("dsml-cut-call", dsml(("read", [("path", "a.txt", True)]))[:60], finish="length", content=None,
219    parser="dsml", source="a DSML call cut by the token limit is no call (its text is the translator's, not checked)")
220
221
222def run(spec, pieces, stream_tools):
223    cls = DsmlOutputParser if spec["parser"] == "dsml" else OutputParser
224    p = cls(thinking=spec["thinking"], tools=spec["tools"], stream_tools=stream_tools, recover=spec["recover"],
225            declared_only=True)
226    evs = []
227    for piece in pieces:
228        evs += p.feed(piece)
229    evs += p.finish(spec["finish"])
230    return evs, p
231
232
233def cut(text, size):
234    return [text[i:i + size] for i in range(0, len(text), size)]
235
236
237class ToolCorpus(unittest.TestCase):
238    def check(self, name, spec, pieces, stream_tools, label):
239        evs, p = run(spec, pieces, stream_tools)
240        calls = [(e.call.name, e.call.arguments) for e in evs if e.kind == "tool_call"]
241        text = lambda kind: "".join(e.text for e in evs if e.kind == kind)   # noqa: E731
242        where = f"{name} [{label}, stream_tools={stream_tools}]"
243        self.assertEqual(calls, spec["calls"], where)
244        # a call announced to the client and then cut stays unfinished there (#211): its text is not repeated as content
245        if spec["content"] is not None:
246            self.assertEqual(text("content").strip(), "" if spec["announced"] and stream_tools else spec["content"], where)
247        self.assertEqual(text("reasoning").strip(), spec["reasoning"].strip(), where)
248        self.assertEqual(p.unread, spec["unread"], where)
249        self.assertEqual(len(p.notes), spec["notes"], where)
250        if stream_tools:
251            for e in (x for x in evs if x.kind == "tool_call"):
252                streamed = "".join(x.text for x in evs if x.kind == "tool_args" and x.call is not None and x.call.id == e.call.id)
253                if streamed:
254                    self.assertEqual(json.loads(streamed), e.call.arguments, where)
255        return evs
256
257    def test_every_specimen_whole_and_in_pieces(self):
258        for name, spec in CORPUS.items():
259            for stream_tools in (True,) if spec["stream_only"] else (False, True):
260                self.check(name, spec, [spec["text"]], stream_tools, "whole")
261                for size in (1, 3, 7):
262                    self.check(name, spec, cut(spec["text"], size), stream_tools, f"pieces of {size}")
263
264    def test_every_specimen_cut_in_two_at_every_byte(self):
265        for name, spec in CORPUS.items():
266            text = spec["text"]
267            for at in range(1, len(text)):
268                self.check(name, spec, [text[:at], text[at:]], True, f"cut at {at}")
269
270    def test_the_same_events_whatever_the_pieces(self):
271        """Text and calls of a specimen do not depend on how the stream was cut (the ids aside)."""
272        for name, spec in CORPUS.items():
273            whole, _ = run(spec, [spec["text"]], True)
274            want = [(e.kind, e.text) for e in whole if e.kind in ("content", "reasoning")]
275            joined = lambda evs, k: "".join(t for kind, t in evs if kind == k)   # noqa: E731
276            for size in (1, 5):
277                got, _ = run(spec, cut(spec["text"], size), True)
278                got = [(e.kind, e.text) for e in got if e.kind in ("content", "reasoning")]
279                for kind in ("content", "reasoning"):
280                    self.assertEqual(joined(got, kind), joined(want, kind), f"{name} pieces of {size}")
281
282    def test_the_sources_are_named(self):
283        for name, spec in CORPUS.items():
284            self.assertTrue(spec["source"], name)
285
286
287if __name__ == "__main__":
288    unittest.main()