The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): "is an update running" readers honour the checkout lock
Teknium607efc192cdb
diff --git a/hermes_cli/main_install_repair.py b/hermes_cli/main_install_repair.pyindex 10eb374794d..676c1607572 100644--- a/hermes_cli/main_install_repair.py+++ b/hermes_cli/main_install_repair.py@@ -203,6 +203,11 @@ def _cleanup_quarantined_exes(scripts_dir: Path | None = None) -> None:scripts_dir = scripts_dir if scripts_dir is not None else _venv_scripts_dir()if scripts_dir is None:return+ from hermes_cli.main import PROJECT_ROOT+ from hermes_cli.update_lock import update_in_progress++ if update_in_progress(PROJECT_ROOT):+ return # every quarantine may be that update's own, mid rename-back_cleanup_pending_shim_renames(scripts_dir)now = _time.time()try:diff --git a/hermes_cli/venv_sync.py b/hermes_cli/venv_sync.pyindex a14d14ecbd3..a648a002c65 100644--- a/hermes_cli/venv_sync.py+++ b/hermes_cli/venv_sync.py@@ -376,7 +376,7 @@ def prepare_launch(project_root: Path, argv: list[str]) -> Path | None:import pmfrom hermes_cli._launchers import resolve_store_python- from hermes_cli.update_lock import UpdateLock, read_live_update+ from hermes_cli.update_lock import UpdateLock, read_live_update, update_in_progresscurrent = pm.venv_is_current(project_root=root)from pm.environments import owning_home_root@@ -401,8 +401,12 @@ def prepare_launch(project_root: Path, argv: list[str]) -> Path | None:# noise (the record's age tracks the wait), leaving the marker armed.passelif not owed_to_cli and (not current or pending.is_file()):+ # Read before claiming: our own claim would answer for us. A free marker over a held+ # checkout lock is a killed update whose tree (its completion child) still runs.+ busy = update_in_progress(root)lock = UpdateLock()- if not lock.acquire():+ if not lock.acquire() or (lock.acquired and busy):+ lock.release()raise RuntimeError("an update is still running; wait for it to exit, then relaunch Hermes")try:# Under the launching update's own claim (its pid is our ancestor) a process itdiff --git a/hermes_cli/web_server_skew_exit.py b/hermes_cli/web_server_skew_exit.pyindex f2cfbd11a8e..e1634cdefe6 100644--- a/hermes_cli/web_server_skew_exit.py+++ b/hermes_cli/web_server_skew_exit.py@@ -38,9 +38,9 @@ def should_retire_for_skew(*, skew: Skew, update_in_progress: bool) -> bool:def _update_in_progress() -> bool:try:- from hermes_cli.update_lock import read_live_update+ from hermes_cli.update_lock import update_in_progress- return read_live_update() is not None+ return update_in_progress()except Exception:return True # cannot prove the swap is over: waitdiff --git a/tests/e2e/core/upgrade/git/test_hostile_lock.py b/tests/e2e/core/upgrade/git/test_hostile_lock.pyindex b4471c020e4..6323e17f3bc 100644--- a/tests/e2e/core/upgrade/git/test_hostile_lock.py+++ b/tests/e2e/core/upgrade/git/test_hostile_lock.py@@ -44,6 +44,20 @@ from pathlib import Pathroot, checkout, mode = Path(sys.argv[1]), sys.argv[2], sys.argv[3]envs = json.loads((root / "envs.json").read_text(encoding="utf-8"))ARGV = [sys.executable, "-m", "hermes_cli.main", "update", "--yes", "--branch", "main", "--no-gateway-restart"]+# The readers a launch / a running server consult, in a fresh process of another home.+READER = """+import json, sys+from pathlib import Path+sys.path.insert(0, sys.argv[1])+from hermes_cli.web_server_skew_exit import _update_in_progress+from hermes_cli.venv_sync import prepare_launch+out = {"skew_reader": _update_in_progress()}+try:+ out["launch"] = repr(prepare_launch(Path(sys.argv[1]), ["status"]))+except RuntimeError as exc:+ out["launch"] = "refused: " + str(exc)+print(json.dumps(out))+"""def ct(pid):@@ -108,6 +122,26 @@ elif mode == "kill-mid-completion":result["child_alive_after"] = child is not None and alive(child)if child is not None and alive(child):os.kill(child, signal.SIGKILL)+elif mode == "orphan-reader":+ first = subprocess.Popen(ARGV, env=envs["home-a"], cwd=checkout, stdin=subprocess.DEVNULL,+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ child = None+ deadline = time.time() + 240+ while child is None and time.time() < deadline and first.poll() is None:+ child = completion_child(envs["home-a"]["HERMES_HOME"])+ time.sleep(0.05)+ result["child_seen"] = child is not None+ os.kill(first.pid, signal.SIGKILL)+ first.wait()+ # The killed owner's marker is gone (any reader compare-and-deletes a dead claim).+ (Path(envs["home-a"]["HERMES_HOME"]) / ".hermes-update-in-progress").unlink(missing_ok=True)+ reader = subprocess.run([sys.executable, "-c", READER, checkout], env=envs["home-b"], cwd=checkout,+ stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=120)+ result["reader_out"] = reader.stdout[-2000:] + reader.stderr[-2000:]+ result["reader"] = json.loads(reader.stdout.strip().splitlines()[-1]) if reader.returncode == 0 else None+ result["child_alive_after"] = child is not None and alive(child)+ if child is not None and alive(child):+ os.kill(child, signal.SIGKILL)result["out"] = result.get("out", "")[-4000:]print(json.dumps(result))'''@@ -218,3 +252,14 @@ def test_killed_owner_keeps_the_checkout_locked_while_its_tree_runs(rig):assert r["rc"] == 2 and REFUSAL in r["out"], (f"a new update started while the killed update's completion child ran (rc={r['rc']}, "f"child alive after: {r['child_alive_after']}):\n{r['out']}")+++def test_orphaned_update_tree_reads_as_in_progress(rig):+ """(e) SIGKILL `hermes update` mid-completion and lose its marker: the completion child still+ holds the checkout lock, so every "is an update running" reader must still say yes."""+ r = rig.driver("orphan-reader", timeout=600)+ assert r["child_seen"] and r["child_alive_after"], f"premise: no completion child outlived the owner: {r}"+ assert r["reader"] is not None, f"reader process failed:\n{r['reader_out']}"+ assert r["reader"]["skew_reader"] is True, f"the server's update probe missed the live update tree: {r}"+ assert r["reader"]["launch"].startswith("refused: an update is still running"), (+ f"a launch ran the completion tail beside the live update tree: {r}")diff --git a/tests/hermes_cli/test_source_completion_stamp.py b/tests/hermes_cli/test_source_completion_stamp.pyindex 6ca887dae08..619142567ed 100644--- a/tests/hermes_cli/test_source_completion_stamp.py+++ b/tests/hermes_cli/test_source_completion_stamp.py@@ -130,16 +130,36 @@ def test_completion_refuses_to_stack_on_a_live_update(tmp_path, monkeypatch, forcomplete_source_checkout(root, desktop=False, assume_yes=True)-def test_completion_runs_under_a_parents_claim_without_releasing_it(tmp_path, monkeypatch):+def test_completion_runs_under_a_parents_claim_without_releasing_it(tmp_path):"""A tail spawned by an orchestrator that holds the lock (venv_sync'sinterrupted-update finish, the updater's own completion child) runs under- its parent's claim and leaves the parent's marker untouched."""- root = _repo(tmp_path)- marker = _sandboxed_marker(tmp_path, monkeypatch)- marker.write_text(f"{os.getppid()}\n{int(time.time())}\n", encoding="utf-8")- _completion_dependencies(monkeypatch, lambda **_kwargs: True)+ its parent's claim and leaves the parent's marker untouched.- assert complete_source_checkout(root, desktop=False, assume_yes=True)+ Real topology: a parent process claims, then runs the tail as its child. The test+ process's own parent can be invisible (a pid-namespaced runner), so it is never used."""+ root = _repo(tmp_path)+ marker = tmp_path / ".hermes-update-in-progress"+ tail = (+ "import json, sys\n"+ f"sys.path.insert(0, {str(Path(__file__).resolve().parents[2])!r})\n"+ "from pathlib import Path\n"+ "import hermes_cli.source_build, hermes_cli.update_cmd_maint, hermes_cli.update_lock, hermes_cli.venv_sync\n"+ "from hermes_cli.source_completion import complete_source_checkout\n"+ "hermes_cli.venv_sync.publish_launchers = lambda root: None\n"+ "hermes_cli.source_build.build_update_products = lambda root, *, desktop: None\n"+ "hermes_cli.update_cmd_maint._run_post_update_maintenance = lambda **_kwargs: True\n"+ f"hermes_cli.update_lock.update_marker_path = lambda: Path({str(marker)!r})\n"+ f"print(json.dumps(complete_source_checkout(Path({str(root)!r}), desktop=False, assume_yes=True)))\n"+ )+ parent = (+ "import os, subprocess, sys, time\n"+ f"open({str(marker)!r}, 'w', encoding='utf-8').write(f'{{os.getpid()}}\\n{{int(time.time())}}\\n')\n"+ "sys.exit(subprocess.call([sys.executable, '-c', sys.argv[1]]))\n"+ )+ run = subprocess.run([sys.executable, "-c", parent, tail], capture_output=True, text=True,+ encoding="utf-8", timeout=120)++ assert run.returncode == 0 and run.stdout.strip().splitlines()[-1:] == ["true"], run.stdout + run.stderrassert marker.exists(), "the parent still owns its claim after our tail"