From 542c046c503af54cf6b29436eff4877f4edb7de4 Mon Sep 17 00:00:00 2001 From: d7ommy Date: Wed, 25 Nov 2026 19:11:41 +0300 Subject: [PATCH 1/2] run_semantic_tests: stop active subprocesses and cancel queued modules on interrupt (SEMANTIC-RUNNER-INTERRUPT) Catch KeyboardInterrupt in run_semantic_tests.py, cancelling queued test modules via pool.shutdown(wait=False, cancel_futures=True) and terminating active child subprocesses so that no orphaned zombie processes or queued modules run after Ctrl+C. In serial mode (-j 1), terminate the discover subprocess on interrupt. Return exit code 130 and output 'interrupted' to stderr without printing a false success summary. Adds regression and lifecycle tests in tests/test_run_semantic_tests.py. AI-assisted (Claude Code) --- scripts/run_semantic_tests.py | 158 +++++++++++++++++++++++++++---- tests/test_run_semantic_tests.py | 127 +++++++++++++++++++++++++ 2 files changed, 264 insertions(+), 21 deletions(-) diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py index 03e0ddab41..628e475744 100644 --- a/scripts/run_semantic_tests.py +++ b/scripts/run_semantic_tests.py @@ -36,10 +36,44 @@ import subprocess import sys import tempfile +import threading import time MAX_TIMEOUT_SECONDS = 24 * 60 * 60 +# The child processes running right now: on SIGINT / Ctrl+C, the main thread terminates them so no orphans linger. +_active_processes = set() +_processes_lock = threading.Lock() + + +def _register_process(proc): + with _processes_lock: + _active_processes.add(proc) + + +def _unregister_process(proc): + with _processes_lock: + _active_processes.discard(proc) + + +def _terminate_active_processes(): + with _processes_lock: + procs = list(_active_processes) + for p in procs: + try: + p.terminate() + except OSError: + pass + for p in procs: + try: + p.kill() + except OSError: + pass + try: + p.wait(timeout=0.2) + except (subprocess.TimeoutExpired, OSError): + pass + # The child runs the module through unittest's own program and writes the result to a file, so the count of tests # comes from the result object and nothing the module writes can change it. The exit codes are unittest's own: 1 # when a test failed, 5 when nothing ran at all, 0 otherwise. The module is left unset, as `python -m unittest` leaves it, so @@ -113,22 +147,41 @@ 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, + text=True, errors="replace") + _register_process(proc) try: - p = subprocess.run(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - text=True, errors="replace", timeout=timeout) - except subprocess.TimeoutExpired as exc: + stdout, stderr = proc.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + try: + proc.kill() + except OSError: + pass + stdout, stderr = proc.communicate() # TimeoutExpired retains bytes even when text=True. parts = [chunk.decode(locale.getpreferredencoding(False), errors="replace") if isinstance(chunk, bytes) - else chunk for chunk in (exc.stdout, exc.stderr) if chunk] + else chunk for chunk in (stdout, stderr) if chunk] out = "".join(parts) return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n" + except BaseException: + try: + proc.kill() + except OSError: + pass + try: + proc.wait(timeout=0.5) + except (subprocess.TimeoutExpired, OSError): + pass + raise + finally: + _unregister_process(proc) count = read_count(count_path) - out = p.stdout + p.stderr + out = stdout + stderr # Discover imports every package initializer, but an empty one has no tests to run. It is included in the # module list so parallel runs see TestCase classes when there are any; without them, it is not a failure. - if p.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in p.stderr: + if proc.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in stderr: return 0, 0, out - return p.returncode, count, out + return proc.returncode, count, out def main(argv=None): @@ -147,26 +200,85 @@ def main(argv=None): print(f"no {a.pattern} files in {directory}") return 1 if a.jobs <= 1: + cmd = [sys.executable, "-m", "unittest", "discover", "-s", directory, + "-p", a.pattern, *(["-v"] if a.verbose else [])] + proc = subprocess.Popen(cmd) + _register_process(proc) + start_time = time.monotonic() try: - return subprocess.call([sys.executable, "-m", "unittest", "discover", "-s", directory, - "-p", a.pattern, *(["-v"] if a.verbose else [])], timeout=a.timeout) + while True: + try: + return proc.wait(timeout=0.2) + except subprocess.TimeoutExpired: + if a.timeout is not None and time.monotonic() - start_time >= a.timeout: + raise except subprocess.TimeoutExpired: - # Inherited stdout/stderr have already emitted any partial test output. + try: + proc.kill() + except OSError: + pass print(f"TIMED OUT after {a.timeout:g} s: unittest discover in {directory}", file=sys.stderr) return 1 + except KeyboardInterrupt: + try: + proc.kill() + except OSError: + pass + try: + proc.wait(timeout=0.5) + except (subprocess.TimeoutExpired, OSError): + pass + print("interrupted", file=sys.stderr) + return 130 + except BaseException: + try: + proc.kill() + except OSError: + pass + raise + finally: + _unregister_process(proc) # Largest files first: they tend to run longest, and one started last would set the wall time alone. modules.sort(key=lambda m: -os.path.getsize(module_path(directory, m))) start, total, failed = time.monotonic(), 0, [] - with concurrent.futures.ThreadPoolExecutor(a.jobs) as pool: - jobs = {pool.submit(run_module, directory, m, a.verbose, a.timeout): m for m in modules} - for job in concurrent.futures.as_completed(jobs): - code, ran, out = job.result() - total += ran - if code: - failed.append(jobs[job]) - print(f"==== FAILED: {jobs[job]}\n{out}", flush=True) - elif a.verbose: - print(f"==== {jobs[job]}\n{out}", flush=True) + pool = concurrent.futures.ThreadPoolExecutor(a.jobs) + jobs = {} + try: + for m in modules: + jobs[pool.submit(run_module, directory, m, a.verbose, a.timeout)] = m + pending = set(jobs) + while pending: + done, _ = concurrent.futures.wait(pending, timeout=0.2, return_when=concurrent.futures.FIRST_COMPLETED) + for job in done: + pending.remove(job) + code, ran, out = job.result() + total += ran + if code: + failed.append(jobs[job]) + print(f"==== FAILED: {jobs[job]}\n{out}", flush=True) + elif a.verbose: + print(f"==== {jobs[job]}\n{out}", flush=True) + except KeyboardInterrupt: + for job in jobs: + job.cancel() + try: + pool.shutdown(wait=False, cancel_futures=True) + except TypeError: + pool.shutdown(wait=False) + _terminate_active_processes() + print("interrupted", file=sys.stderr) + return 130 + except BaseException: + for job in jobs: + job.cancel() + try: + pool.shutdown(wait=False, cancel_futures=True) + except TypeError: + pool.shutdown(wait=False) + _terminate_active_processes() + raise + else: + pool.shutdown(wait=True) took = time.monotonic() - start summary = f"{len(modules)} files, {total} tests, {len(failed)} files failed in {took:.0f} s with {a.jobs} jobs" print(summary + (": " + ", ".join(sorted(failed)) if failed else "")) @@ -183,4 +295,8 @@ def main(argv=None): sys.stdout.reconfigure(errors="replace") except (AttributeError, ValueError, OSError): pass - sys.exit(main()) + try: + sys.exit(main()) + except KeyboardInterrupt: + print("interrupted", file=sys.stderr) + sys.exit(130) diff --git a/tests/test_run_semantic_tests.py b/tests/test_run_semantic_tests.py index cf5f3803a6..aa57640fea 100644 --- a/tests/test_run_semantic_tests.py +++ b/tests/test_run_semantic_tests.py @@ -9,7 +9,10 @@ import subprocess import sys import tempfile +import threading +import time import unittest +import _thread ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(ROOT, "scripts")) @@ -282,6 +285,130 @@ def test_an_empty_suite_fails(self): self.assertEqual(code, 1) self.assertIn("no test*.py files", out) + def test_parallel_interrupt_stops_active_processes_and_cancels_queued_jobs(self): + with tempfile.TemporaryDirectory() as tmp, tempfile.TemporaryDirectory() as marker_dir: + mod_template = ( + "import os, time, unittest\n" + "class T(unittest.TestCase):\n" + " def test_run(self):\n" + " with open(r'{marker}', 'w') as f: f.write('1')\n" + " time.sleep(5)\n" + ) + files = { + f"test_{i}.py": mod_template.format(marker=os.path.join(marker_dir, f"m_{i}.txt")) + for i in range(4) + } + suite(tmp, files) + + def trigger(): + start = time.monotonic() + while time.monotonic() - start < 5: + if len(os.listdir(marker_dir)) >= 2: + break + time.sleep(0.05) + time.sleep(0.05) + _thread.interrupt_main() + + threading.Thread(target=trigger, daemon=True).start() + out, err = io.StringIO(), io.StringIO() + t0 = time.monotonic() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = r.main([tmp, "-j", "2"]) + elapsed = time.monotonic() - t0 + + self.assertEqual(code, 130) + self.assertIn("interrupted", err.getvalue()) + self.assertNotIn("files failed", out.getvalue()) + self.assertNotIn("4 files,", out.getvalue()) + started = os.listdir(marker_dir) + self.assertEqual(len(started), 2, f"Expected 2 started modules, got {started}") + self.assertLess(elapsed, 4.0) + + 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") + content = ( + "import os, time, unittest\n" + "class T(unittest.TestCase):\n" + f" def test_run(self):\n" + f" with open(r'{marker}', 'w') as f: f.write('1')\n" + " time.sleep(5)\n" + ) + suite(tmp, {"test_serial_hang.py": content}) + + def trigger(): + start = time.monotonic() + while time.monotonic() - start < 5: + if os.path.exists(marker): + break + time.sleep(0.05) + time.sleep(0.05) + _thread.interrupt_main() + + threading.Thread(target=trigger, daemon=True).start() + out, err = io.StringIO(), io.StringIO() + t0 = time.monotonic() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = r.main([tmp, "-j", "1"]) + elapsed = time.monotonic() - t0 + + self.assertEqual(code, 130) + self.assertIn("interrupted", err.getvalue()) + self.assertLess(elapsed, 4.0) + + def test_terminate_active_processes_kills_registered_processes(self): + cmd = [sys.executable, "-c", "import time; time.sleep(10)"] + p1 = subprocess.Popen(cmd) + p2 = subprocess.Popen(cmd) + r._register_process(p1) + r._register_process(p2) + try: + self.assertIsNone(p1.poll()) + self.assertIsNone(p2.poll()) + r._terminate_active_processes() + self.assertIsNotNone(p1.poll()) + self.assertIsNotNone(p2.poll()) + finally: + for p in (p1, p2): + try: + p.kill() + except OSError: + pass + + @unittest.skipUnless(os.name == "posix", "POSIX process-group SIGINT test") + def test_posix_sigint_cancels_queued_modules_and_stops_runner(self): + import signal + with tempfile.TemporaryDirectory() as tmp, tempfile.TemporaryDirectory() as marker_dir: + mod_template = ( + "import os, time, unittest\n" + "class T(unittest.TestCase):\n" + " def test_run(self):\n" + " with open(r'{marker}', 'w') as f: f.write('1')\n" + " time.sleep(8)\n" + ) + files = { + f"test_{i}.py": mod_template.format(marker=os.path.join(marker_dir, f"m_{i}.txt")) + for i in range(5) + } + suite(tmp, files) + + script = os.path.join(ROOT, "scripts", "run_semantic_tests.py") + proc = subprocess.Popen([sys.executable, "-I", script, tmp, "-j", "2"], + start_new_session=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True) + start = time.monotonic() + while time.monotonic() - start < 5: + if len(os.listdir(marker_dir)) >= 2: + break + time.sleep(0.05) + time.sleep(0.05) + os.killpg(proc.pid, signal.SIGINT) + stdout, stderr = proc.communicate(timeout=5) + self.assertIn(proc.returncode, (130, -signal.SIGINT, 128 + signal.SIGINT)) + self.assertIn("interrupted", stderr) + self.assertNotIn("5 files,", stdout) + self.assertEqual(len(os.listdir(marker_dir)), 2) + if __name__ == "__main__": unittest.main() From 30a2a1862c9c21eddcc345985b5d74347a40ad85 Mon Sep 17 00:00:00 2001 From: d7ommy Date: Wed, 25 Nov 2026 19:55:46 +0300 Subject: [PATCH 2/2] run_semantic_tests: terminate process tree on Windows via taskkill and increase sleep margin (SEMANTIC-RUNNER-INTERRUPT) - On Windows, terminate child processes using taskkill /F /T /PID to ensure launcher processes (e.g. venv python.exe wrappers) terminate all child workers. - Increase synthetic sleep duration in tests from 5s to 10s and timeout margin to eliminate timing flakiness under high machine load. AI-assisted (Claude Code). --- scripts/run_semantic_tests.py | 45 +++++++++++++++----------------- tests/test_run_semantic_tests.py | 12 ++++----- 2 files changed, 27 insertions(+), 30 deletions(-) diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py index 628e475744..514e781330 100644 --- a/scripts/run_semantic_tests.py +++ b/scripts/run_semantic_tests.py @@ -56,6 +56,21 @@ def _unregister_process(proc): _active_processes.discard(proc) +def _kill_process_tree(proc): + if proc is None: + return + if os.name == "nt": + try: + subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + except OSError: + pass + try: + proc.kill() + except OSError: + pass + + def _terminate_active_processes(): with _processes_lock: procs = list(_active_processes) @@ -65,10 +80,7 @@ def _terminate_active_processes(): except OSError: pass for p in procs: - try: - p.kill() - except OSError: - pass + _kill_process_tree(p) try: p.wait(timeout=0.2) except (subprocess.TimeoutExpired, OSError): @@ -153,10 +165,7 @@ def run_module(directory, module, verbose, timeout=None): try: stdout, stderr = proc.communicate(timeout=timeout) except subprocess.TimeoutExpired: - try: - proc.kill() - except OSError: - pass + _kill_process_tree(proc) stdout, stderr = proc.communicate() # TimeoutExpired retains bytes even when text=True. parts = [chunk.decode(locale.getpreferredencoding(False), errors="replace") if isinstance(chunk, bytes) @@ -164,10 +173,7 @@ def run_module(directory, module, verbose, timeout=None): out = "".join(parts) return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n" except BaseException: - try: - proc.kill() - except OSError: - pass + _kill_process_tree(proc) try: proc.wait(timeout=0.5) except (subprocess.TimeoutExpired, OSError): @@ -213,17 +219,11 @@ def main(argv=None): if a.timeout is not None and time.monotonic() - start_time >= a.timeout: raise except subprocess.TimeoutExpired: - try: - proc.kill() - except OSError: - pass + _kill_process_tree(proc) print(f"TIMED OUT after {a.timeout:g} s: unittest discover in {directory}", file=sys.stderr) return 1 except KeyboardInterrupt: - try: - proc.kill() - except OSError: - pass + _kill_process_tree(proc) try: proc.wait(timeout=0.5) except (subprocess.TimeoutExpired, OSError): @@ -231,10 +231,7 @@ def main(argv=None): print("interrupted", file=sys.stderr) return 130 except BaseException: - try: - proc.kill() - except OSError: - pass + _kill_process_tree(proc) raise finally: _unregister_process(proc) diff --git a/tests/test_run_semantic_tests.py b/tests/test_run_semantic_tests.py index aa57640fea..7fc75e3722 100644 --- a/tests/test_run_semantic_tests.py +++ b/tests/test_run_semantic_tests.py @@ -292,7 +292,7 @@ def test_parallel_interrupt_stops_active_processes_and_cancels_queued_jobs(self) "class T(unittest.TestCase):\n" " def test_run(self):\n" " with open(r'{marker}', 'w') as f: f.write('1')\n" - " time.sleep(5)\n" + " time.sleep(10)\n" ) files = { f"test_{i}.py": mod_template.format(marker=os.path.join(marker_dir, f"m_{i}.txt")) @@ -302,7 +302,7 @@ def test_parallel_interrupt_stops_active_processes_and_cancels_queued_jobs(self) def trigger(): start = time.monotonic() - while time.monotonic() - start < 5: + while time.monotonic() - start < 8: if len(os.listdir(marker_dir)) >= 2: break time.sleep(0.05) @@ -322,7 +322,7 @@ def trigger(): self.assertNotIn("4 files,", out.getvalue()) started = os.listdir(marker_dir) self.assertEqual(len(started), 2, f"Expected 2 started modules, got {started}") - self.assertLess(elapsed, 4.0) + self.assertLess(elapsed, 5.0) def test_serial_interrupt_returns_130_and_prints_interrupted(self): with tempfile.TemporaryDirectory() as tmp, tempfile.TemporaryDirectory() as marker_dir: @@ -332,13 +332,13 @@ def test_serial_interrupt_returns_130_and_prints_interrupted(self): "class T(unittest.TestCase):\n" f" def test_run(self):\n" f" with open(r'{marker}', 'w') as f: f.write('1')\n" - " time.sleep(5)\n" + " time.sleep(10)\n" ) suite(tmp, {"test_serial_hang.py": content}) def trigger(): start = time.monotonic() - while time.monotonic() - start < 5: + while time.monotonic() - start < 8: if os.path.exists(marker): break time.sleep(0.05) @@ -354,7 +354,7 @@ def trigger(): self.assertEqual(code, 130) self.assertIn("interrupted", err.getvalue()) - self.assertLess(elapsed, 4.0) + self.assertLess(elapsed, 5.0) def test_terminate_active_processes_kills_registered_processes(self): cmd = [sys.executable, "-c", "import time; time.sleep(10)"]