okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
d9042a16b
main
1"""Read-only local inventory of setup-written model run configs.""" 2 3import io 4import json 5import os 6import struct 7import tempfile 8import threading 9import unittest 10from contextlib import redirect_stdout 11from http .server import BaseHTTPRequestHandler ,ThreadingHTTPServer 12from pathlib import Path 13from unittest import mock 14 15from strata_cli .cli import main 16 17 18def gguf_fixture (* ,architecture = "qwen4exp" ,tokenizer = True ,expert_type = 42 , 19overlapping_tensors = False )-> bytes : 20def string (value ): 21raw = value .encode () 22return struct .pack ("<Q" ,len (raw ))+ raw 23 24pairs = [("general.architecture" ,8 ,string (architecture ))] 25if tokenizer : 26pairs += [("tokenizer.ggml.model" ,8 ,string ("gpt2" )), 27 ("tokenizer.ggml.tokens" ,9 ,struct .pack ("<IQ" ,8 ,1 )+ string ("a" )), 28 ("tokenizer.ggml.merges" ,9 ,struct .pack ("<IQ" ,8 ,1 )+ string ("a b" ))] 29header = (b"GGUF" + struct .pack ("<IQQ" ,3 ,2 if overlapping_tensors else 1 ,len (pairs ))+ 30b"" .join (string (key )+ struct .pack ("<I" ,kind )+ value for key ,kind ,value in pairs )) 31elements ,payload_bytes = (64 ,18 )if expert_type == 42 else (256 ,144 ) 32header += string ("blk.0.ffn_gate_exps.weight" )+ struct .pack ( 33"<IQIQ" ,1 ,elements ,expert_type ,0 ) 34if overlapping_tensors : 35header += string ("blk.1.ffn_gate_exps.weight" )+ struct .pack ( 36"<IQIQ" ,1 ,elements ,expert_type ,0 ) 37return header + b"\x00" * (- len (header )% 32 )+ b"\x00" * payload_bytes 38 39 40class ModelInventoryTests (unittest .TestCase ): 41def setUp (self ): 42self .temp = tempfile .TemporaryDirectory () 43self .addCleanup (self .temp .cleanup ) 44self .root = Path (self .temp .name ) 45engine = self .root / "engine" 46engine .write_bytes (b"fake engine" ) 47engine .chmod (0o700 ) 48tokenizer = self .root / "tokenizer" 49tokenizer .mkdir () 50for name in ("vocab.json" ,"merges.txt" ,"token_type.json" ): 51 (tokenizer / name ).write_bytes (b"placeholder" ) 52pack = self .root / "pack" 53pack .mkdir () 54self .config = self .root / "strata-demo.json" 55self .config .write_text (json .dumps ({ 56"exe" :str (engine ),"tokenizer" :str (tokenizer ), 57"args" : ["--pack" ,str (pack ),"--max-context" ,"32768" ], 58"backend" :"cuda" ,"model_name" :"Demo model" ,"api_key" :"do-not-disclose" , 59 }),encoding = "utf-8" ) 60 61def command (self ,* args ): 62output = io .StringIO () 63with redirect_stdout (output ): 64code = main (["models" ,* args ,"--install-dir" ,str (self .root ),"--output" ,"json" ]) 65raw = output .getvalue () 66self .assertNotIn ("do-not-disclose" ,raw ) 67return code ,json .loads (raw ) 68 69def test_list_and_inspect_are_read_only_and_do_not_claim_compatibility (self ): 70 (self .root / "strata-demo.shared-settings.json" ).write_text ("{}" ,encoding = "utf-8" ) 71before = {path .name : (path .read_bytes (),path .stat ().st_mtime_ns ) 72for path in self .root .iterdir ()if path .is_file ()} 73code ,listed = self .command ("list" ,"--installed" ) 74self .assertEqual (code ,0 ) 75self .assertEqual (listed ["model_count" ],1 ) 76item = listed ["models" ][0 ] 77self .assertEqual (item ["id" ],"demo" ) 78self .assertEqual (item ["component_status" ],"present" ) 79self .assertEqual (item ["context_tokens" ],32768 ) 80self .assertEqual (item ["execution_compatibility" ],"unverified" ) 81self .assertNotIn ("args" ,item ) 82code ,inspected = self .command ("inspect" ,"demo" ) 83self .assertEqual (code ,0 ) 84self .assertEqual (inspected ["model" ]["source_sha256" ],item ["source_sha256" ]) 85self .assertTrue (inspected ["components" ]["ok" ]) 86after = {path .name : (path .read_bytes (),path .stat ().st_mtime_ns ) 87for path in self .root .iterdir ()if path .is_file ()} 88self .assertEqual (after ,before ) 89 90def test_missing_and_malformed_components_are_distinguished (self ): 91 (self .root / "tokenizer" / "vocab.json" ).unlink () 92code ,listed = self .command ("list" ,"--installed" ) 93self .assertEqual (code ,0 ) 94self .assertEqual (listed ["models" ][0 ]["component_status" ],"missing_or_invalid" ) 95self .assertIn ("COMPONENT_MISSING" ,listed ["models" ][0 ]["issue_codes" ]) 96# #3478: the list names what is missing, so the app can say which files instead of only "some files are missing" 97self .assertEqual ([(m ["part" ],m ["file" ],m ["status" ])for m in listed ["models" ][0 ]["missing" ]], 98 [("tokenizer/vocab.json" ,"vocab.json" ,"missing" )]) 99 (self .root / "strata-broken.json" ).write_text ("{broken" ,encoding = "utf-8" ) 100code ,listed = self .command ("list" ,"--installed" ) 101self .assertEqual (code ,0 ) 102self .assertEqual (listed ["model_count" ],2 ) 103self .assertEqual (listed ["models" ][0 ]["component_status" ],"invalid" ) 104code ,error = self .command ("inspect" ,"broken" ) 105self .assertEqual (code ,5 ) 106self .assertFalse (error ["ok" ]) 107 108def test_invalid_ids_and_symlink_configs_are_rejected (self ): 109code ,error = self .command ("inspect" ,"../demo" ) 110self .assertEqual (code ,2 ) 111self .assertFalse (error ["ok" ]) 112if os .name == "posix" : 113 (self .root / "strata-link.json" ).symlink_to (self .config ) 114code ,listed = self .command ("list" ,"--installed" ) 115self .assertEqual (code ,0 ) 116self .assertEqual (next (row for row in listed ["models" ]if row ["id" ]== "link" ) 117 ["component_status" ],"invalid" ) 118code ,error = self .command ("inspect" ,"link" ) 119self .assertEqual (code ,5 ) 120self .assertFalse (error ["ok" ]) 121 122def test_install_dir_must_be_absolute (self ): 123output = io .StringIO () 124with redirect_stdout (output ): 125code = main (["models" ,"list" ,"--installed" ,"--install-dir" ,"relative" ,"--output" ,"json" ]) 126self .assertEqual (code ,5 ) 127self .assertFalse (json .loads (output .getvalue ())["ok" ]) 128 129def test_served_inventory_uses_read_only_telemetry_connection (self ): 130snapshot = {"model" : {"id" :"served-demo" ,"loaded" :True }, 131"instance" : {"id" :"instance-123" }} 132output = io .StringIO () 133with mock .patch ("strata_cli.client.Endpoint.snapshot" ,return_value = snapshot )as fetch , \ 134redirect_stdout (output ): 135code = main (["models" ,"list" ,"--served" ,"--url" ,"http://127.0.0.1:8095" , 136"--output" ,"json" ]) 137result = json .loads (output .getvalue ()) 138self .assertEqual (code ,0 ) 139self .assertEqual (result ["scope" ],"served_current_instance" ) 140self .assertEqual (result ["models" ], [{"id" :"served-demo" ,"loaded" :True , 141"instance_id" :"instance-123" , 142"execution_compatibility" :"unverified" }]) 143fetch .assert_called_once_with () 144output = io .StringIO () 145with mock .patch ("strata_cli.client.Endpoint.snapshot" ,return_value = { 146"model" : {"id" :None ,"loaded" :None },"instance" : {"id" :"i" }}), \ 147redirect_stdout (output ): 148code = main (["models" ,"list" ,"--served" ,"--url" ,"http://127.0.0.1:8095" , 149"--output" ,"json" ]) 150self .assertEqual (code ,0 ) 151self .assertEqual (json .loads (output .getvalue ())["models" ], []) 152 153def test_served_inventory_reaches_telemetry_with_read_only_key (self ): 154seen = [] 155 156class Handler (BaseHTTPRequestHandler ): 157def do_GET (self ): 158seen .append ((self .path ,self .headers .get ("Authorization" ))) 159if self .path != "/v1/telemetry" or self .headers .get ("Authorization" )!= "Bearer read-only" : 160self .send_error (403 ) 161return 162body = json .dumps ({"schema_version" :1 , 163"instance" : {"id" :"mock-1" ,"state" :"ready" }, 164"model" : {"id" :"example" ,"loaded" :False }}).encode () 165self .send_response (200 ) 166self .send_header ("Content-Type" ,"application/json" ) 167self .send_header ("Content-Length" ,str (len (body ))) 168self .end_headers () 169self .wfile .write (body ) 170 171def log_message (self ,* args ): 172pass 173 174server = ThreadingHTTPServer (("127.0.0.1" ,0 ),Handler ) 175thread = threading .Thread (target = server .serve_forever ,daemon = True ) 176thread .start () 177try : 178output = io .StringIO () 179with mock .patch .dict (os .environ , {"STRATA_TELEMETRY_KEY" :"read-only" }), \ 180redirect_stdout (output ): 181code = main (["models" ,"list" ,"--served" ,"--url" , 182f"http://127.0.0.1: { server . server_port } " , 183"--credential-env" ,"STRATA_TELEMETRY_KEY" ,"--output" ,"json" ]) 184self .assertEqual (code ,0 ) 185self .assertEqual (json .loads (output .getvalue ())["models" ][0 ]["loaded" ],False ) 186self .assertEqual (seen , [("/v1/telemetry" ,"Bearer read-only" )]) 187self .assertNotIn ("read-only" ,output .getvalue ()) 188finally : 189server .shutdown () 190server .server_close () 191thread .join (timeout = 2 ) 192 193def test_connection_flags_require_served_scope (self ): 194output = io .StringIO () 195with redirect_stdout (output ): 196code = main (["models" ,"list" ,"--installed" ,"--url" ,"https://example.invalid" , 197"--output" ,"json" ]) 198self .assertEqual (code ,2 ) 199self .assertFalse (json .loads (output .getvalue ())["ok" ]) 200 201def test_import_plan_inspects_shards_without_adopting_or_copying (self ): 202source = self .root / "source" 203source .mkdir () 204first = source / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf" 205second = source / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf" 206for path in (first ,second ): 207path .write_bytes (gguf_fixture (tokenizer = path == first )) 208 (source / "mmproj-Qwen3.8-Flash-Next-BF16.gguf" ).write_bytes (b"auxiliary" ) 209before = {path .name : (path .read_bytes (),path .stat ().st_mtime_ns ) 210for path in source .iterdir ()} 211output = io .StringIO () 212with redirect_stdout (output ): 213code = main (["models" ,"import" ,str (source ),"--plan" ,"--output" ,"json" ]) 214self .assertEqual (code ,0 ) 215plan = json .loads (output .getvalue ())["plan" ] 216self .assertEqual (plan ["file_count" ],2 ) 217self .assertEqual (plan ["file_set_status" ],"plausible" ) 218self .assertFalse (plan ["would_write" ]) 219self .assertEqual (plan ["execution_compatibility" ],"unverified" ) 220self .assertEqual (plan ["metadata" ]["architecture" ],"qwen4exp" ) 221self .assertEqual (plan ["metadata" ]["tokenizer_model" ],"gpt2" ) 222self .assertTrue (plan ["metadata" ]["payload_extent_valid" ]) 223self .assertEqual (plan ["metadata" ]["tensor_types" ], {"Q2_0" :1 }) 224self .assertEqual (plan ["observed_expert_types" ], ["Q2_0" ]) 225self .assertEqual (plan ["candidate_selection" ]["family" ],"qwen" ) 226self .assertEqual (plan ["candidate_selection" ]["model" ],"Q2_0" ) 227self .assertEqual (len (plan ["ignored_auxiliary_files" ]),1 ) 228self .assertEqual ({path .name : (path .read_bytes (),path .stat ().st_mtime_ns ) 229for path in source .iterdir ()},before ) 230second .unlink () 231output = io .StringIO () 232with redirect_stdout (output ): 233code = main (["models" ,"import" ,str (first ),"--plan" ,"--output" ,"json" ]) 234self .assertEqual (code ,5 ) 235self .assertFalse (json .loads (output .getvalue ())["ok" ]) 236self .assertEqual (json .loads (output .getvalue ())["plan" ]["file_set_status" ], 237"invalid_or_incomplete" ) 238 239def test_import_plan_rejects_symlink_and_wrong_magic (self ): 240wrong = self .root / "bad.gguf" 241wrong .write_bytes (b"NOTG\x03\x00\x00\x00" ) 242output = io .StringIO () 243with redirect_stdout (output ): 244code = main (["models" ,"import" ,str (wrong ),"--plan" ,"--output" ,"json" ]) 245self .assertEqual (code ,5 ) 246self .assertFalse (json .loads (output .getvalue ())["ok" ]) 247self .assertEqual (json .loads (output .getvalue ())["plan" ]["file_set_status" ], 248"invalid_or_incomplete" ) 249if os .name == "posix" : 250link = self .root / "link.gguf" 251link .symlink_to (wrong ) 252output = io .StringIO () 253with redirect_stdout (output ): 254code = main (["models" ,"import" ,str (link ),"--plan" ,"--output" ,"json" ]) 255self .assertEqual (code ,5 ) 256self .assertFalse (json .loads (output .getvalue ())["ok" ]) 257 258def test_import_plan_rejects_other_architecture_and_bounded_metadata (self ): 259candidate = self .root / "other.gguf" 260candidate .write_bytes (gguf_fixture (architecture = "llama" )) 261output = io .StringIO () 262with redirect_stdout (output ): 263code = main (["models" ,"import" ,str (candidate ),"--plan" ,"--output" ,"json" ]) 264self .assertEqual (code ,5 ) 265self .assertIn ("unsupported_or_missing_architecture" ,json .loads (output .getvalue ())["plan" ]["issues" ]) 266# A malicious metadata count must fail before allocating or reading tensor data. 267candidate .write_bytes (b"GGUF" + struct .pack ("<IQQ" ,3 ,1 ,1_000_000_000 )) 268output = io .StringIO () 269with redirect_stdout (output ): 270code = main (["models" ,"import" ,str (candidate ),"--plan" ,"--output" ,"json" ]) 271self .assertEqual (code ,5 ) 272self .assertEqual (json .loads (output .getvalue ())["plan" ]["file_set_status" ],"invalid_or_incomplete" ) 273key = b"tokenizer.ggml.tokens" 274candidate .write_bytes (b"GGUF" + struct .pack ("<IQQ" ,3 ,1 ,1 )+ 275struct .pack ("<Q" ,len (key ))+ key + 276struct .pack ("<IIQ" ,9 ,8 ,500_001 )) 277output = io .StringIO () 278with redirect_stdout (output ): 279code = main (["models" ,"import" ,str (candidate ),"--plan" ,"--output" ,"json" ]) 280self .assertEqual (code ,5 ) 281self .assertIn ("inspection limit" ,json .dumps (json .loads (output .getvalue ())["plan" ]["issues" ])) 282 283def test_import_plan_rejects_truncated_tensor_payload (self ): 284candidate = self .root / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf" 285candidate .write_bytes (gguf_fixture ()[:- 4 ]) 286other = self .root / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf" 287other .write_bytes (gguf_fixture (tokenizer = False )) 288output = io .StringIO () 289with redirect_stdout (output ): 290code = main (["models" ,"import" ,str (candidate ),"--plan" ,"--output" ,"json" ]) 291self .assertEqual (code ,5 ) 292self .assertIn ("payload is shorter" ,json .dumps (json .loads (output .getvalue ())["plan" ]["issues" ])) 293 294def test_import_plan_rejects_unexpected_expert_quantization (self ): 295source = self .root / "quant" 296source .mkdir () 297names = [source / f"Qwen3.8-Flash-Next-GSQ-RCO-Q2_0- { i :05d } -of-00002.gguf" for i in (1 ,2 )] 298names [0 ].write_bytes (gguf_fixture (expert_type = 12 ))# Q4_K under a Q2_0 filename 299names [1 ].write_bytes (gguf_fixture (tokenizer = False )) 300output = io .StringIO () 301with redirect_stdout (output ): 302code = main (["models" ,"import" ,str (source ),"--plan" ,"--output" ,"json" ]) 303self .assertEqual (code ,5 ) 304self .assertIn ("missing_or_unexpected_expert_quantization" , 305json .loads (output .getvalue ())["plan" ]["issues" ]) 306 307def test_import_plan_rejects_overlapping_tensor_ranges (self ): 308source = self .root / "overlap" 309source .mkdir () 310first = source / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf" 311second = source / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf" 312first .write_bytes (gguf_fixture (overlapping_tensors = True )) 313second .write_bytes (gguf_fixture (tokenizer = False )) 314output = io .StringIO () 315with redirect_stdout (output ): 316code = main (["models" ,"import" ,str (source ),"--plan" ,"--output" ,"json" ]) 317self .assertEqual (code ,5 ) 318self .assertIn ("byte ranges overlap" ,json .dumps (json .loads (output .getvalue ())["plan" ]["issues" ])) 319 320def test_import_plan_does_not_advertise_setup_unsupported_variant (self ): 321source = self .root / "unsupported" 322source .mkdir () 323for index in (1 ,2 ): 324 (source / f"Swift-Qwen3.8-Flash-Next-GSQ-RCO-Q2_0- { index :05d } -of-00002.gguf" ).write_bytes ( 325gguf_fixture (tokenizer = index == 1 )) 326output = io .StringIO () 327with redirect_stdout (output ): 328code = main (["models" ,"import" ,str (source ),"--plan" ,"--output" ,"json" ]) 329self .assertEqual (code ,5 ) 330plan = json .loads (output .getvalue ())["plan" ] 331self .assertIsNone (plan ["candidate_selection" ]) 332self .assertIn ("unrecognized_or_unsupported_model_variant" ,plan ["issues" ])