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): converge managed mutation guard (#1669)

Call Whitee7d12ee2261e
diff --git a/core/managed_runtime.py b/core/managed_runtime.py
index 3b5e030fe..2e6b317e0 100644
--- a/core/managed_runtime.py
+++ b/core/managed_runtime.py
@@ -20,7 +20,7 @@ from collections.abc import Callable, Mapping
from dataclasses import dataclass
from pathlib import Path, PurePosixPath, PureWindowsPath
from sysconfig import get_platform
-from typing import Any, Iterator
+from typing import IO, Any, Iterator
from config.atomic_io import write_atomic
from core.dependency_network import (
@@ -74,6 +74,16 @@ _ENSURE_FAILURE_SUFFIXES = frozenset(
)
+def _is_exclusive_regular_file(info: os.stat_result) -> bool:
+ """True only for a one-link regular file that is not a reparse point."""
+
+ if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
+ return False
+ attrs = getattr(info, "st_file_attributes", 0)
+ reparse = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0)
+ return not (reparse and attrs & reparse)
+
+
@dataclass(frozen=True)
class ManagedRuntimeArchive:
platform: str
@@ -484,16 +494,25 @@ class ManagedRuntimeManager:
"ok": False,
"removed": [],
"reason": busy_reason,
- "message": "an install is currently running",
+ "message": (
+ "an install is currently running"
+ if busy_reason == self._reason("install_already_running")
+ else "the install guard could not be inspected"
+ ),
}
try:
result = self._clean_locked(keep_previous=keep_previous, dry_run=True, removed=[])
- if self._preview_raced_busy():
+ raced_reason = self._preview_raced_busy()
+ if raced_reason:
return {
"ok": False,
"removed": [],
- "reason": self._reason("install_already_running"),
- "message": "an install is currently running",
+ "reason": raced_reason,
+ "message": (
+ "an install is currently running"
+ if raced_reason == self._reason("install_already_running")
+ else "the install guard could not be inspected"
+ ),
}
return result
except Exception as exc: # noqa: BLE001
@@ -577,12 +596,8 @@ class ManagedRuntimeManager:
except OSError:
return False
return (
- stat.S_ISREG(open_stat.st_mode)
- and open_stat.st_nlink == 1
- and not stat.S_ISLNK(open_stat.st_mode)
- and stat.S_ISREG(path_stat.st_mode)
- and path_stat.st_nlink == 1
- and not stat.S_ISLNK(path_stat.st_mode)
+ _is_exclusive_regular_file(open_stat)
+ and _is_exclusive_regular_file(path_stat)
and (open_stat.st_dev, open_stat.st_ino) == (path_stat.st_dev, path_stat.st_ino)
)
@@ -597,20 +612,20 @@ class ManagedRuntimeManager:
flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NONBLOCK", 0)
fd = os.open(self._install_file_lock_path, flags)
except OSError:
- return self._reason("install_already_running")
+ return self._reason("clean_inspection_failed")
try:
if not try_windows_exclusive_lock(fd):
os.close(fd)
return self._reason("install_already_running")
if not self._guard_path_matches_fd(fd):
os.close(fd)
- return self._reason("install_already_running")
+ return self._reason("clean_inspection_failed")
self._preview_guard_fd = fd
self._preview_guard_msvcrt = True
return None
except OSError:
os.close(fd)
- return self._reason("install_already_running")
+ return self._reason("clean_inspection_failed")
def _preview_busy_reason(self) -> str | None:
"""Read-only busy check for previews: never creates or rewrites files.
@@ -640,33 +655,24 @@ class ManagedRuntimeManager:
flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0)
fd = os.open(self._install_file_lock_path, flags)
except OSError:
- # Existing but unopenable (ACLs/permissions): a preview cannot
- # know whether an install is active — report it as busy rather
- # than risking a misleading "0 entries" preview.
- return self._reason("install_already_running")
+ return self._reason("clean_inspection_failed")
try:
fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
if not self._guard_path_matches_fd(fd):
os.close(fd)
- return self._reason("install_already_running")
+ return self._reason("clean_inspection_failed")
self._preview_guard_fd = fd
return None
- except OSError:
+ except BlockingIOError:
os.close(fd)
return self._reason("install_already_running")
+ except OSError:
+ os.close(fd)
+ return self._reason("clean_inspection_failed")
except BaseException:
self._release_preview_guard()
raise
- def _preview_lock_missing(self) -> bool:
- try:
- self._install_file_lock_path.lstat()
- except FileNotFoundError:
- return True
- except OSError:
- return False
- return False
-
def _preview_lock_probe(self) -> str | None:
try:
info = self._install_file_lock_path.lstat()
@@ -675,19 +681,24 @@ class ManagedRuntimeManager:
return None
except OSError:
self._preview_lock_was_absent = False
- return self._reason("install_already_running")
+ return self._reason("clean_inspection_failed")
self._preview_lock_was_absent = False
- if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
- return self._reason("install_already_running")
+ if not _is_exclusive_regular_file(info):
+ return self._reason("clean_inspection_failed")
return None
- def _preview_raced_busy(self) -> bool:
- """True when an install started after a lock-absent preview probe."""
+ def _preview_raced_busy(self) -> str | None:
+ """Classify a guard that appeared after a lock-absent preview probe."""
if getattr(self, "_preview_guard_fd", None) is not None:
- return False
+ return None
if not getattr(self, "_preview_lock_was_absent", False):
- return False
- return not self._preview_lock_missing()
+ return None
+ reason = self._preview_lock_probe()
+ if reason is not None:
+ return reason
+ if getattr(self, "_preview_lock_was_absent", False):
+ return None
+ return self._reason("install_already_running")
def _rglob_install_metadata(self, versions_dir: Path) -> Iterator[Path]:
"""rglob metadata files with error-preserving traversal.
@@ -1227,7 +1238,12 @@ class ManagedRuntimeManager:
if not self._install_lock.acquire(blocking=False):
return None
try:
- file_lock = MigrationFileLock(self._install_file_lock_path, timeout_seconds=0)
+ file_lock = MigrationFileLock(
+ self._install_file_lock_path,
+ timeout_seconds=0,
+ _handle_opener=self._open_mutation_lock_handle,
+ _handle_validator=lambda handle: self._guard_path_matches_fd(handle.fileno()),
+ )
file_lock.acquire()
except MigrationLockTimeout:
self._install_lock.release()
@@ -1237,6 +1253,27 @@ class ManagedRuntimeManager:
raise
return file_lock
+ def _open_mutation_lock_handle(self, lock_path: Path) -> IO[str]:
+ try:
+ info = lock_path.lstat()
+ except FileNotFoundError:
+ pass
+ else:
+ if not _is_exclusive_regular_file(info):
+ raise OSError(f"Install guard is not an exclusive regular file: {lock_path}")
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
+ flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_BINARY", 0)
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ fd = os.open(lock_path, flags, 0o644)
+ try:
+ if not self._guard_path_matches_fd(fd):
+ raise OSError(f"Install guard path does not match its descriptor: {lock_path}")
+ return os.fdopen(fd, "r+", encoding="utf-8")
+ except BaseException:
+ os.close(fd)
+ raise
+
def _release_mutation_lock(self, file_lock: MigrationFileLock) -> None:
try:
file_lock.release()
diff --git a/storage/lock.py b/storage/lock.py
index 1baddd90a..ec309c573 100644
--- a/storage/lock.py
+++ b/storage/lock.py
@@ -6,7 +6,7 @@ import threading
import time
from pathlib import Path
from types import TracebackType
-from typing import Optional, Type
+from typing import Callable, IO, Optional, Type
logger = logging.getLogger(__name__)
@@ -101,11 +101,24 @@ class MigrationFileLock:
which is the right answer whenever the work behind the lock has no upper
bound: the OS drops a file lock when its holder dies, so the only way to
wait forever is for a live process to still be working.
+
+ Security-sensitive callers may supply the private opener and validator so
+ the same no-follow descriptor is checked before and after acquisition.
+ Default callers retain the ordinary append-open behavior.
"""
- def __init__(self, lock_path: Path, *, timeout_seconds: float | None = 30.0):
+ def __init__(
+ self,
+ lock_path: Path,
+ *,
+ timeout_seconds: float | None = 30.0,
+ _handle_opener: Callable[[Path], IO[str]] | None = None,
+ _handle_validator: Callable[[IO[str]], bool] | None = None,
+ ):
self.lock_path = lock_path
self.timeout_seconds = timeout_seconds
+ self._handle_opener = _handle_opener
+ self._handle_validator = _handle_validator
self._key = _state_key(self.lock_path)
self._state: _PathLockState | None = None
self._entries = 0
@@ -118,7 +131,16 @@ class MigrationFileLock:
raise MigrationLockTimeout(f"Timed out waiting for migration lock: {self.lock_path}")
try:
if state.depth == 0:
- state.handle = _acquire_file_lock(self.lock_path, deadline)
+ state.handle = _acquire_file_lock(
+ self.lock_path,
+ deadline,
+ handle_opener=self._handle_opener,
+ handle_validator=self._handle_validator,
+ )
+ elif self._handle_validator is not None and (
+ state.handle is None or not self._handle_validator(state.handle)
+ ):
+ raise OSError(f"Lock path failed identity validation: {self.lock_path}")
except BaseException:
state.gate.release()
_return_state(self._key)
@@ -168,34 +190,52 @@ def _acquire_gate(gate, deadline: float | None) -> bool:
return gate.acquire(timeout=remaining)
-def _acquire_file_lock(lock_path: Path, deadline: float | None):
+def _acquire_file_lock(
+ lock_path: Path,
+ deadline: float | None,
+ *,
+ handle_opener: Callable[[Path], IO[str]] | None = None,
+ handle_validator: Callable[[IO[str]], bool] | None = None,
+):
lock_path.parent.mkdir(parents=True, exist_ok=True)
- handle = open(lock_path, "a+", encoding="utf-8")
+ handle = handle_opener(lock_path) if handle_opener is not None else open(lock_path, "a+", encoding="utf-8")
next_log = time.monotonic() + _WAIT_LOG_INTERVAL_SECONDS
- while True:
- # Every attempt locks the same byte. Windows locks a range starting at
- # the current position, and both the append-mode open and the read below
- # leave it at the end of the file, so seeking is what keeps two waiters
- # contending for one byte instead of two disjoint ones.
- handle.seek(0)
- if _try_lock(handle):
+ locked = False
+ try:
+ if handle_validator is not None and not handle_validator(handle):
+ raise OSError(f"Lock path failed identity validation: {lock_path}")
+ while True:
+ # Every attempt locks the same byte. Windows locks a range starting at
+ # the current position, and both the append-mode open and the read below
+ # leave it at the end of the file, so seeking is what keeps two waiters
+ # contending for one byte instead of two disjoint ones.
handle.seek(0)
- handle.truncate()
- handle.write(str(os.getpid()))
- handle.flush()
- return handle
- now = time.monotonic()
- if deadline is not None and now >= deadline:
+ if _try_lock(handle):
+ locked = True
+ if handle_validator is not None and not handle_validator(handle):
+ raise OSError(f"Lock path failed identity validation after acquisition: {lock_path}")
+ handle.seek(0)
+ handle.truncate()
+ handle.write(str(os.getpid()))
+ handle.flush()
+ return handle
+ now = time.monotonic()
+ if deadline is not None and now >= deadline:
+ raise MigrationLockTimeout(f"Timed out waiting for migration lock: {lock_path}")
+ if now >= next_log:
+ next_log = now + _WAIT_LOG_INTERVAL_SECONDS
+ logger.info(
+ "Waiting for the migration lock at %s, held by pid %s",
+ lock_path,
+ _recorded_holder(handle),
+ )
+ time.sleep(0.1)
+ except BaseException:
+ if locked:
+ _release_file_lock(handle)
+ else:
handle.close()
- raise MigrationLockTimeout(f"Timed out waiting for migration lock: {lock_path}")
- if now >= next_log:
- next_log = now + _WAIT_LOG_INTERVAL_SECONDS
- logger.info(
- "Waiting for the migration lock at %s, held by pid %s",
- lock_path,
- _recorded_holder(handle),
- )
- time.sleep(0.1)
+ raise
def _release_file_lock(handle) -> None:
diff --git a/tests/test_managed_runtime.py b/tests/test_managed_runtime.py
index 3f596deb0..1c3dc0c5a 100644
--- a/tests/test_managed_runtime.py
+++ b/tests/test_managed_runtime.py
@@ -6,8 +6,10 @@ import io
import json
import os
import shutil
+import stat
import tarfile
from pathlib import Path
+from types import SimpleNamespace
import pytest
@@ -910,6 +912,257 @@ def test_clean_dry_run_holds_preview_guard_through_planning(
manager._install_lock.release()
[email protected]("runtime_kind", ["git", "memory", "model-hub"])
+def test_subclass_install_refuses_symlinked_mutation_guard_without_external_write(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ runtime_kind: str,
+) -> None:
+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)
+ _archive, manifest = _write_subclass_runtime_fixture(tmp_path, runtime_kind)
+ runtime_dir = tmp_path / f"{runtime_kind}-runtime"
+ runtime_dir.mkdir()
+ victim = tmp_path / f"{runtime_kind}-victim.txt"
+ victim.write_text("do not rewrite", encoding="utf-8")
+ try:
+ (runtime_dir / ".install.lock").symlink_to(victim)
+ except OSError as exc:
+ pytest.skip(f"symlink creation unavailable: {exc}")
+ manager = _subclass_runtime_manager(
+ tmp_path,
+ runtime_kind,
+ manifest,
+ monkeypatch,
+ runtime_dir=runtime_dir,
+ )
+
+ result = manager.ensure()
+
+ assert victim.read_text(encoding="utf-8") == "do not rewrite"
+ assert result["ok"] is False
+ assert result["reason"] == manager._reason("install_lock_failed")
+
+
+def test_real_cleanup_refuses_hardlinked_mutation_guard_without_external_write(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)
+ runtime_dir = tmp_path / "git-runtime"
+ runtime_dir.mkdir()
+ victim = tmp_path / "victim.txt"
+ victim.write_text("do not rewrite", encoding="utf-8")
+ try:
+ os.link(victim, runtime_dir / ".install.lock")
+ except OSError as exc:
+ pytest.skip(f"hard-link creation unavailable: {exc}")
+ manager = GitRuntimeManager(
+ runtime_dir=runtime_dir,
+ manifest_path=tmp_path / "missing-manifest.json",
+ offline=True,
+ )
+
+ result = manager.clean()
+
+ assert victim.read_text(encoding="utf-8") == "do not rewrite"
+ assert result["ok"] is False
+ assert result["reason"] == "git_clean_lock_failed"
+
+
+ ("operation", "expected_reason"),
+ [("install", "git_install_lock_failed"), ("clean", "git_clean_lock_failed")],
+)
+def test_mutation_reports_uninspectable_guard_as_lock_failure(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ operation: str,
+ expected_reason: str,
+) -> None:
+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)
+ _archive, manifest = _write_subclass_runtime_fixture(tmp_path, "git")
+ runtime_dir = tmp_path / "git-runtime"
+ runtime_dir.mkdir()
+ lock_path = runtime_dir / ".install.lock"
+ lock_path.write_text("", encoding="utf-8")
+ manager = GitRuntimeManager(runtime_dir=runtime_dir, manifest_path=manifest)
+ real_lstat = Path.lstat
+
+ def _lstat(self):
+ if self == lock_path:
+ raise OSError("guard unreadable")
+ return real_lstat(self)
+
+ monkeypatch.setattr(Path, "lstat", _lstat)
+
+ result = manager.ensure() if operation == "install" else manager.clean()
+
+ assert result["ok"] is False
+ assert result["reason"] == expected_reason
+
+
[email protected]("runtime_kind", ["git", "memory", "model-hub"])
+def test_subclass_preview_classifies_special_guard_as_inspection_failure(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ runtime_kind: str,
+) -> None:
+ if not hasattr(os, "mkfifo"):
+ pytest.skip("FIFO creation unavailable")
+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)
+ _archive, manifest = _write_subclass_runtime_fixture(tmp_path, runtime_kind)
+ runtime_dir = tmp_path / f"{runtime_kind}-runtime"
+ runtime_dir.mkdir()
+ os.mkfifo(runtime_dir / ".install.lock")
+ manager = _subclass_runtime_manager(
+ tmp_path,
+ runtime_kind,
+ manifest,
+ monkeypatch,
+ runtime_dir=runtime_dir,
+ )
+
+ result = manager.clean(dry_run=True)
+
+ assert result["ok"] is False
+ assert result["reason"] == manager._reason("clean_inspection_failed")
+
+
+def test_preview_classifies_uninspectable_guard_as_inspection_failure(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)
+ runtime_dir = tmp_path / "git-runtime"
+ runtime_dir.mkdir()
+ lock_path = runtime_dir / ".install.lock"
+ lock_path.write_text("", encoding="utf-8")
+ manager = GitRuntimeManager(
+ runtime_dir=runtime_dir,
+ manifest_path=tmp_path / "missing-manifest.json",
+ offline=True,
+ )
+ real_lstat = Path.lstat
+
+ def _lstat(self):
+ if self == lock_path:
+ raise OSError("guard unreadable")
+ return real_lstat(self)
+
+ monkeypatch.setattr(Path, "lstat", _lstat)
+
+ result = manager.clean(dry_run=True)
+
+ assert result["ok"] is False
+ assert result["reason"] == "git_clean_inspection_failed"
+
+
+def test_preview_classifies_special_guard_created_during_planning_as_inspection_failure(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ if not hasattr(os, "mkfifo"):
+ pytest.skip("FIFO creation unavailable")
+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)
+ runtime_dir = tmp_path / "git-runtime"
+ manager = GitRuntimeManager(
+ runtime_dir=runtime_dir,
+ manifest_path=tmp_path / "missing-manifest.json",
+ offline=True,
+ )
+
+ def _create_special_guard(*, keep_previous, dry_run=False, removed=None):
+ runtime_dir.mkdir(parents=True, exist_ok=True)
+ os.mkfifo(runtime_dir / ".install.lock")
+ return {"ok": True, "removed": []}
+
+ monkeypatch.setattr(manager, "_clean_locked", _create_special_guard)
+
+ result = manager.clean(dry_run=True)
+
+ assert result["ok"] is False
+ assert result["reason"] == "git_clean_inspection_failed"
+
+
+def test_windows_preview_classifies_reparse_guard_as_inspection_failure(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)
+ runtime_dir = tmp_path / "git-runtime"
+ runtime_dir.mkdir()
+ lock_path = runtime_dir / ".install.lock"
+ lock_path.write_text("", encoding="utf-8")
+ manager = GitRuntimeManager(
+ runtime_dir=runtime_dir,
+ manifest_path=tmp_path / "missing-manifest.json",
+ offline=True,
+ )
+ real_lstat = Path.lstat
+
+ def _lstat(self):
+ info = real_lstat(self)
+ if self != lock_path:
+ return info
+ return SimpleNamespace(
+ st_mode=info.st_mode,
+ st_nlink=info.st_nlink,
+ st_dev=info.st_dev,
+ st_ino=info.st_ino,
+ st_file_attributes=1,
+ )
+
+ monkeypatch.setattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 1, raising=False)
+ monkeypatch.setattr(Path, "lstat", _lstat)
+ monkeypatch.setattr("core.managed_runtime.fcntl_available", lambda: False)
+ monkeypatch.setattr("core.managed_runtime.try_windows_exclusive_lock", lambda _fd: True)
+
+ result = manager.clean(dry_run=True)
+
+ assert result["ok"] is False
+ assert result["reason"] == "git_clean_inspection_failed"
+
+
+def test_install_refuses_guard_replaced_after_lock_acquisition(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from storage import lock as storage_lock
+
+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)
+ _archive, manifest = _write_subclass_runtime_fixture(tmp_path, "git")
+ runtime_dir = tmp_path / "git-runtime"
+ runtime_dir.mkdir()
+ lock_path = runtime_dir / ".install.lock"
+ lock_path.write_text("", encoding="utf-8")
+ manager = GitRuntimeManager(runtime_dir=runtime_dir, manifest_path=manifest)
+ real_lstat = Path.lstat
+ real_try_lock = storage_lock._try_lock
+ replaced = {"value": False}
+
+ def _lstat(self):
+ info = real_lstat(self)
+ if replaced["value"] and self == lock_path:
+ fields = list(info)
+ fields[1] = info.st_ino + 73
+ return os.stat_result(fields)
+ return info
+
+ def _try_lock(handle):
+ acquired = real_try_lock(handle)
+ if acquired:
+ replaced["value"] = True
+ return acquired
+
+ monkeypatch.setattr(Path, "lstat", _lstat)
+ monkeypatch.setattr(storage_lock, "_try_lock", _try_lock)
+
+ result = manager.ensure()
+
+ assert result["ok"] is False
+ assert result["reason"] == "git_install_lock_failed"
+
+
def test_windows_preview_detects_held_git_lock(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)
runtime_dir = tmp_path / "git-runtime"
@@ -961,7 +1214,7 @@ def test_git_preview_refuses_lock_identity_mismatch(
monkeypatch.setattr(os, "fstat", _fstat)
result = manager.clean(dry_run=True)
assert result["ok"] is False
- assert result["reason"] == "git_install_already_running"
+ assert result["reason"] == "git_clean_inspection_failed"
def test_shared_ensure_failure_vocabulary_matches_reachable_reason_literals() -> None:
diff --git a/tests/test_memory_runtime.py b/tests/test_memory_runtime.py
index f8432905f..fdb584880 100644
--- a/tests/test_memory_runtime.py
+++ b/tests/test_memory_runtime.py
@@ -920,6 +920,57 @@ def test_released_memory_pointer_status_is_shallow_and_resolver_readmits(
assert active["admission_ok"] is expected_admitted
+def test_released_memory_pointer_readmission_refuses_symlinked_mutation_guard(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ manager = MemoryArtifactManager(
+ runtime_dir=tmp_path / "runtime",
+ manifest_path=tmp_path / "missing-manifest.json",
+ offline=True,
+ )
+ pointer = json.loads(
+ (MEMORY_FIXTURES / "released_active_pointer.json").read_text(encoding="utf-8")
+ )
+ pointer["platform"] = memory_artifact.runtime_platform_tag()
+ install_dir = manager.runtime_dir / "versions" / "released"
+ binary = install_dir / "bin" / "python"
+ binary.parent.mkdir(parents=True)
+ binary.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
+ binary.chmod(0o755)
+ pointer["install_dir"] = str(install_dir)
+ (install_dir / manager.spec.metadata_filename).write_text(
+ json.dumps(
+ {
+ **pointer,
+ "binary_sha256": hashlib.sha256(binary.read_bytes()).hexdigest(),
+ }
+ ),
+ encoding="utf-8",
+ )
+ manager._restore_current_pointer(pointer)
+ pointer_path = manager.runtime_dir / "current.json"
+ pointer_before = pointer_path.read_bytes()
+ victim = tmp_path / "victim.txt"
+ victim.write_text("do not rewrite", encoding="utf-8")
+ try:
+ manager._install_file_lock_path.symlink_to(victim)
+ except OSError as exc:
+ pytest.skip(f"symlink creation unavailable: {exc}")
+ monkeypatch.setattr(
+ manager,
+ "_prepare_binary",
+ lambda *_args, **_kwargs: pytest.fail("unsafe guard reached the compatibility probe"),
+ )
+
+ resolved = manager.resolve_python()
+
+ assert victim.read_text(encoding="utf-8") == "do not rewrite"
+ assert resolved is None
+ assert manager._install_reason == "memory_runtime_install_failed"
+ assert pointer_path.read_bytes() == pointer_before
+
+
@pytest.mark.parametrize(
"mismatch",
[
diff --git a/tests/test_migration_lock.py b/tests/test_migration_lock.py
index 14031cbbb..f3e836427 100644
--- a/tests/test_migration_lock.py
+++ b/tests/test_migration_lock.py
@@ -78,6 +78,34 @@ def test_re_entrance_belongs_to_the_path_not_to_one_lock_object(tmp_path: Path)
assert _free_for_another_thread(lock_path) is True
+def test_failed_reentrant_validation_preserves_the_outer_lock(tmp_path: Path) -> None:
+ lock_path = tmp_path / "migration.lock"
+ validation_allowed = True
+
+ def validate_handle(_handle) -> bool:
+ return validation_allowed
+
+ outer = MigrationFileLock(
+ lock_path,
+ timeout_seconds=None,
+ _handle_validator=validate_handle,
+ )
+ inner = MigrationFileLock(
+ lock_path,
+ timeout_seconds=0,
+ _handle_validator=validate_handle,
+ )
+
+ with outer:
+ assert _free_for_another_thread(lock_path) is False
+ validation_allowed = False
+ with pytest.raises(OSError, match="Lock path failed identity validation"):
+ inner.acquire()
+ assert _free_for_another_thread(lock_path) is False
+
+ assert _free_for_another_thread(lock_path) is True
+
+
def test_the_lock_follows_the_database_not_the_route_taken_to_it(tmp_path: Path) -> None:
# Two callers that disagree about which directory is "the" state directory
# would otherwise take two different locks over one database and both