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): protect retention across pointer failures (#1681)

Call White5f01434b58c1
diff --git a/core/managed_runtime.py b/core/managed_runtime.py
index a7da7bd6f..b644f878d 100644
--- a/core/managed_runtime.py
+++ b/core/managed_runtime.py
@@ -197,7 +197,13 @@ class ManagedRuntimeManager:
)
install_dir = self._manifest_install_dir(manifest, archive)
- current_install_dir = self._current_install_dir(self.runtime_dir / "versions")
+ try:
+ current_install_dir = self._current_install_dir(self.runtime_dir / "versions")
+ except OSError:
+ # Ensure can repair a damaged pointer from the selected
+ # manifest's admitted disk record. Cleanup cannot make the
+ # same assumption because it has no replacement transaction.
+ current_install_dir = None
existing_install_dir = current_install_dir or install_dir
existing = self._verified_manifest_binary(existing_install_dir, manifest, archive)
if existing is None and existing_install_dir != install_dir:
@@ -751,31 +757,43 @@ class ManagedRuntimeManager:
) -> dict[str, Any]:
if removed is None:
removed = []
- 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))
-
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)
except FileNotFoundError:
- return {"ok": True, "removed": removed}
+ 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
+
+ install_dirs = (
+ {
+ metadata_path.parent
+ for metadata_path in self._rglob_install_metadata(versions_dir)
+ if metadata_path.parent.is_dir()
+ }
+ if versions_is_dir
+ else set()
+ )
+ 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))
+
if not versions_is_dir:
return {"ok": True, "removed": removed}
-
- install_dirs = {
- metadata_path.parent
- for metadata_path in self._rglob_install_metadata(versions_dir)
- if metadata_path.parent.is_dir()
- }
- current = self._current_install_dir(versions_dir)
- protected = {current} if current is not None else set()
candidates = sorted(
(path for path in install_dirs if path.resolve() not in protected),
key=lambda path: path.stat().st_mtime,
@@ -1132,14 +1150,32 @@ class ManagedRuntimeManager:
)
def _current_install_dir(self, versions_dir: Path) -> Path | None:
+ pointer_path = self.runtime_dir / "current.json"
try:
- pointer = json.loads((self.runtime_dir / "current.json").read_text(encoding="utf-8"))
- candidate = Path(str(pointer.get("install_dir") or "")).resolve()
- if versions_dir.resolve() in candidate.parents:
- return candidate
- except Exception: # noqa: BLE001
- return None
- return None
+ payload = pointer_path.read_text(encoding="utf-8")
+ except FileNotFoundError as exc:
+ try:
+ pointer_path.lstat()
+ except FileNotFoundError:
+ return None
+ except OSError as inspect_exc:
+ raise OSError("current.json is unreadable") from inspect_exc
+ raise OSError("current.json is unreadable") from exc
+ except (OSError, RecursionError, UnicodeError) as exc:
+ raise OSError("current.json is unreadable") from exc
+
+ try:
+ pointer = json.loads(payload)
+ install_dir = pointer.get("install_dir") if isinstance(pointer, dict) else None
+ if not isinstance(install_dir, str) or not install_dir or not Path(install_dir).is_absolute():
+ raise ValueError("current.json has no absolute install_dir")
+ candidate = Path(install_dir).resolve()
+ versions_root = versions_dir.resolve()
+ if candidate == versions_root or versions_root not in candidate.parents:
+ raise ValueError("current.json install_dir is outside versions")
+ return candidate
+ except (OSError, RecursionError, RuntimeError, UnicodeError, ValueError) as exc:
+ raise OSError("current.json is unreadable") from exc
def _prune_empty_version_dirs(self, versions_dir: Path) -> None:
for depth in (3, 2, 1):
diff --git a/tests/test_managed_runtime.py b/tests/test_managed_runtime.py
index 0c5e1ac29..0b373f959 100644
--- a/tests/test_managed_runtime.py
+++ b/tests/test_managed_runtime.py
@@ -854,6 +854,128 @@ def test_clean_dry_run_is_read_only_and_creates_no_lock(
assert not (runtime_dir / ".install.lock").exists()
+def _retention_fixture(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ runtime_kind: str,
+ *,
+ current_is_newest: bool,
+) -> tuple[ManagedRuntimeManager, Path, list[Path]]:
+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)
+ _archive, manifest_path = _write_subclass_runtime_fixture(tmp_path, runtime_kind)
+ manager = _subclass_runtime_manager(tmp_path, runtime_kind, manifest_path, monkeypatch)
+ installed = manager.ensure()
+ assert installed["ok"] is True
+ current = Path(installed["install_dir"])
+ previous = [current.with_name(f"previous-{index}") for index in range(3)]
+ for path in previous:
+ shutil.copytree(current, path)
+
+ current_mtime = 400 if current_is_newest else 100
+ previous_mtimes = (300, 200, 100) if current_is_newest else (400, 300, 200)
+ os.utime(current, (current_mtime, current_mtime))
+ for path, mtime in zip(previous, previous_mtimes):
+ os.utime(path, (mtime, mtime))
+ return manager, current, previous
+
+
[email protected]("keep_previous", [0, 1, 2])
[email protected]("current_is_newest", [True, False])
[email protected]("dry_run", [True, False])
[email protected]("runtime_kind", ["git", "memory", "model-hub"])
+def test_clean_retains_current_plus_requested_previous_regardless_of_mtime_rank(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ keep_previous: int,
+ current_is_newest: bool,
+ dry_run: bool,
+ runtime_kind: str,
+) -> None:
+ manager, current, previous = _retention_fixture(
+ tmp_path,
+ monkeypatch,
+ runtime_kind,
+ current_is_newest=current_is_newest,
+ )
+ expected_removed = set(previous[keep_previous:])
+
+ result = manager.clean(keep_previous=keep_previous, dry_run=dry_run)
+
+ assert result["ok"] is True
+ assert {Path(path) for path in result["removed"]} == expected_removed
+ assert current.is_dir()
+ expected_remaining = set(previous) if dry_run else set(previous[:keep_previous])
+ assert {path for path in previous if path.is_dir()} == expected_remaining
+
+
+ "pointer_state",
+ ["corrupt", "unreadable", "wrong-root", "absent"],
+)
[email protected]("keep_previous", [0, 1])
[email protected]("dry_run", [True, False])
[email protected]("runtime_kind", ["git", "memory", "model-hub"])
+def test_clean_pointer_failure_or_absence_plans_no_install_deletion(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ pointer_state: str,
+ keep_previous: int,
+ dry_run: bool,
+ runtime_kind: str,
+) -> None:
+ manager, current, previous = _retention_fixture(
+ tmp_path,
+ monkeypatch,
+ runtime_kind,
+ current_is_newest=False,
+ )
+ install_dirs = {current, *previous}
+ pointer_path = manager.runtime_dir / "current.json"
+ original_mode = stat.S_IMODE(pointer_path.stat().st_mode)
+ staging_dir: Path | None = None
+ if pointer_state == "corrupt":
+ pointer_path.write_text("{", encoding="utf-8")
+ staging_dir = manager.runtime_dir / "install-pending"
+ staging_dir.mkdir()
+ elif pointer_state == "unreadable":
+ pointer_path.chmod(0)
+ staging_dir = manager.runtime_dir / "install-pending"
+ staging_dir.mkdir()
+ elif pointer_state == "wrong-root":
+ pointer = json.loads(pointer_path.read_text(encoding="utf-8"))
+ damaged_child = current / "damaged-child"
+ damaged_child.mkdir()
+ pointer["install_dir"] = str(damaged_child)
+ pointer_path.write_text(json.dumps(pointer), encoding="utf-8")
+ staging_dir = manager.runtime_dir / "install-pending"
+ staging_dir.mkdir()
+ else:
+ pointer_path.unlink()
+ manifest = manager._load_manifest(allow_network=False)
+ assert manifest is not None
+ archive = manager._manifest_archive_for_platform(manifest)
+ assert archive is not None
+ assert all(
+ manager._verified_manifest_binary(path, manifest, archive) is not None
+ for path in install_dirs
+ )
+
+ try:
+ result = manager.clean(keep_previous=keep_previous, dry_run=dry_run)
+ finally:
+ if pointer_state == "unreadable":
+ pointer_path.chmod(original_mode)
+
+ assert result["removed"] == []
+ assert all(path.is_dir() for path in install_dirs)
+ if pointer_state == "absent":
+ assert result["ok"] is True
+ else:
+ assert staging_dir is not None and staging_dir.is_dir()
+ assert result["ok"] is False
+ assert result["reason"] == manager._reason("clean_inspection_failed")
+
+
def test_clean_dry_run_reports_inspection_failure(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,