okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1"""setup.py and the model tables with models from the signed feed (strata_control/feed_models.py). 2 3python -m pytest tools/test_setup_feed_models.py 4 5A feed model goes into the same tables a built-in model is in, so setup, the Terminal and the app list it after the built-in ones and it is installed, pinned, 6checked and (when wrong) kept as `.bad` by the same code. Downloads, the engine and processes are mocked; a folder signed with a throwaway key is the feed. 7With no `models` member nothing changes: the tables are compared before and after. 8""" 9from __future__import annotations 10 11import argparse 12import base64 13import contextlib 14import copy 15import hashlib 16import importlib .util 17import io 18import json 19import os 20import re 21import sys 22import tempfile 23import unittest 24from pathlib import Path 25from unittest import mock 26 27ROOT = Path (__file__ ).resolve ().parents [1 ] 28sys .path .insert (0 ,str (ROOT )) 29sys .path .insert (0 ,str (ROOT / "tools" )) 30 31from strata_control import feed as feedmod # noqa: E402 32from strata_control import feed_models ,signing # noqa: E402 33 34REV = "0123456789abcdef0123456789abcdef01234567" 35SHIPPED_POLICY = feed_models .UNAVAILABLE_POLICY 36CONTENT = {"a-00001-of-00002.gguf" :b"first part of a model" ,"a-00002-of-00002.gguf" :b"second part" ,"mmproj-q4.gguf" :b"the picture reader" , 37"Q4-model.gguf" :b"one whole model file" } 38 39 40def pin (name ): 41return len (CONTENT [name ]),hashlib .sha256 (CONTENT [name ]).hexdigest () 42 43 44def file_entry (name ,folder = "" ): 45size ,sha = pin (name ) 46return {"name" :name ,"size" :size ,"sha256" :sha ,** ({"path" :f" { folder } / { name } " }if folder else {})} 47 48 49def flash_next (** kw ): 50m = {"id" :"qwen4-test" ,"title" :"Qwen4 Test" ,"by" :"Qwen" ,"about" :"a test model" ,"licence" :"Apache 2.0" , 51"licence_url" :"https://huggingface.co/test/qwen4-test" ,"family" :"qwen4exp" ,"repo" :"test/Qwen4-Test-GGUF" ,"revision" :REV , 52"pictures" :True ,"drafter" :"mtp" ,"context" :131072 ,"min_engine" :"0.2.12" ,"mmproj" :file_entry ("mmproj-q4.gguf" ), 53"quants" : [{"name" :"Q4_K_M" ,"about" :"4-bit" ,"ram_gb" :48 ,"arena_gb" :30.5 , 54"files" : [file_entry ("a-00001-of-00002.gguf" ,"Q4_K_M" ),file_entry ("a-00002-of-00002.gguf" ,"Q4_K_M" )]}]} 55m .update (kw ) 56return m 57 58 59def own_path (** kw ): 60m = flash_next (id = "qwen35-test" ,title = "Qwen35 Test" ,family = "qwen35moe" ,repo = "test/Qwen35-Test-GGUF" ,kv_bytes_per_token = 90112 , 61quants = [{"name" :"UD-Q4" ,"about" :"4-bit" ,"ram_gb" :30 ,"files" : [file_entry ("Q4-model.gguf" )]}],mmproj = file_entry ("mmproj-q4.gguf" )) 62m .update (kw ) 63return m 64 65 66# setup.main() on a Mac runs the Metal installer (metal/setup_mac.py): the command-line tests below are about the PC flow, so on macOS 67# they run it as on Linux (on Linux and Windows this is the platform they already have) 68LINUX_PC = "linux" if sys .platform == "darwin" else sys .platform 69 70 71def fresh_setup (name = "setup_under_test" ): 72"""setup.py loaded again under its own name, so a test's registrations never reach another test.""" 73spec = importlib .util .spec_from_file_location (name ,ROOT / "setup.py" ) 74mod = importlib .util .module_from_spec (spec ) 75spec .loader .exec_module (mod ) 76return mod 77 78 79def tables (mod )-> str : 80return json .dumps ({k :getattr (mod ,k )for k in ("MODELS" ,"FAMILIES" ,"OWN_PATH_FAMILIES" ,"REPO_PINS" ,"HF_REVISIONS" )}, 81sort_keys = True ,default = str )+ repr (sorted (mod .REV_PINS ))+ repr (getattr (mod ,"FEED_MODELS" ,None )) 82 83 84def parsed (* models )-> tuple : 85doc = {"schema_version" :1 ,"feed" :"strata-updates" ,"channel" :"stable" ,"sequence" :1 ,"generated_at" :"2026-11-06T00:00:00Z" ,"expires_at" :None , 86"models" : {"packages" :list (models )}} 87f = feedmod .parse (json .dumps (doc ).encode (),source = "x" ,key_id = "k" ) 88assert not f .models_dropped ,f .models_dropped 89return f .models 90 91 92class Base (unittest .TestCase ): 93def setUp (self ): 94self .tmp = tempfile .TemporaryDirectory () 95self .addCleanup (self .tmp .cleanup ) 96self .root = Path (self .tmp .name ) 97self .key = signing .generate_key () 98keys = self .root / "keys.json" 99keys .write_text (json .dumps ({"keys" : [signing .public_part (self .key )]}),encoding = "utf-8" ) 100patch = mock .patch .dict (os .environ , {"STRATA_COMPONENTS_DIR" :str (self .root / "components" ),"STRATA_UPDATE_TRUSTED_KEYS" :str (keys )}) 101patch .start () 102self .addCleanup (patch .stop ) 103os .environ .pop ("STRATA_FEED_MODELS" ,None ) 104policy = mock .patch .object (feed_models ,"UNAVAILABLE_POLICY" ,"not_offered" )# the tests below were written for "not_offered"; OwnerRule sets its own 105policy .start () 106self .addCleanup (policy .stop ) 107from strata_control import mac_fit # the Mac tables are module globals: each test gets them back as they were 108saved = (dict (mac_fit .MAC_MODELS ),dict (mac_fit .MAC_ABOUT ),list (mac_fit .FEED_FAMILIES )) 109 110def restore_mac (): 111mac_fit .MAC_MODELS .clear () 112mac_fit .MAC_MODELS .update (saved [0 ]) 113mac_fit .MAC_ABOUT .clear () 114mac_fit .MAC_ABOUT .update (saved [1 ]) 115mac_fit .FEED_FAMILIES [:]= saved [2 ] 116self .addCleanup (restore_mac ) 117self .setup = fresh_setup () 118 119def signed_feed (self ,name = "feed" ,sequence = 1 ,models = None )-> str : 120out = self .root / name 121out .mkdir (exist_ok = True ) 122members = {"schema_version" :1 ,"feed" :"strata-updates" ,"channel" :"stable" ,"sequence" :sequence ,"generated_at" :"2026-11-06T00:00:00Z" , 123"expires_at" :None } 124if models is not None : 125members ["models" ]= {"packages" :models } 126payload = (json .dumps (members ,indent = 1 ,sort_keys = True )+ "\n" ).encode () 127 (out / feedmod .FEED_NAME ).write_bytes (payload ) 128 (out / (feedmod .FEED_NAME + ".sig" )).write_text (json .dumps (signing .sign_bytes (self .key ,payload )),encoding = "utf-8" ) 129return str (out ) 130 131 132class NothingChangesWithoutModels (Base ): 133def test_the_tables_are_the_same_without_a_models_member (self ): 134before = tables (self .setup ) 135reference = tables (fresh_setup ("setup_reference" )) 136self .assertEqual (before ,reference ) 137self .setup .feed_models_setup (fetch = False )# no cache 138self .assertEqual (tables (self .setup ),before ) 139self .setup .feed_models_setup (self .signed_feed ("plain" ))# a signed feed with no models member 140self .assertEqual (tables (self .setup ),before ) 141self .assertIsNone (self .setup .FEED_MODELS ) 142self .assertEqual (self .setup .FEED_UNAVAILABLE , {}) 143self .assertFalse ((self .root / "components" ).exists ())# nothing written either 144 145def test_apply_of_an_empty_list_touches_nothing (self ): 146before = tables (self .setup ) 147result = feed_models .apply (self .setup , (), {"qwen4exp" }) 148self .assertEqual ((result .registered ,result .unavailable ,result .skipped ), ([], {}, [])) 149self .assertEqual (tables (self .setup ),before ) 150 151def test_the_menu_helpers_see_the_same_families (self ): 152self .setup .feed_models_setup (self .signed_feed ("plain" )) 153self .assertEqual (self .setup .menu_families (False ),list (fresh_setup ("setup_reference" ).FAMILIES )) 154 155 156class FlashNextModel (Base ): 157def setUp (self ): 158super ().setUp () 159self .result = feed_models .apply (self .setup ,parsed (flash_next ()), {"qwen4exp" ,"qwen35moe" }) 160self .fam = self .setup .FAMILIES ["qwen4-test" ] 161 162def test_it_is_listed_after_the_built_in_ones (self ): 163self .assertEqual (self .result .registered , ["qwen4-test" ]) 164built_in = list (fresh_setup ("setup_reference" ).FAMILIES ) 165self .assertEqual (list (self .setup .FAMILIES ),built_in + ["qwen4-test" ]) 166self .assertEqual (self .setup .menu_families (False )[- 1 ],"qwen4-test" ) 167self .assertEqual (self .fam ["title" ],"Qwen4 Test" ) 168self .assertIn ("Apache 2.0: https://huggingface.co/test/qwen4-test" ,self .fam ["license" ]) 169 170def test_files_folders_and_shards_come_from_the_feed (self ): 171m = "Q4_K_M" 172self .assertEqual (self .setup .model_shards (self .fam ,m ),2 ) 173self .assertEqual ([self .setup .model_file (self .fam ,m ,i )for i in (1 ,2 )], ["a-00001-of-00002.gguf" ,"a-00002-of-00002.gguf" ]) 174base = f" { self . setup . hf_endpoint () } /test/Qwen4-Test-GGUF/resolve/ { REV } /Q4_K_M/" 175self .assertEqual (self .setup .model_hf (self .fam ,m ),base ) 176self .assertEqual (self .fam ["mmproj_hf" ],f" { self . setup . hf_endpoint () } /test/Qwen4-Test-GGUF/resolve/ { REV } /" ) 177d = self .setup .MODELS [m ] 178self .assertEqual ((d ["download_gb" ],d ["ram_gb" ],d ["arena_gb" ],d ["engine" ],d ["families" ]), (0.0 ,48.0 ,30.5 , (0 ,2 ,12 ), ("qwen4-test" ,))) 179self .assertTrue (d ["vision" ]) 180 181def test_every_file_is_pinned_where_downloads_look_it_up (self ): 182base = self .setup .model_hf (self .fam ,"Q4_K_M" ) 183for name in ("a-00001-of-00002.gguf" ,"a-00002-of-00002.gguf" ): 184self .assertEqual (self .setup .file_pin (base + name ),pin (name )) 185self .assertEqual (self .setup .file_pin (self .fam ["mmproj_hf" ]+ "mmproj-q4.gguf" ),pin ("mmproj-q4.gguf" )) 186self .assertEqual (self .fam ["mmproj_sha256" ],pin ("mmproj-q4.gguf" )) 187self .assertIsNone (self .setup .file_pin (base + "other.gguf" )) 188 189def test_its_config_is_found_again_by_choices_from_config (self ): 190cfg = self .root / "strata-qwen4-test-q4_k_m.json" 191cfg .write_text (json .dumps ({"args" : ["--max-context" ,"65536" ],"arch" :"qwen4exp" }),encoding = "utf-8" ) 192got = self .setup .choices_from_config (cfg ) 193self .assertEqual ((got ["family" ],got ["model" ],got ["context" ]), ("qwen4-test" ,"Q4_K_M" ,65536 )) 194 195def test_a_size_name_that_a_built_in_model_has_gets_the_models_id (self ): 196feed_models .apply (self .setup ,parsed (flash_next (id = "qwen4-two" ,quants = [{"name" :"IQ3_S" ,"about" :"x" ,"ram_gb" :40 ,"files" : [file_entry ("Q4-model.gguf" )]}])),None ) 197self .assertIn ("IQ3_S" ,self .setup .MODELS )# the built-in one is untouched 198self .assertEqual (self .setup .MODELS ["IQ3_S" ],fresh_setup ("setup_reference" ).MODELS ["IQ3_S" ]) 199self .assertEqual (self .setup .MODELS ["IQ3_S-qwen4-two" ]["quant" ],"IQ3_S" ) 200 201def test_a_built_in_id_or_tag_is_never_replaced (self ): 202before = copy .deepcopy (self .setup .FAMILIES ["swift" ]) 203for clash in ("swift" ,"qwen" ,"unsloth" ,"qwen36" ,"coder-x" ,"unsloth-2" ): 204result = feed_models .apply (self .setup ,parsed (flash_next (id = clash )),None ) 205self .assertEqual (result .registered , [],clash ) 206self .assertEqual (len (result .skipped ),1 ,clash ) 207self .assertEqual (self .setup .FAMILIES ["swift" ],before ) 208 209def test_a_model_without_a_picture_reader_has_no_mmproj_and_install_does_not_look_one_up (self ): 210# found by the Q4-P8 rehearsal on a real install: setup's step 5 read fam['mmproj'] for a feed model that lists none (KeyError after the checks of the files) 211entry = flash_next (id = "no-reader" ) 212entry .pop ("mmproj" ,None ) 213entry ["pictures" ]= False 214result = feed_models .apply (self .setup ,parsed (entry ),None ) 215self .assertEqual (result .registered , ["no-reader" ]) 216fam = self .setup .FAMILIES ["no-reader" ] 217self .assertNotIn ("mmproj" ,fam ) 218self .assertIs (fam ["vision" ],False ) 219src = (Path (self .setup .__file__ )).read_text (encoding = "utf-8" ) 220self .assertNotIn ("find_in(roots, f\"models/{fam['mmproj']}\") or mmproj\n if vision != \"none\":" ,src ) 221 222def test_the_family_carries_the_feeds_drafter_so_setup_can_leave_the_draft_layer_out (self ): 223# found by the Q4-P8 rehearsal: setup fetched the Flash-Next MTP draft layer (5 GB) for a feed model whose entry says drafter none 224none = feed_models .apply (self .setup ,parsed (flash_next (id = "no-drafter" ,drafter = "none" )),None ) 225self .assertEqual (self .setup .FAMILIES ["no-drafter" ]["drafter" ],"none" ) 226src = Path (self .setup .__file__ ).read_text (encoding = "utf-8" ) 227self .assertIn ('fam.get("feed") and fam.get("drafter") == "none" and a.mtp is None' ,src ) 228 229def test_a_feed_flash_next_size_is_read_in_place_with_a_ram_budget_like_the_built_in_unsloth_sizes (self ): 230# found by the Q4-P8 rehearsal on Strix: without "budget" setup chose the low-RAM mode and began writing a 77 GB second copy of the experts 231result = feed_models .apply (self .setup ,parsed (flash_next (id = "budgeted" )),None ) 232for key in [k for k ,v in self .setup .MODELS .items ()if "budgeted" in v .get ("families" , ())]: 233self .assertIs (self .setup .MODELS [key ]["budget" ],True ) 234self .assertFalse (self .setup .low_ram_wanted (key ,64.0 ,"auto" )) 235 236def test_parts_that_are_not_numbered_are_left_out_with_a_line (self ): 237odd = flash_next (id = "odd-parts" ) 238odd ["quants" ][0 ]["files" ][1 ]= file_entry ("Q4-model.gguf" ,"Q4_K_M" ) 239result = feed_models .apply (self .setup ,parsed (odd ),None ) 240self .assertEqual ((result .registered ,len (result .skipped )), ([],1 )) 241self .assertNotIn ("odd-parts" ,self .setup .FAMILIES ) 242 243 244class OwnPathModel (Base ): 245def setUp (self ): 246super ().setUp () 247self .result = feed_models .apply (self .setup ,parsed (own_path ()), {"qwen4exp" ,"qwen35moe" }) 248self .fam = self .setup .OWN_PATH_FAMILIES ["qwen35-test" ] 249 250def test_it_joins_the_own_path_families (self ): 251self .assertEqual (self .result .registered , ["qwen35-test" ]) 252self .assertIs (self .setup .PREVIEW_FAMILIES ,self .setup .OWN_PATH_FAMILIES ) 253self .assertEqual (list (self .setup .OWN_PATH_FAMILIES ), ["qwen36" ,"qwen35-test" ]) 254self .assertEqual ((self .fam ["arch" ],self .fam ["mtp" ],self .fam ["kv_bytes_per_token" ],list (self .fam ["models" ])), ("qwen35moe" ,2 ,90112 , ["UD-Q4" ])) 255self .assertEqual (self .fam ["file" ].format (q = "UD-Q4" ),"Q4-model.gguf" ) 256url = self .fam ["hf" ]+ "Q4-model.gguf" 257self .assertEqual (self .setup .file_pin (url ),pin ("Q4-model.gguf" )) 258self .assertEqual (self .setup .own_path_size (self .fam ,64.0 ),"UD-Q4" ) 259 260def test_the_built_in_qwen36_is_unchanged (self ): 261self .assertEqual (self .setup .OWN_PATH_FAMILIES ["qwen36" ],fresh_setup ("setup_reference" ).OWN_PATH_FAMILIES ["qwen36" ]) 262 263def test_install_uses_the_feeds_pin_and_the_same_steps (self ): 264calls ,cfg = [], {} 265eng = self .root / "engine" 266eng .mkdir () 267 (eng / self .setup .VEXE ).write_text ("x" ) 268 269def engine_step (a ,gpu ,hip ,amd ,cuda_tk ,vision ): 270return self .root / "llama" ,eng , {"version" :"0.2.12" }, ["/libs" ],gpu ,vision 271 272def write_cfg (path ,c ,source = None ,explicit = None ): 273cfg .update (c ) 274calls .append (("config" ,path .name )) 275 276s = self .setup 277patches = [mock .patch .object (s ,"download" ,lambda url ,dst ,what = None :calls .append (("get" ,url ,dst .name ))), 278mock .patch .object (s ,"verify_sha256" ,lambda p ,size ,sha ,own = False :calls .append (("sha" ,p .name ,size ,sha ))), 279mock .patch .object (s ,"free_gb" ,lambda p :500.0 ),mock .patch .object (s ,"pip_install" ,lambda * a ,** k :None ), 280mock .patch .object (s ,"engine_step" ,engine_step ),mock .patch .object (s ,"engine_families" ,lambda e : {"qwen4exp" ,"qwen35moe" }), 281mock .patch .object (s ,"run" ,lambda cmd ,** k :calls .append (("run" ,cmd ))), 282mock .patch .object (s ,"data_folder" ,lambda d ,* a ,** k : (self .root / "data" , [])), 283mock .patch .object (s ,"write_setup_config" ,write_cfg ), 284mock .patch .object (s ,"write_run_script" ,lambda tag ,p ,port ,o = True :self .root / f"run- { tag } .sh" ), 285mock .patch .object (s ,"recommend_pool_workers" ,lambda a :a ),mock .patch .object (s ,"ROOT" ,self .root )] 286for p in patches : 287p .start () 288self .addCleanup (p .stop ) 289a = argparse .Namespace (family = "qwen35-test" ,model = "UD-Q4" ,check = False ,yes = True ,vision = "cpu" ,models_dir = str (self .root / "models" ),gguf_dir = None , 290context = None ,rope_scaling = None ,rope_scale = None ,kv = None ,resident_budget_gib = None ,low_ram = "auto" ,vram_reserve_mib = None , 291host = None ,api_key = None ,browser = None ,no_start = True ,data_dir = None ,gpu = None ) 292gpu = {"index" :0 ,"count" :1 ,"vram_gb" :16.0 ,"name" :"Test GPU" } 293out = io .StringIO () 294with contextlib .redirect_stdout (out ): 295rc = s .install_own_path (a ,"qwen35-test" ,gpu ,False , [],13 , [],8080 ,64.0 ,None ) 296self .assertEqual (rc ,0 ,out .getvalue ()) 297base = f" { s . hf_endpoint () } /test/Qwen35-Test-GGUF/resolve/ { REV } /" 298self .assertIn (("get" ,base + "Q4-model.gguf" ,"Q4-model.gguf" ),calls ) 299self .assertIn (("get" ,base + "mmproj-q4.gguf" ,"mmproj-q4.gguf" ),calls ) 300self .assertIn (("sha" ,"Q4-model.gguf" ,* pin ("Q4-model.gguf" )),calls )# the feed's size and SHA-256 reach the check 301self .assertIn (("sha" ,"mmproj-q4.gguf" ,* pin ("mmproj-q4.gguf" )),calls ) 302self .assertEqual ((cfg ["arch" ],cfg ["model_name" ]), ("qwen35moe" ,"qwen35-test-ud-q4" )) 303self .assertIn (("config" ,"strata-qwen35-test-ud-q4.json" ),calls ) 304self .assertEqual (cfg ["args" ][cfg ["args" ].index ("--native" )+ 1 ],str (self .root / "models" / "qwen35-test-UD-Q4" / "Q4-model.gguf" )) 305self .assertEqual (cfg ["args" ][cfg ["args" ].index ("--mtp" )+ 1 ],"2" ) 306 307 308class PinVerifyAndBad (Base ): 309"""The same functions a built-in model's download goes through, on a feed model's tiny files.""" 310 311def setUp (self ): 312super ().setUp () 313feed_models .apply (self .setup ,parsed (own_path ()),None ) 314self .fam = self .setup .OWN_PATH_FAMILIES ["qwen35-test" ] 315self .dst = self .root / "models" / "Q4-model.gguf" 316self .dst .parent .mkdir () 317self .url = self .fam ["hf" ]+ "Q4-model.gguf" 318 319def test_a_wrong_file_is_kept_as_bad_and_stops_setup (self ): 320self .dst .write_bytes (b"x" * len (CONTENT ["Q4-model.gguf" ]))# the pinned size, other bytes 321with contextlib .redirect_stdout (io .StringIO ())as out ,self .assertRaises (SystemExit ): 322self .setup .verify_sha256 (self .dst ,* self .fam ["sha256" ]["Q4-model.gguf" ]) 323self .assertTrue (self .dst .with_name ("Q4-model.gguf.bad" ).is_file ()) 324self .assertFalse (self .dst .exists ()) 325self .assertIn ("does not match the pinned SHA-256" ,out .getvalue ()) 326 327def test_a_right_file_passes_and_gets_its_finish_mark (self ): 328self .dst .write_bytes (CONTENT ["Q4-model.gguf" ]) 329with contextlib .redirect_stdout (io .StringIO ()): 330self .setup .verify_sha256 (self .dst ,* self .fam ["sha256" ]["Q4-model.gguf" ]) 331self .assertTrue (self .setup .done (self .dst )) 332 333def test_download_takes_back_a_bad_file_that_matches_the_pin_without_the_network (self ): 334bad = self .dst .with_name ("Q4-model.gguf.bad" ) 335bad .write_bytes (CONTENT ["Q4-model.gguf" ]) 336with contextlib .redirect_stdout (io .StringIO ()),mock .patch .object (self .setup ,"_urlopen" ,side_effect = AssertionError ("network" )): 337self .setup .download (self .url ,self .dst ) 338self .assertEqual (self .dst .read_bytes (),CONTENT ["Q4-model.gguf" ]) 339self .assertFalse (bad .exists ()) 340 341def test_download_does_not_take_back_a_bad_file_of_the_wrong_size_or_bytes (self ): 342bad = self .dst .with_name ("Q4-model.gguf.bad" ) 343bad .write_bytes (b"x" * len (CONTENT ["Q4-model.gguf" ]))# the pinned size, other bytes 344with contextlib .redirect_stdout (io .StringIO ()),mock .patch .object (self .setup ,"_urlopen" ,side_effect = RuntimeError ("network" )), \ 345mock .patch .object (self .setup ,"acquisition" )as acquisition : 346acquisition .require .side_effect = RuntimeError ("stopped before the network" ) 347with self .assertRaises (RuntimeError ): 348self .setup .download (self .url ,self .dst ) 349self .assertFalse (self .dst .exists ()) 350 351 352class RefusalsAndOffline (Base ): 353def test_a_family_the_engine_does_not_run_is_listed_as_not_available_and_never_added (self ): 354result = feed_models .apply (self .setup ,parsed (own_path (),flash_next (id = "later-one" ,family = "qwen5new" )), {"qwen4exp" }) 355self .assertEqual (result .registered , []) 356self .assertEqual (sorted (result .unavailable ), ["later-one" ,"qwen35-test" ]) 357self .assertNotIn ("qwen35-test" ,self .setup .OWN_PATH_FAMILIES ) 358self .assertNotIn ("later-one" ,self .setup .FAMILIES ) 359self .assertEqual (self .setup .FEED_UNAVAILABLE ["qwen35-test" ]["reason" ],feed_models .UNAVAILABLE_ENGINE ) 360self .assertEqual (self .setup .FEED_UNAVAILABLE ["later-one" ]["reason" ],feed_models .UNAVAILABLE_UNKNOWN ) 361self .assertNotIn ("test/Qwen35-Test-GGUF" ,self .setup .HF_REVISIONS )# no pin was added for a model nobody can install 362self .assertFalse ([k for k in self .setup .REV_PINS if k [0 ]== "test/Qwen35-Test-GGUF" ]) 363 364def test_without_an_engine_to_ask_an_installable_family_is_offered_and_setup_checks_at_install (self ): 365result = feed_models .apply (self .setup ,parsed (own_path ()),None ) 366self .assertEqual (result .registered , ["qwen35-test" ]) 367 368def test_naming_an_unavailable_model_on_the_command_line_says_why_and_stops (self ): 369feed = self .signed_feed ("f" ,1 , [own_path ()]) 370argv = ["setup.py" ,"--family" ,"qwen35-test" ,"--feed" ,feed ,"--yes" ] 371with mock .patch .object (sys ,"argv" ,argv ),mock .patch .object (self .setup ,"feed_engine_families" ,lambda : {"qwen4exp" }), \ 372mock .patch .object (self .setup .sys ,"platform" ,LINUX_PC ), \ 373contextlib .redirect_stdout (io .StringIO ())as out ,self .assertRaises (SystemExit )as stop : 374self .setup .main () 375self .assertNotEqual (stop .exception .code ,0 ) 376self .assertIn (feed_models .UNAVAILABLE_ENGINE ,out .getvalue ()) 377 378def test_the_command_line_accepts_a_feed_model_and_its_size (self ): 379feed = self .signed_feed ("f" ,1 , [own_path ()]) 380argv = ["setup.py" ,"--family" ,"qwen35-test" ,"--model" ,"UD-Q4" ,"--feed" ,feed ,"--check" ] 381with mock .patch .object (sys ,"argv" ,argv ),mock .patch .object (self .setup ,"feed_engine_families" ,lambda : {"qwen4exp" ,"qwen35moe" }), \ 382mock .patch .object (self .setup .sys ,"platform" ,LINUX_PC ), \ 383mock .patch .object (self .setup ,"gather_hardware" ,side_effect = SystemExit (77 ),create = True ),contextlib .redirect_stdout (io .StringIO ()): 384try : 385self .setup .main () 386except SystemExit : 387pass 388except Exception :# noqa: BLE001 - the hardware step is not under test 389pass 390self .assertIn ("qwen35-test" ,self .setup .OWN_PATH_FAMILIES )# argparse got past --family / --model 391 392def test_offline_the_last_verified_list_is_what_the_tables_get (self ): 393feed = self .signed_feed ("f" ,7 , [flash_next ()]) 394self .setup .feed_models_setup (feed ) 395self .assertIn ("qwen4-test" ,self .setup .FAMILIES ) 396other = fresh_setup ("setup_offline" ) 397other .feed_models_setup (str (self .root / "unreachable" )) 398self .assertEqual (list (other .FAMILIES )[- 1 ],"qwen4-test" ) 399none = fresh_setup ("setup_none" ) 400none .feed_models_setup (fetch = False ) 401self .assertIn ("qwen4-test" ,none .FAMILIES )# the Terminal and app read the cache only 402 403 404class TerminalAndApp (Base ): 405"""strata_mcp is the app's and the Terminal's one catalog.""" 406 407def table (self ,ram = 64.0 ): 408import strata_mcp as M 409s = M .Strata (ROOT ) 410# the PC these tests describe, not the box they run on (p1006's real Arc card sent install_plan down the Intel path) 411s ._hardware = lambda : {"os" :"TestOS 1" ,"ram_gb" :ram ,"cpu" : {"name" :"Fake CPU" ,"cores" :12 ,"avx2" :True ,"avx512" :False }, 412"gpus" : [{"index" :0 ,"name" :"NVIDIA GeForce RTX 5070" ,"vram_gb" :11.9 ,"arch" :"120" ,"vendor" :"nvidia" , 413"problem" :None ,"usable" :True }]} 414return s ,s .model_table ({"ram_gb" :ram ,"gpus" : [{"index" :0 ,"name" :"x" ,"vram_gb" :12.0 ,"usable" :True }]}) 415 416def test_without_a_list_the_table_is_the_same (self ): 417s ,rows = self .table () 418self .assertEqual ([r ["family" ]for r in rows ], [f for f in fresh_setup ("setup_reference" ).FAMILIES ]+ ["qwen36" ]) 419self .assertTrue (all ("available" not in r for r in rows )) 420 421def test_a_cached_list_adds_its_sizes_after_the_built_in_ones_and_hides_what_cannot_run (self ): 422feed_models .load (self .signed_feed ("f" ,7 , [flash_next (),flash_next (id = "later-one" ,family = "qwen5new" )]),trusted = { 423self .key ["key_id" ]:base64 .b64decode (self .key ["public" ])}) 424s ,rows = self .table () 425by = {r ["family" ]:r for r in rows } 426self .assertEqual ([r ["family" ]for r in rows ][- 2 :], ["qwen4-test" ,"later-one" ]) 427row = by ["qwen4-test" ] 428self .assertEqual ([x ["model" ]for x in row ["sizes" ]], ["Q4_K_M" ]) 429size = row ["sizes" ][0 ] 430self .assertEqual ((size ["id" ],size ["images" ],size ["engine_min" ],size ["ram_needed_gb" ]), ("qwen4-test-q4_k_m" ,True ,"0.2.12" ,48.0 )) 431self .assertEqual (by ["later-one" ]["sizes" ], [])# the app hides a family without sizes 432self .assertFalse (by ["later-one" ]["available" ]) 433self .assertEqual (by ["later-one" ]["unavailable_reason" ],feed_models .UNAVAILABLE_UNKNOWN ) 434import strata_mcp as M 435plan ,args = M .Tools (s ).install_plan ("qwen4-test" ,"Q4_K_M" ,65536 ,"no" ,None ,None ,None ,None ,"auto" ,None ,None ) 436self .assertEqual (args [args .index ("--family" )+ 1 :args .index ("--family" )+ 4 :2 ], ["qwen4-test" ,"Q4_K_M" ])# the install runs setup with the feed model's names 437self .assertEqual (plan ["download_gb" ],0.0 ) 438 439 440class OwnerRule (Base ): 441"""feed_models.UNAVAILABLE_POLICY: one line decides whether a model the engine does not run is only said ("not_offered") or warned about and allowed ("warn_allow").""" 442 443def test_warn_allow_registers_a_known_family_and_keeps_the_sentence (self ): 444with mock .patch .object (feed_models ,"UNAVAILABLE_POLICY" ,"warn_allow" ): 445result = feed_models .apply (self .setup ,parsed (own_path (),flash_next (id = "later-one" ,family = "qwen5new" )), {"qwen4exp" }) 446self .assertEqual (result .registered , ["qwen35-test" ]) 447self .assertIn ("qwen35-test" ,self .setup .OWN_PATH_FAMILIES ) 448self .assertTrue (self .setup .FEED_UNAVAILABLE ["qwen35-test" ]["allowed" ]) 449self .assertNotIn ("later-one" ,self .setup .FAMILIES )# a family this Control does not know is never installable 450self .assertFalse (self .setup .FEED_UNAVAILABLE ["later-one" ]["allowed" ]) 451 452def test_warn_allow_install_warns_and_goes_on (self ): 453with mock .patch .object (feed_models ,"UNAVAILABLE_POLICY" ,"warn_allow" ): 454feed_models .apply (self .setup ,parsed (own_path ()), {"qwen4exp" }) 455s = self .setup 456eng = self .root / "engine" 457eng .mkdir () 458calls = [] 459patches = [mock .patch .object (s ,"download" ,lambda url ,dst ,what = None :calls .append (("get" ,dst .name ))), 460mock .patch .object (s ,"verify_sha256" ,lambda p ,size ,sha ,own = False :None ),mock .patch .object (s ,"free_gb" ,lambda p :500.0 ), 461mock .patch .object (s ,"pip_install" ,lambda * a ,** k :None ), 462mock .patch .object (s ,"engine_step" ,lambda a ,gpu ,hip ,amd ,tk ,v : (self .root / "llama" ,eng , {"version" :"0.2.12" }, [],gpu ,"none" )), 463mock .patch .object (s ,"engine_families" ,lambda e : {"qwen4exp" }),mock .patch .object (s ,"run" ,lambda cmd ,** k :None ), 464mock .patch .object (s ,"data_folder" ,lambda d ,* a ,** k : (self .root / "data" , [])), 465mock .patch .object (s ,"write_setup_config" ,lambda * a ,** k :calls .append (("config" ,))), 466mock .patch .object (s ,"write_run_script" ,lambda tag ,p ,port ,o = True :self .root / "run.sh" ), 467mock .patch .object (s ,"recommend_pool_workers" ,lambda a :a ),mock .patch .object (s ,"ROOT" ,self .root )] 468for p in patches : 469p .start () 470self .addCleanup (p .stop ) 471a = argparse .Namespace (family = "qwen35-test" ,model = "UD-Q4" ,check = False ,yes = True ,vision = "no" ,models_dir = str (self .root / "models" ),gguf_dir = None , 472context = None ,rope_scaling = None ,rope_scale = None ,kv = None ,resident_budget_gib = None ,low_ram = "auto" ,vram_reserve_mib = None , 473host = None ,api_key = None ,browser = None ,no_start = True ,data_dir = None ,gpu = None ) 474out = io .StringIO () 475with contextlib .redirect_stdout (out ): 476rc = s .install_own_path (a ,"qwen35-test" , {"index" :0 ,"count" :1 ,"vram_gb" :16.0 ,"name" :"T" },False , [],13 , [],8080 ,64.0 ,None ) 477self .assertEqual (rc ,0 ,out .getvalue ()) 478self .assertIn (feed_models .UNAVAILABLE_ENGINE ,out .getvalue ()) 479self .assertIn (("get" ,"Q4-model.gguf" ),calls ) 480 481def test_the_shipped_policy_and_words (self ): 482self .assertEqual (SHIPPED_POLICY ,"warn_allow" )# the owner's standing rule: warn plainly, still allow, never refuse 483self .assertEqual (feed_models .UNAVAILABLE_ENGINE ,"needs a newer Strata engine: update Strata to use it" ) 484self .assertEqual (feed_models .UNAVAILABLE_UNKNOWN ,"this Strata version doesn't know this model yet: update Strata to use it" ) 485for family in ("qwen35moe" ,"qwen5new" ): 486self .assertNotIn (family ,feed_models .unavailable_reason (family )) 487 488 489class MacTables (Base ): 490"""The Mac (Metal) tables take the feed's models too: strata_control/mac_fit.py, metal/setup_mac.py and the app's Mac table.""" 491 492def setUp (self ): 493super ().setUp () 494from strata_control import mac_fit 495self .mf = mac_fit 496saved = (dict (mac_fit .MAC_MODELS ),dict (mac_fit .MAC_ABOUT ),list (mac_fit .FEED_FAMILIES )) 497 498def restore (): 499mac_fit .MAC_MODELS .clear () 500mac_fit .MAC_MODELS .update (saved [0 ]) 501mac_fit .MAC_ABOUT .clear () 502mac_fit .MAC_ABOUT .update (saved [1 ]) 503mac_fit .FEED_FAMILIES [:]= saved [2 ] 504self .addCleanup (restore ) 505 506def test_nothing_changes_without_feed_models (self ): 507self .assertEqual (self .mf .all_families (),self .mf .APP_FAMILIES ) 508feed_models .apply (self .setup , (),None ) 509self .assertEqual (self .mf .all_families (), ("qwen" ,"unsloth" ,"gyro" )) 510 511def test_a_feed_model_of_one_or_two_files_is_a_mac_size (self ): 512feed_models .apply (self .setup ,parsed (flash_next ()),None ) 513self .assertEqual (self .mf .all_families (), ("qwen" ,"unsloth" ,"gyro" ,"qwen4-test" )) 514self .assertEqual (self .mf .app_sizes ("qwen4-test" ), ["Q4_K_M" ]) 515d = self .mf .MAC_MODELS ["Q4_K_M" ] 516self .assertEqual ((d ["family" ],d ["shards" ],d ["tested" ]), ("qwen4-test" ,2 ,False )) 517self .assertIn ("has not been measured on a Mac" ," " .join (self .mf .model_note ("Q4_K_M" ,64.0 ))) 518self .assertEqual (self .mf .repacked_gb ("Q4_K_M" ),0.0 ) 519 520def test_a_model_of_more_than_two_files_is_not_offered_on_a_mac (self ): 521big = flash_next (id = "big-one" ) 522big ["quants" ][0 ]["files" ]= [{** file_entry ("a-00001-of-00002.gguf" ),"name" :f"b-0000 { i } -of-00003.gguf" ,"path" :f"Q4_K_M/b-0000 { i } -of-00003.gguf" }for i in (1 ,2 ,3 )] 523result = feed_models .apply (self .setup ,parsed (big ),None ) 524self .assertEqual (result .registered , ["big-one" ]) 525self .assertEqual (self .mf .app_sizes ("big-one" ), []) 526self .assertNotIn ("big-one" ,self .mf .FEED_FAMILIES ) 527 528def test_the_mac_table_lists_it_after_the_built_in_sizes (self ): 529feed_models .load (self .signed_feed ("f" ,7 , [flash_next ()]),trusted = {self .key ["key_id" ]:base64 .b64decode (self .key ["public" ])}) 530import strata_mcp as M 531rows = M .Strata (ROOT ).model_table ({"ram_gb" :64.0 ,"gpus" : [],"mac" : {"chip" :"M4" ,"unified_gb" :64 }}) 532by = {r ["family" ]:r for r in rows } 533self .assertTrue (by ["qwen4-test" ]["feed" ]) 534self .assertEqual ([x ["model" ]for x in by ["qwen4-test" ]["sizes" ]], ["Q4_K_M" ]) 535self .assertNotIn ("feed" ,by ["qwen" ]) 536 537def test_the_terminal_setup_reads_the_feed_for_a_name_it_does_not_know (self ): 538sys .path .insert (0 ,str (ROOT / "metal" )) 539import setup as global_setup 540import setup_mac 541saved = {k :copy .deepcopy (getattr (global_setup ,k ))for k in ("MODELS" ,"FAMILIES" ,"HF_REVISIONS" ,"REV_PINS" ,"FEED_MODELS" ,"FEED_UNAVAILABLE" )} 542 543def restore (): 544for k ,v in saved .items (): 545if isinstance (v ,dict )and k in ("MODELS" ,"FAMILIES" ,"HF_REVISIONS" ,"REV_PINS" ): 546getattr (global_setup ,k ).clear () 547getattr (global_setup ,k ).update (v ) 548else : 549setattr (global_setup ,k ,v ) 550self .addCleanup (restore ) 551feed = self .signed_feed ("f" ,7 , [flash_next ()]) 552setup_mac ._feed_models (["--family" ,"qwen4-test" ,"--feed" ,feed ],False ) 553self .assertIn ("qwen4-test" ,global_setup .FAMILIES ) 554self .assertEqual (setup_mac .model_shard_names ("Q4_K_M" ), ["a-00001-of-00002.gguf" ,"a-00002-of-00002.gguf" ]) 555self .assertEqual (setup_mac .model_shard_names ("Q2_0" ), [global_setup .model_file (global_setup .FAMILIES ["qwen" ],"Q2_0" ,i )for i in (1 ,2 )]) 556 557 558class TerminalRow (Base ): 559def test_the_terminal_names_what_this_engine_does_not_run (self ): 560from strata_cli .launch .catalog import Catalog 561feed_models .load (self .signed_feed ("f" ,7 , [flash_next (id = "later-one" ,family = "qwen5new" )]),trusted = {self .key ["key_id" ]:base64 .b64decode (self .key ["public" ])}) 562hw = {"ram_gb" :64.0 ,"gpus" : [],"disk_free_gb" :500.0 } 563cat = Catalog (src = ROOT ,root = self .root / "inst" ,hardware = hw ) 564self .assertEqual (cat .unavailable (hw ), [("Qwen4 Test" ,feed_models .UNAVAILABLE_UNKNOWN )]) 565self .assertNotIn ("later-one" , [r .family for r in cat .rows (hw )]) 566 567 568if __name__ == "__main__" : 569unittest .main ()