| 1 | """Subprocess helpers: safe timeout + process-tree cleanup. |
| 2 | |
| 3 | Used by Bird/X search and other external-source clients. POSIX children use |
| 4 | their own process group; Windows children run inside a kill-on-close job. |
| 5 | """ |
| 6 | |
| 7 | from __future__ import annotations |
| 8 | |
| 9 | import os |
| 10 | import signal |
| 11 | import subprocess |
| 12 | import tempfile |
| 13 | import threading |
| 14 | import time |
| 15 | from contextlib import ExitStack |
| 16 | from dataclasses import dataclass |
| 17 | from typing import Optional, Sequence |
| 18 | |
| 19 | |
| 20 | class SubprocTimeout(Exception): |
| 21 | """Raised when a subprocess exceeds its timeout and is killed.""" |
| 22 | |
| 23 | def __init__(self, message: str = "", *, started: bool = True): |
| 24 | super().__init__(message) |
| 25 | self.started = started |
| 26 | |
| 27 | |
| 28 | # Live run_with_timeout children, process-wide. Each child is a session |
| 29 | # leader (os.setsid), so a group kill aimed at the engine never reaches it; |
| 30 | # the engine's SIGTERM handler and atexit hook drain this set instead. It |
| 31 | # lives here, not in last30days.py, because the entrypoint runs as |
| 32 | # __main__: importing it by name from lib/ executes a second module copy |
| 33 | # with its own empty registry, and on a worker thread that copy cannot |
| 34 | # install its signal handler either. RLock because cleanup_children runs |
| 35 | # inside a signal handler on the main thread, which may already hold the |
| 36 | # lock in register_child_pid. |
| 37 | _child_pids: set[int] = set() |
| 38 | _child_pids_lock = threading.RLock() |
| 39 | _child_jobs: dict[int, object] = {} |
| 40 | # Set once cleanup_children starts. Worker threads keep running while the |
| 41 | # handler sleeps through the grace, so a source can spawn a child after the |
| 42 | # snapshot; register_child_pid kills such late children itself. |
| 43 | _shutting_down = False |
| 44 | _WINDOWS = os.name == "nt" |
| 45 | |
| 46 | |
| 47 | def register_child_pid(pid: int) -> None: |
| 48 | with _child_pids_lock: |
| 49 | _child_pids.add(pid) |
| 50 | late = _shutting_down |
| 51 | if late: |
| 52 | _kill_child_group(pid, getattr(signal, "SIGKILL", signal.SIGTERM)) |
| 53 | |
| 54 | |
| 55 | def unregister_child_pid(pid: int) -> None: |
| 56 | with _child_pids_lock: |
| 57 | _child_pids.discard(pid) |
| 58 | job = _child_jobs.pop(pid, None) |
| 59 | if job is not None: |
| 60 | job.close() |
| 61 | |
| 62 | |
| 63 | # Upper bound on how long cleanup_children waits for SIGTERMed groups before |
| 64 | # SIGKILLing them. It runs inside the engine's SIGTERM handler, so it must |
| 65 | # finish well inside the MCP server's termGracePeriod |
| 66 | # (mcp/internal/engine/run.go), after which the engine group is SIGKILLed and |
| 67 | # the handler never reaches the escalation. Pinned by tests/test_subproc.py. |
| 68 | CLEANUP_TERM_GRACE_SECONDS = 0.8 |
| 69 | _CLEANUP_POLL_SECONDS = 0.05 |
| 70 | |
| 71 | |
| 72 | def _signal_group(pgid: int, sig: int) -> bool: |
| 73 | """Signal a child's process group; False once the group has no members.""" |
| 74 | try: |
| 75 | os.killpg(pgid, sig) |
| 76 | except (ProcessLookupError, PermissionError, OSError): |
| 77 | return False |
| 78 | return True |
| 79 | |
| 80 | |
| 81 | def _taskkill_pid(pid: int, timeout: float = 2) -> bool: |
| 82 | try: |
| 83 | result = subprocess.run( |
| 84 | ["taskkill", "/F", "/T", "/PID", str(pid)], |
| 85 | stdin=subprocess.DEVNULL, |
| 86 | stdout=subprocess.DEVNULL, |
| 87 | stderr=subprocess.DEVNULL, |
| 88 | timeout=timeout, |
| 89 | check=False, |
| 90 | creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), |
| 91 | ) |
| 92 | except (OSError, subprocess.TimeoutExpired): |
| 93 | return False |
| 94 | return result.returncode == 0 |
| 95 | |
| 96 | |
| 97 | def _kill_windows_tree(pid: int) -> bool: |
| 98 | return _taskkill_pid(pid) |
| 99 | |
| 100 | |
| 101 | def _kill_windows_managed_tree(pid: int) -> bool: |
| 102 | with _child_pids_lock: |
| 103 | job = _child_jobs.get(pid) |
| 104 | if job is not None and job.terminate(): |
| 105 | return True |
| 106 | return _kill_windows_tree(pid) |
| 107 | |
| 108 | |
| 109 | def _kill_child_group(pid: int, sig: int) -> None: |
| 110 | if hasattr(os, "setsid") and hasattr(os, "killpg"): |
| 111 | _signal_group(pid, sig) |
| 112 | return |
| 113 | if _WINDOWS and _kill_windows_managed_tree(pid): |
| 114 | return |
| 115 | try: |
| 116 | os.kill(pid, sig) |
| 117 | except (ProcessLookupError, PermissionError, OSError): |
| 118 | pass |
| 119 | |
| 120 | |
| 121 | def cleanup_children(grace: float = CLEANUP_TERM_GRACE_SECONDS) -> None: |
| 122 | """Terminate the process group of every registered child. |
| 123 | |
| 124 | Windows jobs terminate immediately. On POSIX, SIGTERM every group, wait |
| 125 | up to ``grace`` seconds for the groups to empty, then SIGKILL survivors. |
| 126 | run_with_timeout starts each POSIX child with os.setsid, so the child's |
| 127 | pid is its pgid; signalling the pgid directly still reaches grandchildren |
| 128 | after the leader has been reaped, |
| 129 | and the kernel does not reuse a pid while a group of that id has |
| 130 | members. A group whose only member is an unreaped zombie still reads as |
| 131 | live, which at worst costs the full grace and a harmless SIGKILL. |
| 132 | Children registered after this call starts are SIGKILLed as they |
| 133 | register, since the caller is about to exit. |
| 134 | """ |
| 135 | global _shutting_down |
| 136 | with _child_pids_lock: |
| 137 | _shutting_down = True |
| 138 | pids = list(_child_pids) |
| 139 | if not pids: |
| 140 | return |
| 141 | if not (hasattr(os, "setsid") and hasattr(os, "killpg")): |
| 142 | for pid in pids: |
| 143 | with _child_pids_lock: |
| 144 | if pid in _child_pids: |
| 145 | _kill_child_group(pid, signal.SIGTERM) |
| 146 | return |
| 147 | live = [pgid for pgid in pids if _signal_group(pgid, signal.SIGTERM)] |
| 148 | deadline = time.monotonic() + grace |
| 149 | while live and time.monotonic() < deadline: |
| 150 | time.sleep(_CLEANUP_POLL_SECONDS) |
| 151 | live = [pgid for pgid in live if _signal_group(pgid, 0)] |
| 152 | for pgid in live: |
| 153 | _signal_group(pgid, signal.SIGKILL) |
| 154 | |
| 155 | |
| 156 | @dataclass |
| 157 | class SubprocResult: |
| 158 | """Result of a subprocess run that captured stdout and stderr.""" |
| 159 | |
| 160 | returncode: int |
| 161 | stdout: str |
| 162 | stderr: str |
| 163 | |
| 164 | |
| 165 | def run_with_timeout( |
| 166 | cmd: Sequence[str], |
| 167 | *, |
| 168 | timeout: float, |
| 169 | env: Optional[dict] = None, |
| 170 | cwd: Optional[str | os.PathLike[str]] = None, |
| 171 | on_pid: Optional[callable] = None, |
| 172 | input_text: Optional[str] = None, |
| 173 | deadline_monotonic: Optional[float] = None, |
| 174 | cancel: Optional[threading.Event] = None, |
| 175 | cleanup_grace: float = 5.0, |
| 176 | capture_limit_bytes: Optional[int] = None, |
| 177 | ) -> SubprocResult: |
| 178 | """Run a subprocess with process-group cleanup on timeout. |
| 179 | |
| 180 | Spawns ``cmd`` inside its own process group via ``start_new_session`` where |
| 181 | available. On Windows, the child enters a kill-on-close job before it runs, |
| 182 | so cleanup reaches descendants that inherit the job after launchers exit. |
| 183 | Closing the job on normal return also stops detached descendants. Job setup |
| 184 | failure aborts the suspended child. POSIX signals the group with SIGTERM, |
| 185 | then escalates to SIGKILL if needed. |
| 186 | |
| 187 | Args: |
| 188 | cmd: Command and arguments to spawn. |
| 189 | timeout: Timeout in seconds passed to ``communicate()``. |
| 190 | env: Optional environment dict. If None, inherits parent env. |
| 191 | cwd: Optional working directory for the child process. |
| 192 | on_pid: Optional callable invoked with the child PID right after |
| 193 | spawn. Exceptions raised by the callback are suppressed. The |
| 194 | child is registered for cleanup_children() regardless. |
| 195 | input_text: Optional UTF-8 text supplied on stdin, never argv. |
| 196 | deadline_monotonic: Absolute operation deadline, including startup. |
| 197 | cancel: Optional event checked while waiting for the command. |
| 198 | cleanup_grace: Maximum TERM wait and subsequent KILL/reap wait, each. |
| 199 | capture_limit_bytes: Capture to temporary files instead of pipes, |
| 200 | reading at most this many bytes from each stream after exit. |
| 201 | |
| 202 | Returns: |
| 203 | SubprocResult with returncode, stdout, and stderr as strings. |
| 204 | |
| 205 | Raises: |
| 206 | SubprocTimeout: If the process timed out, was cancelled, or its |
| 207 | absolute deadline elapsed. |
| 208 | FileNotFoundError: If the executable is not found. |
| 209 | OSError: For other spawn failures. |
| 210 | """ |
| 211 | if deadline_monotonic is not None and time.monotonic() >= deadline_monotonic: |
| 212 | raise SubprocTimeout("Command deadline exceeded before spawn", started=False) |
| 213 | if cancel is not None and cancel.is_set(): |
| 214 | raise SubprocTimeout("Command cancelled before spawn", started=False) |
| 215 | if capture_limit_bytes is not None and capture_limit_bytes < 0: |
| 216 | raise ValueError("capture limit must be nonnegative") |
| 217 | own_group = hasattr(os, "setsid") and hasattr(os, "killpg") |
| 218 | native_windows = _WINDOWS |
| 219 | capture = ExitStack() |
| 220 | job = None |
| 221 | try: |
| 222 | stdout_file = capture.enter_context(tempfile.TemporaryFile()) if capture_limit_bytes is not None else None |
| 223 | stderr_file = capture.enter_context(tempfile.TemporaryFile()) if capture_limit_bytes is not None else None |
| 224 | if native_windows: |
| 225 | from .windows_job import CREATE_SUSPENDED, WindowsJob |
| 226 | |
| 227 | job = WindowsJob() |
| 228 | proc = subprocess.Popen( |
| 229 | list(cmd), |
| 230 | stdout=stdout_file if stdout_file is not None else subprocess.PIPE, |
| 231 | stderr=stderr_file if stderr_file is not None else subprocess.PIPE, |
| 232 | stdin=subprocess.PIPE if input_text is not None else None, |
| 233 | text=True, |
| 234 | encoding="utf-8", |
| 235 | errors="replace", |
| 236 | start_new_session=own_group, |
| 237 | env=env, |
| 238 | cwd=cwd, |
| 239 | **({"creationflags": CREATE_SUSPENDED} if native_windows else {}), |
| 240 | ) |
| 241 | except BaseException as exc: |
| 242 | if isinstance(exc, OSError): |
| 243 | exc._last30days_subproc_launch_failed = True |
| 244 | if job is not None: |
| 245 | job.close() |
| 246 | capture.close() |
| 247 | raise |
| 248 | try: |
| 249 | if native_windows: |
| 250 | from .windows_job import resume_suspended_process |
| 251 | |
| 252 | try: |
| 253 | job.assign(proc._handle) |
| 254 | with _child_pids_lock: |
| 255 | _child_pids.add(proc.pid) |
| 256 | _child_jobs[proc.pid] = job |
| 257 | late = _shutting_down |
| 258 | if late: |
| 259 | if not job.terminate(): |
| 260 | proc.kill() |
| 261 | else: |
| 262 | resume_suspended_process(proc.pid) |
| 263 | if late: |
| 264 | raise SubprocTimeout("Command cancelled during shutdown") |
| 265 | except BaseException as exc: |
| 266 | if isinstance(exc, OSError): |
| 267 | exc._last30days_subproc_launch_failed = True |
| 268 | if proc.poll() is None: |
| 269 | try: |
| 270 | proc.kill() |
| 271 | except OSError: |
| 272 | pass |
| 273 | try: |
| 274 | proc.wait(timeout=min(cleanup_grace, 2)) |
| 275 | except subprocess.TimeoutExpired: |
| 276 | pass |
| 277 | raise |
| 278 | else: |
| 279 | register_child_pid(proc.pid) |
| 280 | if on_pid is not None: |
| 281 | try: |
| 282 | on_pid(proc.pid) |
| 283 | except Exception: |
| 284 | pass |
| 285 | try: |
| 286 | deadline = time.monotonic() + timeout |
| 287 | if deadline_monotonic is not None: |
| 288 | deadline = min(deadline, deadline_monotonic) |
| 289 | first = True |
| 290 | while True: |
| 291 | remaining = deadline - time.monotonic() |
| 292 | if remaining <= 0 or (cancel is not None and cancel.is_set()): |
| 293 | raise subprocess.TimeoutExpired(cmd, timeout) |
| 294 | try: |
| 295 | stdout, stderr = proc.communicate( |
| 296 | input=input_text if first else None, |
| 297 | timeout=min(remaining, 0.05) if cancel is not None else remaining, |
| 298 | ) |
| 299 | if deadline_monotonic is not None and time.monotonic() >= deadline_monotonic: |
| 300 | raise subprocess.TimeoutExpired(cmd, timeout) |
| 301 | break |
| 302 | except subprocess.TimeoutExpired: |
| 303 | if cancel is None or time.monotonic() >= deadline or cancel.is_set(): |
| 304 | raise |
| 305 | finally: |
| 306 | first = False |
| 307 | except subprocess.TimeoutExpired: |
| 308 | term_deadline = time.monotonic() + cleanup_grace |
| 309 | pgid = None |
| 310 | try: |
| 311 | if own_group: |
| 312 | pgid = proc.pid |
| 313 | os.killpg(pgid, signal.SIGTERM) |
| 314 | elif not (_WINDOWS and _kill_windows_managed_tree(proc.pid)): |
| 315 | proc.kill() |
| 316 | except (ProcessLookupError, PermissionError, OSError, AttributeError): |
| 317 | pgid = None |
| 318 | proc.kill() |
| 319 | try: |
| 320 | proc.wait(timeout=cleanup_grace) |
| 321 | except subprocess.TimeoutExpired: |
| 322 | # Child ignored SIGTERM (or our killpg lost the race); escalate. |
| 323 | try: |
| 324 | if pgid is not None: |
| 325 | os.killpg(pgid, signal.SIGKILL) |
| 326 | elif not (_WINDOWS and _kill_windows_managed_tree(proc.pid)): |
| 327 | proc.kill() |
| 328 | except (ProcessLookupError, PermissionError, OSError, AttributeError): |
| 329 | proc.kill() |
| 330 | try: |
| 331 | proc.wait(timeout=cleanup_grace) |
| 332 | except subprocess.TimeoutExpired: |
| 333 | pass # process unkillable (e.g. D-state); leave as zombie |
| 334 | else: |
| 335 | if pgid is not None: |
| 336 | # Reaping the leader does not end its process group. Keep |
| 337 | # the remaining members inside the original TERM grace. |
| 338 | while _signal_group(pgid, 0): |
| 339 | remaining = term_deadline - time.monotonic() |
| 340 | if remaining <= 0: |
| 341 | _signal_group(pgid, signal.SIGKILL) |
| 342 | break |
| 343 | time.sleep(min(_CLEANUP_POLL_SECONDS, remaining)) |
| 344 | raise SubprocTimeout(f"Command {cmd[0]} timed out after {timeout}s") |
| 345 | if capture_limit_bytes is not None: |
| 346 | stdout_file.seek(0) |
| 347 | stderr_file.seek(0) |
| 348 | stdout = stdout_file.read(capture_limit_bytes).decode("utf-8", errors="replace") |
| 349 | stderr = stderr_file.read(capture_limit_bytes).decode("utf-8", errors="replace") |
| 350 | except SubprocTimeout: |
| 351 | raise |
| 352 | except BaseException: |
| 353 | if proc.poll() is None: |
| 354 | _kill_child_group(proc.pid, getattr(signal, "SIGKILL", signal.SIGTERM)) |
| 355 | try: |
| 356 | proc.wait(timeout=cleanup_grace) |
| 357 | except subprocess.TimeoutExpired: |
| 358 | pass |
| 359 | raise |
| 360 | finally: |
| 361 | unregister_child_pid(proc.pid) |
| 362 | if job is not None: |
| 363 | job.close() |
| 364 | for pipe in (proc.stdin, proc.stdout, proc.stderr): |
| 365 | if pipe is not None: |
| 366 | pipe.close() |
| 367 | capture.close() |
| 368 | |
| 369 | return SubprocResult( |
| 370 | returncode=proc.returncode, |
| 371 | stdout=stdout or "", |
| 372 | stderr=stderr or "", |
| 373 | ) |
| 374 |