diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py index 514e78133..2950e1991 100644 --- a/scripts/run_semantic_tests.py +++ b/scripts/run_semantic_tests.py @@ -20,6 +20,11 @@ The count of tests comes from unittest's own result object, not from its output: a module that writes a line shaped like unittest's summary to stderr - a nested runner, or an atexit handler that runs after unittest's own summary - cannot change it. +In a parallel run the processes share the modules they compile through a temporary folder that is removed when the +run ends, so the translator is compiled once per job, by the files a run starts with, instead of once per file +(BYTECODE_CACHE_PROGRAM has the reason). Nothing is written into the tree for it, and a file's own +`sys.dont_write_bytecode` still keeps `__pycache__` out of it. + `--timeout SECONDS` limits each module subprocess in parallel mode, or the entire discover subprocess with `-j 1`. The value must be positive and at most 86400 seconds (24 hours), keeping it within platform wait limits. A timeout fails the run and reports any output already produced; other parallel modules keep running. @@ -86,11 +91,72 @@ def _terminate_active_processes(): except (subprocess.TimeoutExpired, OSError): pass +# Where the children find the bytecode another child has already compiled (the folder is the run's own, see main()). +BYTECODE_CACHE_VARIABLE = "LEONIDA_BYTECODE_CACHE" + +# Installed in every child before it imports its test module. A source module whose own bytecode file is missing or +# stale, or was never written because the importing file sets `sys.dont_write_bytecode` (most of this suite does, to +# keep `__pycache__` out of the tree), is compiled by the first child that needs it and read back by the others. A +# child that needs it before that entry is written compiles it too: the jobs of a run start together, so the +# translator is compiled once per job (4 times in a run of 16 files with 4 jobs, 8 times with 8) and read by every +# file after those. +# +# It matters because CPython from 3.12 up to 3.13.15 and 3.14.7 tokenizes a source *string* in time quadratic in its +# f-string replacement fields: every `{` copies the rest of the buffer (`update_fstring_expr` in 3.12's +# Parser/tokenizer.c). 3.13.16, 3.14.8 and 3.15.0 fixed that (gh-155525); 3.12.16 still has it, and CI runs 3.12. +# Importing tools/rdna2spirv.py, 1.2 MB with some 4,800 f-strings, takes 7.2 s on 3.14.7 and 7.5 s on 3.13.13 +# (Windows 11; 0.1 s of it is code generation) against under 0.1 s from bytecode, and each file of the suite paid +# that. Run as a script the same file starts in 0.4 s, because a file is tokenized line by line. +# +# `source_to_code` is what the import system calls when it has no valid bytecode file for a module, so a module whose +# `__pycache__` entry is current never comes here. An entry is named after the path and the bytes of the source it was +# compiled from, so a source that changes during a run, or a second copy of tools/, gets one of its own and no entry is +# ever stale; an entry that cannot be read or written just means compiling, as before. +BYTECODE_CACHE_PROGRAM = ( + "import importlib.machinery, importlib.util, marshal, os, sys\n" + "class SharedBytecodeLoader(importlib.machinery.SourceFileLoader):\n" + " def source_to_code(self, data, path, **options):\n" + " if options or not isinstance(data, bytes):\n" + " return super().source_to_code(data, path, **options)\n" + " key = importlib.util.source_hash(os.fsencode(path) + b'\\0' + data).hex()\n" + " entry = os.path.join(SHARED_BYTECODE, '%s-%d-%s.marshal' % (\n" + " self.name.rpartition('.')[2], sys.flags.optimize, key))\n" + " try:\n" + " with open(entry, 'rb') as handle:\n" + " code = marshal.load(handle)\n" + " except (OSError, EOFError, ValueError, TypeError):\n" + " code = None\n" + " if isinstance(code, type(compile('', path, 'exec'))):\n" + " return code\n" + " code = super().source_to_code(data, path)\n" + " mine = '%s.%d' % (entry, os.getpid())\n" + " try:\n" + " with open(mine, 'wb') as handle:\n" + " marshal.dump(code, handle)\n" + " os.replace(mine, entry)\n" + " except OSError:\n" + " try:\n" + " os.remove(mine)\n" + " except OSError:\n" + " pass\n" + " return code\n" + "class SharedBytecodeFinder:\n" + " @staticmethod\n" + " def find_spec(name, path=None, target=None):\n" + " spec = importlib.machinery.PathFinder.find_spec(name, path, target)\n" + " if spec is not None and type(spec.loader) is importlib.machinery.SourceFileLoader:\n" + " spec.loader = SharedBytecodeLoader(spec.loader.name, spec.loader.path)\n" + " return spec\n" + f"SHARED_BYTECODE = os.environ.get({BYTECODE_CACHE_VARIABLE!r})\n" + # Ahead of the path finder only: built-in and frozen modules keep their own finders. + "if SHARED_BYTECODE and importlib.machinery.PathFinder in sys.meta_path:\n" + " sys.meta_path.insert(sys.meta_path.index(importlib.machinery.PathFinder), SharedBytecodeFinder)\n") + # 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 # the name is imported and not looked up as an attribute of the program itself. -CHILD_PROGRAM = ( +CHILD_PROGRAM = BYTECODE_CACHE_PROGRAM + ( "import json, os, sys, unittest\n" "program = unittest.TestProgram(module=None, argv=['unittest'] + sys.argv[1:], exit=False)\n" "result = program.result\n" @@ -149,8 +215,11 @@ def read_count(path): return 0 -def run_module(directory, module, verbose, timeout=None): - """(return code, tests run, output) of `python -m unittest ` run from `directory`.""" +def run_module(directory, module, verbose, timeout=None, bytecode_cache=None): + """(return code, tests run, output) of `python -m unittest ` run from `directory`. + + `bytecode_cache` is the folder this child shares compiled modules through (BYTECODE_CACHE_PROGRAM); without one + it compiles what it imports itself.""" # `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 # still the initializer's path, so the jobs stay sorted by the file they run. @@ -159,6 +228,11 @@ 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) + # Never the folder of a runner further up (this runner started from a test of another run): it is not ours + # to fill, and it is removed when that run ends. + env.pop(BYTECODE_CACHE_VARIABLE, None) + if bytecode_cache is not None: + env[BYTECODE_CACHE_VARIABLE] = bytecode_cache proc = subprocess.Popen(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, errors="replace") _register_process(proc) @@ -237,12 +311,20 @@ def main(argv=None): _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))) + # One folder of compiled modules for the whole run, outside the tree and gone when the run ends (a file a + # stopped child still holds open on Windows must not turn a finished run into a traceback). + with tempfile.TemporaryDirectory(prefix="leonida-bytecode-", ignore_cleanup_errors=True) as bytecode_cache: + return run_parallel(directory, modules, a, bytecode_cache) + + +def run_parallel(directory, modules, a, bytecode_cache): + """Exit code of the run: the modules, `a.jobs` at a time, each in its own process.""" start, total, failed = time.monotonic(), 0, [] pool = concurrent.futures.ThreadPoolExecutor(a.jobs) 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, bytecode_cache)] = m pending = set(jobs) while pending: done, _ = concurrent.futures.wait(pending, timeout=0.2, return_when=concurrent.futures.FIRST_COMPLETED) diff --git a/tests/semantic/README.md b/tests/semantic/README.md index c355e60c1..af35fda18 100644 --- a/tests/semantic/README.md +++ b/tests/semantic/README.md @@ -18,6 +18,19 @@ fail and one summary line; `-j N` sets how many run at once (`-j 1` is the disco every file's output. Files run side by side, so a test writes only into its own temporary folder (`tempfile`), never to a fixed path, and does not rely on another file having run first. +The processes of a parallel run share what they compile: the first file that imports a module compiles it into a +temporary folder, the others read it from there, and the folder is removed when the run ends. A file that imports +the module before that entry is written compiles it too, so the files a run starts with compile it once per job. +This is for +`tools/rdna2spirv.py`: importing it from source takes 7.2 s on Python 3.14.7 and 7.5 s on 3.13.13 (Windows 11), +because CPython's tokenizer copies the rest of a source string at every f-string `{` and the file has some 4,800 +f-strings (run as a script it is read line by line and starts in 0.4 s). CPython fixed that in 3.13.16, 3.14.8 and +3.15.0 (gh-155525); 3.12, which CI runs, still has it in 3.12.16. Most files here set `sys.dont_write_bytecode` +before they import the translator, so where no `__pycache__` entry exists for it each one compiled it +again. That is every file when the environment forbids bytecode (`PYTHONDONTWRITEBYTECODE`, `-B`): on 8 cores the +478 files other than `test_m*.py` took 533 s that way and take 93 s now, the same as with bytecode allowed. A file +run on its own with `python -m unittest` still compiles the translator itself. + Every file here must call `tools/rdna2spirv.py` (directly, through `support.py`, or by running the tool) and assert on what it emitted. A test that reimplements the instruction in Python passes whatever the translator does, so it is not a regression test. `tests/test_semantic_translator_use.py` enforces this; the interpreter self-tests and the diff --git a/tests/test_run_semantic_tests.py b/tests/test_run_semantic_tests.py index 7fc75e372..6d46c4af6 100644 --- a/tests/test_run_semantic_tests.py +++ b/tests/test_run_semantic_tests.py @@ -5,7 +5,9 @@ """ import contextlib import io +import marshal import os +import re import subprocess import sys import tempfile @@ -40,6 +42,19 @@ # A test that runs a nested unittest runner: that runner writes its own summary to stderr while the test runs. NESTED = ("import sys\nimport unittest\nclass T(unittest.TestCase):\n def test_a(self):\n" " unittest.TextTestRunner(stream=sys.stderr, verbosity=0).run(unittest.TestSuite())\n") +# What most files of tests/semantic do: bytecode writing is off before the module under test is imported, so its own +# `__pycache__` never holds it and every file would compile it again. +USES_HELPER = ("import sys\nsys.dont_write_bytecode = True\nimport unittest\nimport helper\n" + "class T(unittest.TestCase):\n def test_a(self): self.assertEqual(helper.X, {x})\n") +SHOWS_FOLDER = ("import os\nimport unittest\nclass T(unittest.TestCase):\n def test_a(self):\n" + f" folder = os.environ.get({r.BYTECODE_CACHE_VARIABLE!r})\n" + " print('shared-folder=%s exists=%s' % (folder, bool(folder) and os.path.isdir(folder)))\n") + + +def shared_entries(folder, module): + """The shared bytecode files of one module, one per source it was compiled from.""" + name = re.compile(re.escape(module) + r"-\d+-[0-9a-f]+\.marshal") + return sorted(entry for entry in os.listdir(folder) if name.fullmatch(entry)) def suite(tmp, files): @@ -63,6 +78,99 @@ def cli(*argv): capture_output=True, text=True, timeout=15) +class SharedBytecodeTest(unittest.TestCase): + """A module the files of a run have in common is compiled by the first file that imports it and read by the + others: tools/rdna2spirv.py takes seconds to compile, and it used to be compiled once per file.""" + + def helper_suite(self, tmp, second): + suite(tmp, {"helper.py": "X = 1\n", "test_first.py": USES_HELPER.format(x=1), + "test_second.py": USES_HELPER.format(x=second)}) + return os.path.join(tmp, "helper.py") + + def test_a_module_one_file_compiled_is_read_by_the_next(self): + with tempfile.TemporaryDirectory() as tmp, tempfile.TemporaryDirectory() as shared: + helper = self.helper_suite(tmp, second=2) + code, ran, out = r.run_module(tmp, "test_first", False, None, shared) + self.assertEqual((code, ran), (0, 1), out) + entries = shared_entries(shared, "helper") + self.assertEqual(len(entries), 1, os.listdir(shared)) + # A file's result does not say whether it compiled helper.py or read the entry, so the entry is swapped + # for code that says X = 2: test_second passes only by running the entry. + with open(os.path.join(shared, entries[0]), "wb") as f: + marshal.dump(compile("X = 2\n", helper, "exec"), f) + code, ran, out = r.run_module(tmp, "test_second", False, None, shared) + self.assertEqual((code, ran), (0, 1), out) + self.assertEqual(shared_entries(shared, "helper"), entries) + # The file switched bytecode writing off, and that still holds for the tree. + self.assertFalse(os.path.exists(os.path.join(tmp, "__pycache__", "helper." + sys.implementation.cache_tag + + ".pyc"))) + + def test_a_changed_source_is_compiled_again(self): + # Same length and same modification time as the source the entry came from: a `__pycache__` file is trusted + # on those two alone and would run the old code. An entry is named after the bytes it was compiled from. + with tempfile.TemporaryDirectory() as tmp, tempfile.TemporaryDirectory() as shared: + helper = self.helper_suite(tmp, second=3) + before = os.stat(helper) + self.assertEqual(r.run_module(tmp, "test_first", False, None, shared)[:2], (0, 1)) + with open(helper, "w", encoding="utf-8", newline="\n") as f: + f.write("X = 3\n") + os.utime(helper, ns=(before.st_atime_ns, before.st_mtime_ns)) + code, ran, out = r.run_module(tmp, "test_second", False, None, shared) + self.assertEqual((code, ran), (0, 1), out) + self.assertEqual(len(shared_entries(shared, "helper")), 2, os.listdir(shared)) + + def test_an_entry_that_is_not_bytecode_is_compiled_again_and_replaced(self): + for damage in (b"", b"not marshal data", marshal.dumps("a string, not code")): + with self.subTest(damage=damage), tempfile.TemporaryDirectory() as tmp, \ + tempfile.TemporaryDirectory() as shared: + self.helper_suite(tmp, second=1) + self.assertEqual(r.run_module(tmp, "test_first", False, None, shared)[:2], (0, 1)) + (entry,) = shared_entries(shared, "helper") + with open(os.path.join(shared, entry), "wb") as f: + f.write(damage) + code, ran, out = r.run_module(tmp, "test_second", False, None, shared) + self.assertEqual((code, ran), (0, 1), out) + with open(os.path.join(shared, entry), "rb") as f: + self.assertEqual(marshal.load(f).co_filename, os.path.join(tmp, "helper.py")) + + def test_a_folder_that_is_gone_only_means_compiling(self): + with tempfile.TemporaryDirectory() as tmp: + self.helper_suite(tmp, second=1) + code, ran, out = r.run_module(tmp, "test_first", False, None, os.path.join(tmp, "no", "such", "folder")) + self.assertEqual((code, ran), (0, 1), out) + + def test_a_parallel_run_shares_one_folder_and_removes_it(self): + with tempfile.TemporaryDirectory() as tmp: + suite(tmp, {"test_one.py": SHOWS_FOLDER, "test_two.py": SHOWS_FOLDER}) + result = cli(tmp, "-j", "2", "-v") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + folders = re.findall(r"shared-folder=(.+) exists=True", result.stdout) + self.assertEqual(len(folders), 2, result.stdout) + self.assertEqual(len(set(folders)), 1, result.stdout) + self.assertFalse(os.path.exists(folders[0])) + # Outside the suite's folder: nothing is written into the tree for it. + self.assertNotEqual(os.path.commonpath([os.path.realpath(tmp), os.path.realpath(folders[0])]), + os.path.realpath(tmp)) + + def test_a_child_is_not_given_the_folder_of_another_run(self): + # This runner started from a test of an outer run: that run's folder is in the environment, and it is + # neither ours to fill nor there for as long as our children run. + with tempfile.TemporaryDirectory() as tmp, tempfile.TemporaryDirectory() as outer: + suite(tmp, {"test_one.py": SHOWS_FOLDER}) + saved = os.environ.get(r.BYTECODE_CACHE_VARIABLE) + os.environ[r.BYTECODE_CACHE_VARIABLE] = outer + try: + code, ran, out = r.run_module(tmp, "test_one", False) + finally: + if saved is None: + del os.environ[r.BYTECODE_CACHE_VARIABLE] + else: + os.environ[r.BYTECODE_CACHE_VARIABLE] = saved + self.assertEqual((code, ran), (0, 1), out) + self.assertIn("shared-folder=None exists=False", out) + self.assertEqual(os.listdir(outer), []) + + class RunnerTest(unittest.TestCase): def test_parallel_timeout_reports_partial_output_and_keeps_healthy_modules(self): with tempfile.TemporaryDirectory() as tmp: