startup: track decode length and destination capacity separately, support chunked zlib streams #1207
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/1214"
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 Holastor on 2026-11-24T03:37:11Z.
Change
Resolves DirectStorage zlib request failures and chunked streaming read asserts in the startup stand-in (
src/startup_stubs/xcrdapi.cpp):Separation of Decode Length and Destination Capacity (Fixes #1144):
destination_capacityis fixed to the caller-supplieddestination_size.decode_lengthtracks actual decompressed bytes (produced) frominflate_zlib.queue_enqueue_request, page token bounds are computed strictly fromdestination_size((page_offset + destination_size + 0xFFFF) / 0x10000), preventing out-of-bounds reads into the caller's token array.decode_length > destination_capacity, or if page grants are missing / insufficient (needed_pages > granted_pagesor any required token is 0), the request fails withE_FAIL(0x80004005), and the destination memory is left completely unchanged.Chunked Streaming Reads (Fixes #1136):
n \times Dstream innpiece requests targeting 64 KiB destinations: piece 0 starts at file offsetBwith a zlib header, while piecesk \ge 1are stepped by destination size (B + k \times D) without headers.StreamCache(up to 16 entries) indexed by(source, base_offset, compressed_size).has_following_chunkinspects the queue'ssubmittedandwaitingdeques for matching downstream pieces. When piece 0 expands beyond its destination capacity and following chunks are queued, the decompressed stream is cached and slice 0 ([0, D)) is served to piece 0.k \ge 1, slices[k \times D, (k+1) \times D)are served directly fromStreamCache.Source-Built Regression Fixtures (
tests/startup_stub_consumer.cpp):0xAA; verifiesE_FAILand 100% unchanged memory (0xAA).tokens[1] = 0; verifiesE_FAILand 100% unchanged memory (0xAA).0xAA; verifiesE_FAILand buffer untouched.4 \times 64\text{ KiB}) enqueued as 4 separate requests stepped byk \times D; all complete withS_OKand match the original stream byte-for-byte.500\text{ KiB} > 128\text{ KiB}) fails withE_FAILleaving prefilled buffer (0xEE) untouched.Verification
Commit
738bfc48on top ofmainc02af631. Built on Windows 11 Pro x64 (build 26100), MSVC 19.51 (VS 2026 Developer PowerShell), Ninja.Release Preset:
Dev Preset:
Linters:
python -B tests/docs_links_check.py(16 files, 269 links) andpython -B tests/bidi_controls_check.py(1005 files) pass with 0 errors.Checklist
Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T03:41:03Z.
Review: COMMENTED
Technical review on Linux (Windows build/tests were not executed locally).
Checks run (Linux, commit
738bfc48)/root/.local/share/x2w-rev-venv/bin/python -B tests/docs_links_check.py: passed (16Markdown files,269links)./root/.local/share/x2w-rev-venv/bin/python -B tests/bidi_controls_check.py: passed (1005files).Findings
StreamCache::get_slice(src/startup_stubs/xcrdapi.cpp): Whenoffset - it->base_offsetis nearUINT64_MAX,delta + need_bytescan wrap around past0and pass the<= it->data.size()check, causingit->data.begin() + deltato index out of bounds. Checkingdelta <= it->data.size() && need_bytes <= it->data.size() - deltaavoids the overflow.has_following_chunk(src/startup_stubs/xcrdapi.cpp):has_following_chunkinspectswork.submittedandwork.waitingat the moment piece 0 executes, which works when all chunks are enqueued beforeSubmit()(as indstorage_checks), though separateSubmit()calls per chunk would not see later chunks yet.Separation of
decode_lengthvs.destination_capacity, page grant checks (needed_pages <= granted_pagesand non-nulltokens[i]), failure accounting (failed), and thedstoragepositive/negative controls intests/startup_stub_consumer.cppare otherwise clean and title-neutral.Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T03:51:28Z.
Review: COMMENTED
Retest on Linux at commit
50f56203(delta738bfc48..50f56203; Windows build/tests were not executed locally).Findings
StreamCache::get_slice&has_following_chunkwraparound (src/startup_stubs/xcrdapi.cpp): resolved.get_slicenow checksdelta <= it->data.size() && need_bytes <= it->data.size() - delta, andhas_following_chunkcheckse_offset > offset && e_offset - offset == destination_size, preventingu64addition wraparound. (has_following_chunkstill assumes chunks are enqueued beforeSubmit(), as noted in the prior review.)tests/startup_stub_consumer.cpp): added piece 2 with near-wrapping offset0xFFFFFFFFFFFF0000ull, verifyinghr2 != 0anddest2remains0xDD. (Minor comment nit: line 577 saysUINT64_MAX - 0x10000while the literal isUINT64_MAX - 0xFFFF.)Checks run (Linux,
50f56203)/root/.local/share/x2w-rev-venv/bin/python -B -m py_compile tests/startup_stub_check.py: passed./root/.local/share/x2w-rev-venv/bin/python -B tests/docs_links_check.py: passed (16Markdown files,269links)./root/.local/share/x2w-rev-venv/bin/python -B tests/bidi_controls_check.py: passed (1005tracked files).git diff --check 738bfc48..50f56203: passed.Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T03:58:42Z.
Review: CHANGES_REQUESTED
The capacity and wrap checks are separate from stream identity. The global cache can supply a slice to an unrelated standalone read that shares the source and compressed size, because cache lookup happens before the request is identified as a continuation. Please tie each cached slice to the identified queue and continuation requests for a live source. Keep memory requests on direct decode unless their source lifetime and identity can be proved. Add a source-built control where a standalone valid stream shares the cache-key fields and still decodes its own bytes. Also bound the failure diagnostic to the input length so a short invalid header reports a failure without reading beyond it.
Imported from R0Y00/Xbox2Windows. Originally posted by lambirou on 2026-11-24T04:23:26Z.
Review: COMMENTED
Independent Release verification on
mainatb5cb8800with the #1214 diff applied.Environment: Windows 10.0.26300.10075, MSVC 19.44.35228.0, Ninja, AMD Radeon RX 9060 XT 32.0.32029.2010 and WARP.
ctest --preset release --no-tests=error -R '^startup_stubs$' -V: 1/1 passed. The extendedstartup_stubsfixture, including the DirectStorage cases, passes.git diff --check: passed.tests/docs_links_check.py: 16 Markdown files / 272 links, passed.tests/bidi_controls_check.py: 1008 files, passed.The PR also has a successful Windows checks run at
50f56203(run 2965). No game files, dumps or private logs were used. From this independent run, the change is ready to merge.AI-assisted (Codex).
Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T04:37:19Z.
Review: COMMENTED
Linux retest at commit
d6c9a773(delta50f56203..d6c9a773; Windows build andstartup_stubsruntime tests were not executed locally).Delta
50f56203..d6c9a773auditsrc/startup_stubs/xcrdapi.cpp:StreamCachemoved into per-queueQueueWork::cached_streams(max_cached_streams = 16), guarded bywork.mutex.has_zlib_header(input, source_size)validates CMF/FLG (cmf & 0x0F == 8,cmf >> 4 <= 7,(cmf * 256 + flg) % 31 == 0). When a request presents a valid zlib header andinflate_zlibfails,decode_error = trueprevents falling through towork.cached_streams, keeping damaged standalone streams distinct from continuation slices.!direct_decoded && !decode_error && !memory_source && self && self->workwithfile_object->kind == file && file_object->handle != INVALID_HANDLE_VALUE,offset > it->base_offset,destination_size > 0 && (delta % destination_size) == 0, and overflow-safe bounds checks (delta <= it->data.size() && destination_size <= it->data.size() - delta).has_following_chunkrejectse_options & 0x400000(memory sources) and requirese_offset > offset && e_offset - offset == destination_size.tests/startup_stub_consumer.cpp: chunked-stream and negative out-of-bounds/near-wrap controls updated to file-backed sources (OpenFile/CloseFile), plus new controls for standalone streams sharingcompressed_sizeand damaged-checksum streams at a matching continuation offset (dest_badremains0xBB).Checks run (Linux, commit
d6c9a773)/root/.local/share/x2w-rev-venv/bin/python -B tests/bidi_controls_check.py: passed (Self-test passed. Checked 1005 tracked source, script and build/CI files: no bidirectional controls.).tests/startup_stub_check.py/startup_stub_consumer.cpp: not executed on Linux (startup_stub_check.pyrequires Windowskernel32and built DLLs/EXE).Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T05:18:54Z.
Review: APPROVED
Verified the submission ID and entry ID design and the original size, checksum, and physical-destination controls in Windows Release. For the concurrent-batch control, the first worker is held at an existing queue signal until the second Submit has returned. The gated test passed on this commit and failed with only the submission-ID check removed. The shared implementation credits the contribution from #1235.
Imported from R0Y00/Xbox2Windows. Originally posted by Holastor on 2026-11-24T03:44:43Z.
Thank you @tedin7 for the careful review and catching that edge case!
Updated in commit
50f56203:Imported from R0Y00/Xbox2Windows. Originally posted by Holastor on 2026-11-24T04:16:36Z.
Thank you @R0Y00 and @tedin7 for the detailed feedback and requirements.
Addressed in commit
5ad75b5c:Queue-scoped stream caching:
CachedStreamandcached_streamsintostruct QueueWork. Stream caching and continuation lookups are now strictly tied to the identified queue instance (self->work), eliminating global static cache state across queues.Strict direct decode for memory requests:
options & 0x400000) stay strictly on direct decode. Chunk continuation lookups and piece 0 caching are restricted exclusively to live file sources (!memory_source && file_object && file_object->kind == file && file_object->handle != INVALID_HANDLE_VALUE).Stream identity & continuation identification:
offset > it->base_offset,(offset - it->base_offset) % destination_size == 0, and valid slice bounds without addition overflow).Source-built control with shared cache-key fields:
startup_stub_consumerunder scenariodstorage:0x33) and Stream 2 (64 KiB of0x77), both having the exact same compressed sizeS, in the same temporary file object at offsets 0 and 128 KiB.source) and compressed sizeS.0x77) directly and is not intercepted by Stream 1's cached entry.Bounded failure diagnostic:
xcrdapi.cpp, diagnostic header logging reads at mostsource_sizebytes into a zero-initialized array (unsigned h[4] = {}; for (unsigned i = 0; i < 4 && i < source_size; ++i) h[i] = input[i];), preventing any out-of-bounds reads whensource_size < 4.Comment nit:
startup_stub_consumer.cppto stateUINT64_MAX - 0xFFFF.Verification (commit
5ad75b5c)Environment: Windows 11 Pro x64 (build 26100), MSVC 19.51, CMake / Ninja.
Dev preset:
Release preset:
Checks & linters:
git diff --check: clean (0 errors).tests/docs_links_check.py: passed (16 files, 269 links).tests/bidi_controls_check.py: passed (1005 tracked files).Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T04:21:34Z.
Independent Windows retest on commit
5ad75b5c71c47826d7e9bf7dfcc27677f16d724d(pull/1214/head):Environment
14.44.35207(cl.exe/ml64.exex64)WARP)Commands & Results
Debug (
devpreset):Result: 1/1 passed (
startup_stubs:0.49 sec;load xcrdapi.dll: 1/1 exports,dstorage control: exit=0 ok,PASS).Release (
/O2,releasepreset):Result: 1/1 passed (
startup_stubs:0.38 sec;load xcrdapi.dll: 1/1 exports,dstorage control: exit=0 ok,PASS).0 failed, 0 skipped.
Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T04:22:05Z.
The queue-local cache, direct decode for memory sources and short diagnostic all address parts of the review. One case remains: a valid zlib header followed by a checksum failure can still fall through to the cache lookup and report success at a matching offset. Keep an actual decode error distinct from a proven continuation. Please add a generated case that enqueues a standalone stream with a damaged checksum at a matching offset and verifies failure and an unchanged destination.
Imported from R0Y00/Xbox2Windows. Originally posted by lambirou on 2026-11-24T04:23:58Z.
Correction to my review above: I missed the existing
CHANGES_REQUESTEDfrom @R0Y00 about the global stream cache supplying a slice to an unrelated standalone read that shares the source and compressed size.My run covers the Release build and the current source-built tests; it does not address that cache-identity design request. Please treat the “ready to merge” sentence as withdrawn. The PR still needs the cache key tied to the identified queue/continuation request, the standalone-read control, and the bounded failure diagnostic before it is ready.
AI-assisted (Codex).
Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T04:27:48Z.
RTX 4060 Laptop integration update for
5ad75b5. I rebuilt XCRDAPI from the PR head and ran the same offline startup workload. The request-failure counter reached 17, down from 37 in the earlier run. The separate BCPack zero-fill counter remained 37. The diagnostic now identifies destination-capacity rejections on zlib requests targeting physical pages, including capacities below one 64 KiB page. This comparison also included graphics updates, so it does not isolate downstream rendering changes to this DLL.Could the follow-up fixture cover the short final destination in a multi-piece stream and distinguish it from an invalid oversized decode? Keep the destination guard intact and check guard bytes and neighboring page grants. I am retaining the integration logs locally. Refs #1144.
Imported from R0Y00/Xbox2Windows. Originally posted by Holastor on 2026-11-24T04:30:19Z.
Thank you @R0Y00 for pointing out this subtle fall-through case, and thank you @tedin7 and @lambirou for the independent verifications on Windows Server 2025 and Windows 10.
Addressed in commit
d6c9a773:Keep decode errors distinct from continuations:
execute_request(src/startup_stubs/xcrdapi.cpp), when input presents a valid RFC 1950 zlib header but decompression fails (e.g. Adler-32 checksum mismatch or corrupted payload),decode_erroris set totrue.!direct_decoded && !decode_error && ..., preventing an actual decode error from falling through to the cache lookup and reporting a false success at a matching offset.Source-built negative control for damaged checksum at matching offset:
tests/startup_stub_consumer.cpp, addedmake_fixed_deflate_zlib(RFC 1951 fixed Huffman encoder) and a dedicated regression control:0x33) is enqueued at offset 0 with destination 64 KiB (inflating 128 KiB and populating the queue's cached stream).comp_bad) sharing the exact same file object and compressed sizeSis placed at file offset 64 KiB (the exact matching continuation offset for Stream 1).comp_bad.back() ^= 0xFF).0xBB,inflate_zlibfails the checksum check,decode_errorblocks fall-through to the cache, the request fails with non-zero HRESULT (E_FAIL), and the destination buffer remains 100% untouched (0xBB).Verification (commit
d6c9a773)Environment: Windows 11 Pro x64 (build 26100), MSVC 19.51, CMake / Ninja.
Dev preset:
Release preset:
Checks & linters:
git diff --check: clean (0 errors).tests/docs_links_check.py: passed (16 files, 269 links).tests/bidi_controls_check.py: passed (1005 tracked files).Imported from R0Y00/Xbox2Windows. Originally posted by Holastor on 2026-11-24T04:36:33Z.
Thank you @R0Y00 for the integration update and diagnostic details on the 17 remaining request failures.
Addressed in commit
bb35f045:1. Step tracking vs. short destination capacities
D < 64\text{ KiB}, e.g. 36 KiB), matching continuation offsets withdelta % destination_size == 0failed because the offset step between pieces is dictated by the initial stream chunk size (C = 64\text{ KiB}), not the trailing piece's shorter destination size (64\text{ KiB} \pmod{36\text{ KiB}} \ne 0).chunk_sizefrom piece 0 instruct CachedStream(put_stream(..., destination_size, ...)). Continuation lookups step bystep = it->chunk_size ? it->chunk_size : 0x10000.(delta % step) == 0 && delta < it->data.size(), the continuation extractsslice_size = destination_size < available ? destination_size : available. Requests wheredestination_size <= availableare fulfilled cleanly without exceeding remaining uncompressed bytes.2. Multi-piece physical page fixture with intact guard bytes & neighboring grant checks
Extended
tests/startup_stub_consumer.cppunder thedstoragescenario:XMemAllocPhysicalPages(2)/XMemMapPhysicalPages).0xAA.tokens[0] = pages[0]).tokens[0] = pages[1], neighboring tokentokens[1] = 0).hr == 0).0xAA).tokens[1]is verified to remain0(never read or written).3. Negative control: Invalid oversized decode
0x55) with a 100 KiB standalone stream, but specifies destination capacity of 36 KiB with only 1 page grant (tokens[0] = pages[1], neighboringtokens[1] = 0).hr != 0).0x55).tokens[1]remains0.4. Build & Test Verification
Verified on Windows 11 (MSVC, C++20):
All passed without diagnostics or regressions. Refs #1144, #1214.
Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T04:41:11Z.
I reran
startup_stubsin Windows Release onbb35f045. The damaged-Adler32 case and the short final destination now pass.One unrelated read can still get a successful cached result.
has_following_chunkestablishes that the first sibling was queued, but the cache subsequently answers any aligned offset within the inflated range when file and compressed size match. After a valid two-slice submission completes, a later independent request on the same live file and queue at the same aligned offset can still receive the first stream's bytes. Please scope the cache to the actual continuation requests identified for the stream (or expire it at a boundary that guarantees the same property). Add a source-built case with a valid chunked submission followed by a separate Submit with a same-size non-zlib read at a matching offset. The separate read should fail and leave its sentinel unchanged.Imported from R0Y00/Xbox2Windows. Originally posted by lambirou on 2026-11-24T04:49:01Z.
Follow-up for the remaining cache-identity case: #1235, stacked on this PR at
bb35f045. The last commit0846d914scopes the cache to the exact queued continuation entry ids and adds the separate-Submitcontrol with a matching offset and an unchanged sentinel. Local Windows Releasestartup_stubspasses; the new control fails against the previous head.Imported from R0Y00/Xbox2Windows. Originally posted by Holastor on 2026-11-24T04:49:51Z.
Thank you @R0Y00 for the thorough review and testing!
Addressed in commit
9570cec4:1. Scoping stream cache to identified continuations & consuming on fulfillment
find_continuation_offsetsinspects queued entries (work.submittedandwork.waiting) and records the exact matching offsets intoCachedStream::pending_offsets. If no continuation entries are queued, the stream is not cached.offsetto match one of the stream'spending_offsets.pending_offsets.pending_offsets.empty()), the cached stream is immediately erased fromwork.cached_streams.2. Submission boundary expiration
work.submitted.empty()after processing an entry (all entries of the current submission have finished executing), any remaining cached streams inwork.cached_streamsare cleared. This guarantees that cached streams never persist into subsequentSubmit()calls.3. Source-built control: chunked submission followed by separate non-zlib Submit
Extended
tests/startup_stub_consumer.cppunder scenariodstorage:S) and raw non-zlib bytes (0xEE) at continuation offset 64 KiB.hr == 0) and destination buffers both verify to payload0x44.S, destination 64 KiB prefilled with sentinel0x99.hr != 0(E_FAIL).0x99).4. Build & Test Verification
Verified on Windows 11 (MSVC, C++20):
Both
devandreleasepassedstartup_stubscleanly, and all link and bidi checks passed without errors. Refs #1144, #1214.Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T04:59:39Z.
Thanks to both authors for the separate-Submit control. #1214 now tracks offsets and #1235 tracks entry IDs, so please land one shared implementation and keep both contributions credited. The entry IDs are the stronger identity, but both candidates still search the waiting deque, which already belongs to a future Submit. Also, the worker can have two submitted batches queued at once, so an empty deque is not a submission boundary.
For the source-built scope, attach the submission identity when moving waiting entries into submitted and only admit adjacent, matching chunk entries in that same batch. Please include a deterministic check with the first request already submitted and a matching non-zlib request in the next batch before the worker examines continuations. The first request with an undersized standalone destination and the unrelated second request must fail with unchanged sentinels. If real continuation requests need to cross explicit submits, please share a source-built comparison that shows how to identify those requests without matching an independent read. The existing short tail, damaged header/checksum, and physical-page tests still apply.
Imported from R0Y00/Xbox2Windows. Originally posted by Holastor on 2026-11-24T05:11:36Z.
Thank you @R0Y00 and @lambirou!
We have integrated the
entry_iddesign from #1235 into PR #1214 withCo-authored-by: Roland Edi <[email protected]>in commit4f67e704, addressing theSubmit()boundary feedback.Summary of changes
submission_idand monotonicidinEntry:struct Entrygainsu64 id = 0;(assigned monotonically inpush()) andu64 submission_id = 0;.submit(), when moving entries fromwork.waitingtowork.submitted, all entries in that batch receive a unifiedsubmission_id = ++work.next_submission_id.following_chunk_ids()strictly scoped to the current submission:work.waitingis completely removed:following_chunk_idsnow scans onlywork.submitted.status_entry) and halts (break) as soon ase.submission_id != current_submission_id, or when an unrelated/non-zlib request or offset mismatch is encountered.id, stored inCachedStream::continuation_ids.Strict continuation cache lookup & lifecycle:
execute_request()requiresentry_idto be present init->continuation_ids.entry_idis removed fromcontinuation_ids. When empty, the stream is immediately erased fromcached_streams.work.submitted.empty()after processing an entry, any leftover cached streams are cleared.Deterministic two-
Submit()boundary controls (tests/startup_stub_consumer.cpp):Submit()calls:Submit(): Sends a compressed stream targeting an undersized destination buffer (64 KiB destination for 128 KiB uncompressed stream) with no continuation request in that batch. Because no continuation is queued in the batch,following_chunk_idsreturns empty, the stream is not cached, and the request fails cleanly with destination memory untouched (0xA5).Submit(): Immediately enqueued on the same queue and live file handle at the continuation offset (64 KiB), requesting zlib decompression on non-zlib file bytes. Because it belongs to a different submission and cannot match any cached stream, it fails cleanly with non-zero HRESULT and its destination memory remains untouched (0xB6).Submitcontrol testing completed multi-piece streams followed by independent reads.Documentation:
docs/startup-runtime.md.Verification (commit
4f67e704)Environment: Windows 11 Pro x64 (build 26100), MSVC 19.51, CMake / Ninja.
Dev preset:
Release preset:
Checks & linters:
git diff --check: clean (0 errors).tests/docs_links_check.py: passed (16 files, 269 links).tests/bidi_controls_check.py: passed (1005 files).Refs #1144, #1214, #1235.