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
14.4 KiB249 linesraw
1"""Exercise the JSON contract through HTTP, including H3's strict Story shape."""
2import json
3import unittest
4import urllib.error
5import urllib.request
6from pathlib import Path
7from unittest import mock
8
9from serve.frontend import ChatTemplate
10from serve import structured
11from serve.server import ByteTokenizer, MockEngine, Service, serve
12
13try:
14    import jsonschema  # noqa: F401
15    HAVE_JSONSCHEMA = True
16except ImportError:                  # optional: json_schema answers are then only checked to be one object
17    HAVE_JSONSCHEMA = False
18
19
20STORY = {"title": "Photobooth", "sheet": "A single continuous shot.", "cast": [],
21         "boxes": [{"box": 1, "duration_ms": 15000, "new_shot": True, "beat": "Hailee changes poses.",
22                    "on_screen": ["Hailee"], "references": [], "ends": "She smiles."}], "suggestions": []}
23
24
25def object_schema(properties):
26    return {"type": "object", "properties": properties, "required": list(properties), "additionalProperties": False}
27
28
29TEXT = {"type": "string"}
30STORY_SCHEMA = object_schema({
31    "title": TEXT, "sheet": TEXT, "cast": {"type": "array", "items": object_schema({"name": TEXT,
32        "references": {"type": "array", "items": TEXT, "maxItems": 0}})},
33    "boxes": {"type": "array", "minItems": 1, "maxItems": 1, "items": object_schema({
34        "box": {"type": "integer", "minimum": 1, "maximum": 1},
35        "duration_ms": {"type": "integer", "minimum": 1, "maximum": 15000}, "new_shot": {"type": "boolean"},
36        "beat": TEXT, "on_screen": {"type": "array", "items": TEXT},
37        "references": {"type": "array", "items": TEXT, "maxItems": 0}, "ends": TEXT})},
38    "suggestions": {"type": "array", "items": object_schema({"what": TEXT, "why": TEXT,
39        "boxes": {"type": "array", "items": {"type": "integer"}}, "description": TEXT})}})
40FORMAT = {"type": "json_schema", "json_schema": {"name": "h3_story", "strict": True, "schema": STORY_SCHEMA}}
41
42
43class Structured(unittest.TestCase):
44    def request(self, path, body=None, headers=None):
45        req = urllib.request.Request(self.base + path, data=json.dumps(body).encode() if body is not None else None,
46                                     headers={"Content-Type": "application/json", **(headers or {})})
47        try:
48            response = urllib.request.urlopen(req, timeout=10)
49        except urllib.error.HTTPError as error:
50            response = error
51        with response:
52            data = response.read().decode()
53            return response.status, data if "event-stream" in response.headers.get("Content-Type", "") else json.loads(data)
54
55    def setUp(self):
56        self.tok = ByteTokenizer()
57        self.engine = MockEngine(self.tok, json.dumps(STORY), max_context=16384)
58        self.svc = Service(self.engine, self.tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja"))
59        self.httpd = serve(self.svc, port=0)
60        self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}"
61
62    def tearDown(self):
63        self.httpd.shutdown()
64        self.httpd.server_close()
65
66    def chat(self, script=None, **kwargs):
67        if script is not None:
68            self.engine = self.svc.engine = MockEngine(self.tok, script, max_context=16384)
69        req = {"messages": [{"role": "system", "content": "Write a film plan."},
70                            {"role": "user", "content": "Photobooth. 15 seconds."}],
71               "response_format": FORMAT, "reasoning_effort": "none", **kwargs}
72        return self.request("/v1/chat/completions", req)
73
74    def test_h3_schema_success_and_stream_with_reasoning(self):
75        code, reply = self.chat()
76        self.assertEqual(code, 200)
77        self.assertEqual(json.loads(reply["choices"][0]["message"]["content"]), STORY)
78        prompt = self.tok.decode(self.engine.last_prompt)
79        self.assertIn("OUTPUT FORMAT REQUIREMENT", prompt)
80        self.assertIn('"duration_ms"', prompt)
81        code, raw = self.chat("Consider the shot.</think>\n" + json.dumps(STORY), stream=True, reasoning_effort="low")
82        self.assertEqual(code, 200)
83        chunks = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")]
84        content = "".join(c["choices"][0]["delta"].get("content", "") for c in chunks)
85        self.assertEqual(json.loads(content), STORY)
86        self.assertIn("reasoning_content", raw)
87        self.assertIn("data: [DONE]", raw)
88
89    @unittest.skipUnless(HAVE_JSONSCHEMA, "jsonschema is not installed")
90    def test_invalid_generation_is_an_error_and_never_streams_content(self):
91        for script in ("## Film Plan - Photobooth", '{"title":"Only a title"}',
92                       json.dumps({**STORY, "extra": True}),
93                       json.dumps({**STORY, "boxes": [{**STORY["boxes"][0], "duration_ms": "15000"}]})):
94            with self.subTest(script=script):
95                code, reply = self.chat(script)
96                self.assertEqual(code, 502)
97                self.assertEqual(reply["error"]["code"], "structured_output_failed")
98                _, raw = self.chat(script, stream=True)
99                self.assertIn('"structured_output_failed"', raw)
100                self.assertNotIn('"delta"', raw)
101                self.assertIn("data: [DONE]", raw)
102
103    def test_object_mode_strict_json_and_truncation(self):
104        fmt = {"type": "json_object"}
105        self.assertEqual(self.chat('{"answer":4}', response_format=fmt)[0], 200)
106        for script in ('[]', '{"x":NaN}', '{"x":1,"x":2}', '{"x":1e999}', 'no json at all', '{"x":'):
107            self.assertEqual(self.chat(script, response_format=fmt)[0], 502)
108        # #762: the JSON object is taken out of a code fence or the prose around it (the object itself stays strict)
109        for script in ('```json\n{}\n```', 'Here it is: {"answer":4} - done'):
110            self.assertEqual(self.chat(script, response_format=fmt)[0], 200, script)
111        self.assertEqual(self.chat('{"answer":4}', response_format=fmt, max_tokens=5)[0], 502)
112        # Plain text callers retain normal streaming, without a JSON validation gate.
113        self.assertEqual(self.chat("Prose.", response_format={"type": "text"})[0], 200)
114
115    def test_latex_escape_repair_is_opt_in_and_only_after_a_strict_failure(self):
116        # #2893: \alpha is not a JSON escape. Off by default: still a 502. On: one retry after the strict parse failed.
117        bad = r'{"answer":"the angle \alpha and \gamma_0"}'
118        self.assertEqual(self.chat(bad, response_format={"type": "json_object"})[0], 502)
119        self.assertEqual(self.chat(bad, response_format={"type": "json_object", "repair_latex_escapes": False})[0], 502)
120        code, reply = self.chat(bad, response_format={"type": "json_object", "repair_latex_escapes": True})
121        self.assertEqual(code, 200)
122        self.assertEqual(json.loads(reply["choices"][0]["message"]["content"]),
123                         {"answer": "the angle \\alpha and \\gamma_0"})
124        # streaming asks for the same check before any content leaves
125        _, raw = self.chat(bad, stream=True, response_format={"type": "json_object", "repair_latex_escapes": True})
126        self.assertIn(r"\\alpha", raw)
127        # the repair does not hide what is wrong with the answer itself
128        fmt = {"type": "json_object", "repair_latex_escapes": True}
129        for script in ('[]', r'{"x":NaN}', r'{"a":"\alpha","a":2}', 'no json at all', r'{"x":"\alpha'):
130            self.assertEqual(self.chat(script, response_format=fmt)[0], 502, script)
131        self.assertEqual(self.chat(r'{"answer":"\alpha"}', response_format=fmt, max_tokens=5)[0], 502)
132
133    def test_latex_escape_repair_helper(self):
134        fix = structured.repair_latex_escapes
135        self.assertEqual(fix(r'{"a":"\alpha \gamma_0"}'), r'{"a":"\\alpha \\gamma_0"}')
136        for same in (r'{"a":"x\ny\t\"q\" \\ \/ \u00e9"}', '{"a": 1}', ''):
137            self.assertEqual(fix(same), same)
138        self.assertEqual(fix(r'{"a":"\u12"}'), r'{"a":"\\u12"}')        # \u without four hex digits
139        self.assertEqual(fix(r'{"a":"\\alpha"}'), r'{"a":"\\alpha"}')    # an escaped backslash is skipped as a pair
140        self.assertEqual(fix("\\"), "\\\\")                              # a lone trailing backslash
141        # \b is a valid escape: untouched, so it parses (as a backspace), as it does without the option
142        self.assertEqual(json.loads(fix(r'{"a":"\beta \alpha"}'))["a"], "\beta \\alpha")
143
144    def test_the_repair_option_reaches_the_responses_format(self):
145        from serve.responses import text_format
146        self.assertEqual(text_format({"text": {"format": {"type": "json_object", "repair_latex_escapes": True}}}),
147                         {"type": "json_object", "repair_latex_escapes": True})
148        self.assertEqual(text_format({"text": {"format": {"type": "json_object"}}}), {"type": "json_object"})
149
150    def test_rejected_schema_does_not_load_the_engine_or_retry(self):
151        with mock.patch.object(self.svc, "load") as load:
152            code, _ = self.chat(response_format={"type": "json_schema"})
153            self.assertEqual(code, 400)
154            load.assert_not_called()
155        self.engine = self.svc.engine = MockEngine(self.tok, "Markdown is not JSON", max_context=16384)
156        with mock.patch.object(self.engine, "generate", wraps=self.engine.generate) as generate:
157            self.assertEqual(self.chat()[0], 502)
158            self.assertEqual(generate.call_count, 1)
159
160    @unittest.skipUnless(HAVE_JSONSCHEMA, "jsonschema is not installed")
161    def test_invalid_schema_is_400_and_local_refs_work(self):
162        for schema in ({"type": "object", "properties": {"x": {"type": "invalid"}}},
163                       {"type": "object", "$ref": "https://other.example/schema"}):
164            fmt = {"type": "json_schema", "json_schema": {"name": "test", "strict": True, "schema": schema}}
165            self.assertEqual(self.chat(response_format=fmt)[0], 400)
166        schema = object_schema({"answer": {"$ref": "#/$defs/n"}})
167        schema["$defs"] = {"n": {"type": "integer"}}
168        fmt = {"type": "json_schema", "json_schema": {"name": "local", "schema": schema}}
169        self.assertEqual(self.chat('{"answer":4}', response_format=fmt)[0], 200)
170
171    def test_malformed_formats_and_tools_are_rejected_before_loading(self):
172        formats = ([], {"type": "unsupported"},
173                   {"type": "json_schema", "json_schema": {"schema": {"type": "object"}}},
174                   {"type": "json_schema", "json_schema": {"name": "x", "strict": "true", "schema": {"type": "object"}}})
175        with mock.patch.object(self.svc, "load") as load:
176            for fmt in formats:
177                with self.subTest(fmt=fmt):
178                    self.assertEqual(self.chat(response_format=fmt)[0], 400)
179            self.assertEqual(self.chat(tools=[{"type": "function", "function": {"name": "search", "parameters": {"type": "object"}}}])[0], 400)
180            self.assertEqual(self.chat(strata_mcp=True)[0], 400)
181            self.assertEqual(self.request("/v1/chat/completions", [])[0], 400)
182            load.assert_not_called()
183
184    def test_without_jsonschema_an_object_is_still_required(self):
185        # jsonschema is optional: without it json_schema answers are checked to be one JSON object, json_object
186        # never needs it, and nothing is imported at server start
187        with mock.patch.object(structured, "_jsonschema", False):
188            self.assertEqual(self.chat()[0], 200)
189            for script in ("## Film Plan - Photobooth", "[1, 2]"):
190                code, reply = self.chat(script)
191                self.assertEqual(code, 502, script)
192                self.assertEqual(reply["error"]["code"], "structured_output_failed")
193            self.assertEqual(self.chat('{"answer":4}', response_format={"type": "json_object"})[0], 200)
194
195    def test_root_unions_of_object_shapes_are_accepted(self):
196        # A root anyOf of object shapes (sent by apps written against llama.cpp's grammar path) still means
197        # "one JSON object", so it is accepted; a non-object answer is still refused.
198        claim = {"type": "object", "additionalProperties": False, "required": ["claim_text"],
199                 "properties": {"claim_text": {"type": "string", "minLength": 1}}}
200        empty = {"type": "object", "additionalProperties": False, "required": ["outcome"],
201                 "properties": {"outcome": {"type": "string", "enum": ["no_substantive_content"]}}}
202        schemas = [
203            {"anyOf": [claim, empty]},
204            {"oneOf": [claim, empty]},
205            {"allOf": [claim, {"required": ["claim_text"]}]},
206            {"$ref": "#/$defs/claim", "$defs": {"claim": claim}},
207            {"anyOf": [{"$ref": "#/$defs/claim"}, {"anyOf": [empty]}], "$defs": {"claim": claim}},
208        ]
209        for schema in schemas:
210            fmt = {"type": "json_schema", "json_schema": {"name": "union", "strict": True, "schema": schema}}
211            with self.subTest(schema=schema):
212                self.assertEqual(self.chat('{"claim_text":"The term is 12 months."}', response_format=fmt)[0], 200)
213                self.assertEqual(self.chat("[1, 2]", response_format=fmt)[0], 502)
214
215    def test_schemas_that_allow_non_objects_are_still_rejected(self):
216        obj = {"type": "object"}
217        schemas = [
218            {"type": "array", "items": obj},
219            {"type": "string"},
220            {"type": ["object", "null"]},
221            {"anyOf": [obj, {"type": "string"}]},
222            {"anyOf": []},
223            {"oneOf": [obj, {"type": "array"}]},
224            {"allOf": [{"type": "string"}]},
225            {"properties": {"x": {"type": "string"}}},           # no type: any JSON value validates
226            {"$ref": "#/$defs/a", "$defs": {"a": {"$ref": "#/$defs/a"}}},   # reference cycle
227            {"$ref": "#/$defs/missing", "$defs": {}},
228            {"$ref": "#/$defs/s", "$defs": {"s": {"type": "string"}}},
229        ]
230        with mock.patch.object(self.svc, "load") as load:
231            for schema in schemas:
232                fmt = {"type": "json_schema", "json_schema": {"name": "bad", "schema": schema}}
233                with self.subTest(schema=schema):
234                    code, reply = self.chat(response_format=fmt)
235                    self.assertEqual(code, 400)
236                    self.assertIn("only JSON objects", reply["error"]["message"])
237            load.assert_not_called()
238
239    def test_the_server_does_not_import_jsonschema_at_start(self):
240        import subprocess
241        import sys
242        code = ("import sys; import serve.server; "
243                "sys.exit(1 if any(m == 'jsonschema' or m.startswith('jsonschema.') for m in sys.modules) else 0)")
244        r = subprocess.run([sys.executable, "-c", code], cwd=str(Path(__file__).resolve().parents[1]))
245        self.assertEqual(r.returncode, 0)
246
247
248if __name__ == "__main__":
249    unittest.main()