okami.mom/strata

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

Niko1221Merge f-own-2b (cc8c29f31) into f-own-int: our own GGUF reader/writer and quantizers (gguf-py out of the pack tools)0f1e5e4cb

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