Skip to content

D3D12.X: waits for the sparse queue do not hold the sparse state's lock - #1385

Open
MacieGx wants to merge 1 commit into
xcl-dev:mainfrom
MacieGx:d3d12x/sparse-unlocked-waits
Open

MacieGx wants to merge 1 commit into
xcl-dev:mainfrom
MacieGx:d3d12x/sparse-unlocked-waits

Conversation

@MacieGx

@MacieGx MacieGx commented Nov 24, 2026 •

Copy link
Copy Markdown

Two title threads waited on the CPU for XCL's sparse queue while holding the sparse state's mutex: a Map for its copy back, and a submit for room in the upload ring. While the GPU stood still, so did every other thread that needed the lock: commits and decommits, the next Map, the next submit, the activity line. This makes those waits with the lock released. Part of #505.

In the newer retail title (#505) on an RTX 5080, with bounded pipeline waits (XCL_PSO_WAIT_MS=50) and A pressed at 20 s, thread dumps taken while its frames had stopped (on 67a3735 + #433 + #968) showed the two waits above holding the lock for 15 s and more, with a thread moving physical pages and the next Map standing at it. With this change the "sparse: the queue has not reached fence value" lines are gone in the runs below and the title runs about 60–70 s longer before its watchdog ends it. It still ends there: the title's GPU queues waiting on each other (the queue.Wait … released on CPU lines) are not changed by this.

What is in it

  • crates/xcl/src/hle/d3d12x/sparse.rs:
    • wait_released: the wait for the sparse queue's fence (5 s at most, as before) with STATE released; the state is looked at again after it.
    • upload_room / room_released: before each part of the uploads, the two command slots and the ring are checked and waited for with the lock released. before_execute and readback_now upload a part at a time, each as large as the ring has room for, scanned and uploaded in one hold of the lock. The waits inside begin_slot and upload_dirty stay as they are and are not met any more.
    • readback_released: a copy back (readback_now, readback_after_execute) is submitted (readback_submit), waited for with the lock released, then copied into the pages still committed (copy_back, taken out of readback_ranges). READBACK keeps the one readback buffer to one copy at a time; it is taken before STATE.
    • Behaviour that changes: a copy back the queue has not made after 5 s leaves the CPU's view as it is. Before, the readback buffer was copied into it without the copy in it.
    • Behaviour that does not: a submit still waits until the ring has room, with the same warning every 5 s. No upload is dropped.
  • crates/xcl/tests/sparse_lock_released.rs: the sparse queue is held by a fence. (1) A thread maps 8 bytes the GPU wrote; (2) a thread submits 96 MiB of CPU writes, more than the ring holds. In both, a commit and a submit on another thread must be through within 2 s; then the Map must return the GPU's bytes and the first and last 8 bytes of the 96 MiB must be in video memory.
  • 414 lines added and 97 removed (157 of them the test). It can be split in two if that reviews better: the copy back (Map), then the uploads (submit).

Other open PRs on the same lock:

Tested

  • NVIDIA GeForce RTX 5080 (driver 621.24 = 32.0.16.2124), AMD Ryzen 7 5800X3D, 32 GB, Windows 11 Pro 10.0.26200, Rust 1.100.0 stable-x86_64-pc-windows-msvc, release. On 875a603 (this PR rebased onto main 06c9f55).

  • cargo test --release -p xcl --test sparse_lock_released (before the rebases, on 930e8b4):

    • main (930e8b4) with only the test added: 0 passed, 1 failed after 5.6 s ("through within 2 s – behind a Map: false, behind a submit: false");
    • with the change: 1 passed, 0 failed (4 runs).
  • On 875a603: cargo test --release -p xcl --test sparse_lock_released: 1 passed, 0 failed, 0 ignored.

  • cargo test --release -p xcl --lib sparse -- --test-threads=4: 24 passed, 0 failed, 1 ignored.

  • cargo build --release --workspace && cargo test --release --workspace --no-fail-fast -- --test-threads=4 on 875a603: 1262 passed, 4 failed, 46 ignored. The 4 failures are gpu::dxil::fuzz_tests::fuzz_validate_and_gpu_0..3 (CreateComputePipelineState: E_OUTOFMEMORY), which fail the same way on main on this machine. (Earlier: 761 / 0 / 41 on 0012965, 752 / 0 / 41 on 22dd7d0.)

  • SKIPPED (26 lines): no wave64 in dispatch_chain_native_wave64_builds_whole, gpu_wave32_program_in_wave64_hardware, gpu_geometry_wave32_prefix_count_over_a_mask, four recomp::lower::tests::*_agree_with_the_hlsl_path_on_the_gpu, and the wave64 cases of recomp::lower_dxil::tests (a_per_lane_2d_or_3d_group_runs_on_the_gpu, const_and_null_mask_operands…, f16/f32/f64/integer_programs_on_the_gpu, mask_ff0_and_flbit…); three wave32 per-lane cases of f16/f32_programs_on_the_gpu refused (V_MUL_F16, V_PK_MUL_F16, V_CVT_F16_F32, gpu: direct RDNA2 -> DXIL backend (no HLSL / DXC), behind XCL_DIRECT_DXIL #1426); heap_window_out_of_memory_falls_back_to_the_switch_form (no heap windows); pso_measurement_compiles_an_exact_synthetic_record (driver cache cannot be disabled without Developer Mode).

  • The newer retail title (Newer retail title (TitleID 7952987A): reaches world loading, then the title's GPU watchdog ("GPU Loc Sig") after ListX #101 stub #505), release, XCL_NETWORK=0 XCL_ACTIVITY=1 XCL_PSO_WAIT_MS=50 XCL_PRESS_AT=20:A XCL_RUN_SECONDS=300, warm DXIL and driver caches, counts from xcl.log:

    build run ends at last 2 s with a present "sparse: the queue has not reached …" lines
    main 930e8b4 1 163 s, access violation at +0x4684e7 – 0
    main 930e8b4 2 180 s, watchdog (+0x23cf683) 146 s 6
    this PR (22dd7d0, before the rebase) 2 253 s, watchdog 224 s 0
    this PR (22dd7d0, before the rebase) 3 242 s, watchdog 216 s 0

    This PR's run 1 is left out: the scripted A was not taken (no GameInput line), so it stayed on the title screen. Earlier the same day, on 67a3735 + D3D12.X: sparse readbacks don't wait for a queue held by a later signal #433 + D3D12.X: the late-release drain gets the sparse queue without the sparse state's lock #968: without this change 3–9 such lines in each of 4 runs, ending at 168–176 s; with it 0–1 lines, ending at 164 s and 262 s. These are few runs and the title's runs vary a lot; the stall lines are the clear difference.

Regression run

main:

xcl-smoke v1
commit: 568e7db7729c8fa6c8f0f4b32d798faaf11462bb
gpu: NVIDIA GeForce RTX 5080
title: 16b5e5d4
seconds: 60
exit: 0x0
frames shown: 1383 (PresentX 1383)
presents per 2 s (last 3): 35 52 56
device removals: 0
crashes: 0
peak commit: 19703 MB

this PR:

xcl-smoke v1
commit: 875a60352ed34f11f4c4751ed6a740927533366b
gpu: NVIDIA GeForce RTX 5080
title: 16b5e5d4
seconds: 60
exit: 0x0
frames shown: 1552 (PresentX 1552)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 15544 MB

Not tested

  • AMD and Intel GPUs; a debug build.
  • Why the sparse queue stands still in the newer retail title (Newer retail title (TitleID 7952987A): reaches world loading, then the title's GPU watchdog ("GPU Loc Sig") after ListX #101 stub #505). This PR does not change that: if the GPU does not go on, a submit still waits for the ring and frames still stop. It only keeps the title's other threads from standing at the lock meanwhile.
  • A second submitting thread still waits behind the first: title_textures::refresh holds its own lock (REFRESH) around before_execute.
  • UpdateTileMappings and CreateHeap are still called with the lock held.
  • Other threads now get the lock between the parts of a large upload and while a copy back is waited for. A copy back can then overwrite a CPU write another thread made to the same bytes in between; a title thread's own write could already do that, and D3D12.X: sparse readbacks don't wait for a queue held by a later signal #433's worker has the same window. No test covers it.
  • The upload timing line: with more than one part, the time of the earlier parts' uploads and waits is counted under "chunk scan".

AI use

  • Claude Code. Claude Opus 5.5 read the logs and the symbolized thread dumps, ran the game and the tests, reviewed the change and wrote parts of this description. A Claude Fable 5.2 subagent wrote the change, its test and the first draft of the commit message and this description.

🤖 Generated with Claude Code

@jacksonslab

jacksonslab commented Nov 24, 2026 •

Copy link
Copy Markdown

Test report for the open point in the description: this port (22dd7d0) run together with #433 (19004e1).

Tree: main b8b1f49 + #433 + this PR, plus unrelated local merges (#759 stack, #1288, #1315/#1316). Release build, RTX 4070 SUPER 12 GB, i7-14700K, Windows 11 26200.

Merge: two conflicts in sparse.rs, both in the parts the description names.

Tests on the merged tree:

  • cargo test --release -p xcl --test sparse_lock_released --test sparse_readback_waits --test sparse_readback_lands: 1 passed each, 0 failed.
  • cargo test --release -p xcl --lib -- sparse --test-threads=1: 16 passed, 0 failed, 1 ignored.

Retail title (edit): two runs of retail 1.0.2.1 on this combination, Series X profile, on the same tree plus later local merges (#1288, #1422, #1429, #1284 and local diagnostics), so they say little about this PR alone:

  • 1,200 s run with every bind waiting for its pipeline: no sparse: the queue has not reached fence value line, no device removal, no crash; peak local video memory 9,854 MB. The title sat in pipeline compiles for most of it.
  • 311 s run with bounded pipeline waits (XCL_PSO_WAIT_MS=50): 3 has not reached fence value lines, then 0x887a0006 (device hung). 4,178 dispatches had been skipped by then, which I take to be the cause, not this PR; I have not shown that.

Not tested: the whole suite, AMD.

AI use: Claude Code (Claude Opus 5.5) did the merge, ran the tests and wrote this report.

@MacieGx
MacieGx marked this pull request as ready for review November 24, 2026 15:51
@MacieGx
MacieGx force-pushed the d3d12x/sparse-unlocked-waits branch from 22dd7d0 to 0012965 Compare November 24, 2026 16:01
@DavidM1911

Copy link
Copy Markdown
Contributor

Verification on RTX 3060 Ti (Windows 11), branch merged with current main:

  • cargo test -p xcl --lib: all passed, 0 failed, ~21 ignored.

Thanks!

@WebIdentity1

WebIdentity1 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Integration follow-up: the exact PR diff applies cleanly to main 9e3831e, but one depth/stencil command-list close failure in the first integrated full run remains unexplained. Subsequent focused/repeated library tests pass that case; I am not calling the integration clean. Details below.

Readback follow-up on the same exact head 0012965: direct production readback_now preserves a newer4KiB CPU page when the real64MiB upload ring is blocked. It returns after5007ms on RTX3090 /5014ms on AMD integrated; after releasing the queue, an explicit same-page retry produces all1,024correct GPU words. Each adapter:1passed/0failed/0ignored, no skips/timeouts/device-removal errors, fresh Windows Session0 process. Command: cargo test --locked -p xcl --lib timed_out_readback_preserves_unsent_cpu_bytes -- --test-threads=1 --show-output --nocapture, with the respective XCL_ADAPTER; same environment below,227source hashes verified before/after.

The identical fixture on #1495 overwrites all1,024CPU words with old GPU data on both adapters, while its exact parent preserves them. Complete six-run comparison and fixture. This adds readback-timeout preservation evidence; it does not test the Map ABI, concurrent CPU writes during readback, or resolve the separate integration failure above. Codex (GPT-6) wrote and ran the synthetic fixture and prepared this report. No runtime change or competing PR.

Independent native Windows validation of 0012965eda27e2a528b02c8722a415bde3c02788 against its exact parent 17216a14638659e550b76e3e8245728209b86b70: other threads make progress during the wait, and the delayed upload's bytes are preserved, on both RTX3090 and AMD integrated Graphics.

This supports the approach already implemented here for the dropped-upload risk you identified in #1277. I reproduced that risk on exact heads of #1277 and #1495; those reports use their own exact-parent controls.

Tested
Each entry is one fresh-process run; counts are passed / failed / ignored.

Test GPU Exact parent + fixtures Head + fixtures
Existing sparse_lock_released RTX3090 0 /1 /0 1 /0 /0
Existing sparse_lock_released AMD integrated 0 /1 /0 1 /0 /0
Additional delayed-byte recovery RTX3090 1 /0 /0 1 /0 /0
Additional delayed-byte recovery AMD integrated 1 /0 /0 1 /0 /0

No skips or harness timeouts. Parent lock tests exit101 with both behind a Map: false, behind a submit: false; the head tests exit0 and meet the existing two-second progress assertion. Head also passes the original GPU-byte and pending-submit assertions. The only edit to that existing test selects and prints the requested adapter; assertions/timing are unchanged. Parent has the same test copied in.

The additional diagnostic uses the same readback oracle as the #1277/#1495 checks: old0x11 bytes, one4KiB page changed to0x22, a queue held across its five-second warning, then six-second recovery. All1,024GPU words match on both parent and head. Head waits6018ms (3090) /6011ms (AMD); parent6012ms /6018ms. Ring write position advances67108864→67112960, and a same-page retry preserves the correct bytes. Queue drain and device-removal checks pass.

Fixture adaptation: this PR reserves a page of upload-admission headroom, so the earlier fixture's first64MiB before_execute would itself wait. Here I flush initial zeros, seed the tested page's sent hashes through production scan_page, and prime the real64MiB ring through production State::upload_dirty behind the gate. The changed page then goes through production before_execute. No ring-counter injection or simulated wait result. Both parent/head use that identical adapted fixture. The separate existing integration test still exercises before_execute with96MiB, including its first/last8byte checks.

Commands, each with XCL_ADAPTER=3090 or AMD:

cargo test --locked -p xcl --test sparse_lock_released a_wait_for_the_sparse_queue_does_not_hold_the_state -- --test-threads=1 --show-output --nocapture
cargo test --locked -p xcl --lib timed_out_sparse_upload_retries_unsent_bytes -- --test-threads=1 --show-output --nocapture

Windows10 Home19045; Ryzen7 7800X3D; RTX3090 driver591.74 / AMD Radeon integrated32.0.21030.2001; Rust1.98.1 MSVC, Agility1.620.2, debug, SSH Session0. This adds the previously untested AMD/debug coverage for these cases. All227source hashes match each tree; head restored and reverified afterward. Local patch reverse-apply and diff checks pass.

Integration with main after #680 (separate trees, original author diff only)

Main: 9e3831e1f570d3646e53ab753b19ec07eb8f1485. Candidate: that exact revision plus the unchanged diff 17216a1..0012965, applied cleanly; only sparse.rs and this PR's original sparse_lock_released.rs differ. No recovery probe or adapter-selection modifications in these trees. Diff SHA256: 1da64539111fbc6d1c61cd7feb07d029f57949592364c757bbe91ec08e122449. No source push/rebase of the author's branch.

Native interactive Session1, same hardware/toolchain, XCL_ADAPTER=3090, XCL_REQUIRE_GPU=mesh, no heap-window opt-in override for the full pair:

cargo build --locked --workspace
cargo test --locked --workspace --no-fail-fast -- --test-threads=4 --show-output
Full workspace Build exit passed / failed / ignored
main9e3831e 0 774 /2 /41
main + PR1385 0 774 /3 /41

Both test commands exit101; no timeout. Both have four explicit skips: native-wave64 reference tests gpu_geometry_wave32_prefix_count_over_a_mask and gpu_wave32_program_in_wave64_hardware, plus debug-layer tests test_title_draws_with_a_root_signature_under_the_debug_layer and uploads_start_from_each_subresources_state. Sample inputs are unset and system XGameRuntime-dependent early returns are not coverage. Some original fixtures choose the default adapter themselves, so the entire suite is not claimed to execute exclusively on3090.

Both share the known integer-CLAMP failure and a newly merged configuration-sensitive failure: heap_window_out_of_memory_falls_back_to_the_switch_form calls skip_test("no heap windows") without the opt-in, which XCL_REQUIRE_GPU=mesh makes an error. With XCL_HEAP_WINDOWS=1, a separate fresh-process cargo test --locked -p xcl --test gpu_compute_e2e -- --test-threads=1 --show-output --nocapture passes 4 /0 /0 on each tree, no skips/timeouts. Logs identify the3090 and the switch-form retry. This exercises an injected pipeline OOM; it is not an actual driver OOM report. Full-suite counts above are retained, not rewritten as passing.

Additional failure still unexplained: in the integrated first full run, d32s8_targets_take_their_own_size_of_video_memory reaches vram.rs:1010, list.Close().unwrap(), and receives E_FAIL (0x80004005). This is not a poisoned-test-lock failure. The new sparse lock-progress integration test passes.

Bounded follow-up on unchanged sources:

  • cargo test --locked -p xcl --lib d32s8_targets_take_their_own_size_of_video_memory -- --test-threads=1 --show-output --nocapture: 1 /0 /0 on each tree, no skips.
  • Three fresh-process runs per tree of cargo test --locked -p xcl --lib -- --test-threads=4 --show-output: 726 /1 /21 each run, only CLAMP failing, two explicit native-wave64 skips each. The depth/stencil test passes in all six.

The single additional close failure has not been reproduced or attributed to this PR; those later passes do not explain it. Debug-layer diagnostics were unavailable in these runs. No complete full-workspace rerun with heap windows enabled, retail run, or claim that all integration gates are satisfied. All227baseline/228candidate file hashes match before and after testing; original worktrees retained.

Not tested
Full workspace with the local diagnostic fixtures (the full integration above uses the unmodified author diff), retail / xcl-smoke, release, Linux/Wine, why the GPU queue stalls, permanent device loss, or the concurrent CPU-write/readback race noted in the description. No claim of full rendering/gameplay correctness or merge readiness. The diagnostic initializes sparse globals and runs alone. No runtime change or competing PR.

AI use
Codex (GPT-6) inspected the overlap, adapted the local diagnostic and adapter selection, ran native tests and prepared this report. Existing lock-progress test is the author's. Public source/synthetic data only.

Complete local diagnostic and explicit-adapter patch against0012965
diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs
index d48b6d6..3d6f9f7 100644
--- a/crates/xcl/src/hle/d3d12x/sparse.rs
+++ b/crates/xcl/src/hle/d3d12x/sparse.rs
@@ -2393,3 +2393,7 @@ mod tests {
         }
     }
 }
+
+#[cfg(test)]
+#[path = "sparse_timeout_probe.rs"]
+mod sparse_timeout_probe;
diff --git a/crates/xcl/tests/sparse_lock_released.rs b/crates/xcl/tests/sparse_lock_released.rs
index e071d61..fab1308 100644
--- a/crates/xcl/tests/sparse_lock_released.rs
+++ b/crates/xcl/tests/sparse_lock_released.rs
@@ -13,6 +13,7 @@ use windows::core::Interface;
 use windows::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0};
 use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
 use windows::Win32::Graphics::Direct3D12::*;
+use windows::Win32::Graphics::Dxgi::*;
 use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_UNKNOWN, DXGI_SAMPLE_DESC};
 use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject};
 
@@ -46,9 +47,13 @@ fn a_wait_for_the_sparse_queue_does_not_hold_the_state() {
     unsafe {
         std::env::set_var("XCL_UMA_MB", "64");
         std::env::set_var("XCL_COHERENT_MB", "64");
-        let Ok(dev) = xcl::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else {
+        let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap();
+        let selector = xcl::gpu::adapter::Selector::from_env_or("auto");
+        let Some((adapter, desc)) = xcl::gpu::adapter::candidates(&factory, &selector).into_iter().next() else {
             return xcl::gpu::recomp::runner::skip_test("no GPU");
         };
+        println!("adapter={}", xcl::gpu::adapter::name(&desc));
+        let dev = xcl::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_11_0).unwrap();
         let windows = sparse::init(&dev);
         let Some(&(k, raw, _)) = windows.first() else {
             return xcl::gpu::recomp::runner::skip_test("no GPU");
diff --git a/crates/xcl/src/hle/d3d12x/sparse_timeout_probe.rs b/crates/xcl/src/hle/d3d12x/sparse_timeout_probe.rs
new file mode 100644
--- /dev/null
+++ b/crates/xcl/src/hle/d3d12x/sparse_timeout_probe.rs
@@ -0,0 +1,119 @@
+//! Local PR1385 recovery diagnostic; run alone in a fresh process (initializes sparse globals).
+use super::*;
+use windows::Win32::Graphics::{Direct3D::D3D_FEATURE_LEVEL_12_0, Dxgi::*};
+
+unsafe fn drain(queue: &ID3D12CommandQueue, dev: &ID3D12Device) {
+    let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
+    queue.Signal(&done, 1).unwrap();
+    let start = std::time::Instant::now();
+    while done.GetCompletedValue() == 0 && start.elapsed().as_secs() < 10 {
+        std::thread::sleep(std::time::Duration::from_millis(1));
+    }
+    assert_eq!(done.GetCompletedValue(), 1, "queue drained");
+    dev.GetDeviceRemovedReason().unwrap();
+}
+
+unsafe fn read_page(dev: &ID3D12Device, queue: &ID3D12CommandQueue, source: &ID3D12Resource, offset: u64) -> Vec<u32> {
+    let mut rb: Option<ID3D12Resource> = None;
+    let mut desc = buffer_desc(PAGE as u64);
+    desc.Flags = D3D12_RESOURCE_FLAG_NONE;
+    dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() },
+        D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb).unwrap();
+    let rb = rb.unwrap();
+    let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap();
+    let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap();
+    list.CopyBufferRegion(&rb, 0, source, offset, PAGE as u64);
+    list.Close().unwrap();
+    queue.ExecuteCommandLists(&[Some(list.cast::<ID3D12CommandList>().unwrap())]);
+    drain(queue, dev);
+    let mut p = std::ptr::null_mut();
+    rb.Map(0, Some(&D3D12_RANGE { Begin: 0, End: PAGE }), Some(&mut p)).unwrap();
+    let words = std::slice::from_raw_parts(p as *const u32, PAGE / 4).to_vec();
+    rb.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 }));
+    words
+}
+
+#[test]
+fn timed_out_sparse_upload_retries_unsent_bytes() {
+    unsafe {
+        let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap();
+        let sel = crate::gpu::adapter::Selector::from_env_or("auto");
+        let Some((adapter, desc)) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next() else {
+            return crate::gpu::recomp::runner::skip_test("no GPU");
+        };
+        println!("adapter={}", crate::gpu::adapter::name(&desc));
+        let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).unwrap();
+        let windows = init(&dev);
+        assert!(!windows.is_empty(), "sparse windows initialized");
+        for (_, raw, _) in windows { drop(ID3D12Resource::from_raw(raw as *mut c_void)); }
+        let (p, bytes) = alloc(STAGING, TILE).expect("64 MiB sparse allocation");
+        assert_eq!(bytes, STAGING);
+        let title: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap();
+        let sparse = queue().unwrap();
+        before_execute(&title, &[], PAGE);
+        drain(&sparse, &dev);
+        drain(&title, &dev);
+        let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
+        // Ensure a panic never leaves our synthetic queue blocked.
+        struct Unblock(ID3D12Fence);
+        impl Drop for Unblock { fn drop(&mut self) { unsafe { let _ = self.0.Signal(1); } } }
+        let unblock = Unblock(gate.clone());
+        sparse.Wait(&gate, 1).unwrap();
+        std::ptr::write_bytes(p as *mut u8, 0x11, bytes);
+        // PR1385 reserves one page of admission headroom; prime the full real ring directly.
+        // Seed the tested page's sent hashes using the production scanner, then stage actual bytes.
+        {
+            let mut g = STATE.lock().unwrap();
+            let s = g.as_mut().unwrap();
+            let mut scanned = Vec::new();
+            let data = std::slice::from_raw_parts(p as *const u8, PAGE);
+            scan_page(data, p, &mut s.mapped.get_mut(&p).unwrap().sent[0], &mut scanned);
+            assert_eq!(scanned, vec![(p, PAGE)]);
+            s.upload_dirty(&[(p, bytes)]);
+        }
+        let (source, offset, before_write) = {
+            let g = STATE.lock().unwrap();
+            let s = g.as_ref().unwrap();
+            assert_eq!(s.ring_write - s.ring_free, STAGING as u64, "real ring filled behind gate");
+            assert!(!s.inflight.is_empty());
+            assert!(s.fence.GetCompletedValue() < s.inflight.front().unwrap().0);
+            let wi = s.window_index(p).unwrap();
+            (s.windows[wi].1.clone(), (p - s.windows[wi].0) as u64, s.ring_write)
+        };
+        std::ptr::write_bytes(p as *mut u8, 0x22, PAGE);
+        // Bound the old implementation too: recover after six seconds if it keeps waiting.
+        let rescue = gate.clone();
+        let (tx, rx) = std::sync::mpsc::channel::<()>();
+        let recover = std::thread::spawn(move || {
+            let _ = rx.recv_timeout(std::time::Duration::from_secs(6));
+            rescue.Signal(1).unwrap();
+        });
+        let start = std::time::Instant::now();
+        before_execute(&title, &[p], PAGE);
+        let elapsed = start.elapsed();
+        let after_timeout = STATE.lock().unwrap().as_ref().unwrap().ring_write;
+        drop(unblock);
+        let _ = tx.send(());
+        recover.join().unwrap();
+        drain(&sparse, &dev);
+        assert!(elapsed >= std::time::Duration::from_secs(4) && elapsed < std::time::Duration::from_secs(10), "one bounded fence timeout: {elapsed:?}");
+        // Stronger than the next empty write-watch: explicitly offer the same dirty page again.
+        before_execute(&title, &[p], PAGE);
+        let after_retry = STATE.lock().unwrap().as_ref().unwrap().ring_write;
+        let got = read_page(&dev, &title, &source, offset);
+        let wrong = got.iter().filter(|&&v| v != 0x22222222).count();
+        let old = got.iter().filter(|&&v| v == 0x11111111).count();
+        // Diagnostic positive control: invalidate only this page's sent hashes, retry unchanged bytes.
+        STATE.lock().unwrap().as_mut().unwrap().clear_sent_range(p, PAGE);
+        before_execute(&title, &[p], PAGE);
+        let repaired = read_page(&dev, &title, &source, offset);
+        let control_wrong = repaired.iter().filter(|&&v| v != 0x22222222).count();
+        println!("timeout_ms={} ring_before={before_write} ring_after_timeout={after_timeout} ring_after_retry={after_retry}", elapsed.as_millis());
+        println!("words_checked={} wrong_after_retry={wrong} old_words={old} wrong_after_hash_invalidation={control_wrong}", PAGE / 4);
+        drain(&sparse, &dev);
+        assert!(free(p));
+        drain(&sparse, &dev);
+        assert_eq!(control_wrong, 0, "same-byte upload succeeds when hashes are invalidated");
+        assert_eq!(wrong, 0, "retry must upload bytes that timed out before staging");
+    }
+}

@GonZiin GonZiin left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I verified that the sparse queue regression test fails on the parent, passes on this head, and passes in the full workspace after merging with current main. Given the separate results on #1277 and #1495 showing pending uploads lost after a timeout, I would use #1385 as the candidate for the shared upload-ring problem and keep the recovery cases in its review.

Tested

  • Windows 11 Pro 26300, Ryzen 7 7800X3D, Radeon RX 9070 XT (driver 32.0.32029.2010), SDK DXC 1.8.2502.11, Rust 1.100.0 MSVC, debug. Set XCL_ADAPTER=RX 9070 XT for the workspace harness. The standalone integration fixture creates the default D3D12 device.
  • cargo test -p xcl --test sparse_lock_released -- --test-threads=1 --nocapture on head 0012965eda27e2a528b02c8722a415bde3c02788 gave 1 passed, 0 failed and 0 ignored. The unchanged test copied onto parent 17216a14638659e550b76e3e8245728209b86b70 gave 0 passed, 1 failed and 0 ignored. Both the Map and submit cases on the parent held up the other thread past the two-second limit.
  • .\scripts\test.ps1 on the clean temporary merge with main at 9e3831e1f570d3646e53ab753b19ec07eb8f1485 (tree 66e1c11376a91a0e5f23fbbf1c362194e38d6c71) exited 0. It reported 777 passed, 0 failed and 41 ignored. One GPU skip within the passing count was heap_window_out_of_memory_falls_back_to_the_switch_form (no heap windows). Both the sparse queue fixture and the bundled title end-to-end test passed.

Not tested

Retail titles, opt-in sample data and the other two PRs' timeout-recovery probes on this machine.

AI use

Codex (gpt-6.2-sol) compared the three proposals, ran the Windows tests and drafted this review.

@vladbondarenko97

vladbondarenko97 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Retail-title run on NVIDIA. GTA VI 1.0.2.1, RTX 3080 Ti (driver 610.88), Windows 11, release, XCL_PSO_WAIT_MS=50 XCL_PSO_TRACE=1, main 4178e88 + this PR (0012965, clean local merge ea5073b), 900 s requested.

  • No sparse: the queue has not reached line in the run (main b9b6ea6 on the same box logs it every 5 s from 154 s with the sparse queue stuck at 40159, and the title's watchdog fires at 180 s).
  • Presents stop after the 100 s window. At 154.8–155.3 s every title queue reports GPU queue.Wait … >= 0x97f did not complete within 5000 ms: q0, q1, q2 and q4 wait on q3 (prod=qSome(3)/tySome(0)), and q3 waits on q1 (prod=qSome(1)/tySome(2)), all with completed=0x97e.
  • At 170.1 s: unhandled exception 0xc0000005 in ntdll.dll+0x20191 (read at address 0x92b9); the process then did not exit and was killed at the time limit, so smoke.ps1 printed no block. Correction (edited): that fault is in XCL's own thread dumper at the requested 170 s dump (the known dumper crash, xcl run: thread dumps unwind a copy of each stopped thread's stack #253), not in the title; the run was still submitting work at 168.5 s.

On main + #433 the symbolised thread dumps show the run is killed because a thread holds sparse::STATE inside a blocked UpdateTileMappings while the frame-loop thread waits for it in forget_buffer (details on #433); I first misread that as a queue cycle.

Not tested: AMD; together with #433.

AI use: Claude Code (Claude Opus 5.5) ran the box, read the log and wrote this report.

@Alm0stSurely

Alm0stSurely commented Nov 25, 2026 •

Copy link
Copy Markdown

Linux / Proton check of the upload-slot path in 0012965. On main 8c4a46a plus this PR's sparse.rs diff, we extended the integration test with 20 separate small uploads, changing known nonzero words to zero. The sparse queue was gated for more than 6 s (longer than the 5 s wait, far below ring capacity). The submitting thread stayed blocked, another thread read the sparse mappings within 2 s, and after release all 20 zeros and an untouched neighboring word were verified via GPU readback. The extended test passed in 7.66 s. An initial probe combining an independent allocation and submit did not finish within 2 s; the mapping-only probe specifically checks access to STATE.

Runtime comparison on RTX 5080 / 620.73.04, EndeavourOS, Ryzen 9 9950X3D, ~60 GiB usable RAM, Proton Experimental. Same instrumented 689f2db + #1368 as the baseline, plus this PR's sparse.rs delta, fresh copy of the same warm cache, HLSL, XCL_PSO_PRELOAD=0 XCL_PSO_WAIT_MS=250, 240 s cap. In the baseline, begin_slot timed out on two successive targets. With the patch the outer wait kept asking for 39880, completed 39875, at 206, 211, 216, 221 and 226 s. No inner begin_slot timeout marker. The last nonzero present window ended at 200.846 s. Frames at 195/210/225 s were effectively flat gray; device removal 0x887a0005 at 229.246 s and title exception at +0x23cf683 immediately afterwards. Thus the guarded upload path preserved data under a temporary queue stall in the controlled test, but did not restore GPU progress in this run.

Test orchestration and report assisted by Codex (GPT-6.2 Astra).

Two instrumented repeats, same PR and cache starting point. One run logged a sparse timeout (target 37865, completed 37861) and lost the device at 222.357 s. The diagnostic did not recover the origin of that signal. With the diagnostic moved outside the state lock, the next run reached 0x887a0005 at 197.880 s with no logged five-second sparse timeout and no title queue watchdog release. Its 195 s frame was flat RGB(32,32,44). In both captures vkd3d reported a potential crash region containing compute hash aca5623498d28969, dispatch 160×90×1 and a UAV barrier. This region recurs with and without the sparse timeout; the command responsible for device loss remains undetermined.

@thiagocalile

Copy link
Copy Markdown

Tested commit 0012965eda27e2a528b02c8722a415bde3c02788 on an AMD Radeon RX 6600 (8 GB VRAM, RDNA2, native 64-lane waves) with targeted/workspace tests and a 60 s scripts/smoke.ps1 regression run (comparing against main 62265d3).

Tested

  • Hardware: AMD Radeon RX 6600 (8146 MiB VRAM, RDNA2, native wave64 + mesh shaders, driver 32.0.21045.29003; XCL_ADAPTER=radeon), AMD Ryzen 7 5700X3D, 47.9 GB RAM, Windows 11 (10.0.26200.0), Rust 1.100.0 (stable-x86_64-pc-windows-msvc), DXC 1.8.2502.11.
  • XCL_ADAPTER=radeon cargo test -p xcl --lib sparse -- --test-threads=4: 17 passed, 0 failed, 1 ignored (40.45s).
  • XCL_ADAPTER=radeon cargo test --workspace --no-fail-fast -- --test-threads=4: 758 passed, 3 failed, 41 ignored (61.01s).

Regression run (scripts/smoke.ps1, 60 s, release build, XCL_ADAPTER=radeon)

Base (main 62265d3):

xcl-smoke v1
commit: 62265d3bbde2255f849fb650cc29872df91a4cf0
gpu: AMD Radeon RX 6600
title: 3c290c16
seconds: 60
exit: 0x0
frames shown: 1517 (PresentX 1517)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 13034 MB

PR (0012965):

xcl-smoke v1
commit: 0012965eda27e2a528b02c8722a415bde3c02788
gpu: AMD Radeon RX 6600
title: GTA6.Xbox.v1.0.2.1-CYBERLEEK
seconds: 60
exit: 0x0
frames shown: 1526 (PresentX 1526)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 33432 MB

Not tested

  • D3D12 debug layer, NVIDIA / Intel GPUs, Linux / Wine.

AI use

  • Antigravity (Gemini 4 Neon) ran the test suites and scripts/smoke.ps1 runs on my RX 6600 and drafted this report; I checked the output before posting.

@JJAutoCompare

Copy link
Copy Markdown

Empirical test report for PR #1385 on Intel Arc A770 (STOR-WINLAB).

  • PR head tested: 0012965eda27e2a528b02c8722a415bde3c02788 (D3D12.X: waits for the sparse queue do not hold the sparse state's lock)
  • origin/main checked: d63071abaf158ce8ebdb04be9e942d205c2c7d81 (merge-tree check via git merge-tree --write-tree origin/main HEAD: clean, exit 0, tree b5620e2c3df21033592f45654b13db8311929dd7)

Tested

  • Hardware: Intel(R) Arc(TM) A770 Graphics (16258 MiB VRAM, driver 32.0.101.9175, XCL_ADAPTER=A770), AMD Ryzen 7 3800X 8-Core Processor (6 cores / 12 logical processors)
  • OS: Windows 10 Enterprise Evaluation 25H2 (Build 26200.9974)
  • Toolchain: rustc 1.100.0 (0ef1bc386 2026-11-09), debug (dev / test) profile, DXC 1.9.2609.5 (01b62ad47)
  • Build:
    • cargo test --workspace --no-run — ok
    • cargo build --workspace — ok
  • PR-targeted sparse tests (all passed on Intel Arc A770, 0 skipped):
    • cargo test -p xcl --test sparse_lock_released -- --show-output: 1 passed, 0 failed, 0 ignored (a_wait_for_the_sparse_queue_does_not_hold_the_state, 3.04s — ran with 3 sparse VRAM windows)
    • cargo test -p xcl --test sparse_reinit -- --show-output: 1 passed, 0 failed, 0 ignored (the_sparse_state_is_replaced_outside_its_lock, 1.79s)
    • cargo test -p xcl --lib hle::d3d12x::sparse -- --show-output: 14 passed, 0 failed, 1 ignored (early_commit_timing, 4.16s)
  • Full workspace suite:
    • cargo test --workspace -- --test-threads=4 --show-output stopped after xcl lib (697 passed, 15 failed, 21 ignored, 3 SKIPPED) due to the 15 pre-existing Arc A770 gpu::recomp::tests failures below.
    • cargo test --workspace --no-fail-fast -- --test-threads=4 --show-output (all 21 test targets / doc-tests):
      • 745 passed, 16 failed, 41 ignored across all 21 targets (including 5 SKIPPED GPU/adapter tests below, not counted as coverage — i.e., 740 non-skipped passed + 5 skipped):
        • xcl lib (src\lib.rs): 697 passed (incl. 3 SKIPPED), 15 failed, 21 ignored
        • tests\sparse_lock_released.rs: 1 passed, 0 failed, 0 ignored
        • tests\sparse_reinit.rs: 1 passed, 0 failed, 0 ignored
        • tests\e2e.rs: 2 passed (incl. 1 SKIPPED), 1 failed, 0 ignored (all sparse VRAM / upload / readback checks inside xcl_testtitle passed)
        • tests\texture_states.rs: 1 passed (1 SKIPPED), 0 failed, 0 ignored
        • Remaining 16 targets (src\main.rs, bcpack_parity, console_dlls_e2e, console_shaders, disasm_e2e, gpu_compute_e2e, gpu_pso_e2e, heap_probe, low_va, pls_quota, predication_e2e, rpf_e2e, shaders_e2e, xg_oracle, xcl-testtitle, doc-tests): 43 passed, 0 failed, 20 ignored
  • SKIPPED GPU/adapter tests (5 total, not counted as coverage):
    • gpu::recomp::tests::gpu_geometry_wave32_prefix_count_over_a_mask: no wave64
    • gpu::recomp::tests::gpu_wave32_program_in_wave64_hardware: no wave64
    • placed_title_textures_share_vram_and_preserve_pixels: tiled tier < 2
    • test_title_draws_with_a_root_signature_under_the_debug_layer: no d3d12SDKLayers.dll
    • uploads_start_from_each_subresources_state: no D3D12 debug layer (The application requested an operation that depends on an SDK component that is missing or mismatched. (0x887A002D))
  • Failures (16 total — all 16 verified pre-existing on origin/main d63071ab, 0 regressions from PR D3D12.X: waits for the sparse queue do not hold the sparse state's lock #1385):
    • 11 gpu::recomp::tests::* FP64 pipeline failures (CreateComputePipelineState: The parameter is incorrect. (0x80070057) — Arc A770 lacks native FP64):
      • gpu_clamp_and_omod_per_instruction, gpu_f64_class_compare, gpu_f64_compares_with_nan, gpu_f64_literal_high_word, gpu_f64_math_random, gpu_f64_roots, gpu_f64_rounding_and_conversions, gpu_float_compares_random, gpu_frexp_f64_exp_and_mant, gpu_ldexp_f64, gpu_rndne_f64
    • 4 gpu::recomp::tests::* Arc A770 shader precision/wave failures:
      • gpu_nonfused_mad_and_mac_prevent_fma_contraction: assertion left == right failed: v_fma_f32 overflow control should stay fused (left: 2139095040, right: 1946157055)
      • gpu_ps_image_sample_offset_implicit_lod_between_mips: pixel (0,0) = 25.609375, expected 26
      • gpu_valu_16_and_64_bit: assertion left == right failed: lane 0 v_add_f16 keeps the high half (left: 0, right: 3203351424)
      • gpu_wave64_ps_whole_wave_reductions: assertion left == right failed: pixel 0 (lane 0, wave of pixel 0): min / sum over the odd pixels, waterfall read (left: [2, 217, 2], right: [2, 216, 2])
    • 1 tests\e2e.rs failure:
      • test_title_runs_and_game_folder_is_untouched: [FAIL] D3D12.X: dynamic depth bias via RSSetDepthBiasX (#94): top-right [0, 0, 255, 255] (expected green: RSSetDepthBiasX(-1000.5) passes depth test)
    • Baseline check on origin/main (d63071abaf158ce8ebdb04be9e942d205c2c7d81):
      • cargo test -p xcl --lib -- --test-threads=4 --exact <the 15 failing lib tests>: 0 passed, 15 failed, 0 ignored
      • cargo test -p xcl --test e2e -- --exact test_title_runs_and_game_folder_is_untouched: 0 passed, 1 failed, 0 ignored (identical RSSetDepthBiasX (#94) failure)

Not tested

  • Retail title / scripts/smoke.ps1 regression run (no retail game folder on this host)
  • AMD / NVIDIA GPUs
  • Hardware wave64, hardware FP64 ops, D3D12 tiled resources tier >= 2, and D3D12 debug layer (d3d12SDKLayers.dll not installed)
  • Game-data tests guarded by XCL_SAMPLE_* environment variables (unset)
  • Release build profile (--release)

AI use

  • T3 Code / Antigravity (Gemini 4 Neon): checked out PR D3D12.X: waits for the sparse queue do not hold the sparse state's lock #1385 (0012965eda), ran the merge-tree check, built and executed the targeted sparse tests, full workspace test suite, and origin/main baseline failure verification on Intel Arc A770, and compiled/published this empirical test report from the actual command outputs.

The queue of the sparse windows (tile mappings, uploads of CPU writes,
copies back) can stand still for as long as the GPU does. Two title
threads waited for it on the CPU with the sparse state's mutex held:

- a Map with a read range (sparse::readback_now -> readback_ranges ->
  wait_for), 5 s for each copy back, and after the 5 s it copied the
  readback buffer into the CPU's view without the copy in it;
- a submit (sparse::before_execute -> upload_dirty), which waited for
  room in the 64 MiB upload ring in a loop that does not end while the
  queue stands still.

Every other use of the lock stood behind them: commits and decommits
(a thread moving physical pages), the next Map, the next submit, the
activity line.

Now the wait is made with the lock released (wait_released) and the
state is looked at again after it. The uploads go a part at a time,
each as large as the ring has room for (upload_room), scanned and
uploaded in one hold of the lock, so the hole checks and the sent
hashes stay as they were. A copy back is submitted, waited for with
the lock released and then copied into the pages still committed;
READBACK keeps the one readback buffer to one copy at a time. A copy
back the queue has not made after 5 s leaves the CPU's view as it is.
No upload is dropped: a submit still waits until the ring has room.
The lock is taken again with lock_state, so placed buffers released
during a wait (forget_buffer) are let go then, as at every other use.

Measured with tests/sparse_lock_released.rs (the sparse queue held by
a fence): on main a commit and a submit on another thread are not
through within 2 s behind a Map or behind a submit; with this both
are, the Map returns the GPU's bytes and the submit's 96 MiB are in
video memory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@MacieGx
MacieGx force-pushed the d3d12x/sparse-unlocked-waits branch from 0012965 to 875a603 Compare November 25, 2026 13:58
@MacieGx

MacieGx commented Nov 25, 2026

Copy link
Copy Markdown
Author

Rebased onto main 06c9f55 (now 875a603, still one commit). The only conflicts were
main's lock_state() (from "a buffer's last release does not wait for the sparse state's
lock") at the two places this PR takes READBACK first; READBACK stays before STATE, and
wait_released now takes the lock again with lock_state() too, so buffers released during
a wait are let go then. Main's note_internal_wait in readback_after_execute and
before_execute is kept. No other change. Test counts and the new regression run are in the
description.

Thanks for the reports:

@thiagocalile

Copy link
Copy Markdown

Independent retest of rebased head 875a60352ed34f11f4c4751ed6a740927533366b (on main 06c9f5505f63f10c5ec49ef932d75b2c28177324) on an AMD Radeon RX 6600 (8 GB VRAM, RDNA2, native wave64).

Tested

  • Hardware: AMD Radeon RX 6600 (8146 MiB VRAM, RDNA2, driver 32.0.21045.29003, XCL_ADAPTER=radeon), AMD Ryzen 7 5700X3D, 47.9 GB RAM, Windows 11 (10.0.26200.0), Rust 1.100.0 (stable-x86_64-pc-windows-msvc), DXC 1.8.2502.11.
  • XCL_ADAPTER=radeon cargo test -p xcl --lib sparse -- --test-threads=4: 24 passed, 0 failed, 1 ignored (0 skipped).
  • XCL_ADAPTER=radeon cargo test --workspace --no-fail-fast -- --test-threads=4: 1,265 passed, 1 failed, 46 ignored across 24 test binaries (10 SKIPPED: 6 per-lane f16/f32 unsupported ops, 1 pso_measurement_compiles_an_exact_synthetic_record no Developer Mode, 2 no D3D12 debug layer, 1 no heap windows).
    • The sole failure is gpu::dxil::fuzz_tests::fuzz_validate_and_gpu_1 (the known RX 6600 driver 32.0.21045.29003 sext i1 -> i64 miscompile on seed 540, pre-existing on main).

Regression run (scripts/smoke.ps1 -Seconds 60, release builds, XCL_ADAPTER=radeon)

main:

xcl-smoke v1
commit: 06c9f5505f63f10c5ec49ef932d75b2c28177324
gpu: AMD Radeon RX 6600
title: 3c290c16
seconds: 60
exit: 0x0
frames shown: 1469 (PresentX 1469)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 13436 MB

PR #1385 (875a603):

xcl-smoke v1
commit: 875a60352ed34f11f4c4751ed6a740927533366b
gpu: AMD Radeon RX 6600
title: 3c290c16
seconds: 60
exit: 0x0
frames shown: 1532 (PresentX 1532)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 12713 MB

Not tested: NVIDIA / Intel GPUs, Linux/Wine, D3D12 debug-layer tests (SDK debug layer not installed), or world load past the 60 s smoke window.

AI use: Antigravity (Gemini 4 Neon) ran the builds, test suites, and smoke pair and drafted this report; the account owner reviewed and approved posting.

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

Labels

goal:world-load Bears on the retail title getting past world loading

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants