perf(bcpack): precompute rANS advance tables and guard stream widths, codecs, and sizes (RT-BCPACK-STREAM-PERF-AND-GUARDS) #1935

Closed
IlyassRS3 wants to merge 1 commit from upstream-pr/1935 into main
IlyassRS3 commented 2026-11-25 16:11:19 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by IlyassRS3 on 2026-11-25T16:11:19Z.


Item ID: RT-BCPACK-STREAM-PERF-AND-GUARDS (claim: #1608, comment 7167621176)

Problem

In the shared BCPack rANS block stream (runtime/src/bcpack_stream.h, used by runtime/src/bcpack.cpp for DirectStorage texture decompression and tools/bcpack_history_train.cpp):

  1. Out-of-bounds negative array indexing on narrow/malformed widths (Lane::step line 109):
    model = &model_for(width - (byte >> 6), byte & 15) passed w = width - (byte >> 6) directly into models[w - 1] without checking 1 <= w <= 8. When width <= (byte >> 6) or width > 8, models[w - 1] reads out of bounds (verified under UBSan on unpatched main: unsigned offset overflow in std::array::operator[]).
  2. Missing codec and block-alignment guards in visit_blocks():
    Direct callers of visit_blocks() with an unsupported codec (0, 2, >= 8) indexed widths[codec] out of bounds or read zero widths; unaligned size for 16-byte block codecs (3, 5, 6, 7) silently dropped the trailing half-block while returning true.
  3. Per-symbol overhead in Model::advance() and Lane::step():
    Every decoded rANS symbol recomputed bit_width(sym), chased frequency[p] and base[p], calculated base[p] + f * (sym - (1 << (p-1))), and branched on !c (despite there being at most 256 symbols per model). Model::symbol() also checked p < width on every bucket step, and Lane::step() checked Phase::header and Phase::length ahead of the >99%-taken Phase::symbols branch.

Fix

  • runtime/src/bcpack_stream.h:
    • Precompute a 256-entry Model::Step { uint16_t freq, cdf; } table in Model::init() (1 KiB per model, 128 KiB total across the 128 static models) so Model::advance() becomes a single table lookup, multiply, and subtract.
    • Add sentinel base[w + 1] = 65536u in Model::init() so Model::symbol() fast-path loop drops the p < unsigned(width) bound check.
    • Order Phase::symbols first with [[likely]] in Lane::step().
    • Validate model_width = width - (byte >> 6) in [1, 8], model != nullptr, and 0 <= symbol < (1 << model->width) in Lane::step().
    • Validate codec in {1, 3, 4, 5, 6, 7} and block-aligned size (% 8 for BC1/BC4, % 16 for BC3/BC5/BC6H/BC7) in visit_blocks().
  • runtime/test/bcpack_stream_test.cpp & runtime/CMakeLists.txt:
    • Add portable CTest bcpack_stream verifying exhaustive bit-exactness of symbol(fast) vs symbol(slow) and table advance() vs scalar advance() across all 128 models (128 * 65536 slots + all symbols), negative/out-of-range header width rejection, invalid codec & unaligned size rejection, and 1,200 iterations of deterministic adversarial fuzzing across all 6 codecs.

Benchmark (macOS clang++ -O2, 8,000 iterations across all 6 synthetic Python-encoded codecs = 39.06 MiB decoded per run, bit-exact with tools/bcpack.py)

Build Run 1 Run 2 Throughput Speedup
Base (main) 575.16 ms 552.66 ms 67.9–70.7 MiB/s 1.00x
Head (this PR) 481.17 ms 455.98 ms 81.2–85.7 MiB/s 1.20x–1.21x

Verification

  • AI-assisted: yes
  • GPUs tested: none (macOS host, CPU-only unit, fuzz, round-trip, and benchmark tests)
  • Game files used: none
  • Commands run:
    • clang++ -std=c++20 -Wall -Wextra -Werror -O1 -g -fsanitize=address,undefined runtime/test/bcpack_stream_test.cpp runtime/src/bcpack.cpp -> PASS
    • clang++ -std=c++20 -Wall -Wextra -Werror -O1 -g -fsanitize=thread runtime/test/bcpack_stream_test.cpp runtime/src/bcpack.cpp -> PASS
    • clang++ -std=c++20 -Wall -Wextra -Werror -O2 runtime/test/bcpack_stream_test.cpp runtime/src/bcpack.cpp (x3) -> PASS
    • Downstream syntax check: clang++ -std=c++20 -fsyntax-only tools/bcpack_history_train.cpp -> PASS
    • Bit-exact round-trip + A/B -O2 benchmark against synthetic vectors generated by runtime/test/dstorage_vectors.py (all 6 codecs) -> PASS (+20–21% faster)
    • Negative mutation check running bcpack_stream_test.cpp against unpatched main:runtime/src/bcpack_stream.h under ASan+UBSan -> FAILED with UBSan OOB pointer overflow at std::array::operator[] + line 68 failure as expected
    • python3 -I scripts/check_no_game_data.py runtime/src/bcpack_stream.h runtime/test/bcpack_stream_test.cpp runtime/CMakeLists.txt -> PASS
    • python3 -I tests/test_text_write_line_endings.py -> PASS (3/3)
<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5494863776 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/1935). Originally posted by [IlyassRS3](https://github.com/IlyassRS3) on 2026-11-25T16:11:19Z. --- Item ID: `RT-BCPACK-STREAM-PERF-AND-GUARDS` (claim: #1608, comment 7167621176) ## Problem In the shared BCPack rANS block stream (`runtime/src/bcpack_stream.h`, used by `runtime/src/bcpack.cpp` for DirectStorage texture decompression and `tools/bcpack_history_train.cpp`): 1. **Out-of-bounds negative array indexing on narrow/malformed widths (`Lane::step` line 109)**: `model = &model_for(width - (byte >> 6), byte & 15)` passed `w = width - (byte >> 6)` directly into `models[w - 1]` without checking `1 <= w <= 8`. When `width <= (byte >> 6)` or `width > 8`, `models[w - 1]` reads out of bounds (verified under UBSan on unpatched `main`: unsigned offset overflow in `std::array::operator[]`). 2. **Missing codec and block-alignment guards in `visit_blocks()`**: Direct callers of `visit_blocks()` with an unsupported codec (`0`, `2`, `>= 8`) indexed `widths[codec]` out of bounds or read zero widths; unaligned `size` for 16-byte block codecs (`3, 5, 6, 7`) silently dropped the trailing half-block while returning `true`. 3. **Per-symbol overhead in `Model::advance()` and `Lane::step()`**: Every decoded rANS symbol recomputed `bit_width(sym)`, chased `frequency[p]` and `base[p]`, calculated `base[p] + f * (sym - (1 << (p-1)))`, and branched on `!c` (despite there being at most 256 symbols per model). `Model::symbol()` also checked `p < width` on every bucket step, and `Lane::step()` checked `Phase::header` and `Phase::length` ahead of the >99%-taken `Phase::symbols` branch. ## Fix - **`runtime/src/bcpack_stream.h`**: - Precompute a 256-entry `Model::Step { uint16_t freq, cdf; }` table in `Model::init()` (1 KiB per model, 128 KiB total across the 128 static models) so `Model::advance()` becomes a single table lookup, multiply, and subtract. - Add sentinel `base[w + 1] = 65536u` in `Model::init()` so `Model::symbol()` fast-path loop drops the `p < unsigned(width)` bound check. - Order `Phase::symbols` first with `[[likely]]` in `Lane::step()`. - Validate `model_width = width - (byte >> 6)` in `[1, 8]`, `model != nullptr`, and `0 <= symbol < (1 << model->width)` in `Lane::step()`. - Validate `codec` in `{1, 3, 4, 5, 6, 7}` and block-aligned `size` (`% 8` for BC1/BC4, `% 16` for BC3/BC5/BC6H/BC7) in `visit_blocks()`. - **`runtime/test/bcpack_stream_test.cpp`** & **`runtime/CMakeLists.txt`**: - Add portable CTest `bcpack_stream` verifying exhaustive bit-exactness of `symbol(fast)` vs `symbol(slow)` and table `advance()` vs scalar `advance()` across all 128 models (`128 * 65536` slots + all symbols), negative/out-of-range header width rejection, invalid codec & unaligned size rejection, and 1,200 iterations of deterministic adversarial fuzzing across all 6 codecs. ## Benchmark (macOS clang++ `-O2`, 8,000 iterations across all 6 synthetic Python-encoded codecs = 39.06 MiB decoded per run, bit-exact with `tools/bcpack.py`) | Build | Run 1 | Run 2 | Throughput | Speedup | |---|---:|---:|---:|---:| | Base (`main`) | 575.16 ms | 552.66 ms | 67.9–70.7 MiB/s | 1.00x | | Head (this PR) | 481.17 ms | 455.98 ms | 81.2–85.7 MiB/s | **1.20x–1.21x** | ## Verification - **AI-assisted**: yes - **GPUs tested**: none (macOS host, CPU-only unit, fuzz, round-trip, and benchmark tests) - **Game files used**: none - Commands run: - `clang++ -std=c++20 -Wall -Wextra -Werror -O1 -g -fsanitize=address,undefined runtime/test/bcpack_stream_test.cpp runtime/src/bcpack.cpp` -> PASS - `clang++ -std=c++20 -Wall -Wextra -Werror -O1 -g -fsanitize=thread runtime/test/bcpack_stream_test.cpp runtime/src/bcpack.cpp` -> PASS - `clang++ -std=c++20 -Wall -Wextra -Werror -O2 runtime/test/bcpack_stream_test.cpp runtime/src/bcpack.cpp` (x3) -> PASS - Downstream syntax check: `clang++ -std=c++20 -fsyntax-only tools/bcpack_history_train.cpp` -> PASS - Bit-exact round-trip + A/B `-O2` benchmark against synthetic vectors generated by `runtime/test/dstorage_vectors.py` (all 6 codecs) -> PASS (**+20–21% faster**) - Negative mutation check running `bcpack_stream_test.cpp` against unpatched `main:runtime/src/bcpack_stream.h` under ASan+UBSan -> FAILED with UBSan OOB pointer overflow at `std::array::operator[]` + line 68 failure as expected - `python3 -I scripts/check_no_game_data.py runtime/src/bcpack_stream.h runtime/test/bcpack_stream_test.cpp runtime/CMakeLists.txt` -> PASS - `python3 -I tests/test_text_write_line_endings.py` -> PASS (3/3)
copilot-pull-request-reviewer[bot] commented 2026-11-25 16:26:35 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by copilot-pull-request-reviewer[bot] on 2026-11-25T16:26:35Z.

Review: COMMENTED


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.

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6061138222 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/1935#pullrequestreview-6061138222). Originally posted by [copilot-pull-request-reviewer[bot]](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-25T16:26:35Z. **Review:** COMMENTED --- 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 12:09:17 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by zmasi on 2026-11-28T12:09:17Z.


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 d48a957bb + 1dc85d99fd (claim #2570#issuecomment-7238954420):

  • Line-by-line diff audit: Clean (runtime/CMakeLists.txt, runtime/src/bcpack_stream.h, runtime/test/bcpack_stream_test.cpp); precomputes per-symbol {freq, cdf} rANS step entries and base[w + 1] = 65536u sentinel across all 128 models, prioritizes the Phase::symbols hot branch, and guards model_width ([1, 8]), codec IDs ({1, 3, 4, 5, 6, 7}), and 8/16-byte block-size alignment before indexing model or width tables. check_no_game_data.py clean.
  • Red (d48a957bb + PR test): bcpack_stream_test.exe fails (rc=1, failed at line 68: !lane.step(lane_width, in, budget, true) on narrow/invalid width - (byte >> 6) headers).
  • Green (d48a957bb + 1dc85d99fd merge): Auto-merges cleanly (rc=0), compiles with 0 warnings in bcpack_stream.h / bcpack_stream_test.cpp, and passes both bcpack_stream_test.exe (bcpack_stream: exhaustive model/advance parity, width/codec/size guards, and fuzzing OK, rc=0) and full dstorage_test.exe (rc=0).

AI-assisted.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7239030430 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/1935#issuecomment-7239030430). Originally posted by [zmasi](https://github.com/zmasi) on 2026-11-28T12:09:17Z. --- 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` `d48a957bb` + `1dc85d99fd` (claim `#2570#issuecomment-7238954420`): - **Line-by-line diff audit**: Clean (`runtime/CMakeLists.txt`, `runtime/src/bcpack_stream.h`, `runtime/test/bcpack_stream_test.cpp`); precomputes per-symbol `{freq, cdf}` rANS step entries and `base[w + 1] = 65536u` sentinel across all 128 models, prioritizes the `Phase::symbols` hot branch, and guards `model_width` (`[1, 8]`), codec IDs (`{1, 3, 4, 5, 6, 7}`), and 8/16-byte block-size alignment before indexing model or width tables. `check_no_game_data.py` clean. - **Red (`d48a957bb` + PR test)**: `bcpack_stream_test.exe` fails (`rc=1`, `failed at line 68: !lane.step(lane_width, in, budget, true)` on narrow/invalid `width - (byte >> 6)` headers). - **Green (`d48a957bb` + `1dc85d99fd` merge)**: Auto-merges cleanly (`rc=0`), compiles with `0` warnings in `bcpack_stream.h` / `bcpack_stream_test.cpp`, and passes both `bcpack_stream_test.exe` (`bcpack_stream: exhaustive model/advance parity, width/codec/size guards, and fuzzing OK`, `rc=0`) and full `dstorage_test.exe` (`rc=0`). AI-assisted.
MoonEyes commented 2026-11-28 17:54:50 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-11-28T17:54:50Z.


Blocker: tests/test_runtime_paths.py fails with this PR merged onto main: tools/bcpack_calibration/** is missing from the path filter of runtime.yml. Could you add it?

Checked locally on main c1ecf04ed: the same test file(s) pass on main without this PR.

AI-assisted (Claude Code, Claude Opus 5.5), posted for MoonEyes.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7243384566 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/1935#issuecomment-7243384566). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-11-28T17:54:50Z. --- Blocker: `tests/test_runtime_paths.py` fails with this PR merged onto `main`: `tools/bcpack_calibration/**` is missing from the path filter of `runtime.yml`. Could you add it? Checked locally on `main` c1ecf04ed: the same test file(s) pass on `main` without this PR. _AI-assisted (Claude Code, Claude Opus 5.5), posted for MoonEyes._
fiestorra commented 2026-11-30 11:54:16 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by fiestorra on 2026-11-30T11:54:16Z.


Independent verification on this machine (Windows 11, MSVC 19.44.35226), with a negative control that bites on a named line.

1. It applies and builds. merge-tree clean onto main d367675c7; one source file plus its test.

2. With the branch: ctest -R '^bcpack_stream' -> 100% tests passed, 0 failed out of 1.

3. The control - revert only the source, keep the test:

git checkout origin/main -- <the changed source>
cmake --build … --target bcpack_stream_test
ctest -R '^bcpack_stream' --output-on-failure
0% tests passed, 1 tests failed out of 1
failed at line 68: !lane.step(lane_width, in, budget, true)

The failing assertion is !lane.step(lane_width, in, budget, true) - a step that must refuse when the budget is exhausted, and main's code lets it through. That is the change the test owns.

What I did not test: the decoder's output for the cases that do fit the budget, and whether the budget accounting matches the format's real limits.

Why I am commenting: I verify open pull requests that replay onto current main, build the binaries their tests name, run them, then revert only the source change. 34 controls so far: 27 bite.

Written with an AI assistant.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7277680889 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/1935#issuecomment-7277680889). Originally posted by [fiestorra](https://github.com/fiestorra) on 2026-11-30T11:54:16Z. --- Independent verification on this machine (Windows 11, MSVC 19.44.35226), with a negative control that bites on a named line. **1. It applies and builds.** `merge-tree` clean onto `main` `d367675c7`; one source file plus its test. **2. With the branch:** `ctest -R '^bcpack_stream'` -> **100% tests passed, 0 failed out of 1**. **3. The control - revert only the source, keep the test:** ``` git checkout origin/main -- <the changed source> cmake --build … --target bcpack_stream_test ctest -R '^bcpack_stream' --output-on-failure 0% tests passed, 1 tests failed out of 1 failed at line 68: !lane.step(lane_width, in, budget, true) ``` **The failing assertion is `!lane.step(lane_width, in, budget, true)`** - a step that must **refuse** when the budget is exhausted, and `main`'s code lets it through. **That is the change the test owns.** **What I did not test:** the decoder's output for the cases that do fit the budget, and whether the budget accounting matches the format's real limits. **Why I am commenting:** I verify open pull requests that replay onto current `main`, build the binaries their tests name, run them, then revert **only** the source change. **34 controls so far: 27 bite.** Written with an AI assistant.
aslan2142 commented 2026-12-01 16:39:13 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by aslan2142 on 2026-12-01T16:39:13Z.


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.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7317969378 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/1935#issuecomment-7317969378). Originally posted by [aslan2142](https://github.com/aslan2142) on 2026-12-01T16:39:13Z. --- 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.

Pull request closed

Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
ProjectLeonida/mandy!1935
No description provided.