Skip to content

D3D12.X: publish CPU writes only after GPU completion - #3104

Draft
Prime1997 wants to merge 2 commits into
xcl-dev:mainfrom
Prime1997:codex/nvidia-cpu-write-completion
Draft

Prime1997 wants to merge 2 commits into
xcl-dev:mainfrom
Prime1997:codex/nvidia-cpu-write-completion

Conversation

@Prime1997

@Prime1997 Prime1997 commented Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator

CPU-side bottom-of-pipe writes wait for confirmed producer completion on nvidia-dev; the former ten-second fallback could publish a GPU readback before its copy ran. This update also identifies stalled producers in the existing warnings, so waits from different queues and submissions can be distinguished.

Rebased onto main (2026-11-28). nvidia-dev was merged into main by #3203, so this PR now targets main and its branch was rebased onto main 765b2c5bfff6754e8c9886a73e188a86aca3c64c: head e89fbfe27682b44fd5801229b42d97c270ab7060 (was ace812c15a246a51f196f3a69907d7fbee529d8a). main had added completion receipts (after_with_completion), forget_queue and native_queue_signal to cpu_writes.rs, so both commits are ported by hand. This PR's worker (poll, hold, never publish on a timeout) now also sends main's receipt once a submission's stores are made; a removed producer drops the receipt's sender, so a waiter returns instead of blocking; the producer mark goes through native_queue_signal. main's receipt-based versions of writes_land_after_the_queue and readback_u64_lands_after_the_queue are kept. That port needs a review. On the rebased head, on the same RTX 3060 Ti PC, debug profile: cargo check -p xcl --all-targets exited 0, and cargo test -p xcl --lib -- --test-threads=4 a_ready_suffix_never_overtakes_an_unconfirmed_cpu_write device_removal_never_publishes_or_releases_cpu_writes failed_producer_signal_retains_inflight_cpu_write_resources failed_worker_send_retains_inflight_cpu_write_resources gpu_readback_is_not_published_after_an_uncompleted_ten_second_wait pending_cpu_writes_preserve_suffix_without_blocking_other_fences pending_cpu_writes_retain_resources_until_confirmed_completion writes_land_after_the_queue cpu_write completion gave 44 passed, 0 failed, 0 ignored, no SKIPPED. The whole suite and the paired title runs have not been rerun on this head; every other result below is from the earlier head. The rebase and its conflict resolution were done with Claude Code.

What is in it

Tested

  • Current PR head: ace812c15a246a51f196f3a69907d7fbee529d8a.
  • Windows 11 Pro 26200; Intel i5-10400; NVIDIA RTX 3060 Ti driver 32.0.16.1714; Rust 1.100.0; release profile.
  • Combined integration d50f6656fb50b7927a2279d4c78b24222be3da54: cargo build --locked --release -p xcl --target-dir <isolated-target> exited 0 in 228.576s, with 9 warnings. This includes the change but is not a standalone build/test of this PR head.
  • The added producer identifiers received source review and the combined compilation above. The CPU-write ordering/GPU-retirement fixtures were not rerun for this diagnostic-only update; historical results below remain tied to their original heads.
  • Historical evidence from the previous description, not validation of this head: Windows 11 Pro 26200, Intel i5-10400, NVIDIA RTX 3060 Ti driver 32.0.16.1714, Rust 1.100.0, debug/test builds. Unchanged NVIDIA 54225f58 with only the new GPU regression: 0 passed, 1 failed, 0 ignored, 1,806 filtered, no SKIPPED messages; it published zero while the producer was gated. Prior repair head 34e64a69261d9304f30a57886d0feda5ebd6daa6: 12 passed, 0 failed, 0 ignored, 1,801 filtered, no SKIPPED messages.
  • Historical commands: cargo test --locked -p xcl --lib --target-dir <isolated-target> --no-run, then the hle::d3d12x::cpu_writes::tests:: filter with --nocapture --test-threads=1. The before-fix run selected gpu_readback_is_not_published_after_an_uncompleted_ten_second_wait with --exact. Recorded patch hashes tie the prior source to its test receipt; the interrupted initial build is not counted.
  • The previously published head 2d90bc180d718afc796d8ae490f6ecbe9dc5823b and prior combined candidate 5d0833553c68d2afa327c913cd9a22f17ec6f45e were listed as pending in the previous description. Those pending entries are not converted into passes here.

Regression run
Pending paired clean-head main/PR title runs. No smoke result is claimed. Draft while required validation remains incomplete.

Not tested

  • Exact-head full-workspace and paired title tests, AMD/Intel, retail texture recovery or gameplay memory improvement.
  • General worker-panic recovery and queue-address reuse are separate issues. Pending/removed/unmarked resources can remain held until exit; this is completion safety and diagnosis, not a memory-reduction claim.
  • Queue/fence identifiers improve attribution but do not establish the operation responsible for the observed GPU removal.

AI use
Codex (GPT-6) reviewed the source and related PRs, implemented and tested the historical repair, added the diagnostics and prepared this update. Historical tests are explicitly separated from pending current-head validation.

Optional temporary Discord for coordinating contributor work, testing and comparing results: https://discord.gg/6B4TykyC4W

@Prime1997
Prime1997 force-pushed the codex/nvidia-cpu-write-completion branch from 34e64a6 to 2d90bc1 Compare November 28, 2026 07:35
@pickles976

pickles976 commented Nov 28, 2026 •

Copy link
Copy Markdown

Focused CPU-only Wine verification of exact head 2d90bc180d718afc796d8ae490f6ecbe9dc5823b (nvidia-dev base 54225f5884a94cd23b7aab3f703a7c975070aa77), with no source edits.

Tested: six existing ownership/completion-policy fixtures, 6 passed / 0 failed / 0 ignored, fresh Compiling xcl .../xcl-pr3104/crates/xcl provenance, build34.17s / tests0.00s / guarded command34.88s. Filters: pending_cpu_writes, a_ready_suffix_never_overtakes_an_unconfirmed_cpu_write, device_removal_never_publishes_or_releases_cpu_writes, failed_producer_signal_retains_inflight_cpu_write_resources, failed_worker_send_retains_inflight_cpu_write_resources. Command prefix: cargo test --locked --target x86_64-pc-windows-msvc -p xcl --lib --, followed by those filters and --nocapture --test-threads=1.

These exercise generic pending queues, synthetic completion values and drop/publication ownership. They confirm no early publication/release in those models, per-fence independence, ordered suffixes and failure-path retention. They do not invoke the real queue Signal/GetCompletedValue worker or execute GPU commands.

Not tested: the eleven-second real GPU regression, GPU destruction/device-removal behavior, native Windows, full suite, title startup, RAM/frame time, or matched parent. Our Linux/Wine title previously published two writes after a ten-second fence0/wanted1 fallback and later reached its Game-Init watchdog. Removing that unsafe publication is relevant correctness work; it does not make the stuck producer complete. GPU trials are currently parked after a separately captured driver timeout. Retaining unconfirmed resources is safer than recycling them but is not a memory-saving claim.

Additional caller-level coverage suggestion: the new lock orders Signal plus enqueue. The outer real.rs:9324–9333 still performs native Execute, several accounting/readback steps, then cpu_writes_after; execute_with_waits_on's no-wait path calls this without a queue-wide lock. [INFERENCE] concurrent submitters could execute A then B but enqueue B before A if A pauses after native Execute. The passing queue-model tests do not cover that boundary. A deterministic two-submitter fixture pausing at that point would establish whether CPU write order tracks native submission order; this is not a reproduced GPU failure or a demonstrated new regression. The kickoff path at list_x.rs:3930–3946 has the same split boundary.

Environment: i7-13620H /16GiB, Linux6.17, Wine11, Rust1.98.1. RTX4060Laptop8GiB present but not initialized by these tests; idle sampled GPU133MiB, minimum availableRAM8812.6MiB/disk14.603GiB. External9GiB/512MiB scope and global safety guards unchanged. Evidence .compat-runtime/logs/verify-xcl3104-cpu-completion-20261128T074934Z/ contains provenance, log/results and resource samples. No assets/dumps published.

AI-assisted source review, execution and report: omp / OpenAI GPT-6 Astra.

28 Nov follow-up: real CPU publication worker reproduces the submit/enqueue gap

Same production head 2d90bc180d718afc796d8ae490f6ecbe9dc5823b; only the local ignored regression below was added. Fresh intended-worktree compilation 33.68 s. Windows-MSVC/Wine 11 CPU/mock-COM test: 0 passed, 1 failed, 0.06 s, with:

mock native execute order=[1, 2], completed CPU destination=0x11, expected=0x22
left: 17
right: 34

This is more than the earlier generic queue model: it runs list_x::execute_with_waits_on, production cpu_writes::after, Signal/job registration, the actual channel worker, real::fence_completed, publish_ready, and production atomic writes into committed PAGE_READWRITE memory. The queue/fence COM objects and completion are mocks. It does not invoke the complete q_execute_command_lists wrapper or submit GPU commands.

Deterministic schedule: A's mock native Execute returns, then A pauses immediately before after; B executes and registers its writes; the actual worker publishes B's 0x22; A resumes/registers and the worker overwrites it with A's older 0x11. Both mocked fences complete, with no timeout or device-removal path. The production ordinary-submit and Kickoff paths separate native Execute from after this way; the outer PcCall guard records timing, not a held submission mutex. The PR's signal/enqueue lock preserves registration order, but registration order can differ from native submission order.

Suggested owner correction: establish one per-queue ordering boundary covering native submission and its completion/job registration across all submit paths. Prepare bookkeeping before that boundary where possible; do not place CPU/GPU waits under the global FENCES lock. Keep the existing pending/removed/failed-signal lifetime protections. Retain an actual-worker concurrency regression, then validate real controlled pending-fence execution when the hardware test environment is cleared.

No matched parent, title-crash attribution, real GPU ordering certification, or RAM/FPS claim. The first fixture attempt stopped at its static destination's writable-memory precondition; the next had a fixture index type error. Neither was a production result. The final committed-memory probe above reached the asserted consumer-visible overwrite. Its registration is removed and memory is released after both publications; a deadline failure retains an outstanding destination rather than creating a use-after-free.

Command:

cargo test --locked --target x86_64-pc-windows-msvc -p xcl --lib lab_native_submit_order_survives_delayed_cpu_write_enqueue -- --ignored --nocapture --test-threads=1

Evidence: verify-xcl3104-submit-order-worker-20261128T081347Z/. No adapter initialized; sampled GPU stayed at idle 133 MiB. Available RAM minimum 8,881 MiB; all external limits unchanged.

Complete local regression (inside cpu_writes.rs tests module)
    /// Local caller-contract probe: native submits are A then B, but A is
    /// descheduled before `after`. Uses the actual submit helper, enqueue,
    /// worker, fence polling and atomic publication; COM completion is fake.
    #[test]
    #[ignore = "local mock-COM submission-order regression; no GPU required"]
    fn lab_native_submit_order_survives_delayed_cpu_write_enqueue() {
        use std::mem::{offset_of, size_of};
        use windows::core::HRESULT;
        const SLOT: usize = size_of::<usize>();

        #[repr(C)]
        struct Fence {
            vtable: *const usize,
            refs: AtomicU32,
            completed: AtomicU64,
        }
        #[repr(C)]
        struct Queue {
            vtable: *const usize,
            executes: Mutex<Vec<usize>>,
        }
        extern "system" fn unexpected() { std::process::abort(); }
        unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 {
            (*this.cast::<Fence>()).refs.fetch_add(1, Ordering::Relaxed) + 1
        }
        unsafe extern "system" fn release(this: *mut c_void) -> u32 {
            let left = (*this.cast::<Fence>()).refs.fetch_sub(1, Ordering::Release) - 1;
            if left == 0 {
                std::sync::atomic::fence(Ordering::Acquire);
                drop(Box::from_raw(this.cast::<Fence>()));
            }
            left
        }
        unsafe extern "system" fn completed(this: *mut c_void) -> u64 {
            (*this.cast::<Fence>()).completed.load(Ordering::Acquire)
        }
        unsafe extern "system" fn signal(_: *mut c_void, fence: *mut c_void, value: u64) -> HRESULT {
            (*fence.cast::<Fence>()).completed.store(value, Ordering::Release);
            HRESULT(0)
        }
        unsafe extern "system" fn execute(this: *mut c_void, count: u32, lists: *const *mut c_void) {
            let mut order = (*this.cast::<Queue>()).executes.lock().unwrap();
            order.extend(std::slice::from_raw_parts(lists, count as usize).iter().map(|p| *p as usize));
        }
        // Follow the existing mock-COM convention: the worker may retain a
        // fence reference on any failing path, so its vtable lives forever.
        static FENCE_VTABLE: OnceLock<&'static [usize]> = OnceLock::new();
        let fence_vtable = FENCE_VTABLE.get_or_init(|| {
            let mut v = vec![unexpected as usize; size_of::<ID3D12Fence_Vtbl>() / SLOT];
            v[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.AddRef) / SLOT] = add_ref as usize;
            v[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.Release) / SLOT] = release as usize;
            v[offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / SLOT] = completed as usize;
            Box::leak(v.into_boxed_slice())
        });
        let fence = unsafe {
            ID3D12Fence::from_raw(Box::into_raw(Box::new(Fence {
                vtable: fence_vtable.as_ptr(),
                refs: AtomicU32::new(1),
                completed: AtomicU64::new(0),
            })).cast())
        };
        let mut queue_vtable = vec![unexpected as usize; size_of::<ID3D12CommandQueue_Vtbl>() / SLOT];
        queue_vtable[offset_of!(ID3D12CommandQueue_Vtbl, Signal) / SLOT] = signal as usize;
        queue_vtable[offset_of!(ID3D12CommandQueue_Vtbl, ExecuteCommandLists) / SLOT] = execute as usize;
        let queue = Box::new(Queue { vtable: queue_vtable.as_ptr(), executes: Mutex::new(Vec::new()) });
        let queue_address = (&*queue as *const Queue) as usize;
        let registered = {
            let mut fences = FENCES.lock().unwrap();
            match fences.get_or_insert_with(HashMap::new).entry(queue_address) {
                std::collections::hash_map::Entry::Vacant(entry) => {
                    entry.insert(QueueFence { fence, value: 0, failed: false });
                    true
                }
                std::collections::hash_map::Entry::Occupied(_) => false,
            }
        };
        assert!(registered, "fixture must not replace another queue's fence");
        struct Registration(usize);
        impl Drop for Registration {
            fn drop(&mut self) {
                if let Some(fences) = FENCES.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
                    fences.remove(&self.0);
                }
            }
        }
        let registration = Registration(queue_address);
        use windows_sys::Win32::System::Memory::{
            VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RESERVE, MEM_RELEASE, PAGE_READWRITE,
        };
        struct Destination {
            base: usize,
            attempted: AtomicU32,
        }
        impl Drop for Destination {
            fn drop(&mut self) {
                // Never release a destination while an asynchronous job can
                // still write it. Only a failed/deadline path may retain it.
                let attempted = self.attempted.load(Ordering::Acquire);
                let finished = |i: usize| unsafe {
                    (*(self.base.wrapping_add(i * 4) as *const AtomicU32)).load(Ordering::Acquire) != 0
                };
                if (attempted & 1 == 0 || finished(1)) && (attempted & 2 == 0 || finished(2)) {
                    unsafe { VirtualFree(self.base as *mut c_void, 0, MEM_RELEASE); }
                }
            }
        }
        // PE static storage can have write-copy protection under Wine.
        // Use a real committed PAGE_READWRITE allocation, as production requires.
        let base = unsafe { VirtualAlloc(std::ptr::null(), 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) } as usize;
        assert_ne!(base, 0);
        let destination = Destination { base, attempted: AtomicU32::new(0) };
        let attempted = &destination.attempted;
        let address = move |i: usize| base + i * 4;
        let word = |i| unsafe { &*(address(i) as *const AtomicU32) };
        let await_write = |word: &AtomicU32| {
            let start = Instant::now();
            while word.load(Ordering::Acquire) == 0 {
                assert!(start.elapsed() < Duration::from_secs(5), "CPU worker publication deadline");
                std::thread::sleep(Duration::from_millis(1));
            }
        };
        assert!(writable(address(0), 12), "fixture destinations must pass production checks");
        let (submitted_tx, submitted_rx) = mpsc::channel();
        let (resume_tx, resume_rx) = mpsc::channel();
        std::thread::scope(|scope| {
            let a = scope.spawn(move || unsafe {
                let raw = queue_address as *mut c_void;
                let q = ID3D12CommandQueue::from_raw_borrowed(&raw).unwrap();
                super::super::list_x::execute_with_waits_on(raw, &[1usize as *mut c_void], |lists| {
                    (q.vtable().ExecuteCommandLists)(raw, lists.len() as u32, lists.as_ptr());
                    submitted_tx.send(()).unwrap();
                    resume_rx.recv_timeout(Duration::from_secs(5)).expect("release the first submitter");
                    attempted.fetch_or(1, Ordering::Release);
                    after(raw, vec![
                        Write::Immediate(address(0), vec![0x11]),
                        Write::Immediate(address(1), vec![1]),
                    ]);
                });
            });
            submitted_rx.recv_timeout(Duration::from_secs(5)).expect("first native submit");
            unsafe {
                let raw = queue_address as *mut c_void;
                let q = ID3D12CommandQueue::from_raw_borrowed(&raw).unwrap();
                super::super::list_x::execute_with_waits_on(raw, &[2usize as *mut c_void], |lists| {
                    (q.vtable().ExecuteCommandLists)(raw, lists.len() as u32, lists.as_ptr());
                    attempted.fetch_or(2, Ordering::Release);
                    after(raw, vec![
                        Write::Immediate(address(0), vec![0x22]),
                        Write::Immediate(address(2), vec![1]),
                    ]);
                });
            }
            await_write(word(2));
            assert_eq!(word(0).load(Ordering::Acquire), 0x22);
            resume_tx.send(()).unwrap();
            a.join().unwrap();
        });
        await_write(word(1));
        let order = queue.executes.lock().unwrap().clone();
        let actual = word(0).load(Ordering::Acquire);
        drop(registration);
        eprintln!("mock native execute order={order:?}, completed CPU destination={actual:#x}, expected=0x22");
        assert_eq!(order, [1, 2]);
        assert_eq!(actual, 0x22, "earlier native submission must not overwrite a later submission's bottom-of-pipe write");
    }

@Aniseto

Aniseto commented Nov 28, 2026

Copy link
Copy Markdown

Ran the CPU-write completion tests at 2d90bc18 on an NVIDIA Blackwell desktop part:

Environment: Windows 11 Pro build 26200 x64, NVIDIA GeForce RTX 5070 Ti (Blackwell, wave32 only, 16 GB) driver 32.0.16.2124, Intel Core i5-12400F, 64 GB RAM, rustc 1.100.0 (0ef1bc386 2026-11-09), MSVC 14.44.35207, DXC 1.9.2609.5, debug build.

XCL_ADAPTER=NVIDIA cargo test -p xcl --lib hle::d3d12x::cpu_writes::tests:: -- --test-threads=1
12 passed; 0 failed; 0 ignored; 0 measured; 1801 filtered out      (exit 0)

All twelve tests pass at the updated head, including the gated eight-byte GPU-copy regression. The PR description says this exact head had not been individually retested and that the combined validation is pending; this run covers the focused test group only. The thread has an RTX 3060 Ti run and a CPU-only Wine check, but no 5070 Ti.

Not tested: the full workspace suite, a paired smoke run, a retail title, release profile, AMD and Intel GPUs, native wave64 hosts, Wine, game data.

AI-assisted (OpenCode), model: DeepSeek V4.1 Flash Free - checked out the PR's head commit in a detached worktree, built it, ran the tests, wrote this report; the worktree was not modified; no game data was used.

@Aniseto

Aniseto commented Nov 28, 2026

Copy link
Copy Markdown

Re-ran the CPU-write completion tests at ace812c1 after the head moved from 2d90bc18; this is a new response in the same thread, not an edit of my earlier report:

Environment: Windows 11 Pro build 26200 x64, NVIDIA GeForce RTX 5070 Ti (Blackwell, wave32 only, 16 GB) driver 32.0.16.2124, Intel Core i5-12400F, 64 GB RAM, rustc 1.100.0 (0ef1bc386 2026-11-09), MSVC 14.44.35207, DXC 1.9.2609.5, debug build.

XCL_ADAPTER=NVIDIA cargo test -p xcl --lib hle::d3d12x::cpu_writes::tests:: -- --test-threads=1
12 passed; 0 failed; 0 ignored; 0 measured; 1801 filtered out      (exit 0)

All 12 tests pass at the new head, which adds diagnostics for stalled CPU-write producers. Same count as at 2d90bc18. The thread has an RTX 3060 Ti run and a CPU-only Wine check, but no desktop 5070 Ti.

Not tested: a retail title, a paired smoke run, the full workspace suite, release profile, AMD and Intel GPUs, native wave64 hosts, Wine, game data.

AI-assisted (OpenCode), model: DeepSeek V4.1 Flash Free - checked out the PR's head commit in a detached worktree, built it, ran the tests, wrote this report; the worktree was not modified; no game data was used.

Retain pending readbacks and preserve per-fence ordering without blocking
unrelated producers. A real gated GPU-copy regression fails on the unchanged
NVIDIA worker. Prior head 34e64a6 passed all 12 targeted CPU-write tests.

The combined suite exposed a pre-existing fixture race: it observed the
first word before the worker published the second. Use atomic storage,
wait for the final release store, and retain the destination on timeout or
unwind. This fixture correction does not change production behavior.

Focused tests on this updated head, full workspace validation and paired
clean-head title validation remain pending.

Assisted-by: Codex (GPT-6)
Capture the existing diagnostic queue number while the producer is live. Pending and removed producer warnings include that number, the owned fence identity and the accepted Signal mark so separate queue submissions can be distinguished. Failed producer marks and unavailable workers also identify the queue. Polling, warning frequency, publication, and resource lifetime are unchanged.

Assisted-by: Codex (GPT-6)
(cherry picked from commit 7ac4f5d48bab049382ca45759b1ef4907ad7ec58)
@Prime1997
Prime1997 force-pushed the codex/nvidia-cpu-write-completion branch from ace812c to e89fbfe Compare November 28, 2026 22:06
@github-actions github-actions Bot added area:d3d12 D3D12.X runtime, command lists, resources, sparse memory area:docs-ci Documentation, scripts, workflows, repo governance gpu:nvidia Code is specific to NVIDIA / wave32 GPUs (scope tag; see needs:nvidia-test) needs-pr-check Failing the PR description check (CONTRIBUTING.md) and removed needs-pr-check Failing the PR description check (CONTRIBUTING.md) labels Nov 28, 2026
@andrewDoing

andrewDoing commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

I tested the rebased single-worker scheduler at e89fbfe27682b44fd5801229b42d97c270ab7060 on an RTX 5070 (616.92). Independent publication and same-queue FIFO passed. Two GPU-ordered queues writing the same ordinary CPU word produced a stale final value in 5/5 rounds.

  • A waited on a gate, then scheduled 256 immediate writes of the integers 1…256 to two adjacent DWORDs. After those producer marks, A signaled a separate native fence. B waited on that fence and scheduled the value 0xbbccdd11 to only the first DWORD. The GPU order here was explicit.
  • While A was still gated, a third queue published a distinct value to a disjoint cell and returned a receipt. A's cells were still zero. After releasing A, all A and B receipts arrived.
  • The second DWORD, written only by A, ended at 256 every time. The shared first DWORD also ended at 256, although B was ordered last and wrote 0xbbccdd11. All five rounds completed normally; the final value assertion failed.

The worker can retire up to 64 jobs for one ready fence per sweep. A later queue can already be GPU-ready while an earlier queue still has CPU stores left to publish. Both local completion checks can therefore be true even when their final overlapping stores land in the opposite order. This covers an ordinary Immediate destination, outside the registered monotonic sync-cell policy in #2439. It also complements the independent-queue delay reported on #3035.

The test invoked the production scheduler with native queue signals/waits and bounded receipt observations. It measures completion order and final CPU values; guest command recording and retail behavior were outside the fixture. I have not proposed another scheduler PR.

AI use: OpenAI Codex built the test-only fixture, ran all five rounds and drafted this report.

Reverse host-order control, same head and adapter: B submitted its wait and overlapping store before A submitted any of its 256 jobs or its signal. GPU order was still A then B. In 5/5 additional rounds the disjoint queue progressed, the A-only FIFO control finished at 256, and the shared word also ended at 256 instead of 0xbbccdd11. Retiring overlapping stores in host arrival order would therefore also give the wrong answer in this case. The worker needs the queue dependency through CPU publication, including a wait whose signal is submitted later.

@thehollowedone

Copy link
Copy Markdown
Contributor

One publication path remains outside the current #3104 tests at head e89fbfe: an ordinary deferred CPU write followed by a title queue Signal on the same queue. Both ordinary Signal and SignalX forward the native Signal immediately, while the worker's CPU stores can land later. A title waiting for that fence on the CPU could therefore observe completion and read the old word. The completed-value mirror's contract says the writes have landed before its value is published. The existing two-queue report tests a different ordering. This gap also exists on current main; it is not a regression introduced by this PR.

For a bounded correction, consider a per-queue publication fence: after the producer's GPU mark is queued, put a native GPU Wait for the worker's publication value before forwarding a title Signal. The worker advances that value only after its stores. The queue Wait returns to the submitting CPU immediately, so a title can still issue a host wait without deadlocking the submitter. A failed producer mark, failed wait insertion or removal must not publish the title signal. The separate internal Wait64 signal route also needs a check; a failure/cycle-break signal cannot certify CPU publication.

A deterministic regression could pause the worker immediately before an ordinary CPU store, issue the title Signal, and drive the queue through its earlier GPU work. Until the worker is released, require the title fence's completed value and event to stay below the signaled value; afterward require the event, value and word to agree. This is a source-traced ordering concern, not a reproduced test failure or an exercised fix. AI use: Codex (GPT-6.2 Sol) checked the paths and wrote this report; Codex (GPT-6.2 Astra) independently traced the publication ordering.

@vasanex

vasanex commented Nov 29, 2026

Copy link
Copy Markdown
merge-check
base: fa204595a488c60c6c5f905244f0172072c9c2a9
head: e89fbfe27682b44fd5801229b42d97c270ab7060
merge: clean
build: cargo build --workspace -> ok
tests: not run alone; in a stack of 11 of your PRs on this base: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2650 passed, 1 failed, 49 ignored; SKIPPED: 27 lines; failing: #3123's private_physical_pages_reach_the_gpu_on_mapping only. Alone: hle::d3d12x::cpu_writes:: hle::d3d12x::list_x:: 113 passed, 0 failed in 2 runs and hle::d3d12x::list_x:: 101 passed in 2 runs; one earlier run of the first filter ended abnormally after a list_x Wait64BitValueX time-out test (not reproduced in 4 reruns; base 106 passed in 2 runs) - flagged, not attributed.
review: two default-on changes against main. (1) Order across queues: main publishes every queue's writes through one FIFO in enqueue order; here jobs sit per producer fence in a HashMap and up to 64 are retired per fence per sweep (cpu_writes.rs:84-97), so a later queue's write can be published before an earlier queue's - the stale final value andrewDoing measured (5/5), and a regression where host order equals GPU order. (2) main writes after WAIT_MS = 10 s (cpu_writes.rs:65/75 on main); here a stalled fence is never published (:143 only warns) while callers block on recv() for the receipt, so a stall becomes a permanent hang of the submitting thread; one failed Signal turns the queue's CPU writes off for good (`failed`). Overlaps #3035, #562, #1643, #1819.
performance: 60 s smoke of the merged tree (56fd4d5c): 1690 frames, peak commit 18390 MB, 0 removals, 0 crashes (base 1629-1689 frames, 16065-16596 MB; commit is noisy in this series). Load run against the base (150 s, save loaded, one run each): 1982 frames / 14457 submits with the PR, 2014 / 14549 on the base; presents stop at 94 s vs 102 s (both over the video memory budget); no Wait64BitValueX time-out, no producer-stall warning, no removal, no crash in either. So no hang in this load; that does not test the ordering case.
verdict: not yet: cross-queue publication order regresses against main, and removing the 10 s fallback turns a stall into a hang by default (not seen in a 150 s load here)
hardware / tool and model: RTX 3080 10 GB 621.40, Ryzen 9 7950X, Windows 11 26200 / Claude Code (Claude Opus 5.5, Claude Fable 5.2)

How this was run: the suite ran once on the 11 of your PRs that build on this base, merged together (#3047 #3048 #3049 #3091 #3092 #3103 #3104 #3105 #3107 #3123 #3125; a local tree, only #3125 needed a resolution in README and the sparse.rs test module); the base alone gave 2608 passed, 0 failed, 49 ignored with the same 27 SKIPPED lines (21 no wave64, 3 refused per-lane f16/f32 forms, 2 heap windows opt-in, 1 driver cache needs Developer Mode). This PR alone was merged onto the base, built (cargo build --workspace, then release), its modules' lib tests run (debug), and smoke-run once for 60 s (scripts/smoke.ps1, retail title, front end, XCL_PREPARE=0). The smoke numbers are for my local merged tree, not a clean-head block for the description. Load runs: 150 s, the save loaded with A presses, XCL_PREPARE=0, after one warm-up, one run per arm; on this 10 GB card main is over the video memory budget while loading, and presents stop after 94-125 s in every arm.

AI use: Claude Code (Claude Opus 5.5 and Claude Fable 5.2) ran the builds, tests and title runs, reviewed the diff and wrote this; the code points cited were checked against the merged tree.

@bmjask bmjask left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Critical review of current head e89fbfe2. The old ten-second timeout could publish an unfinished GPU readback; the new worker waits for a confirmed fence value and keeps independent producer queues progressing. I found no source-level blocker in the ordering policy. Please verify the operational failure path: after a failed Signal or device removal, the retained job and its readback buffer must not be published, and any completion receipt must terminate rather than leave a title thread waiting indefinitely. The new synthetic tests cover much of this; a device-backed failure test would close the gap. No local Windows run.

@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Review (head e89fbfe, diff read, not a merge-check; draft with PR description and CI red, so not built or run):

  • The CPU-write receipt is now unbounded. completion.wait() (list_x.rs ~3725, ~5418) is a bare recv() (cpu_writes.rs ~306), and the worker neither sends nor drops it while the producer is pending; main's 10 s fallback used to bound this. If a split chunk is held on the GPU by work the same title thread submits only after ExecuteCommandLists returns, the title now hangs for good with no stop_for_unresolved_wait report, where main stalls 10 s and carries on. Bound it, or route it into the existing stop path.
  • Polling instead of an event: the worker checks the GPU every 2 ms (recv_timeout(2ms), ~125), so up to ~2 ms more before each write lands, ~500 wake-ups/s while writes are pending, and it keeps polling after device removal. Not measured.
  • queue_id now runs on every submission (a mutex and a lookup in a list that only grows; the id is stale when a queue address is reused); one warning per held submission can flood the log; the new GPU test adds 11 s to every suite run and its "no hardware device" skip still runs on WARP.
  • CI: late_release::tests::a_pipeline_xcl_lets_go_is_released_by_the_thread failed (late_release.rs:490) and the test process then crashed (0xc0000005); I didn't find that failure in other recent runs, so worth checking whether the new 11 s gated-queue test is involved. No smoke blocks; AI use leaves out Claude Code (and its model) for the rebase; Tested names the old head ace812c.

Fine: sending under the signal lock keeps writes from two submitters in order, no stale event can publish early, removed producers release their waiters, resources stay held when a signal or send fails, each queue keeps its order without waiting on others, and the new GPU test fails on main.

AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.

@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Test report (not a merge-check: draft, PR description red)
base: b2b1f10
head: e89fbfe
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2909 passed, 0 failed, 51 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on main); failing: none
review: not repeated here; my review of this same head is at #3104 (comment), and its findings stand. This run adds what reading couldn't: whether the change merges, builds and passes the whole suite on current main.
performance: no smoke run.
assessment: merges, builds and passes the whole suite on current main (0 failed, its new tests included); the findings in my review stand (it also overlaps #3035 on the same CPU-write worker loop)
hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5

AI-written and posted by Foniass without a human check of each point.

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

Labels

area:d3d12 D3D12.X runtime, command lists, resources, sparse memory area:docs-ci Documentation, scripts, workflows, repo governance gpu:nvidia Code is specific to NVIDIA / wave32 GPUs (scope tag; see needs:nvidia-test)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants