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

Open
opened 2026-11-26 21:19:29 +01:00 by 4ld0 · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/ubiquitarianism/leonida/pull/1935
Author: @IlyassRS3
Created: 11/25/2026
Status: 🔄 Open

Base: main ← Head: fix/rt-bcpack-stream-perf-and-guards


📝 Commits (1)

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

📊 Changes

3 files changed (+194 additions, -28 deletions)

View changed files

📝 runtime/CMakeLists.txt (+17 -0)
📝 runtime/src/bcpack_stream.h (+48 -28)
➕ runtime/test/bcpack_stream_test.cpp (+129 -0)

📄 Description

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)

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/ubiquitarianism/leonida/pull/1935 **Author:** [@IlyassRS3](https://github.com/IlyassRS3) **Created:** 11/25/2026 **Status:** 🔄 Open **Base:** `main` ← **Head:** `fix/rt-bcpack-stream-perf-and-guards` --- ### 📝 Commits (1) - [`1dc85d9`](https://github.com/ubiquitarianism/leonida/commit/1dc85d99fd6d3857cfe8f2b5dda6307f99039e8e) perf(bcpack): precompute rANS advance tables and guard stream widths, codecs, and sizes (RT-BCPACK-STREAM-PERF-AND-GUARDS) ### 📊 Changes **3 files changed** (+194 additions, -28 deletions) <details> <summary>View changed files</summary> 📝 `runtime/CMakeLists.txt` (+17 -0) 📝 `runtime/src/bcpack_stream.h` (+48 -28) ➕ `runtime/test/bcpack_stream_test.cpp` (+129 -0) </details> ### 📄 Description 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) --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
Sign in to join this conversation.
No labels
bug
pull-request
No milestone
No project
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.

Dependencies

No dependencies set

Reference
starred/leonida#1941
No description provided.