startup: implement DirectStorage CancelRequestsWithTag #1869
No reviewers
Labels
No labels
accessibility
awaiting author
bug
documentation
duplicate
enhancement
good first issue
help wanted
invalid
priority: P0
question
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/R0Y00--Xbox2Windows!1869
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-1869"
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?
@chunfeng11221 on GitHub · 2026-11-24 19:48 UTC · original
chunfeng11221:startup/dstorage-cancel→main· +849 −7 · 5 files · 2 commits · openProblem
In
src/startup_stubs/xcrdapi.cpp, DirectStorage queue slot 7 (IDStorageQueue::CancelRequestsWithTag(UINT64 mask, UINT64 value)) is currently a no-op (#1843, slice 3).Change
Implements
CancelRequestsWithTaginsrc/startup_stubs/xcrdapi.cppaccording to Microsoft's MIT-licensed Xbox GDK DirectStorage reference (Xbox-GDK-Samples/Samples/System/SimpleDirectStorageCombo/DirectStorageWin32/dstorage_win32.h, lines 238–331 and 552–562):UINT64 CancellationTagfromDSTORAGE_REQUESToffset+0x38and matches(tag & mask) == value(tag_matches).Submit(work->waiting): compacts matchingEntry::requestentries out in place without heap allocation, preserving the order of non-matching requests, status entries, and fence signals.Submit(work->submitted) & OOM/deferred lists (work->failing,self->unrecorded_head,work->deferred_head): marks matching requestscancelled = truein place (releasing captured page tokens) sosubmitted_total/finished_totaldrain invariants and deferred-completion cutoffs remain intact.run_entry,fail_unrecorded,fail_waiting, andcomplete_deferredskip cancelled requests without performing I/O, touching destinations, incrementingrequests_failed, or settingself->pending = E_FAIL.following_chunk_idsstops at a cancelled entry rather than extending a chunked stream cache across it.setup_mutex()andwork->mutexsequentially (never nested in reverse order), matchingsubmit()'s locking discipline.execute_request(xcrdapi.cpp:519) still reads+0x38as an inflate buffer-sizing hint; left untouched here to keep this PR scoped strictly to slice 3 and conflict-free with slices 1 and 2 (#1847).docs/startup-runtime.mdand registersstartup_storage_cancelplusstartup_storage_cancel_control(WILL_FAIL TRUE) inCMakeLists.txt.Verification
Tested on Windows 11 x64 (
MSVC 19.44.35228, Windows SDK10.0.26100.0, base commit939e514), synthetic file and memory fixtures only (no game files):startup_storage_cancelexercises 7 scenarios againstXCRDAPI.dll:~0ull) beforeSubmit(file and memory sources)0xFFFFFFFF00000000/0x0000000200000000)mask=0x0F, value=0x1Fcancels nothing)mask=0, value=0) including an EOF-failing request — destination stays poisoned, status completesS_OK, and log contains noread failedCancelRequestsWithTagstill executesSubmitconcurrent cancellation — blocks the worker deterministically on a gateEnqueueSignalfence so requests sit inwork->submitted, cancels a matching EOF-failing request live, releases the gate, and confirms clean drain, untouched destination, sibling completion, andS_OKE_FAILon statusdevpreset:ctest --preset dev --no-tests=error -R "^startup_(storage_(alloc_failure|refusal_order|cancel|failure_counts|worker_start)|dstorage_destination)"— 8/8 passed (startup_storage_cancel,startup_storage_cancel_control,startup_storage_alloc_failure,startup_storage_refusal_order,startup_storage_failure_counts,startup_storage_failure_counts_one_bucket_control,startup_dstorage_destination,startup_storage_worker_start).releasepreset:ctest --preset release --no-tests=error -R "^startup_storage_cancel(_control)?$"— 2/2 passed (0.03 s).tests/docs_links_check.py(18 Markdown files, 370 links) andtests/bidi_controls_check.py(1323 tracked files) — both passed.Fail-first mutation controls
startup_storage_cancel_control(--control-expect-uncancelled,WILL_FAIL TRUE): fails as expected because the cancelled request did not write its destination.queue_cancelto no-op):startup_storage_cancelfails across cases 1, 2, 4, 5, 6, and 7.tag_matchesto(tag & mask) == (value & mask)):startup_storage_cancelfails on case 3 (unmasked bit did not cancel).Scope / What this does not establish
RetrieveErrorRecord/GetErrorEvent(slice 2).execute_requestare allowed to finish, matching DirectStorage's "attempts to cancel" contract.Refs #1843.
AI-assisted.
@ChazY11 on GitHub · 2026-11-24 20:18 UTC · original
Built it and broke three parts of the cancellation
At the PR head, Windows 11 build 26300.9974, MSVC 19.44:
Three mutations to
src/startup_stubs/xcrdapi.cpp, each rebuilt into XCRDAPI.dll (the test doesLoadLibraryA(argv[1]))with the DLL timestamp verified to change, then reverted:
tag_matches:return (tag & mask) == value;→return true;cancelledcancellation_tag_offset0x38→0x30The third is the one I care about most: the offset is the only thing tying this to the console
DSTORAGE_REQUESTlayout, and0x30still reads some bytes, so a fixture that only checked "the count went down" would pass. It does not.Measurement note, same trap as in #1874: my first run rebuilt
startup_storage_cancel.exeand reported "not rebuilt" forall three, because the exe is only the harness. Rebuilding the DLL is what makes the mutants visible; a "survivor" that never
rebuilt is not a survivor.
What the fixture covers, from reading it
Submitcompaction in place, order preserved for the entries that stay.--control-expect-uncancelledmode, which is the right shape for the negative control (mask/valuethat match nothing).Two questions
Submitbehaviour. The description covers the pre-Submitpath in detail; for a request already handed to aworker the reference marks it and lets it complete. Does the fixture exercise that ordering (cancel after
Submit, expectthe read to finish and the status to be "cancelled" rather than "failed")? If it does, ignore this — I could not tell from
the names.
mask = 0. Withtag_matchesas written,mask = 0, value = 0matches every request. That is what the referencedoes, but it is also the kind of call a caller makes by accident. A one-line note in the doc row ("mask 0 cancels
everything") would save someone an afternoon.
Verdict
Reviewed. The three parts that make the feature work are each pinned by the new fixture. No objections to the change.
Notes
@tedin7 on GitHub · 2026-11-25 12:53 UTC · original
@chunfeng11221 could you rebase this branch onto current
mainand force-push?GitHub reports head
ece618ecas conflicting withmain, so it cannot be merged as is.Files that conflict with current
main(cf97bee1):src/startup_stubs/xcrdapi.cppCommands run locally:
Once it is rebased and CI is green it will be re-checked right away.
AI-assisted; commands listed were executed locally.
@tedin7 on GitHub · 2026-11-24 19:55 UTC · original · reviewed
Review of head
ece618ec61aee55120c64cd0f08dcb0b1e94b435(one commit onorigin/main;git merge-tree --write-tree origin/main HEADmerges without conflicts).Verdict: no P1, no P2. Three P3 notes. The test and the stub are Windows-only (the stub uses MSVC
__try/__except), so I could not run them here; what I checked, I checked by reading and by a small harness described below.Public contract. I compared the change with Microsoft's MIT-licensed Win32 wrapper in Xbox-GDK-Samples (
DirectStorageWin32/dstorage_win32.handDirectStorageWin32WrapperQueue.cpp, read from GitHub):(CancellationTag & mask) == value, with no masking ofvalue.tag_matchesis exactly that, so avaluewith bits outsidemaskmatches nothing, and case 3 of the test pins it.requests_failedand does not fail later status entries.entry = std::move(work.submitted.front()); pop_front()underwork.mutex) is out ofsubmitted, so it cannot be marked: the same boundary.Optionsis at 0, the destination union at 0x08 to 0x18,DestinationSizeat 0x18, the source union at 0x20 to 0x30,SourceSizeat 0x30,IntermediateSizeat 0x34,CancellationTagat 0x38 andNameat 0x40, so 0x48 in all, which isEntry::bytes. The read at +0x38 stays inside the array.Locking and races
queue_canceltakessetup_mutexto readself->workand scan the unrecorded list, releases it, then takeswork->mutexforwaiting,submitted,failingand the deferred list. It never holds both, so it cannot invert the order Submit uses (work->mutexthensetup_mutex).work->mutexacross the detach and the append; if cancel scans the unrecorded list after the detach, its second step blocks onwork->mutexuntil the node is in the deferred list.submittedandfailinghappens underwork->mutex, the same lock under which the worker moves an entry out, so no entry is read by the worker while it is being edited.tokens.reset()on a marked entry is therefore safe.run_entryreturns early, the worker goes on to++finished_total, sosubmitted_total/finished_totaland the cutoffs of deferred completions are unchanged.following_chunk_idsstops at a cancelled entry, so no read-ahead is started for it. The fourfail_unstartedcall sites skip a cancelled request.Unrecordedis only built indefer_unrecorded, sotagandcancelledare always set from the entry.Commands run locally on Linux
python3 -B tests/docs_links_check.py(18 files, 370 links),python3 -B tests/bidi_controls_check.py(1324 files): pass.git diff --check origin/main...HEAD: clean.x86_64-w64-mingw32-g++compilestests/startup_storage_cancel.cpp; the stub itself does not build with it (MSVC-only SEH inlocal_log.h), and there is no working Wine here, so the DLL and the test were not run.queue_cancel(std::deque<Entry>, in-place move,pop_back) with the PR'stag_matchesandrequest_cancellation_tag, 20,000 random queues of 0 to 11 mixed request/status/signal entries and random masks and values, compared with a plain model, built with ASan and UBSan: 0 mismatches. The mutant with++writereplaced bywrite += 0gives 18,320 mismatches in the same run.Findings
failing, deferred and unrecorded branches ofqueue_cancel(and the threefail_unstartedskips that go with them) only run when an allocation fails; the test's cases 1 to 7 coverwaitingandsubmitted. The existingstartup_storage_alloc_failurefixture shows an injected failure is possible, so one case that cancels an entry that was deferred by a failed allocation would pin them.waiting.size() >= capacity) sees room that the reference queue does not give back until the entry is released. It cannot lose a request; it can only delay an automatic Submit by one.Not run: the Windows build,
startup_storage_canceland its control, and ASan/TSan on the stub itself.AI-assisted; commands listed were executed locally.
@R0Y00 on GitHub · 2026-11-24 20:05 UTC · original · requested changes
The cancellation match and queue-order controls look useful. There is one compatibility blocker before we advertise arbitrary request tags. This PR reads +0x38 as CancellationTag, while execute_request also reads its low word as an uncompressed size and passes it to output.resize. The public Xbox request layout identifies +0x34 as IntermediateSize for combined zlib and BCPack and +0x38 as the opaque tag. With the current decoder, the low word of the tag changes the inflate allocation for an uncancelled request. The raw cancellation fixtures cannot distinguish that.
Please make the ABI and decode sizing consistent before enabling this on main. A source-built accepted case should submit the same zlib payload with two different nonzero tags and verify identical completion, bytes, and bounded decode sizing; the cancellation counterpart should leave the destination unchanged and preserve status/fence ordering. Keep existing chunked and capacity refusals. Coordinate shared layout declarations with #1873.
Microsoft Xbox request definition.
@tedin7 on GitHub · 2026-11-27 09:36 UTC · original
This PR now conflicts with
main. Conflicting files:docs/startup-runtime.mdsrc/startup_stubs/xcrdapi.cppCould you merge
maininto your branch (a merge commit, no force push needed) and resolve these? Thank you.AI-assisted; commands listed were executed locally. (
git merge-tree origin/main <head>)@chunfeng11221 on GitHub · 2026-11-27 09:54 UTC · original
@tedin7 @R0Y00 @ChazY11 Thank you all for the reviews and checks! Merged
main(8a901eb2) via a regular merge commit (c0d2977c, no force-push) and resolved all review items:Merge conflict resolution (
src/startup_stubs/xcrdapi.cpp,docs/startup-runtime.md)#2788object refcounting across all cancellation paths (queue_cancelcallsrelease_entry/release_unrecordedon cancelledwaiting,submitted,failing,unrecorded, anddeferredrequests; thefail_unstartedskip paths unconditionally release retained references).#1873error notification/retrieval (DSTORAGE_ERROR_RECORDandGetErrorEventare untouched by cancelled requests),x2w_local::first_calls, andmain'sstartup_memory_srv_volumeandCopyTextureRegiondoc sections.Request tag & inflate-sizing consistency (@R0Y00)
main(f3f34f3d) keeps+0x34(IntermediateSize) separate from opaque+0x38(CancellationTag) and never sizes the inflate buffer from+0x38.#1873(src/startup_stubs/dstorage_error_record.h):request_cancellation_tagreadsoffsetof(StorageRequest, cancellation_tag)onsizeof(StorageRequest)bytes (Unrecordedreusesbytes[sizeof(StorageRequest)]), andtests/startup_storage_cancel.cppconstructsx2w_startup::StorageRequestand checksx2w_startup::StorageErrorRecorddirectly.tests/startup_storage_cancel.cpp: submits a source-built zlib payload (stored_zlib) with two distinct nonzero tags (0x1111111100000001and0x222222227FFFFFFF, ~2 GiB low word) verifying identicalS_OKcompletion, identical decoded bytes, zero error record, and bounded process commit growth (< 64 MiB), alongside its cancellation counterpart verifying untouched destination, surviving sibling, status/fence ordering, and no error record/event.HRESULT_FROM_WIN32(ERROR_HANDLE_EOF)andRetrieveErrorRecord/GetErrorEventverification, and added Case 9 pinning#2788file refcount release across pre-Submit (waiting) and post-Submit (submitted) cancellations.Reviewer notes (@tedin7, @ChazY11)
cancelled_deferred_entriesintests/startup_storage_worker_start.cppexercisingunrecorded_head->fail_unrecorded,unrecorded_head->deferred_head->complete_deferred, and livework->deferred_headcancellation behind a held prefix fence; added the already-dequeued worker boundary note todocs/startup-runtime.md.Submitcancellation ordering is covered by Case 6 intests/startup_storage_cancel.cpp(holds the worker on aGateFenceafterSubmit, cancels an EOF-failing request live inwork->submitted, and verifies clean drain, untouched destination, surviving sibling,S_OK, zero error record, and unsignaledGetErrorEvent). Added a note indocs/startup-runtime.mdexplicitly calling out thatmask = 0, value = 0matches and cancels every queued request.Local verification (Windows 11 x64, MSVC 19.44)
ctest --preset dev --no-tests=error -R "^startup_(storage_|dstorage_|xcrdapi_)"— 21/21 passed (includingstartup_storage_cancel,startup_storage_cancel_control,startup_storage_worker_start,startup_storage_alloc_failure,startup_storage_refusal_order,startup_storage_failure_counts,startup_xcrdapi_lifetime);tests/startup_stub_check.pyPASS (includingdstorage error recordandstatus-array initial state).ctest --preset release --no-tests=error -R "^startup_(storage_(cancel|worker_start|alloc_failure|refusal_order|failure_counts)|dstorage_destination|xcrdapi_lifetime)"— 10/10 passed;tests/startup_stub_check.pyPASS.tests/docs_links_check.py(40 Markdown files, 555 links) andtests/bidi_controls_check.py(2094 files) both passed.@pigalot on GitHub · 2026-11-27 22:08 UTC · original · approved these changes
I reviewed
c0d2977cmerged over currentmain6cc46a3c. The merge is clean andgit diff --cached --checkis clean.R0Y00's ABI blocker on
ece618ec.main,execute_requestsizes the inflate buffer from+0x34(IntermediateSize), and only when BCPack follows zlib. A zlib-only request inflates toDestinationSize. Nothing reads a size from+0x38.offsetof(StorageRequest, cancellation_tag).dstorage_error_record.hpins that offset at0x38with astatic_assert, so the tag and the decode size no longer overlap.0x1111111100000001and0x222222227FFFFFFF. It checks matching completion and bytes, no error record and bounded commit growth.What I traced.
queue_canceltakessetup_mutexfor the unrecorded list and then, separately,work->mutex. It never holds both, so it can't invert Submit's order.submitted_total/finished_totalcutoffs are unchanged.release_entryandrelease_unrecordednull what they release, so the later release on the normal path is a no-op.What I ran. I did a full build in
devandrelease, then ran27/27 pass in both presets. That includes
startup_storage_cancel, itsWILL_FAILcontrolstartup_storage_cancel_control, andstartup_storage_worker_start.Mutants in
src/startup_stubs/xcrdapi.cpp. For each, I rebuilt indevand ran the same 27 tests:tag_matchesmasksvaluetoostartup_storage_cancel)run_entryignorescancelledstartup_storage_cancel)+0x34instead of+0x38queue_cancelskips the unrecorded liststartup_storage_worker_start)queue_cancelskips the deferred liststartup_storage_worker_start)queue_cancelskipssubmittedstartup_storage_cancel)queue_cancelskipsfailingfollowing_chunk_idsdoesn't stop at a cancelled entryfail_waitingskip removedwaiting, never marked, so the guard can't fireIntermediateSizefrom+0x38(the regression R0Y00 described)Restored and rebuilt afterwards;
git diff --quietis clean.Non-blocking.
+0x34. So the last mutant, which puts back the tag-as-size read, passes every test. The one path that reads a size near the tag is zlib followed by BCPack. A combined zlib+BCPack request whose tag low word is large (0x7FFFFFFF) would pin it, with the same identical-completion and bounded-commit checks.failingbranch is unpinned. This is tedin7's first P3.cancelled_deferred_entriescovers the unrecorded and deferred lists, but not an entry that sits infailingafter an allocation failure.following_chunk_idsstops at a cancelled entry.cancelledcheck infail_waitingis unreachable as written (see the equivalent mutant). Either drop it or add a comment saying why it's kept.Verdict: approve on
c0d2977c. R0Y00's changes request onece618ecstill stands, so the merge waits for R0Y00 to re-check it.Environment: Windows 11 25H2 build 26200.9974; MSVC 19.52.37029; Python 3.12.10. No GPU is involved in these tests.
CI:
Build and test on Windows,Assemble and translate gfx1013 fixturesandRun platform-independent Python checks on Linuxpass onc0d2977c.This reply was AI-assisted.
@JohnConnorNPC on GitHub · 2026-11-28 08:13 UTC · original
Thanks for the cancellation work and for merging
main. I reviewed headc0d2977cagainst currentmain(1f07b2c1):git merge-tree --write-tree 1f07b2c1 c0d2977cexits 0. R0Y00's ABI point is now met, because mergedmainuses+0x34only to size a BCPack decode and the PR reads the tag throughoffsetof(StorageRequest, cancellation_tag), pinned bystatic_assert(... == 0x38). One regression still blocks the merge:following_chunk_ids, the newif (e.cancelled) break;comes beforeif (e_source != source) { continue; }. A cancelled request for another source, placed between a stream's head and its continuation, therefore ends the scan and leavescontinuation_idsempty. My repro queues a gate, A0 (a zlib file head in 2 pieces), B (a memory request), A1 (the continuation), a status and a fence, then cancels B after Submit. With the PR it givesstatus=0x80004005 A0=WRONG A1=WRONG B=untouched, and the piece logssize=0x200b -> zlib failed. With no cancel it givesstatus=0x00000000 A0=ok A1=ok B=copied. With only that line removed it givesstatus=0x00000000 A0=ok A1=ok B=untouched, andstartup_storage_cancelstill passes. Please drop the line. A cancelled id left incontinuation_idsis never consumed, and the worker clearscached_streamsoncesubmittedis empty. Please also add this case to the test, since it is the read-ahead pin that pigalot found missing. R0Y00's changes request still stands, so it needs their re-review after the fix.Also worth fixing:
+0x34read, andout = counters.PagefileUsage;reads the current commit after the fence, when the decode buffer has already been freed. A mutant that sizes a zlib-only inflate from the tag's low word reachesPagefileUsage=2051 MiBduring the decode, yet the test still passes with rc 0 (before=3 MiB after=3 MiB). A zlib+BCPack request with a large tag low word, measured withPeakPagefileUsageor an observable decode size, would pin it. Until then, the docs sentence "pins identical completion, decoded bytes and bounded commit growth" overclaims.failingbranch ofqueue_cancelis unpinned: no case cancels an entry that a failed-allocation Submit left infailing, and pigalot's mutant there survives.100% tests passed out of 41, andgrep -con its log returns0forstartup_storage_canceland0forstartup_storage_worker_start. Please post a Windowsctest --no-tests=error -R '^startup_storage_(cancel(_control)?|worker_start)$' -Vrun on the new head.cancelledcheck infail_waitingis dead code, because waiting entries are compacted out and never marked. Worker_start case C also setse.cancelled = trueonwaitingentries directly, which is a state production code never reaches. TheWILL_FAILcontrol passes on any non-zero exit, includingcannot load XCRDAPI stand-in, soPASS_REGULAR_EXPRESSION "control expected cancelled r1"would pin the reason. The PR body still citesxcrdapi.cpp:519reading+0x38, and its Verification numbers predate the merge.Environment: Linux. I ran a clang-cl 19 cross build (/O2 -MT) of the trial merge with
c3204a9cunder Proton Wine, CPU only, in my own prefix. That merge and the merge with1f07b2c1have byte-identicalxcrdapi.cpp,dstorage_error_record.hand both storage tests (git diff --quietrc 0). This was not an MSVC or Windows run, and I did not run worker_start.This comment was AI-assisted.
View command line instructions
Manual merge helper
Use this merge commit message when completing the merge manually.
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.