Skip to content

tests: parse the translator in pieces: 7 s -> 1 s per uncached import, 60 s -> 17 s in five standalone tests (TEST-TRANSLATOR-PIECEWISE-PARSE) - #2237

Draft
syfyra wants to merge 4 commits into
ProjectLeonida:mainfrom
syfyra:perf/translator-piecewise-parse
Draft

syfyra wants to merge 4 commits into
ProjectLeonida:mainfrom
syfyra:perf/translator-piecewise-parse

Conversation

@syfyra

@syfyra syfyra commented Nov 26, 2026 •

Copy link
Copy Markdown

Claimed in the coordination issue as: TEST-TRANSLATOR-PIECEWISE-PARSE (#1608 (comment))

What and why

A test process that finds no valid .pyc of tools/rdna2spirv.py compiles the 1.2 MB file from source. On CPython 3.12, 3.13.0 to 3.13.15 and 3.14.0 to 3.14.7 that takes 7 s, 0.1 s of it code generation: the tokenizer copies the rest of its input at every f-string field (update_fstring_expr: strlen(tok->cur), PyMem_Malloc, strncpy), and import hands the file over as one string, so the cost grows with the square of the file (4,759 f-strings, about 12,700 fields). CPython fixed it in 3.13.16, 3.14.8 and 3.15.0 (gh-155525 in CPython; read from the release tags). 3.12, which every CI job pins, is security-only and keeps it: v3.12.16 still copies.

That compile happens after every edit of the translator (most test files set sys.dont_write_bytecode, so the stale .pyc is never replaced: 7.2 s on every run of one test file until something else rewrites it), for each of the 14 translator copies test_mutations.py runs, and always where PYTHONDONTWRITEBYTECODE is set.

tests/semantic/piecewise_parse.py parses a source in pieces of 300 lines and joins them into the tree a whole-file parse gives: tokenize (line by line, linear) finds where statements start, top-level statements are parsed in runs, a longer top-level class is cut between the statements of its body, and each piece is parsed with one newline in front for every line before it, so positions are the file's. Anything that does not fit (a piece that does not parse, barry_as_FLUFL, a NUL, a statement that does not start where tokenize said) returns None and the source is compiled the usual way. tests/semantic/support.py hands the modules of TOOLS_DIR to a SourceFileLoader subclass that compiles that tree, through a sys.meta_path finder placed just before PathFinder, and only on the interpreters above. A valid .pyc is still used first.

A .pyc does not help a test that reads the translator's syntax tree. tests/test_runtime_paths.py, tests/test_isa_coverage.py, tests/test_shader_stage_resume.py, tests/test_cmake_translator_deps.py and tests/test_resource_hygiene.py made seven whole-file ast.parse calls on it between them, in every job that runs the standalone tests (check, stdlib-tests-linux, macos-python). They now call piecewise_parse.parse, which takes pieces on the interpreters above and the whole-file parse elsewhere. tools/isa_coverage.py parses inside scan_translator and accepted_names; its test patches ast.parse around those calls on the real translator, and the tool is not edited (#1799 changes those lines).

The helper is in tests/semantic/ because it is test infrastructure that support.py imports as a sibling, like spirv_mini_interp.py; tools/ is what make_game.py runs and what test_mutations.py copies and sabotages, and the loader for TOOLS_DIR should not come out of TOOLS_DIR.

Not changed: files that import rdna2spirv before support or without it (247 of the 491 at 9cd0c3f) still pay the 7 s; test_mutations.py keeps 13 in-process compile() calls on the whole translator text (its CRLF test), which is what is left of its time. scripts/run_semantic_tests.py, test_mutations.py and everything under tools/ are not edited. git merge-tree and git merge-file report no conflict with #2114, #1516, #2201, #1799, #565, #1361, #1372 or #1529.

One visible difference: when a module of tools/ has a syntax error, the SyntaxError (file, line, caret, message) is the same, but the traceback above it shows five importlib frames and support.py's source_to_code, which a plain import hides.

Tested

Windows 11, 8 logical CPUs, no GPU involved. The loader, measured at 9cd0c3f (before = that commit, after = the first commit of this branch on it):

before after
python -m unittest discover -s tests/semantic -p test_ps_semantics.py, Python 3.14.7 7.3 s 1.3 s
the same, Python 3.13.13 7.6 s 1.6 s
the same after the translator's mtime changed, bytecode writing allowed 7.2 s every run 1.2 s every run
tests/semantic/test_mutations.py alone 196.9 s 113.3 s
python -I scripts/run_semantic_tests.py tests/semantic (491 files, 6,312 tests, 0 failed, 8 jobs), bytecode writing allowed 246.4 s 161.3 s
the same with PYTHONDONTWRITEBYTECODE=1 597.6 s 396.7 s
-p "test_[bpv]*.py" on Python 3.13.13 (119 files, 1,892 tests, 0 failed) 171.6 s 88.5 s

The long ones are single runs on a machine other work shares. The branch has since been rebased onto a73a57e: there one file takes 1.3 s again (1.3, 1.3, 1.4) and a plain import of the translator 7.4 s; the long runs were not repeated.

The five standalone tests, Python 3.14.7 at a73a57e, with a valid .pyc of the translator as after CI's compileall step, two runs each (they agree within 0.3 s):

before after
python -I tests/test_runtime_paths.py (2 parses) 16.0 s 3.7 s
python -I tests/test_isa_coverage.py (2) 15.0 s 2.5 s
python -I tests/test_shader_stage_resume.py (1) 14.2 s 8.2 s
python -I tests/test_cmake_translator_deps.py (1) 7.6 s 1.4 s
python -I tests/test_resource_hygiene.py (1) 7.6 s 1.3 s
sum 60.4 s 17.1 s

They were found with a wrapper around compile that records every source over 500 kB, run over the 78 tests/test_*.py that mention the translator: nine such parses, these seven and two in tests/test_piecewise_parse.py itself, which needs the whole-file parse as its reference.

python -I tests/test_piecewise_parse.py: 26 tests, 46 s on 3.14.7 and 49 s on 3.13.13. It compares the trees for the 1,359 Python files under tools/, scripts/, tests/ and make_game.py in pieces of one statement (and the long files of tools/ in pieces of 300 lines; the translator in a test of its own), ast.dump(..., include_attributes=True) for 15 hand-written sources in pieces of 1, 2, 3, 5 and 8 lines with LF, CRLF and CR line ends, the exception for 28 sources with a syntax error and 9 the compiler rejects against compile's, the warnings, the code objects of 7 files and of the translator against compile(bytes), and the finder and loader on throwaway folders. It fails on main (the module does not exist).

Also run: python -m compileall -q on the changed files, python -I tests/test_text_write_line_endings.py, python -I tests/test_ci_registration.py, python -I tests/test_semantic_translator_use.py, python -I tests/test_run_semantic_tests.py (3.13.13, at 9cd0c3f), python -I scripts/check_no_game_data.py on the changed files, and the five tests above on 3.13.13.

From the review (1f92ae6):

  • lixonik ran e654d10 on CPython 3.12.1: 24 of the 25 tests passed and test_barry_as_flufl_is_parsed_whole errored. That parser does not read the barry_as_FLUFL import from the source (_PyPegen_checked_future_import is missing in v3.12.0, v3.12.1 and v3.13.0 and present in v3.12.16, v3.13.13 and v3.14.7), so the stock compile the test took as its reference rejects <>. The test now takes the running interpreter's compile outcome, tree or error, for both spellings. I have no 3.12.1: the new test passes and the old one fails with that parser's behaviour simulated.
  • GrahamboJangles measured the translator on a fixed interpreter (3.14.9: 0.21 s whole, 0.54 s in pieces), so parse() now takes pieces only where needed() says so, as support.py already did for the loader.

Not tested: Python 3.12 here (not installed; the 3.12.1 run above is the reviewer's, and CI's own run on 3.12 is the check), Linux and macOS, and an interpreter with the fix (3.13.16+, 3.14.8+) here.

GPUs tested: n/a

AI-assisted: yes (Claude Code)

Checklist

  • Based on current main and merges cleanly (a conflicting pull request is labeled needs rebase).
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (n/a: no translator rule)

🤖 Generated with Claude Code

syfyra and others added 2 commits November 26, 2026 10:44
… uncached import (TEST-TRANSLATOR-PIECEWISE-PARSE)

On CPython 3.12.0 to 3.14.7 the tokenizer copies the rest of its input at
every f-string field (update_fstring_expr: strlen, PyMem_Malloc, strncpy),
and import hands a module over as one string, so compiling the 1.2 MB
tools/rdna2spirv.py takes 7 s, 0.1 s of it code generation. CPython fixed it
in 3.14.8 and 3.15.0 (gh-155525); 3.12, which CI pins, keeps it.

tests/semantic/piecewise_parse.py finds statement starts with tokenize,
parses top-level statements in pieces of 300 lines (a longer class is cut
between the statements of its body) with one newline in front for every line
before the piece, and joins them into the tree a whole-file parse gives.
Whatever does not fit returns None and the source is compiled the usual way.

tests/semantic/support.py loads the modules of TOOLS_DIR through a
SourceFileLoader subclass that compiles that tree, by a sys.meta_path finder
placed just before PathFinder, only on the interpreters above. A valid .pyc
is still used first.

tests/test_piecewise_parse.py compares the trees for every Python file of
the repository, hand-written boundary cases, the exceptions and warnings
against compile(), and code objects against compile(bytes).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…SLATOR-PIECEWISE-PARSE)

v3.13.16 and v3.13.17 no longer copy the source at an f-string field
(Parser/lexer/lexer.c keeps last_expr_start); v3.12.16 still does. needed()
is now true on 3.12, 3.13.0 to 3.13.15 and 3.14.0 to 3.14.7.

The README paragraph moves below the one about calling the translator, so
it no longer touches the lines ubiquitarianism#2114 adds.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

@lixonik lixonik left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Windows 11 / CPython 3.12.1: 24/25 piecewise parser checks and 22/22 computed-I/J semantic tests passed. The parser suite has one error in the new Barry regression. Details inline.

AI-assisted.

Comment thread tests/test_piecewise_parse.py Outdated
accepted = "from __future__ import barry_as_FLUFL\na = 1\nb = a <> 2\n"
refused = "from __future__ import barry_as_FLUFL\na = 1\nb = a != 2\n"
self.assertIsNone(pp.parse_pieces(accepted, "<test>", 1))
self.assertEqual(dump(pp.parse(accepted, "<test>", 1)), dump(whole(accepted)))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Compare this fallback with the SyntaxError produced by the stock compiler.

On CPython 3.12.1, plain compile(source, ..., flags=ast.PyCF_ONLY_AST, dont_inherit=True) rejects <> even when the same source string starts with from __future__ import barry_as_FLUFL. The fallback in pp.parse correctly takes that path, so this test errors before evaluating its reference. Adding __future__.barry_as_FLUFL.compiler_flag explicitly made stock compile accept it, but pp.parse does not receive that flag. Use the same stock compiler outcome for both calls, while retaining the assertion that the piecewise parser gives up.

@GrahamboJangles

Copy link
Copy Markdown

Reviewed on Windows 11, head e654d10fdf vs base a73a57e133 — and this time I re-measured the headline claim on two interpreters at once: this machine has 3.13.14 (python3, inside the affected 3.13.0–3.13.15 window) and 3.14.9 (python, past the 3.14.8 fix).

The 7 s → 1 s claim reproduces. Timing tools/rdna2spirv.py (1,190,681 bytes) directly:

  • 3.13.14: needed() → True; whole-file parse 9.28 s, parse_pieces 1.55 s, and the piece tree's ast.dump (positions included) equals the whole-file parse's dump exactly. My machine is slower than the author's — same ratio, 6× — so "7 s → 1 s" is right in shape.
  • 3.14.9: needed() → False; whole-file parse 0.21 s, pieces 0.54 s — pieces are slower there, which is exactly why the finder must not (and does not) install on fixed interpreters.

End-to-end proof the loader is actually in the import path: I put a counting spy on piecewise_parse.parse_pieces (module attribute, so support.py picks it up) and timed import support on 3.13.14 with no valid .pyc present: 1.64 s total, and the spy logged 12 tools/ modules compiled from pieces, every one returning a tree (no fallback) — rdna2spirv.py first — with ToolsFinder sitting immediately before PathFinder in sys.meta_path. Same probe on 3.14.9: 0.07 s, zero parse_pieces calls, finder absent (valid 314 pyc used first — the test_a_valid_pyc_is_used_without_parsing rule live at real import).

Tests run at head (real runs, not just read):

  • python3 -I tests/test_piecewise_parse.py -v (3.13.14): 25/25 OK, 60.6 s — matches the docstring's ~45 s, slow machine. python -I tests/test_piecewise_parse.py (3.14.9): 25/25 OK, 38.2 s.
  • Consumer suites at head on 3.13.14: tests/semantic/test_active_cache.py 9 OK, tests/semantic/test_semantic_translator_use.py 3 OK — the translator tests load through the new loader and still pass. tests/semantic/test_alu_add_u16.py 5 OK but ~10.6 s wall: it imports rdna2spirv directly, no support — a live instance of the acknowledged "247 of the 491 files that import the translator without support still pay the 7 s" caveat, consistent with the PR text, not a regression.
  • Repo gates at head: scripts/check_no_game_data.py exit 0; compileall -q clean on all three touched/new files; tests/test_ci_registration.py 16 OK, same count as before — the new test file doesn't desync CI registration.

Code read. The 198-line helper end to end; the give-up discipline is the heart and checks out: _GIVE_UP catching MemoryError/RecursionError is broad but conservative (anything caught falls back to the usual compile, which then reports the real error in its own words), the tab-rule guard (indent not in (None, line[:column]) → body not cut) is deliberately conservative for mixed-indent class bodies, and the class _: dummy-header cut keeps each later piece's statements appended to the real ClassDef body with the end position pinned to the last piece — the test_the_class_ends_where_its_last_token_ends and RepositoryTest full-repo dump comparison pin that from both sides. _rows/_statements start-line bookkeeping (decorators and after-; statements can add rows) matches the _CONTINUES/decorator rules. Hand-written fixtures cover decorated nested classes, one-line if a: b = 1 clause chains, match/case soft keywords, except*, multi-line class headers, and CRLF/BOM/coding lines — every suite passes on both interpreters.

What I did not verify line by line: the two whole-file-parse fallbacks inside parse_pieces (len(rows) <= piece_lines and the short-source early return) were read, not exercised separately — the 25 tests pin their behavior through the boundary cases. Also the gh-155525/CPython-tag history in the docstring is the author's citation; I confirmed the behavior on 3.13.14 vs 3.14.9 matches it, not the tag names.

Coordination: cross-checked open PRs (is:pr TRANSLATOR-PIECEWISE-PARSE → only this one) and the #1608 claim list is fresh; no other PR carries the item. Merge state: mergeable=true, unstable, no failing checks.

Verdict: this is exactly what it claims. Same trees, same code objects, graceful fallback on everything it can't cut, finder active only on the interpreters that pay the quadratic tokenizer cost — reproduced at both ends of the affected window on one machine. The visible traceback difference on syntax errors (five importlib frames above support.py's source_to_code) is documented in the PR body, and test_an_error_in_a_module_is_the_one_the_usual_loader_raises pins the error itself is identical.

syfyra and others added 2 commits November 26, 2026 12:27
…s, 60 s -> 17 s (TEST-TRANSLATOR-PIECEWISE-PARSE)

A .pyc does not help ast.parse. test_runtime_paths.py, test_isa_coverage.py,
test_shader_stage_resume.py, test_cmake_translator_deps.py and
test_resource_hygiene.py read the syntax tree of tools/rdna2spirv.py, seven
whole-file parses of 7 s each on CPython 3.12, 3.13.0 to 3.13.15 and 3.14.0
to 3.14.7. They now call tests/semantic/piecewise_parse.parse, which gives
the same tree (tests/test_piecewise_parse.py) in about 1 s.

tools/isa_coverage.py parses inside scan_translator and accepted_names;
its test patches ast.parse around those two calls on the real translator
instead of changing the tool.

Python 3.14.7, valid .pyc of the translator, two runs each:
test_runtime_paths 16.0 -> 3.7 s, test_isa_coverage 15.0 -> 2.5 s,
test_shader_stage_resume 14.2 -> 8.2 s, test_cmake_translator_deps
7.6 -> 1.4 s, test_resource_hygiene 7.6 -> 1.3 s.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…s pieces only where needed (TEST-TRANSLATOR-PIECEWISE-PARSE)

Two findings from the review of ubiquitarianism#2237:

test_barry_as_flufl_is_parsed_whole errored on CPython 3.12.1 (lixonik):
there the parser does not read `from __future__ import barry_as_FLUFL` from
the source, so the stock compile it took as its reference rejects `<>`.
_PyPegen_checked_future_import is missing in v3.12.0, v3.12.1 and v3.13.0
and present in v3.12.16, v3.13.13 and v3.14.7. The test now takes this
interpreter's compile outcome, tree or error, for both spellings, and still
checks that the pieces give up.

On a fixed interpreter the pieces are the slower way (GrahamboJangles:
0.21 s whole, 0.54 s in pieces for the translator on 3.14.9). support.py
already installs its loader only where needed(); parse() now does the same
for its callers, the five standalone tests, unless piece_lines is named.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@syfyra syfyra changed the title tests: support.py compiles the translator from pieces, 7 s -> 1 s per uncached import (TEST-TRANSLATOR-PIECEWISE-PARSE) tests: parse the translator in pieces: 7 s -> 1 s per uncached import, 60 s -> 17 s in five standalone tests (TEST-TRANSLATOR-PIECEWISE-PARSE) Nov 26, 2026
@Tauwni

Tauwni commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Tested 1f92ae6a5 on an Apple M3 (macOS 26.5.1) with Homebrew's Python 3.12.16 and 3.15.2, against main a73a57e13.

  • tests/test_piecewise_parse.py: 26/26 pass on both.
  • scripts/run_semantic_tests.py tests/semantic: 498 files, 6351 tests, 0 failed on both versions.

The quadratic tokenizer cost is much smaller on this CPU than the 7 s in the description, but the gain on 3.12 is there:

main this PR
whole-file compile() of tools/rdna2spirv.py, 3.12 1.13 s —
import support with no .pyc (PYTHONDONTWRITEBYTECODE=1), 3.12 1.35 s 0.59 s
same, 3.15 (tokenizer already fixed) 0.24 s 0.24 s
full semantic suite, 3.12, 8 jobs 235 s 203 s

On 3.15 the import time is unchanged, as expected, since piecewise_parse.needed() leaves the usual loader in place there.

AI-assisted (Claude Code). No game data.

@syfyra

syfyra commented Nov 26, 2026

Copy link
Copy Markdown
Author

1f92ae6 addresses both reviews.

lixonik: test_barry_as_flufl_is_parsed_whole now takes the running interpreter's compile outcome, tree or error, for both <> and !=, and still asserts that the pieces give up. On 3.12.1 the parser does not read the import from the source: _PyPegen_checked_future_import is missing in v3.12.0, v3.12.1 and v3.13.0 and present in v3.12.16, v3.13.13 and v3.14.7. I have no 3.12.1, so this was checked with that behaviour simulated; a re-run there would confirm it.

GrahamboJangles: with your 3.14.9 figures (0.21 s whole, 0.54 s in pieces) parse() now takes pieces only where needed() says so, which matters since 53604ab makes five standalone tests call it.

AI-assisted (Claude Code).

@lixonik lixonik left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Retested 1f92ae6a5 on Windows 11 and CPython 3.12.1, where the original Barry fixture errored. All 26 piecewise parser tests now pass, including the Barry fallback, and all 22 computed-I/J semantic tests pass. This resolves my earlier test failure.

AI-assisted.

@Andretuta Andretuta left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Benchmarked 1f92ae6a5 on Windows with CPython 3.12.13 (the CI version) on top of current main (including #2193's scripts/run_standalone_tests.py -j 2 in check):

  • Semantic suite (-j 6, 500 files, 6,374 tests): 530.87 s -> 393.90 s (-136.97 s / -25.8%), 0 failures.
  • 5 updated standalone test files (-j 2): 47.09 s -> 12.64 s (-34.45 s; serial -j 1: 83.27 s -> 22.67 s).
  • Same standalone slice + tests/test_piecewise_parse.py (-j 2): 70.28 s (+23.19 s net over main; serial -j 1: 83.01 s vs 83.27 s baseline).

The implementation and fallback discipline in piecewise_parse.py and support.py look solid, and no correctness issues turned up. Before taking this out of draft, it may be worth trimming the default wall-clock cost of tests/test_piecewise_parse.py (which runs on every PR in check, macos-python, and the serial stdlib-tests-linux loop): most of the ~58 s on CPython 3.12 comes from RepositoryTest.test_every_python_file_gives_the_whole_file_tree (tests/test_piecewise_parse.py:783-809, parsing all ~1,360 repo .py files twice) and the two separate whole-file parses of tools/rdna2spirv.py in test_the_translator_tree_and_code_object_slow (lines 824 and 833). Keeping all boundary/error/warning/loader tests plus a smaller representative corpus check by default (or gating the full-tree sweep behind an env var) would preserve the standalone CI time savings as well.

AI-assisted review.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants