Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(runtime): reclaim shared managed archives truthfully (#1723)

Call Whiteff2a95270d2a
diff --git a/core/managed_runtime.py b/core/managed_runtime.py
index b644f878d..37ca1d9ce 100644
--- a/core/managed_runtime.py
+++ b/core/managed_runtime.py
@@ -13,6 +13,7 @@ import stat
import tarfile
import tempfile
import threading
+import time
import urllib.parse
import urllib.request
from collections.abc import Callable, Mapping
@@ -42,6 +43,14 @@ from storage.lock import (
logger = logging.getLogger(__name__)
_SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
+_MANIFEST_CACHE_RE = re.compile(r"^manifest-[0-9a-f]{16}\.json$")
+_ARCHIVE_MTIME_GUARD_SECONDS = 15 * 60
+_ARCHIVE_INSPECTION_FAILED = "archive_inspection_failed"
+_ARCHIVE_REMOVAL_FAILED = "archive_removal_failed"
+_ARCHIVE_PROVENANCE_FILENAME = "archive-provenance.json"
+_ARCHIVE_PROVENANCE_SCHEMA_VERSION = 1
+_PACKAGED_MANIFEST_LINEAGE = "packaged"
+_CUSTOM_MANIFEST_LINEAGE = "custom"
_INSTALL_LOCKS: dict[str, threading.Lock] = {}
_INSTALL_LOCKS_GUARD = threading.Lock()
_ENSURE_FAILURE_SUFFIXES = frozenset(
@@ -83,6 +92,12 @@ def _is_exclusive_regular_file(info: os.stat_result) -> bool:
return not (reparse and attrs & reparse)
+def _is_reparse_point(info: os.stat_result) -> bool:
+ attrs = getattr(info, "st_file_attributes", 0)
+ reparse = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0)
+ return bool(reparse and attrs & reparse)
+
+
@dataclass(frozen=True)
class ManagedRuntimeArchive:
platform: str
@@ -122,6 +137,15 @@ class ManagedRuntimeSpec:
return f".avibe-{self.runtime_id}-runtime.json"
+@dataclass(frozen=True)
+class _ManagedRuntimeInstall:
+ path: Path
+ lineage: str
+ archive_name: str
+ archive_sha256: str
+ mtime: float
+
+
class ManagedRuntimeManager:
"""Shared manifest/download/verify/install core for managed runtimes."""
@@ -143,6 +167,7 @@ class ManagedRuntimeManager:
self._download_error: dict[str, Any] | None = None
self._install_lock = install_lock_for(spec.runtime_id)
self._install_file_lock_path = self.runtime_dir / ".install.lock"
+ self._archive_provenance_path = self.runtime_dir / _ARCHIVE_PROVENANCE_FILENAME
def ensure(
self,
@@ -546,6 +571,7 @@ class ManagedRuntimeManager:
"removed": [],
"reason": self._reason("clean_inspection_failed"),
"message": str(exc),
+ "archives": self._skipped_archive_report(_ARCHIVE_INSPECTION_FAILED),
}
try:
file_lock = self._acquire_mutation_lock()
@@ -577,6 +603,7 @@ class ManagedRuntimeManager:
"removed": list(removed),
"reason": self._reason("clean_inspection_failed"),
"message": str(cop),
+ "archives": self._skipped_archive_report(_ARCHIVE_INSPECTION_FAILED),
}
finally:
self._release_mutation_lock(file_lock)
@@ -760,13 +787,17 @@ class ManagedRuntimeManager:
versions_dir = self.runtime_dir / "versions"
current = self._current_install_dir(versions_dir)
try:
- versions_is_dir = stat.S_ISDIR(versions_dir.stat().st_mode)
+ versions_info = versions_dir.lstat()
except FileNotFoundError:
versions_is_dir = False
except OSError as exc:
# An uninspectable versions tree must not silently preview as
# empty (misleading "0 entries") — surface an inspection failure.
raise OSError(f"versions directory cannot be inspected: {versions_dir}") from exc
+ else:
+ if _is_reparse_point(versions_info) or not stat.S_ISDIR(versions_info.st_mode):
+ raise OSError(f"versions directory is not a confined directory: {versions_dir}")
+ versions_is_dir = True
install_dirs = (
{
@@ -780,32 +811,534 @@ class ManagedRuntimeManager:
resolved_install_dirs = {path.resolve() for path in install_dirs}
if current is not None and current not in resolved_install_dirs:
raise OSError("current.json is unreadable")
- protected = (
- {current}
- if current is not None
- else resolved_install_dirs
- )
- for staging_dir in self.runtime_dir.glob("install-*"):
- if staging_dir.is_dir():
- if not dry_run:
- shutil.rmtree(staging_dir, ignore_errors=True)
- removed.append(str(staging_dir))
+ # Sibling metadata is not needed to reclaim abandoned staging.
+ staging_candidates = self._staging_install_dirs()
+ removal_failed = False
+ for path in staging_candidates:
+ if dry_run:
+ removed.append(str(path))
+ continue
+ if self._remove_tree(path):
+ removed.append(str(path))
+ else:
+ removal_failed = True
- if not versions_is_dir:
- return {"ok": True, "removed": removed}
- candidates = sorted(
+ downloads_present = self._downloads_namespace_present()
+ installs = (
+ self._read_managed_install_records(install_dirs)
+ if current is not None or downloads_present
+ else []
+ )
+ records_by_path = {record.path.resolve(): record for record in installs}
+ if current is not None and current not in records_by_path:
+ raise OSError("current install metadata is unreadable")
+
+ protected = set(resolved_install_dirs) if current is None else {current}
+ keep_count = max(0, keep_previous)
+ if current is not None:
+ by_lineage: dict[str, list[_ManagedRuntimeInstall]] = {}
+ for record in installs:
+ by_lineage.setdefault(record.lineage, []).append(record)
+ current_lineage = records_by_path[current].lineage
+ for lineage, lineage_installs in by_lineage.items():
+ ranked = sorted(lineage_installs, key=lambda item: item.mtime, reverse=True)
+ if lineage == current_lineage:
+ rollback = [record for record in ranked if record.path.resolve() != current]
+ protected.update(record.path.resolve() for record in rollback[:keep_count])
+ elif ranked:
+ # Packaged and custom sources each keep a head. Switching
+ # source class must not erase the only locally recoverable
+ # copy of the alternate lineage.
+ protected.add(ranked[0].path.resolve())
+ protected.update(record.path.resolve() for record in ranked[1 : keep_count + 1])
+
+ install_candidates = sorted(
(path for path in install_dirs if path.resolve() not in protected),
key=lambda path: path.stat().st_mtime,
reverse=True,
)
- for path in candidates[max(0, keep_previous) :]:
- if not dry_run:
- shutil.rmtree(path, ignore_errors=True)
- removed.append(str(path))
- if not dry_run:
+ persisted_provenance = self._read_archive_provenance()
+ candidate_paths = {path.resolve() for path in install_candidates}
+ candidate_provenance = {
+ (record.archive_name, record.archive_sha256)
+ for record in installs
+ if record.path.resolve() in candidate_paths
+ and self._archive_name_is_owned(record.archive_name)
+ }
+ pending_provenance = persisted_provenance | candidate_provenance
+ if not dry_run and pending_provenance != persisted_provenance:
+ try:
+ self._write_archive_provenance(pending_provenance)
+ except OSError as exc:
+ raise OSError("archive provenance cannot be persisted") from exc
+
+ for path in install_candidates:
+ if dry_run:
+ removed.append(str(path))
+ continue
+ if self._remove_tree(path):
+ removed.append(str(path))
+ else:
+ removal_failed = True
+
+ if versions_is_dir and not dry_run:
self._prune_empty_version_dirs(versions_dir)
- return {"ok": True, "removed": removed}
+
+ removed_install_paths = {
+ path.resolve()
+ for path in install_candidates
+ if dry_run or not self._path_exists(path)
+ }
+ retained_installs = [
+ record for record in installs if record.path.resolve() not in removed_install_paths
+ ]
+ protected_archive_sha256s = {record.archive_sha256 for record in retained_installs}
+ if current is not None:
+ protected_archive_sha256s.add(self._current_archive_sha256())
+ install_provenance = {
+ (record.archive_name, record.archive_sha256)
+ for record in installs
+ if self._archive_name_is_owned(record.archive_name)
+ }
+ archive_provenance = pending_provenance | install_provenance
+ archives, terminal_archive_names = self._clean_downloaded_archives(
+ archive_provenance=archive_provenance,
+ protected_sha256s=protected_archive_sha256s,
+ dry_run=dry_run,
+ )
+ if archives["failed_count"]:
+ removal_failed = True
+ if archives.get("skipped_reason") == _ARCHIVE_INSPECTION_FAILED:
+ raise OSError("downloads directory cannot be inspected")
+
+ provenance_failed = False
+ retained_provenance = {
+ pair for pair in pending_provenance if pair[0] not in terminal_archive_names
+ }
+ if not dry_run and retained_provenance != pending_provenance:
+ try:
+ self._write_archive_provenance(retained_provenance)
+ except OSError:
+ logger.warning(
+ "Failed to retire managed %s runtime archive provenance",
+ self.spec.runtime_id,
+ exc_info=True,
+ )
+ provenance_failed = True
+
+ return {
+ "ok": not removal_failed and not provenance_failed,
+ "removed": removed,
+ "reason": (
+ self._reason("clean_inspection_failed")
+ if provenance_failed
+ else self._reason("clean_removal_failed")
+ if removal_failed
+ else None
+ ),
+ "archives": archives,
+ }
+
+ def _downloads_namespace_present(self) -> bool:
+ downloads_dir = self.runtime_dir / "downloads"
+ try:
+ downloads_info = downloads_dir.lstat()
+ except FileNotFoundError:
+ return False
+ except OSError as exc:
+ raise OSError(f"downloads directory cannot be inspected: {downloads_dir}") from exc
+ if _is_reparse_point(downloads_info) or not stat.S_ISDIR(downloads_info.st_mode):
+ raise OSError(f"downloads directory is not a confined directory: {downloads_dir}")
+ return True
+
+ def _read_managed_install_records(self, install_dirs: set[Path]) -> list[_ManagedRuntimeInstall]:
+ records: list[_ManagedRuntimeInstall] = []
+ for install_dir in install_dirs:
+ metadata_path = install_dir / self.spec.metadata_filename
+ try:
+ install_info = install_dir.lstat()
+ metadata_info = metadata_path.lstat()
+ if _is_reparse_point(install_info) or not stat.S_ISDIR(install_info.st_mode):
+ raise OSError("install directory is not a directory")
+ if not _is_exclusive_regular_file(metadata_info):
+ raise OSError("install metadata is not an exclusive regular file")
+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
+ manifest_sha256 = metadata.get("manifest_sha256") if isinstance(metadata, dict) else None
+ archive_name = metadata.get("archive_name") if isinstance(metadata, dict) else None
+ archive_sha256 = metadata.get("archive_sha256") if isinstance(metadata, dict) else None
+ manifest_source = metadata.get("manifest_source") if isinstance(metadata, dict) else None
+ if (
+ metadata.get("provider") != "manifest"
+ or metadata.get("runtime_id") != self.spec.runtime_id
+ or not isinstance(manifest_sha256, str)
+ or not _SHA256_RE.fullmatch(manifest_sha256)
+ or not isinstance(archive_name, str)
+ or not self._archive_name_is_owned(archive_name)
+ or not isinstance(archive_sha256, str)
+ or not _SHA256_RE.fullmatch(archive_sha256)
+ or not isinstance(manifest_source, str)
+ or not manifest_source
+ ):
+ raise ValueError("install metadata is incomplete")
+ lineage = (
+ _PACKAGED_MANIFEST_LINEAGE
+ if manifest_source.startswith("package:")
+ else _CUSTOM_MANIFEST_LINEAGE
+ )
+ records.append(
+ _ManagedRuntimeInstall(
+ path=install_dir,
+ lineage=lineage,
+ archive_name=archive_name,
+ archive_sha256=archive_sha256,
+ mtime=install_info.st_mtime,
+ )
+ )
+ except Exception as exc: # noqa: BLE001
+ raise OSError(f"install metadata is unreadable: {metadata_path}") from exc
+ return records
+
+ def _read_archive_provenance(self) -> set[tuple[str, str]]:
+ try:
+ provenance_info = self._archive_provenance_path.lstat()
+ except FileNotFoundError:
+ return set()
+ except OSError as exc:
+ raise OSError("archive provenance cannot be inspected") from exc
+ if not _is_exclusive_regular_file(provenance_info):
+ raise OSError("archive provenance is not an exclusive regular file")
+ try:
+ payload = json.loads(self._archive_provenance_path.read_text(encoding="utf-8"))
+ entries = payload.get("archives") if isinstance(payload, dict) else None
+ if (
+ payload.get("schema_version") != _ARCHIVE_PROVENANCE_SCHEMA_VERSION
+ or payload.get("runtime_id") != self.spec.runtime_id
+ or not isinstance(entries, list)
+ ):
+ raise ValueError("archive provenance document is invalid")
+ provenance: set[tuple[str, str]] = set()
+ for entry in entries:
+ name = entry.get("name") if isinstance(entry, dict) else None
+ digest = entry.get("sha256") if isinstance(entry, dict) else None
+ if (
+ not isinstance(name, str)
+ or not self._archive_name_is_owned(name)
+ or not isinstance(digest, str)
+ or not _SHA256_RE.fullmatch(digest)
+ ):
+ raise ValueError("archive provenance entry is invalid")
+ provenance.add((name, digest))
+ return provenance
+ except Exception as exc: # noqa: BLE001
+ raise OSError("archive provenance is unreadable") from exc
+
+ def _write_archive_provenance(self, provenance: set[tuple[str, str]]) -> None:
+ write_json_atomic(
+ self._archive_provenance_path,
+ {
+ "schema_version": _ARCHIVE_PROVENANCE_SCHEMA_VERSION,
+ "runtime_id": self.spec.runtime_id,
+ "archives": [
+ {"name": name, "sha256": digest}
+ for name, digest in sorted(provenance)
+ ],
+ },
+ )
+
+ def _staging_install_dirs(self) -> list[Path]:
+ try:
+ runtime_info = self.runtime_dir.lstat()
+ except FileNotFoundError:
+ return []
+ except OSError as exc:
+ raise OSError(f"runtime directory cannot be inspected: {self.runtime_dir}") from exc
+ if _is_reparse_point(runtime_info) or not stat.S_ISDIR(runtime_info.st_mode):
+ raise OSError(f"runtime directory is not a confined directory: {self.runtime_dir}")
+ staging: list[Path] = []
+ try:
+ with os.scandir(self.runtime_dir) as entries:
+ for entry in entries:
+ if entry.name.startswith("install-") and entry.is_dir(follow_symlinks=False):
+ staging.append(self.runtime_dir / entry.name)
+ except OSError as exc:
+ raise OSError(f"runtime directory cannot be inspected: {self.runtime_dir}") from exc
+ return sorted(staging)
+
+ @staticmethod
+ def _path_exists(path: Path) -> bool:
+ try:
+ path.lstat()
+ except FileNotFoundError:
+ return False
+ return True
+
+ def _remove_tree(self, path: Path) -> bool:
+ try:
+ shutil.rmtree(path)
+ if self._path_exists(path):
+ raise OSError("path still exists after removal")
+ except OSError:
+ logger.warning("Failed to remove managed runtime directory %s", path, exc_info=True)
+ return False
+ return True
+
+ def _current_archive_sha256(self) -> str:
+ pointer_path = self.runtime_dir / "current.json"
+ try:
+ pointer = json.loads(pointer_path.read_text(encoding="utf-8"))
+ digest = pointer.get("archive_sha256") if isinstance(pointer, dict) else None
+ if not isinstance(digest, str) or not _SHA256_RE.fullmatch(digest):
+ raise ValueError("current pointer archive digest is invalid")
+ return digest
+ except Exception as exc: # noqa: BLE001
+ raise OSError("current.json is unreadable") from exc
+
+ @staticmethod
+ def _archive_name_is_owned(name: str) -> bool:
+ return bool(name) and Path(name).name == name
+
+ @classmethod
+ def _archive_name_is_candidate(cls, name: str) -> bool:
+ return (
+ cls._archive_name_is_owned(name)
+ and name.isprintable()
+ and not name.endswith(".tmp")
+ and not _MANIFEST_CACHE_RE.fullmatch(name)
+ )
+
+ @staticmethod
+ def _skipped_archive_report(reason: str) -> dict[str, Any]:
+ return {
+ "outcome": "skipped",
+ "removed_count": 0,
+ "removed_bytes": 0,
+ "candidate_count": 0,
+ "candidate_bytes": 0,
+ "failed_count": 0,
+ "skipped_reason": reason,
+ }
+
+ @staticmethod
+ def _archive_report(
+ *,
+ dry_run: bool,
+ candidate_count: int,
+ candidate_bytes: int,
+ removed_count: int,
+ removed_bytes: int,
+ failed_count: int,
+ ) -> dict[str, Any]:
+ report: dict[str, Any] = {
+ "outcome": "partial" if dry_run and candidate_count else "cleaned",
+ "removed_count": removed_count,
+ "removed_bytes": removed_bytes,
+ "candidate_count": candidate_count,
+ "candidate_bytes": candidate_bytes,
+ "failed_count": failed_count,
+ "skipped_reason": None,
+ }
+ if failed_count:
+ report["outcome"] = "partial" if removed_count else "skipped"
+ report["skipped_reason"] = _ARCHIVE_REMOVAL_FAILED
+ return report
+
+ @staticmethod
+ def _sha256_from_fd(fd: int) -> str:
+ digest = hashlib.sha256()
+ with os.fdopen(os.dup(fd), "rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+ def _clean_downloaded_archives(
+ self,
+ *,
+ archive_provenance: set[tuple[str, str]],
+ protected_sha256s: set[str],
+ dry_run: bool,
+ ) -> tuple[dict[str, Any], set[str]]:
+ provenance_by_name: dict[str, set[str]] = {}
+ for name, digest in archive_provenance:
+ provenance_by_name.setdefault(name, set()).add(digest)
+ known_archive_names = set(provenance_by_name)
+ downloads_dir = self.runtime_dir / "downloads"
+ try:
+ downloads_info = downloads_dir.lstat()
+ except FileNotFoundError:
+ return (
+ self._archive_report(
+ dry_run=dry_run,
+ candidate_count=0,
+ candidate_bytes=0,
+ removed_count=0,
+ removed_bytes=0,
+ failed_count=0,
+ ),
+ known_archive_names,
+ )
+ except OSError as exc:
+ raise OSError("downloads directory cannot be inspected") from exc
+ if _is_reparse_point(downloads_info) or not stat.S_ISDIR(downloads_info.st_mode):
+ raise OSError("downloads directory is a symlink or not a directory")
+
+ mtime_floor = time.time() - _ARCHIVE_MTIME_GUARD_SECONDS
+ candidates: list[tuple[Path, int, str, int]] = []
+ terminal_names: set[str] = set()
+ if os.name == "nt":
+ identity = (downloads_info.st_dev, downloads_info.st_ino)
+ try:
+ with os.scandir(downloads_dir) as entries:
+ names = sorted(entry.name for entry in entries)
+ except OSError as exc:
+ raise OSError("downloads directory cannot be inspected") from exc
+ terminal_names.update(known_archive_names - set(names))
+ for name in names:
+ if name not in known_archive_names or not self._archive_name_is_candidate(name):
+ continue
+ path = downloads_dir / name
+ try:
+ entry_info = path.lstat()
+ except FileNotFoundError:
+ terminal_names.add(name)
+ continue
+ except OSError as exc:
+ raise OSError(f"archive cannot be inspected: {name}") from exc
+ if not _is_exclusive_regular_file(entry_info) or entry_info.st_mtime > mtime_floor:
+ continue
+ flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0)
+ try:
+ fd = os.open(path, flags)
+ try:
+ opened = os.fstat(fd)
+ if (opened.st_dev, opened.st_ino) != (entry_info.st_dev, entry_info.st_ino):
+ raise OSError("archive was replaced during inspection")
+ archive_sha256 = self._sha256_from_fd(fd)
+ finally:
+ os.close(fd)
+ except OSError as exc:
+ raise OSError(f"archive cannot be inspected: {name}") from exc
+ if (
+ archive_sha256 in provenance_by_name[name]
+ and archive_sha256 not in protected_sha256s
+ ):
+ candidates.append((path, entry_info.st_size, name, entry_info.st_ino))
+
+ removed_count = 0
+ removed_bytes = 0
+ failed_count = 0
+ if not dry_run:
+ for path, size, name, inode in candidates:
+ try:
+ current_dir = downloads_dir.lstat()
+ if (
+ _is_reparse_point(current_dir)
+ or not stat.S_ISDIR(current_dir.st_mode)
+ or (current_dir.st_dev, current_dir.st_ino) != identity
+ ):
+ raise OSError("downloads directory was replaced")
+ current = path.lstat()
+ if current.st_ino != inode or not _is_exclusive_regular_file(current):
+ raise OSError("archive was replaced after inspection")
+ path.unlink()
+ except FileNotFoundError:
+ terminal_names.add(name)
+ continue
+ except OSError:
+ logger.warning("Failed to remove managed runtime archive %s", path, exc_info=True)
+ failed_count += 1
+ continue
+ removed_count += 1
+ removed_bytes += size
+ terminal_names.add(name)
+ return (
+ self._archive_report(
+ dry_run=dry_run,
+ candidate_count=len(candidates),
+ candidate_bytes=sum(item[1] for item in candidates),
+ removed_count=removed_count,
+ removed_bytes=removed_bytes,
+ failed_count=failed_count,
+ ),
+ terminal_names,
+ )
+
+ flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_DIRECTORY", 0)
+ dir_fd = os.open(downloads_dir, flags)
+ try:
+ opened_dir = os.fstat(dir_fd)
+ if (opened_dir.st_dev, opened_dir.st_ino) != (downloads_info.st_dev, downloads_info.st_ino):
+ raise OSError("downloads directory was replaced before scan")
+ with os.scandir(dir_fd) as entries:
+ names = sorted(entry.name for entry in entries)
+ terminal_names.update(known_archive_names - set(names))
+ for name in names:
+ if name not in known_archive_names or not self._archive_name_is_candidate(name):
+ continue
+ try:
+ entry_info = os.stat(name, dir_fd=dir_fd, follow_symlinks=False)
+ except FileNotFoundError:
+ terminal_names.add(name)
+ continue
+ except OSError as exc:
+ raise OSError(f"archive cannot be inspected: {name}") from exc
+ if not _is_exclusive_regular_file(entry_info) or entry_info.st_mtime > mtime_floor:
+ continue
+ file_flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
+ try:
+ file_fd = os.open(name, file_flags, dir_fd=dir_fd)
+ except FileNotFoundError:
+ terminal_names.add(name)
+ continue
+ try:
+ opened_file = os.fstat(file_fd)
+ if (opened_file.st_dev, opened_file.st_ino) != (
+ entry_info.st_dev,
+ entry_info.st_ino,
+ ):
+ raise OSError("archive was replaced during inspection")
+ archive_sha256 = self._sha256_from_fd(file_fd)
+ finally:
+ os.close(file_fd)
+ if (
+ archive_sha256 in provenance_by_name[name]
+ and archive_sha256 not in protected_sha256s
+ ):
+ candidates.append((downloads_dir / name, entry_info.st_size, name, entry_info.st_ino))
+
+ removed_count = 0
+ removed_bytes = 0
+ failed_count = 0
+ if not dry_run:
+ for path, size, name, inode in candidates:
+ try:
+ current = os.stat(name, dir_fd=dir_fd, follow_symlinks=False)
+ if current.st_ino != inode or not _is_exclusive_regular_file(current):
+ raise OSError("archive was replaced after inspection")
+ os.unlink(name, dir_fd=dir_fd)
+ except FileNotFoundError:
+ terminal_names.add(name)
+ continue
+ except OSError:
+ logger.warning("Failed to remove managed runtime archive %s", path, exc_info=True)
+ failed_count += 1
+ continue
+ removed_count += 1
+ removed_bytes += size
+ terminal_names.add(name)
+ return (
+ self._archive_report(
+ dry_run=dry_run,
+ candidate_count=len(candidates),
+ candidate_bytes=sum(item[1] for item in candidates),
+ removed_count=removed_count,
+ removed_bytes=removed_bytes,
+ failed_count=failed_count,
+ ),
+ terminal_names,
+ )
+ finally:
+ os.close(dir_fd)
def _manifest_installable(self, manifest: ManagedRuntimeManifest) -> bool:
return True
@@ -926,7 +1459,7 @@ class ManagedRuntimeManager:
bin_path = str(item.get("bin_path") or self.spec.default_bin_path)
raw_size = item.get(self.spec.archive_size_field)
size = int(raw_size) if raw_size is not None else None
- if Path(name).name != name or not name:
+ if not self._archive_name_is_owned(name):
raise ValueError("unsafe archive name")
if not _SHA256_RE.fullmatch(sha256):
raise ValueError("invalid archive sha256")
diff --git a/tests/test_managed_runtime.py b/tests/test_managed_runtime.py
index 0b373f959..0e37b47b9 100644
--- a/tests/test_managed_runtime.py
+++ b/tests/test_managed_runtime.py
@@ -8,6 +8,7 @@ import os
import shutil
import stat
import tarfile
+import time
from pathlib import Path
from types import SimpleNamespace
@@ -178,6 +179,113 @@ def _resolve_subclass_runtime(manager: ManagedRuntimeManager, runtime_kind: str)
return manager.resolve_engine_path() # type: ignore[attr-defined]
+def _fixture_runtime_manager(
+ runtime_dir: Path,
+ *,
+ manifest_path: Path | None = None,
+ manifest_url: str | None = None,
+ offline: bool = False,
+) -> FixtureRuntimeManager:
+ return FixtureRuntimeManager(
+ spec=ManagedRuntimeSpec(
+ runtime_id="fixture",
+ manifest_resource="unused.json",
+ version_field="runtime_version",
+ default_bin_path="bin/runtime",
+ ),
+ runtime_dir=runtime_dir,
+ manifest_path=manifest_path,
+ manifest_url=manifest_url,
+ offline=offline,
+ )
+
+
+def _write_fixture_runtime_release(
+ root: Path,
+ manifest_path: Path,
+ *,
+ label: str,
+ version: str,
+ archive_name: str | None = None,
+) -> Path:
+ source_dir = root / "release-sources"
+ source_dir.mkdir(parents=True, exist_ok=True)
+ archive_path = source_dir / (archive_name or f"fixture-{label}.tar.gz")
+ binary_payload = version.encode("utf-8")
+ with tarfile.open(archive_path, "w:gz") as archive_file:
+ member = tarfile.TarInfo("bin/runtime")
+ member.mode = 0o755
+ member.size = len(binary_payload)
+ archive_file.addfile(member, io.BytesIO(binary_payload))
+ manifest_path.write_text(
+ json.dumps(
+ {
+ "schema_version": 1,
+ "runtime_version": version,
+ "source": "fixture",
+ "archives": {
+ managed_runtime.runtime_platform_tag(): {
+ "name": archive_path.name,
+ "url": archive_path.as_uri(),
+ "sha256": hashlib.sha256(archive_path.read_bytes()).hexdigest(),
+ "binary_sha256": hashlib.sha256(binary_payload).hexdigest(),
+ "size": archive_path.stat().st_size,
+ "bin_path": "bin/runtime",
+ }
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+ return archive_path
+
+
+def _install_fixture_runtime_release(
+ manager: FixtureRuntimeManager,
+ root: Path,
+ manifest_path: Path,
+ *,
+ label: str,
+ version: str,
+ archive_name: str | None = None,
+) -> tuple[Path, Path]:
+ source_archive = _write_fixture_runtime_release(
+ root,
+ manifest_path,
+ label=label,
+ version=version,
+ archive_name=archive_name,
+ )
+ installed = manager.ensure()
+ assert installed["ok"] is True
+ return Path(installed["install_dir"]), manager.runtime_dir / "downloads" / source_archive.name
+
+
+def _age_path(path: Path) -> None:
+ stamp = time.time() - 3600
+ os.utime(path, (stamp, stamp))
+
+
+def _archive_provenance(manager: ManagedRuntimeManager) -> set[tuple[str, str]]:
+ payload = json.loads(manager._archive_provenance_path.read_text(encoding="utf-8"))
+ return {(entry["name"], entry["sha256"]) for entry in payload["archives"]}
+
+
+def _archive_unlink_failure(archive_path: Path, real_unlink):
+ def _refuse(path, *args, **kwargs):
+ requested = Path(path)
+ matches = (
+ requested == Path(archive_path.name)
+ if kwargs.get("dir_fd") is not None
+ else requested == archive_path
+ )
+ if matches:
+ raise OSError("archive is in use")
+ return real_unlink(path, *args, **kwargs)
+
+ return _refuse
+
+
@pytest.mark.parametrize("runtime_kind", ["git", "memory", "model-hub"])
def test_subclass_relative_runtime_directory_persists_an_admissible_absolute_path(
tmp_path: Path,
@@ -908,6 +1016,652 @@ def test_clean_retains_current_plus_requested_previous_regardless_of_mtime_rank(
assert {path for path in previous if path.is_dir()} == expected_remaining
+def test_clean_retention_count_is_bounded_by_available_previous(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ manager, current, previous = _retention_fixture(
+ tmp_path,
+ monkeypatch,
+ "git",
+ current_is_newest=False,
+ )
+ shutil.rmtree(previous[1])
+ shutil.rmtree(previous[2])
+
+ result = manager.clean(keep_previous=2)
+
+ assert result["ok"] is True
+ assert result["reason"] is None
+ assert result["removed"] == []
+ assert current.is_dir()
+ assert previous[0].is_dir()
+
+
+def test_clean_reclaims_name_addressed_archives_without_cross_lineage_loss(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ runtime_dir = tmp_path / "runtime"
+ packaged_manifest = tmp_path / "packaged-manifest.json"
+ custom_manifest = tmp_path / "custom-manifest.json"
+ monkeypatch.setattr(managed_runtime.package_resources, "files", lambda _package: tmp_path)
+ packaged_manager = FixtureRuntimeManager(
+ spec=ManagedRuntimeSpec(
+ runtime_id="fixture",
+ manifest_resource=packaged_manifest.name,
+ version_field="runtime_version",
+ default_bin_path="bin/runtime",
+ ),
+ runtime_dir=runtime_dir,
+ )
+ old_packaged, old_packaged_archive = _install_fixture_runtime_release(
+ packaged_manager,
+ tmp_path,
+ packaged_manifest,
+ label="packaged-old",
+ version="packaged-old",
+ )
+ head_packaged, head_packaged_archive = _install_fixture_runtime_release(
+ packaged_manager,
+ tmp_path,
+ packaged_manifest,
+ label="packaged-head",
+ version="packaged-head",
+ )
+ custom_manager = _fixture_runtime_manager(runtime_dir, manifest_path=custom_manifest)
+ current_custom, current_custom_archive = _install_fixture_runtime_release(
+ custom_manager,
+ tmp_path,
+ custom_manifest,
+ label="custom-current",
+ version="custom-current",
+ )
+ for path, mtime in (
+ (old_packaged, 100),
+ (head_packaged, 200),
+ (current_custom, 300),
+ ):
+ os.utime(path, (mtime, mtime))
+ for archive_path in (
+ old_packaged_archive,
+ head_packaged_archive,
+ current_custom_archive,
+ ):
+ _age_path(archive_path)
+
+ preview = custom_manager.clean(keep_previous=0, dry_run=True)
+
+ assert preview["ok"] is True
+ assert preview["reason"] is None
+ assert preview["removed"] == [str(old_packaged)]
+ assert preview["archives"] == {
+ "outcome": "partial",
+ "removed_count": 0,
+ "removed_bytes": 0,
+ "candidate_count": 1,
+ "candidate_bytes": old_packaged_archive.stat().st_size,
+ "failed_count": 0,
+ "skipped_reason": None,
+ }
+
+ result = custom_manager.clean(keep_previous=0)
+
+ assert result["ok"] is True
+ assert result["reason"] is None
+ assert result["removed"] == [str(old_packaged)]
+ assert not old_packaged.exists()
+ assert not old_packaged_archive.exists()
+ assert head_packaged.is_dir() and head_packaged_archive.is_file()
+ assert current_custom.is_dir() and current_custom_archive.is_file()
+ assert result["archives"]["outcome"] == "cleaned"
+ assert result["archives"]["candidate_count"] == 1
+ assert result["archives"]["removed_count"] == 1
+ assert result["archives"]["removed_bytes"] == result["archives"]["candidate_bytes"]
+
+
+def test_clean_preserves_remote_manifest_cache_for_offline_resolution(
+ tmp_path: Path,
+) -> None:
+ runtime_dir = tmp_path / "runtime"
+ manifest_path = tmp_path / "remote-manifest.json"
+ source_archive = _write_fixture_runtime_release(
+ tmp_path,
+ manifest_path,
+ label="current",
+ version="current",
+ )
+ manifest_url = manifest_path.as_uri()
+ online = _fixture_runtime_manager(runtime_dir, manifest_url=manifest_url)
+ installed = online.ensure()
+ assert installed["ok"] is True
+ cached_archive = runtime_dir / "downloads" / source_archive.name
+ manifest_caches = list((runtime_dir / "downloads").glob("manifest-*.json"))
+ assert len(manifest_caches) == 1
+ _age_path(cached_archive)
+ _age_path(manifest_caches[0])
+
+ result = online.clean(keep_previous=0)
+
+ assert result["ok"] is True
+ assert cached_archive.is_file()
+ assert manifest_caches[0].is_file()
+ manifest_path.unlink()
+ source_archive.unlink()
+ offline = _fixture_runtime_manager(runtime_dir, manifest_url=manifest_url, offline=True)
+ reused = offline.ensure()
+ assert reused["ok"] is True
+ assert reused["changed"] is False
+ assert Path(reused["install_dir"]) == Path(installed["install_dir"])
+
+
+def test_clean_archive_candidates_require_known_shape_maturity_and_unprotected_digest(
+ tmp_path: Path,
+) -> None:
+ runtime_dir = tmp_path / "runtime"
+ manifest_path = tmp_path / "manifest.json"
+ manager = _fixture_runtime_manager(runtime_dir, manifest_path=manifest_path)
+ installed: dict[str, tuple[Path, Path]] = {}
+ releases = (
+ ("symlink", "symlink", None),
+ ("directory", "directory", None),
+ ("stale", "stale", None),
+ ("recent", "recent", None),
+ ("tmp", "tmp", "fixture-known.tmp"),
+ ("newline", "newline", "fixture-known.tgz\n"),
+ ("current", "current", None),
+ )
+ for index, (label, version, archive_name) in enumerate(releases, start=1):
+ installed[label] = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label=label,
+ version=version,
+ archive_name=archive_name,
+ )
+ install_dir, _cache_path = installed[label]
+ os.utime(install_dir, (index * 100, index * 100))
+
+ outside = tmp_path / "outside-archive"
+ outside.write_bytes(b"outside")
+ symlink_cache = installed["symlink"][1]
+ symlink_cache.unlink()
+ symlink_cache.symlink_to(outside)
+ directory_cache = installed["directory"][1]
+ directory_cache.unlink()
+ directory_cache.mkdir()
+ stale_cache = installed["stale"][1]
+ _age_path(stale_cache)
+ tmp_cache = installed["tmp"][1]
+ _age_path(tmp_cache)
+ newline_cache = installed["newline"][1]
+ _age_path(newline_cache)
+ current_cache = installed["current"][1]
+ _age_path(current_cache)
+ unknown_cache = runtime_dir / "downloads" / "unknown-archive.tar.gz"
+ unknown_cache.write_bytes(b"unknown")
+ _age_path(unknown_cache)
+
+ result = manager.clean(keep_previous=0)
+
+ assert result["ok"] is True
+ assert result["archives"]["candidate_count"] == 1
+ assert result["archives"]["removed_count"] == 1
+ assert not stale_cache.exists()
+ assert installed["recent"][1].is_file()
+ assert symlink_cache.is_symlink() and outside.read_bytes() == b"outside"
+ assert directory_cache.is_dir()
+ assert tmp_cache.is_file()
+ assert newline_cache.is_file()
+ assert unknown_cache.is_file()
+ assert current_cache.is_file()
+
+
+def test_clean_retries_recent_archive_from_durable_provenance(
+ tmp_path: Path,
+) -> None:
+ runtime_dir = tmp_path / "runtime"
+ manifest_path = tmp_path / "manifest.json"
+ manager = _fixture_runtime_manager(runtime_dir, manifest_path=manifest_path)
+ stale, stale_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="stale",
+ version="stale",
+ )
+ current, _current_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="current",
+ version="current",
+ )
+ os.utime(stale, (100, 100))
+ os.utime(current, (200, 200))
+ stale_digest = hashlib.sha256(stale_archive.read_bytes()).hexdigest()
+
+ first = manager.clean(keep_previous=0)
+
+ assert first["ok"] is True
+ assert not stale.exists() and stale_archive.is_file()
+ assert _archive_provenance(manager) == {(stale_archive.name, stale_digest)}
+
+ _age_path(stale_archive)
+ second = manager.clean(keep_previous=0)
+
+ assert second["ok"] is True
+ assert second["archives"]["candidate_count"] == 1
+ assert second["archives"]["removed_count"] == 1
+ assert not stale_archive.exists()
+ assert _archive_provenance(manager) == set()
+
+
+def test_clean_retries_parser_valid_long_archive_basename_from_provenance(
+ tmp_path: Path,
+) -> None:
+ runtime_dir = tmp_path / "runtime"
+ manifest_path = tmp_path / "manifest.json"
+ manager = _fixture_runtime_manager(runtime_dir, manifest_path=manifest_path)
+ archive_name = f"{'a' * 129} runtime-版本@%.tar.gz"
+ assert len(archive_name.encode("utf-8")) > 128
+ stale, stale_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="stale",
+ version="stale",
+ archive_name=archive_name,
+ )
+ current, _current_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="current",
+ version="current",
+ )
+ os.utime(stale, (100, 100))
+ os.utime(current, (200, 200))
+ stale_digest = hashlib.sha256(stale_archive.read_bytes()).hexdigest()
+
+ first = manager.clean(keep_previous=0)
+
+ assert first["ok"] is True
+ assert not stale.exists() and stale_archive.is_file()
+ assert _archive_provenance(manager) == {(archive_name, stale_digest)}
+
+ _age_path(stale_archive)
+ second = manager.clean(keep_previous=0)
+
+ assert second["ok"] is True
+ assert second["archives"]["candidate_count"] == 1
+ assert second["archives"]["removed_count"] == 1
+ assert not stale_archive.exists()
+ assert _archive_provenance(manager) == set()
+
+
+def test_clean_retries_archive_after_transient_unlink_failure(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ runtime_dir = tmp_path / "runtime"
+ manifest_path = tmp_path / "manifest.json"
+ manager = _fixture_runtime_manager(runtime_dir, manifest_path=manifest_path)
+ stale, stale_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="stale",
+ version="stale",
+ )
+ current, _current_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="current",
+ version="current",
+ )
+ os.utime(stale, (100, 100))
+ os.utime(current, (200, 200))
+ _age_path(stale_archive)
+ stale_digest = hashlib.sha256(stale_archive.read_bytes()).hexdigest()
+ real_unlink = os.unlink
+
+ monkeypatch.setattr(os, "unlink", _archive_unlink_failure(stale_archive, real_unlink))
+ first = manager.clean(keep_previous=0)
+
+ assert first["ok"] is False
+ assert not stale.exists() and stale_archive.is_file()
+ assert _archive_provenance(manager) == {(stale_archive.name, stale_digest)}
+
+ monkeypatch.setattr(os, "unlink", real_unlink)
+ second = manager.clean(keep_previous=0)
+
+ assert second["ok"] is True
+ assert second["archives"]["candidate_count"] == 1
+ assert second["archives"]["removed_count"] == 1
+ assert not stale_archive.exists()
+ assert _archive_provenance(manager) == set()
+
+
+def test_clean_fails_closed_when_archive_provenance_cannot_be_persisted(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ runtime_dir = tmp_path / "runtime"
+ manifest_path = tmp_path / "manifest.json"
+ manager = _fixture_runtime_manager(runtime_dir, manifest_path=manifest_path)
+ stale, stale_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="stale",
+ version="stale",
+ )
+ current, current_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="current",
+ version="current",
+ )
+ os.utime(stale, (100, 100))
+ os.utime(current, (200, 200))
+ staging_dir = runtime_dir / "install-pending"
+ staging_dir.mkdir()
+ monkeypatch.setattr(
+ manager,
+ "_write_archive_provenance",
+ lambda _provenance: (_ for _ in ()).throw(OSError("disk is read-only")),
+ )
+
+ result = manager.clean(keep_previous=0)
+
+ assert result["ok"] is False
+ assert result["reason"] == "fixture_clean_inspection_failed"
+ assert result["removed"] == [str(staging_dir)]
+ assert result["archives"]["skipped_reason"] == "archive_inspection_failed"
+ assert not staging_dir.exists()
+ assert stale.is_dir() and stale_archive.is_file()
+ assert current.is_dir() and current_archive.is_file()
+ assert not manager._archive_provenance_path.exists()
+
+
+def test_clean_reclaims_staging_but_rejects_unsafe_archive_provenance(
+ tmp_path: Path,
+) -> None:
+ runtime_dir = tmp_path / "runtime"
+ manifest_path = tmp_path / "manifest.json"
+ manager = _fixture_runtime_manager(runtime_dir, manifest_path=manifest_path)
+ stale, stale_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="stale",
+ version="stale",
+ )
+ current, current_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="current",
+ version="current",
+ )
+ os.utime(stale, (100, 100))
+ os.utime(current, (200, 200))
+ staging_dir = runtime_dir / "install-pending"
+ staging_dir.mkdir()
+ manager._archive_provenance_path.write_text(
+ json.dumps(
+ {
+ "schema_version": 1,
+ "runtime_id": "fixture",
+ "archives": [{"name": "../outside.tgz", "sha256": "a" * 64}],
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ result = manager.clean(keep_previous=0)
+
+ assert result["ok"] is False
+ assert result["reason"] == "fixture_clean_inspection_failed"
+ assert result["removed"] == [str(staging_dir)]
+ assert result["archives"]["skipped_reason"] == "archive_inspection_failed"
+ assert not staging_dir.exists()
+ assert stale.is_dir() and stale_archive.is_file()
+ assert current.is_dir() and current_archive.is_file()
+
+
+def test_clean_dry_run_does_not_persist_archive_provenance(
+ tmp_path: Path,
+) -> None:
+ runtime_dir = tmp_path / "runtime"
+ manifest_path = tmp_path / "manifest.json"
+ manager = _fixture_runtime_manager(runtime_dir, manifest_path=manifest_path)
+ stale, stale_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="stale",
+ version="stale",
+ )
+ current, _current_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="current",
+ version="current",
+ )
+ os.utime(stale, (100, 100))
+ os.utime(current, (200, 200))
+ _age_path(stale_archive)
+
+ preview = manager.clean(keep_previous=0, dry_run=True)
+
+ assert preview["ok"] is True
+ assert preview["removed"] == [str(stale)]
+ assert preview["archives"]["candidate_count"] == 1
+ assert stale.is_dir() and stale_archive.is_file()
+ assert not manager._archive_provenance_path.exists()
+
+
+def test_clean_keeps_recorded_archive_when_bytes_do_not_match_provenance(
+ tmp_path: Path,
+) -> None:
+ runtime_dir = tmp_path / "runtime"
+ manifest_path = tmp_path / "manifest.json"
+ manager = _fixture_runtime_manager(runtime_dir, manifest_path=manifest_path)
+ stale, stale_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="stale",
+ version="stale",
+ )
+ current, _current_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="current",
+ version="current",
+ )
+ os.utime(stale, (100, 100))
+ os.utime(current, (200, 200))
+ stale_digest = hashlib.sha256(stale_archive.read_bytes()).hexdigest()
+ first = manager.clean(keep_previous=0)
+ assert first["ok"] is True
+ assert not stale.exists()
+ assert _archive_provenance(manager) == {(stale_archive.name, stale_digest)}
+
+ stale_archive.write_bytes(b"replacement bytes")
+ _age_path(stale_archive)
+ second = manager.clean(keep_previous=0)
+
+ assert second["ok"] is True
+ assert second["archives"]["candidate_count"] == 0
+ assert stale_archive.read_bytes() == b"replacement bytes"
+ assert _archive_provenance(manager) == {(stale_archive.name, stale_digest)}
+
+
+def test_clean_fails_closed_for_unreadable_retained_archive_metadata(
+ tmp_path: Path,
+) -> None:
+ runtime_dir = tmp_path / "runtime"
+ manifest_path = tmp_path / "manifest.json"
+ manager = _fixture_runtime_manager(runtime_dir, manifest_path=manifest_path)
+ rollback, rollback_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="rollback",
+ version="rollback",
+ )
+ current, current_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="current",
+ version="current",
+ )
+ rollback_metadata = rollback / manager.spec.metadata_filename
+ rollback_metadata.write_text("{", encoding="utf-8")
+ for archive_path in (rollback_archive, current_archive):
+ _age_path(archive_path)
+
+ result = manager.clean(keep_previous=1)
+
+ assert result["ok"] is False
+ assert result["reason"] == "fixture_clean_inspection_failed"
+ assert result["removed"] == []
+ assert result["archives"]["skipped_reason"] == "archive_inspection_failed"
+ assert rollback.is_dir() and rollback_archive.is_file()
+ assert current.is_dir() and current_archive.is_file()
+
+
+def test_clean_reclaims_staging_before_unreadable_install_metadata_failure(
+ tmp_path: Path,
+) -> None:
+ runtime_dir = tmp_path / "runtime"
+ manifest_path = tmp_path / "manifest.json"
+ manager = _fixture_runtime_manager(runtime_dir, manifest_path=manifest_path)
+ rollback, rollback_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="rollback",
+ version="rollback",
+ )
+ current, current_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="current",
+ version="current",
+ )
+ (rollback / manager.spec.metadata_filename).write_text("{", encoding="utf-8")
+ staging_dir = runtime_dir / "install-pending"
+ staging_dir.mkdir()
+ for archive_path in (rollback_archive, current_archive):
+ _age_path(archive_path)
+
+ result = manager.clean(keep_previous=1)
+
+ assert result["ok"] is False
+ assert result["reason"] == "fixture_clean_inspection_failed"
+ assert result["removed"] == [str(staging_dir)]
+ assert result["archives"]["outcome"] == "skipped"
+ assert result["archives"]["skipped_reason"] == "archive_inspection_failed"
+ assert not staging_dir.exists()
+ assert rollback.is_dir() and rollback_archive.is_file()
+ assert current.is_dir() and current_archive.is_file()
+
+
+def test_clean_does_not_report_an_install_directory_that_removal_did_not_reclaim(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ runtime_dir = tmp_path / "runtime"
+ manifest_path = tmp_path / "manifest.json"
+ manager = _fixture_runtime_manager(runtime_dir, manifest_path=manifest_path)
+ stale, stale_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="stale",
+ version="stale",
+ )
+ current, _current_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="current",
+ version="current",
+ )
+ os.utime(stale, (100, 100))
+ os.utime(current, (200, 200))
+ _age_path(stale_archive)
+ real_rmtree = shutil.rmtree
+
+ def _refuse_one_target(path, *args, **kwargs):
+ if Path(path) == stale:
+ raise OSError("target is in use")
+ return real_rmtree(path, *args, **kwargs)
+
+ monkeypatch.setattr(shutil, "rmtree", _refuse_one_target)
+ result = manager.clean(keep_previous=0)
+
+ assert result["ok"] is False
+ assert result["reason"] == "fixture_clean_removal_failed"
+ assert str(stale) not in result["removed"]
+ assert stale.is_dir()
+ assert stale_archive.is_file()
+ assert result["archives"]["candidate_count"] == 0
+
+
+def test_clean_archive_removal_failure_uses_shared_failure_and_archive_vocabulary(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ runtime_dir = tmp_path / "runtime"
+ manifest_path = tmp_path / "manifest.json"
+ manager = _fixture_runtime_manager(runtime_dir, manifest_path=manifest_path)
+ stale, stale_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="stale",
+ version="stale",
+ )
+ current, _current_archive = _install_fixture_runtime_release(
+ manager,
+ tmp_path,
+ manifest_path,
+ label="current",
+ version="current",
+ )
+ os.utime(stale, (100, 100))
+ os.utime(current, (200, 200))
+ _age_path(stale_archive)
+ real_unlink = os.unlink
+
+ monkeypatch.setattr(os, "unlink", _archive_unlink_failure(stale_archive, real_unlink))
+ result = manager.clean(keep_previous=0)
+
+ assert result["ok"] is False
+ assert result["reason"] == "fixture_clean_removal_failed"
+ assert result["removed"] == [str(stale)]
+ assert not stale.exists()
+ assert stale_archive.is_file()
+ assert result["archives"]["outcome"] == "skipped"
+ assert result["archives"]["candidate_count"] == 1
+ assert result["archives"]["removed_count"] == 0
+ assert result["archives"]["removed_bytes"] == 0
+ assert result["archives"]["failed_count"] == 1
+ assert result["archives"]["skipped_reason"] == "archive_removal_failed"
+
+
@pytest.mark.parametrize(
"pointer_state",
["corrupt", "unreadable", "wrong-root", "absent"],