okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1"""A Qwen4 model of its own shape runs on its own engine component (strata_control/shape_engine.py), picked by the model, beside the Strata engine. 2 3What these tests pin: 4* the names: shape q4_lite, component strata-q4-lite, feed model family qwen4exp_q4_lite, run config reference component:strata-q4-lite; 5* packaging: package_engine --shape makes a package whose manifest id is the shape's component; read as the Strata engine it is refused, so an older Control (which reads only 6strata-engine) ignores one put into its engine folder by hand; a normal package never claims a shape; 7* the feed: member shape_engines, parsed, never mixed into ``engine``; feed_tool packs and lists it and refuses a model of a shape that has no engine; 8* the install (a local signed feed over loopback, a stub engine, a throwaway key): the package is fetched, checked (signature, hashes, shape), placed in 9<components>/shapes/<shape>/engine/, started once, and the Strata engine's files are byte for byte what they were; a bad package or a failed start changes nothing; 10* use: component:strata-q4-lite resolves to that engine, component:strata-engine still to the Strata engine; a missing shape engine is a plain refusal, not a fetch; 11* update: `strata update` brings an installed shape engine up to date beside the older one and prunes beyond two; a PC with none has no such step; 12* older Controls: the feed.py of the Control before this (git) reads the same feed as one without the new member and does not offer the model. 13""" 14from __future__import annotations 15 16import base64 17import hashlib 18import importlib .util 19import json 20import os 21import shutil 22import subprocess 23import sys 24import tempfile 25import unittest 26from pathlib import Path 27from unittest import mock 28 29ROOT = Path (__file__ ).resolve ().parents [2 ] 30sys .path .insert (0 ,str (ROOT )) 31sys .path .insert (0 ,str (ROOT / "packaging" )) 32 33import feed_tool # noqa: E402 34import package_engine # noqa: E402 35from strata_control import components ,engine_component as ec ,feed as feedmod ,shape_engine ,signing ,updater # noqa: E402 36from strata_control .targets import host_platform # noqa: E402 37from tests .terminal import update_fixture as fx # noqa: E402 38 39REV = "0123456789abcdef0123456789abcdef01234567" 40SHAPE = "q4_lite" 41COMP = "strata-q4-lite" 42EXE = shape_engine .exe_name () 43 44 45def stub_source (parent :Path ,version :str ,* ,text :str = "stub strata" ,padding :int = 0 )-> Path : 46src = parent / f"src- { version } " 47src .mkdir (parents = True ) 48 (src / EXE ).write_bytes (f" { text } { version } " .encode ()+ (os .urandom (padding )if padding else b"x" * 100 )) 49 (src / ("cudart64_13.dll" if os .name == "nt" else "libcudart.so.13" )).write_bytes (b"a runtime library " * 50 ) 50return src 51 52 53def build (parent :Path ,version :str ,key :dict | None ,* ,shape :str = SHAPE ,padding :int = 0 ,min_runtime :str | None = None )-> Path : 54out = parent / "built" 55out .mkdir (parents = True ,exist_ok = True ) 56folder = package_engine .build (stub_source (parent ,version ,padding = padding ),"cuda" ,version ,components .host_platform (),out ,entry = EXE ,archs = ("sm_86" ,), 57min_driver = {"nvidia" :"580.65" },build_id = f" { shape or 'plain' } - { version } " ,variant = "cuda13" ,shape = shape ,min_runtime = min_runtime ) 58if key is not None : 59feed_tool .sign_package (folder ,key ) 60return folder 61 62 63def tree (d :Path )-> str : 64h = hashlib .sha256 () 65for p in sorted (Path (d ).rglob ("*" )): 66if p .is_file (): 67h .update (str (p .relative_to (d )).encode ()+ p .read_bytes ()) 68return h .hexdigest () 69 70 71def model_entry (** kw )-> dict : 72m = {"id" :"q4lite-test" ,"title" :"Qwen4 Lite Test" ,"by" :"Qwen" ,"about" :"a test model" ,"licence" :"Apache 2.0" , 73"licence_url" :"https://huggingface.co/test/q4lite" ,"family" :shape_engine .family_of (SHAPE ),"repo" :"test/Q4Lite-GGUF" ,"revision" :REV , 74"drafter" :"none" ,"context" :131072 , 75"quants" : [{"name" :"Q4_K_M" ,"about" :"4-bit" ,"ram_gb" :8 ,"arena_gb" :2.5 , 76"files" : [{"name" :"Q4Lite-Q4_K_M.gguf" ,"size" :1000 ,"sha256" :"a" * 64 }]}]} 77m .update (kw ) 78return m 79 80 81class Base (unittest .TestCase ): 82def setUp (self ): 83self .tmp = tempfile .TemporaryDirectory (prefix = "strata-shape-" ) 84self .addCleanup (self .tmp .cleanup ) 85self .root = Path (self .tmp .name ) 86self .key = fx .make_key () 87trust = self .root / "trust.json" 88trust .write_text (json .dumps ({"keys" : [signing .public_part (self .key )]})) 89self .comp = self .root / "c" 90for p in (mock .patch .dict (os .environ , {"STRATA_UPDATE_TRUSTED_KEYS" :str (trust ),"STRATA_COMPONENTS_DIR" :str (self .comp )}), 91mock .patch .object (signing ,"BUILTIN_KEYS" ,self .root / "none.json" ), 92mock .patch .object (ec ,"cuda_archs_present" ,return_value = ["sm_86" ]), 93mock .patch .object (ec ,"nvidia_driver_version" ,return_value = "610.47" ), 94mock .patch .object (ec ,"detect_backend" ,return_value = ("cuda" ,"test" ))): 95p .start () 96self .addCleanup (p .stop ) 97self .addCleanup (ec .register_signature_verifier ,None ) 98self .hw = {"platform" :host_platform (),"backend" :"cuda" ,"runtime" :None ,"nvidia_driver" :"610.47" ,"cuda_archs" : ["sm_86" ],"gfx" : []} 99self .release = self .root / "release" 100self .release .mkdir () 101self .server = fx .FeedServer (self .release ) 102self .server .__enter__ () 103self .addCleanup (self .server .__exit__ ) 104self .url = self .server .url + "/strata-feed.json" 105# the Strata engine of this PC: a signed stub package in <components>/engine, whose bytes must never change 106plain = build (self .root / "plain" ,"0.1.58" ,self .key ,shape = "" ) 107 (self .comp / "engine" ).mkdir (parents = True ) 108shutil .copytree (plain ,self .comp / "engine" / plain .name ) 109self .strata_before = tree (self .comp / "engine" ) 110 111def publish (self ,* versions ,shape :str = SHAPE ,models = None ,sequence = 1 ,key = None ,extra_members = None ): 112shutil .rmtree (self .release ,ignore_errors = True ) 113 (self .release / "shapes" ).mkdir (parents = True ) 114self .published = getattr (self ,"published" ,0 )+ 1 115for v in versions : 116folder = build (self .root / f"pub- { shape } - { v } - { self . published } " ,v ,key or self .key ,shape = shape ) 117feed_tool .pack_engine (folder ,self .release / "shapes" ,url_prefix = "shapes/" ) 118if models : 119 (self .release / "models" ).mkdir () 120for m in models : 121 (self .release / "models" / f" { m [ 'id' ] } .entry.json" ).write_text (json .dumps (m )) 122return feed_tool .build_feed (self .release ,key = self .key ,sequence = sequence ,shapes_dir = self .release / "shapes" if versions else None , 123models_dir = self .release / "models" if models else None ) 124 125def ensure (self ,lines = None ,** kw ): 126out = []if lines is None else lines 127return shape_engine .ensure (SHAPE ,self .url ,components = self .comp ,hardware = self .hw ,emit = out .append ,** kw ) 128 129def folders (self ): 130return sorted (p .name .split ("-" )[0 ]for p in (self .comp / "shapes" / SHAPE / "engine" ).iterdir ()if p .is_dir ()) 131 132 133class Names (unittest .TestCase ): 134def test_a_shape_has_one_component_one_family_one_reference (self ): 135self .assertEqual (shape_engine .component_id ("q4_lite" ),"strata-q4-lite" ) 136self .assertEqual (shape_engine .shape_of_component ("strata-q4-lite" ),"q4_lite" ) 137self .assertEqual (shape_engine .family_of ("q4_lite" ),"qwen4exp_q4_lite" ) 138self .assertEqual (shape_engine .shape_of_family ("qwen4exp_q4_lite" ),"q4_lite" ) 139self .assertEqual (shape_engine .reference ("q4_lite" ),"component:strata-q4-lite" ) 140self .assertEqual (ec .REFERENCE_PREFIX + COMP ,shape_engine .reference (SHAPE )) 141 142def test_what_is_not_a_shape_is_none (self ): 143for family in ("qwen4exp" ,"qwen35moe" ,"qwen4exp_" ,"qwen4exp_Q4" ,"qwen4exp_q4-lite" ,"qwen4exp_" + "x" * 30 ,None ,7 ): 144self .assertIsNone (shape_engine .shape_of_family (family ),family ) 145for comp in ("strata-engine" ,"strata-dsv41" ,"strata-control" ,"engine" ,"strata-" ,"strata-q4_lite" ,"strata-Q4-lite" ,None ): 146self .assertIsNone (shape_engine .shape_of_component (comp ),comp ) 147 148def test_a_shape_never_becomes_a_component_that_means_something_else (self ): 149for shape in ("engine" ,"dsv41" ,"control" ,"vision" ,"device" ): 150self .assertFalse (shape_engine .valid (shape ),shape ) 151for shape in ("" ,"q" ,"Q4_lite" ,"q4-lite" ,"q4__lite" ,"q4_lite_" ,"1q4" ,"q4 lite" ,"q4/lite" ,"x" * 24 ): 152self .assertFalse (shape_engine .valid (shape ),repr (shape )) 153for shape in ("q4_lite" ,"q4_mid" ,"q4_deep" ,"q4_big" ,"qwen4_a" ,"x" * 23 ): 154self .assertTrue (shape_engine .valid (shape ),shape ) 155self .assertLessEqual (len (shape_engine .family_of ("x" * 23 )),32 ,"a family name must fit the feed's family pattern" ) 156 157 158class Packaging (Base ): 159def test_a_shape_package_is_its_own_component (self ): 160folder = build (self .root / "p" ,"0.1.59" ,self .key ) 161raw = json .loads ((folder / ec .MANIFEST ).read_text ()) 162self .assertEqual ((raw ["id" ],raw ["name" ],raw ["shape" ]), (COMP ,COMP ,SHAPE )) 163comp = ec .read_manifest (folder ,COMP ) 164self .assertEqual ((comp .shape ,comp .id ), (SHAPE ,COMP )) 165self .assertEqual (ec .read_manifest_any (folder ).shape ,SHAPE ) 166self .assertEqual (comp .to_dict ()["shape" ],SHAPE ) 167 168def test_it_is_not_read_as_the_strata_engine_so_an_older_control_ignores_it (self ): 169folder = build (self .root / "p" ,"0.1.59" ,self .key ) 170with self .assertRaises (ec .ComponentProblem )as ctx : 171ec .read_manifest (folder )# what a Control from before this reads, and what the Strata engine's scan reads 172self .assertIn ("not an engine component" ,str (ctx .exception )) 173wrong = shape_engine .component_id ("q4_mid" ) 174with self .assertRaises (ec .ComponentProblem ): 175ec .read_manifest (folder ,wrong )# the id and the shape must agree 176 (self .comp / "engine" / folder .name ).parent .mkdir (parents = True ,exist_ok = True ) 177shutil .copytree (folder ,self .comp / "engine" / folder .name )# copied into the Strata engine's folder by hand 178found ,problems = ec .scan (self .comp ) 179self .assertEqual ([c .version for c in found ], ["0.1.58" ]) 180self .assertEqual (len (problems ),1 ) 181self .assertEqual (ec .resolve (self .comp ,backend = "cuda" ).version ,"0.1.58" ) 182 183def test_a_strata_engine_never_claims_a_shape (self ): 184plain = build (self .root / "p2" ,"0.1.60" ,self .key ,shape = "" ) 185raw = json .loads ((plain / ec .MANIFEST ).read_text ()) 186self .assertEqual (raw ["id" ],"strata-engine" ) 187self .assertNotIn ("shape" ,raw ) 188raw ["shape" ]= SHAPE 189 (plain / ec .MANIFEST ).write_text (json .dumps (raw )) 190with self .assertRaises (ec .ComponentProblem ): 191ec .read_manifest (plain ) 192 193def test_a_bad_shape_name_stops_the_packager (self ): 194with self .assertRaises (SystemExit ): 195build (self .root / "p3" ,"0.1.59" ,None ,shape = "Not A Shape" ) 196with self .assertRaises (SystemExit ): 197build (self .root / "p4" ,"0.1.59" ,None ,shape = "engine" ) 198 199def test_the_command_line_makes_and_verifies_one (self ): 200src = stub_source (self .root / "cli" ,"0.1.59" ) 201out = self .root / "cli-out" 202done = subprocess .run ([sys .executable ,str (ROOT / "packaging" / "package_engine.py" ),"--src" ,str (src ),"--backend" ,"cuda" ,"--version" ,"0.1.59" , 203"--out" ,str (out ),"--arch" ,"sm_86" ,"--entrypoint" ,EXE ,"--shape" ,SHAPE ,"--build-id" ,"x" ],capture_output = True ,text = True ) 204self .assertEqual (done .returncode ,0 ,done .stdout + done .stderr ) 205folder = next (out .iterdir ()) 206verified = subprocess .run ([sys .executable ,str (ROOT / "packaging" / "package_engine.py" ),"--verify" ,str (folder )],capture_output = True ,text = True ) 207self .assertEqual (verified .returncode ,0 ,verified .stdout ) 208self .assertEqual (json .loads ((folder / ec .MANIFEST ).read_text ())["id" ],COMP ) 209 210 211class Feed (Base ): 212def test_the_member_is_parsed_and_kept_apart_from_engine (self ): 213doc = self .publish ("0.1.59" ) 214self .assertEqual (doc ["shape_engines" ]["packages" ][0 ]["shape" ],SHAPE ) 215loaded = feedmod .fetch (self .url ,signing .load_trusted_keys ()) 216self .assertEqual ([(p .shape ,p .version )for p in loaded .shape_engines ], [(SHAPE ,"0.1.59" )]) 217self .assertEqual (loaded .engine , ()) 218self .assertTrue (loaded .shape_engines [0 ].url .startswith ("shapes/strata-q4-lite-0.1.59-" )) 219self .assertEqual (loaded .shape_engines [0 ].to_dict ()["shape" ],SHAPE ) 220 221def test_a_feed_without_the_member_is_what_it_was (self ): 222shutil .rmtree (self .release ,ignore_errors = True ) 223feed_tool .build_feed (self .release ,key = self .key ,sequence = 1 ) 224loaded = feedmod .fetch (self .url ,signing .load_trusted_keys ()) 225self .assertEqual (loaded .shape_engines , ()) 226self .assertNotIn ("shape_engines" ,json .loads ((self .release / feedmod .FEED_NAME ).read_text ())) 227 228def test_an_entry_with_a_shape_this_control_does_not_accept_is_left_out_with_a_line (self ): 229doc = self .publish ("0.1.59" ) 230doc ["shape_engines" ]["packages" ].append ({** doc ["shape_engines" ]["packages" ][0 ],"shape" :"Not Valid" }) 231parsed = feedmod .parse (json .dumps (doc ).encode (),source = "x" ,key_id = "k" ) 232self .assertEqual (len (parsed .shape_engines ),1 ) 233self .assertTrue (any ("shape" in line for line in parsed .skipped ),parsed .skipped ) 234 235def test_the_same_shape_and_version_twice_is_refused (self ): 236doc = self .publish ("0.1.59" ) 237doc ["shape_engines" ]["packages" ].append (dict (doc ["shape_engines" ]["packages" ][0 ])) 238with self .assertRaises (feedmod .FeedError ): 239feedmod .parse (json .dumps (doc ).encode (),source = "x" ,key_id = "k" ) 240 241def test_a_model_of_a_shape_is_parsed_with_its_shape (self ): 242self .publish ("0.1.59" ,models = [model_entry ()]) 243loaded = feedmod .fetch (self .url ,signing .load_trusted_keys ()) 244 (m ,)= loaded .models 245self .assertEqual ((m .family ,m .shape ), (shape_engine .family_of (SHAPE ),SHAPE )) 246self .assertIsNone (feedmod .parse (json .dumps ({"schema_version" :1 ,"channel" :"stable" ,"generated_at" :"2026-11-08T00:00:00Z" ,"sequence" :1 , 247"models" : {"packages" : [model_entry (id = "plain-one" ,family = "qwen4exp" )]}}).encode (),source = "x" ,key_id = "k" ).models [0 ].shape ) 248 249def test_a_model_with_a_broken_shape_name_is_dropped_with_a_line (self ): 250doc = {"schema_version" :1 ,"channel" :"stable" ,"generated_at" :"2026-11-08T00:00:00Z" ,"sequence" :1 , 251"models" : {"packages" : [model_entry (family = "qwen4exp_Q4-bad" )]}} 252parsed = feedmod .parse (json .dumps (doc ).encode (),source = "x" ,key_id = "k" ) 253self .assertEqual ((parsed .models ,len (parsed .models_dropped )), ((),1 )) 254 255def test_build_feed_refuses_a_model_of_a_shape_with_no_engine (self ): 256 (self .release / "models" ).mkdir (parents = True ) 257 (self .release / "models" / "q4lite-test.entry.json" ).write_text (json .dumps (model_entry ())) 258with self .assertRaises (SystemExit )as ctx : 259feed_tool .build_feed (self .release ,key = self .key ,sequence = 1 ,models_dir = self .release / "models" ) 260self .assertIn ("q4_lite" ,str (ctx .exception )) 261with self .assertRaises (SystemExit ): 262self .publish ("0.1.59" ,shape = "q4_mid" ,models = [model_entry ()])# an engine for another shape does not do 263 264def test_pack_engine_names_the_archive_by_the_component_and_the_entry_by_the_shape (self ): 265folder = build (self .root / "pk" ,"0.1.59" ,self .key ) 266out = self .root / "pk-out" 267out .mkdir () 268entry = feed_tool .pack_engine (folder ,out ,url_prefix = "" ) 269self .assertEqual (entry ["shape" ],SHAPE ) 270self .assertTrue (entry ["url" ].startswith ("strata-q4-lite-0.1.59-" ),entry ["url" ]) 271plain = build (self .root / "pk2" ,"0.1.60" ,self .key ,shape = "" ) 272self .assertNotIn ("shape" ,feed_tool .pack_engine (plain ,out ,url_prefix = "" )) 273self .assertTrue (next (p for p in out .glob ("*.entry.json" )if "strata-engine" in p .name )) 274 275def test_verify_feed_lists_the_shape_engines (self ): 276self .publish ("0.1.59" ,models = [model_entry ()]) 277pub = self .root / "pub.json" 278pub .write_text (json .dumps ({"keys" : [signing .public_part (self .key )]})) 279done = subprocess .run ([sys .executable ,str (ROOT / "packaging" / "feed_tool.py" ),"verify-feed" ,str (self .release ),"--pub" ,str (pub )],capture_output = True ,text = True ) 280self .assertEqual (done .returncode ,0 ,done .stdout + done .stderr ) 281self .assertIn ("1 shape engines (q4_lite)" ,done .stdout ) 282 283 284class Install (Base ): 285def test_the_engine_of_the_shape_is_fetched_beside_the_strata_engine (self ): 286self .publish ("0.1.59" ) 287lines = [] 288with mock .patch .object (shape_engine ,"_test_start" ,return_value = (True ,"strata 0.1.59" )): 289exe = self .ensure (lines ) 290self .assertIsNotNone (exe ,lines ) 291self .assertEqual (exe .parent .parent .parent ,self .comp / "shapes" / SHAPE ) 292self .assertTrue (exe .is_file ()) 293self .assertEqual (self .strata_before ,tree (self .comp / "engine" ),"the Strata engine's files must not change" ) 294self .assertEqual (ec .resolve (self .comp ,backend = "cuda" ).version ,"0.1.58" ) 295self .assertIn ("0.1.59" ," " .join (lines )) 296self .assertEqual (shape_engine .newest_version (SHAPE ,self .comp ),"0.1.59" ) 297self .assertEqual (shape_engine .installed_shapes (self .comp ), [SHAPE ]) 298self .assertEqual (json .loads ((exe .parent / ec .MANIFEST ).read_text ())["shape" ],SHAPE ) 299 300def test_the_reference_resolves_to_the_shape_engine_and_the_other_to_the_strata_engine (self ): 301self .publish ("0.1.59" ) 302with mock .patch .object (shape_engine ,"_test_start" ,return_value = (True ,"x" )): 303exe = self .ensure () 304self .assertEqual (Path (ec .expand ("component:strata-q4-lite" , {"backend" :"cuda" })),exe ) 305strata = Path (ec .expand ("component:strata-engine" , {"backend" :"cuda" })) 306self .assertEqual (strata .parent .parent .name ,"engine" ) 307self .assertNotEqual (strata ,exe ) 308self .assertEqual (ec .expand ("/some/path/strata" ),"/some/path/strata" ) 309 310def test_a_shape_with_no_engine_installed_is_a_plain_refusal_and_never_a_fetch (self ): 311with self .assertRaises (shape_engine .ShapeEngineMissing )as ctx : 312ec .expand ("component:strata-q4-lite" , {"backend" :"cuda" }) 313self .assertIsInstance (ctx .exception ,ec .EngineMissing ) 314self .assertEqual (ctx .exception .exit_code ,5 ) 315self .assertIn ("q4_lite" ,str (ctx .exception )) 316self .assertIn ("never downloads" ,str (ctx .exception )) 317with self .assertRaises (ec .EngineMissing ): 318ec .expand ("component:strata-nonsense" , {}) 319self .assertFalse ((self .comp / "shapes" ).exists ()) 320 321def test_a_changed_file_stops_the_start_of_that_engine_only (self ): 322self .publish ("0.1.59" ) 323with mock .patch .object (shape_engine ,"_test_start" ,return_value = (True ,"x" )): 324exe = self .ensure () 325exe .write_bytes (exe .read_bytes ()+ b"changed" ) 326with self .assertRaises (ec .EngineMissing ): 327ec .expand ("component:strata-q4-lite" , {"backend" :"cuda" }) 328self .assertTrue (Path (ec .expand ("component:strata-engine" , {"backend" :"cuda" })).is_file ()) 329 330def test_an_installed_engine_that_is_current_is_not_fetched_again_and_says_nothing (self ): 331self .publish ("0.1.59" ) 332with mock .patch .object (shape_engine ,"_test_start" ,return_value = (True ,"x" )): 333self .assertIsNotNone (self .ensure ()) 334self .server .requests .clear () 335lines = [] 336self .assertIsNotNone (self .ensure (lines )) 337self .assertEqual (lines , []) 338self .assertFalse ([r for r in self .server .requests if r [1 ].endswith (".tar.gz" )],self .server .requests ) 339 340def test_a_cut_download_resumes (self ): 341self .publish ("0.1.59" ) 342shutil .rmtree (self .release ) 343 (self .release / "shapes" ).mkdir (parents = True ) 344folder = build (self .root / "big" ,"0.1.59" ,self .key ,padding = 3_000_000 ) 345feed_tool .pack_engine (folder ,self .release / "shapes" ,url_prefix = "shapes/" ) 346feed_tool .build_feed (self .release ,key = self .key ,sequence = 1 ,shapes_dir = self .release / "shapes" ) 347self .server .cut [next ((self .release / "shapes" ).glob ("*.tar.gz" )).name ]= 800_000 348lines = [] 349with mock .patch .object (shape_engine ,"_test_start" ,return_value = (True ,"x" )): 350self .assertIsNotNone (self .ensure (lines ),lines )# cut part-way: the same run continues from the byte it reached 351ranges = [r [2 ]for r in self .server .requests if r [1 ].endswith (".tar.gz" )] 352self .assertEqual (ranges , [None ,"bytes=800000-" ],"exactly one more request, from the byte the cut reached: no byte twice" ) 353self .assertEqual (self .strata_before ,tree (self .comp / "engine" )) 354 355def test_the_feed_has_no_engine_for_the_shape (self ): 356self .publish ("0.1.59" ,shape = "q4_mid" ) 357lines = [] 358self .assertIsNone (self .ensure (lines )) 359self .assertIn ("The update feed has no engine for q4_lite for this computer." ," " .join (lines )) 360self .assertFalse ((self .comp / "shapes" / SHAPE ).exists ()) 361self .assertEqual (self .strata_before ,tree (self .comp / "engine" )) 362 363def test_no_engine_for_this_pc_is_a_plain_line (self ): 364self .publish ("0.1.59" ) 365self .hw = {** self .hw ,"cuda_archs" : ["sm_61" ]} 366lines = [] 367with mock .patch .object (ec ,"cuda_archs_present" ,return_value = ["sm_61" ]): 368self .assertIsNone (self .ensure (lines )) 369self .assertTrue (lines ) 370self .assertFalse ((self .comp / "shapes" / SHAPE ).exists ()) 371 372def test_a_package_signed_with_another_key_is_refused (self ): 373self .publish ("0.1.59" ,key = fx .make_key ()) 374lines = [] 375self .assertIsNone (self .ensure (lines )) 376self .assertTrue (lines ) 377self .assertFalse ((self .comp / "shapes" / SHAPE / "engine" ).exists ()and list ((self .comp / "shapes" / SHAPE / "engine" ).iterdir ())) 378self .assertEqual (self .strata_before ,tree (self .comp / "engine" )) 379 380def test_a_feed_that_names_another_shape_than_the_package_says_is_refused (self ): 381doc = self .publish ("0.1.59" ) 382entry_file = next ((self .release / "shapes" ).glob ("*.entry.json" )) 383item = json .loads (entry_file .read_text ()) 384item ["shape" ]= "q4_mid" # the feed says q4_mid, the signed manifest says q4_lite 385entry_file .write_text (json .dumps (item )) 386feed_tool .build_feed (self .release ,key = self .key ,sequence = 2 ,shapes_dir = self .release / "shapes" ) 387lines = [] 388with mock .patch .object (shape_engine ,"_test_start" ,return_value = (True ,"x" )): 389self .assertIsNone (shape_engine .ensure ("q4_mid" ,self .url ,components = self .comp ,hardware = self .hw ,emit = lines .append )) 390self .assertIn ("not an engine component" ," " .join (lines )) 391self .assertFalse ((self .comp / "shapes" / "q4_mid" / "engine" ).exists ()and list ((self .comp / "shapes" / "q4_mid" / "engine" ).iterdir ())) 392 393def test_a_package_that_does_not_start_is_removed (self ): 394self .publish ("0.1.59" ) 395lines = [] 396with mock .patch .object (shape_engine ,"_test_start" ,return_value = (False ,"libcudart.so.13: not found" )): 397self .assertIsNone (self .ensure (lines )) 398self .assertIn ("was not installed because it did not start correctly" ," " .join (lines )) 399self .assertFalse ([l for l in lines if "could not be downloaded" in l ],"the approved line is said as it is, not inside another one" ) 400self .assertIn ("The Strata engine is unchanged" ," " .join (lines )) 401self .assertEqual (shape_engine .installed (SHAPE ,self .comp ), []) 402self .assertEqual (self .strata_before ,tree (self .comp / "engine" )) 403 404def test_the_real_start_test_runs_the_program_and_wants_its_name (self ): 405src = self .root / "prog" 406src .mkdir () 407script = src / "strata" 408script .write_text (f'#! { sys . executable } \nimport sys\nprint("strata 0.1.59" if "--version" in sys.argv else "no")\n' ) 409script .chmod (0o755 ) 410if os .name == "nt" : 411self .skipTest ("a script is not a Windows program" ) 412self .assertEqual (shape_engine ._test_start (script ), (True ,"strata 0.1.59" )) 413script .write_text (f'#! { sys . executable } \nprint("hello")\n' ) 414self .assertFalse (shape_engine ._test_start (script )[0 ]) 415 416def _program (self ,geometry ): 417"""A stand-in engine program: `--version` names it, `--geometry` prints `geometry` (None: an engine from before the flag, which exits 2).""" 418src = self .root / f"prog- { geometry } " 419src .mkdir (exist_ok = True ) 420script = src / "strata" 421answer = f'print( { geometry !r } )' if geometry else 'sys.exit(2)' 422script .write_text (f'#! { sys . executable } \nimport sys\nif "--version" in sys.argv:\n print("strata 0.2.13")\nelif "--geometry" in sys.argv:\n { answer } \nelse:\n sys.exit(3)\n' ) 423script .chmod (0o755 ) 424return script 425 426def test_the_engine_must_be_built_for_the_shape_the_signed_manifest_names (self ): 427if os .name == "nt" : 428self .skipTest ("a script is not a Windows program" ) 429self .assertEqual (shape_engine ._test_start (self ._program ("q4_lite" ),shape = "q4_lite" ), (True ,"strata 0.2.13" )) 430self .assertEqual (shape_engine ._test_start (self ._program (None ),shape = "q4_lite" ), (False ,"it does not say which model shape it was built for" ), 431"a shape engine that cannot answer --geometry is refused (owner, 11-09)" ) 432ok ,why = shape_engine ._test_start (self ._program ("flash_next" ),shape = "q4_lite" ) 433self .assertEqual ((ok ,why ), (False ,"it was built for a different model shape (flash_next)" )) 434self .assertEqual (shape_engine ._test_start (self ._program ("flash_next" )), (True ,"strata 0.2.13" ),"no shape asked for: the flag is not read" ) 435 436def test_the_plain_strata_engine_is_never_asked_for_its_shape (self ): 437if os .name == "nt" : 438self .skipTest ("a script is not a Windows program" ) 439self .assertEqual (shape_engine ._test_start (self ._program (None )), (True ,"strata 0.2.13" ),"an engine with no --geometry still installs as the Strata engine" ) 440with mock .patch .object (shape_engine ,"check_geometry" ,side_effect = AssertionError ("asked" )): 441self .assertEqual (shape_engine ._test_start (self ._program ("flash_next" )), (True ,"strata 0.2.13" )) 442 443def test_a_shape_engine_with_no_answer_is_refused_at_install_with_the_owners_reason (self ): 444if os .name == "nt" : 445self .skipTest ("a script is not a Windows program" ) 446self .publish ("0.1.59" ) 447with mock .patch .object (shape_engine ,"_test_start" ,return_value = (False ,shape_engine .NO_SHAPE_ANSWER )): 448lines = [] 449self .assertIsNone (self .ensure (lines ,title = "Q4 Lite Shape" )) 450self .assertIn ("The engine for Q4 Lite Shape 0.1.59 was not installed because it did not start correctly (it does not say which model shape it was built for). " 451"The Strata engine is unchanged." ," " .join (lines )) 452self .assertEqual (shape_engine .installed (SHAPE ,self .comp ), []) 453self .assertEqual (self .strata_before ,tree (self .comp / "engine" )) 454 455def test_the_owners_reason_for_no_answer (self ): 456self .assertEqual (shape_engine .NO_SHAPE_ANSWER ,"it does not say which model shape it was built for" )# owner, 11-09 457 458def test_a_package_built_for_another_shape_is_refused_at_install_with_the_approved_line (self ): 459if os .name == "nt" : 460self .skipTest ("a script is not a Windows program" ) 461self .publish ("0.1.59" ) 462with mock .patch .object (shape_engine ,"_test_start" ,return_value = (False ,"it was built for a different model shape (flash_next)" )): 463lines = [] 464self .assertIsNone (self .ensure (lines ,title = "Q4 Lite Shape" )) 465self .assertIn ("The engine for Q4 Lite Shape 0.1.59 was not installed because it did not start correctly (it was built for a different model shape (flash_next)). " 466"The Strata engine is unchanged." ," " .join (lines )) 467self .assertEqual (shape_engine .installed (SHAPE ,self .comp ), []) 468self .assertEqual (self .strata_before ,tree (self .comp / "engine" )) 469 470def test_min_runtime_newer_than_this_control_keeps_it_from_starting (self ): 471shutil .rmtree (self .release ,ignore_errors = True ) 472 (self .release / "shapes" ).mkdir (parents = True ) 473folder = build (self .root / "mr" ,"0.1.59" ,self .key ,min_runtime = "9.9.9" ) 474feed_tool .pack_engine (folder ,self .release / "shapes" ,url_prefix = "shapes/" ) 475feed_tool .build_feed (self .release ,key = self .key ,sequence = 1 ,shapes_dir = self .release / "shapes" ) 476self .hw = {** self .hw ,"runtime" :"0.1.58" } 477lines = [] 478self .assertIsNone (self .ensure (lines )) 479self .assertIn ("The update feed has no engine for q4_lite for this computer." ," " .join (lines ))# the reason (needs control 9.9.9) is in the row, not in the line 480feed = feedmod .fetch (self .url ,signing .load_trusted_keys ()) 481ctx = updater .Context (components = self .comp ,source = self .url ,trusted = signing .load_trusted_keys (),hardware = self .hw ) 482self .assertIn ("9.9.9" ," " .join (shape_engine .update_one (ctx ,feed ,SHAPE )["reasons" ])) 483 484 485class Update (Base ): 486def installed (self ,* versions ): 487for i ,v in enumerate (versions ): 488self .publish (* versions [:i + 1 ],sequence = i + 1 ) 489with mock .patch .object (shape_engine ,"_test_start" ,return_value = (True ,"x" )): 490self .assertIsNotNone (self .ensure (),v ) 491 492def test_a_newer_package_goes_next_to_the_old_and_the_oldest_beyond_two_goes (self ): 493self .publish ("0.1.59" ) 494with mock .patch .object (shape_engine ,"_test_start" ,return_value = (True ,"x" )): 495self .assertIsNotNone (self .ensure ()) 496self .publish ("0.1.59" ,"0.1.60" ,sequence = 2 ) 497lines = [] 498with mock .patch .object (shape_engine ,"_test_start" ,return_value = (True ,"x" )): 499exe = self .ensure (lines ) 500self .assertEqual (self .folders (), ["0.1.59" ,"0.1.60" ],"the older engine stays" ) 501self .assertIn ("updated from 0.1.59 to 0.1.60" ," " .join (lines )) 502self .assertEqual (Path (ec .expand ("component:strata-q4-lite" , {"backend" :"cuda" })),exe ) 503self .publish ("0.1.59" ,"0.1.60" ,"0.1.61" ,sequence = 3 ) 504with mock .patch .object (shape_engine ,"_test_start" ,return_value = (True ,"x" )),mock .patch ("strata_control.folder_use.in_use" ,return_value = False ): 505self .ensure () 506self .assertEqual (self .folders (), ["0.1.60" ,"0.1.61" ]) 507self .assertEqual (self .strata_before ,tree (self .comp / "engine" )) 508 509def test_an_older_package_in_the_feed_changes_nothing (self ): 510self .installed ("0.1.60" ) 511self .publish ("0.1.59" ,sequence = 5 ) 512self .assertIsNotNone (self .ensure ()) 513self .assertEqual (self .folders (), ["0.1.60" ]) 514 515def test_a_failed_start_of_the_newer_one_keeps_the_old (self ): 516self .installed ("0.1.59" ) 517self .publish ("0.1.59" ,"0.1.60" ,sequence = 9 ) 518lines = [] 519with mock .patch .object (shape_engine ,"_test_start" ,return_value = (False ,"boom" )): 520exe = self .ensure (lines ) 521self .assertEqual (self .folders (), ["0.1.59" ]) 522self .assertTrue (exe .is_file (),"the installed engine still runs the model" ) 523self .assertEqual (shape_engine .newest_version (SHAPE ,self .comp ),"0.1.59" ) 524self .assertIn ("A newer engine for q4_lite is available but could not be installed" ," " .join (lines )) 525self .assertIn ("Still using 0.1.59." ," " .join (lines )) 526self .assertIn ("(boom). Still using 0.1.59." ," " .join (lines ),"the plain reason, not the whole refusal line, is in the newer-engine line" ) 527 528def test_a_refused_acquisition_with_an_engine_installed_never_stops_a_launch (self ): 529self .installed ("0.1.59" ) 530from strata_control import acquisition 531with mock .patch .object (updater ,"open_feed" ,side_effect = acquisition .AcquisitionRefused ("no" )): 532lines = [] 533self .assertTrue (self .ensure (lines ).is_file ()) 534self .assertEqual (lines , []) 535 536def test_an_unreachable_feed_leaves_an_installed_engine_alone_and_says_nothing (self ): 537from tests .terminal import net_dead 538self .installed ("0.1.59" ) 539for kind in net_dead .KINDS :# no network at all / a refused port / a server that never answers 540with net_dead .dead_feed (kind )as dead : 541lines = [] 542exe = shape_engine .ensure (SHAPE ,dead ,components = self .comp ,hardware = self .hw ,emit = lines .append ) 543self .assertTrue (exe .is_file (),kind ) 544self .assertEqual (lines , [],kind ) 545with net_dead .dead_feed ("refused" )as dead :# a shape with no engine yet has nothing to fall back on: that one is said 546lines = [] 547self .assertIsNone (shape_engine .ensure ("q4_mid" ,dead ,components = self .comp ,hardware = self .hw ,emit = lines .append )) 548self .assertTrue (any ("could not be downloaded" in line for line in lines ),lines ) 549 550def test_a_refused_feed_is_asked_once_by_the_launch_check_then_not_for_six_hours (self ): 551"""netpolicy rule 4b: `strata launch` (automatic=True) with an engine installed reads the refusal note; setup (no flag) and a shape 552with no engine yet always read the feed.""" 553from strata_control import netpolicy ,transfer 554from tests .terminal .test_netpolicy import refused_port 555self .installed ("0.1.59" ) 556# the product's own windows (5 s with an engine installed), not net_dead's scaled 0.3 s: Windows reports a refusal only after about 2 s, 557# so a scaled window would see a timeout there, not a refusal 558dead = f"http://127.0.0.1: { refused_port () } /strata-feed.json" 559note = netpolicy .RefusalNote (path = self .root / "state" / "net" / netpolicy .REFUSED_NOTE_NAME ) 560calls = [] 561real = transfer ._open_small 562 563def counting (request ,timeout ,limit ): 564calls .append (request .full_url ) 565return real (request ,timeout ,limit ) 566with mock .patch .object (netpolicy ,"REFUSALS" ,note ),mock .patch .object (transfer ,"_open_small" ,counting ): 567lines = [] 568self .assertTrue (shape_engine .ensure (SHAPE ,dead ,components = self .comp ,hardware = self .hw ,emit = lines .append ,automatic = True ).is_file ()) 569self .assertEqual (lines , []) 570self .assertEqual (len (calls ),1 ,"one try: a refusal is clear at once" ) 571port = dead .split ("/" )[2 ] 572self .assertEqual (list (json .loads (note .path ().read_text (encoding = "utf-8" ))), [port ],"host:port only" ) 573self .assertTrue (shape_engine .ensure (SHAPE ,dead ,components = self .comp ,hardware = self .hw ,emit = lines .append ,automatic = True ).is_file ()) 574self .assertEqual ((len (calls ),lines ), (1 , []),"the next launch check does not connect and says nothing" ) 575self .assertTrue (shape_engine .ensure (SHAPE ,dead ,components = self .comp ,hardware = self .hw ,emit = lines .append ).is_file ()) 576self .assertEqual (len (calls ),2 ,"setup's call (no flag) reads the feed" ) 577self .assertIsNone (shape_engine .ensure ("q4_mid" ,dead ,components = self .comp ,hardware = self .hw ,emit = lines .append ,automatic = True )) 578self .assertEqual (len (calls ),3 ,"no engine installed: the feed is always read" ) 579 580def test_the_launch_asks_as_an_automatic_check_and_setup_does_not (self ): 581runner_src = (ROOT / "strata_cli" / "launch" / "runner.py" ).read_text (encoding = "utf-8" ) 582call = runner_src [runner_src .index ("exe = shape_engine.ensure(" ):] 583self .assertIn ("automatic=True" ,call [:call .index ("\n\n" )]) 584setup_src = (ROOT / "setup.py" ).read_text (encoding = "utf-8" ) 585call = setup_src [setup_src .index ("exe = shape_engine.ensure(" ):] 586self .assertNotIn ("automatic" ,call [:call .index ("\n" )]) 587 588def test_the_explicit_update_has_a_step_only_for_an_installed_shape (self ): 589self .publish ("0.1.59" ) 590ctx = updater .Context (components = self .comp ,source = self .url ,trusted = signing .load_trusted_keys (),hardware = self .hw ) 591feed = feedmod .fetch (self .url ,ctx .trusted ) 592self .assertEqual (updater ._shape_steps (ctx ,feed ,True ), [],"nothing installed: no step, an update never installs a shape engine by itself" ) 593with mock .patch .object (shape_engine ,"_test_start" ,return_value = (True ,"x" )): 594self .assertIsNotNone (self .ensure ()) 595self .publish ("0.1.59" ,"0.1.60" ,sequence = 2 ) 596feed = feedmod .fetch (self .url ,ctx .trusted ) 597steps = updater ._shape_steps (ctx ,feed ,True ) 598self .assertEqual ([name for name ,_ in steps ], [COMP ]) 599self .assertEqual (updater ._shape_steps (ctx ,feed ,False ), []) 600result = steps [0 ][1 ]() 601self .assertEqual ((result ["status" ],result ["installed_before" ],result ["installed_after" ],result ["shape" ]), ("updated" ,"0.1.59" ,"0.1.60" ,SHAPE )) 602self .assertEqual (self .strata_before ,tree (self .comp / "engine" )) 603 604def test_run_update_runs_that_step_and_reports_it (self ): 605self .publish ("0.1.59" ) 606with mock .patch .object (shape_engine ,"_test_start" ,return_value = (True ,"x" )): 607self .assertIsNotNone (self .ensure ()) 608self .publish ("0.1.59" ,"0.1.60" ,sequence = 2 ) 609ctx = updater .Context (components = self .comp ,source = self .url ,trusted = signing .load_trusted_keys (),hardware = self .hw ) 610with mock .patch .object (shape_engine ,"_test_start" ,return_value = (True ,"x" )), \ 611mock .patch .object (updater ,"update_engine" ,return_value = {"component" :"engine" ,"status" :"current" ,"changed" :False }): 612out = updater .run_update (ctx ,control = False ) 613row = next (r for r in out ["results" ]if r .get ("component" )== COMP ) 614self .assertEqual ((row ["status" ],row ["installed_after" ]), ("updated" ,"0.1.60" )) 615self .assertEqual (out ["exit_code" ],0 ) 616from strata_cli import update_cmd 617self .assertEqual (update_cmd ._line ("Strata-q4-lite" ,row ),"Model engine Engine for q4_lite updated from 0.1.59 to 0.1.60." ) 618 619def test_the_components_report_lists_a_shape_engine_only_when_there_is_one (self ): 620self .assertNotIn ("shapes" ,ec .status (self .comp )) 621self .publish ("0.1.59" ) 622with mock .patch .object (shape_engine ,"_test_start" ,return_value = (True ,"x" )): 623self .assertIsNotNone (self .ensure ()) 624rows = ec .status (self .comp )["shapes" ] 625self .assertEqual ([(r ["shape" ],r ["usable" ],r ["engine" ]["shape" ])for r in rows ], [(SHAPE ,True ,SHAPE )]) 626self .assertNotIn ("shape" ,ec .status (self .comp )["engine" ],"the Strata engine's own report is what it was" ) 627 628 629class TitleInLines (Base ): 630"""A person reads the model's title ("Qwen4 Lite Test"), not the geometry's name (q4_lite), in every line; the shape stays in the keys, the JSON and `strata components engine`. 631shape_engine.USE_TITLE is the one switch back.""" 632TITLE = "Qwen4 Lite Test" 633 634def test_the_fetch_lines_name_the_title (self ): 635self .publish ("0.1.59" ) 636lines = [] 637with mock .patch .object (shape_engine ,"_test_start" ,return_value = (True ,"x" )): 638exe = self .ensure (lines ,title = self .TITLE ) 639text = " " .join (lines ) 640self .assertIsNotNone (exe ,lines ) 641self .assertIn (f" { self . TITLE } needs its own engine." ,text ) 642self .assertIn (f"Engine for { self . TITLE } 0.1.59" ,text ) 643self .assertNotIn ("q4_lite needs" ,text ) 644self .assertNotIn ("for q4_lite" ,text ) 645 646def test_the_refusals_name_the_title (self ): 647self .publish ("0.1.59" ,shape = "q4_mid" ) 648lines = [] 649self .assertIsNone (self .ensure (lines ,title = self .TITLE )) 650self .assertIn (f"The update feed has no engine for { self . TITLE } for this computer." ," " .join (lines )) 651with mock .patch .object (shape_engine ,"_test_start" ,return_value = (False ,"boom" )): 652self .publish ("0.1.59" ) 653lines = [] 654self .assertIsNone (self .ensure (lines ,title = self .TITLE )) 655self .assertIn (f"The engine for { self . TITLE } 0.1.59 was not installed because it did not start correctly (boom)." ," " .join (lines )) 656 657def test_a_start_without_the_engine_names_the_title_from_the_run_config (self ): 658with self .assertRaises (shape_engine .ShapeEngineMissing )as ctx : 659ec .expand ("component:strata-q4-lite" , {"backend" :"cuda" ,"shape_title" :self .TITLE }) 660self .assertTrue (str (ctx .exception ).startswith (f" { self . TITLE } needs its own engine" ),str (ctx .exception )) 661self .assertNotIn ("q4_lite" ,str (ctx .exception )) 662self .assertEqual (ctx .exception .shape ,"q4_lite" ) 663with self .assertRaises (shape_engine .ShapeEngineMissing )as ctx :# a config without a title (an older one): the shape's name 664ec .expand ("component:strata-q4-lite" , {"backend" :"cuda" }) 665self .assertTrue (str (ctx .exception ).startswith ("q4_lite needs its own engine" ),str (ctx .exception )) 666 667def test_the_explicit_update_finds_the_title_in_the_feeds_model (self ): 668self .publish ("0.1.59" ,models = [model_entry (title = self .TITLE )]) 669with mock .patch .object (shape_engine ,"_test_start" ,return_value = (True ,"x" )): 670self .assertIsNotNone (self .ensure ()) 671self .publish ("0.1.59" ,"0.1.60" ,sequence = 2 ,models = [model_entry (title = self .TITLE )]) 672ctx = updater .Context (components = self .comp ,source = self .url ,trusted = signing .load_trusted_keys (),hardware = self .hw ) 673feed = feedmod .fetch (self .url ,ctx .trusted ) 674row = updater ._shape_steps (ctx ,feed ,True )[0 ][1 ]() 675self .assertEqual (row ["note" ],f"Engine for { self . TITLE } updated from 0.1.59 to 0.1.60." ) 676self .assertEqual ((row ["shape" ],row ["component" ]), ("q4_lite" ,COMP ),"the keys keep the geometry's name" ) 677self .assertEqual (shape_engine .title_from_feed (feed ,"q4_lite" ),self .TITLE ) 678self .assertIsNone (shape_engine .title_from_feed (feed ,"q4_mid" )) 679 680def test_one_switch_puts_the_geometry_name_back (self ): 681self .publish ("0.1.59" ) 682lines = [] 683with mock .patch .object (shape_engine ,"USE_TITLE" ,False ),mock .patch .object (shape_engine ,"_test_start" ,return_value = (True ,"x" )): 684self .assertIsNotNone (self .ensure (lines ,title = self .TITLE )) 685self .assertIn ("q4_lite needs its own engine." ," " .join (lines )) 686self .assertNotIn (self .TITLE ," " .join (lines )) 687self .assertEqual (shape_engine .shown ("q4_lite" ,self .TITLE ),self .TITLE ) 688self .assertEqual (shape_engine .shown ("q4_lite" ,None ),"q4_lite" ) 689self .assertEqual (shape_engine .shown ("q4_lite" ," " ),"q4_lite" ) 690 691def test_the_components_report_keeps_the_geometry_name (self ): 692self .publish ("0.1.59" ) 693with mock .patch .object (shape_engine ,"_test_start" ,return_value = (True ,"x" )): 694self .assertIsNotNone (self .ensure (title = self .TITLE )) 695self .assertEqual ([r ["shape" ]for r in ec .status (self .comp )["shapes" ]], ["q4_lite" ]) 696 697 698class ApprovedWords (unittest .TestCase ): 699"""The owner approved these exact lines (11-08, "A ok"). {model} is the model's title. A change of a word is a change of this test, which the owner approves first.""" 700 701def test_the_lines_are_the_approved_ones (self ): 702W ,M = shape_engine .WORDS ,"Q4 Lite Shape" 703self .assertEqual (W ["checking" ].format (model = M ),"Checking the engine for Q4 Lite Shape…" ) 704self .assertEqual (W ["fetching" ].format (model = M ),"Q4 Lite Shape needs its own engine. It downloads separately, and the Strata engine stays as it is." ) 705self .assertEqual (W ["installed" ].format (model = M ,version = "0.1.59" ,backend = "cuda" ),"Engine for Q4 Lite Shape 0.1.59 (cuda) is installed." ) 706self .assertEqual (W ["ready" ],W ["installed" ]) 707self .assertEqual (W ["updated" ].format (model = M ,old = "0.1.59" ,new = "0.1.60" ),"Engine for Q4 Lite Shape updated from 0.1.59 to 0.1.60." ) 708self .assertEqual (W ["not_in_feed" ].format (model = M ),"The update feed has no engine for Q4 Lite Shape for this computer." ) 709self .assertEqual (W ["start_failed" ].format (model = M ,version = "0.1.59" ,why = "no library" ), 710"The engine for Q4 Lite Shape 0.1.59 was not installed because it did not start correctly (no library). The Strata engine is unchanged." ) 711self .assertEqual (W ["fetch_failed" ].format (model = M ,why = "no network" ),"The engine for Q4 Lite Shape could not be downloaded: no network" ) 712self .assertEqual (W ["newer_failed" ].format (model = M ,why = "bad hash" ,have = "0.1.59" ), 713"A newer engine for Q4 Lite Shape is available but could not be installed (bad hash). Still using 0.1.59." ) 714self .assertEqual (W ["missing" ].format (model = M ,reason = "nothing matched" ), 715"Q4 Lite Shape needs its own engine, which is not installed or does not fit this PC: nothing matched. Run `strata launch` again, or Download / repair in " 716"the app, to fetch it. Starting a model never downloads an engine." ) 717self .assertEqual (W ["setup_failed" ].format (model = M ),"the engine for Q4 Lite Shape could not be installed" ) 718self .assertEqual (W ["setup_failed_hint" ],"See the line above. Nothing was downloaded for the model. Run this again when the update feed has it." ) 719self .assertEqual (W ["setup_ok" ].format (model = M ,version = "0.1.59" ,folder = "/x/y" ),"engine for Q4 Lite Shape: 0.1.59 in /x/y" ) 720self .assertEqual (W ["update_label" ],"Model engine" ) 721 722def test_no_reasons_or_platform_names_reach_the_lines (self ): 723"""The reasons list and the platform-backend stay in the result rows (and the JSON), not in the line a person reads.""" 724pkgs = [p for p in feedmod .parse (json .dumps ({"schema_version" :1 ,"channel" :"stable" ,"generated_at" :"2026-11-08T00:00:00Z" ,"sequence" :1 , 725"shape_engines" : {"packages" : [dict (shape = "q4_mid" ,version = "0.1.59" ,platform = "linux-x86_64" ,backend = "cuda" ,variant = "" ,archs = ["sm_86" ], 726min_driver = {},min_runtime = None ,build_id = "b" ,format = "tar.gz" ,url = "x" ,size = 1 ,sha256 = "a" * 64 , 727manifest_sha256 = "b" * 64 ,installed_bytes = 1 )]}}).encode (),source = "s" ,key_id = "k" ).shape_engines ] 728feed = mock .Mock (shape_engines = pkgs ,models = ()) 729ctx = mock .Mock (components = Path (tempfile .mkdtemp ()),hardware = {"platform" :host_platform (),"backend" :"cuda" }) 730row = shape_engine .update_one (ctx ,feed ,"q4_lite" ,title = "Q4 Lite Shape" ) 731self .assertEqual (row ["note" ],"The update feed has no engine for Q4 Lite Shape for this computer." ) 732self .assertTrue (row ["reasons" ],"the reasons are in the row" ) 733self .assertEqual ((row ["shape" ],row ["component" ]), ("q4_lite" ,"strata-q4-lite" )) 734 735 736class NoAcquisitionOnStart (unittest .TestCase ): 737def test_only_setup_launch_and_the_explicit_update_fetch_a_shape_engine (self ): 738"""Starting and serving never download: the code that fetches (shape_engine.ensure / update_one) is called from setup.py, the Terminal's launch and the updater only.""" 739allowed = {"setup.py" ,"strata_cli/launch/runner.py" ,"strata_control/updater.py" ,"strata_control/shape_engine.py" } 740found = set () 741for folder in ("serve" ,"strata_cli" ,"strata_control" ): 742for p in (ROOT / folder ).rglob ("*.py" ): 743if p .name .startswith ("test_" ): 744continue 745text = p .read_text (encoding = "utf-8" ) 746if "shape_engine.ensure(" in text or "shape_engine.update_one(" in text or "update_one(ctx" in text : 747found .add (p .relative_to (ROOT ).as_posix ()) 748for p in (ROOT / "strata.py" ,ROOT / "setup.py" ): 749if "shape_engine.ensure(" in p .read_text (encoding = "utf-8" ): 750found .add (p .relative_to (ROOT ).as_posix ()) 751self .assertEqual (sorted (found - allowed ), []) 752self .assertTrue (found ,"the scan found nothing: the check is broken" ) 753 754def test_resolving_a_shape_engine_for_a_start_reaches_no_network_code (self ): 755code = ("import sys\nsys.path.insert(0, %r)\nfrom strata_control import engine_component as ec\n" 756"try:\n ec.expand('component:strata-q4-lite', {})\nexcept ec.EngineMissing:\n pass\n" 757"bad = [m for m in ('strata_control.updater', 'strata_control.transfer', 'urllib.request') if m in sys.modules]\nprint(bad)\n" % str (ROOT )) 758out = subprocess .run ([sys .executable ,"-I" ,"-c" ,code ],capture_output = True ,text = True ,env = {** os .environ ,"STRATA_COMPONENTS_DIR" :tempfile .mkdtemp ()}) 759self .assertEqual (out .stdout .strip (),"[]" ,out .stdout + out .stderr ) 760 761 762class OlderControls (Base ): 763"""A Control from before the member reads the same feed as one without it, and never offers the model.""" 764 765def _old_feed_module (self ,ref :str ): 766shown = subprocess .run (["git" ,"-C" ,str (ROOT ),"show" ,f" { ref } :strata_control/feed.py" ],capture_output = True ) 767if shown .returncode != 0 : 768self .skipTest (f" { ref } is not in this clone" ) 769path = self .root / f"feed_ { ref . replace ( '.' , '_' ) } .py" 770path .write_bytes (shown .stdout ) 771spec = importlib .util .spec_from_file_location (path .stem ,path ) 772mod = importlib .util .module_from_spec (spec ) 773sys .modules [path .stem ]= mod 774try : 775spec .loader .exec_module (mod ) 776finally : 777sys .modules .pop (path .stem ,None ) 778return mod 779 780def _check (self ,ref :str ,has_models :bool ): 781old = self ._old_feed_module (ref ) 782self .publish ("0.1.59" ,models = [model_entry ()]) 783payload = (self .release / feedmod .FEED_NAME ).read_bytes () 784new = feedmod .parse (payload ,source = "s" ,key_id = "k" ) 785before = old .parse (json .dumps ({k :v for k ,v in json .loads (payload ).items ()if k not in ("shape_engines" ,"models" )}).encode (),source = "s" ,key_id = "k" ) 786got = old .parse (payload ,source = "s" ,key_id = "k" ) 787self .assertEqual (got .engine ,before .engine ,"no shape engine is ever an engine for an older Control" ) 788self .assertEqual (got .dsv41 ,before .dsv41 ) 789self .assertEqual ((got .sequence ,got .channel ,got .app ,got .control ), (before .sequence ,before .channel ,before .app ,before .control )) 790self .assertEqual (len (new .shape_engines ),1 ) 791if has_models : 792 (m ,)= got .models 793self .assertEqual (m .family ,"qwen4exp_q4_lite" ) 794self .assertNotIn (m .family ,old .MODEL_FAMILIES_INSTALLABLE ,"a family an older Control does not know is never offered to install" ) 795else : 796self .assertFalse (hasattr (got ,"models" )) 797 798def test_the_control_before_this_one_reads_the_feed_and_does_not_offer_the_model (self ): 799self ._check ("3289d8280" ,True ) 800 801def test_control_0211_ignores_the_new_members (self ): 802self ._check ("v0.2.11" ,False ) 803 804def test_an_older_scan_does_not_see_the_shape_engine_even_in_its_own_folder_layout (self ): 805self .publish ("0.1.59" ) 806with mock .patch .object (shape_engine ,"_test_start" ,return_value = (True ,"x" )): 807self .assertIsNotNone (self .ensure ()) 808# an older Control scans <components>/engine only, and reads strata-engine manifests only 809found ,problems = ec .scan (self .comp ) 810self .assertEqual ([c .version for c in found ], ["0.1.58" ]) 811self .assertEqual (problems , []) 812shape_folder = next ((self .comp / "shapes" / SHAPE / "engine" ).iterdir ()) 813with self .assertRaises (ec .ComponentProblem ): 814ec .read_manifest (shape_folder ) 815 816 817class EveryEngineProgramAnswersTheShapeFlags (unittest .TestCase ): 818"""`strata --geometry` and `strata --families` are answered by every engine program before any device is touched: the CUDA/HIP/Metal 819program (src/program/generate.cpp) and the Intel one (sycl/src/program/generate.cpp, its own program). Without them a SYCL shape engine 820was installed with no geometry check (an engine that does not know the flag is accepted as one from before it).""" 821 822PROGRAMS = ("src/program/generate.cpp" ,"sycl/src/program/generate.cpp" ) 823 824def _early_block (self ,rel ): 825src = (ROOT / rel ).read_text (encoding = "utf-8" ) 826start = src .index ('std::strcmp(argv[i], "--version") == 0' ) 827end = src .index ("\n }\n" ,start )# the end of the early `for (int i = 1; i < argc && i < 3; ++i)` loop 828return src [start :end ] 829 830def test_both_flags_are_in_the_early_loop_of_every_program (self ): 831for rel in self .PROGRAMS : 832with self .subTest (program = rel ): 833block = self ._early_block (rel ) 834self .assertIn ('std::strcmp(argv[i], "--geometry") == 0' ,block ) 835self .assertIn ('std::printf("%s\\n", strata::core::kGeometryName);' ,block ) 836self .assertIn ('std::strcmp(argv[i], "--families") == 0' ,block ) 837self .assertIn ('std::printf("qwen4exp\\n");' ,block ) 838 839def test_the_intel_program_names_no_qwen35_family (self ): 840block = self ._early_block ("sycl/src/program/generate.cpp" ) 841printed = [ln for ln in block .splitlines ()if "std::printf(" in ln ] 842self .assertFalse ([ln for ln in printed if "qwen35moe" in ln ],"the Intel engine has no qwen35moe path" ) 843 844 845if __name__ == "__main__" : 846unittest .main ()