The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): a ZIP swap killed with hermes_cli/ moved aside still reaches recovery
Tekniumf1def901fbd3
diff --git a/hermes_bootstrap.py b/hermes_bootstrap.pyindex 9cb74b77e33..db7a4cd8ef2 100644--- a/hermes_bootstrap.py+++ b/hermes_bootstrap.py@@ -507,6 +507,32 @@ def _legacy_post_swap_invocation(argv: list[str]) -> tuple[Path, list[str]] | No# without this, ``pm`` is unimportable and the launch silently skips PM adoption.harden_import_path(str(_root))++def _settle_interrupted_update() -> None:+ """Put back the tree a killed ``hermes update`` left half-moved, before PM, launch preparation or+ any Hermes package imports from it (``hermes_cli._early_recovery``; ``hermes_cli.main`` repeats the+ call for entries that never reach this module). A killed ZIP swap can leave ``hermes_cli/`` itself+ moved aside: the journal-driven restore then runs from that moved-aside copy, the code that wrote+ the journal. Root files are never absent mid-swap (``update_cmd_zip._commit_staged_replacements``)."""+ try:+ from hermes_cli import _early_recovery as recovery+ except ImportError:+ moved_aside = _root / "hermes_cli.hermes-update-old" / "_early_recovery.py"+ if not (_root / ".hermes-update-zip-swap").is_file() or not moved_aside.is_file():+ return # not a torn update: the imports below report the real damage+ import importlib.util++ spec = importlib.util.spec_from_file_location("_hermes_moved_aside_recovery", moved_aside)+ if spec is None or spec.loader is None:+ return+ recovery = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(recovery)+ if recovery.restore_interrupted_pull(_root):+ recovery.relaunch_after_restore()+++_settle_interrupted_update()+_legacy_post_swap = _legacy_post_swap_invocation(sys.argv[1:])if _legacy_post_swap is not None:# This continuation exists precisely because the replacement tree may notdiff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.pyindex 479accd3583..65be3bd93af 100644--- a/hermes_cli/_early_recovery.py+++ b/hermes_cli/_early_recovery.py@@ -553,8 +553,11 @@ def restore_interrupted_zip_swap(project_root: Path | None = None) -> bool:try:if phase == "swapping":if existed and old.exists():- _drop_path(dst)- os.rename(old, dst)+ if old.is_file() and not old.is_symlink() and not dst.is_dir():+ os.replace(old, dst) # a file entry never goes missing, not even here+ else:+ _drop_path(dst)+ os.rename(old, dst)changed = Trueelif not existed and dst.exists() and not staging.exists():_drop_path(dst)diff --git a/hermes_cli/update_cmd_zip.py b/hermes_cli/update_cmd_zip.pyindex f9b071496d7..5386839ddb9 100644--- a/hermes_cli/update_cmd_zip.py+++ b/hermes_cli/update_cmd_zip.py@@ -97,6 +97,18 @@ def _discard_staged(staged) -> None:logger.warning("could not remove staging path %s: %s", staging, exc)+def _hardlink_backup(path: str, backup: str) -> bool:+ """Hardlink ``path`` to ``backup`` (a stale backup is replaced); False where links are unsupported.+ A link is all-or-nothing, so a killed swap never leaves a short backup the restore would put back."""+ try:+ if os.path.lexists(backup):+ _remove_path(backup)+ os.link(path, backup)+ except OSError:+ return False+ return True++def _commit_staged_replacements(staged, *, on_committed=None) -> None:"""Phase 2: swap every staged entry into place, rolling back all on failure.@@ -108,12 +120,21 @@ def _commit_staged_replacements(staged, *, on_committed=None) -> None:``_atomic_replace_dir`` makes each *individual* directory swap safe, but the ZIP update replaces ~90top-level entries in a loop, and nothing made the loop atomic *as a whole*. See #63717, #76091, #76104.++ A plain file is never absent, not even for one rename: its backup is a hardlink and ``os.replace``+ lands the new bytes over it (a filesystem without hardlinks keeps the move-aside). The root modules every launcher imports first+ (``hermes_constants``, ``hermes_bootstrap``) therefore always import, and ``hermes_bootstrap`` runs the+ journal-driven restore even while a killed swap left a directory (``hermes_cli/`` included) moved aside."""swapped: list[tuple[str, str]] = [] # (dst, backup) in swap order; "" = absenttry:for staging, dst in staged:backup = f"{dst}.hermes-update-old"- if os.path.exists(dst):+ if os.path.isfile(dst) and not os.path.islink(dst) and _hardlink_backup(dst, backup):+ swapped.append((dst, backup))+ os.replace(staging, dst)+ continue+ if os.path.lexists(dst):os.rename(dst, backup)swapped.append((dst, backup))else:@@ -122,8 +143,11 @@ def _commit_staged_replacements(staged, *, on_committed=None) -> None:except OSError:for dst, backup in reversed(swapped): # undo every swap already made so the install stays self-consistenttry:+ if backup and os.path.isfile(backup) and not os.path.islink(backup):+ os.replace(backup, dst)+ continue_remove_path(dst)- if backup and os.path.exists(backup):+ if backup and os.path.lexists(backup):os.rename(backup, dst)except OSError as exc:# Keep restoring the rest; a silent failure here turns a recoverable rollback into a mixed tree.diff --git a/tests/e2e/core/upgrade/git/test_hostile_commit.py b/tests/e2e/core/upgrade/git/test_hostile_commit.pyindex e63ca4dcb5d..dfc93cf58e2 100644--- a/tests/e2e/core/upgrade/git/test_hostile_commit.py+++ b/tests/e2e/core/upgrade/git/test_hostile_commit.py@@ -16,6 +16,8 @@ real git failure, and then judges the next real launch from the files the updatelaunch must put the parked tree back.* ``kill_mid_zip_swap``: the ZIP swap is SIGKILLed between renames. The next launch must finish orroll back the swap, leaving no ``*.hermes-update-staging``/``-old`` sibling to wedge a retry.+* ``kill_mid_zip_swap_with_hermes_cli_moved_aside``: the swap renamed ``hermes_cli/`` (the recovery+ code itself) aside and died before its replacement landed. The next launch must still restore.* ``syntax_error_target``: a release whose startup module does not compile is refused BEFOREHEAD moves (no fast-forward in the reflog), not merely rolled back afterwards."""@@ -187,28 +189,39 @@ sys.path.insert(0, sys.argv[3]) # the install's checkout (the venv's own path pfrom hermes_cli import update_cmd_zip as zimport hermes_cli.main as massert str(m.PROJECT_ROOT) == sys.argv[3], m.PROJECT_ROOT-renames, kill_after = [0], int(sys.argv[2])-real = os.rename-def rename(src, dst):- real(src, dst)- if str(src).endswith(".hermes-update-staging"): # one entry swapped in- renames[0] += 1- if renames[0] >= kill_after:- os.kill(os.getpid(), signal.SIGKILL)-os.rename = rename+swaps, kill_at = [0], sys.argv[2]+def killing(real):+ def move(src, dst):+ real(src, dst)+ if kill_at == "hermes_cli-moved-aside": # the live package renamed away, its replacement not yet in+ if os.path.basename(str(src)) == "hermes_cli" and str(dst).endswith(".hermes-update-old"):+ os.kill(os.getpid(), signal.SIGKILL)+ elif str(src).endswith(".hermes-update-staging"): # one entry swapped in+ swaps[0] += 1+ if swaps[0] >= int(kill_at):+ os.kill(os.getpid(), signal.SIGKILL)+ return move+os.rename, os.replace = killing(os.rename), killing(os.replace)z._download_and_swap_zip("main", sys.argv[1])"""-def test_kill_mid_zip_swap_is_settled_by_the_next_launch(world):+def _zip_killed_at(world, kill_at: str):+ """A ZIP update of a fresh release, SIGKILLed at ``kill_at`` (N-th entry swapped in, or a named point)."""sb = world["sb"]- pre = _head(sb)- target = _release(world, {"e2e_zip_release.py": "Z = 1\n", "hermes_cli/e2e_zip_marker.py": "M = 1\n"})- archive = world["root"] / "release.zip"+ target = _release(world, {"e2e_zip_release.py": f"Z = {world['n']}\n", "hermes_cli/e2e_zip_marker.py": "M = 1\n"})+ archive = world["root"] / f"release-{world['n']}.zip"I.git("archive", "--format=zip", "--prefix=hermes-agent-main/", "-o", str(archive), target, cwd=world["origin"])driver = world["root"] / "zip_driver.py"driver.write_text(_ZIP_DRIVER, encoding="utf-8")- killed = P.run_env(sb, [sb.python, str(driver), archive.as_uri(), "12", str(sb.checkout)], sb.env, timeout=P.UPDATE_TIMEOUT)+ return P.run_env(sb, [sb.python, str(driver), archive.as_uri(), kill_at, str(sb.checkout)], sb.env,+ timeout=P.UPDATE_TIMEOUT)+++def test_kill_mid_zip_swap_is_settled_by_the_next_launch(world):+ sb = world["sb"]+ pre = _head(sb)+ killed = _zip_killed_at(world, "12")at_kill = {"artifacts": _artifacts(sb), "dirty": _tracked_dirty(sb),"new_entry": (sb.checkout / "e2e_zip_release.py").exists()}assert at_kill["artifacts"] and at_kill["dirty"], (@@ -220,3 +233,20 @@ def test_kill_mid_zip_swap_is_settled_by_the_next_launch(world):f"tracked changes {at_kill['dirty']!r})\n" + I.describe(launch))assert _head(sb) == pre and not _tracked_dirty(sb), ("the interrupted ZIP swap left a mixed tree:\n" + _tracked_dirty(sb) + "\n" + I.describe(launch))+++def test_kill_mid_zip_swap_with_hermes_cli_moved_aside_reaches_recovery(world):+ """The one window where the recovery code itself is gone: the swap renamed ``hermes_cli/`` aside+ and died before the replacement landed. The next launch must still reach the journal-driven+ restore (from the moved-aside copy) and run, not die on ``No module named 'hermes_cli'``."""+ sb = world["sb"]+ pre = _head(sb)+ killed = _zip_killed_at(world, "hermes_cli-moved-aside")+ assert not (sb.checkout / "hermes_cli").exists() and (sb.checkout / "hermes_cli.hermes-update-old").is_dir(), (+ "harness: the ZIP swap was not killed with hermes_cli/ moved aside\n" + I.describe(killed))+ launch = _launch(sb, "first launch after a kill with hermes_cli moved aside")+ assert launch.returncode == 0 and (sb.checkout / "hermes_cli" / "main.py").is_file(), (+ "the launch after a kill with hermes_cli/ moved aside could not reach recovery\n" + I.describe(launch))+ assert not _artifacts(sb) and _head(sb) == pre and not _tracked_dirty(sb), (+ f"left {_artifacts(sb)[:5]} / tracked changes {_tracked_dirty(sb)!r}\n" + I.describe(launch))+ P.ok(_update(sb), "the update after the restored swap failed")diff --git a/tests/hermes_cli/test_update_zip_two_phase.py b/tests/hermes_cli/test_update_zip_two_phase.pyindex ef6cb24ec7c..6c781ac3f35 100644--- a/tests/hermes_cli/test_update_zip_two_phase.py+++ b/tests/hermes_cli/test_update_zip_two_phase.py@@ -169,16 +169,16 @@ def test_file_swap_failure_restores_the_original_file(tmp_path, monkeypatch):for n in ("cli.py", "run_agent.py")]- real_rename = os.rename+ real_replace = os.replacecalls = {"n": 0}- def flaky_rename(src, dst):+ def flaky_replace(src, dst): # a root file swaps in by os.replace over its hardlinked backupcalls["n"] += 1- if calls["n"] == 4:+ if calls["n"] == 2:raise OSError("simulated AV interference")- return real_rename(src, dst)+ return real_replace(src, dst)- monkeypatch.setattr(update_cmd.os, "rename", flaky_rename)+ monkeypatch.setattr(update_cmd.os, "replace", flaky_replace)with pytest.raises(OSError):update_cmd._commit_staged_replacements(staged)monkeypatch.undo()@@ -327,3 +327,33 @@ def test_commit_failure_plus_discard_leaves_no_staging_litter(tmp_path, monkeypa# ...and zero litter of any kind (staging OR backup).litter = [p for p in os.listdir(live) if "hermes-update" in p]assert litter == [], f"orphaned update litter: {litter}"+++def test_root_files_never_go_missing_mid_swap(tmp_path, monkeypatch):+ """Every launcher imports ``hermes_constants``/``hermes_bootstrap`` before anything else, and+ ``hermes_bootstrap`` is what reaches the restore after a killed swap: a kill between any two+ filesystem steps must find every root file present (old or new bytes), only directories moved."""+ live, new = tmp_path / "live", tmp_path / "new"+ for side, text in ((live, "old"), (new, "new")):+ (side / "hermes_cli").mkdir(parents=True)+ (side / "hermes_cli" / "main.py").write_text(text, encoding="utf-8")+ for name in ("hermes_constants.py", "hermes_bootstrap.py"):+ (side / name).write_text(text, encoding="utf-8")+ names = ("hermes_constants.py", "hermes_cli", "hermes_bootstrap.py")+ staged = [(update_cmd._stage_replacement(str(new / n), str(live / n)), str(live / n)) for n in names]+ missing: list[str] = []++ def probing(real):+ def step(src, dst):+ real(src, dst)+ missing.extend(n for n in ("hermes_constants.py", "hermes_bootstrap.py") if not (live / n).is_file())+ return step++ monkeypatch.setattr(update_cmd.os, "rename", probing(os.rename))+ monkeypatch.setattr(update_cmd.os, "replace", probing(os.replace))+ update_cmd._commit_staged_replacements(staged)+ monkeypatch.undo()+ assert not missing, f"root modules absent mid-swap: {missing}"+ assert {n: (live / n).read_text(encoding="utf-8-sig") for n in ("hermes_constants.py", "hermes_bootstrap.py")} == {+ "hermes_constants.py": "new", "hermes_bootstrap.py": "new"}+ assert not [p for p in os.listdir(live) if "hermes-update" in p]