GPU: flush only overlapping shadow refreshes before Step::GpuWrite #1472

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

@⁠Sakura-Byte on GitHub · 2026-11-24 18:17 UTC · original
Sakura-Byte:pr/scope-gpu-write-flush → main · +122 −8 · 1 files · 1 commits · open

Summary

  • Previously, HostList::run_deferred called batch.flush() on every Step::GpuWrite(shadow, address, len), draining pending Step::Refresh entries for all shadow buffers in the submission whenever shaders declared a write to any single buffer range.
  • Extracted Batch::flush_one (shared with Batch::flush) and added Batch::flush_gpu_write(shadow, address, len) in crates/victory-gpu/src/host.rs:
    • len == 0 returns without flushing.
    • Otherwise flushes only pending refreshes of shadow whose queued [from, to) range overlaps [address, address.saturating_add(len)) before shadow.writing(address, len) snapshots title bytes.
    • Unrelated Shadow buffers and disjoint ranges on shadow stay queued in Batch::refreshes so subsequent Step::Refresh steps across the submission keep coalescing instead of flushing prematurely.
  • Added synthetic WARP/D3D12 test host::batch::gpu_write_flushes_only_overlapping_shadow_refreshes verifying zero-length/disjoint no-ops, immediate flushing of overlapping same-shadow refreshes before Shadow::writing, and continued coalescing of unrelated shadows across Step::GpuWrite.

Verification

Ran cleanly on clean origin/main (ffe310e) with Cargo.lock untouched:

  • cargo xtask policy: asset policy: 154 files ok
  • cargo clippy --workspace --all-targets --locked -- -D warnings: passed (0 warnings)
  • cargo clippy --workspace --all-targets --all-features --locked -- -D warnings: passed (0 warnings)
  • VICTORY_D3D12_WARP=1 VICTORY_WARP=1 VICTORY_D3D12_DEBUG=1 cargo test -p victory-gpu --features diagnostics --locked host::batch -- --test-threads=1: 3 passed; 0 failed; 1 ignored (texture_checks_per_submission benchmark ignored)
  • VICTORY_D3D12_WARP=1 VICTORY_WARP=1 VICTORY_D3D12_DEBUG=1 cargo test -p victory-gpu --features diagnostics --locked -- --test-threads=1: 54 passed; 0 failed; 1 ignored (only the existing host::batch::texture_checks_per_submission benchmark ignored)

AI-assisted; synthetic tests only, zero game assets.

**@⁠Sakura-Byte** on GitHub · 2026-11-24 18:17 UTC · [original](https://github.com/Marvisak/VIctory/pull/1472) `Sakura-Byte:pr/scope-gpu-write-flush` → `main` · +122 −8 · 1 files · 1 commits · open ### Summary - Previously, `HostList::run_deferred` called `batch.flush()` on every `Step::GpuWrite(shadow, address, len)`, draining pending `Step::Refresh` entries for **all** shadow buffers in the submission whenever shaders declared a write to any single buffer range. - Extracted `Batch::flush_one` (shared with `Batch::flush`) and added `Batch::flush_gpu_write(shadow, address, len)` in `crates/victory-gpu/src/host.rs`: - `len == 0` returns without flushing. - Otherwise flushes only pending refreshes of `shadow` whose queued `[from, to)` range overlaps `[address, address.saturating_add(len))` before `shadow.writing(address, len)` snapshots title bytes. - Unrelated `Shadow` buffers and disjoint ranges on `shadow` stay queued in `Batch::refreshes` so subsequent `Step::Refresh` steps across the submission keep coalescing instead of flushing prematurely. - Added synthetic WARP/D3D12 test `host::batch::gpu_write_flushes_only_overlapping_shadow_refreshes` verifying zero-length/disjoint no-ops, immediate flushing of overlapping same-shadow refreshes before `Shadow::writing`, and continued coalescing of unrelated shadows across `Step::GpuWrite`. ### Verification Ran cleanly on clean `origin/main` (`ffe310e`) with `Cargo.lock` untouched: - `cargo xtask policy`: `asset policy: 154 files ok` - `cargo clippy --workspace --all-targets --locked -- -D warnings`: passed (0 warnings) - `cargo clippy --workspace --all-targets --all-features --locked -- -D warnings`: passed (0 warnings) - `VICTORY_D3D12_WARP=1 VICTORY_WARP=1 VICTORY_D3D12_DEBUG=1 cargo test -p victory-gpu --features diagnostics --locked host::batch -- --test-threads=1`: `3 passed; 0 failed; 1 ignored` (`texture_checks_per_submission` benchmark ignored) - `VICTORY_D3D12_WARP=1 VICTORY_WARP=1 VICTORY_D3D12_DEBUG=1 cargo test -p victory-gpu --features diagnostics --locked -- --test-threads=1`: `54 passed; 0 failed; 1 ignored` (only the existing `host::batch::texture_checks_per_submission` benchmark ignored) *AI-assisted; synthetic tests only, zero game assets.*
Previously Step::GpuWrite called batch.flush(), flushing pending refreshes for every shadow buffer across the submission whenever any single range became GPU-written.

Add Batch::flush_gpu_write (sharing flush_one with Batch::flush) so Step::GpuWrite flushes only pending refreshes on the target shadow whose queued range overlaps [address, address + len), keeping disjoint ranges and unrelated shadows queued to continue coalescing.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 04:33:04 +00:00
Author
Owner

@⁠0xKaji on GitHub · 2026-11-24 19:52 UTC · original

Tested c00db2c on Linux + Wine 11.22 + vkd3d-proton 3.2.0 + NVIDIA RTX 3060 8 GB (cross-built with cargo xwin): clippy -p victory-gpu --tests -D warnings is clean and gpu_write_flushes_only_overlapping_shadow_refreshes passes. But there's a regression in how flush_gpu_write interacts with the bounding-box snapshot in Shadow::writing, and I've reproduced it with a unit test.

What goes wrong

Shadow::writing keeps one snapshot per copy and submission, [min(at, from), max(at + len, to)), and fills any gap between declared ranges from the copy (self.data). On main, every Step::GpuWrite runs batch.flush() first, so the gap bytes already include every queued refresh. With this PR, only refreshes that overlap the declared bytes get flushed. A queued refresh of the same Shadow that sits in the gap gets snapshotted with its pre-refresh bytes:

  1. GpuWrite(s, 0, 256): snapshot [0, 256)
  2. Refresh(s, PAGE, 256): queued
  3. GpuWrite(s, 2*PAGE, 256): disjoint, so the refresh stays queued, and the snapshot grows to [0, 2*PAGE+256) with stale bytes at PAGE
  4. GpuWrite(s, PAGE, 256): the refresh is flushed now, but writing returns early (the range is already inside the box), so the snapshot keeps the stale bytes
  5. After the submission, copy_back(PAGE, 256) sees copy != snapshot and treats the refreshed title bytes as GPU-written. Any title write made to that range in the meantime gets overwritten with the older bytes. This is the scenario the copy_back doc comment warns about (title records broken by old bytes being put back).

The PR's own test steps into the same state: the zero-length GpuWrite(addr_a, 0) leaves before = Some((0, [])), so the next GpuWrite(addr_a + PAGE, 256) grows the snapshot over the still-queued [0, 256) refresh. That test passes only because title memory doesn't change between the refresh and copy_back.

Repro (GPU test, NVIDIA + vkd3d-proton 3.2.0)

build disjoint_refresh_is_in_the_snapshot_a_later_gpu_write_covers
main (ffe310e) pass
this PR (c00db2c) fail: copy_back treated refreshed bytes as GPU-written (left: 256, right: 0)
PR + suggested fix below pass
Test (for mod batch in host.rs)
/// A refresh left queued across a disjoint `Step::GpuWrite` on the same
/// copy must still be in the copy before `Shadow::writing` grows the
/// snapshot over it; otherwise a later declared range over it compares
/// against pre-refresh bytes and puts stale title bytes back.
#[test]
fn disjoint_refresh_is_in_the_snapshot_a_later_gpu_write_covers() {
    use crate::watch::PAGE;

    let Some(host) = super::host() else {
        return;
    };
    let mut mem = vec![0u8; 3 * PAGE];
    let addr = mem.as_ptr() as u64;
    let res = addr as usize ^ 0x5500_0003;
    crate::shadow::register(res, addr, (3 * PAGE) as u64);
    let shadow = crate::shadow::find(addr, (3 * PAGE) as u64).expect("shadow");
    // The copy starts in step with title memory (all zero) ...
    shadow.update(addr as usize, 3 * PAGE);
    // ... then the title writes the middle page; a refresh brings it over.
    mem[PAGE..PAGE + 256].fill(0x11);

    let list = host.new_list().unwrap();
    shadow.gpu_writes(&list, addr, 256);
    shadow.refresh(&list, addr + PAGE as u64, 256);
    shadow.gpu_writes(&list, addr + 2 * PAGE as u64, 256);
    shadow.gpu_writes(&list, addr + PAGE as u64, 256);
    list.close();
    let mut batch = Batch::default();
    list.run_deferred(&mut batch);
    batch.flush();

    // The GPU wrote nothing; the title's thread writes the page meanwhile.
    mem[PAGE..PAGE + 256].fill(0x22);
    let written = shadow.copy_back(addr as usize + PAGE, 256);
    let after = mem[PAGE..PAGE + 256].to_vec();
    shadow.copy_back(addr as usize, 256);
    shadow.copy_back(addr as usize + 2 * PAGE, 256);
    drop(shadow);
    crate::shadow::unregister(res, addr);
    assert_eq!(written, 0, "copy_back treated refreshed bytes as GPU-written");
    assert_eq!(after, vec![0x22u8; 256], "title write overwritten by stale bytes");
}

Suggested fix

Flush the same-Shadow refreshes that overlap the range the snapshot will cover after writing, not just the declared bytes. This also covers the len == 0 case, which can still grow an existing snapshot. Other Shadows stay queued, so the cross-buffer coalescing this PR is after is kept:

// shadow.rs
/// The title addresses the snapshot covers once `writing(address, len)`
/// has grown it (empty when nothing is kept and `len` is zero).
pub(crate) fn snapshot_after(&self, address: usize, len: usize) -> (usize, usize) {
    let (from, to) = self.inside(address, len);
    let (low, high) = match &*self.before.lock().unwrap_or_else(|e| e.into_inner()) {
        Some((at, bytes)) => ((*at).min(from), (at + bytes.len()).max(to)),
        None => (from, to),
    };
    (self.start as usize + low, self.start as usize + high)
}
// host.rs, Batch::flush_gpu_write (replaces the `len == 0` early return and the byte-range test)
let (low, high) = shadow.snapshot_after(address, len);
// ...
if std::sync::Arc::ptr_eq(s, shadow) && *from < high && *to > low {

With this, the repro passes and clippy -D warnings stays clean. As expected, the first assertion of gpu_write_flushes_only_overlapping_shadow_refreshes (batch.refreshes.len() == 1 after the zero-length and disjoint writes on shadow_a) now fails, because that queued shadow_a refresh is exactly the one the grown snapshot covers. That test would need shadow_a's disjoint write to be the first range of the submission (or to drop the zero-length write in front of it) to keep checking the coalescing it's meant to check.

**@⁠0xKaji** on GitHub · 2026-11-24 19:52 UTC · [original](https://github.com/Marvisak/VIctory/pull/1472#issuecomment-7142712654) Tested `c00db2c` on Linux + Wine `11.22` + `vkd3d-proton 3.2.0` + NVIDIA RTX 3060 8 GB (cross-built with `cargo xwin`): `clippy -p victory-gpu --tests -D warnings` is clean and `gpu_write_flushes_only_overlapping_shadow_refreshes` passes. But there's a regression in how `flush_gpu_write` interacts with the bounding-box snapshot in `Shadow::writing`, and I've reproduced it with a unit test. ### What goes wrong `Shadow::writing` keeps **one** snapshot per copy and submission, `[min(at, from), max(at + len, to))`, and fills any gap between declared ranges from the copy (`self.data`). On `main`, every `Step::GpuWrite` runs `batch.flush()` first, so the gap bytes already include every queued refresh. With this PR, only refreshes that overlap the *declared* bytes get flushed. A queued refresh of the **same** `Shadow` that sits in the gap gets snapshotted with its **pre-refresh** bytes: 1. `GpuWrite(s, 0, 256)`: snapshot `[0, 256)` 2. `Refresh(s, PAGE, 256)`: queued 3. `GpuWrite(s, 2*PAGE, 256)`: disjoint, so the refresh stays queued, and the snapshot grows to `[0, 2*PAGE+256)` with stale bytes at `PAGE` 4. `GpuWrite(s, PAGE, 256)`: the refresh is flushed now, but `writing` returns early (the range is already inside the box), so the snapshot keeps the stale bytes 5. After the submission, `copy_back(PAGE, 256)` sees `copy != snapshot` and treats the refreshed title bytes as GPU-written. Any title write made to that range in the meantime gets overwritten with the older bytes. This is the scenario the `copy_back` doc comment warns about (title records broken by old bytes being put back). The PR's own test steps into the same state: the zero-length `GpuWrite(addr_a, 0)` leaves `before = Some((0, []))`, so the next `GpuWrite(addr_a + PAGE, 256)` grows the snapshot over the still-queued `[0, 256)` refresh. That test passes only because title memory doesn't change between the refresh and `copy_back`. ### Repro (GPU test, NVIDIA + `vkd3d-proton 3.2.0`) | build | `disjoint_refresh_is_in_the_snapshot_a_later_gpu_write_covers` | |---|---| | `main` (`ffe310e`) | **pass** | | this PR (`c00db2c`) | **fail**: `copy_back treated refreshed bytes as GPU-written` (`left: 256, right: 0`) | | PR + suggested fix below | **pass** | <details><summary>Test (for <code>mod batch</code> in <code>host.rs</code>)</summary> ```rust /// A refresh left queued across a disjoint `Step::GpuWrite` on the same /// copy must still be in the copy before `Shadow::writing` grows the /// snapshot over it; otherwise a later declared range over it compares /// against pre-refresh bytes and puts stale title bytes back. #[test] fn disjoint_refresh_is_in_the_snapshot_a_later_gpu_write_covers() { use crate::watch::PAGE; let Some(host) = super::host() else { return; }; let mut mem = vec![0u8; 3 * PAGE]; let addr = mem.as_ptr() as u64; let res = addr as usize ^ 0x5500_0003; crate::shadow::register(res, addr, (3 * PAGE) as u64); let shadow = crate::shadow::find(addr, (3 * PAGE) as u64).expect("shadow"); // The copy starts in step with title memory (all zero) ... shadow.update(addr as usize, 3 * PAGE); // ... then the title writes the middle page; a refresh brings it over. mem[PAGE..PAGE + 256].fill(0x11); let list = host.new_list().unwrap(); shadow.gpu_writes(&list, addr, 256); shadow.refresh(&list, addr + PAGE as u64, 256); shadow.gpu_writes(&list, addr + 2 * PAGE as u64, 256); shadow.gpu_writes(&list, addr + PAGE as u64, 256); list.close(); let mut batch = Batch::default(); list.run_deferred(&mut batch); batch.flush(); // The GPU wrote nothing; the title's thread writes the page meanwhile. mem[PAGE..PAGE + 256].fill(0x22); let written = shadow.copy_back(addr as usize + PAGE, 256); let after = mem[PAGE..PAGE + 256].to_vec(); shadow.copy_back(addr as usize, 256); shadow.copy_back(addr as usize + 2 * PAGE, 256); drop(shadow); crate::shadow::unregister(res, addr); assert_eq!(written, 0, "copy_back treated refreshed bytes as GPU-written"); assert_eq!(after, vec![0x22u8; 256], "title write overwritten by stale bytes"); } ``` </details> ### Suggested fix Flush the same-`Shadow` refreshes that overlap the range the snapshot **will cover** after `writing`, not just the declared bytes. This also covers the `len == 0` case, which can still grow an existing snapshot. Other `Shadow`s stay queued, so the cross-buffer coalescing this PR is after is kept: ```rust // shadow.rs /// The title addresses the snapshot covers once `writing(address, len)` /// has grown it (empty when nothing is kept and `len` is zero). pub(crate) fn snapshot_after(&self, address: usize, len: usize) -> (usize, usize) { let (from, to) = self.inside(address, len); let (low, high) = match &*self.before.lock().unwrap_or_else(|e| e.into_inner()) { Some((at, bytes)) => ((*at).min(from), (at + bytes.len()).max(to)), None => (from, to), }; (self.start as usize + low, self.start as usize + high) } ``` ```rust // host.rs, Batch::flush_gpu_write (replaces the `len == 0` early return and the byte-range test) let (low, high) = shadow.snapshot_after(address, len); // ... if std::sync::Arc::ptr_eq(s, shadow) && *from < high && *to > low { ``` With this, the repro passes and `clippy -D warnings` stays clean. As expected, the first assertion of `gpu_write_flushes_only_overlapping_shadow_refreshes` (`batch.refreshes.len() == 1` after the zero-length and disjoint writes on `shadow_a`) now fails, because that queued `shadow_a` refresh is exactly the one the grown snapshot covers. That test would need `shadow_a`'s disjoint write to be the first range of the submission (or to drop the zero-length write in front of it) to keep checking the coalescing it's meant to check.
Author
Owner

@⁠Marvisak on GitHub · 2026-11-25 01:29 UTC · original

Automated triage for the maintainers.

Needs rebase. This pull request conflicts with main (conflicting: crates/victory-gpu/src/host.rs). It will be reviewed once it is rebased onto the current main.


Generated by Claude Code

**@⁠Marvisak** on GitHub · 2026-11-25 01:29 UTC · [original](https://github.com/Marvisak/VIctory/pull/1472#issuecomment-7149604318) <!-- victory-triage v1 head=c00db2cb38331419d5421906c49fe2282813bc7d verdict=needs-rebase at=2026-11-25T01:29:24Z --> Automated triage for the maintainers. **Needs rebase.** This pull request conflicts with `main` (conflicting: `crates/victory-gpu/src/host.rs`). It will be reviewed once it is rebased onto the current `main`. --- _Generated by [Claude Code](https://claude.ai/code)_
This pull request has changes conflicting with the target branch.
  • crates/victory-gpu/src/host.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/1472/head:github-bot/gh-1472'
git switch 'github-bot/gh-1472'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-1472'
git switch 'github-bot/gh-1472'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-1472'
git switch 'github-bot/gh-1472'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-1472'
git switch 'main'
git merge --squash 'github-bot/gh-1472'
git switch 'main'
git merge --ff-only 'github-bot/gh-1472'
git switch 'main'
git merge 'github-bot/gh-1472'
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!1472
No description provided.