From 50137410157eb8428277f5f7b866d54519c85705 Mon Sep 17 00:00:00 2001 From: alexandersato0830 <66799221+alexandersato0830@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:35:24 -0600 Subject: [PATCH] Reap semantic test children that race cancellation --- scripts/run_semantic_tests.py | 20 +++++++++--- tests/test_run_semantic_tests.py | 52 ++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 4 deletions(-) diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py index 514e781330..074b3454d8 100644 --- a/scripts/run_semantic_tests.py +++ b/scripts/run_semantic_tests.py @@ -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): @@ -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 ` 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 @@ -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: @@ -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) @@ -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: @@ -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: diff --git a/tests/test_run_semantic_tests.py b/tests/test_run_semantic_tests.py index 7fc75e3722..f9be1a817d 100644 --- a/tests/test_run_semantic_tests.py +++ b/tests/test_run_semantic_tests.py @@ -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")) @@ -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")