Skip to content

D3D12.X: bail out of sparse::upload_dirty ring wait when fence wait times out - #1495

Closed
b3IKK wants to merge 1 commit into
xcl-dev:mainfrom
b3IKK:d3d12x/sparse-wait-timeout-loop
Closed

b3IKK wants to merge 1 commit into
xcl-dev:mainfrom
b3IKK:d3d12x/sparse-wait-timeout-loop

Conversation

@b3IKK

@b3IKK b3IKK commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

In sparse::State::upload_dirty, the ring-space loop called self.wait_for(fv); self.reclaim_ring(); unconditionally. Because wait_for() logged a warning after 5 s and returned (), a stalled or hung queue caused reclaim_ring() to make no progress and turned the loop into an infinite 5-second-stall loop while holding the global sparse::STATE mutex, deadlocking every thread calling VirtualAlloc/VirtualFree, before_execute, or readback_*.

This has wait_for / wait_for_fence return bool indicating whether the fence reached target, extracts wait_for_ring_space(), and bails out of upload_dirty cleanly if waiting times out without reclaiming space.

What is in it

  • crates/xcl/src/hle/d3d12x/sparse.rs: return bool from wait_for_fence / wait_for, extract wait_for_ring_space() and bail out of upload_dirty on timeout/no-progress, and add unit test wait_for_ring_space_bails_on_timeout_and_reclaims_on_progress.

Tested

  • hardware (GPU + driver, CPU), Windows build, Rust version, debug / release: NVIDIA GeForce RTX 5080 (driver 32.0.16.1088), AMD Ryzen 9 9950X3D, Windows 11 10.0.26300, Rust 1.100.0 (stable-x86_64-pc-windows-msvc), DXC 1.9.2609.5, debug (scripts/test.ps1) and release (scripts/smoke.ps1)
  • .\scripts\test.ps1 (cargo build --workspace + cargo test --workspace -- --test-threads=4): 771 passed, 0 failed, 41 ignored (SKIPPED GPU tests: 2 no wave64 — gpu::recomp::tests::gpu_geometry_wave32_prefix_count_over_a_mask, gpu::recomp::tests::gpu_wave32_program_in_wave64_hardware)
  • cargo test -p xcl --lib wait_for_ring_space_bails_on_timeout_and_reclaims_on_progress: 1 passed, 0 failed

Regression run

main:

xcl-smoke v1
commit: 47efa2ecea0a12934719ae69b81930cf02a4b1c3
gpu: NVIDIA GeForce RTX 5080
title: 9cc6a39e
seconds: 60
exit: 0x0
frames shown: 1226 (PresentX 1226)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 15341 MB

PR:

xcl-smoke v1
commit: 49bdea91ff6530c710c1fdac13c0f4b8edab4f50
gpu: NVIDIA GeForce RTX 5080
title: 9cc6a39e
seconds: 60
exit: 0x0
frames shown: 1653 (PresentX 1653)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 14604 MB

Not tested

  • AMD GPUs and native wave64 hardware
  • other titles (Minecraft Preview, Unicorn Overlord, Fortnite, XDefiant) and Linux / Wine

AI use

  • OpenCode, Gemini 4 Neon: audited sparse.rs, wrote the fix and unit test, ran the test suite and scripts/smoke.ps1 regression runs, and drafted this PR description.

…imes out

In sparse.rs, upload_dirty looped `while (aligned + chunk) - ring_free > STAGING`
calling `self.wait_for(fv); self.reclaim_ring();`. Because wait_for()
only logged a warning after 5 s and returned `()`, a hung or stalled GPU
queue caused reclaim_ring() to make no progress and turned the loop into
an infinite 5-second-stall loop while holding the global sparse::STATE
mutex, deadlocking every thread calling VirtualAlloc/VirtualFree/
before_execute/readback.

Have wait_for / wait_for_fence return `bool` indicating whether the
fence reached `target`, extract wait_for_ring_space(), and bail out of
upload_dirty cleanly if waiting times out without reclaiming space.

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

WebIdentity1 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Additional readback result: the timeout can also overwrite newer CPU bytes with old GPU data. This is now reproduced through production readback_now, beyond the upload-retry finding below.

Same hardware/toolchain as below; each entry is a separate native Windows Session0 process with the identical new synthetic fixture. Counts are passed / failed / ignored.

Exact source + readback fixture GPU Result readback duration Wrong CPU words / wrong GPU words after retry
parent b7aa9f3bd212088e0d927439284dc5ed325ce3c7 RTX3090 1 /0 /0 6007ms 0 /0
PR 49bdea91ff6530c710c1fdac13c0f4b8edab4f50 RTX3090 0 /1 /0 6012ms 1024 /1024
parent b7aa9f3 AMD integrated 1 /0 /0 6022ms 0 /0
PR 49bdea9 AMD integrated 0 /1 /0 6156ms 1024 /1024
alternative #1385 0012965eda27e2a528b02c8722a415bde3c02788 RTX3090 1 /0 /0 5007ms 0 /0
alternative #1385 0012965 AMD integrated 1 /0 /0 5014ms 0 /0

No skips, harness timeouts or device-removal errors. Each oracle checks all1,024words of one4KiB page. Head failures exit101 after drain/free cleanup; all wrong words are the old 0x11111111, replacing expected 0x22222222. The other four runs exit0.

The fixture drains initial tile clears, fills the real64MiB ring with0x11 behind a controlled native queue fence, then changes one CPU page to0x22 and calls readback_now. It primes the ring through production State::upload_dirty and seeds that page's hashes through scan_page, allowing the identical setup on #1385 with its reserved admission space. No fake ring counters or wait results. A guard releases the queue at six seconds, or earlier when readback returns.

On this head, upload times out without staging0x22; readback still submits, completes after recovery and copies GPU0x11 over the CPU page. A later explicit same-page retry cannot reconstruct the overwritten bytes. Ring write stays67108864. The parent stages the changed page after recovery (ring67112960). #1385 returns from readback at its five-second admission timeout with CPU0x22 intact; after releasing the queue, retry uploads it correctly. This tests its existing preservation behavior, not a new proposed implementation.

Command, XCL_ADAPTER=3090 or AMD:

cargo test --locked -p xcl --lib timed_out_readback_preserves_unsent_cpu_bytes -- --test-threads=1 --show-output --nocapture

All227source hashes per tree matched before/after. Fixture SHA256:f072877a38b6bf69a18167049ab997a12db05127cd6c7c583b76829f183183c4. Patch reverse-apply/diff checks pass. No source push or competing PR.

Scope: this calls readback_now directly, not the public Map ABI. No concurrent CPU write during readback, permanent stall, device-removal recovery, partial multi-run suffix, release/full-suite or retail claim. #1385's separate integration caveat remains in its existing report. AI use: Codex (GPT-6) wrote the fixture, ran/checked these tests and prepared this report.

Complete additional readback fixture patch
diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs
index f6f1e0f..33e347b 100644
--- a/crates/xcl/src/hle/d3d12x/sparse.rs
+++ b/crates/xcl/src/hle/d3d12x/sparse.rs
@@ -2304,3 +2304,7 @@ mod tests {
         assert_eq!(inflight.len(), 1);
     }
 }
+
+#[cfg(test)]
+#[path = "sparse_readback_probe.rs"]
+mod sparse_readback_probe;
diff --git a/crates/xcl/src/hle/d3d12x/sparse_readback_probe.rs b/crates/xcl/src/hle/d3d12x/sparse_readback_probe.rs
new file mode 100644
--- /dev/null
+++ b/crates/xcl/src/hle/d3d12x/sparse_readback_probe.rs
@@ -0,0 +1,116 @@
+//! Local readback timeout 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_readback_preserves_unsent_cpu_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();
+        readback_now(p, PAGE);
+        let elapsed = start.elapsed();
+        let cpu_words = std::slice::from_raw_parts(p as *const u32, PAGE / 4).to_vec();
+        let cpu_wrong = cpu_words.iter().filter(|&&v| v != 0x22222222).count();
+        let cpu_old = cpu_words.iter().filter(|&&v| v == 0x11111111).count();
+        let after_readback = 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), "bounded delayed readback: {elapsed:?}");
+        // A same-page retry must still upload the CPU's newer bytes after recovery.
+        before_execute(&title, &[p], PAGE);
+        let got = read_page(&dev, &title, &source, offset);
+        let gpu_wrong = got.iter().filter(|&&v| v != 0x22222222).count();
+        let gpu_old = got.iter().filter(|&&v| v == 0x11111111).count();
+        println!("readback_ms={} ring_before={before_write} ring_after_readback={after_readback}", elapsed.as_millis());
+        println!("words_checked={} cpu_wrong={cpu_wrong} cpu_old={cpu_old} gpu_wrong_after_retry={gpu_wrong} gpu_old_after_retry={gpu_old}", PAGE / 4);
+        drain(&sparse, &dev);
+        assert!(free(p));
+        drain(&sparse, &dev);
+        assert_eq!(cpu_wrong, 0, "readback must preserve CPU bytes that could not be uploaded");
+        assert_eq!(gpu_wrong, 0, "retry must upload the preserved CPU bytes");
+    }
+}

Native Windows timeout-recovery finding on exact head 49bdea91ff6530c710c1fdac13c0f4b8edab4f50: after the new early return, an unsubmitted dirty page remains marked sent and is skipped on retry. Reproduced on RTX3090 and AMD integrated Graphics. The bounded wait is useful; preserving the pending bytes is also necessary.

Overlap follow-up: the earlier #1277 has the same recovery failure (matched native controls). #1385 already identified the hash-loss risk and keeps uploads pending while releasing STATE during waits; its exact-head tests on both GPUs now preserve bytes and pass the existing lock-progress test. Please coordinate these existing alternatives rather than duplicate them. This does not establish full merge readiness.

Tested
Local synthetic fixture (complete patch below), calling production before_execute / upload_dirty:

  1. Allocate 64MiB sparse memory, fill it with 0x11, and fill the real staging ring behind an explicitly blocked queue fence.
  2. Change one 4KiB CPU page to 0x22, then call before_execute again. The real five-second fence wait expires.
  3. Unblock the queue, offer the same dirty page again, and copy its GPU bytes into a separate readback buffer. This explicitly offered retry is stronger than relying on a later empty write-watch scan.
  4. Diagnostic control: invalidate only that page's sent hashes and retry the unchanged CPU bytes. All 1,024 words then match.

The same fixture has a six-second recovery guard so the parent implementation can finish its repeated wait. It does not alter ring positions, stage fake data, inject wait results, or hang the GPU. Queue fences drain and GetDeviceRemovedReason succeeds before cleanup/assertions.

Source + fixture GPU passed / failed / ignored Wait duration Wrong words after retry Wrong words after hash invalidation
parent main b7aa9f3bd212088e0d927439284dc5ed325ce3c7 RTX3090 1 /0 /0 6014ms 0 /1024 0
PR 49bdea9 RTX3090 0 /1 /0 5007ms 1024 /1024 0
parent main b7aa9f3 AMD integrated 1 /0 /0 6022ms 0 /1024 0
PR 49bdea9 AMD integrated 0 /1 /0 5013ms 1024 /1024 0

No skips or harness timeouts. Head failures exit101 on retry must upload bytes that timed out before staging; parent runs exit0. All mismatches on head are the old 0x11111111 words. Ring write position remains67108864 after timeout and retry on head; parent advances to67112960 when recovery permits the page upload.

Mechanism / suggested follow-up
scan_page updates entry.sent before upload_dirty runs. The new return on wait_for_ring_space == false drops the unsubmitted suffix; before_execute then clears dirty_runs. On the explicit retry, the CPU hashes already match sent, so no upload occurs. readback_now has the same scan-before-upload ordering.

Please retain/retry the unsubmitted ranges or propagate the failure so a submit cannot silently consume stale bytes. Hash invalidation plus the explicit dirty-page retry above is a diagnostic control, not a complete proposed fix: the normal write-watch path uses reset, so the next scan need not rediscover that page. The parent control only proves byte recovery after a transient stall; its indefinitely repeated waits still need fixing.

Command for each fresh process, XCL_ADAPTER=3090 or 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. Full227-file source manifests matched each native test tree. Only runtime file differing between parent/head is sparse.rs; the same diagnostic is wired into both. Head + fixture restored afterward, all hashes verified. Fixture patch reverse-apply and diff checks pass.

Not tested
Full workspace with this fixture, retail / xcl-smoke, device-removal recovery, partial multi-run suffixes, Linux/Wine, or a release build. This is a transient queue-delay reproducer, not evidence that it caused a particular game's missing assets. Run alone in a fresh process because it initializes sparse globals. No runtime fix or competing PR is included.

AI use
Codex (GPT-6) inspected the code, wrote the fixture, ran native validation and prepared this report. Public source and synthetic bytes only.

Complete local diagnostic patch against49bdea9
diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs
index f6f1e0f..206a285 100644
--- a/crates/xcl/src/hle/d3d12x/sparse.rs
+++ b/crates/xcl/src/hle/d3d12x/sparse.rs
@@ -1645,6 +1645,10 @@ pub fn forget_buffer(res: usize) {
     }
 }
 
+#[cfg(test)]
+#[path = "sparse_timeout_probe.rs"]
+mod sparse_timeout_probe;
+
 #[cfg(test)]
 mod tests {
     use super::*;
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");
+    }
+}

@b3IKK

b3IKK commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Thank you @WebIdentity1 for the detailed RTX 3090 and AMD iGPU timeout-recovery reproducers — that is a real bug in this PR's early-return path (leaving \entry.sent\ hashes updated for unsent pages and allowing
eadback_now\ to overwrite newer CPU bytes). Since #1385 already addresses this cleanly by releasing \STATE\ during waits and preserving pending uploads, I am closing #1495 in favor of #1385.

@b3IKK b3IKK closed this Nov 24, 2026
@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. (Intermittent single-test flake / 0xc0000005 abort under parallel scheduling; clean on single-threaded rerun — same flake seen on unmodified main.)

Thanks!

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.

3 participants