okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0f1e5e4cb
main
1"""The desktop app's installer: tools/strata_mcp.py and setup.py run on Control's Python in STRATA_CONTROL_INSTALL mode. 2 3What the owner asked for: a user installs the app, picks a model in it and downloads and prepares it, like any normal user. 4What must stay true: a start or a serve never acquires anything (tests/terminal/test_no_acquisition.py), and the install 5itself downloads model files only - no pip, no git, no compiler, no engine fetch, only the bundled preparation tools. 6""" 7 8from __future__import annotations 9 10import importlib .util 11import json 12import os 13import subprocess 14import sys 15import tempfile 16import unittest 17from pathlib import Path 18from unittest import mock 19 20ROOT = Path (__file__ ).resolve ().parents [2 ] 21sys .path .insert (0 ,str (ROOT )) 22 23 24def load_setup (home :Path ,name :str = "setup_control_mode" ): 25"""setup.py imported as the app's installer: the mode is read when the module loads.""" 26env = {"STRATA_CONTROL_INSTALL" :"1" ,"STRATA_INSTALL_DIR" :str (home )} 27with mock .patch .dict (os .environ ,env ): 28spec = importlib .util .spec_from_file_location (name ,ROOT / "setup.py" ) 29module = importlib .util .module_from_spec (spec ) 30spec .loader .exec_module (module ) 31return module 32 33 34class ControlModeTests (unittest .TestCase ): 35def setUp (self ): 36self .tmp = tempfile .TemporaryDirectory () 37self .addCleanup (self .tmp .cleanup ) 38self .home = Path (self .tmp .name )/ "install" 39self .home .mkdir () 40self .S = load_setup (self .home ) 41 42def test_the_folder_everything_is_written_to_is_the_install_folder_not_the_bundle (self ): 43S = self .S 44self .assertTrue (S .CONTROL ) 45self .assertEqual (S .home (),self .home .resolve ()) 46self .assertEqual (S .ROOT ,ROOT ) 47# without the mode nothing moves: HOME is the source folder, as it always was 48spec = importlib .util .spec_from_file_location ("setup_plain_mode" ,ROOT / "setup.py" ) 49plain = importlib .util .module_from_spec (spec ) 50with mock .patch .dict (os .environ , {"STRATA_CONTROL_INSTALL" :"0" }): 51spec .loader .exec_module (plain ) 52self .assertFalse (plain .CONTROL ) 53self .assertEqual (plain .home (),plain .ROOT ) 54 55def test_only_this_python_running_a_bundled_tool_may_run (self ): 56S = self .S 57tool = ROOT / "tools" / "pack_index.py" 58for refused in ( 59 [sys .executable ,"-m" ,"pip" ,"install" ,"numpy" ], 60 ["pip" ,"install" ,"numpy" ], 61 ["git" ,"clone" ,"https://example.invalid/x.git" ], 62 ["cmake" ,"--build" ,"." ], 63 ["winget" ,"install" ,"Nvidia.CUDA" ], 64 [sys .executable ,str (self .home / "evil.py" )],# a script outside the bundled tools 65 [sys .executable ,str (ROOT / "setup.py" ),"--build" ], 66 [sys .executable ], 67 ): 68with self .subTest (refused = refused ),mock .patch .object (S .subprocess ,"run" ,side_effect = AssertionError ("ran" )): 69with self .assertRaises (S .acquisition .AcquisitionRefused ): 70S .run (refused ) 71done = subprocess .CompletedProcess ([],0 ) 72with mock .patch .object (S .subprocess ,"run" ,return_value = done )as runner : 73S .run ([sys .executable ,str (tool ),"--help" ],check = False ) 74runner .assert_called_once () 75 76def test_the_mac_preparation_tools_in_metal_tools_may_run_and_nothing_else_beside_them (self ): 77# mac_repack() and mac_stream run metal/tools/metal_repack.py and stream_experts.py (mac_tools_dir() = ROOT/metal/tools): the bundled Mac tools, like tools/*.py 78S = self .S 79done = subprocess .CompletedProcess ([],0 ) 80for tool in ("metal_repack.py" ,"stream_experts.py" ): 81with self .subTest (allowed = tool ),mock .patch .object (S .subprocess ,"run" ,return_value = done )as runner : 82S .run ([sys .executable ,str (ROOT / "metal" / "tools" / tool ),"--help" ],check = False ) 83runner .assert_called_once () 84for refused in ( 85 [sys .executable ,"-m" ,"metal.tools.metal_repack" ],# -m is never allowed 86 ["python3" ,str (ROOT / "metal" / "tools" / "metal_repack.py" )],# another interpreter 87 [sys .executable ,str (ROOT / "metal" / "kernels" / "evil.py" )],# another folder of the bundle 88 [sys .executable ,str (ROOT / "metal" / "evil.py" )],# metal/ itself 89 [sys .executable ,str (self .home / "metal" / "tools" / "metal_repack.py" )],# a copy in the install folder 90 [sys .executable ,str (ROOT / "metal" / "tools" / ".." / ".." / "setup.py" )], 91 [sys .executable ], 92 ): 93with self .subTest (refused = refused ),mock .patch .object (S .subprocess ,"run" ,side_effect = AssertionError ("ran" )): 94with self .assertRaises (S .acquisition .AcquisitionRefused ): 95S .run (refused ) 96 97def test_no_package_is_installed (self ): 98S = self .S 99with mock .patch .object (S ,"run" ,side_effect = AssertionError ("pip" )), \ 100mock .patch .object (S ,"control_missing_packages" ,return_value = []): 101S .pip_install (["numpy==1" ],"the packages" )# the app ships them; nothing runs 102with mock .patch .object (S ,"control_missing_packages" ,return_value = ["numpy" ]), \ 103self .assertRaises (SystemExit ): 104S .pip_install (["numpy==1" ],"the packages" ) 105 106def test_the_engine_is_the_component_and_a_missing_one_does_not_stop_the_download (self ): 107S = self .S 108empty = Path (self .tmp .name )/ "components" 109empty .mkdir () 110gpu = {"index" :0 ,"vram_gb" :12.0 } 111with mock .patch .dict (os .environ , {"STRATA_COMPONENTS_DIR" :str (empty )}), \ 112mock .patch .object (S ,"download" ,side_effect = AssertionError ("fetched" )), \ 113mock .patch .object (S ,"build_engine" ,side_effect = AssertionError ("built" )), \ 114mock .patch .object (S ,"get_prebuilt" ,side_effect = AssertionError ("fetched an engine" )): 115found ,eng ,meta ,libs ,chosen ,vision = S .engine_step (mock .Mock (build = False ,prebuilt = None ),gpu ,False , [],13 ,"gpu" ) 116self .assertIsNone (found ,"no llama.cpp tree: the engine is the component, gguf-py is vendored" ) 117self .assertFalse ((self .home / "third_party" / "llama.cpp" ).exists (),"nothing is fetched into the install folder" ) 118self .assertEqual (libs , []) 119self .assertEqual (vision ,"none" )# images are not in the first app release 120self .assertEqual (meta ["source" ],"local" ) 121self .assertEqual (S .engine_exe (eng ),"component:strata-engine" ) 122 123def test_the_run_config_goes_to_the_install_folder_and_the_data_folder_sits_beside_it (self ): 124S = self .S 125self .assertEqual (S .installed_configs (), []) 126 (self .home / "strata-q2_0.json" ).write_text (json .dumps ({"exe" :"component:strata-engine" ,"args" : ["--native" ,"x.gguf" ], 127"tokenizer" :"t" }),encoding = "utf-8" ) 128with mock .patch .object (S ,"model_config" ,return_value = True ): 129self .assertEqual ([p .name for p in S .installed_configs ()], ["strata-q2_0.json" ]) 130with mock .patch .dict (os .environ , {"APPDATA" :self .tmp .name ,"XDG_CONFIG_HOME" :self .tmp .name }): 131data ,_ = S .data_folder_in_place () 132self .assertEqual (data ,self .home .resolve ().parent / "Strata-data" ) 133 134@ unittest . skipIf ( os . name == "nt" , "a launcher is a shell script: Linux and macOS bundles" ) 135def test_the_bundle_keeps_one_real_python_and_launchers_for_the_other_names (self ): 136sys .path .insert (0 ,str (ROOT / "apps" / "desktop" / "scripts" )) 137try : 138spec = importlib .util .spec_from_file_location ("stage_control_for_launchers" ,ROOT / "apps" / "desktop" / "scripts" / "stage-control.py" ) 139stage = importlib .util .module_from_spec (spec ) 140spec .loader .exec_module (stage ) 141finally : 142sys .path .pop (0 ) 143folder = Path (self .tmp .name )/ "bundle" 144bindir = folder / "python" / "bin" 145bindir .mkdir (parents = True ) 146real = bindir / "python3.12" 147real .write_text ("#!/bin/sh" + chr (10 )+ "echo real " + chr (34 )+ "$@" + chr (34 )+ chr (10 )) 148real .chmod (0o755 ) 149os .symlink ("python3.12" ,bindir / "python3" ) 150os .symlink ("python3" ,bindir / "python" ) 151self .assertEqual (stage .dedupe_python (folder ), ["python" ,"python3" ]) 152for name in ("python" ,"python3" ): 153f = bindir / name 154self .assertFalse (f .is_symlink ()) 155self .assertLess (f .stat ().st_size ,400 ,"a launcher, not a second copy of the interpreter" ) 156self .assertTrue (os .access (f ,os .X_OK )) 157out = subprocess .run ([str (bindir / "python" ),"a b" ,"c" ],capture_output = True ,text = True ).stdout 158self .assertEqual (out .strip (),"real a b c" ) 159self .assertEqual (stage .dedupe_python (folder ), [],"run twice: nothing left to change" ) 160# no external program: with an empty PATH (and, in the AppImage, libraries that make `dirname` fail) the launcher still starts the 161# interpreter, from another folder and through a relative name. Ubuntu 26.04: "dirname: libsystemd.so.0: version LIBSYSTEMD_254 not found". 162for cwd ,name in ((str (folder ),"python/bin/python3" ), (str (bindir ),"./python" ), (str (bindir .parent ),"bin/python" )): 163r = subprocess .run (["/bin/sh" ,name ,"x" ],capture_output = True ,text = True ,cwd = cwd ,env = {"PATH" :"" }) 164self .assertEqual (r .stdout .strip (),"real x" , (cwd ,name ,r .stderr )) 165 166def test_the_bundle_lists_everything_the_install_imports (self ): 167sys .path .insert (0 ,str (ROOT / "apps" / "desktop" / "scripts" )) 168try : 169spec = importlib .util .spec_from_file_location ("stage_control_for_test" ,ROOT / "apps" / "desktop" / "scripts" / "stage-control.py" ) 170stage = importlib .util .module_from_spec (spec ) 171spec .loader .exec_module (stage ) 172finally : 173sys .path .pop (0 ) 174tools = stage .local_imports (ROOT ,stage .INSTALLER_TOOLS ) 175for need in ("strata_mcp" ,"iq_pack" ,"strata_pack" ,"canonical_xcheck" ,"pack_layer" ,"gguf_reader" ,"gguf_writer" ,"_paths" , 176"strata_gguf" ,"strata_quants" ,"strata_quant_tables" ): 177self .assertIn (need ,tools ) 178out = Path (self .tmp .name )/ "control" 179out .mkdir () 180record = stage .add_installer (out ) 181for name in ("setup.py" ,"ref/load.py" ,"tools/strata_mcp.py" ,"tools/iq_pack.py" ,"data/draft_vocab.bin" ): 182self .assertTrue ((out / name ).is_file (),name ) 183self .assertIn ("tools/strata_pack.py" ,record ["files" ]) 184# every module setup.py's preparation steps run exists in the bundle 185for tool in ("iq_pack" ,"strata_pack" ,"pack_index" ,"strata_tokenizer" ,"mtp_fetch" ,"mtp_pack" ,"mtp_rt" ): 186self .assertTrue ((out / "tools" / f" { tool } .py" ).is_file (),tool ) 187 188 189class InstallerServerTests (unittest .TestCase ): 190"""tools/strata_mcp.py with its source (setup.py, serve/) apart from the install folder, as the app runs it.""" 191 192def setUp (self ): 193self .tmp = tempfile .TemporaryDirectory () 194self .addCleanup (self .tmp .cleanup ) 195self .root = Path (self .tmp .name )/ "install" 196self .root .mkdir () 197spec = importlib .util .spec_from_file_location ("strata_mcp_for_test" ,ROOT / "tools" / "strata_mcp.py" ) 198self .mcp = importlib .util .module_from_spec (spec ) 199with mock .patch .dict (os .environ , {"STRATA_CONTROL_INSTALL" :"1" ,"STRATA_INSTALL_DIR" :str (self .root )}): 200spec .loader .exec_module (self .mcp ) 201 202def test_the_catalog_comes_from_setup_py_in_the_bundle (self ): 203s = self .mcp .Strata (self .root ,ROOT ) 204self .assertEqual (s .root ,self .root .resolve ()) 205self .assertEqual (s .src ,ROOT ) 206models ,families ,contexts ,source = s .tables () 207self .assertEqual (source ,"setup.py" ) 208self .assertIn ("qwen" ,families ) 209self .assertIn ("IQ3_XXS" ,models ) 210self .assertEqual (s .python_override ,sys .executable )# Control's own Python runs the install 211 212def test_the_install_job_runs_on_control_python_without_a_venv_and_may_fetch_only_for_itself (self ): 213s = self .mcp .Strata (self .root ,ROOT ) 214spec_path = self .root / "job.json" 215spec = {"job" :"j1" ,"root" :str (self .root ),"src" :str (ROOT ),"control" :True ,"python" :sys .executable , 216"base_python" :sys .executable ,"create_venv" :False ,"args" : ["--yes" ,"--no-start" ], 217"result" :str (self .root / "result.json" )} 218spec_path .write_text (json .dumps (spec ),encoding = "utf-8" ) 219seen = {} 220 221class FakePopen : 222pid = 4242 223 224def __init__ (self ,cmd ,** kw ): 225seen ["cmd" ],seen ["kw" ]= cmd ,kw 226 227def wait (self ): 228return 0 229 230with mock .patch .dict (os .environ , {"STRATA_NO_ACQUIRE" :"1" ,"PYTHONPATH" :"x" ,"PYTHONHOME" :"y" }), \ 231mock .patch .object (self .mcp .subprocess ,"Popen" ,FakePopen ), \ 232mock .patch .object (self .mcp ,"proc_identity" ,return_value = None ): 233self .assertEqual (self .mcp .install_job (str (spec_path )),0 ) 234self .assertEqual (os .environ ["STRATA_NO_ACQUIRE" ],"1" ,"this process keeps the switch" ) 235self .assertEqual (seen ["cmd" ][:2 ], [sys .executable ,str (ROOT / "setup.py" )]) 236env = seen ["kw" ]["env" ] 237self .assertEqual (env ["STRATA_CONTROL_INSTALL" ],"1" ) 238self .assertEqual (env ["STRATA_INSTALL_DIR" ],str (self .root )) 239self .assertNotIn ("STRATA_NO_ACQUIRE" ,env ,"the explicit install job may fetch the chosen model's files" ) 240self .assertNotIn ("PYTHONPATH" ,env ) 241self .assertNotIn ("PYTHONHOME" ,env ) 242self .assertFalse ((self .root / ".venv" ).exists (),"no virtual environment, no pip" ) 243self .assertIsNotNone (s ) 244 245def test_a_two_file_model_has_one_combined_progress (self ): 246"""The bar went 70 GB -> 0 -> up again because each file reported its own total. One total for the whole model now.""" 247folder = self .root / "Strata-data" / "models" / "IQ3_S" 248folder .mkdir (parents = True ) 249job = {"folder" :str (folder ),"total_gb" :0.004 } 250step5 = {"step" :"5/7: downloading Qwen3.8-Flash-Next IQ3_S" } 251seen = [] 252# file 1 downloading, then complete, then file 2 starts: the combined figure only goes up 253for name ,size in (("a.gguf.part" ,400_000 ), ("a.gguf.part" ,1_500_000 )): 254 (folder / name ).write_bytes (b"x" * size ) 255seen .append (self .mcp .combined_progress (dict (step5 ),job )["download" ]) 256 (folder / "a.gguf.part" ).rename (folder / "a.gguf" ) 257 (folder / "b.gguf.part" ).write_bytes (b"x" * 100_000 ) 258seen .append (self .mcp .combined_progress (dict (step5 ),job )["download" ]) 259 (folder / "b.gguf.part" ).write_bytes (b"x" * 1_000_000 ) 260seen .append (self .mcp .combined_progress (dict (step5 ),job )["download" ]) 261done = [d ["done_gb" ]for d in seen ] 262self .assertEqual (done ,sorted (done ),done ) 263self .assertEqual (seen [- 1 ]["total_gb" ],0.004 ) 264self .assertAlmostEqual (seen [- 1 ]["remaining_gb" ],0.004 - seen [- 1 ]["done_gb" ],places = 2 ) 265self .assertTrue (all (d ["file" ]== "model files" for d in seen )) 266# not a download any more once setup is preparing the files 267self .assertNotIn ("download" ,self .mcp .combined_progress ({"step" :"6/7: preparing the model for Strata" ,"download" : {"x" :1 }},job )) 268# a resumed install counts what is already on disk 269self .assertGreater (self .mcp .combined_progress (dict (step5 ),job )["download" ]["done_gb" ],0 ) 270 271def test_a_model_in_parts_counts_every_part_and_the_picture_reader (self ): 272"""QA 2026-10-18 (6): the bar stopped at 99 % while the picture reader downloaded, and a first whole part looked like a finished 273model. Every part is counted, the picture reader is a part of its own, and 'done' needs all of them.""" 274S = self .mcp .Strata (self .root ,ROOT ).setup_module () 275models = self .root / "Strata-data" / "models" 276files = self .mcp .expected_files (S ,"qwen" ,"IQ3_S" ,models ,True ) 277self .assertEqual ([f ["role" ]for f in files ], ["model" ,"model" ,"vision" ]) 278self .assertEqual (Path (files [2 ]["path" ]).parent ,models ,"the picture reader sits beside the model folders" ) 279folder = Path (files [0 ]["path" ]).parent 280folder .mkdir (parents = True ) 281job = {"folder" :str (folder ),"total_gb" :0.004 ,"files" :files } 282step5 = {"step" :"5/7: downloading Qwen3.8-Flash-Next IQ3_S" } 283# the first part is whole, the second not started: the model is NOT downloaded 284Path (files [0 ]["path" ]).write_bytes (b"x" * 2_000_000 ) 285one = self .mcp .combined_progress (dict (step5 ),job ) 286model = next (x for x in one ["parts" ]if x ["kind" ]== "model" ) 287self .assertEqual ((model ["files_done" ],model ["files_total" ],model ["state" ]), (1 ,2 ,"downloading" )) 288self .assertLess (one ["download" ]["percent" ],99 ) 289# both parts whole, the picture reader under way: still counted, and the bar is not at its end 290Path (files [1 ]["path" ]).write_bytes (b"x" * 2_000_000 ) 291Path (files [2 ]["path" ]).with_name (Path (files [2 ]["path" ]).name + ".part" ).write_bytes (b"x" * 400_000 ) 292two = self .mcp .combined_progress (dict (step5 ),job ) 293vision = next (x for x in two ["parts" ]if x ["kind" ]== "vision" ) 294self .assertEqual (vision ["state" ],"downloading" ) 295self .assertEqual (two ["download" ]["file" ],"picture reader" ) 296self .assertGreater (two ["download" ]["done_gb" ],one ["download" ]["done_gb" ]) 297self .assertGreater (two ["download" ]["total_gb" ],0.004 ,"the picture reader is part of the total" ) 298self .assertLessEqual (two ["download" ]["percent" ],99 ) 299# all whole 300Path (files [2 ]["path" ]).with_name (Path (files [2 ]["path" ]).name + ".part" ).unlink () 301Path (files [2 ]["path" ]).write_bytes (b"x" * 907_543_008 ) 302three = self .mcp .combined_progress (dict (step5 ),job ) 303self .assertTrue (all (x ["state" ]== "done" for x in three ["parts" ])) 304self .assertEqual (three ["download" ]["done_gb" ],three ["download" ]["total_gb" ]) 305# not a download once setup prepares the files 306self .assertNotIn ("download" ,self .mcp .combined_progress ({"step" :"6/7: preparing the model for Strata" ,"download" : {"x" :1 }},job )) 307 308def test_a_pack_with_many_files_reports_the_whole_pack (self ): 309S = self .mcp .Strata (self .root ,ROOT ).setup_module () 310files = self .mcp .expected_files (S ,"nvfp4" ,"NVFP4" ,self .root / "models" ,False ) 311self .assertGreater (len (files ),5 ) 312self .assertTrue (all (f ["bytes" ]for f in files ),"a ready-made pack pins every file's size" ) 313big = next (f for f in files if f ["path" ].endswith ("experts.bin" )) 314Path (big ["path" ]).parent .mkdir (parents = True ) 315Path (big ["path" ]+ ".part" ).write_bytes (b"x" * 1000 ) 316prog = self .mcp .combined_progress ({"step" :"5/7: downloading" }, {"files" :files ,"total_gb" :128.0 }) 317model = prog ["parts" ][0 ] 318self .assertEqual ((model ["kind" ],model ["state" ],model ["files_done" ],model ["files_total" ]), ("model" ,"downloading" ,0 ,len (files ))) 319self .assertAlmostEqual (model ["total_gb" ],sum (f ["bytes" ]for f in files )/ 1e9 ,places = 2 ) 320 321def test_a_config_with_only_some_parts_is_not_ready (self ): 322"""The config names the first part only; 'ready' used to mean that part exists.""" 323data = self .root / "models" / "x" 324data .mkdir (parents = True ) 325first = data / "Model-00001-of-00003.gguf" 326first .write_bytes (b"x" ) 327self .assertEqual (len (self .mcp .shard_gaps ([str (first )])),2 ) 328 (data / "Model-00002-of-00003.gguf" ).write_bytes (b"x" ) 329 (data / "Model-00003-of-00003.gguf.part" ).write_bytes (b"x" ) 330self .assertEqual ([Path (g ).name for g in self .mcp .shard_gaps ([str (first )])], ["Model-00003-of-00003.gguf" ]) 331 (data / "Model-00003-of-00003.gguf.part" ).unlink () 332 (data / "Model-00003-of-00003.gguf" ).write_bytes (b"x" ) 333self .assertEqual (self .mcp .shard_gaps ([str (first )]), []) 334self .assertEqual (self .mcp .shard_gaps ([str (data / "single.gguf" )]), []) 335 336@ unittest . skipUnless ( os . name == "nt" or sys . platform . startswith ( "linux" ), "a PC with a GPU probe" ) 337def test_a_real_install_reaches_the_model_download_with_nothing_else_acquired (self ): 338"""setup.py in the app's mode, as the install job runs it: steps 1-4 pass (PC check, packages bundled, engine component 339optional, llama.cpp source already present) and step 5 asks for the model file. The model host is a folder that does 340not exist, so nothing is downloaded; pip, git, cmake and winget shims that record any call must stay unused.""" 341import setup as plain 342if not plain .gpus (): 343self .skipTest ("no NVIDIA GPU here: setup stops at step 1" ) 344import shutil 345if shutil .disk_usage (self .tmp .name ).free < 130 * 10 ** 9 : 346self .skipTest ("less than 130 GB free: setup stops at its disk check before the download step" ) 347home = Path (self .tmp .name )/ "home" 348shims = Path (self .tmp .name )/ "shims" 349for p in (home / "third_party" / "llama.cpp" / "ggml" ,home / "third_party" / "llama.cpp" / "gguf-py" ,shims ): 350p .mkdir (parents = True ) 351 (home / "third_party" / "llama.cpp" / "ggml" / "CMakeLists.txt" ).write_text ("" ,encoding = "utf-8" ) 352log = Path (self .tmp .name )/ "shim.log" 353for tool in ("pip" ,"pip3" ,"git" ,"cmake" ,"ninja" ,"winget" ,"curl" ,"wget" ,"cl" ,"make" ): 354if os .name == "nt" : 355 (shims / f" { tool } .cmd" ).write_text (f"@echo { tool } %* >> \" { log } \"\r\n" ,encoding = "utf-8" ) 356else : 357 (shims / tool ).write_text (f"#!/bin/sh\necho { tool } \"$@\" >> ' { log } '\n" ,encoding = "utf-8" ) 358 (shims / tool ).chmod (0o755 ) 359env = {k :v for k ,v in os .environ .items ()if k not in ("STRATA_NO_ACQUIRE" ,"PYTHONPATH" ,"VIRTUAL_ENV" )} 360env .update (STRATA_CONTROL_INSTALL = "1" ,STRATA_INSTALL_DIR = str (home ),APPDATA = str (Path (self .tmp .name )/ "appdata" ), 361XDG_CONFIG_HOME = str (Path (self .tmp .name )/ "xdg" ),STRATA_COMPONENTS_DIR = str (Path (self .tmp .name )/ "components" ), 362HF_ENDPOINT = (Path (self .tmp .name )/ "no-such-hf" ).as_uri (),PATH = str (shims )+ os .pathsep + env .get ("PATH" ,"" ), 363PYTHONIOENCODING = "utf-8" ) 364done = subprocess .run ([sys .executable ,str (ROOT / "setup.py" ),"--yes" ,"--no-start" ,"--family" ,"qwen" ,"--model" ,"Q2_0" , 365"--context" ,"32768" ,"--vision" ,"no" ,"--experimental-speed-projection" ,"off" ], 366capture_output = True ,text = True ,env = env ,cwd = str (ROOT ),stdin = subprocess .DEVNULL ,timeout = 300 ) 367out = done .stdout + done .stderr 368self .assertNotEqual (done .returncode ,0 ) 369self .assertIn ("bundled with the app" ,out ) 370self .assertIn ("Step 5: downloading" ,out ) 371self .assertIn ("Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf" ,out ) 372self .assertFalse (log .exists (),"something ran pip, git, cmake or a package manager: " + (log .read_text ()if log .exists ()else "" )) 373 374 375if __name__ == "__main__" : 376unittest .main () 377 378 379class FailedStartTests (unittest .TestCase ): 380def test_a_failed_start_carries_the_last_lines_the_server_wrote (self ): 381"""The app turns `server_exited` into words and keeps the reason under Details: Control reports the log's last lines.""" 382from strata_control import runtime 383owner = [c for _ ,c in vars (runtime ).items ()if isinstance (c ,type )and hasattr (c ,"_log_tail" )][0 ] 384with tempfile .TemporaryDirectory ()as directory : 385fake = mock .Mock () 386fake .state_path = Path (directory )/ "app-1.json" 387fake .name = "app-1" 388self .assertIsNone (owner ._log_tail (fake ))# no log: nothing, no exception 389 (Path (directory )/ "app-1.server.log" ).write_text ("loading\n\nmemory guard: 5.1 GiB free is under 6 GiB\nthe engine process ended: exit code 3\n" ,encoding = "utf-8" ) 390tail = owner ._log_tail (fake ) 391self .assertIn ("memory guard: 5.1 GiB free" ,tail ) 392self .assertTrue (tail .endswith ("exit code 3" )) 393self .assertNotIn ("loading" ,tail .split (" | " )[0 ]if tail .count (" | " )> 2 else "" ) 394 395 396class DeleteModelTests (unittest .TestCase ): 397"""Deleting a downloaded model removes its own files and run config, never what another installed model still uses.""" 398 399def setUp (self ): 400self .tmp = tempfile .TemporaryDirectory () 401self .addCleanup (self .tmp .cleanup ) 402base = Path (self .tmp .name ) 403self .root = base / "install" 404self .root .mkdir () 405self .data = base / "Strata-data" 406spec = importlib .util .spec_from_file_location ("strata_mcp_for_delete" ,ROOT / "tools" / "strata_mcp.py" ) 407self .mcp = importlib .util .module_from_spec (spec ) 408with mock .patch .dict (os .environ , {"STRATA_CONTROL_INSTALL" :"1" ,"STRATA_INSTALL_DIR" :str (self .root )}): 409spec .loader .exec_module (self .mcp ) 410self .s = self .mcp .Strata (self .root ,ROOT ) 411self .tools = self .mcp .Tools (self .s ) 412 413def make (path :Path ,size :int ): 414path .parent .mkdir (parents = True ,exist_ok = True ) 415path .write_bytes (b"x" * size ) 416return path 417self .make = make 418mtp = self .data / "mtp" / "rt" 419make (mtp / "experts.bin" ,3000 ) 420shared_ple = make (self .data / "models" / "Q2_0" / "shard-2.gguf" ,2000 )# the same second shard in both models 421for tag ,size in (("iq3_s" ,10000 ), ("q2_0" ,4000 )): 422folder = self .data / "models" / tag 423first = make (folder / "shard-1.gguf" ,size ) 424make (first .with_name (first .name + ".done" ),1 ) 425pack = self .data / "packs" / tag 426make (pack / "tokenizer" / "vocab.json" ,500 ) 427 (self .root / f"strata- { tag } .json" ).write_text (json .dumps ({"exe" :"component:strata-engine" ,"args" : [ 428"--pack" ,str (pack ),"--native" ,str (first ),"--ple-gguf" ,str (shared_ple ),"--mtp" ,str (mtp ),"--max-context" ,"32768" ]}),encoding = "utf-8" ) 429 (self .root / f"strata- { tag } .log" ).write_text ("log" ,encoding = "utf-8" ) 430 431def test_the_plan_names_what_goes_and_what_stays (self ): 432plan = self .tools .strata_remove (model = "iq3_s" )["plan" ] 433removed = {Path (x ["path" ]).name for x in plan ["remove" ]} 434kept = {Path (x ["path" ]).name for x in plan ["keep" ]} 435self .assertIn ("shard-1.gguf" ,removed ) 436self .assertIn ("iq3_s" ,removed )# its pack folder 437self .assertIn ("strata-iq3_s.json" ,removed ) 438self .assertEqual (kept , {"shard-2.gguf" ,"rt" })# the shared PLE shard and the shared MTP draft 439self .assertEqual (plan ["bytes" ],10000 + 1 + 500 + 3 + (self .root / "strata-iq3_s.json" ).stat ().st_size ) 440 441def test_confirm_deletes_only_that_model_and_the_other_still_has_everything (self ): 442result = self .tools .strata_remove (model = "iq3_s" ,confirm = True ) 443self .assertEqual (result ["failed" ], []) 444self .assertFalse ((self .data / "models" / "iq3_s" ).exists ())# its folder is gone with its file 445self .assertFalse ((self .data / "packs" / "iq3_s" ).exists ()) 446self .assertFalse ((self .root / "strata-iq3_s.json" ).exists ()) 447self .assertTrue ((self .data / "models" / "Q2_0" / "shard-2.gguf" ).is_file ()) 448self .assertTrue ((self .data / "mtp" / "rt" / "experts.bin" ).is_file ()) 449self .assertTrue ((self .data / "models" / "q2_0" / "shard-1.gguf" ).is_file ()) 450self .assertTrue ((self .data / "packs" / "q2_0" / "tokenizer" / "vocab.json" ).is_file ()) 451self .assertTrue ((self .root / "strata-q2_0.json" ).is_file ()) 452 453def test_the_last_model_takes_its_shared_files_with_it (self ): 454self .tools .strata_remove (model = "iq3_s" ,confirm = True ) 455self .tools .strata_remove (model = "q2_0" ,confirm = True ) 456self .assertFalse ((self .data / "mtp" / "rt" ).exists ()) 457self .assertFalse ((self .data / "models" / "Q2_0" / "shard-2.gguf" ).exists ()) 458 459def test_nothing_outside_strata_s_folders_is_touched_and_each_model_reports_its_own_disk_use (self ): 460outside = Path (self .tmp .name )/ "elsewhere" / "mine.gguf" 461self .make (outside ,777 ) 462cfg = self .root / "strata-q2_0.json" 463data = json .loads (cfg .read_text ()) 464data ["args" ]+= ["--ple-gguf" ,str (outside )] 465cfg .write_text (json .dumps (data ),encoding = "utf-8" ) 466plan = self .tools .strata_remove (model = "q2_0" )["plan" ] 467self .assertIn ("mine.gguf" , {Path (x ["path" ]).name for x in plan ["keep" ]}) 468self .tools .strata_remove (model = "q2_0" ,confirm = True ) 469self .assertTrue (outside .is_file ()) 470described = self .s .describe_config (self .root / "strata-iq3_s.json" ) 471self .assertGreater (described ["disk_bytes" ],10000 ) 472 473def test_files_strata_downloaded_into_another_models_folder_are_deleted_too (self ): 474# The app installs into its own Models folder while settings.json names another data folder (#3716). 475other = Path (self .tmp .name )/ "Documents" / "Strata" 476shard = self .make (other / "Models" / "IQ3" / "m-00001.gguf" ,5000 ) 477self .make (shard .with_name (shard .name + ".done" ),1 ) 478pack = other / "packs" / "iq3" 479self .make (pack / "dense.bin" ,300 ) 480self .make (pack / "conversions.json" ,2 ) 481mine = self .make (Path (self .tmp .name )/ "mine" / "own.gguf" ,99 ) 482 (self .root / "strata-iq3x.json" ).write_text (json .dumps ({"exe" :"component:strata-engine" ,"args" : [ 483"--pack" ,str (pack ),"--native" ,str (shard ),"--ple-gguf" ,str (mine )]}),encoding = "utf-8" ) 484result = self .tools .strata_remove (model = "iq3x" ,confirm = True ) 485self .assertEqual (result ["failed" ], []) 486self .assertFalse (shard .exists ()) 487self .assertFalse (pack .exists ()) 488self .assertTrue (mine .is_file (),"a file the person brought stays" ) 489 490def test_every_part_of_a_multi_part_model_goes_with_it_and_a_part_another_model_uses_stays (self ): 491# The run config names only the first part; the others used to stay on disk (#3716). 492folder = self .data / "models" / "IQ3_XXS" 493parts = [self .make (folder / f"Big-0000 { i } -of-00003.gguf" ,5000 )for i in (1 ,2 ,3 )] 494for part in parts : 495self .make (part .with_name (part .name + ".done" ),1 ) 496 (self .root / "strata-iq3xxs.json" ).write_text (json .dumps ({"exe" :"component:strata-engine" ,"args" : [ 497"--native" ,str (parts [0 ]),"--max-context" ,"32768" ]}),encoding = "utf-8" ) 498plan = self .tools .strata_remove (model = "iq3xxs" )["plan" ] 499removed = {Path (x ["path" ]).name for x in plan ["remove" ]} 500self .assertTrue ({p .name for p in parts }<= removed ,removed ) 501result = self .tools .strata_remove (model = "iq3xxs" ,confirm = True ) 502self .assertEqual (result ["failed" ], []) 503self .assertEqual ([p .exists ()for p in parts ], [False ,False ,False ]) 504self .assertFalse (folder .exists ()) 505 506def test_a_part_that_another_model_names_is_kept_when_a_multi_part_model_is_deleted (self ): 507folder = self .data / "models" / "IQ3_XXS" 508parts = [self .make (folder / f"Big-0000 { i } -of-00002.gguf" ,5000 )for i in (1 ,2 )] 509for part in parts : 510self .make (part .with_name (part .name + ".done" ),1 ) 511 (self .root / "strata-iq3xxs.json" ).write_text (json .dumps ({"exe" :"component:strata-engine" ,"args" : ["--native" ,str (parts [0 ])]}),encoding = "utf-8" ) 512 (self .root / "strata-twin.json" ).write_text (json .dumps ({"exe" :"component:strata-engine" ,"args" : ["--native" ,str (parts [0 ])]}),encoding = "utf-8" ) 513self .tools .strata_remove (model = "iq3xxs" ,confirm = True ) 514self .assertTrue (all (p .is_file ()for p in parts ),"the twin config still uses every part" ) 515 516 517class LocalGgufInstallTests (unittest .TestCase ): 518def test_a_plan_from_a_local_folder_adopts_the_files_and_needs_no_download_space (self ): 519with tempfile .TemporaryDirectory ()as tmp : 520root = Path (tmp )/ "install" 521root .mkdir () 522local = Path (tmp )/ "mine" 523local .mkdir () 524spec = importlib .util .spec_from_file_location ("strata_mcp_for_local" ,ROOT / "tools" / "strata_mcp.py" ) 525mcp = importlib .util .module_from_spec (spec ) 526with mock .patch .dict (os .environ , {"STRATA_CONTROL_INSTALL" :"1" ,"STRATA_INSTALL_DIR" :str (root )}): 527spec .loader .exec_module (mcp ) 528tools = mcp .Tools (mcp .Strata (root ,ROOT )) 529plan ,args = tools .install_plan ("qwen" ,"IQ3_S" ,32768 ,"no" ,None ,None ,None ,None ,None ,None ,None ,str (local )) 530self .assertIn ("--gguf-dir" ,args ) 531self .assertEqual (args [args .index ("--gguf-dir" )+ 1 ],str (local )) 532self .assertLessEqual (plan ["disk_needed_gb" ],9 )# the 8 GB for preparing, not the download 533with self .assertRaises (mcp .ToolError ): 534tools .install_plan ("qwen" ,"IQ3_S" ,32768 ,"no" ,None ,None ,None ,None ,None ,None ,None ,str (local / "missing" ))