The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): macOS update custody kills the git tree, not git's pid
Tekniumac884e530aff
diff --git a/hermes_cli/update_custody.py b/hermes_cli/update_custody.pyindex a9b46461489..6c7b5b93ba4 100644--- a/hermes_cli/update_custody.py+++ b/hermes_cli/update_custody.py@@ -328,25 +328,26 @@ def run_git(git_cmd: Sequence[str], args: Sequence[str], **kwargs) -> subprocessmutator = is_local_mutator(argv[1:])if mutator:_prefetch_for_move(list(git_cmd), list(args), kwargs)- elif git_subcommand(argv[1:]) in _FD_LESS_REF_WRITERS and sys.platform != "win32" \- and _held() is not None and "preexec_fn" not in kwargs and _death_signal_preexec() is None:- return _run_owner_watched(argv, kwargs)+ if sys.platform != "win32" and _held() is not None and "preexec_fn" not in kwargs \+ and _death_signal_preexec() is None:+ # No parent-death signal (macOS): the tree runner owns git AND the helpers it starts. A+ # local mutator holds the lock fd and finishes its write if the owner dies, as on Linux.+ return _run_owner_watched(argv, _custody_kwargs(mutator, kwargs), watch_owner=not mutator)return run(argv, inherit_lock=mutator, **kwargs)-# git commands that write refs WITHOUT the lock fd (m3: their network half must not hold it). On-# Linux the parent-death signal ends one whose owner died; where there is none (macOS) a watchdog-# does (R3), or it would go on rewriting refs and leave live `*.lock` files under the next owner.-_FD_LESS_REF_WRITERS = frozenset({"fetch"})-+# git without the lock fd (a fetch's network half must not hold it, m3) dies with its owner: on+# Linux by the parent-death signal; where there is none (macOS) by this watchdog (R3), or a fetch+# would go on rewriting refs and leave live `*.lock` files under the next owner.# The watchdog: stdin is a pipe only the owner writes. A byte = the child finished; EOF with no-# byte = the owner died (the kernel closed its end), so SIGKILL the child, as PR_SET_PDEATHSIG-# would. It holds no lock fd and runs in its own session (a terminal's ^C/hang-up is the owner's).+# byte = the owner died (the kernel closed its end), so SIGKILL the child's whole process group+# (git and the helpers it started: git-remote-https, index-pack, pack-objects), as+# PR_SET_PDEATHSIG would for the child alone. It holds no lock fd and runs in its own session._OWNER_WATCH = ("import os, signal, sys\n""if not os.read(0, 1):\n"" try:\n"- " os.kill(int(sys.argv[1]), signal.SIGKILL)\n" # windows-footgun: ok -- POSIX only (run_git gates win32 out)+ " os.killpg(int(sys.argv[1]), signal.SIGKILL)\n" # windows-footgun: ok -- POSIX only (run_git gates win32 out)" except OSError:\n"" pass\n")@@ -379,20 +380,32 @@ def _owner_watch(pid: int):return dismiss-def _run_owner_watched(argv: Sequence[str], kwargs: dict) -> subprocess.CompletedProcess:- """``subprocess.run`` for an fd-less ref writer, under :func:`_owner_watch` while it runs."""+def _kill_tree(proc: subprocess.Popen) -> None:+ """SIGKILL ``proc``'s process group: the child leads it (``start_new_session``) and is not+ reaped yet, so the group id cannot have been reused."""+ import os+ import signal++ with contextlib.suppress(OSError): # already gone+ os.killpg(proc.pid, signal.SIGKILL) # windows-footgun: ok -- POSIX only (run_git gates win32 out)+++def _run_owner_watched(argv: Sequence[str], kwargs: dict, *, watch_owner: bool = True) -> subprocess.CompletedProcess:+ """``subprocess.run`` for updater git where no parent-death signal exists, under+ :func:`_owner_watch` while it runs. git leads a session of its own, so a timeout, a cancel or+ the owner's death ends its helpers with it, not git's pid alone (#144439)."""input, timeout = kwargs.pop("input", None), kwargs.pop("timeout", None)check = kwargs.pop("check", False)if input is not None:kwargs["stdin"] = subprocess.PIPEif kwargs.pop("capture_output", False):kwargs["stdout"] = kwargs["stderr"] = subprocess.PIPE- with subprocess.Popen(list(argv), **kwargs) as proc:- dismiss = _owner_watch(proc.pid)+ with subprocess.Popen(list(argv), start_new_session=True, **kwargs) as proc:+ dismiss = _owner_watch(proc.pid) if watch_owner else Nonetry:stdout, stderr = proc.communicate(input, timeout=timeout)except subprocess.TimeoutExpired as exc:- proc.kill()+ _kill_tree(proc)try:exc.stdout, exc.stderr = proc.communicate(timeout=_DRAIN_SECONDS)except subprocess.TimeoutExpired:@@ -400,7 +413,7 @@ def _run_owner_watched(argv: Sequence[str], kwargs: dict) -> subprocess.Completeproc.stdin = proc.stdout = proc.stderr = Noneraiseexcept BaseException:- proc.kill()+ _kill_tree(proc)raisefinally:if dismiss is not None:diff --git a/tests/hermes_cli/test_update_custody_tree.py b/tests/hermes_cli/test_update_custody_tree.pynew file mode 100644index 00000000000..6b0b7ed807a--- /dev/null+++ b/tests/hermes_cli/test_update_custody_tree.py@@ -0,0 +1,111 @@+"""#144439: where there is no parent-death signal (macOS), updater git custody owns the git+TREE, not git's pid: a timeout, or the owner's death, ends the helpers git started too.++Real git, real processes. The helper is the fetch's upload-pack (a shell git starts), which+stands in for git-remote-https / index-pack. Linux runs the same code with the parent-death+signal switched off; the macOS tests-os lane runs it natively.+"""++from __future__ import annotations++import os+import subprocess+import sys+import textwrap+import time+from pathlib import Path++import pytest++REPO_ROOT = Path(__file__).resolve().parents[2]+++def _env() -> dict:+ return dict(os.environ, GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull,+ GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@e", GIT_COMMITTER_NAME="t", GIT_COMMITTER_EMAIL="t@e")+++def _alive(pid: int) -> bool:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ if Path(f"/proc/{pid}/stat").exists(): # Linux: a zombie is dead+ stat = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8")+ return stat[stat.rfind(")") + 2:][:1] != "Z"+ return True+++def _gone_within(pid: int, seconds: float) -> bool:+ deadline = time.monotonic() + seconds+ while time.monotonic() < deadline:+ if not _alive(pid):+ return True+ time.sleep(0.05)+ return False+++def fetch_rig(tmp_path, monkeypatch):+ for key, value in _env().items():+ monkeypatch.setenv(key, value)+ repo, remote = tmp_path / "repo", tmp_path / "remote.git"+ repo.mkdir()+ for args in (["init", "-q", "-b", "main"], ["commit", "-q", "--allow-empty", "-m", "one"]):+ subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True)+ subprocess.run(["git", "clone", "-q", "--bare", str(repo), str(remote)], check=True, capture_output=True)+ subprocess.run(["git", "-C", str(repo), "remote", "add", "origin", str(remote)], check=True)+ helper_pid = tmp_path / "helper.pid"+ helper = tmp_path / "helper.sh"+ helper.write_text(f"#!/bin/sh\necho $$ > {helper_pid}.tmp && mv {helper_pid}.tmp {helper_pid}\nsleep 60\n",+ encoding="utf-8")+ helper.chmod(0o755)+ yield repo, helper, helper_pid+ if helper_pid.exists():+ subprocess.run(["kill", "-9", helper_pid.read_text(encoding="utf-8").strip()], capture_output=True, check=False)+++def _wait_pid(path: Path) -> int:+ for _ in range(400):+ if path.exists():+ return int(path.read_text(encoding="utf-8").strip())+ time.sleep(0.05)+ raise AssertionError("the fetch never started its helper")++[email protected]("posix")+def test_a_timed_out_fetch_takes_its_helpers_with_it(fetch_rig, tmp_path, monkeypatch):+ from hermes_cli import update_custody++ repo, helper, helper_pid = fetch_rig+ monkeypatch.setattr(update_custody, "_held", lambda: {"fd": None})+ monkeypatch.setattr(update_custody, "_death_signal_preexec", lambda: None)+ with pytest.raises(subprocess.TimeoutExpired):+ update_custody.run_git(["git"], ["fetch", f"--upload-pack={helper}", "origin"], cwd=str(repo),+ capture_output=True, timeout=2)+ assert _gone_within(_wait_pid(helper_pid), 5), "the fetch's helper outlived the timed-out fetch"++[email protected]("posix")+def test_a_killed_owner_takes_the_fetch_helpers_with_it(fetch_rig, tmp_path):+ repo, helper, helper_pid = fetch_rig+ owner_script = textwrap.dedent(f"""+ import sys+ sys.path.insert(0, {str(REPO_ROOT)!r})+ from pathlib import Path+ from hermes_cli import update_custody, update_lock as ul, update_cmd+ update_custody._death_signal_preexec = lambda: None # what macOS has+ lock = ul.UpdateLock(path=Path(sys.argv[2]), install_root=sys.argv[1])+ assert lock.acquire()+ update_cmd._git_run(["git"], ["fetch", "--upload-pack=" + sys.argv[3], "origin"], cwd=sys.argv[1], network=True)+ """)+ owner = subprocess.Popen([sys.executable, "-c", owner_script, str(repo), str(tmp_path / "marker"), str(helper)],+ env=_env())+ try:+ pid = _wait_pid(helper_pid)+ owner.kill()+ owner.wait(timeout=10)+ assert _gone_within(pid, 10), "the fetch's helper outlived its killed update owner"+ finally:+ if owner.poll() is None:+ owner.kill()