upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/scripts/run_semantic_tests.py
diff options
context:
space:
mode:
authord7ommy <abnalstlll@gmail.com>2026-11-25 19:11:41 +0300
committerd7ommy <abnalstlll@gmail.com>2026-11-25 19:11:41 +0300
commit542c046c503af54cf6b29436eff4877f4edb7de4 (patch)
tree4521a65cc65b72d0fab1cf8bd372f869045c18b9 /scripts/run_semantic_tests.py
parentb0f3d3998f0401eb7df8ddbb7a303d1e6bee9fb8 (diff)
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)
Diffstat (limited to 'scripts/run_semantic_tests.py')
-rw-r--r--scripts/run_semantic_tests.py158
1 files changed, 137 insertions, 21 deletions
diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py
index 03e0ddab4..628e47574 100644
--- a/scripts/run_semantic_tests.py
+++ b/scripts/run_semantic_tests.py
@@ -36,10 +36,44 @@ import re
36import subprocess 36import subprocess
37import sys 37import sys
38import tempfile 38import tempfile
39import threading
39import time 40import time
40 41
41MAX_TIMEOUT_SECONDS = 24 * 60 * 60 42MAX_TIMEOUT_SECONDS = 24 * 60 * 60
42 43
44# The child processes running right now: on SIGINT / Ctrl+C, the main thread terminates them so no orphans linger.
45_active_processes = set()
46_processes_lock = threading.Lock()
47
48
49def _register_process(proc):
50 with _processes_lock:
51 _active_processes.add(proc)
52
53
54def _unregister_process(proc):
55 with _processes_lock:
56 _active_processes.discard(proc)
57
58
59def _terminate_active_processes():
60 with _processes_lock:
61 procs = list(_active_processes)
62 for p in procs:
63 try:
64 p.terminate()
65 except OSError:
66 pass
67 for p in procs:
68 try:
69 p.kill()
70 except OSError:
71 pass
72 try:
73 p.wait(timeout=0.2)
74 except (subprocess.TimeoutExpired, OSError):
75 pass
76
43# The child runs the module through unittest's own program and writes the result to a file, so the count of tests 77# The child runs the module through unittest's own program and writes the result to a file, so the count of tests
44# comes from the result object and nothing the module writes can change it. The exit codes are unittest's own: 1 78# comes from the result object and nothing the module writes can change it. The exit codes are unittest's own: 1
45# when a test failed, 5 when nothing ran at all, 0 otherwise. The module is left unset, as `python -m unittest` leaves it, so 79# 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):
113 with tempfile.TemporaryDirectory() as scratch: 147 with tempfile.TemporaryDirectory() as scratch:
114 count_path = os.path.join(scratch, "count.json") 148 count_path = os.path.join(scratch, "count.json")
115 env = dict(os.environ, LEONIDA_TEST_COUNT=count_path) 149 env = dict(os.environ, LEONIDA_TEST_COUNT=count_path)
150 proc = subprocess.Popen(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
151 text=True, errors="replace")
152 _register_process(proc)
116 try: 153 try:
117 p = subprocess.run(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, 154 stdout, stderr = proc.communicate(timeout=timeout)
118 text=True, errors="replace", timeout=timeout) 155 except subprocess.TimeoutExpired:
119 except subprocess.TimeoutExpired as exc: 156 try:
157 proc.kill()
158 except OSError:
159 pass
160 stdout, stderr = proc.communicate()
120 # TimeoutExpired retains bytes even when text=True. 161 # TimeoutExpired retains bytes even when text=True.
121 parts = [chunk.decode(locale.getpreferredencoding(False), errors="replace") if isinstance(chunk, bytes) 162 parts = [chunk.decode(locale.getpreferredencoding(False), errors="replace") if isinstance(chunk, bytes)
122 else chunk for chunk in (exc.stdout, exc.stderr) if chunk] 163 else chunk for chunk in (stdout, stderr) if chunk]
123 out = "".join(parts) 164 out = "".join(parts)
124 return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n" 165 return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n"
166 except BaseException:
167 try:
168 proc.kill()
169 except OSError:
170 pass
171 try:
172 proc.wait(timeout=0.5)
173 except (subprocess.TimeoutExpired, OSError):
174 pass
175 raise
176 finally:
177 _unregister_process(proc)
125 count = read_count(count_path) 178 count = read_count(count_path)
126 out = p.stdout + p.stderr 179 out = stdout + stderr
127 # Discover imports every package initializer, but an empty one has no tests to run. It is included in the 180 # Discover imports every package initializer, but an empty one has no tests to run. It is included in the
128 # module list so parallel runs see TestCase classes when there are any; without them, it is not a failure. 181 # module list so parallel runs see TestCase classes when there are any; without them, it is not a failure.
129 if p.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in p.stderr: 182 if proc.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in stderr:
130 return 0, 0, out 183 return 0, 0, out
131 return p.returncode, count, out 184 return proc.returncode, count, out
132 185
133 186
134def main(argv=None): 187def main(argv=None):
@@ -147,26 +200,85 @@ def main(argv=None):
147 print(f"no {a.pattern} files in {directory}") 200 print(f"no {a.pattern} files in {directory}")
148 return 1 201 return 1
149 if a.jobs <= 1: 202 if a.jobs <= 1:
203 cmd = [sys.executable, "-m", "unittest", "discover", "-s", directory,
204 "-p", a.pattern, *(["-v"] if a.verbose else [])]
205 proc = subprocess.Popen(cmd)
206 _register_process(proc)
207 start_time = time.monotonic()
150 try: 208 try:
151 return subprocess.call([sys.executable, "-m", "unittest", "discover", "-s", directory, 209 while True:
152 "-p", a.pattern, *(["-v"] if a.verbose else [])], timeout=a.timeout) 210 try:
211 return proc.wait(timeout=0.2)
212 except subprocess.TimeoutExpired:
213 if a.timeout is not None and time.monotonic() - start_time >= a.timeout:
214 raise
153 except subprocess.TimeoutExpired: 215 except subprocess.TimeoutExpired:
154 # Inherited stdout/stderr have already emitted any partial test output. 216 try:
217 proc.kill()
218 except OSError:
219 pass
155 print(f"TIMED OUT after {a.timeout:g} s: unittest discover in {directory}", file=sys.stderr) 220 print(f"TIMED OUT after {a.timeout:g} s: unittest discover in {directory}", file=sys.stderr)
156 return 1 221 return 1
222 except KeyboardInterrupt:
223 try:
224 proc.kill()
225 except OSError:
226 pass
227 try:
228 proc.wait(timeout=0.5)
229 except (subprocess.TimeoutExpired, OSError):
230 pass
231 print("interrupted", file=sys.stderr)
232 return 130
233 except BaseException:
234 try:
235 proc.kill()
236 except OSError:
237 pass
238 raise
239 finally:
240 _unregister_process(proc)
157 # Largest files first: they tend to run longest, and one started last would set the wall time alone. 241 # Largest files first: they tend to run longest, and one started last would set the wall time alone.
158 modules.sort(key=lambda m: -os.path.getsize(module_path(directory, m))) 242 modules.sort(key=lambda m: -os.path.getsize(module_path(directory, m)))
159 start, total, failed = time.monotonic(), 0, [] 243 start, total, failed = time.monotonic(), 0, []
160 with concurrent.futures.ThreadPoolExecutor(a.jobs) as pool: 244 pool = concurrent.futures.ThreadPoolExecutor(a.jobs)
161 jobs = {pool.submit(run_module, directory, m, a.verbose, a.timeout): m for m in modules} 245 jobs = {}
162 for job in concurrent.futures.as_completed(jobs): 246 try:
163 code, ran, out = job.result() 247 for m in modules:
164 total += ran 248 jobs[pool.submit(run_module, directory, m, a.verbose, a.timeout)] = m
165 if code: 249 pending = set(jobs)
166 failed.append(jobs[job]) 250 while pending:
167 print(f"==== FAILED: {jobs[job]}\n{out}", flush=True) 251 done, _ = concurrent.futures.wait(pending, timeout=0.2, return_when=concurrent.futures.FIRST_COMPLETED)
168 elif a.verbose: 252 for job in done:
169 print(f"==== {jobs[job]}\n{out}", flush=True) 253 pending.remove(job)
254 code, ran, out = job.result()
255 total += ran
256 if code:
257 failed.append(jobs[job])
258 print(f"==== FAILED: {jobs[job]}\n{out}", flush=True)
259 elif a.verbose:
260 print(f"==== {jobs[job]}\n{out}", flush=True)
261 except KeyboardInterrupt:
262 for job in jobs:
263 job.cancel()
264 try:
265 pool.shutdown(wait=False, cancel_futures=True)
266 except TypeError:
267 pool.shutdown(wait=False)
268 _terminate_active_processes()
269 print("interrupted", file=sys.stderr)
270 return 130
271 except BaseException:
272 for job in jobs:
273 job.cancel()
274 try:
275 pool.shutdown(wait=False, cancel_futures=True)
276 except TypeError:
277 pool.shutdown(wait=False)
278 _terminate_active_processes()
279 raise
280 else:
281 pool.shutdown(wait=True)
170 took = time.monotonic() - start 282 took = time.monotonic() - start
171 summary = f"{len(modules)} files, {total} tests, {len(failed)} files failed in {took:.0f} s with {a.jobs} jobs" 283 summary = f"{len(modules)} files, {total} tests, {len(failed)} files failed in {took:.0f} s with {a.jobs} jobs"
172 print(summary + (": " + ", ".join(sorted(failed)) if failed else "")) 284 print(summary + (": " + ", ".join(sorted(failed)) if failed else ""))
@@ -183,4 +295,8 @@ if __name__ == "__main__":
183 sys.stdout.reconfigure(errors="replace") 295 sys.stdout.reconfigure(errors="replace")
184 except (AttributeError, ValueError, OSError): 296 except (AttributeError, ValueError, OSError):
185 pass 297 pass
186 sys.exit(main()) 298 try:
299 sys.exit(main())
300 except KeyboardInterrupt:
301 print("interrupted", file=sys.stderr)
302 sys.exit(130)