The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Address PR review feedback (#119150)
beardthelion2f41514cae16
diff --git a/tests/tools/test_local_setsid_descendant_sweep.py b/tests/tools/test_local_setsid_descendant_sweep.pyindex bc29e40af51..49da17d9e9a 100644--- a/tests/tools/test_local_setsid_descendant_sweep.py+++ b/tests/tools/test_local_setsid_descendant_sweep.py@@ -11,6 +11,8 @@ outside the (now-dead) group with SIGKILL afterwards.import osimport signal+import subprocess+import sysimport textwrapimport timefrom types import SimpleNamespace@@ -178,11 +180,15 @@ def test_kill_process_never_killpgs_the_callers_own_group(monkeypatch):@pytest.mark.skipif(os.name != "posix", reason="POSIX process-group semantics")class TestReapUntrackedGroupGuard:- """ProcessRegistry._reap_untracked must never killpg a group the child does- not lead: a child that shares our process group would take the whole- process tree down with it."""-- def test_shared_group_child_gets_proc_kill_only(self, monkeypatch):+ """ProcessRegistry._reap_untracked terminates through _terminate_host_pid,+ which revalidates the kernel start time captured at spawn before signalling.+ pgid == pid only proves group leadership, not identity: a reaped child can+ be recycled onto an unrelated process that leads its own group, and the old+ raw killpg arm would have tree-killed the stranger."""++ def test_termination_delegates_with_recorded_identity(self, monkeypatch):+ """The shared terminate path receives the pid AND the start time+ recorded at spawn; no group primitive is consulted or signalled."""from unittest.mock import MagicMockfrom tools.process_registry import ProcessRegistry@@ -190,32 +196,66 @@ class TestReapUntrackedGroupGuard:reg = ProcessRegistry()proc = MagicMock()proc.pid = 999- session = SimpleNamespace(systemd_unit="")- monkeypatch.setattr(os, "getpgid", lambda pid: 555) # != pid: shared group- killpg_calls = []- monkeypatch.setattr(os, "killpg", lambda pgid, sig: killpg_calls.append((pgid, sig)))+ session = SimpleNamespace(systemd_unit="", host_start_time=4242)+ calls, forbidden = [], []+ monkeypatch.setattr(+ ProcessRegistry, "_terminate_host_pid",+ classmethod(+ lambda cls, pid, expected_start=None: calls.append((pid, expected_start))))+ monkeypatch.setattr(os, "getpgid", lambda pid: forbidden.append(("getpgid", pid)))+ monkeypatch.setattr(os, "killpg", lambda pgid, sig: forbidden.append(("killpg", pgid)))reg._reap_untracked(session, proc)- assert killpg_calls == []- proc.kill.assert_called_once()-- def test_group_leader_child_gets_the_group_signal(self, monkeypatch):- """Control: a start_new_session child leads its own group and is killed- through killpg so its descendants go with it."""- from unittest.mock import MagicMock+ assert calls == [(999, 4242)]+ assert forbidden == []+ def test_group_leader_child_is_reaped(self, monkeypatch):+ """Control: a real start_new_session child whose recorded start time+ still matches is terminated."""from tools.process_registry import ProcessRegistry- reg = ProcessRegistry()- proc = MagicMock()- proc.pid = 999- session = SimpleNamespace(systemd_unit="")- monkeypatch.setattr(os, "getpgid", lambda pid: 999) # == pid: group leader- killpg_calls = []- monkeypatch.setattr(os, "killpg", lambda pgid, sig: killpg_calls.append((pgid, sig)))-- reg._reap_untracked(session, proc)+ monkeypatch.setattr(ProcessRegistry, "_daemon_term_grace_seconds",+ staticmethod(lambda: 0.5))+ proc = subprocess.Popen(+ [sys.executable, "-c", "import time; time.sleep(30)"],+ start_new_session=True)+ try:+ real_start = ProcessRegistry._safe_host_start_time(proc.pid)+ assert real_start is not None, "no /proc start time on this platform?"+ session = SimpleNamespace(systemd_unit="", host_start_time=real_start)++ ProcessRegistry()._reap_untracked(session, proc)++ assert proc.poll() is not None, "matching-identity child must be reaped"+ finally:+ if proc.poll() is None:+ proc.kill()+ proc.wait()++ def test_same_pid_new_start_time_group_leader_survives(self, monkeypatch):+ """Regression: a group leader whose recorded start time does not match+ (the recycled-PID shape: same numeric pid, different process) must NOT+ be signalled, even though getpgid(pid) == pid authorized the old arm."""+ from tools.process_registry import ProcessRegistry- assert len(killpg_calls) == 1 and killpg_calls[0][0] == 999- proc.kill.assert_not_called()+ monkeypatch.setattr(ProcessRegistry, "_daemon_term_grace_seconds",+ staticmethod(lambda: 0.5))+ proc = subprocess.Popen(+ [sys.executable, "-c", "import time; time.sleep(30)"],+ start_new_session=True)+ try:+ real_start = ProcessRegistry._safe_host_start_time(proc.pid)+ assert real_start is not None, "no /proc start time on this platform?"+ assert os.getpgid(proc.pid) == proc.pid # leads its group: old arm fired here+ session = SimpleNamespace(systemd_unit="", host_start_time=real_start + 1)+ # A stub Popen keeps the wait tail from parking 5s on the still-live child.+ stub = SimpleNamespace(pid=proc.pid, wait=lambda timeout=None: None)++ ProcessRegistry()._reap_untracked(session, stub)++ assert not _wait_for_pid_exit(proc.pid, timeout=0.5)+ assert proc.poll() is None+ finally:+ proc.kill()+ proc.wait()diff --git a/tests/tools/test_process_registry.py b/tests/tools/test_process_registry.pyindex 3c4ff4c69c4..2c7b1f3ce1c 100644--- a/tests/tools/test_process_registry.py+++ b/tests/tools/test_process_registry.py@@ -1125,40 +1125,29 @@ class TestPopenLeakOnSetupFailure:def test_popen_killed_when_thread_creation_fails(self, registry):"""If Thread() raises after Popen, proc must be killed — not orphaned."""- killed = []-proc = MagicMock()proc.pid = 9999proc.stdout = iter([])proc.stdin = MagicMock()proc.poll.return_value = None-- def fake_kill():- killed.append(True)-- proc.kill = fake_killproc.wait = MagicMock()def boom(*args, **kwargs):raise RuntimeError("Thread creation failed")- # proc.pid is a MagicMock-backed fake; os.getpgid(fake_pid) would query- # the real OS for an arbitrary PID. On a busy host that PID may exist,- # in which case spawn_local's primary cleanup path- # (os.killpg(os.getpgid(pid), SIGKILL)) succeeds against an UNRELATED- # real process group and proc.kill() is never reached — flaky failure,- # and a real risk of SIGKILLing an innocent process group. Force the- # ProcessLookupError fallback so the test deterministically exercises- # proc.kill() and never issues a real killpg.+ # The orphan path terminates through _terminate_host_pid, which+ # revalidates the recorded kernel start time before signalling, so a+ # MagicMock pid can never reach a real killpg/os.kill.with patch("tools.process_registry._find_shell", return_value="/bin/bash"), \patch("subprocess.Popen", return_value=proc), \patch("threading.Thread", side_effect=boom), \- patch("os.getpgid", side_effect=ProcessLookupError), \+ patch.object(ProcessRegistry, "_terminate_host_pid") as terminate, \patch.object(registry, "_write_checkpoint"):with pytest.raises(RuntimeError, match="Thread creation failed"):registry.spawn_local("echo hello", cwd="/tmp")- assert killed, "proc.kill() must be called when post-Popen setup raises"+ assert terminate.call_count == 1, "post-Popen setup failure must terminate the orphan"+ assert terminate.call_args[0][0] == 9999# =========================================================================# Spawn rewrite regression (issue #68915)diff --git a/tests/verify/test_environment_and_runner.py b/tests/verify/test_environment_and_runner.pyindex d81bced5f5a..16ffaae168a 100644--- a/tests/verify/test_environment_and_runner.py+++ b/tests/verify/test_environment_and_runner.py@@ -10,8 +10,6 @@ from unittest.mock import MagicMock, patchimport pytest-import pytest-from agent.verify.environment import (load_manifest,load_or_detect,diff --git a/tools/process_registry.py b/tools/process_registry.pyindex dbb7ada1f25..7ee93438d8e 100644--- a/tools/process_registry.py+++ b/tools/process_registry.py@@ -1253,29 +1253,13 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin):descendants) so nothing leaks untracked."""with suppress(Exception):if session.systemd_unit:- # Scope teardown is the authoritative cleanup for the worker cgroup- # (never killpg here); the wrapper PID is terminated as fallback.+ # Scope teardown is the authoritative cleanup for the worker cgroup;+ # the systemd-run wrapper PID is terminated below as fallback._stop_systemd_unit(session.systemd_unit)- # The worker runs in its own systemd scope and, since the #70716 session-isolation fix, its- # own session. Stop the scope (kills every process in the worker cgroup), then terminate the- # systemd-run wrapper PID as fallback.- self._terminate_host_pid(proc.pid, session.host_start_time)- elif not _IS_WINDOWS:- try:- kill_signal = getattr(signal, "SIGKILL", signal.SIGTERM)- pgid = os.getpgid(proc.pid)- if pgid == proc.pid:- # The child leads its own group (start_new_session): the- # group signal reaches any descendants with it.- os.killpg(pgid, kill_signal) # windows-footgun: ok - guarded by _IS_WINDOWS above- else:- # Shared our process group — killpg would take the whole- # tree down with it. Kill the direct child only.- proc.kill()- except (ProcessLookupError, PermissionError, OSError):- proc.kill()- else:- proc.kill()+ # _terminate_host_pid revalidates the kernel start time captured at+ # spawn before signalling: pgid == pid would only prove the pid leads a+ # group, and a reaped child can be recycled onto an unrelated leader.+ self._terminate_host_pid(proc.pid, session.host_start_time)with suppress(Exception):proc.wait(timeout=5)