The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(pm): close the lease create→flock race on the writer side, no grace window
teknium1dd3ba4b4b8d6
diff --git a/hermes_cli/runtime_state.py b/hermes_cli/runtime_state.pyindex 6fd4aa84bb3..c799d86729d 100644--- a/hermes_cli/runtime_state.py+++ b/hermes_cli/runtime_state.py@@ -36,8 +36,6 @@ INSTALL_LOCK_TIMEOUT_SECONDS = 10.0# A lease file younger than this is never a prune candidate: its creator may still sit between# ``O_CREAT|O_EXCL`` and ``flock`` (two syscalls; the window is microseconds, the margin generous).-LEASE_GRACE_SECONDS = 60.0-@contextmanagerdef runtime_lock(project: Path, *, timeout: float | None = INSTALL_LOCK_TIMEOUT_SECONDS):"""Hold the per-install dependency lock; yields True when held, False when the wait expired.@@ -155,13 +153,21 @@ def lease_directory(generation: Path) -> Callable[[], None]:leases = generation / ".leases"leases.mkdir(exist_ok=True)_prune_unlocked_leases(leases)- 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:+ while True:+ 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+ # Create and flock are two syscalls; a peer's prune (pm workers and launch run outside+ # ``runtime_lock``) can lock-and-unlink the file in between, and we would then hold an+ # unlinked inode invisible to every collector. The pruner only unlinks while holding the+ # lock, so once we hold it the path is either still ours or already gone for good.+ if lease.exists():+ breakos.close(fd)- raisedef release() -> None:atexit.unregister(release)@@ -215,10 +221,7 @@ def _prune_unlocked_leases(leases: Path) -> bool:the selected generation too, which generation GC intentionally never visits.Fail closed: a lease this user cannot open (root-owned 0o600 from a ``sudo hermes`` on the- same checkout) is held, never a boot failure; a lease younger than ``LEASE_GRACE_SECONDS``- is held too, because ``lease_directory`` creates and locks in two syscalls and callers- outside ``runtime_lock`` (pm workers, launch) would otherwise prune a peer's lease in- between — leaving that peer locking an unlinked inode for its lifetime.+ same checkout) is held, never a boot failure."""held = Falsefor lease in leases.glob("*"):@@ -230,7 +233,7 @@ def _prune_unlocked_leases(leases: Path) -> bool:held = Truecontinuetry:- if time.time() - os.fstat(fd).st_mtime < LEASE_GRACE_SECONDS or not _lock(fd, wait=False):+ if not _lock(fd, wait=False):held = Trueelse:with suppress(OSError):diff --git a/tests/pm/test_runtime_gc.py b/tests/pm/test_runtime_gc.pyindex 1e9beb594e6..e389cbea7e7 100644--- a/tests/pm/test_runtime_gc.py+++ b/tests/pm/test_runtime_gc.py@@ -71,7 +71,6 @@ os._exit(0)leases = generation / ".leases"stale = list(leases.iterdir())assert len(stale) == 1- os.utime(stale[0], (0, 0)) # past LEASE_GRACE_SECONDS: nobody can still be between create and flockrelease = lease_directory(generation)try:@@ -85,9 +84,9 @@ os._exit(0)@pytest.mark.skipif(getattr(os, "geteuid", lambda: 1)() == 0, reason="root opens mode-0 files")-def test_prune_keeps_unopenable_and_just_created_sibling_leases(tmp_path):- """A lease this user cannot open (root-owned, `sudo hermes` on the same checkout) or one a- peer created but has not flocked yet is HELD: boot never raises, GC never collects."""+def test_prune_keeps_unopenable_sibling_lease(tmp_path):+ """A lease this user cannot open (root-owned, `sudo hermes` on the same checkout) is HELD:+ boot never raises and GC never collects."""from hermes_cli.runtime_state import lease_directory, leases_heldgeneration = _generation(tmp_path / "pm-runtime", "selected")@@ -95,15 +94,39 @@ def test_prune_keeps_unopenable_and_just_created_sibling_leases(tmp_path):leases.mkdir()foreign = leases / "foreign"foreign.touch()- os.utime(foreign, (0, 0))foreign.chmod(0)- fresh = leases / "fresh"- fresh.touch()try:lease_directory(generation)()- assert foreign.exists() and fresh.exists()+ assert foreign.exists()assert leases_held(generation)- os.utime(fresh, (0, 0))- assert leases_held(generation) and not fresh.exists()finally:foreign.chmod(0o600)+++def test_lease_taken_while_a_peer_pruned_it_is_retaken(tmp_path, monkeypatch):+ """A peer's prune can lock-and-unlink our lease between create and flock; the writer must+ end up holding a lease the collectors can see, never an unlinked inode."""+ from hermes_cli import runtime_state+ from hermes_cli.runtime_state import lease_directory, leases_held++ generation = _generation(tmp_path / "pm-runtime", "selected")+ leases = generation / ".leases"+ real_lock = runtime_state._lock+ raced = []++ def racing_lock(fd, *, wait, **kw):+ if wait and not raced: # the writer's first take: a peer pruned the file first+ for stray in leases.iterdir():+ stray.unlink()+ raced.append(fd)+ return real_lock(fd, wait=wait, **kw)++ monkeypatch.setattr(runtime_state, "_lock", racing_lock)+ release = lease_directory(generation)+ try:+ assert raced+ assert len(list(leases.iterdir())) == 1+ assert leases_held(generation)+ finally:+ release()+ assert list(leases.iterdir()) == []