Skip to content

GPU: fix 8 overflow, lookup, and snapshot bugs in shadow.rs with regression tests - #1186

Closed
geiyiliyabumo wants to merge 4 commits into
Marvisak:mainfrom
geiyiliyabumo:test/gpu-shadow-tests
Closed

geiyiliyabumo wants to merge 4 commits into
Marvisak:mainfrom
geiyiliyabumo:test/gpu-shadow-tests

Conversation

@geiyiliyabumo

Copy link
Copy Markdown
Contributor

Summary

Closes #906

Full verification details and change notes are documented in #906 (commit c1dd5b1, based on main ffe310e).

 crates/victory-gpu/src/shadow.rs | 243 +++++++++++++++++++++++++++++++++------
 1 file changed, 210 insertions(+), 33 deletions(-)

Verification (Windows 11 x64 MSVC)

  • rustfmt --edition 2024 --check on edited files: PASS
  • cargo xtask policy: PASS (zero game files/data)
  • cargo clippy --all-targets --locked -- -D warnings (default + --features diagnostics where applicable): PASS
  • Targeted & crate unit/GPU tests: PASS

AI-assisted; synthetic tests only, no game files.

@Kal0s-design

Copy link
Copy Markdown

Independent check of c1dd5b1, merged locally onto main ffe310e (clean merge). Windows 11, MSVC, Rust 1.98.1 as pinned.

  • cargo test -p victory-gpu --locked: 52 passed, 0 failed, 1 ignored.
  • The live tests: VICTORY_D3D12_WARP=1 cargo test -p victory-gpu --locked --features diagnostics shadow: 8 passed, 0 failed (none skipped, they ran on the software adapter). Repeated 10 times: 10/10 green.
  • cargo clippy -p victory-gpu --all-targets --locked -- -D warnings, with and without --all-features: clean.
  • Sensitivity: I put this PR's two test modules (tests, warp_tests) on top of main's shadow.rs, nothing else changed, and ran the same WARP command twice. 8 of 8 fail both times. Four are debug-build arithmetic panics (attempt to add with overflow in register, update and loose, attempt to subtract with overflow in refresh); a release build wraps there instead of panicking. The other four are assertion failures, which fail in any build: lookup_checks_past_noncovering_buffers, equal_start_lookup_chooses_the_smallest_covering_buffer, a_newly_declared_gap_takes_its_own_baseline and overlapping_copy_backs_do_not_replay_an_earlier_cpu_edit.

Not covered: the writing and copy_back snapshot changes were only exercised through the software adapter, not on a real GPU or with a title, so the timing between a submission and the title's own writes is untested here.

AI-assisted: yes. Every number above is from my own runs.

@TG0000

TG0000 commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

One regression to look at, at c1dd5b1: writing (shadow.rs:154) lost main's early return when the snapshot already covers the declared range, so every distinct range copies the whole union again (pooled(finish - start), line 176). World frames declare overlapping ranges of a 174 MB heap dozens of times.

A model of just the copies (64 distinct ranges, 4 times each, in 174 MB; not the code in the game): main 785 MB and 68 ms, c1dd5b1 8,363 MB and 658 ms. Suggested fix: keep the return when the union does not grow, and refresh only [from, to).

The "newly declared gap" fix is right, and "overlapping copy-backs replay an earlier CPU edit" is a real bug on main. I just opened a related PR (#1267) that keeps each declared byte once; it conflicts with this one in shadow.rs, and it does not fix that last bug.

AI-assisted (Claude Code).

@geiyiliyabumo

Copy link
Copy Markdown
Contributor Author

Thanks @TG0000 for catching the union reallocation regression in \Shadow::writing!

Pushed a follow-up commit that restores the in-place fast path when \�efore\ already covers [from, to)\—updating only \�ytes[from - *at..to - *at]\ in place without reallocating or recopying the entire union—while preserving both the newly-declared-gap baseline fix and the overlapping copy-back fix.

Added a regression test (\covered_subrange_refreshes_in_place_without_reallocating_snapshot) verifying the snapshot buffer pointer stays unchanged while the gap baseline refreshes. Re-verified with \VICTORY_D3D12_WARP=1 cargo test -p victory-gpu --features diagnostics --lib shadow\ (9/9 passed), clippy (default + --all-features\ -D warnings), and \cargo xtask policy.

AI-assisted; synthetic tests only, no game files.

@TG0000

TG0000 commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Thanks for the quick fix and the test. I have not rerun the model on the new head.

AI-assisted (Claude Code).

@wwwwwwww3333333

Copy link
Copy Markdown

find is now O(registered buffers) on a miss, measured on hardware. @TG0000's writing point is fixed at 1d500e3; the timing below confirms it on the new head. find is unchanged by that commit, and it hasn't come up yet.

On a miss (no registered buffer covers [address, end)), find now walks every entry whose start is at or below address before falling back to loose; main stops after 64. Release build, RX 6750 XT, Windows 11, Rust 1.98.1 MSVC, with a local ignored test that is not part of this PR: 20,000 registered 16-byte buffers below the address, 10,000 lookups. For writing, 50 ranges are declared inside a 64 MiB range declared first.

main c1dd5b1 1d500e3
find miss, per lookup 0.22 µs 62.3 µs 90.2 µs
writing, 50 ranges inside a declared 64 MiB range 0.01 ms 419.6 ms 0.05 ms

The world calls the buffer lookups about 160k times a frame (from a diag frame ledger shown on stream). I can't tell from here how many of those miss, or how many buffers the title has registered, so the real cost may be much smaller than this worst case.

The cap on main is wrong too, as lookup_checks_past_noncovering_buffers shows: with more than 64 non-covering entries in between, it misses the real buffer. One way to keep both: track the longest registered length max_len and stop the reverse scan once k.0 + max_len < end, since no earlier entry can reach end. The scan is then bounded by how many buffers start within max_len below the address, not by the whole map. If one huge heap makes that bound loose, a small separate index for the few large buffers would do it.

Not runtime-tested with game files. AI-assisted (Claude wrote the timing test and the analysis; I ran it on my machine).

@geiyiliyabumo

Copy link
Copy Markdown
Contributor Author

Thanks @wwwwwwww3333333 for benchmarking both \writing\ (confirming \1d500e3\ brought it back from 419.6 ms to 0.05 ms) and catching the O(N) miss regression in \ ind()!

Pushed $sha\ to bound \ ind()\ by the exact longest registered buffer length (\Buffers::max_len):


  • egister\ updates \max_len\ (and recomputes if replacing the longest entry with a shorter one); \unregister\ recomputes only when removing an entry whose length equals \max_len.
  • \ ind(address, len)\ skips the map scan immediately if \len.max(1) > max_len\ and otherwise restricts the reverse \BTreeMap::range\ to (end.saturating_sub(max_len), 0)..=(address, usize::MAX), so misses above small buffers inspect zero out-of-reach entries while hits behind >64 non-covering buffers inside a larger registered range still succeed.
  • Added \max_len_tracks_register_replace_and_unregister; re-verified \VICTORY_D3D12_WARP=1 cargo test -p victory-gpu --features diagnostics --lib shadow\ (10/10 passed), clippy (default + --all-features\ -D warnings), and \cargo xtask policy.

AI-assisted; synthetic tests only, no game files.

@Zipettte

Copy link
Copy Markdown

Tested on AMD Radeon RX 7700 XT (RDNA3, gfx1101), driver 32.0.32029.2010, Windows 11, Rust 1.98.1 MSVC at c1dd5b1: cargo test -p victory-gpu passes, 52 passed / 0 failed. Workspace baseline on main (ffe310e) is green on the same machine (342 passed).

Tested with AI assistance (Claude).

@wwwwwwww3333333

Copy link
Copy Markdown

46f9d80 fixes the case I measured, but the miss is still O(registered buffers) as soon as one large buffer is registered anywhere below the address, and unregister became O(n) per call when many buffers share the longest length. Measured with the real shadow.rs, plus a proposed alternative below.

Release build, RX 6750 XT, i5-13400F, Windows 11, Rust 1.98.1 MSVC, base ffe310e, local ignored timing tests that are not part of this PR:

46f9d80 proposal
find miss past 20,000 16-byte buffers (the earlier case) 0.05 µs 0.05 µs
same, plus one 64 MiB buffer registered elsewhere (not covering) 49.07 µs 0.05 µs
unregister of 20,000 equal-length buffers 306.2 ms 1.4 ms
writing, 50 ranges inside a declared 64 MiB range 0.03 ms 0.03 ms

Why: max_len is global, so one 64 MiB buffer widens the scan window to 64 MiB for every lookup, and every small buffer in it is visited again. In unregister, removing any entry whose length equals max_len rescans the whole map; with many equal lengths (common for a title's pools), that is every call. In a standalone model of the scan, 5,000 / 10,000 / 20,000 equal-length unregisters took 18 / 75 / 310 ms, so it grows quadratically.

Proposal: keep by_start as is (for get_mut, near and the tests) and add a second index by power-of-two length class. A class-c buffer has len < 2^(c+1), so it can only cover [address, end) if start >= end - (2^(c+1) - 1). find scans each non-empty class over that window only and keeps the innermost match with the same tie-breaks as now: largest start, then smallest end, then the first met in descending key order. register and unregister are O(log n), and max_len goes away.

Checks:

  • cargo test -p victory-gpu --lib shadow passes on this machine, with max_len_tracks_register_replace_and_unregister replaced by a class-index test.
  • cargo clippy -p victory-gpu --all-targets -- -D warnings is clean.
  • Separately, the exact register/unregister/find code compiled standalone and matched a brute-force innermost search on 120,000 random lookups. The random buffers were nested, included zero-length and replaced registrations, and everything was unregistered at the end with both indexes left empty.
Diff against 46f9d80
--- a/crates/victory-gpu/src/shadow.rs
+++ b/crates/victory-gpu/src/shadow.rs
@@ -406,38 +406,43 @@
 
 struct Buffers {
     by_start: BTreeMap<(u64, usize), Entry>,
-    /// Longest registered buffer length; bounds reverse scans in [`find`].
-    max_len: u64,
+    /// The same buffers by length class: class `c` holds lengths in
+    /// `[2^c, 2^(c+1))`, start -> end. A class-`c` buffer can only cover
+    /// `[address, end)` if it starts at or above `end - (2^(c+1) - 1)`, so
+    /// [`find`] scans each class over that window only.
+    by_class: [BTreeMap<(u64, usize), u64>; 64],
 }
 
 /// Title buffers by (start address, resource), with their copy once made.
 static BUFFERS: Mutex<Buffers> = Mutex::new(Buffers {
     by_start: BTreeMap::new(),
-    max_len: 0,
+    by_class: [const { BTreeMap::new() }; 64],
 });
 
 fn buffers() -> std::sync::MutexGuard<'static, Buffers> {
     BUFFERS.lock().unwrap_or_else(|e| e.into_inner())
 }
 
+/// The length class of a nonzero length.
+fn class(len: u64) -> usize {
+    63 - len.leading_zeros() as usize
+}
+
 /// A title buffer exists at `start` (`len` bytes).
 pub(crate) fn register(resource: usize, start: u64, len: u64) {
     let Some(end) = start.checked_add(len) else {
         return;
     };
     let mut state = buffers();
-    let replaced = state
+    if let Some(old) = state
         .by_start
-        .insert((start, resource), Entry { end, shadow: None });
-    if len >= state.max_len {
-        state.max_len = len;
-    } else if replaced.is_some_and(|old| old.end - start == state.max_len) {
-        state.max_len = state
-            .by_start
-            .iter()
-            .map(|(&(s, _), e)| e.end - s)
-            .max()
-            .unwrap_or(0);
+        .insert((start, resource), Entry { end, shadow: None })
+        && old.end > start
+    {
+        state.by_class[class(old.end - start)].remove(&(start, resource));
+    }
+    if len > 0 {
+        state.by_class[class(len)].insert((start, resource), end);
     }
 }
 
@@ -445,14 +450,9 @@
 pub(crate) fn unregister(resource: usize, start: u64) {
     let mut state = buffers();
     if let Some(removed) = state.by_start.remove(&(start, resource))
-        && removed.end - start == state.max_len
+        && removed.end > start
     {
-        state.max_len = state
-            .by_start
-            .iter()
-            .map(|(&(s, _), e)| e.end - s)
-            .max()
-            .unwrap_or(0);
+        state.by_class[class(removed.end - start)].remove(&(start, resource));
     }
 }
 
@@ -462,31 +462,44 @@
     let required = len.max(1);
     let end = address.checked_add(required)?;
     let mut state = buffers();
-    // No registered buffer can cover `[address, end)` if `required > max_len`,
-    // or if its start is below `end - max_len`.
+    // The innermost buffer holding the range: the largest start at or below
+    // `address` whose end reaches `end`; of equal starts, the smallest end;
+    // of equal ends, the largest resource (the first met in descending order).
     let mut key: Option<((u64, usize), u64)> = None;
-    if required <= state.max_len {
-        let min_start = end.saturating_sub(state.max_len);
-        // The innermost buffer holding the range: the largest start at or below
-        // `address` whose end reaches `end`; of equal starts, the smallest end.
-        // Same-start entries are contiguous, so the first covering block found
-        // in start-descending order is the innermost.
-        for (&k, e) in state
-            .by_start
-            .range((min_start, 0)..=(address, usize::MAX))
-            .rev()
-        {
-            if let Some((best, bend)) = &key {
-                if best.0 != k.0 {
+    for c in class(required)..64 {
+        let map = &state.by_class[c];
+        if map.is_empty() {
+            continue;
+        }
+        let reach = if c == 63 { u64::MAX } else { (1 << (c + 1)) - 1 };
+        let min_start = end.saturating_sub(reach);
+        let mut here: Option<((u64, usize), u64)> = None;
+        for (&k, &e) in map.range((min_start, 0)..=(address, usize::MAX)).rev() {
+            if key.is_some_and(|(best, _)| k.0 < best.0) {
+                break;
+            }
+            if let Some((first, fend)) = here {
+                if first.0 != k.0 {
                     break;
                 }
-                if e.end >= end && e.end < *bend {
-                    key = Some((k, e.end));
+                if e >= end && e < fend {
+                    here = Some((k, e));
                 }
-            } else if e.end >= end {
-                key = Some((k, e.end));
+            } else if e >= end {
+                here = Some((k, e));
             }
         }
+        if let Some((k, e)) = here {
+            key = match key {
+                Some((best, bend))
+                    if k.0 < best.0
+                        || (k.0 == best.0 && (e > bend || (e == bend && k.1 < best.1))) =>
+                {
+                    Some((best, bend))
+                }
+                _ => Some((k, e)),
+            };
+        }
     }
     let Some((key, _)) = key else {
         drop(state);
@@ -601,22 +614,16 @@
     }
 
     #[test]
-    fn max_len_tracks_register_replace_and_unregister() {
-        // Use a distinctive large length above any concurrent test's buffers.
+    fn class_index_follows_register_replace_and_unregister() {
         let base = 0x7000_0000_0000u64;
-        let big = 0x10_0000_0000u64;
-        let mid = 0x08_0000_0000u64;
-        register(9001, base, mid);
-        assert!(buffers().max_len >= mid);
-        register(9002, base + 0x1000, big);
-        assert_eq!(buffers().max_len, big);
-        // Shrinking the current longest entry recomputes max_len.
-        register(9002, base + 0x1000, 64);
-        assert_eq!(buffers().max_len, mid);
-        // Unregistering the remaining longest entry recomputes max_len again.
+        register(9001, base, 0x10_0000);
+        assert!(buffers().by_class[20].contains_key(&(base, 9001)));
+        // Re-registering with another length moves it to that class.
+        register(9001, base, 64);
+        assert!(!buffers().by_class[20].contains_key(&(base, 9001)));
+        assert!(buffers().by_class[6].contains_key(&(base, 9001)));
         unregister(9001, base);
-        assert!(buffers().max_len < mid);
-        unregister(9002, base + 0x1000);
+        assert!(!buffers().by_class[6].contains_key(&(base, 9001)));
     }
 }
 

Source-level analysis plus unit tests and timings; not runtime-tested with game files. AI-assisted (Claude wrote the proposal and the timing tests; I ran them on my machine).

@geiyiliyabumo

Copy link
Copy Markdown
Contributor Author

Thanks @wwwwwwww3333333 for benchmarking both the large-buffer miss case and equal-length \unregister\ scaling, and for designing the length-class index!

Pushed $sha1186\ adopting the power-of-two length-class index (\�y_class: [BTreeMap<(u64, usize), u64>; 64]):

  • Replaces global \max_len\ so a single large buffer no longer widens the scan window for small-buffer misses, and both
    egister\ and \unregister\ stay O(log n) with zero full-map rescans.
  • Preserves the exact innermost tie-breaking order (largest \start, smallest \end, largest
    esource) and updates the unit test to \class_index_follows_register_replace_and_unregister.
  • Re-verified \VICTORY_D3D12_WARP=1 cargo test -p victory-gpu --features diagnostics --lib shadow\ (10/10 passed) and \cargo clippy -p victory-gpu --all-targets -- -D warnings\ (default & --all-features).

AI-assisted; synthetic tests only, no game files.

@wwwwwwww3333333

Copy link
Copy Markdown

Confirmed at ce94115 on the RX 6750 XT (same machine and timing tests as before, release build):

46f9d80 ce94115
find miss past 20,000 small buffers 0.05 µs 0.08 µs
same, plus one 64 MiB buffer elsewhere 49.07 µs 0.05 µs
unregister of 20,000 equal-length buffers 306.2 ms 1.7 ms
writing, 50 ranges in a 64 MiB range 0.03 ms 0.03 ms

cargo test -p victory-gpu --lib -- --test-threads=1: 53 passed, 0 failed (main: 50). cargo clippy -p victory-gpu --all-targets -- -D warnings is clean. Thanks for taking the length-class index in.

Unit tests only, no game files. AI-assisted (Claude; I ran it on my machine).

@wwwwwwww3333333

Copy link
Copy Markdown

Heads-up: main moved to 70564ae (28 commits, including a rewrite of watch.rs and about 470 changed lines in shadow.rs), and ce94115 now conflicts with it in 7 places in shadow.rs. Most of them are in Shadow::writing/refresh, which main reworked around its new change journal.

The lookup and overflow fixes here are still needed on the new main, though. Its shadow.rs still has:

  • find: .range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end), so a covering buffer more than 64 starts below is still missed, and among equal starts it still takes the first match rather than the innermost.
  • register: end: start + len with no overflow check.
  • loose: end.next_multiple_of(WINDOW) - start, also unchecked.

So the find/register/unregister part of this PR (with the length-class index) should carry over almost as is. The snapshot/writing part needs redoing against main's new journal. Once it's rebased, I'll rerun the same timings and tests on the RX 6750 XT.

Source-level check of 70564ae; nothing run on it for this PR yet. AI-assisted (Claude).

@Marvisak

Copy link
Copy Markdown
Owner

Automated triage for the maintainers. Closing because it does not change behaviour the project needs (formatting, guards for cases that cannot occur, or notes and translations that cannot be kept current).

Eight changes in one against the shadow.rs main replaced today (bounding snapshot, buffer lookup by size class, saturating adds). What still matters is in focused PRs: #402 (lookup past 64 entries) and #261 (snapshot after a copy-back).

If this is mistaken, reply here with what was missed (or push a change and say so) and it will be looked at again. Thank you for the contribution.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GPU: fix 8 overflow, lookup, and snapshot bugs in shadow.rs with regression tests

6 participants