diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py index 514e781330..de9387cd36 100644 --- a/scripts/run_semantic_tests.py +++ b/scripts/run_semantic_tests.py @@ -23,7 +23,10 @@ `--timeout SECONDS` limits each module subprocess in parallel mode, or the entire discover subprocess with `-j 1`. The value must be positive and at most 86400 seconds (24 hours), keeping it within platform wait limits. A timeout fails the run and reports any output already produced; other parallel modules keep running. -The default has no time limit. This stops the direct test subprocess, not any descendants it may have started. +The default has no time limit. On POSIX, timed test subprocesses run in their own sessions: timeout and +cancellation stop their entire process groups, including helpers still holding the output pipes. Untimed +subprocesses stay in the caller's process group. Descendants that leave a timed worker's group are outside +the cleanup boundary. """ import argparse import concurrent.futures @@ -33,6 +36,7 @@ import math import os import re +import signal import subprocess import sys import tempfile @@ -56,6 +60,14 @@ def _unregister_process(proc): _active_processes.discard(proc) +def _start_test_process(cmd, timeout, **kwargs): + # Do not detach untimed jobs from the caller's ordinary process-group signals. + owns_group = os.name == "posix" and timeout is not None + proc = subprocess.Popen(cmd, start_new_session=owns_group, **kwargs) + proc._semantic_owns_group = owns_group + return proc + + def _kill_process_tree(proc): if proc is None: return @@ -65,6 +77,13 @@ def _kill_process_tree(proc): stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) except OSError: pass + elif os.name == "posix" and getattr(proc, "_semantic_owns_group", False): + # A launcher can exit while a helper still owns a copy of its output pipe. The session's group ID is + # the original worker PID even after the launcher exits. + try: + os.killpg(proc.pid, signal.SIGKILL) + except (ProcessLookupError, PermissionError): + pass try: proc.kill() except OSError: @@ -159,7 +178,7 @@ def run_module(directory, module, verbose, timeout=None): with tempfile.TemporaryDirectory() as scratch: count_path = os.path.join(scratch, "count.json") env = dict(os.environ, LEONIDA_TEST_COUNT=count_path) - proc = subprocess.Popen(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + proc = _start_test_process(cmd, timeout, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, errors="replace") _register_process(proc) try: @@ -208,7 +227,7 @@ def main(argv=None): if a.jobs <= 1: cmd = [sys.executable, "-m", "unittest", "discover", "-s", directory, "-p", a.pattern, *(["-v"] if a.verbose else [])] - proc = subprocess.Popen(cmd) + proc = _start_test_process(cmd, a.timeout) _register_process(proc) start_time = time.monotonic() try: diff --git a/tests/test_run_semantic_tests.py b/tests/test_run_semantic_tests.py index 7fc75e3722..5b546658b7 100644 --- a/tests/test_run_semantic_tests.py +++ b/tests/test_run_semantic_tests.py @@ -119,6 +119,38 @@ def test_serial_timeout_keeps_discover_output_and_names_the_suite(self): self.assertIn(tmp, result.stderr) self.assertNotIn("Traceback", result.stdout + result.stderr) + @unittest.skipUnless(os.name == "posix", "POSIX worker process groups") + def test_timeout_stops_helpers_holding_the_output_pipe(self): + child = "import time; time.sleep(6); print('helper-finished-marker', flush=True)" + for jobs, linger in ((1, True), (2, True), (2, False)): + with self.subTest(jobs=jobs, worker_lingers=linger), tempfile.TemporaryDirectory() as tmp: + source = ("import subprocess, sys, time, unittest\n" + "class T(unittest.TestCase):\n" + " def test_helper(self):\n" + f" subprocess.Popen([sys.executable, '-c', {child!r}])\n" + " print('helper-started-marker', flush=True)\n") + if linger: + source += " time.sleep(10)\n" + suite(tmp, {"test_helper.py": source}) + result = cli(tmp, "-j", str(jobs), "--timeout", "2") + output = result.stdout + result.stderr + self.assertEqual(result.returncode, 1, output) + self.assertIn("helper-started-marker", output) + self.assertIn("TIMED OUT after 2 s:", output) + self.assertNotIn("helper-finished-marker", output) + + @unittest.skipUnless(os.name == "posix", "POSIX worker process groups") + def test_untimed_workers_keep_the_runner_process_group(self): + source = ("import os, unittest\n" + "class T(unittest.TestCase):\n" + " def test_group(self):\n" + " self.assertEqual(os.getpgrp(), os.getpgid(os.getppid()))\n") + for jobs in (1, 2): + with self.subTest(jobs=jobs), tempfile.TemporaryDirectory() as tmp: + suite(tmp, {"test_group.py": source}) + result = cli(tmp, "-j", str(jobs)) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + def test_timeout_requires_positive_finite_seconds(self): for value in ("0", "-1", "nan", "inf", "-inf"): with self.subTest(value=value):