okami.mom/strata

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

Niko1221update: --backend amd on a PC with an NVIDIA and an AMD card picks the AMD card's packagefdfca1d9d

main
64.5 KiB1228 linesraw
1"""Finding the engine package for this machine in a local component folder. There is no download path.
2
3The engine (the C++ `strata` binary and its GPU runtime libraries) is a separate, independently versioned
4component. The desktop app and the terminal start whatever is installed in the component folder; nothing here, and
5nothing on the start path, fetches an engine. A missing or unusable engine is a typed error that says what to do
6(`EngineMissing`, exit code 5, the same family as `acquisition.AcquisitionRefused`) and never an attempt to get one.
7
8Layout (``components_dir()``)::
9
10    <components>/engine/<version>-<platform>-<backend>/
11        engine-component.json        the manifest (below)
12        strata.exe | strata          the entrypoint (path from the manifest)
13        *.dll | *.so                 the GPU runtime libraries, hashed in the manifest too
14        BUILD.json                   optional, the engine's own build record
15
16Manifest (``engine-component.json``, schema 2; schema 1 packages still load). packaging/README.md has the full table::
17
18    {"schema_version": 2, "id": "strata-engine", "name": "strata-engine", "version": "0.1.45",
19     "platform": "linux-x86_64", "backend": "cuda", "archs": ["sm_86", "compute_89"],
20     "min_driver": {"nvidia": "580.65"}, "build_id": "be885026f9-cuda13.0", "min_runtime": "0.1.45",
21     "entrypoint": "strata", "files": [{"path": "strata", "sha256": "...", "bytes": 1}, ...],
22     "signature": null}                      # S6 fills it; verify_signature() is the hook
23
24Checks, in order, and each one names what failed:
25
26* the manifest parses strictly; file paths are relative, plain, and stay inside the component folder;
27* the platform and backend are combinations the project commits to (`components.BACKEND_MATRIX`);
28* the backend is the one this machine's GPU needs (detected, or asked for);
29* the signature (none yet; a verifier registered by S6 is called, and `STRATA_REQUIRE_SIGNED_COMPONENTS=1` refuses
30  an unsigned or unverifiable package);
31* every listed file exists with the listed size, and every file's SHA-256 matches (`verify(full=True)`, which is what
32  a start does; the quick listing/status path hashes only the entrypoint);
33* the runtime that is asking is new enough for `min_runtime`, and the GPU driver (when it can be read) for
34  `min_driver`. A package that fails an integrity check is `EngineIntegrityError`: nothing is started.
35
36Nothing here imports anything outside the standard library and `strata_control`.
37"""
38
39from __future__ import annotations
40
41import hashlib
42import json
43import os
44import time
45import re
46import shutil
47import subprocess
48from collections.abc import Callable
49from dataclasses import dataclass, field
50from pathlib import Path, PurePosixPath, PureWindowsPath
51
52from strata_control import acquisition, longpath
53from strata_control.targets import BACKEND_MATRIX, backend_supported, host_platform
54
55SCHEMA_VERSION = 2
56READABLE_SCHEMAS = (1, 2)           # schema 1 (S3's first packages: no archs/min_driver/build_id/signature) still loads
57MANIFEST = "engine-component.json"
58COMPONENT_ID = "strata-engine"
59ENV_DIR = "STRATA_COMPONENTS_DIR"
60ENV_BACKEND = "STRATA_ENGINE_BACKEND"
61ENV_REQUIRE_SIGNED = "STRATA_REQUIRE_SIGNED_COMPONENTS"
62#: The updater's state (``strata update``, ``strata components rollback``) lives in the component folder; the only member the
63#: start path reads is ``engine.pinned``: the folder a manual rollback chose, which wins over a newer installed package.
64UPDATE_STATE = Path(".updates") / "state.json"
65
66#: the version of the control/runtime that is asking; the app reads it from VERSION when it has one.
67RUNTIME_VERSION_FILE = Path(__file__).resolve().parents[1] / "VERSION"
68
69
70class EngineMissing(acquisition.AcquisitionRefused):
71    """No usable engine component for this machine. Nothing was fetched and nothing will be."""
72
73    code = "engine_component_missing"
74    exit_code = 5
75
76    def __init__(self, reason: str, root: Path | None = None, *, problems: list[dict] | None = None, notice: str | None = None):
77        self.reason = reason
78        self.root = root
79        self.problems = problems or []
80        self.plain_notice = notice
81        where = f" in {root}" if root else ""
82        RuntimeError.__init__(
83            self,
84            (f"{notice} (" if notice else "") + f"No engine for this PC was found{where}: {reason}" + (")" if notice else "") + ". The app never downloads an engine while it "
85            f"starts or serves. Download the engine for your GPU with Update engine in the app's Settings, or with "
86            f"`strata update` (or `strata install`) in the Terminal, or copy an engine package into the component folder.")
87        self.what = "the engine component"
88        self.command = "strata install"
89
90
91class EngineIntegrityError(EngineMissing):
92    """A package is installed but is not what its manifest says (a changed or missing file, a bad signature). Nothing
93    was started. The message names the file; the fix is to repair or reinstall the component, never to run it anyway."""
94
95    code = "engine_component_integrity"
96
97    def __init__(self, reason: str, root: Path | None = None, *, problems: list[dict] | None = None):
98        self.reason = reason
99        self.root = root
100        self.problems = problems or []
101        RuntimeError.__init__(
102            self,
103            f"The engine package failed its integrity check, so it was not started: {reason}. Repair or reinstall "
104            f"the engine component with Update engine in the app's Settings or `strata update` in the Terminal "
105            f"(`strata install` also works); the app never downloads one while it runs.")
106        self.what = "the engine component"
107        self.command = "strata install"
108
109
110class ComponentProblem(ValueError):
111    """One engine package is unusable. The message says why; the caller decides what to do next."""
112
113
114class IntegrityProblem(ComponentProblem):
115    """The package's files or signature do not match its manifest (as opposed to a package for another PC)."""
116
117
118@dataclass
119class EngineComponent:
120    id: str
121    version: str
122    platform: str
123    backend: str
124    entrypoint: str
125    files: tuple[tuple[str, str, int], ...]      # (relative path, sha256, bytes)
126    root: Path
127    min_runtime: str | None = None
128    archs: tuple[str, ...] = ()
129    notes: str = ""
130    min_driver: dict = field(default_factory=dict)       # {"nvidia": "580.65"}: the oldest driver the build runs on
131    build_id: str = ""                                    # which engine build this is (source commit + toolkit)
132    variant: str = ""                                     # optional tag when one backend has several builds (cuda13, cuda12)
133    signature: dict | None = None                         # S6: {"alg", "key_id", "value"} over signing_payload()
134    raw: dict = field(default_factory=dict, repr=False)   # the manifest as read, for the signature check
135    shape: str = ""                                       # the engine of one model shape (strata_control/shape_engine.py): its compiled geometry's name; "" for the Strata engine
136
137    @property
138    def exe(self) -> Path:
139        return self.root / self.entrypoint
140
141    @property
142    def cuda_archs(self) -> tuple[str, ...]:
143        return tuple(item for item in self.archs if item.startswith(("sm_", "compute_")))
144
145    @property
146    def hip_archs(self) -> tuple[str, ...]:
147        return tuple(item for item in self.archs if item.startswith("gfx"))
148
149    def to_dict(self) -> dict:
150        return {"id": self.id, "version": self.version, "platform": self.platform, "backend": self.backend,
151                "entrypoint": self.entrypoint, "exe": str(self.exe), "root": str(self.root),
152                "min_runtime": self.min_runtime, "archs": list(self.archs), "min_driver": dict(self.min_driver),
153                "build_id": self.build_id, "variant": self.variant, "signed": bool(self.signature), "file_count": len(self.files), "bytes": sum(item[2] for item in self.files),
154                **({"shape": self.shape} if self.shape else {})}
155
156
157def package_lib_dirs(folder) -> list[str]:
158    """The folders an engine package needs on the library path (``PATH`` on Windows, ``LD_LIBRARY_PATH`` elsewhere): its own folder, then
159    the ones its BUILD.json names in ``lib_dirs`` (relative; the Windows HIP package keeps the ROCm DLLs in ``rocm/bin``, which
160    rocblas.dll's kernel data and ``../.kpack`` are laid out around). Only folders that exist inside the package."""
161    folder = Path(folder)
162    dirs = [str(folder)]
163    try:
164        names = json.loads((folder / "BUILD.json").read_text(encoding="utf-8-sig")).get("lib_dirs") or []
165    except (OSError, ValueError, AttributeError):
166        names = []
167    for name in names:
168        if not isinstance(name, str) or not name or Path(name).is_absolute() or ".." in Path(name).parts:
169            continue
170        path = folder / name
171        if path.is_dir() and str(path) not in dirs:
172            dirs.append(str(path))
173    return dirs
174
175
176# ----------------------------------------------------------------------------------------------- where
177
178def components_dir(environ=None, *, windows: bool | None = None, home: Path | None = None) -> Path:
179    """The per-user component folder. ``STRATA_COMPONENTS_DIR`` wins (the app and the tests set it)."""
180    environ = os.environ if environ is None else environ
181    explicit = environ.get(ENV_DIR)
182    if explicit:
183        return Path(explicit)
184    windows = os.name == "nt" if windows is None else windows
185    home = Path.home() if home is None else home
186    if windows:
187        return Path(environ.get("LOCALAPPDATA") or str(home / "AppData" / "Local")) / "Strata" / "components"
188    return Path(environ.get("XDG_DATA_HOME") or str(home / ".local" / "share")) / "strata" / "components"
189
190
191def engine_dir(root: Path | None = None) -> Path:
192    return (root or components_dir()) / "engine"
193
194
195def newest_installed_version(root: Path | None = None) -> str | None:
196    """The highest engine version in the component folder, or None. A quick scan; nothing is hashed."""
197    try:
198        found, _ = scan(root)
199    except Exception:                                   # noqa: BLE001 - informational only
200        return None
201    return max((item.version for item in found), key=_version_key, default=None)
202
203
204def cached_notice(root: Path | None = None) -> str | None:
205    """"update available (x.y.z): run `strata update`" from the last explicit check, or None. Reads one small local file; it never
206    touches the network, so showing it at a start does not break the rule that only an update step downloads.
207
208    The notice belongs to the versions the check was made for: it is dropped when Control or the installed engine is not the one
209    recorded then (an app install, an update, a rollback), and an engine that is not newer than the installed one is never offered."""
210    offers = cached_offers(root)
211    parts = ([f"engine {offers['engine']}"] if offers.get("engine") else []) + ([f"app {offers['app']}"] if offers.get("app") else [])
212    return f"update available ({', '.join(parts)}): run `strata update`" if parts else None
213
214
215def cached_offers(root: Path | None = None) -> dict:
216    """What the last explicit check found newer, as {"engine": version|None, "app": version|None}; local reads only (the cached
217    check, the installed packages), never the network.  The same rules as `cached_notice`: it belongs to the Control and the packages it was made for,
218    and a package that is not newer than the installed one is never offered."""
219    base = root or components_dir()
220    none = {"engine": None, "app": None}
221    try:
222        last = (json.loads((base / UPDATE_STATE).read_text(encoding="utf-8-sig")).get("last_check") or {})
223    except (OSError, ValueError, AttributeError):
224        return none
225    if not isinstance(last, dict):
226        return none
227    control = runtime_version()
228    if "control" in last and last["control"] != control:
229        return none
230    engine, app = last.get("engine"), last.get("app")
231    installed = newest_installed_version(base)
232    if "engine_installed" in last and last["engine_installed"] != installed:
233        engine = None
234    if engine and installed and _version_key(str(engine)) <= _version_key(installed):
235        engine = None
236    return {"engine": engine or None, "app": app or None}
237
238
239def previous_folder(root: Path | None = None) -> str | None:
240    """The package folder the last update kept as the version to roll back to, if it is still installed."""
241    base = root or components_dir()
242    try:
243        value = json.loads((base / UPDATE_STATE).read_text(encoding="utf-8-sig"))["engine"]["previous"]
244    except (OSError, ValueError, KeyError, TypeError):
245        return None
246    if isinstance(value, str) and value and "/" not in value and "\\" not in value and (engine_dir(base) / value / MANIFEST).is_file():
247        return value
248    return None
249
250
251def pinned_folder(root: Path | None = None) -> str | None:
252    """The package folder a manual rollback pinned, or None. Read-only; a missing or damaged state file means no pin."""
253    try:
254        data = json.loads(((root or components_dir()) / UPDATE_STATE).read_text(encoding="utf-8-sig"))
255        value = data["engine"]["pinned"]
256        return value if isinstance(value, str) and value and "/" not in value and "\\" not in value else None
257    except (OSError, ValueError, KeyError, TypeError):
258        return None
259
260
261# ----------------------------------------------------------------------------------------------- manifest
262
263def _version_key(value: str) -> tuple:
264    return tuple(int(part) if part.isdigit() else 0 for part in re.split(r"[.\-+]", value))
265
266
267def _plain_relative(path: str) -> str:
268    if not isinstance(path, str) or not path or "\0" in path:
269        raise ComponentProblem("a file path is empty")
270    for flavour in (PurePosixPath(path), PureWindowsPath(path)):
271        if flavour.is_absolute() or flavour.drive or flavour.root:
272            raise ComponentProblem(f"file path {path!r} is absolute")
273        if ".." in flavour.parts:
274            raise ComponentProblem(f"file path {path!r} leaves the component folder")
275    return path.replace("\\", "/")
276
277
278def read_manifest(folder: Path, component_id: str = COMPONENT_ID) -> EngineComponent:
279    """The manifest of the package in `folder`. `component_id` is the component the caller expects: the Strata engine (``strata-engine``) or the engine of
280    one model shape (``strata-q4-lite``, strata_control/shape_engine.py). A package of one kind is never read as the other: the id and the ``shape`` member
281    must agree with it, so an older Control (which only knows ``strata-engine``) refuses a shape engine that was put into its engine folder by hand."""
282    path = folder / MANIFEST
283    try:
284        data = json.loads(path.read_text(encoding="utf-8-sig"))
285    except FileNotFoundError:
286        raise ComponentProblem(f"{MANIFEST} is missing") from None
287    except (OSError, ValueError) as exc:
288        raise ComponentProblem(f"{MANIFEST} is not valid JSON ({type(exc).__name__})") from None
289    if not isinstance(data, dict) or data.get("schema_version") not in READABLE_SCHEMAS:
290        raise ComponentProblem(f"{MANIFEST} has an unsupported schema_version")
291    schema = data["schema_version"]
292    if data.get("id") != component_id or data.get("name", component_id) != component_id:
293        raise ComponentProblem(f"{MANIFEST} is not an engine component (id {data.get('id')!r})")
294    shape = ""
295    if component_id == COMPONENT_ID:
296        if data.get("shape"):
297            raise ComponentProblem(f"{MANIFEST} is the engine of a model shape, not the Strata engine")
298    else:
299        from strata_control import shape_engine
300        shape = str(data.get("shape") or "")
301        if not shape or shape_engine.component_id(shape) != component_id:
302            raise ComponentProblem(f"{MANIFEST} names the shape {shape!r}, which is not the one of {component_id}")
303    for key in ("version", "platform", "backend", "entrypoint"):
304        if not isinstance(data.get(key), str) or not data[key]:
305            raise ComponentProblem(f"{MANIFEST} has no {key}")
306    if schema >= 2 and (not isinstance(data.get("build_id"), str) or not data["build_id"].strip()):
307        raise ComponentProblem(f"{MANIFEST} has no build_id")
308    if data["backend"] not in BACKEND_MATRIX:
309        raise ComponentProblem(f"unknown backend {data['backend']!r}")
310    files = data.get("files")
311    if not isinstance(files, list) or not files:
312        raise ComponentProblem(f"{MANIFEST} lists no files")
313    parsed = []
314    for item in files:
315        if not isinstance(item, dict):
316            raise ComponentProblem("a file entry is not an object")
317        rel = _plain_relative(item.get("path"))
318        digest = str(item.get("sha256", "")).lower()
319        if not re.fullmatch(r"[0-9a-f]{64}", digest):
320            raise ComponentProblem(f"{rel} has no valid sha256")
321        size = item.get("bytes")
322        if type(size) is not int or size < 0:
323            raise ComponentProblem(f"{rel} has no valid size")
324        parsed.append((rel, digest, size))
325    entry = _plain_relative(data["entrypoint"])
326    if entry not in {item[0] for item in parsed}:
327        raise ComponentProblem(f"the entrypoint {entry} is not in the file list")
328    if len({item[0] for item in parsed}) != len(parsed):
329        raise ComponentProblem(f"{MANIFEST} lists a file twice")
330    archs = data.get("archs", data.get("cuda_archs")) or []        # schema 1 called the list cuda_archs
331    if not isinstance(archs, list) or not all(isinstance(a, str) and a for a in archs):
332        raise ComponentProblem("archs must be a list of strings")
333    if schema >= 2 and data["backend"] != "cpu" and not archs:
334        raise ComponentProblem(f"{MANIFEST} lists no archs for a {data['backend']} engine")
335    driver = data.get("min_driver") or {}
336    if not isinstance(driver, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in driver.items()):
337        raise ComponentProblem("min_driver must map a vendor to a version string")
338    signature = data.get("signature")
339    if signature is not None and not (isinstance(signature, dict) and isinstance(signature.get("alg"), str)
340                                      and isinstance(signature.get("value"), str)):
341        raise ComponentProblem("signature must be null or {alg, key_id, value}")
342    return EngineComponent(
343        id=data["id"], version=data["version"], platform=data["platform"], backend=data["backend"],
344        entrypoint=entry, files=tuple(parsed), root=folder, min_runtime=data.get("min_runtime"),
345        archs=tuple(archs), notes=str(data.get("notes") or ""), min_driver=dict(driver),
346        build_id=str(data.get("build_id") or ""), variant=str(data.get("variant") or ""), signature=signature,
347        raw=data, shape=shape)
348
349
350def read_manifest_any(folder: Path) -> EngineComponent:
351    """The manifest of a package of either kind: the Strata engine, or the engine of a model shape (its id names the shape's component). For the release tools, which
352    handle both; the start path asks for the one it wants (read_manifest with the component's id)."""
353    try:
354        raw_id = json.loads((folder / MANIFEST).read_text(encoding="utf-8-sig")).get("id")
355    except (OSError, ValueError, AttributeError):
356        raw_id = None
357    if isinstance(raw_id, str) and raw_id != COMPONENT_ID:
358        from strata_control import shape_engine
359        if shape_engine.shape_of_component(raw_id):
360            return read_manifest(folder, raw_id)
361    return read_manifest(folder)
362
363
364# ----------------------------------------------------------------------------------------------- signature (S6)
365
366#: A signature verifier is ``fn(payload: bytes, signature: dict, component) -> None``; it raises
367#: ``IntegrityProblem`` (or any exception) when the signature does not hold. S6 registers one that checks the project's
368#: key; until then there is none, unsigned packages load (unless ``STRATA_REQUIRE_SIGNED_COMPONENTS=1``), and a package
369#: that carries a signature nobody can check is reported as "signature not verified", never as verified.
370_verifier: Callable[[bytes, dict, "EngineComponent"], None] | None = None
371
372
373def register_signature_verifier(fn: Callable[[bytes, dict, "EngineComponent"], None] | None) -> None:
374    global _verifier
375    _verifier = fn
376
377
378def signing_payload(manifest: dict) -> bytes:
379    """The bytes a signature covers: the manifest without its ``signature`` member, as canonical JSON (sorted keys,
380    no spaces, UTF-8). The file hashes are inside it, so one signature covers every file."""
381    body = {key: value for key, value in manifest.items() if key != "signature"}
382    return json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
383
384
385def verify_signature(component: "EngineComponent", environ=None) -> str:
386    """"verified", "unsigned" or "unverified" (signed, no verifier yet). Raises IntegrityProblem for a bad signature,
387    and for an unsigned or unverifiable package when ``STRATA_REQUIRE_SIGNED_COMPONENTS`` is set."""
388    environ = os.environ if environ is None else environ
389    required = environ.get(ENV_REQUIRE_SIGNED, "").strip().lower() in ("1", "true", "yes", "on")
390    if not component.signature:
391        if required:
392            raise IntegrityProblem("the package is not signed and this PC requires signed components")
393        return "unsigned"
394    if _verifier is None:
395        # the keys this build trusts (update_keys.json, plus the explicit test-key file) become the verifier on first use, so
396        # a signed package is verified on every start without anything having to register it first
397        from strata_control import signing
398        try:
399            signing.ensure_component_verifier()
400        except signing.SignatureError as exc:
401            raise IntegrityProblem(f"this PC's update keys cannot be read ({exc})") from None
402    if _verifier is None:
403        if required:
404            raise IntegrityProblem("the package is signed but this build cannot check signatures yet")
405        return "unverified"
406    try:
407        _verifier(signing_payload(component.raw), component.signature, component)
408    except IntegrityProblem:
409        raise
410    except Exception as exc:
411        raise IntegrityProblem(f"the signature does not verify ({type(exc).__name__}: {exc})") from None
412    return "verified"
413
414
415def _sha256(path: Path) -> str:
416    digest = hashlib.sha256()
417    with path.open("rb") as stream:
418        for block in iter(lambda: stream.read(1 << 20), b""):
419            digest.update(block)
420    return digest.hexdigest()
421
422
423def _hash_settled(path: Path, digest: str) -> str | None:
424    """The file's SHA-256, read again once when the first read fails or differs: a file that was just unpacked or is
425    being scanned by a virus checker can read short or locked for a moment, and a failure must not be kept (#3488)."""
426    actual = None
427    for attempt in range(2):
428        try:
429            actual = _sha256(path)
430        except OSError:
431            actual = None
432        if actual == digest:
433            break
434        if attempt == 0:
435            time.sleep(0.5)
436    return actual
437
438
439def verify(component: EngineComponent, *, full: bool = False) -> None:
440    """Raise IntegrityProblem unless the files are what the manifest says. `full` hashes every file; without it only
441    the entrypoint is hashed (sizes are always checked)."""
442    # extended-length paths: under a long user name an AMD engine's files pass 259 characters, which Windows (long paths off)
443    # reports as "missing" for an ordinary path
444    folder = longpath.long_path(component.root)
445    root = folder.resolve()
446    for rel, digest, size in component.files:
447        target = folder / rel
448        try:
449            info = target.lstat()
450        except OSError:
451            raise IntegrityProblem(f"{rel} is missing") from None
452        if target.is_symlink() or not target.is_file():
453            raise IntegrityProblem(f"{rel} is not a regular file")
454        if not longpath.same_tree(target.resolve(), root):
455            raise IntegrityProblem(f"{rel} resolves outside the component folder")
456        if info.st_size != size:
457            raise IntegrityProblem(f"{rel} is {info.st_size} bytes, the manifest says {size}")
458        if full or rel == component.entrypoint:
459            actual = _hash_settled(target, digest)
460            if actual != digest:
461                raise IntegrityProblem(f"{rel} does not match its recorded SHA-256 (expected {digest[:12]}, "
462                                       f"found {actual[:12] if actual else 'unreadable'})")
463    if os.name != "nt" and not os.access(component.exe, os.X_OK):
464        raise IntegrityProblem(f"{component.entrypoint} is not executable")
465
466
467def runtime_version() -> str | None:
468    try:
469        return RUNTIME_VERSION_FILE.read_text(encoding="utf-8").strip() or None
470    except OSError:
471        return None
472
473
474# ----------------------------------------------------------------------------------------------- the GPU
475
476def split_backend(value) -> tuple[str, str]:
477    """(backend, variant) for a name the person typed: "hip-rdna2" is the hip family and its rdna2 package (the way the feed labels an AMD
478    package, #4013), "hip" is the family alone, a make's own name is its family ("amd" -> hip, "nvidia" -> cuda, "intel" -> sycl: the words
479    `strata launch --backend` takes, so `strata update --backend amd` means the same), any other name is returned as it is with no variant."""
480    name = str(value or "").strip().lower()
481    if name not in BACKEND_MATRIX and name.startswith("hip-") and len(name) > 4:
482        return "hip", name[4:]
483    if name not in BACKEND_MATRIX and name in BACKEND_ALIASES:
484        return BACKEND_ALIASES[name], ""
485    return name, ""
486
487
488BACKEND_ALIASES = {"nvidia": "cuda", "amd": "hip", "intel": "sycl", "arc": "sycl"}
489SAVED_KEY = "engine_backend"
490
491
492def clean_backend_name(value) -> str:
493    """What the person typed for --backend, as an engine family name: 'intel' -> 'sycl', 'NVIDIA' -> 'cuda'; '' when it names none."""
494    name = str(value or "").strip().lower()
495    name = BACKEND_ALIASES.get(name, name)
496    return name if name in ("cuda", "hip", "sycl") else ""
497
498
499def saved_backend(environ=None) -> str | None:
500    """The engine family the person chose with `strata launch --backend` (kept in the settings file), or None. It is ignored when this PC
501    has no card of that make (the choice was made on other hardware): the PC's own detection then decides again."""
502    try:
503        from strata_control import discovery
504        value = clean_backend_name(discovery._read_json(discovery.own_settings_file(environ)).get(SAVED_KEY))        # noqa: SLF001
505    except Exception:                                    # noqa: BLE001 - a settings file that cannot be read is no choice
506        return None
507    if not value:
508        return None
509    here = gpu_makes_present()
510    return value if (not here or value in here) else None
511
512
513def save_backend(value, environ=None) -> Path | None:
514    """Keep (or, with a falsy value, forget) the person's engine family choice in the settings file, leaving every other key as it is."""
515    from strata_control import discovery
516    path = discovery.own_settings_file(environ)
517    data = discovery._read_json(path)                    # noqa: SLF001
518    name = clean_backend_name(value)
519    if name:
520        data[SAVED_KEY] = name
521    else:
522        data.pop(SAVED_KEY, None)
523    path.parent.mkdir(parents=True, exist_ok=True)
524    path.write_text(json.dumps(data, indent=1), encoding="utf-8")
525    return path
526
527
528def detect_backend(environ=None) -> tuple[str | None, str]:
529    """(backend, how) for this machine: the engine family its GPU needs. Bounded, read-only probes of tools that are
530    already installed; ``STRATA_ENGINE_BACKEND`` overrides (the tests and the support desk use it)."""
531    environ = os.environ if environ is None else environ
532    forced = split_backend(environ.get(ENV_BACKEND, ""))[0]      # "hip-rdna2" starts the hip family (the package choice reads the variant)
533    if forced:
534        if forced not in BACKEND_MATRIX:
535            raise ComponentProblem(f"{ENV_BACKEND}={forced!r} is not one of {', '.join(sorted(BACKEND_MATRIX))}")
536        return forced, "environment"
537    chosen = saved_backend(environ)
538    if chosen:
539        return chosen, "saved choice"
540    if host_platform().startswith("macos"):
541        return "metal", "platform"
542    # Windows: the display adapters are the machine's own statement about which cards it has, so they decide first. A leftover
543    # nvidia-smi from a card that was taken out, or a toolkit installed for another card, must never outvote them: that is how an
544    # AMD PC was given a CUDA engine (#3688). A tool is only asked about a make that has an adapter here.
545    adapters = windows_display_adapters() if host_platform().startswith("windows") else []
546    present = adapter_makes(adapters)
547    if present:
548        return _first_make(present), "display adapters"
549    probes = (("cuda", ("nvidia-smi", "--query-gpu=name", "--format=csv,noheader")),
550              ("hip", ("rocminfo",) if os.name != "nt" else ("hipInfo",)),
551              ("sycl", ("sycl-ls",)))
552    vendors_here = {a.get("vendor") for a in adapters}
553    vendor_of = {"cuda": "10de", "hip": "1002", "sycl": "8086"}
554    for backend, command in probes:
555        if vendors_here and vendor_of[backend] not in vendors_here:
556            continue                                  # the adapters list no card of this make: a tool that answers is a leftover
557        tool = shutil.which(command[0])
558        if not tool:
559            continue
560        try:
561            done = subprocess.run([tool, *command[1:]], capture_output=True, timeout=8, text=True, errors="replace",
562                                  creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
563        except (OSError, subprocess.SubprocessError):
564            continue
565        if done.returncode == 0 and (done.stdout or "").strip():
566            if backend == "hip" and "gfx" not in done.stdout:
567                continue
568            if backend == "sycl" and "level_zero" not in done.stdout.lower() and "gpu" not in done.stdout.lower():
569                continue
570            return backend, command[0]
571    found = _drm_vendor_backend() if os.name != "nt" else _windows_vendor_backend()
572    if found:
573        return found, "sysfs pci vendor" if os.name != "nt" else "display adapters"
574    return None, "no GPU tool answered"
575
576
577def _first_make(makes) -> str:
578    """The make Strata uses when a PC has cards of several: NVIDIA, then AMD, then Intel (the order of every probe)."""
579    return next(m for m in ("cuda", "hip", "sycl") if m in makes)
580
581
582def adapter_makes(adapters: list[dict] | None) -> set[str]:
583    """The engine families the Windows display adapters call for: cuda (an NVIDIA adapter), hip (an AMD card, not an integrated
584    Radeon), sycl (an Intel adapter). Empty when the list is empty. Read-only, nothing is run."""
585    makes = set()
586    for adapter in adapters or []:
587        vendor = adapter.get("vendor")
588        if vendor == "10de":
589            makes.add("cuda")
590        elif vendor == "8086":
591            makes.add("sycl")
592    if windows_amd_cards(adapters or []):
593        makes.add("hip")
594    return makes
595
596
597def gpu_makes_present() -> set[str]:
598    """The engine families this PC has a graphics card for, from the display adapters (Windows) or the PCI vendors (Linux); empty
599    when that cannot be read. Used to keep an update on the make the installation was built for (#3688)."""
600    if os.name == "nt":
601        return adapter_makes(windows_display_adapters())
602    return _drm_vendor_makes()
603
604
605def _drm_vendor_makes(root: str = "/sys/class/drm") -> set[str]:
606    vendors = set()
607    try:
608        for card in sorted(Path(root).glob("card[0-9]*")):
609            if "-" not in card.name:
610                try:
611                    vendors.add((card / "device" / "vendor").read_text().strip().lower())
612                except OSError:
613                    continue
614    except OSError:
615        return set()
616    return {backend for vendor, backend in (("0x10de", "cuda"), ("0x1002", "hip"), ("0x8086", "sycl")) if vendor in vendors}
617
618
619def wsl_amd_note(backend: str | None, dev_root: str = "/dev", wsl: bool | None = None) -> str | None:
620    """Under WSL (the GPU is reached through /dev/dxg, there is no /dev/kfd) the Linux AMD (HIP) engines hang: librocdxg 1.2.2
621    never completes a barrier-AND packet, so the first GPU command never returns. A plain sentence with one next step for that
622    case, else None. A warning only: the caller goes on (recommend, never force)."""
623    if backend != "hip":
624        return None
625    if wsl is None:
626        import platform
627        import sys
628        wsl = sys.platform.startswith("linux") and "microsoft" in platform.uname().release.lower()
629    if not wsl or not Path(dev_root, "dxg").exists() or Path(dev_root, "kfd").exists():
630        return None
631    return ("The AMD engines do not run under WSL yet: the driver layer WSL uses for the card never finishes a GPU command, so the engine "
632            "would hang at its first step. Use the Strata app or Terminal for Windows, which run the AMD engine directly.")
633
634
635#: The most own memory an integrated GPU reports: its BIOS carve-out (a Raphael iGPU reported 512 MiB, #4971). A card below this is not the one this
636#: PC's engine is chosen for while another card is present. A card that reports no size (NVIDIA and Intel write no such file) is never called integrated
637#: by its missing file; a large unified-memory APU (a Strix Halo with a 32 GiB carve-out) reports a large size and counts as a card.
638INTEGRATED_MAX_VRAM_MIB = 2048
639
640
641def _own_vram(card: Path) -> bool | None:
642    """Whether a display adapter has its own memory above `INTEGRATED_MAX_VRAM_MIB`; None when it reports no size. Read-only sysfs."""
643    try:
644        total = int((card / "device" / "mem_info_vram_total").read_text().strip())
645    except (OSError, ValueError):
646        return None
647    return total > INTEGRATED_MAX_VRAM_MIB * 1024 * 1024
648
649
650def _drm_vendor_backend(root: str = "/sys/class/drm") -> str | None:
651    """Linux without the vendor tools on PATH (a HIP box that runs ROCm from Python wheels has no rocminfo): the PCI
652    vendor of the display adapters decides. NVIDIA 0x10de -> cuda, AMD 0x1002 -> hip, Intel 0x8086 -> sycl, in that
653    order. An integrated GPU does not decide while another make has a card that is not integrated (#4971: a 512 MiB
654    Radeon APU made the whole PC an AMD machine beside the user's Intel Arc); when every card is integrated the old
655    order stands. Read-only sysfs, nothing is run."""
656    if not os.path.isdir(root):
657        return None
658    cards: dict[str, list[bool | None]] = {}
659    try:
660        for card in sorted(Path(root).glob("card[0-9]*")):
661            if "-" in card.name:
662                continue
663            try:
664                vendor = (card / "device" / "vendor").read_text().strip().lower()
665            except OSError:
666                continue
667            cards.setdefault(vendor, []).append(_own_vram(card))
668    except OSError:
669        return None
670    order = (("0x10de", "cuda"), ("0x1002", "hip"), ("0x8086", "sycl"))
671    if not any(v in cards for v, _ in order):
672        return None
673    # a make whose every card is positively integrated (a small own-memory reading) is skipped while another make has a card that is not
674    decisive = [v for v, _ in order if any(flag is not False for flag in cards.get(v, []))]
675    chosen = decisive[0] if decisive else next(v for v, _ in order if v in cards)
676    return dict(order)[chosen]
677
678
679#: Windows AMD cards by PCI device id (VEN_1002), the same table as setup.py's _WIN_AMD_DID (tests/terminal/test_engine_component.py
680#: keeps the two equal): the architecture Strata runs the card as. Integrated Radeons are not in it (the one APU that is supported,
681#: Strix Halo, 0x1586, is in WIN_AMD_UMA_IDS), so an integrated Radeon beside a card never counts as "the GPU".
682WIN_AMD_DEVICE_ARCH = {0x744C: "gfx1100", 0x7448: "gfx1100", 0x745E: "gfx1100", 0x747E: "gfx1101", 0x7480: "gfx1102",
683                       0x7590: "gfx1200", 0x7550: "gfx1201", 0x7551: "gfx1201",
684                       0x73BF: "gfx1030", 0x73AF: "gfx1030", 0x73A5: "gfx1030", 0x73DF: "gfx1031"}
685WIN_AMD_UMA_IDS = {0x1586: "gfx1151"}                                   # Strix Halo: unified memory, supported
686WIN_AMD_IGPU_IDS = {0x150E, 0x1114, 0x1902, 0x15BF, 0x15C8, 0x164F, 0x1900, 0x1901, 0x1681, 0x1638, 0x1636, 0x15D8, 0x15E7}
687_WIN_DISPLAY_CLASS = r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}"
688
689
690def gfx_from_name(name: str) -> str:
691    """The AMD architecture a card's marketing name implies ("" when the name says nothing): the fallback when the PCI device id is
692    not in the table. Only names Strata knows a gfx for; an integrated Radeon with no supported build still maps (it then simply
693    fits no package)."""
694    text = re.sub(r"\s+", " ", str(name or "")).upper()
695    if "AMD" not in text and "RADEON" not in text and "RYZEN" not in text:
696        return ""
697    if re.search(r"\b(?:8060S|8050S)\b", text) or "RYZEN AI MAX" in text:
698        return "gfx1151"
699    if re.search(r"\bR9700\b|\bR97\d\d\b|\bAI PRO R97", text) or re.search(r"\bRX 9070\b", text):
700        return "gfx1201"
701    if re.search(r"\bRX 906\d\b|\bR96\d\d\b|\bAI PRO R96", text):
702        return "gfx1200"
703    found = re.search(r"\b(?:RX |W)(7[5-9]\d\d)\b", text)
704    if found:
705        series = int(found.group(1)) // 100
706        return {79: "gfx1100", 78: "gfx1101", 77: "gfx1101", 76: "gfx1102", 75: "gfx1102"}[series]
707    if re.search(r"\b(?:780M|760M|740M)\b", text):
708        return "gfx1103"
709    if re.search(r"\b(?:880M|890M)\b", text):
710        return "gfx1150"
711    if re.search(r"\b860M\b", text):
712        return "gfx1152"
713    found = re.search(r"\bRX (6\d{3})\b", text)
714    if found:
715        number = int(found.group(1))
716        if number >= 6800:
717            return "gfx1030"
718        if number in (6700, 6750) or "6700 XT" in text:
719            return "gfx1031"
720        if 6600 <= number < 6700:
721            return "gfx1032"
722        if number in (6500, 6400):
723            return "gfx1034"
724    return ""
725
726
727_CIM_CACHE: dict = {}
728CIM_CACHE_SECONDS = 120.0        # one answer (a failed or timed-out one too) serves every caller of this process for this long
729
730
731def _windows_adapters_cim() -> list[dict]:
732    """The CIM query below, asked once per process and 2 minutes: one `strata launch --plan` asked it 18 times (17 s on a healthy PC) and, with the WMI
733    service stuck, 18 times its 15 s timeout, far beyond the 60 s the app waits for Control (#4975). The adapters do not change inside a command."""
734    if os.name != "nt":
735        return []
736    now = time.monotonic()
737    hit = _CIM_CACHE.get("adapters")
738    if hit is not None and now - hit[0] < CIM_CACHE_SECONDS:
739        return [dict(a) for a in hit[1]]
740    found = _windows_adapters_cim_query()
741    _CIM_CACHE["adapters"] = (now, found)
742    return [dict(a) for a in found]
743
744
745def _windows_adapters_cim_query() -> list[dict]:
746    """Second source when the registry key lists nothing: PowerShell's Win32_VideoController (PNPDeviceID has VEN_/DEV_). It can fail for
747    a limited account, so every failure is an empty answer."""
748    if os.name != "nt":
749        return []
750    shell = shutil.which("powershell") or shutil.which("pwsh")
751    if not shell:
752        return []
753    try:
754        done = subprocess.run([shell, "-NoProfile", "-NonInteractive", "-Command",
755                               "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Get-CimInstance Win32_VideoController | ForEach-Object { $_.PNPDeviceID + '|' + $_.Name + '|' + $_.AdapterRAM }"],
756                              capture_output=True, text=True, errors="replace", timeout=15, stdin=subprocess.DEVNULL,
757                              creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
758    except (OSError, subprocess.SubprocessError):
759        return []
760    found = []
761    for line in (done.stdout or "").splitlines():
762        match = re.search(r"VEN_([0-9A-F]{4})&DEV_([0-9A-F]{4})", line, re.I)
763        if not match:
764            continue
765        parts = line.split("|")
766        ram = int(parts[2]) if len(parts) > 2 and parts[2].strip().isdigit() else 0
767        found.append({"vendor": match.group(1).lower(), "device": int(match.group(2), 16),
768                      "name": parts[1].strip() if len(parts) > 1 else "",
769                      "vram_gb": (ram / 2 ** 30) if ram > 0 else 0.0})
770    return found
771
772
773def windows_display_adapters() -> list[dict]:
774    """The display adapters Windows has a driver for: the display-class registry key (readable without admin and without running
775    anything), then Win32_VideoController when the key lists nothing: {"vendor": "10de"|"1002"|"8086"|..., "device": int, "name",
776    "vram_gb"}. Empty off Windows or when neither can be read."""
777    found = _windows_display_adapters_registry()
778    if len({a.get("vendor") for a in found} & {"10de", "1002"}) > 1:
779        # The registry keeps the driver entry of a card that was taken out (an NVIDIA card swapped for a Radeon, #3892): when two makes are
780        # listed, only the adapters Windows reports as present now count.
781        present = {(a["vendor"], a["device"]) for a in _windows_adapters_cim()}
782        now = [a for a in found if (a["vendor"], a["device"]) in present]
783        if now:
784            return now
785    return found or _windows_adapters_cim()
786
787
788def _windows_display_adapters_registry() -> list[dict]:
789    found: list[dict] = []
790    try:
791        import winreg
792        cls = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, _WIN_DISPLAY_CLASS)
793    except (ImportError, OSError):
794        return found
795    index = 0
796    while True:
797        try:
798            sub = winreg.EnumKey(cls, index)
799        except OSError:
800            break
801        index += 1
802        if not sub.isdigit():
803            continue
804        try:
805            key = winreg.OpenKey(cls, sub)
806        except OSError:
807            continue
808        values = {}
809        for name in ("DriverDesc", "MatchingDeviceId", "HardwareInformation.qwMemorySize"):
810            try:
811                values[name] = winreg.QueryValueEx(key, name)[0]
812            except OSError:
813                pass
814        match = re.search(r"VEN_([0-9A-F]{4})&DEV_([0-9A-F]{4})", str(values.get("MatchingDeviceId") or ""), re.I)
815        if not match:
816            continue
817        memory = values.get("HardwareInformation.qwMemorySize")
818        if isinstance(memory, bytes):
819            memory = int.from_bytes(memory[:8], "little")
820        found.append({"vendor": match.group(1).lower(), "device": int(match.group(2), 16),
821                      "name": str(values.get("DriverDesc") or ""),
822                      "vram_gb": (int(memory) / 2 ** 30) if isinstance(memory, int) and memory > 0 else 0.0})
823    return found
824
825
826def windows_amd_cards(adapters: list[dict] | None = None) -> list[dict]:
827    """The AMD graphics cards (not an integrated Radeon) among the Windows display adapters, each with the architecture Strata
828    runs it as ("" when the id is not in the table but the adapter has 3 GB or more of its own memory, so it is no APU)."""
829    cards = []
830    for adapter in (windows_display_adapters() if adapters is None else adapters):
831        if adapter.get("vendor") != "1002":
832            continue
833        device = adapter.get("device")
834        arch = WIN_AMD_DEVICE_ARCH.get(device) or WIN_AMD_UMA_IDS.get(device) or ""
835        if not arch and device not in WIN_AMD_IGPU_IDS:
836            guess = gfx_from_name(adapter.get("name", ""))              # a card whose id is not in the table: its name says
837            if guess in ("gfx1103", "gfx1150", "gfx1152"):               # (those are integrated Radeons)
838                continue
839            arch = guess
840        if not arch and (device in WIN_AMD_IGPU_IDS or float(adapter.get("vram_gb") or 0) < 3.0):
841            continue                                                    # an integrated Radeon (512 MB of carve-out)
842        cards.append({"arch": arch, "name": adapter.get("name", ""), "device": device})
843    return cards
844
845
846def _windows_vendor_backend(adapters: list[dict] | None = None) -> str | None:
847    """Windows without nvidia-smi / hipInfo on PATH: the display adapters decide, NVIDIA first, then an AMD card (an AMD
848    integrated GPU alone is not one), as on Linux. Read-only registry, nothing is run."""
849    adapters = windows_display_adapters() if adapters is None else adapters
850    if any(a.get("vendor") == "10de" for a in adapters):
851        return "cuda"
852    if windows_amd_cards(adapters):
853        return "hip"
854    return None
855
856
857def cuda_archs_present(environ=None) -> list[str]:
858    """``sm_XX`` for each NVIDIA card nvidia-smi reports; empty when it cannot say."""
859    found = []
860    for line in _smi_query("compute_cap"):
861        match = re.fullmatch(r"(\d+)\.(\d+)", line.strip())
862        if match:
863            found.append(f"sm_{match.group(1)}{match.group(2)}")
864    return found
865
866
867def hip_archs_present(kfd_root: str | None = None) -> list[str]:
868    """``gfxNNNN`` for each AMD GPU the Linux kernel driver lists (``gfx_target_version`` is MMmmss: gfx1201 = 120001,
869    gfx1103 = 110003, gfx90a = 90010); Windows: from the display adapters' PCI ids (integrated Radeons left out); empty when
870    it cannot say (no amdgpu/kfd, no permission, an id not in the table)."""
871    if kfd_root is None:
872        if os.name == "nt":
873            return sorted({c["arch"] for c in windows_amd_cards() if c["arch"]})
874        kfd_root = "/sys/class/kfd/kfd/topology/nodes"
875    found = []
876    try:
877        nodes = sorted(Path(kfd_root).iterdir())
878    except OSError:
879        return []
880    for node in nodes:
881        try:
882            for line in (node / "properties").read_text(encoding="utf-8").splitlines():
883                key, _, value = line.partition(" ")
884                if key == "gfx_target_version" and value.strip().isdigit() and int(value) > 0:
885                    number = int(value)
886                    found.append(f"gfx{number // 10000}{number // 100 % 100:x}{number % 100:x}")
887        except OSError:
888            continue
889    return found
890
891
892def hip_archs_from_pci(drm_root: str = "/sys/class/drm", lspci: bool = True) -> list[str]:
893    """Linux, third probe for the AMD architectures when the kernel driver's topology (hip_archs_present) and rocminfo said nothing (no
894    /sys/class/kfd access in an AppImage or a container, no ROCm tools installed): the PCI ids of the AMD display devices, in sysfs
895    (``card0/device/{vendor,device}``) and then ``lspci -nn`` (``[1002:744c]``), mapped through the same tables the Windows probe uses.
896    An integrated Radeon and an id the tables do not know give nothing. Read-only; empty when it cannot say."""
897    ids: list[int] = []
898    try:
899        for card in sorted(Path(drm_root).glob("card[0-9]*")):
900            if "-" in card.name:                                            # card0-DP-1 and the like are connectors
901                continue
902            try:
903                vendor = (card / "device" / "vendor").read_text().strip().lower()
904                device = (card / "device" / "device").read_text().strip().lower()
905            except OSError:
906                continue
907            if vendor == "0x1002" and device.startswith("0x"):
908                ids.append(int(device, 16))
909    except OSError:
910        pass
911    if not ids and lspci and os.name != "nt":
912        tool = shutil.which("lspci")
913        if tool:
914            try:
915                done = subprocess.run([tool, "-nn"], capture_output=True, text=True, errors="replace", timeout=10)
916                for line in (done.stdout or "").splitlines():
917                    if re.search(r"VGA|Display|3D", line):
918                        found = re.search(r"\[1002:([0-9a-f]{4})\]", line, re.I)
919                        if found:
920                            ids.append(int(found.group(1), 16))
921            except (OSError, subprocess.SubprocessError):
922                pass
923    return sorted({WIN_AMD_DEVICE_ARCH.get(i) or WIN_AMD_UMA_IDS.get(i) or "" for i in ids} - {""})
924
925
926_SMI_CACHE: dict = {}
927SMI_CACHE_SECONDS = 30.0         # a card's capability and the driver version do not change inside one command
928
929
930def _smi_query(field_name: str) -> list[str]:
931    """nvidia-smi for one field, asked once per process and 30 s: one `strata launch --plan` on Windows with an engine installed started it 19 times (10 for the
932    compute capability, 9 for the driver version), and a stuck driver would have cost its 8 s timeout each time. A failed answer is kept for the same time."""
933    now = time.monotonic()
934    hit = _SMI_CACHE.get(field_name)
935    if hit is not None and now - hit[0] < SMI_CACHE_SECONDS:
936        return list(hit[1])
937    found = _smi_query_now(field_name)
938    _SMI_CACHE[field_name] = (now, found)
939    return list(found)
940
941
942def _smi_query_now(field_name: str) -> list[str]:
943    tool = shutil.which("nvidia-smi")
944    if not tool:
945        return []
946    try:
947        done = subprocess.run([tool, f"--query-gpu={field_name}", "--format=csv,noheader"], capture_output=True,
948                              timeout=8, text=True, errors="replace", creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
949    except (OSError, subprocess.SubprocessError):
950        return []
951    return [line.strip() for line in (done.stdout or "").splitlines() if line.strip()] if done.returncode == 0 and done.stdout else []
952
953
954def nvidia_driver_version() -> str | None:
955    """The NVIDIA driver version nvidia-smi reports (the oldest one when several cards disagree); None when unreadable."""
956    versions = _smi_query("driver_version")
957    if not versions:                      # Linux without nvidia-smi (Fedora: it is in xorg-x11-drv-nvidia-cuda): the kernel module says
958        try:
959            found = re.search(r"Kernel Module\s+(\d+(?:\.\d+)+)", Path("/proc/driver/nvidia/version").read_text())
960            versions = [found.group(1)] if found else []
961        except OSError:
962            versions = []
963    return min(versions, key=_version_key) if versions else None
964
965
966def _capability(number: str) -> tuple[int, int]:
967    """``86`` -> (8, 6), ``120`` -> (12, 0): the last digit is the minor version."""
968    return int(number[:-1] or 0), int(number[-1])
969
970
971def arch_covers(archs, present: list[str]) -> bool:
972    """Whether a build with `archs` (``sm_86`` = machine code for that card, ``compute_89`` = PTX that any card of
973    that generation or newer can JIT) can run on at least one of the `present` cards (``sm_XX``).
974    Machine code also runs on a card of the same major version with an equal or newer minor version (CUDA's cubin
975    compatibility rule): ``sm_86`` code runs on an ``sm_89`` card (RTX 40) but not on ``sm_80`` (older minor),
976    ``sm_90`` (other major) or ``sm_75``; ``sm_120`` code runs on ``sm_121``."""
977    cards = {item[3:] for item in present if item.startswith("sm_") and item[3:].isdigit()}
978    if not cards:
979        return True              # cannot tell: not a refusal
980    for arch in archs:
981        kind, _, number = arch.partition("_")
982        if not number.isdigit():
983            continue
984        if kind == "sm" and any(number == card or (len(number) > 1 and len(card) > 1 and _capability(card)[0] == _capability(number)[0]
985                                                   and _capability(card)[1] >= _capability(number)[1]) for card in cards):
986            return True
987        if kind == "compute" and any(int(card) >= int(number) for card in cards):
988            return True
989    return False
990
991
992def arch_native(archs, present: list[str]) -> bool:
993    """Whether a build with `archs` holds machine code made for one of the `present` cards itself (``sm_89`` on an ``sm_89`` card),
994    not only code that runs there through the same-major rule of `arch_covers` (``sm_86`` on an RTX 40) or as PTX. Only a tie-breaker
995    between packages that fit equally: a package with the card's own image is taken first (#3935)."""
996    cards = {item[3:] for item in present if item.startswith("sm_") and item[3:].isdigit()}
997    return any(arch.startswith("sm_") and arch[3:] in cards for arch in archs)
998
999
1000# ----------------------------------------------------------------------------------------------- resolve
1001
1002def scan(root: Path | None = None, component_id: str = COMPONENT_ID) -> tuple[list[EngineComponent], list[dict]]:
1003    """Every readable engine package in the folder, and the ones that were not (with the reason). `component_id`: see read_manifest."""
1004    folder = engine_dir(root)
1005    found, problems = [], []
1006    try:
1007        entries = sorted(item for item in folder.iterdir() if item.is_dir() and not item.name.startswith("."))
1008    except OSError:
1009        return [], []
1010    for entry in entries[:64]:
1011        try:
1012            found.append(read_manifest(entry, component_id))
1013        except ComponentProblem as exc:
1014            problems.append({"folder": str(entry), "problem": str(exc)})
1015    return found, problems
1016
1017
1018def driver_notice(have: str | None, need: str) -> str:
1019    """The plain sentence for an NVIDIA driver that is too old for every engine on this PC."""
1020    major = str(need).split(".")[0]
1021    how = ("download it from nvidia.com/drivers" if os.name == "nt" else
1022           "on Ubuntu open Software & Updates > Additional Drivers, or run: sudo ubuntu-drivers install")
1023    return (f"Your NVIDIA graphics driver ({have}) is too old for Strata. Install driver {major} or newer ({how}), "
1024            "restart the computer and open Strata again.")
1025
1026
1027#: The AMD card families a person knows by the box they bought, for the one plain line when a build is for another family.
1028HIP_FAMILIES = (("RX 9000", ("gfx1200", "gfx1201")), ("RX 7000", ("gfx1100", "gfx1101", "gfx1102")), ("RX 6000", ("gfx1030", "gfx1031")),
1029                ("Ryzen AI Max", ("gfx1151",)))
1030
1031
1032def hip_family(arch: str) -> str:
1033    return next((name for name, archs in HIP_FAMILIES if arch in archs), arch)
1034
1035
1036#: AMD architectures no ready-made engine package of this release covers. Empty since 0.2.2: the RX 6000 series (gfx1030 / gfx1031) has
1037#: its own package (Linux `rx6000`, Windows `rdna2`; built, not tested on a real RX 6000 card). The mechanism stays for the next card family
1038#: that has none: a family in this table gets the plain "no ready-made engine" line instead of "Ask for the X build".
1039NO_PACKAGE_HIP: dict[str, str] = {}
1040NO_PACKAGE_SENTENCE = ("This release has no ready-made Strata engine for the AMD {0} series. Strata can only run on it with an engine built for "
1041                       "that card (docs/AMD_HIP.md, \"RDNA2\").")
1042
1043
1044def no_package_note(archs) -> str | None:
1045    """One plain sentence when some of these architectures (gfx1030 ...) have no ready-made package in this release, else None."""
1046    families = sorted({NO_PACKAGE_HIP[a] for a in archs if a in NO_PACKAGE_HIP})
1047    return NO_PACKAGE_SENTENCE.format(" and ".join(families)) if families else None
1048
1049
1050def hip_preference(archs) -> int:
1051    """Tie-break between two AMD engine packages of one version that both cover a PC (a computer with an RX 7900 beside an RX 6800): the
1052    RX 6000 package (gfx103x code only) never wins over another family's, so adding it changed nothing for a PC that was served before."""
1053    archs = [str(a) for a in archs or ()]
1054    return 0 if archs and all(a.startswith("gfx103") for a in archs) else 1
1055
1056
1057def arch_notice(built: tuple[str, ...], here: list[str]) -> str:
1058    """The plain sentence for an AMD engine that has code for other cards than this computer's (a tester build for another card)."""
1059    if here and all(a in NO_PACKAGE_HIP for a in here):      # asking for "the RX 6000 build" would send the person to one that does not exist
1060        have = sorted({hip_family(a) for a in here})
1061        return (f"This computer has an AMD {' and '.join(have)} card ({', '.join(sorted(set(here)))}). {no_package_note(here)}")
1062    built_for = sorted({hip_family(a) for a in built})
1063    have = sorted({hip_family(a) for a in here})
1064    make = lambda names: " and ".join(names)  # noqa: E731
1065    return (f"This build of Strata is for AMD {make(built_for)} cards. This computer has an AMD {make(have)} card ({', '.join(sorted(set(here)))}). "
1066            f"Ask for the {make(have)} build.")
1067
1068
1069RELEASES_URL = "https://github.com/Niko1221/Strata/releases"
1070MAKE_NAMES = {"cuda": "NVIDIA", "hip": "AMD", "sycl": "Intel"}
1071
1072
1073def wrong_make_notice(built: str, archs: tuple[str, ...], here: str) -> str:
1074    """The plain sentence for a build made for another make of graphics card than this computer has (an AMD build on an NVIDIA PC)."""
1075    families = sorted({hip_family(a) for a in archs if any(a in group for _, group in HIP_FAMILIES)})
1076    built_for = f"AMD {' and '.join(families)}" if built == "hip" and families else MAKE_NAMES.get(built, built)
1077    make = MAKE_NAMES.get(here, here)
1078    return f"This Strata is for {built_for} cards. Your PC has an {make} card: download the {make} version from {RELEASES_URL}"
1079
1080
1081def resolve(root: Path | None = None, *, backend: str | None = None, target: str | None = None,
1082            full: bool = False, runtime: str | None = None, component_id: str = COMPONENT_ID) -> EngineComponent:
1083    """The engine to start on this machine, or `EngineMissing` / `EngineIntegrityError`. Never downloads, never creates
1084    the folder. `full=True` hashes every file (a start does); the default is the quick check the listings use."""
1085    base = root or components_dir()
1086    target = target or host_platform()
1087    found, problems = scan(base, component_id)
1088    if not found and not problems:
1089        raise EngineMissing("the component folder holds no engine package", base)
1090    wanted = split_backend(backend)[0] or None if backend else backend     # "amd" / "hip-rx6000" name the hip family
1091    how = "requested"
1092    if wanted is None:
1093        wanted, how = detect_backend()
1094    if wanted is None:
1095        # no GPU tool answered: only a CPU engine can be started
1096        wanted = "cpu"
1097    usable, reasons, broken = [], [], []
1098    compatible, driver_blocked, arch_blocked = 0, [], []
1099    archs_here = cuda_archs_present() if wanted == "cuda" else []
1100    driver_here = nvidia_driver_version() if wanted == "cuda" else None
1101    hip_here = hip_archs_present() if wanted == "hip" else []
1102    have_runtime = runtime if runtime is not None else runtime_version()
1103    for item in found:
1104        label = f"{item.version} {item.platform}-{item.backend}"
1105        if item.platform != target:
1106            reasons.append(f"{label} is for {item.platform}, this PC is {target}")
1107            continue
1108        ok, why = backend_supported(item.backend, target)
1109        if not ok:
1110            reasons.append(f"{label}: {why}")
1111            continue
1112        if item.backend != wanted:
1113            reasons.append(f"{label} is a {item.backend} engine, this PC needs {wanted} ({how})")
1114            continue
1115        compatible += 1
1116        if item.min_runtime and have_runtime and _version_key(have_runtime) < _version_key(item.min_runtime):
1117            reasons.append(f"{label} needs control {item.min_runtime} or newer, this is {have_runtime}")
1118            continue
1119        if item.cuda_archs and archs_here and not arch_covers(item.cuda_archs, archs_here):
1120            reasons.append(f"{label} has code for {', '.join(item.cuda_archs)}, this PC's GPU is "
1121                           f"{', '.join(archs_here)}")
1122            continue
1123        if item.hip_archs and hip_here and not set(item.hip_archs) & set(hip_here):
1124            reasons.append(f"{label} has code for {', '.join(item.hip_archs)}, this PC's GPU is "
1125                           f"{', '.join(hip_here)}")
1126            arch_blocked.append(item)
1127            continue
1128        need = item.min_driver.get("nvidia")
1129        if need and driver_here and _version_key(driver_here) < _version_key(need):
1130            reasons.append(f"{label} needs NVIDIA driver {need} or newer, this PC has {driver_here}")
1131            driver_blocked.append(need)
1132            continue
1133        try:
1134            verify_signature(item)
1135            verify(item, full=full)
1136        except ComponentProblem as exc:
1137            reasons.append(f"{label}: {exc}")
1138            broken.append(f"{label}: {exc}")
1139            continue
1140        usable.append(item)
1141    if not usable:
1142        everything = reasons + [p["folder"] + ": " + p["problem"] for p in problems]
1143        if broken and len(broken) == len(reasons):       # every package that fits this PC failed its integrity check
1144            raise EngineIntegrityError("; ".join(broken), base, problems=problems)
1145        plain = None
1146        if arch_blocked and len(arch_blocked) == compatible and not broken:      # every engine that fits this PC is built for other cards
1147            plain = arch_notice(tuple(sorted({a for item in arch_blocked for a in item.hip_archs})), hip_here)
1148        if plain is None and not compatible and not broken and wanted in MAKE_NAMES:       # every engine here is for another make of card
1149            here_target = [item for item in found if item.platform == target]
1150            other = [item for item in here_target if item.backend in MAKE_NAMES and item.backend != wanted]
1151            if other and len(other) == len(here_target):
1152                top = max(other, key=lambda item: _version_key(item.version))
1153                plain = wrong_make_notice(top.backend, top.archs, wanted)
1154        missing = EngineMissing("; ".join(everything) or "nothing matched", base, problems=problems, notice=plain)
1155        if driver_blocked and len(driver_blocked) == compatible and not broken:
1156            # the only thing in the way is the NVIDIA driver: one plain line that names the version to install
1157            missing.driver_notice = driver_notice(driver_here, min(driver_blocked, key=_version_key))
1158        raise missing
1159    pin = pinned_folder(base)
1160    if pin:                                   # a manual rollback: the pinned package wins while it is usable
1161        for item in usable:
1162            if item.root.name == pin:
1163                return item
1164    # newest version first; with equal versions the build for the newer driver (the CUDA 13 build beside the CUDA 12 one)
1165    return max(usable, key=lambda item: (_version_key(item.version), _version_key(item.min_driver.get("nvidia", "0")),
1166                                         hip_preference(item.hip_archs), arch_native(item.cuda_archs, archs_here)))
1167
1168
1169#: A run config can name its engine as "component:strata-engine" instead of a path: the server then asks the
1170#: component folder for the engine that fits this PC when it starts (a config written before an engine update keeps
1171#: working after it, and a config copied to another PC finds that PC's engine).
1172REFERENCE_PREFIX = "component:"
1173
1174
1175def is_reference(value: object) -> bool:
1176    return isinstance(value, str) and value.startswith(REFERENCE_PREFIX)
1177
1178
1179def expand(value: str, cfg: dict | None = None, *, root: Path | None = None, full: bool = True) -> str:
1180    """The engine path for `value`: unchanged when it is a path, resolved when it is a component reference. This is the
1181    start path, so every file's SHA-256 is checked (`full`): a changed file refuses the start instead of running."""
1182    if not is_reference(value):
1183        return value
1184    name = value[len(REFERENCE_PREFIX):]
1185    backend = (cfg or {}).get("backend")
1186    if name not in ("", COMPONENT_ID):
1187        from strata_control import shape_engine
1188        shape = shape_engine.shape_of_component(name)
1189        if shape is None:
1190            raise EngineMissing(f"the run config names an unknown component {name!r}", root or components_dir())
1191        try:                                              # the engine of a model shape: its own folder, never the Strata engine's
1192            return str(resolve(shape_engine.root(shape, root), backend=backend if backend in BACKEND_MATRIX else None, full=full, component_id=name).exe)
1193        except EngineIntegrityError:
1194            raise
1195        except EngineMissing as exc:
1196            raise shape_engine.ShapeEngineMissing(shape, exc.reason, shape_engine.root(shape, root), problems=exc.problems, title=(cfg or {}).get("shape_title")) from None
1197    return str(resolve(root, backend=backend if backend in BACKEND_MATRIX else None, full=full).exe)
1198
1199
1200def status(root: Path | None = None, *, backend: str | None = None, full: bool = False) -> dict:
1201    """What `strata components engine` and the app's host report. Always answers; never raises for a missing engine."""
1202    base = root or components_dir()
1203    found, problems = scan(base)
1204    backend = split_backend(backend)[0] or None if backend else backend    # `components engine --backend amd` = the hip family
1205    try:
1206        detected, how = detect_backend()
1207    except ComponentProblem as exc:
1208        detected, how = None, str(exc)
1209    report = {"schema_version": 1, "components_dir": str(base), "platform": host_platform(),
1210              "backend": backend or detected, "backend_source": "requested" if backend else how,
1211              "installed": [item.to_dict() for item in found], "problems": problems,
1212              "engine": None, "usable": False, "notice": None, "acquires": False,
1213              "pinned": pinned_folder(base), "previous": previous_folder(base), "update_notice": cached_notice(base),
1214              "update_available": cached_offers(base)}
1215    try:
1216        chosen = resolve(base, backend=backend, full=full)
1217        report["engine"] = chosen.to_dict()
1218        report["usable"] = True
1219    except EngineMissing as exc:
1220        report["notice"] = getattr(exc, "driver_notice", None) or getattr(exc, "plain_notice", None) or str(exc)
1221    try:                                              # the engines of model shapes (strata_control/shape_engine.py): reported only when this PC has one
1222        from strata_control import shape_engine
1223        shapes = shape_engine.status(root)
1224        if shapes:
1225            report["shapes"] = shapes
1226    except Exception:                                 # noqa: BLE001 - informational only
1227        pass
1228    return report