Skip to content

navmesh_decode: ~35% faster --deep on grid-heavy input, ~5x faster on a many-stream archive, output unchanged (PERF-NAVMESH-DECODE) - #7059

Open
TG0000 wants to merge 1 commit into
ItsNotRexed:mainfrom
TG0000:perf/navmesh-decode-fast
Open

TG0000 wants to merge 1 commit into
ItsNotRexed:mainfrom
TG0000:perf/navmesh-decode-fast

Conversation

@TG0000

@TG0000 TG0000 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

PERF-NAVMESH-DECODE (claimed in #7049: #7049 (comment)).

AI-assisted (Claude Code, Claude Sonnet 5.5). Same results, byte for byte, with less time and no more memory.

What changed (tools/navmesh_decode.py only, plus a new test file)

  • inflate_at copied up to 1 MiB of the mapped archive (m[pos:pos + CHUNK]) for every zlib stream, and d.unused_data copied most of it again, though a stream is usually a few KiB. The read window now starts at FIRST_CHUNK (16 KiB) and doubles up to the old CHUNK (1 MiB), so large streams read as before. The bytes consumed, the returned data and the None cases (truncated, corrupt, over the cap) are the same, since zlib does not depend on how the input is chunked.
  • The --deep grid walkers _grid_values, _grid_slots, _grid_octree and _grid_payloads made a _u64 / _u32 call (bounds check + struct.unpack_from) per slot and a Counter increment per key. They now unpack a group's 16 slots with one struct call, check the octree parents as a set, and read the payload words through one memoryview cast (_u32_table, with a struct fallback on a big-endian host, like _u16_max). Insertion order of the slot dict, the counters and the early False returns are kept.

Not touched: main() and the --out/--csv guards (#6234, #6367), the scan loops and wants_more (#6181), _poly_chain and the bit 3 water test (#6136), decode_7a. No Depends on:; this should merge cleanly with them.

Benchmark

python -I, standard library only, Windows 11, Python 3.12, CPython. Synthetic archives built from the builders in tests/test_navmesh_decode.py (nothing from the game). scan(path, deep=True, rows=[]), median of 7 to 40 runs, before (origin/main 6596542) / after:

input before after
260 KB archive, 6 tiles of 3000 polygons / 2500 vertices / 1200 volumes, 6 grids of 4681 octree keys, 30 cover resources 0.099 s / 0.098 s 0.062 s / 0.064 s 1.55x (about 36% less time)
25 MB archive, 3342 streams (1500 small tiles, 1500 incompressible 6-26 KB streams, 300 grids, plus the above) 1.87 s / 1.93 s (two runs) 0.390 s / 0.385 s 4.9x (about 79% less time)

The second row is the case the 1 MiB window hurt: the cost grows with the number of streams, and the real navmeshes.rpf has many. Only the first row measures the decoding itself; its gain is the grid walkers.

Peak memory (tracemalloc, same two inputs), before / after: 4.03 MB / 3.60 MB and 5.71 MB / 3.60 MB. No cache was added.

Parity: the JSON summary and every CSV row (rows) of both archives, with elapsed_s zeroed, hash to the same SHA-256 before and after (34db9b78… and 98682e58…), and no check fails.

Tests

tests/test_navmesh_decode_fast.py (17 tests) keeps the previous implementations as an oracle and compares the whole result with the new ones:

  • grids: octrees of depth 0 to 4, full and partly empty groups, duplicate and out-of-range values, a bad control byte, garbage in empty slots (never read), two slots with one key (the later wins), the slot dict's insertion order, payload words of every kind and the counters they feed, an inner node without the inner word (False, counters untouched), the big-endian payload path, and that no view keeps a bytearray pinned;
  • octree key shapes (no root, key 0, orphans, wrong bit length, 64-bit keys, empty) and 200 random octrees with one corrupted key;
  • inflate_at: streams of 0 bytes up to 3 MiB around every window boundary, noisy and constant, with and without trailing junk; truncated and corrupt streams; a size bound inside the stream; the output cap; reading from an mmap; and that the window doubles up to CHUNK and never past it.

Three mutations of the new code (dropping the root-parent exclusion, keeping the first duplicate key, a window that jumps to 2 MiB) each fail it.

Run here: python -m compileall -q tools/navmesh_decode.py tests, and python -I tests/test_<name>.py for every tests/test_navmesh*.py (cell_fit, decode, decode_fast, index, links, nodes): all pass. tests/semantic was not run (no translator change). No GPU involved.

… grid tables in bulk (PERF-NAVMESH-DECODE)

inflate_at copied up to 1 MiB of the mapped archive for every zlib stream, though most streams are a few KiB;
the window now starts at 16 KiB and doubles up to the old 1 MiB. The --deep grid walkers (_grid_values,
_grid_slots, _grid_octree, _grid_payloads) unpack a group's 16 slots at once, test the octree parents as a set
and read the payload words through one view instead of calling _u64/_u32 per slot. Output is unchanged.

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

Copy link
Copy Markdown
Contributor

Review: PR #7059, navmesh_decode fast paths (PERF-NAVMESH-DECODE)

Verdict: approve. I found no behaviour change. Each rewritten path matches its old version once you account for what decode_grid has already checked by the time it runs, and the new parity suite pins that down. Two small nits are at the end; neither blocks merging.

What changed

1. inflate_at: the read window grows instead of starting at 1 MiB

  • Before, every zlib stream copied up to CHUNK (1 MiB) of the mapped archive, even though most streams are a few KiB.
  • Now the first slice is FIRST_CHUNK (16 KiB). The window doubles on each refill, up to the old CHUNK limit.
  • Output is unchanged because zlib.decompressobj is a streaming decoder. How the input is split into pieces does not change the decompressed bytes, eof, unused_data or unconsumed_tail.
  • The stored-size formula pos - start - len(d.unused_data) - len(pending) stays correct for any window size, since pos always moves by exactly len(pending).
  • The cap + 1 - total output limit and the pos >= size truncation return are untouched.
  • A 1 MiB-plus stream now costs about seven slices instead of one. The extra copying is bounded at roughly double the old amount and only happens on large streams. That is the right trade for an archive made mostly of small streams.

2. _grid_values and _grid_slots: one unpack per group

  • Each group now reads all 32 u64 values (16 key/value pairs) with a single Struct("<32Q").unpack_from, instead of calling _u64 once per slot.
  • The old value is None guard is gone. That is safe because decode_grid only reaches --deep when table_in_bounds holds (0x60 + GRID_GROUP * groups <= len(b)), so _u64 could never have returned None here. The new code reads exactly the same 272 bytes per group.
  • The fast branch in _grid_values (max(ctrl) < 0x80, meaning all 16 slots are occupied) is correct. control_bytes has already ruled out any control byte above 0x80, so "any empty slot" and "max(ctrl) >= 0x80" mean the same thing.
  • Dict insertion order in _grid_slots is preserved (same group and slot order). The test checks this explicitly with list(keys).

3. _grid_octree: one subset test instead of a membership check per key

  • (key.bit_length() - 1) % 3 still rejects key 0, because (-1) % 3 == 2. The explicit key == 0 check is redundant, as the comment says.
  • Only key 1 has key >> 3 == 0, so parents.discard(0) drops exactly the root's pseudo-parent.
  • parents <= keys.keys() is the same as "every non-root key's parent is present". Keys are u64, so negative keys cannot occur.
  • The old code stopped at the first bad key. Nothing else depends on that order: the function has no side effects, so only the boolean matters.

4. _grid_payloads: payload words read through one view

  • Bounds are already established before this runs:

    • payload_in_bounds checks payload + 4 * entries <= len(b).
    • offset_of never returns a negative value, so the negative-index wrap-around of memoryview slicing cannot happen.
    • The caller requires len(keys) == entries.
    • _grid_values has proven every value is below entries.

    So table[value] is always in range, as _u32 was before.

  • The view is released in a finally block, so a bytearray input stays resizable. test_payload_view_does_not_pin_a_bytearray covers this.

  • On refusal (an inner node whose word is not 0x0000ff00), stats is left untouched, exactly as before.

  • On success, Counter.update gives the same counts and the same first-seen key order in key_depth and leaf_payload, so JSON and CSV output is byte-identical.

  • On big-endian hosts it falls back to a struct.unpack_from("<%dI") tuple. The test exercises this by patching sys.byteorder.

Nits (non-blocking)

  • memoryview.cast("I") uses the C unsigned int, which is 4 bytes on every platform CPython supports but is not guaranteed. A one-line guard such as sys.byteorder == "little" and struct.calcsize("I") == 4 would make the fallback cover that case too.
  • _grid_slots unpacks all 32 words even for a group that is completely empty. This is harmless and bounded by table_in_bounds; I mention it only because _grid_values already has a per-group branch.

Tests (Windows 11 Pro, CPython 3.13, no game files)

Check Result
git diff --check PASS
python -m compileall -q make_game.py tools tests PASS
check_no_game_data.py PASS
python -I make_game.py --help PASS
python -I tests/test_navmesh_decode.py 17/17 OK (existing suite, outputs unchanged)
python -I tests/test_navmesh_decode_fast.py 17/17 OK (new parity suite)

The new suite keeps the previous implementations verbatim as ref_* oracles and compares whole results against them. It covers:

  • octrees of depth 0–4;
  • partly empty groups;
  • duplicate and out-of-range values;
  • garbage in empty slots;
  • a key repeated in two slots (the later value wins);
  • 200 seeded random octrees with one corrupted key;
  • zlib streams around every window boundary, with trailing junk;
  • truncated and corrupt streams;
  • the size bound and the output cap;
  • reading from a real mmap;
  • a spy confirming the window doubles and never exceeds CHUNK.

I also ran a synthetic micro-benchmark, comparing the ref_* oracles with the new code on generated data only:

  • 3000 small zlib streams followed by 4 MiB of trailing padding: inflate_at went from 1.71 s to 0.02 s.
  • A 512-group, 4681-key depth-4 octree, run through _grid_values, _grid_slots, _grid_octree and _grid_payloads 50 times: 0.48 s down to 0.22 s.

These numbers are consistent with the claimed ~5× (many-stream archive) and ~35% (--deep on grid-heavy input). I did not reproduce the exact figures in the title, because that needs the real archive.

Rules

  • No game data: all fixtures are built by hand (build_grid, zlib.compress of seeded random bytes, temporary files), and no carved content, logs or hashes are committed.
  • No decryption or protection workarounds: the change only touches the zlib walking and the grid-table parsing.
  • Nothing online: no network access.
  • Fix, don't disable: every acceptance check in decode_grid is unchanged; nothing is skipped or loosened. This PR adds no translator rule, so no docs/design.md contract-table entry is needed.

AI-assisted.

@kapitche

Copy link
Copy Markdown
Contributor

Tested eb0939a merged with main 8575d36 on Linux/Python 3.12.16: pass

  • python -I tests/test_navmesh_decode_fast.py: 17 tests OK
  • Other navmesh tests on the merge: test_navmesh_cell_fit.py, test_navmesh_decode.py, test_navmesh_links.py, test_navmesh_nodes.py: OK; test_navmesh_index.py: OK (1 skipped)
  • Negative control: git checkout upstream/main -- tools/navmesh_decode.py, python -I tests/test_navmesh_decode_fast.py: FAILED (errors=5). Restored with git checkout HEAD --.

Diff read: the struct.Struct("<32Q").unpack_from reads in _grid_values / _grid_slots cannot run past the buffer because decode_grid already requires table_in_bounds (0x60 + GRID_GROUP * groups <= len(b)) before calling them, and _grid_payloads is only reached after payload_in_bounds. The rewritten _grid_octree (every key's depth ok, set of parents minus 0 a subset of keys) is equivalent to the old per-key key >> 3 in keys check, since only key 1 has parent 0 among keys that pass the depth test. Synthetic buffers only; no real archive.

@airp1ane

Copy link
Copy Markdown
Contributor

Tested eb0939a on Windows 11, Python 3.15.2, NVIDIA RTX 4060 Ti (driver 621.24; CPU-only checks, no game files, no GPU/llvm-mc/MSVC used): pass.

Ran the test files this PR adds or changes, from a clean checkout of the PR head: test_navmesh_decode_fast.py - all exit 0.

AI-assisted (Claude Code).

@ne1i

ne1i commented Nov 23, 2026

Copy link
Copy Markdown

Tested eb0939ac on Linux, CPython 3.14, CPU only, synthetic inputs, merged onto main 867d922f: pass

  • python -I tests/test_navmesh_decode_fast.py: Ran 17 tests, OK. With only the non-test files reverted to main: FAILED (errors=5).
  • compileall and scripts/check_no_game_data.py on the changed files: clean.

I did not measure the speed claim.

Independent check (not the author). Run by an AI agent (DeepSeek V4.1 Flash) and re-run by the orchestrating session (Claude Code) before posting; coordination: #8504.

@ne1i

ne1i commented Nov 23, 2026

Copy link
Copy Markdown

Tested eb0939ac on Linux, CPython 3.14, CPU only, synthetic inputs, merged onto main 867d922f0: pass

  • python -I tests/test_navmesh_decode_fast.py: Ran 17 tests, OK. With only tools/navmesh_decode.py reverted to main: FAILED (errors=5), so the new tests exercise the change.
  • compileall and scripts/check_no_game_data.py on the changed files: clean.

The agent's reading, which I did not repeat: the bulk read is only taken when a control byte is at least 0x80, and the existing bounds check already guarantees those bytes; the parity tests instrument the read window rather than re-implementing the old decoder. I did not measure the speed claim.

Independent check (not the author). Run by an AI agent (DeepSeek V4.1 Flash) and re-run by the orchestrating session (Claude Code) before posting.

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