Skip to content

D3D12.X: split sparse readback spin and submission out of STATE lock - #2749

Open
Decodere wants to merge 1 commit into
xcl-dev:nvidia-devfrom
Decodere:ws8-part2-sparse-lock-split
Open

Decodere wants to merge 1 commit into
xcl-dev:nvidia-devfrom
Decodere:ws8-part2-sparse-lock-split

Conversation

@Decodere

@Decodere Decodere commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Targets nvidia-dev (eae01502), independent of #2729 and #2768. Splits async sparse readback fence spinning and command recording out of sparse::STATE so submitting threads and allocation/mapping callers no longer stall behind drain_readbacks_spin GPU waits or readback_after_execute D3D12 recording, while preserving eb784bc3 lock-holder timing (XCL_LOOK_STATS=2), 3c1a475a (XCL_SUBMIT_LOCK_FIRST=1), and 4ac75585 (XCL_MIRROR_FILL_MB=1024).

Part of #2688

What is in it

  • crates/xcl/src/hle/d3d12x/sparse.rs:
    • Extract async readback job queues (rb_jobs, imm_jobs, rb_pool, rb_fence, rbq_done, job_seq, submitting, landing) into Arc<SharedReadbacks> (Mutex<ReadbackQueue> + Condvar, reachable without STATE via static READBACKS) and per-queue fence/recording state (dev, rb_queue_fences) into Arc<Mutex<RbSubmit>>, establishing a strict 2-level DAG (STATE -> ReadbackQueue and RbSubmit -> ReadbackQueue) where STATE and RbSubmit never nest and ReadbackQueue is never held across GPU spins, Condvar waits, D3D12 COM calls, or RbJob drops.
    • Keep unpublished async readback plans visible to settling callers from prepare_after_execute (while STATE is still held) until submit_async_readback publishes or cancels via ReadbackQueue::submitting + RAII SubmittingGuard paired with RB_PENDING and SharedReadbacks::published: wait_and_check_ready waits within the caller's existing budget (lock_ms / unbounded) so concurrent fence observers never return early with stale CPU values when an unrelated unfinished readback is already queued, return false if their budget expires before publication, and wake immediately if a plan is dropped/cancelled on error.
    • Move Drain::TitleDone fence spinning (wait_and_check_ready) outside all locks with a single total spin_us deadline across pending title-done copies; skip locking STATE completely when submitting == 0, no job has finished, and landing == 0. Track landing count under STATE -> ReadbackQueue while jobs are popped and landing so concurrent settle_readbacks* callers synchronize on STATE before reading CPU memory while preserving strict ascending seq landing order.
    • Preserve origin/nvidia-dev (eae01502) lock-holder telemetry (holding(Holder::{Submit,After,Settle,ReadbackThread,CpuRead}), HELD, HELD_AFTER_WAIT, behind) and XCL_SUBMIT_LOCK_FIRST=1 priority (lock_for_submit(), FLUSHERS_WAITING, try_lock_giving_way in settle_readbacks_with, and SUBMITS_WAITING yield checks in start_readback_thread) alongside the SharedReadbacks split.
    • Return excess recycled RbJobs above the 32-job pool cap from land_finished_readbacks, before_execute_on, and readback_ranges so callers drop them outside all locks; decrement remaining unlanded jobs in ReadbackQueue::drop so RB_PENDING stays balanced across init re-initialization (with SubmittingGuard holding Arc<SharedReadbacks> so Drop cannot run while a plan is in flight).
    • Split readback_after_execute into a brief STATE snapshot (prepare_after_execute, leaving the rare rbq.is_none() sync fallback intact) followed by submit_async_readback under RbSubmit outside STATE, pushing ImmJob/RbJob entries to ReadbackQueue only after both queue fences are signalled.
    • Add 6 deterministic unit/concurrency tests and a contention micro-bench in sparse::tests: settle_readbacks_waits_for_copy_fence_without_holding_state, settle_readbacks_skips_state_lock_when_no_job_finished (using an mpsc::channel + recv_timeout(500 ms) and always dropping STATE before worker.join() so a blocking regression fails cleanly instead of deadlocking), concurrent_settle_lands_jobs_in_strict_seq_order, readback_after_execute_records_outside_state_lock_and_drops_excess_outside_locks, state_lock_latency_stays_unblocked_under_readback_spin_contention, and settle_waits_for_in_flight_plan_publication_and_handles_cancellation.

Tested

  • Hardware and toolchain: Windows 11 Home (build 26200), NVIDIA GeForce RTX 4060 8 GB (32-lane waves, driver 621.14), Intel Core i5-11400F (6C/12T), 32 GB RAM, rustc 1.100.0, DXC 1.9.2609.5, debug (WARP) and release (RTX 4060), rebased cleanly onto origin/nvidia-dev (eae01502).
  • New lock-split, publication-visibility, and contention tests (cargo test -p xcl --lib -- --test-threads=1 --nocapture ...):
    • Debug (XCL_ADAPTER=warp): 6 passed, 0 failed, 0 ignored (0 skipped, 1.65 s); contention bench (40 spin calls): STATE lock wait p50=1 us, p99=21 us, max=21 us.
    • Release (RTX 4060): 6 passed, 0 failed, 0 ignored (0 skipped, 1.67 s); contention bench (36 spin calls): STATE lock wait p50=0 us, p99=0 us, max=0 us (vs holding STATE across the 2000 us copy-fence spin before).
  • Full sparse unit + reinit tests on release RTX 4060:
    • cargo test --release -p xcl --lib hle::d3d12x::sparse::tests:: -- --test-threads=4 --nocapture (2× consecutive runs, including 3c1a475a's try_lock_giving_way tests): 68 passed, 0 failed, 1 ignored (early_commit_timing, 0 skipped; 3.51 s / 3.55 s; contention bench p50=0 us, p99=0 us, max=0 us on both runs).
    • cargo test --release -p xcl --test sparse_reinit -- --test-threads=1 --nocapture: 1 passed, 0 failed, 0 ignored (0.49 s).
  • cargo clippy --workspace --all-targets: 0 new warnings and 0 new errors across all added/changed lines in crates/xcl/src/hle/d3d12x/sparse.rs (pre-existing nvidia-dev warnings/errors remain on untouched lines including pre-existing missing_safety_doc on readback_after_execute).
  • Live 25 s RTX 4060 smoke with XCL_LOOK_STATS=2 XCL_SUBMIT_LOCK_FIRST=1 on f644a239 (title: 29640639): 518 frames (PresentX 518), 35 60 60 presents/2 s, 0 device removals, 0 crashes, 14726 MB peak commit, exit: 0x0.

Regression run
Quiet 60 s scripts/smoke.ps1 runs on RTX 4060 with default flags (XCL_LOOK_STATS and XCL_SUBMIT_LOCK_FIRST unset). Includes main merge-base (b49be183, same-day run on this hardware) for pr_check.py, nvidia-dev target base (eae01502), and rebased PR HEAD (f644a239):

main (b49be183, merge-base):

xcl-smoke v1
commit: b49be1836844fe0b0cdb3211dce3cb7fb4e21ac7
gpu: NVIDIA GeForce RTX 4060
title: 29640639
seconds: 60
exit: 0x0
frames shown: 1571 (PresentX 1571)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 13975 MB

nvidia-dev (eae01502, target base):

xcl-smoke v1
commit: eae015021c639866ab061cdff2e9daf8ba9daac5
gpu: NVIDIA GeForce RTX 4060
title: 29640639
seconds: 60
exit: 0x0
frames shown: 1585 (PresentX 1585)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 15900 MB

PR HEAD (f644a239, default flags):

xcl-smoke v1
commit: f644a2399247985f4e83aec6ed8b0cc892b3c14c
gpu: NVIDIA GeForce RTX 4060
title: 29640639
seconds: 60
exit: 0x0
frames shown: 1537 (PresentX 1537)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 15289 MB

Not tested

  • Full --workspace test suite on the rebased eae01502 commit (all 6 targeted lock-split tests debug WARP + release RTX 4060, 2× full sparse::tests:: 68/0/1, sparse_reinit, clippy, and smokes ran on f644a239).
  • Heavy in-world retail gameplay with live sparse readback spin contention: the automated no-input 60 s menu/intro smoke on title: 29640639 does not exercise heavy sparse readback contention (those lock-contention and publication-window paths are verified by the 6 unit/concurrency tests and contention micro-bench above).
  • AMD and Intel GPUs, 64-lane wave GPUs, and Linux / Wine / vkd3d-proton.
  • Optional-env/sample-pack tests (XCL_SAMPLE_RPF/XCL_SAMPLE_TTPF/XCL_SAMPLE_AWC unset) and D3D12 debug-layer tests (d3d12SDKLayers.dll not installed).

AI use

  • Google Antigravity (Gemini 4 Neon): designed and implemented the 2-level DAG ReadbackQueue/RbSubmit lock split and SharedReadbacks/SubmittingGuard publication visibility, wrote the 6 concurrency/contention tests, rebased onto origin/nvidia-dev (eae01502) preserving eb784bc3/3c1a475a telemetry and submit-lock priority, ran clippy, unit tests, and the RTX 4060 retail smoke runs on the hardware above, and updated this description.

@luckyteagirl luckyteagirl left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On 88c2045, the new settle_readbacks_skips_state_lock_when_no_job_finished fixture holds iso.state while calling worker.join(), then drops the guard afterward. The current Some(5000) path avoids blocking on that lock, but a future regression to a blocking STATE.lock()—the behavior this fixture is meant to catch—would make the worker and join wait on each other indefinitely. The existing took < 500 ms assertion would never execute, so CI would hang instead of reporting the regression.

Could the worker send its result over a channel, let the main thread use recv_timeout while it holds STATE, then always release the guard before joining and asserting the timed result? That preserves the timing check without detaching a worker that may still use the fixture. This is exact-head source review; I did not deliberately hang the test.

@KDenKC

KDenKC commented Nov 26, 2026

Copy link
Copy Markdown

Source review of 88c20454, no run. A question about one window this opens:

readback_after_execute_with builds the plan under the STATE lock (prepare_after_execute) and drops the lock. Only after that does submit_async_readback record the copies, signal, push the jobs and RB_PENDING.fetch_add(added). On the base, after_execute did the planning and the RB_PENDING increment under one lock. Between the two here, copies of GPU-written ranges are planned but RB_PENDING is still 0. So settle_readbacks / settle_readbacks_within return at their RB_PENDING == 0 fast path, and readback_now skips its wait_and_check_ready and goes straight to its own pass under the lock. It's a short window, but it's on every submit with readbacks.

Is that intended (e.g. readback_now's own pass is always enough there)? If not, counting the planned jobs inside the lock (incrementing RB_PENDING in prepare_after_execute and settling it if submit_async_readback bails, as on its fence-creation return and the take_or_alloc_rb_job break) would keep the old ordering.

Not tested: no build or run of this head on our side.

AI use: Gemini (Antigravity) flagged it in a review. Claude Code (Claude Opus 5.5) read the paths in the diff and wrote this.

@thehollowedone

Copy link
Copy Markdown

Follow-up to KDenKC's publication-gap comment on head 88c2045: incrementing RB_PENDING when the plan is made would not, by itself, make a settling caller wait for that plan to be published. settle_readbacks_with can still return success when wait_and_check_ready sees no finished queued job or active landing.

A schedule that distinguishes this head from its base is: one unrelated, GPU-unfinished readback is already pending; a second submission completes its title fence for an immediate CPU write, then pauses after prepare_after_execute drops STATE and before submit_async_readback publishes the immediate. A concurrent fence observer sees RB_PENDING > 0, finds only the unfinished old job, and can return the completed fence value while the immediate's CPU destination still holds its old value. On the base path, the submitter holds STATE through publication, so an observer that obtains it within its wait budget serializes with that write. The all-zero RB_PENDING fast path existed on base too; it alone does not prove a regression.

Could an unpublished submission remain visible to settling callers until publication or cancellation, with those callers observing that transition within their existing wait budget? A deterministic regression can use barriers to pause publication after the second title fence completes, start the observer with a bounded test timeout, release publication, and assert the CPU value when the observer reports the fence complete. The current contention test starts settling after joining the submitter, so it does not cover this window.

This is a source trace, not a live reproduction. No build or GPU test of #2749 was run for this finding. AI use: Codex (GPT-6.2 Astra) traced the ordering; Codex (GPT-6.2 Sol) checked the current diff and drafted this comment.

@KDenKC

KDenKC commented Nov 26, 2026

Copy link
Copy Markdown

Thanks @thehollowedone, that is the better framing. Counting the plan earlier only changes the zero fast path, which existed on the base too. Your schedule (an older unfinished job pending, an immediate write planned but not yet published, a fence observer settling in between) is the case that actually differs from the base. Keeping an unpublished submission visible to settling callers until it is published or cancelled is the right shape for a fix; my RB_PENDING suggestion alone would not do it.

AI use: Claude Code (Claude Opus 5.5) wrote this.

@MarcosMDev

Copy link
Copy Markdown

Test report: 88c2045 against its base af2cecc on an RTX 4060 (Windows): full suite, no new failure. No title was run.

cargo build --workspace --locked, then cargo test --workspace --locked --no-fail-fast -- --test-threads=4, debug, each commit in its own worktree and target folder:

  • base af2cecc: 1745 passed, 6 failed, 48 ignored
  • head: 1750 passed, 6 failed, 48 ignored. The 5 new sparse::tests pass, the contention bench included.
  • The same 30 SKIPPED lines on both. The failures are the same 5 tests on both (one is counted twice), already listed in this PR's description.

The suite does not cover the publication window @thehollowedone describes above: as they note, the contention test starts settling after the submitter has joined.

RTX 4060 8 GB (driver 621.01), Ryzen 7 5700X, 24 GB, Windows 11 26200, rustc 1.100.0, DXC 1.9.2609.5.

Not tested: any title or smoke run, the sparse path under a real workload, timings, AMD.

AI use: Claude Code (Claude Opus 5.5) ran the tests and drafted this; I read it before posting.

@thehollowedone

Copy link
Copy Markdown

Follow-up to my source review: I reproduced the planned-but-unpublished immediate window on head 88c20454 with a test-only change. The PR head and nvidia-dev base were unchanged when checked.

The test leaves an older readback unfinished, prepares a second immediate write under STATE, and pauses its submission on a channel. After a title-visible fence completes, settle_readbacks_with(..., Drain::TitleDone, ..., Some(0)) reports success even though the immediate is neither published nor present in CPU memory. The test then releases submission, lands both jobs, verifies the destination value and RB_PENDING == 0, and fails only on the early-success assertion. The channels keep publication paused during the observation; there is no timing sleep.

On Windows 11 build 26300, RTX 3080 Ti (driver 621.35), Ryzen 7 9800X3D, rustc 1.99.1 MSVC:

  • cargo test --offline --locked -p xcl --lib a_planned_immediate_is_visible_to_a_concurrent_fence_observer -- --nocapture --test-threads=1: 0 passed, 1 failed, 0 ignored, 0 GPU skips, with observer reported success before the planned immediate was published. Repeated in a separate process with the same result.
  • cargo test --offline --locked -p xcl --lib readback_after_execute_records_outside_state_lock_and_drops_excess_outside_locks -- --nocapture --test-threads=1: 1 passed, 0 failed, 0 ignored, 0 GPU skips.

A fix needs the planned submission to remain visible until it is published or cancelled, and the settling caller to observe that transition within its wait budget. Merely incrementing RB_PENDING at planning does not make wait_and_check_ready see an unpublished plan. The regression below is offered as a starting point; it does not validate a production fix or prove a retail-title failure.

Test-only regression diff
@@ -7523,6 +7523,72 @@ mod tests {
         }
     }
 
+    /// A fence observer must not report settled while an immediate has been planned but has not
+    /// yet been published to the readback queue. An older unfinished job keeps RB_PENDING nonzero.
+    #[test]
+    fn a_planned_immediate_is_visible_to_a_concurrent_fence_observer() {
+        unsafe {
+            let iso = IsolatedAsyncState::new();
+            let title: ID3D12CommandQueue = iso.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue");
+            let old_title: ID3D12Fence = iso.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("old title fence");
+            let old_done: ID3D12Fence = iso.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("old copy fence");
+            let mut old = iso.make_job(0xAB, 64, old_title.clone(), old_done.clone(), 1, 1);
+            {
+                let mut rq = iso.rb.lock().unwrap();
+                rq.job_seq += 1;
+                old.seq = rq.job_seq;
+                rq.rb_jobs.push_back(old);
+            }
+            RB_PENDING.fetch_add(1, Ordering::Release);
+
+            let dst = iso.base + 0x800;
+            let value = 0xCAFE_BABE_1234_5678u64;
+            let state = Arc::clone(&iso.state);
+            let q_send = SendQueue(title.clone());
+            let (ready_tx, ready_rx) = std::sync::mpsc::channel();
+            let (release_tx, release_rx) = std::sync::mpsc::channel();
+            let submitter = std::thread::spawn(move || {
+                let (plan, excess) = {
+                    let mut g = state.lock().unwrap();
+                    let s = g.as_mut().unwrap();
+                    s.note_queue(&q_send.0);
+                    s.prepare_after_execute(&q_send.0, &[], &[(dst, value, 8)])
+                };
+                drop(excess);
+                ready_tx.send(()).unwrap();
+                release_rx.recv().unwrap();
+                submit_async_readback(&q_send.0, plan.expect("planned immediate"));
+            });
+            ready_rx.recv_timeout(std::time::Duration::from_secs(5)).expect("plan prepared");
+            assert_eq!(std::ptr::read_volatile(dst as *const u64), 0);
+            // Model the title fence that the real fence observer has already seen.
+            let title_visible: ID3D12Fence = iso.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("title-visible fence");
+            title.Signal(&title_visible, 1).expect("signal title-visible fence");
+            let t0 = std::time::Instant::now();
+            while super::super::real::fence_completed(&title_visible) < 1 {
+                assert!(t0.elapsed() < std::time::Duration::from_secs(5), "title fence did not complete");
+                std::thread::yield_now();
+            }
+
+            let early = settle_readbacks_with(&iso.state, &iso.rb, Drain::TitleDone, 300, Some(0));
+            release_tx.send(()).unwrap();
+            submitter.join().unwrap();
+
+            let t1 = std::time::Instant::now();
+            while std::ptr::read_volatile(dst as *const u64) != value {
+                assert!(settle_readbacks_with(&iso.state, &iso.rb, Drain::TitleDone, 2000, None));
+                assert!(t1.elapsed() < std::time::Duration::from_secs(5), "immediate did not land");
+                std::thread::yield_now();
+            }
+            old_title.Signal(1).unwrap();
+            old_done.Signal(1).unwrap();
+            assert!(settle_readbacks_with(&iso.state, &iso.rb, Drain::TitleDone, 2000, None));
+            assert_eq!(std::ptr::read_volatile(dst as *const u64), value);
+            assert_eq!(RB_PENDING.load(Ordering::Acquire), 0, "all test jobs were landed");
+            assert!(!early, "observer reported success before the planned immediate was published");
+        }
+    }
+
     /// `readback_after_execute_with` releases `STATE` before acquiring `RB_SUBMIT` and recording
     /// D3D12 copy commands, and `land_finished_readbacks` returns excess `RbJob`s beyond the 32-job
     /// pool cap so callers drop them outside all locks.

AI use: Codex (GPT-6.2 Sol) wrote and ran the regression and drafted this report; Codex (GPT-6.2 Astra) reviewed the publication/cancellation design.

@Decodere
Decodere force-pushed the ws8-part2-sparse-lock-split branch from 88c2045 to 9cfa753 Compare November 26, 2026 11:29
@Decodere

Copy link
Copy Markdown
Contributor Author

Thanks @luckyteagirl, @KDenKC, and @thehollowedone! Addressed all points in 9cfa7536:

  1. Non-deadlocking settle_readbacks_skips_state_lock_when_no_job_finished (@luckyteagirl): The worker now reports ok over an mpsc::channel; the main thread waits with rx.recv_timeout(500 ms) while holding STATE, always drops the STATE guard before worker.join().unwrap(), and then asserts the timed result so a blocking-lock regression fails cleanly instead of hanging CI.
  2. In-flight publication visibility (@KDenKC / @thehollowedone): Wrapped Mutex<ReadbackQueue> with a Condvar (SharedReadbacks) and added ReadbackQueue::submitting plus an RAII SubmittingGuard acquired in prepare_after_execute while STATE is still held (keeping RB_PENDING elevated until publication or cancellation, and holding Arc<SharedReadbacks> so ReadbackQueue::drop cannot run early). submit_async_readback atomically publishes jobs, decrements submitting, adjusts RB_PENDING, and notifies published (and SubmittingGuard::drop cancels and notifies on any bail/error). wait_and_check_ready waits outside STATE on published while submitting > 0 within the caller's existing wait budget (lock_ms / unbounded), returning false from settle_readbacks_with if the budget expires before publication (including Some(0) while submitting > 0).
  3. Regression test: Added settle_waits_for_in_flight_plan_publication_and_handles_cancellation reproducing the exact schedule (unrelated unfinished readback pending, immediate plan paused after STATE drops and GPU title fence completes, bounded timeout returning false, observer waiting for publication and asserting the landed CPU immediate immediately upon returning true, plus plan-drop cancellation wakeup).

Re-verified all 6 lock-split/publication/contention tests on debug WARP (6/6, p99=2 us) and release RTX 4060 (6/6, p50=p99=max=0 us), full sparse::tests:: (66/0/1), sparse_reinit (1/0/0), full release workspace (1753 passed, 3 pre-existing nvidia-dev failures), and 60 s RTX 4060 smokes (default + XCL_LOOK_STATS=2).

@MarcosMDev

Copy link
Copy Markdown

Follow-up to my report, on the new head 9cfa753 (same base af2cecc, same RTX 4060 and setup):

  • Full suite, same command: 1751 passed, 6 failed, 48 ignored. The same 5 base failures and the same 30 SKIPPED lines as on the base; the 6 new sparse::tests pass, settle_waits_for_in_flight_plan_publication_and_handles_cancellation included.
  • cargo test -p xcl --lib hle::d3d12x::sparse::tests -- --test-threads=4, 20 times in a row: 66 passed, 0 failed every time, no hang.

Not tested: any title or smoke run, timings, AMD.

AI use: Claude Code (Claude Opus 5.5) ran the tests and drafted this; I read it before posting.

@thehollowedone

Copy link
Copy Markdown

Independent RTX 3080 Ti recheck of #2749 head 9cfa7536 against its exact nvidia-dev base af2cecc4. The PR head was unchanged when checked before posting. Windows 11 build 26300, RTX 3080 Ti 12 GiB / NVIDIA 621.35, rustc 1.99.1 MSVC, debug builds. Separate clean source archives and target directories, synthetic tests only.

Both revisions passed cargo build --offline --locked --workspace, then ran cargo test --offline --locked --workspace --no-fail-fast -- --test-threads=4:

revision passed failed ignored GPU SKIPPED notices
base af2cecc4 1,744 7 48 26
head 9cfa7536 1,750 7 48 26

The six distinct failing test names are identical on base and head; two_pass_driver_cache_reuses_both_passes_and_recovers_corrupt_blobs is counted twice. The others are console_mesh_caches_hlsl_compute_pass_in_memory_and_on_disk, pieces_hold_the_texels_of_their_levels, gpu_parts_of_a_texture_go_up_and_the_rest_stays, console_ms_in_as_slot_and_ms_with_as_are_refused_cleanly, and async_compute_pso_registers_real_pso_and_not_standin. The two texture-upload failures both panic on a debug multiplication overflow at texture_upload.rs:1002 on both revisions. This paired run found no additional failure on the head; it is not a whole-suite pass. GPU skips are not coverage.

On the head, cargo test --offline --locked -p xcl --lib hle::d3d12x::sparse::tests:: -- --test-threads=4 passed 66, failed 0, ignored 1, with 0 GPU skips. The new settle_waits_for_in_flight_plan_publication_and_handles_cancellation regression also passed alone (1/0/0) using cargo test --offline --locked -p xcl --lib settle_waits_for_in_flight_plan_publication_and_handles_cancellation -- --nocapture --test-threads=1. I reviewed the new reservation and publication path against my earlier reproducer and found that the original planned-but-unpublished window is closed.

Not tested: a retail title, paired clean-commit smoke, sustained in-world readback traffic, AMD/Intel, or a performance improvement under real contention. The tests establish Ampere coverage for the fix, not a merge-readiness or runtime-speed claim.

AI use: Codex (GPT-6.2 Sol) ran the paired Windows tests and wrote this report; Codex (GPT-6.2 Astra) reviewed the low-level publication path.

@Prime1997 Prime1997 mentioned this pull request Nov 26, 2026
@throny

throny commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

Test report: in the world on an RTX 4080 16 GB (the case under "Not tested"). Three back-to-back runs of the retail title of #505 into the world, two with this PR and one without, same warm caches.

Tested

run tree time in the world presents submits draws dispatches end
13 with this PR 251 s 40 799 76,090 172,294 device removed 0x887a0005 at 423 s
14 base 98 s 23 435 28,916 76,829 device removed 0x887a0005 at 269 s
15 with this PR 747 s 152 2,968 295,016 802,835 ran to the 900 s limit, no removal
  • No crash, no deadlock, no GPU wait timeout and no nvlddmkm event in the two runs with the PR; 2 × 250–750 s of world submits went through the new path.
  • Earlier base runs of this card on the same tree (same day, in [OFFICIAL] Swarm: RAM and VRAM use down, towards stable 30 FPS on AMD and NVIDIA #2688): removed after 303 s, 148 s and 97 s of world, so 4 of 4 base world runs lost the device and none got past 303 s. With the PR: 251 s and 747 s+. That is 2 runs against 4, on a card that sits 3–4 GB over its video memory budget in the world (18.8–19.4 GB in use of a 15.2 GB budget in all three), so I would not call it a fix for the removal: only that it is not worse and that the longest world run this card has had is with it.
  • Throughput is the same order with and without: 0.16 and 0.20 presents/s with, 0.23 without; 3.2–4.0 submits/s with, 4.4 without. The window of the base run is short (98 s), so that difference is inside the noise here.
  • submit cost lines in the world (run 15, at 494 s and 784 s): "refresh lock wait 0.00 ms", "sparse lock 0.01–0.02 ms" of 1.9–4.7 ms refresh per submit. The lines also show 177 and 208 ms "in all" per ExecuteCommandLists of which the listed parts explain under 5 ms; that remainder is what D3D12.X: instrument submitting-thread call breakdown under XCL_LOOK_STATS=2 #2729 is for, not this PR.

Not tested

  • This PR's own tests and the suite (covered by the other reports), AMD, a card that is not over its budget in the world. No sparse readback counters were logged in these runs, so I can't say how often the split path was actually contended.

AI use: Claude Code (Claude Fable 5.2) ran this on the owner's machine and wrote the report.

Previously, `sparse::drain_readbacks_spin` held the global `STATE` mutex across up to 300-2000 us of GPU fence spinning per pending readback job and dropped excess recycled `RbJob`s above the 32-job pool cap while holding `STATE`, `settle_readbacks_within` and `start_readback_thread` contended on `STATE` even when no readback had finished, and `readback_after_execute` held `STATE` across D3D12 `CreateFence`/`CreateCommandAllocator`/`CreateCommandList`/`CreateCommittedResource`/`Map`/`Reset`/`CopyBufferRegion`/`Close`/`pc_execute`/`Signal`.

- Split async readback queues and staging pool into a pure leaf `ReadbackQueue` wrapped in `SharedReadbacks` (`Mutex<ReadbackQueue>` + `Condvar`, reachable via `READBACKS`) and per-queue fence/recording state into `RbSubmit` (`Arc<Mutex<RbSubmit>>`), forming a strict 2-level DAG (`STATE -> ReadbackQueue` and `RbSubmit -> ReadbackQueue`) where `STATE` and `RbSubmit` never nest and `ReadbackQueue` is never held across GPU spins, `Condvar` waits, D3D12 COM calls, or `RbJob` drops.
- Keep unpublished async readback plans visible to settling callers from `prepare_after_execute` (while `STATE` is still held) until `submit_async_readback` publishes or cancels via `ReadbackQueue::submitting` + RAII `SubmittingGuard` paired with `RB_PENDING` and `SharedReadbacks::published`: `wait_and_check_ready` waits within the caller's existing budget (`lock_ms` / unbounded) so concurrent fence observers never return early with stale CPU values when an unrelated unfinished readback is already pending, return `false` if their budget expires before publication, and wake cleanly on cancellation.
- Move `Drain::TitleDone` fence spinning in `settle_readbacks` / `settle_readbacks_within` / `readback_now` completely outside all locks with a single total `spin_us` deadline; skip locking `STATE` entirely when no submission is publishing, no job has finished, and none is mid-landing (`landing == 0`), while preserving strict ascending `seq` order and visibility synchronization under `STATE` when landing finished `imm_jobs` and `rb_jobs`.
- Return excess recycled `RbJob`s above cap 32 from `land_finished_readbacks`, `before_execute_on`, and `readback_ranges` so callers drop them outside all locks; decrement remaining pending jobs in `ReadbackQueue::drop` so `RB_PENDING` stays balanced across `init` re-initialization.
- Gate `start_readback_thread` on `RB_PENDING != 0` and a leaf `READBACKS` check (`has_unpopped_finished_jobs`) before trying `STATE`.
- Split `readback_after_execute` into a brief `STATE` snapshot (`prepare_after_execute`, leaving the rare `rbq.is_none()` sync fallback intact) followed by `submit_async_readback` under `RbSubmit` outside `STATE`, pushing jobs to `ReadbackQueue` only after both queue fences are signalled.
- Add 6 deterministic concurrency/lock-split tests and a contention micro-bench in `sparse::tests` covering zero-lock GPU fence wait, non-deadlocking bounded `recv_timeout` skip-`STATE` regression guard when unfinished, concurrent strict-`seq` landing + `landing > 0` visibility, recording and dropping excess `RbJob`s outside `STATE`, `STATE` lock latency under spin contention, and paused-publication / bounded-timeout / plan-cancellation visibility.

Part of xcl-dev#2688
Assisted-by: Google Antigravity (Gemini 4 Neon)
@Decodere
Decodere force-pushed the ws8-part2-sparse-lock-split branch from 9cfa753 to f644a23 Compare November 26, 2026 18:02
@Decodere

Copy link
Copy Markdown
Contributor Author

Rebased cleanly onto origin/nvidia-dev eae01502 in f644a239 (mergeable, 0 conflicts).

  • Preserved eb784bc3 lock-holder timing, 3c1a475a (XCL_SUBMIT_LOCK_FIRST=1 via lock_for_submit/try_lock_giving_way/SUBMITS_WAITING), 986b44a3, and 4ac75585 alongside the strict 2-level STATE -> SharedReadbacks lock split and rq.submitting + Condvar + RAII SubmittingGuard publication barrier.
  • Re-verified on RTX 4060 (Win11, release): debug WARP (p99=21 us) & release targeted 6/0/0, 2x sparse::tests:: 68/0/1 (0 skipped, p50=p99=max=0 us), sparse_reinit 1/0/0, 0 new clippy warnings, paired 60 s default smoke vs eae01502 (1537 vs 1585 frames, 60 60 60, 15289 vs 15900 MB, 0 rem/crash), and 25 s XCL_LOOK_STATS=2 XCL_SUBMIT_LOCK_FIRST=1 smoke (518 frames, exit: 0x0).

@thehollowedone

Copy link
Copy Markdown

Independent Windows/NVIDIA check of the rebased #2749 head f644a239 against its exact nvidia-dev base eae01502.

On Windows 11 build 26300, Ryzen 7 9800X3D, RTX 3080 Ti (621.35, 12 GiB), rustc 1.99.1:

Command Base PR head
cargo test --offline --locked -p xcl --lib mid_list_write64_wait64_split_avoids_cycle_and_reuses_spares -- --test-threads=1 --nocapture 1 passed, 0 failed 1 passed, 0 failed
cargo test --offline --locked -p xcl --lib hle::d3d12x::list_x::tests:: -- --test-threads=4 not run 50 passed, 0 failed, 0 ignored
cargo test --offline --locked --workspace --no-fail-fast -- --test-threads=4 1,815 passed, 10 failed, 48 ignored; 26 GPU skip notices 1,821 passed, 10 failed, 48 ignored; 26 GPU skip notices

The ten full-suite failures were the same on both revisions in this setup. The head's six additional tests passed. The CI-named mid_list_write64_wait64_split_avoids_cycle_and_reuses_spares failure did not reproduce here, including in the four-thread full head run. This does not explain or clear the CI failure. The 26 skip notices include wave64/refused shader cases and the opt-in heap-window test; they are not GPU coverage.

Not tested: AMD/Intel, a retail smoke on this revision, or a repeat of the CI environment. AI use: Codex (GPT-6.2 Sol) selected the matched commands, ran them, compared the logs, and wrote this report. I checked each reported result against the output.

@MarcosMDev

Copy link
Copy Markdown

Follow-up on the rebased head f644a23 against its new base eae0150 (same RTX 4060 and setup as my report): no new failure.

  • Full suite, cargo test --workspace --locked --no-fail-fast -- --test-threads=4: base 1816 passed, 9 failed, 48 ignored; head 1822 passed, 9 failed, 48 ignored. The same 7 tests fail on both (split_compute_prefers_the_offline_whole_pipeline and the two-pass one count twice), and the same 30 SKIPPED lines.
  • cargo test -p xcl --lib hle::d3d12x::sparse, 10 runs each, as the rebase now goes through XCL_SUBMIT_LOCK_FIRST: with it unset, base 62 passed and head 68 passed every time; with XCL_SUBMIT_LOCK_FIRST=1, the same. No failure in any run.

Not tested: any title, so nothing on how XCL_SUBMIT_LOCK_FIRST=1 and the split behave together in a real run; AMD.

AI use: Claude Code (Claude Opus 5.5) ran the tests and drafted this; I read it before posting.

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.

6 participants