okami.mom/strata

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

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

main
14.9 KiB283 linesraw
1"""`strata launch` settles the engine before it touches the model. With no usable engine and none to get it does NOT refuse (owner decision,
22026-10-18): it warns in plain words (the reason from `strata update`, and the next step), asks whether to download the model anyway (the
3answer is yes unless the person says no; --yes skips the question), downloads, and ends with a message that names the engine problem and the
4next step, exit code 0. Nothing is started without an engine."""
5
6from __future__ import annotations
7
8import io
9import json
10import os
11import unittest
12from pathlib import Path
13from unittest import mock
14
15from strata_cli.launch import settings as S
16from strata_cli.launch.runner import LaunchError, NO_ENGINE_STEP, Runner, no_engine_final, no_engine_warning
17from strata_control import engine_component as ec
18
19ROOT = Path(__file__).resolve().parents[2]
20
21WRONG_FAMILY = ec.arch_notice(("gfx1100", "gfx1101", "gfx1102"), ["gfx1201"])
22USABLE = {"usable": True, "engine": {"version": "0.1.45", "backend": "hip"}, "notice": None}
23UNUSABLE = {"usable": False, "engine": None, "notice": "No engine for this PC was found in /x: the component folder holds no engine package. "
24                                                       "The app never downloads an engine while it starts or serves."}
25
26
27def qwen_catalog():
28    """A catalog stand-in for a Qwen model: since 0.2.4 the runner asks it whether the family is DeepSeek (which has its own engine and skips this step);
29    a bare Mock answers yes to everything."""
30    cat = mock.Mock()
31    cat.strata.multi_family.return_value = False
32    return cat
33
34
35class FakeProc:
36    def __init__(self, events: list[dict], code: int = 0):
37        self.stdout = iter(json.dumps(e) + "\n" for e in events)
38        self._code = code
39
40    def wait(self) -> int:
41        return self._code
42
43
44def update_events(status: str, note: str = "", code: int = 0) -> list[dict]:
45    res = {"component": "engine", "status": status, "changed": status == "updated", "installed_before": None}
46    if note:
47        res["note"] = note
48    return [{"event": "phase", "phase": "feed", "message": "Reading the signed update feed"},
49            {"event": "result", "results": [res], "exit_code": code}]
50
51
52def runner(spawned: list) -> Runner:
53    r = Runner(S.LaunchSettings(family="qwen", model="Q2_0", context=32768), catalog=qwen_catalog(), emit=lambda e: None)
54    r.check_cancel = lambda: None
55    return r
56
57
58class EngineBeforeModel(unittest.TestCase):
59    def run_ensure(self, statuses: list[dict], events: list[dict], code: int = 0):
60        """ensure_engine() with a fake `strata update` and a sequence of engine reports. Returns (spawn count, the error or None)."""
61        spawns, err, _r = self.run_ensure_runner(statuses, events, code)
62        return spawns, err
63
64    def run_ensure_runner(self, statuses: list[dict], events: list[dict], code: int = 0, confirm=None, gb: float = 0.0,
65                          assume_yes: bool = False):
66        """ensure_engine() like run_ensure, returning (spawns, error or None, the runner with .events)."""
67        spawns: list = []
68        seen: list = []
69        r = Runner(S.LaunchSettings(family="qwen", model="Q2_0", context=32768), catalog=qwen_catalog(), emit=seen.append,
70                   confirm=confirm, assume_yes=assume_yes)
71        r.events = seen
72        r.check_cancel = lambda: None
73        err = None
74        with mock.patch.object(ec, "status", side_effect=statuses), \
75                mock.patch.object(Runner, "_spawn", side_effect=lambda argv, **kw: spawns.append(argv) or FakeProc(events, code)), \
76                mock.patch.object(Runner, "download_gb", return_value=gb):
77            try:
78                r.ensure_engine()
79            except LaunchError as e:
80                err = e
81        return spawns, err, r
82
83    def test_engine_present_runs_nothing(self):
84        spawns, err = self.run_ensure([USABLE], [])
85        self.assertIsNone(err)
86        self.assertEqual(spawns, [])
87
88    def test_no_engine_and_the_feed_has_one(self):
89        spawns, err = self.run_ensure([UNUSABLE, USABLE], update_events("updated"))
90        self.assertIsNone(err)
91        self.assertEqual(len(spawns), 1)
92        self.assertIn("update", spawns[0])
93
94    def test_no_engine_and_the_feed_has_none_is_a_warning_not_a_refusal(self):
95        note = "The feed has no engine package for this PC."
96        spawns, err, r = self.run_ensure_runner([UNUSABLE, UNUSABLE], update_events("none-for-this-pc", note))
97        self.assertIsNone(err)
98        self.assertEqual(r.engine_problem, note)
99        warning = no_engine_warning(note)
100        self.assertEqual(r.events[-1].text, warning)
101        self.assertEqual(r.events[-1].level, "warn")
102        self.assertIn("Strata couldn't find an engine for this computer (The feed has no engine package for this PC)", warning)
103        self.assertIn("The model will download, but it may not run until you install the right engine (next step:", warning)
104        self.assertIn(NO_ENGINE_STEP, warning)
105        self.assertNotIn("The app never downloads", warning)          # not the generic line
106
107    def test_no_graphics_card_is_said_plainly_with_no_feed_address(self):
108        report = dict(UNUSABLE, backend=None)
109        spawns, err, r = self.run_ensure_runner([report, report], update_events("none-for-this-pc"))
110        self.assertIsNone(err)
111        self.assertTrue(r.engine_problem.startswith("no graphics card that Strata can use was found"))
112        text = r.events[-1].text
113        self.assertIn("Strata needs an NVIDIA or AMD graphics card", text)
114        self.assertNotIn("--feed", text)
115        self.assertNotIn("<address>", text)
116        self.assertNotIn("--feed", no_engine_final(r.engine_problem))
117
118    def test_the_other_no_engine_texts_do_not_ask_for_a_feed_address_either(self):
119        self.assertNotIn("<address>", NO_ENGINE_STEP)
120        self.assertNotIn("--feed", no_engine_warning("The feed has no engine package for this PC."))
121
122    def test_wrong_family_names_the_plain_reason_in_the_warning(self):
123        spawns, err, r = self.run_ensure_runner([UNUSABLE, UNUSABLE], update_events("none-for-this-pc", WRONG_FAMILY))
124        self.assertIsNone(err)
125        self.assertEqual(r.engine_problem, WRONG_FAMILY)
126        text = r.events[-1].text
127        self.assertIn("This build of Strata is for AMD RX 7000 cards. This computer has an AMD RX 9000 card (gfx1201).", text)
128        self.assertIn("Ask for the RX 9000 build)", text)
129
130    def test_installed_wrong_family_package_uses_its_plain_notice(self):
131        report = {"usable": False, "engine": None, "notice": WRONG_FAMILY}
132        spawns, err, r = self.run_ensure_runner([report, report], update_events("none-for-this-pc"))
133        self.assertEqual(r.engine_problem, WRONG_FAMILY)
134
135    def test_the_question_is_asked_with_the_warning_and_no_stops_before_the_download(self):
136        asked = []
137        spawns, err, r = self.run_ensure_runner([UNUSABLE, UNUSABLE], update_events("none-for-this-pc", "No engine here."),
138                                                confirm=lambda title, text: asked.append((title, text)) or False, gb=66.0)
139        self.assertEqual(len(asked), 1)
140        self.assertIn("Strata couldn't find an engine for this computer (No engine here)", asked[0][1])
141        self.assertIn("Download the model now (about 66 GB)?", asked[0][1])
142        self.assertIsInstance(err, LaunchError)
143        self.assertEqual(err.code, 130)
144        self.assertIn("Nothing was downloaded", err.text)
145
146    def test_yes_goes_on_and_the_yes_flag_asks_nothing(self):
147        asked = []
148        spawns, err, r = self.run_ensure_runner([UNUSABLE, UNUSABLE], update_events("none-for-this-pc", "No engine here."),
149                                                confirm=lambda t, x: asked.append(1) or True, gb=66.0)
150        self.assertIsNone(err)
151        self.assertEqual(len(asked), 1)
152        asked.clear()
153        spawns, err, r = self.run_ensure_runner([UNUSABLE, UNUSABLE], update_events("none-for-this-pc", "No engine here."),
154                                                confirm=lambda t, x: asked.append(1) or False, gb=66.0, assume_yes=True)
155        self.assertIsNone(err)
156        self.assertEqual(asked, [])
157        self.assertEqual(r.engine_problem, "No engine here.")
158
159    def test_nothing_to_download_asks_nothing(self):
160        asked = []
161        spawns, err, r = self.run_ensure_runner([UNUSABLE, UNUSABLE], update_events("none-for-this-pc", "No engine here."),
162                                                confirm=lambda t, x: asked.append(1) or False, gb=0.0)
163        self.assertIsNone(err)
164        self.assertEqual(asked, [])
165
166    def test_the_model_is_downloaded_and_nothing_is_started_without_an_engine(self):
167        r = runner([])
168        started = []
169        with mock.patch.object(ec, "status", return_value=UNUSABLE), \
170                mock.patch.object(Runner, "_spawn", return_value=FakeProc(update_events("none-for-this-pc", WRONG_FAMILY))), \
171                mock.patch.object(Runner, "ensure_model", return_value=Path("/x/strata-q.json")) as model, \
172                mock.patch.object(Runner, "build_config", return_value=Path("/x/launch.json")), \
173                mock.patch.object(Runner, "ensure_profile"), mock.patch.object(Runner, "tune") as tune, \
174                mock.patch.object(Runner, "start", side_effect=lambda: started.append(1)):
175            result = r.run()
176        model.assert_called_once()
177        tune.assert_not_called()
178        self.assertEqual(started, [])
179        self.assertFalse(result.serving)
180        self.assertEqual(result.urls, [])
181        self.assertEqual(result.engine_problem, WRONG_FAMILY)
182        self.assertEqual(result.final_text, no_engine_final(WRONG_FAMILY))
183        self.assertIn("The model is ready, but Strata can't start it yet", result.final_text)
184        self.assertIn("Ask for the RX 9000 build)", result.final_text)
185        self.assertIn(NO_ENGINE_STEP, result.final_text)
186
187    def test_the_setup_child_is_told_to_go_on_without_an_engine(self):
188        r = runner([])
189        r.engine_problem = "No engine here."
190        seen = {}
191
192        class Boom(Exception):
193            pass
194
195        def spawn(self, argv, env=None, cwd=None):
196            seen["env"] = env
197            raise Boom()
198
199        cat = mock.MagicMock()
200        cat.src = ROOT
201        r._catalog = cat
202        r.s = S.LaunchSettings(family="qwen", model="Q2_0", context=32768)
203        # (not an Intel Arc launch: on a box with an Arc card intel_chosen() is true and the model would be adopted, not set up; the
204        # MagicMock catalog used to answer multi_file() with a truthy mock, which hid that before DeepSeek's branch left intel_chosen)
205        with mock.patch.object(Runner, "installed_state", return_value=(None, None)), mock.patch.object(Runner, "_spawn", spawn),                 mock.patch.object(Runner, "intel_chosen", return_value=False):
206            with self.assertRaises(Boom):
207                r.ensure_model()
208        self.assertEqual(seen["env"].get("STRATA_ALLOW_NO_ENGINE"), "1")
209        self.assertNotIn("STRATA_NEED_ENGINE", seen["env"])
210
211    def test_a_failed_update_still_reports_the_old_message(self):
212        spawns, err = self.run_ensure([UNUSABLE], [{"event": "error", "error": {"message": "cannot reach the feed"}}], code=6)
213        self.assertEqual(err.code, 6)
214        self.assertIn("Cannot reach the feed", err.text)      # (the reason is capitalised where it joins the sentence)
215
216
217class SetupControlStep(unittest.TestCase):
218    """setup.py in the app's mode (and under `strata launch`): the engine step comes before the download step."""
219
220    def load_setup(self):
221        """A private copy of setup.py read in the app's mode; the shared `setup` module (other tests) is left as it is."""
222        import importlib.util
223        spec = importlib.util.spec_from_file_location("setup_control_copy", ROOT / "setup.py")
224        module = importlib.util.module_from_spec(spec)
225        with mock.patch.dict(os.environ, {"STRATA_CONTROL_INSTALL": "1"}):
226            spec.loader.exec_module(module)
227        return module
228
229    def step(self, exc: Exception, env: dict) -> tuple[object, str]:
230        setup = self.load_setup()
231        out = io.StringIO()
232        with mock.patch.dict(os.environ, env), mock.patch.object(ec, "resolve", side_effect=exc), \
233                mock.patch.object(setup, "get_llama_cpp", return_value=Path("llama")), \
234                mock.patch.object(setup, "say", lambda *a, **k: out.write(" ".join(map(str, a)) + "\n")), \
235                mock.patch.object(setup, "warn", lambda *a, **k: out.write("WARN " + " ".join(map(str, a)) + "\n")), \
236                mock.patch.object(setup, "ok", lambda *a, **k: None):
237            try:
238                return setup.control_engine_step({}, "none"), out.getvalue()
239            except SystemExit as e:
240                return e, out.getvalue()
241
242    def test_wrong_family_stops_before_the_download_for_launch(self):
243        exc = ec.EngineMissing("nothing matched", Path("/c"), notice=WRONG_FAMILY)
244        res, out = self.step(exc, {"STRATA_NEED_ENGINE": "1"})
245        self.assertIsInstance(res, SystemExit)
246        self.assertIn("Ask for the RX 9000 build.", out)
247        self.assertIn("nothing was downloaded", out)
248
249    def test_wrong_family_goes_on_with_a_warning_when_launch_said_go_on(self):
250        exc = ec.EngineMissing("nothing matched", Path("/c"), notice=WRONG_FAMILY)
251        res, out = self.step(exc, {"STRATA_ALLOW_NO_ENGINE": "1"})
252        self.assertNotIsInstance(res, SystemExit)
253        self.assertIn("no engine is installed for this PC yet", out)
254        self.assertIn("The model is downloaded and prepared now", out)
255
256    def test_no_engine_for_launch_still_stops_setup_when_run_on_its_own(self):
257        res, out = self.step(ec.EngineMissing("the component folder holds no engine package", Path("/c")), {"STRATA_NEED_ENGINE": "1"})
258        self.assertIsInstance(res, SystemExit)
259
260    def test_the_app_with_a_wrong_family_engine_warns_and_still_downloads(self):
261        """Owner decision 2026-10-18: the app downloads the model anyway and warns (its card says so)."""
262        env = {k: v for k, v in os.environ.items() if k != "STRATA_NEED_ENGINE"}
263        exc = ec.EngineMissing("nothing matched", Path("/c"), notice=WRONG_FAMILY)
264        with mock.patch.dict(os.environ, env, clear=True):
265            res, out = self.step(exc, {})
266        self.assertNotIsInstance(res, SystemExit)
267        self.assertIn("Ask for the RX 9000 build.", out)
268        self.assertIn("The model is downloaded and prepared now", out)
269
270    def test_no_engine_stops_before_the_download_for_launch(self):
271        res, out = self.step(ec.EngineMissing("the component folder holds no engine package", Path("/c")), {"STRATA_NEED_ENGINE": "1"})
272        self.assertIsInstance(res, SystemExit)
273
274    def test_the_app_without_an_engine_keeps_its_order(self):
275        env = {k: v for k, v in os.environ.items() if k != "STRATA_NEED_ENGINE"}
276        with mock.patch.dict(os.environ, env, clear=True):
277            res, out = self.step(ec.EngineMissing("the component folder holds no engine package", Path("/c")), {})
278        self.assertNotIsInstance(res, SystemExit)
279        self.assertIn("The model is downloaded and prepared now", out)
280
281
282if __name__ == "__main__":
283    unittest.main()