Skip to content

runtime: bulk copy stored blocks and long zlib matches - #8942

Closed
svds12343 wants to merge 2 commits into
ProjectLeonida:mainfrom
svds12343:perf/zlib-stored-copy
Closed

svds12343 wants to merge 2 commits into
ProjectLeonida:mainfrom
svds12343:perf/zlib-stored-copy

Conversation

@svds12343

@svds12343 svds12343 commented Nov 23, 2026 •

Copy link
Copy Markdown

The runtime inflater appends every stored byte and every byte of a back-reference separately. This change reduces that copying overhead while preserving deflate's forward-overlap semantics, input validation, output limits and checksum validation.

Claims: PERF-ZLIB-STORED-COPY and PERF-ZLIB-MATCH-COPY. Both are included in this PR.

Depends on: #7180 (two error-return hunks conflict; no implementation dependency).

Implementation

  • Stored blocks: BitReader::append_bytes checks the entire byte-aligned payload, inserts its range into the output vector, and advances the input cursor once. LEN/NLEN and the output limit are checked first. Truncated stored payloads fail before appending their incomplete bytes; callers still discard output after failure.
  • Matches of 32–258 bytes: resize once, then copy the available history. If the match overlaps, repeatedly copy from the initialized output prefix, doubling the available prefix until complete. Each individual memcpy is disjoint. Pointers are obtained after resize, which may reallocate. Matches below 32 bytes retain the existing loop to avoid resize/copy overhead.

This follows RFC 1951 sections 3.2.3–3.2.4: an overlapping back-reference repeats bytes just produced, and stored blocks carry raw byte-aligned data. Huffman decoding, Adler-32 and the public API are unchanged.

Performance

Synthetic full zlib_inflate timings, including the checksum, in microseconds. Native Windows 11 Pro N 26200, i7-12700K, MSVC 19.44.35230 /O2 /EHsc /std:c++20. Each result is the median of five separate runs per variant with alternating execution order, pinned to logical CPU 0. Output capacity is reused after warm-up, output is verified, and file reads/compression are outside the timing. No game startup or corpus speedup was measured.

The match-copy measurement compares the stored-only commit 473d7246 with head d3c46a5c817aa1706d454188321120e15d7dddb8. Long-match inputs are repetitions of one byte, three bytes, or bytes 0–250, compressed with Python zlib level 9. Each case inflates 64 MiB per run.

Input Stored-only This head Speedup
4 KiB, one-byte period 14.955 12.561 1.191x
4 KiB, three-byte period 15.025 12.939 1.161x
4 KiB, 251-byte period 16.116 14.430 1.117x
64 KiB, one-byte period 222.989 193.757 1.151x
64 KiB, three-byte period 223.208 188.376 1.185x
64 KiB, 251-byte period 225.720 191.527 1.179x

Controls include random stored bytes, a seeded skewed alphabet, and explicit fixed-Huffman matches of lengths 3, 31, 32 and 33 at distances 1 and 257. The initial 18-case sweep showed control variation from about 5% slower to 1% faster; a longer 64 MiB-per-case check of the affected controls gave the following results (same five-run protocol). These small differences do not establish a control-case speedup or exact performance parity.

Control Stored-only This head Ratio
4 KiB, skewed dynamic 36.145 36.538 0.989x
64 KiB, random stored 183.500 185.699 0.988x
64 KiB, length 3 / distance 1 792.722 787.391 1.007x
64 KiB, length 31 / distance 257 270.477 267.702 1.010x
64 KiB, length 32 / distance 1 266.512 253.480 1.051x

The stored-copy part was measured separately at commit 473d7246 against base 867d922f: 32 B / 4 KiB / 1 MiB stored inputs improve 1.60x / 1.50x / 1.48x. Combined with the separate Adler batching PR #8682, that stored-copy change adds 3.56x / 5.96x / 5.56x over #8682 alone. Those earlier measurements used 128 MiB per case and the same five-run/pinned protocol; they are not measurements of the new head or of game data. This head's combination with #8682 is correctness-tested below.

Validation

Current head d3c46a5c817aa1706d454188321120e15d7dddb8, base 867d922f09b86583859796a174df89555fb32da8.

  • CMake/Ninja RelWithDebInfo, portable CPU targets on native Windows: cmake --build <build> --target shader_library_test mods_test, then ctest --test-dir <build> -R '^(shader_library|mods)$' --output-on-failure: 2/2 pass.
  • New match tests cover 2,560 streams: every length 3–258 at distances 1, 2, 3, 7, 31, 32, 33, 257, 258 and 32768. A stored history is followed by an explicitly encoded fixed-Huffman match. Tests compare every output byte with an independently constructed repeating pattern, both with fresh and reused output capacity; every case checks a one-byte-too-small cap and a distance reaching before the output's beginning. Python zlib 1.3.1 independently decoded every generated stream to the expected bytes.
  • Stored tests cover 14 stored/mixed streams with payload sizes 0, 1, 31, 256, 65535, 65536 and 131070; fixed/stored/fixed block transitions, alignment, truncations, malformed NLEN and output caps. Their expected checksums were independently checked with Python zlib.
  • MSVC AddressSanitizer (/O2 /EHsc /std:c++20 /fsanitize=address /Zi, /link /DEBUG): the current shader-library test passes. Replacing the growing copy with one memmove fails the new tests. Taking the destination pointer before resize triggers a heap-use-after-free in the sanitizer control. The new tests also pass with the prior stored-only header, as expected for a performance change.
  • Separate Python-zlib-generated oracle on the current head: 153 exact-output cases and 4,896 corrupt-checksum rejections pass, covering stored/fixed/dynamic streams and synthetic patterns through 256 KiB.
  • The full translator suite was run before this PR at stored-only commit 473d7246: python -I scripts/run_semantic_tests.py tests/semantic --jobs 20, 447 files / 5957 tests / 494 s, with the two known baseline failures (test_image_atomics_guard, 47 subcases, and test_image_store_d16, one stale cube expectation). Existing fixes include test: exercise narrowed EXEC for image atomic guards #7212/tests(semantic): update image atomics guard and store_d16 tests for recent translator PRs #7916 and tests/semantic: three image test files red on main (stale after #4473 and #6805; LLVM_MC on Windows) #7284. No translator or Python test code changed in this C++ follow-up; the full semantic suite was not rerun for it.
  • git diff --check and python -I scripts/check_no_game_data.py on both changed files and this report pass.

CPU-only. NVIDIA RTX 3070 / driver 610.88 available but not used. No game files. Linux/macOS untested here. AI-assisted: yes (Codex).

Integration

Fresh claim-board and all-state PR searches found no competing match-copy implementation. At this head, merge trees are clean with main, #7734, #8326, #8358, #8364, #8682, #8254, #8348, #8114 and #8445. Separate combined shader-library tests with #7734 (49175d97), #8326 (0f20d3cb), #8682 (9c3ba87a) and the following #7180 resolution all pass.

#7180 (00551ba00) changes failure returns in the same two locations. Keep its error categories before the copies. In inflate_codes, use:

if (in.failed() || distance > out.size()) return ZlibError::data;
if (out.size() + length > limit) return ZlibError::limit;
// Then this PR's short-match / growing-prefix copy.

For stored blocks:

if (length != (~complement & 0xffff)) return fail(ZlibError::data);
if (out.size() + length > limit) return fail(ZlibError::limit);
if (!reader.append_bytes(out, length)) return fail(ZlibError::data);

The combined test additionally checks ZlibError::limit and ZlibError::data for all 2,560 new cap/distance cases. #7180 has separate pre-existing main conflicts in docs/README.md, docs/runtime_imports.md and runtime/CMakeLists.txt, untouched here. This combined check covers the inflater, not the full DirectStorage shim.

  • No game data, keys or protection workarounds, including fixtures and reports.
  • No translator rule change; no translator-contract update is required.

@svds12343 svds12343 changed the title runtime: bulk copy stored zlib blocks runtime: bulk copy stored blocks and long zlib matches Nov 23, 2026
@kawaii-shakal

Copy link
Copy Markdown

Tested d3c46a5c8 on Linux (x86-64, GCC 16.2, CPU only). shader_library_test passes when built with ASan and UBSan.

I also compared zlib_inflate from this PR with the one on main (867d922f0), both under ASan and UBSan, on 30,000 generated streams: 6,000 from Python zlib across levels, strategies and memory levels (some with a limit below the real size), and 24,000 with flipped bits or truncation. Accept/reject, output size and output hash were identical for every stream, with no sanitizer report.

Not tested: MSVC, Windows, or a speed measurement.


Review written by Claude (Claude Code, Opus 5.5), an AI agent, posted from a contributor's account.

@comtek21516

Copy link
Copy Markdown

Tested 473d72467 (it sits directly on main at 867d922f0) on Windows Server 2025, MSVC 14.52 (Visual Studio 18), Ninja RelWithDebInfo, no GPU: pass.

  • Build: all 475 steps; shader_library.h gives the same single warning as on main here, nothing new.
  • shader_library_test / ctest shader_library: passed, with the new stored-block cases (0 to 131,070 bytes, the fixed -> stored -> fixed stream, every truncation, the output limit and the broken NLEN). ctest mods, which reads through the same header, passes.
  • Behaviour is unchanged, as intended: with runtime/src/shader_library.h taken from main and this PR's test kept, the same test also passes. So the new cases pin what the byte-by-byte loop did and the bulk copy matches it on all of them; they are not a test that fails without the change.
  • Code read: bits() pulls one input byte at a time and only when it needs one, so after align() the cursor is on the first unread byte and append_bytes starts where byte() would. count > in_.size() - pos_ cannot wrap, since the cursor never passes the end. A truncated payload now fails before anything of it is appended, where the loop appended the part that was there; the test covers that out stays within the limit.
  • Whole suite: 147 passed, 124 skipped (no Vulkan driver here), 4 failed. The four are gameinput_host, d3d12_sparse_queue_family, vk_bindless_ps_tex and vk_bindless_ps_imgatomic, which fail the same way on main on this machine (runtime tests: skip, not fail, without a Vulkan driver or a working host GameInput (4 ctests) #7452).

Not measured: the speed-up itself. No game files used. AI-assisted (Claude Code).

@smowlyy

smowlyy commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Verified head d3c46a5c8 merged onto main (867d922f0) on native Windows 11 (10.0.26300.9974, MSVC 19.44, RelWithDebInfo):

  • python -I scripts/check_no_game_data.py on both changed files: clean (exit 0)
  • cmake --build runtime/build --target shader_library_test --parallel: built cleanly
  • ctest --test-dir runtime/build -R '^shader_library$' --output-on-failure -V: 1/1 passed (SHA-256, inflate (stored/fixed/dynamic), JSON, FSSM extraction, FSPX programs and index lookup OK)

AI-assisted.

@adamraskin

adamraskin commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Tested d3c46a5 on Windows 11 Home 26300, MSVC 19.44.35211 (VS 2022), CPU only: pass

(This comment first named 473d724; I re-ran everything on the current head.)

  • cmake -S runtime -B runtime/build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo, cmake --build runtime/build --target shader_library_test, ctest --test-dir runtime/build -R "^shader_library$" --output-on-failure: 1/1 pass at d3c46a5, 473d724 and the base 867d922.
  • The new match_copy_checks and stored_block_checks with the base shader_library.h: pass. This is correct, because both changes are only for speed.
  • cl /O2 /EHsc /std:c++20 /fsanitize=address, head: exit 0, no AddressSanitizer finding.
  • Mutation controls at d3c46a5, each with AddressSanitizer:
    • Long match copied with one memcpy of the full length (copied = length): AddressSanitizer reports memcpy-param-overlap in inflate_codes (shader_library.h:160).
    • The stored-block input bound removed from append_bytes: heap-buffer-overflow at shader_library.h:70.
    • pos_ += count removed (at 473d724): the test fails (exit 1).
    • Chunk step min(copied, ...) changed to min(distance, ...): the test passes, but this mutant is equivalent. After the first copy, copied is always a multiple of distance, so the output is the same.
  • Differential fuzz against Python zlib, with an ASan build of the head: 3,000 synthetic streams (zlib levels 0/1/6/9; default, fixed, RLE and filtered strategies; random, single-byte runs, short periods 1–300 bytes, mixed runs, and 0 B to 300 KB). All give exact bytes, and all fail with a cap one byte too small. 12,000 single-bit flips: no crash and no sanitizer finding. One flip is accepted with different bytes, but Python zlib.decompress accepts the same flipped stream with the same output, so it is a true Adler-32 collision. The base gives the same results.
  • The 14 stored-block Adler-32 constants in the test agree with Python zlib.adler32.
  • python -I scripts/check_no_game_data.py on the two changed files: pass.

Not run: mods_test (no Vulkan headers on this machine), timings, Linux and macOS. GPU (RTX 5090, driver 621.24) not used. No game files.

-AI Assisted

@ddaikodaiko

Copy link
Copy Markdown

Windows run of d3c46a5 on main 867d922f0's tree (checked out alone, not merged with the #7180 it says it conflicts with).

Environment: Windows 10 Pro 10.0.19045, Ryzen 5 1600, RTX 3060 Ti, MSVC 19.44 (VS 2022 Build Tools), Windows SDK 10.0.26100, CMake 3.31 + Ninja from VS, Python 3.14.3. No game files.

cmake -S runtime -B runtime\build -G Ninja -DCMAKE_MAKE_PROGRAM=...\ninja.exe -DCMAKE_BUILD_TYPE=RelWithDebInfo
cmake --build runtime\build --target shader_library_test shader_library_corpus_test -j 10
ctest --test-dir runtime\build -R shader_library --output-on-failure
1/2 Test #39: shader_library ...................   Passed    0.22 sec
2/2 Test #41: shader_library_corpus ............***Skipped   0.05 sec
100% tests passed, 0 tests failed out of 2

shader_library is the one that exercises the changed code: runtime/test/shader_library_test.cpp inflates a stored block, a fixed-Huffman stream (hello hello hello leonida) and a dynamic-Huffman one, then the truncation, output-limit and not-zlib refusals (lines 282-294). shader_library_corpus needs LEONIDA_SHADERS and skips here (77), as designed.

I did not measure performance; that is the author's table, and this machine is not the one it was measured on.

@RAINighty

Copy link
Copy Markdown

Tested d3c46a5c8 merged with main 867d922f0 (clean merge) on Windows 11 (10.0.26300), Intel Core i7-14650HX, MSVC 19.44.35228, RelWithDebInfo (Ninja): pass.

  • shader_library passes with this PR; shader_library_corpus is skipped (no corpus here).
  • Control: with main's runtime/src/shader_library.h under this PR's test, shader_library also passes. It is a copy-speed change, so I did not expect the test to fail without it; I did not measure the speed-up.
  • Code not reviewed beyond running it. No GPU or game files.

AI-assisted (Claude Code).

@niilun

niilun commented Nov 23, 2026

Copy link
Copy Markdown

Tested commit d3c46a5c8 on NVIDIA GeForce RTX 3060 Ti (Ampere), driver 610.88 (32.0.16.1088), Python 3.15.1, Windows 10 Enterprise 19045, MSVC 19.52.37029 (VS 2026): pass

Ran the following commands:

cmake -S runtime -B runtime/build -G "Visual Studio 18 2026" -A x64
cmake --build runtime/build --config RelWithDebInfo --parallel
ctest --test-dir runtime/build -C RelWithDebInfo --output-on-failure
  • This builds with no new warnings in shader_library.h and shader_library_test.cpp,
  • shader_library passes,
  • Full ctest: 267/275 pass. The 8 fails are root_signature_oracle, d3d12_vulkan_device, d3d12_close_parity, d3d12_execute_indirect_validation, d3d12_depth_resolve, d3d12_indirect_rt, d3d12_pso_validation and d3d12_set_descriptor_heaps. Though these 8 fail on 867d922f0 on test machine, so these are not caused by this PR.

@tidyhf

tidyhf commented Nov 23, 2026

Copy link
Copy Markdown

Tested d3c46a5 on NVIDIA GeForce RTX 4080, driver 617.42, Windows 11 Pro (26300), MSVC 14.41: pass.

  • cmake -S runtime -B runtime/build, cmake --build runtime/build --config RelWithDebInfo --target shader_library_test, ctest -R ^shader_library$: 1/1 passed, including the new match_copy_checks and stored_block_checks.
  • Read the diff: the stored-block bounds check happens before the copy, and the long-match path handles overlap (distance < length) by doubling the already-written prefix, so each memcpy is disjoint.
  • Baseline: main 867d922 on the same machine passes 273 of 275 ctest tests. The two failures (d3d12_vulkan_device, d3d12_depth_resolve) are the known NVIDIA ones from main dde82f27 on NVIDIA RTX 4070: 4 ctest failures; #8496 fixes d3d12_vulkan_device, d3d12_depth_resolve is new #8720 and aren't touched by this PR.

AI-assisted (Claude Code) test run and review.

@GeremC

GeremC commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested d3c46a5 merged with main 5d74c27 under Wine: pass

On: Linux, Ubuntu 24.04, cross-built with clang-cl 19.1.1 + lld-link + xwin SDK (RelWithDebInfo), run through Wine 9.0; CPU only, no game files.

  • ctest -R ^shader_library$: passed.
  • Negative control, runtime/src/shader_library.h from main with the PR's test kept: it also passes, as expected for a speed-up that keeps the output: the decompression checks agree with the old path too. No timing taken here.

AI-assisted (Claude Code).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.