runtime: decode short Huffman codes with a lookup table in the zlib decoder #1736

Merged
NiiRoZz merged 2 commits from upstream-pr/1743 into main 2026-11-24 20:54:12 +00:00
NiiRoZz commented 2026-11-24 18:02:31 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by NiiRoZz on 2026-11-24T18:02:31Z.


Change

src/startup_stubs/inflate.h (the zlib decoder of the DirectStorage stand-in) decoded every Huffman code one bit at a time; its header said "correct but slow, to be replaced by a real decoder if loading time matters". This PR adds a lookup table for codes of up to 10 bits, filled when the code is built. Longer codes, unused table slots and the last byte of input keep the existing bit-at-a-time loop.

The lookup peeks at the next input bytes without consuming them and then takes exactly the code's length through the existing bits(), so bounds checks, the returned statuses (ok, insufficient_output, corrupt_stream, bad_checksum) and the bit position seen by stored blocks and the Adler-32 trailer are unchanged. No public signature changes, and xcrdapi.cpp is not touched.

This is an independent change; I found no open issue or PR about decoder throughput, and no open PR touches inflate.h or its tests (checked against open PRs by touched file on 2026-11-24).

Verification

Commit 30c332cb on base 65e758b0, Windows 11, MSVC 19.44 x64, release (/O2 /Ob2).

ctest --test-dir out\build\pr-inflate --no-tests=error -R "^(startup_inflate|startup_inflate_status|startup_storage_|startup_dstorage_|cpu_native_dstorage|startup_heartbeat_commit|startup_stubs)"
  • This branch: 15 passed, 0 failed, 0 skipped.
  • Unmodified 65e758b0, same filter with ctest --preset release: 15 passed, 0 failed, 0 skipped.
  • python -B tests/docs_links_check.py and python -B tests/bidi_controls_check.py: pass.

Not run: Debug configuration, and any hardware or WARP test (the change has no GPU path).

Decoded MiB/s on 16 MiB synthetic streams, Ryzen 7 9800X3D, before and after measured back to back with the probe's batch mode (runs vary by roughly 20 to 40 %; the zlib column is CPython's zlib 1.3.1 and includes Python call overhead):

stream class before after zlib
stored 1373 1399 3320
fixed Huffman 413 760 930
dynamic, word text 247 327 450
dynamic, near-incompressible 97 237 375

The timing driver is a local script and is not part of this PR; the probe's batch mode it drives is.

Evidence and follow-up

New fixture data is generated by the test from fixed seeds with CPython's zlib; no external inputs.

  • Differential case in tests/startup_inflate_check.py: 900 seeded random streams (random, repetitive, word and geometric-byte data; levels 0-9; all five zlib strategies; some with a sync or full flush), 92 of them with codes longer than 10 bits (asserted). Each runs at exact capacity, one byte short, truncated, and with one to three bits flipped: 3597 cases. Status, size and bytes must equal the same probe built with X2W_INFLATE_FAST_BITS=0 (bit-at-a-time only) and CPython's zlib.
  • Negative control: a probe built with X2W_INFLATE_FAULTY_TABLE (codes exactly 10 bits long decode as the next symbol) must differ from the reference; it differs in 265 cases.

Local-data observation, not reproducible from this PR: in one local startup run per build, with a local timer around the stand-in's inflate calls (not included here), the same 10,488 streams and 762,010,967 output bytes took 3,957 ms of cumulative decode time before and 2,262 ms after (about 184 and 321 MiB/s). Byte and stream counts were identical in both runs; with one run per build there is no measured run-to-run spread. The public fixture verifies decoding equality and the synthetic throughput, not these numbers.

Things a reviewer may want to weigh:

  • inflate.h gains two test-only macros (X2W_INFLATE_FAST_BITS, X2W_INFLATE_FAULTY_TABLE) and CMake gains two extra probe targets for the reference and the control.
  • Huffman grows by 2 KiB per table.

Left for follow-up (not measured in detail): match copy, the byte-wise stored-block copy, Adler-32, and refilling the bit buffer several bytes at a time.

Checklist

  • This pull request covers one reviewable behavior.
  • I included the exact command and result for every check I ran.
  • I considered a negative control or failure case for a new fixture.
  • I updated README/docs when a capability or build requirement changed. (docs/startup-runtime.md, zlib decoder check)
  • I did not include game files, dumps, distribution links or secrets.

AI-assisted (Claude Code): the change, tests and measurements were produced with an AI agent and the commands listed were executed locally.

🤖 Generated with Claude Code

<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:6588209438 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1743). Originally posted by [NiiRoZz](https://github.com/NiiRoZz) on 2026-11-24T18:02:31Z. --- ## Change `src/startup_stubs/inflate.h` (the zlib decoder of the DirectStorage stand-in) decoded every Huffman code one bit at a time; its header said "correct but slow, to be replaced by a real decoder if loading time matters". This PR adds a lookup table for codes of up to 10 bits, filled when the code is built. Longer codes, unused table slots and the last byte of input keep the existing bit-at-a-time loop. The lookup peeks at the next input bytes without consuming them and then takes exactly the code's length through the existing `bits()`, so bounds checks, the returned statuses (`ok`, `insufficient_output`, `corrupt_stream`, `bad_checksum`) and the bit position seen by stored blocks and the Adler-32 trailer are unchanged. No public signature changes, and `xcrdapi.cpp` is not touched. This is an independent change; I found no open issue or PR about decoder throughput, and no open PR touches `inflate.h` or its tests (checked against open PRs by touched file on 2026-11-24). ## Verification Commit 30c332cb on base 65e758b0, Windows 11, MSVC 19.44 x64, release (`/O2 /Ob2`). ``` ctest --test-dir out\build\pr-inflate --no-tests=error -R "^(startup_inflate|startup_inflate_status|startup_storage_|startup_dstorage_|cpu_native_dstorage|startup_heartbeat_commit|startup_stubs)" ``` - This branch: 15 passed, 0 failed, 0 skipped. - Unmodified 65e758b0, same filter with `ctest --preset release`: 15 passed, 0 failed, 0 skipped. - `python -B tests/docs_links_check.py` and `python -B tests/bidi_controls_check.py`: pass. Not run: Debug configuration, and any hardware or WARP test (the change has no GPU path). Decoded MiB/s on 16 MiB synthetic streams, Ryzen 7 9800X3D, before and after measured back to back with the probe's batch mode (runs vary by roughly 20 to 40 %; the zlib column is CPython's zlib 1.3.1 and includes Python call overhead): | stream class | before | after | zlib | |---|---|---|---| | stored | 1373 | 1399 | 3320 | | fixed Huffman | 413 | 760 | 930 | | dynamic, word text | 247 | 327 | 450 | | dynamic, near-incompressible | 97 | 237 | 375 | The timing driver is a local script and is not part of this PR; the probe's batch mode it drives is. ## Evidence and follow-up New fixture data is generated by the test from fixed seeds with CPython's zlib; no external inputs. - Differential case in `tests/startup_inflate_check.py`: 900 seeded random streams (random, repetitive, word and geometric-byte data; levels 0-9; all five zlib strategies; some with a sync or full flush), 92 of them with codes longer than 10 bits (asserted). Each runs at exact capacity, one byte short, truncated, and with one to three bits flipped: 3597 cases. Status, size and bytes must equal the same probe built with `X2W_INFLATE_FAST_BITS=0` (bit-at-a-time only) and CPython's zlib. - Negative control: a probe built with `X2W_INFLATE_FAULTY_TABLE` (codes exactly 10 bits long decode as the next symbol) must differ from the reference; it differs in 265 cases. Local-data observation, not reproducible from this PR: in one local startup run per build, with a local timer around the stand-in's inflate calls (not included here), the same 10,488 streams and 762,010,967 output bytes took 3,957 ms of cumulative decode time before and 2,262 ms after (about 184 and 321 MiB/s). Byte and stream counts were identical in both runs; with one run per build there is no measured run-to-run spread. The public fixture verifies decoding equality and the synthetic throughput, not these numbers. Things a reviewer may want to weigh: - `inflate.h` gains two test-only macros (`X2W_INFLATE_FAST_BITS`, `X2W_INFLATE_FAULTY_TABLE`) and CMake gains two extra probe targets for the reference and the control. - `Huffman` grows by 2 KiB per table. Left for follow-up (not measured in detail): match copy, the byte-wise stored-block copy, Adler-32, and refilling the bit buffer several bytes at a time. ## Checklist - [x] This pull request covers one reviewable behavior. - [x] I included the exact command and result for every check I ran. - [x] I considered a negative control or failure case for a new fixture. - [x] I updated README/docs when a capability or build requirement changed. (`docs/startup-runtime.md`, zlib decoder check) - [x] I did not include game files, dumps, distribution links or secrets. AI-assisted (Claude Code): the change, tests and measurements were produced with an AI agent and the commands listed were executed locally. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
tedin7 commented 2026-11-24 19:01:15 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T18:10:19Z.

Review: COMMENTED


Review of head 30c332cb5b (base 65e758b0, merge-base with origin/main a4d17cf5). Verdict: no P1, no P2.

Read-through of src/startup_stubs/inflate.h

  • Table bounds: entries are written only at i = reversed + k * 2^len for len <= fast_bits, so every index stays below 1 << fast_bits. Over-subscribed sets return false in construct before the table is filled. Entries are symbol << 4 | len (max 287<<4|10), which fits uint16_t and is never 0, so 0 safely means "slow path".
  • Incomplete sets: unassigned slots stay 0 and fall to the bit-at-a-time loop, which is the old behaviour. Length-0 symbols are never inserted. Codes longer than fast_bits are left to the slow path.
  • Refill/underflow: bits() keeps bit_count < 8 between calls (need <= 13), stored() resets it, and the peek requires 2 unread bytes, so at least 16 bits are available for a code of at most 10. The shift is at most 15 (no 32-bit overflow), and bits(s, len) cannot set failed on the fast path. The last byte of input and the final partial bits still use the slow path.
  • The distance check (distance > out_pos), the length/capacity checks, the stored-block checks and the Adler-32 check are untouched by the diff.

Commands run locally on Linux (g++ 14.2, Python 3.14.8, zlib 1.3.1)

  • g++ -std=c++17 -O2 -Wall -Wextra -fsanitize=address,undefined -fno-sanitize-recover=undefined -I src tests/startup_inflate_probe.cpp, built three ways (default, -DX2W_INFLATE_FAST_BITS=0, -DX2W_INFLATE_FAULTY_TABLE). The only warnings are the existing -Wmissing-field-initializers ones at tests/startup_inflate_probe.cpp:99.
  • python3 -B tests/startup_inflate_check.py <fast> <bitwise> <faulty> with the ASan/UBSan probes passes: 3597 random cases are equal to the bit-at-a-time build and to zlib (92 streams have codes over 10 bits), and the faulty control differs in 265 cases.
  • My own differential run, p_fast and p_fb1/4/9/11/15 (table widths 1, 4, 9, 11, 15, all with ASan/UBSan) against the bit-at-a-time probe: 33216 cases (random bytes after a valid zlib header, about 3000 hand-built dynamic headers with random incomplete or over-subscribed litlen/dist length sets, every truncation of 60 valid streams, and 1-4 bit flips). There were 0 mismatches in status, size and bytes, 0 guard-byte writes, and no sanitizer reports. Every OK result also matched CPython zlib.decompress. A second seed on the default and faulty builds gave 32961 cases: 0 mismatches for the default, 51 for the faulty one.
  • python3 -B tests/docs_links_check.py passes (17 files, 365 links). python3 -B tests/bidi_controls_check.py passes (1296 files). git diff --check origin/main...HEAD is clean.

Local mutations, each reverted with git checkout -- . (worktree clean afterwards)

  1. Removed the bit reversal in the table fill (<< (len - 1 - b) changed to << b). startup_inflate_check.py fails ("fixed: exit 1: rejected").
  2. Peeked the second byte at bit_count + 7 instead of + 8. It fails with the same assertion.
  3. Consumed entry & 7 instead of entry & 15 bits. It fails with the same assertion.
    The new random-stream case compares against the same bit-at-a-time build, so the differential check does its job; the fixed-block case catches these three first.

Nits (not blocking)

  • The 900 streams come from zlib's encoder, so they never contain an incomplete code set. The probe only meets those through the bit flips (the doc says none needed the lenient path with this seed). One hand-built stream with a single 1-bit distance code would pin that path.
  • construct now zeroes and fills a 1024-entry table even for the 19-symbol code-length alphabet. This is a small constant cost per dynamic block, and the reversal loop could be a table lookup if it ever shows in profiles.
  • startup_inflate_probe_bitwise and _faulty are added to the default build even where the startup_inflate test is not registered (no INTAKE_PYTHON). Guarding them with the same condition would save two compiles.

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6044791357 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1743#pullrequestreview-6044791357). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T18:10:19Z. **Review:** COMMENTED --- Review of head 30c332cb5bd165fa7e22a8703abb9f45f095fa07 (base 65e758b0, merge-base with origin/main a4d17cf5). Verdict: no P1, no P2. **Read-through of src/startup_stubs/inflate.h** - Table bounds: entries are written only at `i = reversed + k * 2^len` for `len <= fast_bits`, so every index stays below `1 << fast_bits`. Over-subscribed sets return false in `construct` before the table is filled. Entries are `symbol << 4 | len` (max 287<<4|10), which fits uint16_t and is never 0, so 0 safely means "slow path". - Incomplete sets: unassigned slots stay 0 and fall to the bit-at-a-time loop, which is the old behaviour. Length-0 symbols are never inserted. Codes longer than `fast_bits` are left to the slow path. - Refill/underflow: `bits()` keeps `bit_count < 8` between calls (need <= 13), `stored()` resets it, and the peek requires 2 unread bytes, so at least 16 bits are available for a code of at most 10. The shift is at most 15 (no 32-bit overflow), and `bits(s, len)` cannot set `failed` on the fast path. The last byte of input and the final partial bits still use the slow path. - The distance check (`distance > out_pos`), the length/capacity checks, the stored-block checks and the Adler-32 check are untouched by the diff. **Commands run locally on Linux (g++ 14.2, Python 3.14.8, zlib 1.3.1)** - `g++ -std=c++17 -O2 -Wall -Wextra -fsanitize=address,undefined -fno-sanitize-recover=undefined -I src tests/startup_inflate_probe.cpp`, built three ways (default, `-DX2W_INFLATE_FAST_BITS=0`, `-DX2W_INFLATE_FAULTY_TABLE`). The only warnings are the existing `-Wmissing-field-initializers` ones at tests/startup_inflate_probe.cpp:99. - `python3 -B tests/startup_inflate_check.py <fast> <bitwise> <faulty>` with the ASan/UBSan probes passes: 3597 random cases are equal to the bit-at-a-time build and to zlib (92 streams have codes over 10 bits), and the faulty control differs in 265 cases. - My own differential run, `p_fast` and `p_fb1/4/9/11/15` (table widths 1, 4, 9, 11, 15, all with ASan/UBSan) against the bit-at-a-time probe: 33216 cases (random bytes after a valid zlib header, about 3000 hand-built dynamic headers with random incomplete or over-subscribed litlen/dist length sets, every truncation of 60 valid streams, and 1-4 bit flips). There were 0 mismatches in status, size and bytes, 0 guard-byte writes, and no sanitizer reports. Every OK result also matched CPython `zlib.decompress`. A second seed on the default and faulty builds gave 32961 cases: 0 mismatches for the default, 51 for the faulty one. - `python3 -B tests/docs_links_check.py` passes (17 files, 365 links). `python3 -B tests/bidi_controls_check.py` passes (1296 files). `git diff --check origin/main...HEAD` is clean. **Local mutations, each reverted with `git checkout -- .` (worktree clean afterwards)** 1. Removed the bit reversal in the table fill (`<< (len - 1 - b)` changed to `<< b`). `startup_inflate_check.py` fails ("fixed: exit 1: rejected"). 2. Peeked the second byte at `bit_count + 7` instead of `+ 8`. It fails with the same assertion. 3. Consumed `entry & 7` instead of `entry & 15` bits. It fails with the same assertion. The new random-stream case compares against the same bit-at-a-time build, so the differential check does its job; the fixed-block case catches these three first. **Nits (not blocking)** - The 900 streams come from zlib's encoder, so they never contain an incomplete code set. The probe only meets those through the bit flips (the doc says none needed the lenient path with this seed). One hand-built stream with a single 1-bit distance code would pin that path. - `construct` now zeroes and fills a 1024-entry table even for the 19-symbol code-length alphabet. This is a small constant cost per dynamic block, and the reversal loop could be a table lookup if it ever shows in profiles. - `startup_inflate_probe_bitwise` and `_faulty` are added to the default build even where the `startup_inflate` test is not registered (no `INTAKE_PYTHON`). Guarding them with the same condition would save two compiles. AI-assisted; commands listed were executed locally.
tedin7 commented 2026-11-24 20:00:28 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T19:22:25Z.

Review: COMMENTED


Review of head fe375f4315 (base origin/main ddeaa5eb). Verdict: no P1, no P2. I reviewed an earlier head (30c332cb) of this PR; this is the re-check of the new head.

What changed since 30c332cb One commit, fe375f43, "pin the single 1-bit distance code in the inflate check": a hand-built raw stream with exactly one 1-bit distance code (an incomplete set) in the fast build and the bit-at-a-time build (raw_single_distance, raw_single_distance_bw). That covers the case I called out as not reached by the encoder-made streams. inflate.h itself is unchanged since the earlier review, so the reading of the lookup table (index bounds, unassigned slots, length 0 and over-long codes, the 16-bit peek and the refill at the end of input) stands.

Commands run locally on Linux (g++ 14.2, Python 3.14.8, zlib 1.3.1)

  • g++ -std=c++17 -O2 -fsanitize=address,undefined -fno-sanitize-recover=undefined -I src tests/startup_inflate_probe.cpp, default, -DX2W_INFLATE_FAST_BITS=0 and -DX2W_INFLATE_FAULTY_TABLE.
  • python3 -B tests/startup_inflate_check.py <default> <bitwise> <faulty>: passes (10 cases plus 3 controls; 3597 random cases equal to the bit-at-a-time build and to zlib; the faulty table control differs in 265).
  • Differential run of the default ASan/UBSan probe against the bit-at-a-time probe, two seeds, 7612 cases each (periodic and mixed data with long overlapping matches, capacities around the exact size, truncations, bit flips): 0 mismatches.
  • python3 -B tests/docs_links_check.py, python3 -B tests/bidi_controls_check.py: pass. git diff --check origin/main...HEAD: clean.

Local mutations (each reverted, tree clean afterwards)

  1. Table fill without the bit reversal: the check fails.
  2. Peeking the second input byte at bit_count + 7: fails.
  3. Consuming entry & 7 bits: fails.

Not run: a Windows build and CTest. I have no Windows machine in this environment.

Nit (not blocking) The documented exception (a stream that inflate.h decodes past an incomplete code set that zlib rejects) is still a difference from zlib; the new case pins the single 1-bit distance code as a deliberate accepted form and the bit-at-a-time build agrees with it.

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6045836729 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1743#pullrequestreview-6045836729). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T19:22:25Z. **Review:** COMMENTED --- Review of head fe375f431527fdd8fc4d9ce36d40d32af30d1e35 (base `origin/main` ddeaa5eb). Verdict: no P1, no P2. I reviewed an earlier head (30c332cb) of this PR; this is the re-check of the new head. **What changed since 30c332cb** One commit, fe375f43, "pin the single 1-bit distance code in the inflate check": a hand-built raw stream with exactly one 1-bit distance code (an incomplete set) in the fast build and the bit-at-a-time build (`raw_single_distance`, `raw_single_distance_bw`). That covers the case I called out as not reached by the encoder-made streams. `inflate.h` itself is unchanged since the earlier review, so the reading of the lookup table (index bounds, unassigned slots, length 0 and over-long codes, the 16-bit peek and the refill at the end of input) stands. **Commands run locally on Linux** (g++ 14.2, Python 3.14.8, zlib 1.3.1) - `g++ -std=c++17 -O2 -fsanitize=address,undefined -fno-sanitize-recover=undefined -I src tests/startup_inflate_probe.cpp`, default, `-DX2W_INFLATE_FAST_BITS=0` and `-DX2W_INFLATE_FAULTY_TABLE`. - `python3 -B tests/startup_inflate_check.py <default> <bitwise> <faulty>`: passes (10 cases plus 3 controls; 3597 random cases equal to the bit-at-a-time build and to zlib; the faulty table control differs in 265). - Differential run of the default ASan/UBSan probe against the bit-at-a-time probe, two seeds, 7612 cases each (periodic and mixed data with long overlapping matches, capacities around the exact size, truncations, bit flips): 0 mismatches. - `python3 -B tests/docs_links_check.py`, `python3 -B tests/bidi_controls_check.py`: pass. `git diff --check origin/main...HEAD`: clean. **Local mutations (each reverted, tree clean afterwards)** 1. Table fill without the bit reversal: the check fails. 2. Peeking the second input byte at `bit_count + 7`: fails. 3. Consuming `entry & 7` bits: fails. **Not run:** a Windows build and CTest. I have no Windows machine in this environment. **Nit (not blocking)** The documented exception (a stream that `inflate.h` decodes past an incomplete code set that zlib rejects) is still a difference from zlib; the new case pins the single 1-bit distance code as a deliberate accepted form and the bit-at-a-time build agrees with it. AI-assisted; commands listed were executed locally.
NiiRoZz commented 2026-11-24 20:01:15 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by NiiRoZz on 2026-11-24T19:05:58Z.


fe375f43 adds a hand-built dynamic block whose only distance code is 1 bit long; it must decode with both the table and the bit-at-a-time probe, and a construct() that rejects incomplete distance sets fails it. The same commit builds the bitwise and faulty probes only inside if(EXISTS INTAKE_PYTHON), and the 900-stream counts are unchanged.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7141595645 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1743#issuecomment-7141595645). Originally posted by [NiiRoZz](https://github.com/NiiRoZz) on 2026-11-24T19:05:58Z. --- fe375f43 adds a hand-built dynamic block whose only distance code is 1 bit long; it must decode with both the table and the bit-at-a-time probe, and a construct() that rejects incomplete distance sets fails it. The same commit builds the bitwise and faulty probes only inside if(EXISTS INTAKE_PYTHON), and the 900-stream counts are unchanged.
upstream-sync closed this pull request 2026-11-24 21:00:47 +00:00
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
R0Y00/Xbox2Windows!1736
No description provided.