okami.mom/strata

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

Niko1221Merge f-ci-green-0215: the four red GitHub checks (cmake-cpu on MSVC, py-tools on a CRLF checkout and on macOS, the Windows snapshot time)b749503db

main
38.5 KiB689 linesraw
1"""Tests for setup on a Mac (metal/setup_mac.py and setup.py's hand-over): the Mac check, the pack recommended by
2unified memory, what a bigger choice risks, the engine arguments with the Metal defaults and the config. Runs on any
3PC: sysctl / sw_vers / xcode-select are mocked. No GPU, no network.
4
5    python -m unittest tools.test_setup_mac
6"""
7from __future__ import annotations
8
9import os
10import subprocess
11import sys
12import tempfile
13import unittest
14from pathlib import Path
15from unittest import mock
16
17ROOT = Path(__file__).resolve().parents[1]
18sys.path.insert(0, str(ROOT))
19sys.path.insert(0, str(ROOT / "metal"))
20import setup  # noqa: E402
21import setup_mac as M  # noqa: E402
22
23
24def fake_run(values: dict, clt_rc=0):
25    def run(cmd, **kw):
26        if cmd[0] == "sysctl":
27            return subprocess.CompletedProcess(cmd, 0, values.get(cmd[2], ""), "")
28        if cmd[0] == "sw_vers":
29            return subprocess.CompletedProcess(cmd, 0, values.get("macos", ""), "")
30        if cmd[0] == "xcode-select":
31            return subprocess.CompletedProcess(cmd, clt_rc, "/Library/Developer/CommandLineTools" if clt_rc == 0 else "",
32                                               "")
33        raise AssertionError(cmd)
34    return run
35
36
37M5 = {"machdep.cpu.brand_string": "Apple M5 Max", "hw.memsize": str(128 * 2 ** 30), "macos": "27.2",
38      "hw.perflevel0.physicalcpu": "12"}
39
40
41class MacCheck(unittest.TestCase):
42    def test_reads_chip_memory_macos_and_tools(self):
43        with mock.patch.object(M.platform, "machine", return_value="arm64"):
44            info = M.mac_info(fake_run(M5))
45        self.assertEqual(info["chip"], "Apple M5 Max")
46        self.assertAlmostEqual(info["ram_gb"], 128.0)
47        self.assertEqual(info["macos"], "27.2")
48        self.assertTrue(info["arm64"])
49        self.assertTrue(info["clt"])
50        self.assertEqual(M.mac_problems(info), [])
51
52    def test_an_intel_python_on_apple_silicon_is_still_an_apple_silicon_mac(self):     # #3894
53        with mock.patch.object(M.platform, "machine", return_value="x86_64"):
54            info = M.mac_info(fake_run({**M5, "machdep.cpu.brand_string": "Apple M1 Max"}))
55        self.assertTrue(info["arm64"])
56        self.assertTrue(info["rosetta_python"])
57        self.assertNotIn("Intel", " ".join(M.mac_problems(info)))
58
59    def test_intel_old_macos_and_missing_tools_are_named(self):
60        with mock.patch.object(M.platform, "machine", return_value="x86_64"):
61            info = M.mac_info(fake_run({**M5, "macos": "14.6", "machdep.cpu.brand_string": "Intel Core i9"}, clt_rc=2))
62        p = " | ".join(M.mac_problems(info))
63        self.assertIn("Apple Silicon", p)
64        self.assertIn("macOS 15", p)
65        self.assertIn("xcode-select --install", p)
66
67
68class Recommendation(unittest.TestCase):
69    def test_by_memory(self):
70        # IQ3_S and UD-Q4_K_XL are the recommended sizes; IQ3_S is the default wherever it stays resident
71        self.assertEqual(M.RECOMMENDED, ("IQ3_S", "UD-Q4_K_XL"))
72        rec, notes = M.recommend_model(128)
73        self.assertEqual(rec, "IQ3_S")
74        self.assertTrue(any("UD-Q4_K_XL" in n and "higher quality" in n for n in notes))   # named next to it
75        rec96, notes96 = M.recommend_model(96)
76        self.assertEqual(rec96, "IQ3_S")
77        self.assertFalse(notes96)                       # UD-Q4_K_XL does not fit 96 GB resident: no note
78        self.assertEqual(M.recommend_model(64)[0], "Q2_0")      # no recommended size fits: the largest that does
79        self.assertEqual(M.recommend_model(80)[0], "IQ3_XXS")
80        rec, notes = M.recommend_model(32)
81        self.assertEqual(rec, "Q2_0")
82        self.assertTrue(notes and "stream" in notes[0] and "~14 tok/s" in notes[0])
83        self.assertTrue(M.streams("Q2_0", 32) and M.streams("Q2_0", 48) and not M.streams("Q2_0", 64))
84
85    def test_a_bigger_choice_is_kept_with_a_note(self):
86        notes = M.model_note("IQ3_XXS", 64)
87        self.assertTrue(any("stream from the SSD" in n for n in notes))
88        self.assertEqual(M.model_note("Q2_0", 128), [])
89        self.assertEqual(M.model_note("IQ3_S", 128), [])
90
91    def test_context(self):
92        self.assertEqual(M.recommend_context(64), 32768)
93        self.assertEqual(M.recommend_context(128), 65536)
94
95
96class Config(unittest.TestCase):
97    def test_engine_args_carry_the_metal_defaults(self):
98        args = M.engine_args(Path("/p/packs/q2_0"), [Path("/m/a-00001.gguf"), Path("/m/a-00002.gguf")],
99                             Path("/d/mtp/rt"), 32768)
100        self.assertEqual(args[args.index("--spec") + 1], "2")
101        self.assertEqual(args[args.index("--native") + 1], str(Path("/m/a-00001.gguf")))
102        self.assertEqual(args[args.index("--ple-gguf") + 1], str(Path("/m/a-00002.gguf")))
103        self.assertEqual(args[args.index("--mtp") + 1], str(Path("/d/mtp/rt")))
104        self.assertIn("--expert-profile", args)
105        self.assertNotIn("--hc-q8", args)                         # Q8_0 HC is the engine's own default on Metal
106        st = M.engine_args(Path("/p"), [Path("/a1.gguf"), Path("/a2.gguf")], Path("/d/mtp/rt"), 32768, stream=True)
107        self.assertNotIn("--mtp", st)                             # streaming: one token per step, no draft layer
108        self.assertEqual(st[st.index("--suffix-draft") + 1], "0")
109        self.assertEqual(st[st.index("--spec") + 1], "2")
110        # a big Mac that streams (UD-Q5/Q6 on 128 GB) keeps the draft layer, with a longer window
111        big = M.engine_args(Path("/p"), [Path("/a1.gguf"), Path("/a2.gguf")], Path("/d/mtp/rt"), 65536, stream=True,
112                            ram_gb=128)
113        self.assertEqual(big[big.index("--mtp") + 1], str(Path("/d/mtp/rt")))
114        self.assertEqual(big[big.index("--spec") + 1], "3")
115        self.assertEqual(big[big.index("--suffix-draft") + 1], "0")
116        small = M.engine_args(Path("/p"), [Path("/a1.gguf"), Path("/a2.gguf")], Path("/d/mtp/rt"), 32768, stream=True,
117                              ram_gb=32)
118        self.assertNotIn("--mtp", small)
119        self.assertTrue(M.stream_mtp(False, 16) and M.stream_mtp(True, 128) and not M.stream_mtp(True, 64))
120
121    def test_iq3_s_runs_a_three_token_window_with_min_p(self):
122        # M5 Max, MTP, 5 interleaved pairs, identical tokens: --spec 3 --spec-min-p 0.5 over --spec 2: IQ3_S -0.9% / +2.5% / +16.7% / +4.9%
123        # (story / code / JSON / agent turn), Q2_0 +0.4% / +11.5% / +6.3% / +1.9%
124        shards = [Path("/m/a-00001.gguf"), Path("/m/a-00002.gguf")]
125        iq = M.engine_args(Path("/p/packs/iq3_s"), shards, Path("/d/mtp/rt"), 32768, model="IQ3_S")
126        self.assertEqual(iq[iq.index("--spec") + 1], "3")
127        self.assertEqual(iq[iq.index("--spec-min-p") + 1], "0.5")
128        self.assertIn("--mtp", iq)
129        q2 = M.engine_args(Path("/p/packs/q2_0"), shards, Path("/d/mtp/rt"), 32768, model="Q2_0")
130        self.assertEqual(q2[q2.index("--spec") + 1], "3")
131        self.assertEqual(q2[q2.index("--spec-min-p") + 1], "0.5")
132        coder = M.engine_args(Path("/p/packs/coder"), shards, Path("/d/mtp/rt"), 32768, model="Coder")   # 5 pairs: story -2.5%, code +7.1%, JSON +9.3%, agent +12.5%
133        self.assertEqual(coder[coder.index("--spec") + 1], "3")
134        self.assertEqual(coder[coder.index("--spec-min-p") + 1], "0.5")
135        other = M.engine_args(Path("/p/packs/iq3_xxs"), shards, Path("/d/mtp/rt"), 32768, model="IQ3_XXS")   # not measured: the old default
136        self.assertEqual(other[other.index("--spec") + 1], "2")
137        self.assertNotIn("--spec-min-p", other)
138        none = M.engine_args(Path("/p"), shards, Path("/d/mtp/rt"), 32768)         # no model named: the old default
139        self.assertEqual(none[none.index("--spec") + 1], "2")
140        self.assertNotIn("--spec-min-p", none)
141        # a streaming IQ3_S keeps its own rules: no draft layer on a small Mac (spec 2, nothing else), --spec 3 only on a big one
142        small = M.engine_args(Path("/p"), shards, Path("/d/mtp/rt"), 32768, stream=True, ram_gb=32, model="IQ3_S")
143        self.assertNotIn("--spec-min-p", small)
144        self.assertEqual(small[small.index("--spec") + 1], "2")
145        big = M.engine_args(Path("/p"), shards, Path("/d/mtp/rt"), 65536, stream=True, ram_gb=128, model="IQ3_S")
146        self.assertEqual(big[big.index("--spec") + 1], "3")
147        self.assertNotIn("--spec-min-p", big)
148
149    def test_fp16_decode_is_the_engines_own_default(self):
150        # STRATA_METAL_F16 for a resident IQ3_S / Q2_0 pack is decided by the engine (metal window.cpp f16_auto_for); setup writes nothing for it
151        self.assertFalse(hasattr(M._fit, "engine_env"))
152        self.assertFalse(hasattr(M._fit, "F16_MODELS"))
153
154    def test_config_is_a_model_config_with_the_metal_backend(self):
155        cfg = M.mac_config(Path("/r/build-metal/strata"), ["--pack", "x"], Path("/p"), "qwen3.8-flash-next-q2_0",
156                           "Q2_0", 8080)
157        self.assertEqual(cfg["backend"], "metal")
158        self.assertEqual(cfg["tokenizer"], str(Path("/p") / "tokenizer"))
159        self.assertTrue(cfg["exe"] and isinstance(cfg["args"], list))
160
161
162class Vision(unittest.TestCase):
163    def test_the_projector_is_pinned_and_the_encoder_builds_with_metal(self):
164        self.assertIn("mmproj-Qwen3.8-Flash-Next-BF16.gguf", M.VISION_SHA256)
165        src = (ROOT / "metal" / "setup_mac.py").read_text(encoding="utf-8")
166        self.assertIn('"-DSTRATA_VISION_CUDA=OFF"', src)
167        self.assertIn('cfg["args"] += ["--vision"]', src)
168
169
170class ExpertsFile(unittest.TestCase):
171    """The streaming Mac's <model>.experts: written only with room on the disk, else a warning and the GGUF."""
172
173    def run_it(self, free_gb, done=False):
174        import tempfile
175        sys.path.insert(0, str(ROOT / "metal" / "tools"))
176        import stream_experts
177        d = Path(tempfile.mkdtemp())
178        native = d / "m.gguf"
179        native.write_bytes(b"")
180        if done:
181            (d / "m.gguf.experts").write_bytes(b"")
182            (d / "m.gguf.experts.done").write_text("x")
183        with mock.patch.object(stream_experts, "size_bytes", return_value=40e9), \
184                mock.patch.object(M.S, "free_gb", return_value=free_gb), \
185                mock.patch.object(M.S, "run") as run, mock.patch.object(M.S, "warn") as warn, \
186                mock.patch.object(M.S, "mark") as mark, mock.patch.object(M.S, "say"), mock.patch.object(M.S, "ok"):
187            M.experts_file(native)
188        return run, warn, mark
189
190    def test_fits_needs_the_margin(self):
191        self.assertFalse(M.experts_file_fits(40, 40 + M.EXPERTS_MARGIN_GB - 0.1))
192        self.assertTrue(M.experts_file_fits(40, 40 + M.EXPERTS_MARGIN_GB))
193
194    def test_written_and_verified_with_room(self):
195        run, warn, mark = self.run_it(100)
196        self.assertIn("--verify", run.call_args[0][0])
197        self.assertTrue(str(run.call_args[0][0][1]).endswith("stream_experts.py"))
198        mark.assert_called_once()
199        warn.assert_not_called()
200
201    def test_too_little_disk_warns_and_goes_on(self):
202        run, warn, mark = self.run_it(45)
203        run.assert_not_called()
204        mark.assert_not_called()
205        self.assertIn("not written", warn.call_args[0][0])
206
207    def test_done_is_not_written_again(self):
208        run, warn, mark = self.run_it(100, done=True)
209        run.assert_not_called()
210
211
212class V31Sets(unittest.TestCase):
213    """Round 0214: Unsloth's v3.1 sets on a Mac.  One switch (mac_fit.METAL_Q5_0_DOWN) lists the sets with Q5_0 expert downs; until the Metal kernel exists they carry "missing"."""
214    NEW = ("UD-IQ1_M", "UD-Q2_0", "UD-IQ2_XS", "UD-Q2_K_XL", "UD-IQ3_XXS", "UD-Q3_K_XL", "UD-IQ4_XS-v31")
215    Q5_0 = ("UD-IQ2_XS", "UD-Q2_K_XL", "UD-Q3_K_XL", "UD-IQ4_XS-v31")
216
217    def test_entries_and_files(self):
218        for m in self.NEW:
219            d = M.MAC_MODELS[m]
220            self.assertEqual(d["family"], "unsloth")
221            self.assertEqual(d["shards"], setup.MODELS[m]["shards"])
222            self.assertAlmostEqual(d["shard1_gb"], setup.MODELS[m]["download_gb"] - 28.8, delta=0.15)     # the download less the n-gram table
223            self.assertEqual(M.model_shard_names(m), [setup.model_file(setup.FAMILIES["unsloth"], m, i) for i in range(1, d["shards"] + 1)])
224            self.assertTrue(all(M.shard_sha(n) for n in M.model_shard_names(m)), m)
225            self.assertIn(m, M.MAC_ABOUT)
226
227    def test_all_seven_are_listed_now_the_metal_kernel_exists(self):
228        from strata_control import mac_fit
229        self.assertTrue(mac_fit.METAL_Q5_0_DOWN)            # f-0214-metal: the Q5_0 down kernels
230        for m in self.NEW:
231            self.assertFalse(mac_fit.MAC_MODELS[m].get("missing"), m)
232        self.assertNotIn("does not run on this Metal engine yet", "".join(mac_fit.model_note("UD-Q3_K_XL", 128)))
233
234    def test_the_switch_lists_them_all(self):
235        from strata_control import mac_fit
236        ns = {"__name__": "mac_fit_on", "__file__": mac_fit.__file__}
237        src = Path(mac_fit.__file__).read_text(encoding="utf-8").replace("METAL_Q5_0_DOWN = True", "METAL_Q5_0_DOWN = False")
238        exec(compile(src, mac_fit.__file__, "exec"), ns)                 # the switch off: the four Q5_0-down sets are held back again
239        self.assertEqual([m for m in self.NEW if ns["MAC_MODELS"][m].get("missing")], list(self.Q5_0))
240
241
242class HandOver(unittest.TestCase):
243    def test_darwin_hands_the_run_to_setup_mac(self):
244        with mock.patch.object(setup.sys, "platform", "darwin"), \
245                mock.patch.object(setup.subprocess, "call", return_value=0) as call, \
246                mock.patch.object(setup.sys, "argv", ["setup.py", "--model", "Q2_0", "--yes"]):
247            self.assertEqual(setup.main(), 0)
248        cmd = call.call_args[0][0]
249        self.assertTrue(cmd[1].endswith(str(Path("metal") / "setup_mac.py")))
250        self.assertEqual(cmd[2:], ["--model", "Q2_0", "--yes"])
251
252    def test_other_platforms_never_reach_it(self):
253        src = (ROOT / "setup.py").read_text(encoding="utf-8")
254        self.assertIn('if sys.platform == "darwin":', src)
255        with mock.patch.object(setup, "mac_setup", side_effect=AssertionError("called")), \
256                mock.patch.object(setup.sys, "platform", "linux"), \
257                mock.patch.object(setup.sys, "argv", ["setup.py", "--inspect", "x"]), \
258                mock.patch.object(setup.subprocess, "run", return_value=subprocess.CompletedProcess([], 0)):
259            with self.assertRaises(SystemExit):
260                setup.main()
261
262    def test_setup_sh_fetches_a_pinned_python_on_macos_only(self):
263        sh = (ROOT / "setup.sh").read_text(encoding="utf-8")
264        self.assertIn('[ "$(uname -s)" = Darwin ]', sh)
265        self.assertIn("83dcb04777c798bd95f3687acf9ae84b09860272ee6bdfb05be8bcf9447f75b8", sh)
266
267
268class RepackGuard(unittest.TestCase):
269    """No engine beside a repack: the locks, and the resident rule that matches the engine's arena_budget.h."""
270
271    def test_resident_rule_matches_the_engine(self):
272        # the resident cap: Metal's working set (3/4), and on a Mac of 64 GB or more the RAM less 30%
273        self.assertAlmostEqual(M.gpu_budget_gb(128), 128 * 1.073741824 * 0.70, places=3)    # 96.2 GB, as arena_budget.h
274        self.assertAlmostEqual(M.gpu_budget_gb(96), 96 * 1.073741824 * 0.70, places=3)
275        self.assertAlmostEqual(M.gpu_budget_gb(32), 32 * 1.073741824 * 0.75, places=3)      # a small Mac: the working set
276        self.assertFalse(M.streams("UD-Q4_K_XL", 128))          # 82.6 + 8 GB: resident (measured: nothing compressed)
277        self.assertTrue(M.streams("UD-Q5_K_XL", 128))
278        self.assertTrue(M.streams("UD-Q4_K_XL", 96))
279
280    @unittest.skipIf(sys.platform == "win32", "os.kill(pid, 0) is a probe on macOS and Linux only")
281    def test_a_live_lock_is_seen_a_stale_one_is_dropped(self):
282        import os
283        import tempfile
284        with tempfile.TemporaryDirectory() as d:
285            d = Path(d)
286            self.assertEqual(M.repack_running(d), [])
287            (d / "m-metal.gguf.repack.lock").write_text(str(os.getppid()))          # a live process that is not us
288            self.assertEqual(M.repack_running(d), [os.getppid()])
289            (d / "m-metal.gguf.repack.lock").write_text("999999999")                # no such process
290            self.assertEqual(M.repack_running(d), [])
291            self.assertFalse((d / "m-metal.gguf.repack.lock").exists())             # the stale lock was removed
292            (d / M.PREPARE_LOCK).write_text(str(os.getppid()))
293            self.assertEqual(M.repack_running(d), [os.getppid()])
294            (d / M.PREPARE_LOCK).write_text(str(os.getpid()))                       # our own setup's lock does not stop us
295            self.assertEqual(M.repack_running(d), [])
296
297    @unittest.skipIf(sys.platform == "win32", "os.kill(pid, 0) is a probe on macOS and Linux only")
298    def test_start_refuses_while_a_repack_runs(self):
299        import json
300        import os
301        import tempfile
302        with tempfile.TemporaryDirectory() as d:
303            d = Path(d)
304            gguf, exe = d / "m-metal.gguf", d / "strata"
305            gguf.write_bytes(b"x")
306            exe.write_bytes(b"x")
307            cfg = d / "strata-x.json"
308            cfg.write_text(json.dumps({"exe": str(exe), "args": ["--native", str(gguf)], "port": 8080}))
309            (d / "m-metal.gguf.repack.lock").write_text(str(os.getppid()))
310            with mock.patch.object(M.subprocess, "call", side_effect=AssertionError("started")), \
311                    mock.patch.object(M.S, "fail", side_effect=SystemExit("refused")) as fail:
312                with self.assertRaises(SystemExit):
313                    M.start(cfg, None, False)
314            self.assertIn("repack is still running", fail.call_args[0][0])
315
316    def test_only_this_users_engine_stops_setup(self):
317        """On a shared Mac another user's engine is not ours to stop: pgrep is asked for this user's uid only."""
318        seen = []
319
320        def run(cmd, **kw):
321            seen.append(cmd)
322            return subprocess.CompletedProcess(cmd, 0, "4242 ", "")
323        with mock.patch.object(M.os, "getuid", return_value=501, create=True):
324            self.assertEqual(M.engine_pids(run), [4242])
325        self.assertEqual(seen, [["pgrep", "-u", "501", "-x", "strata"]])
326        self.assertEqual(M.engine_pids(lambda cmd, **kw: subprocess.CompletedProcess(cmd, 1, "", "")), [])
327
328    def test_the_repack_writes_in_bounded_pieces(self):
329        src = (ROOT / "metal" / "tools" / "metal_repack.py").read_text(encoding="utf-8")
330        self.assertIn("SYNC_EVERY = 1 << 30", src)                  # flushed every GiB
331        self.assertIn("nocache(o)", src)                            # F_NOCACHE on the output
332        self.assertIn("buffering=0", src)                           # write() is a write
333        self.assertNotIn("mmap", src)                               # no dirty mapping of the output
334
335
336M4 = {"machdep.cpu.brand_string": "Apple M4", "hw.memsize": str(32 * 2 ** 30), "macos": "27.2", "hw.perflevel0.physicalcpu": "4"}
337
338
339class ControlMode(unittest.TestCase):
340    """The app on a Mac (STRATA_CONTROL_INSTALL=1): model files and a run config naming the engine component. No source build, no
341    metal/setup_mac.py, no Command Line Tools; the Mac rules are strata_control/mac_fit.py's, the module setup_mac.py uses too."""
342
343    def setUp(self):
344        self.tmp = tempfile.TemporaryDirectory()
345        self.addCleanup(self.tmp.cleanup)
346        self.home = Path(self.tmp.name).resolve() / "install"
347        self.data = Path(self.tmp.name).resolve() / "data"
348        self.models = Path(self.tmp.name).resolve() / "own"
349        self.home.mkdir()
350        self.models.mkdir()
351        fam = setup.FAMILIES["qwen"]
352        self.files = []
353        for i in (1, 2):
354            f = self.models / setup.model_file(fam, "Q2_0", i)
355            f.write_bytes(b"x")
356            f.with_name(f.name + ".done").write_text("whole")
357            self.files.append(f)
358
359    def run_setup(self, hw=M4, argv=("--yes", "--no-start", "--family", "qwen", "--model", "Q2_0", "--context", "8192"), clt_rc=0, tool=None, free=500.0):
360        from strata_control import engine_component, mac_fit
361        ran = []
362
363        def fake_tool(cmd, **kw):
364            ran.append(cmd)
365            pack = Path(cmd[cmd.index("--out") + 1])
366            (pack / "tokenizer").mkdir(parents=True, exist_ok=True)
367            (pack / "native_experts.txt").write_text("x")
368            (pack / "tokenizer" / "vocab.json").write_text("{}")
369        patches = [
370            mock.patch.object(setup, "CONTROL", True), mock.patch.object(setup, "_CONTROL_HOME", self.home),
371            mock.patch.object(setup.sys, "platform", "darwin"),
372            mock.patch.object(setup.sys, "argv", ["setup.py", *argv, "--data-dir", str(self.data), "--gguf-dir", str(self.models)]),
373            mock.patch.object(mac_fit, "mac_info", lambda run=None, _real=mac_fit.mac_info: _real(fake_run(hw, clt_rc))),
374            mock.patch.object(setup, "load_settings", lambda: {}), mock.patch.object(setup, "save_settings", lambda s: None),
375            mock.patch.object(setup, "get_llama_cpp", lambda: Path(self.tmp.name) / "llama"),
376            mock.patch.object(setup, "whole_shard", lambda s: True), mock.patch.object(setup, "check_shards", lambda s: None),
377            mock.patch.object(setup, "run", tool or fake_tool), mock.patch.object(setup, "free_gb", lambda p: free),
378            mock.patch.object(setup, "say", lambda *a, **k: self.said.append(" ".join(str(x) for x in a))),
379            mock.patch.object(setup, "ok", lambda *a, **k: None),
380            mock.patch.object(setup, "step", lambda *a, **k: None),
381            mock.patch.object(setup, "warn", lambda *a, **k: self.warnings.append(" ".join(str(x) for x in a))),
382            mock.patch.object(mac_fit.platform, "machine", return_value="arm64"),
383            mock.patch.object(engine_component, "resolve", side_effect=engine_component.EngineMissing("no package here", None)),
384            mock.patch.object(setup, "mac_setup", side_effect=AssertionError("setup_mac.py must not run in Control mode")),
385            mock.patch.object(setup.subprocess, "call", side_effect=AssertionError("nothing is started or built")),
386        ]
387        self.warnings, self.said = [], []
388        for p in patches:
389            p.start()
390            self.addCleanup(p.stop)
391        rc = setup.main()
392        return rc, ran
393
394    def config(self, tag="q2_0"):
395        import json
396        return json.loads((self.home / f"strata-{tag}.json").read_text(encoding="utf-8"))
397
398    def test_the_install_writes_a_run_config_for_the_engine_component(self):
399        rc, ran = self.run_setup()
400        self.assertEqual(rc, 0)
401        cfg = self.config()
402        self.assertEqual(cfg["exe"], "component:strata-engine")
403        self.assertEqual(cfg["backend"], "metal")
404        args = cfg["args"]
405        # a 32 GB Mac streams Q2_0's experts from the SSD: one token per step, no draft layer, the GGUF mapped in place
406        self.assertEqual(args[args.index("--native") + 1], str(self.files[0]))
407        self.assertEqual(args[args.index("--ple-gguf") + 1], str(self.files[1]))
408        self.assertIn("--mmap-experts", args)
409        self.assertNotIn("--mtp", args)
410        self.assertEqual(args[args.index("--suffix-draft") + 1], "0")
411        self.assertEqual(args[args.index("--max-context") + 1], "8192")
412        self.assertEqual(cfg["env"], {"STRATA_METAL_STREAM": "1"})
413        self.assertEqual(cfg["tokenizer"], str(self.data / "packs" / "q2_0" / "tokenizer"))
414        self.assertEqual(len(ran), 1, "only the pack is made (tools/iq_pack.py): no draft layer, no build")
415        self.assertTrue(ran[0][1].endswith("iq_pack.py"))
416        self.assertFalse((ROOT / "build-metal").exists() and any((ROOT / "build-metal").glob("*.stamp")))
417
418    def test_a_model_without_a_draft_layer_is_said_on_a_streaming_mac_too(self):
419        # a feed model whose entry says "drafter: none" (mac_fit's no_mtp) on a Mac that streams (no draft layer there anyway): the model
420        # list's line is said as on Windows and Linux (tools/feed_model_install_gate.py; GitHub's macOS runner did not get it)
421        from strata_control import mac_fit
422        with mock.patch.dict(mac_fit.MAC_MODELS["Q2_0"], {"no_mtp": True}):
423            rc, _ = self.run_setup()
424        self.assertEqual(rc, 0)
425        self.assertIn("  The model list says this model has no draft layer (MTP), so none is fetched or used.", self.said)
426        self.assertNotIn("--mtp", self.config()["args"])
427        rc, _ = self.run_setup()                                  # the Flash-Next size itself says nothing of the kind
428        self.assertFalse([s for s in self.said if "model list says" in s])
429
430    def test_a_big_mac_keeps_the_pack_in_memory_and_adds_the_draft_layer(self):
431        rc, ran = self.run_setup(hw=M5, argv=("--yes", "--no-start", "--model", "IQ3_XXS"))
432        self.assertEqual(rc, 0)
433        cfg = self.config("iq3_xxs")
434        self.assertIn("--mtp", cfg["args"])
435        self.assertEqual(cfg["env"], {"STRATA_METAL_STREAM": "0"})
436        self.assertEqual(cfg["args"][cfg["args"].index("--max-context") + 1], "65536")      # the default context by memory
437
438    def test_no_command_line_tools_needed_and_ud_iq1_s_is_not_offered(self):
439        rc, _ = self.run_setup(clt_rc=2)
440        self.assertEqual(rc, 0)
441        # UD-IQ1_S: never offered.  A name the built-in tables do not know is looked up in the signed feed first (a feed model): no feed here
442        with self.assertRaises(SystemExit), mock.patch.object(setup, "feed_models_setup", lambda *a, **k: None):
443            self.run_setup(argv=("--yes", "--no-start", "--model", "UD-IQ1_S"))
444
445    def test_gyro_is_offered_on_a_mac_as_one_file_with_a_compat_bf16_pack(self):
446        fam = setup.FAMILIES["gyro"]
447        g = self.models / setup.model_file(fam, "Gyro-S", 1)
448        g.write_bytes(b"x")
449        g.with_name(g.name + ".done").write_text("whole")
450        rc, ran = self.run_setup(argv=("--yes", "--no-start", "--family", "gyro", "--model", "Gyro-S", "--context", "8192"))
451        self.assertEqual(rc, 0)
452        cfg = self.config("gyro-gyro-s")
453        args = cfg["args"]
454        self.assertEqual(args[args.index("--native") + 1], str(g), "the one file is the model")
455        self.assertEqual(args[args.index("--ple-gguf") + 1], str(g), "... and holds its n-gram table")
456        self.assertEqual(cfg["backend"], "metal")
457        self.assertEqual(cfg["env"], {"STRATA_METAL_STREAM": "1"}, "29.7 GB of weights stream on a 32 GB Mac")
458        self.assertNotIn("--mtp", args)
459        self.assertTrue(ran[0][1].endswith("iq_pack.py"))
460        self.assertIn("--compat-bf16", ran[0], "Gyro's pack converts the small Q6_K / Q5_K tensors (docs/GYRO.md)")
461        self.assertEqual(cfg["tokenizer"], str(self.data / "packs" / "gyro-gyro-s" / "tokenizer"))
462
463    def test_gyro_m_on_a_small_mac_is_a_warning_not_a_refusal(self):
464        fam = setup.FAMILIES["gyro"]
465        g = self.models / setup.model_file(fam, "Gyro-M", 1)
466        g.write_bytes(b"x")
467        g.with_name(g.name + ".done").write_text("whole")
468        rc, _ = self.run_setup(argv=("--yes", "--no-start", "--family", "gyro", "--model", "Gyro-M", "--context", "8192"))
469        self.assertEqual(rc, 0)
470        said = " ".join(self.warnings)
471        self.assertIn("Gyro-M", said)
472        self.assertIn("stream from the SSD", said)
473        self.assertIn("not been measured on a Mac", said)
474
475    def test_other_platforms_and_the_terminal_still_use_their_own_setup(self):
476        src = (ROOT / "setup.py").read_text(encoding="utf-8")
477        self.assertIn('if sys.platform == "darwin" and not CONTROL:', src)
478        self.assertIn('if sys.platform == "darwin" and CONTROL:', src)
479
480
481class MacAppUnsloth(unittest.TestCase):
482    """Round 0214: the Mac app installs Unsloth's sets as the Terminal's setup_mac does: the shards -> ONE GGUF for the GPU (metal_repack.py --verify, the n-gram table
483    left out), the pack from that file, --native the repacked file, --ple-gguf the table's shard, --mmap-experts.  Header-only fixtures (tests/fixtures/unsloth_v31): no
484    Mac, no weights; the repack and the pack tools are recorded, not run."""
485    setUp = ControlMode.setUp
486    run_setup = ControlMode.run_setup
487    config = ControlMode.config
488    NEW = ("UD-IQ1_M", "UD-Q2_0", "UD-IQ2_XS", "UD-Q2_K_XL", "UD-IQ3_XXS", "UD-Q3_K_XL", "UD-IQ4_XS-v31")
489
490    def shards(self, model):
491        sys.path.insert(0, str(ROOT / "tools"))
492        import unsloth_v31_fixture as FX
493        doc = FX.load()
494        hub = "UD-IQ4_XS" if model == "UD-IQ4_XS-v31" else model
495        for old in self.models.glob("*"):
496            old.unlink()
497        out = []
498        for i, s in enumerate(doc["sets"][hub]["shards"]):
499            h = s["header"] or {"split": [0, len(doc["sets"][hub]["shards"]), 1224], "tensors": []}
500            p = FX.materialize({"header": h}, self.models / s["name"], first=(i == 0))
501            p.with_name(p.name + ".done").write_text("whole")
502            out.append(p)
503        return out
504
505    def tool(self, ran):
506        def fake(cmd, **kw):
507            ran.append([str(x) for x in cmd])
508            if cmd[1].endswith("metal_repack.py"):
509                Path(cmd[cmd.index("--out") + 1]).write_bytes(b"x")
510            else:
511                pack = Path(cmd[cmd.index("--out") + 1])
512                (pack / "tokenizer").mkdir(parents=True, exist_ok=True)
513                (pack / "native_experts.txt").write_text("x")
514                (pack / "tokenizer" / "vocab.json").write_text("{}")
515        return fake
516
517    def install(self, model, hw=M5, **kw):
518        ran = []
519        engines = kw.pop("engines", [])
520        with mock.patch.object(setup, "mac_engine_pids", lambda: engines):
521            rc, _ = self.run_setup(hw=hw, argv=("--yes", "--no-start", "--family", "unsloth", "--model", model, "--context", "8192", "--mtp", "off"),
522                                   tool=self.tool(ran), **kw)
523        return rc, ran
524
525    def test_the_repack_the_pack_and_the_config(self):
526        for model in self.NEW:
527            with self.subTest(model=model):
528                files = self.shards(model)
529                shutil_native = self.data / "metal" / f"unsloth-{model.lower()}-metal.gguf"
530                if shutil_native.exists():
531                    shutil_native.unlink()
532                    shutil_native.with_name(shutil_native.name + ".done").unlink(missing_ok=True)
533                rc, ran = self.install(model)
534                self.assertEqual(rc, 0)
535                self.assertEqual(len(ran), 2, ran)
536                repack, pack = ran
537                self.assertTrue(repack[1].endswith("metal_repack.py"))
538                self.assertEqual(repack[repack.index("--shard1") + 1], str(files[0]))
539                self.assertEqual(repack[repack.index("--out") + 1], str(shutil_native))
540                self.assertIn("--verify", repack)
541                self.assertTrue(pack[1].endswith("iq_pack.py"))
542                self.assertEqual(pack[pack.index("--gguf") + 1], str(shutil_native))        # the pack is read from the repacked file
543                self.assertIn("--compat-bf16", pack)
544                cfg = self.config("unsloth-" + model.lower())
545                a = cfg["args"]
546                self.assertEqual(cfg["exe"], "component:strata-engine")
547                self.assertEqual(a[a.index("--native") + 1], str(shutil_native))
548                self.assertEqual(a[a.index("--native-dense-gguf") + 1], str(shutil_native))
549                self.assertEqual(a[a.index("--ple-gguf") + 1], str(files[-1]))               # the n-gram table: the LAST shard of these sets
550                self.assertIn("--mmap-experts", a)
551                self.assertEqual(cfg["env"]["STRATA_METAL_STREAM"], "1" if M.streams(model, 128.0) else "0")
552                self.assertEqual(cfg["tokenizer"], str(self.data / "packs" / ("unsloth-" + model.lower()) / "tokenizer"))
553                self.assertEqual(cfg["model_name"], "qwen3.8-flash-next-unsloth-" + model.lower())
554                self.assertFalse((shutil_native.parent / ".preparing.lock").exists(), "the prepare lock is gone")
555
556    def test_an_already_repacked_set_is_not_repacked_again(self):
557        model = "UD-IQ1_M"
558        self.shards(model)
559        native = self.data / "metal" / "unsloth-ud-iq1_m-metal.gguf"
560        native.parent.mkdir(parents=True)
561        native.write_bytes(b"x")
562        setup.mark(native)
563        rc, ran = self.install(model)
564        self.assertEqual(rc, 0)
565        self.assertEqual([str(r[1]).replace("\\", "/").rsplit("/", 1)[-1] for r in ran], ["iq_pack.py"])      # (the path is C:\...\iq_pack.py on Windows)
566
567    def test_a_running_engine_stops_the_repack_before_anything_is_written(self):
568        self.shards("UD-IQ1_M")
569        with self.assertRaises(SystemExit):
570            self.install("UD-IQ1_M", engines=[4242])
571        self.assertFalse((self.data / "metal").exists() and any((self.data / "metal").iterdir()))
572
573    def test_the_apps_hint_for_a_running_engine(self):
574        self.shards("UD-IQ1_M")
575        said = []
576
577        def fail(msg, hint=None):
578            said.append((msg, hint))
579            raise SystemExit(1)
580        with mock.patch.object(setup, "fail", fail):
581            with self.assertRaises(SystemExit):
582                self.install("UD-IQ1_M", engines=[4242])
583        self.assertEqual(said[0][0], "a Strata engine is running (pid 4242): preparing a model beside it can freeze this Mac")
584        self.assertEqual(said[0][1], "stop the model in Strata (unload it), then install again")
585
586    def test_the_disk_check_counts_the_repacked_file(self):
587        self.shards("UD-IQ1_M")
588        self.install("UD-IQ1_M", free=30.0)
589        said = [w for w in self.warnings if "are needed on the disk" in w]
590        self.assertEqual(len(said), 1, self.warnings)
591        self.assertIn("about 45 GB", said[0])          # nothing to download (the files are here), the 39.2 GB repacked file and 6 GB to work in
592
593    def test_a_set_the_engine_cannot_run_is_not_offered(self):
594        from strata_control import mac_fit
595        self.shards("UD-Q3_K_XL")
596        with mock.patch.dict(mac_fit.MAC_MODELS, {"UD-Q3_K_XL": {**mac_fit.MAC_MODELS["UD-Q3_K_XL"], "missing": "the Q5_0 expert kernels"}}):
597            with self.assertRaises(SystemExit):
598                self.install("UD-Q3_K_XL")
599
600    def test_the_bundle_carries_the_repack_tools(self):
601        sys.path.insert(0, str(ROOT / "packaging"))
602        import package_terminal as pt
603        self.assertEqual(pt.INSTALLER_METAL_TOOLS, ("metal_repack", "stream_experts"))
604        for n in pt.INSTALLER_METAL_TOOLS:
605            self.assertTrue((ROOT / "metal" / "tools" / f"{n}.py").is_file())
606        with tempfile.TemporaryDirectory() as t:
607            out = pt.add_installer(Path(t))
608            self.assertIn("metal/tools/metal_repack.py", out["files"])
609            self.assertTrue((Path(t) / "metal" / "tools" / "stream_experts.py").is_file())
610
611
612class UpdateFlow(unittest.TestCase):
613    """update.sh asks the same questions as a setup run but does not download model files: a model chosen there must
614    be named, not dropped in silence (an M1 Max picked IQ3_S in update.sh and got no model and no message)."""
615
616    def setUp(self):
617        self.tmp = tempfile.TemporaryDirectory()
618        self.addCleanup(self.tmp.cleanup)
619        self.data = Path(self.tmp.name).resolve() / "data"
620        self.models = Path(self.tmp.name).resolve() / "own"
621        self.data.mkdir()
622        self.models.mkdir()
623        self.said, self.warned = [], []
624
625    def run_update(self, argv=("--update", "--model", "IQ3_S", "--vision", "no", "--yes")):
626        with mock.patch.object(M, "mac_configs", lambda: []), \
627                mock.patch.object(M.S, "data_folder_for", lambda a: (self.data, [])), \
628                mock.patch.object(M, "mac_info", lambda run=None: {"chip": "Apple M1 Max", "ram_gb": 32.0,
629                                                                   "macos": "26.6.2", "arm64": True, "clt": True}), \
630                mock.patch.object(M, "mac_problems", lambda info: []), \
631                mock.patch.object(M.S, "free_gb", lambda p: 200.0), \
632                mock.patch.object(M.S, "step", lambda *a, **k: None), \
633                mock.patch.object(M.S, "say", lambda *a, **k: self.said.append(" ".join(str(x) for x in a))), \
634                mock.patch.object(M.S, "ok", lambda *a, **k: None), \
635                mock.patch.object(M.S, "warn", lambda *a, **k: self.warned.append(" ".join(str(x) for x in a))), \
636                mock.patch.object(M.S, "pip_install", lambda *a, **k: None), \
637                mock.patch.object(M.S, "get_llama_cpp", lambda: self.data / "llama"), \
638                mock.patch.object(M, "build_engine", lambda llama, jobs=None: self.data / "strata"), \
639                mock.patch.object(M.S, "download", side_effect=AssertionError("an update must not download")):
640            return M.main([*argv, "--data-dir", str(self.data), "--gguf-dir", str(self.models)])
641
642    def test_a_model_chosen_in_an_update_is_named_not_dropped(self):
643        self.assertEqual(self.run_update(), 0)
644        self.assertIn("IQ3_S is not installed here", " ".join(self.warned))
645        self.assertIn("does not download model files", " ".join(self.warned))
646        self.assertIn("./setup.sh --setup", " ".join(self.said))
647
648    def test_an_installed_model_keeps_the_update_quiet(self):
649        for n in M.model_shard_names("IQ3_S"):
650            f = self.models / n
651            f.write_bytes(b"x")
652            f.with_name(f.name + ".done").write_text("whole")
653        tag = M.S.FAMILIES["qwen"]["tag"] + "IQ3_S"
654        pack = self.data / "packs" / tag.lower()
655        (pack / "tokenizer").mkdir(parents=True)
656        (pack / "native_experts.txt").write_text("x")
657        (pack / "tokenizer" / "vocab.json").write_text("{}")
658        self.assertEqual(self.run_update(), 0)
659        self.assertFalse([w for w in self.warned if "not installed here" in w], self.warned)
660
661
662class Source(unittest.TestCase):
663    """setup.py hands a Mac over before its own parser runs, so the Mac parser has to know --source:
664    source_hint() recommends it on every platform (#2363)."""
665
666    def test_the_source_flag_reaches_strata_source(self):
667        env = mock.patch.dict(os.environ, {}, clear=False)
668        env.start()
669        self.addCleanup(env.stop)
670        os.environ.pop("STRATA_SOURCE", None)
671        warnings = []
672        # setup.data_folder() is mocked: the real one moves the model files of this checkout and of the data folder in
673        # the user's settings.json into --data-dir, and saves that dir as the new data folder; with a temp dir that
674        # deletes the models on exit and leaves settings.json pointing at a deleted directory
675        with tempfile.TemporaryDirectory() as tmp, \
676                mock.patch.object(setup, "data_folder", lambda requested, *a, **k: (Path(tmp), [])), \
677                mock.patch("subprocess.run", fake_run(M5)), \
678                mock.patch.object(setup, "warn", lambda *a, **k: warnings.append(" ".join(str(x) for x in a))), \
679                mock.patch.object(setup, "say", lambda *a, **k: None), \
680                mock.patch.object(setup, "ok", lambda *a, **k: None), \
681                mock.patch.object(setup, "step", lambda *a, **k: None):
682            M.main(["--source", "modelscope", "--yes", "--check", "--data-dir", tmp])
683        self.assertEqual(os.environ.get("STRATA_SOURCE"), "modelscope")
684        self.assertFalse([w for w in warnings if "--source" in w],
685                         f"--source was not used: {warnings}")
686
687
688if __name__ == "__main__":
689    unittest.main()