Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

control: resolve the engine from a local component folder (no download path), strata components engine, package_engine.py; the component fetcher refuses under STRATA_NO_ACQUIRE

Niko1221dc859b26ffd5
diff --git a/packaging/package_engine.py b/packaging/package_engine.py
new file mode 100644
index 000000000..d29704289
--- /dev/null
+++ b/packaging/package_engine.py
@@ -0,0 +1,105 @@
+#!/usr/bin/env python3
+"""Make a local, unpublished engine package for the component folder (strata_control/engine_component.py).
+
+ python packaging/package_engine.py --src <folder with strata[.exe] and its libraries> --backend cuda \
+ --version 0.1.45 [--platform linux-x86_64] --out <components>/engine [--cuda-arch sm_86 ...]
+
+The result is one folder `<out>/<version>-<platform>-<backend>/` holding the engine binary, the shared libraries
+next to it, BUILD.json when the source has one, and `engine-component.json` (every file's SHA-256 and size). It
+is the thing the app resolves; it is not signed, not published, and nothing here uploads it. Publishing and
+signing are stream S6.
+
+Files taken from --src: the entrypoint, every `*.dll` / `*.so` / `*.so.*` / `*.dylib` in the same folder (the GPU
+runtime libraries the engine loads from beside itself), `BUILD.json`, and `LICENSE*` when present. Nothing else.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import platform
+import shutil
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+
+from strata_control import engine_component as ec # noqa: E402
+from strata_control.components import BACKEND_MATRIX, host_platform # noqa: E402
+
+
+def sha256(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as stream:
+ for block in iter(lambda: stream.read(1 << 20), b""):
+ digest.update(block)
+ return digest.hexdigest()
+
+
+def wanted(path: Path) -> bool:
+ name = path.name.lower()
+ return (name.endswith((".dll", ".so", ".dylib")) or ".so." in name or name == "build.json"
+ or name.startswith("license"))
+
+
+def build(src: Path, backend: str, version: str, target: str, out: Path, *, entry: str | None = None,
+ cuda_archs: tuple[str, ...] = (), min_runtime: str | None = None, notes: str = "") -> Path:
+ if backend not in BACKEND_MATRIX:
+ raise SystemExit(f"unknown backend {backend!r}")
+ entrypoint = entry or ("strata.exe" if target.startswith("windows") else "strata")
+ if not (src / entrypoint).is_file():
+ raise SystemExit(f"{src / entrypoint} does not exist")
+ folder = out / f"{version}-{target}-{backend}"
+ if folder.exists():
+ raise SystemExit(f"{folder} already exists; remove it first (packages are immutable)")
+ staging = out / f".{folder.name}.partial"
+ if staging.exists():
+ shutil.rmtree(staging)
+ staging.mkdir(parents=True)
+ try:
+ names = [entrypoint] + sorted(p.name for p in src.iterdir() if p.is_file() and p.name != entrypoint and wanted(p))
+ files = []
+ for name in names:
+ shutil.copy2(src / name, staging / name)
+ files.append({"path": name, "sha256": sha256(staging / name), "bytes": (staging / name).stat().st_size})
+ manifest = {"schema_version": ec.SCHEMA_VERSION, "id": ec.COMPONENT_ID, "version": version,
+ "platform": target, "backend": backend, "entrypoint": entrypoint, "files": files}
+ if min_runtime:
+ manifest["min_runtime"] = min_runtime
+ if cuda_archs:
+ manifest["cuda_archs"] = list(cuda_archs)
+ if notes:
+ manifest["notes"] = notes
+ (staging / ec.MANIFEST).write_text(json.dumps(manifest, indent=1) + "\n", encoding="utf-8")
+ ec.verify(ec.read_manifest(staging), full=True)
+ staging.rename(folder)
+ except BaseException:
+ shutil.rmtree(staging, ignore_errors=True)
+ raise
+ return folder
+
+
+def main(argv: list[str] | None = None) -> int:
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--src", required=True, type=Path)
+ ap.add_argument("--backend", required=True, choices=sorted(BACKEND_MATRIX))
+ ap.add_argument("--version", required=True)
+ ap.add_argument("--platform", default=None, help="default: this machine")
+ ap.add_argument("--out", required=True, type=Path, help="the component folder's engine/ directory")
+ ap.add_argument("--entrypoint", default=None)
+ ap.add_argument("--cuda-arch", action="append", default=[], help="e.g. sm_86; repeat for several")
+ ap.add_argument("--min-runtime", default=None)
+ ap.add_argument("--notes", default="")
+ a = ap.parse_args(argv)
+ a.out.mkdir(parents=True, exist_ok=True)
+ folder = build(a.src, a.backend, a.version, a.platform or host_platform(), a.out, entry=a.entrypoint,
+ cuda_archs=tuple(a.cuda_arch), min_runtime=a.min_runtime, notes=a.notes)
+ total = sum(p.stat().st_size for p in folder.iterdir())
+ print(f"{folder} ({total / (1 << 20):.1f} MiB, {len(list(folder.iterdir()))} files)")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/strata_cli/cli.py b/strata_cli/cli.py
index b405aa627..550ea8237 100644
--- a/strata_cli/cli.py
+++ b/strata_cli/cli.py
@@ -127,6 +127,13 @@ def parser() -> argparse.ArgumentParser:
components_backend = components_sp.add_parser(
"backends", help="the OS and backend combinations that are committed to, and what is not")
components_backend.add_argument("--output", choices=("human", "json"), default="human")
+ components_engine = components_sp.add_parser(
+ "engine", help="which engine package in the local component folder this PC would start (never downloads)")
+ components_engine.add_argument("--backend", default=None, help="ask for one backend family instead of detecting it")
+ components_engine.add_argument("--components-dir", default=None,
+ help="the component folder (default: STRATA_COMPONENTS_DIR or the per-user folder)")
+ components_engine.add_argument("--full", action="store_true", help="hash every file, not only the entrypoint")
+ components_engine.add_argument("--output", choices=("human", "json"), default="human")
models = sp.add_parser("models", help="inspect setup-written local model run configs")
models_sp = models.add_subparsers(dest="models_command", required=True)
models_list = models_sp.add_parser("list", help="list local installed-model config candidates")
@@ -1649,6 +1656,33 @@ def _components_plan(a: argparse.Namespace) -> int:
return 0
+def _components_engine(a: argparse.Namespace) -> int:
+ """Which engine package the local component folder offers this PC. Read-only; a missing engine is a notice with a
+ non-zero exit (5), never a fetch."""
+ from strata_control import engine_component
+ root = Path(a.components_dir) if a.components_dir else None
+ try:
+ report = engine_component.status(root, backend=a.backend, full=a.full)
+ except engine_component.ComponentProblem as exc:
+ return _error(str(exc), 2, a.output == "json")
+ code = 0 if report["usable"] else 5
+ if a.output == "json":
+ print(json.dumps({"schema_version": 1, "ok": report["usable"], **report}, ensure_ascii=False))
+ return code
+ print(f"component folder {report['components_dir']}")
+ print(f"this PC {report['platform']}, {report['backend'] or 'no GPU found'} ({report['backend_source']})")
+ for item in report["installed"]:
+ print(f" installed {item['version']} {item['platform']}-{item['backend']} {item['root']}")
+ for item in report["problems"]:
+ print(f" unusable {item['folder']}: {item['problem']}")
+ if report["usable"]:
+ print(f"engine {report['engine']['exe']} (version {report['engine']['version']})")
+ else:
+ print(report["notice"], file=sys.stderr)
+ print("nothing was downloaded or changed")
+ return code
+
+
def _components_backends(a: argparse.Namespace) -> int:
"""The committed OS and backend matrix, so an unsupported combination is visible up front."""
from strata_control import components
@@ -1695,6 +1729,8 @@ def _run(a: argparse.Namespace) -> int:
return _components_plan(a)
if a.command == "components" and a.components_command == "backends":
return _components_backends(a)
+ if a.command == "components" and a.components_command == "engine":
+ return _components_engine(a)
if a.command in ("doctor", "components"):
return _doctor(a)
if a.command == "models":
diff --git a/strata_control/components.py b/strata_control/components.py
index 483726c1a..26be458a8 100644
--- a/strata_control/components.py
+++ b/strata_control/components.py
@@ -568,6 +568,8 @@ class ComponentStore:
are kept under `partial/` and a ranged request picks up where it stopped. The result is
verified by the caller before anything is unpacked.
"""
+ from strata_control import acquisition
+ acquisition.require(f"the download of {artifact.name}", "strata install")
import urllib.error
import urllib.request
partial = self.root / "partial" / artifact.name
diff --git a/strata_control/engine_component.py b/strata_control/engine_component.py
new file mode 100644
index 000000000..921433bdd
--- /dev/null
+++ b/strata_control/engine_component.py
@@ -0,0 +1,362 @@
+"""Finding the engine package for this machine in a local component folder. There is no download path.
+
+The engine (the C++ `strata` binary and its GPU runtime libraries) is a separate, independently versioned
+component. The desktop app and the terminal start whatever is installed in the component folder; nothing here, and
+nothing on the start path, fetches an engine. A missing or unusable engine is a typed error that says what to do
+(`EngineMissing`, exit code 5, the same family as `acquisition.AcquisitionRefused`) and never an attempt to get one.
+
+Layout (``components_dir()``)::
+
+ <components>/engine/<version>-<platform>-<backend>/
+ engine-component.json the manifest (below)
+ strata.exe | strata the entrypoint (path from the manifest)
+ *.dll | *.so the GPU runtime libraries, hashed in the manifest too
+ BUILD.json optional, the engine's own build record
+
+Manifest (``engine-component.json``)::
+
+ {"schema_version": 1, "id": "strata-engine", "version": "0.1.45", "platform": "windows-x86_64",
+ "backend": "cuda", "entrypoint": "strata.exe", "min_runtime": "0.1.45",
+ "cuda_archs": ["sm_86"], # optional: GPU architectures the build contains
+ "files": [{"path": "strata.exe", "sha256": "...", "bytes": 1}, ...]}
+
+Checks, in order, and each one names what failed:
+
+* the manifest parses strictly; file paths are relative, plain, and stay inside the component folder;
+* the platform and backend are combinations the project commits to (`components.BACKEND_MATRIX`);
+* the backend is the one this machine's GPU needs (detected, or asked for);
+* every listed file exists with the listed size (always, it is cheap), and the entrypoint's SHA-256 matches;
+ `verify(full=True)` hashes every file (a few hundred MB of libraries: used by Repair and by tests);
+* the runtime that is asking is new enough for `min_runtime`.
+
+Nothing here imports anything outside the standard library and `strata_control`.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import re
+import shutil
+import subprocess
+from dataclasses import dataclass, field
+from pathlib import Path, PurePosixPath, PureWindowsPath
+
+from strata_control import acquisition
+from strata_control.components import BACKEND_MATRIX, backend_supported, host_platform
+
+SCHEMA_VERSION = 1
+MANIFEST = "engine-component.json"
+COMPONENT_ID = "strata-engine"
+ENV_DIR = "STRATA_COMPONENTS_DIR"
+ENV_BACKEND = "STRATA_ENGINE_BACKEND"
+
+#: the version of the control/runtime that is asking; the app reads it from VERSION when it has one.
+RUNTIME_VERSION_FILE = Path(__file__).resolve().parents[1] / "VERSION"
+
+
+class EngineMissing(acquisition.AcquisitionRefused):
+ """No usable engine component for this machine. Nothing was fetched and nothing will be."""
+
+ code = "engine_component_missing"
+ exit_code = 5
+
+ def __init__(self, reason: str, root: Path | None = None, *, problems: list[dict] | None = None):
+ self.reason = reason
+ self.root = root
+ self.problems = problems or []
+ where = f" in {root}" if root else ""
+ RuntimeError.__init__(
+ self,
+ f"No engine for this PC was found{where}: {reason}. The app never downloads an engine while it "
+ f"starts or serves. Install the engine component for your GPU from the Terminal "
+ f"(`strata install`) or copy an engine package into the component folder.")
+ self.what = "the engine component"
+ self.command = "strata install"
+
+
+class ComponentProblem(ValueError):
+ """One engine package is unusable. The message says why; the caller decides what to do next."""
+
+
+@dataclass
+class EngineComponent:
+ id: str
+ version: str
+ platform: str
+ backend: str
+ entrypoint: str
+ files: tuple[tuple[str, str, int], ...] # (relative path, sha256, bytes)
+ root: Path
+ min_runtime: str | None = None
+ cuda_archs: tuple[str, ...] = ()
+ notes: str = ""
+
+ @property
+ def exe(self) -> Path:
+ return self.root / self.entrypoint
+
+ def to_dict(self) -> dict:
+ return {"id": self.id, "version": self.version, "platform": self.platform, "backend": self.backend,
+ "entrypoint": self.entrypoint, "exe": str(self.exe), "root": str(self.root),
+ "min_runtime": self.min_runtime, "cuda_archs": list(self.cuda_archs),
+ "file_count": len(self.files), "bytes": sum(item[2] for item in self.files)}
+
+
+# ----------------------------------------------------------------------------------------------- where
+
+def components_dir(environ=None, *, windows: bool | None = None, home: Path | None = None) -> Path:
+ """The per-user component folder. ``STRATA_COMPONENTS_DIR`` wins (the app and the tests set it)."""
+ environ = os.environ if environ is None else environ
+ explicit = environ.get(ENV_DIR)
+ if explicit:
+ return Path(explicit)
+ windows = os.name == "nt" if windows is None else windows
+ home = Path.home() if home is None else home
+ if windows:
+ return Path(environ.get("LOCALAPPDATA") or str(home / "AppData" / "Local")) / "Strata" / "components"
+ return Path(environ.get("XDG_DATA_HOME") or str(home / ".local" / "share")) / "strata" / "components"
+
+
+def engine_dir(root: Path | None = None) -> Path:
+ return (root or components_dir()) / "engine"
+
+
+# ----------------------------------------------------------------------------------------------- manifest
+
+def _version_key(value: str) -> tuple:
+ return tuple(int(part) if part.isdigit() else 0 for part in re.split(r"[.\-+]", value))
+
+
+def _plain_relative(path: str) -> str:
+ if not isinstance(path, str) or not path or "\0" in path:
+ raise ComponentProblem("a file path is empty")
+ for flavour in (PurePosixPath(path), PureWindowsPath(path)):
+ if flavour.is_absolute() or flavour.drive or flavour.root:
+ raise ComponentProblem(f"file path {path!r} is absolute")
+ if ".." in flavour.parts:
+ raise ComponentProblem(f"file path {path!r} leaves the component folder")
+ return path.replace("\\", "/")
+
+
+def read_manifest(folder: Path) -> EngineComponent:
+ path = folder / MANIFEST
+ try:
+ data = json.loads(path.read_text(encoding="utf-8-sig"))
+ except FileNotFoundError:
+ raise ComponentProblem(f"{MANIFEST} is missing") from None
+ except (OSError, ValueError) as exc:
+ raise ComponentProblem(f"{MANIFEST} is not valid JSON ({type(exc).__name__})") from None
+ if not isinstance(data, dict) or data.get("schema_version") != SCHEMA_VERSION:
+ raise ComponentProblem(f"{MANIFEST} has an unsupported schema_version")
+ if data.get("id") != COMPONENT_ID:
+ raise ComponentProblem(f"{MANIFEST} is not an engine component (id {data.get('id')!r})")
+ for key in ("version", "platform", "backend", "entrypoint"):
+ if not isinstance(data.get(key), str) or not data[key]:
+ raise ComponentProblem(f"{MANIFEST} has no {key}")
+ if data["backend"] not in BACKEND_MATRIX:
+ raise ComponentProblem(f"unknown backend {data['backend']!r}")
+ files = data.get("files")
+ if not isinstance(files, list) or not files:
+ raise ComponentProblem(f"{MANIFEST} lists no files")
+ parsed = []
+ for item in files:
+ if not isinstance(item, dict):
+ raise ComponentProblem("a file entry is not an object")
+ rel = _plain_relative(item.get("path"))
+ digest = str(item.get("sha256", "")).lower()
+ if not re.fullmatch(r"[0-9a-f]{64}", digest):
+ raise ComponentProblem(f"{rel} has no valid sha256")
+ size = item.get("bytes")
+ if type(size) is not int or size < 0:
+ raise ComponentProblem(f"{rel} has no valid size")
+ parsed.append((rel, digest, size))
+ entry = _plain_relative(data["entrypoint"])
+ if entry not in {item[0] for item in parsed}:
+ raise ComponentProblem(f"the entrypoint {entry} is not in the file list")
+ archs = data.get("cuda_archs") or []
+ if not isinstance(archs, list) or not all(isinstance(a, str) for a in archs):
+ raise ComponentProblem("cuda_archs must be a list of strings")
+ return EngineComponent(
+ id=data["id"], version=data["version"], platform=data["platform"], backend=data["backend"],
+ entrypoint=entry, files=tuple(parsed), root=folder, min_runtime=data.get("min_runtime"),
+ cuda_archs=tuple(archs), notes=str(data.get("notes") or ""))
+
+
+def _sha256(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as stream:
+ for block in iter(lambda: stream.read(1 << 20), b""):
+ digest.update(block)
+ return digest.hexdigest()
+
+
+def verify(component: EngineComponent, *, full: bool = False) -> None:
+ """Raise ComponentProblem unless the files are what the manifest says. `full` hashes every file."""
+ root = component.root.resolve()
+ for rel, digest, size in component.files:
+ target = component.root / rel
+ try:
+ info = target.lstat()
+ except OSError:
+ raise ComponentProblem(f"{rel} is missing") from None
+ if target.is_symlink() or not target.is_file():
+ raise ComponentProblem(f"{rel} is not a regular file")
+ try:
+ target.resolve().relative_to(root)
+ except ValueError:
+ raise ComponentProblem(f"{rel} resolves outside the component folder") from None
+ if info.st_size != size:
+ raise ComponentProblem(f"{rel} is {info.st_size} bytes, the manifest says {size}")
+ if (full or rel == component.entrypoint) and _sha256(target) != digest:
+ raise ComponentProblem(f"{rel} does not match its recorded SHA-256")
+ if os.name != "nt" and not os.access(component.exe, os.X_OK):
+ raise ComponentProblem(f"{component.entrypoint} is not executable")
+
+
+def runtime_version() -> str | None:
+ try:
+ return RUNTIME_VERSION_FILE.read_text(encoding="utf-8").strip() or None
+ except OSError:
+ return None
+
+
+# ----------------------------------------------------------------------------------------------- the GPU
+
+def detect_backend(environ=None) -> tuple[str | None, str]:
+ """(backend, how) for this machine: the engine family its GPU needs. Bounded, read-only probes of tools that are
+ already installed; ``STRATA_ENGINE_BACKEND`` overrides (the tests and the support desk use it)."""
+ environ = os.environ if environ is None else environ
+ forced = environ.get(ENV_BACKEND, "").strip().lower()
+ if forced:
+ if forced not in BACKEND_MATRIX:
+ raise ComponentProblem(f"{ENV_BACKEND}={forced!r} is not one of {', '.join(sorted(BACKEND_MATRIX))}")
+ return forced, "environment"
+ if host_platform().startswith("macos"):
+ return "metal", "platform"
+ probes = (("cuda", ("nvidia-smi", "--query-gpu=name", "--format=csv,noheader")),
+ ("hip", ("rocminfo",) if os.name != "nt" else ("hipInfo",)),
+ ("sycl", ("sycl-ls",)))
+ for backend, command in probes:
+ tool = shutil.which(command[0])
+ if not tool:
+ continue
+ try:
+ done = subprocess.run([tool, *command[1:]], capture_output=True, timeout=8, text=True,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
+ except (OSError, subprocess.SubprocessError):
+ continue
+ if done.returncode == 0 and done.stdout.strip():
+ if backend == "hip" and "gfx" not in done.stdout:
+ continue
+ if backend == "sycl" and "level_zero" not in done.stdout.lower() and "gpu" not in done.stdout.lower():
+ continue
+ return backend, command[0]
+ return None, "no GPU tool answered"
+
+
+def cuda_archs_present(environ=None) -> list[str]:
+ """``sm_XX`` for each NVIDIA card nvidia-smi reports; empty when it cannot say."""
+ tool = shutil.which("nvidia-smi")
+ if not tool:
+ return []
+ try:
+ done = subprocess.run([tool, "--query-gpu=compute_cap", "--format=csv,noheader"], capture_output=True,
+ timeout=8, text=True, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
+ except (OSError, subprocess.SubprocessError):
+ return []
+ found = []
+ for line in done.stdout.split():
+ match = re.fullmatch(r"(\d+)\.(\d+)", line.strip())
+ if match:
+ found.append(f"sm_{match.group(1)}{match.group(2)}")
+ return found
+
+
+# ----------------------------------------------------------------------------------------------- resolve
+
+def scan(root: Path | None = None) -> tuple[list[EngineComponent], list[dict]]:
+ """Every readable engine package in the folder, and the ones that were not (with the reason)."""
+ folder = engine_dir(root)
+ found, problems = [], []
+ try:
+ entries = sorted(item for item in folder.iterdir() if item.is_dir() and not item.name.startswith("."))
+ except OSError:
+ return [], []
+ for entry in entries[:64]:
+ try:
+ found.append(read_manifest(entry))
+ except ComponentProblem as exc:
+ problems.append({"folder": str(entry), "problem": str(exc)})
+ return found, problems
+
+
+def resolve(root: Path | None = None, *, backend: str | None = None, target: str | None = None,
+ full: bool = False, runtime: str | None = None) -> EngineComponent:
+ """The engine to start on this machine, or `EngineMissing`. Never downloads, never creates the folder."""
+ base = root or components_dir()
+ target = target or host_platform()
+ found, problems = scan(base)
+ if not found and not problems:
+ raise EngineMissing("the component folder holds no engine package", base)
+ wanted = backend
+ how = "requested"
+ if wanted is None:
+ wanted, how = detect_backend()
+ if wanted is None:
+ # no GPU tool answered: only a CPU engine can be started
+ wanted = "cpu"
+ usable, reasons = [], []
+ archs_here = cuda_archs_present() if wanted == "cuda" else []
+ have_runtime = runtime if runtime is not None else runtime_version()
+ for item in found:
+ label = f"{item.version} {item.platform}-{item.backend}"
+ if item.platform != target:
+ reasons.append(f"{label} is for {item.platform}, this PC is {target}")
+ continue
+ ok, why = backend_supported(item.backend, target)
+ if not ok:
+ reasons.append(f"{label}: {why}")
+ continue
+ if item.backend != wanted:
+ reasons.append(f"{label} is a {item.backend} engine, this PC needs {wanted} ({how})")
+ continue
+ if item.min_runtime and have_runtime and _version_key(have_runtime) < _version_key(item.min_runtime):
+ reasons.append(f"{label} needs control {item.min_runtime} or newer, this is {have_runtime}")
+ continue
+ if item.cuda_archs and archs_here and not set(archs_here) & set(item.cuda_archs):
+ reasons.append(f"{label} has code for {', '.join(item.cuda_archs)}, this PC's GPU is "
+ f"{', '.join(archs_here)}")
+ continue
+ try:
+ verify(item, full=full)
+ except ComponentProblem as exc:
+ reasons.append(f"{label}: {exc}")
+ continue
+ usable.append(item)
+ if not usable:
+ raise EngineMissing("; ".join(reasons + [p["folder"] + ": " + p["problem"] for p in problems])
+ or "nothing matched", base, problems=problems)
+ return max(usable, key=lambda item: _version_key(item.version))
+
+
+def status(root: Path | None = None, *, backend: str | None = None, full: bool = False) -> dict:
+ """What `strata components engine` and the app's host report. Always answers; never raises for a missing engine."""
+ base = root or components_dir()
+ found, problems = scan(base)
+ try:
+ detected, how = detect_backend()
+ except ComponentProblem as exc:
+ detected, how = None, str(exc)
+ report = {"schema_version": 1, "components_dir": str(base), "platform": host_platform(),
+ "backend": backend or detected, "backend_source": "requested" if backend else how,
+ "installed": [item.to_dict() for item in found], "problems": problems,
+ "engine": None, "usable": False, "notice": None, "acquires": False}
+ try:
+ chosen = resolve(base, backend=backend, full=full)
+ report["engine"] = chosen.to_dict()
+ report["usable"] = True
+ except EngineMissing as exc:
+ report["notice"] = str(exc)
+ return report
diff --git a/tests/terminal/test_engine_component.py b/tests/terminal/test_engine_component.py
new file mode 100644
index 000000000..e48e6a93b
--- /dev/null
+++ b/tests/terminal/test_engine_component.py
@@ -0,0 +1,306 @@
+"""Engine resolution from a local component folder: which package is chosen, why one is refused, and that nothing is
+ever fetched. Every folder here is a throwaway; no GPU tool is run (the backend is always given or forced)."""
+
+import contextlib
+import hashlib
+import io
+import json
+import os
+import socket
+import subprocess
+import sys
+import tempfile
+import unittest
+import urllib.request
+from pathlib import Path
+from unittest import mock
+
+from strata_cli import cli
+from strata_control import acquisition, components, engine_component as ec
+
+WINDOWS = os.name == "nt"
+HERE = components.host_platform()
+EXE = "strata.exe" if WINDOWS else "strata"
+
+
+def make_package(root: Path, *, version="0.1.45", platform=None, backend="cuda", archs=(), min_runtime=None,
+ extra=None, entry=None) -> Path:
+ """A fake engine package the way packaging/package_engine.py lays one out."""
+ platform = platform or HERE
+ entry = entry or EXE
+ folder = root / "engine" / f"{version}-{platform}-{backend}"
+ folder.mkdir(parents=True)
+ payload = {entry: b"MZ-not-a-real-engine-" + version.encode(), "cudart64_13.dll" if WINDOWS else "libcudart.so.13":
+ b"runtime-library-bytes" * 50, "BUILD.json": json.dumps({"version": version}).encode()}
+ payload.update(extra or {})
+ files = []
+ for name, data in payload.items():
+ (folder / name).write_bytes(data)
+ files.append({"path": name, "sha256": hashlib.sha256(data).hexdigest(), "bytes": len(data)})
+ if not WINDOWS:
+ (folder / entry).chmod(0o755)
+ manifest = {"schema_version": 1, "id": "strata-engine", "version": version, "platform": platform,
+ "backend": backend, "entrypoint": entry, "files": files}
+ if archs:
+ manifest["cuda_archs"] = list(archs)
+ if min_runtime:
+ manifest["min_runtime"] = min_runtime
+ (folder / ec.MANIFEST).write_text(json.dumps(manifest), encoding="utf-8")
+ return folder
+
+
+def rewrite(folder: Path, **changes):
+ path = folder / ec.MANIFEST
+ data = json.loads(path.read_text(encoding="utf-8"))
+ data.update(changes)
+ path.write_text(json.dumps(data), encoding="utf-8")
+
+
+class NoNetwork:
+ """Any attempt to reach the network or start an installer fails the test that is running."""
+
+ def __enter__(self):
+ def refuse(*a, **k):
+ raise AssertionError("an engine lookup tried to reach the network")
+ self.patches = [mock.patch.object(urllib.request, "urlopen", refuse),
+ mock.patch.object(socket, "create_connection", refuse),
+ mock.patch.object(socket.socket, "connect", refuse)]
+ for item in self.patches:
+ item.start()
+ return self
+
+ def __exit__(self, *exc):
+ for item in self.patches:
+ item.stop()
+
+
+class Resolution(unittest.TestCase):
+ def setUp(self):
+ self.dir = tempfile.TemporaryDirectory()
+ self.root = Path(self.dir.name)
+ self.addCleanup(self.dir.cleanup)
+
+ def test_the_package_for_the_backend_is_chosen(self):
+ make_package(self.root, backend="cuda")
+ make_package(self.root, backend="hip", version="0.1.46")
+ chosen = ec.resolve(self.root, backend="cuda", runtime="0.1.45")
+ self.assertEqual((chosen.backend, chosen.version), ("cuda", "0.1.45"))
+ self.assertEqual(chosen.exe, self.root / "engine" / f"0.1.45-{HERE}-cuda" / EXE)
+ self.assertTrue(chosen.exe.is_file())
+
+ def test_the_newest_compatible_version_wins(self):
+ make_package(self.root, version="0.1.45")
+ make_package(self.root, version="0.1.45.2")
+ make_package(self.root, version="0.1.9") # 0.1.9 < 0.1.45 numerically, not as text
+ self.assertEqual(ec.resolve(self.root, backend="cuda", runtime="1").version, "0.1.45.2")
+
+ def test_nothing_installed_is_a_notice_that_says_nothing_is_fetched(self):
+ with NoNetwork():
+ with self.assertRaises(ec.EngineMissing) as caught:
+ ec.resolve(self.root, backend="cuda")
+ text = str(caught.exception)
+ self.assertIn("never downloads an engine", text)
+ self.assertIn("strata install", text)
+ self.assertIsInstance(caught.exception, acquisition.AcquisitionRefused)
+ self.assertEqual(caught.exception.exit_code, 5)
+ self.assertFalse((self.root / "engine").exists(), "looking must not create the folder")
+
+ def test_a_missing_component_folder_is_the_same_notice(self):
+ with self.assertRaises(ec.EngineMissing):
+ ec.resolve(self.root / "does-not-exist", backend="cuda")
+
+ def test_another_platform_is_refused_with_the_reason(self):
+ other = "linux-x86_64" if WINDOWS else "windows-x86_64"
+ make_package(self.root, platform=other)
+ with self.assertRaises(ec.EngineMissing) as caught:
+ ec.resolve(self.root, backend="cuda")
+ self.assertIn(f"is for {other}", str(caught.exception))
+
+ def test_another_backend_is_refused_with_the_reason(self):
+ make_package(self.root, backend="hip")
+ with self.assertRaises(ec.EngineMissing) as caught:
+ ec.resolve(self.root, backend="cuda")
+ self.assertIn("is a hip engine, this PC needs cuda", str(caught.exception))
+
+ def test_an_unqualified_combination_is_not_attempted(self):
+ if HERE == "macos-arm64":
+ self.skipTest("metal is supported here")
+ make_package(self.root, backend="metal") # metal is macOS arm64 only
+ with self.assertRaises(ec.EngineMissing) as caught:
+ ec.resolve(self.root, backend="metal", target=HERE)
+ self.assertIn("not a supported combination", str(caught.exception))
+
+ def test_runtime_too_old_is_refused(self):
+ make_package(self.root, min_runtime="0.2.0")
+ with self.assertRaises(ec.EngineMissing) as caught:
+ ec.resolve(self.root, backend="cuda", runtime="0.1.45")
+ self.assertIn("needs control 0.2.0", str(caught.exception))
+ self.assertEqual(ec.resolve(self.root, backend="cuda", runtime="0.2.0").version, "0.1.45")
+
+ def test_cuda_archs_must_cover_the_gpu(self):
+ make_package(self.root, archs=("sm_86",))
+ with mock.patch.object(ec, "cuda_archs_present", return_value=["sm_120"]):
+ with self.assertRaises(ec.EngineMissing) as caught:
+ ec.resolve(self.root, backend="cuda", runtime="1")
+ self.assertIn("sm_86", str(caught.exception))
+ with mock.patch.object(ec, "cuda_archs_present", return_value=["sm_86"]):
+ self.assertEqual(ec.resolve(self.root, backend="cuda", runtime="1").version, "0.1.45")
+ with mock.patch.object(ec, "cuda_archs_present", return_value=[]): # cannot tell: not a refusal
+ self.assertEqual(ec.resolve(self.root, backend="cuda", runtime="1").version, "0.1.45")
+
+
+class Integrity(unittest.TestCase):
+ def setUp(self):
+ self.dir = tempfile.TemporaryDirectory()
+ self.root = Path(self.dir.name)
+ self.addCleanup(self.dir.cleanup)
+ self.folder = make_package(self.root)
+
+ def test_a_truncated_library_is_refused(self):
+ lib = next(p for p in self.folder.iterdir() if "cudart" in p.name)
+ lib.write_bytes(lib.read_bytes()[:-3])
+ with self.assertRaisesRegex(ec.EngineMissing, "bytes, the manifest says"):
+ ec.resolve(self.root, backend="cuda", runtime="1")
+
+ def test_a_changed_entrypoint_is_refused_at_once(self):
+ exe = self.folder / EXE
+ exe.write_bytes(b"X" * exe.stat().st_size) # same size, other bytes
+ with self.assertRaisesRegex(ec.EngineMissing, "SHA-256"):
+ ec.resolve(self.root, backend="cuda", runtime="1")
+
+ def test_a_changed_library_is_found_by_the_full_check_only(self):
+ lib = next(p for p in self.folder.iterdir() if "cudart" in p.name)
+ lib.write_bytes(b"Y" * lib.stat().st_size)
+ self.assertEqual(ec.resolve(self.root, backend="cuda", runtime="1").version, "0.1.45")
+ with self.assertRaisesRegex(ec.EngineMissing, "SHA-256"):
+ ec.resolve(self.root, backend="cuda", runtime="1", full=True)
+
+ def test_a_missing_file_is_refused(self):
+ next(p for p in self.folder.iterdir() if "cudart" in p.name).unlink()
+ with self.assertRaisesRegex(ec.EngineMissing, "is missing"):
+ ec.resolve(self.root, backend="cuda", runtime="1")
+
+ def test_manifest_paths_cannot_leave_the_folder(self):
+ data = json.loads((self.folder / ec.MANIFEST).read_text())
+ for bad in ("../outside.bin", "/etc/passwd", "C:\\Windows\\win.ini", "sub/../../x"):
+ with self.subTest(path=bad):
+ broken = dict(data, files=data["files"] + [{"path": bad, "sha256": "0" * 64, "bytes": 1}])
+ (self.folder / ec.MANIFEST).write_text(json.dumps(broken), encoding="utf-8")
+ with self.assertRaises(ec.ComponentProblem):
+ ec.read_manifest(self.folder)
+
+ def test_an_entrypoint_outside_the_file_list_is_refused(self):
+ rewrite(self.folder, entrypoint="other.exe")
+ with self.assertRaisesRegex(ec.ComponentProblem, "not in the file list"):
+ ec.read_manifest(self.folder)
+
+ def test_a_broken_manifest_does_not_hide_a_good_package(self):
+ broken = self.root / "engine" / "0.9-broken"
+ broken.mkdir()
+ (broken / ec.MANIFEST).write_text("{not json", encoding="utf-8")
+ chosen = ec.resolve(self.root, backend="cuda", runtime="1")
+ self.assertEqual(chosen.version, "0.1.45")
+ report = ec.status(self.root, backend="cuda")
+ self.assertTrue(report["usable"])
+ self.assertEqual(len(report["problems"]), 1)
+
+ @unittest.skipIf(WINDOWS, "symlinks need a privilege on Windows")
+ def test_a_symlinked_file_is_refused(self):
+ lib = next(p for p in self.folder.iterdir() if "cudart" in p.name)
+ target = self.root / "elsewhere.bin"
+ target.write_bytes(lib.read_bytes())
+ lib.unlink()
+ lib.symlink_to(target)
+ with self.assertRaisesRegex(ec.EngineMissing, "not a regular file"):
+ ec.resolve(self.root, backend="cuda", runtime="1")
+
+ @unittest.skipIf(WINDOWS, "NTFS has no execute bit")
+ def test_a_non_executable_entrypoint_is_refused(self):
+ (self.folder / EXE).chmod(0o644)
+ with self.assertRaisesRegex(ec.EngineMissing, "not executable"):
+ ec.resolve(self.root, backend="cuda", runtime="1")
+
+
+class Where(unittest.TestCase):
+ def test_environment_wins_then_the_per_user_folder(self):
+ self.assertEqual(ec.components_dir({"STRATA_COMPONENTS_DIR": "/x/y"}), Path("/x/y"))
+ win = ec.components_dir({"LOCALAPPDATA": "C:\\L"}, windows=True)
+ self.assertEqual(win.name, "components")
+ self.assertEqual(win.parent.name, "Strata")
+ posix = ec.components_dir({"XDG_DATA_HOME": "/d"}, windows=False)
+ self.assertEqual(posix.as_posix(), "/d/strata/components")
+
+ def test_backend_override_is_validated(self):
+ self.assertEqual(ec.detect_backend({"STRATA_ENGINE_BACKEND": "HIP"}), ("hip", "environment"))
+ with self.assertRaises(ec.ComponentProblem):
+ ec.detect_backend({"STRATA_ENGINE_BACKEND": "vulkan"})
+
+ def test_detection_runs_only_read_only_tools(self):
+ calls = []
+
+ def fake_run(command, **kw):
+ calls.append(Path(command[0]).stem.lower())
+ return subprocess.CompletedProcess(command, 0, stdout="NVIDIA GeForce RTX 3060\n", stderr="")
+ with mock.patch.object(ec.shutil, "which", lambda name: name), \
+ mock.patch.object(ec.subprocess, "run", fake_run), \
+ mock.patch.object(ec, "host_platform", return_value="linux-x86_64"):
+ self.assertEqual(ec.detect_backend({}), ("cuda", "nvidia-smi"))
+ self.assertEqual(calls, ["nvidia-smi"])
+
+
+class NeverAcquires(unittest.TestCase):
+ """The lookup, the status report and the CLI work with the network and process creation unavailable."""
+
+ def setUp(self):
+ self.dir = tempfile.TemporaryDirectory()
+ self.root = Path(self.dir.name)
+ self.addCleanup(self.dir.cleanup)
+
+ def run_cli(self, *argv):
+ out, err = io.StringIO(), io.StringIO()
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
+ code = cli.main(list(argv))
+ return code, out.getvalue(), err.getvalue()
+
+ def test_status_and_cli_with_the_network_down(self):
+ make_package(self.root)
+ with NoNetwork(), mock.patch.dict(os.environ, {"STRATA_NO_ACQUIRE": "1"}):
+ report = ec.status(self.root, backend="cuda")
+ code, out, _ = self.run_cli("components", "engine", "--components-dir", str(self.root),
+ "--backend", "cuda", "--output", "json")
+ self.assertTrue(report["usable"])
+ self.assertFalse(report["acquires"])
+ self.assertEqual(code, 0)
+ data = json.loads(out)
+ self.assertTrue(data["ok"])
+ self.assertEqual(Path(data["engine"]["exe"]).name, EXE)
+
+ def test_cli_missing_engine_is_exit_5_with_the_notice(self):
+ with NoNetwork():
+ code, out, _ = self.run_cli("components", "engine", "--components-dir", str(self.root),
+ "--backend", "cuda", "--output", "json")
+ self.assertEqual(code, 5)
+ data = json.loads(out)
+ self.assertFalse(data["ok"])
+ self.assertIn("never downloads an engine", data["notice"])
+
+ def test_the_component_fetcher_refuses_where_acquiring_is_forbidden(self):
+ store = components.ComponentStore(self.root / "store")
+ artifact = components.Artifact(name="engine.tar.gz", url="https://example.invalid/e.tgz",
+ sha256="0" * 64, bytes=10)
+ with NoNetwork(), mock.patch.dict(os.environ, {"STRATA_NO_ACQUIRE": "1"}):
+ with self.assertRaises(acquisition.AcquisitionRefused):
+ store._fetch(artifact)
+
+ def test_main_guard_turns_the_notice_into_exit_5(self):
+ def start():
+ ec.resolve(self.root, backend="cuda")
+ err = io.StringIO()
+ with contextlib.redirect_stderr(err):
+ code = acquisition.main_guard(start)
+ self.assertEqual(code, 5)
+ self.assertIn("No engine for this PC", err.getvalue())
+
+
+if __name__ == "__main__":
+ unittest.main()