okami.mom/strata

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

Niko1221Drafting Off in the app: a model saved with Off loads after a restart, and the Models screen shows the saved choice (0.2.15 release test)c77572806

main
25.9 KiB505 linesraw
1"""Small fixes from the 0.2.2 issue sweep, one test class per issue number."""
2
3from __future__ import annotations
4
5import json
6import os
7import sys
8import tempfile
9import unittest
10from pathlib import Path
11
12sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
13
14
15class Issue3298MtpDepth(unittest.TestCase):
16    """Qwen3.6 passes `--mtp 2` (a draft depth); it is not a folder."""
17
18    def setUp(self):
19        self.tmp = tempfile.TemporaryDirectory()
20        self.addCleanup(self.tmp.cleanup)
21        self.root = Path(self.tmp.name)
22
23    def test_doctor_does_not_look_for_a_folder_named_2(self):
24        from strata_control import doctor
25        engine = self.root / "engine"
26        engine.write_text("x", encoding="utf-8")
27        engine.chmod(0o700)
28        tok = self.root / "tok"
29        tok.mkdir()
30        for n in ("vocab.json", "merges.txt", "token_type.json"):
31            (tok / n).write_text("{}", encoding="utf-8")
32        model = self.root / "m.gguf"
33        model.write_bytes(b"x")
34        cfg = self.root / "run.json"
35        cfg.write_text(json.dumps({"exe": str(engine), "args": ["--native", str(model), "--mtp", "2", "--vision"],
36                                   "cwd": str(self.root), "tokenizer": str(tok), "model_name": "q36", "port": 8095}),
37                       encoding="utf-8")
38        report = doctor.inspect(cfg)
39        self.assertNotIn("mtp", [c["name"] for c in report["components"]])
40        self.assertEqual([c["name"] for c in report["components"] if c["status"] not in ("ok",)
41                          and c.get("required") and c["name"] in ("native", "mtp", "pack")], [])
42
43    def test_doctor_still_checks_an_mtp_folder(self):
44        from strata_control import doctor
45        engine = self.root / "engine"
46        engine.write_text("x", encoding="utf-8")
47        engine.chmod(0o700)
48        tok = self.root / "tok"
49        tok.mkdir()
50        for n in ("vocab.json", "merges.txt", "token_type.json"):
51            (tok / n).write_text("{}", encoding="utf-8")
52        cfg = self.root / "run.json"
53        cfg.write_text(json.dumps({"exe": str(engine), "args": ["--mtp", str(self.root / "gone")],
54                                   "cwd": str(self.root), "tokenizer": str(tok), "model_name": "x", "port": 8095}),
55                       encoding="utf-8")
56        report = doctor.inspect(cfg)
57        mtp = [c for c in report["components"] if c["name"] == "mtp"]
58        self.assertEqual(len(mtp), 1)
59        self.assertEqual(mtp[0]["status"], "missing")
60
61    def test_launch_files_present_ignores_a_depth_number(self):
62        from strata_cli.launch.runner import files_present
63        model = self.root / "m.gguf"
64        model.write_bytes(b"x")
65        self.assertEqual(files_present({"args": ["--native", str(model), "--mtp", "2"]}), [])
66        self.assertEqual(files_present({"args": ["--mtp", str(self.root / "gone")]}), [str(self.root / "gone")])
67
68
69class Issue3403MacBuildTools(unittest.TestCase):
70    """The Mac setup compiles without setup.cmake_build(), so cmake and ninja must be installed for it too."""
71
72    def test_missing_build_tools_are_installed_before_the_mac_compile(self):
73        from unittest import mock
74        import setup
75        sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "metal"))
76        import setup_mac as M
77        installed = {"cmake": None, "ninja": None}
78
79        def find(name):
80            return installed[name]
81
82        def pip(packages, what):
83            self.assertTrue(all(p.split("==")[0] in ("cmake", "ninja") for p in packages), packages)
84            for p in packages:
85                installed[p.split("==")[0]] = "/venv/bin/" + p.split("==")[0]
86
87        with mock.patch.object(setup, "find_tool", side_effect=find), mock.patch.object(setup, "pip_install", side_effect=pip) as pi,                 mock.patch.object(setup, "_tool_version", return_value=(True, (3, 31, 0))):
88            self.assertEqual(setup.ensure_build_tools(), ("/venv/bin/cmake", "/venv/bin/ninja"))
89            self.assertEqual(pi.call_count, 1)
90            setup.ensure_build_tools()                       # present now: nothing more is installed
91            self.assertEqual(pi.call_count, 1)
92
93    def test_both_mac_builds_ask_for_the_tools_first(self):
94        import inspect
95        sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "metal"))
96        import setup_mac as M
97        for fn in (M.build_engine, M.build_vision):
98            self.assertIn("S.ensure_build_tools()", inspect.getsource(fn), fn.__name__)
99
100
101@unittest.skipUnless(sys.platform == "win32", "ACLs are Windows only")
102class WindowsRuntimeFolderRefused(unittest.TestCase):
103    """The owner's fresh Windows PC: `strata launch` stopped with "runtime directory must be owner-only" on a folder that was already
104    there with another account in its ACL.  Fake SDDL strings for each way an ACL can look."""
105
106    def setUp(self):
107        from unittest import mock
108        from strata_control import private_files as pf
109        self.pf, self.mock = pf, mock
110        self.me = "S-1-5-21-1-2-3-1001"
111        patch = mock.patch.object(pf, "current_user_sid", return_value=self.me)
112        patch.start()
113        self.addCleanup(patch.stop)
114
115    def offenders(self, sddl):
116        return self.pf.unshared_offenders(sddl)
117
118    def test_the_usual_acls_are_fine(self):
119        for sddl in ("D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)",
120                     "D:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;S-1-5-21-1-2-3-1001)",
121                     "D:PAI(A;OICI;FA;;;LA)(A;OICI;FA;;;SY)",               # the built-in Administrator's alias
122                     "D:P(A;OICI;FA;;;S-1-5-18)(A;OICI;FA;;;S-1-5-32-544)(A;OICIIO;GA;;;CO)(A;OICI;FA;;;OW)"):
123            self.assertEqual(self.offenders(sddl), [], sddl)
124
125    def test_another_account_is_named(self):
126        self.assertEqual(self.offenders("D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)(A;OICI;FR;;;BU)"), ["BU"])
127        self.assertEqual(self.offenders("D:PAI(A;;FA;;;WD)(A;;FA;;;AU)"), ["WD", "AU"])
128        self.assertEqual(self.offenders("D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1002)"), ["S-1-5-21-1-2-3-1002"])
129
130    def test_an_inherit_only_entry_is_not_for_the_folder_itself(self):
131        self.assertEqual(self.offenders("D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)(A;OICIIO;FR;;;BU)(A;CIIO;GR;;;WD)"), [])
132        # the same entry without the IO flag does apply
133        self.assertEqual(self.offenders("D:PAI(A;OICI;FR;;;BU)"), ["BU"])
134
135    def test_deny_entries_do_not_make_it_reachable(self):
136        self.assertEqual(self.offenders("D:PAI(D;;FA;;;BU)(A;OICI;FA;;;S-1-5-21-1-2-3-1001)"), [])
137
138    def test_plain_names(self):
139        self.assertEqual(self.pf.account_name("BU"), "Users")
140        self.assertEqual(self.pf.account_name("WD"), "Everyone")
141        self.assertEqual(self.pf.account_name("S-1-5-32-545"), "Users")
142
143    def test_runtime_dir_repairs_a_folder_that_names_other_accounts(self):
144        from strata_control import runtime
145        pf = self.pf
146        with tempfile.TemporaryDirectory() as tmp:
147            base = Path(tmp) / "runtime"
148            base.mkdir()
149            state = {"fixed": False}
150
151            def sddl(_path):
152                return "D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)" if state["fixed"] else \
153                    "D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)(A;OICI;0x1200a9;;;BU)"
154
155            def restrict(path, directory=None):
156                state["fixed"] = True
157
158            env = {"STRATA_RUNTIME_DIR": str(base)}
159            with self.mock.patch.dict(os.environ, env), self.mock.patch.object(pf, "dacl_sddl", side_effect=sddl), \
160                    self.mock.patch.object(pf, "restrict_to_current_user", side_effect=restrict) as r, \
161                    self.mock.patch.object(pf, "private_mkdir"), self.mock.patch.object(runtime, "_private_mkdir"):
162                self.assertEqual(runtime.runtime_dir(), base)
163                self.assertEqual(r.call_count, 1)
164
165    def test_runtime_dir_still_refuses_and_says_who_when_the_repair_fails(self):
166        from strata_control import profiles, runtime
167        pf = self.pf
168        with tempfile.TemporaryDirectory() as tmp:
169            base = Path(tmp) / "runtime"
170            base.mkdir()
171            with self.mock.patch.dict(os.environ, {"STRATA_RUNTIME_DIR": str(base)}), \
172                    self.mock.patch.object(pf, "dacl_sddl", return_value="D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)(A;OICI;FR;;;BU)"), \
173                    self.mock.patch.object(pf, "restrict_to_current_user", side_effect=OSError("denied")), \
174                    self.mock.patch.object(runtime, "_private_mkdir"):
175                with self.assertRaises(profiles.ProfileError) as cm:
176                    runtime.runtime_dir()
177            self.assertIn("Users", str(cm.exception))
178            self.assertIn(str(base), str(cm.exception))
179            self.assertIn("Properties", str(cm.exception))
180
181
182@unittest.skipUnless(sys.platform == "win32", "ACLs are Windows only")
183class WindowsRuntimeFolderMoreCases(unittest.TestCase):
184    """The cases beyond the first repair (audit-refusals-022.md item 5): a data drive's inherited Users entries, an ACL that cannot be
185    read, a folder made by an elevated run, a drive without permissions, and a message in plain words."""
186
187    ME = "S-1-5-21-1-2-3-1001"
188
189    def run_dir(self, *, sddl, restrict=None, repair=None, acls=True):
190        from unittest import mock
191        from strata_control import private_files as pf, runtime
192        with tempfile.TemporaryDirectory() as tmp:
193            base = Path(tmp) / "runtime"
194            base.mkdir()
195            calls = {"restrict": 0, "repair": 0}
196
197            def r(path, directory=None):
198                calls["restrict"] += 1
199                if restrict:
200                    return restrict(calls)
201            def rp(path, tree=True):
202                calls["repair"] += 1
203                return repair(calls) if repair else False
204            with mock.patch.dict(os.environ, {"STRATA_RUNTIME_DIR": str(base)}), \
205                    mock.patch.object(pf, "current_user_sid", return_value=self.ME), \
206                    mock.patch.object(pf, "dacl_sddl", side_effect=sddl), \
207                    mock.patch.object(pf, "restrict_to_current_user", side_effect=r), \
208                    mock.patch.object(pf, "repair_access", side_effect=rp), \
209                    mock.patch.object(pf, "volume_has_acls", return_value=acls), \
210                    mock.patch.object(runtime, "_private_mkdir"), mock.patch.object(runtime, "_NO_ACL_WARNED", set()), \
211                    mock.patch("sys.stderr", new_callable=lambda: __import__("io").StringIO()) as err:
212                try:
213                    return runtime.runtime_dir(), calls, None, err.getvalue()
214                except Exception as exc:     # noqa: BLE001 - the test looks at the ProfileError text
215                    return None, calls, exc, err.getvalue()
216
217    def test_a_data_drive_folder_with_users_and_authenticated_users_is_repaired_once(self):
218        state = {"fixed": False}
219        def sddl(_):
220            return f"D:PAI(A;OICI;FA;;;{self.ME})" if state["fixed"] else \
221                f"D:PAI(A;OICI;FA;;;{self.ME})(A;OICI;0x1301bf;;;AU)(A;OICI;0x1200a9;;;BU)"
222        base, calls, exc, _ = self.run_dir(sddl=sddl, restrict=lambda c: state.update(fixed=True))
223        self.assertIsNone(exc)
224        self.assertEqual(calls["restrict"], 1)
225
226    def test_an_acl_that_cannot_be_read_is_repaired_then_refused_in_plain_words(self):
227        def sddl(_):
228            raise OSError("access denied")
229        base, calls, exc, _ = self.run_dir(sddl=sddl)
230        self.assertIsNotNone(exc)
231        self.assertEqual((calls["restrict"], calls["repair"]), (1, 1))      # tried both, once each
232        self.assertIn("cannot read the permissions", str(exc))
233        self.assertNotIn("0700", str(exc))
234
235    def test_a_folder_made_by_an_elevated_run_gets_ownership_taken_back(self):
236        state = {"fixed": False}
237        def sddl(_):
238            if not state["fixed"]:
239                raise OSError("access denied")
240            return f"D:PAI(A;OICI;FA;;;{self.ME})"
241        def restrict(calls):
242            raise PermissionError("denied")
243        base, calls, exc, _ = self.run_dir(sddl=sddl, restrict=restrict, repair=lambda c: state.update(fixed=True) or True)
244        self.assertIsNone(exc)
245        self.assertEqual((calls["restrict"], calls["repair"]), (1, 1))
246
247    def test_a_drive_without_permissions_is_used_with_one_warning(self):
248        def sddl(_):
249            raise AssertionError("FAT has no ACL to read")
250        base, calls, exc, err = self.run_dir(sddl=sddl, acls=False)
251        self.assertIsNone(exc)
252        self.assertEqual((calls["restrict"], calls["repair"]), (0, 0))
253        self.assertIn("no file permissions", err)
254
255    def test_the_refusal_names_the_accounts_and_never_says_mode_0700(self):
256        sddl = lambda _: f"D:PAI(A;OICI;FA;;;{self.ME})(A;OICI;FR;;;AU)(A;OICI;FR;;;WD)"   # noqa: E731
257        base, calls, exc, _ = self.run_dir(sddl=sddl)
258        text = str(exc)
259        self.assertIn("Authenticated Users", text)
260        self.assertIn("Everyone", text)
261        self.assertNotIn("0700", text)
262        self.assertEqual(calls["restrict"], 1)
263
264    def test_the_real_system_drive_has_permissions(self):
265        from strata_control import private_files as pf
266        self.assertTrue(pf.volume_has_acls(os.environ.get("SystemRoot", "C:\\Windows")))
267
268
269class Issue3410TrashIsNotAnInstall(unittest.TestCase):
270    def test_trash_folders_are_recognised(self):
271        from strata_control.discovery import in_trash
272        for p in ("/home/u/.local/share/Trash/files/strata", "/mnt/d/.Trash-1000/files/Strata", "/Users/u/.Trash/Strata",
273                  "C:\\$Recycle.Bin\\S-1-5-21\\$R123\\Strata", "/home/u/.local/share/trash/files/strata/x"):
274            self.assertTrue(in_trash(p), p)
275        for p in ("/home/u/bin/strata", "/home/u/Trash-talk/strata", "/home/u/trash/strata", "/opt/Strata",
276                  "C:\\Users\\u\\Strata"):
277            self.assertFalse(in_trash(p), p)
278
279    def test_remembered_installs_in_the_trash_are_not_listed(self):
280        from strata_control import discovery
281        with tempfile.TemporaryDirectory() as tmp:
282            good = Path(tmp) / "bin" / "strata"
283            trash = Path(tmp) / ".local" / "share" / "Trash" / "files" / "strata"
284            got = discovery._installs_in({"installs": [str(trash), str(good)]})
285            self.assertEqual(got, [good])
286
287    def test_setup_does_not_pass_a_trash_folder_on(self):
288        import setup
289        with tempfile.TemporaryDirectory() as tmp:
290            trash = Path(tmp) / ".local" / "share" / "Trash" / "files" / "strata"
291            trash.mkdir(parents=True)
292            (trash / "setup.py").write_text("x")
293            from unittest import mock
294            nowhere = Path(tmp) / "none" / "none" / "home"            # no Strata* folders beside it on this PC
295            with mock.patch.object(setup, "home", return_value=nowhere):
296                self.assertEqual(setup.other_installs({"installs": [str(trash)]}), [])
297                self.assertEqual(setup.other_installs({"installs": [str(trash)] + [str(trash.parent.parent)]}), [])
298
299
300class Issue2971WebToolRowFitsPhones(unittest.TestCase):
301    """A tool row widened the whole page on a phone (752 px page at a 412 px viewport, measured in Chrome). The three rules
302    that keep it inside the viewport; a long tool name is cut with an ellipsis instead of pushing the page."""
303
304    def test_the_rules_are_in_the_stylesheet(self):
305        import re
306        css = (Path(__file__).resolve().parents[2] / "serve" / "web" / "app.css").read_text(encoding="utf-8")
307
308        def rule(selector):
309            m = re.search(r"(?m)^" + re.escape(selector) + r"\s*\{([^}]*)\}", css)
310            self.assertIsNotNone(m, selector)
311            return m.group(1)
312
313        self.assertIn("min-width: 0", rule(".view"))
314        self.assertIn("overflow: hidden", rule(".tool-call > summary"))
315        name = rule(".tool-call__name")
316        for part in ("min-width: 0", "overflow: hidden", "text-overflow: ellipsis"):
317            self.assertIn(part, name)
318
319
320class Issue3188BenchStartsItsOwnServer(unittest.TestCase):
321    """tools/strata_bench.py named `port` in the start-a-server branch without ever setting it."""
322
323    def test_the_start_branch_runs_with_the_config_port(self):
324        from unittest import mock
325        from tools import strata_bench as sb
326        import io
327        from contextlib import redirect_stdout
328        with tempfile.TemporaryDirectory() as tmp:
329            cfg = Path(tmp) / "run.json"
330            cfg.write_text(json.dumps({"port": 18999, "args": []}), encoding="utf-8")
331            started = []
332            with mock.patch.object(sb, "is_strata", return_value=False), \
333                    mock.patch.object(sb, "try_json", return_value=None), \
334                    mock.patch.object(sb, "start_server", side_effect=lambda c, p, g, log: started.append(p) or object()), \
335                    mock.patch.object(sb, "wait_ready", return_value=False), \
336                    mock.patch.object(sb, "stop_server"):
337                out = io.StringIO()
338                with redirect_stdout(out), mock.patch("sys.stderr", io.StringIO()):
339                    code = sb.main(["--config", str(cfg)])
340                self.assertEqual(code, 1)
341                self.assertEqual(started, [18999])
342                self.assertIn("on port 18999", out.getvalue())
343                started.clear()
344                with redirect_stdout(io.StringIO()), mock.patch("sys.stderr", io.StringIO()):
345                    sb.main(["--config", str(cfg), "--port", "18777"])
346                self.assertEqual(started, [18777])
347
348
349@unittest.skipUnless(sys.platform == "win32", "SDDL aliases exist on Windows only")
350class Issue3302AdministratorAlias(unittest.TestCase):
351    """SDDL prints the built-in Administrator (RID 500) as `LA`; the owner-only checks must still accept it."""
352
353    def setUp(self):
354        from unittest import mock
355        from strata_control import private_files as pf
356        self.pf = pf
357        self.mock = mock
358        # the built-in Administrator's string SID on this machine: resolve the alias the same way the fix does
359        import ctypes
360        from ctypes import wintypes
361        pointer = ctypes.c_void_p()
362        pf._advapi.ConvertStringSidToSidW("LA", ctypes.byref(pointer))
363        text = wintypes.LPWSTR()
364        pf._advapi.ConvertSidToStringSidW(pointer.value, ctypes.byref(text))
365        self.admin_sid = text.value
366        self.assertTrue(self.admin_sid.endswith("-500"))
367
368    def test_alias_matches_the_account_it_names(self):
369        self.assertTrue(self.pf._same_sid("LA", self.admin_sid))
370        self.assertTrue(self.pf._same_sid(self.admin_sid, self.admin_sid))
371        self.assertFalse(self.pf._same_sid("LA", "S-1-5-21-1-2-3-1001"))
372        self.assertFalse(self.pf._same_sid("WD", self.admin_sid))
373        self.assertFalse(self.pf._same_sid("S-1-5-21-1-2-3-1001", self.admin_sid))
374
375    def test_private_and_unshared_hold_for_the_built_in_administrator(self):
376        pf = self.pf
377        with self.mock.patch.object(pf, "current_user_sid", return_value=self.admin_sid), \
378                self.mock.patch.object(pf, "dacl_sddl", return_value="D:PAI(A;OICI;FA;;;LA)"):
379            self.assertTrue(pf.is_private("x"))
380            self.assertTrue(pf.is_unshared("x"))
381        with self.mock.patch.object(pf, "current_user_sid", return_value=self.admin_sid), \
382                self.mock.patch.object(pf, "dacl_sddl", return_value="D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)"):
383            self.assertFalse(pf.is_private("x"))
384            self.assertFalse(pf.is_unshared("x"))
385        with self.mock.patch.object(pf, "current_user_sid", return_value=self.admin_sid), \
386                self.mock.patch.object(pf, "dacl_sddl", return_value="D:PAI(A;OICI;FA;;;LA)(A;OICI;FR;;;WD)"):
387            self.assertFalse(pf.is_private("x"))
388            self.assertFalse(pf.is_unshared("x"))
389
390
391
392class Issue3488IntegrityRetry(unittest.TestCase):
393    """A hash that reads wrong once (file just unpacked, or held by a virus scanner) must not stick."""
394
395    def test_second_read_decides(self):
396        from unittest import mock
397        from strata_control import engine_component as ec
398        path = Path("x")
399        with mock.patch.object(ec, "_sha256", side_effect=["bad", "good"]) as sha, mock.patch.object(ec.time, "sleep"):
400            self.assertEqual(ec._hash_settled(path, "good"), "good")
401            self.assertEqual(sha.call_count, 2)
402        with mock.patch.object(ec, "_sha256", side_effect=[PermissionError(), "good"]), mock.patch.object(ec.time, "sleep"):
403            self.assertEqual(ec._hash_settled(path, "good"), "good")
404        with mock.patch.object(ec, "_sha256", return_value="bad"), mock.patch.object(ec.time, "sleep"):
405            self.assertEqual(ec._hash_settled(path, "good"), "bad")      # still wrong after the retry: refuse
406
407
408
409class Issue3501TrashOnPosix(unittest.TestCase):
410    """A Windows Recycle Bin path read on Linux: Path does not split backslashes there."""
411
412    def test_windows_path_on_a_posix_path_class(self):
413        from pathlib import PurePosixPath
414        from unittest import mock
415        from strata_control import discovery
416        with mock.patch.object(discovery, "Path", PurePosixPath):
417            self.assertTrue(discovery.in_trash(r"C:\$Recycle.Bin\S-1-5-21\$R123\Strata"))
418            self.assertTrue(discovery.in_trash("/mnt/d/$RECYCLE.BIN/S-1/Strata"))
419            self.assertFalse(discovery.in_trash(r"C:\Users\a\Strata"))
420
421
422
423class Issue3504MultiValueArgs(unittest.TestCase):
424    """Advanced settings: a two-value option is two argv entries, `off` removes all of its values, an empty value is no bare flag."""
425
426    ARGS = ["--max-context", "131072", "--control-vector-layer-range", "4", "44", "--cvec-dir", "per-layer",
427            "--conversation-cache-mib", "8192"]
428
429    def test_two_values_are_two_entries(self):
430        from strata_control import tune_knobs
431        for typed in ("4,44", "4 44", "4-44"):
432            out = tune_knobs.apply_to_argv(self.ARGS, {"--control-vector-layer-range": typed})
433            i = out.index("--control-vector-layer-range")
434            self.assertEqual(out[i + 1:i + 3], ["4", "44"], typed)
435            self.assertEqual(out.count("--control-vector-layer-range"), 1)
436
437    def test_off_removes_the_option_and_every_value(self):
438        from strata_cli.launch import settings as S
439        from strata_control import tune_knobs
440        extra = {"--control-vector-layer-range": "off", "--cvec-dir": "off"}
441        a, _ = S.as_argv_changes(extra, tune_knobs.BOOL_FLAGS)
442        out = tune_knobs.apply_to_argv(self.ARGS, a)
443        self.assertEqual(out, ["--max-context", "131072", "--conversation-cache-mib", "8192"])
444
445    def test_an_empty_value_is_no_bare_flag(self):
446        from strata_cli.launch import settings as S
447        from strata_control import tune_knobs
448        a, _ = S.as_argv_changes({"--cvec-dir": "", "--kv-grow": ""}, tune_knobs.BOOL_FLAGS)
449        self.assertEqual(a, {"--kv-grow": True})
450        self.assertEqual(tune_knobs.apply_to_argv(self.ARGS, a)[:-1].count("--cvec-dir"), 1)
451
452    def test_set_flag_and_the_table_keep_both_values(self):
453        from strata_cli.launch import params
454        from strata_control import user_args
455        self.assertEqual(user_args.set_flag([], "--control-vector-layer-range", "4,44"),
456                         ["--control-vector-layer-range", "4", "44"])
457        self.assertEqual(params.argv_to_dict(self.ARGS)["--control-vector-layer-range"], "4 44")
458
459
460if __name__ == "__main__":
461    unittest.main()
462
463
464class DoctorAndTheDrafter(unittest.TestCase):
465    """One drafter per run: a model whose drafter is DFlash2 has no MTP layer on disk and is still usable; with the MTP chosen the folder is required."""
466
467    def report(self, **extra):
468        import tempfile
469        from pathlib import Path
470        from strata_control import doctor
471        root = Path(tempfile.mkdtemp())
472        engine = root / "engine"
473        engine.write_text("x", encoding="utf-8")
474        engine.chmod(0o700)
475        tok = root / "tok"
476        tok.mkdir()
477        for n in ("vocab.json", "merges.txt", "token_type.json"):
478            (tok / n).write_text("{}", encoding="utf-8")
479        cfg = root / "run.json"
480        cfg.write_text(json.dumps({"exe": str(engine), "args": ["--mtp", str(root / "gone")], "cwd": str(root), "tokenizer": str(tok),
481                                   "model_name": "qwen3.8-flash-next-iq3_s", "port": 8095, **extra}), encoding="utf-8")
482        return [c for c in doctor.inspect(cfg)["components"] if c["name"] == "mtp"][0]
483
484    def test_the_layer_is_optional_only_when_the_drafter_is_dflash2(self):
485        from unittest import mock
486        from strata_control import drafting
487        with mock.patch.object(drafting, "detect_hardware", return_value=("cuda", ["sm_120"])):
488            self.assertEqual(self.report()["status"], "optional_missing", "Auto is DFlash2 here")
489            self.assertEqual(self.report(drafting="dflash2")["status"], "optional_missing")
490            self.assertEqual(self.report(drafting="mtp")["status"], "missing", "the MTP is chosen: its layer is required")
491            self.assertEqual(self.report(mtp=False)["status"], "missing", "unchanged for a config that switched the layer off by hand")
492        with mock.patch.object(drafting, "detect_hardware", return_value=("sycl", [])):
493            self.assertEqual(self.report()["status"], "optional_missing", "Intel is DFlash2 too")
494        with mock.patch.object(drafting, "detect_hardware", return_value=("cpu", [])):
495            self.assertEqual(self.report()["status"], "missing", "an engine without the code stays on the MTP")
496
497    def test_a_model_saved_with_off_needs_no_mtp_folder(self):
498        """0.2.15 release test (the app, after a restart): a model saved with Drafting Off and no MTP folder was "missing rt" and could not load."""
499        from unittest import mock
500        from strata_control import drafting
501        for hardware in (("cuda", ["sm_120"]), ("cuda", ["sm_60"]), ("hip", ["gfx1201"]), ("cpu", [])):
502            with mock.patch.object(drafting, "detect_hardware", return_value=hardware):
503                self.assertEqual(self.report(drafting="off")["status"], "optional_missing", hardware)
504                self.assertEqual(self.report(drafting="OFF")["status"], "optional_missing", hardware)
505                self.assertEqual(self.report(drafting="mtp")["status"], "missing", "the MTP chosen still needs its layer")