okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221app: Drafting Off fetches no draft layer; the offline note only when no drafter runsb2d08647c

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