diff options
| author | QemmHD <stephenlethco2@gmail.com> | 2026-11-24 01:32:54 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-11-24 01:32:54 -0500 |
| commit | 3eb813ee7ccf4f0affc193004872f26596ae7dc8 (patch) | |
| tree | 6e6a3c010f8d16e2447135c2ff0451f8fa49b141 | |
| parent | f36a7a83d50a4365939853984b5b8e7b9814f21f (diff) | |
| parent | 90eb7284feaae3d2e1511ffef0685d95a7dd7525 (diff) | |
Merge pull request #468 from csmith105/codex/semantic-process-timeout
Why merged: scripts/run_semantic_tests.py gains a per-file timeout and rejects a zero timeout, so one hung semantic test file can't stall the whole run.
Why it's good: security-reviewed (argv-list subprocess on sys.executable only). Tested on Windows 11 merged onto main 8f481cf: tests/test_run_semantic_tests.py 10 passed on main -> 15 passed with this PR (new tests fail without the fix); a real run with --timeout 300 over test_sdwa* ran 40 tests with 0 failures and --timeout 0 is refused. Merges cleanly together with #474.
AI-assisted (Claude Code, Claude Opus 5.5).
| -rw-r--r-- | scripts/run_semantic_tests.py | 44 | ||||
| -rw-r--r-- | tests/test_run_semantic_tests.py | 49 |
2 files changed, 87 insertions, 6 deletions
diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py index a2fa69e3c..29382d5d2 100644 --- a/scripts/run_semantic_tests.py +++ b/scripts/run_semantic_tests.py | |||
| @@ -4,6 +4,7 @@ r"""Run the translator regression suite (tests/semantic) one process per test fi | |||
| 4 | python -I scripts/run_semantic_tests.py tests/semantic -p 'test_image_*.py' # a matching subset | 4 | python -I scripts/run_semantic_tests.py tests/semantic -p 'test_image_*.py' # a matching subset |
| 5 | python -I scripts/run_semantic_tests.py tests/semantic -j 4 # four at a time | 5 | python -I scripts/run_semantic_tests.py tests/semantic -j 4 # four at a time |
| 6 | python -I scripts/run_semantic_tests.py tests/semantic -v # also print the output of the files that pass | 6 | python -I scripts/run_semantic_tests.py tests/semantic -v # also print the output of the files that pass |
| 7 | python -I scripts/run_semantic_tests.py tests/semantic --timeout 300 # optional subprocess time limit | ||
| 7 | 8 | ||
| 8 | `-p` / `--pattern` selects test filenames using unittest discover's glob syntax (default `test*.py`). Quote the | 9 | `-p` / `--pattern` selects test filenames using unittest discover's glob syntax (default `test*.py`). Quote the |
| 9 | pattern so the shell does not expand it. Only Python module filenames are selected, including inside packages; | 10 | pattern so the shell does not expand it. Only Python module filenames are selected, including inside packages; |
| @@ -14,16 +15,25 @@ It runs the files `python -m unittest discover -s tests/semantic` finds (`test*. | |||
| 14 | run side by side because each one writes only into its own temporary folder; a new test must do the same. With -j 1, | 15 | run side by side because each one writes only into its own temporary folder; a new test must do the same. With -j 1, |
| 15 | or on a single core, it runs that discover command itself. Prints the output of every failing file and one summary | 16 | or on a single core, it runs that discover command itself. Prints the output of every failing file and one summary |
| 16 | line, and exits 1 if a file fails or none is found. Standard library only. | 17 | line, and exits 1 if a file fails or none is found. Standard library only. |
| 18 | |||
| 19 | `--timeout SECONDS` limits each module subprocess in parallel mode, or the entire discover subprocess with | ||
| 20 | `-j 1`. The value must be positive and at most 86400 seconds (24 hours), keeping it within platform wait limits. | ||
| 21 | A timeout fails the run and reports any output already produced; other parallel modules keep running. | ||
| 22 | The default has no time limit. This stops the direct test subprocess, not any descendants it may have started. | ||
| 17 | """ | 23 | """ |
| 18 | import argparse | 24 | import argparse |
| 19 | import concurrent.futures | 25 | import concurrent.futures |
| 20 | import fnmatch | 26 | import fnmatch |
| 27 | import locale | ||
| 28 | import math | ||
| 21 | import os | 29 | import os |
| 22 | import re | 30 | import re |
| 23 | import subprocess | 31 | import subprocess |
| 24 | import sys | 32 | import sys |
| 25 | import time | 33 | import time |
| 26 | 34 | ||
| 35 | MAX_TIMEOUT_SECONDS = 24 * 60 * 60 | ||
| 36 | |||
| 27 | 37 | ||
| 28 | def test_modules(directory, pattern="test*.py"): | 38 | def test_modules(directory, pattern="test*.py"): |
| 29 | """Dotted names of the test modules unittest discover finds under `directory` (it enters packages only).""" | 39 | """Dotted names of the test modules unittest discover finds under `directory` (it enters packages only).""" |
| @@ -37,11 +47,25 @@ def test_modules(directory, pattern="test*.py"): | |||
| 37 | return names | 47 | return names |
| 38 | 48 | ||
| 39 | 49 | ||
| 40 | def run_module(directory, module, verbose): | 50 | def positive_seconds(value): |
| 51 | seconds = float(value) | ||
| 52 | if not math.isfinite(seconds) or not 0 < seconds <= MAX_TIMEOUT_SECONDS: | ||
| 53 | raise argparse.ArgumentTypeError( | ||
| 54 | f"timeout must be a positive finite number of seconds no greater than {MAX_TIMEOUT_SECONDS} (24 hours)") | ||
| 55 | return seconds | ||
| 56 | |||
| 57 | |||
| 58 | def run_module(directory, module, verbose, timeout=None): | ||
| 41 | """(return code, tests run, output) of `python -m unittest <module>` run from `directory`.""" | 59 | """(return code, tests run, output) of `python -m unittest <module>` run from `directory`.""" |
| 42 | cmd = [sys.executable, "-m", "unittest", *(["-v"] if verbose else []), module] | 60 | cmd = [sys.executable, "-m", "unittest", *(["-v"] if verbose else []), module] |
| 43 | p = subprocess.run(cmd, cwd=directory, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, | 61 | try: |
| 44 | errors="replace") | 62 | p = subprocess.run(cmd, cwd=directory, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, |
| 63 | errors="replace", timeout=timeout) | ||
| 64 | except subprocess.TimeoutExpired as exc: | ||
| 65 | out = exc.stdout or "" | ||
| 66 | if isinstance(out, bytes): # TimeoutExpired retains bytes even when text=True. | ||
| 67 | out = out.decode(locale.getpreferredencoding(False), errors="replace") | ||
| 68 | return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n" | ||
| 45 | ran = re.search(r"^Ran (\d+) tests? in", p.stdout, re.M) | 69 | ran = re.search(r"^Ran (\d+) tests? in", p.stdout, re.M) |
| 46 | return p.returncode, int(ran.group(1)) if ran else 0, p.stdout | 70 | return p.returncode, int(ran.group(1)) if ran else 0, p.stdout |
| 47 | 71 | ||
| @@ -52,6 +76,9 @@ def main(argv=None): | |||
| 52 | ap.add_argument("-p", "--pattern", default="test*.py", help="test filename glob (default: test*.py)") | 76 | ap.add_argument("-p", "--pattern", default="test*.py", help="test filename glob (default: test*.py)") |
| 53 | ap.add_argument("-j", "--jobs", type=int, default=os.cpu_count() or 1, help="files at a time (default: cores)") | 77 | ap.add_argument("-j", "--jobs", type=int, default=os.cpu_count() or 1, help="files at a time (default: cores)") |
| 54 | ap.add_argument("-v", "--verbose", action="store_true", help="unittest -v, and print passing files' output") | 78 | ap.add_argument("-v", "--verbose", action="store_true", help="unittest -v, and print passing files' output") |
| 79 | ap.add_argument("--timeout", type=positive_seconds, default=None, metavar="SECONDS", | ||
| 80 | help=f"positive finite time limit up to {MAX_TIMEOUT_SECONDS} seconds (24 hours) per module " | ||
| 81 | "subprocess, or for the whole discover subprocess with -j 1 (default: no limit)") | ||
| 55 | a = ap.parse_args(argv) | 82 | a = ap.parse_args(argv) |
| 56 | directory = os.path.abspath(a.directory) | 83 | directory = os.path.abspath(a.directory) |
| 57 | modules = test_modules(directory, a.pattern) | 84 | modules = test_modules(directory, a.pattern) |
| @@ -59,13 +86,18 @@ def main(argv=None): | |||
| 59 | print(f"no {a.pattern} files in {directory}") | 86 | print(f"no {a.pattern} files in {directory}") |
| 60 | return 1 | 87 | return 1 |
| 61 | if a.jobs <= 1: | 88 | if a.jobs <= 1: |
| 62 | return subprocess.call([sys.executable, "-m", "unittest", "discover", "-s", directory, | 89 | try: |
| 63 | "-p", a.pattern, *(["-v"] if a.verbose else [])]) | 90 | return subprocess.call([sys.executable, "-m", "unittest", "discover", "-s", directory, |
| 91 | "-p", a.pattern, *(["-v"] if a.verbose else [])], timeout=a.timeout) | ||
| 92 | except subprocess.TimeoutExpired: | ||
| 93 | # Inherited stdout/stderr have already emitted any partial test output. | ||
| 94 | print(f"TIMED OUT after {a.timeout:g} s: unittest discover in {directory}", file=sys.stderr) | ||
| 95 | return 1 | ||
| 64 | # Largest files first: they tend to run longest, and one started last would set the wall time alone. | 96 | # Largest files first: they tend to run longest, and one started last would set the wall time alone. |
| 65 | modules.sort(key=lambda m: -os.path.getsize(os.path.join(directory, *m.split(".")) + ".py")) | 97 | modules.sort(key=lambda m: -os.path.getsize(os.path.join(directory, *m.split(".")) + ".py")) |
| 66 | start, total, failed = time.monotonic(), 0, [] | 98 | start, total, failed = time.monotonic(), 0, [] |
| 67 | with concurrent.futures.ThreadPoolExecutor(a.jobs) as pool: | 99 | with concurrent.futures.ThreadPoolExecutor(a.jobs) as pool: |
| 68 | jobs = {pool.submit(run_module, directory, m, a.verbose): m for m in modules} | 100 | jobs = {pool.submit(run_module, directory, m, a.verbose, a.timeout): m for m in modules} |
| 69 | for job in concurrent.futures.as_completed(jobs): | 101 | for job in concurrent.futures.as_completed(jobs): |
| 70 | code, ran, out = job.result() | 102 | code, ran, out = job.result() |
| 71 | total += ran | 103 | total += ran |
diff --git a/tests/test_run_semantic_tests.py b/tests/test_run_semantic_tests.py index f9f3e86ae..dcf115fc0 100644 --- a/tests/test_run_semantic_tests.py +++ b/tests/test_run_semantic_tests.py | |||
| @@ -20,6 +20,7 @@ PASS = "import unittest\nimport helper\nclass T(unittest.TestCase):\n def tes | |||
| 20 | " def test_b(self): pass\n" | 20 | " def test_b(self): pass\n" |
| 21 | FAIL = "import unittest\nclass T(unittest.TestCase):\n def test_a(self): self.assertEqual(1, 2, 'boom-msg')\n" | 21 | FAIL = "import unittest\nclass T(unittest.TestCase):\n def test_a(self): self.assertEqual(1, 2, 'boom-msg')\n" |
| 22 | BROKEN = "import no_such_module_anywhere\n" | 22 | BROKEN = "import no_such_module_anywhere\n" |
| 23 | HANG = "import time\nprint('before-sleep-marker', flush=True)\ntime.sleep(60)\n" | ||
| 23 | 24 | ||
| 24 | 25 | ||
| 25 | def suite(tmp, files): | 26 | def suite(tmp, files): |
| @@ -44,6 +45,54 @@ def cli(*argv): | |||
| 44 | 45 | ||
| 45 | 46 | ||
| 46 | class RunnerTest(unittest.TestCase): | 47 | class RunnerTest(unittest.TestCase): |
| 48 | def test_parallel_timeout_reports_partial_output_and_keeps_healthy_modules(self): | ||
| 49 | with tempfile.TemporaryDirectory() as tmp: | ||
| 50 | suite(tmp, {"helper.py": "X = 1\n", "test_hang.py": HANG, | ||
| 51 | "test_pass_one.py": PASS, "test_pass_two.py": PASS}) | ||
| 52 | result = cli(tmp, "-j", "2", "--timeout", "1") | ||
| 53 | self.assertEqual(result.returncode, 1, result.stdout + result.stderr) | ||
| 54 | self.assertIn("before-sleep-marker", result.stdout) | ||
| 55 | self.assertIn("==== FAILED: test_hang", result.stdout) | ||
| 56 | self.assertIn("TIMED OUT after 1 s: test_hang", result.stdout) | ||
| 57 | self.assertIn("3 files, 4 tests, 1 files failed", result.stdout) | ||
| 58 | self.assertNotIn("Traceback", result.stdout + result.stderr) | ||
| 59 | |||
| 60 | def test_serial_timeout_keeps_discover_output_and_names_the_suite(self): | ||
| 61 | with tempfile.TemporaryDirectory() as tmp: | ||
| 62 | suite(tmp, {"test_hang.py": HANG}) | ||
| 63 | result = cli(tmp, "-j", "1", "--timeout", "1") | ||
| 64 | self.assertEqual(result.returncode, 1, result.stdout + result.stderr) | ||
| 65 | self.assertIn("before-sleep-marker", result.stdout) | ||
| 66 | self.assertIn("TIMED OUT after 1 s: unittest discover in", result.stderr) | ||
| 67 | self.assertIn(tmp, result.stderr) | ||
| 68 | self.assertNotIn("Traceback", result.stdout + result.stderr) | ||
| 69 | |||
| 70 | def test_timeout_requires_positive_finite_seconds(self): | ||
| 71 | for value in ("0", "-1", "nan", "inf", "-inf"): | ||
| 72 | with self.subTest(value=value): | ||
| 73 | result = cli("unused-suite", "--timeout=" + value) | ||
| 74 | self.assertEqual(result.returncode, 2, result.stdout + result.stderr) | ||
| 75 | self.assertIn("positive finite", result.stderr) | ||
| 76 | self.assertNotIn("Traceback", result.stderr) | ||
| 77 | |||
| 78 | def test_out_of_range_timeout_is_rejected_before_running_the_suite(self): | ||
| 79 | for jobs in (1, 2): | ||
| 80 | for value in ("86400.1", "1e100"): | ||
| 81 | with self.subTest(jobs=jobs, value=value): | ||
| 82 | result = cli("unused-suite", "-j", str(jobs), "--timeout=" + value) | ||
| 83 | self.assertEqual(result.returncode, 2, result.stdout + result.stderr) | ||
| 84 | self.assertIn("no greater than 86400", result.stderr) | ||
| 85 | self.assertNotIn("Traceback", result.stderr) | ||
| 86 | self.assertNotIn("TIMED OUT", result.stdout + result.stderr) | ||
| 87 | self.assertNotIn("no test*.py files", result.stdout) | ||
| 88 | |||
| 89 | def test_maximum_timeout_runs_a_passing_suite_in_both_modes(self): | ||
| 90 | for jobs in (1, 2): | ||
| 91 | with self.subTest(jobs=jobs), tempfile.TemporaryDirectory() as tmp: | ||
| 92 | suite(tmp, {"helper.py": "X = 1\n", "test_pass.py": PASS}) | ||
| 93 | result = cli(tmp, "-j", str(jobs), "--timeout", "86400") | ||
| 94 | self.assertEqual(result.returncode, 0, result.stdout + result.stderr) | ||
| 95 | |||
| 47 | def test_custom_patterns_find_only_python_modules_in_packages(self): | 96 | def test_custom_patterns_find_only_python_modules_in_packages(self): |
| 48 | with tempfile.TemporaryDirectory() as tmp: | 97 | with tempfile.TemporaryDirectory() as tmp: |
| 49 | suite(tmp, {"case_one.py": "", "case_two.txt": "", "case_bad-name.py": "", | 98 | suite(tmp, {"case_one.py": "", "case_two.txt": "", "case_bad-name.py": "", |