GPU: batch dirty heap page ranges under one diff pass in sync_heaps #3137

Open
MeMako wants to merge 3 commits from upstream-pr/3139 into main
MeMako commented 2026-11-26 09:55:41 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by MeMako on 2026-11-26T09:55:41Z.


Part 1 of the triage-requested 3-part split of #3055: batches dirty 64 KiB heap page ranges, pre-reads mapped pages via read_into into a reusable buffer before locking, and diffs all dirty slot ranges under one self.made -> VIEWS lock with zero thread changes. Part 2 (batched buffer lookup via find_existing_batch / PreparedBuffer) will be opened once Part 1 lands, and #3055 stays as a Draft for Part 3 (parallel sync via crate::texture::in_parallel).

Problem

In descriptor::sync_heaps(), each dirty 64 KiB heap page calls HostHeap::sync_slots individually. Every page allocates three temporary Vecs (records, current, stale), locks VIEWS and self.made separately, and checks VIEWS even for empty unchanged slots (tag != VIEW_TAG && made == 0).

Fix

  • crates/victory-gpu/src/descriptor.rs:
    • Collects dirty slot ranges for a heap in sync_heaps() and passes them in one call to HostHeap::sync_ranges, adding the returned readable slot count to SyncSlots under diagnostics.
    • Replaces views_current(&[[u32; 3]]) -> Vec<bool> with with_views(|views| ...), avoiding the per-page Vec<bool> allocation.
  • crates/victory-gpu/src/descriptor/host.rs:
    • Adds merge_ranges(ranges, cap) to clamp, sort, and merge overlapping/adjacent ranges once (preserving the capped-heap warning via past_cap.max(last - 1)).
    • Adds HostHeap::sync_ranges(&self, ranges: &[(u32, u32)], start: u64, step: u64) -> u64 (keeping sync_slots under #[cfg(test)] as a 1-line wrapper).
    • Pre-reads each mapped 64 KiB page chunk into a reusable buffer via crate::host::read_into before taking any locks (closing the probe-to-read concurrent-unmap window and removing unsafe reads from sync_ranges), then holds self.made -> VIEWS (same lock order as mirror) across the pure in-memory diff pass while skipping the VIEWS lookup for slots with tag != VIEW_TAG.
    • Mirrors stale slots serially via the existing HostHeap::mirror path with no thread changes.
    • Adds unit tests merge_ranges_sorts_clamps_and_merges_adjacent_and_overlapping and sync_ranges_merges_overlapping_and_out_of_order_ranges.

Verification & Benchmarks

Host: Windows 11 (10.0.26200), AMD Ryzen 9 7950X, AMD Radeon RX 9070 XT (RDNA 4, driver 32.0.32029.2010), base main 63bcca4.

  • cargo clippy --workspace --all-targets --locked -- -D warnings: clean.
  • cargo clippy --workspace --all-targets --all-features --locked -- -D warnings: clean.
  • cargo test -p victory-gpu --lib --locked -- --test-threads=1: 233 passed, 0 failed, 1 ignored (including merge_ranges_sorts_clamps_and_merges_adjacent_and_overlapping and sync_ranges_merges_overlapping_and_out_of_order_ranges).
  • cargo run --locked -p xtask -- policy: asset policy: 191 files ok.

Standalone benchmark (--release, world_frame_sync_heaps on Draft #3055, 700,416 slots across 342 dirty 64 KiB pages, 9-round medians, main vs. Part 1 alone):

Case main (63bcca4) median Part 1 (24618c9) median Speedup
Scan-only (0 changed / 700k scanned) 1.48 ms 0.61 ms 2.43x
Typical (6,000 changed / 700k scanned) 5.80 ms 4.60 ms 1.26x
Heavy (14,000 changed / 700k scanned) 10.32 ms 9.26 ms 1.11x

Hardware runs and tests were performed by me on my 7950X / RX 9070 XT; PR and code drafted with Antigravity.

<!-- greyfinch-sync:Marvisak/VIctory:issue:5507816532 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3139). Originally posted by [MeMako](https://github.com/MeMako) on 2026-11-26T09:55:41Z. --- Part 1 of the triage-requested 3-part split of #3055: batches dirty 64 KiB heap page ranges, pre-reads mapped pages via `read_into` into a reusable buffer before locking, and diffs all dirty slot ranges under one `self.made` -> `VIEWS` lock with **zero thread changes**. Part 2 (batched buffer lookup via `find_existing_batch` / `PreparedBuffer`) will be opened once Part 1 lands, and #3055 stays as a Draft for Part 3 (parallel sync via `crate::texture::in_parallel`). ## Problem In `descriptor::sync_heaps()`, each dirty 64 KiB heap page calls `HostHeap::sync_slots` individually. Every page allocates three temporary `Vec`s (`records`, `current`, `stale`), locks `VIEWS` and `self.made` separately, and checks `VIEWS` even for empty unchanged slots (`tag != VIEW_TAG && made == 0`). ## Fix - **`crates/victory-gpu/src/descriptor.rs`**: - Collects dirty slot ranges for a heap in `sync_heaps()` and passes them in one call to `HostHeap::sync_ranges`, adding the returned readable slot count to `SyncSlots` under `diagnostics`. - Replaces `views_current(&[[u32; 3]]) -> Vec<bool>` with `with_views(|views| ...)`, avoiding the per-page `Vec<bool>` allocation. - **`crates/victory-gpu/src/descriptor/host.rs`**: - Adds `merge_ranges(ranges, cap)` to clamp, sort, and merge overlapping/adjacent ranges once (preserving the capped-heap warning via `past_cap.max(last - 1)`). - Adds `HostHeap::sync_ranges(&self, ranges: &[(u32, u32)], start: u64, step: u64) -> u64` (keeping `sync_slots` under `#[cfg(test)]` as a 1-line wrapper). - Pre-reads each mapped 64 KiB page chunk into a reusable buffer via `crate::host::read_into` **before** taking any locks (closing the probe-to-read concurrent-unmap window and removing `unsafe` reads from `sync_ranges`), then holds `self.made` -> `VIEWS` (same lock order as `mirror`) across the pure in-memory diff pass while skipping the `VIEWS` lookup for slots with `tag != VIEW_TAG`. - Mirrors stale slots serially via the existing `HostHeap::mirror` path with no thread changes. - Adds unit tests `merge_ranges_sorts_clamps_and_merges_adjacent_and_overlapping` and `sync_ranges_merges_overlapping_and_out_of_order_ranges`. ## Verification & Benchmarks **Host:** Windows 11 (`10.0.26200`), AMD Ryzen 9 7950X, AMD Radeon RX 9070 XT (RDNA 4, driver `32.0.32029.2010`), base `main` `63bcca4`. - `cargo clippy --workspace --all-targets --locked -- -D warnings`: clean. - `cargo clippy --workspace --all-targets --all-features --locked -- -D warnings`: clean. - `cargo test -p victory-gpu --lib --locked -- --test-threads=1`: **233 passed, 0 failed, 1 ignored** (including `merge_ranges_sorts_clamps_and_merges_adjacent_and_overlapping` and `sync_ranges_merges_overlapping_and_out_of_order_ranges`). - `cargo run --locked -p xtask -- policy`: `asset policy: 191 files ok`. **Standalone benchmark (`--release`, `world_frame_sync_heaps` on Draft #3055, 700,416 slots across 342 dirty 64 KiB pages, 9-round medians, `main` vs. Part 1 alone):** | Case | `main` (`63bcca4`) median | Part 1 (`24618c9`) median | Speedup | |---|---:|---:|---:| | Scan-only (`0` changed / 700k scanned) | 1.48 ms | **0.61 ms** | **2.43x** | | Typical (`6,000` changed / 700k scanned) | 5.80 ms | **4.60 ms** | **1.26x** | | Heavy (`14,000` changed / 700k scanned) | 10.32 ms | **9.26 ms** | **1.11x** | *Hardware runs and tests were performed by me on my 7950X / RX 9070 XT; PR and code drafted with Antigravity.*
Dukestar69 commented 2026-11-26 12:29:44 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Dukestar69 on 2026-11-26T12:29:44Z.

Review: APPROVED


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

  • cargo test -p victory-gpu --lib descriptor:: -- --test-threads=1 --skip dynamic_slots_are_held_until_released: 22/22 passed (including sync_ranges_merges_overlapping_and_out_of_order_ranges).
  • cargo clippy -p victory-gpu --all-targets -- -D warnings: clean.
  • cargo xtask policy: 191 files ok.

Cleanly batches dirty heap page ranges under one diff pass in sync_heaps.

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

<!-- greyfinch-sync:Marvisak/VIctory:review:6074140947 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3139#pullrequestreview-6074140947). Originally posted by [Dukestar69](https://github.com/Dukestar69) on 2026-11-26T12:29:44Z. **Review:** APPROVED --- Verified on RTX 5090 against `origin/main` (`63bcca4`): - `cargo test -p victory-gpu --lib descriptor:: -- --test-threads=1 --skip dynamic_slots_are_held_until_released`: 22/22 passed (including `sync_ranges_merges_overlapping_and_out_of_order_ranges`). - `cargo clippy -p victory-gpu --all-targets -- -D warnings`: clean. - `cargo xtask policy`: 191 files ok. Cleanly batches dirty heap page ranges under one diff pass in `sync_heaps`. Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).
Jackster commented 2026-11-26 13:04:27 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Jackster on 2026-11-26T12:15:34Z.


On the retail title the batch does not move it, and the time is in view creation, not the scan

Same setup as my note on #2821 (Windows 11, RX 7900 XTX, 300 s world runs, same save, same cache). stack2 = 63bcca4 + #2703 #1010 #2985 #2849 #2908 #2472 #2958 #3118 #2821, with and without this PR merged in:

stack2 + this PR
descriptor sync 261.3 ms 239.1 ms
slots mirrored 316,757 394,581
page faults/frame 138,976 249,888
frame (median) 994 ms 1,263 ms

-8% on the sync, not the 2.43x the scan benchmark suggests: that gain needs many unchanged slots to skip, and in the world nearly every slot looked at has changed, so there is little to skip. The frame coming out lower I put down to scene spread in a single run.

What the sync is doing, from counters I added to HostHeap::mirror (~400k slots examined a frame):

  • 47k views made: 3.3k textures, 1.9k buffer shader resources, 8.0k buffer unordered views, ~34k constant-buffer and placed-memory views
  • 54k already current, 17-21k nulled
  • ~274k records examined that are not views of ours

So the cost is the ~47k Create*View calls, not the per-page scan this PR batches.

For scale, deferring the read-only ones (constant buffers, buffer shader resources, non-UAV memory views) to the submission that first reads them took the sync from 261 ms to 126-151 ms and the frame from 1,025 ms to 859-880 ms at the same draw count. That prototype is not correct yet: a skipped slot keeps its previous descriptor, and constant-buffer slots have no read mark to bring them back (the tree marks texture reads; a local change also marks buffer loads; CBVs are the gap).

Suggestion: a "changed vs unchanged" line in the benchmark would predict which titles gain from the batch.

Written with an AI assistant.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7191771681 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3139#issuecomment-7191771681). Originally posted by [Jackster](https://github.com/Jackster) on 2026-11-26T12:15:34Z. --- **On the retail title the batch does not move it, and the time is in view creation, not the scan** Same setup as my note on #2821 (Windows 11, RX 7900 XTX, 300 s world runs, same save, same cache). `stack2` = `63bcca4` + #2703 #1010 #2985 #2849 #2908 #2472 #2958 #3118 #2821, with and without this PR merged in: | | stack2 | + this PR | |---|---|---| | descriptor sync | 261.3 ms | 239.1 ms | | slots mirrored | 316,757 | 394,581 | | page faults/frame | 138,976 | 249,888 | | frame (median) | 994 ms | 1,263 ms | -8% on the sync, not the 2.43x the scan benchmark suggests: that gain needs many *unchanged* slots to skip, and in the world nearly every slot looked at has changed, so there is little to skip. The frame coming out lower I put down to scene spread in a single run. What the sync is doing, from counters I added to `HostHeap::mirror` (~400k slots examined a frame): - 47k views made: 3.3k textures, 1.9k buffer shader resources, 8.0k buffer unordered views, ~34k constant-buffer and placed-memory views - 54k already current, 17-21k nulled - ~274k records examined that are not views of ours So the cost is the ~47k `Create*View` calls, not the per-page scan this PR batches. For scale, deferring the read-only ones (constant buffers, buffer shader resources, non-UAV memory views) to the submission that first reads them took the sync from 261 ms to 126-151 ms and the frame from 1,025 ms to 859-880 ms at the same draw count. That prototype is not correct yet: a skipped slot keeps its previous descriptor, and constant-buffer slots have no read mark to bring them back (the tree marks texture reads; a local change also marks buffer loads; CBVs are the gap). Suggestion: a "changed vs unchanged" line in the benchmark would predict which titles gain from the batch. Written with an AI assistant.
MeMako commented 2026-11-26 13:04:30 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by MeMako on 2026-11-26T12:28:05Z.


Thanks for running this on a real world trace and breaking down the HostHeap::mirror counters — super helpful data!

A few notes on those numbers:

  1. Even with +25% more mirrored slots in the + #3139 run (316,757 -> 394,581, likely scene spread as you noted), descriptor sync still dropped 261.3 -> 239.1 ms (0.825 -> 0.606 us per mirrored slot, -26.5%), which lines up with the heavier-change end of our standalone benchmark table (14k / 700k -> 1.11x).
  2. Good suggestion on the churn ratio — our table currently covers three ratios (0, 6k, and 14k changed out of 700k slots), and adding a higher-churn row (~12% changed, matching your ~47k / 400k ratio) makes sense so readers can see where Part 1's scan/diff speedup tapers off.
  3. Your ~47k Create*View breakdown is spot-on and is exactly why #3055 was split into three parts: Part 1 (#3139) cleans up the sync_heaps scan/diff half (eliminating per-page allocations/locks and skipping empty unchanged slots), while Part 2 (pr/sync-heaps-2-batched-buffers, queued behind this) batches the BUFFERS lookup for buffer/CBV/placed-memory views, and Part 3 (Draft #3055) parallelizes Create*View across workers via crate::texture::in_parallel. Deferring read-only views to first use would also stack nicely on top of all three once CBV read-marking is solved.

Comment drafted with Antigravity.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7192039099 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3139#issuecomment-7192039099). Originally posted by [MeMako](https://github.com/MeMako) on 2026-11-26T12:28:05Z. --- Thanks for running this on a real world trace and breaking down the `HostHeap::mirror` counters — super helpful data! A few notes on those numbers: 1. Even with +25% more mirrored slots in the `+ #3139` run (`316,757 -> 394,581`, likely scene spread as you noted), descriptor sync still dropped `261.3 -> 239.1 ms` (`0.825 -> 0.606 us` per mirrored slot, `-26.5%`), which lines up with the heavier-change end of our standalone benchmark table (`14k / 700k` -> `1.11x`). 2. Good suggestion on the churn ratio — our table currently covers three ratios (`0`, `6k`, and `14k` changed out of `700k` slots), and adding a higher-churn row (~12% changed, matching your ~47k / 400k ratio) makes sense so readers can see where Part 1's scan/diff speedup tapers off. 3. Your ~47k `Create*View` breakdown is spot-on and is exactly why `#3055` was split into three parts: Part 1 (`#3139`) cleans up the `sync_heaps` scan/diff half (eliminating per-page allocations/locks and skipping empty unchanged slots), while **Part 2** (`pr/sync-heaps-2-batched-buffers`, queued behind this) batches the `BUFFERS` lookup for buffer/CBV/placed-memory views, and **Part 3** (Draft `#3055`) parallelizes `Create*View` across workers via `crate::texture::in_parallel`. Deferring read-only views to first use would also stack nicely on top of all three once CBV read-marking is solved. *Comment drafted with Antigravity.*
Jackster commented 2026-11-26 15:02:26 +00:00 (Migrated from github.com)

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


Follow-up: with the read marks in place, the deferral does not hold up

When I wrote the note above I had only the upper bound: skipping read-only slots without making them later. With the translator now marking buffer and constant-buffer heap reads, the host makes a marked slot after the submission that read it, and the saving largely disappears:

stack2 defer, no marks (upper bound) defer + marks
descriptor sync 261 ms 126-151 ms 129 ms
frame (tail) 1,025 ms 859-880 ms 976-997 ms
draws / dropped 2,172 / 637 2,164 / 629 2,134 / 642

-4%, not -25%. The work moves rather than disappearing: the frame needs ~32k distinct views either way, and deferring them only decides when they are made.

One correction to my earlier note that may save someone time: a heap constant buffer is not a kind-13 handle. Shaders read one as a raw buffer view (kind 11, emit/mod.rs "Constant buffers in the heap"), which is why the read-only raw kinds had to be let into the index map (heap_handle) before anything downstream could mark them.

So for this PR's premise: batching helps only stale-heavy workloads (measured: not this one), and deferral helps only if the slots are never made at all (they are). What is left is the number and cost of the views a frame genuinely needs.

Written with an AI assistant.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7194277382 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3139#issuecomment-7194277382). Originally posted by [Jackster](https://github.com/Jackster) on 2026-11-26T14:06:04Z. --- **Follow-up: with the read marks in place, the deferral does not hold up** When I wrote the note above I had only the upper bound: skipping read-only slots without making them later. With the translator now marking buffer and constant-buffer heap reads, the host makes a marked slot after the submission that read it, and the saving largely disappears: | | stack2 | defer, no marks (upper bound) | defer + marks | |---|---|---|---| | descriptor sync | 261 ms | 126-151 ms | 129 ms | | frame (tail) | 1,025 ms | 859-880 ms | 976-997 ms | | draws / dropped | 2,172 / 637 | 2,164 / 629 | 2,134 / 642 | -4%, not -25%. The work moves rather than disappearing: the frame needs ~32k distinct views either way, and deferring them only decides *when* they are made. One correction to my earlier note that may save someone time: a heap constant buffer is not a kind-13 handle. Shaders read one as a **raw buffer view** (kind 11, `emit/mod.rs` "Constant buffers in the heap"), which is why the read-only raw kinds had to be let into the index map (`heap_handle`) before anything downstream could mark them. So for this PR's premise: batching helps only stale-heavy workloads (measured: not this one), and deferral helps only if the slots are never made at all (they are). What is left is the number and cost of the views a frame genuinely needs. Written with an AI assistant.
MeMako commented 2026-11-26 16:05:01 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by MeMako on 2026-11-26T15:06:51Z.


Thanks for the follow-up test — that's a really useful result, and the raw-view (kind 11) note on heap CBVs is great to have documented too.

Ruling out deferral actually lines up directly with why this work was split into three parts per triage feedback on #3055: Part 1 (#3139) is intentionally just the zero-risk structural layer (collapsing the per-page loops into one deduplicated stale batch with no threading or lock-scope changes), not the full fix for those 261 ms. Since a frame genuinely needs those ~32k–47k views created either way, the bigger wins sit in Part 2 (batched BUFFERS lookup) and Part 3 (parallel Create*View across workers).

Draft #3055 already has all three parts stacked together if you ever feel like throwing it on stack2 to see how much of the 261 ms moves once per-view lookup and view creation are batched and parallelized.

Comment drafted with Antigravity.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7195801225 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3139#issuecomment-7195801225). Originally posted by [MeMako](https://github.com/MeMako) on 2026-11-26T15:06:51Z. --- Thanks for the follow-up test — that's a really useful result, and the raw-view (kind 11) note on heap CBVs is great to have documented too. Ruling out deferral actually lines up directly with why this work was split into three parts per triage feedback on `#3055`: Part 1 (`#3139`) is intentionally just the zero-risk structural layer (collapsing the per-page loops into one deduplicated `stale` batch with no threading or lock-scope changes), not the full fix for those 261 ms. Since a frame genuinely needs those ~32k–47k views created either way, the bigger wins sit in **Part 2** (batched `BUFFERS` lookup) and **Part 3** (parallel `Create*View` across workers). Draft `#3055` already has all three parts stacked together if you ever feel like throwing it on `stack2` to see how much of the 261 ms moves once per-view lookup and view creation are batched and parallelized. *Comment drafted with Antigravity.*
imjustprism commented 2026-11-26 18:31:22 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by imjustprism on 2026-11-26T18:31:22Z.

Review: COMMENTED


ran 24618c9 in the title and read the diff. rx 9070 xt, world, medians per frame:

per frame without, 5 runs with this pr, 1 run
heap sync (sync_heaps), ms 10.6 to 14.3 12.1
slots scanned 308,000 to 369,000 333,000

63bcca4 plus #2122 (this card needs it) plus a local timer around sync_heaps. two of the five runs without are plain; the other three have #2051 merged in, which does not touch this path. diag build, series-x, the same scripted key presses, warm shader and pipeline caches, quiet machine, 12-minute runs, medians over 47 to 74 world frame lines per run. no errors and no device removed. one run with the pr, so all i can say is: no change i can measure here. that fits your own table: at 1.48 ms per 700,000 unchanged slots on main, the scan is under 1 ms of the 12 ms here (an estimate from your figure, not a measurement), so the batch can save a few tenths of a millisecond at most. the rest is making the slots that changed, as the comments above found.

what i checked from the description:

  • sync_ranges_merges_overlapping_and_out_of_order_ranges and the other descriptor::host tests pass here.
  • "zero thread changes": yes, nothing starts a thread.
  • the benchmark table: the benchmark is not in the diff, so i could not run it.
  • "zero lock-scope changes": the code does change it, see the first point.

points from reading the diff:

  • lock scope, descriptor/host.rs:731 and :732. on main each 64 KiB page read its records with no lock, then took VIEWS alone, let it go, and took made alone. now made and VIEWS are held together across every range of the heap, with the reads of title memory inside (host.rs:737). the order is the one mirror already uses (host.rs:790), so nothing can deadlock. but a title thread that records a view (descriptor.rs:504) or releases a resource (descriptor.rs:535) takes VIEWS without SHADER_HEAPS: on main it could get in between two pages, now it waits for the whole heap. the hold is short, about your scan time, and i did not measure the wait. either the description and the doc on sync_ranges should say so (the doc also says it skips VIEWS for empty slots, while VIEWS stays locked and only the lookup is skipped), or the records can be read into a buffer before the locks are taken, which keeps the old scope.
  • a question on the probe, descriptor.rs:189. each page is probed with a 4-byte read and its records are read later with plain reads. on main the read came right after the probe of that page. now it comes after all pages are probed, two sorts, and the waits for both locks. the comment there says the title unmaps heap pages; if it can do that while another thread submits, the window for a fault is wider than it was. the race itself is older than this pr. do you know whether that can happen? reading each range with read_into before the locks would close it, and it is the same change as above.
  • the new test passes with the sort and the merge taken out of sync_ranges (i ran it that way: 1 passed), because a slot that is listed twice is mirrored twice with the same result. so it pins the result but not the merging. its doc says "adjacent", and no two of its ranges touch; (0, 16), (16, 32) would cover that.
  • the ranges are sorted and merged in sync_heaps (descriptor.rs:202) and again in sync_ranges (host.rs:722), after Tracked::take already sorted its runs (watch.rs:464). sync_heaps is the only caller outside tests, so one of the two is enough.

nothing here is a wrong result: each slot's stale decision matches main, the clamp to count holds, and last - 1 runs only when last is above count.

<!-- greyfinch-sync:Marvisak/VIctory:review:6079009842 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3139#pullrequestreview-6079009842). Originally posted by [imjustprism](https://github.com/imjustprism) on 2026-11-26T18:31:22Z. **Review:** COMMENTED --- ran 24618c9 in the title and read the diff. rx 9070 xt, world, medians per frame: | per frame | without, 5 runs | with this pr, 1 run | |---|---|---| | heap sync (`sync_heaps`), ms | 10.6 to 14.3 | 12.1 | | slots scanned | 308,000 to 369,000 | 333,000 | 63bcca4 plus #2122 (this card needs it) plus a local timer around `sync_heaps`. two of the five runs without are plain; the other three have #2051 merged in, which does not touch this path. diag build, series-x, the same scripted key presses, warm shader and pipeline caches, quiet machine, 12-minute runs, medians over 47 to 74 world frame lines per run. no errors and no device removed. one run with the pr, so all i can say is: no change i can measure here. that fits your own table: at 1.48 ms per 700,000 unchanged slots on main, the scan is under 1 ms of the 12 ms here (an estimate from your figure, not a measurement), so the batch can save a few tenths of a millisecond at most. the rest is making the slots that changed, as the comments above found. what i checked from the description: - `sync_ranges_merges_overlapping_and_out_of_order_ranges` and the other `descriptor::host` tests pass here. - "zero thread changes": yes, nothing starts a thread. - the benchmark table: the benchmark is not in the diff, so i could not run it. - "zero lock-scope changes": the code does change it, see the first point. points from reading the diff: - lock scope, `descriptor/host.rs:731` and `:732`. on main each 64 KiB page read its records with no lock, then took `VIEWS` alone, let it go, and took `made` alone. now `made` and `VIEWS` are held together across every range of the heap, with the reads of title memory inside (`host.rs:737`). the order is the one `mirror` already uses (`host.rs:790`), so nothing can deadlock. but a title thread that records a view (`descriptor.rs:504`) or releases a resource (`descriptor.rs:535`) takes `VIEWS` without `SHADER_HEAPS`: on main it could get in between two pages, now it waits for the whole heap. the hold is short, about your scan time, and i did not measure the wait. either the description and the doc on `sync_ranges` should say so (the doc also says it skips `VIEWS` for empty slots, while `VIEWS` stays locked and only the lookup is skipped), or the records can be read into a buffer before the locks are taken, which keeps the old scope. - a question on the probe, `descriptor.rs:189`. each page is probed with a 4-byte read and its records are read later with plain reads. on main the read came right after the probe of that page. now it comes after all pages are probed, two sorts, and the waits for both locks. the comment there says the title unmaps heap pages; if it can do that while another thread submits, the window for a fault is wider than it was. the race itself is older than this pr. do you know whether that can happen? reading each range with `read_into` before the locks would close it, and it is the same change as above. - the new test passes with the sort and the merge taken out of `sync_ranges` (i ran it that way: 1 passed), because a slot that is listed twice is mirrored twice with the same result. so it pins the result but not the merging. its doc says "adjacent", and no two of its ranges touch; `(0, 16), (16, 32)` would cover that. - the ranges are sorted and merged in `sync_heaps` (`descriptor.rs:202`) and again in `sync_ranges` (`host.rs:722`), after `Tracked::take` already sorted its runs (`watch.rs:464`). `sync_heaps` is the only caller outside tests, so one of the two is enough. nothing here is a wrong result: each slot's stale decision matches main, the clamp to `count` holds, and `last - 1` runs only when `last` is above `count`.
MeMako commented 2026-11-27 01:26:36 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by MeMako on 2026-11-27T01:26:36Z.


Thanks for the review and the 9070 XT run. Good catches all around, pushed fixes in f799496:

  • Probe-to-read race (descriptor.rs:189): Yes, SHADER_HEAPS only stops the Heap from being dropped, not another thread unmapping backing pages. Replaced the 4-byte probe + later plain reads with page-chunked read_into copies into a reusable buffer before taking any locks, which closes that window and removes the unsafe reads from sync_ranges.
  • Lock scope (descriptor/host.rs:731-732): With read_into moved out front, self.made and VIEWS are now only held across the pure in-memory diff. Updated the sync_ranges doc and PR description to state the actual lock scope and clarify that empty slots skip the VIEWS lookup, not the lock.
  • Double sort/merge: Consolidated into a single merge_ranges(ranges, cap) helper in descriptor/host.rs and dropped the duplicate pass in sync_heaps.
  • Tests: Added merge_ranges_sorts_clamps_and_merges_adjacent_and_overlapping with (0, 16), (16, 32) so removing the sort or merge actually fails, and added an adjacent pair to sync_ranges_merges_overlapping_and_out_of_order_ranges.

Re: the benchmark, world_frame_sync_heaps lives on Draft #3055 to keep this diff small.

Re-ran clippy (default + --all-features), victory-gpu lib tests (233 passed), and xtask policy on Win 11 / RX 9070 XT.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7207291570 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3139#issuecomment-7207291570). Originally posted by [MeMako](https://github.com/MeMako) on 2026-11-27T01:26:36Z. --- Thanks for the review and the 9070 XT run. Good catches all around, pushed fixes in `f799496`: - **Probe-to-read race (`descriptor.rs:189`):** Yes, `SHADER_HEAPS` only stops the `Heap` from being dropped, not another thread unmapping backing pages. Replaced the 4-byte probe + later plain reads with page-chunked `read_into` copies into a reusable buffer before taking any locks, which closes that window and removes the `unsafe` reads from `sync_ranges`. - **Lock scope (`descriptor/host.rs:731-732`):** With `read_into` moved out front, `self.made` and `VIEWS` are now only held across the pure in-memory diff. Updated the `sync_ranges` doc and PR description to state the actual lock scope and clarify that empty slots skip the `VIEWS` lookup, not the lock. - **Double sort/merge:** Consolidated into a single `merge_ranges(ranges, cap)` helper in `descriptor/host.rs` and dropped the duplicate pass in `sync_heaps`. - **Tests:** Added `merge_ranges_sorts_clamps_and_merges_adjacent_and_overlapping` with `(0, 16), (16, 32)` so removing the sort or merge actually fails, and added an adjacent pair to `sync_ranges_merges_overlapping_and_out_of_order_ranges`. Re: the benchmark, `world_frame_sync_heaps` lives on Draft `#3055` to keep this diff small. Re-ran `clippy` (default + `--all-features`), `victory-gpu` lib tests (233 passed), and `xtask policy` on Win 11 / RX 9070 XT.
AndyLatimer commented 2026-11-27 02:30:48 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by AndyLatimer on 2026-11-27T02:30:48Z.

Review: CHANGES_REQUESTED


Tested f799496 locally against origin/main (63bcca4, clean merge) on Windows 11, NVIDIA GeForce RTX 3060 Ti, Rust 1.98.1 MSVC. Two bugs found and reproduced with synthetic tests:

  1. sync_ranges drops committed 4 KiB OS pages inside partially uncommitted 64 KiB blocks (crates/victory-gpu/src/descriptor/host.rs):

    • sync_ranges reads each span once per watch::PAGE (64 KiB) via read_into. If a 64 KiB chunk contains a committed 4 KiB OS page followed by an uncommitted 4 KiB page, ReadProcessMemory fails for the entire 64 KiB read and skips mirroring valid descriptors on the committed 4 KiB page.
    • Reproduced on f799496 with sync_ranges_mirrors_committed_4k_page_beside_uncommitted_page (1 committed 4 KiB page + uncommitted remainder in a 64 KiB reservation): sync_ranges returned 0 scanned slots (expected 128) and left slot 2 unmirrored.
    • Falling back to 4 KiB (4096) chunks only when the 64 KiB read_into fails preserves the normal 64 KiB fast path while mirroring committed 4 KiB pages.
  2. merge_ranges records past_cap on empty or inverted ranges (crates/victory-gpu/src/descriptor/host.rs):

    • if last > cap runs without checking first < last, so merge_ranges(&[(70, 70), (80, 75)], 64) returns ([], Some(74)) instead of ([], None) and triggers a spurious "title slot past the host heap" warning via self.mirror(highest, ...).
    • (Also worth noting: probing only at(highest) suppresses that diagnostic if a mapped past-cap range ends in an unmapped tail page.)

With the patch below applied on top of f799496:

  • Both new regression tests (sync_ranges_mirrors_committed_4k_page_beside_uncommitted_page and the merge_ranges empty/inverted case) fail on f799496 and pass with the patch.
  • cargo test -p victory-gpu --lib --locked descriptor:: -- --skip dynamic_slots_are_held_until_released --test-threads=1: 24 passed, 0 failed (skipping only the pre-existing NVIDIA 1M heap-cap failure).
  • cargo clippy -p victory-gpu --all-targets --locked -- -D warnings (default and --all-features) and rustfmt --edition 2024 --check: clean.
Patch and regression tests against f799496
diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs
index 6be649d..9801b0f 100644
--- a/crates/victory-gpu/src/descriptor/host.rs
+++ b/crates/victory-gpu/src/descriptor/host.rs
@@ -718,9 +718,46 @@ impl HostHeap {
         }
         let total_slots: usize = clamped.iter().map(|&(a, b)| (b - a) as usize).sum();
         let page_size = crate::watch::PAGE as u64;
+        const OS_PAGE: u64 = 4096;
         let mut page_buf: Vec<u8> = Vec::new();
         let mut readable: Vec<(u32, u32)> = Vec::with_capacity(clamped.len());
         let mut records: Vec<[u32; 3]> = Vec::with_capacity(total_slots);
+        let mut read_span = |a: u32, b: u32| -> bool {
+            let addr = at(a);
+            let n = (b - a) as usize;
+            let bytes = (n - 1) * step as usize + 12;
+            if page_buf.len() < bytes {
+                page_buf.resize(bytes, 0);
+            }
+            if !crate::host::read_into(addr as *const u8, &mut page_buf[..bytes]) {
+                return false;
+            }
+            readable.push((a, b));
+            for k in 0..n {
+                let off = k * step as usize;
+                records.push([
+                    u32::from_ne_bytes([
+                        page_buf[off],
+                        page_buf[off + 1],
+                        page_buf[off + 2],
+                        page_buf[off + 3],
+                    ]),
+                    u32::from_ne_bytes([
+                        page_buf[off + 4],
+                        page_buf[off + 5],
+                        page_buf[off + 6],
+                        page_buf[off + 7],
+                    ]),
+                    u32::from_ne_bytes([
+                        page_buf[off + 8],
+                        page_buf[off + 9],
+                        page_buf[off + 10],
+                        page_buf[off + 11],
+                    ]),
+                ]);
+            }
+            true
+        };
         for &(first, last) in &clamped {
             let mut i = first;
             while i < last {
@@ -730,35 +767,17 @@ impl HostHeap {
                 // is not page-aligned and may straddle a page boundary).
                 let fit = ((next_page - addr) / step).max(1);
                 let j = last.min(i.saturating_add(fit as u32));
-                let n = (j - i) as usize;
-                let bytes = (n - 1) * step as usize + 12;
-                if page_buf.len() < bytes {
-                    page_buf.resize(bytes, 0);
-                }
-                if crate::host::read_into(addr as *const u8, &mut page_buf[..bytes]) {
-                    readable.push((i, j));
-                    for k in 0..n {
-                        let off = k * step as usize;
-                        records.push([
-                            u32::from_ne_bytes([
-                                page_buf[off],
-                                page_buf[off + 1],
-                                page_buf[off + 2],
-                                page_buf[off + 3],
-                            ]),
-                            u32::from_ne_bytes([
-                                page_buf[off + 4],
-                                page_buf[off + 5],
-                                page_buf[off + 6],
-                                page_buf[off + 7],
-                            ]),
-                            u32::from_ne_bytes([
-                                page_buf[off + 8],
-                                page_buf[off + 9],
-                                page_buf[off + 10],
-                                page_buf[off + 11],
-                            ]),
-                        ]);
+                if !read_span(i, j) {
+                    // A 64 KiB chunk may straddle committed and uncommitted 4 KiB
+                    // OS pages; retry per 4 KiB page so committed slots survive.
+                    let mut sub = i;
+                    while sub < j {
+                        let sub_addr = at(sub);
+                        let next_os = (sub_addr & !(OS_PAGE - 1)) + OS_PAGE;
+                        let sub_fit = ((next_os - sub_addr) / step).max(1);
+                        let sub_end = j.min(sub.saturating_add(sub_fit as u32));
+                        let _ = read_span(sub, sub_end);
+                        sub = sub_end;
                     }
                 }
                 i = j;
@@ -1918,7 +1937,7 @@ fn merge_ranges(ranges: &[(u32, u32)], cap: u32) -> (Vec<(u32, u32)>, Option<u32
     let mut past_cap: Option<u32> = None;
     let mut raw: Vec<(u32, u32)> = Vec::with_capacity(ranges.len());
     for &(first, last) in ranges {
-        if last > cap {
+        if first < last && last > cap {
             let high = last - 1;
             past_cap = Some(past_cap.map_or(high, |m| m.max(high)));
         }
@@ -2593,6 +2612,7 @@ mod tests {
             (vec![(0, 64)], Some(67))
         );
         assert_eq!(merge_ranges(&[(70, 80), (10, 10)], 64), (vec![], Some(79)));
+        assert_eq!(merge_ranges(&[(70, 70), (80, 75)], 64), (vec![], None));
     }
 
     /// `sync_ranges` merges overlapping, adjacent, and out-of-order ranges
@@ -2654,4 +2674,53 @@ mod tests {
         crate::shadow::unregister(pool, base);
         crate::watch::tests::free(pool);
     }
+
+    /// When a 64 KiB heap block has a committed 4 KiB page followed by an
+    /// uncommitted 4 KiB page, `sync_ranges` must still mirror the descriptors
+    /// on the committed 4 KiB page instead of dropping the whole 64 KiB chunk.
+    #[test]
+    fn sync_ranges_mirrors_committed_4k_page_beside_uncommitted_page() {
+        use windows_sys::Win32::System::Memory::{
+            MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree,
+        };
+        let Some(heap) = HostHeap::new(false, 256) else {
+            return;
+        };
+        assert!(heap.view_addresses().is_some());
+        let pool = crate::watch::tests::pool(1);
+        let base = pool as u64;
+        crate::shadow::register(pool, base, 64 << 10);
+
+        // SAFETY: reserve one 64 KiB page and commit only its first 4 KiB OS page.
+        let mem = unsafe {
+            VirtualAlloc(std::ptr::null(), crate::watch::PAGE, MEM_RESERVE, PAGE_READWRITE)
+        };
+        assert!(!mem.is_null());
+        // SAFETY: committing the first 4 KiB page inside our reservation.
+        let committed = unsafe { VirtualAlloc(mem, 4096, MEM_COMMIT, PAGE_READWRITE) };
+        assert_eq!(committed, mem);
+
+        let step = 32u64;
+        let start = mem as u64;
+        let mut resource = [0u32; 14];
+        (resource[0], resource[4]) = (1, 64);
+        let mut view = [0u32; 16];
+        (view[1], view[2], view[6], view[7]) =
+            (1, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, 16, 4);
+        (view[10], view[11]) = (base as u32, (base >> 32) as u32);
+        // Slot 2 lies in the committed first 4 KiB page; slots 128..256 lie in
+        // the uncommitted second 4 KiB page of the same 64 KiB watch::PAGE.
+        crate::descriptor::create_placed_srv(std::ptr::null(), &resource, &view, start + 2 * step);
+
+        let synced = heap.sync_ranges(&[(0, 256)], start, step);
+        let got = heap.address_at(2);
+
+        // SAFETY: releasing our reservation.
+        unsafe { VirtualFree(mem, 0, MEM_RELEASE) };
+        crate::shadow::unregister(pool, base);
+        crate::watch::tests::free(pool);
+
+        assert_eq!(synced, 128, "committed 4 KiB page slots should be scanned");
+        assert_eq!(got, Some(base), "descriptor on committed 4 KiB page must be mirrored");
+    }
 }

Synthetic tests only; AI-assisted review.

<!-- greyfinch-sync:Marvisak/VIctory:review:6082710458 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3139#pullrequestreview-6082710458). Originally posted by [AndyLatimer](https://github.com/AndyLatimer) on 2026-11-27T02:30:48Z. **Review:** CHANGES_REQUESTED --- Tested `f799496` locally against `origin/main` (`63bcca4`, clean merge) on Windows 11, NVIDIA GeForce RTX 3060 Ti, Rust 1.98.1 MSVC. Two bugs found and reproduced with synthetic tests: 1. **`sync_ranges` drops committed 4 KiB OS pages inside partially uncommitted 64 KiB blocks (`crates/victory-gpu/src/descriptor/host.rs`)**: - `sync_ranges` reads each span once per `watch::PAGE` (64 KiB) via `read_into`. If a 64 KiB chunk contains a committed 4 KiB OS page followed by an uncommitted 4 KiB page, `ReadProcessMemory` fails for the entire 64 KiB read and skips mirroring valid descriptors on the committed 4 KiB page. - Reproduced on `f799496` with `sync_ranges_mirrors_committed_4k_page_beside_uncommitted_page` (1 committed 4 KiB page + uncommitted remainder in a 64 KiB reservation): `sync_ranges` returned `0` scanned slots (expected `128`) and left slot 2 unmirrored. - Falling back to 4 KiB (`4096`) chunks **only when the 64 KiB `read_into` fails** preserves the normal 64 KiB fast path while mirroring committed 4 KiB pages. 2. **`merge_ranges` records `past_cap` on empty or inverted ranges (`crates/victory-gpu/src/descriptor/host.rs`)**: - `if last > cap` runs without checking `first < last`, so `merge_ranges(&[(70, 70), (80, 75)], 64)` returns `([], Some(74))` instead of `([], None)` and triggers a spurious `"title slot past the host heap"` warning via `self.mirror(highest, ...)`. - (Also worth noting: probing only `at(highest)` suppresses that diagnostic if a mapped past-cap range ends in an unmapped tail page.) With the patch below applied on top of `f799496`: - Both new regression tests (`sync_ranges_mirrors_committed_4k_page_beside_uncommitted_page` and the `merge_ranges` empty/inverted case) fail on `f799496` and pass with the patch. - `cargo test -p victory-gpu --lib --locked descriptor:: -- --skip dynamic_slots_are_held_until_released --test-threads=1`: **24 passed, 0 failed** (skipping only the pre-existing NVIDIA 1M heap-cap failure). - `cargo clippy -p victory-gpu --all-targets --locked -- -D warnings` (default and `--all-features`) and `rustfmt --edition 2024 --check`: **clean**. <details> <summary>Patch and regression tests against f799496</summary> ```diff diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 6be649d..9801b0f 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -718,9 +718,46 @@ impl HostHeap { } let total_slots: usize = clamped.iter().map(|&(a, b)| (b - a) as usize).sum(); let page_size = crate::watch::PAGE as u64; + const OS_PAGE: u64 = 4096; let mut page_buf: Vec<u8> = Vec::new(); let mut readable: Vec<(u32, u32)> = Vec::with_capacity(clamped.len()); let mut records: Vec<[u32; 3]> = Vec::with_capacity(total_slots); + let mut read_span = |a: u32, b: u32| -> bool { + let addr = at(a); + let n = (b - a) as usize; + let bytes = (n - 1) * step as usize + 12; + if page_buf.len() < bytes { + page_buf.resize(bytes, 0); + } + if !crate::host::read_into(addr as *const u8, &mut page_buf[..bytes]) { + return false; + } + readable.push((a, b)); + for k in 0..n { + let off = k * step as usize; + records.push([ + u32::from_ne_bytes([ + page_buf[off], + page_buf[off + 1], + page_buf[off + 2], + page_buf[off + 3], + ]), + u32::from_ne_bytes([ + page_buf[off + 4], + page_buf[off + 5], + page_buf[off + 6], + page_buf[off + 7], + ]), + u32::from_ne_bytes([ + page_buf[off + 8], + page_buf[off + 9], + page_buf[off + 10], + page_buf[off + 11], + ]), + ]); + } + true + }; for &(first, last) in &clamped { let mut i = first; while i < last { @@ -730,35 +767,17 @@ impl HostHeap { // is not page-aligned and may straddle a page boundary). let fit = ((next_page - addr) / step).max(1); let j = last.min(i.saturating_add(fit as u32)); - let n = (j - i) as usize; - let bytes = (n - 1) * step as usize + 12; - if page_buf.len() < bytes { - page_buf.resize(bytes, 0); - } - if crate::host::read_into(addr as *const u8, &mut page_buf[..bytes]) { - readable.push((i, j)); - for k in 0..n { - let off = k * step as usize; - records.push([ - u32::from_ne_bytes([ - page_buf[off], - page_buf[off + 1], - page_buf[off + 2], - page_buf[off + 3], - ]), - u32::from_ne_bytes([ - page_buf[off + 4], - page_buf[off + 5], - page_buf[off + 6], - page_buf[off + 7], - ]), - u32::from_ne_bytes([ - page_buf[off + 8], - page_buf[off + 9], - page_buf[off + 10], - page_buf[off + 11], - ]), - ]); + if !read_span(i, j) { + // A 64 KiB chunk may straddle committed and uncommitted 4 KiB + // OS pages; retry per 4 KiB page so committed slots survive. + let mut sub = i; + while sub < j { + let sub_addr = at(sub); + let next_os = (sub_addr & !(OS_PAGE - 1)) + OS_PAGE; + let sub_fit = ((next_os - sub_addr) / step).max(1); + let sub_end = j.min(sub.saturating_add(sub_fit as u32)); + let _ = read_span(sub, sub_end); + sub = sub_end; } } i = j; @@ -1918,7 +1937,7 @@ fn merge_ranges(ranges: &[(u32, u32)], cap: u32) -> (Vec<(u32, u32)>, Option<u32 let mut past_cap: Option<u32> = None; let mut raw: Vec<(u32, u32)> = Vec::with_capacity(ranges.len()); for &(first, last) in ranges { - if last > cap { + if first < last && last > cap { let high = last - 1; past_cap = Some(past_cap.map_or(high, |m| m.max(high))); } @@ -2593,6 +2612,7 @@ mod tests { (vec![(0, 64)], Some(67)) ); assert_eq!(merge_ranges(&[(70, 80), (10, 10)], 64), (vec![], Some(79))); + assert_eq!(merge_ranges(&[(70, 70), (80, 75)], 64), (vec![], None)); } /// `sync_ranges` merges overlapping, adjacent, and out-of-order ranges @@ -2654,4 +2674,53 @@ mod tests { crate::shadow::unregister(pool, base); crate::watch::tests::free(pool); } + + /// When a 64 KiB heap block has a committed 4 KiB page followed by an + /// uncommitted 4 KiB page, `sync_ranges` must still mirror the descriptors + /// on the committed 4 KiB page instead of dropping the whole 64 KiB chunk. + #[test] + fn sync_ranges_mirrors_committed_4k_page_beside_uncommitted_page() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + let Some(heap) = HostHeap::new(false, 256) else { + return; + }; + assert!(heap.view_addresses().is_some()); + let pool = crate::watch::tests::pool(1); + let base = pool as u64; + crate::shadow::register(pool, base, 64 << 10); + + // SAFETY: reserve one 64 KiB page and commit only its first 4 KiB OS page. + let mem = unsafe { + VirtualAlloc(std::ptr::null(), crate::watch::PAGE, MEM_RESERVE, PAGE_READWRITE) + }; + assert!(!mem.is_null()); + // SAFETY: committing the first 4 KiB page inside our reservation. + let committed = unsafe { VirtualAlloc(mem, 4096, MEM_COMMIT, PAGE_READWRITE) }; + assert_eq!(committed, mem); + + let step = 32u64; + let start = mem as u64; + let mut resource = [0u32; 14]; + (resource[0], resource[4]) = (1, 64); + let mut view = [0u32; 16]; + (view[1], view[2], view[6], view[7]) = + (1, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, 16, 4); + (view[10], view[11]) = (base as u32, (base >> 32) as u32); + // Slot 2 lies in the committed first 4 KiB page; slots 128..256 lie in + // the uncommitted second 4 KiB page of the same 64 KiB watch::PAGE. + crate::descriptor::create_placed_srv(std::ptr::null(), &resource, &view, start + 2 * step); + + let synced = heap.sync_ranges(&[(0, 256)], start, step); + let got = heap.address_at(2); + + // SAFETY: releasing our reservation. + unsafe { VirtualFree(mem, 0, MEM_RELEASE) }; + crate::shadow::unregister(pool, base); + crate::watch::tests::free(pool); + + assert_eq!(synced, 128, "committed 4 KiB page slots should be scanned"); + assert_eq!(got, Some(base), "descriptor on committed 4 KiB page must be mirrored"); + } } ``` </details> Synthetic tests only; AI-assisted review.
MeMako commented 2026-11-27 05:09:13 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by MeMako on 2026-11-27T05:09:13Z.


Thanks for catching both edge cases and providing the repros! Pushed fixes in 63d630a:

  • Partially committed 64 KiB blocks (sync_ranges): Kept the 64 KiB watch::PAGE fast path and added a 4 KiB (OS_PAGE) read_into fallback when a 64 KiB read fails, so committed 4 KiB OS pages next to uncommitted pages are still mirrored. Added your sync_ranges_mirrors_committed_4k_page_beside_uncommitted_page regression test.
  • Empty / inverted ranges & unmapped tails (merge_ranges / past_cap): Guarded past_cap with first < last && last > cap (added (70, 70), (80, 75) assertion to merge_ranges_sorts_clamps_and_merges_adjacent_and_overlapping). Also added a fallback probe on first.max(cap) across past-cap spans when at(highest) sits on an uncommitted tail page so mapped overflow still emits the past-cap warning.

Verified with cargo test -p victory-gpu --lib --locked -- --test-threads=1 (234 passed, 0 failed, 1 ignored), cargo clippy --workspace --all-targets --locked -- -D warnings (default + --all-features), rustfmt --edition 2024 --check on the modified ranges, and cargo run --locked -p xtask -- policy (191 files ok) on Win 11 / RX 9070 XT.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7210393328 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3139#issuecomment-7210393328). Originally posted by [MeMako](https://github.com/MeMako) on 2026-11-27T05:09:13Z. --- Thanks for catching both edge cases and providing the repros! Pushed fixes in `63d630a`: - **Partially committed 64 KiB blocks (`sync_ranges`):** Kept the 64 KiB `watch::PAGE` fast path and added a 4 KiB (`OS_PAGE`) `read_into` fallback when a 64 KiB read fails, so committed 4 KiB OS pages next to uncommitted pages are still mirrored. Added your `sync_ranges_mirrors_committed_4k_page_beside_uncommitted_page` regression test. - **Empty / inverted ranges & unmapped tails (`merge_ranges` / `past_cap`):** Guarded `past_cap` with `first < last && last > cap` (added `(70, 70), (80, 75)` assertion to `merge_ranges_sorts_clamps_and_merges_adjacent_and_overlapping`). Also added a fallback probe on `first.max(cap)` across past-cap spans when `at(highest)` sits on an uncommitted tail page so mapped overflow still emits the past-cap warning. Verified with `cargo test -p victory-gpu --lib --locked -- --test-threads=1` (234 passed, 0 failed, 1 ignored), `cargo clippy --workspace --all-targets --locked -- -D warnings` (default + `--all-features`), `rustfmt --edition 2024 --check` on the modified ranges, and `cargo run --locked -p xtask -- policy` (191 files ok) on Win 11 / RX 9070 XT.
KainanP commented 2026-11-27 12:31:13 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by KainanP on 2026-11-27T12:31:13Z.


Contention numbers for the SHADER_HEAPS wait in #3425, this PR (63d630a) against its base 63bcca4:

base #3139
sync_heaps, RTX, 12 runs 9.6 ms 11.0 ms (+15 %)
title-thread wait per frame 49.5 ms 56.5 ms
game-shaped heap (1,245,184 slots, pages past the cap too), 5 runs 7.9 ms 7.9 ms

The sync is no faster here, and the lock scope is unchanged, so title threads wait as long as before. For comparison, #3055 (same first commit 24618c9) was 7.6 ms on the same runs. No views were lost or stale. The full victory-gpu suite on RTX fails only the two tests that main also fails here.

Bench: sync_contention_bench (#[ignore]d; commit f34bcfb8, cherry-picks onto any tree). A placed, write-watched view heap of 2^20 slots (the host heap caps it at 934,464 here). Each frame, one thread rewrites 200 random 64 KiB pages (50 changed records each) and runs one sync_heaps, while 5 title threads write a placed-buffer SRV every 20 µs into pages of their own. "Wait" is the title threads' time in view writes beyond the uncontended 2–3 µs, summed per frame. Release build, RTX 4060 Laptop, runs interleaved with the base, medians of 30 frames per run. The bench also checks that every view written before a sync is the slot's view address after it, and that every slot is right after a final quiet sync.

AI use: Claude Code (Claude Opus 5.5).

<!-- greyfinch-sync:Marvisak/VIctory:comment:7218338570 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3139#issuecomment-7218338570). Originally posted by [KainanP](https://github.com/KainanP) on 2026-11-27T12:31:13Z. --- Contention numbers for the `SHADER_HEAPS` wait in #3425, this PR (`63d630a`) against its base `63bcca4`: | | base | #3139 | |---|---|---| | `sync_heaps`, RTX, 12 runs | 9.6 ms | 11.0 ms (+15 %) | | title-thread wait per frame | 49.5 ms | 56.5 ms | | game-shaped heap (1,245,184 slots, pages past the cap too), 5 runs | 7.9 ms | 7.9 ms | The sync is no faster here, and the lock scope is unchanged, so title threads wait as long as before. For comparison, #3055 (same first commit `24618c9`) was 7.6 ms on the same runs. No views were lost or stale. The full `victory-gpu` suite on RTX fails only the two tests that `main` also fails here. Bench: [`sync_contention_bench`](https://github.com/KainanP/VIctory/blob/bench/sync-heaps-contention/crates/victory-gpu/src/descriptor/sync_bench.rs) (`#[ignore]`d; commit `f34bcfb8`, cherry-picks onto any tree). A placed, write-watched view heap of 2^20 slots (the host heap caps it at 934,464 here). Each frame, one thread rewrites 200 random 64 KiB pages (50 changed records each) and runs one `sync_heaps`, while 5 title threads write a placed-buffer SRV every 20 µs into pages of their own. "Wait" is the title threads' time in view writes beyond the uncontended 2–3 µs, summed per frame. Release build, RTX 4060 Laptop, runs interleaved with the base, medians of 30 frames per run. The bench also checks that every view written before a sync is the slot's view address after it, and that every slot is right after a final quiet sync. _AI use: Claude Code (Claude Opus 5.5)._
KainanP commented 2026-11-27 13:06:22 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by KainanP on 2026-11-27T13:06:22Z.


Follow-up to my contention numbers above, this time in the sync_slots shape #3425 reports (18.1 ms/frame for ~384k slots). It shows something the earlier run didn't.

Bench: sync_slots_bench on bench/sync-slots (f233390e, on top of f34bcfb8). Each frame, 192 random 64 KiB pages (393,216 slots, the "384k slots" of #3425) of a 2^20-slot placed, write-watched view heap are written. 0, ~9,500 or ~85,000 records among them change, and one sync_heaps runs. Each shape runs without and with 5 title threads writing a view every 20 µs. It checks every changed slot's view address after each sync, and every slot at the end. RTX 4060 Laptop. Base 63bcca4 and the PRs ran interleaved (7 runs for the ~9.5k row, 3 for the others). Ratios are per-run against base. #3265, which doesn't touch the sync, gave ×0.81-1.04 in the same runs, so read anything within ~±15% as noise.

changed records title threads base sync_heaps #3139 ratio title wait/frame, base → #3139
0 0 2.9 ms 4.9 ms ×1.81
0 5 3.6 ms 5.2 ms ×1.80 18 → 26 ms
~9,500 0 12.3 ms 12.1 ms ×1.06
~9,500 5 13.1 ms 13.2 ms ×1.07 64 → 66 ms
~85,000 0 159 ms 128 ms ×0.71
~85,000 5 160 ms 136 ms ×0.84 779 → 660 ms

When the pages are written but no record changed (the title copying the same tables in again), the sync takes ~1.8× as long as on base: 2.9 → 4.9 ms for 393k slots. With a realistic ~9,500 changed records it's even. Only with ~85,000 changed per frame is it ahead, and only partly beyond noise. My guess is the up-front read_into of the whole merged ranges, which copies every record once more before the diff, but I haven't profiled it. 0 lost and 0 stale slots in every run.

For comparison, #3055 (which contains this PR's first commit) is ×0.63-0.82 in all six rows.

AI use: Claude Code (Claude Opus 5.5).

<!-- greyfinch-sync:Marvisak/VIctory:comment:7219062858 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3139#issuecomment-7219062858). Originally posted by [KainanP](https://github.com/KainanP) on 2026-11-27T13:06:22Z. --- Follow-up to my contention numbers above, this time in the `sync_slots` shape #3425 reports (18.1 ms/frame for ~384k slots). It shows something the earlier run didn't. **Bench:** `sync_slots_bench` on [`bench/sync-slots`](https://github.com/KainanP/VIctory/commits/bench/sync-slots) (`f233390e`, on top of `f34bcfb8`). Each frame, 192 random 64 KiB pages (393,216 slots, the "384k slots" of #3425) of a 2^20-slot placed, write-watched view heap are written. 0, ~9,500 or ~85,000 records among them change, and one `sync_heaps` runs. Each shape runs without and with 5 title threads writing a view every 20 µs. It checks every changed slot's view address after each sync, and every slot at the end. RTX 4060 Laptop. Base `63bcca4` and the PRs ran interleaved (7 runs for the ~9.5k row, 3 for the others). Ratios are per-run against base. #3265, which doesn't touch the sync, gave ×0.81-1.04 in the same runs, so read anything within ~±15% as noise. | changed records | title threads | base `sync_heaps` | #3139 | ratio | title wait/frame, base → #3139 | |---|---|---|---|---|---| | 0 | 0 | 2.9 ms | 4.9 ms | **×1.81** | | | 0 | 5 | 3.6 ms | 5.2 ms | **×1.80** | 18 → 26 ms | | ~9,500 | 0 | 12.3 ms | 12.1 ms | ×1.06 | | | ~9,500 | 5 | 13.1 ms | 13.2 ms | ×1.07 | 64 → 66 ms | | ~85,000 | 0 | 159 ms | 128 ms | ×0.71 | | | ~85,000 | 5 | 160 ms | 136 ms | ×0.84 | 779 → 660 ms | When the pages are written but no record changed (the title copying the same tables in again), the sync takes ~1.8× as long as on base: 2.9 → 4.9 ms for 393k slots. With a realistic ~9,500 changed records it's even. Only with ~85,000 changed per frame is it ahead, and only partly beyond noise. My guess is the up-front `read_into` of the whole merged ranges, which copies every record once more before the diff, but I haven't profiled it. 0 lost and 0 stale slots in every run. For comparison, #3055 (which contains this PR's first commit) is ×0.63-0.82 in all six rows. _AI use: Claude Code (Claude Opus 5.5)._
passerbyyhx commented 2026-11-29 16:22:18 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by passerbyyhx on 2026-11-29T16:22:18Z.


Ran sync_ranges_merges_overlapping_and_out_of_order_ranges and sync_ranges_mirrors_committed_4k_page_beside_uncommitted_page at 63d630a0124a069d57b5d580fa7f054783b3ccdf on RTX 4090 Laptop (10de:2757) and WARP (1414:008c). Both tests passed on each adapter. Test-only instrumentation verified the D3D12 device LUID/vendor and required heap creation so an unavailable heap could not yield a passing early return. Scope is descriptor mirror correctness for these two cases; no frame-time or contention measurements.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7258850472 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3139#issuecomment-7258850472). Originally posted by [passerbyyhx](https://github.com/passerbyyhx) on 2026-11-29T16:22:18Z. --- Ran `sync_ranges_merges_overlapping_and_out_of_order_ranges` and `sync_ranges_mirrors_committed_4k_page_beside_uncommitted_page` at `63d630a0124a069d57b5d580fa7f054783b3ccdf` on RTX 4090 Laptop (10de:2757) and WARP (1414:008c). Both tests passed on each adapter. Test-only instrumentation verified the D3D12 device LUID/vendor and required heap creation so an unavailable heap could not yield a passing early return. Scope is descriptor mirror correctness for these two cases; no frame-time or contention measurements.
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/3139:upstream-pr/3139'
git switch 'upstream-pr/3139'

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