Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions scripts/run_semantic_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -33,6 +36,7 @@
import math
import os
import re
import signal
import subprocess
import sys
import tempfile
Expand All @@ -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
Expand All @@ -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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Bound the pipe drain after sending the group kill. A helper that deliberately starts its own session can inherit the worker's stdout and stderr. The helper is outside the stated kill scope, but the second, unbounded proc.communicate() still waits for its pipes. A synthetic parallel worker with a detached helper that sleeps 2.5 s took 2.66 s to return for --timeout 0.5. A long-lived helper can hold the runner open indefinitely. Could the timeout path give the pipes a bounded drain without terminating the detached helper?

except (ProcessLookupError, PermissionError):
pass
try:
proc.kill()
except OSError:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
32 changes: 32 additions & 0 deletions tests/test_run_semantic_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading