The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): a restored relaunch may relaunch again once current; update --check backs off
Tekniumeea30482750e
diff --git a/hermes_cli/venv_sync.py b/hermes_cli/venv_sync.pyindex e4fa41a82aa..e21eb7c1376 100644--- a/hermes_cli/venv_sync.py+++ b/hermes_cli/venv_sync.py@@ -370,12 +370,17 @@ def _tree_matches_completed_stamp(root: Path) -> bool:return info.commit == commit and not info.dirty+# `hermes update` flags that report and exit without changing anything (subcommands/update.py).+_REPORT_ONLY_UPDATE_FLAGS = frozenset({"--check", "--plan", "--list-venv-holders"})++def _may_retry_completion(root: Path, command: list[str], *, current: bool) -> bool:"""Whether this launch runs the owed repair now; a suppressed one says why when it matters."""import sys- if not current and command[:1] == ["update"]:+ if not current and command[:1] == ["update"] and not _REPORT_ONLY_UPDATE_FLAGS & set(command):# `hermes update` is the remedy every backed-off launch names: it always tries the repair.+ # Its report-only forms change nothing, so they stay inside the backoff like any launch.return Truemay_retry, attempts, backoff = completion_retry_state(root)if not may_retry and attempts >= COMPLETION_RETRY_MAX_ATTEMPTS:@@ -398,15 +403,19 @@ def _may_retry_completion(root: Path, command: list[str], *, current: bool) -> breturn may_retry-def _relaunch_target(python: Path, *, same: bool) -> Path | None:- """*python*, unless this process is already a relaunch into that same interpreter.+def _relaunch_target(root: Path, python: Path, *, same: bool) -> Path | None:+ """*python*, unless this process is a relaunch into that same interpreter and is still stale.- A relaunched child that asks to relaunch into itself again would find the same install state- in the next child too: exec'ing would loop forever (#122513), so it boots as it is.+ A relaunched child that is still stale would find the same install state in the next child+ too: exec'ing would loop forever (#122513), so it boots as it is. The marker can outlive the+ relaunch that set it (a restore re-execs ``sys.orig_argv``), so a marked child whose sync DID+ make the install current relaunches once more: that next child boots current, never here."""import sys- if same and getattr(sys, "_hermes_relaunched", False):+ import pm++ if same and getattr(sys, "_hermes_relaunched", False) and not pm.venv_is_current(project_root=root):print("hermes: relaunching did not leave this install current; running with the ""dependencies it has — run `hermes update` to finish it", file=sys.stderr, flush=True)return None@@ -515,7 +524,7 @@ def prepare_launch(project_root: Path, argv: list[str]) -> Path | None:same = os.path.normcase(os.path.abspath(python)) == os.path.normcase(os.path.abspath(sys.executable))if not current or not same:publish_launchers(root)- return _relaunch_target(python, same=same)+ return _relaunch_target(root, python, same=same)if owed_to_cli:# Left owed, not dropped: say so (once, in the process that boots) where an# operator of the unit will read it.@@ -691,7 +700,8 @@ def relaunch_command(if option in ("-W", "-X") and index < len(original):options.append(original[index])index += 1- # _hermes_relaunched marks the child this starts (not processes it spawns) for _relaunch_target.+ # _hermes_relaunched marks the child this starts (not processes it spawns) for _relaunch_target;+ # a restore re-execs sys.orig_argv and keeps it, which is why that guard re-checks currency.prefix = (f"import sys, runpy; sys.path.insert(0, {str(root)!r}); sys.argv = {argv!r}; ""sys._hermes_relaunched = True; ")if argv[0] == "-c":diff --git a/tests/hermes_cli/test_launch_relaunch_loop.py b/tests/hermes_cli/test_launch_relaunch_loop.pyindex 8a0ebb4184d..517c0ffdbd3 100644--- a/tests/hermes_cli/test_launch_relaunch_loop.py+++ b/tests/hermes_cli/test_launch_relaunch_loop.py@@ -34,18 +34,29 @@ with generations.open("a") as fh:if len(generations.read_text().split()) > int(os.environ["GENERATION_CAP"]):raise SystemExit(99)+state = Path(scratch, "state")+def sync(*_args, **_kwargs):with Path(scratch, "syncs").open("a") as fh:fh.write(f"{launch}\n")if sync_mode == "fail":raise RuntimeError("sync failed")+ state.write_text("current")-pm.venv_is_current = lambda **_kw: False+# "restore": PM's answer follows the sync; otherwise it never says current.+pm.venv_is_current = lambda **_kw: sync_mode == "restore" and state.read_text() == "current"pm.sync_venv = syncpm.client.ensure_tools_for_sync = lambda: None_launchers.resolve_store_python = lambda *_a, **_k: Path(sys.executable)venv_sync.publish_launchers = lambda *_a, **_k: None+if sync_mode == "restore" and getattr(sys, "_hermes_relaunched", False) and not Path(scratch, "restored").exists():+ # The relaunched child restores a torn update: the restored tree's dependencies are stale again.+ Path(scratch, "restored").write_text("1")+ state.write_text("stale")+ from hermes_cli import _early_recovery+ _early_recovery.relaunch_after_restore()+try:python = venv_sync.prepare_launch(Path(root), command_args)if python is not None:@@ -57,6 +68,8 @@ print("BOOTED")def _launch(tmp_path: Path, root: Path, sync_mode: str, launch: int, argv: list[str]):+ if not (tmp_path / "state").exists():+ (tmp_path / "state").write_text("stale", encoding="utf-8")script = tmp_path / "launch.py"script.write_text(_LAUNCH, encoding="utf-8")env = {"PATH": "/usr/bin:/bin", "HOME": str(tmp_path), "HERMES_HOME": str(tmp_path / "home"),@@ -75,12 +88,12 @@ def _syncs(tmp_path: Path) -> int:@pytest.mark.platforms("posix")[email protected]("argv", [[], ["update"]], ids=["launch", "update"])[email protected]("argv", [[], ["update"], ["update", "--check"]], ids=["launch", "update", "update-check"])def test_backed_off_failed_sync_boots_on_the_previous_dependencies(tmp_path, monkeypatch, argv):"""#139952 records a failed launch sync so relaunches back off. A launch inside that backoff(or past the cap) has run no repair, so relaunching it would re-enter the same decision andexec again forever; it must boot on the previous dependencies, and `hermes update` (the- remedy every backed-off launch names) still tries the repair."""+ remedy every backed-off launch names) still tries the repair; its report-only `--check` does not."""from hermes_cli import venv_syncroot = tmp_path / "checkout"@@ -94,7 +107,7 @@ def test_backed_off_failed_sync_boots_on_the_previous_dependencies(tmp_path, monassert result.returncode == 0, f"launch {launch} looped: {generations} generations\n{result.stderr}"assert result.stdout.strip() == "BOOTED"assert generations == 1- expected = 4 if argv else venv_sync.COMPLETION_RETRY_BACKOFF_ATTEMPTS+ expected = 4 if argv == ["update"] else venv_sync.COMPLETION_RETRY_BACKOFF_ATTEMPTSassert _syncs(tmp_path) == expected, "a backed-off launch re-ran the failing repair"if not argv:@@ -108,10 +121,7 @@ def test_backed_off_failed_sync_boots_on_the_previous_dependencies(tmp_path, monassert result.stderr.count("could not be finished automatically") == 1[email protected]("posix")-def test_relaunched_child_never_relaunches_into_itself(tmp_path):- """A sync that never makes the install current (the PM answer disagrees with what the sync- did) must not turn every launch into an exec chain: the relaunched child boots."""+def _committed_checkout(tmp_path: Path) -> Path:from hermes_cli.source_stamp import write_source_stamproot = tmp_path / "checkout"@@ -124,9 +134,30 @@ def test_relaunched_child_never_relaunches_into_itself(tmp_path):["add", "-A"], ["commit", "-m", "init"]):subprocess.run(["git", *args], cwd=root, env=git_env, check=True, capture_output=True, timeout=30)assert write_source_stamp(root)["dirty"] is False+ return root+[email protected]("posix")+def test_relaunched_child_never_relaunches_into_itself(tmp_path):+ """A sync that never makes the install current (the PM answer disagrees with what the sync+ did) must not turn every launch into an exec chain: the relaunched child boots."""+ root = _committed_checkout(tmp_path)result, generations = _launch(tmp_path, root, "ok", 1, [])assert result.returncode == 0, f"looped: {generations} generations\n{result.stderr}"assert result.stdout.strip() == "BOOTED"assert generations == 2, "the first relaunch into the store interpreter is still taken"assert "relaunching did not leave this install current" in result.stderr++[email protected]("posix")+def test_marker_kept_by_a_restore_does_not_refuse_a_relaunch_that_worked(tmp_path):+ """A restore re-execs ``sys.orig_argv``, so the restored process still carries the relaunch+ marker. When its sync makes the install current, it relaunches once more and that child+ boots current; it never claims the relaunch left the install stale."""+ root = _committed_checkout(tmp_path)+ result, generations = _launch(tmp_path, root, "restore", 1, [])+ assert result.returncode == 0, f"looped: {generations} generations\n{result.stderr}"+ assert result.stdout.strip() == "BOOTED"+ assert "relaunching did not leave this install current" not in result.stderr+ # launch -> relaunched child (restores) -> restored process (syncs) -> its relaunch boots+ assert generations == 4