[pr-performance] Opt-in DARNER_LATE_FENCE=1 to avoid CPU stalls on in-flight cross-queue fence waits #93

Open
hingeowl wants to merge 1 commit from hingeowl/Darner:vercetti/late-fence into main
Contributor

Summary

Adds opt-in DARNER_LATE_FENCE=1 (off by default) to avoid CPU stalls on in-flight cross-queue fence waits when running on a single FIFO host queue.

When a waiting queue encounters Ask::Wait(fence, value) or Job::Wait(fence, value) whose signal is already queued in-flight on the host relay (Late::Signal), host::late_fence_met() allows the waiting queue to proceed behind the in-flight signal instead of stalling the sender thread for the GPU to drain. Guarded off automatically when two_queues::on() is active.

Provenance

  • Ported from https://github.com/lobomfz/VIctory-xmem commit 9d72949c520646e44a1cdb1f451fd1b6f2de07f9 (GPL-3.0-or-later), adapted to Darner's FenceRef and guarded against two_queues::on().
  • Rebased cleanly onto main (b3a615f).

Validation

  • Unit tests: cargo test --locked -p darner-gpu --lib queue::behind passed.
  • 2-round 60 s interleaved spinning-camera A/B (RTX 4090 / Ryzen 9 7950X3D, Series X, 1440p, RT off, DARNER_RELAY=2, canonical play.rs settings, DARNER_LATE_FENCE=0 vs 1, same binary):
Metric DARNER_LATE_FENCE=0 (R1 / R2) DARNER_LATE_FENCE=1 (R1 / R2) Summary Delta
Draws/frame 7,982 / 7,917 7,556 / 7,841 1.77% drift
FPS (median) 20.5 / 21.9 (21.9) 20.9 / 22.2 (22.2) +0.3 FPS
FrameMedMs 49.0 / 46.2 ms (49.0) 47.1 / 46.4 ms (47.1) -1.9 ms
FrameP95Ms 63.1 / 57.7 ms (63.1) 60.1 / 58.9 ms (60.1) -3.0 ms
SubmitMs 34.1 / 31.5 ms (34.1) 32.2 / 32.4 ms (32.4) -1.7 ms
ListsMs 18.4 ms 17.3 ms -1.1 ms
GPU Busy / VRAM 65% / 21,799 MB 64% / 21,891 MB Parity
  • Verdict: IMPROVED (-1.9 ms median frame time, -3.0 ms P95, -1.7 ms submit, visually verified spotless with nonBlack=99.99%, magenta=0%).
  • (Reference baseline on unmodified main b3a615f: 19.4 FPS, 49.6 ms med, 65.0 ms P95, 35.1 ms submit, 7,946 draws.)
## Summary Adds opt-in `DARNER_LATE_FENCE=1` (off by default) to avoid CPU stalls on in-flight cross-queue fence waits when running on a single FIFO host queue. When a waiting queue encounters `Ask::Wait(fence, value)` or `Job::Wait(fence, value)` whose signal is already queued in-flight on the host relay (`Late::Signal`), `host::late_fence_met()` allows the waiting queue to proceed behind the in-flight signal instead of stalling the sender thread for the GPU to drain. Guarded off automatically when `two_queues::on()` is active. ## Provenance - Ported from `https://github.com/lobomfz/VIctory-xmem` commit `9d72949c520646e44a1cdb1f451fd1b6f2de07f9` (GPL-3.0-or-later), adapted to Darner's `FenceRef` and guarded against `two_queues::on()`. - Rebased cleanly onto `main` (`b3a615f`). ## Validation - **Unit tests:** `cargo test --locked -p darner-gpu --lib queue::behind` passed. - **2-round 60 s interleaved spinning-camera A/B** (RTX 4090 / Ryzen 9 7950X3D, Series X, 1440p, RT off, `DARNER_RELAY=2`, canonical `play.rs` settings, `DARNER_LATE_FENCE=0` vs `1`, same binary): | Metric | `DARNER_LATE_FENCE=0` (R1 / R2) | `DARNER_LATE_FENCE=1` (R1 / R2) | Summary Delta | |---|---:|---:|---:| | **Draws/frame** | `7,982` / `7,917` | `7,556` / `7,841` | `1.77%` drift | | **FPS (median)** | `20.5` / `21.9` (`21.9`) | `20.9` / `22.2` (`22.2`) | **`+0.3 FPS`** | | **FrameMedMs** | `49.0` / `46.2 ms` (`49.0`) | `47.1` / `46.4 ms` (`47.1`) | **`-1.9 ms`** | | **FrameP95Ms** | `63.1` / `57.7 ms` (`63.1`) | `60.1` / `58.9 ms` (`60.1`) | **`-3.0 ms`** | | **SubmitMs** | `34.1` / `31.5 ms` (`34.1`) | `32.2` / `32.4 ms` (`32.4`) | **`-1.7 ms`** | | **ListsMs** | `18.4 ms` | `17.3 ms` | **`-1.1 ms`** | | **GPU Busy / VRAM** | `65%` / `21,799 MB` | `64%` / `21,891 MB` | Parity | - **Verdict:** **IMPROVED** (`-1.9 ms` median frame time, `-3.0 ms` P95, `-1.7 ms` submit, visually verified spotless with `nonBlack=99.99%`, `magenta=0%`). - *(Reference baseline on unmodified `main` `b3a615f`: `19.4 FPS`, `49.6 ms` med, `65.0 ms` P95, `35.1 ms` submit, `7,946` draws.)*
Ported from VIctory-xmem 9d72949c, adapted to Darner's FenceRef and guarded against two_queues::on().

Upstream-Repository: https://github.com/lobomfz/VIctory-xmem
Upstream-Commit: 9d72949c520646e44a1cdb1f451fd1b6f2de07f9
Contributor

I reproduced a stale upload on 08e3ed5b77365eb66880df5a72e88fae5c82e32f with an RTX 4060 8 GB (621.40), Windows 11 build 26300, and Rust 1.98.1.

The synthetic test submits a producer and a consumer through Darner's graphics and compute queues, which share one real D3D12 direct queue. The producer's Write64BitValueBottomOfPipeX changes the source from 0x1b to 0xb7 when the relay publishes it. The consumer waits on the producer's emulated fence, snapshots the source with defer_fill, and copies that upload buffer into a D3D12 readback.

What the test holds DARNER_LATE_FENCE Consumer CPU prep before fence publication GPU readback Runs
Producer on the D3D12 queue 0 No 0xb7 6/6 passed
Producer on the D3D12 queue 1 Yes 0x1b 6/6 failed the readback assertion
Relay after draining the completed producer, before its CPU write 0 No 0xb7 6/6 passed
Relay after draining the completed producer, before its CPU write 1 Yes 0x1b 6/6 failed the readback assertion

Each row covers three runs with DARNER_RELAY=1 and three with DARNER_RELAY=2. In every run the producer's fence was 0 while publication was held. Both emulated fences later reached 1 and the CPU source became 0xb7. In the first pair of rows the D3D12 fence itself holds the producer. That pair also reproduced with just the fixture in queue.rs. In the second pair a test-only latch holds the relay after the GPU completed the producer and the relay took its pending Late::Write. The test queues the producer's fence signal during that latch.

late_fence_met can accept the pending signal in both windows. FIFO orders the GPU copies. The CPU prelude had already captured the consumer's upload bytes before the relay published the producer's write. The demonstrated case needs the emulated wait to keep holding while a preceding bottom-of-pipe write is queued or in hand. This test covers a bottom-of-pipe value and CPU upload preparation. Gameplay, other CPU copy-back paths, and performance were outside its scope.

To reproduce, apply the test patch at the commit above and run the test below in a fresh process for each switch combination. I used an isolated Darner home and cache. Common settings were DARNER_ADAPTER=RTX 4060, DARNER_ASYNC_SUBMIT=1, DARNER_QUEUE_WAIT=1, DARNER_ASYNC_QUEUE=0, DARNER_LATE_WAIT=3, DARNER_LATE_WAIT_WRITES=1, DARNER_CARD_STEPS=0, DARNER_THIN=0, DARNER_JOIN_PARTS=1, and DARNER_SUBMIT_SPLIT=0. Use DARNER_RELAY=1 or 2, DARNER_LATE_FENCE=0 or 1, and DARNER_TEST_RELAY_LANDING=0 for the GPU gate or 1 for the relay latch.

cargo --config 'profile.test.debug=0' test --locked -p darner-gpu --lib queue::tests::a_cross_queue_fence_wait_preserves_a_bottom_of_pipe_write -- --exact --ignored --test-threads=1 --nocapture
Synthetic test patch
diff --git a/crates/darner-gpu/src/host.rs b/crates/darner-gpu/src/host.rs
index 44372fb..4637ae1 100644
--- a/crates/darner-gpu/src/host.rs
+++ b/crates/darner-gpu/src/host.rs
@@ -8420,7 +8420,17 @@ fn relay_worker() {
             }
         };
         match next {
-            Ok(items) => host.relay_land(items, &mut fetch),
+            Ok(items) => {
+                #[cfg(test)]
+                if items.iter().any(|item| matches!(item, Late::Write(..))) {
+                    let pause = RELAY_TEST_PAUSE.lock().unwrap().take();
+                    if let Some((paused, resume)) = pause {
+                        let _ = paused.send(());
+                        let _ = resume.recv_timeout(std::time::Duration::from_secs(10));
+                    }
+                }
+                host.relay_land(items, &mut fetch)
+            }
             Err(u64::MAX) => fail(format_args!("relay: device lost before publishing queued GPU work")),
             Err(target) => {
                 let waiting = std::time::Instant::now();
@@ -8438,6 +8448,20 @@ fn relay_worker() {
     }
 }
 
+#[cfg(test)]
+type RelayTestPause = (std::sync::mpsc::Sender<()>, std::sync::mpsc::Receiver<()>);
+
+#[cfg(test)]
+static RELAY_TEST_PAUSE: Mutex<Option<RelayTestPause>> = Mutex::new(None);
+
+#[cfg(test)]
+pub(crate) fn pause_before_relay_write() -> (std::sync::mpsc::Receiver<()>, std::sync::mpsc::Sender<()>) {
+    let (paused, at_landing) = std::sync::mpsc::channel();
+    let (release, resume) = std::sync::mpsc::channel();
+    assert!(RELAY_TEST_PAUSE.lock().unwrap().replace((paused, resume)).is_none());
+    (at_landing, release)
+}
+
 /// [`relay`]: what shaders wrote to the declared ranges `back` of copies
 /// in the PC's memory goes into title memory. As [`hand_back`], each byte
 /// once, the pieces that differ found on several threads; but the merge is
diff --git a/crates/darner-gpu/src/queue.rs b/crates/darner-gpu/src/queue.rs
index cd13a6e..03ad635 100644
--- a/crates/darner-gpu/src/queue.rs
+++ b/crates/darner-gpu/src/queue.rs
@@ -2007,6 +2007,134 @@ mod tests {
     use super::*;
     use crate::object::slot;
 
+    #[cfg(windows)]
+    #[test]
+    #[ignore = "requires a D3D12 adapter and DARNER_ASYNC_SUBMIT=1; run in its own process"]
+    fn a_cross_queue_fence_wait_preserves_a_bottom_of_pipe_write() {
+        use crate::object::IUNKNOWN;
+        use std::{ffi::c_void, ptr, sync::mpsc, thread, time::{Duration, Instant}};
+        use windows::Win32::Graphics::Direct3D12::{D3D12_FENCE_FLAG_NONE, D3D12_RANGE, ID3D12Fence};
+
+        struct Gate(ID3D12Fence);
+        impl Drop for Gate {
+            fn drop(&mut self) {
+                // SAFETY: this is the CPU signal that releases the test's queue wait.
+                let _ = unsafe { self.0.Signal(1) };
+            }
+        }
+
+        fn make_queue(kind: u32) -> This {
+            let desc = QueueDesc { kind, priority: 0, flags: 0, nodes: 0 };
+            let mut queue = ptr::null();
+            assert_eq!(create(ptr::null(), &desc, &IUNKNOWN, &mut queue), S_OK);
+            queue
+        }
+
+        fn make_list(kind: u32) -> This {
+            let mut allocator = ptr::null();
+            let mut list = ptr::null();
+            assert_eq!(crate::list::create_allocator(ptr::null(), kind, &IUNKNOWN, &mut allocator), S_OK);
+            assert_eq!(crate::list::create_list(ptr::null(), 0, kind, allocator, ptr::null(), &IUNKNOWN, &mut list), S_OK);
+            slot::<extern "system" fn(This) -> u32>(allocator, 0x10)(allocator);
+            list
+        }
+
+        fn make_fence() -> This {
+            let mut fence = ptr::null();
+            assert_eq!(crate::fence::create(ptr::null(), 0, 0, &IUNKNOWN, &mut fence), S_OK);
+            fence
+        }
+
+        const OLD: u64 = 0x1b;
+        const NEW: u64 = 0xb7;
+        let host = crate::host::host().expect("a D3D12 device");
+        assert!(behind::on());
+        assert!(waits());
+        assert!(crate::host::late());
+        assert!(!crate::host::two_queues::on());
+        let guest = Box::into_raw(Box::new(OLD));
+        let producer_queue = make_queue(0);
+        let consumer_queue = make_queue(2);
+        let producer = make_list(0);
+        let consumer = make_list(2);
+        let published = make_fence();
+        let done = make_fence();
+        let (scratch, scratch_data) = host.upload_buffer_own(8).expect("producer upload");
+        let producer_readback = host.read_back_buffer(8).expect("producer readback");
+        let (upload, upload_data) = host.upload_buffer_own(8).expect("consumer upload");
+        let readback = host.read_back_buffer(8).expect("consumer readback");
+        let (prepared, preparation) = mpsc::channel();
+        let a = crate::list::host_list_held(producer).expect("producer host list");
+        a.keep(&scratch);
+        a.keep(&producer_readback);
+        // SAFETY: live resources with eight bytes, and the command list is open.
+        unsafe {
+            scratch_data.cast::<u64>().write_unaligned(0x43);
+            a.list.CopyBufferRegion(&producer_readback, 0, &scratch, 0, 8);
+        }
+        let write64 = if crate::device::newer() { 0x240 } else { 0x230 };
+        slot::<extern "system" fn(This, u64, u64, u32, u32)>(producer, write64)(
+            producer, guest as u64, NEW, 0, 0,
+        );
+        assert_eq!(slot::<extern "system" fn(This) -> HRESULT>(producer, 0x48)(producer), S_OK);
+
+        let b = crate::list::host_list_held(consumer).expect("consumer host list");
+        b.keep(&upload);
+        b.keep(&readback);
+        b.defer_fill(upload_data, guest.cast::<u8>(), 8);
+        b.defer_host(move || { let _ = prepared.send(()); });
+        // SAFETY: live resources with eight bytes, and the command list is open.
+        unsafe { b.list.CopyBufferRegion(&readback, 0, &upload, 0, 8) };
+        assert_eq!(slot::<extern "system" fn(This) -> HRESULT>(consumer, 0x48)(consumer), S_OK);
+
+        // SAFETY: these are ordinary D3D12 fence calls on the host's direct queue.
+        let gate = Gate(unsafe { host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE) }.expect("gate"));
+        unsafe { host.queue().Wait(&gate.0, 1) }.expect("insert gate before either list");
+        let hold_landing = crate::asked_for!("DARNER_TEST_RELAY_LANDING");
+        let pause = hold_landing.then(crate::host::pause_before_relay_write);
+        execute(producer_queue, 1, &producer);
+        let resume_landing = pause.map(|(at_landing, resume)| {
+            unsafe { gate.0.Signal(1) }.expect("let the producer run");
+            at_landing.recv_timeout(Duration::from_secs(5)).expect("producer completed on the GPU and relay took the write");
+            resume
+        });
+        assert_eq!(signal(producer_queue, published, 1), S_OK);
+        assert_eq!(wait(consumer_queue, published, 1), S_OK);
+        execute(consumer_queue, 1, &consumer);
+        assert_eq!(signal(consumer_queue, done, 1), S_OK);
+        let prepared_before_publication = preparation.recv_timeout(Duration::from_secs(2)).is_ok();
+        let fence_before_publication = crate::fence::completed(published);
+        if let Some(resume) = resume_landing {
+            resume.send(()).expect("resume relay landing");
+        } else {
+            unsafe { gate.0.Signal(1) }.expect("open gate");
+        }
+
+        let deadline = Instant::now() + Duration::from_secs(10);
+        while crate::fence::completed(done) < 1 && Instant::now() < deadline {
+            thread::sleep(Duration::from_millis(1));
+        }
+        assert_eq!(crate::fence::completed(done), 1, "consumer did not finish");
+        assert_eq!(crate::fence::completed(published), 1, "producer did not finish");
+        let range = D3D12_RANGE { Begin: 0, End: 8 };
+        let mut data = ptr::null_mut::<c_void>();
+        // SAFETY: the guest fences have completed and the result resource has eight bytes.
+        let (source, result) = unsafe {
+            readback.Map(0, Some(&range), Some(&mut data)).expect("map consumer readback");
+            let result = data.cast::<u64>().read_unaligned();
+            readback.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 }));
+            let source = *Box::from_raw(guest);
+            (source, result)
+        };
+        for object in [producer, consumer, producer_queue, consumer_queue, published, done] {
+            slot::<extern "system" fn(This) -> u32>(object, 0x10)(object);
+        }
+        eprintln!("hold_landing={hold_landing} prepared_before_publication={prepared_before_publication} fence_before_publication={fence_before_publication} source={source:#04x} gpu_readback={result:#04x}");
+        assert_eq!(fence_before_publication, 0, "producer fence advanced while publication was held");
+        assert_eq!(source, NEW, "the bottom-of-pipe write did not land");
+        assert_eq!(result, NEW, "the GPU read back the bytes copied during the consumer's CPU preparation");
+    }
+
     #[test]
     fn the_queue_table_has_room_after_its_last_method() {
         crate::object::assert_room::<QUEUE, 46>(&super::FUNCTIONS, 38);
I reproduced a stale upload on `08e3ed5b77365eb66880df5a72e88fae5c82e32f` with an RTX 4060 8 GB (621.40), Windows 11 build 26300, and Rust 1.98.1. The synthetic test submits a producer and a consumer through Darner's graphics and compute queues, which share one real D3D12 direct queue. The producer's `Write64BitValueBottomOfPipeX` changes the source from `0x1b` to `0xb7` when the relay publishes it. The consumer waits on the producer's emulated fence, snapshots the source with `defer_fill`, and copies that upload buffer into a D3D12 readback. | What the test holds | `DARNER_LATE_FENCE` | Consumer CPU prep before fence publication | GPU readback | Runs | |---|---:|---|---:|---:| | Producer on the D3D12 queue | 0 | No | `0xb7` | 6/6 passed | | Producer on the D3D12 queue | 1 | Yes | `0x1b` | 6/6 failed the readback assertion | | Relay after draining the completed producer, before its CPU write | 0 | No | `0xb7` | 6/6 passed | | Relay after draining the completed producer, before its CPU write | 1 | Yes | `0x1b` | 6/6 failed the readback assertion | Each row covers three runs with `DARNER_RELAY=1` and three with `DARNER_RELAY=2`. In every run the producer's fence was 0 while publication was held. Both emulated fences later reached 1 and the CPU source became `0xb7`. In the first pair of rows the D3D12 fence itself holds the producer. That pair also reproduced with just the fixture in `queue.rs`. In the second pair a test-only latch holds the relay after the GPU completed the producer and the relay took its pending `Late::Write`. The test queues the producer's fence signal during that latch. `late_fence_met` can accept the pending signal in both windows. FIFO orders the GPU copies. The CPU prelude had already captured the consumer's upload bytes before the relay published the producer's write. The demonstrated case needs the emulated wait to keep holding while a preceding bottom-of-pipe write is queued or in hand. This test covers a bottom-of-pipe value and CPU upload preparation. Gameplay, other CPU copy-back paths, and performance were outside its scope. To reproduce, apply the test patch at the commit above and run the test below in a fresh process for each switch combination. I used an isolated Darner home and cache. Common settings were `DARNER_ADAPTER=RTX 4060`, `DARNER_ASYNC_SUBMIT=1`, `DARNER_QUEUE_WAIT=1`, `DARNER_ASYNC_QUEUE=0`, `DARNER_LATE_WAIT=3`, `DARNER_LATE_WAIT_WRITES=1`, `DARNER_CARD_STEPS=0`, `DARNER_THIN=0`, `DARNER_JOIN_PARTS=1`, and `DARNER_SUBMIT_SPLIT=0`. Use `DARNER_RELAY=1` or `2`, `DARNER_LATE_FENCE=0` or `1`, and `DARNER_TEST_RELAY_LANDING=0` for the GPU gate or `1` for the relay latch. ```powershell cargo --config 'profile.test.debug=0' test --locked -p darner-gpu --lib queue::tests::a_cross_queue_fence_wait_preserves_a_bottom_of_pipe_write -- --exact --ignored --test-threads=1 --nocapture ``` <details> <summary>Synthetic test patch</summary> ```diff diff --git a/crates/darner-gpu/src/host.rs b/crates/darner-gpu/src/host.rs index 44372fb..4637ae1 100644 --- a/crates/darner-gpu/src/host.rs +++ b/crates/darner-gpu/src/host.rs @@ -8420,7 +8420,17 @@ fn relay_worker() { } }; match next { - Ok(items) => host.relay_land(items, &mut fetch), + Ok(items) => { + #[cfg(test)] + if items.iter().any(|item| matches!(item, Late::Write(..))) { + let pause = RELAY_TEST_PAUSE.lock().unwrap().take(); + if let Some((paused, resume)) = pause { + let _ = paused.send(()); + let _ = resume.recv_timeout(std::time::Duration::from_secs(10)); + } + } + host.relay_land(items, &mut fetch) + } Err(u64::MAX) => fail(format_args!("relay: device lost before publishing queued GPU work")), Err(target) => { let waiting = std::time::Instant::now(); @@ -8438,6 +8448,20 @@ fn relay_worker() { } } +#[cfg(test)] +type RelayTestPause = (std::sync::mpsc::Sender<()>, std::sync::mpsc::Receiver<()>); + +#[cfg(test)] +static RELAY_TEST_PAUSE: Mutex<Option<RelayTestPause>> = Mutex::new(None); + +#[cfg(test)] +pub(crate) fn pause_before_relay_write() -> (std::sync::mpsc::Receiver<()>, std::sync::mpsc::Sender<()>) { + let (paused, at_landing) = std::sync::mpsc::channel(); + let (release, resume) = std::sync::mpsc::channel(); + assert!(RELAY_TEST_PAUSE.lock().unwrap().replace((paused, resume)).is_none()); + (at_landing, release) +} + /// [`relay`]: what shaders wrote to the declared ranges `back` of copies /// in the PC's memory goes into title memory. As [`hand_back`], each byte /// once, the pieces that differ found on several threads; but the merge is diff --git a/crates/darner-gpu/src/queue.rs b/crates/darner-gpu/src/queue.rs index cd13a6e..03ad635 100644 --- a/crates/darner-gpu/src/queue.rs +++ b/crates/darner-gpu/src/queue.rs @@ -2007,6 +2007,134 @@ mod tests { use super::*; use crate::object::slot; + #[cfg(windows)] + #[test] + #[ignore = "requires a D3D12 adapter and DARNER_ASYNC_SUBMIT=1; run in its own process"] + fn a_cross_queue_fence_wait_preserves_a_bottom_of_pipe_write() { + use crate::object::IUNKNOWN; + use std::{ffi::c_void, ptr, sync::mpsc, thread, time::{Duration, Instant}}; + use windows::Win32::Graphics::Direct3D12::{D3D12_FENCE_FLAG_NONE, D3D12_RANGE, ID3D12Fence}; + + struct Gate(ID3D12Fence); + impl Drop for Gate { + fn drop(&mut self) { + // SAFETY: this is the CPU signal that releases the test's queue wait. + let _ = unsafe { self.0.Signal(1) }; + } + } + + fn make_queue(kind: u32) -> This { + let desc = QueueDesc { kind, priority: 0, flags: 0, nodes: 0 }; + let mut queue = ptr::null(); + assert_eq!(create(ptr::null(), &desc, &IUNKNOWN, &mut queue), S_OK); + queue + } + + fn make_list(kind: u32) -> This { + let mut allocator = ptr::null(); + let mut list = ptr::null(); + assert_eq!(crate::list::create_allocator(ptr::null(), kind, &IUNKNOWN, &mut allocator), S_OK); + assert_eq!(crate::list::create_list(ptr::null(), 0, kind, allocator, ptr::null(), &IUNKNOWN, &mut list), S_OK); + slot::<extern "system" fn(This) -> u32>(allocator, 0x10)(allocator); + list + } + + fn make_fence() -> This { + let mut fence = ptr::null(); + assert_eq!(crate::fence::create(ptr::null(), 0, 0, &IUNKNOWN, &mut fence), S_OK); + fence + } + + const OLD: u64 = 0x1b; + const NEW: u64 = 0xb7; + let host = crate::host::host().expect("a D3D12 device"); + assert!(behind::on()); + assert!(waits()); + assert!(crate::host::late()); + assert!(!crate::host::two_queues::on()); + let guest = Box::into_raw(Box::new(OLD)); + let producer_queue = make_queue(0); + let consumer_queue = make_queue(2); + let producer = make_list(0); + let consumer = make_list(2); + let published = make_fence(); + let done = make_fence(); + let (scratch, scratch_data) = host.upload_buffer_own(8).expect("producer upload"); + let producer_readback = host.read_back_buffer(8).expect("producer readback"); + let (upload, upload_data) = host.upload_buffer_own(8).expect("consumer upload"); + let readback = host.read_back_buffer(8).expect("consumer readback"); + let (prepared, preparation) = mpsc::channel(); + let a = crate::list::host_list_held(producer).expect("producer host list"); + a.keep(&scratch); + a.keep(&producer_readback); + // SAFETY: live resources with eight bytes, and the command list is open. + unsafe { + scratch_data.cast::<u64>().write_unaligned(0x43); + a.list.CopyBufferRegion(&producer_readback, 0, &scratch, 0, 8); + } + let write64 = if crate::device::newer() { 0x240 } else { 0x230 }; + slot::<extern "system" fn(This, u64, u64, u32, u32)>(producer, write64)( + producer, guest as u64, NEW, 0, 0, + ); + assert_eq!(slot::<extern "system" fn(This) -> HRESULT>(producer, 0x48)(producer), S_OK); + + let b = crate::list::host_list_held(consumer).expect("consumer host list"); + b.keep(&upload); + b.keep(&readback); + b.defer_fill(upload_data, guest.cast::<u8>(), 8); + b.defer_host(move || { let _ = prepared.send(()); }); + // SAFETY: live resources with eight bytes, and the command list is open. + unsafe { b.list.CopyBufferRegion(&readback, 0, &upload, 0, 8) }; + assert_eq!(slot::<extern "system" fn(This) -> HRESULT>(consumer, 0x48)(consumer), S_OK); + + // SAFETY: these are ordinary D3D12 fence calls on the host's direct queue. + let gate = Gate(unsafe { host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE) }.expect("gate")); + unsafe { host.queue().Wait(&gate.0, 1) }.expect("insert gate before either list"); + let hold_landing = crate::asked_for!("DARNER_TEST_RELAY_LANDING"); + let pause = hold_landing.then(crate::host::pause_before_relay_write); + execute(producer_queue, 1, &producer); + let resume_landing = pause.map(|(at_landing, resume)| { + unsafe { gate.0.Signal(1) }.expect("let the producer run"); + at_landing.recv_timeout(Duration::from_secs(5)).expect("producer completed on the GPU and relay took the write"); + resume + }); + assert_eq!(signal(producer_queue, published, 1), S_OK); + assert_eq!(wait(consumer_queue, published, 1), S_OK); + execute(consumer_queue, 1, &consumer); + assert_eq!(signal(consumer_queue, done, 1), S_OK); + let prepared_before_publication = preparation.recv_timeout(Duration::from_secs(2)).is_ok(); + let fence_before_publication = crate::fence::completed(published); + if let Some(resume) = resume_landing { + resume.send(()).expect("resume relay landing"); + } else { + unsafe { gate.0.Signal(1) }.expect("open gate"); + } + + let deadline = Instant::now() + Duration::from_secs(10); + while crate::fence::completed(done) < 1 && Instant::now() < deadline { + thread::sleep(Duration::from_millis(1)); + } + assert_eq!(crate::fence::completed(done), 1, "consumer did not finish"); + assert_eq!(crate::fence::completed(published), 1, "producer did not finish"); + let range = D3D12_RANGE { Begin: 0, End: 8 }; + let mut data = ptr::null_mut::<c_void>(); + // SAFETY: the guest fences have completed and the result resource has eight bytes. + let (source, result) = unsafe { + readback.Map(0, Some(&range), Some(&mut data)).expect("map consumer readback"); + let result = data.cast::<u64>().read_unaligned(); + readback.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 })); + let source = *Box::from_raw(guest); + (source, result) + }; + for object in [producer, consumer, producer_queue, consumer_queue, published, done] { + slot::<extern "system" fn(This) -> u32>(object, 0x10)(object); + } + eprintln!("hold_landing={hold_landing} prepared_before_publication={prepared_before_publication} fence_before_publication={fence_before_publication} source={source:#04x} gpu_readback={result:#04x}"); + assert_eq!(fence_before_publication, 0, "producer fence advanced while publication was held"); + assert_eq!(source, NEW, "the bottom-of-pipe write did not land"); + assert_eq!(result, NEW, "the GPU read back the bytes copied during the consumer's CPU preparation"); + } + #[test] fn the_queue_table_has_room_after_its_last_method() { crate::object::assert_room::<QUEUE, 46>(&super::FUNCTIONS, 38); ``` </details>
Contributor

The stale value also occurs with a plain list readback as the producer's sole CPU publication. On 08e3ed5b77365eb66880df5a72e88fae5c82e32f, the defer_read_back case returned 0x1b in all four opt-in runs and the expected 0xb7 in all four opt-out runs. These cover relay modes 1 and 2, both before the producer's GPU work finishes and after the relay takes the completed list. The original fixture covered bottom-of-pipe writes. First reproduction

I tested the guard below on the same head. It keeps the emulated wait while the relay is settling and scans only as far as the matching pending signal. Earlier bottom-of-pipe writes, list or texture readbacks, declared copy-backs, or work via card_steps keep the wait held. submit records the plain-readback bit alongside texture_back_ranges under the existing list lock. The predicate uses the stored bit under LINE.

Producer with the guard and DARNER_LATE_FENCE=1 Cases passed Consumer CPU prep while publication was held GPU readback
Bottom-of-pipe write 16/16 No 0xb7
Plain list readback 16/16 No 0xb7
GPU-only copy with no CPU publication 8/8 Yes Expected 0x1b

Two additional opt-out runs passed. Ten of the opt-in runs used the separate sender (DARNER_RELAY=2 DARNER_RELAY_COPY=1 DARNER_SUBMIT_SPLIT=1). The fixture confirmed that both submissions went through it. The nine queue::behind unit tests and flight_texture_back_ranges_refuse_stale_shadow_holder passed. So did cargo clippy --locked -p darner-gpu --all-targets --all-features -- -D warnings. Hardware was RTX 4060 8 GB, driver 621.40, Windows 11 build 26300, and Rust 1.98.1. This covers synthetic queue ordering. Frequency in gameplay and the effect on frame times remain unmeasured.

Apply the fixture at 08e3ed5b77365eb66880df5a72e88fae5c82e32f to test the original behaviour, or apply both patches to test the guard. Use the settings in the first report. Set DARNER_TEST_FENCE_READBACK=1 for the plain readback or DARNER_TEST_FENCE_GPU_ONLY=1 for the GPU-only control. Leaving those switches off selects the bottom-of-pipe write. DARNER_TEST_RELAY_LANDING=0 holds the D3D12 queue and 1 holds the relay before it publishes. Run each combination in its own process.

cargo --config 'profile.test.debug=0' test --locked -p darner-gpu --lib queue::tests::a_cross_queue_fence_wait_orders_cpu_publication -- --exact --ignored --test-threads=1 --nocapture
Tested guard (candidate patch)
diff --git a/crates/darner-gpu/src/host.rs b/crates/darner-gpu/src/host.rs
index 44372fb..03cb730 100644
--- a/crates/darner-gpu/src/host.rs
+++ b/crates/darner-gpu/src/host.rs
@@ -6316,6 +6316,8 @@ struct Sent {
     own: Option<card_steps::Taken>,
     /// Title-memory ranges written when its shader textures are copied back.
     texture_back_ranges: Vec<(usize, usize)>,
+    /// A list reads back bytes into title memory when this submission lands.
+    list_read_backs: bool,
     /// Its bottom-of-pipe writes.
     writes: Vec<(usize, crate::queue::Written, usize)>,
     /// Published ([`split_send`]): what the thread that sends it does.
@@ -6999,6 +7001,7 @@ struct Flight {
     /// The list of ours that ran ahead of them ([`card_steps`]).
     own: Option<card_steps::Taken>,
     texture_back_ranges: Vec<(usize, usize)>,
+    list_read_backs: bool,
 }
 
 /// One thing in the line of what waits for the card, in order.
@@ -7720,17 +7723,26 @@ pub(crate) fn late_signal(fence: crate::object::This, value: u64) -> bool {
 /// a waiting queue can submit right behind the in-flight signal without
 /// stalling the sender thread for the GPU to drain.
 pub(crate) fn late_fence_met(fence: crate::object::This, value: u64) -> bool {
-    static ON: OnceLock<bool> = OnceLock::new();
-    if !*ON.get_or_init(|| std::env::var_os("DARNER_LATE_FENCE").is_some_and(|v| v == "1")) {
+    if !crate::asked_for!("DARNER_LATE_FENCE") || two_queues::on() {
         return false;
     }
-    if two_queues::on() {
+    let line = line();
+    // A landing has already taken its pending writes and read-backs out of the line.
+    if line.settling {
         return false;
     }
-    let line = line();
-    line.line
-        .iter()
-        .any(|item| matches!(item, Late::Signal(f, v) if f.as_this() == fence && *v >= value))
+    // FIFO orders the GPU work. CPU preparation still waits for earlier
+    // results written to title memory.
+    for item in &line.line {
+        match item {
+            Late::Signal(f, v) if f.as_this() == fence && *v >= value => return true,
+            Late::Write(..) => return false,
+            Late::Run(flight) if flight.list_read_backs || flight.own.is_some()
+                || !flight.back.is_empty() || !flight.texture_back_ranges.is_empty() => return false,
+            _ => {}
+        }
+    }
+    false
 }
 
 /// A queue stands at `wait`, which memory does not meet now ([`late`]):
@@ -11284,6 +11296,7 @@ impl Host {
                 back: sent.back,
                 own: sent.own,
                 texture_back_ranges: sent.texture_back_ranges,
+                list_read_backs: sent.list_read_backs,
             }));
             items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
             *flying >= late_most()
@@ -11349,6 +11362,7 @@ impl Host {
                 back: sent.back,
                 own: sent.own,
                 texture_back_ranges: sent.texture_back_ranges,
+                list_read_backs: sent.list_read_backs,
             }));
             items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
         }
@@ -12348,8 +12362,11 @@ impl Host {
             *submitted += 1;
             let back = crate::picked::with(declared, &picked.written);
             let mut texture_back_ranges = Vec::new();
+            let mut list_read_backs = false;
             for list in runs {
-                texture_back_ranges.extend(list.deferred().texture_backs.iter().map(crate::texback::Back::range));
+                let deferred = list.deferred();
+                texture_back_ranges.extend(deferred.texture_backs.iter().map(crate::texback::Back::range));
+                list_read_backs |= !deferred.backs.is_empty();
             }
             let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
             SUBMISSION_US[0].fetch_add(started.elapsed().saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
@@ -12376,6 +12393,7 @@ impl Host {
                 back,
                 own,
                 texture_back_ranges,
+                list_read_backs,
                 writes,
                 handoff: Some(Box::new(handoff)),
             };
@@ -12459,8 +12477,11 @@ impl Host {
             split.part(5);
             let back = crate::picked::with(declared, &picked.written);
             let mut texture_back_ranges = Vec::new();
+            let mut list_read_backs = false;
             for list in runs {
-                texture_back_ranges.extend(list.deferred().texture_backs.iter().map(crate::texback::Back::range));
+                let deferred = list.deferred();
+                texture_back_ranges.extend(deferred.texture_backs.iter().map(crate::texback::Back::range));
+                list_read_backs |= !deferred.backs.is_empty();
             }
             let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
             SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
@@ -12473,6 +12494,7 @@ impl Host {
                 back,
                 own,
                 texture_back_ranges,
+                list_read_backs,
                 writes,
                 handoff: None,
             };
diff --git a/crates/darner-gpu/src/host/card_steps.rs b/crates/darner-gpu/src/host/card_steps.rs
index ddadf97..e2da581 100644
--- a/crates/darner-gpu/src/host/card_steps.rs
+++ b/crates/darner-gpu/src/host/card_steps.rs
@@ -3200,6 +3200,7 @@ mod tests {
             back: vec![(shadow.clone(), vec![(start, start + 4096)])],
             own: None,
             texture_back_ranges: vec![(start + 256, start + 512)],
+            list_read_backs: false,
         })];
         let active = writers(&items);
         assert!(
Synthetic fixture
diff --git a/crates/darner-gpu/src/host.rs b/crates/darner-gpu/src/host.rs
index 03cb730..2fc0428 100644
--- a/crates/darner-gpu/src/host.rs
+++ b/crates/darner-gpu/src/host.rs
@@ -8432,7 +8432,17 @@ fn relay_worker() {
             }
         };
         match next {
-            Ok(items) => host.relay_land(items, &mut fetch),
+            Ok(items) => {
+                #[cfg(test)]
+                if items.iter().any(|item| matches!(item, Late::Run(_))) {
+                    let pause = RELAY_TEST_PAUSE.lock().unwrap().take();
+                    if let Some((paused, resume)) = pause {
+                        let _ = paused.send(());
+                        let _ = resume.recv_timeout(std::time::Duration::from_secs(10));
+                    }
+                }
+                host.relay_land(items, &mut fetch)
+            }
             Err(u64::MAX) => fail(format_args!("relay: device lost before publishing queued GPU work")),
             Err(target) => {
                 let waiting = std::time::Instant::now();
@@ -8450,6 +8460,25 @@ fn relay_worker() {
     }
 }
 
+#[cfg(test)]
+type RelayTestPause = (std::sync::mpsc::Sender<()>, std::sync::mpsc::Receiver<()>);
+
+#[cfg(test)]
+static RELAY_TEST_PAUSE: Mutex<Option<RelayTestPause>> = Mutex::new(None);
+
+#[cfg(test)]
+pub(crate) fn pause_before_relay_publication() -> (std::sync::mpsc::Receiver<()>, std::sync::mpsc::Sender<()>) {
+    let (paused, at_landing) = std::sync::mpsc::channel();
+    let (release, resume) = std::sync::mpsc::channel();
+    assert!(RELAY_TEST_PAUSE.lock().unwrap().replace((paused, resume)).is_none());
+    (at_landing, release)
+}
+
+#[cfg(test)]
+pub(crate) fn published_submission_count() -> u64 {
+    SEND_STATS[0].load(Ordering::Relaxed)
+}
+
 /// [`relay`]: what shaders wrote to the declared ranges `back` of copies
 /// in the PC's memory goes into title memory. As [`hand_back`], each byte
 /// once, the pieces that differ found on several threads; but the merge is
diff --git a/crates/darner-gpu/src/queue.rs b/crates/darner-gpu/src/queue.rs
index cd13a6e..67b5878 100644
--- a/crates/darner-gpu/src/queue.rs
+++ b/crates/darner-gpu/src/queue.rs
@@ -2007,6 +2007,161 @@ mod tests {
     use super::*;
     use crate::object::slot;
 
+    #[cfg(windows)]
+    #[test]
+    #[ignore = "requires a D3D12 adapter and DARNER_ASYNC_SUBMIT=1; run in its own process"]
+    fn a_cross_queue_fence_wait_orders_cpu_publication() {
+        use crate::object::IUNKNOWN;
+        use std::{ffi::c_void, ptr, sync::mpsc, thread, time::{Duration, Instant}};
+        use windows::Win32::Graphics::Direct3D12::{D3D12_FENCE_FLAG_NONE, D3D12_RANGE, ID3D12Fence};
+
+        struct Gate(ID3D12Fence);
+        impl Drop for Gate {
+            fn drop(&mut self) {
+                // SAFETY: this is the CPU signal that releases the test's queue wait.
+                let _ = unsafe { self.0.Signal(1) };
+            }
+        }
+
+        fn make_queue(kind: u32) -> This {
+            let desc = QueueDesc { kind, priority: 0, flags: 0, nodes: 0 };
+            let mut queue = ptr::null();
+            assert_eq!(create(ptr::null(), &desc, &IUNKNOWN, &mut queue), S_OK);
+            queue
+        }
+
+        fn make_list(kind: u32) -> This {
+            let mut allocator = ptr::null();
+            let mut list = ptr::null();
+            assert_eq!(crate::list::create_allocator(ptr::null(), kind, &IUNKNOWN, &mut allocator), S_OK);
+            assert_eq!(crate::list::create_list(ptr::null(), 0, kind, allocator, ptr::null(), &IUNKNOWN, &mut list), S_OK);
+            slot::<extern "system" fn(This) -> u32>(allocator, 0x10)(allocator);
+            list
+        }
+
+        fn make_fence() -> This {
+            let mut fence = ptr::null();
+            assert_eq!(crate::fence::create(ptr::null(), 0, 0, &IUNKNOWN, &mut fence), S_OK);
+            fence
+        }
+
+        const OLD: u64 = 0x1b;
+        const NEW: u64 = 0xb7;
+        let read_back = crate::asked_for!("DARNER_TEST_FENCE_READBACK");
+        let gpu_only = crate::asked_for!("DARNER_TEST_FENCE_GPU_ONLY");
+        assert!(!(read_back && gpu_only));
+        let expected = if gpu_only { OLD } else { NEW };
+        let host = crate::host::host().expect("a D3D12 device");
+        assert!(behind::on());
+        assert!(waits());
+        assert!(crate::host::late());
+        assert!(!crate::host::two_queues::on());
+        let guest = Box::into_raw(Box::new(OLD));
+        let producer_queue = make_queue(0);
+        let consumer_queue = make_queue(2);
+        let producer = make_list(0);
+        let consumer = make_list(2);
+        let published = make_fence();
+        let done = make_fence();
+        let (scratch, scratch_data) = host.upload_buffer_own(8).expect("producer upload");
+        let producer_readback = host.read_back(8).expect("producer readback");
+        let (upload, upload_data) = host.upload_buffer_own(8).expect("consumer upload");
+        let readback = host.read_back_buffer(8).expect("consumer readback");
+        let (prepared, preparation) = mpsc::channel();
+        let a = crate::list::host_list_held(producer).expect("producer host list");
+        a.keep(&scratch);
+        a.keep(producer_readback.resource());
+        // SAFETY: live resources with eight bytes, and the command list is open.
+        unsafe {
+            scratch_data.cast::<u64>().write_unaligned(NEW);
+            a.list.CopyBufferRegion(producer_readback.resource(), 0, &scratch, 0, 8);
+        }
+        if read_back {
+            a.defer_read_back(producer_readback, guest.cast::<u8>(), crate::resource::ReadbackRows {
+                row: 8,
+                rows: 1,
+                depth: 1,
+                pitch: 8,
+                slice_pitch: 8,
+            });
+        } else if !gpu_only {
+            let write64 = if crate::device::newer() { 0x240 } else { 0x230 };
+            slot::<extern "system" fn(This, u64, u64, u32, u32)>(producer, write64)(
+                producer, guest as u64, NEW, 0, 0,
+            );
+        }
+        assert_eq!(slot::<extern "system" fn(This) -> HRESULT>(producer, 0x48)(producer), S_OK);
+
+        let b = crate::list::host_list_held(consumer).expect("consumer host list");
+        b.keep(&upload);
+        b.keep(&readback);
+        b.defer_fill(upload_data, guest.cast::<u8>(), 8);
+        b.defer_host(move || { let _ = prepared.send(()); });
+        // SAFETY: live resources with eight bytes, and the command list is open.
+        unsafe { b.list.CopyBufferRegion(&readback, 0, &upload, 0, 8) };
+        assert_eq!(slot::<extern "system" fn(This) -> HRESULT>(consumer, 0x48)(consumer), S_OK);
+
+        // SAFETY: these are ordinary D3D12 fence calls on the host's direct queue.
+        let gate = Gate(unsafe { host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE) }.expect("gate"));
+        unsafe { host.queue().Wait(&gate.0, 1) }.expect("insert gate before either list");
+        let hold_landing = crate::asked_for!("DARNER_TEST_RELAY_LANDING");
+        let split = crate::asked_for!("DARNER_SUBMIT_SPLIT");
+        let published_before_test = crate::host::published_submission_count();
+        let pause = hold_landing.then(crate::host::pause_before_relay_publication);
+        execute(producer_queue, 1, &producer);
+        let resume_landing = pause.map(|(at_landing, resume)| {
+            unsafe { gate.0.Signal(1) }.expect("let the producer run");
+            at_landing.recv_timeout(Duration::from_secs(5)).expect("relay took the completed producer");
+            resume
+        });
+        assert_eq!(signal(producer_queue, published, 1), S_OK);
+        assert_eq!(wait(consumer_queue, published, 1), S_OK);
+        execute(consumer_queue, 1, &consumer);
+        assert_eq!(signal(consumer_queue, done, 1), S_OK);
+        let prepared_before_publication = preparation.recv_timeout(Duration::from_secs(2)).is_ok();
+        let fence_before_publication = crate::fence::completed(published);
+        if let Some(resume) = resume_landing {
+            resume.send(()).expect("resume relay landing");
+        } else {
+            unsafe { gate.0.Signal(1) }.expect("open gate");
+        }
+
+        let deadline = Instant::now() + Duration::from_secs(10);
+        while (crate::fence::completed(done) < 1
+            || split && crate::host::published_submission_count() < published_before_test + 2)
+            && Instant::now() < deadline
+        {
+            thread::sleep(Duration::from_millis(1));
+        }
+        assert_eq!(crate::fence::completed(done), 1, "consumer did not finish");
+        assert_eq!(crate::fence::completed(published), 1, "producer did not finish");
+        let published_lists = crate::host::published_submission_count() - published_before_test;
+        if split {
+            assert_eq!(published_lists, 2, "both submissions must use the separate sender");
+        }
+        let range = D3D12_RANGE { Begin: 0, End: 8 };
+        let mut data = ptr::null_mut::<c_void>();
+        // SAFETY: the guest fences have completed and the result resource has eight bytes.
+        let (source, result) = unsafe {
+            readback.Map(0, Some(&range), Some(&mut data)).expect("map consumer readback");
+            let result = data.cast::<u64>().read_unaligned();
+            readback.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 }));
+            let source = *Box::from_raw(guest);
+            (source, result)
+        };
+        for object in [producer, consumer, producer_queue, consumer_queue, published, done] {
+            slot::<extern "system" fn(This) -> u32>(object, 0x10)(object);
+        }
+        eprintln!("read_back={read_back} gpu_only={gpu_only} hold_landing={hold_landing} published_lists={published_lists} prepared_before_publication={prepared_before_publication} fence_before_publication={fence_before_publication} source={source:#04x} gpu_readback={result:#04x}");
+        assert_eq!(fence_before_publication, 0, "producer fence advanced while publication was held");
+        assert_eq!(source, expected, "the producer did not publish the expected source bytes");
+        assert_eq!(result, expected, "the GPU read back the bytes copied during the consumer's CPU preparation");
+        if gpu_only && !hold_landing {
+            assert_eq!(prepared_before_publication, crate::asked_for!("DARNER_LATE_FENCE"),
+                "GPU-only work should take the fast path only when enabled");
+        }
+    }
+
     #[test]
     fn the_queue_table_has_room_after_its_last_method() {
         crate::object::assert_room::<QUEUE, 46>(&super::FUNCTIONS, 38);
The stale value also occurs with a plain list readback as the producer's sole CPU publication. On `08e3ed5b77365eb66880df5a72e88fae5c82e32f`, the `defer_read_back` case returned `0x1b` in all four opt-in runs and the expected `0xb7` in all four opt-out runs. These cover relay modes 1 and 2, both before the producer's GPU work finishes and after the relay takes the completed list. The original fixture covered bottom-of-pipe writes. [First reproduction](https://git.gtahub.st/TrustNo1/Darner/pulls/93#issuecomment-853439) I tested the guard below on the same head. It keeps the emulated wait while the relay is settling and scans only as far as the matching pending signal. Earlier bottom-of-pipe writes, list or texture readbacks, declared copy-backs, or work via `card_steps` keep the wait held. `submit` records the plain-readback bit alongside `texture_back_ranges` under the existing list lock. The predicate uses the stored bit under `LINE`. | Producer with the guard and `DARNER_LATE_FENCE=1` | Cases passed | Consumer CPU prep while publication was held | GPU readback | |---|---:|---|---:| | Bottom-of-pipe write | 16/16 | No | `0xb7` | | Plain list readback | 16/16 | No | `0xb7` | | GPU-only copy with no CPU publication | 8/8 | Yes | Expected `0x1b` | Two additional opt-out runs passed. Ten of the opt-in runs used the separate sender (`DARNER_RELAY=2 DARNER_RELAY_COPY=1 DARNER_SUBMIT_SPLIT=1`). The fixture confirmed that both submissions went through it. The nine `queue::behind` unit tests and `flight_texture_back_ranges_refuse_stale_shadow_holder` passed. So did `cargo clippy --locked -p darner-gpu --all-targets --all-features -- -D warnings`. Hardware was RTX 4060 8 GB, driver 621.40, Windows 11 build 26300, and Rust 1.98.1. This covers synthetic queue ordering. Frequency in gameplay and the effect on frame times remain unmeasured. Apply the fixture at `08e3ed5b77365eb66880df5a72e88fae5c82e32f` to test the original behaviour, or apply both patches to test the guard. Use the settings in the first report. Set `DARNER_TEST_FENCE_READBACK=1` for the plain readback or `DARNER_TEST_FENCE_GPU_ONLY=1` for the GPU-only control. Leaving those switches off selects the bottom-of-pipe write. `DARNER_TEST_RELAY_LANDING=0` holds the D3D12 queue and `1` holds the relay before it publishes. Run each combination in its own process. ```powershell cargo --config 'profile.test.debug=0' test --locked -p darner-gpu --lib queue::tests::a_cross_queue_fence_wait_orders_cpu_publication -- --exact --ignored --test-threads=1 --nocapture ``` <details> <summary>Tested guard (candidate patch)</summary> ```diff diff --git a/crates/darner-gpu/src/host.rs b/crates/darner-gpu/src/host.rs index 44372fb..03cb730 100644 --- a/crates/darner-gpu/src/host.rs +++ b/crates/darner-gpu/src/host.rs @@ -6316,6 +6316,8 @@ struct Sent { own: Option<card_steps::Taken>, /// Title-memory ranges written when its shader textures are copied back. texture_back_ranges: Vec<(usize, usize)>, + /// A list reads back bytes into title memory when this submission lands. + list_read_backs: bool, /// Its bottom-of-pipe writes. writes: Vec<(usize, crate::queue::Written, usize)>, /// Published ([`split_send`]): what the thread that sends it does. @@ -6999,6 +7001,7 @@ struct Flight { /// The list of ours that ran ahead of them ([`card_steps`]). own: Option<card_steps::Taken>, texture_back_ranges: Vec<(usize, usize)>, + list_read_backs: bool, } /// One thing in the line of what waits for the card, in order. @@ -7720,17 +7723,26 @@ pub(crate) fn late_signal(fence: crate::object::This, value: u64) -> bool { /// a waiting queue can submit right behind the in-flight signal without /// stalling the sender thread for the GPU to drain. pub(crate) fn late_fence_met(fence: crate::object::This, value: u64) -> bool { - static ON: OnceLock<bool> = OnceLock::new(); - if !*ON.get_or_init(|| std::env::var_os("DARNER_LATE_FENCE").is_some_and(|v| v == "1")) { + if !crate::asked_for!("DARNER_LATE_FENCE") || two_queues::on() { return false; } - if two_queues::on() { + let line = line(); + // A landing has already taken its pending writes and read-backs out of the line. + if line.settling { return false; } - let line = line(); - line.line - .iter() - .any(|item| matches!(item, Late::Signal(f, v) if f.as_this() == fence && *v >= value)) + // FIFO orders the GPU work. CPU preparation still waits for earlier + // results written to title memory. + for item in &line.line { + match item { + Late::Signal(f, v) if f.as_this() == fence && *v >= value => return true, + Late::Write(..) => return false, + Late::Run(flight) if flight.list_read_backs || flight.own.is_some() + || !flight.back.is_empty() || !flight.texture_back_ranges.is_empty() => return false, + _ => {} + } + } + false } /// A queue stands at `wait`, which memory does not meet now ([`late`]): @@ -11284,6 +11296,7 @@ impl Host { back: sent.back, own: sent.own, texture_back_ranges: sent.texture_back_ranges, + list_read_backs: sent.list_read_backs, })); items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); *flying >= late_most() @@ -11349,6 +11362,7 @@ impl Host { back: sent.back, own: sent.own, texture_back_ranges: sent.texture_back_ranges, + list_read_backs: sent.list_read_backs, })); items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); } @@ -12348,8 +12362,11 @@ impl Host { *submitted += 1; let back = crate::picked::with(declared, &picked.written); let mut texture_back_ranges = Vec::new(); + let mut list_read_backs = false; for list in runs { - texture_back_ranges.extend(list.deferred().texture_backs.iter().map(crate::texback::Back::range)); + let deferred = list.deferred(); + texture_back_ranges.extend(deferred.texture_backs.iter().map(crate::texback::Back::range)); + list_read_backs |= !deferred.backs.is_empty(); } let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect(); SUBMISSION_US[0].fetch_add(started.elapsed().saturating_sub(settled).as_micros() as u64, Ordering::Relaxed); @@ -12376,6 +12393,7 @@ impl Host { back, own, texture_back_ranges, + list_read_backs, writes, handoff: Some(Box::new(handoff)), }; @@ -12459,8 +12477,11 @@ impl Host { split.part(5); let back = crate::picked::with(declared, &picked.written); let mut texture_back_ranges = Vec::new(); + let mut list_read_backs = false; for list in runs { - texture_back_ranges.extend(list.deferred().texture_backs.iter().map(crate::texback::Back::range)); + let deferred = list.deferred(); + texture_back_ranges.extend(deferred.texture_backs.iter().map(crate::texback::Back::range)); + list_read_backs |= !deferred.backs.is_empty(); } let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect(); SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed); @@ -12473,6 +12494,7 @@ impl Host { back, own, texture_back_ranges, + list_read_backs, writes, handoff: None, }; diff --git a/crates/darner-gpu/src/host/card_steps.rs b/crates/darner-gpu/src/host/card_steps.rs index ddadf97..e2da581 100644 --- a/crates/darner-gpu/src/host/card_steps.rs +++ b/crates/darner-gpu/src/host/card_steps.rs @@ -3200,6 +3200,7 @@ mod tests { back: vec![(shadow.clone(), vec![(start, start + 4096)])], own: None, texture_back_ranges: vec![(start + 256, start + 512)], + list_read_backs: false, })]; let active = writers(&items); assert!( ``` </details> <details> <summary>Synthetic fixture</summary> ```diff diff --git a/crates/darner-gpu/src/host.rs b/crates/darner-gpu/src/host.rs index 03cb730..2fc0428 100644 --- a/crates/darner-gpu/src/host.rs +++ b/crates/darner-gpu/src/host.rs @@ -8432,7 +8432,17 @@ fn relay_worker() { } }; match next { - Ok(items) => host.relay_land(items, &mut fetch), + Ok(items) => { + #[cfg(test)] + if items.iter().any(|item| matches!(item, Late::Run(_))) { + let pause = RELAY_TEST_PAUSE.lock().unwrap().take(); + if let Some((paused, resume)) = pause { + let _ = paused.send(()); + let _ = resume.recv_timeout(std::time::Duration::from_secs(10)); + } + } + host.relay_land(items, &mut fetch) + } Err(u64::MAX) => fail(format_args!("relay: device lost before publishing queued GPU work")), Err(target) => { let waiting = std::time::Instant::now(); @@ -8450,6 +8460,25 @@ fn relay_worker() { } } +#[cfg(test)] +type RelayTestPause = (std::sync::mpsc::Sender<()>, std::sync::mpsc::Receiver<()>); + +#[cfg(test)] +static RELAY_TEST_PAUSE: Mutex<Option<RelayTestPause>> = Mutex::new(None); + +#[cfg(test)] +pub(crate) fn pause_before_relay_publication() -> (std::sync::mpsc::Receiver<()>, std::sync::mpsc::Sender<()>) { + let (paused, at_landing) = std::sync::mpsc::channel(); + let (release, resume) = std::sync::mpsc::channel(); + assert!(RELAY_TEST_PAUSE.lock().unwrap().replace((paused, resume)).is_none()); + (at_landing, release) +} + +#[cfg(test)] +pub(crate) fn published_submission_count() -> u64 { + SEND_STATS[0].load(Ordering::Relaxed) +} + /// [`relay`]: what shaders wrote to the declared ranges `back` of copies /// in the PC's memory goes into title memory. As [`hand_back`], each byte /// once, the pieces that differ found on several threads; but the merge is diff --git a/crates/darner-gpu/src/queue.rs b/crates/darner-gpu/src/queue.rs index cd13a6e..67b5878 100644 --- a/crates/darner-gpu/src/queue.rs +++ b/crates/darner-gpu/src/queue.rs @@ -2007,6 +2007,161 @@ mod tests { use super::*; use crate::object::slot; + #[cfg(windows)] + #[test] + #[ignore = "requires a D3D12 adapter and DARNER_ASYNC_SUBMIT=1; run in its own process"] + fn a_cross_queue_fence_wait_orders_cpu_publication() { + use crate::object::IUNKNOWN; + use std::{ffi::c_void, ptr, sync::mpsc, thread, time::{Duration, Instant}}; + use windows::Win32::Graphics::Direct3D12::{D3D12_FENCE_FLAG_NONE, D3D12_RANGE, ID3D12Fence}; + + struct Gate(ID3D12Fence); + impl Drop for Gate { + fn drop(&mut self) { + // SAFETY: this is the CPU signal that releases the test's queue wait. + let _ = unsafe { self.0.Signal(1) }; + } + } + + fn make_queue(kind: u32) -> This { + let desc = QueueDesc { kind, priority: 0, flags: 0, nodes: 0 }; + let mut queue = ptr::null(); + assert_eq!(create(ptr::null(), &desc, &IUNKNOWN, &mut queue), S_OK); + queue + } + + fn make_list(kind: u32) -> This { + let mut allocator = ptr::null(); + let mut list = ptr::null(); + assert_eq!(crate::list::create_allocator(ptr::null(), kind, &IUNKNOWN, &mut allocator), S_OK); + assert_eq!(crate::list::create_list(ptr::null(), 0, kind, allocator, ptr::null(), &IUNKNOWN, &mut list), S_OK); + slot::<extern "system" fn(This) -> u32>(allocator, 0x10)(allocator); + list + } + + fn make_fence() -> This { + let mut fence = ptr::null(); + assert_eq!(crate::fence::create(ptr::null(), 0, 0, &IUNKNOWN, &mut fence), S_OK); + fence + } + + const OLD: u64 = 0x1b; + const NEW: u64 = 0xb7; + let read_back = crate::asked_for!("DARNER_TEST_FENCE_READBACK"); + let gpu_only = crate::asked_for!("DARNER_TEST_FENCE_GPU_ONLY"); + assert!(!(read_back && gpu_only)); + let expected = if gpu_only { OLD } else { NEW }; + let host = crate::host::host().expect("a D3D12 device"); + assert!(behind::on()); + assert!(waits()); + assert!(crate::host::late()); + assert!(!crate::host::two_queues::on()); + let guest = Box::into_raw(Box::new(OLD)); + let producer_queue = make_queue(0); + let consumer_queue = make_queue(2); + let producer = make_list(0); + let consumer = make_list(2); + let published = make_fence(); + let done = make_fence(); + let (scratch, scratch_data) = host.upload_buffer_own(8).expect("producer upload"); + let producer_readback = host.read_back(8).expect("producer readback"); + let (upload, upload_data) = host.upload_buffer_own(8).expect("consumer upload"); + let readback = host.read_back_buffer(8).expect("consumer readback"); + let (prepared, preparation) = mpsc::channel(); + let a = crate::list::host_list_held(producer).expect("producer host list"); + a.keep(&scratch); + a.keep(producer_readback.resource()); + // SAFETY: live resources with eight bytes, and the command list is open. + unsafe { + scratch_data.cast::<u64>().write_unaligned(NEW); + a.list.CopyBufferRegion(producer_readback.resource(), 0, &scratch, 0, 8); + } + if read_back { + a.defer_read_back(producer_readback, guest.cast::<u8>(), crate::resource::ReadbackRows { + row: 8, + rows: 1, + depth: 1, + pitch: 8, + slice_pitch: 8, + }); + } else if !gpu_only { + let write64 = if crate::device::newer() { 0x240 } else { 0x230 }; + slot::<extern "system" fn(This, u64, u64, u32, u32)>(producer, write64)( + producer, guest as u64, NEW, 0, 0, + ); + } + assert_eq!(slot::<extern "system" fn(This) -> HRESULT>(producer, 0x48)(producer), S_OK); + + let b = crate::list::host_list_held(consumer).expect("consumer host list"); + b.keep(&upload); + b.keep(&readback); + b.defer_fill(upload_data, guest.cast::<u8>(), 8); + b.defer_host(move || { let _ = prepared.send(()); }); + // SAFETY: live resources with eight bytes, and the command list is open. + unsafe { b.list.CopyBufferRegion(&readback, 0, &upload, 0, 8) }; + assert_eq!(slot::<extern "system" fn(This) -> HRESULT>(consumer, 0x48)(consumer), S_OK); + + // SAFETY: these are ordinary D3D12 fence calls on the host's direct queue. + let gate = Gate(unsafe { host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE) }.expect("gate")); + unsafe { host.queue().Wait(&gate.0, 1) }.expect("insert gate before either list"); + let hold_landing = crate::asked_for!("DARNER_TEST_RELAY_LANDING"); + let split = crate::asked_for!("DARNER_SUBMIT_SPLIT"); + let published_before_test = crate::host::published_submission_count(); + let pause = hold_landing.then(crate::host::pause_before_relay_publication); + execute(producer_queue, 1, &producer); + let resume_landing = pause.map(|(at_landing, resume)| { + unsafe { gate.0.Signal(1) }.expect("let the producer run"); + at_landing.recv_timeout(Duration::from_secs(5)).expect("relay took the completed producer"); + resume + }); + assert_eq!(signal(producer_queue, published, 1), S_OK); + assert_eq!(wait(consumer_queue, published, 1), S_OK); + execute(consumer_queue, 1, &consumer); + assert_eq!(signal(consumer_queue, done, 1), S_OK); + let prepared_before_publication = preparation.recv_timeout(Duration::from_secs(2)).is_ok(); + let fence_before_publication = crate::fence::completed(published); + if let Some(resume) = resume_landing { + resume.send(()).expect("resume relay landing"); + } else { + unsafe { gate.0.Signal(1) }.expect("open gate"); + } + + let deadline = Instant::now() + Duration::from_secs(10); + while (crate::fence::completed(done) < 1 + || split && crate::host::published_submission_count() < published_before_test + 2) + && Instant::now() < deadline + { + thread::sleep(Duration::from_millis(1)); + } + assert_eq!(crate::fence::completed(done), 1, "consumer did not finish"); + assert_eq!(crate::fence::completed(published), 1, "producer did not finish"); + let published_lists = crate::host::published_submission_count() - published_before_test; + if split { + assert_eq!(published_lists, 2, "both submissions must use the separate sender"); + } + let range = D3D12_RANGE { Begin: 0, End: 8 }; + let mut data = ptr::null_mut::<c_void>(); + // SAFETY: the guest fences have completed and the result resource has eight bytes. + let (source, result) = unsafe { + readback.Map(0, Some(&range), Some(&mut data)).expect("map consumer readback"); + let result = data.cast::<u64>().read_unaligned(); + readback.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 })); + let source = *Box::from_raw(guest); + (source, result) + }; + for object in [producer, consumer, producer_queue, consumer_queue, published, done] { + slot::<extern "system" fn(This) -> u32>(object, 0x10)(object); + } + eprintln!("read_back={read_back} gpu_only={gpu_only} hold_landing={hold_landing} published_lists={published_lists} prepared_before_publication={prepared_before_publication} fence_before_publication={fence_before_publication} source={source:#04x} gpu_readback={result:#04x}"); + assert_eq!(fence_before_publication, 0, "producer fence advanced while publication was held"); + assert_eq!(source, expected, "the producer did not publish the expected source bytes"); + assert_eq!(result, expected, "the GPU read back the bytes copied during the consumer's CPU preparation"); + if gpu_only && !hold_landing { + assert_eq!(prepared_before_publication, crate::asked_for!("DARNER_LATE_FENCE"), + "GPU-only work should take the fast path only when enabled"); + } + } + #[test] fn the_queue_table_has_room_after_its_last_method() { crate::object::assert_room::<QUEUE, 46>(&super::FUNCTIONS, 38); ``` </details>
First-time contributor

Replay A/B on RTX 5070 Ti: DARNER_LATE_FENCE=1 in gameplay, no measurable gain

Measured 08e3ed5b77 merged on top of release v2026.12.03.02, against the plain release, on a ~6.5 minute replay route (same save, recorded controller input) through a cutscene, a scene cut and a stretch of free play. The switch was on in both PR runs (first line of each log).

Build fps (range) CPU prep ms median ms p95 ms p99 ms frames over 100 ms per run
v2026.12.03.02 (3 runs) 38.30 (38.17-38.46) 9.57 26.8 29.8 37.8 20 / 11 / 8
+ PR 93, DARNER_LATE_FENCE=1 (2 runs) 38.38 (37.68-39.07) 9.87 27.1 31.7 39.3 6 / 12

Crashes: none in any run (no device loss, no host GPU failure). Fps means are within the release's own run-to-run spread, so: no measurable difference on this route. With only 3 release runs, that spread is not well known yet; differences under ~2-3% can't be resolved here. This adds the gameplay frame-time side that the synthetic reports above left unmeasured; it says nothing about the stale-read case they show, since nothing on this route checks for it.

Config: RTX 5070 Ti 16 GB, Ryzen 7 9800X3D, 32 GB RAM, Windows 11; scripts\play-nvidia.ps1 -Build release (Series X, 1440p native, DLSS Quality, no frame generation, fullscreen, no fps cap). Each build had one unmeasured warm-up run first. The release base excludes its first measured run, which was still compiling shaders (about 3,300 compiles during the route).

Measured unattended on a replay bench (same save, recorded controller input); numbers and text prepared with Claude.

### Replay A/B on RTX 5070 Ti: DARNER_LATE_FENCE=1 in gameplay, no measurable gain Measured `08e3ed5b77` merged on top of release v2026.12.03.02, against the plain release, on a ~6.5 minute replay route (same save, recorded controller input) through a cutscene, a scene cut and a stretch of free play. The switch was on in both PR runs (first line of each log). | Build | fps (range) | CPU prep ms | median ms | p95 ms | p99 ms | frames over 100 ms per run | |---|---:|---:|---:|---:|---:|---:| | v2026.12.03.02 (3 runs) | 38.30 (38.17-38.46) | 9.57 | 26.8 | 29.8 | 37.8 | 20 / 11 / 8 | | + PR 93, `DARNER_LATE_FENCE=1` (2 runs) | 38.38 (37.68-39.07) | 9.87 | 27.1 | 31.7 | 39.3 | 6 / 12 | Crashes: none in any run (no device loss, no host GPU failure). Fps means are within the release's own run-to-run spread, so: **no measurable difference** on this route. With only 3 release runs, that spread is not well known yet; differences under ~2-3% can't be resolved here. This adds the gameplay frame-time side that the synthetic reports above left unmeasured; it says nothing about the stale-read case they show, since nothing on this route checks for it. Config: RTX 5070 Ti 16 GB, Ryzen 7 9800X3D, 32 GB RAM, Windows 11; `scripts\play-nvidia.ps1 -Build release` (Series X, 1440p native, DLSS Quality, no frame generation, fullscreen, no fps cap). Each build had one unmeasured warm-up run first. The release base excludes its first measured run, which was still compiling shaders (about 3,300 compiles during the route). Measured unattended on a replay bench (same save, recorded controller input); numbers and text prepared with Claude.
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u 'vercetti/late-fence:hingeowl-vercetti/late-fence'
git switch 'hingeowl-vercetti/late-fence'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'hingeowl-vercetti/late-fence'
git switch 'hingeowl-vercetti/late-fence'
git rebase 'main'
git switch 'main'
git merge --ff-only 'hingeowl-vercetti/late-fence'
git switch 'hingeowl-vercetti/late-fence'
git rebase 'main'
git switch 'main'
git merge --no-ff 'hingeowl-vercetti/late-fence'
git switch 'main'
git merge --squash 'hingeowl-vercetti/late-fence'
git switch 'main'
git merge --ff-only 'hingeowl-vercetti/late-fence'
git switch 'main'
git merge 'hingeowl-vercetti/late-fence'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
3 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
TrustNo1/Darner!93
No description provided.