GPU: compact watch page tracking with dense PageBits and inline OneOrMany storage #3227

Open
0xKaji wants to merge 2 commits from upstream-pr/3229 into main
0xKaji commented 2026-11-26 13:48:02 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by 0xKaji on 2026-11-26T13:48:02Z.


Summary

Compacts victory-gpu's write-watch metadata in watch.rs to eliminate per-page BTreeSet nodes and per-page heap Vec allocations when tracking hundreds of thousands of 64 KiB pages.

Changes

  • PageBits dense bitset (watch.rs): Replaces Changed.0: Mutex<BTreeSet<usize>> with a contiguous Box<[u64]> bitset relative to the tracked range's start page (1 bit per 64 KiB page = 16 bytes per MiB), with O(1) insert/remove/contains and trailing_zeros()-based range_pages.
  • OneOrMany<T> inline storage (watch.rs): Replaces Vec<Arc<Changed>> in Guards::holders and Vec<usize> in Guards::alias_of with an inline single-element enum (One(T) | Many(Vec<T>)) that spills to Vec only when a page has multiple holders/aliases and collapses back to One on retain.
  • Tracked::disarm trimming (watch.rs): Shrinks oversized Saved::armed (> 64) and Saved::bytes (> 16) capacities when disarming.

Verification

  • cargo xwin clippy --workspace --all-targets --locked --target x86_64-pc-windows-msvc -- -D warnings
  • cargo xwin clippy --workspace --all-targets --all-features --locked --target x86_64-pc-windows-msvc -- -D warnings
  • cargo test -p xtask --locked (6/6 passed)
  • Wine watch::tests:: --test-threads=1: 17/17 passed (including page_bits_tracks_multi_word_ranges and one_or_many_spills_and_collapses).
  • Touches watch.rs in areas distinct from #3154 (alias page unprotection on last tracker drop), #3156 (take_split unmapped merge), and #3161 (transitive alias groups).
<!-- greyfinch-sync:Marvisak/VIctory:issue:5511202532 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3229). Originally posted by [0xKaji](https://github.com/0xKaji) on 2026-11-26T13:48:02Z. --- ## Summary Compacts `victory-gpu`'s write-watch metadata in `watch.rs` to eliminate per-page `BTreeSet` nodes and per-page heap `Vec` allocations when tracking hundreds of thousands of 64 KiB pages. ## Changes - **`PageBits` dense bitset (`watch.rs`):** Replaces `Changed.0: Mutex<BTreeSet<usize>>` with a contiguous `Box<[u64]>` bitset relative to the tracked range's start page (1 bit per 64 KiB page = 16 bytes per MiB), with O(1) `insert`/`remove`/`contains` and `trailing_zeros()`-based `range_pages`. - **`OneOrMany<T>` inline storage (`watch.rs`):** Replaces `Vec<Arc<Changed>>` in `Guards::holders` and `Vec<usize>` in `Guards::alias_of` with an inline single-element enum (`One(T) | Many(Vec<T>)`) that spills to `Vec` only when a page has multiple holders/aliases and collapses back to `One` on `retain`. - **`Tracked::disarm` trimming (`watch.rs`):** Shrinks oversized `Saved::armed` (> 64) and `Saved::bytes` (> 16) capacities when disarming. ## Verification - `cargo xwin clippy --workspace --all-targets --locked --target x86_64-pc-windows-msvc -- -D warnings` - `cargo xwin clippy --workspace --all-targets --all-features --locked --target x86_64-pc-windows-msvc -- -D warnings` - `cargo test -p xtask --locked` (6/6 passed) - Wine `watch::tests:: --test-threads=1`: **17/17 passed** (including `page_bits_tracks_multi_word_ranges` and `one_or_many_spills_and_collapses`). ## Related PRs - Touches `watch.rs` in areas distinct from `#3154` (alias page unprotection on last tracker drop), `#3156` (`take_split` unmapped merge), and `#3161` (transitive alias groups).
Dukestar69 commented 2026-11-26 14:09:06 +00:00 (Migrated from github.com)

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

Review: APPROVED


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

  • cargo test -p victory-gpu --lib watch:: -- --test-threads=1: 17/17 passed (including one_or_many_spills_and_collapses and page_bits_tracks_multi_word_ranges).
  • cargo test -p victory-gpu --lib shadow:: -- --test-threads=1: 10/10 passed.
  • cargo clippy -p victory-gpu --all-targets -- -D warnings: clean.
  • cargo xtask policy: 191 files ok.

Cleanly compacts watch page tracking with dense PageBits and inline OneOrMany storage.

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

<!-- greyfinch-sync:Marvisak/VIctory:review:6075535097 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3229#pullrequestreview-6075535097). Originally posted by [Dukestar69](https://github.com/Dukestar69) on 2026-11-26T14:09:06Z. **Review:** APPROVED --- Verified on RTX 5090 against `origin/main` (`63bcca4`): - `cargo test -p victory-gpu --lib watch:: -- --test-threads=1`: 17/17 passed (including `one_or_many_spills_and_collapses` and `page_bits_tracks_multi_word_ranges`). - `cargo test -p victory-gpu --lib shadow:: -- --test-threads=1`: 10/10 passed. - `cargo clippy -p victory-gpu --all-targets -- -D warnings`: clean. - `cargo xtask policy`: 191 files ok. Cleanly compacts watch page tracking with dense `PageBits` and inline `OneOrMany` storage. Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).
Desamodeth commented 2026-11-26 22:08:59 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Desamodeth on 2026-11-26T22:08:59Z.

Code review location: crates/victory-gpu/src/watch.rs; line 122

@@ -43,10 +43,207 @@ use std::sync::{Arc, Mutex};
 /// they saved.
 pub(crate) const PAGE: usize = 64 << 10;
 
+/// Dense bitset of changed 64 KiB pages for a [`Tracked`] range `[base, base + words.len() * 64)`.
+struct PageBits {
+    base: usize,
+    words: Box<[u64]>,
+    count: usize,
+}
+
+impl PageBits {
+    fn from_pages(start_page: usize, end_page: usize, pages: &[usize]) -> Self {
+        let len = end_page.saturating_sub(start_page).div_ceil(64);
+        let mut bits = Self {
+            base: start_page,
+            words: vec![0u64; len].into_boxed_slice(),
+            count: 0,
+        };
+        for &p in pages {
+            bits.insert(p);
+        }
+        bits
+    }
+
+    fn insert(&mut self, page: usize) -> bool {
+        let Some(rel) = page.checked_sub(self.base) else {
+            return false;
+        };
+        let word = rel / 64;
+        let Some(slot) = self.words.get_mut(word) else {
+            return false;
+        };
+        let mask = 1u64 << (rel % 64);
+        if *slot & mask == 0 {
+            *slot |= mask;
+            self.count += 1;
+            true
+        } else {
+            false
+        }
+    }
+
+    fn remove(&mut self, page: usize) -> bool {
+        let Some(rel) = page.checked_sub(self.base) else {
+            return false;
+        };
+        let word = rel / 64;
+        let Some(slot) = self.words.get_mut(word) else {
+            return false;
+        };
+        let mask = 1u64 << (rel % 64);
+        if *slot & mask != 0 {
+            *slot &= !mask;
+            self.count -= 1;
+            true
+        } else {
+            false
+        }
+    }
+
+    fn contains(&self, page: usize) -> bool {
+        let Some(rel) = page.checked_sub(self.base) else {
+            return false;
+        };
+        let word = rel / 64;
+        self.words
+            .get(word)
+            .is_some_and(|&w| w & (1u64 << (rel % 64)) != 0)
+    }
+
+    fn is_empty(&self) -> bool {
+        self.count == 0
+    }
+
+    fn range_pages(&self, from: usize, to: usize) -> Vec<usize> {
+        let mut out = Vec::new();
+        let start = from.max(self.base);
+        let limit = self.base + self.words.len() * 64;
+        let end = to.min(limit);
+        if start >= end {

A mixed tracker can reach this with an empty dirty set. Its count is maintained on insert/remove, so this check skips scanning the whole bitset. The CPU measurements are in the review.

        if self.is_empty() || start >= end {
<!-- greyfinch-sync:Marvisak/VIctory:review-comment:4713744006 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3229#discussion_r4713744006). Originally posted by [Desamodeth](https://github.com/Desamodeth) on 2026-11-26T22:08:59Z. **Code review location:** `crates/victory-gpu/src/watch.rs`; line 122 ~~~~diff @@ -43,10 +43,207 @@ use std::sync::{Arc, Mutex}; /// they saved. pub(crate) const PAGE: usize = 64 << 10; +/// Dense bitset of changed 64 KiB pages for a [`Tracked`] range `[base, base + words.len() * 64)`. +struct PageBits { + base: usize, + words: Box<[u64]>, + count: usize, +} + +impl PageBits { + fn from_pages(start_page: usize, end_page: usize, pages: &[usize]) -> Self { + let len = end_page.saturating_sub(start_page).div_ceil(64); + let mut bits = Self { + base: start_page, + words: vec![0u64; len].into_boxed_slice(), + count: 0, + }; + for &p in pages { + bits.insert(p); + } + bits + } + + fn insert(&mut self, page: usize) -> bool { + let Some(rel) = page.checked_sub(self.base) else { + return false; + }; + let word = rel / 64; + let Some(slot) = self.words.get_mut(word) else { + return false; + }; + let mask = 1u64 << (rel % 64); + if *slot & mask == 0 { + *slot |= mask; + self.count += 1; + true + } else { + false + } + } + + fn remove(&mut self, page: usize) -> bool { + let Some(rel) = page.checked_sub(self.base) else { + return false; + }; + let word = rel / 64; + let Some(slot) = self.words.get_mut(word) else { + return false; + }; + let mask = 1u64 << (rel % 64); + if *slot & mask != 0 { + *slot &= !mask; + self.count -= 1; + true + } else { + false + } + } + + fn contains(&self, page: usize) -> bool { + let Some(rel) = page.checked_sub(self.base) else { + return false; + }; + let word = rel / 64; + self.words + .get(word) + .is_some_and(|&w| w & (1u64 << (rel % 64)) != 0) + } + + fn is_empty(&self) -> bool { + self.count == 0 + } + + fn range_pages(&self, from: usize, to: usize) -> Vec<usize> { + let mut out = Vec::new(); + let start = from.max(self.base); + let limit = self.base + self.words.len() * 64; + let end = to.min(limit); + if start >= end { ~~~~ --- A mixed tracker can reach this with an empty dirty set. Its count is maintained on insert/remove, so this check skips scanning the whole bitset. The CPU measurements are in the review. ```suggestion if self.is_empty() || start >= end { ```
Desamodeth commented 2026-11-26 22:08:59 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Desamodeth on 2026-11-26T22:08:59Z.

Review: COMMENTED


Measured the dirty-page index on Windows x64 at e3194263 versus main@63bcca43. For a 1 GiB span (16,384 console pages), a fully dirty index retained 167,064 B on main and 2,048 B here. Reading the whole dirty set took 11.9–12.0 → 7.73–7.74 µs. With only one dirty page, the same query took 28 → 252–254 ns. A 64-page query around it took about 28 ns on both. Heap figures cover the dirty index only.

I suggest the empty-set check below. Mixed trackers have no clean bit and can still reach range_pages with zero dirty pages. With just the middle page eligible at registration, then removed, a full-span query took 9.8 ns on main, 223–224 ns here, and 8.9 ns with the check. The check also matched the tree oracle over 9,000 mutations and range queries.

I updated #3395 (31a5b6bd) to consume the borrowed aliases via .iter(). Both PRs together passed all 17 watch tests in default and diagnostics builds, and workspace Clippy in both configurations. The inline suggestion also passed both watch suites. CPU-only synthetic measurements on a Ryzen 7 9800X3D, rustc 1.98.1 release, two runs of 12 interleaved batches including the dirty-set lock and result vector. AI-assisted with Codex Astra 6.2 High.

<!-- greyfinch-sync:Marvisak/VIctory:review:6081004102 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3229#pullrequestreview-6081004102). Originally posted by [Desamodeth](https://github.com/Desamodeth) on 2026-11-26T22:08:59Z. **Review:** COMMENTED --- Measured the dirty-page index on Windows x64 at `e3194263` versus `main@63bcca43`. For a 1 GiB span (16,384 console pages), a fully dirty index retained 167,064 B on main and 2,048 B here. Reading the whole dirty set took 11.9–12.0 → 7.73–7.74 µs. With only one dirty page, the same query took 28 → 252–254 ns. A 64-page query around it took about 28 ns on both. Heap figures cover the dirty index only. I suggest the empty-set check below. Mixed trackers have no clean bit and can still reach `range_pages` with zero dirty pages. With just the middle page eligible at registration, then removed, a full-span query took 9.8 ns on main, 223–224 ns here, and 8.9 ns with the check. The check also matched the tree oracle over 9,000 mutations and range queries. I updated #3395 (`31a5b6bd`) to consume the borrowed aliases via `.iter()`. Both PRs together passed all 17 watch tests in default and diagnostics builds, and workspace Clippy in both configurations. The inline suggestion also passed both watch suites. CPU-only synthetic measurements on a Ryzen 7 9800X3D, rustc 1.98.1 release, two runs of 12 interleaved batches including the dirty-set lock and result vector. AI-assisted with Codex Astra 6.2 High.
Jackster commented 2026-11-26 22:52:28 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Jackster on 2026-11-26T22:52:28Z.


Windows 11, 63bcca4 + this PR, Radeon RX 7900 XTX:

  • cargo test -p victory-gpu --lib: 233 passed / 0 failed / 1 ignored (unpatched 63bcca4 here: 231 passed; +2).
  • cargo clippy -p victory-gpu --all-targets -- -D warnings: clean.

The two added tests are watch::tests::page_bits_tracks_multi_word_ranges and watch::tests::one_or_many_spills_and_collapses, both passing, and the watch/eviction tests that use runtime_pages are unchanged. Synthetic only. AI-assisted.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7205058773 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3229#issuecomment-7205058773). Originally posted by [Jackster](https://github.com/Jackster) on 2026-11-26T22:52:28Z. --- Windows 11, `63bcca4` + this PR, Radeon RX 7900 XTX: - `cargo test -p victory-gpu --lib`: 233 passed / 0 failed / 1 ignored (unpatched `63bcca4` here: 231 passed; +2). - `cargo clippy -p victory-gpu --all-targets -- -D warnings`: clean. The two added tests are `watch::tests::page_bits_tracks_multi_word_ranges` and `watch::tests::one_or_many_spills_and_collapses`, both passing, and the watch/eviction tests that use `runtime_pages` are unchanged. Synthetic only. AI-assisted.
0xKaji commented 2026-11-26 22:55:10 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by 0xKaji on 2026-11-26T22:55:10Z.


Thanks for the benchmark and review! Applied your self.is_empty() fast-path suggestion in PageBits::range_pages and re-verified with workspace clippy (-D warnings) and all 17 watch::tests.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7205097701 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3229#issuecomment-7205097701). Originally posted by [0xKaji](https://github.com/0xKaji) on 2026-11-26T22:55:10Z. --- Thanks for the benchmark and review! Applied your `self.is_empty()` fast-path suggestion in `PageBits::range_pages` and re-verified with workspace clippy (`-D warnings`) and all 17 `watch::tests`.
fuzeofficlal commented 2026-11-27 00:00:01 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by fuzeofficlal on 2026-11-27T00:00:01Z.

Review: APPROVED


Looks good — clean, safe replacement of per-tracker BTreeSet<usize> and per-page Vec allocations with dense PageBits and inline OneOrMany storage.

Checked crates/victory-gpu/src/watch.rs:52-246 and every call site (track_as, Drop for Tracked, take, taken, changed, disarm, mark_changed, title_memory_remapped, title_memory_aliased):

  • PageBits maintains count accurately across duplicate inserts/removes, short-circuits range_pages when empty or out of bounds, and handles single-word, cross-word, and exact 64-page-aligned boundaries cleanly (and base <= usize::MAX >> 16 keeps base + words.len() * 64 overflow-free on 64-bit).
  • OneOrMany + map_push/map_retain spill cleanly from inline One to Many, collapse back to One when reduced to a single element, remove empty map keys, and preserve alias deduplication in title_memory_aliased.
  • disarm() trims oversized armed/bytes capacities cleanly without changing semantics.

Verification (f992d7f3):

  • cargo xtask policy and cargo clippy -p victory-gpu (default and --features diagnostics, --tests -- -D warnings): passed.
  • watch::tests:: (17/17): passed on both hardware GPU and WARP (--features diagnostics, VICTORY_D3D12_DEBUG=1).
  • Randomized differential oracle test comparing PageBits against BTreeSet<usize> across 70 (base, span) boundary configurations (including (usize::MAX >> 16) - 300, spans 0/1/2/63/64/65/127/128/129/260, and to = usize::MAX, 80 ops each) and OneOrMany + map_push/map_retain against BTreeMap<usize, Vec<u32>> (5,000 ops): zero divergences.
<!-- greyfinch-sync:Marvisak/VIctory:review:6081794786 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3229#pullrequestreview-6081794786). Originally posted by [fuzeofficlal](https://github.com/fuzeofficlal) on 2026-11-27T00:00:01Z. **Review:** APPROVED --- Looks good — clean, safe replacement of per-tracker `BTreeSet<usize>` and per-page `Vec` allocations with dense `PageBits` and inline `OneOrMany` storage. Checked `crates/victory-gpu/src/watch.rs:52-246` and every call site (`track_as`, `Drop for Tracked`, `take`, `taken`, `changed`, `disarm`, `mark_changed`, `title_memory_remapped`, `title_memory_aliased`): - `PageBits` maintains `count` accurately across duplicate inserts/removes, short-circuits `range_pages` when empty or out of bounds, and handles single-word, cross-word, and exact 64-page-aligned boundaries cleanly (and `base <= usize::MAX >> 16` keeps `base + words.len() * 64` overflow-free on 64-bit). - `OneOrMany` + `map_push`/`map_retain` spill cleanly from inline `One` to `Many`, collapse back to `One` when reduced to a single element, remove empty map keys, and preserve alias deduplication in `title_memory_aliased`. - `disarm()` trims oversized `armed`/`bytes` capacities cleanly without changing semantics. Verification (`f992d7f3`): - `cargo xtask policy` and `cargo clippy -p victory-gpu` (default and `--features diagnostics`, `--tests -- -D warnings`): passed. - `watch::tests::` (17/17): passed on both hardware GPU and WARP (`--features diagnostics`, `VICTORY_D3D12_DEBUG=1`). - Randomized differential oracle test comparing `PageBits` against `BTreeSet<usize>` across 70 `(base, span)` boundary configurations (including `(usize::MAX >> 16) - 300`, spans `0/1/2/63/64/65/127/128/129/260`, and `to = usize::MAX`, 80 ops each) and `OneOrMany` + `map_push`/`map_retain` against `BTreeMap<usize, Vec<u32>>` (5,000 ops): zero divergences.
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/3229:upstream-pr/3229'
git switch 'upstream-pr/3229'

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/3229'
git switch 'upstream-pr/3229'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3229'
git switch 'upstream-pr/3229'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3229'
git switch 'main'
git merge --squash 'upstream-pr/3229'
git switch 'main'
git merge --ff-only 'upstream-pr/3229'
git switch 'main'
git merge 'upstream-pr/3229'
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!3227
No description provided.