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++
updates: signed feed, Ed25519 verifier, component updater with resume, staged test-start, switch and rollback
Niko1221c8698f6257a0
diff --git a/packaging/feed_tool.py b/packaging/feed_tool.pynew file mode 100644index 000000000..5e4f0f77f--- /dev/null+++ b/packaging/feed_tool.py@@ -0,0 +1,254 @@+#!/usr/bin/env python3+"""The release-side tool for the update feed: keys, signed packages, archives, the signed feed.++Nothing here runs on a user's PC. It runs on the owner's release machine, with the owner's private key, and writes files+that are then uploaded (to a local folder or a local HTTP server while testing; to the real host only when the owner+decides). Nothing is uploaded by this tool.++Typical use (the owner's offline machine; replace ``KEYDIR`` with a folder that is NOT in a git checkout):++ python packaging/feed_tool.py keygen --out KEYDIR # once: feed-key.json (SECRET) + feed-key.pub.json+ python packaging/feed_tool.py sign-package <components>/engine/0.1.46-linux-x86_64-cuda --key KEYDIR/feed-key.json+ python packaging/feed_tool.py pack-engine <that folder> --out RELEASE/engine # archive + <name>.entry.json+ python packaging/feed_tool.py pack-control <control bundle folder> --version 0.1.46 --platform linux-x86_64 --out RELEASE/control+ python packaging/feed_tool.py build-feed --out RELEASE --sequence 12 --key KEYDIR/feed-key.json \+ --engine RELEASE/engine --control RELEASE/control [--app-json tauri-latest.json] [--channel stable] [--expires-days 365]+ python packaging/feed_tool.py verify-feed RELEASE --pub KEYDIR/feed-key.pub.json++``keygen`` never prints the secret and refuses to write inside a git checkout or over an existing file. The public file's+entry goes into ``strata_control/update_keys.json`` (``keys``) once, in the commit that ships the first signed release.+The Tauri updater key is a different key (minisign, made by ``tauri signer generate``); its public half goes in+``tauri.conf.json`` and in ``update_keys.json`` as ``app_minisign_public``.+"""++from __future__ import annotations++import argparse+import datetime as dt+import hashlib+import json+import os+import stat+import sys+import tarfile+import zipfile+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))++from strata_control import engine_component as ec, feed as feedmod, signing # noqa: E402+++def _inside_git(path: Path) -> bool:+ for parent in [path.resolve(), *path.resolve().parents]:+ if (parent / ".git").exists():+ return True+ return False+++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 _load_key(path: Path) -> dict:+ key = json.loads(path.read_text(encoding="utf-8"))+ if key.get("alg") != signing.ALG or "seed" not in key:+ raise SystemExit(f"{path} is not a secret key file made by `feed_tool.py keygen`")+ return key+++def keygen(out: Path, *, allow_git: bool = False) -> dict:+ out = Path(out)+ if _inside_git(out) and not allow_git:+ raise SystemExit(f"{out} is inside a git checkout; a private key must not be where it can be committed. Choose another folder.")+ secret, public = out / "feed-key.json", out / "feed-key.pub.json"+ if secret.exists() or public.exists():+ raise SystemExit(f"{secret} or {public} already exists; refusing to overwrite a key")+ out.mkdir(parents=True, exist_ok=True)+ key = signing.generate_key()+ fd = os.open(secret, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)+ with os.fdopen(fd, "w", encoding="utf-8") as stream:+ json.dump(key, stream, indent=1)+ stream.write("\n")+ public.write_text(json.dumps({"keys": [signing.public_part(key)]}, indent=1) + "\n", encoding="utf-8")+ return signing.public_part(key)+++def sign_package(folder: Path, key: dict) -> str:+ """Put the signature into the package's manifest. Returns the manifest's SHA-256 afterwards (the feed names it)."""+ path = Path(folder) / ec.MANIFEST+ manifest = json.loads(path.read_text(encoding="utf-8-sig"))+ manifest["signature"] = None+ payload = ec.signing_payload(manifest)+ manifest["signature"] = signing.sign_bytes(key, payload)+ path.write_text(json.dumps(manifest, indent=1) + "\n", encoding="utf-8")+ ec.read_manifest(Path(folder)) # still a valid manifest+ signing.verify_bytes({key["key_id"]: __import__("base64").b64decode(key["public"])}, payload, manifest["signature"])+ return _sha256(path)+++def _mode(path: Path, rel: str, entrypoint: str | None) -> int:+ if rel == entrypoint:+ return 0o755+ try:+ return 0o755 if path.stat().st_mode & stat.S_IXUSR and os.name != "nt" else 0o644+ except OSError:+ return 0o644+++def _write_archive(files: list[tuple[str, Path]], archive: Path, fmt: str, entrypoint: str | None) -> None:+ archive.parent.mkdir(parents=True, exist_ok=True)+ if fmt == "zip":+ with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as zf:+ for rel, path in files:+ zf.write(path, rel)+ return+ mode = {"tar.gz": "w:gz", "tar.xz": "w:xz"}[fmt]+ with tarfile.open(archive, mode) as tar:+ for rel, path in files:+ info = tar.gettarinfo(str(path), arcname=rel)+ info.uid = info.gid = 0+ info.uname = info.gname = ""+ info.mtime = 0+ info.mode = _mode(path, rel, entrypoint)+ with path.open("rb") as stream:+ tar.addfile(info, stream)+++def _tree(folder: Path) -> list[tuple[str, Path]]:+ found = []+ for path in sorted(folder.rglob("*")):+ if path.is_file() and not path.is_symlink():+ found.append((path.relative_to(folder).as_posix(), path))+ return found+++def pack_engine(folder: Path, out: Path, fmt: str = "tar.gz", *, url_prefix: str = "engine/") -> dict:+ """Archive a (signed) engine package folder and return its feed entry. The archive holds the folder's files at its root."""+ folder = Path(folder)+ component = ec.read_manifest(folder)+ files = _tree(folder)+ installed = sum(p.stat().st_size for _, p in files)+ name = f"strata-engine-{folder.name}.{fmt}"+ archive = Path(out) / name+ _write_archive(files, archive, fmt, component.entrypoint)+ entry = {"version": component.version, "platform": component.platform, "backend": component.backend,+ "variant": component.variant, "archs": list(component.archs), "min_driver": dict(component.min_driver),+ "min_runtime": component.min_runtime, "build_id": component.build_id, "format": fmt,+ "url": f"{url_prefix}{name}", "size": archive.stat().st_size, "sha256": _sha256(archive),+ "manifest_sha256": _sha256(folder / ec.MANIFEST), "installed_bytes": installed, "notes": component.notes}+ (Path(out) / (name + ".entry.json")).write_text(json.dumps(entry, indent=1) + "\n", encoding="utf-8")+ return entry+++def pack_control(folder: Path, out: Path, *, version: str, platform: str, fmt: str = "tar.gz",+ entry_file: str = "strata.py", url_prefix: str = "control/") -> dict:+ folder = Path(folder)+ files = _tree(folder)+ installed = sum(p.stat().st_size for _, p in files)+ name = f"strata-control-{version}-{platform}.{fmt}"+ archive = Path(out) / name+ _write_archive(files, archive, fmt, entry_file)+ entry = {"platform": platform, "format": fmt, "url": f"{url_prefix}{name}", "size": archive.stat().st_size,+ "sha256": _sha256(archive), "installed_bytes": installed, "entry": entry_file, "version": version}+ (Path(out) / (name + ".entry.json")).write_text(json.dumps(entry, indent=1) + "\n", encoding="utf-8")+ return entry+++def build_feed(out: Path, *, key: dict, sequence: int, channel: str = "stable", engine_dir: Path | None = None,+ control_dir: Path | None = None, app_json: Path | None = None, expires_days: int | None = None,+ now: dt.datetime | None = None) -> dict:+ now = now or dt.datetime.now(dt.timezone.utc)+ document: dict = {"schema_version": feedmod.SCHEMA_VERSION, "feed": "strata-updates", "channel": channel,+ "sequence": sequence, "generated_at": now.strftime("%Y-%m-%dT%H:%M:%SZ"),+ "expires_at": (now + dt.timedelta(days=expires_days)).strftime("%Y-%m-%dT%H:%M:%SZ") if expires_days else None}+ if engine_dir:+ document["engine"] = {"packages": [json.loads(p.read_text(encoding="utf-8"))+ for p in sorted(Path(engine_dir).glob("*.entry.json"))]}+ if control_dir:+ entries = [json.loads(p.read_text(encoding="utf-8")) for p in sorted(Path(control_dir).glob("*.entry.json"))]+ versions = {e["version"] for e in entries}+ if len(versions) > 1:+ raise SystemExit(f"the control packages are for different versions: {sorted(versions)}")+ if entries:+ document["control"] = {"version": versions.pop(), "packages": [{k: v for k, v in e.items() if k != "version"} for e in entries]}+ if app_json:+ document["app"] = json.loads(Path(app_json).read_text(encoding="utf-8"))+ payload = (json.dumps(document, indent=1, sort_keys=True) + "\n").encode("utf-8")+ Path(out).mkdir(parents=True, exist_ok=True)+ (Path(out) / feedmod.FEED_NAME).write_bytes(payload)+ signature = signing.sign_bytes(key, payload)+ (Path(out) / (feedmod.FEED_NAME + feedmod.SIGNATURE_SUFFIX)).write_text(json.dumps(signature) + "\n", encoding="utf-8")+ if "app" in document: # the file the Tauri updater plugin reads+ latest = Path(out) / "app" / "latest.json"+ latest.parent.mkdir(parents=True, exist_ok=True)+ latest.write_text(json.dumps({k: v for k, v in document["app"].items()}, indent=1) + "\n", encoding="utf-8")+ # a parse of what was written is the last check: a feed this tool makes must be a feed Control accepts+ feedmod.verify_and_parse(payload, json.dumps(signature).encode(), source=str(Path(out) / feedmod.FEED_NAME),+ trusted={key["key_id"]: __import__("base64").b64decode(key["public"])}, now=now)+ return document+++def main(argv: list[str] | None = None) -> int:+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ sub = ap.add_subparsers(dest="cmd", required=True)+ k = sub.add_parser("keygen")+ k.add_argument("--out", type=Path, required=True)+ sp = sub.add_parser("sign-package")+ sp.add_argument("folder", type=Path)+ sp.add_argument("--key", type=Path, required=True)+ pe = sub.add_parser("pack-engine")+ pe.add_argument("folder", type=Path)+ pe.add_argument("--out", type=Path, required=True)+ pe.add_argument("--format", choices=feedmod.FORMATS, default="tar.gz")+ pc = sub.add_parser("pack-control")+ pc.add_argument("folder", type=Path)+ pc.add_argument("--out", type=Path, required=True)+ pc.add_argument("--version", required=True)+ pc.add_argument("--platform", required=True, choices=feedmod.PLATFORMS)+ pc.add_argument("--format", choices=feedmod.FORMATS, default="tar.gz")+ bf = sub.add_parser("build-feed")+ bf.add_argument("--out", type=Path, required=True)+ bf.add_argument("--key", type=Path, required=True)+ bf.add_argument("--sequence", type=int, required=True)+ bf.add_argument("--channel", default="stable")+ bf.add_argument("--engine", type=Path)+ bf.add_argument("--control", type=Path)+ bf.add_argument("--app-json", type=Path)+ bf.add_argument("--expires-days", type=int)+ vf = sub.add_parser("verify-feed")+ vf.add_argument("source")+ vf.add_argument("--pub", type=Path, required=True)+ a = ap.parse_args(argv)+ if a.cmd == "keygen":+ public = keygen(a.out)+ print(f"wrote {a.out / 'feed-key.json'} (SECRET, keep it offline and backed up) and {a.out / 'feed-key.pub.json'}")+ print(f"key_id {public['key_id']}")+ elif a.cmd == "sign-package":+ print("manifest sha256", sign_package(a.folder, _load_key(a.key)))+ elif a.cmd == "pack-engine":+ entry = pack_engine(a.folder, a.out, a.format)+ print(json.dumps({k: entry[k] for k in ("version", "backend", "variant", "size", "sha256", "manifest_sha256")}, indent=1))+ elif a.cmd == "pack-control":+ entry = pack_control(a.folder, a.out, version=a.version, platform=a.platform, fmt=a.format)+ print(json.dumps({k: entry[k] for k in ("version", "platform", "size", "sha256")}, indent=1))+ elif a.cmd == "build-feed":+ doc = build_feed(a.out, key=_load_key(a.key), sequence=a.sequence, channel=a.channel, engine_dir=a.engine,+ control_dir=a.control, app_json=a.app_json, expires_days=a.expires_days)+ print(f"wrote {a.out / feedmod.FEED_NAME} (+ .sig); engines {len((doc.get('engine') or {}).get('packages', []))}, "+ f"control {'yes' if 'control' in doc else 'no'}, app {'yes' if 'app' in doc else 'no'}")+ elif a.cmd == "verify-feed":+ trusted = signing.load_trusted_keys(a.pub, environ={})+ loaded = feedmod.fetch(a.source, trusted)+ print(f"ok: sequence {loaded.sequence}, channel {loaded.channel}, signed by {loaded.key_id}, "+ f"{len(loaded.engine)} engine packages, control {len(loaded.control)}, app {'yes' if loaded.app else 'no'}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/strata_control/engine_component.py b/strata_control/engine_component.pyindex 78445d85c..3eff4ae0e 100644--- a/strata_control/engine_component.py+++ b/strata_control/engine_component.py@@ -58,6 +58,9 @@ COMPONENT_ID = "strata-engine"ENV_DIR = "STRATA_COMPONENTS_DIR"ENV_BACKEND = "STRATA_ENGINE_BACKEND"ENV_REQUIRE_SIGNED = "STRATA_REQUIRE_SIGNED_COMPONENTS"+#: The updater's state (``strata update``, ``strata components rollback``) lives in the component folder; the only member the+#: start path reads is ``engine.pinned``: the folder a manual rollback chose, which wins over a newer installed package.+UPDATE_STATE = Path(".updates") / "state.json"#: 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"@@ -161,6 +164,16 @@ def engine_dir(root: Path | None = None) -> Path:return (root or components_dir()) / "engine"+def pinned_folder(root: Path | None = None) -> str | None:+ """The package folder a manual rollback pinned, or None. Read-only; a missing or damaged state file means no pin."""+ try:+ data = json.loads(((root or components_dir()) / UPDATE_STATE).read_text(encoding="utf-8-sig"))+ value = data["engine"]["pinned"]+ return value if isinstance(value, str) and value and "/" not in value and "\\" not in value else None+ except (OSError, ValueError, KeyError, TypeError):+ return None++# ----------------------------------------------------------------------------------------------- manifestdef _version_key(value: str) -> tuple:@@ -499,6 +512,11 @@ def resolve(root: Path | None = None, *, backend: str | None = None, target: strif broken and len(broken) == len(reasons): # every package that fits this PC failed its integrity checkraise EngineIntegrityError("; ".join(broken), base, problems=problems)raise EngineMissing("; ".join(everything) or "nothing matched", base, problems=problems)+ pin = pinned_folder(base)+ if pin: # a manual rollback: the pinned package wins while it is usable+ for item in usable:+ if item.root.name == pin:+ return item# newest version first; with equal versions the build for the newer driver (the CUDA 13 build beside the CUDA 12 one)return max(usable, key=lambda item: (_version_key(item.version), _version_key(item.min_driver.get("nvidia", "0"))))@@ -536,7 +554,8 @@ def status(root: Path | None = None, *, backend: str | None = None, full: bool =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}+ "engine": None, "usable": False, "notice": None, "acquires": False,+ "pinned": pinned_folder(base)}try:chosen = resolve(base, backend=backend, full=full)report["engine"] = chosen.to_dict()diff --git a/strata_control/feed.py b/strata_control/feed.pynew file mode 100644index 000000000..c1452d0a6--- /dev/null+++ b/strata_control/feed.py@@ -0,0 +1,367 @@+"""The signed update feed: what is published, how it is checked, which engine package fits a PC.++One small document, ``strata-feed.json``, with a detached Ed25519 signature ``strata-feed.json.sig`` (the signature covers the+file's exact bytes, so there is no canonicalisation to get wrong). It lists, for one channel:++* ``app``: the desktop app, in exactly the shape of Tauri's static updater JSON (``version``, ``notes``, ``pub_date``,+ ``platforms{<tauri target>: {url, signature}}``), plus ``sha256`` and ``size`` per platform. The Tauri updater plugin+ reads a copy of this member at ``app/latest.json`` and checks the minisign signature itself;+* ``control``: the runtime component (Control: bundled Python, ``strata_control``, the CLI and server), one archive per platform;+* ``engine``: the engine packages, one entry per platform / backend / variant, each with ``version``, ``archs``,+ ``min_driver``, ``min_runtime``, ``size``, ``sha256`` of the archive, ``manifest_sha256`` of the package's+ ``engine-component.json`` (which holds every file's hash) and a URL.++The feed's signature plus those hashes is the whole chain of trust: a package whose archive hash or manifest hash is not the+one in the signed feed is never installed. Three refusals are tested: a bad signature, a bad hash and a downgrade. The+downgrade guard has two parts: a feed whose ``sequence`` is lower than the last one this PC accepted is refused (a replayed+old feed), and a package older than the installed one is never installed by an update.++Nothing here touches the network itself; `strata_control.transfer` does.+"""++from __future__ import annotations++import datetime as dt+import json+import re+from dataclasses import dataclass, field++from strata_control import signing, transfer+from strata_control.targets import BACKEND_MATRIX++SCHEMA_VERSION = 1+FEED_NAME = "strata-feed.json"+SIGNATURE_SUFFIX = ".sig"+FORMATS = ("tar.gz", "tar.xz", "zip")+PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-arm64", "macos-x86_64")+#: Tauri's names for the same platforms.+TAURI_TARGETS = {"windows-x86_64": "windows-x86_64", "linux-x86_64": "linux-x86_64",+ "macos-arm64": "darwin-aarch64", "macos-x86_64": "darwin-x86_64"}+_VERSION = re.compile(r"\d+\.\d+\.\d+(?:\.\d+)?")+_HEX64 = re.compile(r"[0-9a-f]{64}")+++class FeedError(RuntimeError):+ """The feed or something it lists cannot be trusted or used. `exit_code` is the CLI's."""++ def __init__(self, message: str, exit_code: int = 5):+ super().__init__(message)+ self.exit_code = exit_code+++class FeedDowngrade(FeedError):+ """A feed or a package older than what this PC already has."""+++def version_key(value: str) -> tuple[int, ...]:+ if not isinstance(value, str) or not _VERSION.fullmatch(value):+ raise FeedError(f"{value!r} is not a version number (expected like 0.1.46 or 0.1.46.1)")+ parts = [int(p) for p in value.split(".")]+ return tuple(parts + [0] * (4 - len(parts)))+++def _need(obj: dict, key: str, kind, where: str):+ value = obj.get(key)+ if not isinstance(value, kind) or isinstance(value, bool) and kind is int:+ raise FeedError(f"the feed's {where} has no valid {key}")+ return value+++def _hex(value, where: str) -> str:+ if not isinstance(value, str) or not _HEX64.fullmatch(value.lower()):+ raise FeedError(f"the feed's {where} has no valid sha256")+ return value.lower()+++@dataclass(frozen=True)+class EnginePackage:+ version: str+ platform: str+ backend: str+ variant: str+ archs: tuple[str, ...]+ min_driver: dict+ min_runtime: str | None+ build_id: str+ url: str+ format: str+ size: int+ sha256: str+ manifest_sha256: str+ installed_bytes: int+ notes: str = ""++ @property+ def label(self) -> str:+ return f"{self.version} {self.platform}-{self.backend}" + (f"-{self.variant}" if self.variant else "")++ def to_dict(self) -> dict:+ return {"version": self.version, "platform": self.platform, "backend": self.backend, "variant": self.variant,+ "archs": list(self.archs), "min_driver": dict(self.min_driver), "min_runtime": self.min_runtime,+ "build_id": self.build_id, "size": self.size, "installed_bytes": self.installed_bytes,+ "format": self.format, "url": self.url, "sha256": self.sha256, "manifest_sha256": self.manifest_sha256}+++@dataclass(frozen=True)+class ControlPackage:+ version: str+ platform: str+ url: str+ format: str+ size: int+ sha256: str+ installed_bytes: int+ entry: str = "strata.py"++ @property+ def label(self) -> str:+ return f"control {self.version} {self.platform}"+++@dataclass(frozen=True)+class AppRelease:+ version: str+ notes: str+ pub_date: str+ platforms: dict # {platform: {"url", "signature", "sha256", "size", "format"?}}++ def for_platform(self, platform: str) -> dict | None:+ return self.platforms.get(platform)+++@dataclass+class Feed:+ sequence: int+ channel: str+ generated_at: str+ expires_at: str | None+ app: AppRelease | None+ control: tuple[ControlPackage, ...]+ engine: tuple[EnginePackage, ...]+ source: str # where it was read from (the base for relative URLs)+ key_id: str # who signed it+ raw: bytes = field(default=b"", repr=False)++ def url(self, ref: str) -> str:+ return transfer.resolve_ref(transfer.base_of(self.source), ref)+++# ---------------------------------------------------------------------------------------------- parsing++def _time(value, what: str) -> dt.datetime:+ try:+ parsed = dt.datetime.fromisoformat(str(value).replace("Z", "+00:00"))+ except ValueError:+ raise FeedError(f"the feed's {what} is not a timestamp") from None+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=dt.timezone.utc)+++def _engine_package(item: dict) -> EnginePackage:+ if not isinstance(item, dict):+ raise FeedError("an engine entry in the feed is not an object")+ where = f"engine entry {item.get('version')!r}"+ version = _need(item, "version", str, where)+ version_key(version)+ platform = _need(item, "platform", str, where)+ if platform not in PLATFORMS:+ raise FeedError(f"the feed's {where} names an unknown platform {platform!r}")+ backend = _need(item, "backend", str, where)+ if backend not in BACKEND_MATRIX:+ raise FeedError(f"the feed's {where} names an unknown backend {backend!r}")+ archs = item.get("archs")+ if not isinstance(archs, list) or not all(isinstance(a, str) and a for a in archs) or (backend != "cpu" and not archs):+ raise FeedError(f"the feed's {where} needs a list of archs")+ driver = item.get("min_driver") or {}+ if not isinstance(driver, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in driver.items()):+ raise FeedError(f"the feed's {where} has an invalid min_driver")+ fmt = _need(item, "format", str, where)+ if fmt not in FORMATS:+ raise FeedError(f"the feed's {where} uses an unsupported archive format {fmt!r}")+ size = _need(item, "size", int, where)+ installed = _need(item, "installed_bytes", int, where)+ if size <= 0 or installed <= 0:+ raise FeedError(f"the feed's {where} declares a size that cannot be a real file")+ runtime = item.get("min_runtime")+ if runtime is not None:+ version_key(runtime)+ return EnginePackage(version=version, platform=platform, backend=backend, variant=str(item.get("variant") or ""),+ archs=tuple(archs), min_driver=dict(driver), min_runtime=runtime,+ build_id=_need(item, "build_id", str, where), url=_need(item, "url", str, where), format=fmt,+ size=size, sha256=_hex(item.get("sha256"), where),+ manifest_sha256=_hex(item.get("manifest_sha256"), where), installed_bytes=installed,+ notes=str(item.get("notes") or ""))+++def _control_package(item: dict, version: str) -> ControlPackage:+ where = "control entry"+ platform = _need(item, "platform", str, where)+ if platform not in PLATFORMS:+ raise FeedError(f"the feed's control entry names an unknown platform {platform!r}")+ fmt = _need(item, "format", str, where)+ if fmt not in FORMATS:+ raise FeedError(f"the feed's control entry uses an unsupported archive format {fmt!r}")+ size, installed = _need(item, "size", int, where), _need(item, "installed_bytes", int, where)+ if size <= 0 or installed <= 0:+ raise FeedError("the feed's control entry declares a size that cannot be a real file")+ return ControlPackage(version=version, platform=platform, url=_need(item, "url", str, where), format=fmt,+ size=size, sha256=_hex(item.get("sha256"), where), installed_bytes=installed,+ entry=str(item.get("entry") or "strata.py"))+++def parse(payload: bytes, *, source: str, key_id: str) -> Feed:+ """The feed document, strictly. Unknown members are ignored; missing or mistyped ones are errors."""+ try:+ data = json.loads(payload.decode("utf-8-sig"))+ except (ValueError, UnicodeError):+ raise FeedError("the update feed is not valid JSON") from None+ if not isinstance(data, dict) or data.get("schema_version") != SCHEMA_VERSION:+ raise FeedError("the update feed has an unsupported schema_version")+ sequence = data.get("sequence")+ if type(sequence) is not int or sequence < 0:+ raise FeedError("the update feed has no sequence number")+ channel = _need(data, "channel", str, "header")+ generated = _need(data, "generated_at", str, "header")+ _time(generated, "generated_at")+ expires = data.get("expires_at")+ if expires is not None:+ _time(expires, "expires_at")+ app = None+ raw_app = data.get("app")+ if raw_app is not None:+ if not isinstance(raw_app, dict):+ raise FeedError("the feed's app member is not an object")+ version_key(_need(raw_app, "version", str, "app entry"))+ platforms = raw_app.get("platforms")+ if not isinstance(platforms, dict) or not platforms:+ raise FeedError("the feed's app entry lists no platforms")+ parsed_platforms = {}+ by_tauri = {v: k for k, v in TAURI_TARGETS.items()}+ for target, entry in platforms.items():+ plat = by_tauri.get(str(target).split("-nsis")[0].split("-msi")[0])+ if plat is None or not isinstance(entry, dict):+ raise FeedError(f"the feed's app entry names an unknown platform {target!r}")+ parsed_platforms[plat] = {"url": _need(entry, "url", str, "app entry"),+ "signature": _need(entry, "signature", str, "app entry"),+ "sha256": _hex(entry.get("sha256"), "app entry"),+ "size": _need(entry, "size", int, "app entry"), "target": target}+ app = AppRelease(version=raw_app["version"], notes=str(raw_app.get("notes") or ""),+ pub_date=str(raw_app.get("pub_date") or ""), platforms=parsed_platforms)+ control = []+ raw_control = data.get("control")+ if raw_control is not None:+ if not isinstance(raw_control, dict):+ raise FeedError("the feed's control member is not an object")+ cver = _need(raw_control, "version", str, "control entry")+ version_key(cver)+ control = [_control_package(item, cver) for item in (raw_control.get("packages") or [])]+ engine = []+ raw_engine = data.get("engine")+ if raw_engine is not None:+ if not isinstance(raw_engine, dict) or not isinstance(raw_engine.get("packages"), list):+ raise FeedError("the feed's engine member lists no packages")+ engine = [_engine_package(item) for item in raw_engine["packages"]]+ seen = set()+ for pkg in engine:+ ident = (pkg.version, pkg.platform, pkg.backend, pkg.variant)+ if ident in seen:+ raise FeedError(f"the feed lists engine {pkg.label} twice")+ seen.add(ident)+ return Feed(sequence=sequence, channel=channel, generated_at=generated, expires_at=expires, app=app,+ control=tuple(control), engine=tuple(engine), source=source, key_id=key_id, raw=payload)+++def verify_and_parse(payload: bytes, signature_bytes: bytes, *, source: str, trusted: dict[str, bytes],+ last_sequence: int | None = None, channel: str | None = None,+ now: dt.datetime | None = None) -> Feed:+ """Check the signature over `payload`, then parse; then the three guards: the channel is the one asked for, the feed has+ not expired, and its sequence is not lower than the last one accepted (a replayed older feed is a downgrade)."""+ if not trusted:+ raise FeedError("this build trusts no update key (update_keys.json is empty and STRATA_UPDATE_TRUSTED_KEYS is not set), "+ "so no update can be verified; nothing was downloaded")+ try:+ signature = json.loads(signature_bytes.decode("utf-8-sig"))+ except (ValueError, UnicodeError):+ raise FeedError("the update feed's signature file is not valid") from None+ try:+ key_id = signing.verify_bytes(trusted, payload, signature)+ except signing.SignatureError as exc:+ raise FeedError(f"the update feed is not trusted: {exc}") from None+ feed = parse(payload, source=source, key_id=key_id)+ if channel and feed.channel != channel:+ raise FeedError(f"the feed is for the {feed.channel!r} channel, this PC follows {channel!r}")+ now = now or dt.datetime.now(dt.timezone.utc)+ if feed.expires_at and _time(feed.expires_at, "expires_at") < now:+ raise FeedError(f"the update feed expired on {feed.expires_at}; refusing a stale feed")+ if last_sequence is not None and feed.sequence < last_sequence:+ raise FeedDowngrade(f"the update feed is older than the one already accepted (sequence {feed.sequence} < {last_sequence}); "+ "refusing a replayed feed")+ return feed+++def fetch(source: str, trusted: dict[str, bytes], **guards) -> Feed:+ """Read the feed and its signature from `source` (an https URL, a loopback http URL, a file URL or a folder/file path)."""+ location = source+ if transfer.kind_of(source) == "path":+ path = transfer._local_path(source)+ if path.is_dir():+ location = str(path / FEED_NAME)+ elif transfer.kind_of(source) in ("http", "https") and not source.rsplit("/", 1)[-1].endswith(".json"):+ location = source.rstrip("/") + "/" + FEED_NAME+ try:+ payload = transfer.read_small(location)+ signature = transfer.read_small(location + SIGNATURE_SUFFIX)+ except transfer.TransferError as exc:+ raise FeedError(f"the update feed could not be read: {exc}", 6) from None+ return verify_and_parse(payload, signature, source=location, trusted=trusted, **guards)+++# ---------------------------------------------------------------------------------------------- hardware and selection++def gfx_covers(archs, present: list[str]) -> bool:+ """HIP: the build holds machine code for at least one of the installed AMD GPUs (``gfx1201``). Unknown GPUs: not a refusal."""+ if not present:+ return True+ return any(a in present for a in archs)+++def engine_fit_reasons(pkg: EnginePackage, hardware: dict) -> list[str]:+ """Why `pkg` cannot run on the machine `hardware` describes; empty when it fits. `hardware` is what+ `updater.detect_hardware()` returns: platform, backend, nvidia driver, cuda archs, gfx names, runtime version."""+ from strata_control import engine_component as ec+ reasons = []+ if pkg.platform != hardware["platform"]:+ reasons.append(f"{pkg.label} is for {pkg.platform}, this PC is {hardware['platform']}")+ return reasons+ wanted = hardware.get("backend") or "cpu"+ if pkg.backend != wanted:+ reasons.append(f"{pkg.label} is a {pkg.backend} engine, this PC needs {wanted}")+ return reasons+ runtime = hardware.get("runtime")+ if pkg.min_runtime and runtime and ec._version_key(runtime) < ec._version_key(pkg.min_runtime):+ reasons.append(f"{pkg.label} needs control {pkg.min_runtime} or newer, this is {runtime}")+ cuda_archs = tuple(a for a in pkg.archs if a.startswith(("sm_", "compute_")))+ if pkg.backend == "cuda" and cuda_archs and hardware.get("cuda_archs") and not ec.arch_covers(cuda_archs, hardware["cuda_archs"]):+ reasons.append(f"{pkg.label} has code for {', '.join(cuda_archs)}, this PC's GPU is {', '.join(hardware['cuda_archs'])}")+ if pkg.backend == "hip" and not gfx_covers(pkg.archs, hardware.get("gfx") or []):+ reasons.append(f"{pkg.label} has code for {', '.join(pkg.archs)}, this PC's GPU is {', '.join(hardware['gfx'])}")+ need, have = pkg.min_driver.get("nvidia"), hardware.get("nvidia_driver")+ if pkg.backend == "cuda" and need and have and ec._version_key(have) < ec._version_key(need):+ reasons.append(f"{pkg.label} needs NVIDIA driver {need} or newer, this PC has {have}")+ return reasons+++def select_engine(packages, hardware: dict) -> tuple[EnginePackage | None, list[str]]:+ """The best package for this PC and, when none fits, every reason. Best = newest version; with equal versions the build+ that needs the newer driver (CUDA 13 beside CUDA 12), as `engine_component.resolve` chooses between installed ones."""+ from strata_control import engine_component as ec+ fitting, reasons = [], []+ for pkg in packages:+ why = engine_fit_reasons(pkg, hardware)+ if why:+ reasons.extend(why)+ else:+ fitting.append(pkg)+ if not fitting:+ return None, reasons+ best = max(fitting, key=lambda p: (version_key(p.version), ec._version_key(p.min_driver.get("nvidia", "0"))))+ return best, reasonsdiff --git a/strata_control/preset_marks.py b/strata_control/preset_marks.pynew file mode 100644index 000000000..b67ecde2b--- /dev/null+++ b/strata_control/preset_marks.py@@ -0,0 +1,106 @@+"""Saved tuning presets after the engine changed: mark them for the short re-check, never delete them.++A tuning preset is valid for one identity (GPU and driver, engine build, model file, context). When an engine update+changes the engine part of that identity the presets are not wrong, only unconfirmed. The plan (4b) says to offer a short+check of about two minutes, not a full re-tune, and to keep every preset.++This module is the one thing the updater writes about presets, and it is deliberately not a preset store: it writes a+small, separate file next to the tuning state, ``<state>/tuning/recheck.json``, and never opens, moves or rewrites a+preset. The tuner (S5) reads `pending()` when it loads a preset and, once the short check passed or the user re-tuned,+calls `clear(mark_id)`. The file is created only when an engine identity actually changed, so a PC without an earlier+engine, or an update to a build with the same identity, writes nothing.++ {"schema_version": 1,+ "pending": [{"id": "...", "reason": "engine_changed", "component": "strata-engine",+ "from": {"version", "build_id", "manifest_sha256", "backend", "platform", "variant"},+ "to": {... same ...}, "marked_at": "<iso>"}]}+"""++from __future__ import annotations++import datetime as dt+import json+import os+import tempfile+import uuid+from pathlib import Path++from strata_control import paths++SCHEMA_VERSION = 1+IDENTITY_KEYS = ("version", "build_id", "manifest_sha256", "backend", "platform", "variant")+++def marks_path(base: Path | None = None) -> Path:+ return (base or paths.state_base()) / "tuning" / "recheck.json"+++def identity_of(component, manifest_sha256: str) -> dict:+ """The engine part of a preset's identity, from an installed `EngineComponent`."""+ return {"version": component.version, "build_id": component.build_id, "manifest_sha256": manifest_sha256,+ "backend": component.backend, "platform": component.platform, "variant": component.variant}+++def _read(path: Path) -> dict:+ try:+ data = json.loads(path.read_text(encoding="utf-8-sig"))+ except (OSError, ValueError):+ return {"schema_version": SCHEMA_VERSION, "pending": []}+ if not isinstance(data, dict) or not isinstance(data.get("pending"), list):+ return {"schema_version": SCHEMA_VERSION, "pending": []}+ return data+++def _write(path: Path, data: dict) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ descriptor, temp = tempfile.mkstemp(prefix=".recheck-", suffix=".tmp", dir=path.parent)+ try:+ with os.fdopen(descriptor, "w", encoding="utf-8") as stream:+ json.dump(data, stream, indent=1, sort_keys=True)+ stream.write("\n")+ os.replace(temp, path)+ finally:+ if os.path.exists(temp):+ os.unlink(temp)+++def pending(base: Path | None = None) -> list[dict]:+ return list(_read(marks_path(base))["pending"])+++def mark_engine_changed(before: dict | None, after: dict, *, base: Path | None = None,+ now: dt.datetime | None = None) -> dict | None:+ """Record that presets measured on `before` are unconfirmed on `after`. Returns the mark, or None when nothing is owed:+ there was no earlier engine, or the identity did not change. Presets are not touched."""+ if before is None:+ return None+ if all(before.get(key) == after.get(key) for key in IDENTITY_KEYS):+ return None+ path = marks_path(base)+ data = _read(path)+ when = (now or dt.datetime.now(dt.timezone.utc)).isoformat()+ mark = {"id": uuid.uuid4().hex, "reason": "engine_changed", "component": "strata-engine",+ "from": {k: before.get(k) for k in IDENTITY_KEYS}, "to": {k: after.get(k) for k in IDENTITY_KEYS},+ "marked_at": when}+ # a second change before the check supersedes the first: one pending re-check from the identity the presets were measured on+ older = [m for m in data["pending"] if m.get("reason") == "engine_changed"]+ if older:+ mark["from"] = older[0]["from"]+ data["pending"] = [m for m in data["pending"] if m.get("reason") != "engine_changed"]+ if all(mark["from"].get(k) == mark["to"].get(k) for k in IDENTITY_KEYS):+ _write(path, data) # rolled back to the identity the presets were measured on: nothing is owed any more+ return None+ data["pending"].append(mark)+ _write(path, data)+ return mark+++def clear(mark_id: str, base: Path | None = None) -> bool:+ path = marks_path(base)+ data = _read(path)+ kept = [m for m in data["pending"] if m.get("id") != mark_id]+ if len(kept) == len(data["pending"]):+ return False+ data["pending"] = kept+ _write(path, data)+ return Truediff --git a/strata_control/signing.py b/strata_control/signing.pynew file mode 100644index 000000000..be2424248--- /dev/null+++ b/strata_control/signing.py@@ -0,0 +1,330 @@+"""Ed25519 signatures for the update feed and the engine components, with no third-party package.++The packaged Control ships a pinned CPython with hash-locked wheels; adding a crypto wheel for one signature check would+widen that lock for no gain. Ed25519 (RFC 8032) is small enough to carry here: verification is what every installed PC+runs, signing is what the owner's release machine runs (`packaging/feed_tool.py`). Both are checked against the RFC's+test vectors in tests/terminal/test_update_feed.py.++Two kinds of key exist and must not be mixed up:++* the **feed/component key** (this module): an Ed25519 key the owner keeps offline. It signs the update feed index and every+ engine package manifest. Installed copies of Control carry the public half in ``update_keys.json`` and nothing else+ can add to it except the explicit, documented override ``STRATA_UPDATE_TRUSTED_KEYS`` (a file of extra public keys;+ the test suite and a local feed use it, and the CLI says so when it is in effect).+* the **app updater key** (Tauri's minisign key): signs the desktop installer. ``minisign_verify`` below checks such a+ signature so the Terminal can verify an app installer it downloads, the same way the Tauri updater does.++A public key is ``{"key_id": "<16 hex>", "alg": "ed25519", "public": "<base64 of the 32 bytes>"}``. ``key_id`` is the first 8 bytes+of SHA-256 of the public key, so a signature names the key that made it without anyone choosing the name.+"""++from __future__ import annotations++import base64+import hashlib+import json+import os+import secrets+from pathlib import Path++ALG = "ed25519"+ENV_EXTRA_KEYS = "STRATA_UPDATE_TRUSTED_KEYS"+BUILTIN_KEYS = Path(__file__).with_name("update_keys.json")+++class SignatureError(ValueError):+ """A signature, a key or a signed document is not what it claims to be."""+++# ---------------------------------------------------------------------------------------------- RFC 8032 Ed25519++_P = 2 ** 255 - 19+_L = 2 ** 252 + 27742317777372353535851937790883648493+_D = -121665 * pow(121666, _P - 2, _P) % _P+_I = pow(2, (_P - 1) // 4, _P)+++def _inv(x: int) -> int:+ return pow(x, _P - 2, _P)+++def _recover_x(y: int, sign: int) -> int | None:+ if y >= _P:+ return None+ xx = (y * y - 1) * _inv(_D * y * y + 1) % _P+ x = pow(xx, (_P + 3) // 8, _P)+ if (x * x - xx) % _P != 0:+ x = x * _I % _P+ if (x * x - xx) % _P != 0:+ return None+ if x == 0 and sign:+ return None+ if x & 1 != sign:+ x = _P - x+ return x+++_GY = 4 * _inv(5) % _P+_GX = _recover_x(_GY, 0)+_G = (_GX, _GY, 1, _GX * _GY % _P)+++def _add(a, b):+ a1 = (a[1] - a[0]) * (b[1] - b[0]) % _P+ b1 = (a[1] + a[0]) * (b[1] + b[0]) % _P+ c1 = 2 * a[3] * b[3] * _D % _P+ d1 = 2 * a[2] * b[2] % _P+ e, f, g, h = b1 - a1, d1 - c1, d1 + c1, b1 + a1+ return (e * f % _P, g * h % _P, f * g % _P, e * h % _P)+++def _mul(scalar: int, point):+ result = (0, 1, 1, 0)+ while scalar > 0:+ if scalar & 1:+ result = _add(result, point)+ point = _add(point, point)+ scalar >>= 1+ return result+++def _equal(a, b) -> bool:+ return (a[0] * b[2] - b[0] * a[2]) % _P == 0 and (a[1] * b[2] - b[1] * a[2]) % _P == 0+++def _compress(point) -> bytes:+ zi = _inv(point[2])+ x, y = point[0] * zi % _P, point[1] * zi % _P+ return int(y | ((x & 1) << 255)).to_bytes(32, "little")+++def _decompress(data: bytes):+ if len(data) != 32:+ return None+ value = int.from_bytes(data, "little")+ y, sign = value & ((1 << 255) - 1), value >> 255+ x = _recover_x(y, sign)+ if x is None:+ return None+ return (x, y, 1, x * y % _P)+++def _sha512(*parts: bytes) -> bytes:+ return hashlib.sha512(b"".join(parts)).digest()+++def _secret_expand(seed: bytes) -> tuple[int, bytes]:+ if len(seed) != 32:+ raise SignatureError("an Ed25519 seed is 32 bytes")+ h = _sha512(seed)+ a = int.from_bytes(h[:32], "little")+ a &= (1 << 254) - 8+ a |= 1 << 254+ return a, h[32:]+++def public_from_seed(seed: bytes) -> bytes:+ a, _ = _secret_expand(seed)+ return _compress(_mul(a, _G))+++def sign_raw(seed: bytes, message: bytes) -> bytes:+ a, prefix = _secret_expand(seed)+ public = _compress(_mul(a, _G))+ r = int.from_bytes(_sha512(prefix, message), "little") % _L+ big_r = _compress(_mul(r, _G))+ h = int.from_bytes(_sha512(big_r, public, message), "little") % _L+ s = (r + h * a) % _L+ return big_r + int(s).to_bytes(32, "little")+++def verify_raw(public: bytes, message: bytes, signature: bytes) -> bool:+ """RFC 8032 verification (cofactorless; non-canonical encodings and s >= L are refused)."""+ if len(public) != 32 or len(signature) != 64:+ return False+ point_a = _decompress(public)+ point_r = _decompress(signature[:32])+ if point_a is None or point_r is None:+ return False+ s = int.from_bytes(signature[32:], "little")+ if s >= _L:+ return False+ h = int.from_bytes(_sha512(signature[:32], public, message), "little") % _L+ return _equal(_mul(s, _G), _add(point_r, _mul(h, point_a)))+++# ---------------------------------------------------------------------------------------------- keys++def key_id_of(public: bytes) -> str:+ return hashlib.sha256(public).digest()[:8].hex()+++def generate_key() -> dict:+ """A new key pair as the dictionary `write_key_files` stores. The seed is the secret: it is never printed."""+ seed = secrets.token_bytes(32)+ public = public_from_seed(seed)+ return {"alg": ALG, "key_id": key_id_of(public),+ "public": base64.b64encode(public).decode("ascii"), "seed": base64.b64encode(seed).decode("ascii")}+++def public_part(key: dict) -> dict:+ return {"alg": ALG, "key_id": key["key_id"], "public": key["public"]}+++def _b64(value, what: str, length: int) -> bytes:+ try:+ raw = base64.b64decode(str(value), validate=True)+ except (ValueError, TypeError):+ raise SignatureError(f"{what} is not valid base64") from None+ if len(raw) != length:+ raise SignatureError(f"{what} must be {length} bytes")+ return raw+++def parse_public(entry: dict) -> tuple[str, bytes]:+ if not isinstance(entry, dict) or entry.get("alg") != ALG:+ raise SignatureError("a public key entry needs alg ed25519")+ public = _b64(entry.get("public"), "a public key", 32)+ key_id = key_id_of(public)+ if entry.get("key_id") != key_id:+ raise SignatureError(f"the key_id {entry.get('key_id')!r} does not belong to that public key")+ return key_id, public+++def load_trusted_keys(extra: str | os.PathLike | None = None, *, environ=None) -> dict[str, bytes]:+ """{key_id: public key bytes}: the keys shipped in ``update_keys.json`` plus a file of extra keys when+ ``STRATA_UPDATE_TRUSTED_KEYS`` (or `extra`) names one. A malformed entry is an error, never skipped, so a typo cannot+ quietly turn into "trust nothing" or "trust something else"."""+ environ = os.environ if environ is None else environ+ keys: dict[str, bytes] = {}+ for path in (BUILTIN_KEYS, extra or environ.get(ENV_EXTRA_KEYS)):+ if not path:+ continue+ p = Path(path)+ if p == BUILTIN_KEYS and not p.exists():+ continue+ try:+ data = json.loads(p.read_text(encoding="utf-8-sig"))+ except (OSError, ValueError) as exc:+ raise SignatureError(f"the key file {p} cannot be read ({type(exc).__name__})") from None+ entries = data.get("keys") if isinstance(data, dict) else data+ if not isinstance(entries, list):+ raise SignatureError(f"the key file {p} has no list of keys")+ for entry in entries:+ key_id, public = parse_public(entry)+ keys[key_id] = public+ return keys+++def extra_keys_in_effect(environ=None) -> bool:+ environ = os.environ if environ is None else environ+ return bool(environ.get(ENV_EXTRA_KEYS))+++# ---------------------------------------------------------------------------------------------- signing documents++def sign_bytes(key: dict, payload: bytes) -> dict:+ """``{"alg", "key_id", "value"}`` over exactly `payload`."""+ seed = _b64(key.get("seed"), "the secret seed", 32)+ if public_from_seed(seed) != base64.b64decode(key["public"]) or key_id_of(public_from_seed(seed)) != key["key_id"]:+ raise SignatureError("the secret seed does not match the public key in the key file")+ return {"alg": ALG, "key_id": key["key_id"], "value": base64.b64encode(sign_raw(seed, payload)).decode("ascii")}+++def verify_bytes(trusted: dict[str, bytes], payload: bytes, signature: dict) -> str:+ """The key_id that signed `payload`; raises SignatureError when the signature is missing, from an unknown key, or bad."""+ if not isinstance(signature, dict) or signature.get("alg") != ALG:+ raise SignatureError("the signature is not an ed25519 signature")+ key_id = signature.get("key_id")+ public = trusted.get(key_id) if isinstance(key_id, str) else None+ if public is None:+ raise SignatureError(f"the signature was made by a key this PC does not trust ({key_id!r})")+ raw = _b64(signature.get("value"), "the signature value", 64)+ if not verify_raw(public, payload, raw):+ raise SignatureError("the signature does not match the signed content")+ return key_id+++def install_component_verifier(trusted: dict[str, bytes]) -> None:+ """Hook the engine component's signature check (engine_component.register_signature_verifier) to `trusted`.+ A manifest then counts as verified only if one of these keys signed its canonical payload."""+ from strata_control import engine_component++ def verifier(payload: bytes, signature: dict, component) -> None:+ try:+ verify_bytes(trusted, payload, signature)+ except SignatureError as exc:+ raise engine_component.IntegrityProblem(str(exc)) from None++ engine_component.register_signature_verifier(verifier)+++def ensure_component_verifier() -> bool:+ """Register the verifier with the shipped keys (and the explicit extra-keys file) unless one is registered already.+ Returns False when there are no keys to check against: signed packages are then reported unverified, never verified."""+ from strata_control import engine_component+ if engine_component._verifier is not None:+ return True+ trusted = load_trusted_keys()+ if not trusted:+ return False+ install_component_verifier(trusted)+ return True+++# ---------------------------------------------------------------------------------------------- minisign (Tauri updater)++def minisign_public(text_or_b64: str) -> tuple[bytes, bytes]:+ """(key id, public key) from a minisign public key: the Tauri ``pubkey`` value (base64 of the .pub file) or the file text."""+ text = text_or_b64.strip()+ if "untrusted comment" not in text:+ try:+ text = base64.b64decode(text, validate=True).decode("utf-8")+ except (ValueError, UnicodeError):+ raise SignatureError("the minisign public key is not valid") from None+ lines = [line for line in text.splitlines() if line.strip() and not line.startswith("untrusted comment")]+ if not lines:+ raise SignatureError("the minisign public key has no key line")+ raw = _b64(lines[0].strip(), "the minisign public key", 42)+ if raw[:2] != b"Ed":+ raise SignatureError("the minisign public key is not an Ed25519 key")+ return raw[2:10], raw[10:42]+++def minisign_verify(public_text: str, signature_text: str, data_chunks) -> None:+ """Check a minisign signature (the Tauri updater's format) over `data_chunks` (an iterable of bytes).++ Legacy ``Ed`` signs the data itself, ``ED`` signs its BLAKE2b-512 digest (what Tauri produces); both are accepted.+ The signature can be the Tauri updater JSON value (base64 of the .sig file) or the file text."""+ key_id, public = minisign_public(public_text)+ text = signature_text.strip()+ if "untrusted comment" not in text:+ try:+ text = base64.b64decode(text, validate=True).decode("utf-8")+ except (ValueError, UnicodeError):+ raise SignatureError("the app signature is not valid base64") from None+ lines = [line for line in text.splitlines() if line.strip()]+ body = [line for line in lines if not line.startswith(("untrusted comment", "trusted comment"))]+ if not body:+ raise SignatureError("the app signature has no signature line")+ raw = _b64(body[0].strip(), "the app signature", 74)+ algorithm, signer, signature = raw[:2], raw[2:10], raw[10:74]+ if signer != key_id:+ raise SignatureError("the app signature was made by a different key than the one this build trusts")+ if algorithm == b"ED":+ digest = hashlib.blake2b(digest_size=64)+ for chunk in data_chunks:+ digest.update(chunk)+ message = digest.digest()+ elif algorithm == b"Ed":+ message = b"".join(data_chunks)+ else:+ raise SignatureError("the app signature uses an unknown algorithm")+ if not verify_raw(public, message, signature):+ raise SignatureError("the app installer does not match its signature")+ # the global signature covers the trusted comment: it is checked when present so a tampered comment is refused too+ comment = next((line[len("trusted comment: "):] for line in lines if line.startswith("trusted comment: ")), None)+ if comment is not None and len(body) > 1:+ global_sig = _b64(body[1].strip(), "the app signature's global part", 64)+ if not verify_raw(public, signature + comment.encode("utf-8"), global_sig):+ raise SignatureError("the app signature's comment was changed")diff --git a/strata_control/transfer.py b/strata_control/transfer.pynew file mode 100644index 000000000..5aa85fb65--- /dev/null+++ b/strata_control/transfer.py@@ -0,0 +1,244 @@+"""Fetching update files: small documents, and large archives with resume and progress.++This is the only network code of the update path. It is reached from `strata update` / `strata components update` and+the app's explicit "Update" step, never from a start or a serve: ``require_acquisition`` is called by the caller before+anything here runs, and it refuses under ``STRATA_NO_ACQUIRE``.++A *source* is where the feed lives: an ``https://`` URL (or ``http://`` to a loopback address, which is how a local test+feed is served), a ``file://`` URL, or a plain folder / file path. Everything the feed points at is resolved against it+by `resolve_ref`, which refuses a reference that leaves the source.+"""++from __future__ import annotations++import hashlib+import http.client+import ipaddress+import os+import threading+import urllib.error+import urllib.parse+import urllib.request+from pathlib import Path+from typing import Callable++CHUNK = 1 << 20+SMALL_LIMIT = 8 << 20+ENV_ALLOW_HTTP = "STRATA_UPDATE_ALLOW_HTTP"+++class TransferError(RuntimeError):+ """Something could not be fetched. `resumable` says whether a partial file was kept for the next attempt."""++ def __init__(self, message: str, *, resumable: bool = False):+ super().__init__(message)+ self.resumable = resumable+++class ChecksumMismatch(TransferError):+ """The bytes arrived but are not the bytes the signed feed names. The partial file was deleted."""+++class Cancelled(TransferError):+ """The caller asked to stop. The partial file is kept."""++ def __init__(self, message: str = "cancelled"):+ super().__init__(message, resumable=True)+++def _is_loopback(host: str) -> bool:+ if host in ("localhost",):+ return True+ try:+ return ipaddress.ip_address(host).is_loopback+ except ValueError:+ return False+++def kind_of(source: str) -> str:+ """"http", "https", "file" or "path"."""+ parsed = urllib.parse.urlparse(source)+ if len(parsed.scheme) == 1: # a Windows drive letter+ return "path"+ if parsed.scheme in ("http", "https", "file"):+ return parsed.scheme+ if parsed.scheme:+ raise TransferError(f"the update source scheme {parsed.scheme!r} is not supported (https, a loopback http, file or a folder)")+ return "path"+++def check_url_policy(url: str, environ=None) -> None:+ environ = os.environ if environ is None else environ+ parsed = urllib.parse.urlparse(url)+ if parsed.scheme == "https":+ return+ if parsed.scheme == "http":+ if _is_loopback(parsed.hostname or "") or environ.get(ENV_ALLOW_HTTP) == "1":+ return+ raise TransferError(f"{url} is plain http; updates are fetched over https (a loopback address is the only exception)")+ raise TransferError(f"{url} is not an https address")+++def _local_path(source: str) -> Path:+ if source.startswith("file:"):+ parsed = urllib.parse.urlparse(source)+ path = urllib.request.url2pathname(parsed.path)+ if os.name == "nt" and path.startswith(("/", "\\")) and len(path) > 2 and path[2] == ":":+ path = path[1:]+ return Path(path)+ return Path(source)+++def base_of(source: str) -> str:+ """The folder / URL prefix that references in the feed are relative to."""+ kind = kind_of(source)+ if kind in ("http", "https"):+ return source.rsplit("/", 1)[0] + "/"+ path = _local_path(source)+ return str(path.parent if path.suffix else path)+++def resolve_ref(base: str, ref: str, environ=None) -> str:+ """The absolute location a feed reference points at. A relative reference stays inside the base; an absolute one must+ pass the URL policy (https, or a loopback http) and, for a local base, may not be a remote address at all."""+ if not isinstance(ref, str) or not ref or "\0" in ref or "\\" in ref:+ raise TransferError(f"the feed contains an unusable file reference {ref!r}")+ parsed = urllib.parse.urlparse(ref)+ kind = kind_of(base)+ if parsed.scheme:+ if kind in ("path", "file"):+ raise TransferError(f"the local feed refers to a remote address ({ref}); a local feed may only name files inside its own folder")+ check_url_policy(ref, environ)+ return ref+ if ref.startswith("/") or ".." in ref.split("/"):+ raise TransferError(f"the feed reference {ref!r} leaves the feed's own location")+ if kind in ("http", "https"):+ return urllib.parse.urljoin(base if base.endswith("/") else base + "/", ref)+ root = _local_path(base).resolve()+ target = (root / ref).resolve()+ if root != target and root not in target.parents:+ raise TransferError(f"the feed reference {ref!r} leaves the feed's own folder")+ return str(target)+++class _PolicyRedirects(urllib.request.HTTPRedirectHandler):+ def redirect_request(self, req, fp, code, msg, headers, newurl):+ check_url_policy(newurl)+ return super().redirect_request(req, fp, code, msg, headers, newurl)+++_opener = urllib.request.build_opener(_PolicyRedirects)+_USER_AGENT = "strata-updater/1"+++def read_small(location: str, *, limit: int = SMALL_LIMIT, timeout: float = 30) -> bytes:+ """A small document (the feed, its signature). Larger than `limit` is refused, not truncated."""+ kind = kind_of(location)+ try:+ if kind in ("http", "https"):+ check_url_policy(location)+ request = urllib.request.Request(location, headers={"User-Agent": _USER_AGENT, "Cache-Control": "no-cache"})+ with _opener.open(request, timeout=timeout) as response:+ data = response.read(limit + 1)+ else:+ path = _local_path(location)+ if path.stat().st_size > limit:+ raise TransferError(f"{location} is larger than {limit} bytes")+ data = path.read_bytes()+ except TransferError:+ raise+ except urllib.error.HTTPError as exc:+ raise TransferError(f"the update server answered {exc.code} for {location}") from None+ except (urllib.error.URLError, OSError, TimeoutError) as exc:+ reason = getattr(exc, "reason", exc)+ raise TransferError(f"could not read {location} ({type(exc).__name__}: {reason})") from None+ if len(data) > limit:+ raise TransferError(f"{location} is larger than {limit} bytes")+ return data+++def sha256_file(path: Path) -> str:+ digest = hashlib.sha256()+ with Path(path).open("rb") as stream:+ for block in iter(lambda: stream.read(CHUNK), b""):+ digest.update(block)+ return digest.hexdigest()+++def download(location: str, partial: Path, *, size: int, sha256: str,+ progress: Callable[[int, int], None] | None = None,+ cancel: threading.Event | None = None, timeout: float = 60) -> Path:+ """Fetch `location` into `partial` (resuming what is there) and return it once it has exactly `size` bytes and the+ SHA-256 `sha256`. An interrupted transfer keeps the partial file (`TransferError.resumable`); a complete file with the+ wrong hash is deleted, because resuming cannot repair it."""+ partial = Path(partial)+ partial.parent.mkdir(parents=True, exist_ok=True)+ have = partial.stat().st_size if partial.exists() else 0+ if have > size:+ partial.unlink()+ have = 0+ if have < size:+ _transfer(location, partial, have, size, progress, cancel, timeout)+ elif progress:+ progress(size, size)+ final = partial.stat().st_size+ if final != size:+ raise TransferError(f"{location} delivered {final} of {size} bytes; the partial file is kept and the next try resumes it",+ resumable=True)+ if sha256_file(partial) != sha256.lower():+ partial.unlink(missing_ok=True)+ raise ChecksumMismatch(f"{location} does not match the SHA-256 in the signed feed; the download was deleted")+ return partial+++def _transfer(location, partial: Path, have: int, size: int, progress, cancel, timeout) -> None:+ kind = kind_of(location)+ done = have+ try:+ if kind in ("http", "https"):+ check_url_policy(location)+ headers = {"User-Agent": _USER_AGENT}+ if have:+ headers["Range"] = f"bytes={have}-"+ request = urllib.request.Request(location, headers=headers)+ with _opener.open(request, timeout=timeout) as response:+ if have and response.status != 206:+ have = done = 0 # the server ignored the range: start over, never append to a prefix+ _copy(response, partial, "wb" if not have else "ab", done, size, progress, cancel)+ else:+ path = _local_path(location)+ with path.open("rb") as source:+ source.seek(have)+ _copy(source, partial, "ab" if have else "wb", have, size, progress, cancel)+ except Cancelled:+ raise+ except urllib.error.HTTPError as exc:+ if exc.code == 416:+ partial.unlink(missing_ok=True)+ raise TransferError(f"the server could not resume {location}; the partial file was removed, try again",+ resumable=False) from None+ raise TransferError(f"the update server answered {exc.code} for {location}") from None+ except (urllib.error.URLError, OSError, TimeoutError, ConnectionError, http.client.HTTPException) as exc:+ got = partial.stat().st_size if partial.exists() else 0+ reason = getattr(exc, "reason", exc)+ raise TransferError(f"the download of {location} was interrupted after {got} of {size} bytes "+ f"({type(exc).__name__}: {reason}); the partial file is kept and the next try resumes it",+ resumable=True) from None+++def _copy(source, partial: Path, mode: str, done: int, size: int, progress, cancel) -> None:+ with partial.open(mode) as out:+ while True:+ if cancel is not None and cancel.is_set():+ out.flush()+ raise Cancelled()+ block = source.read(CHUNK)+ if not block:+ break+ if done + len(block) > size:+ raise TransferError("the server sent more bytes than the feed says; the download was stopped")+ out.write(block)+ done += len(block)+ if progress:+ progress(done, size)+ out.flush()diff --git a/strata_control/update_keys.json b/strata_control/update_keys.jsonnew file mode 100644index 000000000..c6e1b771f--- /dev/null+++ b/strata_control/update_keys.json@@ -0,0 +1,4 @@+{+ "schema_version": 1,+ "keys": []+}diff --git a/strata_control/updater.py b/strata_control/updater.pynew file mode 100644index 000000000..bfba51656--- /dev/null+++ b/strata_control/updater.py@@ -0,0 +1,930 @@+"""The component updater: the one explicit step that downloads and installs engines (and Control, and the app installer).++Everything that fetches software lives behind this module. Starting or serving never imports it (`acquisition.require`+refuses here when ``STRATA_NO_ACQUIRE`` is set), so a PC that only runs models never reaches the network.++What an engine update does, in order, and what keeps the old engine safe at each point:++1. read the signed feed (`feed.py`); a bad signature, an expired feed or an older sequence number ends here;+2. detect the hardware and pick the best package that fits it (`feed.select_engine`); nothing newer, nothing to do;+3. refuse to go on while an engine is serving (wait, or ask);+4. download the archive next to the component folder with resume and progress; the SHA-256 in the signed feed decides;+5. unpack it into a *staging* component folder (``.updates/staging/<id>/engine/<name>``), never into the live ``engine/``;+6. check the package: the manifest is the one the feed named (SHA-256), says what the feed says, carries a valid+ signature, every file matches its recorded hash, and it fits this PC;+7. **test-start** it from the staging folder through the real start path (owner runtime, a saved model, one token);+8. only if that passed, move it into ``engine/`` (a rename), re-resolve to confirm it is the one a start will pick, record the+ previous version for a manual rollback, and mark saved tuning presets for the short re-check.++If any step fails, the live ``engine/`` folder has not changed: the previous engine keeps working, and what failed is+named. The previous version stays installed (``strata components rollback`` returns to it); older ones are removed.+Models and presets are never read, moved, deleted or downloaded here.+"""++from __future__ import annotations++import contextlib+import datetime as dt+import json+import os+import re+import shutil+import socket+import subprocess+import sys+import tarfile+import tempfile+import threading+import time+import uuid+import zipfile+from dataclasses import dataclass, field+from pathlib import Path+from typing import Callable++from strata_control import acquisition, components, engine_component as ec, feed as feedmod, preset_marks, signing, transfer+from strata_control.targets import host_platform++STATE_DIR = ".updates"+SKEW_FREE_BYTES = 1.15+++class UpdateError(RuntimeError):+ """An update step stopped. `exit_code` is the CLI's; the old engine is untouched unless the message says otherwise."""++ def __init__(self, message: str, exit_code: int = 6):+ super().__init__(message)+ self.exit_code = exit_code+++class Busy(UpdateError):+ """An engine is serving, so nothing was installed or switched."""++ def __init__(self, serving: list[dict]):+ names = ", ".join(item.get("profile", "an engine") for item in serving) or "an engine"+ super().__init__(f"{names} is serving. Stop it (or wait until it is idle) and run the update again; "+ "the update never replaces or tests an engine while one is serving.", 7)+ self.serving = serving+++class TestStartFailed(UpdateError):+ __test__ = False # not a pytest class++ def __init__(self, label: str, reason: str):+ super().__init__(f"The new engine {label} did not pass its test start ({reason}). It was not installed; "+ "your current engine is unchanged.", 6)+ self.label = label+ self.reason = reason+++# ---------------------------------------------------------------------------------------------- state++def updates_dir(root: Path) -> Path:+ return root / STATE_DIR+++def update_lock(root: Path):+ """One updater at a time per component folder."""+ directory = updates_dir(root)+ directory.mkdir(parents=True, exist_ok=True)+ handle = open(directory / "update.lock", "a+b")+ try:+ if os.name == "nt":+ import msvcrt+ handle.seek(0)+ try:+ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)+ except OSError:+ raise UpdateError("another update is already running for this component folder", 7) from None+ else:+ import fcntl+ try:+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)+ except OSError:+ raise UpdateError("another update is already running for this component folder", 7) from None+ yield+ finally:+ try:+ if os.name == "nt":+ import msvcrt+ handle.seek(0)+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)+ except OSError:+ pass+ handle.close()+++class State:+ """``<components>/.updates/state.json``: the last accepted feed sequence, which engine is the previous one, a pin set by a+ manual rollback, versions not to offer again. Plain JSON, replaced atomically; a damaged file reads as empty."""++ def __init__(self, root: Path):+ self.path = updates_dir(root) / "state.json"+ self.data = self._read()++ def _read(self) -> dict:+ try:+ data = json.loads(self.path.read_text(encoding="utf-8-sig"))+ if isinstance(data, dict):+ return data+ except (OSError, ValueError):+ pass+ return {}++ def section(self, name: str) -> dict:+ value = self.data.get(name)+ if not isinstance(value, dict):+ value = self.data[name] = {}+ return value++ def history(self, entry: dict) -> None:+ log = self.data.setdefault("history", [])+ log.append(entry)+ del log[:-30]++ def save(self) -> None:+ self.path.parent.mkdir(parents=True, exist_ok=True)+ self.data["schema_version"] = 1+ descriptor, temp = tempfile.mkstemp(prefix=".state-", suffix=".tmp", dir=self.path.parent)+ try:+ with os.fdopen(descriptor, "w", encoding="utf-8") as stream:+ json.dump(self.data, stream, indent=1, sort_keys=True)+ stream.write("\n")+ os.replace(temp, self.path)+ finally:+ if os.path.exists(temp):+ os.unlink(temp)+++# ---------------------------------------------------------------------------------------------- hardware++def _gfx_names() -> list[str]:+ found: list[str] = []+ kfd = Path("/sys/class/kfd/kfd/topology/nodes")+ if kfd.is_dir():+ for node in sorted(kfd.iterdir()):+ try:+ text = (node / "properties").read_text()+ except OSError:+ continue+ match = re.search(r"^gfx_target_version\s+(\d+)", text, re.MULTILINE)+ if match and int(match.group(1)) > 0:+ value = int(match.group(1))+ found.append(f"gfx{value // 10000}{(value // 100) % 100:x}{value % 100:x}")+ if not found:+ tool = shutil.which("rocminfo") if os.name != "nt" else shutil.which("hipInfo")+ if tool:+ try:+ done = subprocess.run([tool], capture_output=True, text=True, timeout=10,+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))+ found = sorted(set(re.findall(r"\bgfx[0-9a-f]{3,4}\b", done.stdout)))+ except (OSError, subprocess.SubprocessError):+ pass+ return sorted(set(found))+++def detect_hardware(environ=None) -> dict:+ """What the package choice depends on. Read-only probes of tools that are already installed (nvidia-smi, rocminfo, sysfs);+ ``STRATA_ENGINE_BACKEND`` overrides the backend like it does for a start. Anything unreadable is left empty, which the+ selection treats as "cannot tell", never as a refusal."""+ environ = os.environ if environ is None else environ+ backend, how = ec.detect_backend(environ)+ hw = {"platform": host_platform(), "backend": backend, "backend_source": how, "runtime": ec.runtime_version(),+ "nvidia_driver": None, "cuda_archs": [], "gfx": []}+ if backend == "cuda":+ hw["nvidia_driver"] = ec.nvidia_driver_version()+ hw["cuda_archs"] = ec.cuda_archs_present()+ elif backend == "hip":+ hw["gfx"] = _gfx_names()+ return hw+++# ---------------------------------------------------------------------------------------------- serving++def serving_now() -> list[dict]:+ """Engines that are serving: managed instances of the owner runtime and anything holding the shared activity lease+ (`strata serve`, a runtime host). Empty when nothing is. The exclusive lease is only tried, never kept."""+ from strata_control import profiles, runtime+ try:+ managed = runtime.active_managed_instances()+ except (profiles.ProfileError, OSError):+ managed = []+ if managed:+ return managed+ try:+ descriptor = runtime.acquire_activity_lease(shared=False)+ except profiles.ProfileError as exc:+ if "lease" in str(exc):+ return [{"profile": "a running Strata server", "state": "serving"}]+ return []+ except OSError:+ return []+ try:+ os.close(descriptor)+ except OSError:+ pass+ return []+++def wait_until_idle(check: Callable[[], list[dict]], *, wait: float, emit: Callable, cancel=None,+ poll: float = 3.0) -> None:+ """Return when nothing is serving; raise `Busy` if something still is after `wait` seconds (0 = do not wait)."""+ deadline = time.monotonic() + wait+ serving = check()+ while serving:+ if wait <= 0 or time.monotonic() >= deadline or (cancel is not None and cancel.is_set()):+ raise Busy(serving)+ emit({"event": "waiting", "message": "An engine is serving; waiting for it to stop before updating.",+ "serving": serving})+ time.sleep(poll)+ serving = check()+++# ---------------------------------------------------------------------------------------------- context++@dataclass+class Context:+ components: Path+ source: str+ trusted: dict+ hardware: dict+ emit: Callable[[dict], None] = lambda event: None+ cancel: threading.Event | None = None+ test_start: Callable | None = None # (stage_root, component, ctx) -> dict; defaults to `default_test_start`+ serving: Callable[[], list[dict]] = serving_now+ wait: float = 0.0 # seconds to wait for a serving engine to stop+ force: bool = False+ channel: str = "stable"+ app_version: str | None = None+ now: dt.datetime | None = None+ run_config: str | None = None # a run config for the test start (default: an installed model's)+ test_timeout: float = 600.0+ poll: float = 3.0+ environ: dict = field(default_factory=lambda: dict(os.environ))+ allow_no_model_smoke: bool = True+ state_base: Path | None = None # where tuning/recheck.json goes (default: the per-user state folder)++ def say(self, phase: str, message: str, **extra) -> None:+ self.emit({"event": "phase", "phase": phase, "message": message, **extra})+++def require_acquisition(what: str) -> None:+ """The update path acquires by definition; a process that has forbidden acquiring (a start, a serve) may not run it."""+ acquisition.require(what, "`strata update` from a terminal")+++def open_feed(ctx: Context, state: State) -> feedmod.Feed:+ require_acquisition("the update feed")+ last = (state.data.get("feed") or {}).get("sequence")+ ctx.say("feed", "Reading the signed update feed")+ loaded = feedmod.fetch(ctx.source, ctx.trusted, last_sequence=last, channel=ctx.channel, now=ctx.now)+ info = state.section("feed")+ info.update({"sequence": loaded.sequence, "key_id": loaded.key_id, "source": ctx.source, "channel": loaded.channel,+ "checked_at": (ctx.now or dt.datetime.now(dt.timezone.utc)).isoformat()})+ return loaded+++# ---------------------------------------------------------------------------------------------- archives++def _archive_size(archive: Path, fmt: str) -> int:+ if fmt == "zip":+ with zipfile.ZipFile(archive) as zf:+ return sum(info.file_size for info in zf.infolist())+ mode = {"tar.gz": "r:gz", "tar.xz": "r:xz"}[fmt]+ with tarfile.open(archive, mode) as tar:+ return sum(m.size for m in tar.getmembers() if m.isfile())+++def extract(archive: Path, destination: Path, fmt: str, installed_bytes: int) -> None:+ """Unpack into a fresh folder. The archive's own total size must not exceed what the signed feed declared, so a package+ cannot grow into a disk-filling bomb; names and links are checked by `components.safe_extract` before anything is written."""+ try:+ total = _archive_size(archive, fmt)+ except (tarfile.TarError, zipfile.BadZipFile, OSError, EOFError) as exc:+ raise UpdateError(f"the downloaded archive cannot be read ({type(exc).__name__})", 5) from None+ if total > installed_bytes:+ raise UpdateError(f"the archive holds {total} bytes, the signed feed says the package is {installed_bytes}; not unpacked", 5)+ if destination.exists():+ shutil.rmtree(destination, ignore_errors=True)+ try:+ components.safe_extract(archive, destination, fmt=fmt)+ except components.ComponentError as exc:+ shutil.rmtree(destination, ignore_errors=True)+ raise UpdateError(f"the archive was refused: {exc}", 5) from None+++def _free_space_check(root: Path, need: int) -> None:+ root.mkdir(parents=True, exist_ok=True)+ free = shutil.disk_usage(root).free+ if free < need * SKEW_FREE_BYTES:+ raise UpdateError(f"not enough free space in {root}: {free // (1 << 20)} MiB free, about {int(need * SKEW_FREE_BYTES) // (1 << 20)} MiB needed", 6)+++def _download(ctx: Context, state_name: str, url_ref: str, size: int, sha256: str, label: str, feed: feedmod.Feed) -> Path:+ work = updates_dir(ctx.components) / "partial"+ partial = work / f"{sha256[:16]}.part"+ start = time.monotonic()+ last = {"at": 0.0, "pct": -1}++ def progress(done: int, total: int) -> None:+ now = time.monotonic()+ pct = int(done * 100 / total) if total else 0+ if now - last["at"] >= 0.25 or pct != last["pct"] and pct in (0, 100):+ last["at"], last["pct"] = now, pct+ rate = done / max(now - start, 1e-6)+ ctx.emit({"event": "progress", "phase": "download", "component": state_name, "label": label,+ "done": done, "total": total, "percent": pct, "bytes_per_second": int(rate)})++ ctx.say("download", f"Downloading {label} ({size / (1 << 20):.0f} MiB)", component=state_name)+ try:+ return transfer.download(feed.url(url_ref), partial, size=size, sha256=sha256, progress=progress, cancel=ctx.cancel)+ except transfer.Cancelled:+ raise UpdateError("the update was stopped; the partial download is kept and the next update resumes it", 130) from None+ except transfer.ChecksumMismatch as exc:+ raise UpdateError(str(exc), 5) from None+ except transfer.TransferError as exc:+ raise UpdateError(str(exc), 6) from None+++# ---------------------------------------------------------------------------------------------- engine++def folder_name(pkg: feedmod.EnginePackage) -> str:+ return f"{pkg.version}-{pkg.platform}-{pkg.backend}" + (f"-{pkg.variant}" if pkg.variant else "")+++def _manifest_sha(folder: Path) -> str:+ return transfer.sha256_file(folder / ec.MANIFEST)+++def installed_engine(root: Path, hardware: dict) -> tuple[ec.EngineComponent | None, str | None]:+ """(the engine a start would use, why not). A package that fails its integrity check is reported, not hidden."""+ try:+ return ec.resolve(root, backend=hardware.get("backend"), full=True, runtime=hardware.get("runtime")), None+ except ec.EngineMissing as exc:+ return None, str(exc)+++def _engine_view(component: ec.EngineComponent | None) -> dict | None:+ if component is None:+ return None+ return {"version": component.version, "platform": component.platform, "backend": component.backend,+ "variant": component.variant, "build_id": component.build_id, "folder": component.root.name,+ "signed": bool(component.signature)}+++def decide_engine(feed: feedmod.Feed, ctx: Context, state: State) -> dict:+ """What an update would do for the engine, without downloading anything."""+ return _choose_engine(feed, ctx, state)[0]+++def _choose_engine(feed: feedmod.Feed, ctx: Context, state: State) -> tuple[dict, feedmod.EnginePackage | None]:+ installed, missing_reason = installed_engine(ctx.components, ctx.hardware)+ offered, reasons = feedmod.select_engine([p for p in feed.engine], ctx.hardware)+ section = state.section("engine")+ report = {"installed": _engine_view(installed), "offered": offered.to_dict() if offered else None,+ "reasons": reasons, "status": "none-for-this-pc", "download_bytes": 0,+ "previous": section.get("previous"), "pinned": section.get("pinned"),+ "problem": missing_reason if installed is None and missing_reason and "holds no engine" not in missing_reason else None}+ if offered is None:+ if not feed.engine:+ report["status"] = "not-in-feed"+ return report, None+ report["download_bytes"] = offered.size+ if installed is None:+ report["status"] = "install"+ return report, offered+ have, want = feedmod.version_key(installed.version), feedmod.version_key(offered.version)+ if want < have:+ report["status"] = "current"+ report["note"] = f"the feed offers {offered.version}, older than the installed {installed.version}; an update never downgrades"+ elif want == have:+ report["status"] = "current"+ else:+ report["status"] = "available"+ bad = (section.get("failed") or {}).get(offered.version)+ if report["status"] == "available" and not ctx.force:+ if bad and bad.get("manifest_sha256") == offered.manifest_sha256:+ report["status"] = "failed-before"+ report["note"] = (f"{offered.version} failed its test start on {bad.get('at', 'an earlier try')} ({bad.get('reason')}); "+ "run with --force to try it again")+ elif offered.version in (section.get("skipped") or []):+ report["status"] = "skipped"+ report["note"] = f"{offered.version} was rolled back from; run with --force to install it again"+ return report, offered+++def _serving_or_empty(ctx: Context) -> list[dict]:+ try:+ return ctx.serving()+ except Exception: # noqa: BLE001 - informational only+ return []+++def check(ctx: Context) -> dict:+ """Read the signed feed and say what an update would do for the engine, Control and the app. Downloads nothing but the feed."""+ with update_lock(ctx.components):+ state = State(ctx.components)+ feed = open_feed(ctx, state)+ report = {"feed": {"source": ctx.source, "sequence": feed.sequence, "channel": feed.channel, "key_id": feed.key_id,+ "generated_at": feed.generated_at, "trusted_by": "test key file" if signing.extra_keys_in_effect(ctx.environ) else "built-in keys"},+ "engine": decide_engine(feed, ctx, state), "control": decide_control(feed, ctx, state),+ "app": decide_app(feed, ctx), "serving": _serving_or_empty(ctx), "hardware": ctx.hardware}+ state.save()+ return report+++def stage_engine(ctx: Context, feed: feedmod.Feed, pkg: feedmod.EnginePackage, archive: Path) -> tuple[Path, ec.EngineComponent]:+ """Unpack and check a downloaded engine package in a staging component folder. Returns (staging root, component)."""+ stage_root = updates_dir(ctx.components) / "staging" / uuid.uuid4().hex[:12]+ folder = stage_root / "engine" / folder_name(pkg)+ ctx.say("verify", f"Unpacking {pkg.label}", component="engine")+ folder.parent.mkdir(parents=True, exist_ok=True)+ try:+ extract(archive, folder, pkg.format, pkg.installed_bytes)+ manifest = folder / ec.MANIFEST+ if not manifest.is_file():+ raise UpdateError(f"the package has no {ec.MANIFEST}", 5)+ if transfer.sha256_file(manifest) != pkg.manifest_sha256:+ raise UpdateError("the package's manifest is not the one the signed feed names; not installed", 5)+ try:+ component = ec.read_manifest(folder)+ except ec.ComponentProblem as exc:+ raise UpdateError(f"the package manifest is invalid: {exc}", 5) from None+ mismatches = [name for name, a, b in (+ ("version", component.version, pkg.version), ("platform", component.platform, pkg.platform),+ ("backend", component.backend, pkg.backend), ("variant", component.variant, pkg.variant),+ ("build_id", component.build_id, pkg.build_id), ("archs", set(component.archs), set(pkg.archs)),+ ("min_driver", component.min_driver, pkg.min_driver), ("min_runtime", component.min_runtime, pkg.min_runtime))+ if a != b]+ if mismatches:+ raise UpdateError(f"the package says something different from the signed feed ({', '.join(mismatches)}); not installed", 5)+ ctx.say("verify", "Checking the package signature and every file", component="engine")+ outer = ec._verifier+ signing.install_component_verifier(ctx.trusted)+ try:+ ec.verify_signature(component, {**ctx.environ, ec.ENV_REQUIRE_SIGNED: "1"})+ ec.verify(component, full=True)+ except ec.ComponentProblem as exc:+ raise UpdateError(f"the package failed its check: {exc}", 5) from None+ finally:+ ec.register_signature_verifier(outer)+ why = feedmod.engine_fit_reasons(pkg, ctx.hardware)+ if why:+ raise UpdateError("; ".join(why), 5)+ return stage_root, component+ except BaseException:+ shutil.rmtree(stage_root, ignore_errors=True)+ raise+++def discover_run_config(environ=None) -> Path | None:+ """A saved model's run config for the test start: the one a saved profile uses if its files are all present, otherwise any+ installed model whose files are present. None when no model is installed (the first run)."""+ from strata_control import models, profiles+ try:+ listed = models.list_installed()+ except Exception: # noqa: BLE001 - discovery is best effort+ return None+ ready = [m for m in listed.get("models", []) if m.get("component_status") == "present" and m.get("source_config")]+ if not ready:+ return None+ try:+ used = {profile.get("source_config") for profile in profiles.list_profiles() if profile.get("source_config")}+ except Exception: # noqa: BLE001+ used = set()+ ready.sort(key=lambda m: (m["source_config"] not in used, m["id"]))+ return Path(ready[0]["source_config"])+++def _free_port() -> int:+ with socket.socket() as probe:+ probe.bind(("127.0.0.1", 0))+ return probe.getsockname()[1]+++def _patched_environ(values: dict):+ old = {key: os.environ.get(key) for key in values}+ os.environ.update(values)+ try:+ yield+ finally:+ for key, value in old.items():+ if value is None:+ os.environ.pop(key, None)+ else:+ os.environ[key] = value+++def binary_smoke(component: ec.EngineComponent, timeout: float = 60) -> dict:+ """No model installed yet: the engine must at least load (its libraries resolve, the GPU runtime initialises the loader) and+ report its version. Weaker than a one-token answer, and reported as such."""+ var = "PATH" if os.name == "nt" else ("DYLD_LIBRARY_PATH" if sys.platform == "darwin" else "LD_LIBRARY_PATH")+ env = dict(os.environ)+ env[var] = str(component.root) + os.pathsep + env.get(var, "")+ try:+ done = subprocess.run([str(component.exe), "--version"], capture_output=True, text=True, timeout=timeout, env=env,+ cwd=str(component.root), creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))+ except (OSError, subprocess.SubprocessError) as exc:+ raise TestStartFailed(component.version, f"the engine could not run ({type(exc).__name__}: {exc})") from None+ if done.returncode != 0:+ tail = (done.stderr or done.stdout).strip().splitlines()[-1:] or ["no output"]+ raise TestStartFailed(component.version, f"--version exited {done.returncode}: {tail[0][:200]}")+ return {"mode": "binary-only", "detail": "no model is installed yet, so the engine was run with --version only",+ "output": done.stdout.strip()[:200]}+++def default_test_start(stage_root: Path, component: ec.EngineComponent, ctx: Context) -> dict:+ """Start the staged engine through the real start path (owner runtime, `component:strata-engine`, a saved model), wait for+ the one-token generation probe, and stop it. Everything runs in an isolated runtime, profile and component folder, so a+ user's own instances, profiles and engines are not involved. With no model installed the engine is only run with --version."""+ source = Path(ctx.run_config) if ctx.run_config else discover_run_config(ctx.environ)+ if source is None:+ if not ctx.allow_no_model_smoke:+ raise TestStartFailed(component.version, "no installed model to test with")+ return binary_smoke(component)+ from strata_control import profiles, runtime+ sandbox = Path(tempfile.mkdtemp(prefix="test-start-", dir=stage_root))+ try:+ cfg = json.loads(source.read_text(encoding="utf-8-sig"))+ cfg["exe"] = ec.REFERENCE_PREFIX + ec.COMPONENT_ID+ cfg["backend"] = component.backend+ cfg.pop("lib_dirs", None)+ cfg["host"] = "127.0.0.1"+ cfg["port"] = _free_port()+ cfg["log"] = str(sandbox / "engine.log")+ config_path = sandbox / "run.json"+ config_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8")+ env = {"STRATA_COMPONENTS_DIR": str(stage_root), "STRATA_PROFILE_DIR": str(sandbox / "profiles"),+ "STRATA_RUNTIME_DIR": str(sandbox / "runtime"), "STRATA_NO_ACQUIRE": "1",+ "STRATA_ENGINE_BACKEND": component.backend}+ name = "updtest"+ with _patched_environ(env):+ os.environ.pop("STRATA_API_KEY", None)+ profiles.create(name, str(config_path))+ started = None+ try:+ started = runtime.start(name, wait=min(ctx.test_timeout, 600), shutdown_timeout=20)+ if not started.get("ok") or started.get("state") != "ready":+ log = Path(sandbox / "engine.log")+ tail = ""+ if log.exists():+ tail = " | " + " ".join(log.read_text(errors="replace").splitlines()[-3:])[:300]+ raise TestStartFailed(component.version,+ f"it did not become ready ({started.get('error') or started.get('state')}){tail}")+ return {"mode": "full", "model": cfg.get("model_name") or source.stem, "state": started["state"],+ "detail": "started, answered a one-token probe, stopped"}+ except TestStartFailed:+ raise+ except Exception as exc: # noqa: BLE001+ raise TestStartFailed(component.version, f"{type(exc).__name__}: {exc}") from None+ finally:+ try:+ runtime.stop(name, timeout=60)+ except Exception: # noqa: BLE001 - stopping a sandbox is best effort+ pass+ finally:+ shutil.rmtree(sandbox, ignore_errors=True)+++def _move_dir(source: Path, destination: Path) -> None:+ last = None+ for attempt in range(6): # antivirus and indexers hold a fresh folder for a moment on Windows+ try:+ os.replace(source, destination)+ return+ except OSError as exc:+ last = exc+ time.sleep(0.4 * (attempt + 1))+ raise UpdateError(f"the new engine could not be moved into place ({last})", 6)+++def prune_engines(root: Path, keep: set[str]) -> list[str]:+ removed = []+ folder = ec.engine_dir(root)+ if not folder.is_dir():+ return removed+ for entry in sorted(folder.iterdir()):+ if entry.is_dir() and not entry.name.startswith(".") and entry.name not in keep:+ try:+ shutil.rmtree(entry)+ removed.append(entry.name)+ except OSError:+ pass # in use: it goes with the next update+ return removed+++def update_engine(ctx: Context, feed: feedmod.Feed, state: State) -> dict:+ """Install the best engine package for this PC if it is newer than the installed one. See the module docstring."""+ decision, pkg = _choose_engine(feed, ctx, state)+ status = decision["status"]+ result = {"component": "engine", "status": status, "installed_before": decision["installed"], "changed": False}+ if status not in ("install", "available") and not (ctx.force and status in ("failed-before", "skipped")):+ result["note"] = decision.get("note") or {"current": "The engine is up to date.",+ "none-for-this-pc": "The feed has no engine package for this PC.",+ "not-in-feed": "The feed lists no engines."}.get(status, status)+ if status == "none-for-this-pc":+ result["reasons"] = decision["reasons"]+ return result+ root = ctx.components+ _free_space_check(root, pkg.size + pkg.installed_bytes)+ archive = _download(ctx, "engine", pkg.url, pkg.size, pkg.sha256, f"engine {pkg.label}", feed)+ # busy check after the long download: a model may have been started meanwhile; the verified archive is kept for the retry+ wait_until_idle(ctx.serving, wait=ctx.wait, emit=ctx.emit, cancel=ctx.cancel, poll=ctx.poll)+ try:+ stage_root, staged = stage_engine(ctx, feed, pkg, archive)+ except UpdateError as exc:+ if exc.exit_code == 5:+ archive.unlink(missing_ok=True) # a refused package is not kept for a retry+ raise+ before_installed, _ = installed_engine(root, ctx.hardware)+ before_identity = preset_marks.identity_of(before_installed, _manifest_sha(before_installed.root)) if before_installed else None+ try:+ ctx.say("test", f"Test-starting engine {pkg.label} before switching to it", component="engine")+ runner = ctx.test_start or default_test_start+ try:+ smoke = runner(stage_root, staged, ctx)+ except TestStartFailed as exc:+ section = state.section("engine")+ section.setdefault("failed", {})[pkg.version] = {+ "manifest_sha256": pkg.manifest_sha256, "reason": exc.reason[:300],+ "at": (ctx.now or dt.datetime.now(dt.timezone.utc)).isoformat()}+ state.history({"at": section["failed"][pkg.version]["at"], "action": "update-engine", "to": pkg.version,+ "from": before_installed.version if before_installed else None, "ok": False,+ "detail": f"test start failed: {exc.reason[:200]}"})+ state.save()+ raise+ # last look before the switch: an engine may have started during the test-start+ wait_until_idle(ctx.serving, wait=ctx.wait, emit=ctx.emit, cancel=ctx.cancel, poll=ctx.poll)+ name = folder_name(pkg)+ live = ec.engine_dir(root)+ live.mkdir(parents=True, exist_ok=True)+ final = live / name+ staged_folder = stage_root / "engine" / name+ if final.exists():+ if (final / ec.MANIFEST).is_file() and _manifest_sha(final) == pkg.manifest_sha256:+ shutil.rmtree(staged_folder, ignore_errors=True) # already installed byte for byte: only the state changes+ else:+ final = live / f"{name}-{pkg.manifest_sha256[:8]}"+ _move_dir(staged_folder, final)+ else:+ _move_dir(staged_folder, final)+ ctx.say("switch", f"Switching to engine {pkg.label}", component="engine")+ section = state.section("engine")+ old_pin = section.pop("pinned", None)+ state.save() # a start reads the pin from the file, so the unpin is written before the check+ try:+ chosen = ec.resolve(root, backend=ctx.hardware.get("backend"), full=True, runtime=ctx.hardware.get("runtime"))+ if chosen.root.name != final.name:+ raise ec.EngineMissing(f"a start would pick {chosen.root.name}, not {final.name}", root)+ except ec.EngineMissing as exc:+ if old_pin:+ section["pinned"] = old_pin+ state.save()+ # the rename did not give a working engine: put it back where it cannot be picked+ shutil.rmtree(live / ".rejected", ignore_errors=True)+ (live / ".rejected").mkdir(parents=True, exist_ok=True)+ if final.exists():+ _move_dir(final, live / ".rejected" / final.name)+ raise UpdateError(f"the new engine was not accepted after the switch ({exc}); the previous engine is unchanged", 6) from None+ previous = before_installed.root.name if before_installed and before_installed.root.name != final.name else section.get("previous")+ section["previous"] = previous+ section["active"] = final.name+ section.get("failed", {}).pop(pkg.version, None)+ skipped = [v for v in section.get("skipped", []) if v != pkg.version]+ section["skipped"] = skipped+ after_identity = preset_marks.identity_of(chosen, pkg.manifest_sha256)+ mark = preset_marks.mark_engine_changed(before_identity, after_identity, base=ctx.state_base)+ keep = {final.name} | ({previous} if previous else set())+ removed = prune_engines(root, keep)+ state.history({"at": (ctx.now or dt.datetime.now(dt.timezone.utc)).isoformat(), "action": "update-engine",+ "from": before_installed.version if before_installed else None, "to": pkg.version, "ok": True,+ "detail": smoke.get("mode")})+ state.save()+ archive.unlink(missing_ok=True)+ result.update({"changed": True, "status": "updated", "installed_after": _engine_view(chosen), "test_start": smoke,+ "previous": previous, "removed": removed, "presets_marked": bool(mark)})+ ctx.say("done", f"Engine {pkg.version} is installed and will be used on the next start", component="engine")+ return result+ finally:+ shutil.rmtree(stage_root, ignore_errors=True)+++def rollback_engine(ctx: Context) -> dict:+ """Return to the previous engine version, which the last update kept. Nothing is downloaded. A pin makes the older+ package the one a start picks even though a newer one is installed; the next successful update clears it."""+ with update_lock(ctx.components):+ state = State(ctx.components)+ section = state.section("engine")+ previous = section.get("previous")+ if not previous:+ raise UpdateError("there is no previous engine to return to (the last update kept none, or none has happened)", 2)+ folder = ec.engine_dir(ctx.components) / previous+ wait_until_idle(ctx.serving, wait=ctx.wait, emit=ctx.emit, cancel=ctx.cancel, poll=ctx.poll)+ try:+ target = ec.read_manifest(folder)+ signing.ensure_component_verifier()+ ec.verify(target, full=True)+ except (ec.ComponentProblem, OSError) as exc:+ raise UpdateError(f"the previous engine ({previous}) can no longer be used: {exc}", 5) from None+ current, _ = installed_engine(ctx.components, ctx.hardware)+ leaving = current.root.name if current else None+ before_identity = preset_marks.identity_of(current, _manifest_sha(current.root)) if current else None+ section["pinned"] = previous+ state.save() # a start reads the pin from the file, so it is written before it is checked+ try:+ chosen = ec.resolve(ctx.components, backend=ctx.hardware.get("backend"), full=True, runtime=ctx.hardware.get("runtime"))+ if chosen.root.name != previous:+ raise ec.EngineMissing(f"a start would pick {chosen.root.name}", ctx.components)+ except ec.EngineMissing as exc:+ section.pop("pinned", None)+ state.save()+ raise UpdateError(f"the previous engine does not fit this PC any more: {exc}", 5) from None+ if current and current.version != target.version:+ skip = section.setdefault("skipped", [])+ if current.version not in skip:+ skip.append(current.version)+ section["previous"] = leaving+ section["active"] = previous+ mark = preset_marks.mark_engine_changed(before_identity, preset_marks.identity_of(chosen, _manifest_sha(chosen.root)), base=ctx.state_base)+ state.history({"at": (ctx.now or dt.datetime.now(dt.timezone.utc)).isoformat(), "action": "rollback-engine",+ "from": current.version if current else None, "to": target.version, "ok": True})+ state.save()+ return {"component": "engine", "status": "rolled-back", "from": current.version if current else None,+ "to": target.version, "folder": previous, "presets_marked": bool(mark)}+++# ---------------------------------------------------------------------------------------------- control++def control_dir(root: Path) -> Path:+ return root / "control"+++def active_control(root: Path) -> dict | None:+ try:+ data = json.loads((control_dir(root) / "active.json").read_text(encoding="utf-8-sig"))+ return data if isinstance(data, dict) and data.get("version") and data.get("folder") else None+ except (OSError, ValueError):+ return None+++def decide_control(feed: feedmod.Feed, ctx: Context, state: State) -> dict:+ here = ctx.hardware["platform"]+ pkg = next((p for p in feed.control if p.platform == here), None)+ installed = (active_control(ctx.components) or {}).get("version") or ec.runtime_version()+ report = {"installed": installed, "offered": pkg.version if pkg else None, "status": "not-in-feed", "download_bytes": 0}+ if pkg is None:+ return report+ report["download_bytes"] = pkg.size+ if not installed:+ report["status"] = "available"+ else:+ have, want = feedmod.version_key(installed), feedmod.version_key(pkg.version)+ report["status"] = "available" if want > have else "current"+ return report+++def update_control(ctx: Context, feed: feedmod.Feed, state: State) -> dict:+ """Stage a newer Control bundle beside the running one, run it once (`--version`), and only then point the app and the+ terminal at it (``components/control/active.json``). The running Control is never modified."""+ decision = decide_control(feed, ctx, state)+ result = {"component": "control", "status": decision["status"], "changed": False, "installed_before": decision["installed"]}+ if decision["status"] != "available":+ return result+ pkg = next(p for p in feed.control if p.platform == ctx.hardware["platform"])+ root = ctx.components+ _free_space_check(root, pkg.size + pkg.installed_bytes)+ archive = _download(ctx, "control", pkg.url, pkg.size, pkg.sha256, f"Control {pkg.version}", feed)+ stage = updates_dir(root) / "staging" / ("control-" + uuid.uuid4().hex[:8])+ try:+ ctx.say("verify", f"Unpacking Control {pkg.version}", component="control")+ extract(archive, stage, pkg.format, pkg.installed_bytes)+ entry = stage / pkg.entry+ if not entry.is_file():+ raise UpdateError(f"the Control package has no {pkg.entry}", 5)+ python = stage / "python" / ("python.exe" if os.name == "nt" else "bin/python3")+ interpreter = str(python) if python.is_file() else sys.executable+ ctx.say("test", f"Test-starting Control {pkg.version}", component="control")+ try:+ done = subprocess.run([interpreter, str(entry), "--version"], capture_output=True, text=True, timeout=120, cwd=str(stage),+ env={**ctx.environ, "PYTHONNOUSERSITE": "1", "STRATA_NO_ACQUIRE": "1"},+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))+ except (OSError, subprocess.SubprocessError) as exc:+ raise TestStartFailed(f"Control {pkg.version}", f"{type(exc).__name__}: {exc}") from None+ if done.returncode != 0 or pkg.version not in done.stdout:+ raise TestStartFailed(f"Control {pkg.version}", f"--version said {done.stdout.strip()[:120]!r} (exit {done.returncode})")+ final = control_dir(root) / pkg.version+ control_dir(root).mkdir(parents=True, exist_ok=True)+ if final.exists():+ shutil.rmtree(final, ignore_errors=True)+ _move_dir(stage, final)+ section = state.section("control")+ previous = active_control(root)+ section["previous"] = previous+ pointer = control_dir(root) / "active.json"+ temp = pointer.with_suffix(".tmp")+ temp.write_text(json.dumps({"version": pkg.version, "folder": pkg.version, "sha256": pkg.sha256}), encoding="utf-8")+ os.replace(temp, pointer)+ keep = {pkg.version} | ({previous["folder"]} if previous else set())+ for entry_dir in control_dir(root).iterdir():+ if entry_dir.is_dir() and entry_dir.name not in keep:+ shutil.rmtree(entry_dir, ignore_errors=True)+ state.history({"at": (ctx.now or dt.datetime.now(dt.timezone.utc)).isoformat(), "action": "update-control",+ "from": decision["installed"], "to": pkg.version, "ok": True})+ archive.unlink(missing_ok=True)+ result.update({"changed": True, "status": "updated", "installed_after": pkg.version,+ "note": "Control switches on the next start of the app or the terminal"})+ return result+ finally:+ shutil.rmtree(stage, ignore_errors=True)+++# ---------------------------------------------------------------------------------------------- app++def app_public_key(environ=None) -> str | None:+ environ = os.environ if environ is None else environ+ explicit = environ.get("STRATA_APP_UPDATE_PUBKEY")+ if explicit:+ return explicit+ try:+ data = json.loads(signing.BUILTIN_KEYS.read_text(encoding="utf-8-sig"))+ value = data.get("app_minisign_public")+ return value if isinstance(value, str) and value else None+ except (OSError, ValueError):+ return None+++def decide_app(feed: feedmod.Feed, ctx: Context) -> dict:+ report = {"installed": ctx.app_version, "offered": None, "status": "not-in-feed", "notes": "", "download_bytes": 0}+ if feed.app is None:+ return report+ entry = feed.app.for_platform(ctx.hardware["platform"])+ if entry is None:+ report["status"] = "none-for-this-pc"+ return report+ report.update({"offered": feed.app.version, "notes": feed.app.notes, "download_bytes": entry["size"]})+ if not ctx.app_version:+ report["status"] = "unknown-installed"+ else:+ report["status"] = "available" if feedmod.version_key(feed.app.version) > feedmod.version_key(ctx.app_version) else "current"+ return report+++def update_app(ctx: Context, feed: feedmod.Feed) -> dict:+ """The Terminal's share of an app update: download the installer, check its SHA-256 (signed feed) and its minisign signature+ (the key the app trusts), and leave it in ``.updates/app``. The Desktop app installs itself through Tauri's updater; a+ terminal only fetches and verifies, because installing an app is the platform installer's job."""+ decision = decide_app(feed, ctx)+ result = {"component": "app", "status": decision["status"], "changed": False, "installed_before": decision["installed"]}+ if decision["status"] not in ("available", "unknown-installed"):+ return result+ entry = feed.app.for_platform(ctx.hardware["platform"])+ key = app_public_key(ctx.environ)+ if not key:+ raise UpdateError("this build has no app update key (update_keys.json app_minisign_public); the app installer cannot be verified, so it was not downloaded", 5)+ root = ctx.components+ _free_space_check(root, entry["size"])+ archive = _download(ctx, "app", entry["url"], entry["size"], entry["sha256"], f"Strata app {feed.app.version}", feed)++ def chunks():+ with archive.open("rb") as stream:+ yield from iter(lambda: stream.read(1 << 20), b"")+ try:+ signing.minisign_verify(key, entry["signature"], chunks())+ except signing.SignatureError as exc:+ archive.unlink(missing_ok=True)+ raise UpdateError(f"the app installer failed its signature check: {exc}; it was deleted", 5) from None+ target_dir = updates_dir(root) / "app"+ target_dir.mkdir(parents=True, exist_ok=True)+ name = Path(transfer.resolve_ref(transfer.base_of(feed.source), entry["url"]).replace("\\", "/")).name or f"strata-app-{feed.app.version}"+ target = target_dir / name+ os.replace(archive, target)+ result.update({"changed": True, "status": "downloaded", "installed_after": None, "version": feed.app.version, "path": str(target),+ "note": "Verified. Run the installer to finish; models and settings are kept."})+ return result+++# ---------------------------------------------------------------------------------------------- the one command++def run_update(ctx: Context, *, engine: bool = True, control: bool = True, app: bool = False) -> dict:+ """`strata update`: the feed once, then the engine, Control and (if asked) the app installer, each reported separately.+ A component that fails does not undo one that succeeded; the exit code is the worst one."""+ require_acquisition("the update")+ results, failure = [], None+ with update_lock(ctx.components):+ state = State(ctx.components)+ feed = open_feed(ctx, state)+ state.save()+ steps = ([("engine", lambda: update_engine(ctx, feed, state))] if engine else []) + \+ ([("control", lambda: update_control(ctx, feed, state))] if control else []) + \+ ([("app", lambda: update_app(ctx, feed))] if app else [])+ for name, step in steps:+ try:+ results.append(step())+ except UpdateError as exc:+ results.append({"component": name, "status": "failed", "changed": False, "error": str(exc), "exit_code": exc.exit_code})+ failure = failure or exc+ state.save()+ return {"feed": {"source": ctx.source, "sequence": feed.sequence, "channel": feed.channel, "key_id": feed.key_id},+ "results": results, "exit_code": failure.exit_code if failure else 0}diff --git a/tests/terminal/test_update_feed.py b/tests/terminal/test_update_feed.pynew file mode 100644index 000000000..8768b02ce--- /dev/null+++ b/tests/terminal/test_update_feed.py@@ -0,0 +1,246 @@+"""The signed feed and its checks: a bad signature, a bad hash and a downgrade are all refused, and the choice of engine package+follows the hardware. No network and no engine here (the end-to-end flow is test_updater.py)."""++import base64+import datetime as dt+import json+import os+import tempfile+import unittest+from pathlib import Path+from unittest import mock++from strata_control import feed as feedmod, signing, transfer+from tests.terminal import update_fixture as fx++SEED1 = bytes.fromhex("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60")+PUB1 = bytes.fromhex("d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a")+SIG1 = bytes.fromhex("e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b")+SEED2 = bytes.fromhex("4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb")+PUB2 = bytes.fromhex("3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c")+SIG2 = bytes.fromhex("92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00")+++class Ed25519(unittest.TestCase):+ def test_rfc8032_vectors(self):+ self.assertEqual(signing.public_from_seed(SEED1), PUB1)+ self.assertEqual(signing.sign_raw(SEED1, b""), SIG1)+ self.assertTrue(signing.verify_raw(PUB1, b"", SIG1))+ self.assertEqual(signing.public_from_seed(SEED2), PUB2)+ self.assertEqual(signing.sign_raw(SEED2, b"\x72"), SIG2)+ self.assertTrue(signing.verify_raw(PUB2, b"\x72", SIG2))++ def test_tampering_is_refused(self):+ self.assertFalse(signing.verify_raw(PUB2, b"\x73", SIG2))+ self.assertFalse(signing.verify_raw(PUB1, b"\x72", SIG2))+ bad = bytearray(SIG2)+ bad[10] ^= 1+ self.assertFalse(signing.verify_raw(PUB2, b"\x72", bytes(bad)))+ self.assertFalse(signing.verify_raw(PUB2, b"\x72", SIG2[:63]))+ high_s = SIG2[:32] + (int.from_bytes(SIG2[32:], "little") + signing._L).to_bytes(32, "little")+ self.assertFalse(signing.verify_raw(PUB2, b"\x72", high_s), "a non-canonical s must be refused")++ def test_documents_and_key_ids(self):+ key = signing.generate_key()+ trusted = fx.trusted_of(key)+ signature = signing.sign_bytes(key, b"hello")+ self.assertEqual(signing.verify_bytes(trusted, b"hello", signature), key["key_id"])+ with self.assertRaises(signing.SignatureError):+ signing.verify_bytes(trusted, b"hellO", signature)+ other = signing.generate_key()+ with self.assertRaisesRegex(signing.SignatureError, "does not trust"):+ signing.verify_bytes(fx.trusted_of(other), b"hello", signature)+ entry = signing.public_part(key)+ entry["key_id"] = "0" * 16+ with self.assertRaises(signing.SignatureError):+ signing.parse_public(entry)++ def test_minisign_app_signature(self):+ public, secret = fx.minisign_pair()+ blob = os.urandom(5000)+ sig = fx.minisign_sign(blob, secret)+ signing.minisign_verify(public, sig, [blob[:1000], blob[1000:]])+ with self.assertRaises(signing.SignatureError):+ signing.minisign_verify(public, sig, [blob + b"x"])+ other_public, _ = fx.minisign_pair()+ with self.assertRaisesRegex(signing.SignatureError, "different key"):+ signing.minisign_verify(other_public, sig, [blob])+ text = base64.b64decode(sig).decode().replace("timestamp:1", "timestamp:2")+ with self.assertRaisesRegex(signing.SignatureError, "comment was changed"):+ signing.minisign_verify(public, base64.b64encode(text.encode()).decode(), [blob])+++def entry(version="0.1.46", backend="cuda", variant="cuda13", archs=("sm_86", "compute_89"), driver="580.65", **extra):+ base = {"version": version, "platform": "linux-x86_64", "backend": backend, "variant": variant, "archs": list(archs),+ "min_driver": {"nvidia": driver} if backend == "cuda" else {}, "min_runtime": None, "build_id": f"b-{version}-{variant}",+ "format": "tar.gz", "url": f"engine/e-{version}-{variant}.tar.gz", "size": 1000, "sha256": "a" * 64,+ "manifest_sha256": "b" * 64, "installed_bytes": 2000, "notes": ""}+ base.update(extra)+ return base+++def document(**over):+ doc = {"schema_version": 1, "feed": "strata-updates", "channel": "stable", "sequence": 5,+ "generated_at": "2026-10-15T00:00:00Z", "expires_at": None, "engine": {"packages": [entry()]}}+ doc.update(over)+ return doc+++def signed(doc, key):+ payload = (json.dumps(doc, indent=1, sort_keys=True) + "\n").encode()+ return payload, json.dumps(signing.sign_bytes(key, payload)).encode()+++class FeedChecks(unittest.TestCase):+ def setUp(self):+ self.key = signing.generate_key()+ self.trusted = fx.trusted_of(self.key)++ def load(self, payload, sig, **guards):+ return feedmod.verify_and_parse(payload, sig, source="/feeds/strata-feed.json", trusted=self.trusted, **guards)++ def test_a_good_feed_loads(self):+ feed = self.load(*signed(document(), self.key))+ self.assertEqual((feed.sequence, feed.channel, feed.key_id), (5, "stable", self.key["key_id"]))+ self.assertEqual(feed.engine[0].label, "0.1.46 linux-x86_64-cuda-cuda13")++ def test_a_bad_signature_is_refused(self):+ payload, sig = signed(document(), self.key)+ forged = json.loads(sig)+ raw = bytearray(base64.b64decode(forged["value"]))+ raw[3] ^= 0x40+ forged["value"] = base64.b64encode(bytes(raw)).decode()+ with self.assertRaisesRegex(feedmod.FeedError, "not trusted"):+ self.load(payload, json.dumps(forged).encode())++ def test_a_feed_changed_after_signing_is_refused(self):+ payload, sig = signed(document(), self.key)+ with self.assertRaisesRegex(feedmod.FeedError, "does not match the signed content"):+ self.load(payload.replace(b'"sequence": 5', b'"sequence": 6'), sig)++ def test_a_feed_signed_by_an_unknown_key_is_refused(self):+ payload, sig = signed(document(), signing.generate_key())+ with self.assertRaisesRegex(feedmod.FeedError, "does not trust"):+ self.load(payload, sig)++ def test_no_trusted_keys_means_no_update(self):+ payload, sig = signed(document(), self.key)+ with self.assertRaisesRegex(feedmod.FeedError, "trusts no update key"):+ feedmod.verify_and_parse(payload, sig, source="x/strata-feed.json", trusted={})++ def test_an_older_feed_is_a_downgrade(self):+ payload, sig = signed(document(sequence=4), self.key)+ with self.assertRaises(feedmod.FeedDowngrade):+ self.load(payload, sig, last_sequence=5)+ self.assertEqual(self.load(*signed(document(sequence=5), self.key), last_sequence=5).sequence, 5)+ self.assertEqual(self.load(*signed(document(sequence=9), self.key), last_sequence=5).sequence, 9)++ def test_an_expired_feed_and_another_channel_are_refused(self):+ payload, sig = signed(document(expires_at="2026-01-01T00:00:00Z"), self.key)+ with self.assertRaisesRegex(feedmod.FeedError, "expired"):+ self.load(payload, sig, now=dt.datetime(2026, 10, 15, tzinfo=dt.timezone.utc))+ with self.assertRaisesRegex(feedmod.FeedError, "channel"):+ self.load(*signed(document(channel="beta"), self.key), channel="stable")++ def test_malformed_entries_are_errors_not_defaults(self):+ for change in ({"sha256": "nothex"}, {"size": 0}, {"format": "rar"}, {"platform": "plan9"}, {"backend": "tpu"},+ {"version": "latest"}, {"archs": []}, {"manifest_sha256": None}, {"size": True}):+ with self.subTest(change=change):+ with self.assertRaises(feedmod.FeedError):+ self.load(*signed(document(engine={"packages": [entry(**change)]}), self.key))+ with self.assertRaisesRegex(feedmod.FeedError, "twice"):+ self.load(*signed(document(engine={"packages": [entry(), entry()]}), self.key))+ with self.assertRaises(feedmod.FeedError):+ self.load(b"not json", signed(document(), self.key)[1])++ def test_versions_are_strict_and_ordered(self):+ self.assertLess(feedmod.version_key("0.1.9"), feedmod.version_key("0.1.10"))+ self.assertLess(feedmod.version_key("0.1.45"), feedmod.version_key("0.1.45.1"))+ with self.assertRaises(feedmod.FeedError):+ feedmod.version_key("0.1.x")+++class Selection(unittest.TestCase):+ HW = {"platform": "linux-x86_64", "backend": "cuda", "runtime": "0.1.45", "nvidia_driver": "615.71", "cuda_archs": ["sm_86"], "gfx": []}++ def pick(self, packages, **hw):+ parsed = [feedmod._engine_package(p) for p in packages]+ return feedmod.select_engine(parsed, {**self.HW, **hw})++ def test_cuda_13_when_the_driver_is_new_enough_else_12(self):+ both = [entry(variant="cuda12", driver="575.51", archs=("sm_60", "sm_86", "compute_89")), entry(variant="cuda13")]+ self.assertEqual(self.pick(both)[0].variant, "cuda13")+ old = self.pick(both, nvidia_driver="576.02")+ self.assertEqual(old[0].variant, "cuda12")+ self.assertTrue(any("580.65" in r for r in old[1]))+ self.assertIsNone(self.pick(both, nvidia_driver="500.00")[0])++ def test_the_newest_version_wins_and_the_card_must_be_covered(self):+ newer = [entry("0.1.45"), entry("0.1.46")]+ self.assertEqual(self.pick(newer)[0].version, "0.1.46")+ pascal = self.pick([entry(archs=("sm_75", "sm_86", "compute_86"))], cuda_archs=["sm_61"])+ self.assertIsNone(pascal[0])+ self.assertIn("this PC's GPU is sm_61", pascal[1][0])+ self.assertIsNotNone(self.pick([entry(archs=("sm_75", "compute_75"))], cuda_archs=["sm_120"])[0], "PTX covers a newer card")++ def test_hip_by_gfx_sycl_and_metal_by_platform(self):+ hip = [entry(backend="hip", variant="", archs=("gfx1200", "gfx1201"))]+ self.assertIsNotNone(self.pick(hip, backend="hip", gfx=["gfx1201"])[0])+ self.assertIsNone(self.pick(hip, backend="hip", gfx=["gfx1100"])[0])+ self.assertIsNotNone(self.pick(hip, backend="hip", gfx=[])[0], "an unreadable gfx is not a refusal")+ self.assertIsNone(self.pick(hip, backend="cuda")[0], "a HIP package is not offered to an NVIDIA PC")+ sycl = [entry(backend="sycl", variant="", archs=("intel-arc",))]+ self.assertIsNotNone(self.pick(sycl, backend="sycl")[0])+ metal = dict(entry(backend="metal", variant="", archs=("apple-gpu",)), platform="macos-arm64")+ self.assertIsNone(self.pick([metal])[0], "wrong platform")+ self.assertIsNotNone(self.pick([metal], platform="macos-arm64", backend="metal")[0])++ def test_min_runtime(self):+ got = self.pick([entry(min_runtime="0.1.50")])+ self.assertIsNone(got[0])+ self.assertIn("needs control 0.1.50", got[1][0])+++class References(unittest.TestCase):+ def test_references_stay_inside_the_feed(self):+ base = "http://127.0.0.1:9/feed/"+ self.assertEqual(transfer.resolve_ref(base, "engine/a.tar.gz"), "http://127.0.0.1:9/feed/engine/a.tar.gz")+ for bad in ("../x", "/etc/passwd", "a/../../b", "file:///etc/passwd", "ftp://example.com/x", "a\\b", "http://example.com/x"):+ with self.subTest(bad=bad), self.assertRaises(transfer.TransferError):+ transfer.resolve_ref(base, bad)+ self.assertEqual(transfer.resolve_ref("https://example.com/f/", "https://cdn.example.com/x"), "https://cdn.example.com/x")++ def test_a_local_feed_cannot_name_a_remote_address(self):+ with tempfile.TemporaryDirectory() as folder:+ with self.assertRaises(transfer.TransferError):+ transfer.resolve_ref(folder, "https://evil.example.com/x")+ with self.assertRaises(transfer.TransferError):+ transfer.resolve_ref(folder, "../outside")+ self.assertTrue(transfer.resolve_ref(folder, "engine/a").startswith(str(Path(folder).resolve())))+++class Downloads(unittest.TestCase):+ def test_a_partial_file_resumes_and_a_bad_hash_is_deleted(self):+ import hashlib+ with tempfile.TemporaryDirectory() as folder:+ data = os.urandom(300_000)+ source = Path(folder) / "a.bin"+ source.write_bytes(data)+ partial = Path(folder) / "x.part"+ partial.write_bytes(data[:100_000])+ seen = []+ done = transfer.download(str(source), partial, size=len(data), sha256=hashlib.sha256(data).hexdigest(),+ progress=lambda d, t: seen.append(d))+ self.assertEqual(done.read_bytes(), data)+ self.assertEqual(seen[0] > 100_000, True, "it continued from the partial file instead of starting over")+ partial.write_bytes(data[:50_000])+ with self.assertRaises(transfer.ChecksumMismatch):+ transfer.download(str(source), partial, size=len(data), sha256="0" * 64)+ self.assertFalse(partial.exists(), "bytes that fail the signed hash are not kept")+ partial.write_bytes(b"x" * (len(data) + 5))+ transfer.download(str(source), partial, size=len(data), sha256=hashlib.sha256(data).hexdigest())+ self.assertEqual(partial.read_bytes(), data, "an oversized stale partial is discarded, not appended to")+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/terminal/test_updater.py b/tests/terminal/test_updater.pynew file mode 100644index 000000000..2dc6092e2--- /dev/null+++ b/tests/terminal/test_updater.py@@ -0,0 +1,486 @@+"""The component updater end to end against a LOCAL feed: a folder of signed archives served by a loopback HTTP server, stub+engines behind real schema-2 packages, the real start path for the test start.++Proves: an update downloads (with resume), verifies signature and every hash, installs side by side, test-starts the new+engine from a staging folder through the owner runtime, and only then switches; a failing test start leaves the old engine+working; the previous version is kept and can be returned to; saved presets are marked, not touched; models are never+fetched; nothing runs while an engine serves; and a start/serve process (STRATA_NO_ACQUIRE) cannot reach any of it."""++import hashlib+import json+import os+import shutil+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++from strata_control import acquisition, engine_component as ec, feed as feedmod, preset_marks, signing, updater+from strata_control.targets import host_platform+from tests.terminal import update_fixture as fx++PLATFORM = host_platform()+WINDOWS = os.name == "nt"+++class UpdaterCase(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory(prefix="strata-updater-")+ self.addCleanup(self.temp.cleanup)+ self.root = Path(self.temp.name)+ self.components = self.root / "components"+ self.state_base = self.root / "state"+ self.release = self.root / "release"+ self.release.mkdir()+ for name in ("STRATA_NO_ACQUIRE", "STRATA_API_KEY", "STRATA_REQUIRE_SIGNED_COMPONENTS", "STRATA_UPDATE_TRUSTED_KEYS"):+ patch = mock.patch.dict(os.environ)+ patch.start()+ self.addCleanup(patch.stop)+ os.environ.pop(name, None)+ env = mock.patch.dict(os.environ, {+ "STRATA_PROFILE_DIR": str(self.root / "profiles"), "STRATA_RUNTIME_DIR": str(self.root / "runtime"),+ "STRATA_COMPONENTS_DIR": str(self.components), "STRATA_ENGINE_BACKEND": "cuda",+ "FAKE_ENGINE_MARK": str(self.root / "ran.txt")})+ env.start()+ self.addCleanup(env.stop)+ for target, value in ((ec, "cuda_archs_present"), (ec, "nvidia_driver_version")):+ patch = mock.patch.object(target, value, return_value=["sm_86"] if value == "cuda_archs_present" else "610.47")+ patch.start()+ self.addCleanup(patch.stop)+ self.addCleanup(ec.register_signature_verifier, None)+ self.key = fx.make_key()+ self.trusted = fx.trusted_of(self.key)+ self.hardware = {"platform": PLATFORM, "backend": "cuda", "runtime": None, "nvidia_driver": "610.47",+ "cuda_archs": ["sm_86"], "gfx": []}+ self.models = self.root / "models"+ self.models.mkdir()+ (self.models / "model.gguf").write_bytes(b"GGUF" + os.urandom(2048))+ self.model_digest = hashlib.sha256((self.models / "model.gguf").read_bytes()).hexdigest()+ self.preset = self.state_base / "tuning" / "presets" / "iq3-128k.json"+ self.preset.parent.mkdir(parents=True)+ self.preset.write_text('{"name": "IQ3_S 128K full speed", "settings": {"expert_cache": 1500}}\n')+ self.preset_bytes = self.preset.read_bytes()+ self._run_config()+ self.server = fx.FeedServer(self.release)+ self.server.__enter__()+ self.addCleanup(self.server.__exit__)+ self.sequence = 0+ self.addCleanup(self._stop_runtime)++ def _stop_runtime(self):+ from strata_control import runtime+ try:+ if runtime._read_state("updtest") is not None:+ runtime.stop("updtest", timeout=10)+ except Exception: # noqa: BLE001+ pass++ def _run_config(self):+ from tools.strata_tokenizer import BYTE_TO_UNICODE+ tokenizer = self.root / "tokenizer"+ tokenizer.mkdir()+ tokens = [BYTE_TO_UNICODE[i] for i in range(256)] + ["ab", "<|im_start|>", "<|im_end|>", "<|endoftext|>"]+ (tokenizer / "vocab.json").write_text(json.dumps({token: i for i, token in enumerate(tokens)}))+ (tokenizer / "merges.txt").write_text("a b")+ (tokenizer / "token_type.json").write_text(json.dumps([0] * 257 + [3, 3, 3]))+ self.config = self.root / "run.json"+ self.config.write_text(json.dumps({"exe": "/some/old/engine", "backend": "cuda", "tokenizer": str(tokenizer), "args": [],+ "cwd": str(self.root), "model_name": "fake", "host": "127.0.0.1", "port": 0}))++ # ------------------------------------------------------------------ helpers++ def install_current(self, version="0.1.45", **kwargs):+ folder = fx.build_package(self.root / f"inst-{version}", version, **kwargs)+ target = self.components / "engine" / folder.name+ target.parent.mkdir(parents=True, exist_ok=True)+ shutil.copytree(folder, target)+ return target++ def publish(self, *versions, sequence=None, key=None, **options):+ """Sign + archive each (version, engine_source[, kwargs]) and write a signed feed. Returns the package folders."""+ shutil.rmtree(self.release, ignore_errors=True)+ self.release.mkdir()+ out = self.release / "engine"+ out.mkdir()+ key = key or self.key+ self.sequence = sequence or self.sequence + 1+ folders = []+ for item in versions:+ version, source, extra = (item + ({},))[:3] if len(item) == 2 else item+ folder = fx.build_package(self.root / f"pub-{self.sequence}-{version}", version, engine_source=source, key=extra.pop("sign_with", key), **extra)+ folders.append(folder)+ from feed_tool import pack_engine+ pack_engine(folder, out)+ from feed_tool import build_feed+ build_feed(self.release, key=key, sequence=self.sequence, engine_dir=out, **options)+ return folders++ def ctx(self, **over):+ values = dict(components=self.components, source=self.server.url + "/strata-feed.json", trusted=self.trusted,+ hardware=self.hardware, run_config=str(self.config), state_base=self.state_base, poll=0.05,+ test_timeout=60, serving=lambda: [], environ=dict(os.environ))+ values.update(over)+ events = values.pop("events", None)+ context = updater.Context(**values)+ if events is not None:+ context.emit = events.append+ return context++ def engine_folders(self):+ folder = self.components / "engine"+ return sorted(p.name for p in folder.iterdir() if p.is_dir()) if folder.exists() else []++ def resolved(self):+ return ec.resolve(self.components, backend="cuda").version++ def assert_user_data_untouched(self):+ self.assertEqual(self.preset.read_bytes(), self.preset_bytes, "a saved preset must not change")+ self.assertEqual(hashlib.sha256((self.models / "model.gguf").read_bytes()).hexdigest(), self.model_digest)++ def archive_requests(self):+ return [r for r in self.server.requests if r[1].endswith((".tar.gz", ".zip"))]+++class EngineUpdate(UpdaterCase):+ def test_check_reads_only_the_feed(self):+ self.install_current()+ self.publish(("0.1.46", fx.GOOD_ENGINE))+ report = updater.check(self.ctx())+ self.assertEqual(report["engine"]["status"], "available")+ self.assertEqual((report["engine"]["installed"]["version"], report["engine"]["offered"]["version"]), ("0.1.45", "0.1.46"))+ self.assertEqual([r[1] for r in self.server.requests], ["/strata-feed.json", "/strata-feed.json.sig"])+ self.assertEqual(self.engine_folders(), [f"0.1.45-{PLATFORM}-cuda-cuda13"])++ def test_update_downloads_verifies_test_starts_then_switches(self):+ old = self.install_current()+ self.publish(("0.1.46", fx.GOOD_ENGINE))+ events = []+ out = updater.run_update(self.ctx(events=events), control=False)+ result = out["results"][0]+ self.assertEqual((out["exit_code"], result["status"], result["changed"]), (0, "updated", True), out)+ self.assertEqual(result["test_start"]["mode"], "full")+ self.assertEqual(self.resolved(), "0.1.46")+ self.assertEqual(sorted(self.engine_folders()), [f"0.1.45-{PLATFORM}-cuda-cuda13", f"0.1.46-{PLATFORM}-cuda-cuda13"],+ "the previous version stays for a manual rollback")+ # the test start ran the staged copy, not a file in the live folder+ ran = (self.root / "ran.txt").read_text().splitlines()[0]+ self.assertIn(os.sep + ".updates" + os.sep + "staging" + os.sep, ran)+ phases = [e.get("phase") for e in events if e.get("event") == "phase"]+ self.assertEqual(phases, ["feed", "download", "verify", "verify", "test", "switch", "done"])+ progress = [e for e in events if e.get("event") == "progress"]+ self.assertTrue(progress and progress[-1]["percent"] == 100 and progress[-1]["done"] == progress[-1]["total"])+ self.assertEqual(sorted(p.name for p in (self.components / ".updates" / "staging").iterdir()), [], "staging is cleaned")+ self.assertEqual(list((self.components / ".updates" / "partial").iterdir()), [], "the archive is removed after the switch")+ state = json.loads((self.components / ".updates" / "state.json").read_text())+ self.assertEqual(state["engine"]["previous"], old.name)+ self.assertEqual(state["feed"]["sequence"], self.sequence)+ # presets are marked for the short re-check and kept as they were+ marks = preset_marks.pending(self.state_base)+ self.assertEqual(len(marks), 1)+ self.assertEqual((marks[0]["from"]["version"], marks[0]["to"]["version"]), ("0.1.45", "0.1.46"))+ self.assert_user_data_untouched()+ # nothing but the feed and the engine archive was requested: no model, no app+ self.assertEqual({r[1] for r in self.server.requests}, {"/strata-feed.json", "/strata-feed.json.sig", *{r[1] for r in self.archive_requests()}})+ self.assertEqual(len(self.archive_requests()), 1)+ # a second update with nothing newer changes nothing and downloads nothing+ again = updater.run_update(self.ctx(), control=False)+ self.assertEqual(again["results"][0]["status"], "current")+ self.assertEqual(len(self.archive_requests()), 1)++ def test_the_next_update_drops_versions_older_than_the_previous_one(self):+ self.install_current()+ self.publish(("0.1.46", fx.GOOD_ENGINE))+ updater.run_update(self.ctx(), control=False)+ self.publish(("0.1.47", fx.GOOD_ENGINE))+ out = updater.run_update(self.ctx(), control=False)+ self.assertEqual(out["results"][0]["status"], "updated")+ self.assertEqual(self.engine_folders(), [f"0.1.46-{PLATFORM}-cuda-cuda13", f"0.1.47-{PLATFORM}-cuda-cuda13"])+ self.assertEqual(self.resolved(), "0.1.47")++ def test_a_failing_test_start_keeps_the_old_engine(self):+ self.install_current()+ self.publish(("0.1.47", fx.BAD_ENGINE))+ out = updater.run_update(self.ctx(), control=False)+ result = out["results"][0]+ self.assertEqual((out["exit_code"], result["status"]), (6, "failed"), out)+ self.assertIn("did not pass its test start", result["error"])+ self.assertIn("unchanged", result["error"])+ self.assertEqual(self.resolved(), "0.1.45")+ self.assertEqual(self.engine_folders(), [f"0.1.45-{PLATFORM}-cuda-cuda13"], "the failed engine was never put in the live folder")+ self.assertEqual(sorted(p.name for p in (self.components / ".updates" / "staging").iterdir()), [])+ self.assertEqual(preset_marks.pending(self.state_base), [])+ self.assert_user_data_untouched()+ # it is not offered again until forced, and the archive is not downloaded twice+ again = updater.run_update(self.ctx(), control=False)+ self.assertEqual(again["results"][0]["status"], "failed-before", again)+ self.assertIn("--force", again["results"][0]["note"])+ forced = updater.run_update(self.ctx(force=True), control=False)+ self.assertEqual(forced["results"][0]["status"], "failed")+ self.assertEqual(len(self.archive_requests()), 1, "the verified archive was kept and reused")+ # a fixed build of the same version is a different manifest and is tried+ self.publish(("0.1.47", fx.GOOD_ENGINE))+ fixed = updater.run_update(self.ctx(), control=False)+ self.assertEqual(fixed["results"][0]["status"], "updated", fixed)+ self.assertEqual(self.resolved(), "0.1.47")++ def test_an_interrupted_download_resumes(self):+ self.install_current()+ self.publish(("0.1.46", fx.GOOD_ENGINE, {"padding": 3_000_000}))+ self.server.cut[".tar.gz"] = 700_000+ first = updater.run_update(self.ctx(), control=False)+ self.assertEqual((first["exit_code"], first["results"][0]["status"]), (6, "failed"))+ self.assertIn("resumes it", first["results"][0]["error"])+ self.assertEqual(self.resolved(), "0.1.45", "an interrupted update keeps the old engine working")+ partial = list((self.components / ".updates" / "partial").iterdir())+ self.assertEqual(len(partial), 1)+ kept = partial[0].stat().st_size+ self.assertTrue(0 < kept <= 700_000, kept)+ second = updater.run_update(self.ctx(), control=False)+ self.assertEqual(second["results"][0]["status"], "updated", second)+ ranges = [r[2] for r in self.archive_requests()]+ self.assertEqual(ranges[0], None)+ self.assertEqual(ranges[1], f"bytes={kept}-", "the second try asked only for the missing bytes")+ self.assertEqual(self.resolved(), "0.1.46")++ def test_a_download_that_is_not_the_signed_hash_is_refused(self):+ self.install_current()+ self.publish(("0.1.46", fx.GOOD_ENGINE))+ archive = next((self.release / "engine").glob("*.tar.gz"))+ data = bytearray(archive.read_bytes())+ data[len(data) // 2] ^= 0x55 # same size, one byte different+ archive.write_bytes(bytes(data))+ out = updater.run_update(self.ctx(), control=False)+ result = out["results"][0]+ self.assertEqual((out["exit_code"], result["status"]), (5, "failed"))+ self.assertIn("SHA-256 in the signed feed", result["error"])+ self.assertEqual(list((self.components / ".updates" / "partial").iterdir()), [], "bytes that fail the hash are deleted")+ self.assertEqual(self.resolved(), "0.1.45")+ self.assertFalse((self.root / "ran.txt").exists(), "a package that failed its hash must never run")++ def test_a_package_the_feed_did_not_describe_is_refused(self):+ self.install_current()+ self.publish(("0.1.46", fx.GOOD_ENGINE))+ entry = next((self.release / "engine").glob("*.entry.json"))+ data = json.loads(entry.read_text())+ data["manifest_sha256"] = "c" * 64+ entry.write_text(json.dumps(data))+ from feed_tool import build_feed+ build_feed(self.release, key=self.key, sequence=self.sequence + 1, engine_dir=self.release / "engine")+ out = updater.run_update(self.ctx(), control=False)+ self.assertEqual(out["exit_code"], 5)+ self.assertIn("manifest is not the one the signed feed names", out["results"][0]["error"])+ self.assertEqual(self.resolved(), "0.1.45")+ self.assertFalse((self.root / "ran.txt").exists())++ def test_unsigned_and_wrongly_signed_packages_are_refused(self):+ self.install_current()+ other = fx.make_key()+ for label, kind in (("not signed", None), ("trust", other)):+ with self.subTest(label=label):+ shutil.rmtree(self.release, ignore_errors=True)+ self.release.mkdir()+ self.sequence += 1+ folder = fx.build_package(self.root / f"x-{self.sequence}", "0.1.46", key=kind)+ from feed_tool import build_feed, pack_engine+ (self.release / "engine").mkdir()+ pack_engine(folder, self.release / "engine")+ build_feed(self.release, key=self.key, sequence=self.sequence, engine_dir=self.release / "engine")+ out = updater.run_update(self.ctx(), control=False)+ self.assertEqual(out["exit_code"], 5, out)+ self.assertIn(label, out["results"][0]["error"])+ self.assertEqual(self.resolved(), "0.1.45")+ self.assertFalse((self.root / "ran.txt").exists())++ def test_a_downgrade_is_never_installed(self):+ self.install_current("0.1.45")+ self.publish(("0.1.44", fx.GOOD_ENGINE))+ out = updater.run_update(self.ctx(), control=False)+ result = out["results"][0]+ self.assertEqual((result["status"], result["changed"]), ("current", False))+ self.assertIn("never downgrades", updater.check(self.ctx())["engine"]["note"])+ self.assertEqual(self.archive_requests(), [])+ self.assertEqual(self.resolved(), "0.1.45")++ def test_a_replayed_older_feed_is_refused(self):+ self.install_current()+ self.publish(("0.1.46", fx.GOOD_ENGINE), sequence=7)+ self.assertEqual(updater.run_update(self.ctx(), control=False)["results"][0]["status"], "updated")+ self.publish(("0.1.46", fx.GOOD_ENGINE), sequence=3)+ with self.assertRaises(feedmod.FeedDowngrade):+ updater.run_update(self.ctx(), control=False)+ with self.assertRaises(feedmod.FeedDowngrade):+ updater.check(self.ctx())++ def test_nothing_is_replaced_while_an_engine_serves(self):+ self.install_current()+ self.publish(("0.1.46", fx.GOOD_ENGINE))+ out = updater.run_update(self.ctx(serving=lambda: [{"profile": "app-1", "state": "ready"}]), control=False)+ self.assertEqual((out["exit_code"], out["results"][0]["status"]), (7, "failed"))+ self.assertIn("app-1 is serving", out["results"][0]["error"])+ self.assertEqual(self.resolved(), "0.1.45")+ self.assertFalse((self.root / "ran.txt").exists(), "no test start while another engine serves")+ # the download was not wasted: the next try reuses the verified archive+ done = updater.run_update(self.ctx(), control=False)+ self.assertEqual(done["results"][0]["status"], "updated")+ self.assertEqual(len(self.archive_requests()), 1)++ def test_waiting_for_the_engine_to_stop(self):+ self.install_current()+ self.publish(("0.1.46", fx.GOOD_ENGINE))+ answers = [[{"profile": "app-1"}], [{"profile": "app-1"}], [], []]+ events = []+ out = updater.run_update(self.ctx(serving=lambda: answers.pop(0) if answers else [], wait=30, events=events), control=False)+ self.assertEqual(out["results"][0]["status"], "updated", out)+ self.assertTrue(any(e.get("event") == "waiting" for e in events))++ def test_manual_rollback_returns_to_the_previous_engine_and_is_not_undone_by_the_next_update(self):+ self.install_current()+ self.publish(("0.1.46", fx.GOOD_ENGINE))+ updater.run_update(self.ctx(), control=False)+ out = updater.rollback_engine(self.ctx())+ self.assertEqual((out["status"], out["from"], out["to"]), ("rolled-back", "0.1.46", "0.1.45"))+ self.assertEqual(self.resolved(), "0.1.45")+ self.assertEqual(ec.status(self.components, backend="cuda")["pinned"], f"0.1.45-{PLATFORM}-cuda-cuda13")+ self.assertEqual(preset_marks.pending(self.state_base), [], "back on the engine the presets were measured on: nothing owed")+ again = updater.run_update(self.ctx(), control=False)+ self.assertEqual(again["results"][0]["status"], "skipped")+ self.assertEqual(self.resolved(), "0.1.45")+ forced = updater.run_update(self.ctx(force=True), control=False)+ self.assertEqual(forced["results"][0]["status"], "updated", forced)+ self.assertEqual(self.resolved(), "0.1.46")+ self.assert_user_data_untouched()++ def test_rollback_without_a_previous_engine_says_so(self):+ self.install_current()+ with self.assertRaisesRegex(updater.UpdateError, "no previous engine"):+ updater.rollback_engine(self.ctx())++ def test_first_run_installs_the_engine_for_this_pc_without_a_model(self):+ self.publish(("0.1.46", fx.GOOD_ENGINE))+ out = updater.run_update(self.ctx(run_config=None), control=False)+ result = out["results"][0]+ self.assertEqual((out["exit_code"], result["status"]), (0, "updated"), out)+ self.assertEqual(result["test_start"]["mode"], "binary-only")+ self.assertEqual(self.resolved(), "0.1.46")+ self.assertEqual(preset_marks.pending(self.state_base), [], "no earlier engine, so nothing to re-check")++ def test_a_broken_installed_engine_is_replaced_by_a_good_one(self):+ folder = self.install_current("0.1.46")+ library = next(p for p in folder.iterdir() if p.name.startswith(("cudart", "libcudart")))+ body = bytearray(library.read_bytes())+ body[5] ^= 0xFF+ library.write_bytes(bytes(body))+ self.publish(("0.1.46", fx.GOOD_ENGINE))+ self.assertEqual(updater.check(self.ctx())["engine"]["status"], "install")+ out = updater.run_update(self.ctx(), control=False)+ self.assertEqual(out["results"][0]["status"], "updated", out)+ self.assertEqual(self.resolved(), "0.1.46")++ def test_the_package_for_another_gpu_is_not_offered(self):+ self.publish(("0.1.46", fx.GOOD_ENGINE, {"archs": ("sm_90",)}))+ out = updater.run_update(self.ctx(hardware={**self.hardware, "cuda_archs": ["sm_61"]}), control=False)+ self.assertEqual(out["results"][0]["status"], "none-for-this-pc")+ self.assertIn("sm_61", " ".join(out["results"][0]["reasons"]))+ self.assertEqual(self.archive_requests(), [])++ def test_a_process_that_forbids_acquiring_cannot_update(self):+ self.install_current()+ self.publish(("0.1.46", fx.GOOD_ENGINE))+ with mock.patch.dict(os.environ, {"STRATA_NO_ACQUIRE": "1"}):+ with self.assertRaises(acquisition.AcquisitionRefused):+ updater.run_update(self.ctx(), control=False)+ with self.assertRaises(acquisition.AcquisitionRefused):+ updater.check(self.ctx())+ self.assertEqual(self.server.requests, [], "not even the feed is read where acquiring is forbidden")++ def test_a_started_engine_check_does_not_import_the_updater(self):+ """The start path (engine_component, runtime) must not reach the update machinery or the network code."""+ import subprocess+ code = ("import sys; import strata_control.engine_component, strata_control.runtime, strata_control.acquisition; "+ "print(sorted(m for m in sys.modules if m in ('strata_control.updater','strata_control.transfer','strata_control.feed','urllib.request')))")+ done = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, cwd=str(fx.ROOT))+ self.assertEqual(done.returncode, 0, done.stderr)+ self.assertEqual(done.stdout.strip(), "[]")+++class OtherComponents(UpdaterCase):+ def build_with_app(self, version="0.2.0", tamper=False):+ public, secret = fx.minisign_pair()+ installer = os.urandom(5000)+ (self.release / "app").mkdir(parents=True, exist_ok=True)+ (self.release / "app" / "Strata_setup.bin").write_bytes(installer)+ sig = fx.minisign_sign(installer + (b"x" if tamper else b""), secret)+ app = {"version": version, "notes": "Faster starts.", "pub_date": "2026-10-15T00:00:00Z",+ "platforms": {feedmod.TAURI_TARGETS[PLATFORM]: {"url": "app/Strata_setup.bin", "signature": sig,+ "sha256": hashlib.sha256(installer).hexdigest(), "size": len(installer)}}}+ (self.root / "tauri.json").write_text(json.dumps(app))+ from feed_tool import build_feed+ (self.release / "engine").mkdir(exist_ok=True)+ build_feed(self.release, key=self.key, sequence=self.sequence + 1, app_json=self.root / "tauri.json")+ self.sequence += 1+ return public, installer++ def test_the_app_installer_is_downloaded_and_its_signature_checked(self):+ public, installer = self.build_with_app()+ ctx = self.ctx(app_version="0.1.0", environ={**os.environ, "STRATA_APP_UPDATE_PUBKEY": public})+ report = updater.check(ctx)+ self.assertEqual((report["app"]["status"], report["app"]["offered"]), ("available", "0.2.0"))+ out = updater.run_update(ctx, engine=False, control=False, app=True)+ result = out["results"][0]+ self.assertEqual((out["exit_code"], result["status"]), (0, "downloaded"), out)+ self.assertEqual(Path(result["path"]).read_bytes(), installer)+ self.assertEqual((self.release / "app" / "latest.json").exists(), True, "the Tauri updater's file is written beside the feed")+ self.assertEqual(self.engine_folders(), [], "an app-only update downloads 0 engine bytes")+ self.assertEqual(self.archive_requests(), [])+ self.assertTrue(all(r[1].startswith(("/strata-feed", "/app/")) for r in self.server.requests))++ def test_an_installer_with_a_bad_signature_is_deleted(self):+ public, _ = self.build_with_app(tamper=True)+ ctx = self.ctx(app_version="0.1.0", environ={**os.environ, "STRATA_APP_UPDATE_PUBKEY": public})+ out = updater.run_update(ctx, engine=False, control=False, app=True)+ self.assertEqual(out["exit_code"], 5)+ self.assertIn("signature", out["results"][0]["error"])+ self.assertFalse((self.components / ".updates" / "app").exists() and any((self.components / ".updates" / "app").iterdir()))++ def test_no_app_key_no_app_download(self):+ self.build_with_app()+ ctx = self.ctx(app_version="0.1.0", environ={k: v for k, v in os.environ.items() if k != "STRATA_APP_UPDATE_PUBKEY"})+ with mock.patch.object(updater, "app_public_key", return_value=None):+ out = updater.run_update(ctx, engine=False, control=False, app=True)+ self.assertEqual(out["exit_code"], 5)+ self.assertEqual([r for r in self.server.requests if r[1].startswith("/app/")], [])++ def test_control_is_staged_run_once_and_pointed_at(self):+ bundle = self.root / "control-bundle"+ (bundle / "strata_control").mkdir(parents=True)+ (bundle / "strata.py").write_text("print('strata 0.1.46 (python stub)')\n")+ (bundle / "strata_control" / "__init__.py").write_text("")+ from feed_tool import build_feed, pack_control+ (self.release / "control").mkdir()+ pack_control(bundle, self.release / "control", version="0.1.46", platform=PLATFORM)+ build_feed(self.release, key=self.key, sequence=1, control_dir=self.release / "control")+ out = updater.run_update(self.ctx(), engine=False, control=True)+ self.assertEqual(out["results"][0]["status"], "updated", out)+ active = updater.active_control(self.components)+ self.assertEqual(active["version"], "0.1.46")+ self.assertTrue((self.components / "control" / "0.1.46" / "strata.py").is_file())+ again = updater.run_update(self.ctx(), engine=False, control=True)+ self.assertEqual(again["results"][0]["status"], "current")++ def test_a_control_that_cannot_run_is_not_switched_to(self):+ bundle = self.root / "control-bad"+ bundle.mkdir()+ (bundle / "strata.py").write_text("import sys; sys.exit(9)\n")+ from feed_tool import build_feed, pack_control+ (self.release / "control").mkdir()+ pack_control(bundle, self.release / "control", version="0.1.46", platform=PLATFORM)+ build_feed(self.release, key=self.key, sequence=1, control_dir=self.release / "control")+ out = updater.run_update(self.ctx(), engine=False, control=True)+ self.assertEqual((out["exit_code"], out["results"][0]["status"]), (6, "failed"))+ self.assertIsNone(updater.active_control(self.components))+ self.assertFalse((self.components / "control" / "0.1.46").exists())+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/terminal/update_fixture.py b/tests/terminal/update_fixture.pynew file mode 100644index 000000000..7f6e32800--- /dev/null+++ b/tests/terminal/update_fixture.py@@ -0,0 +1,152 @@+"""Shared pieces for the update tests: stub engine packages, signed archives, a feed folder and a local HTTP server that+supports Range requests and can cut a transfer short. Nothing here touches the network beyond 127.0.0.1."""++from __future__ import annotations++import base64+import hashlib+import json+import os+import re+import sys+import threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT / "packaging"))++import feed_tool # noqa: E402+import package_engine # noqa: E402+from strata_control import components, signing # noqa: E402++WINDOWS = os.name == "nt"++GOOD_ENGINE = (+ "import sys, os\nfrom pathlib import Path\n"+ "Path(os.environ['FAKE_ENGINE_MARK']).write_text(os.path.abspath(__file__) + '\\n' + ' '.join(sys.argv[1:]))\n"+ "if '--version' in sys.argv:\n print('strata-engine stub'); sys.exit(0)\n"+ "print('READY 4096 stop', flush=True)\n"+ "for line in sys.stdin:\n"+ " if line.strip() == 'QUIT': break\n"+ " if line.startswith(('GEN ', 'BGEN ')):\n"+ " slot = int(line.split()[1]) if line.startswith('BGEN ') else None\n"+ " print('T 97', flush=True)\n"+ " print('DONE 1 1 1.0 1.0 length 0 0 0', flush=True)\n"+ " if slot is not None: print(f'BADM {slot} 0', flush=True)\n")+BAD_ENGINE = "import sys\nif '--version' in sys.argv:\n sys.exit(0)\nsys.exit(3)\n" # starts, then dies before READY+++def make_key() -> dict:+ return signing.generate_key()+++def trusted_of(key: dict) -> dict:+ return {key["key_id"]: base64.b64decode(key["public"])}+++def build_package(parent: Path, version: str, *, engine_source: str = GOOD_ENGINE, key: dict | None = None,+ backend: str = "cuda", variant: str = "cuda13", build_id: str | None = None, archs=("sm_86", "compute_89"),+ min_driver=None, padding: int = 0) -> Path:+ """A schema-2 package made by the real packager (a stub engine behind a manifest-declared entrypoint). `padding` bytes of+ an incompressible 'library' make the archive big enough for a transfer to be cut part-way."""+ src = parent / f"src-{version}-{variant}"+ src.mkdir(parents=True)+ (src / "engine_main.py").write_text(engine_source, encoding="utf-8")+ if WINDOWS:+ entry = "strata.cmd"+ (src / entry).write_bytes(f'@echo off\r\n"{sys.executable}" "%~dp0engine_main.py" %*\r\n'.encode())+ library = "cudart64_13.dll"+ else:+ entry = "strata"+ (src / entry).write_text(f'#!/bin/sh\nexec "{sys.executable}" "$(dirname "$0")/engine_main.py" "$@"\n')+ (src / entry).chmod(0o755)+ library = "libcudart.so.13"+ (src / library).write_bytes(os.urandom(padding) if padding else b"a runtime library the stub never loads " * 50)+ out = parent / "built"+ out.mkdir(exist_ok=True)+ folder = package_engine.build(src, backend, version, components.host_platform(), out, entry=entry, archs=tuple(archs),+ min_driver=min_driver or {"nvidia": "580.65"}, build_id=build_id or f"stub-{version}",+ variant=variant, include=["engine_main.py"])+ if key is not None:+ feed_tool.sign_package(folder, key)+ return folder+++def minisign_pair() -> tuple[str, bytes]:+ """(Tauri-style public key value, 32-byte seed): a TEST minisign key, ED25519 with the BLAKE2b-prehash 'ED' mode."""+ seed = os.urandom(32)+ public = signing.public_from_seed(seed)+ key_id = os.urandom(8)+ text = "untrusted comment: minisign public key: TEST\n" + base64.b64encode(b"Ed" + key_id + public).decode() + "\n"+ return base64.b64encode(text.encode()).decode(), key_id + seed+++def minisign_sign(blob: bytes, key_id_and_seed: bytes, comment: str = "timestamp:1") -> str:+ key_id, seed = key_id_and_seed[:8], key_id_and_seed[8:]+ digest = hashlib.blake2b(blob, digest_size=64).digest()+ sig = signing.sign_raw(seed, digest)+ trusted = comment.encode()+ global_sig = signing.sign_raw(seed, sig + trusted)+ text = ("untrusted comment: signature from minisign secret key\n" + base64.b64encode(b"ED" + key_id + sig).decode() + "\n"+ f"trusted comment: {comment}\n" + base64.b64encode(global_sig).decode() + "\n")+ return base64.b64encode(text.encode()).decode()+++class FeedServer:+ """Serves `root` on 127.0.0.1 with Range support. `cut` = {path-suffix: bytes}: the first response for that path stops after+ that many bytes (once), closing the connection. `requests` records (method, path, range)."""++ def __init__(self, root: Path):+ self.root = Path(root)+ self.requests: list[tuple[str, str, str | None]] = []+ self.cut: dict[str, int] = {}+ outer = self++ class Handler(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_GET(self):+ rng = self.headers.get("Range")+ outer.requests.append(("GET", self.path, rng))+ target = (outer.root / self.path.lstrip("/")).resolve()+ if outer.root.resolve() not in target.parents or not target.is_file():+ self.send_error(404)+ return+ data = target.read_bytes()+ start, status = 0, 200+ if rng:+ match = re.fullmatch(r"bytes=(\d+)-", rng)+ if match:+ start, status = int(match.group(1)), 206+ body = data[start:]+ self.send_response(status)+ self.send_header("Content-Length", str(len(body)))+ if status == 206:+ self.send_header("Content-Range", f"bytes {start}-{len(data) - 1}/{len(data)}")+ self.end_headers()+ limit = next((n for suffix, n in list(outer.cut.items()) if self.path.endswith(suffix)), None)+ if limit is not None:+ del outer.cut[next(s for s in outer.cut if self.path.endswith(s))]+ self.wfile.write(body[:limit])+ self.wfile.flush()+ self.connection.close()+ return+ self.wfile.write(body)++ self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)++ @property+ def url(self) -> str:+ return f"http://127.0.0.1:{self.server.server_address[1]}"++ def __enter__(self):+ self.thread.start()+ return self++ def __exit__(self, *exc):+ self.server.shutdown()+ self.server.server_close()+ return False