okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
21.2 KiB363 linesraw
1"""Owner test round 8 (7 machines), the Control / TUI / setup fixes: F5, F3, N2 to N9, N11."""
2
3import argparse
4import io
5import json
6import os
7import sys
8import tempfile
9import unittest
10from contextlib import redirect_stdout
11from pathlib import Path
12from unittest import mock
13
14from strata_cli.launch import adopt, library, runner as R
15from strata_cli.launch import settings as S
16from strata_cli.launch.runner import Runner
17from tests.terminal.launch_support import HW_12, HW_2X16, Home, catalog
18
19
20def runner_for(**kw) -> Runner:
21    return Runner(S.LaunchSettings(family="qwen", model="IQ3_XXS", context=32768, vision="off", **kw), catalog=catalog(HW_12))
22
23
24class EngineExitIsExplained(unittest.TestCase):
25    """F5 (L3): an Arc engine died with 'No device of requested type available' and the person saw only 'server_exited'."""
26
27    def config_with_log(self, lines):
28        folder = tempfile.TemporaryDirectory()
29        self.addCleanup(folder.cleanup)
30        log = Path(folder.name) / "engine.log"
31        log.write_text("\n".join(lines) + "\n", encoding="utf-8")
32        cfg = Path(folder.name) / "run.json"
33        cfg.write_text(json.dumps({"log": str(log)}), encoding="utf-8")
34        return cfg, log
35
36    def test_arc_without_the_render_group_names_the_cause_the_next_step_and_the_log(self):
37        cfg, log = self.config_with_log(["strata generate: memory guard: limit 61.6 GiB", "strata generate: SYCL init",
38                                         "terminate called after throwing an instance of 'sycl::exception'",
39                                         "  what():  No device of requested type available. -1 (PI_ERROR_DEVICE_NOT_FOUND)"])
40        text, nxt = R.explain_engine_exit({"state": "failed", "error": "server_exited", "engine_exit_code": 134}, cfg)
41        self.assertIn("stopped while it was loading the model", text)
42        self.assertIn("No device of requested type available", text)
43        self.assertNotIn("server_exited", text + nxt)
44        self.assertIn("render group", nxt)
45        self.assertIn(str(log), nxt)
46
47    def test_a_gpu_runtime_start_failure_gets_a_plain_sentence_and_keeps_the_runtime_text_out_of_it(self):
48        cfg, log = self.config_with_log(["strata generate: loading", "terminate called after throwing an instance of 'rocr::AMD::hsa_exception'",
49                                         "  what():  "])
50        text, nxt = R.explain_engine_exit({"state": "failed", "error": "server_exited", "engine_exit_code": 134}, cfg)
51        self.assertIn("stopped while it was loading the model (exit code 134)", text)
52        self.assertNotIn("hsa_exception", text + nxt)
53        self.assertNotIn("terminate called", text + nxt)
54        self.assertIn("graphics card was not ready yet", nxt)
55        self.assertIn("wait a few seconds", nxt)
56        self.assertIn("restart the PC", nxt)
57        self.assertIn(str(log), nxt)
58        text, nxt = R.explain_engine_exit({"error": "server_exited", "engine_exit_code": 134,
59                                           "log_tail": "terminate called after throwing an instance of 'rocr::AMD::hsa_exception' | what():"}, None)
60        self.assertNotIn("hsa_exception", text)
61        self.assertIn("graphics card was not ready yet", nxt)
62
63    def test_a_real_cause_in_the_same_log_wins_over_the_gpu_runtime_start_failure(self):
64        cfg, log = self.config_with_log(["strata generate: CUDA error: out of memory",
65                                         "terminate called after throwing an instance of 'rocr::AMD::hsa_exception'", "  what():  "])
66        text, nxt = R.explain_engine_exit({"state": "failed", "error": "server_exited", "engine_exit_code": 134}, cfg)
67        self.assertIn("out of memory", text)
68        self.assertIn("--context 16k", nxt)
69        self.assertNotIn("graphics card was not ready", nxt)
70        cfg, _ = self.config_with_log(["Permission denied: /dev/dri/renderD128", "terminate called after throwing an instance of 'rocr::AMD::hsa_exception'"])
71        self.assertIn("render group", R.explain_engine_exit({"error": "server_exited", "engine_exit_code": 134}, cfg)[1])
72        cfg, _ = self.config_with_log(["hsaKmtOpenKFD ok", "strata generate: CUDA error: out of memory"])
73        self.assertNotIn("graphics card was not ready", R.explain_engine_exit({"error": "server_exited"}, cfg)[1])
74
75    def test_out_of_memory_and_old_engine_get_their_own_next_step(self):
76        cfg, _ = self.config_with_log(["strata generate: CUDA error: out of memory"])
77        self.assertIn("--context 16k", R.explain_engine_exit({"error": "server_exited"}, cfg)[1])
78        cfg, _ = self.config_with_log(["strata generate: no kernel for TQK6 on this engine"])
79        self.assertIn("strata update", R.explain_engine_exit({"error": "server_exited"}, cfg)[1])
80
81    def test_an_unreadable_log_still_says_the_stage_and_where_to_look(self):
82        text, nxt = R.explain_engine_exit({"state": "failed", "error": "server_exited", "log_tail": "boom | Error: cannot map the pack"}, None)
83        self.assertIn("cannot map the pack", text)
84        self.assertIn("strata logs", nxt)
85        text, _ = R.explain_engine_exit({"state": "starting", "error": "startup_wait_expired"}, None)
86        self.assertIn("did not finish loading in time", text)
87
88
89class NoTuiNeverAsks(unittest.TestCase):
90    def test_no_tui_keeps_the_models_and_says_so_without_input(self):
91        with tempfile.TemporaryDirectory() as old, tempfile.TemporaryDirectory() as new:
92            (Path(old) / "models").mkdir()
93            (Path(old) / "models" / "a.gguf").write_bytes(b"x" * 2048)
94            from strata_cli.launch import cmd
95            a = argparse.Namespace(data_dir=new, move_data=False, yes=False, plan=False, no_tui=True)
96            cat = mock.Mock()
97            cat.data_dir.return_value = Path(old)
98            out = io.StringIO()
99            with mock.patch.object(library, "movable_library", return_value=40.0), mock.patch("builtins.input", side_effect=AssertionError("asked")), \
100                    mock.patch.object(sys, "stdin") as stdin, redirect_stdout(out):
101                stdin.isatty.return_value = True
102                self.assertFalse(cmd._move_data_choice(a, S.LaunchSettings(), cat, False))
103            self.assertIn("Keeping your 40 GB of models where they are", out.getvalue())
104            self.assertIn("--move-data", out.getvalue())
105
106    def test_a_run_without_a_keyboard_says_the_same(self):
107        from strata_cli.launch import cmd
108        a = argparse.Namespace(data_dir="/new", move_data=False, yes=False, plan=False, no_tui=False)
109        out = io.StringIO()
110        with mock.patch.object(library, "movable_library", return_value=3.0), mock.patch("builtins.input", side_effect=AssertionError("asked")), \
111                mock.patch.object(sys, "stdin") as stdin, redirect_stdout(out):
112            stdin.isatty.return_value = False
113            self.assertFalse(cmd._move_data_choice(a, S.LaunchSettings(), mock.Mock(), False))
114        self.assertIn("Keeping your 3.0 GB", out.getvalue())
115
116
117class SetupArguments(unittest.TestCase):
118    def installed(self, h: Home, **cfg):
119        path = h.base / "install" / "strata-iq3_xxs.json"
120        path.parent.mkdir(parents=True, exist_ok=True)
121        path.write_text(json.dumps({"exe": "x", "args": [], **cfg}), encoding="utf-8")
122        return path
123
124    def test_a_context_change_forwards_the_installed_roles(self):
125        # F3: 0=main,1=helper came back from a 32k to 16k change as 0=helper,1=main
126        with Home() as h:
127            path = self.installed(h, gpu=[1, 0], gpus_asked=True, gpu_roles={"0": "main", "1": "helper"})
128            r = runner_for()
129            with mock.patch.object(Runner, "installed_state", return_value=(path, None)):
130                a = r.setup_args()
131            self.assertEqual(a[a.index("--gpu-roles") + 1], "0=main,1=helper")
132
133    def test_installed_cards_are_forwarded_and_the_automatic_pick_is_not(self):
134        with Home() as h:
135            path = self.installed(h, gpu=[1, 0], gpus_asked=True)
136            with mock.patch.object(Runner, "installed_state", return_value=(path, None)):
137                a = runner_for().setup_args()
138            self.assertEqual(a[a.index("--gpus") + 1], "1,0")
139            path = self.installed(h, gpu=0)                               # never asked: setup picks again
140            with mock.patch.object(Runner, "installed_state", return_value=(path, None)):
141                a = runner_for().setup_args()
142            self.assertNotIn("--gpus", a)
143            self.assertNotIn("--gpu", a)
144
145    def test_cards_named_on_the_command_line_win_over_the_installed_ones(self):
146        with Home() as h:
147            path = self.installed(h, gpu=[1, 0], gpus_asked=True, gpu_roles={"0": "main", "1": "helper"})
148            with mock.patch.object(Runner, "installed_state", return_value=(path, None)):
149                a = runner_for(gpus=[0]).setup_args()
150            self.assertEqual(a[a.index("--gpu") + 1], "0")
151            self.assertNotIn("--gpu-roles", a)
152
153    def test_a_remembered_single_card_is_said_when_the_pc_has_more(self):
154        # NVIDIA: after `--gpu 0` the next launch with nothing named stayed on one card without a word (boston, 2x A6000)
155        base = {"exe": "x", "args": [], "gpu": 0, "gpus_asked": True}
156        with Home():
157            two = Runner(S.LaunchSettings(family="qwen", model="IQ3_XXS"), catalog=catalog(HW_2X16))
158            two.say_remembered_cards(base)
159            self.assertEqual(len(two.notices), 1)
160            self.assertIn("stays on card 0", two.notices[0])
161            self.assertIn("strata launch --gpu 0,1", two.notices[0])
162            self.assertIn("remembered", two.notices[0])
163            one = Runner(S.LaunchSettings(family="qwen", model="IQ3_XXS"), catalog=catalog(HW_12))
164            one.say_remembered_cards(base)                                                     # one card in the PC: nothing to say
165            self.assertEqual(one.notices, [])
166            both = Runner(S.LaunchSettings(family="qwen", model="IQ3_XXS"), catalog=catalog(HW_2X16))
167            both.say_remembered_cards({**base, "gpu": [0, 1]})                                 # all cards are used: nothing to say
168            both.say_remembered_cards({**base, "gpus_asked": False})                           # setup's own pick is not a choice
169            self.assertEqual(both.notices, [])
170            named = Runner(S.LaunchSettings(family="qwen", model="IQ3_XXS", gpus=[0]), catalog=catalog(HW_2X16))
171            named.say_remembered_cards(base)                                                   # named on this launch: the person knows
172            self.assertEqual(named.notices, [])
173
174    def test_mtp_off_reaches_setup(self):
175        with Home():
176            a = runner_for(mtp="off").setup_args()
177            self.assertEqual(a[a.index("--mtp") + 1], "off")
178            self.assertNotIn("--mtp", runner_for().setup_args())
179
180    def test_setup_skips_the_draft_layer_download_for_mtp_off(self):
181        # setup.py is a script; its two fetch sites must be guarded by the explicit --mtp off (N3: a 5.2 GB download happened anyway)
182        text = (Path(__file__).resolve().parents[2] / "setup.py").read_text(encoding="utf-8")
183        self.assertIn('if a.mtp == "off" and not (rt / "experts.bin").exists():', text)
184        self.assertIn('if use_mtp and a.mtp == "off" and not (mtp / "mtp-q2_0.gguf").exists():', text)
185        self.assertIn('"use --data-dir on a bigger drive (strata launch --data-dir)" if CONTROL', text)       # N2: a launch option, not --models-dir
186
187
188class PlanPredictsEveryDownload(unittest.TestCase):
189    def setUp(self):
190        from tests.terminal.launch_support import not_intel
191        not_intel(self)
192
193    def plan_text(self, h: Home, own: Path, **kw) -> dict:
194        s = S.LaunchSettings(family="qwen", model="IQ3_XXS", context=32768, vision="on", model_path=str(own), data_dir=str(h.base / "data"), **kw)
195        r = Runner(s, catalog=catalog(HW_12))
196        with mock.patch.object(Runner, "check_own_files"), mock.patch.object(Runner, "ready_pack_gap", return_value=None):
197            return r.download_plan()
198
199    def test_a_local_gguf_without_a_reader_shows_the_picture_reader_and_the_switch(self):
200        with Home() as h:
201            own = h.base / "own"
202            own.mkdir()
203            (own / "m-00001-of-00002.gguf").write_bytes(b"x")
204            plan = self.plan_text(h, own)
205            self.assertIn("picture reader", plan["text"])
206            self.assertIn("--vision off", plan["text"])
207            self.assertIn("draft layer", plan["text"])
208            self.assertIn("--mtp off", plan["text"])
209
210    def test_a_reader_beside_the_files_is_used_and_not_counted(self):
211        with Home() as h:
212            own = h.base / "own"
213            own.mkdir()
214            (own / "m-00001-of-00002.gguf").write_bytes(b"x")
215            (own / "mmproj-Qwen3.8-Flash-Next-BF16.gguf").write_bytes(b"x")
216            plan = self.plan_text(h, own)
217            self.assertNotIn("picture reader", plan["text"])
218
219    def test_mtp_off_is_not_counted(self):
220        with Home() as h:
221            own = h.base / "own"
222            own.mkdir()
223            (own / "m-00001-of-00002.gguf").write_bytes(b"x")
224            self.assertNotIn("draft layer", self.plan_text(h, own, mtp="off")["text"])
225
226
227class ReadyPackPlan(unittest.TestCase):
228    def test_a_ready_made_pack_is_counted_and_the_hint_is_a_launch_option(self):
229        with Home() as h:
230            own = h.base / "own"
231            own.mkdir()
232            r = Runner(S.LaunchSettings(family="qwen", model="IQ3_XXS", context=32768, vision="off", model_path=str(own)), catalog=catalog(HW_12))
233            gap = {"gb": 129.0, "folder": str(h.base / "data" / "models"), "free_gb": 110.0}
234            with mock.patch.object(Runner, "ready_pack_gap", return_value=gap):
235                plan = r.download_plan()
236            self.assertGreaterEqual(plan["gb"], 129.0)
237            self.assertIn("ready-made pack", plan["text"])
238            self.assertIn("--data-dir", plan["text"])
239            self.assertNotIn("Nothing to download", plan["text"])
240
241
242class EngineIsFreshEnough(unittest.TestCase):
243    def test_versions_compare_by_numbers(self):
244        self.assertEqual(R.version_tuple("0.1.45.3"), (0, 1, 45, 3))
245        self.assertEqual(R.version_tuple("junk"), ())
246
247    def test_an_old_engine_is_named_in_plain_words_and_a_current_one_is_not(self):
248        with Home():
249            r = runner_for()
250            r.catalog.strata.setup_module()           # loads setup.py's tables (MIN_ENGINE)
251            words = r.stale_engine("0.1.45.3")
252            self.assertIn("older than this model needs", words)
253            self.assertIn("0.1.45.3", words)
254            self.assertIsNone(r.stale_engine("0.1.47"))
255            self.assertIsNone(r.stale_engine("source"))
256
257    def test_gyro_on_a_mac_needs_engine_0_1_47(self):
258        with Home():
259            r = Runner(S.LaunchSettings(family="gyro", model="Gyro-S", context=32768, vision="off"), catalog=catalog(HW_12))
260            with mock.patch.object(sys, "platform", "darwin"):
261                self.assertEqual(r.needed_engine(), (0, 1, 47))
262                self.assertIn("older than this model needs (0.1.47", r.stale_engine("0.1.45.3"))
263                self.assertIsNone(r.stale_engine("0.1.47"))
264            with mock.patch.object(sys, "platform", "linux"):
265                self.assertLess(r.needed_engine(), (0, 1, 47))               # CUDA, HIP and SYCL had the kernels earlier
266                self.assertIsNone(r.stale_engine("0.1.46"))
267            with mock.patch.object(sys, "platform", "darwin"):
268                q = Runner(S.LaunchSettings(family="qwen", model="IQ3_XXS", context=32768, vision="off"), catalog=catalog(HW_12))
269                self.assertLess(q.needed_engine(), (0, 1, 47))              # only Gyro is held to it
270
271    def test_a_stale_engine_is_updated_or_said_never_ignored(self):
272        with Home():
273            r = runner_for()
274            events = []
275            r.emit = lambda stage, text, pct=None, level="info", **kw: events.append((level, text))
276            before = {"usable": True, "engine": {"version": "0.1.45.3", "backend": "cuda"}}
277            proc = mock.Mock()
278            proc.stdout = iter([])
279            proc.wait.return_value = 0
280            from strata_control import engine_component as ec
281            with mock.patch.object(ec, "status", return_value=before), mock.patch.object(Runner, "_spawn", return_value=proc):
282                r.ensure_engine()
283            self.assertTrue(any(level == "warn" and "older than this model needs" in text for level, text in events), events)
284            self.assertTrue(any("strata update" in n for n in r.notices), r.notices)
285
286
287class InstallIsNotHijacked(unittest.TestCase):
288    def test_an_earlier_install_outside_the_chosen_data_folder_is_named(self):
289        with Home() as h:
290            cat = mock.Mock()
291            cat.places = [mock.Mock(path=h.base / "old" / "Strata", source="app", configs=2)]
292            words = R.install_isolation_words(cat, str(h.base / "scratch"))
293            self.assertEqual(len(words), 1)
294            self.assertIn("earlier install", words[0])
295            self.assertIn(str(h.base / "old" / "Strata"), words[0])
296            cat.places = [mock.Mock(path=h.base / "scratch" / "install", source="app", configs=1)]
297            self.assertEqual(R.install_isolation_words(cat, str(h.base / "scratch")), [])
298            cat.places = [mock.Mock(path=h.base / "old", source="explicit", configs=1)]
299            self.assertEqual(R.install_isolation_words(cat, str(h.base / "scratch")), [])
300            self.assertEqual(R.install_isolation_words(cat, None), [])
301
302    def test_an_install_inside_strata_data_dir_comes_first(self):
303        from strata_control import discovery
304        with tempfile.TemporaryDirectory() as data, tempfile.TemporaryDirectory() as other:
305            for folder in (Path(data) / "install", Path(other) / "install"):
306                folder.mkdir()
307                (folder / "strata-q.json").write_text("{}", encoding="utf-8")
308            env = {"STRATA_DATA_DIR": data}
309            found = discovery.places(environ=env, here=Path(other) / "install", home=Path(other))
310            self.assertEqual(Path(found[0].path).resolve(), (Path(data) / "install").resolve())
311
312
313class IdentityAndAdoption(unittest.TestCase):
314    def test_family_that_does_not_match_the_file_header_is_warned_about(self):
315        with Home() as h:
316            r = Runner(S.LaunchSettings(family="swift", model="IQ2_XS", model_path=str(h.base)), catalog=catalog(HW_12))
317            plan = {"candidate_selection": {"family": "qwen", "model": "IQ3_XXS"}, "folder_holds": [], "issues": []}
318            from strata_control import models
319            with mock.patch.object(models, "own_path_problem", return_value=None), mock.patch.object(models, "plan_import", return_value=plan), \
320                    mock.patch.object(models, "import_target", return_value=str(h.base)):
321                r.resolve_own_files()
322            self.assertEqual(len(r.identity_notes), 1)
323            self.assertIn("look like qwen IQ3_XXS", r.identity_notes[0])
324            self.assertIn("not swift IQ2_XS", r.identity_notes[0])
325            self.assertEqual((r.s.family, r.s.model), ("swift", "IQ2_XS"))        # warned, never forced
326
327    def test_gyro_is_adopted_like_the_others_and_the_text_has_no_double_period(self):
328        with Home() as h:
329            data = h.base / "data"
330            model_dir = data / "models" / "gyro-Gyro-S"
331            model_dir.mkdir(parents=True)
332            (model_dir / "Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf").write_bytes(b"x")
333            pack = data / "packs" / "gyro-gyro-s"
334            (pack / "tokenizer").mkdir(parents=True)
335            (pack / "index.txt").write_text("x", encoding="utf-8")
336            cfg, problems = adopt.plan(family="gyro", model="Gyro-S", model_dir=model_dir, data_dir=data, src=Path(__file__).resolve().parents[2],
337                                       context=8192, kv=None, model_name="gyro", family_def={}, log=h.base / "x.log", backend="sycl",
338                                       pack_name="gyro-gyro-s")
339            self.assertEqual(problems, [], problems)
340            self.assertEqual(cfg["args"][cfg["args"].index("--ple-gguf") + 1], cfg["args"][cfg["args"].index("--native") + 1])
341            _, refused = adopt.plan(family="nvfp4", model="NVFP4", model_dir=model_dir, data_dir=data, src=Path("."), context=8192, kv=None,
342                                    model_name="x", family_def={}, log=h.base / "x.log", backend=None)
343            self.assertTrue(refused[0].endswith("not for nvfp4"))                 # the caller adds the one full stop
344
345
346class UpdateCheckNamesTheChoice(unittest.TestCase):
347    def test_the_selected_package_is_printed_before_the_rejected_ones(self):
348        from strata_cli import update_cmd
349        report = {"feed": {"sequence": 107, "channel": "stable", "key_id": "k", "trusted_by": "built-in keys"},
350                  "engine": {"status": "install", "installed": None, "download_bytes": 5 << 20,
351                             "offered": {"version": "0.1.47", "platform": "linux-x86_64", "backend": "cuda", "variant": "cuda12"},
352                             "reasons": ["0.1.47 linux-x86_64-cuda-cuda13 needs driver 580"], "note": None},
353                  "control": {"status": "current", "installed": "0.1.47", "offered": None}, "app": {"status": "not-in-feed"}}
354        out = io.StringIO()
355        with redirect_stdout(out):
356            update_cmd._print_check(report)
357        text = out.getvalue()
358        self.assertIn("selected for this PC: 0.1.47 linux-x86_64-cuda-cuda12", text)
359        self.assertLess(text.index("selected for this PC"), text.index("not used for this PC"))
360
361
362if __name__ == "__main__":
363    unittest.main()