fix: send the title's bytes under shader writes as their own runs, not coalesced #292

Open
github-bot wants to merge 1 commit from github-bot/gh-292 into main AGit
Owner

@⁠Skyfrye on GitHub · 2026-11-26 01:28 UTC · original
Skyfrye:nep/under-writes-exact → main · +67 −6 · 1 files · 1 commits · draft

Draft: an in-game check is pending (the change and its test are done).

Change

VICTORY_COPY_COALESCE=<bytes> (08f8a1b, set to 256 by the launcher's fast set since #265) joins changed runs that lie fewer bytes apart into one range sent up to a copy in the card's memory. Its comment gives the reason it is safe: "the bytes between them are the same on the CPU side and the card (nothing of the stretch is being written by shaders: update cut those ranges out)". That holds for the refresh (Shadow::copy's changed spans), but the same helper, Shadow::card_changed_runs, is also what Shadow::merge_under_writes sends with. That function exists for the opposite case: it puts "the bytes the title changed into the copy, in the ranges shaders may be writing, and only those bytes, so that what the shaders write beside them stays". There, the bytes between two runs are the flights' shaders' on the card, and a range joined across them puts the CPU side's older bytes back over them (with VICTORY_UNDER_WRITES_MASKS=1 the mask is built from the joined range, so it covers the gap too).

card_changed_runs now takes the gap from its caller: the refresh passes copy_coalesce_gap() as before, merge_under_writes passes 0. The switch's comment says it is for refreshes only.

What this is not: the GPU hangs at world entry I see with the launcher's fast set (DXGI_ERROR_DEVICE_HUNG, the same 35 submissions in the air each time) still happen with VICTORY_COPY_COALESCE=0 (2 of 2 runs), so this change is not their fix. It is a fix of the switch's own premise.

Linked issue: none.

Verification

Windows 11 26300, Rust 1.98.1 (MSVC), on upstream main at 578098b (merges cleanly on c4c93bd), from third_party/victory:

cargo build --locked --release -p victory                  -> Finished, no new warning
cargo test --locked -p victory-gpu --lib                   -> 184 passed, 3 failed, 3 ignored
VICTORY_COPY_COALESCE=256 cargo test --locked -p victory-gpu --lib -- title_words_under_shader_writes -> 1 passed

The 3 failures are the same on main without this change (183 passed, 3 failed): descriptor::host::tests::spans_say_the_next_start_and_the_lowest_level_viewed, indirect::tests::warp_card_fetch_copies_flagged_pieces_to_their_slots, indirect::tests::warp_card_patch_writes_the_masked_bytes_and_no_others.

New test title_words_under_shader_writes_go_up_on_their_own: a copy in the card's memory (software adapter) over write-watched memory, the whole range declared as written by a flight's shaders, the title changes two words 96 bytes apart; merge_under_writes must send [(100, 104), (200, 204)]. Revert check: with the old call (copy_coalesce_gap()) and VICTORY_COPY_COALESCE=256 set, as the launcher sets it, it fails with left: [(100, 204)]. Without the switch it passes either way (the gap is then 0 for both callers), which is why it has to be run with the switch set.

Pending: a game run with the fast set where the picture of the world is compared (the gap bytes are the shaders' between flights; what reads them is the next submission's shaders).

Oracle and test data

No game file. The test builds its memory itself.

Checklist

  • The PR covers a single reviewable behaviour (title bytes under shader writes are sent as their own runs).
  • A test fails without this change and passes with it (with the launcher's VICTORY_COPY_COALESCE=256, said above).
  • The commands and results of each check are given above (the in-game check is pending, said above).
  • An unimplemented function returns an error (E_NOTIMPL), never a fake success. (Nothing unimplemented here.)
  • README: not touched.
  • No game, console or SDK file, no key, no dump, no download link.
  • Findings drawn from a title: none beyond the hang counts above.
  • Code taken from another project: none.

AI assistance: written with Claude Code. Claude Opus 5.5 found the mismatch while looking for the cause of the GPU hangs, wrote the change and its test, and wrote this description.

🤖 Generated with Claude Code

**@⁠Skyfrye** on GitHub · 2026-11-26 01:28 UTC · [original](https://github.com/LooperSalty/AnyXboxX/pull/292) `Skyfrye:nep/under-writes-exact` → `main` · +67 −6 · 1 files · 1 commits · draft **Draft: an in-game check is pending** (the change and its test are done). ## Change `VICTORY_COPY_COALESCE=<bytes>` (08f8a1b, set to 256 by the launcher's fast set since #265) joins changed runs that lie fewer bytes apart into one range sent up to a copy in the card's memory. Its comment gives the reason it is safe: "the bytes between them are the same on the CPU side and the card (nothing of the stretch is being written by shaders: `update` cut those ranges out)". That holds for the refresh (`Shadow::copy`'s changed spans), but the same helper, `Shadow::card_changed_runs`, is also what `Shadow::merge_under_writes` sends with. That function exists for the opposite case: it puts "the bytes the title changed into the copy, in the ranges shaders may be writing, and only those bytes, so that what the shaders write beside them stays". There, the bytes between two runs are the flights' shaders' on the card, and a range joined across them puts the CPU side's older bytes back over them (with `VICTORY_UNDER_WRITES_MASKS=1` the mask is built from the joined range, so it covers the gap too). `card_changed_runs` now takes the gap from its caller: the refresh passes `copy_coalesce_gap()` as before, `merge_under_writes` passes 0. The switch's comment says it is for refreshes only. What this is not: the GPU hangs at world entry I see with the launcher's fast set (DXGI_ERROR_DEVICE_HUNG, the same 35 submissions in the air each time) still happen with `VICTORY_COPY_COALESCE=0` (2 of 2 runs), so this change is not their fix. It is a fix of the switch's own premise. Linked issue: none. ## Verification Windows 11 26300, Rust 1.98.1 (MSVC), on upstream `main` at `578098b` (merges cleanly on `c4c93bd`), from `third_party/victory`: ``` cargo build --locked --release -p victory -> Finished, no new warning cargo test --locked -p victory-gpu --lib -> 184 passed, 3 failed, 3 ignored VICTORY_COPY_COALESCE=256 cargo test --locked -p victory-gpu --lib -- title_words_under_shader_writes -> 1 passed ``` The 3 failures are the same on `main` without this change (183 passed, 3 failed): `descriptor::host::tests::spans_say_the_next_start_and_the_lowest_level_viewed`, `indirect::tests::warp_card_fetch_copies_flagged_pieces_to_their_slots`, `indirect::tests::warp_card_patch_writes_the_masked_bytes_and_no_others`. New test `title_words_under_shader_writes_go_up_on_their_own`: a copy in the card's memory (software adapter) over write-watched memory, the whole range declared as written by a flight's shaders, the title changes two words 96 bytes apart; `merge_under_writes` must send `[(100, 104), (200, 204)]`. Revert check: with the old call (`copy_coalesce_gap()`) and `VICTORY_COPY_COALESCE=256` set, as the launcher sets it, it fails with `left: [(100, 204)]`. Without the switch it passes either way (the gap is then 0 for both callers), which is why it has to be run with the switch set. Pending: a game run with the fast set where the picture of the world is compared (the gap bytes are the shaders' between flights; what reads them is the next submission's shaders). ## Oracle and test data No game file. The test builds its memory itself. ## Checklist - [x] The PR covers a single reviewable behaviour (title bytes under shader writes are sent as their own runs). - [x] A test fails without this change and passes with it (with the launcher's `VICTORY_COPY_COALESCE=256`, said above). - [x] The commands and results of each check are given above (the in-game check is pending, said above). - [x] An unimplemented function returns an error (`E_NOTIMPL`), never a fake success. (Nothing unimplemented here.) - [x] README: not touched. - [x] No game, console or SDK file, no key, no dump, no download link. - [x] Findings drawn from a title: none beyond the hang counts above. - [x] Code taken from another project: none. AI assistance: written with Claude Code. Claude Opus 5.5 found the mismatch while looking for the cause of the GPU hangs, wrote the change and its test, and wrote this description. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
`VICTORY_COPY_COALESCE` (the launcher sets 256) joins changed runs a few
bytes apart into one range sent up to the card. That holds for refreshes,
where no shader writes the stretch, but `merge_under_writes` uses the same
path for the title's bytes in ranges a flight's shaders may be writing:
the bytes between two such runs are the shaders' on the card, and a range
joined across them put the CPU side's older bytes back over them.

`card_changed_runs` now takes the gap from its caller: the refresh passes
the switch's value, `merge_under_writes` passes 0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 05:42:10 +00:00
Author
Owner

@⁠mauroalvare on GitHub · 2026-11-26 01:46 UTC · original

Independent D3D12 readback on NVIDIA and WARP

I ran the same synthetic probe against c4c93bdc413191a9dc909998d2d53080a3f0c880 (the PR base) and the exact PR head 770a1a2b48fc1304eb0883aa159b0fd31534f743. The PR branch joins main at 578098b96f0b3140c9e082a8747782d940f0a1d2. The VIctory tree is identical at that merge base and the tested base.

The probe registers a 64 KiB write-watched title buffer, fills the device-side UAV with 0x5a5a5a5a using a synthetic compute shader, then writes CPU words at offsets 100 and 200. It runs the real Shadow::merge_under_writes → Host::card_before upload prelude. After a fence it reads all 64 KiB back and checks both CPU words and every other GPU-written word.

Adapter / setting Base PR head
RTX 5070 Ti, gap 256, masked dispatch 104 bytes in 1 range, 24 GPU-written words clobbered 8 bytes in 2 ranges, all words correct
RTX 5070 Ti, gap 256, direct copies Same failure Same pass
WARP, gap 256, masked dispatch and direct copies Same failure in both Same pass in both
RTX 5070 Ti and WARP, gap 0, masked dispatch Pass on both Pass on both

At byte 148 the readback was 0x00000000 on base with gap 256 and 0x5a5a5a5a on the PR. The CPU values were 0x11111111 and 0x22222222 on both revisions. The probe checked DXGI adapter identity (0x10de, RTX 5070 Ti, NVIDIA driver 621.40 and 0x1414, Microsoft Basic Render Driver with the software flag) and required one mask dispatch with masks enabled and zero with direct copies. All 12 cases executed. Windows x64, Rust 1.98.1 MSVC, Cargo test profile. The fixture uses synthetic memory and shaders.

The PR's own WARP range test passed with VICTORY_COPY_COALESCE=256. cargo test --locked --offline -p victory-loader --test load_probe passed 2/2 on base. cargo xtask policy passed on the PR (199 files). GitHub Actions tests passed at this head (run #667).

One test isolation issue reproduced locally. With cargo test --locked --offline -p victory-gpu --lib --features diagnostics -- --test-threads=1, base had 196 passed / 3 failed / 3 ignored, while the clean PR head had 196 passed / 4 failed / 3 ignored. The pre-existing failures were spans_say_the_next_start_and_the_lowest_level_viewed, warp_card_fetch_copies_flagged_pieces_to_their_slots, and warp_card_patch_writes_the_masked_bytes_and_no_others. The extra failure was watch::tests::written_pages_are_reported_to_every_asker at assert!(before.is_empty()). It passed alone and failed once in three runs of the pair below. Excluding only the PR's WARP regression from the full suite on the PR restored the base result. This is consistent with the process-wide write-watch journal retaining a stamp when an address is freed and reused in the same test process.

$env:VICTORY_COPY_COALESCE = '256'
cargo test --locked --offline -p victory-gpu --lib --features diagnostics -- --test-threads=1 --nocapture shadow::card_merge_tests::title_words_under_shader_writes_go_up_on_their_own watch::tests::written_pages_are_reported_to_every_asker
Reproduce the GPU readback

Apply the test-only diff below to each SHA and run from third_party/victory.

$env:VICTORY_CARD_BUFFERS = '1'
$env:VICTORY_CARD_BUFFERS_MIN_KB = '64'
$env:VICTORY_CARD_BUFFERS_MB = '8'
$env:VICTORY_UNDER_WRITES_WORDS = '1'
$env:VICTORY_UNDER_WRITES_MASKS = '1'
$env:VICTORY_UNDER_WRITES_MASKS_LEAST = '1'
$env:VICTORY_COPY_COALESCE = '256'
cargo test --locked --offline -p victory-gpu --lib --features diagnostics host::nvidia_qa_pr292::preserves_gpu_writes_between_title_words -- --exact --nocapture --test-threads=1

Set VICTORY_D3D12_WARP=1 for WARP and leave it unset for the 5070 Ti. Repeat with VICTORY_UNDER_WRITES_MASKS=0 for the direct copy path, and with VICTORY_UNDER_WRITES_MASKS=1 VICTORY_COPY_COALESCE=0 for the control.

diff --git a/third_party/victory/crates/victory-gpu/src/host.rs b/third_party/victory/crates/victory-gpu/src/host.rs
index 011407c..a7aa32b 100644
--- a/third_party/victory/crates/victory-gpu/src/host.rs
+++ b/third_party/victory/crates/victory-gpu/src/host.rs
@@ -9476,3 +9476,153 @@ mod batch {   // Batch::texture_due lives here; `mod tests` is already taken at
         assert_eq!(ram_idle_ms(None), 10_000);
     }
 }
+
+#[cfg(test)]
+mod nvidia_qa_pr292 {
+    use super::*;
+    use windows::Win32::Foundation::WAIT_OBJECT_0;
+    use windows::Win32::Graphics::Direct3D::{Fxc::D3DCompile, ID3DBlob};
+    use windows_sys::Win32::System::Memory::{
+        MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc,
+        VirtualFree,
+    };
+
+    const LEN: usize = 64 << 10;
+    const MEM_WRITE_WATCH: u32 = 0x20_0000;
+    const SEED: u32 = 0x5a5a_5a5a;
+    const TITLE_WORDS: [(usize, u32); 2] = [(100, 0x1111_1111), (200, 0x2222_2222)];
+    const FILL: &str = r#"
+        RWByteAddressBuffer dest : register(u0);
+        [RootSignature("UAV(u0)")]
+        [numthreads(64, 1, 1)]
+        void main(uint3 id : SV_DispatchThreadID) {
+            dest.Store(id.x * 4, 0x5a5a5a5a);
+        }
+    "#;
+
+    struct Title(*mut u8);
+
+    impl Drop for Title {
+        fn drop(&mut self) {
+            crate::shadow::unregister(1, self.0 as u64);
+            // SAFETY: the address was reserved by this test and is no longer read.
+            assert_ne!(unsafe { VirtualFree(self.0.cast(), 0, MEM_RELEASE) }, 0);
+        }
+    }
+
+    #[test]
+    fn preserves_gpu_writes_between_title_words() {
+        let host = host().expect("a D3D12 device is required");
+        let (name, _) = adapter_summary().expect("DXGI must identify the test device");
+        // SAFETY: the host holds a live DXGI adapter for the D3D12 device.
+        let adapter = unsafe { host.adapter.as_ref().unwrap().GetDesc1().unwrap() };
+        let software = adapter.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0;
+        if on_warp() {
+            assert!(software, "WARP requested, got {name}");
+        } else {
+            assert_eq!(adapter.VendorId, 0x10de);
+            assert!(name.contains("RTX 5070 Ti") && !software, "got {name}");
+        }
+        let masks_on = under_writes_masks();
+        println!("adapter={name}; vendor={:#06x}; software={software}; coalesce={}; masks={masks_on}",
+            adapter.VendorId, std::env::var("VICTORY_COPY_COALESCE").unwrap());
+        assert!(host.card_ready(), "card upload pipeline failed to initialize");
+        // SAFETY: a new write-watched allocation, as used by title buffers.
+        let address = unsafe {
+            VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE)
+        }.cast::<u8>();
+        assert!(!address.is_null());
+        let _title = Title(address);
+        let start = address as u64;
+        crate::shadow::register(1, start, LEN as u64);
+        let shadow = crate::shadow::find(start, LEN as u64).expect("registered title buffer");
+        assert!(shadow.carded(), "registered title buffer did not get a card-side copy");
+        shadow.update(start as usize, LEN);
+        let initial = host.card_before(&[], false);
+
+        let readback = host.read_back_buffer(LEN as u64).unwrap();
+        let (seed_allocator, seed_list) = host.make_prelude().unwrap();
+        let (read_allocator, read_list) = host.make_prelude().unwrap();
+
+        // SAFETY: the synthetic shader and root signature address exactly LEN
+        // bytes of a live UAV. The command objects stay alive until the fence.
+        let (root, pso) = unsafe {
+            let mut blob: Option<ID3DBlob> = None;
+            D3DCompile(
+                FILL.as_ptr().cast(), FILL.len(), windows::core::s!("synthetic fill"),
+                None, None, windows::core::s!("main"), windows::core::s!("cs_5_1"),
+                0, 0, &mut blob, None,
+            ).unwrap();
+            let blob = blob.unwrap();
+            let code = std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize());
+            let root: ID3D12RootSignature = host.device.CreateRootSignature(0, code).unwrap();
+            let pso: ID3D12PipelineState = host.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
+                pRootSignature: std::mem::transmute_copy(&root),
+                CS: D3D12_SHADER_BYTECODE { pShaderBytecode: code.as_ptr().cast(), BytecodeLength: code.len() },
+                ..Default::default()
+            }).unwrap();
+            seed_list.Reset(&seed_allocator, &pso).unwrap();
+            seed_list.SetComputeRootSignature(&root);
+            seed_list.SetComputeRootUnorderedAccessView(0, shadow.buffer.GetGPUVirtualAddress());
+            seed_list.Dispatch((LEN / 4 / 64) as u32, 1, 1);
+            seed_list.Close().unwrap();
+            host.queue.ExecuteCommandLists(&[Some(seed_list.cast().unwrap())]);
+            (root, pso)
+        };
+
+        shadow.writing(start as usize, LEN);
+        for (offset, word) in TITLE_WORDS {
+            // SAFETY: the word fits inside the private allocation.
+            unsafe { address.add(offset).cast::<u32>().write_unaligned(word) };
+        }
+        let mut budget = 1000;
+        assert!(!shadow.merge_under_writes(start as usize, LEN, &mut budget), "merge asked to wait");
+        assert_eq!(budget, 998, "the merge should find both title writes");
+        let stats = &crate::shadow::CARD_STATS;
+        let bytes_before = stats[0].load(Ordering::Relaxed);
+        let ranges_before = stats[1].load(Ordering::Relaxed);
+        let masks_before = CARD_MASKED_PASSES.load(Ordering::Relaxed);
+        let plan = host.card_before(&[], false).expect("no runtime upload was submitted");
+        let bytes = stats[0].load(Ordering::Relaxed) - bytes_before;
+        let ranges = stats[1].load(Ordering::Relaxed) - ranges_before;
+        let passes = CARD_MASKED_PASSES.load(Ordering::Relaxed) - masks_before;
+        assert_eq!(passes, u64::from(masks_on), "unexpected upload path");
+
+        // SAFETY: both lists use the same direct queue. The buffer decays to
+        // COMMON across ExecuteCommandLists. The fence orders the CPU map.
+        let words = unsafe {
+            read_list.Reset(&read_allocator, None).unwrap();
+            read_list.CopyBufferRegion(&readback, 0, &shadow.buffer, 0, LEN as u64);
+            read_list.Close().unwrap();
+            host.queue.ExecuteCommandLists(&[Some(read_list.cast().unwrap())]);
+            let fence: ID3D12Fence = host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
+            host.queue.Signal(&fence, 1).unwrap();
+            fence.SetEventOnCompletion(1, host.event).unwrap();
+            assert_eq!(WaitForSingleObject(host.event, 10_000), WAIT_OBJECT_0);
+            host.device.GetDeviceRemovedReason().unwrap();
+            let mut data = std::ptr::null_mut();
+            readback.Map(0, None, Some(&mut data)).unwrap();
+            let words = std::slice::from_raw_parts(data.cast::<u32>(), LEN / 4).to_vec();
+            readback.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 }));
+            words
+        };
+        host.card_done(plan);
+        if let Some(plan) = initial {
+            host.card_done(plan);
+        }
+        drop((root, pso));
+
+        println!("uploaded_bytes={bytes}; ranges={ranges}; mask_dispatches={passes}; readback[100]={:#010x}; readback[148]={:#010x}; readback[200]={:#010x}",
+            words[100 / 4], words[148 / 4], words[200 / 4]);
+        for (offset, word) in TITLE_WORDS {
+            assert_eq!(words[offset / 4], word, "CPU write at byte {offset}");
+        }
+        let mut expected = vec![SEED; LEN / 4];
+        for (offset, word) in TITLE_WORDS {
+            expected[offset / 4] = word;
+        }
+        let changed = words.iter().zip(&expected).filter(|(got, expected)| got != expected).count();
+        assert_eq!(changed, 0, "the upload clobbered {changed} GPU-written words");
+        assert_eq!((bytes, ranges), (8, 2));
+    }
+}

This validation was prepared with AI assistance (OpenAI Codex).

**@⁠mauroalvare** on GitHub · 2026-11-26 01:46 UTC · [original](https://github.com/LooperSalty/AnyXboxX/pull/292#issuecomment-7180112053) ## Independent D3D12 readback on NVIDIA and WARP I ran the same synthetic probe against `c4c93bdc413191a9dc909998d2d53080a3f0c880` (the PR base) and the exact PR head `770a1a2b48fc1304eb0883aa159b0fd31534f743`. The PR branch joins `main` at `578098b96f0b3140c9e082a8747782d940f0a1d2`. The VIctory tree is identical at that merge base and the tested base. The probe registers a 64 KiB write-watched title buffer, fills the device-side UAV with `0x5a5a5a5a` using a synthetic compute shader, then writes CPU words at offsets 100 and 200. It runs the real `Shadow::merge_under_writes` → `Host::card_before` upload prelude. After a fence it reads all 64 KiB back and checks both CPU words and every other GPU-written word. | Adapter / setting | Base | PR head | | --- | --- | --- | | RTX 5070 Ti, gap 256, masked dispatch | 104 bytes in 1 range, 24 GPU-written words clobbered | 8 bytes in 2 ranges, all words correct | | RTX 5070 Ti, gap 256, direct copies | Same failure | Same pass | | WARP, gap 256, masked dispatch and direct copies | Same failure in both | Same pass in both | | RTX 5070 Ti and WARP, gap 0, masked dispatch | Pass on both | Pass on both | At byte 148 the readback was `0x00000000` on base with gap 256 and `0x5a5a5a5a` on the PR. The CPU values were `0x11111111` and `0x22222222` on both revisions. The probe checked DXGI adapter identity (`0x10de`, RTX 5070 Ti, NVIDIA driver `621.40` and `0x1414`, Microsoft Basic Render Driver with the software flag) and required one mask dispatch with masks enabled and zero with direct copies. All 12 cases executed. Windows x64, Rust 1.98.1 MSVC, Cargo test profile. The fixture uses synthetic memory and shaders. The PR's own WARP range test passed with `VICTORY_COPY_COALESCE=256`. `cargo test --locked --offline -p victory-loader --test load_probe` passed 2/2 on base. `cargo xtask policy` passed on the PR (199 files). GitHub Actions `tests` passed at this head ([run #667](https://github.com/LooperSalty/AnyXboxX/actions/runs/45735962899)). One test isolation issue reproduced locally. With `cargo test --locked --offline -p victory-gpu --lib --features diagnostics -- --test-threads=1`, base had 196 passed / 3 failed / 3 ignored, while the clean PR head had 196 passed / 4 failed / 3 ignored. The pre-existing failures were `spans_say_the_next_start_and_the_lowest_level_viewed`, `warp_card_fetch_copies_flagged_pieces_to_their_slots`, and `warp_card_patch_writes_the_masked_bytes_and_no_others`. The extra failure was `watch::tests::written_pages_are_reported_to_every_asker` at `assert!(before.is_empty())`. It passed alone and failed once in three runs of the pair below. Excluding only the PR's WARP regression from the full suite on the PR restored the base result. This is consistent with the process-wide write-watch journal retaining a stamp when an address is freed and reused in the same test process. ```powershell $env:VICTORY_COPY_COALESCE = '256' cargo test --locked --offline -p victory-gpu --lib --features diagnostics -- --test-threads=1 --nocapture shadow::card_merge_tests::title_words_under_shader_writes_go_up_on_their_own watch::tests::written_pages_are_reported_to_every_asker ``` <details> <summary>Reproduce the GPU readback</summary> Apply the test-only diff below to each SHA and run from `third_party/victory`. ```powershell $env:VICTORY_CARD_BUFFERS = '1' $env:VICTORY_CARD_BUFFERS_MIN_KB = '64' $env:VICTORY_CARD_BUFFERS_MB = '8' $env:VICTORY_UNDER_WRITES_WORDS = '1' $env:VICTORY_UNDER_WRITES_MASKS = '1' $env:VICTORY_UNDER_WRITES_MASKS_LEAST = '1' $env:VICTORY_COPY_COALESCE = '256' cargo test --locked --offline -p victory-gpu --lib --features diagnostics host::nvidia_qa_pr292::preserves_gpu_writes_between_title_words -- --exact --nocapture --test-threads=1 ``` Set `VICTORY_D3D12_WARP=1` for WARP and leave it unset for the 5070 Ti. Repeat with `VICTORY_UNDER_WRITES_MASKS=0` for the direct copy path, and with `VICTORY_UNDER_WRITES_MASKS=1 VICTORY_COPY_COALESCE=0` for the control. ```diff diff --git a/third_party/victory/crates/victory-gpu/src/host.rs b/third_party/victory/crates/victory-gpu/src/host.rs index 011407c..a7aa32b 100644 --- a/third_party/victory/crates/victory-gpu/src/host.rs +++ b/third_party/victory/crates/victory-gpu/src/host.rs @@ -9476,3 +9476,153 @@ mod batch { // Batch::texture_due lives here; `mod tests` is already taken at assert_eq!(ram_idle_ms(None), 10_000); } } + +#[cfg(test)] +mod nvidia_qa_pr292 { + use super::*; + use windows::Win32::Foundation::WAIT_OBJECT_0; + use windows::Win32::Graphics::Direct3D::{Fxc::D3DCompile, ID3DBlob}; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, + VirtualFree, + }; + + const LEN: usize = 64 << 10; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + const SEED: u32 = 0x5a5a_5a5a; + const TITLE_WORDS: [(usize, u32); 2] = [(100, 0x1111_1111), (200, 0x2222_2222)]; + const FILL: &str = r#" + RWByteAddressBuffer dest : register(u0); + [RootSignature("UAV(u0)")] + [numthreads(64, 1, 1)] + void main(uint3 id : SV_DispatchThreadID) { + dest.Store(id.x * 4, 0x5a5a5a5a); + } + "#; + + struct Title(*mut u8); + + impl Drop for Title { + fn drop(&mut self) { + crate::shadow::unregister(1, self.0 as u64); + // SAFETY: the address was reserved by this test and is no longer read. + assert_ne!(unsafe { VirtualFree(self.0.cast(), 0, MEM_RELEASE) }, 0); + } + } + + #[test] + fn preserves_gpu_writes_between_title_words() { + let host = host().expect("a D3D12 device is required"); + let (name, _) = adapter_summary().expect("DXGI must identify the test device"); + // SAFETY: the host holds a live DXGI adapter for the D3D12 device. + let adapter = unsafe { host.adapter.as_ref().unwrap().GetDesc1().unwrap() }; + let software = adapter.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0; + if on_warp() { + assert!(software, "WARP requested, got {name}"); + } else { + assert_eq!(adapter.VendorId, 0x10de); + assert!(name.contains("RTX 5070 Ti") && !software, "got {name}"); + } + let masks_on = under_writes_masks(); + println!("adapter={name}; vendor={:#06x}; software={software}; coalesce={}; masks={masks_on}", + adapter.VendorId, std::env::var("VICTORY_COPY_COALESCE").unwrap()); + assert!(host.card_ready(), "card upload pipeline failed to initialize"); + // SAFETY: a new write-watched allocation, as used by title buffers. + let address = unsafe { + VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) + }.cast::<u8>(); + assert!(!address.is_null()); + let _title = Title(address); + let start = address as u64; + crate::shadow::register(1, start, LEN as u64); + let shadow = crate::shadow::find(start, LEN as u64).expect("registered title buffer"); + assert!(shadow.carded(), "registered title buffer did not get a card-side copy"); + shadow.update(start as usize, LEN); + let initial = host.card_before(&[], false); + + let readback = host.read_back_buffer(LEN as u64).unwrap(); + let (seed_allocator, seed_list) = host.make_prelude().unwrap(); + let (read_allocator, read_list) = host.make_prelude().unwrap(); + + // SAFETY: the synthetic shader and root signature address exactly LEN + // bytes of a live UAV. The command objects stay alive until the fence. + let (root, pso) = unsafe { + let mut blob: Option<ID3DBlob> = None; + D3DCompile( + FILL.as_ptr().cast(), FILL.len(), windows::core::s!("synthetic fill"), + None, None, windows::core::s!("main"), windows::core::s!("cs_5_1"), + 0, 0, &mut blob, None, + ).unwrap(); + let blob = blob.unwrap(); + let code = std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize()); + let root: ID3D12RootSignature = host.device.CreateRootSignature(0, code).unwrap(); + let pso: ID3D12PipelineState = host.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: code.as_ptr().cast(), BytecodeLength: code.len() }, + ..Default::default() + }).unwrap(); + seed_list.Reset(&seed_allocator, &pso).unwrap(); + seed_list.SetComputeRootSignature(&root); + seed_list.SetComputeRootUnorderedAccessView(0, shadow.buffer.GetGPUVirtualAddress()); + seed_list.Dispatch((LEN / 4 / 64) as u32, 1, 1); + seed_list.Close().unwrap(); + host.queue.ExecuteCommandLists(&[Some(seed_list.cast().unwrap())]); + (root, pso) + }; + + shadow.writing(start as usize, LEN); + for (offset, word) in TITLE_WORDS { + // SAFETY: the word fits inside the private allocation. + unsafe { address.add(offset).cast::<u32>().write_unaligned(word) }; + } + let mut budget = 1000; + assert!(!shadow.merge_under_writes(start as usize, LEN, &mut budget), "merge asked to wait"); + assert_eq!(budget, 998, "the merge should find both title writes"); + let stats = &crate::shadow::CARD_STATS; + let bytes_before = stats[0].load(Ordering::Relaxed); + let ranges_before = stats[1].load(Ordering::Relaxed); + let masks_before = CARD_MASKED_PASSES.load(Ordering::Relaxed); + let plan = host.card_before(&[], false).expect("no runtime upload was submitted"); + let bytes = stats[0].load(Ordering::Relaxed) - bytes_before; + let ranges = stats[1].load(Ordering::Relaxed) - ranges_before; + let passes = CARD_MASKED_PASSES.load(Ordering::Relaxed) - masks_before; + assert_eq!(passes, u64::from(masks_on), "unexpected upload path"); + + // SAFETY: both lists use the same direct queue. The buffer decays to + // COMMON across ExecuteCommandLists. The fence orders the CPU map. + let words = unsafe { + read_list.Reset(&read_allocator, None).unwrap(); + read_list.CopyBufferRegion(&readback, 0, &shadow.buffer, 0, LEN as u64); + read_list.Close().unwrap(); + host.queue.ExecuteCommandLists(&[Some(read_list.cast().unwrap())]); + let fence: ID3D12Fence = host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + host.queue.Signal(&fence, 1).unwrap(); + fence.SetEventOnCompletion(1, host.event).unwrap(); + assert_eq!(WaitForSingleObject(host.event, 10_000), WAIT_OBJECT_0); + host.device.GetDeviceRemovedReason().unwrap(); + let mut data = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut data)).unwrap(); + let words = std::slice::from_raw_parts(data.cast::<u32>(), LEN / 4).to_vec(); + readback.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 })); + words + }; + host.card_done(plan); + if let Some(plan) = initial { + host.card_done(plan); + } + drop((root, pso)); + + println!("uploaded_bytes={bytes}; ranges={ranges}; mask_dispatches={passes}; readback[100]={:#010x}; readback[148]={:#010x}; readback[200]={:#010x}", + words[100 / 4], words[148 / 4], words[200 / 4]); + for (offset, word) in TITLE_WORDS { + assert_eq!(words[offset / 4], word, "CPU write at byte {offset}"); + } + let mut expected = vec![SEED; LEN / 4]; + for (offset, word) in TITLE_WORDS { + expected[offset / 4] = word; + } + let changed = words.iter().zip(&expected).filter(|(got, expected)| got != expected).count(); + assert_eq!(changed, 0, "the upload clobbered {changed} GPU-written words"); + assert_eq!((bytes, ranges), (8, 2)); + } +} ``` </details> This validation was prepared with AI assistance (OpenAI Codex).
Author
Owner

@⁠KainanP on GitHub · 2026-11-26 10:32 UTC · original

Test report for #292 on three adapters.

Merges cleanly onto current main. Setup: current origin/main (c4c93bd) merged with this PR, Windows 11, cargo test --locked in third_party/victory. Adapters: RTX 4060 Laptop (DXGI 0), Intel UHD 8086:a78b (16-lane waves, no FP64), WARP. The hardware adapter is picked by name through a local, uncommitted test hook and confirmed in its log; WARP for victory-gpu is --features diagnostics + VICTORY_D3D12_WARP=1. victory-gpu runs with --test-threads=1.

victory-gpu --lib main main + #292
RTX 4060 Laptop 183 passed, main's 3 failed first run 184 passed, main's 3 failed; then 4 failed in 3 of 4 more full runs
Intel UHD 183 passed, main's 3 failed 183 passed, 4 failed (6 of 7 full runs)
WARP 196 passed, main's 3 failed 196 passed, 4 failed (1 run)

"main's 3" = descriptor::host::tests::spans_say_the_next_start_and_the_lowest_level_viewed, indirect::tests::warp_card_fetch_copies_flagged_pieces_to_their_slots, indirect::tests::warp_card_patch_writes_the_masked_bytes_and_no_others. They fail on all three adapters on main too.

New failure: watch::tests::written_pages_are_reported_to_every_asker at watch.rs:2022, assertion failed: before.is_empty(). It depends on test order and is not tied to an adapter:

  • that test alone: passes (3/3);
  • that test with only title_words_under_shader_writes_go_up_on_their_own, or with all of shadow::: passes;
  • the full suite with --skip title_words_under: passes (3/3, RTX);
  • the full suite with the new test: fails most runs on all three adapters. No other PR I ran today (#254–#337) shows it.

So something the new test leaves behind (its write-watched region freed with VirtualFree, or what merge_under_writes recorded for it) is seen by a later test that gets a fresh write-watched allocation, probably at the reused address. It could be the pending range it pushes, or watch state kept for that range. I did not find which. Clearing that state, or keeping the region alive to the end of the process, should fix it.

The new test passes in every run.

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

**@⁠KainanP** on GitHub · 2026-11-26 10:32 UTC · [original](https://github.com/LooperSalty/AnyXboxX/pull/292#issuecomment-7189501610) Test report for #292 on three adapters. Merges cleanly onto current main. Setup: current `origin/main` (c4c93bd) merged with this PR, Windows 11, `cargo test --locked` in `third_party/victory`. Adapters: RTX 4060 Laptop (DXGI 0), Intel UHD 8086:a78b (16-lane waves, no FP64), WARP. The hardware adapter is picked by name through a local, uncommitted test hook and confirmed in its log; WARP for victory-gpu is `--features diagnostics` + `VICTORY_D3D12_WARP=1`. victory-gpu runs with `--test-threads=1`. | `victory-gpu --lib` | main | main + #292 | |---|---|---| | RTX 4060 Laptop | 183 passed, main's 3 failed | first run 184 passed, main's 3 failed; then **4 failed in 3 of 4 more full runs** | | Intel UHD | 183 passed, main's 3 failed | 183 passed, **4 failed** (6 of 7 full runs) | | WARP | 196 passed, main's 3 failed | 196 passed, **4 failed** (1 run) | "main's 3" = `descriptor::host::tests::spans_say_the_next_start_and_the_lowest_level_viewed`, `indirect::tests::warp_card_fetch_copies_flagged_pieces_to_their_slots`, `indirect::tests::warp_card_patch_writes_the_masked_bytes_and_no_others`. They fail on all three adapters on main too. **New failure:** `watch::tests::written_pages_are_reported_to_every_asker` at `watch.rs:2022`, `assertion failed: before.is_empty()`. It depends on test order and is not tied to an adapter: - that test alone: passes (3/3); - that test with only `title_words_under_shader_writes_go_up_on_their_own`, or with all of `shadow::`: passes; - the full suite with `--skip title_words_under`: passes (3/3, RTX); - the full suite with the new test: fails most runs on all three adapters. No other PR I ran today (#254–#337) shows it. So something the new test leaves behind (its write-watched region freed with `VirtualFree`, or what `merge_under_writes` recorded for it) is seen by a later test that gets a fresh write-watched allocation, probably at the reused address. It could be the `pending` range it pushes, or watch state kept for that range. I did not find which. Clearing that state, or keeping the region alive to the end of the process, should fix it. The new test passes in every run. _AI use: Claude Code (Claude Opus 5.5) ran the tests and wrote this._
github-bot force-pushed github-bot/gh-292 from 770a1a2b48 to 8ca6d516f5 2026-11-26 15:03:52 +00:00 Compare
Author
Owner

@⁠Skyfrye on GitHub · 2026-11-26 15:03 UTC · original

Rebased on main at 2cc6593. Since #291 and #340 came in through #358, Card has two more fields (me, prints), so the test's Card now sets them; the change itself is the same. VICTORY_D3D12_WARP=1 cargo test --locked -p victory-gpu --lib title_words_under_shader_writes -> 1 passed. It is also in the integration build with #354, #345 and #360-#362, #381 and #382: 259 passed and the 3 failures main has.

🤖 Generated with Claude Code

**@⁠Skyfrye** on GitHub · 2026-11-26 15:03 UTC · [original](https://github.com/LooperSalty/AnyXboxX/pull/292#issuecomment-7195719521) Rebased on `main` at `2cc6593`. Since #291 and #340 came in through #358, `Card` has two more fields (`me`, `prints`), so the test's `Card` now sets them; the change itself is the same. `VICTORY_D3D12_WARP=1 cargo test --locked -p victory-gpu --lib title_words_under_shader_writes` -> 1 passed. It is also in the integration build with #354, #345 and #360-#362, #381 and #382: 259 passed and the 3 failures main has. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
This pull request has changes conflicting with the target branch.
  • third_party/victory/crates/victory-gpu/src/shadow.rs
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/292/head:github-bot/gh-292'
git switch 'github-bot/gh-292'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-292'
git switch 'github-bot/gh-292'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-292'
git switch 'github-bot/gh-292'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-292'
git switch 'main'
git merge --squash 'github-bot/gh-292'
git switch 'main'
git merge --ff-only 'github-bot/gh-292'
git switch 'main'
git merge 'github-bot/gh-292'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.