upleb.uk

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

summaryrefslogtreecommitdiff
path: root/scripts
diff options
context:
space:
mode:
authoraslan2142 <jan.trencansky@protonmail.com>2026-11-25 20:21:39 +0100
committerGitHub <noreply@github.com>2026-11-25 20:21:39 +0100
commite48ff03744faff2c429a3968166e28893ec4e9a8 (patch)
tree7c29016c89de946b0a78833ed8b91ef3e84cb7df /scripts
parent205bda4a4ac8d0d4f14064497e49c722e1b5af27 (diff)
parent30a2a1862c9c21eddcc345985b5d74347a40ad85 (diff)
Merge pull request #1936 from abnalstlll-byte/feat/semantic-runner-interrupt
run_semantic_tests: stop active subprocesses and cancel queued modules on interrupt (SEMANTIC-RUNNER-INTERRUPT)
Diffstat (limited to 'scripts')
-rw-r--r--scripts/run_semantic_tests.py155
1 files changed, 134 insertions, 21 deletions
diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py
index 03e0ddab4..514e78133 100644
--- a/scripts/run_semantic_tests.py
+++ b/scripts/run_semantic_tests.py
@@ -36,10 +36,56 @@ 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 _kill_process_tree(proc):
60 if proc is None:
61 return
62 if os.name == "nt":
63 try:
64 subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)],
65 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
66 except OSError:
67 pass
68 try:
69 proc.kill()
70 except OSError:
71 pass
72
73
74def _terminate_active_processes():
75 with _processes_lock:
76 procs = list(_active_processes)
77 for p in procs:
78 try:
79 p.terminate()
80 except OSError:
81 pass
82 for p in procs:
83 _kill_process_tree(p)
84 try:
85 p.wait(timeout=0.2)
86 except (subprocess.TimeoutExpired, OSError):
87 pass
88
43# The child runs the module through unittest's own program and writes the result to a file, so the count of tests 89# 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 90# 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 91# 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 +159,35 @@ def run_module(directory, module, verbose, timeout=None):
113 with tempfile.TemporaryDirectory() as scratch: 159 with tempfile.TemporaryDirectory() as scratch:
114 count_path = os.path.join(scratch, "count.json") 160 count_path = os.path.join(scratch, "count.json")
115 env = dict(os.environ, LEONIDA_TEST_COUNT=count_path) 161 env = dict(os.environ, LEONIDA_TEST_COUNT=count_path)
162 proc = subprocess.Popen(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
163 text=True, errors="replace")
164 _register_process(proc)
116 try: 165 try:
117 p = subprocess.run(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, 166 stdout, stderr = proc.communicate(timeout=timeout)
118 text=True, errors="replace", timeout=timeout) 167 except subprocess.TimeoutExpired:
119 except subprocess.TimeoutExpired as exc: 168 _kill_process_tree(proc)
169 stdout, stderr = proc.communicate()
120 # TimeoutExpired retains bytes even when text=True. 170 # TimeoutExpired retains bytes even when text=True.
121 parts = [chunk.decode(locale.getpreferredencoding(False), errors="replace") if isinstance(chunk, bytes) 171 parts = [chunk.decode(locale.getpreferredencoding(False), errors="replace") if isinstance(chunk, bytes)
122 else chunk for chunk in (exc.stdout, exc.stderr) if chunk] 172 else chunk for chunk in (stdout, stderr) if chunk]
123 out = "".join(parts) 173 out = "".join(parts)
124 return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n" 174 return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n"
175 except BaseException:
176 _kill_process_tree(proc)
177 try:
178 proc.wait(timeout=0.5)
179 except (subprocess.TimeoutExpired, OSError):
180 pass
181 raise
182 finally:
183 _unregister_process(proc)
125 count = read_count(count_path) 184 count = read_count(count_path)
126 out = p.stdout + p.stderr 185 out = stdout + stderr
127 # Discover imports every package initializer, but an empty one has no tests to run. It is included in the 186 # 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. 187 # 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: 188 if proc.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in stderr:
130 return 0, 0, out 189 return 0, 0, out
131 return p.returncode, count, out 190 return proc.returncode, count, out
132 191
133 192
134def main(argv=None): 193def main(argv=None):
@@ -147,26 +206,76 @@ def main(argv=None):
147 print(f"no {a.pattern} files in {directory}") 206 print(f"no {a.pattern} files in {directory}")
148 return 1 207 return 1
149 if a.jobs <= 1: 208 if a.jobs <= 1:
209 cmd = [sys.executable, "-m", "unittest", "discover", "-s", directory,
210 "-p", a.pattern, *(["-v"] if a.verbose else [])]
211 proc = subprocess.Popen(cmd)
212 _register_process(proc)
213 start_time = time.monotonic()
150 try: 214 try:
151 return subprocess.call([sys.executable, "-m", "unittest", "discover", "-s", directory, 215 while True:
152 "-p", a.pattern, *(["-v"] if a.verbose else [])], timeout=a.timeout) 216 try:
217 return proc.wait(timeout=0.2)
218 except subprocess.TimeoutExpired:
219 if a.timeout is not None and time.monotonic() - start_time >= a.timeout:
220 raise
153 except subprocess.TimeoutExpired: 221 except subprocess.TimeoutExpired:
154 # Inherited stdout/stderr have already emitted any partial test output. 222 _kill_process_tree(proc)
155 print(f"TIMED OUT after {a.timeout:g} s: unittest discover in {directory}", file=sys.stderr) 223 print(f"TIMED OUT after {a.timeout:g} s: unittest discover in {directory}", file=sys.stderr)
156 return 1 224 return 1
225 except KeyboardInterrupt:
226 _kill_process_tree(proc)
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 _kill_process_tree(proc)
235 raise
236 finally:
237 _unregister_process(proc)
157 # Largest files first: they tend to run longest, and one started last would set the wall time alone. 238 # 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))) 239 modules.sort(key=lambda m: -os.path.getsize(module_path(directory, m)))
159 start, total, failed = time.monotonic(), 0, [] 240 start, total, failed = time.monotonic(), 0, []
160 with concurrent.futures.ThreadPoolExecutor(a.jobs) as pool: 241 pool = concurrent.futures.ThreadPoolExecutor(a.jobs)
161 jobs = {pool.submit(run_module, directory, m, a.verbose, a.timeout): m for m in modules} 242 jobs = {}
162 for job in concurrent.futures.as_completed(jobs): 243 try:
163 code, ran, out = job.result() 244 for m in modules:
164 total += ran 245 jobs[pool.submit(run_module, directory, m, a.verbose, a.timeout)] = m
165 if code: 246 pending = set(jobs)
166 failed.append(jobs[job]) 247 while pending:
167 print(f"==== FAILED: {jobs[job]}\n{out}", flush=True) 248 done, _ = concurrent.futures.wait(pending, timeout=0.2, return_when=concurrent.futures.FIRST_COMPLETED)
168 elif a.verbose: 249 for job in done:
169 print(f"==== {jobs[job]}\n{out}", flush=True) 250 pending.remove(job)
251 code, ran, out = job.result()
252 total += ran
253 if code:
254 failed.append(jobs[job])
255 print(f"==== FAILED: {jobs[job]}\n{out}", flush=True)
256 elif a.verbose:
257 print(f"==== {jobs[job]}\n{out}", flush=True)
258 except KeyboardInterrupt:
259 for job in jobs:
260 job.cancel()
261 try:
262 pool.shutdown(wait=False, cancel_futures=True)
263 except TypeError:
264 pool.shutdown(wait=False)
265 _terminate_active_processes()
266 print("interrupted", file=sys.stderr)
267 return 130
268 except BaseException:
269 for job in jobs:
270 job.cancel()
271 try:
272 pool.shutdown(wait=False, cancel_futures=True)
273 except TypeError:
274 pool.shutdown(wait=False)
275 _terminate_active_processes()
276 raise
277 else:
278 pool.shutdown(wait=True)
170 took = time.monotonic() - start 279 took = time.monotonic() - start
171 summary = f"{len(modules)} files, {total} tests, {len(failed)} files failed in {took:.0f} s with {a.jobs} jobs" 280 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 "")) 281 print(summary + (": " + ", ".join(sorted(failed)) if failed else ""))
@@ -183,4 +292,8 @@ if __name__ == "__main__":
183 sys.stdout.reconfigure(errors="replace") 292 sys.stdout.reconfigure(errors="replace")
184 except (AttributeError, ValueError, OSError): 293 except (AttributeError, ValueError, OSError):
185 pass 294 pass
186 sys.exit(main()) 295 try:
296 sys.exit(main())
297 except KeyboardInterrupt:
298 print("interrupted", file=sys.stderr)
299 sys.exit(130)