The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): the ZIP swap lock keeps one inode and never admits without a lock
Teknium4d462e19c5a6
diff --git a/.gitignore b/.gitignoreindex eb08488bcc1..8e831afe327 100644--- a/.gitignore+++ b/.gitignore@@ -264,6 +264,7 @@ docs/superpowers/*.update-incomplete.lock# Kernel lock `hermes update` holds on the checkout (hermes_cli/update_lock.py)..hermes-update.lock+.hermes-update-zip-swap.lock# Checkout fingerprint the __pycache__ tree was last validated against# (launch-time stale-bytecode sweep). Runtime state, never a code change.diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.pyindex 2c9d7f75081..5014e2ebaa8 100644--- a/hermes_cli/_early_recovery.py+++ b/hermes_cli/_early_recovery.py@@ -499,36 +499,62 @@ ZIP_SWAP_JOURNAL = ".hermes-update-zip-swap"_ZIP_STAGING_SUFFIX, _ZIP_OLD_SUFFIX = ".hermes-update-staging", ".hermes-update-old"+class ZipSwapLock:+ """``zip_swap_owner_lock``'s verdict: truthy only while this process holds the kernel lock.++ ``reason`` names a refusal: ``busy`` (a live owner holds it) or why no lock could be taken at all.+ """++ __slots__ = ("owned", "reason")++ def __init__(self, owned: bool, reason: str = "") -> None:+ self.owned, self.reason = owned, reason++ def __bool__(self) -> bool:+ return self.owned++@contextlib.contextmanagerdef zip_swap_owner_lock(root: Path, *, wait: float = 0.0):- """Yields True while this process owns the ZIP swap lock, False when a live owner holds it.+ """Yields a truthy ``ZipSwapLock`` while this process owns the ZIP swap lock, a falsy one otherwise.- The lock file is removed again once no journal is left, so a settled install carries no- breadcrumb (the swap itself also runs under the update lock; this one only proves liveness)."""+ The lock file is a stable sidecar: never unlinked, so every process locks the same inode (an+ unlink lets a waiter keep the old inode while a newcomer locks a fresh one). No lock, no admission:+ a root where the file cannot be opened or locked refuses with the reason (fail closed)."""lock_path = Path(root) / (ZIP_SWAP_JOURNAL + ".lock")try:fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o644)- except OSError:- yield True # unwritable root: no swap can run there either+ except OSError as exc:+ yield ZipSwapLock(False, f"cannot open the ZIP swap lock {lock_path}: {exc.strerror or exc}")return- owned = Falsetry:deadline = time.monotonic() + wait- while not _lock_fd(fd, True):+ while True:+ try:+ if sys.platform == "win32":+ import msvcrt++ os.lseek(fd, 0, os.SEEK_SET)+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)+ else:+ import fcntl++ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)+ break+ except OSError as exc:+ if exc.errno not in _CLAIM_HELD_ERRNOS:+ yield ZipSwapLock(False, f"cannot lock the ZIP swap lock {lock_path}: {exc.strerror or exc}")+ returnif time.monotonic() >= deadline:- yield False+ yield ZipSwapLock(False, "busy")returntime.sleep(0.05)- owned = Truetry:- yield True+ yield ZipSwapLock(True)finally:_lock_fd(fd, False)finally:os.close(fd)- if owned and not (Path(root) / ZIP_SWAP_JOURNAL).exists():- with contextlib.suppress(OSError):- lock_path.unlink()def write_zip_swap_journal(root: Path, phase: str, entries: list) -> None:@@ -563,6 +589,8 @@ def restore_interrupted_zip_swap(project_root: Path | None = None) -> bool:if not journal.is_file() or _pytest_owns_live_checkout(root):return Falsewith zip_swap_owner_lock(root) as owned:+ if not owned and owned.reason != "busy":+ print(f"⚠ An interrupted ZIP update cannot be settled: {owned.reason}.", file=sys.stderr)if not owned or not journal.is_file():return Falseimport jsondiff --git a/hermes_cli/update_cmd_zip.py b/hermes_cli/update_cmd_zip.pyindex 16b0148e986..ac399fe2912 100644--- a/hermes_cli/update_cmd_zip.py+++ b/hermes_cli/update_cmd_zip.py@@ -372,7 +372,8 @@ def _journaled_stage_and_swap(extracted: str, entries: list[str], root: Path, taraise RuntimeError("an interrupted ZIP update could not be settled; see the warning above")with zip_swap_owner_lock(root, wait=10.0) as owned:if not owned:- raise RuntimeError("another `hermes update` is swapping this install right now")+ raise RuntimeError("another `hermes update` is swapping this install right now"+ if owned.reason == "busy" else f"no ZIP swap lock, no swap ({owned.reason})")# A leftover backup counts: _stage_replacement puts it back as the entry before the swap.journal_entries = [[item, any(os.path.lexists(os.path.join(root, item + suffix))for suffix in ("", ".hermes-update-old"))] for item in entries]diff --git a/tests/hermes_cli/test_update_zip_completion.py b/tests/hermes_cli/test_update_zip_completion.pyindex 69a7bdd9b7b..5dbd9856fb6 100644--- a/tests/hermes_cli/test_update_zip_completion.py+++ b/tests/hermes_cli/test_update_zip_completion.py@@ -17,6 +17,11 @@ from hermes_cli.update_inventory import RuntimeRecord, UpdatePlanimport hermes_yaml+def _swap_leftovers(root):+ """Staging/backup siblings and the journal; the swap lock is a stable sidecar that stays (one inode)."""+ return [p for p in root.glob("*.hermes-update-*") if p.name != ".hermes-update-zip-swap.lock"]++@pytest.fixturedef zip_update(tmp_path, monkeypatch, isolated_source_completion):home = tmp_path / "home"@@ -151,7 +156,7 @@ def test_zip_command_migrates_profiles_recovers_snapshot_and_verifies_fleet(assert receipt["runtime_outcomes"][0]["outcome"] == "restarted"assert update_receipt._current.get() is Noneassert state.token["resume_needed"] is False- assert not list(state.root.glob("*.hermes-update-*"))+ assert not _swap_leftovers(state.root)@pytest.mark.parametrize("verdict", ["healthy", "unsafe-sqlite", "stale-fleet"])@@ -232,8 +237,8 @@ def test_zip_failure_recovers_pause_without_completion_mutations(zip_update, monassert (state.root / "pyproject.toml").read_bytes() == old_projectassert (state.root / "payload.txt").read_text() == "old"if failure != "preparation":- assert {p.relative_to(state.root): p.read_bytes()- for p in state.root.rglob("*") if p.is_file()} == original_tree+ assert {p.relative_to(state.root): p.read_bytes() for p in state.root.rglob("*")+ if p.is_file() and p.name != ".hermes-update-zip-swap.lock"} == original_treeassert state.events == ["resume"]assert state.token["resume_needed"] is Falseassert {profile: (profile / "config.yaml").read_bytes() for profile in before} == before@@ -244,7 +249,7 @@ def test_zip_failure_recovers_pause_without_completion_mutations(zip_update, mon# record of THIS run, never a success.latest = state.active / "logs/update_receipts/latest.json"assert not latest.exists() or json.loads(latest.read_text())["outcome"] != "success"- assert not list(state.root.glob("*.hermes-update-*"))+ assert not _swap_leftovers(state.root)@pytest.mark.parametrize("route", ["direct", "git-failure"])@@ -368,10 +373,10 @@ def test_zip_recovers_crashed_backup_before_failed_copy_and_retry(zip_update, moassert error.value.code == 1witness = target / "code.py" if entry == "tools" else targetassert witness.read_text(encoding="utf-8") == ("retained" if entry == "tools" else "old")- assert not list(root.glob("*.hermes-update-*"))+ assert not _swap_leftovers(root)update_cmd_zip._download_and_swap_zip("main", "local fixture")assert witness.read_text(encoding="utf-8") == "new"- assert not list(root.glob("*.hermes-update-*"))+ assert not _swap_leftovers(root)def test_atomic_directory_compat_entrypoint(tmp_path):@@ -383,7 +388,7 @@ def test_atomic_directory_compat_entrypoint(tmp_path):update_cmd_zip._atomic_replace_dir(str(src), str(dst))assert {p.name for p in dst.iterdir()} == {"new"}assert (dst / "new").read_text(encoding="utf-8") == "new"- assert not list(tmp_path.glob("*.hermes-update-*"))+ assert not _swap_leftovers(tmp_path)def test_zip_refuses_non_main_before_transport(zip_update, monkeypatch, capsys):