okami.mom/strata

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

Niko1221Merge f-027-gh-eng: GitHub engine items for 0.2.76ca60e9a0

main
49.9 KiB795 linesraw
1"""serve/test_responses.py - #451: the Responses API (POST /v1/responses) against the mock engine (no GPU, no pack).
2
3    python -m unittest serve.test_responses -v
4"""
5from __future__ import annotations
6
7import base64
8import contextlib
9import http.client
10import io
11import json
12import sys
13import unittest
14from pathlib import Path
15
16sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
17from serve import responses  # noqa: E402
18from serve.frontend import ChatTemplate  # noqa: E402
19from serve.responses import (ENCRYPTED_PREFIX, ResponsesError, collect, input_messages, prompt_made,  # noqa: E402
20                             prompt_tools, request_tools, template_kwargs, text_format, thread_title_events)
21from serve.server import ByteTokenizer, MockEngine, Service, serve  # noqa: E402
22
23ROOT = Path(__file__).resolve().parents[1]
24TEMPLATE = ChatTemplate(ROOT / "serve/chat_template.jinja")
25
26CALL = ("Let me look.\n</think>\n\nChecking.\n\n<tool_call>\n<function=exec_command>\n<parameter=cmd>\ncat a.txt\n"
27        "</parameter>\n</function>\n</tool_call>")
28ANSWER = "Read it.\n</think>\n\nThe file says before."
29TOOLS = [{"type": "function", "name": "exec_command", "description": "Runs a command.", "strict": False,
30          "parameters": {"type": "object", "properties": {"cmd": {"type": "string"}}, "required": ["cmd"]}}]
31
32
33# ------------------------------------------------------------------------------------------------ parsing
34class Parsing(unittest.TestCase):
35    def test_a_string_input_is_one_user_message(self):
36        self.assertEqual(input_messages({"input": "hi", "instructions": "Be brief."}),
37                         [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "hi"}])
38
39    def test_leading_developer_messages_join_the_system_message_later_ones_become_user(self):
40        msgs = input_messages({"instructions": "I", "input": [
41            {"type": "message", "role": "developer", "content": [{"type": "input_text", "text": "D1"},
42                                                                 {"type": "input_text", "text": "D2"}]},
43            {"role": "user", "content": "u"},
44            {"type": "message", "role": "developer", "content": "late"}]})
45        self.assertEqual(msgs, [{"role": "system", "content": "I\n\nD1D2"}, {"role": "user", "content": "u"},
46                                {"role": "user", "content": "late"}])
47
48    def test_codex_history_becomes_one_assistant_turn_per_answer(self):
49        items = [{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "edit it"}]},
50                 {"type": "reasoning", "id": "rs_1", "summary": [],
51                  "content": [{"type": "reasoning_text", "text": "look first"}]},
52                 {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "Looking."}]},
53                 {"type": "function_call", "id": "fc_1", "call_id": "c1", "name": "exec_command",
54                  "arguments": "{\"cmd\":\"cat a\"}"},
55                 {"type": "function_call", "id": "fc_2", "call_id": "c2", "name": "spawn_agent",
56                  "namespace": "multi_agent_v1", "arguments": "{}"},
57                 # results in the order they finished, not the order of the calls
58                 {"type": "function_call_output", "call_id": "c2", "output": "agent"},
59                 {"type": "function_call_output", "call_id": "c1",
60                  "output": [{"type": "input_text", "text": "before"}]},
61                 {"type": "reasoning", "id": "rs_2", "summary": [{"type": "summary_text", "text": "s"}],
62                  "content": [{"type": "reasoning_text", "text": "now write"}]},
63                 {"type": "function_call", "call_id": "c3", "name": "exec_command", "arguments": "{\"cmd\":\"w\"}"},
64                 {"type": "function_call_output", "call_id": "c3", "output": "ok"}]
65        self.assertEqual(input_messages({"input": items}), [
66            {"role": "user", "content": "edit it"},
67            {"role": "assistant", "content": "Looking.", "reasoning_content": "look first", "tool_calls": [
68                {"function": {"name": "exec_command", "arguments": {"cmd": "cat a"}}},
69                {"function": {"name": "multi_agent_v1.spawn_agent", "arguments": {}}}]},
70            {"role": "tool", "content": "before"}, {"role": "tool", "content": "agent"},
71            {"role": "assistant", "content": "", "reasoning_content": "now write", "tool_calls": [
72                {"function": {"name": "exec_command", "arguments": {"cmd": "w"}}}]},
73            {"role": "tool", "content": "ok"}])
74
75    def test_reasoning_comes_back_from_our_encrypted_content_and_foreign_tokens_are_ignored(self):
76        enc = ENCRYPTED_PREFIX + base64.b64encode(json.dumps({"text": "hidden"}).encode()).decode()
77        for item, want in (({"encrypted_content": enc, "summary": []}, "hidden"),
78                           ({"encrypted_content": "gAAAAAB-someone-elses", "summary": []}, None)):
79            msgs = input_messages({"input": [{"role": "user", "content": "q"}, {"type": "reasoning", **item},
80                                             {"role": "assistant", "content": "a"}]})
81            self.assertEqual(msgs[1].get("reasoning_content"), want)
82        with self.assertRaises(ResponsesError) as e:
83            input_messages({"input": [{"type": "reasoning", "encrypted_content": ENCRYPTED_PREFIX + "!!"}]})
84        self.assertEqual(e.exception.param, "input[0].encrypted_content")
85
86    def test_bad_arguments_from_a_cut_off_call_do_not_refuse_the_conversation(self):
87        msgs = input_messages({"input": [{"role": "user", "content": "q"},
88                                         {"type": "function_call", "call_id": "c", "name": "f", "arguments": "{\"a"},
89                                         {"type": "function_call_output", "call_id": "c", "output": "x"}]})
90        self.assertEqual(msgs[1]["tool_calls"][0]["function"]["arguments"], {"arguments": "{\"a"})
91
92    def test_unsupported_items_are_named(self):
93        for items, param in (([{"type": "item_reference", "id": "msg_1"}], "input[0]"),
94                             ([{"type": "web_search_call"}], "input[0].type"),
95                             ([{"role": "user", "content": [{"type": "input_file", "file_id": "f"}]}],
96                              "input[0].content[0].type"),
97                             ([{"role": "robot", "content": "x"}], "input[0].role")):
98            with self.assertRaises(ResponsesError) as e:
99                input_messages({"input": items})
100            self.assertEqual(e.exception.param, param)
101        with self.assertRaises(ResponsesError):
102            input_messages({})
103
104    def test_tools_namespaces_custom_and_hosted(self):
105        tools, names, skipped = request_tools({"tools": [
106            *TOOLS, {"type": "namespace", "name": "mcp_fs", "description": "Files.",
107                     "tools": [{"type": "function", "name": "read", "parameters": {"type": "object"}}]},
108            {"type": "custom", "name": "apply_patch", "description": "Patch.",
109             "format": {"type": "grammar", "syntax": "lark", "definition": "start: \"x\""}},
110            {"type": "web_search"}]})
111        self.assertEqual([t["name"] for t in tools], ["exec_command", "mcp_fs.read", "apply_patch"])
112        self.assertEqual(tools[1]["description"], "Files.")
113        self.assertIn("start: \"x\"", tools[2]["description"])
114        self.assertEqual(names["mcp_fs.read"], ("mcp_fs", "read", "function"))
115        self.assertEqual(names["apply_patch"], (None, "apply_patch", "custom"))
116        self.assertEqual(skipped, ["web_search"])
117        self.assertIsNone(request_tools({"tools": TOOLS, "tool_choice": "none"})[0])
118
119    def test_additional_tools_input_items_are_accepted(self):
120        """#782: Codex sends an `additional_tools` input item; it used to be refused with a 400."""
121        extra = {"type": "additional_tools", "tools": [{"type": "function", "name": "later_tool",
122                                                         "parameters": {"type": "object"}}]}
123        req = {"input": [{"type": "message", "role": "user", "content": "hi"}, extra,
124                         {"type": "additional_tools"}], "tools": TOOLS}
125        self.assertEqual([m["role"] for m in input_messages(req)], ["user"])
126        tools, names, _ = request_tools(req)
127        self.assertEqual([t["name"] for t in tools], ["exec_command", "later_tool"])
128        self.assertIn("later_tool", names)
129
130    def test_effort_and_text_format(self):
131        self.assertEqual(template_kwargs({"reasoning": {"effort": "minimal"}}, {}), {"enable_thinking": False})
132        self.assertEqual(template_kwargs({"reasoning": {"effort": "high"}}, {}), {"reasoning_effort": "xhigh"})
133        self.assertEqual(template_kwargs({"reasoning": {"summary": "auto"}}, {}), {})      # Codex: the default
134        self.assertEqual(template_kwargs({}, {"reasoning_effort": "low"}), {"reasoning_effort": "low"})
135        with self.assertRaises(ResponsesError):
136            template_kwargs({"reasoning": {"effort": "huge"}}, {})
137        self.assertEqual(text_format({"text": {"format": {"type": "json_schema", "name": "n", "schema": {}}}}),
138                         {"type": "json_schema", "json_schema": {"name": "n", "schema": {}}})
139        self.assertIsNone(text_format({"text": {"format": {"type": "text"}}}))
140
141
142# ------------------------------------------------------------------------------------------------ Codex compaction
143HISTORY = [{"role": "user", "content": "hi"},
144           {"type": "function_call", "name": "exec_command", "arguments": "{}", "call_id": "c1"},
145           {"type": "function_call_output", "call_id": "c1", "output": "ok"}]
146COMPACT_PROMPT = "You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary."   # Codex's default
147OTHER_TOOLS = [{"type": "function", "name": "read_file", "description": "Reads a file.",
148                "parameters": {"type": "object", "properties": {"path": {"type": "string"}}}}]
149A, B = ("019a-a", "019a-a"), ("019a-b", "019a-b")    # (session_id, thread_id) of two root conversations
150
151
152def codex_meta(kind, conversation=A):
153    """client_metadata as Codex 0.160 sends it: the turn metadata is a JSON string."""
154    session, thread = conversation
155    return {"session_id": session, "thread_id": thread, "x-codex-turn-metadata": json.dumps(
156        {"session_id": session, "thread_id": thread, "request_kind": kind})}
157
158
159def codex_request(kind, conversation=A, tools=None, last=COMPACT_PROMPT, meta=None):
160    """A Codex request; a compaction one is the conversation again with `tools: []` (codex-rs compact.rs).  Every
161    conversation sends the same prompt_cache_key here: it is not what tells them apart."""
162    req = {"instructions": "Be brief", "tools": tools or [], "tool_choice": "auto", "prompt_cache_key": "same",
163           "parallel_tool_calls": bool(tools), "input": HISTORY + ([{"role": "user", "content": last}]
164                                                                    if kind == "compaction" else [])}
165    req["client_metadata"] = codex_meta(kind, conversation) if meta is None else meta
166    return req
167
168
169def tools_of(req):
170    """(the request's tools, the prompt's tools), as _responses_prepare gets them (the prompt then goes out)."""
171    tools = request_tools(req)[0]
172    shown = prompt_tools(req, tools)
173    prompt_made(req, shown)
174    return tools, shown
175
176
177class CodexCompaction(unittest.TestCase):
178    def setUp(self):
179        responses._kept_prompt_tools = (None, None)
180
181    def test_a_compaction_prompt_starts_as_its_conversations_last_prompt(self):
182        turn = codex_request("turn", tools=TOOLS)
183        before = TEMPLATE.render(input_messages(turn), tools=tools_of(turn)[1], add_generation_prompt=False)
184        req = codex_request("compaction")
185        own, shown = tools_of(req)
186        self.assertIsNone(own)                           # the request's tools: still none
187        self.assertEqual(shown, request_tools(turn)[0])
188        self.assertTrue(TEMPLATE.render(input_messages(req), tools=shown).startswith(before))
189        self.assertFalse(TEMPLATE.render(input_messages(req), tools=own).startswith(before))   # what it was
190        shown.clear()                                    # the kept list is nobody's to change
191        self.assertEqual(tools_of(req)[1], request_tools(turn)[0])
192        self.assertEqual(tools_of(req)[1], request_tools(turn)[0])   # a compaction leaves the entry as it was
193
194    def test_another_conversation_never_gets_these_tools(self):
195        tools_of(codex_request("turn", A, TOOLS))
196        b = tools_of(codex_request("turn", B, OTHER_TOOLS))[1]
197        self.assertIsNone(tools_of(codex_request("compaction", A))[1])    # one entry, B's: A reads again
198        self.assertEqual(tools_of(codex_request("compaction", B))[1], b)
199        for other in (("019a-b", "019a-sub"),            # a sub-agent: the root's session, its own thread
200                      ("019a-fork", "019a-fork")):        # a fork, or an ephemeral fork (same prompt_cache_key)
201            self.assertIsNone(tools_of(codex_request("compaction", other))[1])
202        self.assertEqual(tools_of(codex_request("compaction", B))[1], b)  # and they changed nothing
203        tools_of(codex_request("turn", A, TOOLS))
204        self.assertIsNone(tools_of(codex_request("compaction", B))[1])    # A's turn came last: B reads again
205        self.assertEqual(tools_of(codex_request("compaction", A))[1], request_tools({"tools": TOOLS})[0])
206
207    def test_requests_that_are_not_a_codex_compaction_are_rendered_as_sent(self):
208        tools_of(codex_request("turn", tools=TOOLS))
209        self.assertEqual(tools_of({"input": "another chat"}), (None, None))
210        self.assertEqual(tools_of({"input": COMPACT_PROMPT, "prompt_cache_key": "same"}), (None, None))
211        self.assertEqual(tools_of(codex_request("compaction", meta={})), (None, None))
212        self.assertEqual(tools_of(codex_request("compaction"))[1], request_tools({"tools": TOOLS})[0])
213        self.assertEqual(tools_of(codex_request("turn")), (None, None))   # a turn of A without tools ...
214        self.assertIsNone(tools_of(codex_request("compaction"))[1])        # ... is what its compaction follows
215
216    def test_the_compact_prompt_in_a_message_is_not_a_compaction(self):
217        tools_of(codex_request("turn", tools=TOOLS))
218        quoted = {"input": HISTORY + [{"role": "user", "content": COMPACT_PROMPT}], "tools": []}
219        self.assertEqual(tools_of(quoted), (None, None))  # the compact prompt's words, without Codex saying so
220        turn = codex_request("turn", last=COMPACT_PROMPT)
221        turn["input"] = HISTORY + [{"role": "user", "content": "Explain this: " + COMPACT_PROMPT}]
222        self.assertEqual(tools_of(turn), (None, None))   # Codex says it is a turn: as sent
223
224    def test_a_thread_title_turn_does_not_replace_the_kept_tools(self):
225        tools_of(codex_request("turn", tools=TOOLS))
226        kept = responses._kept_prompt_tools
227        title = codex_request("turn", ("019a-title", "019a-title"))
228        meta = json.loads(title["client_metadata"]["x-codex-turn-metadata"])
229        meta["thread_source"] = "thread_title"
230        title["client_metadata"]["x-codex-turn-metadata"] = json.dumps(meta)
231        prompt_made(title, None)
232        self.assertEqual(responses._kept_prompt_tools, kept)
233        self.assertEqual(tools_of(codex_request("compaction"))[1], request_tools({"tools": TOOLS})[0])
234
235    def test_a_custom_compact_prompt_is_a_compaction_when_codex_says_so(self):
236        first = tools_of(codex_request("turn", tools=TOOLS))[1]
237        self.assertEqual(tools_of(codex_request("compaction", last="Summarize it my way."))[1], first)
238
239    def test_a_compaction_that_sends_tools_keeps_them(self):
240        tools_of(codex_request("turn", tools=TOOLS))
241        own, shown = tools_of(codex_request("compaction", tools=OTHER_TOOLS))
242        self.assertEqual(shown, own)
243
244    def test_without_its_conversation_nothing_is_kept_or_used(self):
245        for meta in ({}, {"session_id": "019a-a", "thread_id": "019a-a"},     # only the flat keys
246                     {"x-codex-turn-metadata": json.dumps({"request_kind": "turn"})},
247                     {"x-codex-turn-metadata": json.dumps({"request_kind": "turn", "session_id": "019a-a"})},
248                     {"x-codex-turn-metadata": json.dumps({"request_kind": "turn", "thread_id": "019a-a"})}):
249            tools_of(codex_request("turn", tools=TOOLS, meta=meta))
250            self.assertEqual(responses._kept_prompt_tools, (None, None))
251        tools_of(codex_request("turn", tools=TOOLS))
252        kept = responses._kept_prompt_tools
253        compaction = {"x-codex-turn-metadata": json.dumps({"request_kind": "compaction"})}
254        self.assertEqual(tools_of(codex_request("compaction", meta=compaction)), (None, None))
255        self.assertEqual(responses._kept_prompt_tools, kept)
256
257    def test_malformed_metadata_is_no_error_and_no_reuse(self):
258        first = tools_of(codex_request("turn", tools=TOOLS))[1]
259        for meta in ("x", ["x"], {"x-codex-turn-metadata": None}, {"x-codex-turn-metadata": "{not json"},
260                     {"x-codex-turn-metadata": "[]"}, {"x-codex-turn-metadata": "\"compaction\""},
261                     {"x-codex-turn-metadata": {"request_kind": "compaction", "session_id": "019a-a",
262                                                "thread_id": "019a-a"}},          # an object: not what Codex sends
263                     {"x-codex-turn-metadata": json.dumps({"request_kind": "compaction", "session_id": 1,
264                                                           "thread_id": 1})},
265                     {"x-codex-turn-metadata": json.dumps({"request_kind": "compaction", "session_id": "",
266                                                           "thread_id": ""})}):
267            self.assertEqual(tools_of(codex_request("compaction", meta=meta)), (None, None), meta)
268        self.assertEqual(tools_of(codex_request("compaction"))[1], first)   # A's entry was not touched
269        odd = {"x-codex-turn-metadata": json.dumps({"request_kind": ["compaction"], "session_id": "019a-a",
270                                                    "thread_id": "019a-a"})}
271        self.assertEqual(tools_of(codex_request("compaction", meta=odd)), (None, None))   # not a compaction: as sent
272
273
274class NoLeakedSampler(unittest.TestCase):
275    """Test isolation: a stopped server stops its hardware sampler.  Every Service these tests started used to leave one
276    running (21 after this file), polling NVML and psutil every second, which skewed serve/test_parallel's timings."""
277
278    def test_server_close_ends_the_sampler(self):
279        import time
280        tok = ByteTokenizer()
281        httpd = serve(Service(MockEngine(tok, ANSWER, max_context=16384), tok, TEMPLATE), port=0)
282        sampler = getattr(getattr(httpd, "svc", None), "telemetry", None)
283        self.assertIsNotNone(sampler, "the server did not initialize telemetry")
284        thread = getattr(sampler, "_thread", None)
285        self.assertIsNotNone(thread, "the server did not start its hardware sampler thread")
286        self.assertTrue(thread.is_alive(), "the hardware sampler thread died immediately")
287        httpd.shutdown()
288        httpd.server_close()
289        thread.join(timeout=5.0)
290        self.assertFalse(thread.is_alive(), "a stopped server left its hardware sampler running")
291
292
293# ------------------------------------------------------------------------------------------------ over HTTP
294class Server(unittest.TestCase):
295    script = ANSWER
296
297    def setUp(self):
298        self.tok = ByteTokenizer()
299        self.engine = MockEngine(self.tok, self.script, max_context=16384)
300        self.svc = Service(self.engine, self.tok, TEMPLATE)
301        self.httpd = serve(self.svc, port=0)
302        self.port = self.httpd.server_address[1]
303
304    def tearDown(self):
305        self.httpd.shutdown()
306        self.httpd.server_close()
307
308    def post(self, body, path="/v1/responses", headers=None):
309        """(status, parsed body: a dict, or the list of SSE events of a stream)."""
310        c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=30)
311        try:
312            with contextlib.redirect_stdout(io.StringIO()):
313                c.request("POST", path, body=json.dumps(body).encode(),
314                          headers={"Content-Type": "application/json", **(headers or {})})
315                r = c.getresponse()
316                raw = r.read().decode()
317            if r.getheader("Content-Type") == "text/event-stream":
318                events = []
319                for block in raw.split("\n\n"):
320                    lines = block.strip().splitlines()
321                    if not lines or lines[0].startswith(":"):
322                        continue
323                    name = lines[0][len("event: "):]
324                    data = json.loads(lines[1][len("data: "):])
325                    self.assertEqual(name, data["type"])
326                    events.append(data)
327                return r.status, events
328            return r.status, json.loads(raw)
329        finally:
330            c.close()
331
332
333
334class OverHttp(Server):
335    def test_non_streaming_text_with_reasoning(self):
336        code, r = self.post({"model": "m", "input": "hi", "store": False})
337        self.assertEqual(code, 200)
338        self.assertEqual((r["object"], r["status"], r["error"]), ("response", "completed", None))
339        rs, msg = r["output"]
340        self.assertEqual(rs["type"], "reasoning")
341        self.assertEqual(rs["content"], [{"type": "reasoning_text", "text": "Read it.\n"}])
342        self.assertEqual(rs["summary"], [])
343        self.assertNotIn("encrypted_content", rs)
344        self.assertEqual(msg["type"], "message")
345        self.assertEqual(msg["content"][0]["text"], "The file says before.")
346        u = r["usage"]
347        self.assertEqual(u["output_tokens"], len(self.tok.encode(ANSWER)) + 1)        # + the end-of-turn token
348        self.assertEqual(u["output_tokens_details"]["reasoning_tokens"], len("Read it.\n</think>"))
349        self.assertEqual(u["total_tokens"], u["input_tokens"] + u["output_tokens"])
350        self.assertEqual(r["store"], False)
351
352    def test_stream_event_order(self):
353        code, events = self.post({"model": "m", "input": "hi", "stream": True,
354                                  "include": ["reasoning.encrypted_content"]})
355        self.assertEqual(code, 200)
356        types = [e["type"] for e in events]
357        deltas_r = types.count("response.reasoning_text.delta")
358        deltas_t = types.count("response.output_text.delta")
359        self.assertGreater(deltas_r, 0)
360        self.assertGreater(deltas_t, 0)
361        self.assertEqual(types, ["response.created", "response.in_progress",
362                                 "response.output_item.added", *["response.reasoning_text.delta"] * deltas_r,
363                                 "response.reasoning_text.done", "response.output_item.done",
364                                 "response.output_item.added", "response.content_part.added",
365                                 *["response.output_text.delta"] * deltas_t,
366                                 "response.output_text.done", "response.content_part.done",
367                                 "response.output_item.done", "response.completed"])
368        self.assertEqual([e["sequence_number"] for e in events], list(range(len(events))))
369        final = events[-1]["response"]
370        self.assertEqual(final["status"], "completed")
371        rs, msg = final["output"]
372        self.assertEqual([e["item"]["id"] for e in events if e["type"] == "response.output_item.done"],
373                         [rs["id"], msg["id"]])
374        self.assertEqual("".join(e["delta"] for e in events if e["type"] == "response.output_text.delta"),
375                         msg["content"][0]["text"])
376        self.assertTrue(rs["encrypted_content"].startswith(ENCRYPTED_PREFIX))
377        # the encrypted_content alone brings the thinking back into the prompt
378        replay = input_messages({"input": [{"role": "user", "content": "hi"},
379                                           {"type": "reasoning", "summary": [], "encrypted_content":
380                                            rs["encrypted_content"]}, msg]})
381        self.assertEqual(replay[1]["reasoning_content"], "Read it.\n")
382
383    def test_max_output_tokens_ends_incomplete(self):
384        code, r = self.post({"model": "m", "input": "hi", "max_output_tokens": 5})
385        self.assertEqual(code, 200)
386        self.assertEqual(r["status"], "incomplete")
387        self.assertEqual(r["incomplete_details"], {"reason": "max_output_tokens"})
388        self.assertEqual(r["output"][0]["status"], "incomplete")
389        code, events = self.post({"model": "m", "input": "hi", "max_output_tokens": 5, "stream": True})
390        self.assertEqual(events[-1]["type"], "response.incomplete")
391
392    def test_max_output_tokens_zero_and_minus_one_mean_no_cap(self):
393        # #4036: the documented "no cap" values; the answer is complete, not cut at the cap
394        for n in (0, -1):
395            code, r = self.post({"model": "m", "input": "hi", "max_output_tokens": n})
396            self.assertEqual((code, r["status"]), (200, "completed"), (n, r))
397            self.assertIsNone(r["incomplete_details"])
398            code, events = self.post({"model": "m", "input": "hi", "max_output_tokens": n, "stream": True})
399            self.assertEqual((code, events[-1]["type"]), (200, "response.completed"), n)
400
401    def test_max_output_tokens_bad_values_are_400(self):
402        for n in (-2, -100, 1.5, True, "5"):
403            code, r = self.post({"model": "m", "input": "hi", "max_output_tokens": n})
404            self.assertEqual(code, 400, (n, r))
405            self.assertEqual(r["error"]["param"], "max_output_tokens", n)
406
407    def test_effort_none_does_not_think(self):
408        self.engine.scripts = [self.tok.encode("Hello.<|im_end|>", parse_special=True)]
409        self.engine.script = self.engine.scripts[0]
410        code, r = self.post({"model": "m", "input": "hi", "reasoning": {"effort": "none"}})
411        self.assertEqual([o["type"] for o in r["output"]], ["message"])
412        self.assertIn("<think>\n\n</think>", self.tok.decode(self.engine.last_prompt))
413
414    def test_errors_use_the_responses_format(self):
415        for body, param in (({"model": "m"}, "input"), ({"model": "m", "input": "x", "previous_response_id": "r"},
416                                                         "previous_response_id"),
417                            ({"model": "m", "input": "x", "reasoning": {"effort": "huge"}}, "reasoning.effort")):
418            code, r = self.post(body)
419            self.assertEqual(code, 400)
420            self.assertEqual(set(r["error"]), {"message", "type", "param", "code"})
421            self.assertEqual(r["error"]["param"], param)
422        code, r = self.post({}, path="/v1/responses/resp_123/cancel")
423        self.assertEqual(code, 404)
424        self.assertEqual(r["error"]["code"], "not_found")
425        c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=30)
426        c.request("POST", "/v1/responses", body=b"{not json", headers={"Content-Type": "application/json"})
427        r = c.getresponse()
428        err = json.loads(r.read())["error"]
429        c.close()
430        self.assertEqual((r.status, err["type"], err["param"]), (400, "invalid_request_error", None))
431
432    def test_too_long_for_the_context(self):
433        code, r = self.post({"model": "m", "input": "x" * 20000})
434        self.assertEqual(code, 400)
435        self.assertEqual(r["error"]["code"], "context_length_exceeded")
436
437    def test_api_key_and_foreign_pages(self):
438        self.svc.api_key = "s3cret"
439        self.assertEqual(self.post({"model": "m", "input": "hi"})[0], 401)
440        self.assertEqual(self.post({"model": "m", "input": "hi"}, headers={"Authorization": "Bearer s3cret"})[0], 200)
441        self.svc.api_key = None
442        code, r = self.post({"model": "m", "input": "hi"}, headers={"Origin": "https://evil.example.com"})
443        self.assertEqual(code, 403)
444
445    def test_a_foreign_page_cannot_name_a_file_as_an_image(self):
446        """#553: the chat routes refuse a file image from another origin; so does /v1/responses."""
447        def body(src):
448            return {"model": "m", "input": [{"role": "user", "content": [
449                {"type": "input_text", "text": "what is it?"}, {"type": "input_image", "image_url": src}]}]}
450        self.svc.cors_origins = ["*"]                  # a page cors_origins lets in may send JSON, not name a file
451        for src in (r"\\host\share\x.png", "/etc/passwd", "file:///C:/x.png"):
452            with self.subTest(src=src):
453                code, r = self.post(body(src), headers={"Origin": "https://evil.example.com"})
454                self.assertEqual(code, 400, r)
455                self.assertIn("another origin", r["error"]["message"])
456        # data: and http(s) are the page's own to send: not refused by this check (no vision here, so a 400 of another kind)
457        for src in ("data:image/png;base64,iVBORw0KGgo=", "https://example.com/x.png"):
458            code, r = self.post(body(src), headers={"Origin": "https://evil.example.com"})
459            self.assertNotIn("another origin", json.dumps(r))
460
461    def test_json_schema_text_format(self):
462        self.engine.scripts = [self.tok.encode("</think>\n\n{\"n\": 3}<|im_end|>", parse_special=True)]
463        self.engine.script = self.engine.scripts[0]
464        fmt = {"type": "json_schema", "name": "num", "strict": True,
465               "schema": {"type": "object", "properties": {"n": {"type": "integer"}}, "required": ["n"]}}
466        code, r = self.post({"model": "m", "input": "a number", "text": {"format": fmt}})
467        self.assertEqual(code, 200, r)
468        self.assertEqual(r["output"][-1]["content"][0]["text"], "{\"n\":3}")
469        code, events = self.post({"model": "m", "input": "a number", "text": {"format": fmt}, "stream": True})
470        self.assertEqual([e["delta"] for e in events if e["type"] == "response.output_text.delta"], ["{\"n\":3}"])
471        self.assertEqual(events[-1]["type"], "response.completed")
472        # an answer that fails the schema - only jsonschema can tell: it is optional (serve/structured.py), and
473        # without it a json_schema answer is checked to be one JSON object, which {"n": 3} is
474        try:
475            import jsonschema  # noqa: F401
476        except ImportError:
477            return
478        bad = {**fmt, "schema": {**fmt["schema"], "properties": {"n": {"type": "string"}}}}
479        code, r = self.post({"model": "m", "input": "a number", "text": {"format": bad}})
480        self.assertEqual((code, r["error"]["code"]), (502, "structured_output_failed"))
481        code, events = self.post({"model": "m", "input": "a number", "text": {"format": bad}, "stream": True})
482        self.assertEqual(events[-1]["type"], "response.failed")
483        self.assertEqual(events[-1]["response"]["error"]["code"], "structured_output_failed")
484
485    def test_monitor_and_status(self):
486        self.svc.api_monitor = True
487        self.post({"model": "m", "input": "hi", "stream": True})
488        rec = self.svc.request_records()[0]
489        self.assertEqual(rec["path"], "/v1/responses")
490        full = self.svc.request_records(rec["id"])
491        self.assertEqual(full["output"], "The file says before.")
492        self.assertEqual(full["reasoning"], "Read it.\n")
493        self.assertIn("/v1/responses", self.svc.v1_status()["dialects"])
494
495
496class ToolRoundTrip(Server):
497    script = [CALL, ANSWER]
498
499    def test_function_call_round_trip(self):
500        user = {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "what is in a.txt?"}]}
501        code, events = self.post({"model": "m", "instructions": "You are a coding agent.", "input": [user],
502                                  "tools": TOOLS, "store": False, "stream": True,
503                                  "include": ["reasoning.encrypted_content"], "reasoning": {"summary": "auto"},
504                                  "parallel_tool_calls": True, "tool_choice": "auto"})
505        self.assertEqual(code, 200)
506        first_prompt = self.tok.decode(self.engine.last_prompt)
507        types = [e["type"] for e in events]
508        n_args = types.count("response.function_call_arguments.delta")
509        self.assertGreater(n_args, 0)
510        call_part = types[types.index("response.output_text.done") + 2:]
511        self.assertEqual(call_part, ["response.output_item.done", "response.output_item.added",
512                                     *["response.function_call_arguments.delta"] * n_args,
513                                     "response.function_call_arguments.done", "response.output_item.done",
514                                     "response.completed"])
515        output = events[-1]["response"]["output"]
516        self.assertEqual([o["type"] for o in output], ["reasoning", "message", "function_call"])
517        fc = output[2]
518        self.assertEqual((fc["name"], json.loads(fc["arguments"]), fc["status"]),
519                         ("exec_command", {"cmd": "cat a.txt"}, "completed"))
520        self.assertTrue(fc["call_id"])
521        added = next(e for e in events if e["type"] == "response.output_item.added"
522                     and e["item"]["type"] == "function_call")
523        self.assertEqual((added["item"]["call_id"], added["item"]["arguments"]), (fc["call_id"], ""))
524        # Codex sends everything back, plus the result: the prompt continues exactly where the model stopped
525        code, r = self.post({"model": "m", "instructions": "You are a coding agent.", "tools": TOOLS, "store": False,
526                             "input": [user, *output, {"type": "function_call_output", "call_id": fc["call_id"],
527                                                       "output": "before"}]})
528        self.assertEqual(code, 200, r)
529        second_prompt = self.tok.decode(self.engine.last_prompt)
530        self.assertTrue(second_prompt.startswith(first_prompt + CALL + "<|im_end|>"), second_prompt[-600:])
531        self.assertIn("<tool_response>\nbefore\n</tool_response>", second_prompt)
532        self.assertEqual(r["output"][-1]["content"][0]["text"], "The file says before.")
533
534    def test_quoted_incomplete_wrapper_is_not_a_completed_call(self):
535        text = "Format: " + CALL[CALL.index("<tool_call>"):].removesuffix("</tool_call>") + "and then I explain it."
536        self.engine.scripts = [self.tok.encode("</think>\n\n" + text + "<|im_end|>", parse_special=True)]
537        self.engine.script = self.engine.scripts[0]
538        for stream in (False, True):
539            code, result = self.post({"model": "m", "input": "explain the format", "tools": TOOLS, "stream": stream})
540            self.assertEqual(code, 200, result)
541            final = result[-1]["response"] if stream else result
542            calls = [item for item in final["output"] if item["type"] == "function_call"]
543            self.assertFalse(any(item["status"] == "completed" for item in calls))
544            for call in calls:
545                with self.assertRaises(ValueError):
546                    json.loads(call["arguments"])
547            self.assertEqual("".join(item["content"][0]["text"] for item in final["output"]
548                                     if item["type"] == "message"), text)
549
550    def test_namespace_call_written_with_double_underscore(self):
551        # Qwen writes Codex's MCP tools in their flat `mcp__server__tool` form; Codex only
552        # runs the call when it comes back with its namespace.
553        self.engine.scripts = [self.tok.encode(
554            "</think>\n\n<tool_call>\n<function=mcp__websearch__web_search>\n<parameter=query>\nstrata\n"
555            "</parameter>\n</function>\n</tool_call><|im_end|>", parse_special=True)]
556        self.engine.script = self.engine.scripts[0]
557        tools = [{"type": "namespace", "name": "mcp__websearch", "description": "Search.", "tools": [
558            {"type": "function", "name": "web_search",
559             "parameters": {"type": "object", "properties": {"query": {"type": "string"}}}}]}]
560        code, r = self.post({"model": "m", "input": "go", "tools": tools})
561        self.assertEqual(code, 200, r)
562        call, = r["output"]
563        self.assertEqual((call["namespace"], call["name"], json.loads(call["arguments"])),
564                         ("mcp__websearch", "web_search", {"query": "strata"}))
565
566        # Two canonical names share this alias. It must not invoke the first namespace.
567        self.engine.scripts = [self.tok.encode(
568            "</think>\n\n<tool_call>\n<function=a__b__c>\n</function>\n</tool_call><|im_end|>",
569            parse_special=True)]
570        self.engine.script = self.engine.scripts[0]
571        tools = [{"type": "namespace", "name": "a", "tools": [{"type": "function", "name": "b__c"}]},
572                 {"type": "namespace", "name": "a__b", "tools": [{"type": "function", "name": "c"}]}]
573        for stream in (False, True):
574            code, r = self.post({"model": "m", "input": "go", "tools": tools, "stream": stream})
575            self.assertEqual(code, 200, r)
576            output = r[-1]["response"]["output"] if stream else r["output"]
577            # not an alias of either: with tools declared (the 0.2.2 rule, #3075) a call for an undeclared name stays text
578            self.assertFalse([item for item in output if item.get("type") == "function_call"], output)
579            self.assertIn("a__b__c", json.dumps(output))
580
581        # A declared exact name wins over alias spellings and keeps its string schema.
582        tools.append({"type": "function", "name": "a__b__c", "parameters": {
583            "type": "object", "properties": {"path": {"type": "string"}}}})
584        self.engine.scripts = [self.tok.encode(
585            "</think>\n\n<tool_call>\n<function=a__b__c>\n<parameter=path>\n123\n</parameter>\n"
586            "</function>\n</tool_call><|im_end|>", parse_special=True)]
587        self.engine.script = self.engine.scripts[0]
588        for stream in (False, True):
589            code, r = self.post({"model": "m", "input": "go", "tools": tools, "stream": stream})
590            self.assertEqual(code, 200, r)
591            output = r[-1]["response"]["output"] if stream else r["output"]
592            call, = output
593            self.assertNotIn("namespace", call)
594            self.assertEqual((call["name"], json.loads(call["arguments"])), ("a__b__c", {"path": "123"}))
595
596    def test_namespace_and_custom_calls_come_back_under_their_own_names(self):
597        self.engine.scripts = [self.tok.encode(
598            "</think>\n\n<tool_call>\n<function=multi_agent_v1.spawn_agent>\n<parameter=message>\nhi\n</parameter>\n"
599            "</function>\n</tool_call>\n<tool_call>\n<function=apply_patch>\n<parameter=input>\n*** Begin Patch\n"
600            "</parameter>\n</function>\n</tool_call><|im_end|>", parse_special=True)]
601        self.engine.script = self.engine.scripts[0]
602        tools = [{"type": "namespace", "name": "multi_agent_v1", "description": "Agents.", "tools": [
603            {"type": "function", "name": "spawn_agent", "strict": False,
604             "parameters": {"type": "object", "properties": {"message": {"type": "string"}}}}]},
605            {"type": "custom", "name": "apply_patch", "description": "Edit files."}]
606        code, r = self.post({"model": "m", "input": "go", "tools": tools})
607        self.assertEqual(code, 200, r)
608        ns, custom = r["output"]
609        self.assertEqual((ns["type"], ns["namespace"], ns["name"], json.loads(ns["arguments"])),
610                         ("function_call", "multi_agent_v1", "spawn_agent", {"message": "hi"}))
611        self.assertEqual((custom["type"], custom["name"], custom["input"]),
612                         ("custom_tool_call", "apply_patch", "*** Begin Patch"))
613        msgs = input_messages({"input": [{"role": "user", "content": "go"}, ns, custom,
614                                         {"type": "function_call_output", "call_id": ns["call_id"], "output": "1"},
615                                         {"type": "custom_tool_call_output", "call_id": custom["call_id"],
616                                          "output": "2"}]})
617        self.assertEqual([c["function"]["name"] for c in msgs[1]["tool_calls"]],
618                         ["multi_agent_v1.spawn_agent", "apply_patch"])
619
620
621class JsonFormatWithTools(Server):
622    """#782: Codex's review request carries an `additional_tools` item, tools, and `text.format` json_schema together.
623    A tool call passes through; the schema is checked on the answer that ends in text."""
624    FMT = {"type": "json_schema", "name": "guardian_review", "strict": True,
625           "schema": {"type": "object", "properties": {"outcome": {"type": "string"}, "rationale": {"type": "string"}},
626                      "required": ["outcome", "rationale"], "additionalProperties": False}}
627
628    def request(self, **extra):
629        user = {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "review this call"}]}
630        more = {"type": "additional_tools", "role": "developer", "tools": [
631            {"type": "function", "name": "later_tool", "parameters": {"type": "object"}}]}
632        return {"model": "m", "instructions": "You are a reviewer.", "input": [more, user], "tools": TOOLS,
633                "tool_choice": "auto", "parallel_tool_calls": False, "store": False,
634                "text": {"format": self.FMT}, **extra}
635
636    def script_with(self, text):
637        self.engine.scripts = [self.tok.encode(text, parse_special=True)]
638        self.engine.script = self.engine.scripts[0]
639
640    def test_a_tool_call_passes_through(self):
641        self.script_with(CALL + "<|im_end|>")
642        for stream in (False, True):
643            code, r = self.post(self.request(stream=stream))
644            self.assertEqual(code, 200, r)
645            final = r if not stream else r[-1]["response"]
646            self.assertEqual(final["status"], "completed")
647            self.assertEqual([o["type"] for o in final["output"]][-2:], ["message", "function_call"])
648            call, = [o for o in final["output"] if o["type"] == "function_call"]
649            self.assertEqual((call["type"], call["name"], json.loads(call["arguments"])),
650                             ("function_call", "exec_command", {"cmd": "cat a.txt"}))
651        # the model is told the schema is for its final answer, not for a turn that calls a tool
652        self.assertIn("applies only to your final answer", self.tok.decode(self.engine.last_prompt))
653
654    def test_the_final_text_answer_is_the_schema_object(self):
655        self.script_with('</think>\n\n{"outcome": "allow", "rationale": "read only"}<|im_end|>')
656        code, r = self.post(self.request())
657        self.assertEqual(code, 200, r)
658        self.assertEqual(json.loads(r["output"][-1]["content"][0]["text"]),
659                         {"outcome": "allow", "rationale": "read only"})
660        code, events = self.post(self.request(stream=True))
661        self.assertEqual(events[-1]["type"], "response.completed")
662        self.assertEqual(len([e for e in events if e["type"] == "response.output_text.delta"]), 1)
663
664    def test_a_text_answer_that_breaks_the_schema_fails_as_without_tools(self):
665        try:
666            import jsonschema  # noqa: F401
667        except ImportError:
668            self.skipTest("the schema check needs jsonschema")
669        self.script_with('</think>\n\n{"outcome": 3}<|im_end|>')
670        code, r = self.post(self.request())
671        self.assertEqual((code, r["error"]["code"]), (502, "structured_output_failed"))
672
673
674class ThreadTitle(Server):
675    def test_a_thread_title_is_answered_without_the_engine(self):
676        self.svc.codex_thread_titles = True                      # opt-in: "codex_thread_titles": true in the config
677        user = {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "what is in a.txt?"}]}
678        code, r = self.post({"model": "m", "instructions": "You are a coding agent.", "input": [user], "tools": TOOLS})
679        self.assertEqual(code, 200, r)
680        seen = list(self.engine.last_prompt)
681        self.assertTrue(seen)
682        meta = {"session_id": "019a-title", "thread_id": "019a-title", "request_kind": "turn",
683                "thread_source": "thread_title"}
684        code, r = self.post({
685            "model": "m", "instructions": "You are Codex", "tools": [],
686            "client_metadata": {"x-codex-turn-metadata": json.dumps(meta)},
687            "input": [{"type": "message", "role": "user", "content": [
688                {"type": "input_text", "text": "Generate a concise title.\n\nUser prompt:\n只回四個字然後停:傾印測試"}]}]})
689        self.assertEqual(code, 200, r)
690        self.assertEqual(self.engine.last_prompt, seen)
691        self.assertEqual(json.loads(r["output"][0]["content"][0]["text"]), {"title": "只回四個字然後停:傾印測試"})
692        long = {"model": "m", "instructions": "You are Codex", "tools": [],
693                "client_metadata": {"x-codex-turn-metadata": json.dumps(meta)},
694                "input": "User prompt:\n" + ("甲" * 40) + "。"}
695        self.assertEqual(json.loads(collect(thread_title_events(long, "m"))["output"][0]["content"][0]["text"]),
696                         {"title": "甲" * 36})
697
698    def test_off_by_default_the_engine_answers(self):
699        meta = {"thread_source": "thread_title"}
700        code, r = self.post({"model": "m", "instructions": "You are Codex", "tools": [],
701                             "client_metadata": {"x-codex-turn-metadata": json.dumps(meta)},
702                             "input": "User prompt:" + chr(10) + "hello"})
703        self.assertEqual(code, 200, r)
704        self.assertTrue(self.engine.last_prompt)                  # it ran on the engine
705        self.assertNotIn('"title"', json.dumps(r["output"]))
706
707
708class CodexCompactionOverHttp(Server):
709    # the compaction answer is tool calls the conversation's tools would make a namespace call and a custom call
710    script = [CALL, "</think>\n\n<tool_call>\n<function=multi_agent_v1.spawn_agent>\n<parameter=message>\nhi\n"
711                    "</parameter>\n</function>\n</tool_call>\n<tool_call>\n<function=apply_patch>\n<parameter=input>\n"
712                    "*** Begin Patch\n</parameter>\n</function>\n</tool_call>"]
713    tools = TOOLS + [{"type": "namespace", "name": "multi_agent_v1", "description": "Agents.", "tools": [
714        {"type": "function", "name": "spawn_agent", "parameters": {"type": "object", "properties": {
715            "message": {"type": "string"}}}}]}, {"type": "custom", "name": "apply_patch", "description": "Edit files."}]
716
717    def setUp(self):
718        super().setUp()
719        responses._kept_prompt_tools = (None, None)
720        self.svc.codex_compaction_cache = True       # opt-in (#924)
721        self.parser_tools = []
722        run = self.svc.run
723
724        def recorded(ids, thinking, tools, *rest):
725            self.parser_tools.append(tools)
726            return run(ids, thinking, tools, *rest)
727        self.svc.run = recorded
728
729    def compaction(self, meta, output="before", between=None, **extra):
730        """Codex's turn, (`between`,) then its compaction request: (the compaction prompt, its status and response)."""
731        self.engine.turns, self.engine.script = 0, self.engine.scripts[0]
732        user = {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "what is in a.txt?"}]}
733        turn = {"model": "m", "instructions": "You are a coding agent.", "input": [user], "tools": self.tools,
734                "include": ["reasoning.encrypted_content"], "client_metadata": codex_meta("turn")}
735        code, r = self.post(turn)
736        self.assertEqual(code, 200, r)
737        self.first_prompt = self.tok.decode(self.engine.last_prompt)
738        call = r["output"][-1]
739        if between:
740            between()
741        code, r = self.post({**turn, "tools": [], "parallel_tool_calls": False, "client_metadata": meta, "input": [
742            user, *r["output"], {"type": "function_call_output", "call_id": call["call_id"], "output": output},
743            {"type": "message", "role": "user", "content": [{"type": "input_text", "text": COMPACT_PROMPT}]}],
744            **extra})
745        return self.tok.decode(self.engine.last_prompt), code, r
746
747    def test_the_kept_tools_shape_only_the_prompt(self):
748        prompt, code, r = self.compaction(codex_meta("compaction"))
749        self.assertEqual(code, 200, r)
750        self.assertTrue(prompt.startswith(self.first_prompt + CALL + "<|im_end|>"))   # the cached conversation
751        self.assertIn("multi_agent_v1.spawn_agent", prompt[:prompt.index("<|im_end|>")])
752        self.assertEqual(self.parser_tools[-1], None)    # the parser gets the request's tools: none
753        self.assertEqual(r["tools"], [])
754        # the calls come back as for any request without tools: no namespace, no custom tool
755        outputs = [(o["type"], o["name"], o.get("namespace")) for o in r["output"]]
756        self.assertEqual(outputs, [("function_call", "multi_agent_v1.spawn_agent", None),
757                                   ("function_call", "apply_patch", None)])
758        # the same request without Codex's metadata (upstream's behaviour): the same answer, but its prompt starts
759        # differently, so the engine reads it from the start
760        plain, code, r2 = self.compaction({})
761        self.assertEqual(code, 200, r2)
762        self.assertFalse(plain.startswith(self.first_prompt))
763        self.assertNotIn("multi_agent_v1.spawn_agent", plain[:plain.index("<|im_end|>")])
764        self.assertEqual(self.parser_tools[-1], None)
765        self.assertEqual([(o["type"], o["name"], o.get("namespace")) for o in r2["output"]], outputs)
766
767    def test_a_compaction_too_long_with_the_kept_tools_is_rendered_as_sent(self):
768        long = "before\n" * 300                         # a long tool output: the turn fits, its compaction barely
769        plain, code, r = self.compaction({}, long, max_output_tokens=64)
770        self.assertEqual(code, 200, r)
771        fits = len(self.engine.last_prompt) + 64 + 8     # the request as sent, its output, CTX_SLACK
772        shown, code, r = self.compaction(codex_meta("compaction"), long, max_output_tokens=64)
773        self.assertGreater(len(self.engine.last_prompt) + 64 + 8, fits)   # with the kept tools it would not fit
774        self.engine.max_context = fits
775        again, code, r = self.compaction(codex_meta("compaction"), long, max_output_tokens=64)
776        self.assertEqual(code, 200, r)                   # as without the kept tools, not a context error
777        self.assertEqual(again, plain)
778        self.assertEqual(self.parser_tools[-1], None)
779
780
781    def test_a_request_that_fails_leaves_the_kept_tools_as_they_were(self):
782        before, code, r = self.compaction(codex_meta("compaction"))
783        self.assertEqual(code, 200, r)
784
785        def fails():                                     # B's turn is too long: its prompt never reaches the engine
786            code, r = self.post({"model": "m", "input": "x" * 20000, "tools": TOOLS,
787                                 "client_metadata": codex_meta("turn", B)})
788            self.assertEqual((code, r["error"]["code"]), (400, "context_length_exceeded"))
789        again, code, r = self.compaction(codex_meta("compaction"), between=fails)
790        self.assertEqual(code, 200, r)
791        self.assertEqual(again, before)                  # so A's compaction still starts as A's turn
792
793
794if __name__ == "__main__":
795    unittest.main()