"""Wall-clock-bounded subprocesses that are stopped together with everything they started. ``subprocess.run(timeout=...)`` kills only the direct child and then waits for its pipes; a browser or agent grandchild that inherited them keeps that wait open forever. These helpers start the child in its own process group (a new console process group on Windows) and, on timeout, kill the whole group before collecting what it printed. """ from __future__ import annotations import os from pathlib import Path import signal import subprocess from typing import Mapping, Sequence DRAIN_SECONDS = 5 def process_group_options() -> dict[str, object]: """``Popen`` keyword arguments that make the child the leader of a new process group.""" if os.name == "nt": return {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} return {"start_new_session": True} def kill_process_group(process: subprocess.Popen) -> None: """Kill ``process`` and every descendant that stayed in its process group.""" if os.name == "nt": try: subprocess.run(["taskkill", "/T", "/F", "/PID", str(process.pid)], capture_output=True, timeout=30, check=False) except (OSError, subprocess.SubprocessError): pass else: try: os.killpg(process.pid, signal.SIGKILL) except (ProcessLookupError, PermissionError): pass try: process.kill() except OSError: pass def drain(process: subprocess.Popen) -> tuple[str, str]: """Collect output after a kill without trusting that every pipe holder died.""" try: stdout, stderr = process.communicate(timeout=DRAIN_SECONDS) except subprocess.TimeoutExpired: for stream in (process.stdout, process.stderr): if stream is not None: stream.close() stdout = stderr = "" return stdout or "", stderr or "" def run_isolated( argv: Sequence[str], timeout: float, *, input: str | None = None, cwd: str | Path | None = None, env: Mapping[str, str] | None = None, check: bool = True, ) -> subprocess.CompletedProcess[str]: """Run ``argv`` in its own process group; on timeout kill the whole group (browser children too). Raises ``subprocess.TimeoutExpired`` (carrying the partial output) after the group is dead, and ``subprocess.CalledProcessError`` on a non-zero exit when ``check`` is true. """ process = subprocess.Popen( list(argv), stdin=subprocess.PIPE if input is not None else subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace", cwd=None if cwd is None else str(cwd), env=None if env is None else dict(env), **process_group_options(), ) try: stdout, stderr = process.communicate(input, timeout=timeout) except subprocess.TimeoutExpired: kill_process_group(process) stdout, stderr = drain(process) raise subprocess.TimeoutExpired(process.args, timeout, output=stdout, stderr=stderr) from None except BaseException: # Interrupted (for example KeyboardInterrupt): never leave the group running. kill_process_group(process) drain(process) raise if check and process.returncode != 0: raise subprocess.CalledProcessError(process.returncode, list(argv), stdout, stderr) return subprocess.CompletedProcess(list(argv), process.returncode, stdout, stderr) def tail(text: str | bytes | None, limit: int = 300) -> str: """Last non-empty line of a process stream, shortened for an error message.""" if isinstance(text, bytes): text = text.decode("utf-8", "replace") lines = [line.strip() for line in (text or "").splitlines() if line.strip()] return lines[-1][:limit] if lines else "" __all__ = ["drain", "kill_process_group", "process_group_options", "run_isolated", "tail"]