GPU: deduplicate identical per-list defer_gpu_write declarations #3112

Open
fuzeofficlal wants to merge 2 commits from upstream-pr/3114 into main
fuzeofficlal commented 2026-11-26 08:29:37 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by fuzeofficlal on 2026-11-26T08:29:37Z.


Summary

HostList::defer_gpu_write previously pushed a new Step::GpuWrite into Deferred::copies on every draw or dispatch, even when the same command list repeatedly declared the exact same (shadow, address, len, marked, memory) tuple with no intervening step that writes title memory. In world command lists this appends thousands of redundant Step::GpuWrite entries per frame, repeating Arc::clone, batch.flush() / shadow.writing(...) lock acquisitions in run_deferred, and HashMap deduplication work in Host::execute.

This change mirrors the existing per-list Deferred::refreshed deduplication:

  • Track recorded declarations in Deferred::gpu_writes: HashSet<(usize, usize, usize, bool, bool)> keyed by (Arc::as_ptr(shadow) as usize, address, len, marked, memory).
    • Including both marked and memory in the key ensures that an earlier marked == true declaration never suppresses a subsequent marked == false declaration (which must flush and take a pre-submit snapshot), and an earlier memory == false declaration never suppresses a subsequent memory == true declaration (which governs withholding() on title-memory misses).
    • Because the first accepted declaration pushes Step::GpuWrite(shadow.clone(), ...) into Deferred::copies, the Arc<Shadow> stays alive until HostList::reset() replaces Deferred, so Arc::as_ptr(shadow) cannot alias another copy while in gpu_writes.
  • Add Deferred::title_written(&mut self) to clear both refreshed and gpu_writes, called by HostList::defer_copy and HostList::defer (merging defer's two self.deferred() lock acquisitions into one). HostList::reset continues to reset the entire Deferred struct.

Verification

  • Added four tests in crates/victory-gpu/src/host.rs (host::gpu_write_dedup::*):
    • identical_gpu_writes_deduplicate_until_title_written_or_reset
    • distinct_marked_and_memory_flags_are_never_collapsed
    • deduped_marked_then_unmarked_and_post_copy_writes_copy_back
    • deduped_ordinary_then_memory_write_still_withholds_on_miss
  • Hardware D3D12 (RTX 5090): cargo test -p victory-gpu --lib --locked -- host::gpu_write_dedup:: host::batch:: host::withholding:: — 6 passed, 0 failed.
  • WARP (VICTORY_D3D12_WARP=1): cargo test -p victory-gpu --locked --features diagnostics — 250 passed, 0 failed (1 existing benchmark ignored), verified across 4 consecutive parallel runs.
  • cargo clippy --workspace --all-targets --locked -- -D warnings and --all-features: 0 warnings.
  • cargo test -p xtask --locked policy::tests::repository_passes_policy: passed.
<!-- greyfinch-sync:Marvisak/VIctory:issue:6622611357 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3114). Originally posted by [fuzeofficlal](https://github.com/fuzeofficlal) on 2026-11-26T08:29:37Z. --- ### Summary `HostList::defer_gpu_write` previously pushed a new `Step::GpuWrite` into `Deferred::copies` on every draw or dispatch, even when the same command list repeatedly declared the exact same `(shadow, address, len, marked, memory)` tuple with no intervening step that writes title memory. In world command lists this appends thousands of redundant `Step::GpuWrite` entries per frame, repeating `Arc::clone`, `batch.flush()` / `shadow.writing(...)` lock acquisitions in `run_deferred`, and `HashMap` deduplication work in `Host::execute`. This change mirrors the existing per-list `Deferred::refreshed` deduplication: - Track recorded declarations in `Deferred::gpu_writes: HashSet<(usize, usize, usize, bool, bool)>` keyed by `(Arc::as_ptr(shadow) as usize, address, len, marked, memory)`. - Including both `marked` and `memory` in the key ensures that an earlier `marked == true` declaration never suppresses a subsequent `marked == false` declaration (which must flush and take a pre-submit snapshot), and an earlier `memory == false` declaration never suppresses a subsequent `memory == true` declaration (which governs `withholding()` on title-memory misses). - Because the first accepted declaration pushes `Step::GpuWrite(shadow.clone(), ...)` into `Deferred::copies`, the `Arc<Shadow>` stays alive until `HostList::reset()` replaces `Deferred`, so `Arc::as_ptr(shadow)` cannot alias another copy while in `gpu_writes`. - Add `Deferred::title_written(&mut self)` to clear both `refreshed` and `gpu_writes`, called by `HostList::defer_copy` and `HostList::defer` (merging `defer`'s two `self.deferred()` lock acquisitions into one). `HostList::reset` continues to reset the entire `Deferred` struct. ### Verification - Added four tests in `crates/victory-gpu/src/host.rs` (`host::gpu_write_dedup::*`): - `identical_gpu_writes_deduplicate_until_title_written_or_reset` - `distinct_marked_and_memory_flags_are_never_collapsed` - `deduped_marked_then_unmarked_and_post_copy_writes_copy_back` - `deduped_ordinary_then_memory_write_still_withholds_on_miss` - Hardware D3D12 (RTX 5090): `cargo test -p victory-gpu --lib --locked -- host::gpu_write_dedup:: host::batch:: host::withholding::` — 6 passed, 0 failed. - WARP (`VICTORY_D3D12_WARP=1`): `cargo test -p victory-gpu --locked --features diagnostics` — 250 passed, 0 failed (1 existing benchmark ignored), verified across 4 consecutive parallel runs. - `cargo clippy --workspace --all-targets --locked -- -D warnings` and `--all-features`: 0 warnings. - `cargo test -p xtask --locked policy::tests::repository_passes_policy`: passed.
Dukestar69 commented 2026-11-26 08:53:36 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Dukestar69 on 2026-11-26T08:53:36Z.

Review: APPROVED


Verified on RTX 5090 & WARP against origin/main (63bcca4):

  • cargo test -p victory-gpu --lib host::gpu_write_dedup:: -- --test-threads=1: 4/4 passed on RTX 5090 and WARP.
  • cargo test -p victory-gpu --lib shadow:: -- --test-threads=1: 10/10 passed on RTX 5090 and WARP.
  • cargo test -p victory-gpu --lib draw:: -- --test-threads=1: 20/20 passed on RTX 5090.
  • cargo clippy -p victory-gpu --all-targets -- -D warnings: clean.
  • cargo xtask policy: 191 files ok.

Cleanly deduplicates identical per-list defer_gpu_write declarations without collapsing distinct marked/memory flags or breaking post-copy/withholding semantics.

Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).

<!-- greyfinch-sync:Marvisak/VIctory:review:6071021448 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3114#pullrequestreview-6071021448). Originally posted by [Dukestar69](https://github.com/Dukestar69) on 2026-11-26T08:53:36Z. **Review:** APPROVED --- Verified on RTX 5090 & WARP against `origin/main` (`63bcca4`): - `cargo test -p victory-gpu --lib host::gpu_write_dedup:: -- --test-threads=1`: 4/4 passed on RTX 5090 and WARP. - `cargo test -p victory-gpu --lib shadow:: -- --test-threads=1`: 10/10 passed on RTX 5090 and WARP. - `cargo test -p victory-gpu --lib draw:: -- --test-threads=1`: 20/20 passed on RTX 5090. - `cargo clippy -p victory-gpu --all-targets -- -D warnings`: clean. - `cargo xtask policy`: 191 files ok. Cleanly deduplicates identical per-list `defer_gpu_write` declarations without collapsing distinct marked/memory flags or breaking post-copy/withholding semantics. Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).
Marvisak commented 2026-11-26 10:05:05 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Marvisak on 2026-11-26T09:19:59Z.


Automated triage for the maintainers.

Needs work: CI is failing. By my reading the change is right. HostList::defer_gpu_write (crates/victory-gpu/src/host.rs) skips a Step::GpuWrite that repeats an identical (shadow, address, len, marked, memory) declaration until defer_copy, defer or reset clears the set. On main, a repeated step only runs batch.flush() and Shadow::writing, and writing does nothing for a range it already holds. Dropping the repeat therefore only defers a flush that a later step does anyway. The key includes marked and memory, which keeps the snapshot and withholding behaviour. The Arc held by the first step stops the pointer key from being reused. Please fix the failing check job. Also coordinate with #3113, which adds its own Deferred::title_written: the merged helper should clear refreshed, filled and gpu_writes. With CI green this would be a merge candidate.

CI: check failing.


Generated by Claude Code

<!-- greyfinch-sync:Marvisak/VIctory:comment:7187801216 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3114#issuecomment-7187801216). Originally posted by [Marvisak](https://github.com/Marvisak) on 2026-11-26T09:19:59Z. --- <!-- victory-triage v1 head=ddcc62673e602b302521b06761baa73bf331d500 verdict=needs-work at=2026-11-26T09:21:00Z --> Automated triage for the maintainers. **Needs work: CI is failing.** By my reading the change is right. `HostList::defer_gpu_write` (`crates/victory-gpu/src/host.rs`) skips a `Step::GpuWrite` that repeats an identical `(shadow, address, len, marked, memory)` declaration until `defer_copy`, `defer` or `reset` clears the set. On `main`, a repeated step only runs `batch.flush()` and `Shadow::writing`, and `writing` does nothing for a range it already holds. Dropping the repeat therefore only defers a flush that a later step does anyway. The key includes `marked` and `memory`, which keeps the snapshot and withholding behaviour. The `Arc` held by the first step stops the pointer key from being reused. Please fix the failing `check` job. Also coordinate with #3113, which adds its own `Deferred::title_written`: the merged helper should clear `refreshed`, `filled` and `gpu_writes`. With CI green this would be a merge candidate. CI: `check` failing. --- _Generated by [Claude Code](https://claude.ai/code)_
fuzeofficlal commented 2026-11-26 12:06:00 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by fuzeofficlal on 2026-11-26T11:48:54Z.


Re-pushed identical tree (ddcc6267 -> 09cda65e) to re-trigger CI after an unrelated flaky failure in descriptor::host::tests::views_bound_while_another_slot_gets_its_texture_do_not_wait.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7191200337 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3114#issuecomment-7191200337). Originally posted by [fuzeofficlal](https://github.com/fuzeofficlal) on 2026-11-26T11:48:54Z. --- Re-pushed identical tree (`ddcc6267` -> `09cda65e`) to re-trigger CI after an unrelated flaky failure in `descriptor::host::tests::views_bound_while_another_slot_gets_its_texture_do_not_wait`.
yumaste commented 2026-11-26 15:02:27 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by yumaste on 2026-11-26T14:09:04Z.


I tested an ordering case on Windows with WARP. A repeated unmarked Step::GpuWrite can still matter as a flush boundary for a refresh queued since the preceding declaration. A later Step::Host can observe that boundary, for example when reading a shadow in diagnostics.

The fixture declares an unmarked write to A, queues a refresh of dirty B, repeats the identical write to A, and reads B in defer_host. The capture is the byte observed at that step.

Build B observed in host step B after submission
main 63bcca4 0x22 0x22
#3114 09cda65 0x11 0x22
#3114 with a pending-refresh guard 0x22 0x22

I verified a local guard that sets a flag when Refresh, Heap or Memory is recorded, and keeps the next unmarked write even when its key is already present. That recorded write clears the flag because it flushes the batch. Copy and Run also clear it through title_written. The guarded tree passed all 41 tests selected by host:: with diagnostics under WARP, including the four tests from this PR and the reproducer below. The fixture establishes the deferred-ordering difference without any title assets.

Regression test for host.rs, inside the existing test module withholding
#[test]
fn repeated_write_flushes_a_later_refresh_before_host_work() {
    use crate::watch::PAGE;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicU32, Ordering};

    let host = super::host().expect("WARP");
    let a = crate::watch::tests::pool(1);
    let b = crate::watch::tests::pool(1);
    // SAFETY: these bytes are in our allocated pools.
    unsafe { (b as *mut u8).write_volatile(0x11) };
    for address in [a, b] {
        crate::shadow::register(address, address as u64, PAGE as u64);
    }
    let write = crate::shadow::find(a as u64, PAGE as u64).unwrap();
    let read = crate::shadow::find(b as u64, PAGE as u64).unwrap();
    read.update(b, PAGE);
    assert_eq!(read.read_host(b as u64, 1)[0] & 0xff, 0x11);

    {
        let _guard = crate::watch::writing(b, 1);
        // SAFETY: the guard opens the page for this write.
        unsafe { (b as *mut u8).write_volatile(0x22) };
    }
    let list = host.new_list().unwrap();
    write.gpu_writes(&list, a as u64, PAGE as u64, false);
    read.refresh(&list, b as u64, PAGE as u64);
    write.gpu_writes(&list, a as u64, PAGE as u64, false);
    let observed = Arc::new(AtomicU32::new(0));
    let at_host_step = observed.clone();
    let read_at_host_step = read.clone();
    list.defer_host(move || {
        at_host_step.store(read_at_host_step.read_host(b as u64, 1)[0] & 0xff, Ordering::Relaxed);
    });
    list.close();
    host.execute(&[&list]);
    let intermediate = observed.load(Ordering::Relaxed);
    let end = read.read_host(b as u64, 1)[0] & 0xff;

    drop(list);
    for address in [a, b] {
        crate::shadow::unregister(address, address as u64);
    }
    drop((write, read));
    for address in [a, b] {
        crate::watch::tests::free(address);
    }
    assert_eq!(end, 0x22, "the final flush happened");
    assert_eq!(intermediate, 0x22, "host step must see the refreshed shadow");
}
$env:VICTORY_D3D12_WARP = '1'
cargo test --locked -p victory-gpu --lib --features diagnostics repeated_write_flushes_a_later_refresh_before_host_work -- --test-threads=1

AI-assisted (Codex).

<!-- greyfinch-sync:Marvisak/VIctory:comment:7194348017 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3114#issuecomment-7194348017). Originally posted by [yumaste](https://github.com/yumaste) on 2026-11-26T14:09:04Z. --- I tested an ordering case on Windows with WARP. A repeated unmarked `Step::GpuWrite` can still matter as a flush boundary for a refresh queued since the preceding declaration. A later `Step::Host` can observe that boundary, for example when reading a shadow in diagnostics. The fixture declares an unmarked write to A, queues a refresh of dirty B, repeats the identical write to A, and reads B in `defer_host`. The capture is the byte observed at that step. | Build | B observed in host step | B after submission | | --- | ---: | ---: | | `main` `63bcca4` | `0x22` | `0x22` | | #3114 `09cda65` | `0x11` | `0x22` | | #3114 with a pending-refresh guard | `0x22` | `0x22` | I verified a local guard that sets a flag when `Refresh`, `Heap` or `Memory` is recorded, and keeps the next unmarked write even when its key is already present. That recorded write clears the flag because it flushes the batch. `Copy` and `Run` also clear it through `title_written`. The guarded tree passed all 41 tests selected by `host::` with diagnostics under WARP, including the four tests from this PR and the reproducer below. The fixture establishes the deferred-ordering difference without any title assets. <details> <summary>Regression test for host.rs, inside the existing test module withholding</summary> ```rust #[test] fn repeated_write_flushes_a_later_refresh_before_host_work() { use crate::watch::PAGE; use std::sync::Arc; use std::sync::atomic::{AtomicU32, Ordering}; let host = super::host().expect("WARP"); let a = crate::watch::tests::pool(1); let b = crate::watch::tests::pool(1); // SAFETY: these bytes are in our allocated pools. unsafe { (b as *mut u8).write_volatile(0x11) }; for address in [a, b] { crate::shadow::register(address, address as u64, PAGE as u64); } let write = crate::shadow::find(a as u64, PAGE as u64).unwrap(); let read = crate::shadow::find(b as u64, PAGE as u64).unwrap(); read.update(b, PAGE); assert_eq!(read.read_host(b as u64, 1)[0] & 0xff, 0x11); { let _guard = crate::watch::writing(b, 1); // SAFETY: the guard opens the page for this write. unsafe { (b as *mut u8).write_volatile(0x22) }; } let list = host.new_list().unwrap(); write.gpu_writes(&list, a as u64, PAGE as u64, false); read.refresh(&list, b as u64, PAGE as u64); write.gpu_writes(&list, a as u64, PAGE as u64, false); let observed = Arc::new(AtomicU32::new(0)); let at_host_step = observed.clone(); let read_at_host_step = read.clone(); list.defer_host(move || { at_host_step.store(read_at_host_step.read_host(b as u64, 1)[0] & 0xff, Ordering::Relaxed); }); list.close(); host.execute(&[&list]); let intermediate = observed.load(Ordering::Relaxed); let end = read.read_host(b as u64, 1)[0] & 0xff; drop(list); for address in [a, b] { crate::shadow::unregister(address, address as u64); } drop((write, read)); for address in [a, b] { crate::watch::tests::free(address); } assert_eq!(end, 0x22, "the final flush happened"); assert_eq!(intermediate, 0x22, "host step must see the refreshed shadow"); } ``` ```powershell $env:VICTORY_D3D12_WARP = '1' cargo test --locked -p victory-gpu --lib --features diagnostics repeated_write_flushes_a_later_refresh_before_host_work -- --test-threads=1 ``` </details> AI-assisted (Codex).
fuzeofficlal commented 2026-11-26 16:41:11 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by fuzeofficlal on 2026-11-26T16:41:11Z.


Thanks @yumaste for catching this edge case and putting together a minimal reproducer!

Pushed ccbba392 adding a Deferred::pending_refresh guard set when Step::Refresh, Step::Heap, or Step::Memory is recorded, cleared on title_written (Copy/Run), HostList::reset, and any recorded unmarked Step::GpuWrite (while leaving it set for marked writes, which do not flush Batch). While pending_refresh is set, a repeated unmarked defer_gpu_write is still recorded once as a flush boundary before deduplicating subsequent repeats again.

Added regression test host::gpu_write_dedup::repeated_unmarked_write_flushes_pending_refresh_before_host_work covering the Refresh -> defer_host ordering (0x11 before fix -> 0x22 after), marked preservation, Heap/Memory queueing, and Copy/Run clearing, verified on both RTX 5090 and WARP with VICTORY_D3D12_DEBUG=1.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7197966024 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3114#issuecomment-7197966024). Originally posted by [fuzeofficlal](https://github.com/fuzeofficlal) on 2026-11-26T16:41:11Z. --- Thanks @yumaste for catching this edge case and putting together a minimal reproducer! Pushed `ccbba392` adding a `Deferred::pending_refresh` guard set when `Step::Refresh`, `Step::Heap`, or `Step::Memory` is recorded, cleared on `title_written` (`Copy`/`Run`), `HostList::reset`, and any recorded unmarked `Step::GpuWrite` (while leaving it set for `marked` writes, which do not flush `Batch`). While `pending_refresh` is set, a repeated unmarked `defer_gpu_write` is still recorded once as a flush boundary before deduplicating subsequent repeats again. Added regression test `host::gpu_write_dedup::repeated_unmarked_write_flushes_pending_refresh_before_host_work` covering the `Refresh` -> `defer_host` ordering (`0x11` before fix -> `0x22` after), `marked` preservation, `Heap`/`Memory` queueing, and `Copy`/`Run` clearing, verified on both RTX 5090 and WARP with `VICTORY_D3D12_DEBUG=1`.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3114:upstream-pr/3114'
git switch 'upstream-pr/3114'

Merge

Merge the changes and update on Forgejo.

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

git switch 'main'
git merge --no-ff 'upstream-pr/3114'
git switch 'upstream-pr/3114'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3114'
git switch 'upstream-pr/3114'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3114'
git switch 'main'
git merge --squash 'upstream-pr/3114'
git switch 'main'
git merge --ff-only 'upstream-pr/3114'
git switch 'main'
git merge 'upstream-pr/3114'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
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.

Reference
Marvisak/VIctory!3112
No description provided.