runtime: speed up stored blocks, match copies and symbol decoding in the zlib decoder #1812
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/1819"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from R0Y00/Xbox2Windows. Originally posted by NiiRoZz on 2026-11-24T19:13:45Z.
Change
Follow-up to #1743, which must land first: this branch is built on its head (
fe375f43), so until it merges the diff here also shows its two commits. The new work is fe375f43..ea3b6378.It continues the same thing #1743 started, decode throughput of
src/startup_stubs/inflate.h(the zlib decoder of the DirectStorage stand-in), with no change to results. Three steps, kept as separate commits so they can be reviewed one at a time:c7fa63c4: a stored block is copied with one bounds-checkedmemcpyinstead of byte by byte.c0e5059c: a match is copied 8 bytes at a time when the distance allows it, and withmemsetfor distance 1; the copy never writes past the end of the match.587688e9: away from the ends of the buffers, symbols are decoded from a 64-bit bit buffer in a loop that runs only while at least 8 input bytes and 258 output bytes remain, so one refill covers a whole length/distance pair (at most 10+5+10+13 = 38 bits) and no per-symbol bounds check is needed. End of block, codes longer than the table width, invalid symbols and distances before the first output byte are left to the existing careful loop, and unused whole bytes are given back on exit so stored blocks and the Adler-32 trailer see the same position as before.Statuses (
ok,insufficient_output,corrupt_stream,bad_checksum), public signatures andxcrdapi.cppare unchanged. The remaining commits are tests, controls, compile-time checks and the benchmark mode.No other open PR touches
inflate.hor its tests (checked by touched file on 2026-11-24).Verification
Head
ea3b6378, Windows 11, MSVC 19.44 x64. A trial merge with currentmainis clean.startup_inflateonly: passed.python -B tests/docs_links_check.pyandpython -B tests/bidi_controls_check.py: pass.Not run: a sanitizer build of this head, and any hardware or WARP test (no GPU path).
Throughput, reproducible with the mode this PR adds (not a ctest; interleaved builds, warm-up dropped, best of N, output checksummed):
Decoded MiB/s on 16 MiB synthetic streams, Ryzen 7 9800X3D:
The machine was under other load during this run and numbers move by tens of percent between runs; in one earlier run of the same build the stored class came out below zlib. Read the zlib column as "about level", not as a margin.
Evidence and follow-up
All inputs are generated by the test from fixed seeds or written by hand as raw deflate; no external data.
ea3b6378after review): 5 streams of 96 to 160 KiB, three of them hand-built fixed blocks with matches at distance 32768 (zlib's encoder never emits that distance) and lengths up to 258, at exact capacity, one byte short, at inner match ends and truncated; 52 cases equal to the bit-at-a-time build and to zlib.memcpyhas an oracle other than zlib.X2W_INFLATE_FAULTY_TABLE(from #1743),X2W_INFLATE_FAULTY_MARGIN(one output byte short), a 7-byte input margin, and a fast loop without its distance check.static_asserts for the table width range and for the byte order the 8-byte loads assume.One existing difference from zlib is kept as it was before this PR and is now checked more narrowly: a truncated stored block that also does not fit the destination is reported as
corrupt_streamhere and as insufficient output by zlib (809 cases with this seed; the check requires a stored block to be the one involved).Local observation, not reproducible from this PR: a separate review harness compared the decoder before #1743, #1743 and this head on about 240,000 generated and hand-built raw-deflate cases (codes up to 15 bits, incomplete and over-subscribed code sets, every distance 1 to 9 at lengths 3 to 258, the maximum distance, stored blocks of 0 and 65535 bytes at any bit position, truncations and bit flips, guard pages on both sides of both buffers) and found no difference in status, size or destination bytes.
Second local observation, also not reproducible from this PR: in one local startup run per build on a quiet machine, with a local timer around the stand-in's inflate calls (not included here), the same streams and the same 762,010,967 output bytes took 2,490 ms of cumulative decode time with #1743 alone and 1,504 ms with this head (about 292 and 483 MiB/s). Byte totals were identical; with one run per build there is no measured run-to-run spread. Wall time to the end of that load did not change at the 10 s resolution of the log, so this is a CPU-time saving there, not a demonstrated loading-time saving.
Things a reviewer may want to weigh: three speed steps in one PR (one subject, separate commits; I can split it if preferred); the test file grows by about 325 lines; the test-only macros in
inflate.hmust have the same value in every translation unit linked into one binary (noted in a comment).Left for follow-up: Adler-32 is now the largest remaining cost (most of the stored path); a second-level table for long codes showed about 1 % in the profile and was not done.
Checklist
docs/startup-runtime.md, zlib decoder check and the benchmark command)AI-assisted (Claude Code): the change, tests and measurements were produced with AI agents, reviewed by a separate agent, and the commands listed were executed locally.
🤖 Generated with Claude Code
Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T19:22:24Z.
Review: COMMENTED
Review of head
a95e7f191e(a merge of #1743 atfe375f43into the second-pass branch; baseorigin/mainddeaa5eb). Verdict: no P1, no P2. Three nits below.What I read The part of the diff that is new on top of #1743:
copy_match, the fast loop incodes(), the stored-blockmemcpy, the probe and the new test cases.Fast loop (
codes, src/startup_stubs/inflate.h)buffer |= next << count; in_pos += (63 - count) >> 3; count |= 56keepscountequal to the bits actually loaded for everycountfrom 0 to 63, socountis 56 to 63 after a refill. The loaded bytes are all inside the input: the loop runs only while at leastfast_in_margin(8) bytes remain, and the 8-byte read is amemcpy, so there is no unaligned or aliasing access. The little-endian assumption is guarded by the new#error.static_assertlimitsfast_bitsto 15 (48 bits).distance > out_pos):usedis a local, and on exitin_pos - (count >> 3)hands back the whole bytes andbit_count = count & 7keeps the invariantbit_count < 8thatdecode(),stored()and the Adler-32 trailer rely on. The unconsumed partial byte is the lowcount & 7bits, which is what is stored.out_size. The careful loop still does the capacity check and setsoverflow.copy_match: the 8-byte chunk branch needsdistance >= 8andlength >= 8. Each chunk's source ends at or before its destination, somemcpynever sees overlapping ranges, and the final chunk ends at the match end and only rewrites bytes whose source is already final. Fordistance < 8the byte loop keeps the forward-overlap semantics, anddistance == 1ismemset. It never writes pastout + length.memcpyis skipped whenlength == 0, so a nulloutis not passed. The capacity check comes first.Commands run locally on Linux (g++ 14.2, Python 3.14.8, zlib 1.3.1). The probe now calls
VirtualAlloc, so I built it against a small local stand-in for the three<windows.h>calls (mmap and mprotect guard pages, kept outside the repository).g++ -std=c++17 -O2 -fsanitize=address,undefined -fno-sanitize-recover=undefined -I srcfor the default,X2W_INFLATE_FAST_BITS=0andX2W_INFLATE_FAULTY_TABLEprobes; the three fast-loop control probes without sanitizers, so that the guard-page fault is a plain SIGSEGV (the check expects 0xC0000005 on Windows; I ran a scratch copy oftests/startup_inflate_check.pywith that one constant set to -11).startup_inflate_check.py: passes. 900 random streams / 3597 cases equal to the bit-at-a-time build and to zlib; 57 boundary streams / 63994 cases equal to the bit-at-a-time build and to zlib in 63185 (809 are truncated stored blocks neither can complete); the four controls are caught (table, input margin, output margin, distance).python3 -B tests/docs_links_check.pyandpython3 -B tests/bidi_controls_check.pypass;git diff --check origin/main...HEADis clean.Local mutations (each reverted, tree clean afterwards)
distance >= 8changed to>= 4: the check fails.in_pos - (count >> 3) + 1): fails.memcpyone byte short: fails.(62 - count) >> 3bytes: fails.Not run: a Windows build and the CTest run (and the
--benchtimings in the docs). I have no Windows machine in this environment, so the Windows probe with realVirtualAllocguard pages and the claimed speed-up are not confirmed by me.Nits (not blocking)
inflate.hcan decode where zlib reports "invalid distances set" (one such case in my first seed: 1 of 7612). It is the documented exception, it is identical in the bit-at-a-time build, and this PR does not change it.copy_matchand the fast loop are guarded byfast_bits > 0, so the reference build keeps the old byte loops; good for the differential, but the bit-at-a-time probe therefore does not exercisecopy_match's byte loop under the new code. The default build does fordistance < 8.AI-assisted; commands listed were executed locally.
Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T20:09:05Z.
Review: COMMENTED
Review of head
ea3b637824(baseorigin/mainddeaa5eb). Verdict: no P1, no P2, 0 defects found. Retest after my earlier review ofa95e7f19.What changed since
a95e7f19One commit,ea3b6378: no change tosrc/startup_stubs/inflate.horCMakeLists.txt. It adds a window case totests/startup_inflate_check.py(LENGTH_BASE/DISTANCE_BASEtables,fixed_tokens,window_cases,expect_window, called with its own seed) and one paragraph indocs/startup-runtime.md. So my earlier reading ofcopy_match, the fast loop, the refill and exit arithmetic and the stored-blockmemcpystill holds, because the decoder bytes are identical.The new test, read against RFC 1951
code // 2 - 1, last base 24577) match section 3.2.5.fixed_tokensuses the fixed Huffman code of 3.2.6 (8/9/7/8 bits) and 5-bit distance codes. Length 258 is forced to code 28, as the RFC requires.assert reference(stream, "zlib") == datachecks each stream against CPython zlib before anything runs, so the test data are valid streams.Commands run locally on Linux (g++ 14.2, Python 3, zlib 1.3.1). The probe calls
VirtualAlloc,VirtualProtectandVirtualFree, so I built it against a small local stand-in for those three<windows.h>calls (mmap and mprotect guard pages, kept outside the repository).g++ -std=c++17 -O2 -fsanitize=address,undefined -fno-sanitize-recover=undefinedfor the default probe, theX2W_INFLATE_FAST_BITS=0probe and theX2W_INFLATE_FAULTY_TABLEprobe; the margin, input-margin and distance controls without sanitizers so the guard page gives a plain SIGSEGV (a scratch copy oftests/startup_inflate_check.pywithACCESS_VIOLATION = -11; the repo expects 0xC0000005 on Windows).startup_inflate_check.py: passes. 900 random streams / 3597 cases; 57 boundary streams / 63994 cases (equal to zlib in 63185, 809 truncated stored blocks neither can complete); window: 5 streams / 52 cases equal to bit-at-a-time decoding and to zlib in all; the four controls are caught.git diff --check origin/main...HEADclean;python3 -B tests/docs_links_check.pyandpython3 -B tests/bidi_controls_check.pypass.if (distance > out_pos) break;changed to also break fordistance > 32767. The window case does not fail, which is expected: the fast loop then hands the match to the careful loop, which produces identical output. It is an equivalent mutant, not a gap in the test. I did not find a mutation specific to distance 32768 that the existing cases miss (earlier mutations from my first review are still caught by the earlier cases).Not run: a Windows build, the CTest run and the
--benchtimings in the docs. I have no Windows machine in this environment, so the Windows probe with realVirtualAllocguard pages and the claimed speed-up are not confirmed by me. Verification here is Linux plus source analysis, pending a Windows 2025 run.Nits (not blocking)
docs/startup-runtime.md: the new window paragraph has two lines far over the width used in the rest of the file (the line with "zlib's encoder keeps 262 bytes of lookahead out of its window and never reaches distance 32768, so three are fixed blocks written by" and the one ending "In every case the probe ends both the stream and the destination"). A re-wrap would match the surrounding text. The docs link check passes either way.AI-assisted; commands listed were executed locally.
Imported from R0Y00/Xbox2Windows. Originally posted by NiiRoZz on 2026-11-24T20:05:06Z.
ea3b6378adds a window case: 5 streams of 96 to 160 KiB, three of them hand-built fixed blocks with matches at distance 32768 (zlib's encoder never emits it) and lengths up to 258, at exact capacity, one byte short, at inner match ends and truncated, 52 cases equal to the bit-at-a-time build and to zlib. A build that rejects distances above 32767 fails it, and the existing random, boundary and control counts are unchanged.