GPU: bound shadow buffer lookup by maximum registered size instead of 64 entries #2096

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

@⁠fuzeofficlal on GitHub · 2026-11-25 04:49 UTC · original
fuzeofficlal:fix/gpu-shadow-overflow-and-find-906 → main · +143 −21 · 1 files · 1 commits · open

Refs #906.

Summary

  • Replace the fixed .take(64) cap in shadow::find (crates/victory-gpu/src/shadow.rs) with a reverse scan bounded by the maximum buffer size currently registered in BUFFERS (lowest = end.saturating_sub(max_size), returning None immediately when lowest > address).
  • Track max_size on Buffers::insert and recompute it on Buffers::remove when the previous maximum-size entry is unregistered, so misses reaching loose() stop at the live maximum buffer bound while lookups still reach a covering outer buffer past more than 64 smaller inner buffers.

Verification

  • shadow::tests::find_reaches_covering_buffer_past_many_inner_buffers
  • shadow::tests::find_stops_at_max_size_bound_and_tightens_on_unregister
  • cargo clippy -p victory-gpu --tests --locked -- -D warnings and cargo xtask policy: passed.
**@⁠fuzeofficlal** on GitHub · 2026-11-25 04:49 UTC · [original](https://github.com/Marvisak/VIctory/pull/2096) `fuzeofficlal:fix/gpu-shadow-overflow-and-find-906` → `main` · +143 −21 · 1 files · 1 commits · open Refs #906. ### Summary - Replace the fixed `.take(64)` cap in `shadow::find` (`crates/victory-gpu/src/shadow.rs`) with a reverse scan bounded by the maximum buffer size currently registered in `BUFFERS` (`lowest = end.saturating_sub(max_size)`, returning `None` immediately when `lowest > address`). - Track `max_size` on `Buffers::insert` and recompute it on `Buffers::remove` when the previous maximum-size entry is unregistered, so misses reaching `loose()` stop at the live maximum buffer bound while lookups still reach a covering outer buffer past more than 64 smaller inner buffers. ### Verification - `shadow::tests::find_reaches_covering_buffer_past_many_inner_buffers` - `shadow::tests::find_stops_at_max_size_bound_and_tightens_on_unregister` - `cargo clippy -p victory-gpu --tests --locked -- -D warnings` and `cargo xtask policy`: passed.
Replace the fixed `.take(64)` cap in `shadow::find` with a scan bounded
by the maximum buffer size currently registered in `BUFFERS`:

- Track `max_size` alongside the `BUFFERS` map, updating it on `register`
  and recomputing it on `unregister` (or replacement shrinkage) when the
  previous maximum-size entry is removed, so the bound stays tight.
- Bound the reverse scan in `find_buffer` using `max_size`, allowing
  lookups to reach a covering outer buffer past more than 64 smaller
  inner buffers while stopping misses immediately outside `max_size`.
- Add unit tests covering lookup past 128 inner buffers and `max_size`
  bounding/tightening on `unregister`.

Refs #906.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 04:54:41 +00:00
Author
Owner

@⁠Marvisak on GitHub · 2026-11-25 10:36 UTC · original · edited 2026-11-25 11:23 UTC

Automated triage for the maintainers.

Merge candidate. shadow::find now scans backwards only from end - max_size (find_buffer), where Buffers tracks the largest registered length and recomputes it when the largest entry is removed or replaced; a buffer that covers [address, end) must start at or after that bound, so lookups still reach an outer buffer past many smaller ones while misses reaching loose() stop early. The overflow guards and the equal-start tie-breaker are gone. #402 overlaps but currently has merge conflicts; this one merges cleanly. CI passes.

On your reply: confirmed in 2f43424, this is what was asked. A minor follow-up, not a blocker: Buffers::remove rescans the whole map each time an entry of the maximum size goes, which is O(n) per release if many buffers share that size; a size-count map would make it O(log n).


Generated by Claude Code

**@⁠Marvisak** on GitHub · 2026-11-25 10:36 UTC · [original](https://github.com/Marvisak/VIctory/pull/2096#issuecomment-7159924855) · edited 2026-11-25 11:23 UTC <!-- victory-triage v1 head=2f434243f82c511c9169b8e5b64363fc3ac0caa9 verdict=merge-candidate at=2026-11-25T11:23:40Z --> Automated triage for the maintainers. **Merge candidate.** `shadow::find` now scans backwards only from `end - max_size` (`find_buffer`), where `Buffers` tracks the largest registered length and recomputes it when the largest entry is removed or replaced; a buffer that covers `[address, end)` must start at or after that bound, so lookups still reach an outer buffer past many smaller ones while misses reaching `loose()` stop early. The overflow guards and the equal-start tie-breaker are gone. #402 overlaps but currently has merge conflicts; this one merges cleanly. CI passes. On your reply: confirmed in `2f43424`, this is what was asked. A minor follow-up, not a blocker: `Buffers::remove` rescans the whole map each time an entry of the maximum size goes, which is O(n) per release if many buffers share that size; a size-count map would make it O(log n). --- _Generated by [Claude Code](https://claude.ai/code)_
Author
Owner

@⁠fuzeofficlal on GitHub · 2026-11-25 10:51 UTC · original

Updated in 2f434243 per triage feedback:

  • Bounded find_buffer by the maximum currently registered buffer size (lowest = end.saturating_sub(max_size) over (lowest, 0)..=(address, usize::MAX)), tightening max_size on unregister when the largest buffer is removed so misses stop early instead of walking the map.
  • Dropped all u64::MAX overflow/saturating guards and the equal-start tie-breaker.
**@⁠fuzeofficlal** on GitHub · 2026-11-25 10:51 UTC · [original](https://github.com/Marvisak/VIctory/pull/2096#issuecomment-7160276566) Updated in `2f434243` per triage feedback: - Bounded `find_buffer` by the maximum currently registered buffer size (`lowest = end.saturating_sub(max_size)` over `(lowest, 0)..=(address, usize::MAX)`), tightening `max_size` on `unregister` when the largest buffer is removed so misses stop early instead of walking the map. - Dropped all `u64::MAX` overflow/saturating guards and the equal-start tie-breaker.
Author
Owner

@⁠DenRakEiw on GitHub · 2026-11-25 04:56 UTC · original · approved these changes

Verified locally merged onto origin/main (940d32f, Windows 11 x64, Rust 1.98.1 MSVC):

  • cargo test -p victory-gpu --lib shadow:: — 6 passed, 0 failed (including overflowing_ranges_are_rejected_without_panic and find_scans_past_sixty_four_siblings_and_picks_tightest_equal_start)
  • cargo clippy -p victory-gpu --all-targets — 0 warnings
  • cargo xtask policy — ok (183 files ok)

Clean overflow guards on shadow range arithmetic and complete sibling scan in find(). Looks good.

AI-assisted (Gemini 4 Neon).

**@⁠DenRakEiw** on GitHub · 2026-11-25 04:56 UTC · [original](https://github.com/Marvisak/VIctory/pull/2096#pullrequestreview-6052066805) · **approved these changes** Verified locally merged onto `origin/main` (`940d32f`, Windows 11 x64, Rust 1.98.1 MSVC): - `cargo test -p victory-gpu --lib shadow::` — 6 passed, 0 failed (including `overflowing_ranges_are_rejected_without_panic` and `find_scans_past_sixty_four_siblings_and_picks_tightest_equal_start`) - `cargo clippy -p victory-gpu --all-targets` — 0 warnings - `cargo xtask policy` — ok (`183 files ok`) Clean overflow guards on shadow range arithmetic and complete sibling scan in `find()`. Looks good. AI-assisted (Gemini 4 Neon).
Author
Owner

@⁠catminou4 on GitHub · 2026-11-25 05:02 UTC · original · reviewed

Static review only: victory-gpu is Windows-only (D3D12/windows_sys) — nothing compiles or runs on macOS; source review of the diff.

Shadow range arithmetic overflow-guarded + scan — memory-safety hardening on the shadow-memory path.

**@⁠catminou4** on GitHub · 2026-11-25 05:02 UTC · [original](https://github.com/Marvisak/VIctory/pull/2096#pullrequestreview-6052105132) · **reviewed** Static review only: victory-gpu is Windows-only (D3D12/windows_sys) — nothing compiles or runs on macOS; source review of the diff. Shadow range arithmetic overflow-guarded + scan — memory-safety hardening on the shadow-memory path.
Author
Owner

@⁠Desamodeth on GitHub · 2026-11-26 21:10 UTC · original · reviewed

The full rescan mentioned in triage is visible in both removal and in-place replacement on 2f434243. With 4,096 equal 4 KiB buffers, removing them one by one visits 8,386,560 remaining entries under the registry mutex. Shrinking all 4,096 at the same keys visits 16,777,216 entries.

CPU time per batch of 4,096 mutations, across two opposite-order runs:

Workload main 63bcca43 This PR Suggested size counts
Remove equal 4 KiB registrations 0.13–0.15 ms 6.48–6.64 ms 0.13–0.15 ms
Replace each 4 KiB registration with 2 KiB 0.09–0.10 ms 13.01–13.21 ms 0.105–0.106 ms
Remove 4,096 distinct sizes, largest first 0.14–0.15 ms 6.49–6.53 ms 0.40–0.42 ms

The suggestion keeps the PR's exact lookup bound and stores one count per distinct length. The extra live heap requested by the index was 192 B for one length, 2,016 B for 64 lengths and 139,968 B for 4,096 lengths. Registering the all-distinct batch also took 0.34–0.36 ms vs 0.16–0.21 ms here. I tested a single counter for ties too. It fixed the equal-size case, but largest-first removal still took 9.27–9.30 ms.

Isolated Windows x64 registry benchmark, Ryzen 7 9800X3D, rustc 1.98.1 release, production mutex and map operations. Each sample started empty, registered disjoint buffers and performed one hit per buffer before timing mutations. Eleven timed samples per case in each run. Separate allocation-counting binary. Checked exact maxima after 6,000 mixed mutations and 18,000 lookups against an exhaustive reference, including shared start addresses and replacements. The covering buffer beyond 64 siblings is still found. The suggestion applies to this head and to this PR applied over current main. Full crate, D3D12 and in-game frequency were outside this CPU measurement. AI-assisted with Codex.

**@⁠Desamodeth** on GitHub · 2026-11-26 21:10 UTC · [original](https://github.com/Marvisak/VIctory/pull/2096#pullrequestreview-6080510542) · **reviewed** The full rescan mentioned in triage is visible in both removal and in-place replacement on `2f434243`. With 4,096 equal 4 KiB buffers, removing them one by one visits 8,386,560 remaining entries under the registry mutex. Shrinking all 4,096 at the same keys visits 16,777,216 entries. CPU time per batch of 4,096 mutations, across two opposite-order runs: | Workload | main `63bcca43` | This PR | Suggested size counts | | --- | ---: | ---: | ---: | | Remove equal 4 KiB registrations | 0.13–0.15 ms | 6.48–6.64 ms | 0.13–0.15 ms | | Replace each 4 KiB registration with 2 KiB | 0.09–0.10 ms | 13.01–13.21 ms | 0.105–0.106 ms | | Remove 4,096 distinct sizes, largest first | 0.14–0.15 ms | 6.49–6.53 ms | 0.40–0.42 ms | The suggestion keeps the PR's exact lookup bound and stores one count per distinct length. The extra live heap requested by the index was 192 B for one length, 2,016 B for 64 lengths and 139,968 B for 4,096 lengths. Registering the all-distinct batch also took 0.34–0.36 ms vs 0.16–0.21 ms here. I tested a single counter for ties too. It fixed the equal-size case, but largest-first removal still took 9.27–9.30 ms. Isolated Windows x64 registry benchmark, Ryzen 7 9800X3D, rustc 1.98.1 release, production mutex and map operations. Each sample started empty, registered disjoint buffers and performed one hit per buffer before timing mutations. Eleven timed samples per case in each run. Separate allocation-counting binary. Checked exact maxima after 6,000 mixed mutations and 18,000 lookups against an exhaustive reference, including shared start addresses and replacements. The covering buffer beyond 64 siblings is still found. The suggestion applies to this head and to this PR applied over current main. Full crate, D3D12 and in-game frequency were outside this CPU measurement. AI-assisted with Codex.
@ -790,0 +828,4 @@
.max()
.unwrap_or(0);
}
}
Author
Owner

@⁠Desamodeth on GitHub · 2026-11-26 21:10 UTC · original

Keep the bound exact on replacement and removal. This is the size-count variant measured above.

struct Buffers {
    map: BTreeMap<(u64, usize), Entry>,
    /// Number of live registrations of each buffer length.
    size_counts: BTreeMap<u64, usize>,
    /// Cached so range lookups do not need to visit the size index.
    max_size: u64,
}

impl Buffers {
    const fn new() -> Self {
        Self {
            map: BTreeMap::new(),
            size_counts: BTreeMap::new(),
            max_size: 0,
        }
    }

    fn insert(&mut self, resource: usize, start: u64, len: u64) {
        if let Some(prev) = self.map.insert(
            (start, resource),
            Entry {
                end: start + len,
                shadow: None,
            },
        ) {
            let previous_len = prev.end - start;
            if previous_len == len {
                return;
            }
            self.forget_size(previous_len);
        }
        *self.size_counts.entry(len).or_default() += 1;
        self.max_size = self.max_size.max(len);
    }

    fn remove(&mut self, resource: usize, start: u64) -> Option<Entry> {
        let removed = self.map.remove(&(start, resource))?;
        self.forget_size(removed.end - start);
        Some(removed)
    }

    fn forget_size(&mut self, len: u64) {
        let count = self.size_counts.get_mut(&len).expect("registered buffer length");
        *count -= 1;
        if *count == 0 {
            self.size_counts.remove(&len);
            if len == self.max_size {
                self.max_size = self.size_counts.last_key_value().map_or(0, |(&size, _)| size);
            }
        }
    }
}
**@⁠Desamodeth** on GitHub · 2026-11-26 21:10 UTC · [original](https://github.com/Marvisak/VIctory/pull/2096#discussion_r4713391674) Keep the bound exact on replacement and removal. This is the size-count variant measured above. ```suggestion struct Buffers { map: BTreeMap<(u64, usize), Entry>, /// Number of live registrations of each buffer length. size_counts: BTreeMap<u64, usize>, /// Cached so range lookups do not need to visit the size index. max_size: u64, } impl Buffers { const fn new() -> Self { Self { map: BTreeMap::new(), size_counts: BTreeMap::new(), max_size: 0, } } fn insert(&mut self, resource: usize, start: u64, len: u64) { if let Some(prev) = self.map.insert( (start, resource), Entry { end: start + len, shadow: None, }, ) { let previous_len = prev.end - start; if previous_len == len { return; } self.forget_size(previous_len); } *self.size_counts.entry(len).or_default() += 1; self.max_size = self.max_size.max(len); } fn remove(&mut self, resource: usize, start: u64) -> Option<Entry> { let removed = self.map.remove(&(start, resource))?; self.forget_size(removed.end - start); Some(removed) } fn forget_size(&mut self, len: u64) { let count = self.size_counts.get_mut(&len).expect("registered buffer length"); *count -= 1; if *count == 0 { self.size_counts.remove(&len); if len == self.max_size { self.max_size = self.size_counts.last_key_value().map_or(0, |(&size, _)| size); } } } } ```
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/2096/head:github-bot/gh-2096'
git switch 'github-bot/gh-2096'

Merge

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