Skip to content

The agent that grows with you

fix(update): launchers reach the launch-time repair before any other checkout module

Tekniumfd73042f2db3
diff --git a/hermes_bootstrap.py b/hermes_bootstrap.py
index db7a4cd8ef2..f42d20d7174 100644
--- a/hermes_bootstrap.py
+++ b/hermes_bootstrap.py
@@ -533,6 +533,20 @@ def _settle_interrupted_update() -> None:
_settle_interrupted_update()
+
+def _pin_launcher_home() -> None:
+ """A minted launcher (``hermes_cli._launchers``) pins ``HERMES_HOME`` to the install's default
+ root. That needs ``hermes_constants`` from the checkout, so the launcher asks for it here, after
+ the repair above: a merge killed while writing ``hermes_constants.py`` must not keep the repair
+ from ever running. The flag name is ``_launchers.PIN_DEFAULT_HOME_FLAG``."""
+ if getattr(sys, "_hermes_pin_default_home", False) and not os.environ.get("HERMES_HOME"):
+ from hermes_constants import get_default_hermes_root
+
+ os.environ["HERMES_HOME"] = str(get_default_hermes_root())
+
+
+_pin_launcher_home()
+
_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 not
diff --git a/hermes_cli/_launchers.py b/hermes_cli/_launchers.py
index 35d53d3bc24..eed03d79f09 100644
--- a/hermes_cli/_launchers.py
+++ b/hermes_cli/_launchers.py
@@ -22,6 +22,10 @@ if __name__ == "__main__":
from pm.environments import owning_home_root, store_root
+# ``sys`` attribute a launcher sets before ``import hermes_bootstrap``: pin HERMES_HOME to the
+# install's default root once the launch-time repair ran (``hermes_bootstrap._pin_launcher_home``).
+PIN_DEFAULT_HOME_FLAG = "_hermes_pin_default_home"
+
def _inline_string_literal(value: str) -> str:
"""Keep inline Python source intact through Windows PowerShell's native argv quoting."""
@@ -44,15 +48,24 @@ def runtime_command(repo_root: Path, args=(), *, module: str = "hermes_cli.main"
python = python or resolve_store_python(root) or Path(sys.executable)
entry = f"exec({_inline_string_literal(code)})" if code is not None else (
f"runpy.run_module({_inline_string_literal(module)}, run_name='__main__', alter_sys=True)")
- default_home = (_inline_string_literal(str(home)) if home is not None else
- "str(__import__('hermes_constants').get_default_hermes_root())")
+ # A literal home is pinned up front; the default one needs ``hermes_constants`` from the
+ # checkout, so it is pinned only after ``hermes_bootstrap``'s launch-time repair (see
+ # ``_launcher_script``), here again for a bootstrap that predates that hook.
+ if home is not None:
+ pin, settle = (f"os.environ['HERMES_HOME'] = os.environ.get('HERMES_HOME') or "
+ f"{_inline_string_literal(str(home))}; "), ""
+ else:
+ pin = f"sys.{PIN_DEFAULT_HOME_FLAG} = True; "
+ settle = ("os.environ.get('HERMES_HOME') or os.environ.__setitem__('HERMES_HOME', "
+ "str(__import__('hermes_constants').get_default_hermes_root())); ")
bootstrap = (
"import os, sys, runpy; "
"os.environ.pop('PYTHONHOME', None); os.environ.pop('PYTHONPATH', None); "
"os.environ.pop('VIRTUAL_ENV', None); "
f"sys.path.insert(0, {_inline_string_literal(str(root))}); "
- f"os.environ['HERMES_HOME'] = os.environ.get('HERMES_HOME') or {default_home}; "
- "import hermes_bootstrap; "
+ + pin
+ + "import hermes_bootstrap; "
+ + settle
+ entry
)
return [str(python), "-I", "-c", bootstrap, *args]
@@ -296,20 +309,38 @@ def _launcher_script(name: str, repo_root: Path, dependencies: Path | None) -> s
module, func = ENTRY_POINTS[name]
# Profile boot repairs shared launchers: their default must stay at the
# install's dependency root, not whichever profile triggered publication.
+ #
+ # The launch-time repair of a checkout a killed update left torn (``hermes_bootstrap`` ->
+ # ``_early_recovery.restore_interrupted_pull``) runs before ANY other checkout module is
+ # imported: a merge killed while writing ``hermes_constants.py`` must not stop every launch
+ # before the repair. The default-home pin (which needs ``hermes_constants``) happens inside
+ # ``hermes_bootstrap`` right after the repair (``_PIN_DEFAULT_HOME``), and here again for a
+ # bootstrap that predates that hook.
+ root = str(repo_root.resolve())
return (
"import os, re, sys\n"
"os.environ.pop('PYTHONHOME', None)\n"
"os.environ.pop('PYTHONPATH', None)\n"
- f"sys.path.insert(0, {str(repo_root.resolve())!r})\n"
- "if sys.argv[1:2] == ['--print-runtime-command']: sys.dont_write_bytecode = True\n"
- "from hermes_constants import get_default_hermes_root\n"
- "os.environ['HERMES_HOME'] = os.environ.get('HERMES_HOME') or str(get_default_hermes_root())\n"
+ f"sys.path.insert(0, {root!r})\n"
"if sys.argv[1:2] == ['--print-runtime-command']:\n"
+ " sys.dont_write_bytecode = True\n"
" from pathlib import Path\n"
+ " try:\n"
+ " from hermes_cli import _early_recovery\n"
+ " except ImportError:\n"
+ " _early_recovery = None\n"
+ f" if _early_recovery is not None and _early_recovery.restore_interrupted_pull(Path({root!r})):\n"
+ " _early_recovery.relaunch_after_restore()\n"
+ " from hermes_constants import get_default_hermes_root\n"
+ " os.environ['HERMES_HOME'] = os.environ.get('HERMES_HOME') or str(get_default_hermes_root())\n"
" from hermes_cli._launchers import print_runtime_command\n"
- f" print_runtime_command(Path({str(repo_root.resolve())!r}), sys.argv[2:])\n"
+ f" print_runtime_command(Path({root!r}), sys.argv[2:])\n"
" sys.exit(0)\n"
+ f"sys.{PIN_DEFAULT_HOME_FLAG} = True\n"
"import hermes_bootstrap\n"
+ "if not os.environ.get('HERMES_HOME'):\n"
+ " from hermes_constants import get_default_hermes_root\n"
+ " os.environ['HERMES_HOME'] = str(get_default_hermes_root())\n"
"if sys.argv[1:2] == ['--run-module']:\n"
" import runpy\n"
" if len(sys.argv) < 3: sys.exit('hermes: --run-module needs a module')\n"
diff --git a/tests/hermes_cli/test_source_launcher_publication.py b/tests/hermes_cli/test_source_launcher_publication.py
index ff316f50501..ce71bf3e105 100644
--- a/tests/hermes_cli/test_source_launcher_publication.py
+++ b/tests/hermes_cli/test_source_launcher_publication.py
@@ -535,6 +535,73 @@ def test_sync_migrates_old_store_wrapper_before_python_collection(tmp_path, monk
assert json.loads(result.stdout)["value"] == "ready"
assert Path(json.loads(result.stdout)["exe"]) == store / "python-B/bin/python3"
+def _torn_by_a_killed_merge(tmp_path, monkeypatch):
+ """A git install whose update was killed mid-merge while git rewrote ``hermes_constants.py``.
+
+ Git rewrites a file as unlink, create, write: the kill left HEAD at the old commit, the
+ interrupted-pull marker of a dead updater, ``.git/index.lock`` and no ``hermes_constants.py``.
+ """
+ repo, home, interpreter = fixture_tree(tmp_path, monkeypatch)
+ for relative in ("hermes_cli/update_lock.py", "hermes_cli/update_custody.py"):
+ shutil.copy2(ROOT / relative, repo / relative)
+
+ def git(*args):
+ return subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True,
+ text=True, encoding="utf-8").stdout.strip()
+
+ git("init", "-q", "-b", "main")
+ git("config", "user.email", "[email protected]")
+ git("config", "user.name", "t")
+ git("add", "-A")
+ git("commit", "-qm", "pre")
+ pre = git("rev-parse", "HEAD")
+ constants = repo / "hermes_constants.py"
+ original = constants.read_bytes()
+ constants.write_bytes(original + b"\nTARGET_ONLY = 1\n")
+ git("commit", "-qam", "target")
+ target = git("rev-parse", "HEAD")
+ git("reset", "-q", "--hard", pre)
+ from hermes_cli import _early_recovery
+
+ marker = _early_recovery.interrupted_pull_marker(repo)
+ marker.write_text(f"pid=0\npre={pre}\ntarget={target}\nstash=\n", encoding="utf-8", newline="")
+ constants.unlink()
+ (repo / ".git" / "index.lock").touch()
+ select_generation(repo, "one", "repaired")
+ return repo, home, interpreter, pre, original, marker
+
+
[email protected]("surface", ["launcher", "runtime-command"])
+def test_a_merge_killed_writing_hermes_constants_is_repaired_by_the_next_launch(tmp_path, monkeypatch, surface):
+ """C1 recovery reachability: the launcher reaches the repair before importing any other
+ checkout module, so a torn ``hermes_constants.py`` is put back instead of killing every launch."""
+ repo, home, interpreter, pre, original, marker = _torn_by_a_killed_merge(tmp_path, monkeypatch)
+ env = dict(os.environ)
+ env.pop("HERMES_HOME", None) # the default-home pin itself needs hermes_constants
+ env.pop("HERMES_RUNTIME_DIR", None)
+ env.pop("PYTEST_CURRENT_TEST", None) # the repair stands down in a checkout pytest itself runs from
+ if surface == "launcher":
+ out = tmp_path / "commands"
+ out.mkdir()
+ command = [str(_launchers._mint_shell_launcher("hermes", out, interpreter,
+ _launchers._launcher_script("hermes", repo, None)))]
+ else:
+ command = _launchers.runtime_command(repo, python=interpreter)
+ result = subprocess.run(command, cwd=tmp_path, env=env, capture_output=True,
+ text=True, encoding="utf-8", errors="replace", timeout=60)
+ assert "No module named 'hermes_constants'" not in result.stderr, result.stderr
+ assert result.returncode == 7, result.stdout + result.stderr
+ receipt = json.loads(result.stdout.strip().splitlines()[-1])
+ assert receipt["value"] == "repaired"
+ assert Path(receipt["home"]) == home, "the default home is still pinned, after the repair"
+ assert (repo / "hermes_constants.py").read_bytes() == original
+ assert not marker.exists() and not (repo / ".git" / "index.lock").exists()
+ head = subprocess.run(["git", "-C", str(repo), "rev-parse", "HEAD"], capture_output=True,
+ text=True, encoding="utf-8", check=True).stdout.strip()
+ assert head == pre
+
+
def test_update_import_probe_uses_selected_dependencies(tmp_path, monkeypatch):
from hermes_cli import update_cmd, update_cmd_validation