Skip to content
Closed
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
20 changes: 16 additions & 4 deletions scripts/run_semantic_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,12 @@
_processes_lock = threading.Lock()


def _register_process(proc):
def _register_process(proc, cancelled=None):
with _processes_lock:
if cancelled is not None and cancelled.is_set():
return False
_active_processes.add(proc)
return True


def _unregister_process(proc):
Expand Down Expand Up @@ -149,7 +152,7 @@ def read_count(path):
return 0


def run_module(directory, module, verbose, timeout=None):
def run_module(directory, module, verbose, timeout=None, cancelled=None):
"""(return code, tests run, output) of `python -m unittest <target>` run from `directory`."""
# `python -m unittest pkg.__init__` imports pkg and then runs the same file again as pkg.__init__, so a
# registration in the initializer happens twice. Running the package itself imports it once; module_path() is
Expand All @@ -159,9 +162,15 @@ 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)
if cancelled is not None and cancelled.is_set():
return 130, 0, ""
proc = subprocess.Popen(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, errors="replace")
_register_process(proc)
# Cancellation can take its snapshot while this worker is still inside Popen.
if not _register_process(proc, cancelled):
with proc:
_kill_process_tree(proc)
return 130, 0, ""
try:
stdout, stderr = proc.communicate(timeout=timeout)
except subprocess.TimeoutExpired:
Expand Down Expand Up @@ -239,10 +248,11 @@ def main(argv=None):
modules.sort(key=lambda m: -os.path.getsize(module_path(directory, m)))
start, total, failed = time.monotonic(), 0, []
pool = concurrent.futures.ThreadPoolExecutor(a.jobs)
cancelled = threading.Event()
jobs = {}
try:
for m in modules:
jobs[pool.submit(run_module, directory, m, a.verbose, a.timeout)] = m
jobs[pool.submit(run_module, directory, m, a.verbose, a.timeout, cancelled)] = m
pending = set(jobs)
while pending:
done, _ = concurrent.futures.wait(pending, timeout=0.2, return_when=concurrent.futures.FIRST_COMPLETED)
Expand All @@ -256,6 +266,7 @@ def main(argv=None):
elif a.verbose:
print(f"==== {jobs[job]}\n{out}", flush=True)
except KeyboardInterrupt:
cancelled.set()
for job in jobs:
job.cancel()
try:
Expand All @@ -266,6 +277,7 @@ def main(argv=None):
print("interrupted", file=sys.stderr)
return 130
except BaseException:
cancelled.set()
for job in jobs:
job.cancel()
try:
Expand Down
52 changes: 52 additions & 0 deletions tests/test_run_semantic_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import time
import unittest
import _thread
from unittest.mock import patch

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "scripts"))
Expand Down Expand Up @@ -324,6 +325,57 @@ def trigger():
self.assertEqual(len(started), 2, f"Expected 2 started modules, got {started}")
self.assertLess(elapsed, 5.0)

def test_interrupt_during_worker_launch_cleans_up_the_late_child(self):
with tempfile.TemporaryDirectory() as tmp:
marker = os.path.join(tmp, "completed")
suite(tmp, {"test_launch.py": (
"import time, unittest\n"
"from pathlib import Path\n"
"class T(unittest.TestCase):\n"
" def test_finish(self):\n"
" time.sleep(2)\n"
f" Path({marker!r}).touch()\n"
)})
spawned, resume, finished = threading.Event(), threading.Event(), threading.Event()
popen = subprocess.Popen
terminate_active = r._terminate_active_processes
run_module = r.run_module

def launch_before_registration(argv, **kwargs):
proc = popen(argv, **kwargs)
if argv[:2] == [sys.executable, "-c"]:
spawned.set()
if not resume.wait(5):
proc.kill()
proc.communicate()
raise RuntimeError("worker launch was never resumed")
return proc

def interrupt(*args, **kwargs):
self.assertTrue(spawned.wait(5))
raise KeyboardInterrupt

def resume_after_cancellation():
terminate_active()
resume.set()

def observe_worker(*args, **kwargs):
try:
return run_module(*args, **kwargs)
finally:
finished.set()

with (
patch.object(r.subprocess, "Popen", side_effect=launch_before_registration),
patch.object(r.concurrent.futures, "wait", side_effect=interrupt),
patch.object(r, "_terminate_active_processes", side_effect=resume_after_cancellation),
patch.object(r, "run_module", side_effect=observe_worker),
):
code, _ = run(tmp, "-j", "2")
self.assertTrue(finished.wait(7))
self.assertEqual(code, 130)
self.assertFalse(os.path.exists(marker), "untracked child completed after cancellation")

def test_serial_interrupt_returns_130_and_prints_interrupted(self):
with tempfile.TemporaryDirectory() as tmp, tempfile.TemporaryDirectory() as marker_dir:
marker = os.path.join(marker_dir, "serial_marker.txt")
Expand Down