Repository navigation
GPU: fix 8 overflow, lookup, and snapshot bugs in shadow.rs with regression tests - #1186
geiyiliyabumo wants to merge 4 commits into
Conversation
|
Independent check of
Not covered: the AI-assisted: yes. Every number above is from my own runs. |
|
One regression to look at, at c1dd5b1: A model of just the copies (64 distinct ranges, 4 times each, in 174 MB; not the code in the game): The "newly declared gap" fix is right, and "overlapping copy-backs replay an earlier CPU edit" is a real bug on AI-assisted (Claude Code). |
|
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. |
|
Thanks for the quick fix and the test. I have not rerun the model on the new head. AI-assisted (Claude Code). |
|
On a miss (no registered buffer covers
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 Not runtime-tested with game files. AI-assisted (Claude wrote the timing test and the analysis; I ran it on my machine). |
|
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):
AI-assisted; synthetic tests only, no game files. |
|
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 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:
Why: Proposal: keep Checks:
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). |
|
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]):
AI-assisted; synthetic tests only, no game files. |
|
Confirmed at ce94115 on the RX 6750 XT (same machine and timing tests as before, release build):
Unit tests only, no game files. AI-assisted (Claude; I ran it on my machine). |
|
Heads-up: main moved to 70564ae (28 commits, including a rewrite of The lookup and overflow fixes here are still needed on the new main, though. Its
So the Source-level check of 70564ae; nothing run on it for this PR yet. AI-assisted (Claude). |
|
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. |
Summary
Closes #906
Full verification details and change notes are documented in #906 (commit
c1dd5b1, based onmainffe310e).Verification (Windows 11 x64 MSVC)
rustfmt --edition 2024 --checkon edited files: PASScargo xtask policy: PASS (zero game files/data)cargo clippy --all-targets --locked -- -D warnings(default +--features diagnosticswhere applicable): PASSAI-assisted; synthetic tests only, no game files.