Skip to content

gamedata_reader: convert scalars, vectors and number arrays 1.5-2.9x faster, same values - #7706

Open
TG0000 wants to merge 2 commits into
ItsNotRexed:mainfrom
TG0000:perf/gamedata-reader-fast
Open

TG0000 wants to merge 2 commits into
ItsNotRexed:mainfrom
TG0000:perf/gamedata-reader-fast

Conversation

@TG0000

@TG0000 TG0000 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

AI-assisted (Claude Code, Claude Sonnet 5.5). Claimed in the coordination issue (#7599) as a new PERF item.

What

tools/gamedata_reader.py conversion hot paths, with no change to values, statistics (elements by convention), types or errors:

  • parse_scalar: isdecimal() replaces the INT regex call, and one combined SCALAR pattern (int, hex, float; ignore-case kept on the float part only) replaces up to three fullmatch calls.
  • parse_content: a body whose characters are only 0-9 . + - and ASCII whitespace converts with float()/int() in one pass (all tokens dotted, or none dotted; any ValueError, for example 1.2.3, falls back to the token-by-token path); vector/matrix grouping uses zip.
  • Reader.convert: returns <x value=".."/> and plain <v x y z w/> elements before the full ladder, and skips with_attributes when every attribute is one a convention consumes. assemble classifies children in one loop instead of up to two all() passes.
  • No cache and no global mutable state, so there is nothing to bound; the GC is untouched.

Not touched: read, run, documents, the docstring header, tools/gamedata_sps1.py, tools/gamedata_xml.py, tools/rbf0_tree.py. Open PRs touching this file (#7512, #6568, #3856, #4291) change other lines.

Benchmarks (synthetic documents generated by hand, no game data; Windows 11, Python 3.12.10, min of 40 interleaved Reader().read runs, before = origin/main 6664b0d)

document before after change
mixed, 3000 items (2.21 MB: scalars, vectors, typed items, 5 array kinds, extra attributes) 452.1 ms 273.4 ms -39.5% (1.65x)
arrays only (0.85 MB) 144.7 ms 50.8 ms -64.9% (2.85x)
scalars and vectors only (0.63 MB) 164.1 ms 102.3 ms -37.6% (1.60x)
sparse/odd: extra attributes everywhere, 500-token mixed arrays (0x2, 2.5f, ints) that take the fallback path (0.54 MB) 137.2 ms 101.2 ms -26.2% (1.35x)

A second full run of the same script gave mixed -37.1%, arrays only -60.6%, scalars/vectors -43.2% and sparse/odd -21.6%, so the sparse/odd stress case (nearly every token on the fallback path) sits around 22-26% while the three realistic shapes stay at 33-65%. The machine is noisy: repeated runs of the same comparison varied by about +-8 points (the sparse row went from 22% to 26% between runs), and the others stayed above 33%. For scale, ET.iterparse alone takes about 78 ms of the mixed document and is unchanged.

Memory (tracemalloc peak of one Reader().read)

document before after
mixed (dense) 34.18 MB 34.17 MB
arrays only (dense) 4.24 MB 4.24 MB
scalars/vectors only 3.07 MB 3.06 MB
sparse/odd 2.95 MB 2.95 MB

An earlier draft that validated a whole array body with one repeated regex peaked at 29 MB against 5.4 MB for a 60k-float body (the regex engine keeps state per repeated token); the unit test below caught it and it was replaced by the character-set check used here.

Tests

New tests/test_gamedata_reader_fast_paths.py (standard library, platform-independent: every expectation is computed by a reference implementation inside the test, no hashes or byte pins):

  • parse_scalar against the reference on known edge tokens (hex case, 1.5f, inf/nan, 1_0, Arabic-Indic digits, NBSP, empty), 60,000 random tokens and 20,000 random numbers; value, type (1 vs 1.0 vs True), signed zero, NaN and error message all compared.
  • parse_content on every array kind against bodies that take the bulk paths and their near misses (non-ASCII whitespace and digits, 1..5, 1.5 2, odd counts) plus 40,000 random bodies.
  • Reader.read against a reference Reader subclass without the shortcuts on 500 generated documents (with and without type handlers) and the vector-shortcut edge cases: values, stats and types equal.
  • Memory: peak of dense, sparse and mixed arrays no higher than the reference (5% slack), and no module-level container grows with the input.
    Two deliberate bugs (skipping the float check in the vector shortcut; widening the no-extras shortcut) each fail three of these tests.

Run on Windows 11, Python 3.12.10, no GPU involved:

  • python -m compileall -q tools/gamedata_reader.py tests
  • python -I tests/test_gamedata_reader.py (22 tests, OK)
  • python -I tests/test_gamedata_reader_fast_paths.py (10 tests, OK)
  • tests/semantic was not run (the translator is not touched).

🤖 Generated with Claude Code

…faster, same values

parse_scalar tests the common token shapes without a regex call and matches the rest with one combined pattern;
parse_content converts an array body of plain decimal numbers with float()/int() in one pass and groups with zip;
Reader.convert returns <x value=".."/> and plain vectors before the full ladder, skips with_attributes when every
attribute is one a convention consumes, and assemble classifies children in one loop. No cache and no global state.

tests/test_gamedata_reader_fast_paths.py compares the values, statistics, types and errors with an inline reference
implementation on known tokens, random tokens, random array bodies and random generated documents.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@CourtyardGames

Copy link
Copy Markdown

Confirmed a behavior change at 45ba98a when a registered type handler replaces the element’s attribute dictionary. With a synthetic <Item type="Distance"/>, my handler did:

element.attrib = {**element.attrib, "units": "meters"}
return 7

The base reader returned {"$value": 7, "@units": "meters"} and counted one extra attribute. The PR returns just 7 and drops that count. As a control, using element.set("units", "meters") in the same handler preserved the attribute on both versions. Reproduced on Windows with CPython 3.12.13 and 3.14, no game data.

Reader.convert now retains the pre-handler dictionary across _convert. Reading el.attrib again immediately after that call, before checking for extra attributes, would preserve the handler result while keeping the early scalar and vector returns.

AI-assisted source review and synthetic test.

@illusionart453-max

Copy link
Copy Markdown

Independent check of 45ba98a on Windows 11 / Python 3.15.0: pass.

  • python -I tests/test_gamedata_reader_fast_paths.py: 10 passed.
  • python -I tests/test_gamedata_reader.py: 22 passed.
  • Compared the actual parent module from HEAD^ directly with this head, rather than the test's inline reference: 28,854 scalar outcomes match, including every Unicode decimal digit in signed, decimal and exponent forms, deterministic random tokens, and 4,299/4,300/4,301/5,000-digit integer boundaries. Types, float.hex() values (including signed zero), NaN outcomes and exception text matched.
  • 15,000 direct-parent array outcomes match across five content kinds, including malformed mixed tokens and width errors.
  • A separate synthetic 60,000-float body benchmark gave median parse_content times of 40.44 ms parent and 9.69 ms PR over 12 runs each, about 4.17x here. This is a conversion microbenchmark, not an end-to-end read measurement.

No game files or GPU involved. AI-assisted verification (Codex).

@Kev-Ball

Copy link
Copy Markdown

Retail check at 45ba98ac1 against parent 6664b0dbb, CachyOS / CPython 3.14.10. I ran the default reader over the full Xbox 1.0.2.1 common.rpf carve. Of 267 XML payloads, both versions read the same 259. All 259 CLI-exported JSON files matched byte for byte. For the eight refusals the exception type and message matched, and every input produced the same per-convention counters and type counts.

Summed thread CPU time inside Reader.read went from 3.197 s to 2.518 s (21% less). Each pair used the same bytes with call order alternating by document; JSON export and comparisons were outside the timing. This covers the default reader with empty handler registries. The registered-handler discrepancy reported above is a separate path. AI-assisted QA.

@hcampbell98

Copy link
Copy Markdown

Tested 45ba98ac1 merged with main dde82f27e on Linux (WSL2, CPython 3.14.4 and 3.12.13, CPU only, no game files): Fail (registered type handler el.attrib replacement regression).

What passes

  • Merge, git diff --check dde82f27e...HEAD, python3 -I scripts/check_no_game_data.py ..., and python3 -m compileall -q tools tests: clean / exit 0.
  • tests/test_gamedata_reader.py: 22/22 OK on CPython 3.14.4 (0.521s) and CPython 3.12.13 (0.393s).
  • tests/test_gamedata_reader_fast_paths.py: 10/10 OK on CPython 3.14.4 (1.620s) and CPython 3.12.13 (1.858s).
  • Venv pytest -q: 32 passed, 359 subtests passed (2.66s).
  • tests/test_ci_registration.py 14/14 OK; tests/test_runner_calls_all_tests.py 3/3 OK; all other tests/test_gamedata_*.py pass except pre-existing tests/test_gamedata_blobs.py (test_missing_file_names_what_is_wrong, 2 != 1, identical on dde82f27e).
  • Synthetic read benchmark (4,000 scalars, 4,000 vectors, 20,000-float array, best of 5): 0.0445s (ReferenceReader) -> 0.0218s (Reader, 2.04x faster).

Blocking finding

tools/gamedata_reader.py:163,183-185 (Reader.convert) binds attrib = el.attrib before calling value = self._convert(el, use_type_handler) and uses that pre-handler attrib afterward. If a registered type handler reassigns el.attrib (independently confirming @CourtyardGames's report plus the converse stale-attribute leak):

  1. Adding an attribute (el.attrib = {**el.attrib, "units": "meters"} on <Item type="Distance"/>, returning 7):
    • main dde82f27e & ReferenceReader: [{'$value': 7, '@units': 'meters'}] with stats={'type handler': 1, 'extra attributes': 1, 'list': 1}
    • This PR (45ba98ac1): [7] with stats={'type handler': 1, 'list': 1} (silently drops @units and the extra attributes stat)
  2. Stripping an attribute (el.attrib = {"type": "Distance"} on <Item type="Distance" extra="1"/>, returning 7):
    • ReferenceReader: [7] with stats={'type handler': 1, 'list': 1}
    • This PR (45ba98ac1): [{'$value': 7, '@extra': 1}] with stats={'type handler': 1, 'extra attributes': 1, 'list': 1} (leaks the removed @extra attribute)

Refreshing attrib = el.attrib right after self._convert(el, use_type_handler) preserves both fast paths and exact equivalence on el.attrib replacement.

AI-assisted.

@TG0000

TG0000 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @hcampbell98 and @CourtyardGames for catching that! Fixed in 4da8991 by refreshing attrib = el.attrib right after self._convert(el, use_type_handler) and added regression tests in tests/test_gamedata_reader_fast_paths.py covering both adding and stripping attributes via a type handler (test_gamedata_reader.py 22/22 + test_gamedata_reader_fast_paths.py 11/11 OK). AI-assisted.

@memorypressure

Copy link
Copy Markdown

Tested head 45ba98a vs main dde82f2 (merged tree 746ac6856, clean): new suite Ran 10 OK; the gamedata family Ran 177 with one failure — test_gamedata_blobs BadCarveIndexTest.test_missing_file_names_what_is_wrong — which fails identically on clean main (main-side regression from #6701's error-convention flip), not attributable to you. Since your suite compares against an inline reference, I ran an independent differential between main's and your gamedata_reader: 1,541 crafted tokens, 12,160 kind×body combos, 3,000 random documents — 0 mismatches in values, types, exceptions and stats. Mutation probes on the three fast branches turn the suite red (41/31/101 failures), md5-clean restore. Measured: array bodies 2.9-3.7x, int scalars ~1.5x — but float scalars 0.84x and hex scalars 0.63x; the title range holds for array/mixed workloads, so a one-word scope note on the title would be accurate. Checks pending. AI-assisted: yes. Tested on Linux (RTX 5080 host, CPU-only run).

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.

6 participants