Skip to content

The agent that grows with you

fix(pm): re-check the selected generation after an unlocked boot lease

ethernetb80bd18c766c
diff --git a/hermes_cli/runtime_state.py b/hermes_cli/runtime_state.py
index e8dc35aa4cd..e48923b7ad0 100644
--- a/hermes_cli/runtime_state.py
+++ b/hermes_cli/runtime_state.py
@@ -4,7 +4,8 @@ from __future__ import annotations
import atexit
import errno
import base64
-from contextlib import contextmanager
+from collections.abc import Callable
+from contextlib import contextmanager, suppress
import hashlib
import json
import logging
@@ -182,25 +183,36 @@ def finish_publication(project: Path) -> None:
recover_publication(project)
-def lease_generation(environment: Path) -> None:
- """Hold a kernel lock until process exit.
+def lease_generation(environment: Path) -> Callable[[], None]:
+ """Hold a kernel lock until process exit; the returned callable releases it early.
- Call under ``runtime_lock`` at boot; when that lock times out it is still safe to lease
- without it, because the collector only removes generations that are NOT selected and are
- older than a day — the generation being leased here is the selected one.
+ Call under ``runtime_lock`` at boot. Without the lock (``runtime_lock`` timed out) the
+ caller must re-read the selection after leasing: an installer may have moved it in between,
+ and an unselected, unleased generation is exactly what the collector removes.
"""
generation = environment.parent
if not (generation / ".lease-managed").is_file():
- return # Generations produced before leases stay conservatively retained.
+ return lambda: None # Generations produced before leases stay conservatively retained.
leases = generation / ".leases"
leases.mkdir(exist_ok=True)
- fd = os.open(leases / uuid.uuid4().hex, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o600)
+ lease = leases / uuid.uuid4().hex
+ fd = os.open(lease, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o600)
try:
_lock(fd, wait=True)
except BaseException:
os.close(fd)
raise
- atexit.register(os.close, fd)
+
+ def release() -> None:
+ atexit.unregister(release)
+ os.close(fd)
+ # Best effort: the collector ignores unlocked lease files, but one per
+ # invocation would otherwise accumulate for the life of the generation.
+ with suppress(OSError):
+ lease.unlink()
+
+ atexit.register(release)
+ return release
def collect_generations(project: Path, *, min_age_seconds: float = 86400) -> list[Path]:
diff --git a/pm/environments.py b/pm/environments.py
index 8cc55100204..6945dc4bf7e 100644
--- a/pm/environments.py
+++ b/pm/environments.py
@@ -208,7 +208,12 @@ def activate_dependencies(project_root: Path) -> None:
if held:
recover_publication(project_root)
environment = selected_venv(project_root)
- lease_generation(environment)
+ release = lease_generation(environment)
+ # Without the lock, an installer may commit a new generation between the
+ # read and the lease, leaving the leased one unselected and collectable.
+ while not held and (current := selected_venv(project_root)) != environment:
+ release()
+ environment, release = current, lease_generation(current)
selected = site_packages(environment)
if not selected.is_dir() and not runtime_facts_path(project_root).is_file():
return
diff --git a/tests/pm/test_lease_reselection.py b/tests/pm/test_lease_reselection.py
new file mode 100644
index 00000000000..99d846d6f22
--- /dev/null
+++ b/tests/pm/test_lease_reselection.py
@@ -0,0 +1,75 @@
+"""A reader that lost the install lock still ends up leasing the generation it imports from."""
+import contextlib
+import json
+import os
+import sys
+
+import pytest
+
+
+def generations(tmp_path, monkeypatch):
+ from pm.environments import install_state_dir, runtime_facts_path, site_packages
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
+ state = install_state_dir(repo)
+ for name in ("first", "second"):
+ venv = state / "environments" / name / "venv"
+ venv.mkdir(parents=True)
+ (venv / "pyvenv.cfg").write_text("version = 3.11")
+ site_packages(venv).mkdir(parents=True)
+ (venv.parent / ".lease-managed").touch()
+
+ def select(name):
+ environment = state / "environments" / name / "venv"
+ runtime_facts_path(repo).write_text(json.dumps({"packages": {"venv": {"environment": str(environment)}}}))
+ return environment.resolve()
+
+ return repo, state, select
+
+
+def test_unlocked_reader_releases_a_lease_the_installer_moved_away_from(generations, monkeypatch):
+ from hermes_cli import runtime_state
+ from pm.environments import activate_dependencies
+
+ repo, state, select = generations
+ first = select("first")
+ real_lease = runtime_state.lease_generation
+ leased = []
+
+ def racing_lease(environment):
+ # The installer commits between the reader's selection read and its lease.
+ if not leased:
+ select("second")
+ leased.append(environment)
+ return real_lease(environment)
+
+ @contextlib.contextmanager
+ def lost_lock(project, **kwargs):
+ yield False
+
+ monkeypatch.setattr(runtime_state, "runtime_lock", lost_lock)
+ monkeypatch.setattr(runtime_state, "lease_generation", racing_lease)
+ # Activation rewrites this process's import path and environment; keep it scoped.
+ monkeypatch.setattr(sys, "path", list(sys.path))
+ for key in ("PYTHONPATH", "PATH", "VIRTUAL_ENV"):
+ monkeypatch.setenv(key, os.environ.get(key, ""))
+
+ activate_dependencies(repo)
+
+ assert leased[0] == first and leased[-1] == state / "environments" / "second" / "venv"
+ assert not any((first.parent / ".leases").iterdir()), "the stale lease must be released"
+ assert len(list((state / "environments" / "second" / ".leases").iterdir())) == 1
+
+
+def test_release_removes_the_lease_file(generations):
+ from hermes_cli.runtime_state import lease_generation
+
+ _, state, select = generations
+ environment = select("first")
+ release = lease_generation(environment)
+ assert list((environment.parent / ".leases").iterdir())
+ release()
+ assert not list((environment.parent / ".leases").iterdir())