Skip to content

The agent that grows with you

fix(update): a `hermes update` killed mid-pull no longer bricks every entry point

teknium1e30f8c63442c
diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.py
index e049fb7253e..813e911fe83 100644
--- a/hermes_cli/_early_recovery.py
+++ b/hermes_cli/_early_recovery.py
@@ -8,6 +8,7 @@ the known-fragile core packages, using the pins from pyproject.toml).
from __future__ import annotations
+import contextlib
import importlib
import os
import shutil
@@ -210,6 +211,113 @@ def _marker_owner_is_live(marker: Path) -> bool:
return False
+# ``hermes update`` writes this into ``.git/`` right before git moves the checkout and removes it once
+# git is done. Git rewrites the tree file by file and moves HEAD last, so an update killed in between
+# leaves HEAD on the old commit with a prefix of the files already new; that mixed tree fails at import
+# in every entry point, ``hermes update`` included. A marker whose owner is gone means exactly that.
+INTERRUPTED_PULL_MARKER = "hermes-update-pull"
+# A fast-forward takes seconds; past this a "live" owner pid is a recycled one.
+_INTERRUPTED_PULL_MAX_AGE_SECONDS = 10 * 60
+
+
+def interrupted_pull_marker(root: Path) -> Path:
+ return root / ".git" / INTERRUPTED_PULL_MARKER
+
+
+def restore_interrupted_pull(project_root: Path | None = None) -> bool:
+ """Put back the files a killed ``hermes update`` had half-moved to the new commit. Never raises.
+
+ Returns True when files were restored: modules this process already imported may be the
+ half-written ones, so the caller must relaunch (``relaunch_after_restore``).
+
+ Fast path (no marker) is one ``stat``. Acts only when the marker's owner is gone and HEAD is still
+ the pre-pull commit: every path that differs between it and the pull target returns to HEAD (the
+ commit the venv was built for), so the install is whole again and ``hermes update`` redoes the
+ update from the start. Paths the update does not change keep any local edits; the updater's
+ autostash (if any) stays in ``git stash list``.
+ """
+ try:
+ root = _project_root() if project_root is None else project_root
+ marker = interrupted_pull_marker(root)
+ if not marker.is_file() or _pytest_owns_live_checkout(root):
+ return False
+ fields = dict(line.partition("=")[::2] for line in marker.read_text(encoding="utf-8").splitlines())
+ try:
+ owner = int(fields.get("pid", ""))
+ except ValueError:
+ owner = -1
+ # Our own pid is never the owner: this runs at startup, and containers hand a retry the
+ # killed updater's pid.
+ if (owner != os.getpid() and _pid_is_running(owner)
+ and time.time() - marker.stat().st_mtime < _INTERRUPTED_PULL_MAX_AGE_SECONDS):
+ return False
+
+ def git(*args: str, stdin: str | None = None) -> subprocess.CompletedProcess:
+ return subprocess.run(["git", "--literal-pathspecs", "-C", str(root), *args], input=stdin,
+ capture_output=True, text=True, timeout=120,
+ stdin=None if stdin is not None else subprocess.DEVNULL)
+
+ pre, target = fields.get("pre", "").strip(), fields.get("target", "").strip()
+ if not pre or not target or git("rev-parse", "HEAD").stdout.strip() != pre:
+ marker.unlink() # git finished (HEAD moved) or the marker is unusable
+ return False
+ diff = git("diff", "--name-status", "-z", "--no-renames", pre, target)
+ if diff.returncode != 0:
+ return False
+ parts = diff.stdout.split("\0")
+ added = [p for s, p in zip(parts[::2], parts[1::2]) if s == "A"]
+ kept = [p for s, p in zip(parts[::2], parts[1::2]) if s and s != "A"]
+ # The dead git's index lock would refuse every command below.
+ (root / ".git" / "index.lock").unlink(missing_ok=True)
+ status = git("status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames")
+ dirty = {entry[3:] for entry in status.stdout.split("\0") if len(entry) > 3}
+ if status.returncode != 0 or dirty.isdisjoint(added + kept):
+ if status.returncode == 0:
+ marker.unlink() # the killed git never reached the tree: nothing to put back
+ return False
+ print("⚠ A previous `hermes update` was killed while git was writing the new code — "
+ f"restoring the checkout to {pre[:10]}...", file=sys.stderr)
+ ok = True
+ if kept:
+ ok = git("restore", "--source=HEAD", "--staged", "--worktree", "--pathspec-from-file=-",
+ "--pathspec-file-nul", stdin="\0".join(kept)).returncode == 0
+ if added and ok:
+ ok = git("rm", "-q", "--cached", "--ignore-unmatch", "--pathspec-from-file=-",
+ "--pathspec-file-nul", stdin="\0".join(added)).returncode == 0
+ for rel in added:
+ path = root / rel
+ path.unlink(missing_ok=True)
+ with contextlib.suppress(OSError):
+ os.removedirs(path.parent) # stops at the first non-empty dir
+ if ok:
+ marker.unlink()
+ print(" ✓ Checkout restored; `hermes update` updates it again.", file=sys.stderr)
+ if fields.get("stash", "").strip():
+ print(f" Your local changes are still in the update's stash ({fields['stash'].strip()}).",
+ file=sys.stderr)
+ return True
+ print(f" ✗ Could not restore it automatically. Recover with: git -C {root} reset --hard {pre}",
+ file=sys.stderr)
+ except Exception:
+ pass # Never block launch — the import that follows surfaces the real error.
+ return False
+
+
+def relaunch_after_restore() -> None:
+ """Re-run this command from the restored tree; never returns.
+
+ Everything imported so far (this package, ``hermes_bootstrap``, ``hermes_cli.main`` itself) may
+ be the killed git's new files, and they would run against the restored old tree.
+ """
+ argv = [sys.executable, *sys.orig_argv[1:]]
+ sys.stdout.flush()
+ sys.stderr.flush()
+ if sys.platform == "win32":
+ # os.execv on Windows spawns and exits, detaching the console's wait on us.
+ sys.exit(subprocess.call(argv)) # windows-footgun: ok — interactive child keeps our console
+ os.execv(sys.executable, argv)
+
+
def _pinned_specs(packages: list[str], project_root: Path) -> list[str]:
"""Map bare package names to their pinned specs from pyproject.toml.
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index be58df9a905..525203cc94d 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -17,6 +17,16 @@ try:
except ModuleNotFoundError:
pass
+# A `hermes update` killed while git was writing the new tree leaves a mix of old and new files that
+# fails at the next import, whichever it is — put the old tree back before importing anything else
+# from the checkout, then rerun the command (this module may itself be one of the new files).
+# ``_early_recovery`` is stdlib-only and imported unguarded on purpose: same package
+# dir, so if IT can't import nothing in hermes_cli can.
+from hermes_cli import _early_recovery as _early_recovery_mod
+
+if _early_recovery_mod.restore_interrupted_pull():
+ _early_recovery_mod.relaunch_after_restore()
+
# Windows: neutralize CPython's ``platform._syscmd_ver`` before anything else
# imports — it shells out ``cmd /c ver`` and flashes a console when this
# process is windowless (pythonw gateway, kanban workers). No-op on POSIX.
@@ -44,13 +54,9 @@ _startup_fast.normalize_hermes_home_env()
# the hermes_cli.config/env_loader imports further down would then crash before
# main() reaches _recover_from_interrupted_install(). ``_early_recovery`` is
# stdlib-only (safe on a corrupted venv) and repairs just enough to finish this
-# import; the marker lifecycle stays with the full recovery path. Its own
-# import is unguarded on purpose: same package dir, so if IT can't import
-# nothing in hermes_cli can.
+# import; the marker lifecycle stays with the full recovery path.
# It is also the canonical home of the probe/repair tables reused by the full recovery path below. See
# #57828.
-from hermes_cli import _early_recovery as _early_recovery_mod
-
try:
_early_recovery_mod.recover_if_needed()
except Exception:
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 6a1f42ddc61..01c4f0a2734 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -19,6 +19,7 @@ from pathlib import Path
from hermes_cli.config import get_hermes_home # noqa: F401 (re-exported; patched via update_cmd)
from hermes_cli import update_handoff as _update_handoff
from hermes_cli.update_cmd_common import _best_effort
+from hermes_cli._early_recovery import interrupted_pull_marker
from hermes_constants import get_default_hermes_root, project_venv_dir, venv_python_path
# Re-exports: every split-module name stays reachable (and monkeypatchable) as update_cmd.<name>.
@@ -866,11 +867,19 @@ def _pull_updates(
# critical-path file (PR #28452 incident: orphan merge-conflict markers in hermes_cli/config.py bricked
# every user who ran ``hermes update`` for the 7 minutes between the bad commit and the fix landing).
pre_pull_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)
+ # Git moves the tree file by file and HEAD last: if this process dies in between, the next launch
+ # of any entry point finds this marker and puts the old tree back (_early_recovery).
+ pull_marker = interrupted_pull_marker(_m().PROJECT_ROOT)
+ with _best_effort('Could not write the interrupted-pull marker: %s'):
+ pull_marker.write_text(
+ f"pid={os.getpid()}\npre={pre_pull_sha}\ntarget=origin/{branch}\nstash={auto_stash_ref or ''}\n",
+ encoding="utf-8")
try:
# merge --ff-only the already-fetched ref instead of `git pull`, which would do a
# SECOND network fetch; identical in effect given the fresh tracking ref.
if _git_run(git_cmd, ["merge", "--ff-only", f"origin/{branch}"]).returncode != 0:
_reconcile_diverged_checkout(git_cmd, branch, pre_pull_sha)
+ pull_marker.unlink(missing_ok=True) # git is done: the tree is whole again
_rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha)
update_succeeded = True
finally:
diff --git a/tests/hermes_cli/test_update_interrupted_pull.py b/tests/hermes_cli/test_update_interrupted_pull.py
new file mode 100644
index 00000000000..50b4485650a
--- /dev/null
+++ b/tests/hermes_cli/test_update_interrupted_pull.py
@@ -0,0 +1,104 @@
+"""A `hermes update` killed while git writes the new tree must leave a recoverable install.
+
+Git rewrites the checkout file by file and moves HEAD last, so a kill in between leaves HEAD on the
+old commit with some files already new — a mix that fails at import in every entry point. The
+updater brackets the move with a marker; the next launch (``_early_recovery``, before any other
+checkout import) puts the old tree back so ``hermes update`` can simply run again.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from hermes_cli import _early_recovery as er
+from hermes_cli import update_cmd
+
+
+def _git(root: Path, *args: str) -> str:
+ return subprocess.run(["git", "-C", str(root), *args], check=True, capture_output=True,
+ text=True).stdout.strip()
+
+
+def checkout(tmp_path, monkeypatch):
+ """An install at commit A whose fetched ``origin/main`` is B (modifies, deletes, adds a package)."""
+ origin = tmp_path / "origin"
+ origin.mkdir()
+ _git(origin, "init", "-q", "-b", "main")
+ _git(origin, "config", "user.email", "[email protected]")
+ _git(origin, "config", "user.name", "t")
+ for name, body in {"utils.py": "OLD = 1\n", "gone.py": "x = 1\n", "notes.md": "user file\n"}.items():
+ (origin / name).write_text(body)
+ _git(origin, "add", "-A")
+ _git(origin, "commit", "-qm", "A")
+ (origin / "utils.py").write_text("NEW = 1\n")
+ (origin / "gone.py").unlink()
+ (origin / "newpkg").mkdir()
+ (origin / "newpkg" / "__init__.py").write_text("from utils import NEW\n")
+ _git(origin, "add", "-A")
+ _git(origin, "commit", "-qm", "B")
+ root = tmp_path / "install"
+ _git(tmp_path, "clone", "-q", str(origin), str(root))
+ _git(root, "reset", "-q", "--hard", "HEAD~1")
+ monkeypatch.setattr("hermes_cli.main.PROJECT_ROOT", root)
+ return root, _git(root, "rev-parse", "HEAD"), _git(root, "rev-parse", "origin/main")
+
+
+def _pull(root: Path) -> None:
+ update_cmd._pull_updates(["git"], "main", None, prompt_for_restore=False, gw_input_fn=None,
+ discard_local_changes=False, keep_stash=False)
+
+
+def _kill_mid_pull(root: Path, monkeypatch) -> None:
+ """The fast-forward writes one new file, holds index.lock, and the process dies."""
+ real = update_cmd._git_run
+
+ def dying_git_run(git_cmd, args, *a, **kw):
+ if args[:1] == ["merge"]:
+ (root / "newpkg").mkdir()
+ (root / "newpkg" / "__init__.py").write_text("from utils import NEW\n")
+ (root / ".git" / "index.lock").touch()
+ raise KeyboardInterrupt # SIGKILL: nothing after this line of the updater runs
+ return real(git_cmd, args, *a, **kw)
+
+ monkeypatch.setattr(update_cmd, "_git_run", dying_git_run)
+ with pytest.raises(KeyboardInterrupt):
+ _pull(root)
+ monkeypatch.setattr(update_cmd, "_git_run", real)
+
+
+def test_killed_pull_is_restored_on_next_launch_and_update_reruns(checkout, monkeypatch):
+ root, a, b = checkout
+ (root / "notes.md").write_text("edited while bricked\n") # a path the update never touches
+ _kill_mid_pull(root, monkeypatch)
+ assert _git(root, "rev-parse", "HEAD") == a # the torn state: HEAD old, newpkg already new
+ marker = er.interrupted_pull_marker(root)
+ # A retry in a container gets the killed updater's pid: our own pid is never a live owner.
+ assert f"pid={os.getpid()}" in marker.read_text()
+
+ assert er.restore_interrupted_pull(root) is True, "restored files mean the caller must relaunch"
+
+ assert _git(root, "rev-parse", "HEAD") == a
+ assert _git(root, "status", "--porcelain", "--untracked-files=all") == "M notes.md"
+ assert not (root / "newpkg").exists() and not (root / ".git" / "index.lock").exists()
+ assert not marker.exists()
+ (root / "notes.md").write_text("user file\n")
+ _pull(root) # `hermes update` again: a normal fast-forward
+ assert _git(root, "rev-parse", "HEAD") == b and not marker.exists()
+
+
+def test_pull_marker_of_a_live_updater_is_left_alone(checkout, monkeypatch):
+ root, a, _b = checkout
+ _kill_mid_pull(root, monkeypatch)
+ marker = er.interrupted_pull_marker(root)
+ # Another `hermes` launched while an update is mid-pull must not race its git.
+ marker.write_text(marker.read_text().replace(f"pid={os.getpid()}", f"pid={os.getppid()}"))
+
+ assert er.restore_interrupted_pull(root) is False
+
+ assert marker.exists() and (root / "newpkg" / "__init__.py").exists()
+ assert (root / ".git" / "index.lock").exists()