okami.mom/strata

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

Niko1221Merge f-0215-teststart: update: the test start resolves paths of a removed Control version first (#5681)40df1f76f

main
97.8 KiB1753 linesraw
1"""The component updater: the one explicit step that downloads and installs engines (and Control, and the app installer).
2
3Everything that fetches software lives behind this module. Starting or serving never imports it (`acquisition.require`
4refuses here when ``STRATA_NO_ACQUIRE`` is set), so a PC that only runs models never reaches the network.
5
6What an engine update does, in order, and what keeps the old engine safe at each point:
7
81. read the signed feed (`feed.py`); a bad signature, an expired feed or an older sequence number ends here;
92. detect the hardware and pick the best package that fits it (`feed.select_engine`); nothing newer, nothing to do;
103. refuse to go on while an engine is serving (wait, or ask);
114. download the archive next to the component folder with resume and progress; the SHA-256 in the signed feed decides;
125. unpack it into a *staging* component folder (``.updates/staging/<id>/engine/<name>``), never into the live ``engine/``;
136. check the package: the manifest is the one the feed named (SHA-256), says what the feed says, carries a valid
14   signature, every file matches its recorded hash, and it fits this PC;
157. **test-start** it from the staging folder through the real start path (owner runtime, a saved model, one token);
168. only if that passed, move it into ``engine/`` (a rename), re-resolve to confirm it is the one a start will pick, record the
17   previous version for a manual rollback, and mark saved tuning presets for the short re-check.
18
19If any step fails, the live ``engine/`` folder has not changed: the previous engine keeps working, and what failed is
20named. Every older engine stays installed until the person deletes it (Settings > Engine, ``strata components remove``);
21``strata components use`` / ``rollback`` switch between them.
22Models and presets are never read, moved, deleted or downloaded here.
23"""
24
25from __future__ import annotations
26
27import contextlib
28import datetime as dt
29import json
30import os
31import re
32import shutil
33import socket
34import subprocess
35import sys
36import tarfile
37import tempfile
38import threading
39import time
40import uuid
41import zipfile
42from dataclasses import dataclass, field
43from pathlib import Path
44from typing import Callable
45
46from strata_control import acquisition, components, engine_component as ec, feed as feedmod, folder_use, longpath, preset_marks, signing, transfer
47from strata_control.targets import host_platform
48from strata_control import atomic as _atomic_mod
49
50STATE_DIR = ".updates"
51STAGE_DIR = ".s"                 # staging is short on purpose: <components>\.s\<4 hex>\engine\<folder> (see longpath.py)
52SKEW_FREE_BYTES = 1.15
53
54
55def megabytes(n) -> int:
56    """Decimal megabytes (1 MB = 1,000,000 bytes), rounded half up, at least 1: the one figure for an engine's size in the Terminal, the app
57    (apps/host/src/lib/format.ts megabytes) and the release page. Both sides are tested on the same numbers."""
58    return max(1, int((n or 0) / 1_000_000 + 0.5))
59
60
61class UpdateError(RuntimeError):
62    """An update step stopped. `exit_code` is the CLI's; the old engine is untouched unless the message says otherwise."""
63
64    def __init__(self, message: str, exit_code: int = 6):
65        super().__init__(message)
66        self.exit_code = exit_code
67
68
69LAUNCH_NEXT_STEP = "Stop the model first (`strata launch --stop`), then run `strata update` again. Nothing was changed."
70
71
72class Busy(UpdateError):
73    """An engine is serving, so nothing was installed or switched."""
74
75    def __init__(self, serving: list[dict]):
76        if any(str(item.get("profile", "")).startswith("launch-") for item in serving):
77            super().__init__("Strata's own launch is using the graphics card. " + LAUNCH_NEXT_STEP, 7)
78            self.serving = serving
79            return
80        names = ", ".join(item.get("profile", "an engine") for item in serving) or "an engine"
81        super().__init__(f"{names} is serving. Stop it (or wait until it is idle) and run the update again; "
82                         "the update never replaces or tests an engine while one is serving.", 7)
83        self.serving = serving
84
85
86class TestStartFailed(UpdateError):
87    __test__ = False                       # not a pytest class
88
89    #: reasons that say the graphics card or memory was busy, not that the engine is broken
90    BUSY = re.compile(r"timed?[ -]?out|out of memory|\boom\b|not enough (gpu |video |free )?memory|vram|memory allocation|"
91                      r"cudaerrormemory|device (is )?(busy|in use)|resource busy|no free (gpu|memory)", re.I)
92
93    @staticmethod
94    def plain(label: str, reason: str, busy: bool, hint: str | None) -> str:
95        """The one text of a failed test start (X01): what did not work in plain words, that nothing was changed, and one next step. The engine's
96        own words stay in ``reason`` (the state file, the JSON output and the kept log), never in this sentence."""
97        what = "Control" if label.startswith("Control") else "engine"
98        head = (f"The new {label} did not start correctly on this computer, so it was not installed. Your current {what} is unchanged."
99                if what == "Control" else
100                f"The new engine {label} did not start correctly on this computer, so it was not installed. Your current engine is unchanged.")
101        low = reason.lower()
102        library = missing_library(reason)
103        if what == "Control":
104            cause = f"It answered `--version` with: {reason.split('--version said', 1)[1].strip()}" if "--version said" in low else \
105                "It did not answer `--version` in time or at all."
106        elif library:
107            cause = f"The engine needs the system library {library}, and this computer does not have it."
108        elif "one-token probe" in low:
109            cause = "The engine started but stopped before it answered a test question."
110        elif "--version exited" in low or "could not run" in low:
111            cause = "The engine program did not run on this computer."
112        elif "no installed model" in low:
113            cause = "There is no installed model to test the engine with."
114        elif low.startswith("it "):                      # Strata's own plain sentences ("it was still loading the model after 10 minutes")
115            cause = reason[:1].upper() + reason[1:].rstrip(".") + "."
116        elif busy:
117            cause = "The graphics card or memory was in use."
118        else:
119            cause = "The engine reported a problem while it started."
120        if hint is None:
121            hint = ("Run `strata update --force` to try again; if it fails again, report it with the log." if not busy and what == "engine"
122                    else "Run `strata update` again.")
123        return f"{head} {cause} {hint}"
124
125    def __init__(self, label: str, reason: str, *, busy: bool | None = None, hint: str | None = None):
126        # busy: True/False says outright whether the card or memory was busy (the wait-expired reasons carry the engine's log tail, which
127        # mentions VRAM on every healthy start and must not be read as a busy card, #3683); None reads it from the words of the reason
128        self.busy = bool(self.BUSY.search(reason)) if busy is None else busy
129        if hint is None and self.busy:
130            hint = ("The graphics card or memory looks busy: close programs that use the card (games, video, other models) "
131                    "and run `strata update` again.")
132        super().__init__(self.plain(label, reason, self.busy, hint), 6)
133        self.label = label
134        self.reason = reason
135
136
137#: The loader's own words when a program needs a shared library the system does not have (glibc's ld.so).
138_MISSING_LIBRARY = re.compile(r"error while loading shared libraries:\s*([^\s:]+):\s*cannot open shared object file")
139
140#: The package that holds a system library, per Linux family (debian = Debian, Ubuntu, Mint ...; fedora = Fedora, RHEL, Rocky ...; arch = Arch,
141#: Manjaro ...). Only libraries an engine package can need from the system and that a family names differently are listed. Arch: gcc-libs pulls in
142#: libatomic / libgomp / libstdc++ / libgcc both before and after Arch split them into their own packages.
143LIBRARY_PACKAGES = {
144    "libatomic.so.1": {"debian": "libatomic1", "fedora": "libatomic", "arch": "gcc-libs"},
145    "libgomp.so.1": {"debian": "libgomp1", "fedora": "libgomp", "arch": "gcc-libs"},
146    "libstdc++.so.6": {"debian": "libstdc++6", "fedora": "libstdc++", "arch": "gcc-libs"},
147    "libgcc_s.so.1": {"debian": "libgcc-s1", "fedora": "libgcc", "arch": "gcc-libs"},
148    "libnuma.so.1": {"debian": "libnuma1", "fedora": "numactl-libs", "arch": "numactl"},
149    "libz.so.1": {"debian": "zlib1g", "fedora": "zlib", "arch": "zlib"},
150}
151_INSTALL = {"debian": "sudo apt install {}", "fedora": "sudo dnf install {}", "arch": "sudo pacman -S {}"}
152
153
154def missing_library(text: str | None) -> str | None:
155    """The shared library the loader could not find (``libatomic.so.1``), from a program's output; None when it says no such thing."""
156    found = _MISSING_LIBRARY.search(text or "")
157    return found.group(1) if found else None
158
159
160def linux_family(os_release: str = "/etc/os-release") -> str | None:
161    """debian, fedora or arch for this Linux (from /etc/os-release ID and ID_LIKE), or None when it is none of them or cannot be read."""
162    try:
163        text = Path(os_release).read_text(encoding="utf-8", errors="replace")
164    except OSError:
165        return None
166    words = []
167    for line in text.splitlines():
168        key, _, value = line.partition("=")
169        if key.strip() in ("ID", "ID_LIKE"):
170            words += value.strip().strip("\"'").lower().split()
171    for family, names in (("debian", ("debian", "ubuntu")), ("fedora", ("fedora", "rhel", "centos")), ("arch", ("arch", "archlinux"))):
172        if any(w in names for w in words):
173            return family
174    return None
175
176
177def library_hint(library: str, family: str | None = None) -> str:
178    """The one next step for a missing system library: the command that installs its package on this Linux, or the package names when the
179    family is not known, then run the update again."""
180    packages = LIBRARY_PACKAGES.get(library)
181    if packages and family in packages:
182        return f"Install it with `{_INSTALL[family].format(packages[family])}`, then run `strata update` again."
183    if packages:
184        return (f"Install it with your system's package manager ({packages['debian']} on Debian and Ubuntu, {packages['fedora']} on Fedora, "
185                f"{packages['arch']} on Arch), then run `strata update` again.")
186    return "Install the package that has it with your system's package manager, then run `strata update` again."
187
188
189# ---------------------------------------------------------------------------------------------- state
190
191def updates_dir(root: Path) -> Path:
192    return root / STATE_DIR
193
194
195@contextlib.contextmanager
196def update_lock(root: Path):
197    """One updater at a time per component folder."""
198    directory = updates_dir(root)
199    directory.mkdir(parents=True, exist_ok=True)
200    handle = open(directory / "update.lock", "a+b")
201    try:
202        if os.name == "nt":
203            import msvcrt
204            handle.seek(0)
205            try:
206                msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
207            except OSError:
208                raise UpdateError("another update is already running for this component folder", 7) from None
209        else:
210            import fcntl
211            try:
212                fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
213            except OSError:
214                raise UpdateError("another update is already running for this component folder", 7) from None
215        yield
216    finally:
217        try:
218            if os.name == "nt":
219                import msvcrt
220                handle.seek(0)
221                msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
222        except OSError:
223            pass
224        handle.close()
225
226
227class State:
228    """``<components>/.updates/state.json``: the last accepted feed sequence, which engine is the previous one, a pin set by a
229    manual rollback, versions not to offer again. Plain JSON, replaced atomically; a damaged file reads as empty."""
230
231    def __init__(self, root: Path):
232        self.path = updates_dir(root) / "state.json"
233        self.data = self._read()
234
235    def _read(self) -> dict:
236        try:
237            data = json.loads(self.path.read_text(encoding="utf-8-sig"))
238            if isinstance(data, dict):
239                return data
240        except (OSError, ValueError):
241            pass
242        return {}
243
244    def section(self, name: str) -> dict:
245        value = self.data.get(name)
246        if not isinstance(value, dict):
247            value = self.data[name] = {}
248        return value
249
250    def history(self, entry: dict) -> None:
251        log = self.data.setdefault("history", [])
252        log.append(entry)
253        del log[:-30]
254
255    def save(self) -> None:
256        self.path.parent.mkdir(parents=True, exist_ok=True)
257        self.data["schema_version"] = 1
258        descriptor, temp = tempfile.mkstemp(prefix=".state-", suffix=".tmp", dir=self.path.parent)
259        try:
260            with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
261                json.dump(self.data, stream, indent=1, sort_keys=True)
262                stream.write("\n")
263            _atomic_mod.replace(temp, self.path)
264        finally:
265            if os.path.exists(temp):
266                os.unlink(temp)
267
268
269# ---------------------------------------------------------------------------------------------- hardware
270
271def _gfx_names() -> list[str]:
272    found: list[str] = []
273    kfd = Path("/sys/class/kfd/kfd/topology/nodes")
274    if kfd.is_dir():
275        for node in sorted(kfd.iterdir()):
276            try:
277                text = (node / "properties").read_text()
278            except OSError:
279                continue
280            match = re.search(r"^gfx_target_version\s+(\d+)", text, re.MULTILINE)
281            if match and int(match.group(1)) > 0:
282                value = int(match.group(1))
283                found.append(f"gfx{value // 10000}{(value // 100) % 100:x}{value % 100:x}")
284    if not found:
285        tool = shutil.which("rocminfo") if os.name != "nt" else shutil.which("hipInfo")
286        if tool:
287            try:
288                done = subprocess.run([tool], capture_output=True, text=True, errors="replace", timeout=10,
289                                      creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
290                found = sorted(set(re.findall(r"\bgfx[0-9a-f]{3,4}\b", done.stdout)))
291            except (OSError, subprocess.SubprocessError):
292                pass
293    if not found and os.name != "nt":
294        try:
295            found = ec.hip_archs_from_pci()                  # no kfd topology and no rocminfo: the PCI ids of the AMD cards say (an AppImage, a container)
296        except Exception:                                   # noqa: BLE001 - detection is best effort
297            found = []
298    if not found and os.name == "nt":
299        # a normal Windows PC has no hipInfo (it ships with the HIP SDK): the display adapters' PCI ids / names say which gfx it is
300        try:
301            found = ec.hip_archs_present()
302        except Exception:                                   # noqa: BLE001 - detection is best effort
303            found = []
304    return sorted(set(found))
305
306
307def _amd_card_names() -> list[str]:
308    if os.name != "nt":
309        return []
310    try:
311        return [c["name"] for c in ec.windows_amd_cards() if c.get("name")]
312    except Exception:                                       # noqa: BLE001
313        return []
314
315
316def detect_hardware(environ=None) -> dict:
317    """What the package choice depends on. Read-only probes of tools that are already installed (nvidia-smi, rocminfo, sysfs);
318    ``STRATA_ENGINE_BACKEND`` overrides the backend like it does for a start. Anything unreadable is left empty, which the
319    selection treats as "cannot tell", never as a refusal."""
320    environ = os.environ if environ is None else environ
321    prefer = ""
322    family, prefer = ec.split_backend(environ.get(ec.ENV_BACKEND, ""))
323    if prefer:
324        # "hip-rx9070" is how the feed labels a package; accept it as "the hip family, this variant"
325        environ = {**environ, ec.ENV_BACKEND: family}
326    backend, how = ec.detect_backend(environ)
327    hw = {"platform": host_platform(), "backend": backend, "backend_source": how, "runtime": ec.runtime_version(),
328          "nvidia_driver": None, "cuda_archs": [], "gfx": [], "gpu_names": [], "variant_wanted": prefer,
329          "makes": sorted(ec.gpu_makes_present())}
330    if backend == "cuda":
331        hw["nvidia_driver"] = ec.nvidia_driver_version()
332        hw["cuda_archs"] = ec.cuda_archs_present()
333    elif backend == "hip":
334        hw["gfx"] = _gfx_names()
335        hw["gpu_names"] = _amd_card_names()
336    return hw
337
338
339# ---------------------------------------------------------------------------------------------- serving
340
341def serving_now() -> list[dict]:
342    """Engines that are serving: managed instances of the owner runtime and anything holding the shared activity lease
343    (`strata serve`, a runtime host). Empty when nothing is. The exclusive lease is only tried, never kept."""
344    from strata_control import profiles, runtime
345    try:
346        managed = runtime.active_managed_instances()
347    except (profiles.ProfileError, OSError):
348        managed = []
349    if managed:
350        return managed
351    try:
352        descriptor = runtime.acquire_activity_lease(shared=False)
353    except profiles.ProfileError as exc:
354        if "lease" in str(exc):
355            return [{"profile": "a running Strata server", "state": "serving"}]
356        return []
357    except OSError:
358        return []
359    try:
360        os.close(descriptor)
361    except OSError:
362        pass
363    return []
364
365
366def wait_until_idle(check: Callable[[], list[dict]], *, wait: float, emit: Callable, cancel=None,
367                    poll: float = 3.0) -> None:
368    """Return when nothing is serving; raise `Busy` if something still is after `wait` seconds (0 = do not wait)."""
369    deadline = time.monotonic() + wait
370    serving = check()
371    while serving:
372        if wait <= 0 or time.monotonic() >= deadline or (cancel is not None and cancel.is_set()):
373            raise Busy(serving)
374        emit({"event": "waiting", "message": "An engine is serving; waiting for it to stop before updating.",
375              "serving": serving})
376        time.sleep(poll)
377        serving = check()
378
379
380def idle_gate(ctx: "Context") -> None:
381    """Called after a download, right before the first thing is staged, test-started or switched: with a gate attached, the models the person agreed to
382    stop are stopped here (and a model nobody agreed to stop is refused); then, as always, nothing may still be serving."""
383    gate = getattr(ctx, "gate", None)
384    if gate is not None:
385        gate.release(ctx.serving)
386    wait_until_idle(ctx.serving, wait=ctx.wait, emit=ctx.emit, cancel=ctx.cancel, poll=ctx.poll)
387
388
389# ---------------------------------------------------------------------------------------------- context
390
391@dataclass
392class Context:
393    components: Path
394    source: str
395    trusted: dict
396    hardware: dict
397    emit: Callable[[dict], None] = lambda event: None
398    cancel: threading.Event | None = None
399    test_start: Callable | None = None           # (stage_root, component, ctx) -> dict; defaults to `default_test_start`
400    serving: Callable[[], list[dict]] = serving_now
401    wait: float = 0.0                             # seconds to wait for a serving engine to stop
402    force: bool = False
403    channel: str = "stable"
404    app_version: str | None = None
405    now: dt.datetime | None = None
406    run_config: str | None = None                 # a run config for the test start (default: an installed model's)
407    test_timeout: float = 600.0
408    poll: float = 3.0
409    environ: dict = field(default_factory=lambda: dict(os.environ))
410    allow_no_model_smoke: bool = True
411    state_base: Path | None = None                # where tuning/recheck.json goes (default: the per-user state folder)
412    feed_timeout: float = 30.0                    # seconds a read of the feed may wait (the quiet daily check uses 5)
413    automatic: bool = False                       # a read of the feed nobody asked for by name (netpolicy rule 4b: the refusal note)
414    gate: object | None = None                    # strata_control.engine_update.ModelGate: what to do when a model is loaded (None: refuse before anything is downloaded)
415
416    def say(self, phase: str, message: str, **extra) -> None:
417        self.emit({"event": "phase", "phase": phase, "message": message, **extra})
418
419
420def require_acquisition(what: str) -> None:
421    """The update path acquires by definition; a process that has forbidden acquiring (a start, a serve) may not run it."""
422    acquisition.require(what, "`strata update` from a terminal")
423
424
425def downgrade_words(sequence, accepted, state_file: Path) -> str:
426    """A feed older than the one already accepted (A01b/A05), in plain words: both numbers, the folder that remembers the newer one, and one next step.
427    The sentence keeps "older than the one already accepted" so a log search for the old text still finds it."""
428    return (f"this update source is older than the one already accepted on this computer (its sequence is {sequence}, the accepted one is "
429            f"{accepted}; refusing a replayed feed). The newer one is remembered in {state_file.parent}. Use the newest release folder; "
430            f"if you really want this older one, delete {state_file} and run this again.")
431
432
433def open_feed(ctx: Context, state: State) -> feedmod.Feed:
434    require_acquisition("the update feed")
435    last = (state.data.get("feed") or {}).get("sequence")
436    ctx.say("feed", "Reading the signed update feed")
437    try:
438        loaded = feedmod.fetch(ctx.source, ctx.trusted, timeout=ctx.feed_timeout, last_sequence=last, channel=ctx.channel, now=ctx.now,
439                               automatic=ctx.automatic)
440    except feedmod.FeedDowngrade as exc:
441        raise feedmod.FeedDowngrade(downgrade_words(exc.sequence, exc.accepted, state.path)) from None
442    for line in loaded.skipped:                       # an entry from a newer release that this Control cannot use: said once, never an error
443        ctx.say("feed", line)
444    try:                                              # the feed's model list, kept (signature and all) for a PC that is offline later; nothing when the feed has none
445        from strata_control import feed_models
446        feed_models.remember(loaded, state.path.parent.parent)
447    except Exception:                                 # noqa: BLE001 - never part of an update
448        pass
449    info = state.section("feed")
450    info.update({"sequence": loaded.sequence, "key_id": loaded.key_id, "source": ctx.source, "channel": loaded.channel,
451                 "checked_at": (ctx.now or dt.datetime.now(dt.timezone.utc)).isoformat()})
452    return loaded
453
454
455# ---------------------------------------------------------------------------------------------- archives
456
457def _archive_size(archive: Path, fmt: str) -> int:
458    if fmt == "zip":
459        with zipfile.ZipFile(archive) as zf:
460            return sum(info.file_size for info in zf.infolist())
461    mode = {"tar.gz": "r:gz", "tar.xz": "r:xz"}[fmt]
462    with tarfile.open(archive, mode) as tar:
463        return sum(m.size for m in tar.getmembers() if m.isfile())
464
465
466def _extract_with_links(archive: Path, destination: Path, fmt: str) -> None:
467    """Like `components.safe_extract`, but a relative symbolic link that stays inside `destination` is allowed. A Control bundle's
468    Python needs them (libpython, terminfo). Every name is checked before anything is written; hard links, devices, absolute
469    links and links that leave the folder are refused."""
470    mode = {"tar.gz": "r:gz", "tar.xz": "r:xz"}.get(fmt)
471    if mode is None:
472        raise components.ComponentError(f"links are only unpacked from tar archives, not {fmt}")
473    root = destination.resolve()
474    with tarfile.open(archive, mode) as tar:
475        members = tar.getmembers()
476        for m in members:
477            components._check_member_within(destination, m.name)
478            if m.isdir() or m.isfile():
479                continue
480            if not m.issym():
481                raise components.UnsafeArchive(f"the archive contains a member that is not a file or a symbolic link ({m.name!r})")
482            link = m.linkname.replace("\\", "/")
483            if not link or link.startswith("/") or re.match(r"^[A-Za-z]:", link):
484                raise components.UnsafeArchive(f"the archive has an absolute symbolic link ({m.name!r})")
485            resolved = (destination / m.name).parent.joinpath(link).resolve()
486            if resolved != root and root not in resolved.parents:
487                raise components.UnsafeArchive(f"the symbolic link {m.name!r} leaves the package")
488        destination.mkdir(parents=True, exist_ok=True)
489        links = []
490        for m in members:
491            target = components._check_member_within(destination, m.name)
492            if m.isdir():
493                target.mkdir(parents=True, exist_ok=True)
494            elif m.isfile():
495                target.parent.mkdir(parents=True, exist_ok=True)
496                source = tar.extractfile(m)
497                with target.open("wb") as out:
498                    shutil.copyfileobj(source, out)
499                if m.mode & 0o111:
500                    target.chmod(0o755)
501            else:
502                links.append((target, m.linkname))
503        for target, linkname in links:
504            target.parent.mkdir(parents=True, exist_ok=True)
505            os.symlink(linkname, target)
506
507
508def extract(archive: Path, destination: Path, fmt: str, installed_bytes: int, *, allow_links: bool = False) -> None:
509    """Unpack into a fresh folder. The archive's own total size must not exceed what the signed feed declared, so a package
510    cannot grow into a disk-filling bomb; names and links are checked by `components.safe_extract` before anything is written
511    (an engine package may not contain links; a Control bundle may contain relative links that stay inside it)."""
512    try:
513        total = _archive_size(archive, fmt)
514    except (tarfile.TarError, zipfile.BadZipFile, OSError, EOFError) as exc:
515        raise UpdateError(f"the downloaded archive cannot be read ({type(exc).__name__})", 5) from None
516    if total > installed_bytes:
517        raise UpdateError(f"the archive holds {total} bytes, the signed feed says the package is {installed_bytes}; not unpacked", 5)
518    destination = longpath.long_path(destination)        # extended-length form: a long user name must not stop the unpacking
519    if destination.exists():
520        shutil.rmtree(destination, ignore_errors=True)
521    try:
522        if allow_links:
523            _extract_with_links(archive, destination, fmt)
524        else:
525            components.safe_extract(archive, destination, fmt=fmt)
526    except components.ComponentError as exc:
527        shutil.rmtree(destination, ignore_errors=True)
528        raise UpdateError(f"the archive was refused: {exc}", 5) from None
529    except OSError as exc:
530        shutil.rmtree(destination, ignore_errors=True)
531        raise UpdateError(f"the package could not be unpacked: {longpath.describe_oserror(exc)}", 6) from None
532
533
534def _free_space_check(root: Path, need: int, ctx: "Context | None" = None, sha256: str = "", component: str = "") -> None:
535    """Stop only when the drive cannot hold the bytes that are still to be written (the package not yet downloaded plus its unpacked
536    size). The 1.15 margin is a guess at working room, not a need: below it the update warns and goes on. A resumed download's
537    partial file is already on the drive, so it is not counted a second time."""
538    root.mkdir(parents=True, exist_ok=True)
539    free = shutil.disk_usage(root).free
540    have = 0
541    if ctx is not None and sha256:
542        try:
543            have = (updates_dir(ctx.components) / "partial" / f"{sha256[:16]}.part").stat().st_size
544        except OSError:
545            have = 0
546    real = max(need - have, 0)
547    drive = root.anchor or str(root)
548    if free < real:
549        raise UpdateError(f"not enough free space on {drive}: {free // (1 << 20)} MiB free, {real // (1 << 20)} MiB needed. "
550                          f"Free up some space on {drive} and run the update again", 6)
551    if free < real * SKEW_FREE_BYTES and ctx is not None:
552        ctx.say("warn", f"Little free space on {drive}: {free // (1 << 20)} MiB free for about {real // (1 << 20)} MiB. "
553                        "The update goes on and should fit; free up space if it stops.", component=component or "update")
554
555
556def _download(ctx: Context, state_name: str, url_ref: str, size: int, sha256: str, label: str, feed: feedmod.Feed) -> Path:
557    work = updates_dir(ctx.components) / "partial"
558    partial = work / f"{sha256[:16]}.part"
559    start = time.monotonic()
560    last = {"at": 0.0, "pct": -1}
561
562    def progress(done: int, total: int) -> None:
563        now = time.monotonic()
564        pct = int(done * 100 / total) if total else 0
565        if now - last["at"] >= 0.25 or pct != last["pct"] and pct in (0, 100):
566            last["at"], last["pct"] = now, pct
567            rate = done / max(now - start, 1e-6)
568            ctx.emit({"event": "progress", "phase": "download", "component": state_name, "label": label,
569                      "done": done, "total": total, "percent": pct, "bytes_per_second": int(rate)})
570
571    ctx.say("download", f"Downloading {label} ({megabytes(size)} MB)", component=state_name)
572    try:
573        what = label if label.lower().startswith("the ") else "the " + label          # "the engine 0.1.59 (cuda)", in the network rule's sentences
574        return transfer.download(feed.url(url_ref), partial, size=size, sha256=sha256, progress=progress, cancel=ctx.cancel, what=what,
575                                 say=lambda line: ctx.say("download", line, component=state_name))
576    except transfer.Cancelled:
577        raise UpdateError("the update was stopped; the partial download is kept and the next update resumes it", 130) from None
578    except transfer.ChecksumMismatch as exc:
579        raise UpdateError(str(exc), 5) from None
580    except transfer.TransferError as exc:
581        raise UpdateError(str(exc), 6) from None
582
583
584# ---------------------------------------------------------------------------------------------- engine
585
586def folder_name(pkg: feedmod.EnginePackage) -> str:
587    return f"{pkg.version}-{pkg.platform}-{pkg.backend}" + (f"-{pkg.variant}" if pkg.variant else "")
588
589
590def _manifest_sha(folder: Path) -> str:
591    return transfer.sha256_file(folder / ec.MANIFEST)
592
593
594def installed_engine(root: Path, hardware: dict) -> tuple[ec.EngineComponent | None, str | None]:
595    """(the engine a start would use, why not). A package that fails its integrity check is reported, not hidden."""
596    try:
597        return ec.resolve(root, backend=hardware.get("backend"), full=True, runtime=hardware.get("runtime")), None
598    except ec.EngineMissing as exc:
599        return None, str(exc)
600
601
602def _engine_view(component: ec.EngineComponent | None) -> dict | None:
603    if component is None:
604        return None
605    return {"version": component.version, "platform": component.platform, "backend": component.backend,
606            "variant": component.variant, "build_id": component.build_id, "folder": component.root.name,
607            "signed": bool(component.signature)}
608
609
610def decide_engine(feed: feedmod.Feed, ctx: Context, state: State) -> dict:
611    """What an update would do for the engine, without downloading anything."""
612    return _choose_engine(feed, ctx, state)[0]
613
614
615GPU_MAKES = ("cuda", "hip", "sycl")
616
617
618def installed_gpu_makes(root: Path, platform: str | None) -> set[str]:
619    """The GPU makes (cuda / hip / sycl) of the engines installed for this platform, whatever their state."""
620    try:
621        found, _ = ec.scan(root)
622    except OSError:
623        return set()
624    return {item.backend for item in found if item.platform == platform and item.backend in GPU_MAKES}
625
626
627def make_guard(ctx: Context) -> str | None:
628    """Never cross GPU makes (#3688). An update replaces the engine; it does not convert the PC from one make of card to another,
629    and a package for the wrong make can only fail its test start. When the engine already installed is for a different make
630    than the one detected:
631      - if this PC really has a card of the installed make too (the display adapters / PCI vendors say so), the update stays
632        on the installed make (a PC with an NVIDIA card and an AMD card keeps the engine it was set up with);
633      - otherwise nothing is chosen and the returned sentence says why.
634    An explicit ask (``--backend``, ``STRATA_ENGINE_BACKEND``) is the person's decision and passes. Returns None when the update
635    may go on."""
636    hw = ctx.hardware
637    want = hw.get("backend")
638    if want not in GPU_MAKES or hw.get("backend_source") in ("environment", "requested", "installed engine", "saved choice"):
639        return None
640    have = installed_gpu_makes(ctx.components, hw.get("platform"))
641    if not have or want in have:
642        return None
643    here = set(hw.get("makes") or [])
644    keep = [make for make in GPU_MAKES if make in have and make in here]
645    if keep:
646        ctx.hardware = {**detect_hardware({**ctx.environ, ec.ENV_BACKEND: keep[0]}), "backend_source": "installed engine"}
647        return None
648    mine = " and ".join(ec.MAKE_NAMES[m] for m in GPU_MAKES if m in have)
649    return (f"The engine installed here is for {mine} cards, but this update would give your PC {ec.MAKE_NAMES[want]} one. "
650            f"Nothing was changed. If you really changed your graphics card, download the {ec.MAKE_NAMES[want]} version "
651            f"from {ec.RELEASES_URL}.")
652
653
654def _choose_engine(feed: feedmod.Feed, ctx: Context, state: State) -> tuple[dict, feedmod.EnginePackage | None]:
655    refusal = make_guard(ctx)
656    if refusal:
657        installed, _ = installed_engine(ctx.components, {**ctx.hardware, "backend": next(iter(sorted(installed_gpu_makes(ctx.components, ctx.hardware.get("platform")))), None)})
658        return {"installed": _engine_view(installed), "offered": None, "reasons": [refusal], "status": "wrong-make", "note": refusal,
659                "download_bytes": 0, "previous": state.section("engine").get("previous"), "pinned": state.section("engine").get("pinned"),
660                "problem": None}, None
661    installed, missing_reason = installed_engine(ctx.components, ctx.hardware)
662    sticky = {**ctx.hardware, "installed_variant": installed.variant if installed is not None and installed.backend in ("hip", "cuda") else ""}
663    offered, reasons = feedmod.select_engine([p for p in feed.engine], sticky)
664    section = state.section("engine")
665    report = {"installed": _engine_view(installed), "offered": offered.to_dict() if offered else None,
666              "reasons": reasons, "status": "none-for-this-pc", "download_bytes": 0,
667              "previous": section.get("previous"), "pinned": section.get("pinned"),
668              "problem": missing_reason if installed is None and missing_reason and "holds no engine" not in missing_reason else None}
669    if offered is None:
670        if not feed.engine:
671            report["status"] = "not-in-feed"
672        else:
673            hip = [p for p in feed.engine if p.backend == "hip" and p.platform == ctx.hardware.get("platform")]
674            if hip and ctx.hardware.get("backend") == "hip" and ctx.hardware.get("gfx") and not any(
675                    feedmod.engine_fit_reasons(p, ctx.hardware) == [] for p in hip):
676                # a build for another AMD card family: one plain line instead of the list of reasons
677                report["note"] = ec.arch_notice(tuple(sorted({a for p in hip for a in p.archs if a.startswith("gfx")})), ctx.hardware["gfx"])
678        return report, None
679    report["download_bytes"] = offered.size
680    if installed is None:
681        report["status"] = "install"
682        return report, offered
683    have, want = feedmod.version_key(installed.version), feedmod.version_key(offered.version)
684    if want < have:
685        report["status"] = "current"
686        report["note"] = f"the feed offers {offered.version}, older than the installed {installed.version}; an update never downgrades"
687    elif want == have:
688        report["status"] = "current"
689    else:
690        report["status"] = "available"
691    # The offered engine is already installed (the person switched to an older one for a test): the update only makes it the engine in use again,
692    # with nothing to download. A version the person switched away from is never hidden from the update (owner, 11-01).
693    local = installed_copy(ctx.components, offered)
694    if report["status"] == "available" and local:
695        report["installed_locally"] = local
696        report["download_bytes"] = 0
697        return report, offered
698    bad = (section.get("failed") or {}).get(offered.version)
699    if bad and _failed_mark_is_old(bad, ctx):
700        bad = None                                           # a failure is held against a version for a day, not for ever
701    if report["status"] == "available" and not ctx.force:
702        if bad and bad.get("manifest_sha256") == offered.manifest_sha256:
703            report["status"] = "failed-before"
704            report["note"] = (f"{offered.version} failed its test start on {bad.get('at', 'an earlier try')} ({bad.get('reason')}); "
705                              "run `strata update --force` to try it again")
706    return report, offered
707
708
709def installed_copy(root: Path, pkg: feedmod.EnginePackage) -> str | None:
710    """The installed package folder that is byte for byte the feed's ``pkg`` (same name, same manifest hash), or None."""
711    folder = ec.engine_dir(root) / folder_name(pkg)
712    try:
713        if (folder / ec.MANIFEST).is_file() and _manifest_sha(folder) == pkg.manifest_sha256:
714            return folder.name
715    except OSError:
716        pass
717    return None
718
719
720def _serving_or_empty(ctx: Context) -> list[dict]:
721    try:
722        return ctx.serving()
723    except Exception:                                   # noqa: BLE001 - informational only
724        return []
725
726
727def check(ctx: Context) -> dict:
728    """Read the signed feed and say what an update would do for the engine, Control and the app. Downloads nothing but the feed."""
729    with update_lock(ctx.components):
730        state = State(ctx.components)
731        feed = open_feed(ctx, state)
732        report = {"feed": {"source": ctx.source, "sequence": feed.sequence, "channel": feed.channel, "key_id": feed.key_id,
733                           "generated_at": feed.generated_at, "trusted_by": "test key file" if signing.extra_keys_in_effect(ctx.environ) else "built-in keys"},
734                  "engine": decide_engine(feed, ctx, state), "control": decide_control(feed, ctx, state),
735                  "app": decide_app(feed, ctx), "serving": _serving_or_empty(ctx), "hardware": ctx.hardware}
736        state.data["last_check"] = _last_check(ctx, report)
737        state.save()
738        return report
739
740
741def _last_check(ctx: Context, report: dict, control_version: str | None = None) -> dict:
742    """What the feed offers that is newer than what is installed, kept for the notice a start or the app shows without touching the network
743    (engine_component.cached_offers).  ``control_version``: the Control an update has just installed (the notice belongs to it, not to the one running)."""
744    return {
745        "at": (ctx.now or dt.datetime.now(dt.timezone.utc)).isoformat(),
746        "engine": report["engine"]["offered"]["version"] if report["engine"]["status"] in ("available", "install") and report["engine"]["offered"] else None,
747        "app": report["app"]["offered"] if report["app"]["status"] == "available" else None,
748        # the versions this result is for, so a later Control, engine or app change drops the cached notice
749        "control": control_version or ec.runtime_version(), "engine_installed": ec.newest_installed_version(ctx.components)}
750
751
752def new_stage(root: Path, prefix: str = "") -> Path:
753    r"""A fresh, short staging folder: ``<components>\.s\<4 hex>``. Old leftovers (a crashed update; the update lock is held, so
754    nothing else uses them) are swept first, along with the longer folder older versions used."""
755    base = root / STAGE_DIR
756    for old in [base, updates_dir(root) / "staging"]:
757        if old.exists():
758            shutil.rmtree(longpath.long_path(old), ignore_errors=True)
759    while True:
760        stage = base / (prefix + uuid.uuid4().hex[:4])
761        if not stage.exists():
762            return stage
763
764
765def stage_engine(ctx: Context, feed: feedmod.Feed, pkg: feedmod.EnginePackage, archive: Path, *, component_id: str = ec.COMPONENT_ID) -> tuple[Path, ec.EngineComponent]:
766    """Unpack and check a downloaded engine package in a staging component folder. Returns (staging root, component). `component_id`: the engine of a model shape
767    (strata_control/shape_engine.py) is read and checked as its own component, never as the Strata engine."""
768    stage_root = new_stage(ctx.components)
769    folder = stage_root / "engine" / folder_name(pkg)
770    ctx.say("verify", f"Unpacking {pkg.label}", component="engine")
771    longpath.long_path(folder.parent).mkdir(parents=True, exist_ok=True)
772    try:
773        extract(archive, folder, pkg.format, pkg.installed_bytes)
774        manifest = folder / ec.MANIFEST
775        if not manifest.is_file():
776            raise UpdateError(f"the package has no {ec.MANIFEST}", 5)
777        if transfer.sha256_file(manifest) != pkg.manifest_sha256:
778            raise UpdateError("the package's manifest is not the one the signed feed names; not installed", 5)
779        try:
780            component = ec.read_manifest(folder, component_id)
781        except ec.ComponentProblem as exc:
782            raise UpdateError(f"the package manifest is invalid: {exc}", 5) from None
783        mismatches = [name for name, a, b in (
784            ("version", component.version, pkg.version), ("platform", component.platform, pkg.platform), ("shape", component.shape, pkg.shape),
785            ("backend", component.backend, pkg.backend), ("variant", component.variant, pkg.variant),
786            ("build_id", component.build_id, pkg.build_id), ("archs", set(component.archs), set(pkg.archs)),
787            ("min_driver", component.min_driver, pkg.min_driver), ("min_runtime", component.min_runtime, pkg.min_runtime))
788            if a != b]
789        if mismatches:
790            raise UpdateError(f"the package says something different from the signed feed ({', '.join(mismatches)}); not installed", 5)
791        ctx.say("verify", "Checking the package signature and every file", component="engine")
792        outer = ec._verifier
793        signing.install_component_verifier(ctx.trusted)
794        try:
795            ec.verify_signature(component, {**ctx.environ, ec.ENV_REQUIRE_SIGNED: "1"})
796            ec.verify(component, full=True)
797        except ec.ComponentProblem as exc:
798            raise UpdateError(f"the package failed its check: {exc}", 5) from None
799        finally:
800            ec.register_signature_verifier(outer)
801        why = feedmod.engine_fit_reasons(pkg, ctx.hardware)
802        if why:
803            raise UpdateError("; ".join(why), 5)
804        _warn_if_deep(ctx, ctx.components / "engine" / folder_name(pkg), max((len(rel) for rel, _, _ in component.files), default=0) + 1)
805        return stage_root, component
806    except BaseException:
807        shutil.rmtree(longpath.long_path(stage_root), ignore_errors=True)
808        raise
809
810
811def discover_run_config(environ=None) -> Path | None:
812    """A saved model's run config for the test start: the one a saved profile uses if its files are all present, otherwise any
813    installed model whose files are present. DeepSeek models are left out (strata_control/retired.py: this Strata does not run them).
814    None when no model can be used (the first run)."""
815    from strata_control import models, profiles, retired
816    try:
817        listed = models.list_installed()
818    except Exception:                                   # noqa: BLE001 - discovery is best effort
819        return None
820    ready = [m for m in listed.get("models", []) if m.get("component_status") == "present" and m.get("source_config")
821             and not retired.config_file_reason(m["source_config"])]
822    if not ready:
823        return None
824    try:
825        used = {profile.get("source_config") for profile in profiles.list_profiles() if profile.get("source_config")}
826    except Exception:                                   # noqa: BLE001
827        used = set()
828    ready.sort(key=lambda m: (m["source_config"] not in used, m["id"]))
829    return Path(ready[0]["source_config"])
830
831
832def _free_port() -> int:
833    with socket.socket() as probe:
834        probe.bind(("127.0.0.1", 0))
835        return probe.getsockname()[1]
836
837
838@contextlib.contextmanager
839def _patched_environ(values: dict):
840    old = {key: os.environ.get(key) for key in values}
841    os.environ.update(values)
842    try:
843        yield
844    finally:
845        for key, value in old.items():
846            if value is None:
847                os.environ.pop(key, None)
848            else:
849                os.environ[key] = value
850
851
852def _keep_text(ctx: "Context | None", component: ec.EngineComponent, text: str) -> Path | None:
853    """What the engine printed at its test start, kept as ``.updates/logs/test-start-<version>.log`` (the file `_keep_log` writes for a full test
854    start), so a failed update can still be read after the downloaded package is gone. None when there is no context or it cannot be written."""
855    if ctx is None:
856        return None
857    try:
858        target = updates_dir(ctx.components) / "logs"
859        target.mkdir(parents=True, exist_ok=True)
860        path = target / f"test-start-{component.version}.log"
861        path.write_bytes(text.encode("utf-8", errors="replace")[-65536:])
862        logs = sorted(target.glob("test-start-*.log"), key=lambda p: p.stat().st_mtime)
863        for old in logs[:-5]:
864            old.unlink(missing_ok=True)
865        return path
866    except OSError:
867        return None
868
869
870def binary_smoke(component: ec.EngineComponent, timeout: float = 60, ctx: "Context | None" = None) -> dict:
871    """No model installed yet: the engine must at least load (its libraries resolve, the GPU runtime initialises the loader) and
872    report its version. Weaker than a one-token answer, and reported as such. With ``ctx`` a failure keeps the engine's output in
873    ``.updates/logs`` and says where; a missing system library is named, with the package that has it."""
874    var = "PATH" if os.name == "nt" else ("DYLD_LIBRARY_PATH" if sys.platform == "darwin" else "LD_LIBRARY_PATH")
875    env = dict(os.environ)
876    env[var] = os.pathsep.join(ec.package_lib_dirs(component.root)) + os.pathsep + env.get(var, "")
877    command = [str(component.exe), "--version"]
878    try:
879        done = subprocess.run(command, capture_output=True, text=True, errors="replace", timeout=timeout, env=env,
880                              cwd=str(component.root), creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
881    except (OSError, subprocess.SubprocessError) as exc:
882        _keep_text(ctx, component, f"$ {' '.join(command)}\n{type(exc).__name__}: {exc}\n")
883        raise TestStartFailed(component.version, f"the engine could not run ({type(exc).__name__}: {exc})") from None
884    if done.returncode != 0:
885        text = (done.stderr or "") + "\n" + (done.stdout or "")
886        options = re.findall(r"^\s+--[a-z0-9][a-z0-9-]*", text, re.MULTILINE)
887        if done.returncode == 2 and len(options) >= 5:
888            # an engine built before it answered --version prints its usage (the list of its own options) and exits 2: it loaded, its libraries
889            # resolved, the GPU runtime started and its argument parser ran. That is what this test is for; say so, do not fail it.
890            return {"mode": "binary-only", "detail": "no model is installed yet; this engine does not answer --version, but it loaded and listed its options "
891                                                     f"({len(options)} of them), so it runs", "output": ""}
892        kept = _keep_text(ctx, component, f"$ {' '.join(command)}\nexit code {done.returncode}\n--- stderr\n{done.stderr or ''}\n--- stdout\n{done.stdout or ''}\n")
893        library = missing_library(text)
894        tail = (done.stderr or done.stdout).strip().splitlines()[-1:] or ["no output"]
895        reason = f"--version exited {done.returncode}: {tail[0][:200]}"
896        if library and library not in reason:
897            reason += f" (error while loading shared libraries: {library}: cannot open shared object file)"
898        where = f" The engine's log from this test is in {kept}." if kept else ""
899        if library:
900            raise TestStartFailed(component.version, reason, busy=False, hint=library_hint(library, linux_family()) + where)
901        hint = f"Run `strata update --force` to try again; if it fails again, report it with the log: {kept}" if kept else None
902        raise TestStartFailed(component.version, reason, hint=hint)
903    return {"mode": "binary-only", "detail": "no model is installed yet, so the engine was run with --version only",
904            "output": done.stdout.strip()[:200]}
905
906
907def _log_tail(sandbox: Path, component: ec.EngineComponent) -> str:
908    log = sandbox / "engine.log"
909    try:
910        lines = log.read_text(errors="replace").splitlines()[-3:]
911    except OSError:
912        return ""
913    return " | " + " ".join(lines)[:300] if lines else ""
914
915
916def _keep_log(sandbox: Path, component: ec.EngineComponent, ctx: Context) -> None:
917    """The engine's log from the test start (the last 64 KiB), kept in ``.updates/logs`` so a failed update can be read afterwards."""
918    log = sandbox / "engine.log"
919    try:
920        data = log.read_bytes()[-65536:]
921        target = updates_dir(ctx.components) / "logs"
922        target.mkdir(parents=True, exist_ok=True)
923        (target / f"test-start-{component.version}.log").write_bytes(data)
924        logs = sorted(target.glob("test-start-*.log"), key=lambda p: p.stat().st_mtime)
925        for old in logs[:-5]:
926            old.unlink(missing_ok=True)
927    except OSError:
928        pass
929
930
931_RECORD_LIMIT = 65536                     # bytes read from any one kept file
932_RECORDS_KEPT = 3                         # failed test starts whose records stay in .updates/logs
933
934
935def _scrub(value, key: str = ""):
936    """A kept JSON record without anything that could authorise a request: keys that name a token or a key keep only their first
937    characters (enough to see that two records agree), the API key is dropped."""
938    if isinstance(value, dict):
939        return {k: _scrub(v, str(k)) for k, v in value.items()}
940    if isinstance(value, list):
941        return [_scrub(v, key) for v in value]
942    low = key.lower()
943    if isinstance(value, str) and value and ("api_key" in low or low in ("key", "authorization")):
944        return "<removed>"
945    if isinstance(value, str) and ("token" in low or "secret" in low or low.endswith("_key")):
946        return value[:8] + "...(rest removed)"
947    return value
948
949
950def _keep_records(sandbox: Path, component: ec.EngineComponent, ctx: Context) -> None:
951    """A failed test start keeps what the sandbox knew, because the sandbox is deleted right after (#3654): the run config the test used
952    (without keys), the host, child and ready records of the runtime (their PIDs show a mismatch), and the host and server logs, next to the
953    engine log in ``.updates/logs/test-start-<version>-failed``. The last few failed starts are kept. Best effort: it never hides the failure."""
954    try:
955        target = updates_dir(ctx.components) / "logs" / f"test-start-{component.version}-failed"
956        shutil.rmtree(target, ignore_errors=True)
957        target.mkdir(parents=True)
958        wanted = [sandbox / "run.json", sandbox / "engine.log"]
959        wanted += sorted((sandbox / "runtime").glob("*.json")) + sorted((sandbox / "runtime").glob("*.log"))
960        for source in wanted:
961            try:
962                if not source.is_file():
963                    continue
964                data = source.read_bytes()[-_RECORD_LIMIT:]
965                if source.suffix == ".json":
966                    try:
967                        data = (json.dumps(_scrub(json.loads(data.decode("utf-8-sig"))), indent=1) + "\n").encode("utf-8")
968                    except ValueError:
969                        pass                                                   # not JSON after all: kept as it is
970                (target / source.name).write_bytes(data)
971            except OSError:
972                continue
973        folders = sorted((d for d in target.parent.glob("test-start-*-failed") if d.is_dir()), key=lambda d: d.stat().st_mtime)
974        for old in folders[:-_RECORDS_KEPT]:
975            shutil.rmtree(old, ignore_errors=True)
976    except OSError:
977        pass
978
979
980def _warn_if_deep(ctx: Context, folder: Path, longest_inside: int) -> None:
981    """Tell the person, in plain words, when the engine will sit too deep for Windows' ordinary path limit and long paths are
982    off. The install continues: Strata's own file work uses extended paths; only the engine's own loading may not."""
983    if getattr(ctx, "_deep_warned", False):
984        return
985    words = longpath.warning_for(folder, longest_inside)
986    if words and not longpath.plain_long_paths_work(ctx.components):
987        ctx._deep_warned = True
988        ctx.say("warn", words, component="engine")
989
990
991def _test_progress(ctx: Context, component: ec.EngineComponent):
992    """What the person sees while the staged engine is test-started: a line when the phase changes and one about every 30 seconds,
993    so a long load or a stuck probe is never a silent wait (#3683: 10 minutes of nothing, then a timeout)."""
994    began = time.monotonic()
995    seen = {"phase": None, "at": 0.0}
996    words = {"loading": "is loading the model",
997             "verifying_generation": "has loaded the model; waiting for it to answer one token",
998             "ready_file_not_matched": "says it is ready; checking that it is the engine Strata started"}
999
1000    def progress(status: dict) -> None:
1001        phase = status.get("phase") if status.get("state") == "starting" else None
1002        if phase not in words:
1003            return
1004        now = time.monotonic()
1005        if phase != seen["phase"] or now - seen["at"] >= 30:
1006            seen["phase"], seen["at"] = phase, now
1007            ctx.say("test", f"Engine {component.version} {words[phase]} ({int(now - began)} s)", component="engine")
1008
1009    return progress
1010
1011
1012def _test_start_failure(component: ec.EngineComponent, started: dict, ctx: Context, tail: str) -> TestStartFailed:
1013    """The plain reason a test start did not pass, in the words of what the engine was doing when it ran out of time."""
1014    error = started.get("error")
1015    minutes = max(1, int(min(ctx.test_timeout, 600) // 60))
1016    log = updates_dir(ctx.components) / "logs" / f"test-start-{component.version}.log"
1017    if error == "startup_wait_expired":
1018        phase = started.get("phase")
1019        kept = f" The engine's log from this test is in {log}."
1020        if phase == "verifying_generation":
1021            return TestStartFailed(component.version, f"it loaded the model but did not answer one token within {minutes} minutes",
1022                                   busy=False, hint="Nothing was changed. Run `strata update` again; if it happens again, report it with the log." + kept)
1023        if phase == "ready_file_not_matched":
1024            return TestStartFailed(component.version, f"it reported that it was ready, but Strata could not match it to the engine process it "
1025                                   f"started", busy=False,
1026                                   hint="This looks like a problem in Strata, not in your engine or card. Nothing was changed; report it with the log." + kept)
1027        return TestStartFailed(component.version, f"it was still loading the model after {minutes} minutes", busy=True,
1028                               hint="Nothing was changed. A slow disk or a card that other programs are using can do this: close them and run "
1029                                    "`strata update` again." + kept)
1030    reason = f"it did not answer a one-token probe ({error or started.get('state')}){tail}"
1031    try:
1032        library = missing_library(tail) or missing_library(log.read_text(errors="replace"))
1033    except OSError:
1034        library = missing_library(tail)
1035    if library:                                          # the engine program never ran: the system lacks a library it needs
1036        if not missing_library(reason):
1037            reason += f" | error while loading shared libraries: {library}: cannot open shared object file"
1038        return TestStartFailed(component.version, reason, busy=False, hint=library_hint(library, linux_family()) + f" The engine's log from this test is in {log}.")
1039    # #4692: "report it with the log" named no log. The engine's words stay out of the sentence, but the person is told where the kept log is.
1040    hint = (None if TestStartFailed.BUSY.search(reason) else
1041            f"Run `strata update --force` to try again; if it fails again, report it with the log: {log}")
1042    return TestStartFailed(component.version, reason, hint=hint)
1043
1044
1045TEST_CONTEXT = 4096
1046_TEST_DROP_WITH_VALUE = ("--kv-resident", "--vision-tokens")
1047_TEST_DROP_FLAGS = ("--vision",)
1048
1049
1050def light_test_args(args: list) -> list:
1051    """The saved model's engine options made light for the test start (#3842): a short context, no KV kept in VRAM and no picture reader. The
1052    test asks whether the NEW engine loads and answers one token, not whether this card holds the model's 262,144-token settings next to the
1053    desktop and the running model; a 16 GB card refused good engines with 'out of memory' at the first weight upload."""
1054    out, i = [], 0
1055    values = [str(x) for x in args]
1056    while i < len(values):
1057        item = values[i]
1058        nxt = values[i + 1] if i + 1 < len(values) else None
1059        if item == "--max-context" and nxt is not None:
1060            try:
1061                out += [item, str(min(int(nxt), TEST_CONTEXT))]
1062            except ValueError:
1063                out += [item, nxt]
1064            i += 2
1065        elif item in _TEST_DROP_WITH_VALUE and nxt is not None:
1066            i += 2
1067        elif item in _TEST_DROP_FLAGS:
1068            i += 2 if nxt is not None and not nxt.startswith("--") else 1
1069        else:
1070            out.append(item)
1071            i += 1
1072    return out
1073
1074
1075def default_test_start(stage_root: Path, component: ec.EngineComponent, ctx: Context) -> dict:
1076    """Start the staged engine through the real start path (owner runtime, `component:strata-engine`, a saved model), wait for
1077    the one-token generation probe, and stop it. Everything runs in an isolated runtime, profile and component folder, so a
1078    user's own instances, profiles and engines are not involved. With no model installed the engine is only run with --version."""
1079    source = Path(ctx.run_config) if ctx.run_config else discover_run_config(ctx.environ)
1080    if source is None:
1081        if not ctx.allow_no_model_smoke:
1082            raise TestStartFailed(component.version, "no installed model to test with")
1083        return binary_smoke(component, ctx=ctx)
1084    from strata_control import profiles, runtime
1085    sandbox = Path(tempfile.mkdtemp(prefix="t-", dir=stage_root))
1086    try:
1087        cfg = json.loads(source.read_text(encoding="utf-8-sig"))
1088        # paths setup wrote inside a Control folder that is gone (an AppImage's /tmp/.mount_<random>, a moved install): this Control's own files (QAGUI-LIN 0213)
1089        from strata_control import control_paths
1090        cfg = control_paths.repoint(cfg)
1091        # #5681: paths in a version folder an update removed (components/control/0.1.56/...) are resolved to the current version HERE, while
1092        # STRATA_COMPONENTS_DIR is still the real one: under the sandbox's (the stage, which has no control folder) the start's own repair
1093        # found no current Control and the test start failed with a ProfileError about the old file
1094        from strata_control import cfg_paths
1095        cfg, _moved, _lost = cfg_paths.resolve_config(cfg)
1096        cfg["exe"] = ec.REFERENCE_PREFIX + ec.COMPONENT_ID
1097        cfg["backend"] = component.backend
1098        cfg.pop("lib_dirs", None)
1099        if isinstance(cfg.get("args"), list):
1100            cfg["args"] = light_test_args(cfg["args"])
1101        cfg["host"] = "127.0.0.1"
1102        cfg["port"] = _free_port()
1103        cfg["log"] = str(sandbox / "engine.log")
1104        config_path = sandbox / "run.json"
1105        config_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8")
1106        env = {"STRATA_COMPONENTS_DIR": str(stage_root), "STRATA_PROFILE_DIR": str(sandbox / "profiles"),
1107               "STRATA_RUNTIME_DIR": str(sandbox / "runtime"), "STRATA_NO_ACQUIRE": "1",
1108               "STRATA_ENGINE_BACKEND": component.backend}
1109        name = "updtest"
1110        with _patched_environ(env):
1111            os.environ.pop("STRATA_API_KEY", None)
1112            profiles.create(name, str(config_path))
1113            started = None
1114            try:
1115                started = runtime.start(name, wait=min(ctx.test_timeout, 600), shutdown_timeout=20,
1116                                        on_status=_test_progress(ctx, component))
1117                if started.get("ok") and started.get("state") == "ready" and started.get("generation_ready") is not True:
1118                    # a server that loads its model on the first request is "ready" without having generated anything:
1119                    # force the load and the one-token probe, because that is what the new engine has to be able to do
1120                    ctx.say("test", f"Engine {component.version} is up; asking it for one token", component="engine")
1121                    started = {**started, **runtime.verify(name, timeout=min(ctx.test_timeout, 600), load=True)}
1122                if not started.get("ok") or started.get("state") != "ready" or started.get("generation_ready") is not True:
1123                    _keep_log(sandbox, component, ctx)
1124                    _keep_records(sandbox, component, ctx)
1125                    raise _test_start_failure(component, started, ctx, _log_tail(sandbox, component))
1126                _keep_log(sandbox, component, ctx)
1127                return {"mode": "full", "model": cfg.get("model_name") or source.stem, "state": started["state"],
1128                        "generation_ready": True, "detail": "started, answered a one-token probe, stopped"}
1129            except TestStartFailed:
1130                _keep_log(sandbox, component, ctx)
1131                _keep_records(sandbox, component, ctx)
1132                raise
1133            except Exception as exc:                    # noqa: BLE001
1134                _keep_log(sandbox, component, ctx)
1135                _keep_records(sandbox, component, ctx)
1136                raise TestStartFailed(component.version, f"{type(exc).__name__}: {exc}") from None
1137            finally:
1138                try:
1139                    runtime.stop(name, timeout=60)
1140                except Exception:                       # noqa: BLE001 - stopping a sandbox is best effort
1141                    pass
1142    finally:
1143        shutil.rmtree(longpath.long_path(sandbox), ignore_errors=True)
1144
1145
1146#: How long a folder rename is retried before the copy is used instead (seconds). A 950 MB engine that was just written is scanned by
1147#: the virus scanner for longer than the old 8 seconds on a slow disk (#4853: unpacked and checked, then "the update didn't finish").
1148MOVE_PATIENCE_S = 40.0
1149
1150
1151def _move_dir(source: Path, destination: Path, *, patience: float = MOVE_PATIENCE_S, sleep=time.sleep, clock=time.monotonic) -> None:
1152    """Put a checked folder where it belongs. A rename is the normal way; on Windows it is refused for as long as any program (the virus
1153    scanner, the indexer, Explorer) holds one file inside the folder, so it is retried for `patience` seconds. If it is still refused,
1154    the folder is copied instead: a copy needs only to read the files, and the caller checks the copy again (every file's hash is
1155    verified when the engine is chosen), so a copy that is wrong is never used."""
1156    last = None
1157    deadline = clock() + patience
1158    attempt = 0
1159    while True:
1160        try:
1161            os.replace(source, destination)
1162            return
1163        except OSError as exc:
1164            last = exc
1165            if clock() >= deadline:
1166                break
1167            attempt += 1
1168            sleep(min(0.4 * attempt, 3.0))
1169    try:
1170        shutil.copytree(longpath.long_path(source), longpath.long_path(destination))
1171    except OSError as exc:
1172        shutil.rmtree(longpath.long_path(destination), ignore_errors=True)
1173        raise UpdateError(f"the new engine could not be moved into place ({longpath.describe_oserror(last)}); copying it did not work "
1174                          f"either ({longpath.describe_oserror(exc)})", 6) from None
1175    shutil.rmtree(longpath.long_path(source), ignore_errors=True)         # the staging folder is removed again at the end; a held file waits
1176
1177
1178def prune_engines(root: Path, keep: set[str]) -> list[str]:
1179    removed = []
1180    folder = ec.engine_dir(root)
1181    if not folder.is_dir():
1182        return removed
1183    for entry in sorted(folder.iterdir()):
1184        if entry.is_dir() and not entry.name.startswith(".") and entry.name not in keep:
1185            try:
1186                shutil.rmtree(longpath.long_path(entry))
1187                removed.append(entry.name)
1188            except OSError:
1189                pass                                     # in use: it goes with the next update
1190    return removed
1191
1192
1193def update_engine(ctx: Context, feed: feedmod.Feed, state: State) -> dict:
1194    """Install the best engine package for this PC if it is newer than the installed one. See the module docstring."""
1195    decision, pkg = _choose_engine(feed, ctx, state)
1196    status = decision["status"]
1197    result = {"component": "engine", "status": status, "installed_before": decision["installed"], "changed": False}
1198    if status not in ("install", "available") and not (ctx.force and status in ("failed-before", "skipped")):
1199        result["note"] = decision.get("note") or {"current": "The engine is up to date.",
1200                                                   "none-for-this-pc": "The feed has no engine package for this PC.",
1201                                                   "not-in-feed": "The feed lists no engines."}.get(status, status)
1202        if status == "none-for-this-pc":
1203            result["reasons"] = decision["reasons"]
1204        return result
1205    root = ctx.components
1206    local = decision.get("installed_locally")
1207    if local:
1208        return _switch_to_installed(ctx, state, local, result)
1209    have_makes = installed_gpu_makes(root, pkg.platform)
1210    if pkg.backend in GPU_MAKES and have_makes and pkg.backend not in have_makes and ctx.hardware.get("backend_source") not in ("environment", "requested", "saved choice"):
1211        raise UpdateError(f"the {pkg.label} engine is for another make of graphics card than the installed one; nothing was staged", 5)
1212    _warn_if_deep(ctx, ec.engine_dir(root) / folder_name(pkg), longpath.LONGEST_IN_PACKAGE.get(pkg.backend, longpath.LONGEST_IN_PACKAGE_DEFAULT) + 1)
1213    _free_space_check(root, pkg.size + pkg.installed_bytes, ctx, pkg.sha256, "engine")
1214    archive = _download(ctx, "engine", pkg.url, pkg.size, pkg.sha256, f"engine {pkg.label}", feed)
1215    # busy check after the long download: a model may have been started meanwhile; the verified archive is kept for the retry
1216    idle_gate(ctx)
1217    try:
1218        stage_root, staged = stage_engine(ctx, feed, pkg, archive)
1219    except UpdateError as exc:
1220        if exc.exit_code == 5:
1221            archive.unlink(missing_ok=True)             # a refused package is not kept for a retry
1222        raise
1223    return _finish_engine_install(ctx, state, pkg, stage_root, staged, archive, result, delete_archive=True)
1224
1225
1226def _switch_to_installed(ctx: Context, state: State, folder: str, result: dict) -> dict:
1227    """An update to an engine that is already on this computer: nothing is downloaded; it becomes the engine in use and any pin is cleared."""
1228    from strata_control import engine_library
1229    idle_gate(ctx)
1230    ctx.say("switch", "This engine is already on this computer; switching to it", component="engine")
1231    out = engine_library.use_qwen_unlocked(ctx, state, folder)
1232    chosen, _ = installed_engine(ctx.components, ctx.hardware)
1233    result.update({"changed": out.get("changed", False), "status": "updated" if out.get("changed") else "current", "installed_after": _engine_view(chosen),
1234                   "previous": state.section("engine").get("previous"), "removed": [], "presets_marked": bool(out.get("presets_marked")), "from_disk": True})
1235    state.history({"at": (ctx.now or dt.datetime.now(dt.timezone.utc)).isoformat(), "action": "update-engine", "from": (result.get("installed_before") or {}).get("version"),
1236                   "to": chosen.version if chosen else None, "ok": True, "detail": "already installed"})
1237    state.save()
1238    ctx.say("done", f"Engine {chosen.version if chosen else ''} is in use from the next start", component="engine")
1239    return result
1240
1241
1242def _finish_engine_install(ctx: Context, state: State, pkg: feedmod.EnginePackage, stage_root: Path, staged: ec.EngineComponent,
1243                           archive: Path, result: dict, *, delete_archive: bool) -> dict:
1244    """The part of an engine install both ways share (a download from the feed, a file the person chose): test-start the staged engine,
1245    switch to it, keep the previous one, remove the staging folder. ``archive`` is only deleted when Strata downloaded it."""
1246    root = ctx.components
1247    before_installed, _ = installed_engine(root, ctx.hardware)
1248    before_identity = preset_marks.identity_of(before_installed, _manifest_sha(before_installed.root)) if before_installed else None
1249    try:
1250        ctx.say("test", f"Test-starting engine {pkg.label} before switching to it", component="engine")
1251        runner = ctx.test_start or default_test_start
1252        try:
1253            smoke = runner(stage_root, staged, ctx)
1254        except TestStartFailed as exc:
1255            try:                                             # a model of Strata's own launch holds the card: one next step, not the engine's words
1256                own = [s for s in ctx.serving() if str(s.get("profile", "")).startswith("launch-")]
1257            except Exception:                                # noqa: BLE001
1258                own = []
1259            if own:
1260                raise Busy(own) from None
1261            section = state.section("engine")
1262            at = (ctx.now or dt.datetime.now(dt.timezone.utc)).isoformat()
1263            if not exc.busy:                                 # a busy card says nothing about the engine: the next update tries again
1264                section.setdefault("failed", {})[pkg.version] = {
1265                    "manifest_sha256": pkg.manifest_sha256, "reason": exc.reason[:300], "at": at}
1266            state.history({"at": at, "action": "update-engine", "to": pkg.version,
1267                           "from": before_installed.version if before_installed else None, "ok": False,
1268                           "detail": f"test start failed: {exc.reason[:200]}"})
1269            state.save()
1270            raise
1271        # last look before the switch: an engine may have started during the test-start
1272        idle_gate(ctx)
1273        name = folder_name(pkg)
1274        live = ec.engine_dir(root)
1275        live.mkdir(parents=True, exist_ok=True)
1276        final = live / name
1277        staged_folder = stage_root / "engine" / name
1278        if final.exists():
1279            if (final / ec.MANIFEST).is_file() and _manifest_sha(final) == pkg.manifest_sha256:
1280                shutil.rmtree(longpath.long_path(staged_folder), ignore_errors=True)       # already installed byte for byte: only the state changes
1281            else:
1282                final = live / f"{name}-{pkg.manifest_sha256[:8]}"
1283                _move_dir(staged_folder, final)
1284        else:
1285            _move_dir(staged_folder, final)
1286        ctx.say("switch", f"Switching to engine {pkg.label}", component="engine")
1287        section = state.section("engine")
1288        old_pin = section.pop("pinned", None)
1289        state.save()                                      # a start reads the pin from the file, so the unpin is written before the check
1290        try:
1291            chosen = ec.resolve(root, backend=ctx.hardware.get("backend"), full=True, runtime=ctx.hardware.get("runtime"))
1292            if chosen.root.name != final.name:
1293                raise ec.EngineMissing(f"a start would pick {chosen.root.name}, not {final.name}", root)
1294        except ec.EngineMissing as exc:
1295            if old_pin:
1296                section["pinned"] = old_pin
1297                state.save()
1298            # the rename did not give a working engine: put it back where it cannot be picked
1299            shutil.rmtree(longpath.long_path(live / ".rejected"), ignore_errors=True)
1300            (live / ".rejected").mkdir(parents=True, exist_ok=True)
1301            if final.exists():
1302                _move_dir(final, live / ".rejected" / final.name)
1303            raise UpdateError(f"the new engine was not accepted after the switch ({exc}); the previous engine is unchanged", 6) from None
1304        previous = before_installed.root.name if before_installed and before_installed.root.name != final.name else section.get("previous")
1305        section["previous"] = previous
1306        section["active"] = final.name
1307        section.get("failed", {}).pop(pkg.version, None)
1308        skipped = [v for v in section.get("skipped", []) if v != pkg.version]
1309        section["skipped"] = skipped
1310        after_identity = preset_marks.identity_of(chosen, pkg.manifest_sha256)
1311        mark = preset_marks.mark_engine_changed(before_identity, after_identity, base=ctx.state_base)
1312        removed: list[str] = []                           # every older engine stays until the person deletes it (Settings > Engine, `strata components remove`)
1313        state.history({"at": (ctx.now or dt.datetime.now(dt.timezone.utc)).isoformat(), "action": "update-engine",
1314                       "from": before_installed.version if before_installed else None, "to": pkg.version, "ok": True,
1315                       "detail": smoke.get("mode")})
1316        state.save()
1317        if delete_archive:
1318            archive.unlink(missing_ok=True)
1319        result.update({"changed": True, "status": "updated", "installed_after": _engine_view(chosen), "test_start": smoke,
1320                       "previous": previous, "removed": removed, "presets_marked": bool(mark)})
1321        ctx.say("done", f"Engine {pkg.version} is installed and will be used on the next start", component="engine")
1322        return result
1323    finally:
1324        shutil.rmtree(longpath.long_path(stage_root), ignore_errors=True)
1325
1326
1327def _archive_format(archive: Path) -> str:
1328    name = archive.name.lower()
1329    for suffix, fmt in ((".tar.gz", "tar.gz"), (".tgz", "tar.gz"), (".tar.xz", "tar.xz"), (".zip", "zip")):
1330        if name.endswith(suffix):
1331            return fmt
1332    raise UpdateError("this is not a Strata engine package (it should be a .tar.gz or .zip file from the release page)", 5)
1333
1334
1335def install_engine_file(ctx: Context, archive: Path) -> dict:
1336    """Install an engine package the person downloaded themselves (the offline path of the first-run card). No feed and no network:
1337    the package must carry the feed key's signature on its manifest, every file must match the manifest, and the package must fit this
1338    PC. After that it goes through the same test start and switch as a downloaded one. The file the person chose is left where it is."""
1339    archive = Path(archive)
1340    if not archive.is_file():
1341        raise UpdateError(f"{archive} is not a file", 5)
1342    fmt = _archive_format(archive)
1343    state_root = ctx.components
1344    with update_lock(state_root):
1345        state = State(state_root)
1346        stage_root = new_stage(state_root)
1347        keep_stage = False
1348        try:
1349            try:
1350                total = _archive_size(archive, fmt)
1351            except (tarfile.TarError, zipfile.BadZipFile, OSError, EOFError) as exc:
1352                raise UpdateError(f"this file cannot be read as a package ({type(exc).__name__}); download it again", 5) from None
1353            _free_space_check(state_root, total * 2, ctx, "", "engine")
1354            folder = stage_root / "engine" / "incoming"
1355            longpath.long_path(folder.parent).mkdir(parents=True, exist_ok=True)
1356            ctx.say("verify", "Unpacking the engine file", component="engine")
1357            extract(archive, folder, fmt, total)
1358            try:
1359                component = ec.read_manifest(folder)
1360            except ec.ComponentProblem as exc:
1361                raise UpdateError(f"this file is not a Strata engine package: {exc}", 5) from None
1362            ctx.say("verify", "Checking the package signature and every file", component="engine")
1363            outer = ec._verifier
1364            signing.install_component_verifier(ctx.trusted)
1365            try:
1366                ec.verify_signature(component, {**ctx.environ, ec.ENV_REQUIRE_SIGNED: "1"})
1367                ec.verify(component, full=True)
1368            except ec.ComponentProblem as exc:
1369                raise UpdateError(f"this file did not pass the security check, so it was not used ({exc})", 5) from None
1370            finally:
1371                ec.register_signature_verifier(outer)
1372            pkg = feedmod.EnginePackage(
1373                version=component.version, platform=component.platform, backend=component.backend, variant=component.variant or "",
1374                archs=tuple(component.archs), min_driver=dict(component.min_driver or {}), min_runtime=component.min_runtime,
1375                build_id=component.build_id, url="", format=fmt, size=archive.stat().st_size, sha256=transfer.sha256_file(archive),
1376                manifest_sha256=transfer.sha256_file(folder / ec.MANIFEST), installed_bytes=total)
1377            why = feedmod.engine_fit_reasons(pkg, ctx.hardware)
1378            if why:
1379                raise UpdateError("this file is not a Strata engine for this PC: " + "; ".join(why), 5)
1380            # the staged folder gets the name an installed package has
1381            final_stage = stage_root / "engine" / folder_name(pkg)
1382            if final_stage != folder:
1383                _move_dir(folder, final_stage)
1384            staged = ec.read_manifest(final_stage)
1385            before, _ = installed_engine(state_root, ctx.hardware)
1386            if before is not None and feedmod.version_key(before.version) > feedmod.version_key(pkg.version) and not ctx.force:
1387                return {"component": "engine", "status": "current", "changed": False, "installed_before": _engine_view(before),
1388                        "note": f"Engine {before.version} is already installed and is newer than this file ({pkg.version}); nothing was changed."}
1389            result = {"component": "engine", "status": "install" if before is None else "available",
1390                      "installed_before": _engine_view(before), "changed": False, "source": "file"}
1391            keep_stage = True
1392            return _finish_engine_install(ctx, state, pkg, stage_root, staged, archive, result, delete_archive=False)
1393        finally:
1394            if not keep_stage:
1395                shutil.rmtree(longpath.long_path(stage_root), ignore_errors=True)
1396
1397
1398def switch_engine(ctx: Context, state: State, name: str, target: ec.EngineComponent, *, unpin_if_automatic: bool = False,
1399                  what: str = "engine") -> dict:
1400    """Make the installed package folder ``name`` the engine a start uses. Nothing is downloaded or removed; the package was verified by the
1401    caller. A pin makes the package the one a start picks even though a newer one is installed. With ``unpin_if_automatic`` the pin is dropped
1402    when the package is what a start picks anyway (the newest one), so the engine follows updates again. One writer of the pin and of the
1403    previous / skipped bookkeeping: `strata components rollback` and `use_engine` (Settings > Engine, `strata components use`) both come here."""
1404    section = state.section("engine")
1405    current, _ = installed_engine(ctx.components, ctx.hardware)
1406    leaving = current.root.name if current else None
1407    before_identity = preset_marks.identity_of(current, _manifest_sha(current.root)) if current else None
1408    old_pin = section.get("pinned")
1409    automatic = False
1410    if unpin_if_automatic:
1411        section.pop("pinned", None)
1412        state.save()
1413        try:
1414            picked = ec.resolve(ctx.components, backend=ctx.hardware.get("backend"), full=True, runtime=ctx.hardware.get("runtime"))
1415            automatic = picked.root.name == name
1416        except ec.EngineMissing:
1417            automatic = False
1418    if not automatic:
1419        section["pinned"] = name
1420    state.save()                                      # a start reads the pin from the file, so it is written before it is checked
1421    try:
1422        chosen = ec.resolve(ctx.components, backend=ctx.hardware.get("backend"), full=True, runtime=ctx.hardware.get("runtime"))
1423        if chosen.root.name != name:
1424            raise ec.EngineMissing(f"a start would pick {chosen.root.name}", ctx.components)
1425    except ec.EngineMissing as exc:
1426        if old_pin:
1427            section["pinned"] = old_pin
1428        else:
1429            section.pop("pinned", None)
1430        state.save()
1431        raise UpdateError(f"the {what} does not fit this PC any more: {exc}", 5) from None
1432    forward = bool(current) and feedmod.version_key(target.version) > feedmod.version_key(current.version)
1433    if forward:
1434        # going to the newer engine: it is no longer one the person left, so a later update may offer it
1435        section["skipped"] = [v for v in section.get("skipped", []) if v != target.version]
1436    elif current and current.version != target.version:
1437        skip = section.setdefault("skipped", [])
1438        if current.version not in skip:
1439            skip.append(current.version)
1440    section["previous"] = leaving
1441    section["active"] = name
1442    mark = preset_marks.mark_engine_changed(before_identity, preset_marks.identity_of(chosen, _manifest_sha(chosen.root)), base=ctx.state_base)
1443    state.history({"at": (ctx.now or dt.datetime.now(dt.timezone.utc)).isoformat(), "action": "rollback-engine" if what != "engine" else "use-engine",
1444                   "from": current.version if current else None, "to": target.version, "ok": True})
1445    state.save()
1446    return {"component": "engine", "status": "rolled-forward" if forward else "rolled-back", "from": current.version if current else None,
1447            "to": target.version, "folder": name, "presets_marked": bool(mark), "automatic": automatic}
1448
1449
1450def rollback_engine(ctx: Context) -> dict:
1451    """Return to the previous engine version, which the last switch or update left. Nothing is downloaded. A pin makes the older
1452    package the one a start picks even though a newer one is installed; the next successful update clears it."""
1453    with update_lock(ctx.components):
1454        state = State(ctx.components)
1455        section = state.section("engine")
1456        previous = section.get("previous")
1457        if not previous:
1458            raise UpdateError("there is no previous engine to return to (the last update kept none, or none has happened)", 2)
1459        folder = ec.engine_dir(ctx.components) / previous
1460        wait_until_idle(ctx.serving, wait=ctx.wait, emit=ctx.emit, cancel=ctx.cancel, poll=ctx.poll)
1461        try:
1462            target = ec.read_manifest(folder)
1463            signing.ensure_component_verifier()
1464            ec.verify(target, full=True)
1465        except (ec.ComponentProblem, OSError) as exc:
1466            raise UpdateError(f"the previous engine ({previous}) can no longer be used: {exc}", 5) from None
1467        current, _ = installed_engine(ctx.components, ctx.hardware)
1468        if current is not None and current.root.name == previous:
1469            # an earlier rollback is still in force (S3: the text said "0.1.45.3 -> 0.1.45.3"): there is nothing to leave behind
1470            raise UpdateError(f"the engine is already the previous one ({current.version}); there is nothing older to return to. "
1471                              "Run `strata update --force` to try the newer version again.", 2)
1472        return switch_engine(ctx, state, previous, target, what="previous engine")
1473
1474
1475# ---------------------------------------------------------------------------------------------- control
1476
1477def control_dir(root: Path) -> Path:
1478    return root / "control"
1479
1480
1481def active_control(root: Path) -> dict | None:
1482    try:
1483        data = json.loads((control_dir(root) / "active.json").read_text(encoding="utf-8-sig"))
1484        return data if isinstance(data, dict) and data.get("version") and data.get("folder") else None
1485    except (OSError, ValueError):
1486        return None
1487
1488
1489def source_tree_version(root: Path | None = None) -> str | None:
1490    """The version of a source checkout (it has no VERSION file): the project version in its CMakeLists.txt, the same rule `strata --version` uses.
1491    Used only to PRINT what a checkout runs (`update --check` said `Control  ?: available`); the decision to stage a Control copy does not use it."""
1492    root = root or Path(__file__).resolve().parents[1]
1493    try:
1494        found = re.search(r"^\s*project\([^)]*?VERSION\s+([0-9]+(?:\.[0-9]+)+)", (root / "CMakeLists.txt").read_text(encoding="utf-8", errors="replace"), re.MULTILINE)
1495    except OSError:
1496        return None
1497    return found.group(1) if found else None
1498
1499
1500def decide_control(feed: feedmod.Feed, ctx: Context, state: State) -> dict:
1501    here = ctx.hardware["platform"]
1502    pkg = next((p for p in feed.control if p.platform == here), None)
1503    installed = (active_control(ctx.components) or {}).get("version") or ec.runtime_version()
1504    report = {"installed": installed, "offered": pkg.version if pkg else None, "status": "not-in-feed", "download_bytes": 0}
1505    if pkg is None:
1506        return report
1507    report["download_bytes"] = pkg.size
1508    if not installed:
1509        report["status"] = "available"
1510    else:
1511        have, want = feedmod.version_key(installed), feedmod.version_key(pkg.version)
1512        report["status"] = "available" if want > have else "current"
1513    return report
1514
1515
1516CONTROL_VERSION_TIMEOUTS = (240, 360)       # seconds: antivirus scans a fresh python.exe on its first run, which can take minutes
1517
1518
1519def _control_version(interpreter: str, entry: Path, stage: Path, ctx: Context, version: str):
1520    """Run `--version` of the staged Control; once more, with more time, when the first try timed out, failed to start or said nothing."""
1521    last_error = None
1522    done = None
1523    for attempt, timeout in enumerate(CONTROL_VERSION_TIMEOUTS):
1524        try:
1525            done = subprocess.run([interpreter, str(entry), "--version"], capture_output=True, text=True, errors="replace", timeout=timeout, cwd=str(stage),
1526                                  env={**ctx.environ, "PYTHONNOUSERSITE": "1", "STRATA_NO_ACQUIRE": "1", "STRATA_HANDOVER": "1"},
1527                                  creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
1528            last_error = None
1529            if done.returncode == 0 and version in done.stdout:
1530                return done
1531        except (OSError, subprocess.SubprocessError) as exc:
1532            last_error = exc
1533        if attempt + 1 < len(CONTROL_VERSION_TIMEOUTS):
1534            ctx.say("test", f"Control {version} did not answer yet (a virus scanner may be checking it); trying once more", component="control")
1535    if last_error is not None:
1536        raise TestStartFailed(f"Control {version}", f"{type(last_error).__name__}: {last_error}") from None
1537    return done
1538
1539
1540def _failed_mark_is_old(mark: dict, ctx: Context, hours: float = 24.0) -> bool:
1541    try:
1542        then = dt.datetime.fromisoformat(str(mark.get("at")))
1543        if then.tzinfo is None:
1544            then = then.replace(tzinfo=dt.timezone.utc)
1545        return (ctx.now or dt.datetime.now(dt.timezone.utc)) - then > dt.timedelta(hours=hours)
1546    except (TypeError, ValueError):
1547        return False
1548
1549
1550def update_control(ctx: Context, feed: feedmod.Feed, state: State) -> dict:
1551    """Stage a newer Control bundle beside the running one, run it once (`--version`), and only then point the app and the
1552    terminal at it (``components/control/active.json``). The running Control is never modified."""
1553    decision = decide_control(feed, ctx, state)
1554    result = {"component": "control", "status": decision["status"], "changed": False, "installed_before": decision["installed"]}
1555    if decision["status"] != "available":
1556        return result
1557    pkg = next(p for p in feed.control if p.platform == ctx.hardware["platform"])
1558    root = ctx.components
1559    _free_space_check(root, pkg.size + pkg.installed_bytes, ctx, pkg.sha256, "control")
1560    archive = _download(ctx, "control", pkg.url, pkg.size, pkg.sha256, f"Control {pkg.version}", feed)
1561    idle_gate(ctx)                                       # a new Control never takes over beside a model that is loaded without the person's yes
1562    stage = new_stage(root, "c")
1563    try:
1564        ctx.say("verify", f"Unpacking Control {pkg.version}", component="control")
1565        extract(archive, stage, pkg.format, pkg.installed_bytes, allow_links=pkg.format != "zip")
1566        entry = stage / pkg.entry
1567        if not entry.is_file():
1568            raise UpdateError(f"the Control package has no {pkg.entry}", 5)
1569        python = stage / "python" / ("python.exe" if os.name == "nt" else "bin/python3")
1570        interpreter = str(python) if python.is_file() else sys.executable
1571        ctx.say("test", f"Test-starting Control {pkg.version}", component="control")
1572        done = _control_version(interpreter, entry, stage, ctx, pkg.version)
1573        if done.returncode != 0 or pkg.version not in done.stdout:
1574            raise TestStartFailed(f"Control {pkg.version}", f"--version said {done.stdout.strip()[:120]!r} (exit {done.returncode})")
1575        final = control_dir(root) / pkg.version
1576        control_dir(root).mkdir(parents=True, exist_ok=True)
1577        if final.exists():
1578            shutil.rmtree(longpath.long_path(final), ignore_errors=True)
1579        _move_dir(stage, final)
1580        section = state.section("control")
1581        previous = active_control(root)
1582        section["previous"] = previous
1583        pointer = control_dir(root) / "active.json"
1584        temp = pointer.with_suffix(".tmp")
1585        temp.write_text(json.dumps({"version": pkg.version, "folder": pkg.version, "sha256": pkg.sha256}), encoding="utf-8")
1586        _atomic_mod.replace(temp, pointer)
1587        keep = {pkg.version} | ({previous["folder"]} if previous else set())
1588        for entry_dir in control_dir(root).iterdir():
1589            if entry_dir.is_dir() and entry_dir.name not in keep and not folder_use.in_use(entry_dir):      # (never the Control a running server runs from)
1590                shutil.rmtree(longpath.long_path(entry_dir), ignore_errors=True)
1591        state.history({"at": (ctx.now or dt.datetime.now(dt.timezone.utc)).isoformat(), "action": "update-control",
1592                       "from": decision["installed"], "to": pkg.version, "ok": True})
1593        archive.unlink(missing_ok=True)
1594        result.update({"changed": True, "status": "updated", "installed_after": pkg.version,
1595                       "note": "the Terminal hands over to it from the next command; the app uses it from its next start"})
1596        return result
1597    finally:
1598        shutil.rmtree(longpath.long_path(stage), ignore_errors=True)
1599
1600
1601# ---------------------------------------------------------------------------------------------- app
1602
1603def app_public_key(environ=None) -> str | None:
1604    environ = os.environ if environ is None else environ
1605    explicit = environ.get("STRATA_APP_UPDATE_PUBKEY")
1606    if explicit:
1607        return explicit
1608    try:
1609        data = json.loads(signing.BUILTIN_KEYS.read_text(encoding="utf-8-sig"))
1610        value = data.get("app_minisign_public")
1611        return value if isinstance(value, str) and value else None
1612    except (OSError, ValueError):
1613        return None
1614
1615
1616def decide_app(feed: feedmod.Feed, ctx: Context) -> dict:
1617    report = {"installed": ctx.app_version, "offered": None, "status": "not-in-feed", "notes": "", "download_bytes": 0}
1618    if feed.app is None:
1619        return report
1620    entry = feed.app.for_platform(ctx.hardware["platform"])
1621    if entry is None:
1622        report["status"] = "none-for-this-pc"
1623        return report
1624    report.update({"offered": feed.app.version, "notes": feed.app.notes, "download_bytes": entry["size"]})
1625    if not ctx.app_version:
1626        report["status"] = "unknown-installed"
1627    else:
1628        report["status"] = "available" if feedmod.app_version_key(feed.app.version) > feedmod.app_version_key(ctx.app_version) else "current"
1629    return report
1630
1631
1632def update_app(ctx: Context, feed: feedmod.Feed) -> dict:
1633    """The Terminal's share of an app update: download the installer, check its SHA-256 (signed feed) and its minisign signature
1634    (the key the app trusts), and leave it in ``.updates/app``. The Desktop app installs itself through Tauri's updater; a
1635    terminal only fetches and verifies, because installing an app is the platform installer's job."""
1636    decision = decide_app(feed, ctx)
1637    result = {"component": "app", "status": decision["status"], "changed": False, "installed_before": decision["installed"]}
1638    if decision["status"] not in ("available", "unknown-installed"):
1639        return result
1640    entry = feed.app.for_platform(ctx.hardware["platform"])
1641    key = app_public_key(ctx.environ)
1642    if not key:
1643        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)
1644    root = ctx.components
1645    _free_space_check(root, entry["size"], ctx, entry["sha256"], "app")
1646    archive = _download(ctx, "app", entry["url"], entry["size"], entry["sha256"], f"Strata app {feed.app.version}", feed)
1647
1648    def chunks():
1649        with archive.open("rb") as stream:
1650            yield from iter(lambda: stream.read(1 << 20), b"")
1651    try:
1652        signing.minisign_verify(key, entry["signature"], chunks())
1653    except signing.SignatureError as exc:
1654        archive.unlink(missing_ok=True)
1655        raise UpdateError(f"the app installer failed its signature check: {exc}; it was deleted", 5) from None
1656    target_dir = updates_dir(root) / "app"
1657    target_dir.mkdir(parents=True, exist_ok=True)
1658    name = Path(transfer.resolve_ref(transfer.base_of(feed.source), entry["url"]).replace("\\", "/")).name or f"strata-app-{feed.app.version}"
1659    target = target_dir / name
1660    _atomic_mod.replace(archive, target)
1661    result.update({"changed": True, "status": "downloaded", "installed_after": None, "version": feed.app.version, "path": str(target),
1662                   "note": "Verified. Run the installer to finish; models and settings are kept."})
1663    return result
1664
1665
1666# ---------------------------------------------------------------------------------------------- the one command
1667
1668def _installed_before(name: str, ctx: Context):
1669    """What was installed when a step failed, for the report: the engine's view, Control's version, or nothing."""
1670    try:
1671        if name == "engine":
1672            return _engine_view(installed_engine(ctx.components, ctx.hardware)[0])
1673        if name == "control":
1674            return (active_control(ctx.components) or {}).get("version") or ec.runtime_version()
1675    except Exception:                                   # noqa: BLE001 - reporting only
1676        pass
1677    return None
1678
1679
1680def pending_changes(feed: feedmod.Feed, ctx: Context, state: State, *, engine: bool = True, control: bool = True) -> list[str]:
1681    """What this update would install or switch, in words, from the feed alone (nothing is downloaded).  Empty: nothing to do."""
1682    out = []
1683    if engine:
1684        decision = decide_engine(feed, ctx, state)
1685        if decision["status"] in ("install", "available") or (ctx.force and decision["status"] in ("failed-before", "skipped")):
1686            offered = (decision.get("offered") or {}).get("version")
1687            have = (decision.get("installed") or {}).get("version")
1688            out.append(f"engine {have} -> {offered}" if have else f"engine {offered}")
1689    if control:
1690        decision = decide_control(feed, ctx, state)
1691        if decision["status"] == "available":
1692            out.append(f"Control {decision['installed']} -> {decision['offered']}")
1693    return out
1694
1695
1696def _model_check(ctx: Context, feed: feedmod.Feed, state: State, *, engine: bool, control: bool) -> None:
1697    """Before anything is downloaded: with a model loaded and something to install, either wait for it to stop (--wait), ask (a gate), or refuse.
1698    An update never starts by itself beside a loaded model, and never half-runs (the engine refused while Control moves on)."""
1699    changes = pending_changes(feed, ctx, state, engine=engine, control=control)
1700    if not changes:
1701        return
1702    if ctx.wait:
1703        wait_until_idle(ctx.serving, wait=ctx.wait, emit=ctx.emit, cancel=ctx.cancel, poll=ctx.poll)
1704    serving = ctx.serving()
1705    if not serving:
1706        return
1707    gate = getattr(ctx, "gate", None)
1708    if gate is None:
1709        raise Busy(serving)
1710    gate.consent(serving, "It would update the " + " and the ".join(changes) + ".")
1711
1712
1713def _shape_steps(ctx: Context, feed: feedmod.Feed, engine: bool) -> list:
1714    """One step for each model-shape engine installed here (strata_control/shape_engine.py): the explicit update brings it up to the feed's, beside the older one; the Strata engine is
1715    not touched. A PC that never installed one has no such step."""
1716    if not engine:
1717        return []
1718    from strata_control import shape_engine
1719    return [(shape_engine.component_id(shape), (lambda shape=shape: shape_engine.update_one(ctx, feed, shape, install_missing=False)))
1720            for shape in shape_engine.installed_shapes(ctx.components)]
1721
1722
1723def run_update(ctx: Context, *, engine: bool = True, control: bool = True, app: bool = False) -> dict:
1724    """`strata update`: the feed once, then the engine, Control and (if asked) the app installer, each reported separately.
1725    A component that fails does not undo one that succeeded; the exit code is the worst one."""
1726    require_acquisition("the update")
1727    results, failure = [], None
1728    with update_lock(ctx.components):
1729        state = State(ctx.components)
1730        feed = open_feed(ctx, state)
1731        state.save()
1732        _model_check(ctx, feed, state, engine=engine, control=control)
1733        steps = ([("engine", lambda: update_engine(ctx, feed, state))] if engine else []) + \
1734                _shape_steps(ctx, feed, engine) + \
1735                ([("control", lambda: update_control(ctx, feed, state))] if control else []) + \
1736                ([("app", lambda: update_app(ctx, feed))] if app else [])
1737        for name, step in steps:
1738            try:
1739                results.append(step())
1740            except UpdateError as exc:
1741                results.append({"component": name, "status": "failed", "changed": False, "error": str(exc), "exit_code": exc.exit_code,
1742                                "installed_before": _installed_before(name, ctx)})
1743                failure = failure or exc
1744        if any(r.get("component") == "engine" and r.get("status") == "updated" for r in results):
1745            state.data.get("last_check", {}).pop("engine", None)
1746        try:                                              # the feed was read for this update: what it offers that is still newer is kept for the app's one card
1747            now_control = next((r.get("installed_after") for r in results if r.get("component") == "control" and r.get("status") == "updated"), None)
1748            state.data["last_check"] = _last_check(ctx, {"engine": decide_engine(feed, ctx, state), "app": decide_app(feed, ctx)}, now_control)
1749        except Exception:                                 # noqa: BLE001 - only a hint for the app
1750            pass
1751        state.save()
1752    return {"feed": {"source": ctx.source, "sequence": feed.sequence, "channel": feed.channel, "key_id": feed.key_id},
1753            "results": results, "exit_code": failure.exit_code if failure else 0}