okami.mom/strata

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

Niko1221Tests: the terminal suites know a linux-aarch64 host (fixture Terminal named for the host; HIP-only tests skip where there is no HIP engine); pins and locks tests list the new targetb0e897b41

main
24.9 KiB467 linesraw
1"""Engine resolution from a local component folder: which package is chosen, why one is refused, and that nothing is
2ever fetched. Every folder here is a throwaway; no GPU tool is run (the backend is always given or forced)."""
3
4import contextlib
5import hashlib
6import io
7import json
8import os
9import socket
10import subprocess
11import sys
12import tempfile
13import unittest
14import urllib.request
15from pathlib import Path
16from unittest import mock
17
18from strata_cli import cli
19from strata_control import acquisition, components, engine_component as ec
20
21WINDOWS = os.name == "nt"
22HERE = components.host_platform()
23NO_HIP = HERE == "linux-aarch64"      # the DGX Spark: CUDA only
24EXE = "strata.exe" if WINDOWS else "strata"
25
26
27def make_package(root: Path, *, version="0.1.45", platform=None, backend="cuda", archs=(), min_runtime=None,
28                 extra=None, entry=None) -> Path:
29    """A fake engine package the way packaging/package_engine.py lays one out."""
30    platform = platform or HERE
31    entry = entry or EXE
32    folder = root / "engine" / f"{version}-{platform}-{backend}"
33    folder.mkdir(parents=True)
34    payload = {entry: b"MZ-not-a-real-engine-" + version.encode(), "cudart64_13.dll" if WINDOWS else "libcudart.so.13":
35              b"runtime-library-bytes" * 50, "BUILD.json": json.dumps({"version": version}).encode()}
36    payload.update(extra or {})
37    files = []
38    for name, data in payload.items():
39        (folder / name).write_bytes(data)
40        files.append({"path": name, "sha256": hashlib.sha256(data).hexdigest(), "bytes": len(data)})
41    if not WINDOWS:
42        (folder / entry).chmod(0o755)
43    manifest = {"schema_version": 1, "id": "strata-engine", "version": version, "platform": platform,
44                "backend": backend, "entrypoint": entry, "files": files}
45    if archs:
46        manifest["cuda_archs"] = list(archs)
47    if min_runtime:
48        manifest["min_runtime"] = min_runtime
49    (folder / ec.MANIFEST).write_text(json.dumps(manifest), encoding="utf-8")
50    return folder
51
52
53def rewrite(folder: Path, **changes):
54    path = folder / ec.MANIFEST
55    data = json.loads(path.read_text(encoding="utf-8"))
56    data.update(changes)
57    path.write_text(json.dumps(data), encoding="utf-8")
58
59
60class NoNetwork:
61    """Any attempt to reach the network or start an installer fails the test that is running."""
62
63    def __enter__(self):
64        def refuse(*a, **k):
65            raise AssertionError("an engine lookup tried to reach the network")
66        self.patches = [mock.patch.object(urllib.request, "urlopen", refuse),
67                        mock.patch.object(socket, "create_connection", refuse),
68                        mock.patch.object(socket.socket, "connect", refuse)]
69        for item in self.patches:
70            item.start()
71        return self
72
73    def __exit__(self, *exc):
74        for item in self.patches:
75            item.stop()
76
77
78class Resolution(unittest.TestCase):
79    def setUp(self):
80        self.dir = tempfile.TemporaryDirectory()
81        self.root = Path(self.dir.name)
82        self.addCleanup(self.dir.cleanup)
83
84    def test_the_package_for_the_backend_is_chosen(self):
85        make_package(self.root, backend="cuda")
86        make_package(self.root, backend="hip", version="0.1.46")
87        chosen = ec.resolve(self.root, backend="cuda", runtime="0.1.45")
88        self.assertEqual((chosen.backend, chosen.version), ("cuda", "0.1.45"))
89        self.assertEqual(chosen.exe, self.root / "engine" / f"0.1.45-{HERE}-cuda" / EXE)
90        self.assertTrue(chosen.exe.is_file())
91
92    def test_the_newest_compatible_version_wins(self):
93        make_package(self.root, version="0.1.45")
94        make_package(self.root, version="0.1.45.2")
95        make_package(self.root, version="0.1.9")                 # 0.1.9 < 0.1.45 numerically, not as text
96        self.assertEqual(ec.resolve(self.root, backend="cuda", runtime="1").version, "0.1.45.2")
97
98    def test_nothing_installed_is_a_notice_that_says_nothing_is_fetched(self):
99        with NoNetwork():
100            with self.assertRaises(ec.EngineMissing) as caught:
101                ec.resolve(self.root, backend="cuda")
102        text = str(caught.exception)
103        self.assertIn("never downloads an engine", text)
104        self.assertIn("strata install", text)
105        self.assertIsInstance(caught.exception, acquisition.AcquisitionRefused)
106        self.assertEqual(caught.exception.exit_code, 5)
107        self.assertFalse((self.root / "engine").exists(), "looking must not create the folder")
108
109    def test_a_missing_component_folder_is_the_same_notice(self):
110        with self.assertRaises(ec.EngineMissing):
111            ec.resolve(self.root / "does-not-exist", backend="cuda")
112
113    def test_another_platform_is_refused_with_the_reason(self):
114        other = "linux-x86_64" if WINDOWS else "windows-x86_64"
115        make_package(self.root, platform=other)
116        with self.assertRaises(ec.EngineMissing) as caught:
117            ec.resolve(self.root, backend="cuda")
118        self.assertIn(f"is for {other}", str(caught.exception))
119
120    @unittest.skipIf(NO_HIP, "there is no HIP engine for arm64 Linux (BACKEND_MATRIX): this test builds one for the host platform")
121    def test_another_backend_is_refused_with_the_reason(self):
122        make_package(self.root, backend="hip")
123        with self.assertRaises(ec.EngineMissing) as caught:
124            ec.resolve(self.root, backend="cuda")
125        self.assertIn("is a hip engine, this PC needs cuda", str(caught.exception))
126
127    def test_an_unqualified_combination_is_not_attempted(self):
128        if HERE == "macos-arm64":
129            self.skipTest("metal is supported here")
130        make_package(self.root, backend="metal")                 # metal is macOS arm64 only
131        with self.assertRaises(ec.EngineMissing) as caught:
132            ec.resolve(self.root, backend="metal", target=HERE)
133        self.assertIn("not a supported combination", str(caught.exception))
134
135    def test_runtime_too_old_is_refused(self):
136        make_package(self.root, min_runtime="0.2.0")
137        with self.assertRaises(ec.EngineMissing) as caught:
138            ec.resolve(self.root, backend="cuda", runtime="0.1.45")
139        self.assertIn("needs control 0.2.0", str(caught.exception))
140        self.assertEqual(ec.resolve(self.root, backend="cuda", runtime="0.2.0").version, "0.1.45")
141
142    def test_cuda_archs_must_cover_the_gpu(self):
143        make_package(self.root, archs=("sm_86",))
144        with mock.patch.object(ec, "cuda_archs_present", return_value=["sm_120"]):
145            with self.assertRaises(ec.EngineMissing) as caught:
146                ec.resolve(self.root, backend="cuda", runtime="1")
147        self.assertIn("sm_86", str(caught.exception))
148        with mock.patch.object(ec, "cuda_archs_present", return_value=["sm_86"]):
149            self.assertEqual(ec.resolve(self.root, backend="cuda", runtime="1").version, "0.1.45")
150        with mock.patch.object(ec, "cuda_archs_present", return_value=[]):     # cannot tell: not a refusal
151            self.assertEqual(ec.resolve(self.root, backend="cuda", runtime="1").version, "0.1.45")
152
153
154class Integrity(unittest.TestCase):
155    def setUp(self):
156        self.dir = tempfile.TemporaryDirectory()
157        self.root = Path(self.dir.name)
158        self.addCleanup(self.dir.cleanup)
159        self.folder = make_package(self.root)
160
161    def test_a_truncated_library_is_refused(self):
162        lib = next(p for p in self.folder.iterdir() if "cudart" in p.name)
163        lib.write_bytes(lib.read_bytes()[:-3])
164        with self.assertRaisesRegex(ec.EngineMissing, "bytes, the manifest says"):
165            ec.resolve(self.root, backend="cuda", runtime="1")
166
167    def test_a_changed_entrypoint_is_refused_at_once(self):
168        exe = self.folder / EXE
169        exe.write_bytes(b"X" * exe.stat().st_size)               # same size, other bytes
170        with self.assertRaisesRegex(ec.EngineMissing, "SHA-256"):
171            ec.resolve(self.root, backend="cuda", runtime="1")
172
173    def test_a_changed_library_is_found_by_the_full_check_only(self):
174        lib = next(p for p in self.folder.iterdir() if "cudart" in p.name)
175        lib.write_bytes(b"Y" * lib.stat().st_size)
176        self.assertEqual(ec.resolve(self.root, backend="cuda", runtime="1").version, "0.1.45")
177        with self.assertRaisesRegex(ec.EngineMissing, "SHA-256"):
178            ec.resolve(self.root, backend="cuda", runtime="1", full=True)
179
180    def test_a_missing_file_is_refused(self):
181        next(p for p in self.folder.iterdir() if "cudart" in p.name).unlink()
182        with self.assertRaisesRegex(ec.EngineMissing, "is missing"):
183            ec.resolve(self.root, backend="cuda", runtime="1")
184
185    def test_manifest_paths_cannot_leave_the_folder(self):
186        data = json.loads((self.folder / ec.MANIFEST).read_text())
187        for bad in ("../outside.bin", "/etc/passwd", "C:\\Windows\\win.ini", "sub/../../x"):
188            with self.subTest(path=bad):
189                broken = dict(data, files=data["files"] + [{"path": bad, "sha256": "0" * 64, "bytes": 1}])
190                (self.folder / ec.MANIFEST).write_text(json.dumps(broken), encoding="utf-8")
191                with self.assertRaises(ec.ComponentProblem):
192                    ec.read_manifest(self.folder)
193
194    def test_an_entrypoint_outside_the_file_list_is_refused(self):
195        rewrite(self.folder, entrypoint="other.exe")
196        with self.assertRaisesRegex(ec.ComponentProblem, "not in the file list"):
197            ec.read_manifest(self.folder)
198
199    def test_a_broken_manifest_does_not_hide_a_good_package(self):
200        broken = self.root / "engine" / "0.9-broken"
201        broken.mkdir()
202        (broken / ec.MANIFEST).write_text("{not json", encoding="utf-8")
203        chosen = ec.resolve(self.root, backend="cuda", runtime="1")
204        self.assertEqual(chosen.version, "0.1.45")
205        report = ec.status(self.root, backend="cuda")
206        self.assertTrue(report["usable"])
207        self.assertEqual(len(report["problems"]), 1)
208
209    @unittest.skipIf(WINDOWS, "symlinks need a privilege on Windows")
210    def test_a_symlinked_file_is_refused(self):
211        lib = next(p for p in self.folder.iterdir() if "cudart" in p.name)
212        target = self.root / "elsewhere.bin"
213        target.write_bytes(lib.read_bytes())
214        lib.unlink()
215        lib.symlink_to(target)
216        with self.assertRaisesRegex(ec.EngineMissing, "not a regular file"):
217            ec.resolve(self.root, backend="cuda", runtime="1")
218
219    @unittest.skipIf(WINDOWS, "NTFS has no execute bit")
220    def test_a_non_executable_entrypoint_is_refused(self):
221        (self.folder / EXE).chmod(0o644)
222        with self.assertRaisesRegex(ec.EngineMissing, "not executable"):
223            ec.resolve(self.root, backend="cuda", runtime="1")
224
225
226class Where(unittest.TestCase):
227    def test_environment_wins_then_the_per_user_folder(self):
228        self.assertEqual(ec.components_dir({"STRATA_COMPONENTS_DIR": "/x/y"}), Path("/x/y"))
229        win = ec.components_dir({"LOCALAPPDATA": "C:\\L"}, windows=True)
230        self.assertEqual(win.name, "components")
231        self.assertEqual(win.parent.name, "Strata")
232        posix = ec.components_dir({"XDG_DATA_HOME": "/d"}, windows=False)
233        self.assertEqual(posix.as_posix(), "/d/strata/components")
234
235    def test_backend_override_is_validated(self):
236        self.assertEqual(ec.detect_backend({"STRATA_ENGINE_BACKEND": "HIP"}), ("hip", "environment"))
237        with self.assertRaises(ec.ComponentProblem):
238            ec.detect_backend({"STRATA_ENGINE_BACKEND": "vulkan"})
239
240    def test_detection_runs_only_read_only_tools(self):
241        calls = []
242
243        def fake_run(command, **kw):
244            calls.append(Path(command[0]).stem.lower())
245            return subprocess.CompletedProcess(command, 0, stdout="NVIDIA GeForce RTX 3060\n", stderr="")
246        with mock.patch.object(ec.shutil, "which", lambda name: name), \
247                mock.patch.object(ec.subprocess, "run", fake_run), \
248                mock.patch.object(ec, "host_platform", return_value="linux-x86_64"):
249            self.assertEqual(ec.detect_backend({}), ("cuda", "nvidia-smi"))
250        self.assertEqual(calls, ["nvidia-smi"])
251
252
253class WindowsAmd(unittest.TestCase):
254    """Windows PCs with an AMD card and no HIP SDK / nvidia-smi: the display adapters decide the engine."""
255
256    OWNER_PC = [{"vendor": "10de", "device": 0x2F04, "name": "NVIDIA GeForce RTX 5070", "vram_gb": 12.0},
257                {"vendor": "1002", "device": 0x164E, "name": "AMD Radeon(TM) Graphics", "vram_gb": 0.5}]
258    TESTER_A = [{"vendor": "1002", "device": 0x7550, "name": "AMD Radeon RX 9070 XT", "vram_gb": 16.0}]
259    RYZEN_IGPU_AND_CARD = [{"vendor": "1002", "device": 0x164E, "name": "AMD Radeon(TM) Graphics", "vram_gb": 0.5},
260                           {"vendor": "1002", "device": 0x744C, "name": "AMD Radeon RX 7900 XTX", "vram_gb": 24.0}]
261    IGPU_ONLY = [{"vendor": "1002", "device": 0x15BF, "name": "AMD Radeon 780M Graphics", "vram_gb": 0.5}]
262
263    def test_a_removed_nvidia_card_left_in_the_registry_does_not_win(self):      # #3892
264        old = {"vendor": "10de", "device": 0x2684, "name": "NVIDIA GeForce RTX 4090", "vram_gb": 24.0}
265        new = self.TESTER_A[0]
266        with mock.patch.object(ec, "_windows_display_adapters_registry", return_value=[old, new]),                 mock.patch.object(ec, "_windows_adapters_cim", return_value=[dict(new)]):
267            self.assertEqual(ec._windows_vendor_backend(), "hip")
268        with mock.patch.object(ec, "_windows_display_adapters_registry", return_value=[old, new]),                 mock.patch.object(ec, "_windows_adapters_cim", return_value=[dict(old), dict(new)]):
269            self.assertEqual(ec._windows_vendor_backend(), "cuda")                  # both really there: NVIDIA first, as before
270        with mock.patch.object(ec, "_windows_display_adapters_registry", return_value=[old, new]),                 mock.patch.object(ec, "_windows_adapters_cim", return_value=[]):
271            self.assertEqual(ec._windows_vendor_backend(), "cuda")                  # Windows could not say: nothing is dropped
272
273    def test_nvidia_wins_and_an_integrated_radeon_is_not_a_card(self):
274        self.assertEqual(ec._windows_vendor_backend(self.OWNER_PC), "cuda")
275        self.assertEqual(ec.windows_amd_cards(self.OWNER_PC), [])
276
277    def test_an_amd_card_is_hip(self):
278        self.assertEqual(ec._windows_vendor_backend(self.TESTER_A), "hip")
279        self.assertEqual([c["arch"] for c in ec.windows_amd_cards(self.TESTER_A)], ["gfx1201"])
280
281    def test_a_card_beside_an_integrated_radeon_counts_only_the_card(self):
282        self.assertEqual(ec._windows_vendor_backend(self.RYZEN_IGPU_AND_CARD), "hip")
283        self.assertEqual([c["arch"] for c in ec.windows_amd_cards(self.RYZEN_IGPU_AND_CARD)], ["gfx1100"])
284
285    def test_an_integrated_radeon_alone_is_no_gpu_for_the_engine(self):
286        self.assertIsNone(ec._windows_vendor_backend(self.IGPU_ONLY))
287        self.assertIsNone(ec._windows_vendor_backend([]))
288
289    def test_an_unknown_id_with_its_own_memory_is_a_card_without_an_arch(self):
290        cards = ec.windows_amd_cards([{"vendor": "1002", "device": 0x9999, "name": "AMD Radeon RX Future", "vram_gb": 20.0}])
291        self.assertEqual(cards, [{"arch": "", "name": "AMD Radeon RX Future", "device": 0x9999}])
292
293    def test_detect_backend_on_windows_uses_the_adapters_when_no_tool_answers(self):
294        with mock.patch.object(ec.shutil, "which", lambda name: None), mock.patch.object(ec.os, "name", "nt"),                 mock.patch.object(ec, "host_platform", return_value="windows-x86_64"),                 mock.patch.object(ec, "windows_display_adapters", return_value=self.TESTER_A):
295            self.assertEqual(ec.detect_backend({}), ("hip", "display adapters"))
296
297    def test_the_arch_table_is_the_one_setup_uses(self):
298        sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
299        import setup as strata_setup
300        self.assertEqual({k: v for k, v in strata_setup._WIN_AMD_DID.items() if k not in strata_setup.AMD_IGPU_PCI},
301                         ec.WIN_AMD_DEVICE_ARCH)
302        self.assertEqual({k: v for k, v in strata_setup.AMD_IGPU_PCI.items() if v == strata_setup.STRIX_HALO_ARCH}, ec.WIN_AMD_UMA_IDS)
303        for device in strata_setup.AMD_IGPU_PCI:
304            if device not in ec.WIN_AMD_UMA_IDS:
305                self.assertIn(device, ec.WIN_AMD_IGPU_IDS)
306
307
308@unittest.skipIf(NO_HIP, "there is no HIP engine for arm64 Linux (BACKEND_MATRIX): this test builds one for the host platform")
309class WrongCardFamily(unittest.TestCase):
310    """A tester build is for one AMD card family; on another family the person gets one plain line, not a technical list."""
311
312    def setUp(self):
313        self.dir = tempfile.TemporaryDirectory()
314        self.root = Path(self.dir.name)
315        self.addCleanup(self.dir.cleanup)
316        self.folder = make_package(self.root, backend="hip", archs=("gfx1200", "gfx1201"))
317
318    def test_an_rx7000_card_with_the_rx9000_build_is_told_to_ask_for_the_other_build(self):
319        with mock.patch.object(ec, "hip_archs_present", return_value=["gfx1100"]):
320            with self.assertRaises(ec.EngineMissing) as caught:
321                ec.resolve(self.root, backend="hip", runtime="1")
322            note = ec.status(self.root, backend="hip")["notice"]
323        self.assertTrue(str(caught.exception).startswith("This build of Strata is for AMD RX 9000 cards."), str(caught.exception))
324        self.assertIn("Ask for the RX 7000 build.", note)
325        self.assertIn("(gfx1100)", note)
326        self.assertNotIn("component", note)
327
328    def test_an_amd_build_on_an_nvidia_pc_names_the_nvidia_download(self):
329        with mock.patch.object(ec, "hip_archs_present", return_value=[]):
330            note = ec.status(self.root, backend="cuda")["notice"]
331        self.assertTrue(note.startswith("This Strata is for AMD RX 9000 cards. Your PC has an NVIDIA card: download the NVIDIA version from "), note)
332        self.assertIn("https://github.com/Niko1221/Strata/releases", note)
333
334    def test_the_matching_family_is_not_blocked(self):
335        with mock.patch.object(ec, "hip_archs_present", return_value=["gfx1201"]):
336            self.assertEqual(ec.resolve(self.root, backend="hip", runtime="1").backend, "hip")
337
338
339@unittest.skipIf(NO_HIP, "there is no HIP engine for arm64 Linux (BACKEND_MATRIX): this test builds one for the host platform")
340class Rx6000Package(unittest.TestCase):
341    """0.2.2: the RX 6000 package (gfx1030 / gfx1031) is the one an RX 6000 card finds, and no other card family finds it."""
342
343    def setUp(self):
344        self.dir = tempfile.TemporaryDirectory()
345        self.root = Path(self.dir.name)
346        self.addCleanup(self.dir.cleanup)
347
348    def kfd(self, *versions):
349        nodes = Path(self.dir.name) / "kfd"
350        for i, ver in enumerate(versions):
351            node = nodes / str(i)
352            node.mkdir(parents=True)
353            (node / "properties").write_text(f"cpu_cores_count 0{chr(10)}simd_count 80{chr(10)}gfx_target_version {ver}{chr(10)}", encoding="utf-8")
354        return str(nodes)
355
356    def test_the_kfd_topology_names_rdna2_cards(self):
357        self.assertEqual(ec.hip_archs_present(self.kfd(100300, 100301, 110000, 120001)), ["gfx1030", "gfx1031", "gfx1100", "gfx1201"])
358
359    def test_an_rx6000_card_finds_the_rx6000_package_and_an_rx7000_card_does_not(self):
360        make_package(self.root, backend="hip", archs=("gfx1030", "gfx1031"))
361        with mock.patch.object(ec, "hip_archs_present", return_value=["gfx1030"]):
362            self.assertEqual(ec.resolve(self.root, backend="hip", runtime="1").hip_archs, ("gfx1030", "gfx1031"))
363            self.assertIsNone(ec.status(self.root, backend="hip")["notice"])
364        with mock.patch.object(ec, "hip_archs_present", return_value=["gfx1100"]):
365            with self.assertRaises(ec.EngineMissing) as caught:
366                ec.resolve(self.root, backend="hip", runtime="1")
367        self.assertTrue(str(caught.exception).startswith("This build of Strata is for AMD RX 6000 cards."), str(caught.exception))
368        self.assertIn("Ask for the RX 7000 build.", str(caught.exception))
369
370    def test_the_rx9000_package_on_an_rx6000_card_names_a_build_that_exists(self):
371        make_package(self.root, backend="hip", archs=("gfx1200", "gfx1201"))
372        with mock.patch.object(ec, "hip_archs_present", return_value=["gfx1030"]):
373            with self.assertRaises(ec.EngineMissing) as caught:
374                ec.resolve(self.root, backend="hip", runtime="1")
375        self.assertIn("Ask for the RX 6000 build.", str(caught.exception))
376
377
378class NeverAcquires(unittest.TestCase):
379    """The lookup, the status report and the CLI work with the network and process creation unavailable."""
380
381    def setUp(self):
382        self.dir = tempfile.TemporaryDirectory()
383        self.root = Path(self.dir.name)
384        self.addCleanup(self.dir.cleanup)
385
386    def run_cli(self, *argv):
387        out, err = io.StringIO(), io.StringIO()
388        with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
389            code = cli.main(list(argv))
390        return code, out.getvalue(), err.getvalue()
391
392    def test_status_and_cli_with_the_network_down(self):
393        make_package(self.root)
394        with NoNetwork(), mock.patch.dict(os.environ, {"STRATA_NO_ACQUIRE": "1"}):
395            report = ec.status(self.root, backend="cuda")
396            code, out, _ = self.run_cli("components", "engine", "--components-dir", str(self.root),
397                                        "--backend", "cuda", "--output", "json")
398        self.assertTrue(report["usable"])
399        self.assertFalse(report["acquires"])
400        self.assertEqual(code, 0)
401        data = json.loads(out)
402        self.assertTrue(data["ok"])
403        self.assertEqual(Path(data["engine"]["exe"]).name, EXE)
404
405    def test_cli_missing_engine_is_exit_5_with_the_notice(self):
406        with NoNetwork():
407            code, out, _ = self.run_cli("components", "engine", "--components-dir", str(self.root),
408                                        "--backend", "cuda", "--output", "json")
409        self.assertEqual(code, 5)
410        data = json.loads(out)
411        self.assertFalse(data["ok"])
412        self.assertIn("never downloads an engine", data["notice"])
413
414    def test_a_driver_too_old_for_every_engine_gets_one_plain_line_naming_the_version(self):
415        a = make_package(self.root, version="0.1.45", backend="cuda")
416        rewrite(a, min_driver={"nvidia": "580.65"})
417        with mock.patch.object(ec, "nvidia_driver_version", return_value="550.120"):
418            with self.assertRaises(ec.EngineMissing) as caught:
419                ec.resolve(self.root, backend="cuda", runtime="1")
420            note = ec.status(self.root, backend="cuda")["notice"]
421        self.assertIn("580.65", str(caught.exception), "the technical reason stays for the log")
422        self.assertIn("(550.120)", note)
423        self.assertIn("driver 580 or newer", note)
424        self.assertNotIn("component", note)
425        # two builds: the line names the lower requirement; a driver that runs one of them is no problem
426        folder = self.root / "engine" / "0.1.45-twelve"
427        folder.mkdir(parents=True)
428        for item in a.iterdir():
429            (folder / item.name).write_bytes(item.read_bytes())
430        (folder / "strata").chmod(0o755) if not WINDOWS else None
431        rewrite(folder, min_driver={"nvidia": "575.51"})
432        with mock.patch.object(ec, "nvidia_driver_version", return_value="550.120"):
433            self.assertIn("driver 575 or newer", ec.status(self.root, backend="cuda")["notice"])
434        with mock.patch.object(ec, "nvidia_driver_version", return_value="576.02"):
435            self.assertEqual(ec.resolve(self.root, backend="cuda", runtime="1").root.name, "0.1.45-twelve")
436        with mock.patch.object(ec, "nvidia_driver_version", return_value="580.178.04"):
437            self.assertEqual(ec.resolve(self.root, backend="cuda", runtime="1").root.name, a.name, "the newer-driver build wins")
438
439    def test_the_driver_version_comes_from_the_kernel_module_when_there_is_no_nvidia_smi(self):
440        text = "NVRM version: NVIDIA UNIX x86_64 Kernel Module  580.95.05  Thu Sep 11 2026 GCC version: gcc 15"
441        with mock.patch.object(ec, "_smi_query", return_value=[]), mock.patch.object(Path, "read_text", return_value=text):
442            self.assertEqual(ec.nvidia_driver_version(), "580.95.05")
443        with mock.patch.object(ec, "_smi_query", return_value=["575.57.08", "580.95.05"]):
444            self.assertEqual(ec.nvidia_driver_version(), "575.57.08", "the oldest when cards disagree")
445        with mock.patch.object(ec, "_smi_query", return_value=[]), mock.patch.object(Path, "read_text", side_effect=OSError):
446            self.assertIsNone(ec.nvidia_driver_version())
447
448    def test_the_component_fetcher_refuses_where_acquiring_is_forbidden(self):
449        store = components.ComponentStore(self.root / "store")
450        artifact = components.Artifact(name="engine.tar.gz", url="https://example.invalid/e.tgz",
451                                       sha256="0" * 64, bytes=10)
452        with NoNetwork(), mock.patch.dict(os.environ, {"STRATA_NO_ACQUIRE": "1"}):
453            with self.assertRaises(acquisition.AcquisitionRefused):
454                store._fetch(artifact)
455
456    def test_main_guard_turns_the_notice_into_exit_5(self):
457        def start():
458            ec.resolve(self.root, backend="cuda")
459        err = io.StringIO()
460        with contextlib.redirect_stderr(err):
461            code = acquisition.main_guard(start)
462        self.assertEqual(code, 5)
463        self.assertIn("No engine for this PC", err.getvalue())
464
465
466if __name__ == "__main__":
467    unittest.main()