runtime: optimize ArenaBlocks walk, node reuse, and power-of-two align_up (RT-ARENA-BLOCKS-PERF-AND-REUSE) #1985

Closed
leonida/mandy
quietfold wants to merge 0 commits from perf/rt-arena-blocks-perf-and-reuse into main

Pull request closed

This pull request cannot be reopened because the branch was deleted.

quietfold commented 2026-11-25 17:26:08 +00:00

Item ID: RT-ARENA-BLOCKS-PERF-AND-REUSE (claimed in #1608)

Summary

Optimizes leonida::ArenaBlocks (runtime/src/arena_blocks.h), the GPU address arena's free-block allocator used on resource creation and destruction:

  1. Sequential walk without repeated O(log N) tree descents: allocate() previously restarted blocks_.lower_bound(cursor) from the RB-tree root on every single free block and called blocks_.find(block) before cut(). Undersized or unaligned blocks never invoke keep_out(), and when keep_out() runs without mutating blocks_ (checked via a monotonic mutation_ counter), the existing iterator remains valid — turning the first-fit walk from O(k log N) into O(k) sequential iterator increments and cutting directly without a redundant lookup.
  2. Re-entrant reset() detection: tracks a separate monotonic mutation_ counter incremented in reset(), cut(), and release() (leaving cuts() unchanged), so a re-entrant reset() inside keep_out() when cuts() == 0 is still caught cleanly.
  3. O(1) total-free-space early rejection: returns false immediately when bytes > free_bytes_ (when no block can satisfy bytes and keep_out() could never be invoked).
  4. Power-of-two align_up() fast path: replaces 64-bit modulo/division with overflow-safe bitmask arithmetic for power-of-two alignments while keeping the exact fallback for arbitrary alignments.
  5. Zero-allocation RB-tree node reuse in cut() and release():
    • cut() shrinks the node in place on suffix/middle cuts, uses std::map::extract() + hinted insert() on prefix cuts (reusing the node with zero heap allocation), and uses emplace_hint() on middle splits.
    • release() extends an adjacent left neighbor in place, recycles an absorbed right node via extract() + hinted insert(), and uses emplace_hint() for isolated inserts.
  6. Expanded unit tests in runtime/test/arena_blocks_test.cpp covering 2^63 power-of-two overflow, non-power-of-two alignment, re-entrant reset() when cuts() == 0, bytes > free_bytes() fast reject, and all prefix/middle/suffix/left/right/3-way coalesce paths.

Benchmarks (-O2, bit-exact A/B vs upstream/main)

  • Fragmented 2,000-hole scan × 5,000 alloc/release: 94.926 ms → 16.776 ms (5.66× faster)
  • Mixed alloc/release churn (200k ops, 256 slots): 20.393 ms → 11.721 ms (1.74× faster)
  • Oversized reject (1,000 holes × 20,000 calls): 0.079 ms → 0.036 ms (2.18× faster)

Testing & Disclosure

  • AI-assisted: yes
  • GPUs tested: none (macOS host, CPU-only portable unit test and A/B benchmark)
  • clang++ -std=c++20 -g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer -Wall -Wextra -Werror runtime/test/arena_blocks_test.cpp: PASS
  • clang++ -std=c++20 -g -O1 -fsanitize=thread -fno-omit-frame-pointer -Wall -Wextra -Werror runtime/test/arena_blocks_test.cpp: PASS
  • clang++ -std=c++20 -O2 -Wall -Wextra -Werror runtime/test/arena_blocks_test.cpp: PASS
  • python3 -I scripts/check_no_game_data.py runtime/src/arena_blocks.h runtime/test/arena_blocks_test.cpp: PASS
  • python3 -I tests/test_text_write_line_endings.py: PASS (3/3)
Item ID: `RT-ARENA-BLOCKS-PERF-AND-REUSE` (claimed in #1608) ## Summary Optimizes `leonida::ArenaBlocks` (`runtime/src/arena_blocks.h`), the GPU address arena's free-block allocator used on resource creation and destruction: 1. **Sequential walk without repeated O(log N) tree descents**: `allocate()` previously restarted `blocks_.lower_bound(cursor)` from the RB-tree root on every single free block and called `blocks_.find(block)` before `cut()`. Undersized or unaligned blocks never invoke `keep_out()`, and when `keep_out()` runs without mutating `blocks_` (checked via a monotonic `mutation_` counter), the existing iterator remains valid — turning the first-fit walk from O(k log N) into O(k) sequential iterator increments and cutting directly without a redundant lookup. 2. **Re-entrant `reset()` detection**: tracks a separate monotonic `mutation_` counter incremented in `reset()`, `cut()`, and `release()` (leaving `cuts()` unchanged), so a re-entrant `reset()` inside `keep_out()` when `cuts() == 0` is still caught cleanly. 3. **O(1) total-free-space early rejection**: returns `false` immediately when `bytes > free_bytes_` (when no block can satisfy `bytes` and `keep_out()` could never be invoked). 4. **Power-of-two `align_up()` fast path**: replaces 64-bit modulo/division with overflow-safe bitmask arithmetic for power-of-two alignments while keeping the exact fallback for arbitrary alignments. 5. **Zero-allocation RB-tree node reuse in `cut()` and `release()`**: - `cut()` shrinks the node in place on suffix/middle cuts, uses `std::map::extract()` + hinted `insert()` on prefix cuts (reusing the node with zero heap allocation), and uses `emplace_hint()` on middle splits. - `release()` extends an adjacent left neighbor in place, recycles an absorbed right node via `extract()` + hinted `insert()`, and uses `emplace_hint()` for isolated inserts. 6. **Expanded unit tests** in `runtime/test/arena_blocks_test.cpp` covering 2^63 power-of-two overflow, non-power-of-two alignment, re-entrant `reset()` when `cuts() == 0`, `bytes > free_bytes()` fast reject, and all prefix/middle/suffix/left/right/3-way coalesce paths. ## Benchmarks (`-O2`, bit-exact A/B vs `upstream/main`) - Fragmented 2,000-hole scan × 5,000 alloc/release: 94.926 ms → **16.776 ms** (**5.66×** faster) - Mixed alloc/release churn (200k ops, 256 slots): 20.393 ms → **11.721 ms** (**1.74×** faster) - Oversized reject (1,000 holes × 20,000 calls): 0.079 ms → **0.036 ms** (**2.18×** faster) ## Testing & Disclosure - AI-assisted: yes - GPUs tested: none (macOS host, CPU-only portable unit test and A/B benchmark) - `clang++ -std=c++20 -g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer -Wall -Wextra -Werror runtime/test/arena_blocks_test.cpp`: PASS - `clang++ -std=c++20 -g -O1 -fsanitize=thread -fno-omit-frame-pointer -Wall -Wextra -Werror runtime/test/arena_blocks_test.cpp`: PASS - `clang++ -std=c++20 -O2 -Wall -Wextra -Werror runtime/test/arena_blocks_test.cpp`: PASS - `python3 -I scripts/check_no_game_data.py runtime/src/arena_blocks.h runtime/test/arena_blocks_test.cpp`: PASS - `python3 -I tests/test_text_write_line_endings.py`: PASS (3/3)
copilot-pull-request-reviewer[bot] reviewed 2026-11-25 17:26:19 +00:00
copilot-pull-request-reviewer[bot] left a comment
No description provided.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
zmasi commented 2026-11-28 11:51:48 +00:00

Verified on Windows 11 (10.0.26200.9974) with MSVC 19.44.35228 (x64, /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2) against main 24549bdb1 + 5735c1cf6 (claim #2570#issuecomment-7238799031):

  • Line-by-line diff audit: Clean (runtime/src/arena_blocks.h, runtime/test/arena_blocks_test.cpp); tracks a monotonic mutation_ counter across reset(), cut(), and release() so re-entrant reset() inside keep_out() when cuts() == 0 is detected, walks blocks_ sequentially while skipping undersized/unaligned blocks without invoking keep_out(), reuses std::map nodes via extract/insert, and adds a power-of-two align_up fast path with overflow check. check_no_game_data.py clean.
  • Red (24549bdb1 + PR test): arena_blocks_test.exe fails (rc=1 at line 313: b.allocate(0x1000, kAlign, reset_keep_out, out) && did_reset && out == kReserved + 0x4000).
  • Green (24549bdb1 + 5735c1cf6 merge): Merges cleanly (rc=0), compiles with 0 /W4 warnings, and arena_blocks_test.exe passes (arena_blocks: ok, rc=0).

AI-assisted.

Verified on Windows 11 (`10.0.26200.9974`) with MSVC `19.44.35228` (`x64`, `/std:c++20 /EHsc /W4 /permissive- /utf-8 /O2`) against `main` `24549bdb1` + `5735c1cf6` (claim `#2570#issuecomment-7238799031`): - **Line-by-line diff audit**: Clean (`runtime/src/arena_blocks.h`, `runtime/test/arena_blocks_test.cpp`); tracks a monotonic `mutation_` counter across `reset()`, `cut()`, and `release()` so re-entrant `reset()` inside `keep_out()` when `cuts() == 0` is detected, walks `blocks_` sequentially while skipping undersized/unaligned blocks without invoking `keep_out()`, reuses `std::map` nodes via `extract`/`insert`, and adds a power-of-two `align_up` fast path with overflow check. `check_no_game_data.py` clean. - **Red (`24549bdb1` + PR test)**: `arena_blocks_test.exe` fails (`rc=1` at `line 313: b.allocate(0x1000, kAlign, reset_keep_out, out) && did_reset && out == kReserved + 0x4000`). - **Green (`24549bdb1` + `5735c1cf6` merge)**: Merges cleanly (`rc=0`), compiles with `0` `/W4` warnings, and `arena_blocks_test.exe` passes (`arena_blocks: ok`, `rc=0`). AI-assisted.
Kal0s-design commented 2026-11-30 12:55:08 +00:00

Independent Windows check under AddressSanitizer of 5735c1cf6 merged onto current main 497bdd039 (clean, tree 0c56b3c78). MSVC 19.50 (toolset 14.50) x64, /std:c++20 /W4 /permissive- /Od /MDd /fsanitize=address, so the debug STL's checked iterators are on too and flag any use of an invalidated blocks_ iterator, which is what the in-place walk and the extract/hinted-insert node reuse could get wrong.

  • runtime/test/arena_blocks_test.cpp from the merged tree: arena_blocks: ok under ASan + checked iterators, and at /O2 /MD. 0 warnings at /W4.
  • A local randomized probe (not part of the PR), built twice under the same flags, once with main's arena_blocks.h and once with this PR's. 300 arenas × 2,000 operations: allocate with power-of-two and arbitrary alignments and 0 to 3 keep-out ranges, release, and allocate_at. One allocate in 16 has a keep_out that releases a live range during the walk, which exercises the mutation_ path. After every operation it checks that each allocation is aligned, inside [reserved, size), and overlaps no live range or keep-out range, that check() returns none, and that consistent(live_bytes) holds.
    • Both builds: 600,000 operations, 201,549 allocations, 0 violations, no ASan or iterator-debug report.
    • A digest of every result (each success flag, offset and release fault) is identical between main and this PR (23a49f055b1a230b), so first-fit places every allocation at the same offset as before.

GPUs tested: n/a (CPU unit test). AI-assisted: yes.

**Independent Windows check under AddressSanitizer** of `5735c1cf6` merged onto current `main` `497bdd039` (clean, tree `0c56b3c78`). MSVC 19.50 (toolset 14.50) x64, `/std:c++20 /W4 /permissive- /Od /MDd /fsanitize=address`, so the debug STL's checked iterators are on too and flag any use of an invalidated `blocks_` iterator, which is what the in-place walk and the `extract`/hinted-`insert` node reuse could get wrong. - `runtime/test/arena_blocks_test.cpp` from the merged tree: `arena_blocks: ok` under ASan + checked iterators, and at `/O2 /MD`. 0 warnings at `/W4`. - A local randomized probe (not part of the PR), built twice under the same flags, once with `main`'s `arena_blocks.h` and once with this PR's. 300 arenas × 2,000 operations: `allocate` with power-of-two and arbitrary alignments and 0 to 3 keep-out ranges, `release`, and `allocate_at`. One `allocate` in 16 has a `keep_out` that releases a live range during the walk, which exercises the `mutation_` path. After every operation it checks that each allocation is aligned, inside `[reserved, size)`, and overlaps no live range or keep-out range, that `check()` returns `none`, and that `consistent(live_bytes)` holds. - Both builds: 600,000 operations, 201,549 allocations, 0 violations, no ASan or iterator-debug report. - A digest of every result (each success flag, offset and release fault) is identical between `main` and this PR (`23a49f055b1a230b`), so first-fit places every allocation at the same offset as before. GPUs tested: n/a (CPU unit test). AI-assisted: yes.
merzleckeier commented 2026-11-30 13:09:41 +00:00

Independent Linux A/B for 5735c1cf6 against 497bdd039 using GitHub’s merge 0b9b10e4e. CachyOS x86-64. GCC 16.2.1 -O2 and Clang 23.1.5 -O1 with ASan + UBSan. Both builds use C++20 and -Wall -Wextra -Werror.

MEASURED (one archived run per revision per build mode). The stock arena_blocks_test passed in all four builds. A separate byte-bitmap oracle enumerated every initial occupancy of a six-byte arena at base 3 and at UINT64_MAX - 6. It tried 25 keep-out masks (empty, every contiguous interval, and three fragmented masks), request lengths 0–7, and 13 alignments including zero, non-powers of two, and values near the integer limit. Each build matched the oracle on 332,800 allocation attempts (14,188 first fits) and 2,688 contiguous releases (2,046 overlapping already-free bytes), including exact placement, coalescing, and free-byte/fault accounting.

MEASURED heap traffic. A replacement scalar operator new and operator delete counted calls only during each individual allocate_at or release. Both build modes gave the same counts.

Operation Main new / delete PR new / delete
Prefix or suffix cut (each) 1 / 1 0 / 0
Middle split 2 / 1 1 / 0
Whole-block cut 0 / 1 0 / 1
Release joining only the left or right block (each) 1 / 1 0 / 0
Release joining both blocks 1 / 2 0 / 1
Isolated release 1 / 0 1 / 0
Release partly overlapping two blocks (one on each side, or both on the right, each) 1 / 2 0 / 1

CPU-only synthetic test. AI-assisted. A second agent recomputed the counts from the raw output.

**Independent Linux A/B for `5735c1cf6`** against `497bdd039` using GitHub’s merge `0b9b10e4e`. CachyOS x86-64. GCC 16.2.1 `-O2` and Clang 23.1.5 `-O1` with ASan + UBSan. Both builds use C++20 and `-Wall -Wextra -Werror`. **MEASURED (one archived run per revision per build mode)**. The stock `arena_blocks_test` passed in all four builds. A separate byte-bitmap oracle enumerated every initial occupancy of a six-byte arena at base 3 and at `UINT64_MAX - 6`. It tried 25 keep-out masks (empty, every contiguous interval, and three fragmented masks), request lengths 0–7, and 13 alignments including zero, non-powers of two, and values near the integer limit. Each build matched the oracle on 332,800 allocation attempts (14,188 first fits) and 2,688 contiguous releases (2,046 overlapping already-free bytes), including exact placement, coalescing, and free-byte/fault accounting. **MEASURED heap traffic**. A replacement scalar `operator new` and `operator delete` counted calls only during each individual `allocate_at` or `release`. Both build modes gave the same counts. | Operation | Main `new / delete` | PR `new / delete` | | --- | ---: | ---: | | Prefix or suffix cut (each) | 1 / 1 | 0 / 0 | | Middle split | 2 / 1 | 1 / 0 | | Whole-block cut | 0 / 1 | 0 / 1 | | Release joining only the left or right block (each) | 1 / 1 | 0 / 0 | | Release joining both blocks | 1 / 2 | 0 / 1 | | Isolated release | 1 / 0 | 1 / 0 | | Release partly overlapping two blocks (one on each side, or both on the right, each) | 1 / 2 | 0 / 1 | CPU-only synthetic test. AI-assisted. A second agent recomputed the counts from the raw output.
aslan2142 commented 2026-12-01 16:40:32 +00:00

Closing this PR because the legacy C++ Vulkan runtime (and legacy Python shader compiler) is now considered deprecated in favor of the new Rust Vulkan runtime (in progress) and the Rust DX12 runtime (d3d12/) available now. Thank you for the contribution! If you believe this PR was closed by mistake (for example, if it still applies to active tools, d3d12/, or general docs), please feel free to reopen it.

Closing this PR because the legacy C++ Vulkan runtime (and legacy Python shader compiler) is now considered deprecated in favor of the new Rust Vulkan runtime (in progress) and the Rust DX12 runtime (`d3d12/`) available now. Thank you for the contribution! If you believe this PR was closed by mistake (for example, if it still applies to active tools, `d3d12/`, or general docs), please feel free to reopen it.
Sign in to join this conversation.
No description provided.