okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b2d08647c
main
1"""tools/test_strata_mcp.py - tests for tools/strata_mcp.py (Strata's MCP server), standard library only. 2 3python -m unittest tools/test_strata_mcp.py -v 4 5Setup and the model server are fakes (a temporary Strata folder with a stand-in setup.py and serve/server.py), so 6nothing is downloaded and no GPU is used: the JSON-RPC handshake, argument checks, install / start / stop with real 7background processes, status against a fake HTTP server, and that the built-in model table still matches setup.py. 8""" 9from __future__import annotations 10 11import io 12import json 13import os 14import socket 15import subprocess 16import sys 17import tempfile 18import threading 19import time 20import unittest 21from unittest import mock 22from http .server import BaseHTTPRequestHandler ,HTTPServer 23from pathlib import Path 24 25HERE = Path (__file__ ).resolve ().parent 26sys .path .insert (0 ,str (HERE )) 27import strata_mcp as M # noqa: E402 28 29FAKE_SETUP = r''' 30import json, sys, time 31from pathlib import Path 32def main(): 33root = Path(__file__).resolve().parent 34(root / "setup-args.json").write_text(json.dumps(sys.argv[1:])) 35print("Strata - fake setup", flush=True) 36print("\n=== Step 1: checking your PC ===", flush=True) 37print(" [ok] GPU: fake", flush=True) 38print("\n=== Step 5: downloading Qwen3.8-Flash-Next Q2_0 ===", flush=True) 39for pct in (10, 20, 30): 40print(f"\r model.gguf: {pct * 0.5:.2f} / 50.00 GB ({pct}%) ", end="", flush=True) 41print(flush=True) 42if (root / "slow").exists(): 43end = time.time() + 30 44while not (root / "go").exists() and time.time() < end: 45time.sleep(0.1) 46if (root / "fail").exists(): 47print("\n [X] not enough free disk space", flush=True) 48print(" use --models-dir on a bigger drive", flush=True) 49sys.exit(1) 50a = sys.argv 51model = a[a.index("--model") + 1].lower() 52cfg = {"exe": sys.executable, "args": ["--max-context", a[a.index("--context") + 1]], "port": 8080, 53"model_name": "qwen3.8-flash-next-" + model, "log": str(root / f"strata-{model}.log")} 54(root / f"strata-{model}.json").write_text(json.dumps(cfg)) 55print("All set.", flush=True) 56 57 58if __name__ == "__main__": 59main() 60''' 61 62FAKE_SERVER = r''' 63import json, os, signal, socketserver, sys, time 64from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer 65from pathlib import Path 66a = sys.argv 67port = int(a[a.index("--port") + 1]) 68cfg = json.loads(Path(a[a.index("--config") + 1]).read_text()) 69root = Path(__file__).resolve().parent.parent 70print("loading the model (fake) ...", flush=True) 71if cfg.get("crash"): 72print("engine failed: out of memory (fake)", flush=True) 73sys.exit(3) 74time.sleep(cfg.get("delay", 0)) 75state = {"loaded": True} 76class H(BaseHTTPRequestHandler): 77def log_message(self, *x): 78pass 79def js(self, code, obj): 80b = json.dumps(obj).encode() 81self.send_response(code) 82self.send_header("Content-Type", "application/json") 83self.send_header("Content-Length", str(len(b))) 84self.end_headers() 85self.wfile.write(b) 86def do_GET(self): 87p = self.path.split("?")[0] 88if p == "/health": 89self.js(200, {"status": "ok", "service": "strata", "model": cfg["model_name"], "max_context": 32768, 90"images": False, "api_key": False, "loaded": state["loaded"]}) 91elif p == "/status": 92self.js(200, {"busy": bool(cfg.get("busy")), "queued": 0}) 93elif p == "/v1/status": 94self.js(200, {"service": "strata", "engine": "0.1.32", "uptime_s": 5, "activity": {"requests": 0}, 95"machine": {"gpu": {"name": "Fake GPU", "used_mib": 11000, "total_mib": 12227}, 96"ram": {"used_gib": 40.0, "total_gib": 63.1}}}) 97else: 98self.js(404, {"error": {"message": "not found"}}) 99def do_POST(self): 100n = int(self.headers.get("Content-Length") or 0) 101body = json.loads(self.rfile.read(n) or b"{}") 102p = self.path.split("?")[0] 103if p == "/unload": 104state["loaded"] = False 105with open(root / "unloaded.txt", "a") as f: 106f.write(str(port) + "\n") 107self.js(200, {"status": "unloaded"}) 108elif p == "/v1/chat/completions": 109with open(root / "bench-request.json", "w") as f: 110json.dump(body, f) 111self.js(200, {"model": cfg["model_name"], "choices": [{"message": {"content": "x"}, "finish_reason": "length"}], 112"usage": {"prompt_tokens": 30, "completion_tokens": body.get("max_tokens", 1)}, 113"timings": {"predicted_per_second": 61.5, "prompt_per_second": 400.0}}) 114else: 115self.js(404, {}) 116class Srv(ThreadingHTTPServer): 117# http.server's server_bind asks socket.getfqdn("127.0.0.1") for a name nothing here uses; on GitHub's macOS runner a fresh 118# process waited longer for that answer than the tests wait for the server 119def server_bind(self): 120socketserver.TCPServer.server_bind(self) 121self.server_name, self.server_port = self.server_address[:2] 122httpd = Srv(("127.0.0.1", port), H) 123def term(*_): 124print("[strata] stopped (fake)", flush=True) 125os._exit(0) 126signal.signal(signal.SIGTERM, term) 127print(f"ready: http://127.0.0.1:{port}/v1", flush=True) 128httpd.serve_forever() 129''' 130 131 132def free_port ()-> int : 133s = socket .socket () 134s .bind (("127.0.0.1" ,0 )) 135p = s .getsockname ()[1 ] 136s .close () 137return p 138 139 140def wait_for (cond ,seconds = 30.0 ): 141end = time .time ()+ seconds 142while time .time ()< end : 143if cond (): 144return True 145time .sleep (0.1 ) 146return cond () 147 148 149FAKE_HW = {"os" :"TestOS 1" ,"ram_gb" :64.0 ,"cpu" : {"name" :"Fake CPU" ,"cores" :12 ,"avx2" :True ,"avx512" :True }, 150"gpus" : [{"index" :0 ,"name" :"NVIDIA GeForce RTX 5070" ,"vram_gb" :11.9 ,"arch" :"120" ,"vendor" :"nvidia" , 151"problem" :None ,"usable" :True }]} 152 153 154class FakeRoot (unittest .TestCase ): 155"""A temporary Strata folder: fake setup.py and serve/server.py, its own settings file (data folder).""" 156 157def setUp (self ): 158self .tmp = tempfile .TemporaryDirectory () 159base = Path (self .tmp .name ) 160self .root = base / "Strata" 161 (self .root / "serve" ).mkdir (parents = True ) 162 (self .root / "setup.py" ).write_text (FAKE_SETUP ) 163 (self .root / "serve" / "server.py" ).write_text (FAKE_SERVER ) 164self .env_backup = {k :os .environ .get (k )for k in ("APPDATA" ,"XDG_CONFIG_HOME" )} 165os .environ ["APPDATA" ]= os .environ ["XDG_CONFIG_HOME" ]= str (base / "config" ) 166self .strata = M .Strata (self .root ) 167self .strata .python_override = sys .executable 168self .strata .health_timeout = 1.0 169self .strata ._hardware = lambda :dict (FAKE_HW ) 170self .strata .disk_free = lambda p :1000.0 171self .tools = M .Tools (self .strata ) 172self .extra = [] 173# the tests must never see a Strata server that happens to run on the real default port on this PC 174self ._default_port = M .DEFAULT_PORT 175M .DEFAULT_PORT = free_port () 176 177def tearDown (self ): 178M .DEFAULT_PORT = self ._default_port 179for p in self .extra : 180if p .poll ()is None : 181p .kill () 182p .wait (10 ) 183srv = self .strata .state ("server" ) 184if srv and M .proc_alive (srv .get ("pid" ),srv .get ("ident" )): 185M .proc_kill_tree (srv ["pid" ],srv ["ident" ]) 186M .wait_gone (srv ["pid" ],srv ["ident" ],10 ) 187job = self .strata .state ("install" ) 188if job and M .proc_alive (job .get ("pid" ),job .get ("ident" )): 189M .proc_kill_tree (job ["pid" ],job ["ident" ]) 190M .wait_gone (job ["pid" ],job ["ident" ],10 ) 191for p in self .strata .children : 192try : 193p .wait (5 ) 194except subprocess .TimeoutExpired : 195pass 196for k ,v in self .env_backup .items (): 197if v is None : 198os .environ .pop (k ,None ) 199else : 200os .environ [k ]= v 201for _ in range (20 ):# Windows: a log may still be closing 202try : 203self .tmp .cleanup () 204break 205except OSError : 206time .sleep (0.25 ) 207 208def call (self ,name ,args = None ): 209"""A tools/call through the JSON-RPC layer: (result dict, isError).""" 210srv = M .McpServer (self .strata ,io .BytesIO ()) 211r = srv .handle ({"jsonrpc" :"2.0" ,"id" :1 ,"method" :"tools/call" , 212"params" : {"name" :name ,"arguments" :args or {}}}) 213res = r ["result" ] 214return json .loads (res ["content" ][0 ]["text" ]),res ["isError" ] 215 216def write_config (self ,tag = "q2_0" ,port = 8080 ,** extra ): 217cfg = {"exe" :sys .executable ,"args" : ["--max-context" ,"32768" ],"port" :port , 218"model_name" :f"qwen3.8-flash-next- { tag } " ,"log" :str (self .root / f"strata- { tag } .log" ),** extra } 219 (self .root / f"strata- { tag } .json" ).write_text (json .dumps (cfg )) 220 (self .root / f"strata- { tag } .log" ).write_text ("engine line 1\nengine line 2\n" ) 221return cfg 222 223 224# ------------------------------------------------------------------------------------------------ the protocol 225class Protocol (FakeRoot ): 226def run_lines (self ,msgs ): 227inp = io .BytesIO (("\n" .join (m if isinstance (m ,str )else json .dumps (m )for m in msgs )+ "\n" ).encode ()) 228out = io .BytesIO () 229M .McpServer (self .strata ,out ).serve (inp ) 230return {m .get ("id" ):m for m in (json .loads (x )for x in out .getvalue ().decode ().splitlines ())} 231 232def test_handshake_list_call (self ): 233r = self .run_lines ([ 234 {"jsonrpc" :"2.0" ,"id" :1 ,"method" :"initialize" , 235"params" : {"protocolVersion" :"2025-06-18" ,"capabilities" : {},"clientInfo" : {"name" :"t" ,"version" :"1" }}}, 236 {"jsonrpc" :"2.0" ,"method" :"notifications/initialized" }, 237 {"jsonrpc" :"2.0" ,"id" :2 ,"method" :"tools/list" }, 238 {"jsonrpc" :"2.0" ,"id" :3 ,"method" :"tools/call" ,"params" : {"name" :"strata_models" ,"arguments" : {}}}, 239 {"jsonrpc" :"2.0" ,"id" :4 ,"method" :"ping" }, 240 ]) 241init = r [1 ]["result" ] 242self .assertEqual (init ["protocolVersion" ],"2025-06-18" ) 243self .assertIn ("tools" ,init ["capabilities" ]) 244self .assertEqual (init ["serverInfo" ]["name" ],"strata" ) 245names = [t ["name" ]for t in r [2 ]["result" ]["tools" ]] 246self .assertEqual (names , ["strata_status" ,"strata_models" ,"strata_remove" ,"strata_install" ,"strata_start" ,"strata_stop" , 247"strata_logs" ,"strata_benchmark" ,"strata_connect_info" ]) 248for t in r [2 ]["result" ]["tools" ]: 249self .assertEqual (t ["inputSchema" ]["type" ],"object" ) 250self .assertFalse (t ["inputSchema" ]["additionalProperties" ]) 251self .assertGreater (len (t ["description" ]),60 ) 252call = r [3 ]["result" ] 253self .assertFalse (call ["isError" ]) 254self .assertIn ("families" ,call ["structuredContent" ]) 255self .assertEqual (json .loads (call ["content" ][0 ]["text" ])["recommendation" ]["model" ],"IQ3_S" ) 256self .assertEqual (r [4 ]["result" ], {}) 257self .assertNotIn (None ,r )# the notification got no answer 258 259def test_older_protocol_and_errors (self ): 260r = self .run_lines ([ 261 {"jsonrpc" :"2.0" ,"id" :1 ,"method" :"initialize" ,"params" : {"protocolVersion" :"2024-11-05" }}, 262"{not json" , 263 {"jsonrpc" :"2.0" ,"id" :2 ,"method" :"tools/call" ,"params" : {"name" :"rm_rf" ,"arguments" : {}}}, 264 {"jsonrpc" :"2.0" ,"id" :3 ,"method" :"no/such" }, 265 {"jsonrpc" :"2.0" ,"id" :4 ,"method" :"tools/call" ,"params" : {"name" :"strata_logs" ,"arguments" : []}}, 266 ]) 267self .assertEqual (r [1 ]["result" ]["protocolVersion" ],"2024-11-05" ) 268self .assertEqual (r [None ]["error" ]["code" ],- 32700 ) 269self .assertEqual (r [2 ]["error" ]["code" ],- 32602 ) 270self .assertEqual (r [3 ]["error" ]["code" ],- 32601 ) 271self .assertTrue (r [4 ]["result" ]["isError" ]) 272self .assertNotIn ("structuredContent" ,r [4 ]["result" ])# 2024-11-05 has no structured results 273 274def test_real_stdio_process (self ): 275"""The script itself over a pipe: stdout carries only JSON-RPC lines.""" 276msgs = [{"jsonrpc" :"2.0" ,"id" :1 ,"method" :"initialize" ,"params" : {"protocolVersion" :"2025-06-18" }}, 277 {"jsonrpc" :"2.0" ,"id" :2 ,"method" :"tools/list" }, 278 {"jsonrpc" :"2.0" ,"id" :3 ,"method" :"tools/call" , 279"params" : {"name" :"strata_logs" ,"arguments" : {"source" :"setup" }}}] 280p = subprocess .run ([sys .executable ,str (HERE / "strata_mcp.py" ),"--root" ,str (self .root )], 281input = "\n" .join (json .dumps (m )for m in msgs )+ "\n" ,capture_output = True ,text = True , 282timeout = 60 ,env = dict (os .environ )) 283lines = [json .loads (x )for x in p .stdout .splitlines ()] 284self .assertEqual (sorted (m ["id" ]for m in lines ), [1 ,2 ,3 ]) 285self .assertEqual (len (next (m for m in lines if m ["id" ]== 2 )["result" ]["tools" ]),9 ) 286self .assertIn ("ready" ,p .stderr ) 287 288def test_not_a_strata_folder (self ): 289p = subprocess .run ([sys .executable ,str (HERE / "strata_mcp.py" ),"--root" ,self .tmp .name ],input = "" , 290capture_output = True ,text = True ,timeout = 60 ) 291self .assertEqual (p .returncode ,2 ) 292 293 294# ------------------------------------------------------------------------------------------------ validation 295class Validation (FakeRoot ): 296def assertRejected (self ,tool ,args ,text ): 297res ,err = self .call (tool ,args ) 298self .assertTrue (err ,f" { tool } { args } was accepted: { res } " ) 299self .assertIn (text ,res ["error" ]) 300 301def test_install_arguments (self ): 302self .assertRejected ("strata_install" , {"model" :"Q9_X" },"model must be one of" ) 303self .assertRejected ("strata_install" , {"family" :"llama" },"family must be one of" ) 304self .assertRejected ("strata_install" , {"context" :100 },"context must be between" ) 305self .assertRejected ("strata_install" , {"gpus" :"0;rm -rf /" },"gpus=" ) 306self .assertRejected ("strata_install" , {"gpus" :"0 && calc" },"gpus=" ) 307self .assertRejected ("strata_install" , {"gpu" :- 1 },"between" ) 308self .assertRejected ("strata_install" , {"gpu" :"1; calc" },"whole number" ) 309self .assertRejected ("strata_install" , {"gpu" :0 ,"gpus" :"0,1" },"not both" ) 310self .assertRejected ("strata_install" , {"port" :80 },"between" ) 311self .assertRejected ("strata_install" , {"backend" :"rocm" },"backend must be one of" ) 312self .assertRejected ("strata_install" , {"command" :"setup.py --build" },"unknown argument" ) 313res ,err = self .call ("strata_install" , {"family" :"swift" ,"model" :"IQ3_S" }) 314self .assertFalse (err ,res )# Swift 1.5 got its IQ3_S (same shard layout as its IQ2_XS) 315self .assertIn ("--family swift --model IQ3_S" ,res ["plan" ]["setup_command" ]) 316res ,err = self .call ("strata_install" , {"family" :"unsloth" ,"model" :"UD-Q4_K_XL" ,"vision" :"yes" }) 317self .assertFalse (err ,res )# #967: images are allowed with UD-Q4_K_XL (setup warns) 318self .assertEqual (res ["plan" ]["images" ],"yes" ) 319self .assertRejected ("strata_install" , {"vision" :"yes\nrm" },"control characters" ) 320 321def test_amd_vision_follows_the_picture_rule (self ): 322"""Owner rule 2026-10-18: pictures are on for AMD too, on Linux and Windows (setup picks the reader: CPU under 24 GB, GPU from 24 GB).""" 323for win in (False ,True ): 324with mock .patch .object (M ,"WIN" ,win ): 325for asked in ("yes" ,"gpu" ,"cpu" ): 326res ,err = self .call ("strata_install" , {"backend" :"hip" ,"vision" :asked }) 327self .assertFalse (err ,res ) 328self .assertEqual (res ["plan" ]["images" ],asked ) 329self .assertIn ("--vision " + asked ,res ["plan" ]["setup_command" ]) 330res ,err = self .call ("strata_install" , {"backend" :"hip" ,"vision" :"no" }) 331self .assertFalse (err ,res ) 332self .assertEqual (res ["plan" ]["images" ],"no" ) 333 334def test_pictures_default_on (self ): 335"""Nothing asked: pictures are on where the model can read them (any backend), off for a model that cannot.""" 336for backend in (None ,"cuda" ,"hip" ): 337args = {"backend" :backend }if backend else {} 338res ,err = self .call ("strata_install" ,args ) 339self .assertFalse (err ,res ) 340self .assertEqual (res ["plan" ]["images" ],"yes" ) 341self .assertIn ("--vision yes" ,res ["plan" ]["setup_command" ]) 342res ,err = self .call ("strata_install" , {"vision" :"no" }) 343self .assertFalse (err ,res ) 344self .assertEqual (res ["plan" ]["images" ],"no" ) 345 346def test_data_dir_paths (self ): 347self .assertRejected ("strata_install" , {"data_dir" :"models" },"absolute" ) 348self .assertRejected ("strata_install" , {"data_dir" :str (self .root .parent / "x" / ".." / "Strata-x" )},"'..'" ) 349self .assertRejected ("strata_install" , {"data_dir" :str (self .root .parent / "Documents" )},"named Strata" ) 350self .assertRejected ("strata_install" , {"data_dir" :str (self .root .parent / "nope" / "Strata-data" )}, 351"does not exist" ) 352self .assertRejected ("strata_install" , {"data_dir" :"\\\\server\\share\\Strata-data" },"network" ) 353sysdir = (os .environ .get ("SystemRoot" ,"C:\\Windows" )+ "\\Strata-data" )if M .WIN else "/etc/Strata-data" 354self .assertRejected ("strata_install" , {"data_dir" :sysdir },"system folder" ) 355ok = [self .root .parent / "Strata-data" ,self .root / "models-here" ,self .root .parent / "Strata-big" ] 356for d in ok : 357self .assertEqual (M .norm (self .tools .check_data_dir (str (d ))),M .norm (d )) 358 359@ unittest . skipIf ( M . WIN , "POSIX paths" ) 360def test_a_drive_the_desktop_mounted_is_not_a_system_folder (self ): 361"""/run/media/<user>/<drive> sits inside /run, but it is where an external drive is mounted.""" 362for raw in ("/run/media/ann/Backup/Strata-data" ,"/run/media/ann/Backup/Strata" ): 363self .assertTrue (M .mounted_drive (M .norm (raw )),raw ) 364for raw in ("/run" ,"/run/media" ,"/run/user/1000/Strata-data" ,"/run/systemd/Strata-data" ,"/etc/Strata-data" ): 365self .assertFalse (M .mounted_drive (M .norm (raw )),raw ) 366 367def test_the_persons_own_data_folder_is_accepted_whatever_it_is_called (self ): 368"""The app writes the folder the person chose into the settings file (apps/host model-folder.mjs); an AI tool naming a new 369folder still needs a Strata... name.""" 370chosen = self .root .parent / "my-big-disk" 371chosen .mkdir () 372self .assertRejected ("strata_install" , {"data_dir" :str (chosen )},"named Strata" ) 373settings = self .tools .s .settings_path () 374settings .parent .mkdir (parents = True ,exist_ok = True ) 375settings .write_text (json .dumps ({"data_dir" :str (chosen )})) 376self .assertEqual (M .norm (self .tools .check_data_dir (str (chosen ))),M .norm (chosen )) 377 378def test_other_tools_arguments (self ): 379self .assertRejected ("strata_start" , {"model" :"../../etc/passwd" },"not valid" ) 380self .assertRejected ("strata_start" , {"model" :"q2_0" },"no model is installed" ) 381self .write_config ("q2_0" ) 382self .assertRejected ("strata_start" , {"model" :"iq3_s" },"no installed model 'iq3_s'" ) 383self .assertRejected ("strata_start" , {"wait_seconds" :100000 },"between" ) 384self .assertRejected ("strata_logs" , {"lines" :0 },"between" ) 385self .assertRejected ("strata_logs" , {"source" :"/etc/passwd" },"source must be one of" ) 386self .assertRejected ("strata_benchmark" , {"max_tokens" :100000 },"between" ) 387self .assertRejected ("strata_stop" , {"force" :"yes" },"true or false" ) 388 389def test_engine_log_outside_is_not_read (self ): 390self .write_config ("q2_0" ,log = str (Path (self .tmp .name ).parent / "elsewhere.log" )) 391res ,err = self .call ("strata_logs" , {"source" :"engine" ,"model" :"q2_0" }) 392self .assertTrue (err ) 393self .assertIn ("outside the Strata folder" ,res ["error" ]) 394self .write_config ("q2_0" ) 395res ,err = self .call ("strata_logs" , {"source" :"engine" }) 396self .assertFalse (err ) 397self .assertEqual (res ["lines" ], ["engine line 1" ,"engine line 2" ]) 398 399 400# ------------------------------------------------------------------------------------------------ install 401class Install (FakeRoot ): 402def wait_job (self ): 403self .assertTrue (wait_for (lambda :not self .strata .install_job ()["running" ],60 )) 404 405def test_plan_then_install (self ): 406res ,err = self .call ("strata_install" , {}) 407self .assertFalse (err ) 408self .assertIn ("Nothing was done yet" ,res ["summary" ]) 409self .assertEqual ((res ["plan" ]["family" ],res ["plan" ]["model" ],res ["plan" ]["context" ]), ("qwen" ,"IQ3_S" ,131072 )) 410self .assertFalse ((self .root / "setup-args.json" ).exists ()) 411self .assertIsNone (self .strata .install_job ()) 412 413res ,err = self .call ("strata_install" , {"model" :"Q2_0" ,"context" :65536 ,"vision" :"no" ,"confirm" :True }) 414self .assertFalse (err ,res ) 415self .assertIn ("started in the background" ,res ["summary" ]) 416self .wait_job () 417args = json .loads ((self .root / "setup-args.json" ).read_text ()) 418self .assertEqual (args [:2 ], ["--yes" ,"--no-start" ]) 419for pair in (["--family" ,"qwen" ], ["--model" ,"Q2_0" ], ["--context" ,"65536" ], ["--vision" ,"no" ]): 420i = args .index (pair [0 ]) 421self .assertEqual (args [i :i + 2 ],pair ) 422res ,err = self .call ("strata_install" , {}) 423self .assertEqual (res ["install" ]["result" ],"installed" ) 424self .assertEqual (res ["install" ]["exit_code" ],0 ) 425self .assertEqual (res ["next" ],"strata_start" ) 426st ,_ = self .call ("strata_status" , {"hardware" :False }) 427self .assertEqual ([m ["model" ]for m in st ["installed" ]["models" ]], ["q2_0" ]) 428 429def test_progress_while_running_and_cancel (self ): 430 (self .root / "slow" ).write_text ("" ) 431res ,err = self .call ("strata_install" , {"family" :"coder" ,"confirm" :True }) 432self .assertFalse (err ,res ) 433self .assertTrue (wait_for (lambda : (self .strata .install_job ()or {}).get ("download" )is not None ,30 )) 434res ,err = self .call ("strata_install" , {"model" :"IQ3_S" ,"confirm" :True })# a second call: progress only 435self .assertFalse (err ) 436self .assertIn ("an install is running" ,res ["summary" ]) 437self .assertEqual (res ["install" ]["step" ],"5/7: downloading Qwen3.8-Flash-Next Q2_0" ) 438self .assertEqual (res ["install" ]["download" ]["percent" ],30 ) 439res ,err = self .call ("strata_start" , {}) 440self .assertTrue (err ) 441self .assertIn ("install is still running" ,res ["error" ]) 442res ,err = self .call ("strata_install" , {"cancel" :True }) 443self .assertIn ("stopped" ,res ["summary" ]) 444self .assertFalse (self .strata .install_job ()["running" ]) 445 446def test_failure_is_reported (self ): 447 (self .root / "fail" ).write_text ("" ) 448self .call ("strata_install" , {"model" :"Q2_0" ,"confirm" :True }) 449self .wait_job () 450res ,_ = self .call ("strata_install" , {}) 451self .assertEqual (res ["install" ]["result" ],"failed" ) 452self .assertIn ("not enough free disk space - use --models-dir on a bigger drive" ,res ["install" ]["error" ]) 453 454def test_disk_space_is_checked (self ): 455self .strata .disk_free = lambda p :10.0 456res ,err = self .call ("strata_install" , {"model" :"Q2_0" }) 457self .assertIn ("not enough free disk space" ,res ["plan" ]["disk_short" ]) 458res ,err = self .call ("strata_install" , {"model" :"Q2_0" ,"confirm" :True }) 459self .assertTrue (err ) 460self .assertIsNone (self .strata .install_job ()) 461 462 463# ------------------------------------------------------------------------------------------------ start / stop / status 464class StartStop (FakeRoot ): 465def test_start_status_bench_stop (self ): 466port = free_port () 467self .write_config ("q2_0" ,port = port ,delay = 1.5 ) 468res ,err = self .call ("strata_start" , {"wait_seconds" :30 }) 469self .assertFalse (err ,res ) 470self .assertIn ("Strata is running" ,res ["summary" ]) 471pid = res ["server" ]["pid" ] 472 473st ,_ = self .call ("strata_status" , {"hardware" :False }) 474self .assertIn (f"running on port { port } " ,st ["summary" ]) 475srv = st ["running" ][0 ] 476self .assertEqual (srv ["engine_version" ],"0.1.32" ) 477self .assertEqual (srv ["gpu" ]["total_mib" ],12227 ) 478self .assertIn ("this MCP server" ,srv ["started_by" ]) 479 480res ,err = self .call ("strata_start" , {})# already running: nothing new 481self .assertIn ("already running" ,res ["summary" ]) 482 483b ,err = self .call ("strata_benchmark" , {"max_tokens" :64 }) 484self .assertFalse (err ,b ) 485self .assertEqual (b ["output_tok_s" ],61.5 ) 486sent = json .loads ((self .root / "bench-request.json" ).read_text ()) 487self .assertEqual ((sent ["temperature" ],sent ["max_tokens" ],sent ["reasoning_effort" ]), (0 ,64 ,"none" )) 488 489c ,_ = self .call ("strata_connect_info" , {}) 490self .assertEqual (c ["openai_base_url" ],f"http://127.0.0.1: { port } /v1" ) 491 492logs ,_ = self .call ("strata_logs" , {"source" :"server" }) 493self .assertTrue (any (line .startswith ("ready:" )for line in logs ["lines" ])) 494 495res ,err = self .call ("strata_stop" , {}) 496self .assertFalse (err ,res ) 497self .assertIn ("Strata stopped" ,res ["summary" ]) 498self .assertEqual (res ["engine_unloaded" ],"unloaded" ) 499self .assertEqual ((self .root / "unloaded.txt" ).read_text ().split (), [str (port )]) 500ident = M .proc_identity (pid ) 501self .assertIsNone (ident ) 502st ,_ = self .call ("strata_status" , {"hardware" :False }) 503self .assertEqual (st ["running" ], []) 504res ,_ = self .call ("strata_stop" , {}) 505self .assertEqual (res ["summary" ],"Strata is not running" ) 506 507def test_start_reports_a_crash (self ): 508self .write_config ("q2_0" ,port = free_port (),crash = True ) 509res ,err = self .call ("strata_start" , {"wait_seconds" :30 }) 510self .assertTrue (err ) 511self .assertIn ("out of memory (fake)" ,res ["error" ]) 512self .assertEqual (self .strata .state ("server" ), {}) 513 514def test_loading_then_ready (self ): 515port = free_port () 516self .write_config ("q2_0" ,port = port ,delay = 3 ) 517res ,err = self .call ("strata_start" , {"wait_seconds" :0 }) 518self .assertIn ("loading" ,res ["summary" ]) 519st ,_ = self .call ("strata_status" , {"hardware" :False }) 520self .assertIn ("loading" ,st ["summary" ]) 521self .assertTrue (wait_for (lambda :self .strata .probe (port )is not None ,30 )) 522 523def test_stop_while_busy_needs_force (self ): 524port = free_port () 525self .write_config ("q2_0" ,port = port ,busy = True ) 526self .call ("strata_start" , {"wait_seconds" :30 }) 527res ,err = self .call ("strata_stop" , {}) 528self .assertTrue (err ) 529self .assertIn ("force=true" ,res ["error" ]) 530res ,err = self .call ("strata_stop" , {"force" :True }) 531self .assertFalse (err ,res ) 532 533def test_external_server_is_only_unloaded (self ): 534port = free_port () 535self .write_config ("q2_0" ,port = port ) 536p = subprocess .Popen ([sys .executable ,str (self .root / "serve" / "server.py" ),"--config" , 537str (self .root / "strata-q2_0.json" ),"--port" ,str (port )], 538stdout = subprocess .DEVNULL ,stderr = subprocess .DEVNULL ) 539self .extra .append (p ) 540self .assertTrue (wait_for (lambda :self .strata .probe (port )is not None ,30 )) 541st ,_ = self .call ("strata_status" , {"hardware" :False }) 542self .assertIn ("outside this MCP server" ,st ["running" ][0 ]["started_by" ]) 543res ,err = self .call ("strata_start" , {}) 544self .assertIn ("started outside this MCP server" ,res ["summary" ]) 545res ,err = self .call ("strata_stop" , {}) 546self .assertFalse (err ,res ) 547self .assertIn ("only its model was unloaded" ,res ["summary" ]) 548time .sleep (0.5 ) 549self .assertIsNone (p .poll ())# the server itself was not touched 550 551def test_never_kills_an_unrelated_process (self ): 552other = subprocess .Popen ([sys .executable ,"-c" ,"import time; time.sleep(60)" ]) 553self .extra .append (other ) 554# a stale record: this process id, but another start time (a reused id) 555self .strata .save_state ("server" , {"pid" :other .pid ,"ident" :"win:1" if M .WIN else "linux:1" , 556"port" :free_port (),"model" :"q2_0" }) 557res ,_ = self .call ("strata_stop" , {}) 558self .assertEqual (res ["summary" ],"Strata is not running" ) 559self .assertFalse (M .proc_terminate (other .pid ,"linux:1" )) 560time .sleep (0.3 ) 561self .assertIsNone (other .poll ()) 562 563def test_status_sees_other_programs_on_the_port (self ): 564class H (BaseHTTPRequestHandler ): 565def do_GET (self ): 566self .send_response (404 ) 567self .end_headers () 568 569def log_message (self ,* a ): 570pass 571httpd = HTTPServer (("127.0.0.1" ,0 ),H ) 572port = httpd .server_address [1 ] 573threading .Thread (target = httpd .serve_forever ,daemon = True ).start () 574try : 575self .write_config ("q2_0" ,port = port ) 576st ,_ = self .call ("strata_status" , {"hardware" :False }) 577self .assertEqual (st ["running" ], []) 578self .assertEqual (st ["ports_used_by_other_programs" ][0 ]["port" ],port ) 579res ,err = self .call ("strata_start" , {}) 580self .assertTrue (err ) 581self .assertIn ("used by another program" ,res ["error" ]) 582finally : 583httpd .shutdown () 584httpd .server_close () 585 586 587# ------------------------------------------------------------------------------------------------ helpers 588class Helpers (unittest .TestCase ): 589def test_progress_from_setup_output (self ): 590with tempfile .TemporaryDirectory ()as d : 591f = Path (d )/ "setup.log" 592f .write_text ("=== Step 4: the Strata engine ===\n [ok] engine\n=== Step 5: downloading X ===\n" 593"\r a.gguf: 1.00 / 50.00 GB (2%) \r a.gguf: 25.00 / 50.00 GB (50%) \n" ) 594p = M .install_progress (M .read_tail (f ,50 )) 595self .assertEqual (p ["step" ],"5/7: downloading X" ) 596self .assertEqual (p ["download" ], {"file" :"a.gguf" ,"done_gb" :25.0 ,"total_gb" :50.0 ,"percent" :50 }) 597self .assertNotIn ("error" ,p ) 598 599def test_builtin_table_matches_setup (self ): 600s = M .Strata (HERE .parent ) 601S = s .setup_module () 602self .assertIsNotNone (S ,"the repository's setup.py did not import" ) 603self .assertEqual (list (S .MODELS ),list (M .FALLBACK_MODELS )) 604for m ,d in S .MODELS .items (): 605for k in ("download_gb" ,"ram_gb" ,"arena_gb" ): 606self .assertEqual (d [k ],M .FALLBACK_MODELS [m ][k ],f" { m } { k } " ) 607for k in ("experimental" ,"vision" ): 608self .assertEqual (d .get (k ),M .FALLBACK_MODELS [m ].get (k ),f" { m } { k } " ) 609self .assertEqual (d .get ("families" , ("qwen" ,"swift" )),M .FALLBACK_MODELS [m ].get ("families" , ("qwen" ,"swift" ))) 610self .assertEqual (list (S .FAMILIES ),list (M .FALLBACK_FAMILIES )) 611for f ,d in S .FAMILIES .items (): 612self .assertEqual (d ["tag" ],M .FALLBACK_FAMILIES [f ]["tag" ]) 613self .assertEqual (list (S .CONTEXTS ),M .FALLBACK_CONTEXTS ) 614 615def test_unsloth_sizes (self ): 616"""0.1.39: UD-IQ4_XS is a regular size, listed first; MODEL-UPDATE Phase 2: UD-Q4_K_XL is no longer experimental, 617and UD-Q5_K_XL, UD-Q6_K_XL and Q8_0 follow by size.""" 618s = M .Strata (HERE .parent ) 619for models in (s .tables ()[0 ],M .FALLBACK_MODELS ): 620self .assertEqual (s .sizes_of (models ,"unsloth" ), ["UD-IQ4_XS" ,"UD-Q4_K_XL" ,"UD-Q5_K_XL" ,"UD-Q6_K_XL" ,"Q8_0" ,"UD-IQ1_M" ,"UD-Q2_0" , 621"UD-IQ2_XS" ,"UD-Q2_K_XL" ,"UD-IQ3_XXS" ,"UD-Q3_K_XL" ,"UD-IQ4_XS-v31" ]) 622self .assertFalse (models ["UD-IQ4_XS" ].get ("experimental" )) 623self .assertFalse (models ["UD-Q4_K_XL" ].get ("experimental" )) 624self .assertEqual (s .sizes_of (M .FALLBACK_MODELS ,"qwen" ), ["Q2_0" ,"IQ2_XS" ,"IQ3_XXS" ,"IQ3_S" ]) 625fam = next (f for f in s .model_table ({"ram_gb" :63.7 ,"gpus" : []})if f ["family" ]== "unsloth" ) 626self .assertFalse (fam ["experimental" ]) 627self .assertTrue (fam ["images" ]) 628by = {x ["model" ]:x for x in fam ["sizes" ]} 629self .assertEqual ((by ["UD-IQ4_XS" ]["experimental" ],by ["UD-IQ4_XS" ]["images" ]), (False ,True )) 630self .assertEqual ((by ["UD-Q4_K_XL" ]["experimental" ],by ["UD-Q4_K_XL" ]["images" ]), (False ,True ))# #967 631self .assertFalse (by ["UD-IQ4_XS" ]["on_this_pc" ].startswith ("experimental" )) 632self .assertEqual (by ["UD-IQ1_M" ]["on_this_pc" ],"fits" )# 63.7 GB of RAM, no card: 39.2 GB (68.0 download minus the 28.8 GB table) 633self .assertEqual (by ["UD-IQ4_XS" ]["on_this_pc" ],"may run slower" )# 64.9 GB 634self .assertEqual (by ["UD-Q4_K_XL" ]["on_this_pc" ],"may run slower" )# 82.5 GB 635fam = next (f for f in s .model_table ({"ram_gb" :127.8 ,"gpus" : []})if f ["family" ]== "unsloth" ) 636by = {x ["model" ]:x for x in fam ["sizes" ]} 637self .assertEqual (by ["UD-Q4_K_XL" ]["on_this_pc" ],"fits" ) 638self .assertEqual (by ["Q8_0" ]["on_this_pc" ],"may run slower" )# 133.8 GB (188.2 minus its 54.4 GB table) against 127.8 GB 639 640def test_qwen36_is_listed_with_its_three_sizes (self ): 641"""QA 2026-10-18: the Qwen3.6-35B-A3B page of the first-run setup showed no versions, because setup.py keeps the family 642in OWN_PATH_FAMILIES (not FAMILIES) and the model list only walked FAMILIES.""" 643s = M .Strata (HERE .parent ) 644self .assertIn ("qwen36" ,s .tables ()[1 ]) 645fam = next (f for f in s .model_table ({"ram_gb" :63.7 ,"gpus" : [{"index" :0 ,"name" :"x" ,"vram_gb" :12.0 ,"usable" :True }]}) 646if f ["family" ]== "qwen36" ) 647by = {x ["model" ]:x for x in fam ["sizes" ]} 648self .assertEqual (list (by ), ["UD-Q4_K_XL" ,"UD-Q6_K_XL" ,"Q8_0" ]) 649self .assertEqual (by ["UD-Q4_K_XL" ]["id" ],"qwen36-ud-q4_k_xl" )# the tag the install writes its config under 650self .assertEqual (by ["UD-Q4_K_XL" ]["download_gb" ],22.9 ) 651self .assertTrue (all (x ["images" ]and x ["engine_min" ]== "0.1.45" and x ["gpu_options" ]is None for x in by .values ())) 652self .assertEqual ({x ["on_this_pc" ]for x in by .values ()}, {"fits" }) 653# #5715: the app's context estimate reads Qwen3.6's own figures from the row (strata_control/own_path_fit.py); other models have none 654from strata_control import own_path_fit 655self .assertEqual ({m :x ["context_fit" ]for m ,x in by .items ()}, {m :own_path_fit .inputs ("qwen3.6-35b-a3b" ,m )for m in by }) 656self .assertEqual (by ["UD-Q4_K_XL" ]["context_fit" ]["bytes_per_token" ],47104 ) 657others = [x for f in s .model_table ({"ram_gb" :63.7 ,"gpus" : []})if f ["family" ]!= "qwen36" for x in f ["sizes" ]] 658self .assertTrue (others and not any ("context_fit" in x for x in others )) 659small = next (f for f in s .model_table ({"ram_gb" :16 ,"gpus" : []})if f ["family" ]== "qwen36" ) 660self .assertEqual ({x ["on_this_pc" ]for x in small ["sizes" ]}, {"may run slower" })# 16 GB, no card: 21 to 36 GB of weights 661self .assertEqual (s .sizes_of (s .tables ()[0 ],"unsloth" )[:5 ], ["UD-IQ4_XS" ,"UD-Q4_K_XL" ,"UD-Q5_K_XL" ,"UD-Q6_K_XL" ,"Q8_0" ])# the Unsloth Flash-Next sizes are untouched (round 0214 adds sizes after them) 662 663def test_qwen36_install_plan (self ): 664s = M .Strata (HERE .parent ) 665s .hardware = lambda fresh = False : {"ram_gb" :64.0 ,"gpus" : [{"index" :0 ,"name" :"x" ,"vram_gb" :12.0 ,"usable" :True ,"vendor" :"nvidia" }], 666"cpu" : {"avx2" :True }} 667s .disk_free = lambda p :1000.0 668plan ,args = M .Tools (s ).install_plan ("qwen36" ,"UD-Q4_K_XL" ,32768 ,"yes" ,"int8" ,None ,None ,None ,"auto" ,None ,None ) 669self .assertEqual ((plan ["title" ],plan ["download_gb" ],plan ["family" ]), ("Qwen3.6-35B-A3B UD-Q4_K_XL" ,22.9 ,"qwen36" )) 670self .assertEqual (args [:10 ], ["--yes" ,"--no-start" ,"--family" ,"qwen36" ,"--model" ,"UD-Q4_K_XL" ,"--context" ,"32768" , 671"--vision" ,"yes" ]) 672for flag in ("--kv" ,"--low-ram" ,"--experimental-speed-projection" ):# Flash-Next settings: setup would only warn 673self .assertNotIn (flag ,args ) 674plan ,_a = M .Tools (s ).install_plan ("qwen36" ,None ,32768 ,"no" ,None ,None ,None ,None ,None ,None ,None ) 675self .assertEqual (plan ["model" ],"UD-Q4_K_XL" ) 676# #5715: no context given: the size that fits the 12 GB card (32K), not 128K; a 16 GB card keeps 128K 677_p ,args = M .Tools (s ).install_plan ("qwen36" ,"UD-Q4_K_XL" ,None ,"no" ,None ,None ,None ,None ,None ,None ,None ) 678self .assertEqual (args [args .index ("--context" )+ 1 ],"32768" ) 679s .hardware = lambda fresh = False : {"ram_gb" :64.0 ,"gpus" : [{"index" :0 ,"name" :"x" ,"vram_gb" :15.93 ,"usable" :True ,"vendor" :"nvidia" }], 680"cpu" : {"avx2" :True }} 681_p ,args = M .Tools (s ).install_plan ("qwen36" ,"UD-Q4_K_XL" ,None ,"no" ,None ,None ,None ,None ,None ,None ,None ) 682self .assertEqual (args [args .index ("--context" )+ 1 ],"131072" ) 683with self .assertRaises (M .ToolError ): 684M .Tools (s ).install_plan ("qwen36" ,"IQ3_S" ,32768 ,"no" ,None ,None ,None ,None ,None ,None ,None ) 685 686def test_the_apps_drafting_off_reaches_setup_as_mtp_off (self ): 687# notes-ctrl-fix-2: the app's Off on a Mac still fetched the draft layer; the installer had no word for it (the Terminal's 1821f298d passes --mtp off) 688s = M .Strata (HERE .parent ) 689s .hardware = lambda fresh = False : {"ram_gb" :64.0 ,"gpus" : [{"index" :0 ,"name" :"x" ,"vram_gb" :16.0 ,"usable" :True ,"vendor" :"nvidia" }], 690"cpu" : {"avx2" :True }} 691s .disk_free = lambda p :1000.0 692tools = M .Tools (s ) 693_p ,args = tools .install_plan ("qwen36" ,"UD-Q4_K_XL" ,32768 ,"no" ,None ,None ,None ,None ,None ,None ,None ,None ,None ,"off" ) 694self .assertEqual (args [args .index ("--mtp" ):args .index ("--mtp" )+ 2 ], ["--mtp" ,"off" ]) 695_p ,args = tools .install_plan ("qwen36" ,"UD-Q4_K_XL" ,32768 ,"no" ,None ,None ,None ,None ,None ,None ,None ) 696self .assertNotIn ("--mtp" ,args ,"no word: setup decides as before" ) 697models ,families ,contexts ,_src = s .tables () 698schema = next (t for t in M .tool_defs (models ,families ,contexts )if t ["name" ]== "strata_install" )["inputSchema" ]["properties" ] 699self .assertEqual (schema ["mtp" ]["enum" ], ["on" ,"off" ]) 700 701def test_recommendation_follows_ram (self ): 702s = M .Strata (HERE .parent ) 703gpu = [{"index" :0 ,"name" :"x" ,"vram_gb" :24.0 ,"usable" :True ,"vendor" :"nvidia" }] 704cases = {96 : ("qwen" ,"IQ3_S" ,131072 ),48 : ("qwen" ,"IQ3_S" ,131072 ),32 : ("qwen" ,"IQ3_XXS" ,131072 ),12 : ("coder" ,"IQ1_M" ,131072 )}# the owner's tiers count RAM + VRAM (24 GB card): 120, 72, 56 GB; the Coder where the older rules stand 705for ram ,want in cases .items (): 706r = s .recommend ({"ram_gb" :ram ,"gpus" :gpu ,"cpu" : {"avx2" :True }}) 707self .assertEqual ((r ["family" ],r ["model" ],r ["context" ]),want ,ram ) 708r = s .recommend ({"ram_gb" :16 ,"gpus" : [{** gpu [0 ],"vram_gb" :8.0 }],"cpu" : {"avx2" :True }}) 709self .assertIsNone (r ["model" ]) 710r = s .recommend ({"ram_gb" :64 ,"gpus" : [],"cpu" : {"avx2" :True }}) 711self .assertIsNone (r ["model" ]) 712r = s .recommend ({"ram_gb" :64 ,"gpus" : [{** gpu [0 ],"vram_gb" :12.0 }],"cpu" : {"avx2" :True }}) 713self .assertEqual (r ["context" ],131072 )# 128K on every card, a 12 GB one too (owner, 2026-11-01) 714 715def test_a_pick_that_reads_from_the_ssd_says_so (self ): 716# #3425: 36 GB RAM + 16 GB VRAM - 5 GB is the 48 GB tier; about 8 GB of IQ3_XXS would come from the SSD 717s = M .Strata (HERE .parent ) 718gpu = [{"index" :0 ,"name" :"x" ,"vram_gb" :15.9 ,"usable" :True ,"vendor" :"nvidia" }] 719r = s .recommend ({"ram_gb" :36.0 ,"gpus" :gpu ,"cpu" : {"avx2" :True }}) 720self .assertEqual ((r ["family" ],r ["model" ]), ("qwen" ,"IQ3_XXS" )) 721self .assertTrue (any ("read from the SSD" in n for n in r ["notes" ]),r ["notes" ]) 722roomy = s .recommend ({"ram_gb" :64 ,"gpus" :gpu ,"cpu" : {"avx2" :True }}) 723self .assertFalse (any ("read from the SSD" in n for n in roomy ["notes" ]),roomy ["notes" ]) 724 725def test_3425_the_tiers_leave_5_gb_for_windows (self ): 726# the reporter: RTX 5080 (16 GB) + 32 GB of RAM used to sum to 48 GB and get IQ3_XXS; now the 40 GB tier 727s = M .Strata (HERE .parent ) 728gpu = [{"index" :0 ,"name" :"x" ,"vram_gb" :15.9 ,"usable" :True ,"vendor" :"nvidia" }] 729self .assertEqual (M .TIER_SYSTEM_RESERVE_GB ,5.0 ) 730r = s .recommend ({"ram_gb" :31.9 ,"gpus" :gpu ,"cpu" : {"avx2" :True }}) 731self .assertEqual ((r ["family" ],r ["model" ]), ("swift" ,"IQ2_XS" )) 732# boundary: 43 GB of RAM + VRAM is the lowest 40 GB tier PC, 51 GB the lowest 48 GB tier PC 733def pick (ram ,vram ): 734g = [{** gpu [0 ],"vram_gb" :vram }] 735r = s .recommend ({"ram_gb" :ram ,"gpus" :g ,"cpu" : {"avx2" :True }}) 736return r ["family" ],r ["model" ] 737self .assertEqual (pick (30.0 ,13.0 ), ("swift" ,"IQ2_XS" )) 738self .assertNotEqual (pick (30.0 ,12.9 ), ("swift" ,"IQ2_XS" )) 739self .assertEqual (pick (38.0 ,13.0 ), ("qwen" ,"IQ3_XXS" )) 740self .assertEqual (pick (38.0 ,12.9 ), ("swift" ,"IQ2_XS" )) 741self .assertEqual (pick (54.0 ,13.0 ), ("qwen" ,"IQ3_S" )) 742self .assertEqual (pick (54.0 ,12.9 ), ("qwen" ,"IQ3_XXS" )) 743 744 745class PhysicalCores (unittest .TestCase ): 746"""#3417: the hardware report's cpu.cores is the physical cores; the Work profile takes 80% of it for --pool-workers.""" 747 748def test_physical_not_logical (self ): 749from strata_control import tune_machine 750with mock .patch .object (tune_machine ,"cpu" ,return_value = {"model" :"x" ,"logical" :16 ,"physical" :8 ,"hybrid" :False }),mock .patch .object (M .os ,"cpu_count" ,return_value = 16 ): 751self .assertEqual (M .physical_cores (),8 ) 752 753def test_unknown_falls_back_to_threads (self ): 754from strata_control import tune_machine 755with mock .patch .object (tune_machine ,"cpu" ,return_value = {"physical" :None }),mock .patch .object (M .os ,"cpu_count" ,return_value = 16 ): 756self .assertEqual (M .physical_cores (),16 ) 757with mock .patch .object (tune_machine ,"cpu" ,side_effect = OSError ("no" )),mock .patch .object (M .os ,"cpu_count" ,return_value = 4 ): 758self .assertEqual (M .physical_cores (),4 ) 759 760 761class MacCatalog (unittest .TestCase ): 762"""A Mac (Apple Silicon): one pool of unified memory, judged by strata_control/mac_fit.py (the rules metal/setup_mac.py uses).""" 763 764def hw (self ,ram ,macos = "27.2" ,chip = "Apple M4" ): 765from strata_control import mac_fit 766s = M .Strata (HERE .parent ) 767info = {"chip" :chip ,"ram_gb" :float (ram ),"macos" :macos ,"arm64" :True ,"clt" :"" ,"perf_cores" :4 } 768with mock .patch .object (M .sys ,"platform" ,"darwin" ),mock .patch .object (mac_fit ,"mac_info" ,return_value = info ): 769hw = s ._hardware () 770return s ,hw 771 772def test_the_hardware_is_one_apple_gpu_with_unified_memory (self ): 773s ,hw = self .hw (32 ) 774self .assertEqual (hw ["ram_gb" ],32.0 ) 775self .assertEqual (len (hw ["gpus" ]),1 ) 776g = hw ["gpus" ][0 ] 777self .assertEqual ((g ["vendor" ],g ["name" ],g ["usable" ],g ["vram_gb" ],g ["unified_gb" ]), ("apple" ,"Apple M4" ,True ,0.0 ,32.0 )) 778self .assertEqual (hw ["mac" ]["unified_gb" ],32.0 ) 779self .assertFalse (hw ["nvidia_smi" ]) 780 781def test_recommendation_by_unified_memory (self ): 782cases = {32 : ("Q2_0" ,32768 ),48 : ("Q2_0" ,32768 ),80 : ("IQ3_XXS" ,32768 ),128 : ("IQ3_S" ,65536 )} 783for ram , (model ,ctx )in cases .items (): 784s ,hw = self .hw (ram ) 785r = s .recommend (hw ) 786self .assertEqual ((r ["family" ],r ["model" ],r ["context" ],r ["backend" ]), ("qwen" ,model ,ctx ,"metal" ),ram ) 787self .assertNotIn ("NVIDIA" ,r ["why" ]) 788self .assertFalse ([n for n in r ["notes" ]if "UD-" in n ],"the Unsloth sizes are not offered in the app yet" ) 789s ,hw = self .hw (32 ) 790self .assertIn ("read from the SSD" ,s .recommend (hw )["why" ]) 791s ,hw = self .hw (128 ) 792self .assertIn ("stays in memory" ,s .recommend (hw )["why" ]) 793 794def test_a_mac_too_small_or_too_old_has_no_recommendation_and_says_why (self ): 795s ,hw = self .hw (8 ) 796r = s .recommend (hw ) 797self .assertIsNone (r ["model" ]) 798self .assertIn ("8 GB of unified memory" ,r ["why" ]) 799s ,hw = self .hw (32 ,macos = "14.6" ) 800r = s .recommend (hw ) 801self .assertIsNone (r ["model" ]) 802self .assertIn ("macOS 15 or newer" ,r ["why" ]) 803 804def test_the_model_list_is_the_macs_sizes_with_unified_memory_verdicts (self ): 805s ,hw = self .hw (32 ) 806fams = s .model_table (hw ) 807self .assertEqual ([f ["family" ]for f in fams ], ["qwen" ,"unsloth" ,"gyro" ], 808"Unsloth's sets since round 0214 (the app repacks them), no Swift or NVFP4 on a Mac; Gyro after the regular sizes" ) 809by = {x ["model" ]:x for x in fams [0 ]["sizes" ]} 810self .assertEqual (list (by ), ["Q2_0" ,"IQ3_XXS" ,"IQ3_S" ]) 811un = {x ["model" ]:x for x in fams [1 ]["sizes" ]} 812self .assertEqual (list (un ), ["UD-IQ1_M" ,"UD-Q2_0" ,"UD-IQ2_XS" ,"UD-Q2_K_XL" ,"UD-IQ3_XXS" ,"UD-Q3_K_XL" ,"UD-IQ4_XS-v31" ,"UD-Q4_K_XL" ,"UD-Q5_K_XL" ,"UD-Q6_K_XL" ]) 813self .assertEqual ((un ["UD-IQ1_M" ]["download_gb" ],un ["UD-IQ1_M" ]["experts_gb" ]), (68.0 ,34.8 )) 814self .assertTrue (all (x ["on_this_pc" ]and x ["images" ]and x ["id" ]== "unsloth-" + x ["model" ].lower ()for x in un .values ())) 815self .assertEqual (un ["UD-Q5_K_XL" ]["on_this_pc" ],"may run slower" ,"32 GB: 99 GB of weights, said not refused" ) 816gy = {x ["model" ]:x for x in fams [2 ]["sizes" ]} 817self .assertEqual (list (gy ), ["Gyro-S" ,"Gyro-M" ]) 818self .assertEqual (gy ["Gyro-S" ]["download_gb" ],58.5 ) 819self .assertEqual ({v ["on_this_pc" ]for v in gy .values ()}, {"may run slower" },"32 GB: both stream (said, not refused)" ) 820self .assertEqual (by ["Q2_0" ]["on_this_pc" ],"may run slower" ) 821self .assertEqual (by ["IQ3_S" ]["on_this_pc" ],"may run slower" ) 822self .assertTrue (all (x ["images" ]for x in by .values ()),"the Mac engine carries the Metal picture reader: pictures are on" ) 823s ,hw = self .hw (128 ) 824fits = {x ["model" ]:x ["on_this_pc" ]for f in s .model_table (hw )for x in f ["sizes" ]} 825from strata_control import mac_fit 826for m ,v in fits .items ():# the 128 GB Mac keeps ~96 GB resident: UD-Q5_K_XL and UD-Q6_K_XL (104 / 115 GB to map) stream, said not refused 827self .assertEqual (v == "fits" ,not mac_fit .streams (m ,128.0 ),m ) 828self .assertIn (v , ("fits" ,"may run slower" ),m ) 829self .assertEqual ({m for m ,v in fits .items ()if v != "fits" }, {"UD-Q5_K_XL" ,"UD-Q6_K_XL" }) 830s ,hw = self .hw (8 ) 831self .assertEqual ({x ["on_this_pc" ]for f in s .model_table (hw )for x in f ["sizes" ]}, {"may run slower" })# too little memory: the same two words 832 833def test_the_install_plan_on_a_mac_has_no_card_kv_or_ram_options (self ): 834s ,hw = self .hw (32 ) 835s .hardware = lambda fresh = False :hw 836s .disk_free = lambda p :1000.0 837with tempfile .TemporaryDirectory ()as own : 838plan ,args = M .Tools (s ).install_plan ("qwen" ,"Q2_0" ,None ,"no" ,"int8" ,0 ,None ,None ,"auto" ,None ,None ,own ) 839self .assertEqual (plan ["context" ],32768 ) 840self .assertEqual (args [:9 ], ["--yes" ,"--no-start" ,"--family" ,"qwen" ,"--model" ,"Q2_0" ,"--context" ,"32768" ,"--vision" ]) 841for flag in ("--kv" ,"--gpu" ,"--gpus" ,"--low-ram" ,"--backend" ): 842self .assertNotIn (flag ,args ) 843self .assertIn ("--gguf-dir" ,args ) 844with tempfile .TemporaryDirectory ()as own :# nothing said about pictures: on, as everywhere (the Mac's reader is the Metal one) 845_plan ,args = M .Tools (s ).install_plan ("qwen" ,"Q2_0" ,None ,None ,"int8" ,0 ,None ,None ,"auto" ,None ,None ,own ) 846self .assertEqual (args [args .index ("--vision" )+ 1 ],"yes" ) 847with self .assertRaises (M .ToolError ): 848s2 ,hw2 = self .hw (8 ) 849s2 .hardware = lambda fresh = False :hw2 850M .Tools (s2 ).install_plan (None ,None ,None ,None ,None ,None ,None ,None ,None ,None ,None ) 851 852def test_the_install_plan_counts_the_repacked_file_of_an_unsloth_set (self ): 853"""Round 0214: the Mac app repacks Unsloth's shards into one GGUF: the disk it needs is the download, that file (mac_fit shard1_gb) and room to work.""" 854s ,hw = self .hw (128 ) 855s .hardware = lambda fresh = False :hw 856s .disk_free = lambda p :1000.0 857# a person's data folder, not the system's temp folder: on macOS that is under /var/folders, which the tool refuses as a system folder. 858# The account's own home from the user database: the test's fake root may point HOME at a temp folder 859real_home = None 860if sys .platform == "darwin" : 861import pwd 862real_home = pwd .getpwuid (os .getuid ()).pw_dir 863with tempfile .TemporaryDirectory (dir = real_home )as t : 864target = Path (t )/ "Strata-data" 865target .mkdir () 866plan ,args = M .Tools (s ).install_plan ("unsloth" ,"UD-IQ1_M" ,None ,"no" ,"int8" ,0 ,None ,None ,"auto" ,None ,str (target )) 867plain ,_ = M .Tools (s ).install_plan ("qwen" ,"Q2_0" ,None ,"no" ,"int8" ,0 ,None ,None ,"auto" ,None ,str (target )) 868self .assertEqual (plan ["disk_needed_gb" ],round (68.0 + 8 + 39.2 )) 869self .assertEqual (plain ["disk_needed_gb" ],round (plain ["download_gb" ]+ 8 ))# no repack for a GSQ-RCO file 870self .assertEqual (args [:6 ], ["--yes" ,"--no-start" ,"--family" ,"unsloth" ,"--model" ,"UD-IQ1_M" ]) 871s .disk_free = lambda p :100.0 872with tempfile .TemporaryDirectory (dir = real_home )as t :# (the same reason as above) 873target = Path (t )/ "Strata-data" 874target .mkdir () 875short ,_ = M .Tools (s ).install_plan ("unsloth" ,"UD-IQ1_M" ,None ,"no" ,"int8" ,0 ,None ,None ,"auto" ,None ,str (target )) 876self .assertIn ("not enough free disk space" ,short ["disk_short" ]) 877 878def test_a_pc_is_unchanged (self ): 879s = M .Strata (HERE .parent ) 880r = s .recommend ({"ram_gb" :96 ,"gpus" : [{"index" :0 ,"name" :"x" ,"vram_gb" :24.0 ,"usable" :True ,"vendor" :"nvidia" }], 881"cpu" : {"avx2" :True }}) 882self .assertEqual ((r ["family" ],r ["model" ]), ("qwen" ,"IQ3_S" )) 883self .assertIn ("unsloth" , [f ["family" ]for f in s .model_table ({"ram_gb" :96 ,"gpus" : []})]) 884 885 886class MixedGraphics (unittest .TestCase ): 887def test_an_integrated_amd_gpu_beside_an_nvidia_card_is_not_offered (self ): 888s = M .Strata (HERE .parent ) 889S = s .setup_module () 890nv = [{"index" :0 ,"name" :"NVIDIA GeForce RTX 5090" ,"vram_gb" :31.8 ,"arch" :"120" ,"driver" :"580.95" }] 891igpu = [{"index" :0 ,"name" :"AMD Radeon Graphics" ,"vram_gb" :0.5 ,"arch" :"gfx1036" ,"uma" :True }] 892with mock .patch .object (M .sys ,"platform" ,"linux" ),mock .patch .object (M ,"WIN" ,False ),mock .patch .object (S ,"gpus" ,lambda : [dict (g )for g in nv ]),mock .patch .object (S ,"gpu_problem" ,lambda g :None ),mock .patch .object (S ,"amd_gpus" ,lambda : [dict (g )for g in igpu ]),mock .patch .object (S ,"amd_problem" ,lambda g :None ): 893hw = s ._hardware () 894by = {g ["vendor" ]:g for g in hw ["gpus" ]} 895self .assertTrue (by ["nvidia" ]["usable" ]) 896self .assertFalse (by ["amd" ]["usable" ]) 897self .assertIn ("NVIDIA card" ,by ["amd" ]["problem" ]) 898# the RTX and the Ryzen iGPU both say index 0 (each make counts from 0), so the report gives each a stable id of its own 899self .assertEqual ((by ["nvidia" ]["index" ],by ["amd" ]["index" ]), (0 ,0 )) 900self .assertEqual (sorted (g ["id" ]for g in hw ["gpus" ]), ["amd:0" ,"nvidia:0" ]) 901rec = s .recommend ({** hw ,"ram_gb" :92.0 }) 902self .assertEqual ((rec ["backend" ],rec ["gpu" ]["name" ]), ("cuda" ,"NVIDIA GeForce RTX 5090" )) 903# with no NVIDIA card the integrated GPU stays what it was 904with mock .patch .object (M .sys ,"platform" ,"linux" ),mock .patch .object (M ,"WIN" ,False ),mock .patch .object (S ,"gpus" ,lambda : []),mock .patch .object (S ,"amd_gpus" ,lambda : [dict (g )for g in igpu ]),mock .patch .object (S ,"amd_problem" ,lambda g :None ): 905self .assertTrue (s ._hardware ()["gpus" ][0 ]["usable" ]) 906 907def test_two_gtx_1080_are_a_working_pc_on_the_cuda_12_engine (self ): 908"""#3655: Pascal cards were flagged 'not supported' and both started Off, so the app said no card was usable. When Pascal is all the PC has 909(and no AMD card), setup runs them with the CUDA 12 engine, and the hardware report now says so; a newer card keeps the old behaviour.""" 910s = M .Strata (HERE .parent ) 911S = s .setup_module () 912pascal = [{"index" :0 ,"name" :"NVIDIA GeForce GTX 1080" ,"vram_gb" :8.0 ,"arch" :"61" ,"driver" :"581.15" }, 913 {"index" :1 ,"name" :"NVIDIA GeForce GTX 1080" ,"vram_gb" :8.0 ,"arch" :"61" ,"driver" :"581.15" }] 914igpu = [{"index" :0 ,"name" :"AMD Radeon(TM) Graphics" ,"vram_gb" :0.5 ,"arch" :"gfx90c" ,"uma" :True }] 915patches = (mock .patch .object (M .sys ,"platform" ,"linux" ),mock .patch .object (M ,"WIN" ,False ), 916mock .patch .object (S ,"amd_gpus" ,lambda : [dict (g )for g in igpu ]),mock .patch .object (S ,"amd_problem" ,lambda g :"integrated graphics" ), 917mock .patch .dict (M .os .environ , {"STRATA_EXPERIMENTAL_SM60" :"" }),mock .patch .object (S ,"OLD_GPUS" ,None )) 918with mock .patch .object (S ,"gpus" ,lambda : [dict (g )for g in pascal ]): 919for p in patches : 920p .start () 921try : 922hw = s ._hardware () 923finally : 924for p in reversed (patches ): 925p .stop () 926nv = [g for g in hw ["gpus" ]if g ["vendor" ]== "nvidia" ] 927self .assertEqual ([(g ["usable" ],g ["problem" ],g .get ("engine_variant" ))for g in nv ], [(True ,None ,"cuda12" )]* 2 ) 928# a newer card in the PC: Pascal stays an opt-in, the ready-made engine is recommended 929mixed = [{"index" :0 ,"name" :"NVIDIA GeForce GTX 1080" ,"vram_gb" :8.0 ,"arch" :"61" ,"driver" :"581.15" }, 930 {"index" :1 ,"name" :"NVIDIA GeForce RTX 3060" ,"vram_gb" :12.0 ,"arch" :"86" ,"driver" :"581.15" }] 931with mock .patch .object (S ,"gpus" ,lambda : [dict (g )for g in mixed ]): 932for p in patches : 933p .start () 934try : 935hw = s ._hardware () 936finally : 937for p in reversed (patches ): 938p .stop () 939by = {g ["name" ]:g for g in hw ["gpus" ]if g ["vendor" ]== "nvidia" } 940self .assertFalse (by ["NVIDIA GeForce GTX 1080" ]["usable" ]) 941self .assertTrue (by ["NVIDIA GeForce RTX 3060" ]["usable" ]) 942 943def test_an_amd_card_the_installed_engine_has_no_code_for_is_not_usable (self ): 944"""#3203: the engine package lists its GPU code; a card outside it is flagged unusable with the plain reason, so no list offers it.""" 945status = {"usable" :True ,"engine" : {"backend" :"hip" ,"archs" : ["gfx1200" ,"gfx1201" ]}} 946hw = {"gpus" : [{"vendor" :"amd" ,"index" :0 ,"name" :"AMD Radeon 760M" ,"arch" :"gfx1103" ,"usable" :False ,"problem" :"integrated" }, 947 {"vendor" :"amd" ,"index" :1 ,"name" :"AMD Radeon RX 6800 XT" ,"arch" :"gfx1030" ,"usable" :True ,"problem" :None }, 948 {"vendor" :"amd" ,"index" :2 ,"name" :"AMD Radeon RX 9070 XT" ,"arch" :"gfx1201" ,"usable" :True ,"problem" :None }, 949 {"vendor" :"nvidia" ,"index" :0 ,"name" :"NVIDIA GeForce RTX 3060" ,"arch" :"86" ,"usable" :True ,"problem" :None }]} 950with mock .patch ("strata_control.engine_component.status" ,lambda :status ): 951M .Strata ._engine_code (hw ) 952by = {g ["name" ]:g for g in hw ["gpus" ]} 953self .assertFalse (by ["AMD Radeon RX 6800 XT" ]["usable" ]) 954self .assertIn ("no code for gfx1030" ,by ["AMD Radeon RX 6800 XT" ]["problem" ]) 955self .assertEqual (by ["AMD Radeon 760M" ]["problem" ],"integrated" ,"an earlier reason stays" ) 956self .assertTrue (by ["AMD Radeon RX 9070 XT" ]["usable" ]) 957self .assertTrue (by ["NVIDIA GeForce RTX 3060" ]["usable" ]) 958# no engine package that lists archs (a source build, no engine yet): nothing is judged 959for other in ({"usable" :False }, {"usable" :True ,"engine" : {"backend" :"cuda" ,"archs" : ["sm_86" ]}}): 960again = {"gpus" : [{"vendor" :"amd" ,"index" :1 ,"name" :"x" ,"arch" :"gfx1030" ,"usable" :True ,"problem" :None }]} 961with mock .patch ("strata_control.engine_component.status" ,lambda other = other :other ): 962M .Strata ._engine_code (again ) 963self .assertTrue (again ["gpus" ][0 ]["usable" ]) 964 965@ mock . patch ( "strata_control.engine_component.status" , lambda : { "usable" : False }) # not this PC's installed (CUDA) engine 966def test_windows_lists_an_amd_card_and_not_the_integrated_radeon (self ): 967s = M .Strata (HERE .parent ) 968S = s .setup_module () 969cards = [{"index" :0 ,"name" :"AMD Radeon RX 9070 XT" ,"vram_gb" :15.9 ,"arch" :"gfx1201" ,"driver" :"32.0.1" }, 970 {"index" :1 ,"name" :"AMD Radeon(TM) Graphics" ,"vram_gb" :0.5 ,"arch" :"unknown (PCI 164E)" ,"driver" :"32.0.1" }] 971with mock .patch .object (M ,"WIN" ,True ),mock .patch .object (S ,"gpus" ,lambda : []),mock .patch .object (S ,"amd_gpus" ,lambda : [dict (g )for g in cards ]),mock .patch .object (M ,"windows_video_controllers" ,lambda : [{"name" :"AMD Radeon RX 9070 XT" ,"driver" :"32" }]),mock .patch .object (S ,"ram_gb" ,lambda :64.0 ),mock .patch .object (S ,"page_file_gb" ,lambda :10.0 ): 972hw = s ._hardware () 973by = {g ["name" ]:g for g in hw ["gpus" ]} 974self .assertTrue (by ["AMD Radeon RX 9070 XT" ]["usable" ]) 975self .assertFalse (by ["AMD Radeon(TM) Graphics" ]["usable" ]) 976rec = s .recommend ({** hw ,"ram_gb" :64.0 }) 977self .assertEqual ((rec ["backend" ],rec ["gpu" ]["name" ]), ("hip" ,"AMD Radeon RX 9070 XT" )) 978 979@ mock . patch ( "strata_control.engine_component.status" , lambda : { "usable" : False }) 980def test_a_windows_strix_halo_reports_the_reserve_setup_writes_for_it (self ): 981"""QAGUI-STRIX 11-09 (APP-WIN item 3): the app's Load on a unified-memory chip uses the reserve setup would write (setup_config.UMA_WIN_RESERVE_MIB, G16) 982when the run config has none; the report carries it on a Windows gfx1151 only, from the same constant.""" 983from strata_control import setup_config 984s = M .Strata (HERE .parent ) 985S = s .setup_module () 986strix = [{"index" :0 ,"name" :"AMD Radeon(TM) 8060S Graphics" ,"vram_gb" :95.8 ,"arch" :"gfx1151" ,"driver" :"32.0.1" ,"uma" :True , 987"dedicated_gb" :64.0 ,"shared_gb" :31.8 }] 988common = (mock .patch .object (S ,"gpus" ,lambda : []),mock .patch .object (S ,"amd_problem" ,lambda g :None ), 989mock .patch .object (M ,"windows_video_controllers" ,lambda : [{"name" :strix [0 ]["name" ],"driver" :"32" }]), 990mock .patch .object (S ,"ram_gb" ,lambda :63.6 ),mock .patch .object (S ,"page_file_gb" ,lambda :10.0 )) 991for win ,cards ,want in ((True ,strix ,setup_config .UMA_WIN_RESERVE_MIB ), (False ,strix ,None ), 992 (True , [{** strix [0 ],"arch" :"gfx1150" }],None ), (True , [{** strix [0 ],"uma" :False }],None ), 993 (True , [{** strix [0 ],"arch" :"gfx1151:sramecc-:xnack-" }],setup_config .UMA_WIN_RESERVE_MIB )): 994with self .subTest (win = win ,arch = cards [0 ]["arch" ],uma = cards [0 ].get ("uma" )),mock .patch .object (M ,"WIN" ,win ), \ 995mock .patch .object (S ,"amd_gpus" ,lambda c = cards : [dict (g )for g in c ]), \ 996common [0 ],common [1 ],common [2 ],common [3 ],common [4 ]: 997hw = s ._hardware () 998amd = [g for g in hw ["gpus" ]if g .get ("vendor" )== "amd" ] 999self .assertEqual (amd [0 ].get ("setup_reserve_mib" ),want ) 1000self .assertEqual (setup_config .UMA_WIN_RESERVE_MIB ,700 ) 1001 1002 1003if __name__ == "__main__" : 1004unittest .main () 1005 1006 1007class RemoveMissingFilesTest (unittest .TestCase ): 1008"""Deleting a model whose plan lists files that are already gone (or inside a folder removed earlier) is a success, not 'Some files could not be removed'.""" 1009 1010def test_missing_paths_are_already_removed (self ): 1011import importlib .util ,tempfile ,threading 1012from pathlib import Path 1013spec = importlib .util .spec_from_file_location ("strata_mcp_rm" ,Path (__file__ ).with_name ("strata_mcp.py" )) 1014mod = importlib .util .module_from_spec (spec ) 1015spec .loader .exec_module (mod ) 1016with tempfile .TemporaryDirectory ()as d : 1017root = Path (d ) 1018folder = root / "Gyro-M" 1019folder .mkdir () 1020 (folder / "a.gguf" ).write_bytes (b"x" ) 1021 (folder / "b.gguf" ).write_bytes (b"y" ) 1022gone = root / "already-gone.gguf" 1023cfg = root / "model.json" 1024cfg .write_text ("{}" ) 1025plan = {"model" :"gyro-m" ,"gb" :0.1 ,"remove" : [ 1026 {"path" :str (folder )}, {"path" :str (folder / "a.gguf" )}, {"path" :str (gone )}, {"path" :str (cfg )}]} 1027 1028class S : 1029lock = threading .RLock () 1030def find_config (self ,model ):return cfg 1031def removal_plan (self ,config ):return plan 1032def install_job (self ):return None 1033def tracked_server (self ):return None 1034def model_paths (self ,c ):return ([], []) 1035def read_config (self ,c ):return {} 1036 1037result = mod .Tools (S ()).strata_remove (model = "gyro-m" ,confirm = True ) 1038self .assertEqual (result ["failed" ], [],result ) 1039self .assertFalse (folder .exists ());self .assertFalse (cfg .exists ()) 1040again = mod .Tools (S ()).strata_remove (model = "gyro-m" ,confirm = True ) 1041self .assertEqual (again ["failed" ], [],"a second delete of the same model finds nothing left and still succeeds" ) 1042 1043 1044class DiskUsageTest (unittest .TestCase ): 1045"""QA 2026-10-18 (F02): Storage showed IQ3_S as 0.0 GB while it uses 84 GB, and Gyro-S as 119 GB while it is 59 GB. The sizes come from the real 1046files: every part of a model in parts, the picture reader, the packs; a file one config names through several flags counts once; a 1047file two models share counts once in the total; a model's own figure leaves out another model's files.""" 1048 1049def setUp (self ): 1050self .tmp = tempfile .TemporaryDirectory () 1051self .addCleanup (self .tmp .cleanup ) 1052d = Path (self .tmp .name ) 1053self .root ,self .data ,self .own = d / "install" ,d / "data" ,d / "owner-folder" 1054for p in (self .root ,self .data / "models" / "gyro-Gyro-S" ,self .data / "packs" / "swift-iq2_xs" ,self .data / "mtp" / "rt" ,self .own ): 1055p .mkdir (parents = True ) 1056 (d / "settings.json" ).write_text (json .dumps ({"data_dir" :str (self .data )}),encoding = "utf-8" ) 1057env = mock .patch .dict (os .environ , {"STRATA_SETTINGS_FILE" :str (d / "settings.json" )}) 1058env .start () 1059self .addCleanup (env .stop ) 1060 1061def blob (self ,path :Path ,size :int )-> str : 1062path .write_bytes (b"x" * size ) 1063return str (path ) 1064 1065def write_config (self ,name :str ,args :list ,vision = None ): 1066cfg = {"exe" :sys .executable ,"args" :args ,"port" :8080 } 1067if vision : 1068cfg ["vision" ]= {"mmproj" :vision } 1069 (self .root / f"strata- { name } .json" ).write_text (json .dumps (cfg ),encoding = "utf-8" ) 1070 1071def test_sizes_come_from_the_files_not_from_what_may_be_deleted (self ): 1072gyro = self .blob (self .data / "models" / "gyro-Gyro-S" / "Gyro-S.gguf" ,59_000 ) 1073reader = self .blob (self .data / "models" / "mmproj.gguf" ,900 ) 1074part1 = self .blob (self .own / "Model-IQ3_S-00001-of-00002.gguf" ,30_000 ) 1075self .blob (self .own / "Model-IQ3_S-00002-of-00002.gguf" ,54_000 ) 1076# Gyro: the one file is --native, --ple-gguf, --embd-gguf and --native-dense-gguf at once 1077self .write_config ("gyro-gyro-s" , ["--native" ,gyro ,"--ple-gguf" ,gyro ,"--embd-gguf" ,gyro ,"--native-dense-gguf" ,gyro ],reader ) 1078# IQ3_S: adopted from the person's own folder, the config names the first part only 1079self .write_config ("iq3_s" , ["--native" ,part1 ],reader ) 1080s = M .Strata (self .root ) 1081use = s .disk_usage () 1082self .assertEqual (use ["models" ]["gyro-gyro-s" ]["bytes" ],59_000 ,"the Gyro file is counted once, not four times" ) 1083self .assertEqual (use ["models" ]["iq3_s" ]["bytes" ],84_000 ,"both parts of IQ3_S, although the config names the first" ) 1084self .assertEqual (use ["shared_bytes" ],900 ,"the picture reader both use is one file" ) 1085self .assertEqual (use ["total_bytes" ],59_000 + 84_000 + 900 ,"rows plus the shared files add up to the total" ) 1086self .assertEqual (use ["models" ]["iq3_s" ]["shared_bytes" ],900 ) 1087# deleting IQ3_S would remove nothing: its files are the person's own 1088by = {d ["model" ]:d for d in (s .describe_config (c ,use )for c in s .configs ())} 1089self .assertEqual (by ["iq3_s" ]["disk_bytes" ],84_000 ) 1090self .assertEqual (by ["iq3_s" ]["removable_gb" ],0.0 ) 1091self .assertEqual (by ["gyro-gyro-s" ]["disk_bytes" ],59_000 ) 1092 1093def test_a_pack_folder_and_the_shared_draft_layer_count_once (self ): 1094gguf = self .blob (self .data / "models" / "gyro-Gyro-S" / "m.gguf" ,10_000 ) 1095pack = self .data / "packs" / "swift-iq2_xs" 1096self .blob (pack / "experts.bin" ,40_000 ) 1097self .blob (pack / "index.txt" ,100 ) 1098mtp = self .data / "mtp" / "rt" 1099self .blob (mtp / "experts.bin" ,5_000 ) 1100self .write_config ("swift-iq2_xs" , ["--native" ,gguf ,"--pack" ,str (pack ),"--mtp" ,str (mtp )]) 1101link_target = self .data / "models" / "gyro-Gyro-S" / "m2.gguf" 1102try : 1103os .link (gguf ,link_target )# a hard link: the same bytes under another name 1104except OSError : 1105self .skipTest ("no hard links here" ) 1106self .write_config ("other" , ["--native" ,str (link_target ),"--mtp" ,str (mtp )]) 1107use = M .Strata (self .root ).disk_usage () 1108self .assertEqual (use ["models" ]["swift-iq2_xs" ]["bytes" ],40_100 ) 1109self .assertEqual (use ["models" ]["other" ]["bytes" ],0 ) 1110self .assertEqual (use ["shared_bytes" ],10_000 + 5_000 ,"the hard-linked GGUF and the draft layer are shared" ) 1111self .assertEqual (use ["total_bytes" ],55_100 ) 1112 1113def test_a_model_with_a_part_missing_is_not_ready (self ): 1114part1 = self .blob (self .own / "Model-00001-of-00003.gguf" ,10 ) 1115self .blob (self .own / "Model-00002-of-00003.gguf" ,10 ) 1116self .write_config ("three-parts" , ["--native" ,part1 ]) 1117s = M .Strata (self .root ) 1118desc = s .describe_config (s .configs ()[0 ]) 1119self .assertFalse (desc ["ready" ],"one part of three is on disk: not downloaded" ) 1120self .assertTrue (any (m .endswith ("Model-00003-of-00003.gguf" )for m in desc ["missing_files" ]),desc ["missing_files" ]) 1121self .blob (self .own / "Model-00003-of-00003.gguf" ,10 ) 1122desc = s .describe_config (s .configs ()[0 ]) 1123self .assertEqual ([m for m in desc ["missing_files" ]if m .endswith (".gguf" )], []) 1124 1125 1126class DraftLayerAndCancel (unittest .TestCase ): 1127"""#3257: the draft layer's download shows real progress, and a cancel ends the whole tree.""" 1128 1129def test_step_6_shows_the_draft_layer_download_added_to_the_finished_model_files (self ): 1130lines = ["=== Step 6: preparing the model for Strata ===" ," > python mtp_fetch.py fetch" , 1131" MTP draft layer: 2.00 / 5.00 GB (40%)" ] 1132with tempfile .TemporaryDirectory ()as d : 1133shard = Path (d )/ "m-00001-of-00001.gguf" 1134shard .write_bytes (b"x" * 20_000_000 ) 1135job = {"files" : [{"path" :str (shard ),"bytes" :None ,"role" :"model" }],"total_gb" :60 } 1136prog = M .combined_progress (M .install_progress (lines ),job ) 1137self .assertEqual (prog ["download" ]["file" ],"Draft layer" ) 1138self .assertEqual ([p ["kind" ]for p in prog ["parts" ]], ["model" ,"draft" ]) 1139self .assertEqual (prog ["parts" ][0 ]["state" ],"done" ) 1140self .assertAlmostEqual (prog ["parts" ][1 ]["done_gb" ],2.0 ) 1141self .assertAlmostEqual (prog ["parts" ][1 ]["total_gb" ],5.0 ) 1142self .assertGreater (prog ["download" ]["total_gb" ],5.0 ) 1143self .assertEqual (prog ["download" ]["percent" ],min (99 ,int (100 * prog ["download" ]["done_gb" ]/ prog ["download" ]["total_gb" ]))) 1144 1145def test_without_a_file_list_the_draft_layer_alone_is_shown (self ): 1146prog = M .combined_progress (M .install_progress (["=== Step 6: x ===" ," MTP draft layer: 5.00 / 5.00 GB (100%)" ]), {}) 1147self .assertEqual ([(p ["kind" ],p ["state" ])for p in prog ["parts" ]], [("draft" ,"done" )]) 1148 1149def test_other_step_6_output_still_shows_no_download (self ): 1150prog = M .combined_progress (M .install_progress (["=== Step 6: x ===" ," IQ2_XS: 0.00 / 0.00 GB (0%)" ]), {}) 1151self .assertNotIn ("download" ,prog ) 1152 1153@ unittest . skipUnless ( M . WIN , "Windows process trees" ) 1154def test_cancel_ends_a_grandchild_even_when_taskkill_does_not_reach_it (self ): 1155"""setup.py -> tools/*.py: taskkill /T walks parent ids; a snapshot taken first still finds the grandchild.""" 1156code = ("import subprocess,sys,time; c=subprocess.Popen([sys.executable,'-c','import time; time.sleep(120)']);" 1157"print(c.pid, flush=True); time.sleep(120)" ) 1158top = subprocess .Popen ([sys .executable ,"-c" ,code ],stdout = subprocess .PIPE ,text = True ) 1159grand = int (top .stdout .readline ()) 1160try : 1161ident ,gident = M .proc_identity (top .pid ),M .proc_identity (grand ) 1162self .assertTrue (ident and gident ) 1163self .assertIn ((grand ,gident ),M .proc_tree_snapshot (top .pid )) 1164real_run = subprocess .run 1165 1166def no_taskkill (cmd ,* a ,** kw ):# the case of #3257: taskkill ends the parent only 1167if cmd and cmd [0 ]== "taskkill" : 1168return real_run (["taskkill" ,"/PID" ,str (top .pid ),"/F" ],capture_output = True ) 1169return real_run (cmd ,* a ,** kw ) 1170with mock .patch .object (M .subprocess ,"run" ,no_taskkill ): 1171M .proc_kill_tree (top .pid ,ident ) 1172M .wait_gone (grand ,gident ,10 ) 1173self .assertFalse (M .proc_alive (grand ,gident ),"the grandchild kept running" ) 1174self .assertFalse (M .proc_alive (top .pid ,ident )) 1175finally : 1176for pid in (grand ,top .pid ): 1177subprocess .run (["taskkill" ,"/PID" ,str (pid ),"/T" ,"/F" ],capture_output = True ) 1178top .wait (10 )