diff --git a/src/secfoo/agents/base.py b/src/secfoo/agents/base.py index 093aa7c..e77a3ea 100644 --- a/src/secfoo/agents/base.py +++ b/src/secfoo/agents/base.py @@ -21,6 +21,35 @@ Status = Literal["success", "failed", "timeout", "binary_not_found"] +def _kill_process_tree(pid: int, *, posix: bool = os.name == "posix") -> None: + """Kill `pid` and its descendants after a timeout. + + os.killpg/os.getpgid only exist on POSIX (start_new_session=True above + puts the child in its own process group there). Windows has no process + group equivalent reachable from the stdlib, so `taskkill /T` (kill + process tree) is used instead -- both are needed to reliably contain + Cursor's documented `agent -p` hang bug if it spawns any grandchildren; + killing just the direct child (e.g. subprocess.run's own timeout + handling, or Popen.kill()) is not enough. + + `posix` defaults to the real platform and only exists so tests can + exercise both branches on a single OS -- monkeypatching os.name itself + is not safe here since pytest's own traceback machinery reads it too. + """ + try: + if posix: + os.killpg(os.getpgid(pid), signal.SIGKILL) + else: + subprocess.run( + ["taskkill", "/F", "/T", "/PID", str(pid)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=False, + ) + except (ProcessLookupError, OSError): + pass + + @dataclass class AgentResult: agent: str @@ -67,10 +96,9 @@ def run(self, prompt: str, *, workdir: Path, timeout: int | None = None) -> Agen started = time.monotonic() # Driven via Popen (rather than subprocess.run) so that on timeout we - # can killpg() the whole process group. subprocess.run's own timeout - # handling only kills the direct child, which is not enough to - # reliably contain Cursor's documented `agent -p` hang bug if it - # spawns any grandchildren. + # can kill the whole process tree via _kill_process_tree() -- see + # its docstring for why subprocess.run's own timeout handling isn't + # enough on its own. proc = subprocess.Popen( cmd, cwd=workdir, @@ -95,10 +123,7 @@ def run(self, prompt: str, *, workdir: Path, timeout: int | None = None) -> Agen raw_report=self.extract_report(stdout) if status == "success" else "", ) except subprocess.TimeoutExpired: - try: - os.killpg(os.getpgid(proc.pid), signal.SIGKILL) - except ProcessLookupError: - pass + _kill_process_tree(proc.pid) stdout, stderr = proc.communicate() duration = time.monotonic() - started return AgentResult( diff --git a/tests/test_agents/test_base.py b/tests/test_agents/test_base.py index 18af316..ddf08b8 100644 --- a/tests/test_agents/test_base.py +++ b/tests/test_agents/test_base.py @@ -2,6 +2,7 @@ import subprocess +from secfoo.agents.base import _kill_process_tree from secfoo.agents.claude import ClaudeAdapter from secfoo.settings import Defaults, SecfooConfig @@ -49,3 +50,53 @@ def test_stdin_is_devnull_so_interactive_prompts_fail_fast_not_hang(fake_popen, adapter = ClaudeAdapter() adapter.run("hi", workdir=tmp_path) assert fake.call_kwargs["stdin"] == subprocess.DEVNULL + + +def test_kill_process_tree_uses_killpg_on_posix(monkeypatch): + # raising=False: os.getpgid/os.killpg/signal.SIGKILL don't exist as + # attributes at all outside POSIX (that's the bug this whole file is + # about), so there's nothing for monkeypatch to find here on Windows. + sigkill = object() + calls = [] + monkeypatch.setattr("secfoo.agents.base.os.getpgid", lambda pid: pid, raising=False) + monkeypatch.setattr("secfoo.agents.base.os.killpg", lambda pgid, sig: calls.append((pgid, sig)), raising=False) + monkeypatch.setattr("secfoo.agents.base.signal.SIGKILL", sigkill, raising=False) + _kill_process_tree(4321, posix=True) + assert calls == [(4321, sigkill)] + + +def test_kill_process_tree_swallows_missing_process_on_posix(monkeypatch): + """The target may have already exited by the time we try to kill it -- + that's a normal race, not an error.""" + + def _raise(pid): + raise ProcessLookupError + + monkeypatch.setattr("secfoo.agents.base.os.getpgid", _raise, raising=False) + # Never actually called (getpgid raises first) -- just needs to exist as + # an attribute so the call expression resolves on a platform without it. + monkeypatch.setattr("secfoo.agents.base.os.killpg", lambda pgid, sig: None, raising=False) + monkeypatch.setattr("secfoo.agents.base.signal.SIGKILL", object(), raising=False) + _kill_process_tree(4321, posix=True) # must not raise + + +def test_kill_process_tree_uses_taskkill_on_windows(monkeypatch): + """os.killpg/os.getpgid don't exist outside POSIX -- Windows has no + process-group equivalent in the stdlib, so this must shell out to + `taskkill /T` (kill the whole process tree) instead.""" + calls = [] + monkeypatch.setattr("secfoo.agents.base.subprocess.run", lambda *a, **kw: calls.append((a, kw))) + _kill_process_tree(4321, posix=False) + assert calls + args, kwargs = calls[0] + assert args[0] == ["taskkill", "/F", "/T", "/PID", "4321"] + assert kwargs["stdout"] == subprocess.DEVNULL + assert kwargs["stderr"] == subprocess.DEVNULL + + +def test_kill_process_tree_swallows_taskkill_errors_on_windows(monkeypatch): + def _raise(*a, **kw): + raise OSError("taskkill not found") + + monkeypatch.setattr("secfoo.agents.base.subprocess.run", _raise) + _kill_process_tree(4321, posix=False) # must not raise