Skip to content

D3D12.X: stop sparse upload_dirty ring wait when fence times out - #1277

Open
ExoCalibra wants to merge 1 commit into
xcl-dev:mainfrom
ExoCalibra:pr/sparse-upload-wait-timeout
Open

ExoCalibra wants to merge 1 commit into
xcl-dev:mainfrom
ExoCalibra:pr/sparse-upload-wait-timeout

Conversation

@ExoCalibra

@ExoCalibra ExoCalibra commented Nov 24, 2026 •

Copy link
Copy Markdown

sparse::State::wait_for returns after 5 s with a warning if the sparse upload queue stalls, but upload_dirty called wait_for(fv) inside a while loop waiting for staging ring space. When the oldest in-flight fence failed to advance, reclaim_ring freed nothing and upload_dirty looped forever while holding the global STATE mutex, hanging xcl-activity (sparse::pool_bytes) and every subsequent submit thread permanently.

What is in it

  • crates/xcl/src/hle/d3d12x/sparse.rs: return whether wait_for reached its target fence value, break out of upload_dirty with a bounded warning on timeout so STATE is released cleanly, and add GPU regression test upload_dirty_exits_when_ring_fence_wait_times_out.

Tested

  • Hardware / OS / toolchain: NVIDIA GeForce RTX 3080 Ti (driver 32.0.16.1088), AMD Ryzen 7 7800X3D, Windows 11 Pro Build 26200, rustc 1.100.0 (0ef1bc386 2026-11-09), debug (scripts/test.ps1) + release (cargo build --release -p xcl).
  • .\scripts\test.ps1 (cargo test --workspace -- --test-threads=4): 742 passed, 0 failed, 41 ignored.
  • SKIPPED GPU tests on this adapter: 2 (no wave64 — gpu_geometry_wave32_prefix_count_over_a_mask, gpu_wave32_program_in_wave64_hardware).

Regression run

Main (67a3735):

xcl-smoke v1
commit: 67a3735177f42cf8e5c886e67a974da7f87541b3
gpu: NVIDIA GeForce RTX 3080 Ti
title: 9cc6a39e
seconds: 60
exit: 0x0
frames shown: 1084 (PresentX 1084)
presents per 2 s (last 3): 59 59 56
device removals: 0
crashes: 0
peak commit: 16561 MB

PR (0f66820):

xcl-smoke v1
commit: 0f66820065129bca1e0cd7f3ae0125e140d835f3
gpu: NVIDIA GeForce RTX 3080 Ti
title: 9cc6a39e
seconds: 60
exit: 0x0
frames shown: 1090 (PresentX 1091)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 15699 MB

Not tested

  • The timeout bail-out branch is exercised by the GPU unit test (upload_dirty_exits_when_ring_fence_wait_times_out) and did not trigger during the healthy 60 s retail smoke run.
  • AMD RDNA / wave64 GPUs and Intel GPUs.
  • XCL_SAMPLE_* tests on local sample files (not set).

AI use

  • Antigravity (Gemini 4 Neon): assisted with root-cause analysis, fix, GPU regression test, audit, rebase verification, and PR description. All code, tests, and smoke logs reviewed by the author.

sparse::State::wait_for intentionally returns after 5 s with a warning if the sparse queue stalls, but upload_dirty wrapped wait_for in a while loop waiting for staging ring space. When the oldest in-flight fence failed to advance, reclaim_ring freed nothing and upload_dirty looped forever while holding the global STATE mutex, blocking xcl-activity (pool_bytes) and every submitting thread.

Return whether wait_for reached its target fence value, bail out of upload_dirty with a bounded warning on timeout so STATE is released, and add a GPU regression test reproducing a full staging ring with a stalled fence.
@DavidM1911

Copy link
Copy Markdown
Contributor

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

  • cargo test -p xcl --lib sparse: 17 passed, 0 failed, 1 ignored.

Thanks!

@futurepro62

Copy link
Copy Markdown

Full-suite run to go with the subset check above. Tested exact head 0f66820 (on its base 47efa2e).

Tested

  • NVIDIA GeForce RTX 5070 Ti 16 GB (Blackwell, 32-lane waves only, mesh shaders), driver 616.64, Ryzen 7 9800X3D, Windows 11 Home 26300, Rust 1.100.0 MSVC, debug, D3D12 debug layer installed.
  • cargo build --workspace, then XCL_REQUIRE_GPU=mesh cargo test --workspace -- --test-threads=4: 742 passed, 0 failed, 41 ignored. SKIPPED (no wave64): gpu_geometry_wave32_prefix_count_over_a_mask, gpu_wave32_program_in_wave64_hardware.
  • The new tests ran and passed: upload_dirty_exits_when_ring_fence_wait_times_out.
  • Same head on the AMD Radeon iGPU of the 9800X3D (RDNA2, XCL_ADAPTER=radeon), cargo test --workspace -- --test-threads=4: 742 passed, 0 failed, 41 ignored, no skips.

Not tested

  • a release build, a game (test run only).

AI use

  • Claude Code (Claude Opus 5.5) ran the tests and wrote this report. I checked it before posting.

gustavsi added a commit to gustavsi/xcl that referenced this pull request Nov 24, 2026
…all#1248, ivall#1250, ivall#1265, ivall#1273, ivall#1277, ivall#1278

Fix sudden RAM OOM during world loading under XCL_PSO_WAIT_MS and integrate 6 new upstream PRs:
- pso_async.rs: track active waiters via WantGuard so build_is_wanted() drops back to false once resolve_within times out, preventing all background workers from bypassing BIG_COMPILES and commit-memory guards simultaneously (adds unit test a_timed_out_bind_clears_wanted_demand).
- ivall#1248: pack <= 4 KiB sampled textures into 4 KiB heap slots instead of 64 KiB tiles (~768 MiB VRAM saved).
- ivall#1250: late_release seals/waits only when nothing is in flight.
- ivall#1265: default SRVs of multisampled depth buffers use Texture2DMS/Texture2DMSArray.
- ivall#1273: skip budgeted bind waits when all workers are busy / build is queued behind others.
- ivall#1277: exit sparse::upload_dirty cleanly if staging ring fence wait times out.
- ivall#1278: isolate >= 4 MiB DXIL compute driver compiles in a dedicated GIANT_COMPILES queue.

Assisted-by: Antigravity (Google DeepMind)
anoyarou added a commit to anoyarou/xcl that referenced this pull request Nov 24, 2026
…d harden compute/sparse paths

- crates/xcl/src/hle/d3d12x/pso_async.rs (fixes 1 MiB thread stack overflow / deadlock seen alongside ivall#611):
  Add urgent_queue() spawning dedicated 64 MiB-stack xcl-pso-wait-* workers and offload unstarted jobs in resolve_wait_for(..., None) instead of executing job() inline on the title's 1 MiB stack threads, avoiding silent Wine thread deaths without skipping compute dispatches (ivall#675, ivall#891). Guard build() with std::panic::catch_unwind plus a Drop completion guard so panics always call complete(p, 0) and notify waiters.
- crates/xcl/src/hle/d3d12x/pso_async.rs & kernelx.rs (ivall#1288, ivall#505, ivall#232):
  Track active pipeline bind waits via HELD / title_held() and export kernelx::Sleep backed by title_sleep() so Sleep skips counting time spent blocked on background PSO compilation (XCL_SLEEP_HOLD=0 disables).
- crates/xcl/src/hle/d3d12x/bind.rs, device_x.rs & real.rs (ivall#1195):
  Track console compute PSOs (CONSOLE_COMPUTE) and Dispatch-capable command signatures (DISPATCH_SIGNATURES) so ExecuteIndirect skips dispatches against untranslated console compute stand-ins or fallbacks while still forwarding native PC compute pipelines.
- crates/xcl/src/hle/d3d12x/sparse.rs (ivall#1419, ivall#1277):
  Extract wait_fence_until() to ResetEvent before SetEventOnCompletion and re-check GetCompletedValue() until target or deadline so stale signals on the reusable auto-reset event cannot end waits early; bail cleanly from upload_dirty() if ring fence reclaim times out instead of holding STATE indefinitely.
- crates/xcl/src/gpu/recomp/emit.rs & tests.rs (ivall#1361):
  Split GFX10.30 SADDR == 0x7F (ST immediate-only 0u base) from SADDR == 0x7D (v[ADDR] base) in Em::scratch and update ENC_FLAT_SCRATCH VADDR test encodings to 0x7D.

Assisted-by: Antigravity (Gemini 4 Neon)
@WebIdentity1

WebIdentity1 commented Nov 24, 2026 •

Copy link
Copy Markdown

Independent native recovery check: this branch reproduces the dropped-upload risk already described by #1385's author. Exact head 0f66820065129bca1e0cd7f3ae0125e140d835f3; exact parent 47efa2ecea0a12934719ae69b81930cf02a4b1c3.

Tested
The same fixture used for #1495, unchanged (SHA256 1fd8f7d154e9663b25d9fe98153fccd2bc8de5291db5aa24414e48f3ddfaa958): fill the real64MiB staging ring behind a controlled queue fence with0x11, change a4KiB page to0x22, wait through the actual5-second timeout, release the gate, explicitly retry that same dirty page, then read all1,024words from the GPU. A six-second recovery guard lets the parent finish without an infinite wait.

Source GPU passed / failed / ignored Wait Wrong words after retry
parent47efa2e RTX3090 1 /0 /0 6015ms 0 /1024
head0f66820 RTX3090 0 /1 /0 5015ms 1024 /1024
parent47efa2e AMD integrated 1 /0 /0 6018ms 0 /1024
head0f66820 AMD integrated 0 /1 /0 5002ms 1024 /1024

No skips or harness timeouts. Head exits101 on the byte assertion; parent exits0. All wrong head words are the old0x11111111. Head ring_write stays67108864 through timeout and retry; parent advances to67112960. Invalidating only the page's sent hashes and explicitly retrying the unchanged bytes yields0wrong on both GPUs. Queue drain/device-removal checks succeed; cleanup occurs before the failing assertion.

scan_page updates the hashes before upload, and the new early return loses the remaining bytes while before_execute clears its dirty runs. The next same-page retry sees matching hashes and stages nothing. Invalidation alone is not a complete fix: normal write-watch scans reset their records, so the next dirty-page list need not include the page. Retain pending uploads or propagate the failure. #1385 already proposes keeping pending work while releasing STATE during waits; native validation of that alternative now passes the byte-recovery and existing lock-progress tests on RTX3090 and AMD, with exact-parent controls. These focused results do not establish full merge readiness.

Fresh process for each run, XCL_ADAPTER=3090 / AMD:
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. All222source-file hashes match each tree; parent/head differ only in sparse.rs, plus identical diagnostic wiring. Restored head verified. Patch reverse-apply and diff checks pass.

Not tested
Full workspace with this fixture, retail / xcl-smoke, actual device loss, partial multi-run suffixes, release, Linux/Wine. The existing timeout test demonstrates bounded return; this additional test checks recovery bytes. The parent control does not endorse repeated waits under STATE. Run alone because the fixture initializes sparse globals. No competing runtime implementation or PR.

AI use
Codex (GPT-6) inspected the overlap, adapted diagnostic wiring, ran tests and prepared this report. Synthetic bytes/public source only.

Complete diagnostic patch against0f66820
diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs
index 9b992d8..9a89710 100644
--- a/crates/xcl/src/hle/d3d12x/sparse.rs
+++ b/crates/xcl/src/hle/d3d12x/sparse.rs
@@ -2311,3 +2311,7 @@ mod tests {
         }
     }
 }
+
+#[cfg(test)]
+#[path = "sparse_timeout_probe.rs"]
+mod sparse_timeout_probe;
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,108 @@
+//! Local PR1495 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();
+        drain(&sparse, &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);
+        let pages: Vec<usize> = (p..p + bytes).step_by(PAGE).collect();
+        before_execute(&title, &pages, PAGE);
+        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");
+    }
+}

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.

4 participants