Skip to content

The agent that grows with you

fix(update): a killed syntax rollback keeps its recovery record until the tree is whole

Teknium2cfa57f70b99
diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.py
index 07c6c1bc688..2c9d7f75081 100644
--- a/hermes_cli/_early_recovery.py
+++ b/hermes_cli/_early_recovery.py
@@ -422,34 +422,61 @@ def _restore_claim(git_dir: Path):
os.close(fd)
-def _held_open(path: Path) -> bool:
- """True when a running process has ``path`` open, the usual sign of a live git owning its lock.
-
- Best effort, not exact: Linux answers through /proc, but a live git that owns ``index.lock`` without
- an open fd (``commit`` waiting in the editor, or between closing the lock and renaming it) reads as
- dead; Windows refuses to unlink a file another process has open, so the caller's unlink is its probe;
- macOS/BSD have no portable check at all. The claim only orders Hermes launches, so on those paths a
- live git's lock can be removed; its command then fails and the marker stays for the next launch.
+def _held_open(path: Path, root: Path | None = None) -> bool | None:
+ """Whether a running process may still own ``path`` (a git lock): True, False, or None (unknowable).
+
+ False is proof, not a guess: Linux reads every process's fds through /proc and also counts any live
+ ``git`` whose working directory is inside ``root`` (``commit`` waiting in the editor keeps
+ ``index.lock`` with its fd closed); macOS/BSD ask ``lsof``. Without either check the answer is None
+ and the caller never deletes the lock. Windows needs no answer here: it refuses to unlink a file
+ another process has open, so the caller's unlink is the probe.
"""
proc = Path("/proc")
- if not (proc / "self" / "fd").is_dir():
- return False
- target = os.path.realpath(path)
- for fd_dir in proc.glob("[0-9]*/fd"):
- try:
- if any(os.readlink(entry.path) == target for entry in os.scandir(fd_dir)):
+ if (proc / "self" / "fd").is_dir():
+ target = os.path.realpath(path)
+ inside = os.path.realpath(root) + os.sep if root is not None else None
+ for pid_dir in proc.glob("[0-9]*"):
+ try:
+ if any(os.readlink(entry.path) == target for entry in os.scandir(pid_dir / "fd")):
+ return True
+ except OSError:
+ pass
+ if inside is None:
+ continue
+ try:
+ comm = (pid_dir / "comm").read_text(encoding="utf-8", errors="replace").strip()
+ cwd = os.readlink(pid_dir / "cwd")
+ except OSError:
+ continue
+ if comm.startswith("git") and (cwd + os.sep).startswith(inside):
return True
- except OSError:
- continue
- return False
+ return False
+ import shutil
+
+ lsof = shutil.which("lsof") or next((p for p in ("/usr/sbin/lsof", "/usr/bin/lsof") if os.path.isfile(p)), None)
+ if lsof is None:
+ return None
+ try:
+ found = subprocess.run([lsof, "-t", "--", str(path)], capture_output=True, text=True, timeout=20,
+ stdin=subprocess.DEVNULL)
+ except (OSError, subprocess.SubprocessError):
+ return None
+ if found.stdout.strip():
+ return True
+ return False if found.returncode in (0, 1) else None # lsof exits 1 when nothing has the file open
+
+def _release_dead_index_lock(git_dir: Path, root: Path | None = None) -> bool:
+ """Drop a killed git's ``index.lock`` (it refuses every git command) once its owner is PROVEN gone.
-def _release_dead_index_lock(git_dir: Path) -> bool:
- """Drop the killed git's ``index.lock`` (it refuses every git command); False while a live git holds it."""
+ False while a live git may hold it, or when this platform cannot prove it dead: the caller then
+ keeps the interrupted-pull marker, so the next launch tries again instead of a rollback being lost.
+ """
lock = git_dir / "index.lock"
deadline = time.monotonic() + 5
while lock.exists():
- if not _held_open(lock):
+ held = None if sys.platform == "win32" else _held_open(lock, root)
+ if held is False or sys.platform == "win32":
try:
lock.unlink()
return True
@@ -457,6 +484,8 @@ def _release_dead_index_lock(git_dir: Path) -> bool:
return True
except PermissionError: # Windows: open in a live process
pass
+ elif held is None:
+ return False
if time.monotonic() > deadline:
return False
time.sleep(0.1)
@@ -648,13 +677,24 @@ def _restore_holding_claim(root: Path, marker: Path, *, after_failure: bool = Fa
**({"text": True, "encoding": "utf-8", "errors": "replace"} if text else {}))
rollback = fields.get("rollback", "").strip()
- if rollback in ("branch", "detach") and pre and target and git("rev-parse", "HEAD").stdout.strip() == target:
+ rollback = rollback if rollback in ("branch", "detach") else ""
+ head = git("rev-parse", "HEAD")
+ if head.returncode != 0:
+ print(f"⚠ Could not read HEAD to repair an interrupted `hermes update` ({head.stderr.strip()}); "
+ "the next launch retries.", file=sys.stderr)
+ return False
+ if rollback and pre and target and head.stdout.strip() == target:
# A syntax rollback killed before it moved HEAD back: redo that step (HEAD and index, no file),
# so the restore below lands on ``pre`` (the code the update started from), not the broken tree.
- if rollback == "detach":
- git("update-ref", "--no-deref", "HEAD", pre)
- git("reset", "-q", pre)
- if not pre or not target or git("rev-parse", "HEAD").stdout.strip() != pre:
+ # Every step is checked, and the killed step's ``index.lock`` goes first, only once its git is
+ # proven gone: until HEAD is on ``pre`` this marker is the rollback's only record.
+ reason = _redo_rollback_head(git, git_dir, root, pre, rollback, after_failure=after_failure)
+ if reason is not None:
+ print(f"⚠ An interrupted `hermes update` rollback to {pre[:10]} cannot resume yet ({reason}); "
+ "the next launch retries.", file=sys.stderr)
+ return False
+ head = git("rev-parse", "HEAD")
+ if not pre or not target or head.stdout.strip() != pre:
marker.unlink() # git finished (HEAD moved) or the marker is unusable
return False
if any((git_dir / name).exists() for name in _GIT_OPERATION_IN_PROGRESS):
@@ -671,12 +711,17 @@ def _restore_holding_claim(root: Path, marker: Path, *, after_failure: bool = Fa
# After a git that EXITED (``after_failure``) no git of ours is left: a lock now is another git's
# (often the very reason ours failed), never ours to drop. The scan below only reads.
foreign_lock = after_failure and (git_dir / "index.lock").exists()
- if not foreign_lock and not _release_dead_index_lock(git_dir):
+ if not foreign_lock and not _release_dead_index_lock(git_dir, root):
print("⚠ A running git holds the index after an interrupted `hermes update`; the next launch "
"finishes the restore.", file=sys.stderr)
return False
written = _paths_git_wrote(git, root, pre, target)
if written is None: # after a gc or re-clone: nothing left to compare against
+ if rollback and not _rollback_verified(git, git_dir, pre):
+ print(f"⚠ An interrupted `hermes update` rollback to {pre[:10]} is not verified and commit "
+ f"{target[:10]} is gone. Inspect `git -C {root} status`; `git -C {root} reset --hard "
+ f"{pre[:10]}` finishes it.", file=sys.stderr)
+ return False
marker.unlink()
print(f"⚠ Ignoring a stale interrupted-update marker: commit {target[:10]} is gone.", file=sys.stderr)
return False
@@ -700,6 +745,13 @@ def _restore_holding_claim(root: Path, marker: Path, *, after_failure: bool = Fa
for rel in sorted(new_dirs, key=lambda d: d.count("/"), reverse=True):
with contextlib.suppress(OSError):
(root / rel).rmdir() # only when empty: an untracked file inside keeps it
+ if rollback and not _rollback_verified(git, git_dir, pre):
+ # A rollback owns the whole tree (the update parked local edits first): only HEAD on ``pre``
+ # with no tracked change left is a finished rollback. Anything less keeps its only record.
+ print(f" ✗ The rollback to {pre[:10]} is not verified yet (tracked files still differ); the next "
+ f"launch retries. Inspect `git -C {root} status`; `git -C {root} reset --hard {pre[:10]}` "
+ "finishes it by hand.", file=sys.stderr)
+ return bool(restore or added)
marker.unlink()
if not restore and not added:
return False # the killed git never reached the tree: nothing to put back
@@ -709,6 +761,37 @@ def _restore_holding_claim(root: Path, marker: Path, *, after_failure: bool = Fa
return True
+def _redo_rollback_head(git, git_dir: Path, root: Path, pre: str, mode: str, *, after_failure: bool) -> str | None:
+ """Move HEAD (and the index) back to ``pre`` for a killed syntax rollback; None, or why not yet.
+
+ The killed step's ``index.lock`` is reclaimed first, and only when its git is proven gone. After a
+ git that exited in this very process (``after_failure``) a lock is never ours to judge.
+ """
+ lock = git_dir / "index.lock"
+ if lock.exists() and (after_failure or not _release_dead_index_lock(git_dir, root)):
+ return "a git may still hold .git/index.lock"
+ if mode == "detach":
+ moved = git("update-ref", "--no-deref", "HEAD", pre)
+ if moved.returncode != 0:
+ return f"git update-ref failed: {(moved.stderr.strip().splitlines() or ['?'])[-1]}"
+ reset = git("reset", "-q", pre)
+ if reset.returncode != 0:
+ return f"git reset failed: {(reset.stderr.strip().splitlines() or ['?'])[-1]}"
+ head = git("rev-parse", "HEAD")
+ if head.returncode != 0 or head.stdout.strip() != pre:
+ return "HEAD did not move back"
+ return None
+
+
+def _rollback_verified(git, git_dir: Path, pre: str) -> bool:
+ """The whole-tree rollback landed: HEAD is ``pre``, no index lock, no tracked change."""
+ head = git("rev-parse", "HEAD")
+ if head.returncode != 0 or head.stdout.strip() != pre or (git_dir / "index.lock").exists():
+ return False
+ status = git("status", "--porcelain", "-z", "--untracked-files=no")
+ return status.returncode == 0 and not status.stdout.strip("\0")
+
+
def _put_back_paths(git, root: Path, restore: list[str], added: list[str]) -> subprocess.CompletedProcess | None:
"""Return ``restore`` to HEAD and drop ``added``; the failed git run, or None."""
if restore:
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index c0a2f5df58a..5aaa46ce48f 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -946,8 +946,13 @@ def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha, *, rollback_branch=N
if rollback_result.returncode == 0:
rollback_args = ["reset", "--hard", pre_pull_sha]
rollback_result = _git_run(git_cmd, rollback_args)
- if rollback_result.returncode == 0:
- _commit.drop_added_files(root, added)
+ if rollback_result.returncode == 0 and not _commit.drop_added_files(root, added):
+ rollback_result = subprocess.CompletedProcess(
+ rollback_args, 1, "", "could not remove the broken release's added files")
+ if rollback_result.returncode == 0 and not _commit.tree_whole_at(git_cmd, root, pre_pull_sha):
+ # git said yes; the tree must agree (HEAD on pre, no tracked change) before the marker goes.
+ rollback_result = subprocess.CompletedProcess(
+ rollback_args, 1, "", f"the checkout is not whole at {pre_pull_sha[:10]}")
if rollback_result.returncode != 0 and _commit.settle_failed_tree_move(root):
rollback_result = subprocess.CompletedProcess(rollback_args, 0, "", "") # restored in-process
if rollback_result.returncode == 0 and parked:
@@ -965,6 +970,8 @@ def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha, *, rollback_branch=N
print(f" cd {root} && git {shlex.join(rollback_args)}")
if rollback_result.stderr.strip():
print(f" ({rollback_result.stderr.strip().splitlines()[0]})")
+ if interrupted_pull_marker(root).is_file():
+ print(f" The next `hermes` launch also finishes the rollback to {pre_pull_sha[:10]} on its own.")
else:
print(" Could not capture pre-pull SHA — recover manually with:")
print(f" cd {_m().PROJECT_ROOT} && git reflog && git reset --hard <prev-sha>")
diff --git a/hermes_cli/update_cmd_commit.py b/hermes_cli/update_cmd_commit.py
index 6d70dcadd5e..11ad7e17a98 100644
--- a/hermes_cli/update_cmd_commit.py
+++ b/hermes_cli/update_cmd_commit.py
@@ -129,17 +129,37 @@ def files_added_by(git_cmd, root: Path, pre: str, target: str | None) -> list[st
return [p for p in cp.stdout.split("\0") if p] if cp.returncode == 0 else []
-def drop_added_files(root: Path, added: list[str]) -> None:
- """Every one is the move's own file: git refuses to move a checkout over an untracked file."""
+def drop_added_files(root: Path, added: list[str]) -> bool:
+ """Every one is the move's own file: git refuses to move a checkout over an untracked file.
+
+ False when one of them is still there (the caller keeps the marker; the restore retries)."""
root = Path(root)
+ gone = True
for rel in added:
- (root / rel).unlink(missing_ok=True)
+ try:
+ (root / rel).unlink(missing_ok=True)
+ except OSError:
+ gone = False
for parent in sorted({p for rel in added for p in Path(rel).parents if str(p) != "."},
key=lambda p: len(p.parts), reverse=True):
try:
(root / parent).rmdir() # only when empty: anything else inside keeps it
except OSError:
pass
+ return gone and not any(os.path.lexists(root / rel) for rel in added)
+
+
+def tree_whole_at(git_cmd, root: Path, sha: str) -> bool:
+ """HEAD is ``sha``, no ``index.lock`` is left and no tracked file differs from it."""
+ def run(*args: str) -> subprocess.CompletedProcess:
+ return subprocess.run([*git_cmd, *args], cwd=str(root), capture_output=True, text=True, encoding="utf-8",
+ errors="replace", stdin=subprocess.DEVNULL, timeout=120)
+
+ head = run("rev-parse", "-q", "--verify", "HEAD")
+ if head.returncode != 0 or head.stdout.strip() != sha or (interrupted_pull_marker(Path(root)).parent / "index.lock").exists():
+ return False
+ status = run("status", "--porcelain", "-z", "--untracked-files=no")
+ return status.returncode == 0 and not status.stdout.strip("\0")
def settle_failed_tree_move(root: Path) -> bool:
diff --git a/tests/hermes_cli/test_update_interrupted_pull.py b/tests/hermes_cli/test_update_interrupted_pull.py
index 25a89925d11..dfb32ffd662 100644
--- a/tests/hermes_cli/test_update_interrupted_pull.py
+++ b/tests/hermes_cli/test_update_interrupted_pull.py
@@ -9,6 +9,7 @@ checkout import) puts the old tree back so ``hermes update`` can simply run agai
from __future__ import annotations
import os
+import shutil
import subprocess
import sys
from pathlib import Path
@@ -306,3 +307,104 @@ def test_concurrent_launches_take_turns_and_all_rerun_from_the_restored_tree(tmp
assert _git(root, "status", "--porcelain", "--untracked-files=all") == f"M {names[-1]}"
assert (root / names[-1]).read_text(encoding="utf-8") == "user edit\n"
assert not marker.exists()
+
+
+def _broken_release(tmp_path: Path, nfiles: int) -> tuple[Path, str, str]:
+ """A checkout whose HEAD is a release with an uncompilable module (``target``) over ``pre``."""
+ root = tmp_path / "install"
+ root.mkdir()
+ _git(root, "init", "-q", "-b", "main")
+ _git(root, "config", "user.email", "[email protected]")
+ _git(root, "config", "user.name", "t")
+ (root / "module.py").write_text("good = True\n", encoding="utf-8", newline="")
+ (root / "bulk").mkdir()
+ for i in range(nfiles): # enough index work that git holds index.lock long enough to be killed
+ (root / "bulk" / f"f{i}.txt").write_text(f"{i}\n", encoding="utf-8", newline="")
+ _git(root, "add", "-A")
+ _git(root, "commit", "-qm", "pre")
+ pre = _git(root, "rev-parse", "HEAD")
+ (root / "module.py").write_text("def broken(:\n", encoding="utf-8", newline="")
+ (root / "added.py").write_text("X = 1\n", encoding="utf-8", newline="")
+ for i in range(0, nfiles, 2):
+ (root / "bulk" / f"f{i}.txt").write_text(f"{i} new\n", encoding="utf-8", newline="")
+ _git(root, "add", "-A")
+ _git(root, "commit", "-qm", "broken target")
+ return root, pre, _git(root, "rev-parse", "HEAD")
+
+
+def _rollback_marker(root: Path, pre: str, target: str) -> Path:
+ marker = er.interrupted_pull_marker(root)
+ marker.write_text(f"pid=0\npre={pre}\ntarget={target}\nstash=\nrollback=branch\n", encoding="utf-8", newline="")
+ return marker
+
+
+def _sigkill_git_once_index_lock_exists(root: Path, *args: str) -> int:
+ """Run a real git and SIGKILL it the moment inotify reports ``.git/index.lock`` created."""
+ import ctypes
+ import signal
+ import struct
+
+ libc = ctypes.CDLL(None, use_errno=True)
+ fd = libc.inotify_init1(0)
+ assert fd >= 0 and libc.inotify_add_watch(fd, str(root / ".git").encode(), 0x100) >= 0 # IN_CREATE
+ git = subprocess.Popen(["git", "-C", str(root), *args], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ try:
+ while git.poll() is None:
+ buf, i = os.read(fd, 4096), 0
+ while i < len(buf):
+ length = struct.unpack_from("iIII", buf, i)[3]
+ name, i = buf[i + 16:i + 16 + length].rstrip(b"\0"), i + 16 + length
+ if name == b"index.lock":
+ os.kill(git.pid, signal.SIGKILL)
+ return git.wait()
+ return git.wait()
+ finally:
+ os.close(fd)
+
+
[email protected](not sys.platform.startswith("linux"), reason="inotify kill cell")
+def test_a_rollback_killed_inside_its_reset_is_finished_by_the_next_launch(tmp_path):
+ """The syntax rollback's own ``git reset -q pre`` is SIGKILLed holding ``index.lock``: HEAD is still the
+ broken release. The next launch must reclaim that dead lock, redo the rollback and land on ``pre``
+ whole; the marker (the rollback's only record) may go only then."""
+ for attempt in range(10):
+ cell = tmp_path / f"try{attempt}"
+ cell.mkdir()
+ root, pre, target = _broken_release(cell, 3000)
+ marker = _rollback_marker(root, pre, target)
+ _sigkill_git_once_index_lock_exists(root, "reset", "-q", pre)
+ if (root / ".git" / "index.lock").exists() and _git(root, "rev-parse", "HEAD") == target:
+ break
+ else:
+ pytest.fail("harness: the SIGKILL never landed while git held index.lock")
+
+ assert er.restore_interrupted_pull(root) is True, "the broken files were put back: the caller relaunches"
+ assert _git(root, "rev-parse", "HEAD") == pre
+ assert _git(root, "status", "--porcelain", "--untracked-files=all") == ""
+ assert (root / "module.py").read_text(encoding="utf-8") == "good = True\n"
+ assert not (root / ".git" / "index.lock").exists() and not marker.exists()
+
+
+def test_a_rollback_marker_outlives_a_lock_that_may_still_be_live(tmp_path):
+ """While a live process holds ``index.lock`` the rollback cannot resume: HEAD stays on the broken
+ release, so the marker must stay too (never 'git finished'), and the lock is not stolen. Once the
+ holder is gone the next launch finishes the rollback."""
+ root, pre, target = _broken_release(tmp_path, 20)
+ marker = _rollback_marker(root, pre, target)
+ lock = root / ".git" / "index.lock"
+ holder = subprocess.Popen([sys.executable, "-c", "import sys, time; f = open(sys.argv[1], 'w'); "
+ "print('held', flush=True); time.sleep(120)", str(lock)],
+ stdout=subprocess.PIPE, text=True)
+ try:
+ assert holder.stdout.readline().strip() == "held"
+ assert er.restore_interrupted_pull(root) is False
+ assert marker.exists(), "a rollback that could not run erased its own recovery record"
+ assert lock.exists() and _git(root, "rev-parse", "HEAD") == target
+ finally:
+ holder.kill()
+ holder.wait()
+ if sys.platform == "darwin" and not shutil.which("lsof"):
+ pytest.skip("no lsof: the dead lock cannot be proven dead here")
+ assert er.restore_interrupted_pull(root) is True
+ assert _git(root, "rev-parse", "HEAD") == pre and not marker.exists() and not lock.exists()
+ assert _git(root, "status", "--porcelain", "--untracked-files=no") == ""