| 1 | """Tests for scripts/lib/subproc.py. |
| 2 | |
| 3 | Covers the process-group cleanup path, timeout behavior, success path, |
| 4 | PID callback wiring, and environment inheritance. |
| 5 | """ |
| 6 | |
| 7 | import builtins |
| 8 | import errno |
| 9 | import os as real_os |
| 10 | import platform |
| 11 | import sys |
| 12 | import unittest |
| 13 | from unittest.mock import MagicMock, patch |
| 14 | |
| 15 | from lib import subproc |
| 16 | |
| 17 | IS_WINDOWS = platform.system() == "Windows" |
| 18 | |
| 19 | def get_shell_cmd(cmd_str: str) -> list[str]: |
| 20 | if IS_WINDOWS: |
| 21 | if cmd_str == "echo hello": |
| 22 | return [sys.executable, "-c", "print('hello')"] |
| 23 | elif cmd_str == "exit 3": |
| 24 | return ["cmd", "/c", "exit 3"] |
| 25 | elif cmd_str == "echo err >&2": |
| 26 | return [sys.executable, "-c", "import sys;print('err', file=sys.stderr)"] |
| 27 | elif cmd_str in ("sleep 10", "sleep 10 & wait"): |
| 28 | return ["powershell", "-Command", "Start-Sleep 10"] |
| 29 | elif cmd_str == "echo $LAST30DAYS_TEST_VAR": |
| 30 | return ["cmd", "/c", "echo %LAST30DAYS_TEST_VAR%"] |
| 31 | elif cmd_str == "true": |
| 32 | return ["cmd", "/c", "exit 0"] |
| 33 | elif cmd_str == "echo ok": |
| 34 | return ["cmd", "/c", "echo ok"] |
| 35 | else: |
| 36 | raise ValueError(f"No Windows command mapping for: {cmd_str}") |
| 37 | return ["sh", "-c", cmd_str] |
| 38 | |
| 39 | |
| 40 | class TestSubprocTimeout(unittest.TestCase): |
| 41 | def test_exception_class_raises_without_a_message(self): |
| 42 | with self.assertRaises(subproc.SubprocTimeout) as caught: |
| 43 | raise subproc.SubprocTimeout |
| 44 | self.assertEqual(str(caught.exception), "") |
| 45 | self.assertTrue(caught.exception.started) |
| 46 | |
| 47 | |
| 48 | class TestRunWithTimeout(unittest.TestCase): |
| 49 | def setUp(self): |
| 50 | self.addCleanup(setattr, subproc, "_shutting_down", False) |
| 51 | |
| 52 | def test_spawn_errors_preserve_original_type_and_errno(self): |
| 53 | for error_number in (errno.ENOENT, errno.EAGAIN, errno.EMFILE): |
| 54 | error = OSError(error_number, "command could not start") |
| 55 | with self.subTest(error_number=error_number), \ |
| 56 | patch.object(subproc.subprocess, "Popen", side_effect=error): |
| 57 | with self.assertRaises(type(error)) as caught: |
| 58 | subproc.run_with_timeout(["missing-command"], timeout=1) |
| 59 | self.assertIs(caught.exception, error) |
| 60 | self.assertEqual(caught.exception.errno, error_number) |
| 61 | |
| 62 | def test_success_returns_stdout(self): |
| 63 | result = subproc.run_with_timeout( |
| 64 | get_shell_cmd("echo hello"), |
| 65 | timeout=5, |
| 66 | ) |
| 67 | self.assertEqual(result.returncode, 0) |
| 68 | self.assertEqual(result.stdout.strip(), "hello") |
| 69 | self.assertEqual(result.stderr, "") |
| 70 | |
| 71 | def test_nonzero_exit_returns_returncode_not_exception(self): |
| 72 | result = subproc.run_with_timeout( |
| 73 | get_shell_cmd("exit 3"), |
| 74 | timeout=5, |
| 75 | ) |
| 76 | self.assertEqual(result.returncode, 3) |
| 77 | |
| 78 | def test_captures_stderr(self): |
| 79 | result = subproc.run_with_timeout( |
| 80 | get_shell_cmd("echo err >&2"), |
| 81 | timeout=5, |
| 82 | ) |
| 83 | self.assertEqual(result.stderr.strip(), "err") |
| 84 | |
| 85 | def test_timeout_raises_subproctimeout(self): |
| 86 | with self.assertRaises(subproc.SubprocTimeout): |
| 87 | subproc.run_with_timeout( |
| 88 | get_shell_cmd("sleep 10"), |
| 89 | timeout=1, |
| 90 | ) |
| 91 | |
| 92 | def test_timeout_kills_process_group(self): |
| 93 | """A slow child inside a shell should be killed when the group is signaled.""" |
| 94 | with self.assertRaises(subproc.SubprocTimeout): |
| 95 | # Parent shell spawns a child that sleeps long. |
| 96 | # Without process-group cleanup, the child would orphan. |
| 97 | subproc.run_with_timeout( |
| 98 | get_shell_cmd("sleep 10 & wait"), |
| 99 | timeout=1, |
| 100 | ) |
| 101 | |
| 102 | @unittest.skipIf(IS_WINDOWS, "process groups are POSIX-only") |
| 103 | def test_timeout_kills_grandchild_after_leader_exits(self): |
| 104 | import pathlib |
| 105 | import signal |
| 106 | import sys |
| 107 | import tempfile |
| 108 | import time |
| 109 | |
| 110 | child = """ |
| 111 | import os, pathlib, signal, sys, time |
| 112 | if sys.argv[2] == "ignore": |
| 113 | signal.signal(signal.SIGTERM, signal.SIG_IGN) |
| 114 | pathlib.Path(sys.argv[1]).write_text(str(os.getpid())) |
| 115 | time.sleep(15) |
| 116 | """ |
| 117 | leader = """ |
| 118 | import signal, subprocess, sys, time |
| 119 | signal.signal(signal.SIGTERM, lambda *_: sys.exit(0)) |
| 120 | subprocess.Popen([sys.executable, "-c", *sys.argv[1:]], |
| 121 | stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
| 122 | time.sleep(15) |
| 123 | """ |
| 124 | |
| 125 | def running(pid): |
| 126 | try: |
| 127 | real_os.kill(pid, 0) |
| 128 | if sys.platform.startswith("linux"): |
| 129 | state = pathlib.Path(f"/proc/{pid}/stat").read_text().rpartition(") ")[2].split()[0] |
| 130 | return state != "Z" |
| 131 | return True |
| 132 | except (ProcessLookupError, FileNotFoundError): |
| 133 | return False |
| 134 | |
| 135 | for mode in ("default", "ignore"): |
| 136 | with self.subTest(term_handler=mode), tempfile.TemporaryDirectory() as tmp: |
| 137 | pidfile = pathlib.Path(tmp, "grandchild.pid") |
| 138 | |
| 139 | def wait_ready(pid): |
| 140 | deadline = time.monotonic() + 3 |
| 141 | while time.monotonic() < deadline: |
| 142 | if pidfile.exists() and pidfile.stat().st_size: |
| 143 | return |
| 144 | time.sleep(0.01) |
| 145 | |
| 146 | try: |
| 147 | started = time.monotonic() |
| 148 | with self.assertRaises(subproc.SubprocTimeout): |
| 149 | subproc.run_with_timeout( |
| 150 | [sys.executable, "-c", leader, child, str(pidfile), mode], |
| 151 | timeout=0.1, |
| 152 | on_pid=wait_ready, |
| 153 | ) |
| 154 | self.assertLess(time.monotonic() - started, 9) |
| 155 | pid = int(pidfile.read_text()) |
| 156 | deadline = time.monotonic() + 1 |
| 157 | while running(pid) and time.monotonic() < deadline: |
| 158 | time.sleep(0.01) |
| 159 | self.assertFalse(running(pid), "grandchild survived the leader's clean TERM exit") |
| 160 | self.assertEqual(subproc._child_pids, set()) |
| 161 | finally: |
| 162 | if pidfile.exists() and pidfile.stat().st_size: |
| 163 | pid = int(pidfile.read_text()) |
| 164 | if running(pid): |
| 165 | try: |
| 166 | real_os.kill(pid, signal.SIGKILL) |
| 167 | except ProcessLookupError: |
| 168 | pass |
| 169 | |
| 170 | def test_missing_command_raises_oserror(self): |
| 171 | """Missing executables raise FileNotFoundError (or PermissionError on |
| 172 | some filesystems if a same-named junk file exists).""" |
| 173 | with self.assertRaises(OSError): |
| 174 | subproc.run_with_timeout( |
| 175 | ["/nonexistent-path/last30days-test-no-such-bin"], |
| 176 | timeout=5, |
| 177 | ) |
| 178 | |
| 179 | def test_env_is_passed_through(self): |
| 180 | import os |
| 181 | env = {"LAST30DAYS_TEST_VAR": "custom_value"} |
| 182 | if IS_WINDOWS: |
| 183 | for k in ("SystemRoot", "SystemDrive", "PATH", "COMSPEC", "TEMP", "TMP"): |
| 184 | if k in os.environ: |
| 185 | env[k] = os.environ[k] |
| 186 | else: |
| 187 | env["PATH"] = "/usr/bin:/bin" |
| 188 | result = subproc.run_with_timeout( |
| 189 | get_shell_cmd("echo $LAST30DAYS_TEST_VAR"), |
| 190 | timeout=5, |
| 191 | env=env, |
| 192 | ) |
| 193 | self.assertEqual(result.stdout.strip(), "custom_value") |
| 194 | |
| 195 | def test_on_pid_callback_receives_pid(self): |
| 196 | seen_pids = [] |
| 197 | subproc.run_with_timeout( |
| 198 | get_shell_cmd("true"), |
| 199 | timeout=5, |
| 200 | on_pid=lambda pid: seen_pids.append(pid), |
| 201 | ) |
| 202 | self.assertEqual(len(seen_pids), 1) |
| 203 | self.assertIsInstance(seen_pids[0], int) |
| 204 | self.assertGreater(seen_pids[0], 0) |
| 205 | |
| 206 | def test_child_pid_registered_during_run_and_cleared_after(self): |
| 207 | """Every run_with_timeout child is in the cleanup registry while alive.""" |
| 208 | seen = [] |
| 209 | observed_registered = [] |
| 210 | observed_job = [] |
| 211 | |
| 212 | def observe(pid): |
| 213 | seen.append(pid) |
| 214 | observed_registered.append(pid in subproc._child_pids) |
| 215 | if IS_WINDOWS: |
| 216 | observed_job.append(pid in subproc._child_jobs) |
| 217 | |
| 218 | with patch.object( |
| 219 | subproc, "unregister_child_pid", wraps=subproc.unregister_child_pid |
| 220 | ) as unreg: |
| 221 | result = subproc.run_with_timeout( |
| 222 | get_shell_cmd("echo ok"), |
| 223 | timeout=5, |
| 224 | on_pid=observe, |
| 225 | ) |
| 226 | self.assertEqual(result.stdout.strip(), "ok") |
| 227 | self.assertEqual(observed_registered, [True]) |
| 228 | if IS_WINDOWS: |
| 229 | self.assertEqual(observed_job, [True]) |
| 230 | unreg.assert_called_once_with(seen[0]) |
| 231 | self.assertEqual(subproc._child_pids, set()) |
| 232 | self.assertEqual(subproc._child_jobs, {}) |
| 233 | |
| 234 | def test_timed_out_child_is_unregistered(self): |
| 235 | with self.assertRaises(subproc.SubprocTimeout): |
| 236 | subproc.run_with_timeout(get_shell_cmd("sleep 10"), timeout=1) |
| 237 | self.assertEqual(subproc._child_pids, set()) |
| 238 | |
| 239 | @unittest.skipIf(IS_WINDOWS, "process groups are POSIX-only") |
| 240 | def test_cleanup_children_kills_group_spawned_on_worker_thread(self): |
| 241 | """Pipeline sources spawn on ThreadPoolExecutor workers; the main-thread |
| 242 | SIGTERM handler must see those children in the same registry and kill |
| 243 | the whole setsid group, grandchildren included.""" |
| 244 | import tempfile |
| 245 | import threading |
| 246 | import time |
| 247 | |
| 248 | outcome = {} |
| 249 | registered = threading.Event() |
| 250 | |
| 251 | def on_pid(pid): |
| 252 | outcome["pid"] = pid |
| 253 | registered.set() |
| 254 | |
| 255 | with tempfile.TemporaryDirectory() as tmp: |
| 256 | pidfile = real_os.path.join(tmp, "grandchild.pid") |
| 257 | |
| 258 | def worker(): |
| 259 | try: |
| 260 | subproc.run_with_timeout( |
| 261 | ["sh", "-c", f"sleep 30 & echo $! > {pidfile}; wait"], |
| 262 | timeout=20, |
| 263 | on_pid=on_pid, |
| 264 | ) |
| 265 | outcome["error"] = None |
| 266 | except Exception as exc: |
| 267 | outcome["error"] = exc |
| 268 | |
| 269 | thread = threading.Thread(target=worker) |
| 270 | start = time.monotonic() |
| 271 | thread.start() |
| 272 | deadline = start + 5 |
| 273 | while time.monotonic() < deadline and not ( |
| 274 | real_os.path.exists(pidfile) and real_os.path.getsize(pidfile) |
| 275 | ): |
| 276 | time.sleep(0.01) |
| 277 | self.assertTrue(real_os.path.getsize(pidfile)) |
| 278 | self.assertTrue(registered.wait(max(0, deadline - time.monotonic()))) |
| 279 | self.assertIn(outcome["pid"], subproc._child_pids) |
| 280 | |
| 281 | subproc.cleanup_children() |
| 282 | thread.join(10) |
| 283 | |
| 284 | # The backgrounded sleep inherits the stdout pipe, so communicate() |
| 285 | # returns well before the 20s timeout only if the grandchild died too. |
| 286 | self.assertFalse(thread.is_alive()) |
| 287 | self.assertLess(time.monotonic() - start, 10) |
| 288 | self.assertIsNone(outcome["error"]) |
| 289 | self.assertEqual(subproc._child_pids, set()) |
| 290 | |
| 291 | @unittest.skipIf(IS_WINDOWS, "process groups are POSIX-only") |
| 292 | def test_cleanup_children_sigkills_term_ignoring_group(self): |
| 293 | """Engine SIGTERM cannot fall through to run_with_timeout's own SIGKILL |
| 294 | escalation, so cleanup_children must escalate a group whose leader and |
| 295 | grandchild both ignore SIGTERM.""" |
| 296 | import tempfile |
| 297 | import threading |
| 298 | import time |
| 299 | |
| 300 | outcome = {} |
| 301 | registered = threading.Event() |
| 302 | with tempfile.TemporaryDirectory() as tmp: |
| 303 | pidfile = real_os.path.join(tmp, "grandchild.pid") |
| 304 | |
| 305 | def worker(): |
| 306 | try: |
| 307 | outcome["result"] = subproc.run_with_timeout( |
| 308 | ["sh", "-c", f"trap '' TERM; sleep 30 & echo $! > {pidfile}; wait"], |
| 309 | timeout=20, |
| 310 | on_pid=lambda _: registered.set(), |
| 311 | ) |
| 312 | except Exception as exc: |
| 313 | outcome["error"] = exc |
| 314 | |
| 315 | thread = threading.Thread(target=worker) |
| 316 | thread.start() |
| 317 | deadline = time.monotonic() + 5 |
| 318 | while time.monotonic() < deadline and not ( |
| 319 | real_os.path.exists(pidfile) and real_os.path.getsize(pidfile) |
| 320 | ): |
| 321 | time.sleep(0.01) |
| 322 | self.assertTrue(real_os.path.getsize(pidfile)) |
| 323 | self.assertTrue(registered.wait(max(0, deadline - time.monotonic()))) |
| 324 | |
| 325 | start = time.monotonic() |
| 326 | subproc.cleanup_children(grace=0.3) |
| 327 | elapsed = time.monotonic() - start |
| 328 | thread.join(5) |
| 329 | |
| 330 | self.assertGreaterEqual(elapsed, 0.3) |
| 331 | self.assertLess(elapsed, 1.0) |
| 332 | self.assertFalse(thread.is_alive()) |
| 333 | self.assertNotIn("error", outcome) |
| 334 | self.assertEqual(outcome["result"].returncode, -9) |
| 335 | self.assertEqual(subproc._child_pids, set()) |
| 336 | |
| 337 | @unittest.skipIf(IS_WINDOWS, "process groups are POSIX-only") |
| 338 | def test_child_registered_after_cleanup_started_is_killed(self): |
| 339 | """Workers keep running while the handler waits out the grace; a child |
| 340 | spawned after the snapshot must not outlive the engine.""" |
| 341 | import time |
| 342 | |
| 343 | subproc._shutting_down = True |
| 344 | start = time.monotonic() |
| 345 | result = subproc.run_with_timeout(get_shell_cmd("sleep 10"), timeout=5) |
| 346 | self.assertEqual(result.returncode, -9) |
| 347 | self.assertLess(time.monotonic() - start, 2) |
| 348 | self.assertEqual(subproc._child_pids, set()) |
| 349 | |
| 350 | def test_cleanup_children_returns_immediately_when_registry_empty(self): |
| 351 | import time |
| 352 | |
| 353 | self.assertEqual(subproc._child_pids, set()) |
| 354 | start = time.monotonic() |
| 355 | subproc.cleanup_children() |
| 356 | self.assertLess(time.monotonic() - start, 0.05) |
| 357 | |
| 358 | def test_cleanup_grace_fits_inside_mcp_term_grace(self): |
| 359 | """The engine's SIGTERM handler runs cleanup_children; the MCP server |
| 360 | SIGKILLs the engine termGracePeriod after its SIGTERM. Keep at least |
| 361 | half of that window as margin for the SIGKILL pass and handler exit.""" |
| 362 | import pathlib |
| 363 | import re |
| 364 | |
| 365 | run_go = pathlib.Path(__file__).resolve().parents[1] / "mcp" / "internal" / "engine" / "run.go" |
| 366 | match = re.search( |
| 367 | r"^const termGracePeriod = (\d+) \* time\.Second$", |
| 368 | run_go.read_text(encoding="utf-8"), |
| 369 | re.M, |
| 370 | ) |
| 371 | self.assertIsNotNone(match, "termGracePeriod declaration not found in run.go") |
| 372 | self.assertLessEqual(subproc.CLEANUP_TERM_GRACE_SECONDS * 2, int(match.group(1))) |
| 373 | |
| 374 | def test_lib_never_imports_engine_entrypoint(self): |
| 375 | """last30days.py runs as __main__; importing it by name from lib/ |
| 376 | executes a second copy whose state (child registry, signal handler) |
| 377 | the running engine never sees.""" |
| 378 | import pathlib |
| 379 | import re |
| 380 | |
| 381 | lib_dir = pathlib.Path(subproc.__file__).parent |
| 382 | pattern = re.compile(r"^\s*(from\s+last30days\s+import|import\s+last30days\b)", re.M) |
| 383 | offenders = [ |
| 384 | str(path.relative_to(lib_dir)) |
| 385 | for path in lib_dir.rglob("*.py") |
| 386 | if pattern.search(path.read_text(encoding="utf-8", errors="replace")) |
| 387 | ] |
| 388 | self.assertEqual(offenders, []) |
| 389 | |
| 390 | @unittest.skipIf(IS_WINDOWS, "POSIX fallback simulation uses sh") |
| 391 | def test_timeout_falls_back_to_kill_when_killpg_unavailable(self): |
| 392 | """Without POSIX groups or Windows tree cleanup, kill the direct child.""" |
| 393 | real_hasattr = builtins.hasattr |
| 394 | |
| 395 | def selective_hasattr(obj, name): |
| 396 | if obj is real_os and name in ("killpg", "getpgid", "setsid"): |
| 397 | return False |
| 398 | return real_hasattr(obj, name) |
| 399 | |
| 400 | with patch.object(builtins, "hasattr", side_effect=selective_hasattr): |
| 401 | with self.assertRaises(subproc.SubprocTimeout): |
| 402 | subproc.run_with_timeout( |
| 403 | ["sh", "-c", "sleep 10"], |
| 404 | timeout=1, |
| 405 | ) |
| 406 | |
| 407 | def test_windows_timeout_terminates_owned_process_tree(self): |
| 408 | timeout_error = subproc.subprocess.TimeoutExpired("node", 1) |
| 409 | |
| 410 | class FakeProc: |
| 411 | pid = 4321 |
| 412 | _handle = 9876 |
| 413 | stdin = stdout = stderr = None |
| 414 | returncode = None |
| 415 | |
| 416 | def __init__(self): |
| 417 | self.killed = False |
| 418 | |
| 419 | def communicate(self, **kwargs): |
| 420 | raise timeout_error |
| 421 | |
| 422 | def wait(self, timeout=None): |
| 423 | self.returncode = 1 |
| 424 | return 1 |
| 425 | |
| 426 | def poll(self): |
| 427 | return self.returncode |
| 428 | |
| 429 | def kill(self): |
| 430 | self.killed = True |
| 431 | |
| 432 | fake = FakeProc() |
| 433 | real_hasattr = builtins.hasattr |
| 434 | |
| 435 | def windows_hasattr(obj, name): |
| 436 | if obj is real_os and name in ("setsid", "killpg"): |
| 437 | return False |
| 438 | return real_hasattr(obj, name) |
| 439 | |
| 440 | job = MagicMock() |
| 441 | job.terminate.return_value = True |
| 442 | with patch.object(builtins, "hasattr", side_effect=windows_hasattr), \ |
| 443 | patch.object(subproc, "_WINDOWS", True), \ |
| 444 | patch("lib.windows_job.WindowsJob", return_value=job), \ |
| 445 | patch("lib.windows_job.resume_suspended_process") as resume, \ |
| 446 | patch.object(subproc, "_kill_windows_tree") as kill_tree, \ |
| 447 | patch.object(subproc.subprocess, "Popen", return_value=fake): |
| 448 | with self.assertRaises(subproc.SubprocTimeout): |
| 449 | subproc.run_with_timeout(["node", "bird-search.mjs"], timeout=1) |
| 450 | |
| 451 | job.assign.assert_called_once_with(fake._handle) |
| 452 | resume.assert_called_once_with(fake.pid) |
| 453 | job.terminate.assert_called_once_with() |
| 454 | kill_tree.assert_not_called() |
| 455 | self.assertFalse(fake.killed) |
| 456 | |
| 457 | def test_windows_tree_kill_uses_pid_scoped_taskkill_and_handles_failure(self): |
| 458 | import subprocess |
| 459 | |
| 460 | with patch.object(subproc.subprocess, "run", return_value=subprocess.CompletedProcess([], 0)) as run: |
| 461 | self.assertTrue(subproc._kill_windows_tree(4321)) |
| 462 | run.assert_called_once_with( |
| 463 | ["taskkill", "/F", "/T", "/PID", "4321"], |
| 464 | stdin=subprocess.DEVNULL, |
| 465 | stdout=subprocess.DEVNULL, |
| 466 | stderr=subprocess.DEVNULL, |
| 467 | timeout=2, |
| 468 | check=False, |
| 469 | creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), |
| 470 | ) |
| 471 | |
| 472 | with patch.object(subproc.subprocess, "run", side_effect=subprocess.TimeoutExpired("taskkill", 2)): |
| 473 | self.assertFalse(subproc._kill_windows_tree(4321)) |
| 474 | |
| 475 | with patch.object(subproc.subprocess, "run", return_value=subprocess.CompletedProcess([], 1)): |
| 476 | self.assertFalse(subproc._kill_windows_tree(4321)) |
| 477 | |
| 478 | def test_windows_shutdown_terminates_owned_process_tree(self): |
| 479 | real_hasattr = builtins.hasattr |
| 480 | |
| 481 | def windows_hasattr(obj, name): |
| 482 | if obj is real_os and name in ("setsid", "killpg"): |
| 483 | return False |
| 484 | return real_hasattr(obj, name) |
| 485 | |
| 486 | with patch.object(builtins, "hasattr", side_effect=windows_hasattr), \ |
| 487 | patch.object(subproc, "_WINDOWS", True), \ |
| 488 | patch.object(subproc, "_child_pids", {4321}), \ |
| 489 | patch.object(subproc, "_shutting_down", False), \ |
| 490 | patch.object(subproc, "_kill_windows_tree", return_value=True) as kill_tree: |
| 491 | subproc.cleanup_children() |
| 492 | |
| 493 | kill_tree.assert_called_once_with(4321) |
| 494 | |
| 495 | def test_windows_tree_kill_failure_falls_back_to_direct_child(self): |
| 496 | timeout_error = subproc.subprocess.TimeoutExpired("node", 1) |
| 497 | |
| 498 | class FakeProc: |
| 499 | pid = 4321 |
| 500 | _handle = 9876 |
| 501 | stdin = stdout = stderr = None |
| 502 | returncode = None |
| 503 | |
| 504 | def __init__(self): |
| 505 | self.killed = False |
| 506 | |
| 507 | def communicate(self, **kwargs): |
| 508 | raise timeout_error |
| 509 | |
| 510 | def wait(self, timeout=None): |
| 511 | self.returncode = 1 |
| 512 | return 1 |
| 513 | |
| 514 | def poll(self): |
| 515 | return self.returncode |
| 516 | |
| 517 | def kill(self): |
| 518 | self.killed = True |
| 519 | |
| 520 | fake = FakeProc() |
| 521 | real_hasattr = builtins.hasattr |
| 522 | |
| 523 | def windows_hasattr(obj, name): |
| 524 | if obj is real_os and name in ("setsid", "killpg"): |
| 525 | return False |
| 526 | return real_hasattr(obj, name) |
| 527 | |
| 528 | job = MagicMock() |
| 529 | job.terminate.return_value = False |
| 530 | with patch.object(builtins, "hasattr", side_effect=windows_hasattr), \ |
| 531 | patch.object(subproc, "_WINDOWS", True), \ |
| 532 | patch("lib.windows_job.WindowsJob", return_value=job), \ |
| 533 | patch("lib.windows_job.resume_suspended_process") as resume, \ |
| 534 | patch.object(subproc, "_kill_windows_tree", return_value=False) as kill_tree, \ |
| 535 | patch.object(subproc.subprocess, "Popen", return_value=fake): |
| 536 | with self.assertRaises(subproc.SubprocTimeout): |
| 537 | subproc.run_with_timeout(["node", "bird-search.mjs"], timeout=1) |
| 538 | |
| 539 | job.assign.assert_called_once_with(fake._handle) |
| 540 | resume.assert_called_once_with(fake.pid) |
| 541 | job.terminate.assert_called_once_with() |
| 542 | kill_tree.assert_called_once_with(fake.pid) |
| 543 | self.assertTrue(fake.killed) |
| 544 | |
| 545 | @unittest.skipUnless(IS_WINDOWS, "native Windows process-tree validation") |
| 546 | def test_windows_timeout_kills_shim_grandchild(self): |
| 547 | self._assert_windows_timeout_kills_grandchild(shim_exits=False) |
| 548 | |
| 549 | @unittest.skipUnless(IS_WINDOWS, "native Windows process-tree validation") |
| 550 | def test_windows_timeout_kills_grandchild_after_shim_exits(self): |
| 551 | self._assert_windows_timeout_kills_grandchild(shim_exits=True) |
| 552 | |
| 553 | @unittest.skipUnless(IS_WINDOWS, "native Windows process-tree validation") |
| 554 | def test_windows_timeout_kills_grandchild_after_two_ancestors_exit(self): |
| 555 | self._assert_windows_timeout_kills_grandchild(shim_exits=True, intermediate_exits=True) |
| 556 | |
| 557 | @unittest.skipUnless(IS_WINDOWS, "native Windows process-tree validation") |
| 558 | def test_windows_success_reaps_detached_grandchild(self): |
| 559 | self._assert_windows_timeout_kills_grandchild(shim_exits=True, normal_exit=True) |
| 560 | |
| 561 | @unittest.skipUnless(IS_WINDOWS, "native Windows process-tree validation") |
| 562 | def test_windows_job_assignment_failure_never_starts_child(self): |
| 563 | import pathlib |
| 564 | import sys |
| 565 | import tempfile |
| 566 | |
| 567 | from lib.windows_job import WindowsJob |
| 568 | |
| 569 | spawned = [] |
| 570 | real_popen = subproc.subprocess.Popen |
| 571 | |
| 572 | def record_spawn(*args, **kwargs): |
| 573 | proc = real_popen(*args, **kwargs) |
| 574 | spawned.append(proc) |
| 575 | return proc |
| 576 | |
| 577 | with tempfile.TemporaryDirectory() as tmp: |
| 578 | marker = pathlib.Path(tmp, "started") |
| 579 | try: |
| 580 | with patch.object(WindowsJob, "assign", side_effect=OSError("job assignment refused")), \ |
| 581 | patch.object(subproc.subprocess, "Popen", side_effect=record_spawn): |
| 582 | with self.assertRaisesRegex(OSError, "job assignment refused"): |
| 583 | subproc.run_with_timeout( |
| 584 | [sys.executable, "-c", "import pathlib,sys;pathlib.Path(sys.argv[1]).touch()", str(marker)], |
| 585 | timeout=2, |
| 586 | ) |
| 587 | self.assertEqual(len(spawned), 1) |
| 588 | self.assertIsNotNone(spawned[0].poll(), "suspended child survived assignment failure") |
| 589 | self.assertFalse(marker.exists(), "child ran without a process job") |
| 590 | self.assertNotIn(spawned[0].pid, subproc._child_pids) |
| 591 | self.assertNotIn(spawned[0].pid, subproc._child_jobs) |
| 592 | finally: |
| 593 | for proc in spawned: |
| 594 | if proc.poll() is None: |
| 595 | proc.kill() |
| 596 | proc.wait(timeout=2) |
| 597 | |
| 598 | @unittest.skipUnless(IS_WINDOWS, "native Windows process-tree validation") |
| 599 | def test_windows_shutdown_during_registration_never_starts_child(self): |
| 600 | import pathlib |
| 601 | import sys |
| 602 | import tempfile |
| 603 | |
| 604 | from lib.windows_job import WindowsJob |
| 605 | |
| 606 | spawned = [] |
| 607 | real_popen = subproc.subprocess.Popen |
| 608 | real_assign = WindowsJob.assign |
| 609 | |
| 610 | def record_spawn(*args, **kwargs): |
| 611 | proc = real_popen(*args, **kwargs) |
| 612 | spawned.append(proc) |
| 613 | return proc |
| 614 | |
| 615 | def shut_down_before_registration(job, handle): |
| 616 | real_assign(job, handle) |
| 617 | subproc._shutting_down = True |
| 618 | |
| 619 | with tempfile.TemporaryDirectory() as tmp: |
| 620 | marker = pathlib.Path(tmp, "started") |
| 621 | try: |
| 622 | with patch.object(WindowsJob, "assign", shut_down_before_registration), \ |
| 623 | patch.object(subproc.subprocess, "Popen", side_effect=record_spawn): |
| 624 | with self.assertRaises(subproc.SubprocTimeout): |
| 625 | subproc.run_with_timeout( |
| 626 | [sys.executable, "-c", "import pathlib,sys;pathlib.Path(sys.argv[1]).touch()", str(marker)], |
| 627 | timeout=2, |
| 628 | ) |
| 629 | self.assertEqual(len(spawned), 1) |
| 630 | self.assertIsNotNone(spawned[0].poll(), "suspended child survived shutdown") |
| 631 | self.assertFalse(marker.exists(), "child ran after shutdown began") |
| 632 | self.assertNotIn(spawned[0].pid, subproc._child_pids) |
| 633 | self.assertNotIn(spawned[0].pid, subproc._child_jobs) |
| 634 | finally: |
| 635 | for proc in spawned: |
| 636 | if proc.poll() is None: |
| 637 | proc.kill() |
| 638 | proc.wait(timeout=2) |
| 639 | |
| 640 | def _assert_windows_timeout_kills_grandchild(self, *, shim_exits, intermediate_exits=False, normal_exit=False): |
| 641 | import ctypes |
| 642 | import pathlib |
| 643 | import signal |
| 644 | import sys |
| 645 | import tempfile |
| 646 | import threading |
| 647 | import time |
| 648 | |
| 649 | kernel = ctypes.WinDLL("kernel32", use_last_error=True) |
| 650 | kernel.OpenProcess.argtypes = (ctypes.c_ulong, ctypes.c_int, ctypes.c_ulong) |
| 651 | kernel.OpenProcess.restype = ctypes.c_void_p |
| 652 | kernel.GetExitCodeProcess.argtypes = (ctypes.c_void_p, ctypes.POINTER(ctypes.c_ulong)) |
| 653 | kernel.GetExitCodeProcess.restype = ctypes.c_int |
| 654 | kernel.CloseHandle.argtypes = (ctypes.c_void_p,) |
| 655 | |
| 656 | def running(pid): |
| 657 | handle = kernel.OpenProcess(0x1000, False, pid) |
| 658 | if not handle: |
| 659 | return False |
| 660 | try: |
| 661 | exit_code = ctypes.c_ulong() |
| 662 | self.assertTrue(kernel.GetExitCodeProcess(handle, ctypes.byref(exit_code))) |
| 663 | return exit_code.value == 259 |
| 664 | finally: |
| 665 | kernel.CloseHandle(handle) |
| 666 | |
| 667 | grandchild = ( |
| 668 | "import os,pathlib,sys,time;" |
| 669 | "pathlib.Path(sys.argv[1]).write_text(str(os.getpid()));" |
| 670 | "time.sleep(12)" |
| 671 | ) |
| 672 | shim = ( |
| 673 | "import subprocess,sys,time;" |
| 674 | "subprocess.Popen([sys.executable,'-c',sys.argv[2],sys.argv[1]]" |
| 675 | + (",stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL" if normal_exit else "") |
| 676 | + ");" |
| 677 | + ("" if shim_exits else "time.sleep(30)") |
| 678 | ) |
| 679 | with tempfile.TemporaryDirectory() as tmp: |
| 680 | pidfile = pathlib.Path(tmp, "grandchild.pid") |
| 681 | intermediate_pidfile = pathlib.Path(tmp, "intermediate.pid") |
| 682 | if intermediate_exits: |
| 683 | intermediate = ( |
| 684 | "import os,pathlib,subprocess,sys;" |
| 685 | "pathlib.Path(sys.argv[1]).write_text(str(os.getpid()));" |
| 686 | "subprocess.Popen([sys.executable,'-c',sys.argv[3],sys.argv[2]])" |
| 687 | ) |
| 688 | shim = ( |
| 689 | "import subprocess,sys;" |
| 690 | "subprocess.Popen([sys.executable,'-c',sys.argv[3],sys.argv[1],sys.argv[2],sys.argv[4]])" |
| 691 | ) |
| 692 | cmd = [ |
| 693 | sys.executable, "-c", shim, str(intermediate_pidfile), |
| 694 | str(pidfile), intermediate, grandchild, |
| 695 | ] |
| 696 | else: |
| 697 | cmd = [sys.executable, "-c", shim, str(pidfile), grandchild] |
| 698 | shim_pids = [] |
| 699 | observed_live = [] |
| 700 | observed_root_exit = [] |
| 701 | observed_intermediate_exit = [] |
| 702 | bystander = ( |
| 703 | subproc.subprocess.Popen( |
| 704 | [sys.executable, "-c", "import time;time.sleep(12)"], |
| 705 | stdout=subproc.subprocess.DEVNULL, |
| 706 | stderr=subproc.subprocess.DEVNULL, |
| 707 | ) |
| 708 | if shim_exits else None |
| 709 | ) |
| 710 | |
| 711 | def wait_for_grandchild(pid): |
| 712 | shim_pids.append(pid) |
| 713 | deadline = time.monotonic() + 5 |
| 714 | while time.monotonic() < deadline: |
| 715 | if pidfile.exists() and pidfile.stat().st_size: |
| 716 | observed_live.append(running(int(pidfile.read_text()))) |
| 717 | if shim_exits: |
| 718 | while running(pid) and time.monotonic() < deadline: |
| 719 | time.sleep(0.01) |
| 720 | observed_root_exit.append(not running(pid)) |
| 721 | if intermediate_exits: |
| 722 | while not intermediate_pidfile.exists() and time.monotonic() < deadline: |
| 723 | time.sleep(0.01) |
| 724 | if intermediate_pidfile.exists(): |
| 725 | intermediate_pid = int(intermediate_pidfile.read_text()) |
| 726 | while running(intermediate_pid) and time.monotonic() < deadline: |
| 727 | time.sleep(0.01) |
| 728 | observed_intermediate_exit.append(not running(intermediate_pid)) |
| 729 | return |
| 730 | time.sleep(0.01) |
| 731 | self.fail("grandchild did not write its PID") |
| 732 | |
| 733 | def kill_owned_processes(): |
| 734 | grandchild_pid = pidfile.read_text().strip() if pidfile.exists() else "" |
| 735 | targets = shim_pids + ([int(grandchild_pid)] if grandchild_pid.isdigit() else []) |
| 736 | if intermediate_pidfile.exists(): |
| 737 | targets.append(int(intermediate_pidfile.read_text())) |
| 738 | for pid in targets: |
| 739 | if running(pid): |
| 740 | try: |
| 741 | subproc.subprocess.run( |
| 742 | ["taskkill", "/F", "/T", "/PID", str(pid)], |
| 743 | stdout=subproc.subprocess.DEVNULL, |
| 744 | stderr=subproc.subprocess.DEVNULL, |
| 745 | timeout=2, |
| 746 | check=False, |
| 747 | ) |
| 748 | except (OSError, subproc.subprocess.TimeoutExpired): |
| 749 | pass |
| 750 | if running(pid): |
| 751 | try: |
| 752 | real_os.kill(pid, signal.SIGTERM) |
| 753 | except OSError: |
| 754 | pass |
| 755 | |
| 756 | watchdog = threading.Timer(10, kill_owned_processes) |
| 757 | watchdog.daemon = True |
| 758 | watchdog.start() |
| 759 | try: |
| 760 | started = time.monotonic() |
| 761 | if normal_exit: |
| 762 | result = subproc.run_with_timeout(cmd, timeout=5, on_pid=wait_for_grandchild) |
| 763 | self.assertEqual(result.returncode, 0) |
| 764 | else: |
| 765 | with self.assertRaises(subproc.SubprocTimeout): |
| 766 | subproc.run_with_timeout(cmd, timeout=0.2, on_pid=wait_for_grandchild) |
| 767 | self.assertLess(time.monotonic() - started, 8, "cleanup waited for the grandchild to exit") |
| 768 | self.assertTrue(shim_pids) |
| 769 | self.assertEqual(observed_live, [True], "grandchild was not alive before timeout") |
| 770 | if shim_exits: |
| 771 | self.assertEqual(observed_root_exit, [True], "shim did not exit before timeout") |
| 772 | if intermediate_exits: |
| 773 | self.assertEqual(observed_intermediate_exit, [True], "intermediate did not exit before timeout") |
| 774 | self.assertTrue(pidfile.exists()) |
| 775 | shim_pid = shim_pids[0] |
| 776 | grandchild_pid = int(pidfile.read_text()) |
| 777 | self.assertFalse(running(shim_pid), "shim survived its timeout") |
| 778 | self.assertFalse(running(grandchild_pid), "grandchild survived its timeout") |
| 779 | if bystander is not None: |
| 780 | self.assertTrue(running(bystander.pid), "unrelated process was terminated") |
| 781 | finally: |
| 782 | watchdog.cancel() |
| 783 | kill_owned_processes() |
| 784 | if bystander is not None and running(bystander.pid): |
| 785 | bystander.kill() |
| 786 | bystander.wait(timeout=2) |
| 787 | |
| 788 | def test_on_pid_callback_exceptions_are_suppressed(self): |
| 789 | """If the PID callback raises, the subprocess should still run to completion.""" |
| 790 | def raising_callback(pid): |
| 791 | raise RuntimeError("boom") |
| 792 | |
| 793 | # Should not raise, callback exception is swallowed. |
| 794 | result = subproc.run_with_timeout( |
| 795 | get_shell_cmd("echo ok"), |
| 796 | timeout=5, |
| 797 | on_pid=raising_callback, |
| 798 | ) |
| 799 | self.assertEqual(result.returncode, 0) |
| 800 | self.assertEqual(result.stdout.strip(), "ok") |
| 801 | |
| 802 | @unittest.skipIf(IS_WINDOWS, "POSIX SIGTERM escalation uses sh") |
| 803 | def test_sigterm_ignoring_child_is_sigkill_escalated(self): |
| 804 | """A child that ignores SIGTERM must be escalated to SIGKILL. |
| 805 | |
| 806 | Without escalation, ``proc.wait(timeout=5)`` raises |
| 807 | ``subprocess.TimeoutExpired`` past the ``except`` block instead of the |
| 808 | documented ``SubprocTimeout``, and the child stays alive. |
| 809 | """ |
| 810 | with self.assertRaises(subproc.SubprocTimeout): |
| 811 | subproc.run_with_timeout( |
| 812 | ["sh", "-c", "trap '' TERM; sleep 30"], |
| 813 | timeout=1, |
| 814 | ) |
| 815 | |
| 816 | @unittest.skipIf(IS_WINDOWS, "POSIX killpg simulation requires os.getpgid") |
| 817 | def test_escalation_path_guards_killpg_attributeerror(self): |
| 818 | """The SIGKILL escalation must not crash if killpg is unavailable (Windows). |
| 819 | |
| 820 | Regression for the #588 class of bug on the escalation path added in |
| 821 | #433: os.killpg raising AttributeError must be caught and fall back to |
| 822 | proc.kill(), so the documented SubprocTimeout surfaces instead of a bare |
| 823 | AttributeError. The primary SIGTERM path was already guarded (#552); this |
| 824 | mirrors that guard on the escalation path. |
| 825 | """ |
| 826 | TimeoutExpired = subproc.subprocess.TimeoutExpired |
| 827 | |
| 828 | class _FakeProc: |
| 829 | def __init__(self): |
| 830 | self.pid = 4321 |
| 831 | self.kill_count = 0 |
| 832 | self.stdin = self.stdout = self.stderr = None |
| 833 | |
| 834 | def communicate(self, timeout=None, input=None): |
| 835 | raise TimeoutExpired(cmd="x", timeout=timeout) |
| 836 | |
| 837 | def wait(self, timeout=None): |
| 838 | # First wait (timeout=5) forces the SIGKILL escalation branch; |
| 839 | # the final bounded wait is swallowed if the process still |
| 840 | # refuses to exit. |
| 841 | if timeout is not None: |
| 842 | raise TimeoutExpired(cmd="x", timeout=timeout) |
| 843 | return 0 |
| 844 | |
| 845 | def kill(self): |
| 846 | self.kill_count += 1 |
| 847 | |
| 848 | fake = _FakeProc() |
| 849 | with patch.object(subproc.subprocess, "Popen", return_value=fake), \ |
| 850 | patch.object(subproc.os, "getpgid", lambda pid: pid), \ |
| 851 | patch.object(subproc.os, "killpg", side_effect=AttributeError("no killpg on Windows")): |
| 852 | with self.assertRaises(subproc.SubprocTimeout): |
| 853 | subproc.run_with_timeout(["x"], timeout=1) |
| 854 | # Both the primary and escalation paths must have fallen back to kill(). |
| 855 | self.assertGreaterEqual(fake.kill_count, 2) |
| 856 | |
| 857 | |
| 858 | class TestWindowsBatchProbe(unittest.TestCase): |
| 859 | @unittest.skipUnless(IS_WINDOWS, "Windows .cmd batch execution test") |
| 860 | def test_probe_dependency_runs_windows_cmd_in_dir_with_spaces(self): |
| 861 | import tempfile |
| 862 | from pathlib import Path |
| 863 | from lib import health |
| 864 | |
| 865 | health.clear_dependency_probe_cache() |
| 866 | self.addCleanup(health.clear_dependency_probe_cache) |
| 867 | with tempfile.TemporaryDirectory() as tmp: |
| 868 | spaced_dir = Path(tmp) / "dir with spaces" |
| 869 | spaced_dir.mkdir() |
| 870 | shim = spaced_dir / "fakecli.cmd" |
| 871 | shim.write_text("@echo off\r\necho fakecli 1.2.3\r\n", encoding="ascii") |
| 872 | existing_path = real_os.environ.get("PATH", "") |
| 873 | with patch.dict( |
| 874 | real_os.environ, |
| 875 | {"PATH": f"{spaced_dir}{real_os.pathsep}{existing_path}"}, |
| 876 | ): |
| 877 | probe = health.probe_dependency("fakecli") |
| 878 | self.assertEqual(probe.status, health.OK) |
| 879 | self.assertTrue(probe.ok) |
| 880 | self.assertIn("1.2.3", probe.detail) |
| 881 | |
| 882 | |
| 883 | if __name__ == "__main__": |
| 884 | unittest.main() |
| 885 |