The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: a Ctrl-C'd build runner can no longer kill the custodian of its detached writers
Teknium61470f10a419
diff --git a/hermes_cli/update_custody.py b/hermes_cli/update_custody.pyindex 3e00d0ef34f..5ff9c75d995 100644--- a/hermes_cli/update_custody.py+++ b/hermes_cli/update_custody.py@@ -567,12 +567,11 @@ def _join_launcher_python() -> str:# this stdlib parent, which holds the fd until no descendant of the command is left.# * The command stays in the CALLER's process group: every group kill that stops a build (a# Ctrl-C'd completion child's ``killpg``, Desktop's ``kill(-pid)``) reaches node and everything-# under it that did not start a session of its own. This launcher leaves that group (E): a-# SIGKILL of the group would otherwise kill the custodian too, and a descendant in a session of-# its own would go on writing with the checkout lock free. It outlives the kill, settles the-# tree as below, and only then exits (releasing the fd). A launcher started as its group's-# leader (a caller that gave it a session) cannot leave it; that group is then its own.-# * Linux: the launcher is a child subreaper, so a descendant orphaned by node's exit (or by any+# under it that did not start a session of its own. The custodian leaves that group (E): a+# SIGKILL of the group would otherwise kill it too, and a descendant in a session of its own+# would go on writing with the checkout lock free. It outlives the kill, settles the tree as+# below, and only then exits (releasing the fd).+# * Linux: the custodian is a child subreaper, so a descendant orphaned by node's exit (or by any# intermediate's) is re-parented to it, never to init. Once node exits it SIGKILLs and reaps# its children until none is left; it only signals its own unreaped children, so no pid it# kills can have been reused (never a ``killpg`` of an already reaped leader's group).@@ -581,10 +580,32 @@ def _join_launcher_python() -> str:# plus what they started. Best effort: a process born and orphaned between two samples escapes.# * SIGINT/SIGTERM/SIGHUP are forwarded to node (a node still running 10 s later is killed); the# descendants are then killed as above.+# * The custodian is NOT the process the runner sees (R4): ``subprocess.run`` SIGKILLs its own+# child when Ctrl-C reaches the caller, and no group separation survives a direct kill. The+# runner's child only forks the custodian (own group) and relays signals to it and its exit+# status back; it leaves the caller's group too, or a terminal's Ctrl-C would reach node twice. Killed, it leaves the custodian to settle: node gets the same 10 s it gets after+# a forwarded signal (it is usually still cleaning up from the same Ctrl-C), then the tree is+# killed as above and only then is the fd dropped._REAP_TREE = r"""import os, signal, subprocess, sys, timeKILL = signal.SIGKILL # windows-footgun: ok - POSIX-only launcherfds = tuple(int(fd) for fd in sys.argv[1].split(','))+caller = os.getpgrp()+if caller != os.getpid():+ os.setpgid(0, 0)+stand_in = os.getpid()+custodian = os.fork()+if custodian:+ def relay(signum, frame):+ try:+ os.kill(custodian, signum)+ except OSError:+ pass+ for name in ('SIGINT', 'SIGTERM', 'SIGHUP'):+ signal.signal(getattr(signal, name), relay)+ code = os.waitstatus_to_exitcode(os.waitpid(custodian, 0)[1])+ sys.exit(code if code >= 0 else 128 - code)+os.setpgid(0, 0)me = os.getpid()reaper = Falseif sys.platform.startswith('linux'):@@ -645,9 +666,6 @@ def kill(pids):except OSError:pass-caller = os.getpgrp()-if caller != me:- os.setpgid(0, 0)p = subprocess.Popen(sys.argv[2:], pass_fds=fds, process_group=caller)got = []@@ -669,7 +687,7 @@ while True:passif not reaper:sample(p.pid)- if got:+ if got or os.getppid() != stand_in:deadline = deadline or time.monotonic() + 10if time.monotonic() > deadline:p.kill()diff --git a/tests/hermes_cli/test_update_custody.py b/tests/hermes_cli/test_update_custody.pyindex bdb77c64e1e..8b6ad3b4bbe 100644--- a/tests/hermes_cli/test_update_custody.py+++ b/tests/hermes_cli/test_update_custody.py@@ -509,6 +509,62 @@ def test_a_group_kill_of_the_caller_keeps_custody_until_a_detached_writer_is_gonos.kill(int(beat.read_text(encoding="utf-8").split()[0]), signal.SIGKILL) # windows-footgun: ok - Linux-only test[email protected](not sys.platform.startswith("linux"), reason="POSIX sessions + /proc")[email protected]_system_guard_bypass # Ctrl-C of the caller's own group is the scenario under test[email protected](("verbose", "cleanup"), [("1", 2), ("0", 0)], ids=["verbose-slow-cleanup", "captured-instant-exit"])+def test_a_ctrl_c_keeps_custody_until_a_detached_writer_is_gone(repo, tmp_path, verbose, cleanup):+ """R4: on Ctrl-C the build runner's ``subprocess.run`` SIGKILLs its own child, which was the+ launcher holding custody; a command still cleaning up from the interrupt then exited and+ dropped the last lock fd while a writer in a session of its own went on writing under the+ next owner. A contender must only acquire once that writer has stopped."""+ import contextlib+ import signal++ beat, ready = tmp_path / "beat", tmp_path / "ready"+ writer = (f"import os, pathlib, time; os.setsid(); os.closerange(3, 4096); p = pathlib.Path({str(beat)!r})\n" # windows-footgun: ok - Linux-only test+ "for i in range(300):\n p.write_text(f'{os.getpid()} {i}'); time.sleep(0.1)")+ # A build that cleans up for `cleanup` s after SIGINT (2 s: longer than subprocess.run's interrupt wait).+ command = [sys.executable, "-c", textwrap.dedent(f"""+ import pathlib, signal, subprocess, sys, time+ signal.signal(signal.SIGINT, lambda *_: (time.sleep({cleanup}), sys.exit(130)))+ subprocess.Popen([sys.executable, '-c', {writer!r}], stdin=subprocess.DEVNULL)+ pathlib.Path({str(ready)!r}).touch()+ while True: time.sleep(0.1)+ """)]+ caller = textwrap.dedent(f"""+ import os, sys+ sys.path.insert(0, {str(REPO_ROOT)!r})+ os.environ["HERMES_VERBOSE"] = {verbose!r}+ from pathlib import Path+ from hermes_cli import update_lock as ul+ from hermes_cli.source_build import run_in_custody+ repo = Path({str(repo)!r})+ assert ul.UpdateLock(path=Path({str(tmp_path / "marker")!r}), install_root=repo).acquire()+ run_in_custody(repo, {command!r}, "probe build", stdin=__import__("subprocess").DEVNULL)+ """)+ owner = subprocess.Popen([sys.executable, "-c", caller], start_new_session=True,+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ deadline = time.monotonic() + 20+ while not (beat.exists() and ready.exists()) and time.monotonic() < deadline:+ time.sleep(0.1)+ assert beat.exists() and ready.exists(), "the build never started"+ os.killpg(owner.pid, signal.SIGINT) # windows-footgun: ok - Linux-only test+ owner.wait(timeout=10)+ contender = ul.UpdateLock(path=tmp_path / "next-marker", install_root=repo)+ deadline = time.monotonic() + 30+ while not contender.acquire():+ assert time.monotonic() < deadline, "the checkout stayed locked after the interrupted build settled"+ time.sleep(0.1)+ try:+ seen = beat.read_text(encoding="utf-8")+ time.sleep(1)+ assert beat.read_text(encoding="utf-8") == seen, "a detached build writer kept writing under the next owner"+ finally:+ contender.release()+ with contextlib.suppress(ProcessLookupError, ValueError):+ os.kill(int(beat.read_text(encoding="utf-8").split()[0]), signal.SIGKILL) # windows-footgun: ok - Linux-only test++@pytest.mark.skipif(not sys.platform.startswith("linux"), reason="POSIX sessions + /proc")@pytest.mark.parametrize("platform", [None, "darwin"], ids=["subreaper", "ps-walk"])def test_a_detached_grandchild_outliving_node_dies_before_the_build_returns(repo, tmp_path, platform):