GPU: skip unchanged texture uploads via prelude copy recording #230

Open
github-bot wants to merge 2 commits from github-bot/gh-230 into main AGit
Owner

@⁠wbkepler on GitHub · 2026-11-24 01:38 UTC · original
wbkepler:gpu/skip-clean-texture-uploads → main · +702 −153 · 4 files · 2 commits · open

Summary

  • Decouples title-written texture CopyTextureRegion recording from command-list record time onto HostList::prelude at submission time so unchanged textures are not DMA-copied every frame.
  • texture::upload now registers (Arc<Staging>, Arc<HostTexture>) with the HostList without transitioning to COPY_DEST or baking CopyTextureRegion into the main list (preserving host_written skipping, per-list first_use dedup, and resource lifetimes).
  • Staging::refresh returns dirty: bool across both MEM_WRITE_WATCH and blake3 hash paths.
  • HostList::prelude transitions to COPY_DEST, records CopyTextureRegion, and transitions into the main list's expected first state only when refresh reports dirty contents (including first upload), skipping all GPU copies and redundant barriers on clean frames.
  • Adds 3 live D3D12 WARP unit tests in texture.rs covering initial pixel readback, zero copies on clean/reused/multi-list submissions (both hash and MEM_WRITE_WATCH paths), single re-upload on CPU modification, and host_written protection.

Verification

  • cargo clippy --workspace --all-targets — passed (zero new warnings)
  • cargo clippy -p victory --features diagnostics --all-targets — passed
  • cargo test --workspace — passed (46 passed, 1 ignored in victory-gpu)
  • cargo xtask policy — passed (151 files ok)
**@⁠wbkepler** on GitHub · 2026-11-24 01:38 UTC · [original](https://github.com/Marvisak/VIctory/pull/230) `wbkepler:gpu/skip-clean-texture-uploads` → `main` · +702 −153 · 4 files · 2 commits · open ## Summary - Decouples title-written texture `CopyTextureRegion` recording from command-list record time onto `HostList::prelude` at submission time so unchanged textures are not DMA-copied every frame. - `texture::upload` now registers `(Arc<Staging>, Arc<HostTexture>)` with the `HostList` without transitioning to `COPY_DEST` or baking `CopyTextureRegion` into the main list (preserving `host_written` skipping, per-list `first_use` dedup, and resource lifetimes). - `Staging::refresh` returns `dirty: bool` across both `MEM_WRITE_WATCH` and `blake3` hash paths. - `HostList::prelude` transitions to `COPY_DEST`, records `CopyTextureRegion`, and transitions into the main list's expected first state only when `refresh` reports dirty contents (including first upload), skipping all GPU copies and redundant barriers on clean frames. - Adds 3 live D3D12 WARP unit tests in `texture.rs` covering initial pixel readback, zero copies on clean/reused/multi-list submissions (both hash and `MEM_WRITE_WATCH` paths), single re-upload on CPU modification, and `host_written` protection. ## Verification - `cargo clippy --workspace --all-targets` — passed (zero new warnings) - `cargo clippy -p victory --features diagnostics --all-targets` — passed - `cargo test --workspace` — passed (46 passed, 1 ignored in `victory-gpu`) - `cargo xtask policy` — passed (151 files ok)
Decouple title-written texture CopyTextureRegion recording from
command-list record time so unchanged textures are no longer DMA-copied
over PCIe on every command list every frame:

- At record time (`texture::upload`), register the texture's `Staging`
  and `Arc<HostTexture>` with the `HostList` (still skipping
  `host_written` textures and deduplicating per list) without
  transitioning to `COPY_DEST` or unconditionally recording
  `CopyTextureRegion` on the main command list.
- At submission time (`Host::execute`), `Staging::refresh()` returns
  whether title memory actually changed (including first-time upload)
  via either write-watch or blake3 hashing.
- Only when `refresh()` reports dirty contents does `HostList::prelude`
  transition the host texture to `COPY_DEST`, record `CopyTextureRegion`
  for every subresource from the staging buffer, and transition it into
  the main command list's expected initial state. Clean frames record
  zero GPU texture copies and zero redundant barriers.
- Add D3D12 WARP tests in `crates/victory-gpu/src/texture.rs` verifying
  initial upload pixel readback, zero GPU copies on unchanged subsequent
  frames (both hash-checked and `MEM_WRITE_WATCH` paths, across multiple
  and reused lists), fresh single-copy re-upload on CPU modification,
  and `host_written` protection.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 03:55:42 +00:00
Author
Owner

@⁠jeremygold02 on GitHub · 2026-11-24 05:32 UTC · original

Thanks @⁠wbkepler for adding upload-count checks for unchanged, CPU-written, and host-written textures.

I tested commit 6a96adbfb8fcb001686dc251a24cda3dd34ee51c with:

cargo test --locked -p victory-gpu --lib texture -- --test-threads=1

The texture-filter run completed with 6 passed, 0 failed, 1 ignored benchmark, and 40 filtered tests. The three new cases verify:

The WARP tests return early when the software adapter is unavailable, and the harness reports that return as passed; this run does not distinguish that case from executing the assertions. The tests cover the D3D12 WARP path, not a hardware adapter or a title’s texture workload.

**@⁠jeremygold02** on GitHub · 2026-11-24 05:32 UTC · [original](https://github.com/Marvisak/VIctory/pull/230#issuecomment-7123041347) Thanks @⁠wbkepler for adding upload-count checks for unchanged, CPU-written, and host-written textures. I tested commit `6a96adbfb8fcb001686dc251a24cda3dd34ee51c` with: ``` cargo test --locked -p victory-gpu --lib texture -- --test-threads=1 ``` The texture-filter run completed with 6 passed, 0 failed, 1 ignored benchmark, and 40 filtered tests. The three new cases verify: - [`warp_skips_clean_texture_uploads_and_reuploads_on_change`](https://github.com/Marvisak/VIctory/blob/6a96adbfb8fcb001686dc251a24cda3dd34ee51c/crates/victory-gpu/src/texture.rs#L539) records one initial copy, no copies for unchanged memory across multiple lists or resubmission, exactly one new copy after CPU data changes, and no extra copy on the next clean submission; readback pixels and resource state are also checked. - [`warp_write_watched_texture_uploads_only_when_written`](https://github.com/Marvisak/VIctory/blob/6a96adbfb8fcb001686dc251a24cda3dd34ee51c/crates/victory-gpu/src/texture.rs#L622) checks initial upload, clean-page skipping, a fresh upload after a write to watched memory, and skipping again when clean. - [`host_written_texture_never_queues_cpu_upload`](https://github.com/Marvisak/VIctory/blob/6a96adbfb8fcb001686dc251a24cda3dd34ee51c/crates/victory-gpu/src/texture.rs#L699) verifies a host-written resource does not enqueue CPU-to-GPU work. The WARP tests return early when the software adapter is unavailable, and the harness reports that return as passed; this run does not distinguish that case from executing the assertions. The tests cover the D3D12 WARP path, not a hardware adapter or a title’s texture workload.
Author
Owner

@⁠andrewpozdnakov7-jpg on GitHub · 2026-11-24 10:05 UTC · original

I checked a related ordering case on 6a96adb for #758. Recording and closing a CopyResource list marks the destination host-written immediately. If that list is discarded, an independent list still skips the CPU texture upload. A Windows D3D12 WARP regression confirmed that the upload is queued before recording the copy and suppressed afterward, even though the copy list is never submitted.

The patch keeps the write marker on the command list and applies it while preparing submitted lists in order. The unsubmitted-copy regression passes with it. A second test submits a real GPU copy followed by a reader in one batch, checks that it emitted zero staging copies, and reads back the GPU-copied pixels. With the submission-time guard disabled, that second test fails.

The diagnostic suite can still hit the existing write-watch flake documented in #185. That test failed in 2 of 5 full runs before this patch and 1 of 5 with it, and passed in isolation on both. Library Clippy with warnings denied passed. This patch covers discarded lists. The later CPU-write case in #758 is still separate.

AI-assisted. Synthetic WARP tests only.

Tested follow-up diff for 6a96adb
diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs
index b65fab8baaf77653a823ca9cdab57bc8d05620b5..0f27f72c2153779dc490d7be7d0c561315792ccc 100644
--- a/crates/victory-gpu/src/host.rs
+++ b/crates/victory-gpu/src/host.rs
@@ -406,6 +406,8 @@ enum Step {
     Host(Box<dyn Fn() + Send>),
     /// Shaders write a range (address, bytes) of a buffer's host copy.
     GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
+    /// A submitted copy or resolve makes this host texture authoritative.
+    TextureHostWrite(std::sync::Arc<crate::resource::HostTexture>),
     /// Brings a texture's staging buffer up to date and, when dirty, copies
     /// it into the host texture on the list's prelude: once per submission,
     /// whichever lists sample it, until a `Copy` or `Run` intervenes.
@@ -1227,6 +1229,10 @@ impl HostList {
         self.deferred().copies.push(Step::Host(Box::new(work)));
     }
 
+    pub(crate) fn defer_texture_write(&self, texture: std::sync::Arc<crate::resource::HostTexture>) {
+        self.deferred().copies.push(Step::TextureHostWrite(texture));
+    }
+
     /// Brings a texture's staging buffer up to date when the list is
     /// submitted (and copies it to `texture` on the prelude only if dirty),
     /// keeping both alive until the list is reset.
@@ -1303,8 +1309,15 @@ impl HostList {
                     shadow.writing(*address, *len);
                     continue;
                 }
+                Step::TextureHostWrite(copy) => {
+                    copy.host_written.store(true, Ordering::Relaxed);
+                    continue;
+                }
                 Step::Texture(staging, copy) => {
-                    if batch.texture_due(staging) && staging.refresh() {
+                    if !copy.host_written.load(Ordering::Relaxed)
+                        && batch.texture_due(staging)
+                        && staging.refresh()
+                    {
                         uploads.push((staging.clone(), copy.clone()));
                     }
                     continue;
diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs
index 78d6d736e282363deb6c59132a2d133d000b326e..85dd4753765f54d7cdcca23c979c8d7d878734a5 100644
--- a/crates/victory-gpu/src/list.rs
+++ b/crates/victory-gpu/src/list.rs
@@ -448,7 +448,7 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) {
         ) {
             ensure_state(list, dst, COPY_DEST);
             ensure_state(list, src, COPY_SOURCE);
-            crate::texture::host_written(dst);
+            crate::texture::defer_host_write(list, dst);
             #[cfg(feature = "diagnostics")]
             list.note_op(|| format!("copy resource {src:?} to {dst:?}"));
             // SAFETY: an open list and live textures.
@@ -539,7 +539,7 @@ extern "system" fn copy_texture_region(
             from.resource = texture.as_raw().cast_const().cast();
         }
         ensure_state(list, dst.resource, COPY_DEST);
-        crate::texture::host_written(dst.resource);
+        crate::texture::defer_host_write(list, dst.resource);
         let mut to_location = dst;
         to_location.resource = to.as_raw().cast_const().cast();
         let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>());
@@ -623,7 +623,7 @@ extern "system" fn resolve(
         const RESOLVE_SOURCE: u32 = 0x2000;
         ensure_state(list, dst, RESOLVE_DEST);
         ensure_state(list, src, RESOLVE_SOURCE);
-        crate::texture::host_written(dst);
+        crate::texture::defer_host_write(list, dst);
         #[cfg(feature = "diagnostics")]
         list.note_op(|| format!("resolve {src:?} to {dst:?} format {format}"));
         // SAFETY: an open list and live textures; the region is inside both.
diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs
index 46c5c71abfaee7f985586417519eb243e3ad35d3..9a8402a6dc169f4fe6e11a5b581968bccbd95dbc 100644
--- a/crates/victory-gpu/src/resource.rs
+++ b/crates/victory-gpu/src/resource.rs
@@ -761,6 +761,7 @@ struct Resource {
 pub(crate) struct HostTexture {
     pub(crate) texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource,
     pub(crate) state: std::sync::atomic::AtomicU32,
+    pub(crate) host_written: std::sync::atomic::AtomicBool,
 }
 
 /// Moves the host texture to `wanted` (a host texture state); the host
@@ -941,6 +942,7 @@ fn hand_out_resource(
             std::sync::Arc::new(HostTexture {
                 texture,
                 state: state.into(),
+                host_written: false.into(),
             })
         }),
     });
@@ -1409,6 +1411,57 @@ mod tests {
         heap
     }
 
+    #[cfg(all(windows, feature = "diagnostics"))]
+    #[test]
+    #[ignore = "requires D3D12"]
+    fn recording_an_unsubmitted_copy_keeps_cpu_texture_uploads() {
+        let _host = crate::host::host().expect("D3D12 host");
+        let null = std::ptr::null();
+        let allocator_iid = crate::object::guid(
+            0x6102dee4, 0xaf59, 0x4b09, [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24],
+        );
+        let list_iid = crate::object::guid(
+            0x5b160d0f, 0xac1b, 0x4185, [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55],
+        );
+        let mut allocator = null;
+        assert_eq!(crate::list::create_allocator(null, 0, &allocator_iid, &mut allocator), S_OK);
+        let command_list = || {
+            let mut list = null;
+            assert_eq!(crate::list::create_list(null, 0, 0, allocator, null, &list_iid, &mut list), S_OK);
+            list
+        };
+        let new_texture = || {
+            let mut resource = null;
+            let desc = ResourceDesc { layout: 1, ..texture(4, 4, 28, 1) };
+            assert_eq!(
+                create_committed(null, &PROPERTIES, 0, &desc, 0, null.cast(), &RESOURCE_IIDS[0], &mut resource),
+                S_OK,
+            );
+            resource
+        };
+        let (src, dst) = (new_texture(), new_texture());
+        let upload_is_queued = |list| {
+            let list = crate::list::host_list(list).expect("host list");
+            crate::texture::upload(list, dst, host_resource(dst).expect("host texture"));
+            list.has_deferred_work()
+        };
+        let (control, copy, sample) = (command_list(), command_list(), command_list());
+        let before = upload_is_queued(control);
+        let copy_resource = slot::<extern "system" fn(This, This, This)>(copy, 0x88);
+        copy_resource(copy, dst, src);
+        let close = slot::<extern "system" fn(This) -> HRESULT>(copy, 0x48);
+        assert_eq!(close(copy), S_OK);
+        // The control and copy lists are never submitted. This independent
+        // list must still see the guest-backed destination as uploadable.
+        let after = upload_is_queued(sample);
+
+        for object in [sample, copy, control, dst, src, allocator] {
+            slot::<Release>(object, 0x10)(object);
+        }
+        assert!(before, "the control must queue the upload");
+        assert!(after, "an unsubmitted CopyResource suppressed the upload");
+    }
+
     #[test]
     fn heaps_are_zeroed_aligned_memory() {
         let heap = heap(1 << 20);
diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs
index c8c13e99abb5f14c381a0871c45cccb31db66374..6d939fb8e60a5ce9c235c4ef27964d467092ce45 100644
--- a/crates/victory-gpu/src/texture.rs
+++ b/crates/victory-gpu/src/texture.rs
@@ -64,15 +64,11 @@ unsafe impl Sync for Staging {}
 
 static STAGING: Mutex<Option<HashMap<usize, Arc<Staging>>>> = Mutex::new(None);
 
-/// Textures the host GPU wrote by a copy or resolve: their contents are on
-/// the host, not in title memory, which stays as it was.
-static HOST_WRITTEN: Mutex<Option<std::collections::HashSet<usize>>> = Mutex::new(None);
-
-/// A host copy or resolve writes `resource`.
-pub(crate) fn host_written(resource: This) {
-    let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
-    set.get_or_insert_with(Default::default)
-        .insert(resource as usize);
+/// Records a copy or resolve's write alongside the list's other deferred work.
+pub(crate) fn defer_host_write(list: &HostList, resource: This) {
+    if let Some(copy) = crate::resource::host_copy(resource) {
+        list.defer_texture_write(copy);
+    }
 }
 
 /// The title released a resource.
@@ -81,10 +77,6 @@ pub(crate) fn forget(resource: usize) {
     if let Some(map) = map.as_mut() {
         map.remove(&resource);
     }
-    let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
-    if let Some(set) = set.as_mut() {
-        set.remove(&resource);
-    }
 }
 
 /// Whether `resource`'s host copy takes its contents from title memory:
@@ -100,19 +92,14 @@ pub(crate) fn title_written(texture: &ID3D12Resource) -> bool {
 /// only when its contents changed (including first upload), copied into its
 /// host texture on the list's prelude command list.
 pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) {
-    let host_written = HOST_WRITTEN
-        .lock()
-        .unwrap_or_else(|e| e.into_inner())
-        .as_ref()
-        .is_some_and(|set| set.contains(&(resource as usize)));
-    // shortcut: a texture the host copied into keeps the host's contents
-    // even if the title later writes its memory too.
-    if host_written || !list.first_use(resource as usize) {
-        return;
-    }
     let Some(copy) = crate::resource::host_copy(resource) else {
         return;
     };
+    if copy.host_written.load(std::sync::atomic::Ordering::Relaxed)
+        || !list.first_use(resource as usize)
+    {
+        return;
+    }
     let Some(staging) = staging(resource, texture) else {
         return;
     };
@@ -402,6 +389,7 @@ mod tests {
         let copy = Arc::new(HostTexture {
             texture: resource.unwrap(),
             state: AtomicU32::new(D3D12_RESOURCE_STATE_COMMON.0 as u32),
+            host_written: false.into(),
         });
         (copy, layout_tex)
     }
@@ -696,19 +684,52 @@ mod tests {
     }
 
     #[test]
-    fn host_written_texture_never_queues_cpu_upload() {
+    fn submitted_texture_write_prevents_a_later_staging_copy() {
         let Some(host) = Host::new_warp() else {
             return;
         };
-        let (copy, _) = make_rgba_texture(&host, 4, 4);
-        let fake_resource = 0x1234_5678usize as This;
-        host_written(fake_resource);
-        let list = host.new_list().expect("new list");
-        upload(&list, fake_resource, &copy.texture);
-        assert!(
-            !list.has_deferred_work(),
-            "host-written textures must not queue CPU-to-GPU uploads"
-        );
-        forget(fake_resource as usize);
+        let (copy, tex) = make_rgba_texture(&host, 4, 4);
+        let layout = tex.planes[0].layout.clone();
+        let mut title_mem = vec![0u8; layout.size as usize];
+        fill_linear_rgba(&layout, &mut title_mem, [0x11, 0x22, 0x33, 0xff]);
+        let staging = create_staging(
+            &host,
+            std::ptr::null(),
+            &copy.texture,
+            layout,
+            title_mem.as_ptr(),
+        )
+        .expect("create staging");
+        let (source, source_tex) = make_rgba_texture(&host, 4, 4);
+        let source_layout = source_tex.planes[0].layout.clone();
+        let mut source_mem = vec![0u8; source_layout.size as usize];
+        let gpu_pixel = [0x44, 0x55, 0x66, 0xff];
+        fill_linear_rgba(&source_layout, &mut source_mem, gpu_pixel);
+        let source_staging = create_staging(
+            &host,
+            std::ptr::null(),
+            &source.texture,
+            source_layout,
+            source_mem.as_ptr(),
+        )
+        .expect("create source staging");
+        let writer = host.new_list().expect("writer");
+        writer.defer_texture(source_staging, source.clone());
+        writer.expect_texture_state(&source, D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32);
+        writer.expect_texture_state(&copy, D3D12_RESOURCE_STATE_COPY_DEST.0 as u32);
+        writer.defer_texture_write(copy.clone());
+        // SAFETY: compatible textures, with the source and destination
+        // states established by the prelude.
+        unsafe { writer.list.CopyResource(&copy.texture, &source.texture) };
+        writer.close();
+        let reader = host.new_list().expect("reader");
+        reader.defer_texture(staging.clone(), copy.clone());
+        reader.expect_texture_state(&copy, SHADER_RESOURCE);
+        reader.close();
+
+        host.execute(&[&writer, &reader]);
+
+        assert_eq!(staging.gpu_uploads(), 0, "the host write takes precedence");
+        assert!(all_pixels_eq(&read_back_rgba(&host, &copy, 4, 4), gpu_pixel));
     }
 }
**@⁠andrewpozdnakov7-jpg** on GitHub · 2026-11-24 10:05 UTC · [original](https://github.com/Marvisak/VIctory/pull/230#issuecomment-7128295691) I checked a related ordering case on `6a96adb` for #758. Recording and closing a `CopyResource` list marks the destination host-written immediately. If that list is discarded, an independent list still skips the CPU texture upload. A Windows D3D12 WARP regression confirmed that the upload is queued before recording the copy and suppressed afterward, even though the copy list is never submitted. The patch keeps the write marker on the command list and applies it while preparing submitted lists in order. The unsubmitted-copy regression passes with it. A second test submits a real GPU copy followed by a reader in one batch, checks that it emitted zero staging copies, and reads back the GPU-copied pixels. With the submission-time guard disabled, that second test fails. The diagnostic suite can still hit the existing write-watch flake documented in #185. That test failed in 2 of 5 full runs before this patch and 1 of 5 with it, and passed in isolation on both. Library Clippy with warnings denied passed. This patch covers discarded lists. The later CPU-write case in #758 is still separate. AI-assisted. Synthetic WARP tests only. <details> <summary>Tested follow-up diff for 6a96adb</summary> ~~~diff diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index b65fab8baaf77653a823ca9cdab57bc8d05620b5..0f27f72c2153779dc490d7be7d0c561315792ccc 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -406,6 +406,8 @@ enum Step { Host(Box<dyn Fn() + Send>), /// Shaders write a range (address, bytes) of a buffer's host copy. GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize), + /// A submitted copy or resolve makes this host texture authoritative. + TextureHostWrite(std::sync::Arc<crate::resource::HostTexture>), /// Brings a texture's staging buffer up to date and, when dirty, copies /// it into the host texture on the list's prelude: once per submission, /// whichever lists sample it, until a `Copy` or `Run` intervenes. @@ -1227,6 +1229,10 @@ impl HostList { self.deferred().copies.push(Step::Host(Box::new(work))); } + pub(crate) fn defer_texture_write(&self, texture: std::sync::Arc<crate::resource::HostTexture>) { + self.deferred().copies.push(Step::TextureHostWrite(texture)); + } + /// Brings a texture's staging buffer up to date when the list is /// submitted (and copies it to `texture` on the prelude only if dirty), /// keeping both alive until the list is reset. @@ -1303,8 +1309,15 @@ impl HostList { shadow.writing(*address, *len); continue; } + Step::TextureHostWrite(copy) => { + copy.host_written.store(true, Ordering::Relaxed); + continue; + } Step::Texture(staging, copy) => { - if batch.texture_due(staging) && staging.refresh() { + if !copy.host_written.load(Ordering::Relaxed) + && batch.texture_due(staging) + && staging.refresh() + { uploads.push((staging.clone(), copy.clone())); } continue; diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 78d6d736e282363deb6c59132a2d133d000b326e..85dd4753765f54d7cdcca23c979c8d7d878734a5 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -448,7 +448,7 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { ) { ensure_state(list, dst, COPY_DEST); ensure_state(list, src, COPY_SOURCE); - crate::texture::host_written(dst); + crate::texture::defer_host_write(list, dst); #[cfg(feature = "diagnostics")] list.note_op(|| format!("copy resource {src:?} to {dst:?}")); // SAFETY: an open list and live textures. @@ -539,7 +539,7 @@ extern "system" fn copy_texture_region( from.resource = texture.as_raw().cast_const().cast(); } ensure_state(list, dst.resource, COPY_DEST); - crate::texture::host_written(dst.resource); + crate::texture::defer_host_write(list, dst.resource); let mut to_location = dst; to_location.resource = to.as_raw().cast_const().cast(); let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>()); @@ -623,7 +623,7 @@ extern "system" fn resolve( const RESOLVE_SOURCE: u32 = 0x2000; ensure_state(list, dst, RESOLVE_DEST); ensure_state(list, src, RESOLVE_SOURCE); - crate::texture::host_written(dst); + crate::texture::defer_host_write(list, dst); #[cfg(feature = "diagnostics")] list.note_op(|| format!("resolve {src:?} to {dst:?} format {format}")); // SAFETY: an open list and live textures; the region is inside both. diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 46c5c71abfaee7f985586417519eb243e3ad35d3..9a8402a6dc169f4fe6e11a5b581968bccbd95dbc 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -761,6 +761,7 @@ struct Resource { pub(crate) struct HostTexture { pub(crate) texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, pub(crate) state: std::sync::atomic::AtomicU32, + pub(crate) host_written: std::sync::atomic::AtomicBool, } /// Moves the host texture to `wanted` (a host texture state); the host @@ -941,6 +942,7 @@ fn hand_out_resource( std::sync::Arc::new(HostTexture { texture, state: state.into(), + host_written: false.into(), }) }), }); @@ -1409,6 +1411,57 @@ mod tests { heap } + #[cfg(all(windows, feature = "diagnostics"))] + #[test] + #[ignore = "requires D3D12"] + fn recording_an_unsubmitted_copy_keeps_cpu_texture_uploads() { + let _host = crate::host::host().expect("D3D12 host"); + let null = std::ptr::null(); + let allocator_iid = crate::object::guid( + 0x6102dee4, 0xaf59, 0x4b09, [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24], + ); + let list_iid = crate::object::guid( + 0x5b160d0f, 0xac1b, 0x4185, [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55], + ); + let mut allocator = null; + assert_eq!(crate::list::create_allocator(null, 0, &allocator_iid, &mut allocator), S_OK); + let command_list = || { + let mut list = null; + assert_eq!(crate::list::create_list(null, 0, 0, allocator, null, &list_iid, &mut list), S_OK); + list + }; + let new_texture = || { + let mut resource = null; + let desc = ResourceDesc { layout: 1, ..texture(4, 4, 28, 1) }; + assert_eq!( + create_committed(null, &PROPERTIES, 0, &desc, 0, null.cast(), &RESOURCE_IIDS[0], &mut resource), + S_OK, + ); + resource + }; + let (src, dst) = (new_texture(), new_texture()); + let upload_is_queued = |list| { + let list = crate::list::host_list(list).expect("host list"); + crate::texture::upload(list, dst, host_resource(dst).expect("host texture")); + list.has_deferred_work() + }; + let (control, copy, sample) = (command_list(), command_list(), command_list()); + let before = upload_is_queued(control); + let copy_resource = slot::<extern "system" fn(This, This, This)>(copy, 0x88); + copy_resource(copy, dst, src); + let close = slot::<extern "system" fn(This) -> HRESULT>(copy, 0x48); + assert_eq!(close(copy), S_OK); + // The control and copy lists are never submitted. This independent + // list must still see the guest-backed destination as uploadable. + let after = upload_is_queued(sample); + + for object in [sample, copy, control, dst, src, allocator] { + slot::<Release>(object, 0x10)(object); + } + assert!(before, "the control must queue the upload"); + assert!(after, "an unsubmitted CopyResource suppressed the upload"); + } + #[test] fn heaps_are_zeroed_aligned_memory() { let heap = heap(1 << 20); diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index c8c13e99abb5f14c381a0871c45cccb31db66374..6d939fb8e60a5ce9c235c4ef27964d467092ce45 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -64,15 +64,11 @@ unsafe impl Sync for Staging {} static STAGING: Mutex<Option<HashMap<usize, Arc<Staging>>>> = Mutex::new(None); -/// Textures the host GPU wrote by a copy or resolve: their contents are on -/// the host, not in title memory, which stays as it was. -static HOST_WRITTEN: Mutex<Option<std::collections::HashSet<usize>>> = Mutex::new(None); - -/// A host copy or resolve writes `resource`. -pub(crate) fn host_written(resource: This) { - let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); - set.get_or_insert_with(Default::default) - .insert(resource as usize); +/// Records a copy or resolve's write alongside the list's other deferred work. +pub(crate) fn defer_host_write(list: &HostList, resource: This) { + if let Some(copy) = crate::resource::host_copy(resource) { + list.defer_texture_write(copy); + } } /// The title released a resource. @@ -81,10 +77,6 @@ pub(crate) fn forget(resource: usize) { if let Some(map) = map.as_mut() { map.remove(&resource); } - let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(set) = set.as_mut() { - set.remove(&resource); - } } /// Whether `resource`'s host copy takes its contents from title memory: @@ -100,19 +92,14 @@ pub(crate) fn title_written(texture: &ID3D12Resource) -> bool { /// only when its contents changed (including first upload), copied into its /// host texture on the list's prelude command list. pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) { - let host_written = HOST_WRITTEN - .lock() - .unwrap_or_else(|e| e.into_inner()) - .as_ref() - .is_some_and(|set| set.contains(&(resource as usize))); - // shortcut: a texture the host copied into keeps the host's contents - // even if the title later writes its memory too. - if host_written || !list.first_use(resource as usize) { - return; - } let Some(copy) = crate::resource::host_copy(resource) else { return; }; + if copy.host_written.load(std::sync::atomic::Ordering::Relaxed) + || !list.first_use(resource as usize) + { + return; + } let Some(staging) = staging(resource, texture) else { return; }; @@ -402,6 +389,7 @@ mod tests { let copy = Arc::new(HostTexture { texture: resource.unwrap(), state: AtomicU32::new(D3D12_RESOURCE_STATE_COMMON.0 as u32), + host_written: false.into(), }); (copy, layout_tex) } @@ -696,19 +684,52 @@ mod tests { } #[test] - fn host_written_texture_never_queues_cpu_upload() { + fn submitted_texture_write_prevents_a_later_staging_copy() { let Some(host) = Host::new_warp() else { return; }; - let (copy, _) = make_rgba_texture(&host, 4, 4); - let fake_resource = 0x1234_5678usize as This; - host_written(fake_resource); - let list = host.new_list().expect("new list"); - upload(&list, fake_resource, &copy.texture); - assert!( - !list.has_deferred_work(), - "host-written textures must not queue CPU-to-GPU uploads" - ); - forget(fake_resource as usize); + let (copy, tex) = make_rgba_texture(&host, 4, 4); + let layout = tex.planes[0].layout.clone(); + let mut title_mem = vec![0u8; layout.size as usize]; + fill_linear_rgba(&layout, &mut title_mem, [0x11, 0x22, 0x33, 0xff]); + let staging = create_staging( + &host, + std::ptr::null(), + &copy.texture, + layout, + title_mem.as_ptr(), + ) + .expect("create staging"); + let (source, source_tex) = make_rgba_texture(&host, 4, 4); + let source_layout = source_tex.planes[0].layout.clone(); + let mut source_mem = vec![0u8; source_layout.size as usize]; + let gpu_pixel = [0x44, 0x55, 0x66, 0xff]; + fill_linear_rgba(&source_layout, &mut source_mem, gpu_pixel); + let source_staging = create_staging( + &host, + std::ptr::null(), + &source.texture, + source_layout, + source_mem.as_ptr(), + ) + .expect("create source staging"); + let writer = host.new_list().expect("writer"); + writer.defer_texture(source_staging, source.clone()); + writer.expect_texture_state(&source, D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32); + writer.expect_texture_state(&copy, D3D12_RESOURCE_STATE_COPY_DEST.0 as u32); + writer.defer_texture_write(copy.clone()); + // SAFETY: compatible textures, with the source and destination + // states established by the prelude. + unsafe { writer.list.CopyResource(&copy.texture, &source.texture) }; + writer.close(); + let reader = host.new_list().expect("reader"); + reader.defer_texture(staging.clone(), copy.clone()); + reader.expect_texture_state(&copy, SHADER_RESOURCE); + reader.close(); + + host.execute(&[&writer, &reader]); + + assert_eq!(staging.gpu_uploads(), 0, "the host write takes precedence"); + assert!(all_pixels_eq(&read_back_rgba(&host, &copy, 4, 4), gpu_pixel)); } } ~~~ </details>
Author
Owner

@⁠aycow on GitHub · 2026-11-24 18:54 UTC · original

The bindless refresh composition now retains pending #413 requests through discard/reorder/reset and delegates the native upload decision to your ordered prelude. All 42 ordinary/placed cases passed AMD/NVIDIA/WARP full GBV, including preservation of a #230-marked GPU producer. Production hunk eba699d is isolated for your and the #413 author's review. The validation extends only to GPU producers this composition marks through the existing copy/resolve path.

**@⁠aycow** on GitHub · 2026-11-24 18:54 UTC · [original](https://github.com/Marvisak/VIctory/pull/230#issuecomment-7141313882) The [bindless refresh composition](https://github.com/aycow/VIctory/blob/23af5ea/docs/direct-texture-upload-ownership.md) now retains pending #413 requests through discard/reorder/reset and delegates the native upload decision to your ordered prelude. All 42 ordinary/placed cases passed AMD/NVIDIA/WARP full GBV, including preservation of a #230-marked GPU producer. Production hunk eba699d is isolated for your and the #413 author's review. The validation extends only to GPU producers this composition marks through the existing copy/resolve path.
Author
Owner

@⁠wbkepler on GitHub · 2026-11-24 20:42 UTC · original

Rebased onto current main (ffe310e) as 067ece6; one trivial comment-only conflict in a host.rs test, and every texture-writing copy/resolve path (CopyResource, CopyTextureRegion, Resolve) still marks the texture host-written at submission time. Gate clean.

AI-assisted (Claude Code); checked on Windows 11 / RTX 5090.

**@⁠wbkepler** on GitHub · 2026-11-24 20:42 UTC · [original](https://github.com/Marvisak/VIctory/pull/230#issuecomment-7143944930) Rebased onto current main (`ffe310e`) as `067ece6`; one trivial comment-only conflict in a host.rs test, and every texture-writing copy/resolve path (CopyResource, CopyTextureRegion, Resolve) still marks the texture host-written at submission time. Gate clean. _AI-assisted (Claude Code); checked on Windows 11 / RTX 5090._
Author
Owner

@⁠Marvisak on GitHub · 2026-11-25 00:22 UTC · original

Automated triage for the maintainers.

Needs rebase. This PR does not merge cleanly into current main (ac2525d). Conflicting files: crates/victory-gpu/src/host.rs, crates/victory-gpu/src/resource.rs, crates/victory-gpu/src/texture.rs.

The content has not been reviewed yet; it will be once the branch is rebased onto main.


Generated by Claude Code

**@⁠Marvisak** on GitHub · 2026-11-25 00:22 UTC · [original](https://github.com/Marvisak/VIctory/pull/230#issuecomment-7148433980) <!-- victory-triage v1 head=067ece6b119459d3085b8208a5c8cbd4514ce7e8 verdict=needs-rebase at=2026-11-25T00:13:20Z --> Automated triage for the maintainers. **Needs rebase.** This PR does not merge cleanly into current `main` (ac2525d). Conflicting files: `crates/victory-gpu/src/host.rs`, `crates/victory-gpu/src/resource.rs`, `crates/victory-gpu/src/texture.rs`. The content has not been reviewed yet; it will be once the branch is rebased onto `main`. --- _Generated by [Claude Code](https://claude.ai/code)_
Author
Owner

@⁠andrewpozdnakov7-jpg on GitHub · 2026-11-25 01:03 UTC · original

Independent WARP confirmation for the submission-order fix, related to #1891. I recorded a CopyResource that snapshots a 4×4 RGBA8 texture and a second list that overwrites it. I tried both recording orders and both submission orders through VIctory, then read all 16 texels of the snapshot.

Upstream 42363ab6cd and your prelude-only parent fbec4e2c6a both gave 16/16 when the two orders agreed and 0/16 in each reversed case. One reversed case read the old CPU color after the submitted copy. The other read zero when the snapshot was submitted first. Your 067ece6b11 gave 16/16 in all four cases.

The regression is one test commit directly on 067ece6. Strict GPU Clippy and asset policy passed. The full WARP run had 57 passed, 1 failed, 1 ignored. The existing write-watch test failed with the new test both enabled and filtered out, and passed on its own. The merge with current main still conflicts in host.rs, resource.rs and texture.rs.

**@⁠andrewpozdnakov7-jpg** on GitHub · 2026-11-25 01:03 UTC · [original](https://github.com/Marvisak/VIctory/pull/230#issuecomment-7149168691) Independent WARP confirmation for the submission-order fix, related to #1891. I recorded a CopyResource that snapshots a 4×4 RGBA8 texture and a second list that overwrites it. I tried both recording orders and both submission orders through VIctory, then read all 16 texels of the snapshot. Upstream 42363ab6cd5265f0fb3b500ad265f2b84c6b5dbf and your prelude-only parent fbec4e2c6ae3f19c07f3aa0d9acc3a68c2556ccd both gave 16/16 when the two orders agreed and 0/16 in each reversed case. One reversed case read the old CPU color after the submitted copy. The other read zero when the snapshot was submitted first. Your 067ece6b119459d3085b8208a5c8cbd4514ce7e8 gave 16/16 in all four cases. [The regression](https://github.com/andrewpozdnakov7-jpg/VIctory/commit/52cc201418a76411dc9b8bcd993bfc43e97be785) is one test commit directly on 067ece6. Strict GPU Clippy and asset policy passed. The full WARP run had 57 passed, 1 failed, 1 ignored. The existing write-watch test failed with the new test both enabled and filtered out, and passed on its own. The merge with current main still conflicts in host.rs, resource.rs and texture.rs.
Author
Owner

@⁠Calvix2k on GitHub · 2026-11-25 02:22 UTC · original

Independent confirmation of the fix on a third vendor, on your exact head 067ece6 (no rebase), Windows 10 19045, RX 7800 XT (RDNA3), driver 32.0.32029.2010.

list::tests::texture_copy_reads_follow_submission_order from @⁠andrewpozdnakov7-jpg's 52cc201, applied verbatim to this branch, cargo test -p victory-gpu --features diagnostics --lib:

  • main 940d32f: FAILED — the two opposite record/submit orders read 0/16 pixels, matching orders 16/16.
  • this branch 067ece6: 1 passed, all four orders read 16/16; the class's other 58 tests filter out normally.

So the upload-decision-at-recording-order dependency reproduces on WARP, Blackwell, Ada and RDNA3 here, and prelude recording plus the deferred host_written mark fixes it on all four.

One thing if you rebase: on main the conflicts are real, not just context — host.rs grew the prelude/barrier paths and texture.rs's upload path changed since ffe310e, so git cherry-pick leaves 14 hunks in those two files. Happy to help work through them here, or to test a rebased branch on this GPU; the regression test above is the check I would use.

**@⁠Calvix2k** on GitHub · 2026-11-25 02:22 UTC · [original](https://github.com/Marvisak/VIctory/pull/230#issuecomment-7150646576) Independent confirmation of the fix on a third vendor, on your exact head `067ece6` (no rebase), Windows 10 19045, **RX 7800 XT (RDNA3)**, driver 32.0.32029.2010. `list::tests::texture_copy_reads_follow_submission_order` from @⁠andrewpozdnakov7-jpg's `52cc201`, applied verbatim to this branch, `cargo test -p victory-gpu --features diagnostics --lib`: - **main `940d32f`**: FAILED — the two opposite record/submit orders read 0/16 pixels, matching orders 16/16. - **this branch `067ece6`**: **1 passed**, all four orders read 16/16; the class's other 58 tests filter out normally. So the upload-decision-at-recording-order dependency reproduces on WARP, Blackwell, Ada and RDNA3 here, and prelude recording plus the deferred `host_written` mark fixes it on all four. One thing if you rebase: on `main` the conflicts are real, not just context — `host.rs` grew the prelude/barrier paths and `texture.rs`'s upload path changed since `ffe310e`, so `git cherry-pick` leaves 14 hunks in those two files. Happy to help work through them here, or to test a rebased branch on this GPU; the regression test above is the check I would use.
Author
Owner

@⁠andrewpozdnakov7-jpg on GitHub · 2026-11-25 08:13 UTC · original

I prepared a rebased branch on current main for #230 and #1891. The base is 940d32f69b22265690a0b5a15d6ded572ba33baf. The two rebased code commits are 0794859 and b5dffe8, with the original Git author preserved. The submission-order regression is a separate commit. The prior version on 067ece6 remains available.

The same native WARP test reads all 16 texels from the snapshot. Current main gets 16/16 when recording and submission order match, and 0/16 in both reversed cases. The rebased branch reads 16/16 in all four orders. Full GPU suite with diagnostics went from 146 passed / 1 failed / 2 ignored to 151 passed / 0 failed / 2 ignored, including the four prelude tests. Strict GPU Clippy in both configurations, strict workspace Clippy with all features, and the asset policy passed.

The rebase keeps current main's shared host texture, staging bounds, write tracking, and depth-twin prelude. It defers host-write marks for copy, resolve, and alias-copy destinations.

If you include the test, please preserve its Git author. If you fold it into another commit, please add:

Co-authored-by: andrewpozdnakov7-jpg [email protected]

**@⁠andrewpozdnakov7-jpg** on GitHub · 2026-11-25 08:13 UTC · [original](https://github.com/Marvisak/VIctory/pull/230#issuecomment-7156767790) I prepared a [rebased branch on current main](https://github.com/andrewpozdnakov7-jpg/VIctory/tree/rebase/230-texture-upload-order) for #230 and #1891. The base is `940d32f69b22265690a0b5a15d6ded572ba33baf`. The two rebased code commits are `0794859` and `b5dffe8`, with the original Git author preserved. The [submission-order regression](https://github.com/andrewpozdnakov7-jpg/VIctory/commit/3f363a6b6b8157246d1657f431bf25345ecbd452) is a separate commit. The prior version on `067ece6` remains available. The same native WARP test reads all 16 texels from the snapshot. Current main gets 16/16 when recording and submission order match, and 0/16 in both reversed cases. The rebased branch reads 16/16 in all four orders. Full GPU suite with diagnostics went from 146 passed / 1 failed / 2 ignored to 151 passed / 0 failed / 2 ignored, including the four prelude tests. Strict GPU Clippy in both configurations, strict workspace Clippy with all features, and the asset policy passed. The rebase keeps current main's shared host texture, staging bounds, write tracking, and depth-twin prelude. It defers host-write marks for copy, resolve, and alias-copy destinations. If you include the test, please preserve its Git author. If you fold it into another commit, please add: Co-authored-by: andrewpozdnakov7-jpg <[email protected]>
Author
Owner

@⁠Slay326 on GitHub · 2026-11-25 14:13 UTC · original

A data point from an RTX 3070 (8 GB) in case it helps this PR along. On our local test branch (main 940d32f plus #1962 and the memory PRs #2129, #2180, #1873, #1969, #2161) we use an equivalent of this change: a list copies a texture's staging buffer only after its memory changed (about 3,000 texture copies per frame before, 22 ms of GPU time).

On top of that we let a staging buffer go once a submitted list has copied it and its memory has not been detiled for 3 s; the next detiling makes it again. That only works when lists stop copying unchanged buffers, which is what this PR does. In a 480 s world run of Grand Theft Auto VI, staging memory stays at 14-36 MB instead of 3.3 GB and growing. The patch builds on this PR's behaviour and has a synthetic test; I can open it as a follow-up once this lands, or share the branch if that is easier.

AI-assisted.

**@⁠Slay326** on GitHub · 2026-11-25 14:13 UTC · [original](https://github.com/Marvisak/VIctory/pull/230#issuecomment-7164940814) A data point from an RTX 3070 (8 GB) in case it helps this PR along. On our local test branch (main 940d32f plus #1962 and the memory PRs #2129, #2180, #1873, #1969, #2161) we use an equivalent of this change: a list copies a texture's staging buffer only after its memory changed (about 3,000 texture copies per frame before, 22 ms of GPU time). On top of that we let a staging buffer go once a submitted list has copied it and its memory has not been detiled for 3 s; the next detiling makes it again. That only works when lists stop copying unchanged buffers, which is what this PR does. In a 480 s world run of Grand Theft Auto VI, staging memory stays at 14-36 MB instead of 3.3 GB and growing. The patch builds on this PR's behaviour and has a synthetic test; I can open it as a follow-up once this lands, or share the branch if that is easier. AI-assisted.
Author
Owner

@⁠assttro on GitHub · 2026-11-26 13:02 UTC · original

A third ordering case that #230 and #1934 don't cover: two CPU versions of one texture in one submission

While testing #230 (as rebased in andrewpozdnakov7-jpg/VIctory@rebase/230-texture-upload-order, head 3f363a6), I hit a case that the record-order fixes don't reach.

The case. One ExecuteCommandLists([A, W, B]):

  • A samples title texture T;
  • W CPU-writes T's memory (a deferred copy at submission);
  • B samples T again.

A should see the old bytes and B the new ones. Every prelude is prepared before the GPU runs anything, and #230 (and #1934, as far as I can read it) keeps one persistently mapped Staging buffer per texture. So B's refresh detiles the new bytes into the same buffer that A's prelude copy still references, and A reads the new data.

Result on 3f363a6 alone: 16 of 16 pixels wrong for A's read (RTX 3070, driver 610.88).

Fix (small, on top of #230): the Batch in Host::execute tracks which staging buffers a GPU copy in this submission already references (uploaded_textures).

  • The first dirty version still uses the mapped buffer.
  • A later dirty version of the same texture in the same submission is detiled into a fresh upload buffer.
  • The Batch holds those buffers (upload_buffers) until after the fence wait.
  • texture::upload_changed (the bindless path) goes through the same Batch::refresh_texture, so the ordinary and heap-indexed paths share the tracking.
  • Clean checks allocate nothing. A failed allocation goes to host::fail, so the version identity never advances silently.

Tests (release + diagnostics, RTX 3070, all with zero-mismatch readback):

  • texture_upload_keeps_each_lists_cpu_generation: the [A, W, B] case. Pass. It failed with 16 of 16 pixels wrong before the fix.
  • bindless_upload_keeps_each_generation_in_one_batch: the same case through upload_changed. Pass.
    • Its negative control (one Batch per call, i.e. the old behaviour) loses all 16 of 16 early pixels.
  • Restated from aycow's docs/direct-texture-upload-ownership.md:
    • bindless_upload_preserves_an_earlier_submitted_gpu_producer: Pass.
    • bindless_rebind_retires_the_upload_for_the_old_native_texture: Pass.
    • bindless_alias_delivers_one_upload_per_submission: two placed aliases of one memory, three views, one copy per submission. Pass.
  • Existing #230 tests: all still pass (texture_copy_reads_follow_submission_order, discarded_copy_list_still_uploads_cpu_texture, warp_*).
  • Debug layer: with VICTORY_D3D12_DEBUG=1, none of these tests logs a validation error. There's a positive-control test that proves the check is live.

I can share the patch (against 3f363a6) or open it as a PR to the rebase branch, whichever is easier for whoever lands #230. Happy to rebase it onto current main once #230 or #1934 is settled.

AI-assisted (Claude); results above are from my own runs.

**@⁠assttro** on GitHub · 2026-11-26 13:02 UTC · [original](https://github.com/Marvisak/VIctory/pull/230#issuecomment-7192796686) **A third ordering case that #230 and #1934 don't cover: two CPU versions of one texture in one submission** While testing #230 (as rebased in `andrewpozdnakov7-jpg/VIctory@rebase/230-texture-upload-order`, head 3f363a6), I hit a case that the record-order fixes don't reach. **The case.** One `ExecuteCommandLists([A, W, B])`: - A samples title texture T; - W CPU-writes T's memory (a deferred copy at submission); - B samples T again. A should see the old bytes and B the new ones. Every prelude is prepared before the GPU runs anything, and #230 (and #1934, as far as I can read it) keeps one persistently mapped `Staging` buffer per texture. So B's refresh detiles the new bytes into the same buffer that A's prelude copy still references, and A reads the new data. **Result on 3f363a6 alone:** 16 of 16 pixels wrong for A's read (RTX 3070, driver 610.88). **Fix (small, on top of #230):** the `Batch` in `Host::execute` tracks which staging buffers a GPU copy in this submission already references (`uploaded_textures`). - The first dirty version still uses the mapped buffer. - A later dirty version of the same texture in the same submission is detiled into a fresh upload buffer. - The `Batch` holds those buffers (`upload_buffers`) until after the fence wait. - `texture::upload_changed` (the bindless path) goes through the same `Batch::refresh_texture`, so the ordinary and heap-indexed paths share the tracking. - Clean checks allocate nothing. A failed allocation goes to `host::fail`, so the version identity never advances silently. **Tests** (release + diagnostics, RTX 3070, all with zero-mismatch readback): - `texture_upload_keeps_each_lists_cpu_generation`: the [A, W, B] case. Pass. It failed with 16 of 16 pixels wrong before the fix. - `bindless_upload_keeps_each_generation_in_one_batch`: the same case through `upload_changed`. Pass. - Its negative control (one `Batch` per call, i.e. the old behaviour) loses all 16 of 16 early pixels. - **Restated from aycow's `docs/direct-texture-upload-ownership.md`:** - `bindless_upload_preserves_an_earlier_submitted_gpu_producer`: Pass. - `bindless_rebind_retires_the_upload_for_the_old_native_texture`: Pass. - `bindless_alias_delivers_one_upload_per_submission`: two placed aliases of one memory, three views, one copy per submission. Pass. - **Existing #230 tests:** all still pass (`texture_copy_reads_follow_submission_order`, `discarded_copy_list_still_uploads_cpu_texture`, `warp_*`). - **Debug layer:** with `VICTORY_D3D12_DEBUG=1`, none of these tests logs a validation error. There's a positive-control test that proves the check is live. I can share the patch (against 3f363a6) or open it as a PR to the rebase branch, whichever is easier for whoever lands #230. Happy to rebase it onto current `main` once #230 or #1934 is settled. *AI-assisted (Claude); results above are from my own runs.*
Author
Owner

@⁠andrewpozdnakov7-jpg on GitHub · 2026-11-26 15:10 UTC · original

@⁠assttro Yes, please share the batch fix as a branch or commit on 3f363a6. Could you include both regressions, texture_upload_keeps_each_lists_cpu_generation and bindless_upload_keeps_each_generation_in_one_batch?

I'll run the same tests before and after the patch on app-local WARP, including both readbacks in ExecuteCommandLists([A, W, B]), and keep your Git authorship when applying it.

**@⁠andrewpozdnakov7-jpg** on GitHub · 2026-11-26 15:10 UTC · [original](https://github.com/Marvisak/VIctory/pull/230#issuecomment-7195895048) @⁠assttro Yes, please share the batch fix as a branch or commit on [`3f363a6`](https://github.com/andrewpozdnakov7-jpg/VIctory/commit/3f363a6b6b8157246d1657f431bf25345ecbd452). Could you include both regressions, `texture_upload_keeps_each_lists_cpu_generation` and `bindless_upload_keeps_each_generation_in_one_batch`? I'll run the same tests before and after the patch on app-local WARP, including both readbacks in `ExecuteCommandLists([A, W, B])`, and keep your Git authorship when applying it.
Author
Owner

@⁠andrewpozdnakov7-jpg on GitHub · 2026-11-26 17:23 UTC · original

I independently reproduced the [A, W, B] case with a test-only probe on 3f363a6. A and B sample the same 4x4 texture into separate buffers, and the middle list performs a deferred CPU copy from red to green. All three lists are submitted together. Three app-local Agility 1.620.2/WARP 1.0.22 runs on each revision gave the same result for watched and untracked memory.

Revision A, before CPU copy B, after CPU copy Next submission
63bcca43 16/16 red 16/16 red 16/16 green
3f363a6 16/16 green 16/16 green 16/16 green
Expected per-list ordering red green green

The rebase reproduces your early overwrite. On current main the later list sees stale bytes until the next submission, consistent with its single initial upload pass. This probe is an independent ordinary descriptor-table check. Your patch and both proposed tests are still the next step, especially for the heap-indexed path. If you reuse the probe, please retain its Git author on cherry-pick or add Co-authored-by: andrewpozdnakov7-jpg <[email protected]> if folding it into another commit. AI-assisted with Codex.

**@⁠andrewpozdnakov7-jpg** on GitHub · 2026-11-26 17:23 UTC · [original](https://github.com/Marvisak/VIctory/pull/230#issuecomment-7198932954) I independently reproduced the `[A, W, B]` case with a [test-only probe on `3f363a6`](https://github.com/andrewpozdnakov7-jpg/VIctory/commit/452e73bd7571677f52658c3cd1e074e5b6d10ac6). `A` and `B` sample the same 4x4 texture into separate buffers, and the middle list performs a deferred CPU copy from red to green. All three lists are submitted together. Three app-local Agility 1.620.2/WARP 1.0.22 runs on each revision gave the same result for watched and untracked memory. | Revision | A, before CPU copy | B, after CPU copy | Next submission | | --- | --- | --- | --- | | `63bcca43` | 16/16 red | 16/16 red | 16/16 green | | `3f363a6` | 16/16 green | 16/16 green | 16/16 green | | Expected per-list ordering | red | green | green | The rebase reproduces your early overwrite. On current main the later list sees stale bytes until the next submission, consistent with its single initial upload pass. This probe is an independent ordinary descriptor-table check. Your patch and both proposed tests are still the next step, especially for the heap-indexed path. If you reuse the probe, please retain its Git author on cherry-pick or add `Co-authored-by: andrewpozdnakov7-jpg <[email protected]>` if folding it into another commit. AI-assisted with Codex.
This pull request has changes conflicting with the target branch.
  • crates/victory-gpu/src/host.rs
  • crates/victory-gpu/src/list.rs
  • crates/victory-gpu/src/resource.rs
  • crates/victory-gpu/src/texture.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/230/head:github-bot/gh-230'
git switch 'github-bot/gh-230'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-230'
git switch 'github-bot/gh-230'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-230'
git switch 'github-bot/gh-230'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-230'
git switch 'main'
git merge --squash 'github-bot/gh-230'
git switch 'main'
git merge --ff-only 'github-bot/gh-230'
git switch 'main'
git merge 'github-bot/gh-230'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No reviewers
No milestone
No assignees
1 participant
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
github/Marvisak--VIctory!230
No description provided.