okami.mom/strata

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

Niko1221Merge main 6c642df75 into f-own-int (round 16: network waits, robustness, Windows kill-on-close job start, GitHub and transfer fixes)cd9745050

main
32.2 KiB691 linesraw
1"""Independent, versioned components: manifests, safe unpacking, atomic activation, rollback.
2
3The application, the engine, the agent runtime, tuning and prepared data are separate deliverables
4with separate lifecycles, so they are separate *components* here. This module is the machinery they
5share: what a component is, whether it may be used on this machine, how it is verified before it is
6unpacked, how it is unpacked without escaping its directory, how it is cached, and how it is
7activated and rolled back.
8
9The design decisions that matter, and why:
10
11**Verification happens before anything is written.** A manifest names each artifact's SHA-256. An
12artifact whose digest does not match is refused and nothing is extracted — not extracted-then-checked,
13because a compromised archive can do damage during extraction.
14
15**Unpacking cannot escape its destination.** Archive members are validated: no absolute paths, no
16`..` segments, no symlinks or hard links pointing outside, no device or FIFO members, and on Windows
17no drive-relative or UNC paths. Every member's resolved destination is checked to be inside the
18target. This is the one place where a hostile input turns into arbitrary file writes, so it is
19checked rather than trusted, and the checks are tested with the actual attack shapes.
20
21**Installation is by content digest, not by version string.** The cache is keyed on the digest of the
22artifact bytes, so a rebuilt artifact with an unchanged version number is a different cache entry,
23and a compatible application update reuses components rather than re-downloading them.
24
25**Activation is a rename, and the previous target is kept.** A component version becomes active by
26renaming a directory into place, which is atomic within a filesystem; the version it replaced is
27moved aside rather than deleted, so rollback restores it exactly. Nothing is ever deleted on
28activation.
29
30**Interrupted transfers are the normal case, not the exception.** A partial download is kept with a
31digest of what is there, resumed when possible, and only promoted to the cache once complete and
32verified. A crash during activation leaves the store consistent because the rename either happened or
33it did not.
34"""
35
36from __future__ import annotations
37
38import hashlib
39import json
40import re
41import shutil
42import stat
43import tarfile
44import time
45import zipfile
46from dataclasses import asdict, dataclass
47from pathlib import Path, PurePosixPath
48from typing import Any, Iterable
49
50SCHEMA_VERSION = 1
51
52from strata_control.targets import BACKEND_MATRIX, ComponentError, backend_supported, host_platform  # noqa: E402,F401
53from strata_control import atomic as _atomic_mod
54#: Component kinds, so a manifest cannot claim a role the architecture does not have.
55KINDS = ("application", "runtime", "agent-runtime", "tuning", "engine", "prepared-data")
56
57
58class UnsafeArchive(ComponentError):
59    """An archive member would escape the destination. Nothing was extracted."""
60
61
62# --------------------------------------------------------------------------- manifests
63
64@dataclass
65class Artifact:
66    """One downloadable file, identified by content."""
67
68    name: str
69    url: str | None
70    sha256: str
71    bytes: int
72    format: str = "tar.gz"          # tar.gz | tar.xz | zip | file
73    unpack_to: str | None = None    # where inside the component the archive's root lands
74
75    def verify_bytes(self, payload: bytes) -> None:
76        actual = hashlib.sha256(payload).hexdigest()
77        if actual != self.sha256:
78            raise ComponentError(
79                f"the downloaded {self.name} does not match its manifest: expected "
80                f"{self.sha256[:16]}…, got {actual[:16]}…")
81        if self.bytes and len(payload) != self.bytes:
82            raise ComponentError(
83                f"{self.name} is {len(payload)} bytes, the manifest declares {self.bytes}")
84
85    def verify_file(self, path: Path) -> None:
86        digest = hashlib.sha256()
87        size = 0
88        with Path(path).open("rb") as fh:
89            for block in iter(lambda: fh.read(1 << 20), b""):
90                digest.update(block)
91                size += len(block)
92        if digest.hexdigest() != self.sha256:
93            raise ComponentError(
94                f"{path.name} does not match its manifest: expected {self.sha256[:16]}…, "
95                f"got {digest.hexdigest()[:16]}…")
96        if self.bytes and size != self.bytes:
97            raise ComponentError(f"{path.name} is {size} bytes, the manifest declares {self.bytes}")
98
99
100@dataclass
101class Component:
102    """A versioned, independently installable piece of the product."""
103
104    id: str
105    version: str
106    kind: str
107    backend: str | None
108    platforms: tuple[str, ...]
109    artifacts: tuple[Artifact, ...]
110    requires: tuple[str, ...] = ()
111    provides: tuple[str, ...] = ()
112    license: str = ""
113    notes: str = ""
114    #: Where the payload must be on the PATH or on disk once active, relative to the component root.
115    entrypoint: str | None = None
116
117    @property
118    def cache_key(self) -> str:
119        """The identity of this component's bytes, not its version label.
120
121        A rebuilt artifact with the same version is a different key, so a cache hit is a statement
122        about the bytes rather than about a string someone typed.
123        """
124        joined = "|".join(f"{a.name}:{a.sha256}" for a in sorted(self.artifacts, key=lambda a: a.name))
125        return hashlib.sha256(f"{self.id}@{self.version}|{joined}".encode()).hexdigest()
126
127    def to_dict(self) -> dict[str, Any]:
128        data = asdict(self)
129        data["schema_version"] = SCHEMA_VERSION
130        data["cache_key"] = self.cache_key
131        return data
132
133
134def parse_manifest(payload: str | bytes | dict) -> Component:
135    """Read a component manifest, refusing anything that is not one.
136
137    A manifest is the input that decides what gets downloaded and unpacked, so it is parsed strictly:
138    a missing digest or an unknown kind is an error, not a default.
139    """
140    if isinstance(payload, (str, bytes)):
141        try:
142            data = json.loads(payload)
143        except json.JSONDecodeError as e:
144            raise ComponentError(f"the component manifest is not valid JSON: {e}") from None
145    else:
146        data = payload
147    if not isinstance(data, dict):
148        raise ComponentError("the component manifest must be a JSON object")
149    if data.get("schema_version") != SCHEMA_VERSION:
150        raise ComponentError(
151            f"unsupported manifest schema_version {data.get('schema_version')!r}; expected "
152            f"{SCHEMA_VERSION}")
153
154    for required in ("id", "version", "kind", "artifacts"):
155        if not data.get(required):
156            raise ComponentError(f"the component manifest has no {required!r}")
157    if data["kind"] not in KINDS:
158        raise ComponentError(
159            f"unknown component kind {data['kind']!r}; expected one of {', '.join(KINDS)}")
160    if not re.fullmatch(r"[a-z0-9][a-z0-9._-]{0,63}", str(data["id"])):
161        raise ComponentError(f"the component id {data['id']!r} is not a plain lowercase name")
162
163    artifacts: list[Artifact] = []
164    for raw in data["artifacts"]:
165        if not isinstance(raw, dict):
166            raise ComponentError("every artifact must be a JSON object")
167        for required in ("name", "sha256", "bytes"):
168            if raw.get(required) in (None, ""):
169                raise ComponentError(f"an artifact has no {required!r}: {raw.get('name')!r}")
170        digest = str(raw["sha256"]).lower()
171        if not re.fullmatch(r"[0-9a-f]{64}", digest):
172            raise ComponentError(
173                f"an artifact's sha256 is not a 64-character hex digest: {raw['sha256']!r}")
174        try:
175            size = int(raw["bytes"])
176        except (TypeError, ValueError):
177            raise ComponentError(f"an artifact's bytes is not a number: {raw['bytes']!r}") from None
178        if size <= 0:
179            raise ComponentError(f"an artifact declares {size} bytes, which cannot be a real file")
180        # A path-like name would be used as a filename later, so it must not be one.
181        if "/" in str(raw["name"]) or "\\" in str(raw["name"]) or str(raw["name"]) in (".", ".."):
182            raise ComponentError(f"an artifact name is a path, which is not allowed: {raw['name']!r}")
183        artifacts.append(Artifact(
184            name=str(raw["name"]), url=raw.get("url"), sha256=digest, bytes=size,
185            format=str(raw.get("format", "tar.gz")),
186            unpack_to=raw.get("unpack_to")))
187    if not artifacts:
188        raise ComponentError("the component manifest lists no artifacts")
189
190    platforms = data.get("platforms")
191    if platforms is None:
192        raise ComponentError(
193            "the component manifest does not say which platforms it supports; an unstated platform "
194            "would be treated as every platform")
195    if not isinstance(platforms, (list, tuple)) or not platforms:
196        raise ComponentError("the component's platforms must be a non-empty list")
197
198    return Component(
199        id=str(data["id"]), version=str(data["version"]), kind=str(data["kind"]),
200        backend=data.get("backend"), platforms=tuple(str(p) for p in platforms),
201        artifacts=tuple(artifacts), requires=tuple(data.get("requires") or ()),
202        provides=tuple(data.get("provides") or ()), license=str(data.get("license") or ""),
203        notes=str(data.get("notes") or ""), entrypoint=data.get("entrypoint"))
204
205
206def check_compatible(component: Component, *, target: str | None = None,
207                     backend: str | None = None) -> list[str]:
208    """Why this component cannot be used here. An empty list means it can.
209
210    Compatibility is a refusal gate, not a warning: activating an engine built for another backend is
211    the failure this exists to prevent, and the packet is explicit that unsupported combinations stay
212    explicitly gated rather than attempted.
213    """
214    target = target or host_platform()
215    reasons: list[str] = []
216    if target not in component.platforms:
217        reasons.append(
218            f"{component.id} {component.version} supports {', '.join(component.platforms)}, not {target}")
219    if component.backend and backend is not None and component.backend != backend:
220        reasons.append(
221            f"{component.id} is built for the {component.backend} backend, not {backend}")
222    if component.backend:
223        supported, why = backend_supported(component.backend, target)
224        if not supported:
225            reasons.append(why)
226    return reasons
227
228
229# --------------------------------------------------------------------------- safe unpacking
230
231def _is_unsafe_member(name: str) -> str | None:
232    """Why an archive member name is unsafe, or None if it is fine.
233
234    The attack shapes are listed explicitly rather than relying on a single normalisation trick,
235    because a name that survives normalisation on one platform can still be absolute on another.
236    """
237    if not name or name in (".", "./"):
238        return "an empty member name"
239    if "\x00" in name:
240        return "a NUL byte in the name"
241    # Windows separators are treated as separators on every platform: an archive built on Windows
242    # must not be able to escape a destination on macOS, and vice versa.
243    normalised = name.replace("\\", "/")
244    if normalised.startswith("/"):
245        return "an absolute path"
246    if re.match(r"^[A-Za-z]:", normalised):
247        return "a drive-letter path"
248    if normalised.startswith("//"):
249        return "a UNC path"
250    parts = PurePosixPath(normalised).parts
251    if any(part == ".." for part in parts):
252        return "a '..' segment"
253    return None
254
255
256def _check_member_within(destination: Path, member_name: str) -> Path:
257    """The member's resolved destination, refusing anything outside `destination`.
258
259    Both the lexical check above and this resolved check are performed: the lexical one catches the
260    obvious shapes, and this one catches a path that is only outside after resolution.
261    """
262    unsafe = _is_unsafe_member(member_name)
263    if unsafe:
264        raise UnsafeArchive(f"the archive contains {unsafe}: {member_name!r}")
265    target = (destination / member_name.replace("\\", "/")).resolve()
266    root = destination.resolve()
267    if target != root and root not in target.parents:
268        raise UnsafeArchive(f"the archive member {member_name!r} would land outside the destination")
269    return target
270
271
272def safe_extract(archive: Path, destination: Path, *, fmt: str | None = None) -> list[str]:
273    """Unpack an archive into `destination`, or refuse without writing.
274
275    Validated before any member is written: every member's name and resolved destination is checked
276    first, so a refusal leaves the destination untouched rather than half-populated.
277    """
278    archive = Path(archive)
279    destination = Path(destination)
280    fmt = fmt or _format_of(archive)
281    members = _members(archive, fmt)
282
283    # Validate everything first: a refusal must not leave a partial extraction behind.
284    for name, kind in members:
285        _check_member_within(destination, name)
286        if kind in ("symlink", "hardlink", "device", "fifo"):
287            # A link inside the archive can point anywhere, including outside; verifying where each
288            # one points is more permissive than this product needs, so links are refused outright.
289            raise UnsafeArchive(
290                f"the archive contains a {kind} member ({name!r}); links are not accepted because a "
291                "link can point outside the destination")
292        if kind == "other":
293            raise UnsafeArchive(f"the archive contains an unsupported member type ({name!r})")
294
295    destination.mkdir(parents=True, exist_ok=True)
296    written: list[str] = []
297    if fmt in ("tar.gz", "tar.xz", "tar.bz2", "tar"):
298        with tarfile.open(archive, _tar_mode(fmt)) as tar:
299            for member in tar.getmembers():
300                target = _check_member_within(destination, member.name)
301                if member.isdir():
302                    target.mkdir(parents=True, exist_ok=True)
303                    continue
304                target.parent.mkdir(parents=True, exist_ok=True)
305                source = tar.extractfile(member)
306                if source is None:
307                    continue
308                with target.open("wb") as out:
309                    shutil.copyfileobj(source, out)
310                # Preserve the executable bit, which a bundled runtime or engine needs, and nothing
311                # else: the archive's own permission bits are not trusted for setuid or setgid.
312                mode = member.mode & 0o777
313                if mode:
314                    target.chmod(mode | (stat.S_IXUSR if mode & 0o100 else 0))
315                written.append(member.name)
316    elif fmt == "zip":
317        with zipfile.ZipFile(archive) as zf:
318            for info in zf.infolist():
319                target = _check_member_within(destination, info.filename)
320                if info.is_dir():
321                    target.mkdir(parents=True, exist_ok=True)
322                    continue
323                target.parent.mkdir(parents=True, exist_ok=True)
324                with zf.open(info) as source, target.open("wb") as out:
325                    shutil.copyfileobj(source, out)
326                written.append(info.filename)
327    else:
328        raise ComponentError(f"unsupported archive format {fmt!r}")
329    return written
330
331
332def _format_of(archive: Path) -> str:
333    name = archive.name.lower()
334    for suffix, fmt in ((".tar.gz", "tar.gz"), (".tgz", "tar.gz"), (".tar.xz", "tar.xz"),
335                        (".txz", "tar.xz"), (".tar.bz2", "tar.bz2"), (".zip", "zip"),
336                        (".tar", "tar")):
337        if name.endswith(suffix):
338            return fmt
339    raise ComponentError(f"cannot tell the archive format of {archive.name!r} from its name")
340
341
342def _tar_mode(fmt: str) -> str:
343    return {"tar.gz": "r:gz", "tar.xz": "r:xz", "tar.bz2": "r:bz2", "tar": "r:"}[fmt]
344
345
346def _members(archive: Path, fmt: str) -> list[tuple[str, str]]:
347    """Every member as (name, kind), used for validation before extraction."""
348    out: list[tuple[str, str]] = []
349    if fmt == "zip":
350        with zipfile.ZipFile(archive) as zf:
351            for info in zf.infolist():
352                out.append((info.filename, "dir" if info.is_dir() else "file"))
353        return out
354    with tarfile.open(archive, _tar_mode(fmt)) as tar:
355        for member in tar.getmembers():
356            if member.isdir():
357                kind = "dir"
358            elif member.isfile():
359                kind = "file"
360            elif member.issym():
361                kind = "symlink"
362            elif member.islnk():
363                kind = "hardlink"
364            elif member.ischr() or member.isblk():
365                kind = "device"
366            elif member.isfifo():
367                kind = "fifo"
368            else:
369                kind = "other"
370            out.append((member.name, kind))
371    return out
372
373
374# --------------------------------------------------------------------------- the store
375
376@dataclass
377class InstalledComponent:
378    """A component version present on disk, and whether it is the active one."""
379
380    id: str
381    version: str
382    cache_key: str
383    path: str
384    installed_at: float
385    artifact_sha256: tuple[str, ...] = ()
386    active: bool = False
387
388
389class ComponentStore:
390    """Installed components, a content-addressed cache, and atomic activation with rollback.
391
392    Layout::
393
394        <root>/cache/<cache_key>/          unpacked payload, immutable once complete
395        <root>/active/<component-id>       a directory rename-linked to a cached version
396        <root>/previous/<component-id>     the version that was active before the last activation
397        <root>/partial/<artifact-name>     an interrupted transfer, kept for resume
398        <root>/state.json                  what is installed and what is active
399    """
400
401    def __init__(self, root: Path) -> None:
402        self.root = Path(root)
403        for part in ("cache", "active", "previous", "partial"):
404            (self.root / part).mkdir(parents=True, exist_ok=True)
405
406    # ------------------------------------------------------------------ state
407
408    @property
409    def state_path(self) -> Path:
410        return self.root / "state.json"
411
412    def state(self) -> dict[str, Any]:
413        if not self.state_path.exists():
414            return {"schema_version": SCHEMA_VERSION, "components": {}}
415        try:
416            data = json.loads(self.state_path.read_text(encoding="utf-8"))
417        except json.JSONDecodeError:
418            # A damaged state file must not make the store unusable; the cache on disk is the truth
419            # about what is present, and the state file is rebuilt from it as things are activated.
420            return {"schema_version": SCHEMA_VERSION, "components": {}}
421        if data.get("schema_version") != SCHEMA_VERSION:
422            return {"schema_version": SCHEMA_VERSION, "components": {}}
423        return data
424
425    def _save_state(self, data: dict[str, Any]) -> None:
426        temp = self.state_path.parent / (self.state_path.name + ".tmp")
427        temp.write_text(json.dumps(data, indent=1, sort_keys=True) + "\n", encoding="utf-8")
428        _atomic_mod.replace(temp, self.state_path)
429
430    # ------------------------------------------------------------------ cache and installation
431
432    def cached(self, component: Component) -> Path | None:
433        """The cached payload for exactly these bytes, if it is complete."""
434        path = self.root / "cache" / component.cache_key
435        marker = path / ".complete"
436        return path if marker.exists() else None
437
438    def install(self, component: Component, *, source: Path | None = None,
439                payloads: dict[str, bytes] | None = None,
440                target: str | None = None, backend: str | None = None) -> Path:
441        """Verify and unpack a component into the cache, reusing it when the bytes are known.
442
443        Every artifact is verified *before* unpacking, so a mismatch writes nothing. A component
444        whose bytes are already cached is not downloaded or unpacked again, which is what makes a
445        compatible application update free of engine re-downloads.
446        """
447        reasons = check_compatible(component, target=target, backend=backend)
448        if reasons:
449            raise ComponentError("; ".join(reasons), 2)
450
451        existing = self.cached(component)
452        if existing is not None and source is None and payloads is None:
453            return existing
454
455        destination = self.root / "cache" / component.cache_key
456        if destination.exists() and (destination / ".complete").exists():
457            return destination
458
459        # A staging directory named for the cache key, so a crash leaves an incomplete directory that
460        # is never mistaken for a complete one (the `.complete` marker is written last).
461        staging = self.root / "cache" / f".{component.cache_key}.partial"
462        if staging.exists():
463            shutil.rmtree(staging, ignore_errors=True)
464        staging.mkdir(parents=True)
465
466        try:
467            for artifact in component.artifacts:
468                data = self._obtain(artifact, source=source, payloads=payloads)
469                artifact.verify_bytes(data)
470                into = staging / (artifact.unpack_to or "")
471                into.mkdir(parents=True, exist_ok=True)
472                if artifact.format in ("tar.gz", "tar.xz", "tar.bz2", "tar", "zip"):
473                    temp_archive = staging / f".{artifact.name}.archive"
474                    temp_archive.write_bytes(data)
475                    try:
476                        safe_extract(temp_archive, into, fmt=artifact.format)
477                    finally:
478                        temp_archive.unlink(missing_ok=True)
479                else:
480                    (into / artifact.name).write_bytes(data)
481                    if artifact.name.endswith((".sh", ".bin")):
482                        (into / artifact.name).chmod(0o755)
483            (staging / ".complete").write_text(
484                json.dumps({"cache_key": component.cache_key, "id": component.id,
485                            "version": component.version, "installed_at": time.time()},
486                           indent=1) + "\n", encoding="utf-8")
487            if destination.exists():
488                shutil.rmtree(destination, ignore_errors=True)
489            _atomic_mod.replace(staging, destination)
490        except BaseException:
491            # Leave nothing that looks complete.
492            shutil.rmtree(staging, ignore_errors=True)
493            raise
494
495        state = self.state()
496        state["components"].setdefault(component.id, {})["installed"] = (
497            state["components"].get(component.id, {}).get("installed") or {})
498        state["components"][component.id]["installed"][component.version] = asdict(InstalledComponent(
499            id=component.id, version=component.version, cache_key=component.cache_key,
500            path=str(destination), installed_at=time.time(),
501            artifact_sha256=tuple(a.sha256 for a in component.artifacts)))
502        self._save_state(state)
503        return destination
504
505    def _obtain(self, artifact: Artifact, *, source: Path | None,
506                payloads: dict[str, bytes] | None) -> bytes:
507        """The artifact's bytes, from memory, from disk, or from its URL."""
508        if payloads and artifact.name in payloads:
509            return payloads[artifact.name]
510        if source is not None:
511            candidate = Path(source)
512            if candidate.is_dir():
513                candidate = candidate / artifact.name
514            if not candidate.exists():
515                raise ComponentError(f"the artifact {artifact.name} is not at {candidate}")
516            return candidate.read_bytes()
517        if artifact.url:
518            return self._fetch(artifact)
519        raise ComponentError(
520            f"{artifact.name} has no url and no local source was given, so it cannot be obtained")
521
522    def _fetch(self, artifact: Artifact) -> bytes:
523        """Download with resume, keeping partial bytes for a later attempt.
524
525        A single interrupted transfer is the normal case on a real connection, so the partial bytes
526        are kept under `partial/` and a ranged request picks up where it stopped. The result is
527        verified by the caller before anything is unpacked.
528        """
529        from strata_control import acquisition
530        acquisition.require(f"the download of {artifact.name}", "strata install")
531        import urllib.error
532        import urllib.request
533        from strata_control import tls
534        tls.install()
535        partial = self.root / "partial" / artifact.name
536        have = partial.stat().st_size if partial.exists() else 0
537        if have > artifact.bytes:
538            partial.unlink()                       # a stale file from a different artifact
539            have = 0
540        headers = {"Range": f"bytes={have}-"} if have else {}
541        request = urllib.request.Request(artifact.url, headers=headers)
542        mode = "ab" if have else "wb"
543        try:
544            from strata_control import netpolicy        # the network rule: 12 s, one retry with 30 s, clear failures at once; reads stall out after 60 s
545            try:
546                answer = netpolicy.open_url(netpolicy.urlopen, request)
547            except netpolicy.NetFailure as failure:
548                raise ComponentError(failure.headline("the " + artifact.name) + " " + failure.next_step()) from None
549            with answer as response:
550                if have and response.status != 206:
551                    # The server ignored the range, so start again rather than appending to a prefix
552                    # and producing a corrupt file that would fail verification much later.
553                    have, mode = 0, "wb"
554                with partial.open(mode) as out:
555                    while True:
556                        block = response.read(1 << 20)
557                        if not block:
558                            break
559                        out.write(block)
560        except (urllib.error.URLError, OSError) as e:
561            if tls.is_certificate_error(e):
562                raise ComponentError(f"the download of {artifact.name} stopped. " + tls.explain(tls.host_of(artifact.url))) from e
563            raise ComponentError(
564                f"the download of {artifact.name} was interrupted after "
565                f"{partial.stat().st_size if partial.exists() else 0} of {artifact.bytes} bytes; "
566                f"the partial file is kept and a later attempt resumes it ({e})") from e
567        data = partial.read_bytes()
568        if len(data) != artifact.bytes:
569            raise ComponentError(
570                f"the download of {artifact.name} is {len(data)} bytes but the manifest declares "
571                f"{artifact.bytes}; the partial file is kept so a later attempt can resume it")
572        partial.unlink(missing_ok=True)
573        return data
574
575    # ------------------------------------------------------------------ activation and rollback
576
577    def active_path(self, component_id: str) -> Path:
578        return self.root / "active" / component_id
579
580    def activate(self, component: Component, *, target: str | None = None,
581                 backend: str | None = None) -> dict[str, Any]:
582        """Make a cached version active, moving the previous one aside.
583
584        The move is a rename, so it either happens or it does not. The version being replaced is
585        moved to `previous/` rather than deleted, which is what makes `rollback` exact.
586        """
587        reasons = check_compatible(component, target=target, backend=backend)
588        if reasons:
589            raise ComponentError("; ".join(reasons), 2)
590        source = self.cached(component)
591        if source is None:
592            raise ComponentError(
593                f"{component.id} {component.version} is not installed; install it before activating")
594        active = self.active_path(component.id)
595        previous = self.root / "previous" / component.id
596
597        moved_aside: str | None = None
598        if active.exists():
599            if previous.exists():
600                shutil.rmtree(previous, ignore_errors=True)
601            _atomic_mod.replace(active, previous)
602            moved_aside = str(previous)
603
604        # Record what is being displaced BEFORE the activation, so a crash between the two leaves a
605        # rollback record that points at the previous version rather than at the new one.
606        state = self.state()
607        entry = state["components"].setdefault(component.id, {})
608        displaced = dict(entry.get("active") or {})
609        if moved_aside and displaced:
610            entry["rollback"] = {"version": displaced.get("version"),
611                                 "cache_key": displaced.get("cache_key"), "path": moved_aside}
612        self._save_state(state)
613
614        # The cache is never consumed: an application update that reuses an installed engine depends
615        # on the cached payload still being there, so the active directory is a copy. The copy goes
616        # in beside the target and is renamed into place, so the active path is never half-populated.
617        active.parent.mkdir(parents=True, exist_ok=True)
618        incoming = active.parent / f".{component.id}.incoming"
619        if incoming.exists():
620            shutil.rmtree(incoming, ignore_errors=True)
621        shutil.copytree(source, incoming, symlinks=False)
622        _atomic_mod.replace(incoming, active)
623
624        state = self.state()
625        entry = state["components"].setdefault(component.id, {})
626        entry["active"] = {"version": component.version, "cache_key": component.cache_key,
627                           "activated_at": time.time(), "from": str(source)}
628        self._save_state(state)
629        return {"id": component.id, "version": component.version, "active": str(active),
630                "moved_aside": moved_aside}
631
632    def rollback(self, component_id: str) -> dict[str, Any]:
633        """Restore the version that was active before the last activation.
634
635        Refuses when there is nothing to restore rather than leaving the component absent, because
636        "rollback succeeded" and "the component is now missing" must not be the same outcome.
637        """
638        previous = self.root / "previous" / component_id
639        if not previous.exists():
640            raise ComponentError(
641                f"there is no previous version of {component_id} to restore", 2)
642        active = self.active_path(component_id)
643        if active.exists():
644            abandoned = self.root / "previous" / f"{component_id}.replaced"
645            if abandoned.exists():
646                shutil.rmtree(abandoned, ignore_errors=True)
647            _atomic_mod.replace(active, abandoned)
648        _atomic_mod.replace(previous, active)
649        state = self.state()
650        entry = state["components"].get(component_id, {})
651        restored = entry.get("rollback", {})
652        entry["active"] = {"version": restored.get("version"), "cache_key": restored.get("cache_key"),
653                           "activated_at": time.time(), "restored": True}
654        entry.pop("rollback", None)
655        self._save_state(state)
656        return {"id": component_id, "restored": restored.get("version"), "active": str(active)}
657
658    def installed(self, component_id: str) -> list[InstalledComponent]:
659        """Every version of a component present in the cache."""
660        entry = self.state().get("components", {}).get(component_id, {})
661        out: list[InstalledComponent] = []
662        active = (entry.get("active") or {}).get("cache_key")
663        for version, data in (entry.get("installed") or {}).items():
664            out.append(InstalledComponent(
665                id=component_id, version=version, cache_key=data.get("cache_key", ""),
666                path=data.get("path", ""), installed_at=data.get("installed_at", 0.0),
667                artifact_sha256=tuple(data.get("artifact_sha256") or ()),
668                active=data.get("cache_key") == active))
669        return sorted(out, key=lambda c: c.installed_at)
670
671    def prune_cache(self, *, keep: Iterable[str] = ()) -> list[str]:
672        """Delete cached payloads that nothing refers to. Never touches an active or previous one.
673
674        A compatible application update must not download an engine again, so pruning keeps whatever
675        the active and previous versions point at, plus anything the caller names.
676        """
677        keep_keys = set(keep)
678        state = self.state()
679        for entry in state.get("components", {}).values():
680            for key in (entry.get("active") or {}, entry.get("rollback") or {}):
681                if key.get("cache_key"):
682                    keep_keys.add(key["cache_key"])
683        removed: list[str] = []
684        cache = self.root / "cache"
685        for path in cache.iterdir() if cache.exists() else []:
686            if not path.is_dir() or path.name.startswith("."):
687                continue
688            if path.name not in keep_keys:
689                shutil.rmtree(path, ignore_errors=True)
690                removed.append(path.name)
691        return removed