Skip to content

The agent that grows with you

fix(update): the start-of-update index.lock reclaim never takes a live git's lock

Tekniumaa4507388e87
diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.py
index 4ecf2662f04..a60f526875f 100644
--- a/hermes_cli/_early_recovery.py
+++ b/hermes_cli/_early_recovery.py
@@ -545,73 +545,206 @@ class _Holder(str):
"""A process that may own a git lock, e.g. ``pid 4242 (git commit)``: truthy, and never ``is True``."""
-# Git subcommands that can keep ``index.lock`` (or a ref lock) with its fd CLOSED while they wait
-# (``commit``/``merge``/``rebase``/``tag``... in the editor). A reader in the tree (``git log`` in a
-# pager, ``git status``, ``gitstatusd``, the fsmonitor daemon) is not one: while it really holds a lock
-# its open fd names it.
-_LOCK_KEEPING_GIT = frozenset({
- "am", "cherry-pick", "commit", "merge", "pull", "rebase", "revert", "stash", "tag", "notes",
+# Git subcommands that only read: none takes ``index.lock`` and then waits with its fd CLOSED. Every
+# other git (``commit``/``merge``/``rebase``/``am``/``stash``... in the editor or a hook, a dashed
+# ``git-commit`` from git-core, an alias, a wrapper, a third-party ``git-<tool>``, a git whose
+# subcommand cannot be read) may hold ``index.lock`` with no fd naming it, so it counts as a holder.
+# A reader (a paged ``git log``, ``cat-file --batch``, a background ``fetch``) counts only while its
+# fd is on the lock.
+_READER_GIT = frozenset({
+ "annotate", "blame", "cat-file", "check-attr", "check-ignore", "check-mailmap", "check-ref-format",
+ "cherry", "count-objects", "describe", "diff", "diff-files", "diff-index", "diff-tree",
+ "for-each-ref", "fsmonitor--daemon", "grep", "help", "log", "ls-files", "ls-remote", "ls-tree",
+ "merge-base", "name-rev", "range-diff", "rev-list", "rev-parse", "shortlog", "show", "show-branch",
+ "show-ref", "status", "var", "verify-commit", "verify-tag", "version", "whatchanged",
+ "credential", "credential-cache", "credential-store",
+ # Transfers write objects and refs, never the index.
+ "fetch", "fetch-pack", "http-fetch", "index-pack", "pack-objects", "remote-http", "remote-https",
+ "upload-pack",
})
+# Global options that take the NEXT argument as their value (``git -C <dir> -c k=v commit``).
+_GIT_VALUE_OPTIONS = frozenset({
+ "-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env", "--super-prefix", "--attr-source",
+})
+# What points a git at a repository other than its cwd.
+_GIT_LOCATION_ENV = ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR")
+
+
+def _git_program(arg0: str) -> str | None:
+ """``git`` or ``git-<sub>`` when ``arg0`` (an argv[0], a comm, a psutil name) runs git, else None.
+
+ Any directory (``/usr/lib/git-core/git-commit``), either separator, ``.exe`` and case folded:
+ Windows runs ``git.exe`` and ``git-commit.exe``."""
+ name = re.split(r"[\\/]", arg0.strip())[-1].lower()
+ name = name[:-4] if name.endswith(".exe") else name
+ return name if name == "git" or name.startswith("git-") else None
+
+def _git_argv(cmdline: bytes | list[str]) -> list[str]:
+ if isinstance(cmdline, bytes):
+ return [a.decode("utf-8", "replace") for a in cmdline.split(b"\0") if a]
+ return [str(a) for a in cmdline if a]
-def _git_subcommand_of(cmdline: bytes) -> str | None:
- args = [a.decode("utf-8", "replace") for a in cmdline.split(b"\0") if a][1:]
- it = iter(args)
+
+def _git_subcommand_of(cmdline: bytes | list[str]) -> str | None:
+ """The subcommand a git argv runs: ``commit`` for ``git -C x -c k=v commit`` and for a dashed
+ ``/usr/lib/git-core/git-commit`` (``git-commit.exe``); None when argv[0] is not git or names none."""
+ args = _git_argv(cmdline)
+ program = _git_program(args[0]) if args else None
+ if program is None:
+ return None
+ if program != "git":
+ return program[len("git-"):]
+ it = iter(args[1:])
for arg in it:
- if arg in ("-c", "-C", "--git-dir", "--work-tree", "--namespace", "--exec-path", "--config-env"):
+ if arg in _GIT_VALUE_OPTIONS:
next(it, None)
elif not arg.startswith("-"):
return arg
return None
-def _held_open(path: Path, root: Path | None = None) -> _Holder | bool | None:
+def _checkout_places(*paths: Path | str | None) -> tuple[str, ...]:
+ """The checkout's own paths as given AND resolved, so another process's path need not be resolved."""
+ places = {os.path.normcase(os.path.normpath(os.path.abspath(p))) for p in paths if p is not None}
+ places |= {os.path.normcase(os.path.realpath(p)) for p in paths if p is not None}
+ return tuple(sorted(places))
+
+
+def _path_within(path: str, places: tuple[str, ...]) -> bool:
+ """``path`` is one of ``places`` or under it, by PATH COMPONENTS (``/x/hermes-backup`` is not in ``/x/hermes``).
+
+ Lexical: another process's cwd is already the kernel's resolved path, and resolving a stranger's
+ path would touch whatever it names."""
+ if not os.path.isabs(path):
+ return False
+ lexical = os.path.normcase(os.path.normpath(path))
+ for place in places:
+ try:
+ if os.path.commonpath([lexical, place]) == place:
+ return True
+ except ValueError: # another drive
+ continue
+ return False
+
+
+def git_works_in(args: list[str], cwd: str | None, env: dict[str, str] | None, places: tuple[str, ...]) -> bool:
+ """A git with this argv/cwd/environment works in ``places``: its cwd, a path argument (absolute,
+ or relative to its cwd, ``--opt=<path>`` too) or a ``GIT_DIR``-style variable is inside one."""
+ def inside(value: str) -> bool:
+ if not value:
+ return False
+ if not os.path.isabs(value):
+ if not cwd:
+ return False
+ value = os.path.join(cwd, value)
+ return _path_within(value, places)
+
+ if cwd and _path_within(cwd, places):
+ return True
+ for arg in args[1:]:
+ if inside(arg.partition("=")[2] if arg.startswith("-") else arg):
+ return True
+ return any(inside((env or {}).get(key, "")) for key in _GIT_LOCATION_ENV)
+
+
+def _could_write(uid: int | None, git_dir: Path) -> bool:
+ """A process running as ``uid`` may write ``git_dir`` (root, its owner, or a group/world-writable dir)."""
+ try:
+ st = os.stat(git_dir)
+ except OSError:
+ return True
+ return uid is None or uid in (0, st.st_uid) or bool(st.st_mode & 0o022)
+
+
+def _held_open(path: Path, root: Path | None = None, *, any_git: bool = False) -> _Holder | bool | None:
"""Whether a running process may still own ``path`` (a git lock): the holder, False, or None (unknowable).
The holder is a truthy :class:`_Holder` naming it (``pid 4242 (git commit)``). False is proof, not
- a guess: Linux reads every process's fds through /proc and also counts any live ``git`` working
- inside ``root`` whose subcommand can keep ``index.lock`` with its fd closed (``commit`` waiting in
- the editor, :data:`_LOCK_KEEPING_GIT`); readers there (a paged ``git log``, ``gitstatusd``, the
- fsmonitor daemon) only count while their fd is on the lock. 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.
+ a guess: Linux reads every process's fds through /proc and, with ``root``, also counts any live git
+ working in the checkout (cwd, a path argument or ``GIT_DIR``) that is not a pure reader
+ (:data:`_READER_GIT`; ``any_git`` counts readers too), whatever form runs it: ``git commit``
+ waiting in the editor has CLOSED its lock fd, and a dashed ``git-commit``, an alias or ``git.exe``
+ is the same git. A git that could write the git dir but whose cwd or environment cannot be read
+ makes the answer None. macOS/BSD ask ``lsof`` for open fds and ``ps`` for any such git (``ps``
+ cannot say where it works, so any counts). 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.
"""
+ if (Path("/proc") / "self" / "fd").is_dir():
+ return _held_open_proc(path, root, any_git)
+ return _held_open_lsof(path, root, any_git)
+
+
+# Daemons a git spawns that outlive it, often with the checkout as cwd, and never take the index
+# lock: even ``any_git`` ignores them, or one cached credential would keep a dead lock for hours.
+_NEVER_LOCKS = frozenset({"credential-cache--daemon", "fsmonitor--daemon"})
+
+
+def _counts_as_holder(args: list[str], any_git: bool) -> bool:
+ sub = _git_subcommand_of(args)
+ return sub not in _NEVER_LOCKS and (any_git or sub not in _READER_GIT)
+
+
+def _held_open_proc(path: Path, root: Path | None, any_git: bool) -> _Holder | bool | None:
proc = Path("/proc")
- 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
+ target = os.path.realpath(path)
+ places = _checkout_places(root, path.parent) if root is not None else None
+ unknowable = False
- def name(pid_dir: Path) -> str:
- try:
- argv = (pid_dir / "cmdline").read_bytes().split(b"\0")
- words = [a.decode("utf-8", "replace") for a in argv if a][:3]
- if words:
- return " ".join([os.path.basename(words[0]), *words[1:]])
- except OSError:
- pass
- try:
- return (pid_dir / "comm").read_bytes().decode("ascii", "replace").strip() # /proc: Linux only
- except OSError:
- return "?"
+ def name(args: list[str], pid_dir: Path) -> str:
+ if args:
+ return " ".join([os.path.basename(args[0]), *args[1:3]])
+ try:
+ return (pid_dir / "comm").read_bytes().decode("ascii", "replace").strip() # /proc: Linux only
+ except OSError:
+ return "?"
- 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 _Holder(f"pid {pid_dir.name} ({name(pid_dir)})")
- except OSError:
- pass
- if inside is None:
- continue
- try:
- comm = (pid_dir / "comm").read_bytes().decode("ascii", "replace").strip()
- cwd = os.readlink(pid_dir / "cwd")
- cmdline = (pid_dir / "cmdline").read_bytes()
- except OSError:
- continue
- if comm == "git" and (cwd + os.sep).startswith(inside) \
- and _git_subcommand_of(cmdline) in _LOCK_KEEPING_GIT:
- return _Holder(f"pid {pid_dir.name} ({name(pid_dir)})")
- return False
+ for pid_dir in proc.glob("[0-9]*"):
+ try:
+ if any(os.readlink(entry.path) == target for entry in os.scandir(pid_dir / "fd")):
+ try:
+ args = _git_argv((pid_dir / "cmdline").read_bytes())
+ except OSError:
+ args = []
+ return _Holder(f"pid {pid_dir.name} ({name(args, pid_dir)})")
+ except OSError:
+ pass
+ if places is None:
+ continue
+ try:
+ uid = pid_dir.stat().st_uid
+ except OSError:
+ continue # exited
+ try:
+ args = _git_argv((pid_dir / "cmdline").read_bytes())
+ comm = (pid_dir / "comm").read_bytes().decode("ascii", "replace").strip()
+ except OSError:
+ if pid_dir.exists() and _could_write(uid, path.parent):
+ unknowable = True # hidden from us (hidepid) yet able to write here: it may be a git
+ continue
+ if not args:
+ continue # a zombie or a kernel thread holds nothing
+ if _git_program(args[0]) is None and _git_program(comm) is None:
+ continue
+ if int(pid_dir.name) == os.getpid() or not _counts_as_holder(args, any_git):
+ continue
+ try:
+ cwd = os.readlink(pid_dir / "cwd").removesuffix(" (deleted)")
+ env = dict(entry.decode("utf-8", "replace").partition("=")[::2]
+ for entry in (pid_dir / "environ").read_bytes().split(b"\0") if entry)
+ except OSError:
+ if git_works_in(args, None, None, places):
+ return _Holder(f"pid {pid_dir.name} ({name(args, pid_dir)})")
+ if pid_dir.exists() and _could_write(uid, path.parent):
+ unknowable = True # a lock-keeping git we cannot place may be working here
+ continue
+ if git_works_in(args, cwd, env, places):
+ return _Holder(f"pid {pid_dir.name} ({name(args, pid_dir)})")
+ return None if unknowable else False
+
+
+def _held_open_lsof(path: Path, root: Path | None, any_git: bool) -> _Holder | bool | None:
import shutil
lsof = shutil.which("lsof") or next((p for p in ("/usr/sbin/lsof", "/usr/bin/lsof") if os.path.isfile(p)), None)
@@ -627,7 +760,42 @@ def _held_open(path: Path, root: Path | None = None) -> _Holder | bool | None:
if pids:
names = [line[1:] for line in found.stdout.splitlines() if line.startswith("c")]
return _Holder(f"pid {pids[0]} ({names[0] if names else '?'})")
- return False if found.returncode in (0, 1) else None # lsof exits 1 when nothing has the file open
+ if found.returncode not in (0, 1): # lsof exits 1 when nothing has the file open
+ return None
+ return False if root is None else _ps_git_holder(path.parent, any_git)
+
+
+def _ps_git_holder(git_dir: Path, any_git: bool) -> _Holder | bool | None:
+ """An empty ``lsof`` is no proof: ``git commit`` waiting in the editor has closed its lock fd.
+ ``ps`` cannot say where a git works, so every git (by executable name, dashed forms included)
+ that could write ``git_dir`` and is not a pure reader keeps the lock."""
+ def ps(*columns: str) -> list[list[str]] | None:
+ try:
+ out = subprocess.run(["ps", "-A", *(f"-o{c}=" for c in columns)], capture_output=True,
+ text=True, encoding="utf-8", errors="replace",
+ timeout=20, stdin=subprocess.DEVNULL)
+ except (OSError, subprocess.SubprocessError):
+ return None
+ if out.returncode != 0:
+ return None
+ return [line.split(None, len(columns) - 1) for line in out.stdout.splitlines() if line.strip()]
+
+ named = ps("pid", "uid", "comm") # comm: the executable (``/usr/libexec/git-core/git-commit``)
+ commands = ps("pid", "command")
+ if named is None or commands is None:
+ return None
+ argv = {row[0]: row[1].split() for row in commands if len(row) == 2}
+ for row in named:
+ if len(row) != 3 or not (row[0].isdigit() and row[1].isdigit()) or int(row[0]) == os.getpid():
+ continue
+ if _git_program(row[2]) is None and not (argv.get(row[0]) and _git_program(argv[row[0]][0])):
+ continue
+ args = argv.get(row[0]) or [row[2]]
+ if _git_program(args[0]) is None:
+ args = [row[2]] # an argv[0] with spaces: no subcommand, so it counts
+ if _could_write(int(row[1]), git_dir) and _counts_as_holder(args, any_git):
+ return _Holder(f"pid {row[0]} ({' '.join([os.path.basename(args[0]), *args[1:3]])})")
+ return False
def _index_lock_holder(git_dir: Path, root: Path | None) -> str:
@@ -636,16 +804,17 @@ def _index_lock_holder(git_dir: Path, root: Path | None) -> str:
return f"a running git ({held})" if isinstance(held, _Holder) else "a running git"
-def _release_dead_index_lock(git_dir: Path, root: Path | None = None) -> bool:
+def _release_dead_index_lock(git_dir: Path, root: Path | None = None, *, any_git: bool = False) -> bool:
"""Drop a killed git's ``index.lock`` (it refuses every git command) once its owner is PROVEN gone.
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.
+ ``any_git``: every git working in ``root`` keeps it, readers included (:func:`_held_open`).
"""
lock = git_dir / "index.lock"
deadline = time.monotonic() + 5
while lock.exists():
- held = None if sys.platform == "win32" else _held_open(lock, root)
+ held = None if sys.platform == "win32" else _held_open(lock, root, any_git=any_git)
if held is False or sys.platform == "win32":
try:
lock.unlink()
diff --git a/hermes_cli/gitlock.py b/hermes_cli/gitlock.py
index 94d615eb9c9..ff420c396a0 100644
--- a/hermes_cli/gitlock.py
+++ b/hermes_cli/gitlock.py
@@ -113,12 +113,17 @@ def release_dead_index_lock(repo_root: Path) -> bool:
A git killed while it held the index lock (an update's tree killed by the user, a probe killed
by its own timeout) leaves it behind, and every later merge/stash/reset refuses with "File
exists". The age floor above keeps such a lock for 10 minutes, so the next ``hermes update``
- died at its fast-forward (#132089; the Windows crash cell ``mid_fetch``). Ownership is the
- launch-time repair's proof (``_early_recovery._release_dead_index_lock``): a live holder keeps
- it. Windows can only prove it by the unlink, which a lock-keeping git with its fd closed (a
- ``git commit`` waiting in the editor) would not stop, so there a git working in this checkout
- keeps it. An interrupted tree move owns its own lock judgement, so its marker defers to that
- repair.
+ died at its fast-forward (#132089; the Windows crash cell ``mid_fetch``).
+
+ Two conditions, both required. A killed update run must be behind the lock
+ (:func:`_killed_update_owns`): necessary, never sufficient, since a user's ``git commit`` can take
+ the lock after that run died. And no git of ANY form may be working in this checkout: a
+ ``git commit`` waiting in the editor has closed its lock fd, so an absent fd proves nothing, and
+ it runs as ``git``, a dashed ``git-commit``, an alias or ``git.exe``. Linux reads every process's
+ cwd, path arguments and ``GIT_DIR`` through /proc (``_early_recovery._held_open`` with
+ ``any_git``); macOS keeps the lock while any git runs (``ps`` cannot say where); Windows scans
+ with psutil (:func:`_windows_git_in_checkout`). Whatever cannot be read keeps the lock. An
+ interrupted tree move owns its own lock judgement, so its marker defers to that repair.
"""
from hermes_cli._early_recovery import _git_dir, _release_dead_index_lock, interrupted_pull_marker
@@ -127,53 +132,101 @@ def release_dead_index_lock(repo_root: Path) -> bool:
lock = git_dir / "index.lock"
if not lock.exists() or interrupted_pull_marker(root).exists():
return False
- # No holder is not proof of a dead one: a git that just created the lock may not have it
- # open yet. Only a lock a killed update left is ours to take; anything else waits for the
- # age-floor sweep and the update refuses on it truthfully.
if not _killed_update_owns(lock):
return False
if os.name == "nt" and _windows_git_in_checkout(root) is not False:
return False
- return _release_dead_index_lock(git_dir, root)
+ return _release_dead_index_lock(git_dir, root, any_git=True)
-def _killed_update_owns(lock: Path) -> bool:
- """The latest update run died without finishing and ``lock`` was created after it started."""
+def _receipt_time(value: object) -> Optional[float]:
from datetime import datetime
- from hermes_cli.update_receipt import _owner_alive, read_latest_receipt
+ try:
+ return datetime.fromisoformat(str(value)).timestamp()
+ except (TypeError, ValueError):
+ return None
+
+
+def _killed_update_owns(lock: Path) -> bool:
+ """The last update run that started before ``lock`` was written died unfinished, its processes gone.
+
+ Read from the durable per-run records (read-only), not only ``latest.json``: a retry that kept
+ the then-live lock and failed replaced ``latest.json``, and the killed run's evidence must
+ still stand once the lock's git is gone. A run that started after the lock was written cannot
+ have left it, so a later run never discharges an earlier killed one.
+ """
+ import json
- latest = read_latest_receipt() or {}
- if latest.get("outcome") not in ("running", "interrupted") or _owner_alive(latest):
+ from hermes_cli import update_receipt
+
+ try:
+ written = lock.stat().st_mtime
+ except OSError:
return False
+ records: list[dict] = []
try:
- started = datetime.fromisoformat(str(latest.get("started_at"))).timestamp()
- return lock.stat().st_mtime >= started
- except (OSError, ValueError):
+ for directory in update_receipt._receipt_dirs():
+ for path in directory.glob("update_*.json"):
+ try:
+ record = json.loads(path.read_text(encoding="utf-8-sig"))
+ except (OSError, ValueError):
+ continue
+ if isinstance(record, dict):
+ records.append(record)
+ except OSError:
+ pass
+ latest = update_receipt.read_latest_receipt()
+ if isinstance(latest, dict):
+ records.append(latest) # a store from before per-run records
+ runs: dict[str, tuple[float, dict]] = {}
+ for record in records:
+ started = _receipt_time(record.get("started_at"))
+ if started is None or started > written:
+ continue
+ key = str(record.get("update_id") or id(record))
+ held = runs.get(key)
+ # One run, several copies (its archive, latest.json, a profile mirror): a terminal copy wins.
+ if held is None or (held[1].get("outcome") in ("running", "interrupted")
+ and record.get("outcome") not in ("running", "interrupted")):
+ runs[key] = (started, record)
+ if not runs:
return False
+ _started, last = max(runs.values(), key=lambda run: run[0])
+ return last.get("outcome") in ("running", "interrupted") and not update_receipt._owner_alive(last)
def _windows_git_in_checkout(root: Path) -> "bool | None":
- """Whether a ``git.exe`` works in ``root`` (its cwd or argv names it); None when unknowable.
+ """Whether any git (``git.exe``, a dashed ``git-<sub>.exe``) works in ``root``; None when unknowable.
- Scoped to the checkout: a system-wide check would keep the lock whenever any editor or
- terminal elsewhere runs git, which on Windows is most of the time.
+ Works in: its cwd, a path argument or a ``GIT_DIR``-style variable is inside the checkout or
+ its git dir, compared by path components (``hermes-backup`` is not inside ``hermes``). Scoped to
+ the checkout: a system-wide check would keep the lock whenever any editor or terminal elsewhere
+ runs git, which on Windows is most of the time. A git whose cwd cannot be read keeps the lock.
"""
+ from hermes_cli._early_recovery import _NEVER_LOCKS, _checkout_places, _git_dir, _git_program, \
+ _git_subcommand_of, git_works_in
+
try:
import psutil
except ImportError:
return None
- inside = os.path.normcase(os.path.realpath(root))
+ places = _checkout_places(root, _git_dir(Path(root)))
try:
- for proc in psutil.process_iter(["name", "cwd", "cmdline"]):
- if (proc.info.get("name") or "").lower() != "git.exe":
+ for proc in psutil.process_iter(["pid", "name", "cwd", "cmdline", "environ"]):
+ info = proc.info
+ if info.get("pid") == os.getpid():
continue
- cwd = proc.info.get("cwd")
- if not cwd:
- return None # a git we cannot inspect may be working here
- places = [cwd, *(arg for arg in proc.info.get("cmdline") or () if os.path.isabs(arg))]
- if any(os.path.normcase(os.path.realpath(place)).startswith(inside) for place in places):
+ args = [str(a) for a in info.get("cmdline") or () if a]
+ if _git_program(info.get("name") or "") is None and not (args and _git_program(args[0])):
+ continue
+ if _git_subcommand_of(args or [info.get("name") or ""]) in _NEVER_LOCKS:
+ continue
+ cwd = info.get("cwd")
+ if git_works_in(args or [info.get("name") or "git"], cwd, info.get("environ"), places):
return True
+ if not cwd and proc.is_running():
+ return None # a git we cannot inspect may be working here
except Exception: # health: allow BLE001 -- a failed scan keeps the lock, never drops it
return None
return False
diff --git a/tests/hermes_cli/test_gitlock.py b/tests/hermes_cli/test_gitlock.py
index bbd6d3ae9d3..5cecf353553 100644
--- a/tests/hermes_cli/test_gitlock.py
+++ b/tests/hermes_cli/test_gitlock.py
@@ -339,9 +339,14 @@ def _status_blocked_on_a_fifo(repo: Path, *argv: str) -> subprocess.Popen:
proc = subprocess.Popen(["git", *argv, "status", "--porcelain"], cwd=repo,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
deadline = time.monotonic() + 20
- while not (repo / ".git" / "index.lock").exists():
- assert proc.poll() is None and time.monotonic() < deadline, "git status never took index.lock"
- time.sleep(0.05)
+ try:
+ while not (repo / ".git" / "index.lock").exists():
+ assert proc.poll() is None and time.monotonic() < deadline, "git status never took index.lock"
+ time.sleep(0.05)
+ except BaseException:
+ proc.kill() # never leave the blocked git behind a failed setup
+ proc.wait()
+ raise
return proc
@@ -390,5 +395,133 @@ def _killed_update_receipt() -> None:
update_receipt.begin_update_receipt()
current = update_receipt._current.get()
current.data.update(pid=dead.pid, pid_create_time=None, writer_pid=dead.pid, writer_create_time=None)
- update_receipt._write_latest((json.dumps(current.data) + "\n").encode("utf-8"))
+ payload = (json.dumps(current.data) + "\n").encode("utf-8")
+ for stale in update_receipt._receipt_dir().glob(f"update_*_{current.data['update_id']}.json"):
+ stale.unlink() # the run's own archive, as its dead process last wrote it
+ update_receipt._run_file(update_receipt._receipt_dir(), current.data).write_bytes(payload)
+ update_receipt._write_latest(payload)
update_receipt._current.set(None)
+
+
+def _git_in_the_editor(repo: Path, tmp_path: Path, argv: list[str]) -> subprocess.Popen:
+ """A real ``git commit`` form holding ``index.lock`` while its editor waits: the lock fd is CLOSED."""
+ import sys
+
+ editor = tmp_path / "editor.py"
+ editor.write_text("import sys, time\nfrom pathlib import Path\n"
+ "Path(sys.argv[1] + '.ready').write_text('')\n"
+ "while not Path(sys.argv[1] + '.go').exists(): time.sleep(0.02)\n"
+ "Path(sys.argv[1]).write_text('fixture\\n')\n", encoding="utf-8")
+ (repo / "a.txt").write_text("changed\n")
+ proc = subprocess.Popen(argv, cwd=repo, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ env={**os.environ, "GIT_EDITOR": f"{sys.executable} {editor}"})
+ msg = repo / ".git" / "COMMIT_EDITMSG"
+ deadline = time.monotonic() + 20
+ while not Path(f"{msg}.ready").exists():
+ if proc.poll() is not None or time.monotonic() > deadline:
+ proc.kill()
+ proc.wait()
+ raise AssertionError(f"{argv} never reached its editor")
+ time.sleep(0.02)
+ return proc
+
+
[email protected](not Path("/proc/self/fd").is_dir(), reason="ownership proof via /proc (Linux)")
[email protected]("form", ["dashed git-commit in the editor", "a reader git in the checkout"])
+def test_a_killed_updates_lock_stays_while_any_git_works_in_the_checkout(repo: Path, tmp_path: Path, form) -> None:
+ """Review P1: the killed-update receipt plus a younger lock let the reclaim delete the lock of a
+ live ``/usr/lib/git-core/git-commit -a`` waiting in its editor (fd closed, and not ``comm == git``):
+ the user's commit then died "unable to write new index file". No git of any form may be working in
+ the checkout when the start-of-update reclaim takes the lock."""
+ from hermes_cli.gitlock import release_dead_index_lock
+
+ lock = repo / ".git" / "index.lock"
+ _killed_update_receipt()
+ if form.startswith("dashed"):
+ exec_path = subprocess.run(["git", "--exec-path"], capture_output=True, text=True, check=True).stdout.strip()
+ dashed = Path(exec_path) / "git-commit"
+ if not dashed.exists():
+ pytest.skip("this git ships no dashed git-commit")
+ proc = _git_in_the_editor(repo, tmp_path, [str(dashed), "-a"])
+ assert lock.exists(), "premise: git commit holds index.lock in its editor"
+ else:
+ lock.write_bytes(b"")
+ proc = subprocess.Popen(["git", "cat-file", "--batch"], cwd=repo, stdin=subprocess.PIPE,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ try:
+ assert release_dead_index_lock(repo) is False
+ assert lock.exists(), f"{form}: the reclaim deleted a lock a live git may own"
+ finally:
+ Path(f"{repo / '.git' / 'COMMIT_EDITMSG'}.go").write_text("")
+ if form.startswith("dashed"):
+ assert proc.wait(timeout=20) == 0, "the user's commit failed"
+ else:
+ proc.kill()
+ proc.wait()
+ if not form.startswith("dashed"):
+ assert release_dead_index_lock(repo) is True, "once the checkout's git is gone the killed update's lock goes"
+
+
+def test_lock_keeping_git_is_recognised_in_every_form_and_by_path_components(tmp_path: Path, monkeypatch) -> None:
+ """Review P1/secondary, the hosts with no /proc: the macOS branch had only an (empty) ``lsof``,
+ and the Windows scan matched ``git.exe`` alone and compared paths with ``startswith``
+ (``hermes-backup`` read as inside ``hermes``). Injected process metadata, not a native run."""
+ import types
+
+ from hermes_cli import _early_recovery as er
+ from hermes_cli import gitlock
+
+ assert er._git_subcommand_of(b"/usr/lib/git-core/git-commit\0-a\0") == "commit"
+ assert er._git_subcommand_of(["C:\\Git\\mingw64\\libexec\\git-core\\GIT-COMMIT.EXE"]) == "commit"
+ assert er._git_subcommand_of(["git", "-C", "x", "-c", "k=v", "--no-pager", "save", "-a"]) == "save"
+
+ root = tmp_path / "hermes"
+ (root / ".git").mkdir(parents=True)
+ (tmp_path / "hermes-backup").mkdir()
+ lock = root / ".git" / "index.lock"
+ lock.write_bytes(b"")
+
+ def ps_lists(command: str):
+ def run(argv, **_kw):
+ if argv[0] == "lsof":
+ return subprocess.CompletedProcess(argv, 1, "", "")
+ rows = (f"4242 {getattr(os, 'getuid', lambda: 0)()} {command.split()[0]}" if "-ocomm=" in argv else f"4242 {command}")
+ return subprocess.CompletedProcess(argv, 0, rows + "\n", "")
+ return run
+
+ monkeypatch.setattr("shutil.which", lambda name: name)
+ monkeypatch.setattr(er.subprocess, "run", ps_lists("/Library/Developer/CommandLineTools/usr/libexec/git-core/git-commit -a"))
+ assert er._held_open_lsof(lock, root, False), "macOS: a dashed git-commit with its fd closed keeps the lock"
+ monkeypatch.setattr(er.subprocess, "run", ps_lists("git log --oneline"))
+ assert er._held_open_lsof(lock, root, False) is False and er._held_open_lsof(lock, root, True)
+ monkeypatch.undo()
+
+ def scan(cwd: Path, name: str = "git.exe"):
+ proc = types.SimpleNamespace(info={"pid": 4242, "name": name, "cwd": str(cwd), "cmdline": [name, "commit"],
+ "environ": {}}, is_running=lambda: True)
+ psutil = types.SimpleNamespace(process_iter=lambda attrs: [proc])
+ monkeypatch.setitem(__import__("sys").modules, "psutil", psutil)
+ return gitlock._windows_git_in_checkout(root)
+
+ assert scan(tmp_path / "hermes-backup") is False, "a sibling directory is not this checkout"
+ assert scan(root / "sub") is True and scan(root, "git-commit.exe") is True
+
+
+def test_a_failed_retry_never_erases_the_killed_updates_claim(repo: Path) -> None:
+ """Review secondary: a retry that kept the then-live lock and failed replaced latest.json, so once
+ the git died the killed run's lock waited for the 10-minute sweep. The durable per-run records
+ still name the killed run: the last run that started before the lock was written."""
+ from hermes_cli import update_receipt
+ from hermes_cli.gitlock import release_dead_index_lock
+
+ lock = repo / ".git" / "index.lock"
+ _killed_update_receipt()
+ time.sleep(0.05)
+ lock.write_bytes(b"") # the killed run's git took it, then died with it
+ time.sleep(0.05)
+ update_receipt.begin_update_receipt() # the retry: refused on the lock, and finalized failed
+ update_receipt.finalize_update_receipt("failed")
+ assert update_receipt.read_latest_receipt()["outcome"] == "failed"
+
+ assert release_dead_index_lock(repo) is True
+ assert not lock.exists()