okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6ca60e9a0
main
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 : 14import jsonschema # noqa: F401 15HAVE_JSONSCHEMA = True 16except ImportError :# optional: json_schema answers are then only checked to be one object 17HAVE_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 ): 26return {"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 ): 44def request (self ,path ,body = None ,headers = None ): 45req = urllib .request .Request (self .base + path ,data = json .dumps (body ).encode ()if body is not None else None , 46headers = {"Content-Type" :"application/json" ,** (headers or {})}) 47try : 48response = urllib .request .urlopen (req ,timeout = 10 ) 49except urllib .error .HTTPError as error : 50response = error 51with response : 52data = response .read ().decode () 53return response .status ,data if "event-stream" in response .headers .get ("Content-Type" ,"" )else json .loads (data ) 54 55def setUp (self ): 56self .tok = ByteTokenizer () 57self .engine = MockEngine (self .tok ,json .dumps (STORY ),max_context = 16384 ) 58self .svc = Service (self .engine ,self .tok ,ChatTemplate (Path (__file__ ).parent / "chat_template.jinja" )) 59self .httpd = serve (self .svc ,port = 0 ) 60self .base = f"http://127.0.0.1: { self . httpd . server_address [ 1 ] } " 61 62def tearDown (self ): 63self .httpd .shutdown () 64self .httpd .server_close () 65 66def chat (self ,script = None ,** kwargs ): 67if script is not None : 68self .engine = self .svc .engine = MockEngine (self .tok ,script ,max_context = 16384 ) 69req = {"messages" : [{"role" :"system" ,"content" :"Write a film plan." }, 70 {"role" :"user" ,"content" :"Photobooth. 15 seconds." }], 71"response_format" :FORMAT ,"reasoning_effort" :"none" ,** kwargs } 72return self .request ("/v1/chat/completions" ,req ) 73 74def test_h3_schema_success_and_stream_with_reasoning (self ): 75code ,reply = self .chat () 76self .assertEqual (code ,200 ) 77self .assertEqual (json .loads (reply ["choices" ][0 ]["message" ]["content" ]),STORY ) 78prompt = self .tok .decode (self .engine .last_prompt ) 79self .assertIn ("OUTPUT FORMAT REQUIREMENT" ,prompt ) 80self .assertIn ('"duration_ms"' ,prompt ) 81code ,raw = self .chat ("Consider the shot.</think>\n" + json .dumps (STORY ),stream = True ,reasoning_effort = "low" ) 82self .assertEqual (code ,200 ) 83chunks = [json .loads (line [6 :])for line in raw .splitlines ()if line .startswith ("data: {" )] 84content = "" .join (c ["choices" ][0 ]["delta" ].get ("content" ,"" )for c in chunks ) 85self .assertEqual (json .loads (content ),STORY ) 86self .assertIn ("reasoning_content" ,raw ) 87self .assertIn ("data: [DONE]" ,raw ) 88 89@ unittest . skipUnless ( HAVE_JSONSCHEMA , "jsonschema is not installed" ) 90def test_invalid_generation_is_an_error_and_never_streams_content (self ): 91for script in ("## Film Plan - Photobooth" ,'{"title":"Only a title"}' , 92json .dumps ({** STORY ,"extra" :True }), 93json .dumps ({** STORY ,"boxes" : [{** STORY ["boxes" ][0 ],"duration_ms" :"15000" }]})): 94with self .subTest (script = script ): 95code ,reply = self .chat (script ) 96self .assertEqual (code ,502 ) 97self .assertEqual (reply ["error" ]["code" ],"structured_output_failed" ) 98_ ,raw = self .chat (script ,stream = True ) 99self .assertIn ('"structured_output_failed"' ,raw ) 100self .assertNotIn ('"delta"' ,raw ) 101self .assertIn ("data: [DONE]" ,raw ) 102 103def test_object_mode_strict_json_and_truncation (self ): 104fmt = {"type" :"json_object" } 105self .assertEqual (self .chat ('{"answer":4}' ,response_format = fmt )[0 ],200 ) 106for script in ('[]' ,'{"x":NaN}' ,'{"x":1,"x":2}' ,'{"x":1e999}' ,'no json at all' ,'{"x":' ): 107self .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) 109for script in ('```json\n{}\n```' ,'Here it is: {"answer":4} - done' ): 110self .assertEqual (self .chat (script ,response_format = fmt )[0 ],200 ,script ) 111self .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. 113self .assertEqual (self .chat ("Prose." ,response_format = {"type" :"text" })[0 ],200 ) 114 115def 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. 117bad = r'{"answer":"the angle \alpha and \gamma_0"}' 118self .assertEqual (self .chat (bad ,response_format = {"type" :"json_object" })[0 ],502 ) 119self .assertEqual (self .chat (bad ,response_format = {"type" :"json_object" ,"repair_latex_escapes" :False })[0 ],502 ) 120code ,reply = self .chat (bad ,response_format = {"type" :"json_object" ,"repair_latex_escapes" :True }) 121self .assertEqual (code ,200 ) 122self .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 }) 126self .assertIn (r"\\alpha" ,raw ) 127# the repair does not hide what is wrong with the answer itself 128fmt = {"type" :"json_object" ,"repair_latex_escapes" :True } 129for script in ('[]' ,r'{"x":NaN}' ,r'{"a":"\alpha","a":2}' ,'no json at all' ,r'{"x":"\alpha' ): 130self .assertEqual (self .chat (script ,response_format = fmt )[0 ],502 ,script ) 131self .assertEqual (self .chat (r'{"answer":"\alpha"}' ,response_format = fmt ,max_tokens = 5 )[0 ],502 ) 132 133def test_latex_escape_repair_helper (self ): 134fix = structured .repair_latex_escapes 135self .assertEqual (fix (r'{"a":"\alpha \gamma_0"}' ),r'{"a":"\\alpha \\gamma_0"}' ) 136for same in (r'{"a":"x\ny\t\"q\" \\ \/ \u00e9"}' ,'{"a": 1}' ,'' ): 137self .assertEqual (fix (same ),same ) 138self .assertEqual (fix (r'{"a":"\u12"}' ),r'{"a":"\\u12"}' )# \u without four hex digits 139self .assertEqual (fix (r'{"a":"\\alpha"}' ),r'{"a":"\\alpha"}' )# an escaped backslash is skipped as a pair 140self .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 142self .assertEqual (json .loads (fix (r'{"a":"\beta \alpha"}' ))["a" ],"\beta \\alpha" ) 143 144def test_the_repair_option_reaches_the_responses_format (self ): 145from serve .responses import text_format 146self .assertEqual (text_format ({"text" : {"format" : {"type" :"json_object" ,"repair_latex_escapes" :True }}}), 147 {"type" :"json_object" ,"repair_latex_escapes" :True }) 148self .assertEqual (text_format ({"text" : {"format" : {"type" :"json_object" }}}), {"type" :"json_object" }) 149 150def test_rejected_schema_does_not_load_the_engine_or_retry (self ): 151with mock .patch .object (self .svc ,"load" )as load : 152code ,_ = self .chat (response_format = {"type" :"json_schema" }) 153self .assertEqual (code ,400 ) 154load .assert_not_called () 155self .engine = self .svc .engine = MockEngine (self .tok ,"Markdown is not JSON" ,max_context = 16384 ) 156with mock .patch .object (self .engine ,"generate" ,wraps = self .engine .generate )as generate : 157self .assertEqual (self .chat ()[0 ],502 ) 158self .assertEqual (generate .call_count ,1 ) 159 160@ unittest . skipUnless ( HAVE_JSONSCHEMA , "jsonschema is not installed" ) 161def test_invalid_schema_is_400_and_local_refs_work (self ): 162for schema in ({"type" :"object" ,"properties" : {"x" : {"type" :"invalid" }}}, 163 {"type" :"object" ,"$ref" :"https://other.example/schema" }): 164fmt = {"type" :"json_schema" ,"json_schema" : {"name" :"test" ,"strict" :True ,"schema" :schema }} 165self .assertEqual (self .chat (response_format = fmt )[0 ],400 ) 166schema = object_schema ({"answer" : {"$ref" :"#/$defs/n" }}) 167schema ["$defs" ]= {"n" : {"type" :"integer" }} 168fmt = {"type" :"json_schema" ,"json_schema" : {"name" :"local" ,"schema" :schema }} 169self .assertEqual (self .chat ('{"answer":4}' ,response_format = fmt )[0 ],200 ) 170 171def test_malformed_formats_and_tools_are_rejected_before_loading (self ): 172formats = ([], {"type" :"unsupported" }, 173 {"type" :"json_schema" ,"json_schema" : {"schema" : {"type" :"object" }}}, 174 {"type" :"json_schema" ,"json_schema" : {"name" :"x" ,"strict" :"true" ,"schema" : {"type" :"object" }}}) 175with mock .patch .object (self .svc ,"load" )as load : 176for fmt in formats : 177with self .subTest (fmt = fmt ): 178self .assertEqual (self .chat (response_format = fmt )[0 ],400 ) 179self .assertEqual (self .chat (tools = [{"type" :"function" ,"function" : {"name" :"search" ,"parameters" : {"type" :"object" }}}])[0 ],400 ) 180self .assertEqual (self .chat (strata_mcp = True )[0 ],400 ) 181self .assertEqual (self .request ("/v1/chat/completions" , [])[0 ],400 ) 182load .assert_not_called () 183 184def 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 187with mock .patch .object (structured ,"_jsonschema" ,False ): 188self .assertEqual (self .chat ()[0 ],200 ) 189for script in ("## Film Plan - Photobooth" ,"[1, 2]" ): 190code ,reply = self .chat (script ) 191self .assertEqual (code ,502 ,script ) 192self .assertEqual (reply ["error" ]["code" ],"structured_output_failed" ) 193self .assertEqual (self .chat ('{"answer":4}' ,response_format = {"type" :"json_object" })[0 ],200 ) 194 195def 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. 198claim = {"type" :"object" ,"additionalProperties" :False ,"required" : ["claim_text" ], 199"properties" : {"claim_text" : {"type" :"string" ,"minLength" :1 }}} 200empty = {"type" :"object" ,"additionalProperties" :False ,"required" : ["outcome" ], 201"properties" : {"outcome" : {"type" :"string" ,"enum" : ["no_substantive_content" ]}}} 202schemas = [ 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 ] 209for schema in schemas : 210fmt = {"type" :"json_schema" ,"json_schema" : {"name" :"union" ,"strict" :True ,"schema" :schema }} 211with self .subTest (schema = schema ): 212self .assertEqual (self .chat ('{"claim_text":"The term is 12 months."}' ,response_format = fmt )[0 ],200 ) 213self .assertEqual (self .chat ("[1, 2]" ,response_format = fmt )[0 ],502 ) 214 215def test_schemas_that_allow_non_objects_are_still_rejected (self ): 216obj = {"type" :"object" } 217schemas = [ 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 ] 230with mock .patch .object (self .svc ,"load" )as load : 231for schema in schemas : 232fmt = {"type" :"json_schema" ,"json_schema" : {"name" :"bad" ,"schema" :schema }} 233with self .subTest (schema = schema ): 234code ,reply = self .chat (response_format = fmt ) 235self .assertEqual (code ,400 ) 236self .assertIn ("only JSON objects" ,reply ["error" ]["message" ]) 237load .assert_not_called () 238 239def test_the_server_does_not_import_jsonschema_at_start (self ): 240import subprocess 241import sys 242code = ("import sys; import serve.server; " 243"sys.exit(1 if any(m == 'jsonschema' or m.startswith('jsonschema.') for m in sys.modules) else 0)" ) 244r = subprocess .run ([sys .executable ,"-c" ,code ],cwd = str (Path (__file__ ).resolve ().parents [1 ])) 245self .assertEqual (r .returncode ,0 ) 246 247 248if __name__ == "__main__" : 249unittest .main ()