Skip to content

bvh_match: stream the manifest's Items instead of loading it whole (BUILD-1222) - #4310

Open
vibryxcx wants to merge 3 commits into
ItsNotRexed:mainfrom
vibryxcx:build-1222-stream-manifest
Open

vibryxcx wants to merge 3 commits into
ItsNotRexed:mainfrom
vibryxcx:build-1222-stream-manifest

Conversation

@vibryxcx

Copy link
Copy Markdown

Claimed in the coordination issue as: BUILD-1222 (claim; offered to @NiiRoZz, who had first refusal, here)

What and why

tools/bvh_match.py loaded the whole rpf9dump models manifest with json.load. A full levels.rpf manifest is 5.1 GB, and the process reached 20.6 GB of RAM.

main() now calls a new read_items(), which:

  • reads the manifest in 1 MB chunks and decodes one Items entry at a time (standard library only: json.JSONDecoder.raw_decode on a sliding buffer);
  • keeps only the fields the tool reads: Offset, File, Name, MeshTris, MeshModels, MeshGeoms, MeshShaders, and each material's Shader, with the material list kept in place because MeshShaders indexes it;
  • decodes and drops every other top-level member (Count, Scan, ...);
  • raises ValueError for anything that isn't such an object (a top-level array, a truncated file, an item that isn't an object, a trailing comma), so main() still prints one error: line and exits 2.

Nothing else in the matching changed: model_geometries() gives the same rows for a slimmed item as for the full one.

Tested

Windows 11 Pro 25H2 (build 26200), Python 3.12.10. CPU only, synthetic manifests; no GPU or game files.

  • python -I tests/test_bvh_match.py -v: 22/22 OK (18 existing + 4 new in TestStreamedManifest). The new tests run with a 7-byte chunk, so every token, number and item crosses a chunk boundary. They cover: slimmed items equal to a full load on the kept fields, extra fields dropped, members before and after Items, a quoted and non-ASCII name, empty/missing Items, five broken inputs, and main() reporting a truncated manifest in one line with exit 2.
  • Negative control: the new tests against main's tools/bvh_match.py give FAILED (errors=3).
  • Memory, on a synthetic 102 MB manifest with 40,000 items (each with extra material parameters, textures, bounds and LOD arrays), measured with tracemalloc: json.load peaks at 730 MB, read_items at 63 MB, in about the same time.
  • python -m compileall -q on both files and git diff --check: clean.

AI-assisted (Claude Code).

Checklist

  • 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 change.)

🤖 Generated with Claude Code

…UILD-1222)

A full levels.rpf `rpf9dump models` manifest is 5.1 GB, and json.load of it
took the process to 20.6 GB RAM. read_items() now reads the manifest in
1 MB chunks, decodes one item at a time and keeps only the fields the tool
reads (Offset, File, Name, MeshTris, MeshModels, MeshGeoms, MeshShaders and
each material's Shader, in place). Other top-level members are decoded and
dropped. A broken manifest is a ValueError, so main() still prints one line
and exits 2.

On a 102 MB synthetic manifest (40,000 items) the peak Python memory goes
from 730 MB to 63 MB at the same speed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@shdann

shdann commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested 2a07d70 on Windows, CPython 3.14.7, CPU only (no GPU, no game files). I used synthetic inputs only.

python -m pytest -q tests/test_bvh_match.py gives 22 tests passed and 5 subtests passed. I used a virtual environment with tests/requirements.txt.

I found one defect in the streaming reader. It refuses a valid JSON number when the first 1 MiB chunk ends at the exponent marker. When I move the same number by one space, the command succeeds. The merge base (03b09a0) accepts the two files.

Run this script from the repository root:

import json, runpy, tempfile
from pathlib import Path
t = runpy.run_path("tests/test_bvh_match.py")
with tempfile.TemporaryDirectory() as tmp:
    d = Path(tmp)
    blas = d / "blas.bin"
    blas.write_bytes(t["build"](t["LEAVES"], bounds=t["BOUNDS"])[0])
    t["write_obj"](d / "a.obj", [t["group"](2)])
    rows = json.dumps([t["item"](0, "a.obj", [2])])
    for extra in (0, 1):
        prefix = '{"Scale":'
        s = prefix + " " * ((1 << 20) - len(prefix) - 2 + extra) + '1e2,"Items":' + rows + '}'
        assert json.loads(s)["Scale"] == 100
        path = d / "manifest.json"
        path.write_text(s, encoding="ascii")
        print(extra, t["M"].main([str(blas), str(path)]))

Actual result: exit status 2 for extra=0, with expected , or }, found 'e'. Exit status 0 for extra=1.
Expected result: exit status 0 and the same candidate in the two cases.

Cause: raw_decode can return the integer part of a number while the rest of the exponent is still in the next chunk.
Possible correction: before you keep a number, check that a delimiter follows it in the buffer; if the buffer ends first, read the next chunk. A test at a real or reduced chunk boundary can pin it.

AI-assisted.

@Kam471 Kam471 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.

Ran this at 2a07d70a on Windows 11: python -I tests/test_bvh_match.py -> 22 tests, OK; compileall and git diff --check clean.

The manifest Items are now streamed instead of loaded whole, and the new cases cover the truncated/duplicate/large-manifest paths while the existing matching tests pass. No blocking issue.

@SweatierKey

Copy link
Copy Markdown
Contributor

Tested 2a07d70a on Linux (WSL2, Python 3.13.5, CPU only, no game files): pass.

  • Code read (tools/bvh_match.py, tests/test_bvh_match.py):
    • read_items streams top-level manifest keys in CHUNK-sized reads, slimming each entry in Items via _slim to ITEM_FIELDS plus positional Materials[i]["Shader"] before moving on, and compacts buf[pos:] on every more() call so memory stays bounded to one item plus the slimmed list.
    • complete_scalar=True properly guards against split numbers/booleans at chunk boundaries on non-Items top-level fields.
  • Checks run (clean worktree on 03b09a08):
    • python3 -I tests/test_bvh_match.py -v: 22/22 OK (including all 4 new TestStreamedManifest tests with CHUNK = 7 and malformed-JSON error handling).
    • git diff --check, test_docs_links.py (6/6), test_docs_repo_paths.py (2/2), test_text_write_line_endings.py (3/3), test_text_encoding.py (2/2): all pass.

AI-assisted review.

Review of ItsNotRexed#4310 (shdann): when the first 1 MiB chunk ended at the exponent
marker, raw_decode returned 1 for 1e|2 and the reader then failed on e.
A top-level scalar now has to end at least SCALAR_TAIL characters before
the buffer's end (or at end of file); otherwise the next chunk is read and
the value decoded again. Items are objects, so their numbers were never
affected. A test tries six numbers (exponents, signs, a 20-digit integer)
at every alignment against 5-, 7-, 11- and 13-character chunks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@vibryxcx

Copy link
Copy Markdown
Author

@shdann thanks, that's a real bug and a very clear repro. Fixed in f57e683: a top-level scalar now has to end at least 32 characters before the end of the buffer (or at end of file), otherwise the reader takes the next chunk and decodes the value again. Items themselves are objects, so their numbers were never at risk.

  • Your script at f57e683, Windows 11, Python 3.12.10: exit 0 for both extra=0 and extra=1.
  • New test_a_number_split_at_any_chunk_boundary: 1e2, -0.5E+3, 2.5e-07, a 20-digit integer, 0 and -7 at every alignment against 5-, 7-, 11- and 13-character chunks. python -I tests/test_bvh_match.py: 23/23 OK; the same test against 2a07d70 fails (29 errors).

@Kam471 thanks for the run.

AI-assisted (Claude Code).

@Flyander Flyander 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.

P2 — trailing JSON is accepted (tools/bvh_match.py:198)

I reproduced this on f57e6839 with the synthetic manifest {"Items":[{"Offset":1}]}junk: read_items() returns [{'Offset': 1}] instead of rejecting the invalid file. It returns as soon as it sees the closing } and never checks that the rest of the input is whitespace. The previous json.load() rejected extra data, so a truncated or concatenated manifest can now produce a plausible but incomplete match report.

After the closing brace, consume whitespace through EOF and raise ValueError if any non-whitespace remains. Please add a regression case for trailing garbage (and a second JSON value).

Review of ItsNotRexed#4310 (Flyander): read_items() returned as soon as it saw the
closing brace, so `{"Items":[...]}junk` or a second JSON value after the
object was accepted, while json.load refused both. Only whitespace may now
follow the object; anything else is a ValueError ("extra data after the
manifest object"), so main() prints one line and exits 2 as before. The
test checks junk, a second object, a stray bracket and an empty object
with junk, each also refused by json.loads, and that trailing whitespace
and newlines are still fine.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@vibryxcx

Copy link
Copy Markdown
Author

@Flyander good catch, thanks. Fixed in 6b60bfe: after the closing brace only whitespace may follow; anything else is a ValueError ("extra data after the manifest object"), so main() prints one line and exits 2, as json.load made it do before.

  • Your example {"Items":[{"Offset":1}]}junk now raises instead of returning [{'Offset': 1}].
  • New test_trailing_data_is_refused_like_json_load: junk, a second JSON object, a stray ] and {}x are refused (each also refused by json.loads), while trailing spaces and newlines are still accepted. Runs with 7-byte chunks.
  • python -I tests/test_bvh_match.py: 24/24 OK on Windows 11, Python 3.12.10; the new test against f57e683 fails (4 failures).

AI-assisted (Claude Code).

@Flyander Flyander 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.

The updated stream reader now rejects non-whitespace after the closing object, and the tests cover junk, a second JSON value, and valid whitespace. The chunk-boundary scalar regression also exercises exponent forms and multiple chunk sizes. I rechecked both fixes and found no remaining actionable issue in this diff.

@sds-228 sds-228 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.

Code review of 6b60bfe: the manifest stream parser retries split numbers, rejects trailing data, and covers every field read later. 24 tests OK; compileall and diff check clean.

AI-assisted (OpenCode).

@kapitche

Copy link
Copy Markdown
Contributor

Tested 6b60bfe merged with main 1cc6e3c on Linux/Python 3.12.16: concern (conflicts with main, and the merged result regresses the bucket rule)

  1. Textual conflict in tools/bvh_match.py (main moved: the non-object manifest check now lives in main() before items = manifest.get("Items")). Resolving it by taking read_items(a.manifest) works, since read_items already raises ValueError for a non-object manifest.

  2. After that resolution, python -I tests/test_bvh_match.py fails 2 of 46: test_no_bucket_rule_keeps_every_geometry and test_the_bucket_rule_leaves_buckets_1_and_2_out. Cause: main now selects geometries by the material's RenderBucket (ASSET-349, bvh_match: leave out geometries by render bucket (ASSET-349) #6330), but _slim() keeps only {"Shader": ...} per material, so every geometry reports "no render bucket" and the rule is silently not applied (3 candidates instead of 1). Adding "RenderBucket" to the kept material fields in _slim (and to the ITEM_FIELDS comment) fixes it: 46 of 46 pass. Please rebase on main and keep RenderBucket in the slimmed materials; a test that feeds read_items output through match_candidates with buckets would catch this.

Negative control: with tools/bvh_match.py from main and the PR's tests, 76 errors (no read_items), so the streaming tests do test the new code. On main alone the suite is 40 of 40.

Redundancy: not redundant; no merged PR streams the manifest (merged bvh_match PRs: #4559, #6330, #3935, #3787, #4497, #2712).

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.

7 participants