GPU: track hot MEM_WRITE_WATCH buffer pages via batched GetWriteWatch instead of PAGE_READONLY guard faults #3615

Open
Texbirds wants to merge 4 commits from upstream-pr/3615 into main
Texbirds commented 2026-11-27 21:38:53 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Texbirds on 2026-11-27T21:38:53Z.


Problem

On every submission, watch::Tracked::take_split re-guards modified 64 KiB pages with VirtualProtect(PAGE_READONLY) (triggering cross-core TLB shootdowns). For hot CPU-written buffer pages (ring buffers, per-frame constants, instance/command data written every frame), the title's very next CPU write immediately faults into on_write (hardware #PF → kernel exception dispatch → user-mode VEH → global GUARDS mutex → VirtualProtect(PAGE_READWRITE) TLB shootdown → replay).

victory-hle already allocates runtime pools with MEM_WRITE_WATCH, and watch.rs already queries GetWriteWatch to classify them — but never used hardware write-watch to track writes on hot pages.

Approach

Keep PAGE_READONLY guards for cold pages (preserving zero-syscall Tracked::clean() via DIRTY bits), section/aliased views, texture stagings, descriptor heaps, and armed GPU-write ranges, while adaptively promoting hot MEM_WRITE_WATCH buffer-copy pages to batched hardware GetWriteWatch:

  • Promotion (HOT_THRESHOLD = 3): After 3 consecutive guard faults on a page with no physical aliases, where every holder is an unarmed host buffer copy (copy == true), protect_noting calls ResetWriteWatch (which atomically verifies the page is a MEM_WRITE_WATCH allocation and clears its dirty bits) and moves the page into Guards::watched without calling VirtualProtect(PAGE_READONLY).
  • Batched polling (WATCH_BATCH_PAGES = 64, up to 4 MiB per syscall): Tracked::take_split groups contiguous watched pages into runs of up to 64 pages and polls/resets them in a single GetWriteWatch(WRITE_WATCH_FLAG_RESET, ...) call using a stack buffer sized for all 64 × 16 = 1,024 hardware 4 KiB subpages, propagating dirty bits to any other buffer copies sharing those pages.
  • Automatic cool-down (COOL_TAKES = 2): If a watched page sees 2 consecutive quiet takes with 0 CPU writes, it is demoted back to PAGE_READONLY so cold trackers return to zero-syscall Tracked::clean().
  • Exactness & safety invariants:
    • Tracked::arm acquires GUARDS before Saved (matching global lock order) and atomically demotes any watched page in the armed range back to PAGE_READONLY (polling pending writes first) so on_write always captures Changed::save pre-write bytes before concurrent CPU writes land.
    • Tracked::changed performs a non-resetting GetWriteWatch(0, ...) peek on watched pages so Shadow::copy_back_marked / Shadow::copy_back_page never falsely drop GPU writes on untouched hot pages.
    • Tracked::taken, track(..., copy=false), title_memory_remapped, title_memory_aliased, and Drop for Tracked all cleanly demote/clear watched state with zero lost writes.

Benchmarks (--release, Windows 11 x64, Ryzen 9 5900X + NVIDIA GeForce RTX 3080 Ti)

1. End-to-end 8-thread CPU writers + real D3D12 Shadow::update on RTX 3080 Ti (512 hot pages = 32 MiB × 100 frames, cargo test --release --locked -p victory-gpu -- watch::tests::bench_multithreaded_shadow_refresh_on_host_gpu --ignored --nocapture):

Metric Pre-change (PAGE_READONLY + VEH) Post-change (Batched MEM_WRITE_WATCH) Gain
Title CPU writes (8 threads) 378.96 ms (3.79 ms/frame) 16.90 ms (0.17 ms/frame) 22.4× faster (−95.5%)
D3D12 Shadow::update (take + 32 MiB copy) 746.60 ms (7.47 ms/frame) 633.24 ms (6.33 ms/frame) −15.2% (−1.14 ms/frame)
Total end-to-end wall time 1,125.59 ms (11.26 ms/frame) 650.17 ms (6.50 ms/frame) 1.73× faster (−42.2%)

2. Single-threaded tracking-only A/B (256 hot pages = 16 MiB × 100 frames, cargo test --release --locked -p victory-gpu -- watch::tests::bench_hot_write_watch_vs_guards --ignored --nocapture):

  • PAGE_READONLY guards + VEH: 88.45 ms (0.88 ms/frame)
  • Batched MEM_WRITE_WATCH: 19.42 ms (0.19 ms/frame) — 4.6× faster

Verification (Windows 11 x64, RTX 3080 Ti + WARP, Rust 1.98.1)

  • cargo run --locked -p xtask -- policy: 191 files ok
  • cargo clippy --locked -p victory-gpu --all-targets -- -D warnings: 0 warnings
  • cargo clippy --locked -p victory-gpu --all-targets --all-features -- -D warnings: 0 warnings
  • cargo test --locked -p victory-gpu -- watch::: 21/21 passed (2 benchmarks ignored)
  • VICTORY_D3D12_WARP=1 cargo test --locked -p victory-gpu --features diagnostics -- watch:: shadow:: bindless:: descriptor::: 56/56 passed
  • RTX 3080 Ti hardware watch:: shadow:: bindless:: descriptor::: 55/55 passed (excluding the pre-existing NVIDIA 1M view-heap test dynamic_slots_are_held_until_released)
<!-- greyfinch-sync:Marvisak/VIctory:issue:5533408620 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3615). Originally posted by [Texbirds](https://github.com/Texbirds) on 2026-11-27T21:38:53Z. --- ### Problem On every submission, `watch::Tracked::take_split` re-guards modified 64 KiB pages with `VirtualProtect(PAGE_READONLY)` (triggering cross-core TLB shootdowns). For hot CPU-written buffer pages (ring buffers, per-frame constants, instance/command data written every frame), the title's very next CPU write immediately faults into `on_write` (hardware `#PF` → kernel exception dispatch → user-mode VEH → global `GUARDS` mutex → `VirtualProtect(PAGE_READWRITE)` TLB shootdown → replay). `victory-hle` already allocates runtime pools with `MEM_WRITE_WATCH`, and `watch.rs` already queries `GetWriteWatch` to classify them — but never used hardware write-watch to track writes on hot pages. ### Approach Keep `PAGE_READONLY` guards for cold pages (preserving zero-syscall `Tracked::clean()` via `DIRTY` bits), section/aliased views, texture stagings, descriptor heaps, and armed GPU-write ranges, while adaptively promoting **hot `MEM_WRITE_WATCH` buffer-copy pages** to batched hardware `GetWriteWatch`: - **Promotion (`HOT_THRESHOLD = 3`):** After 3 consecutive guard faults on a page with no physical aliases, where every holder is an unarmed host buffer copy (`copy == true`), `protect_noting` calls `ResetWriteWatch` (which atomically verifies the page is a `MEM_WRITE_WATCH` allocation and clears its dirty bits) and moves the page into `Guards::watched` without calling `VirtualProtect(PAGE_READONLY)`. - **Batched polling (`WATCH_BATCH_PAGES = 64`, up to 4 MiB per syscall):** `Tracked::take_split` groups contiguous watched pages into runs of up to 64 pages and polls/resets them in a single `GetWriteWatch(WRITE_WATCH_FLAG_RESET, ...)` call using a stack buffer sized for all `64 × 16 = 1,024` hardware 4 KiB subpages, propagating dirty bits to any other buffer copies sharing those pages. - **Automatic cool-down (`COOL_TAKES = 2`):** If a watched page sees 2 consecutive quiet takes with 0 CPU writes, it is demoted back to `PAGE_READONLY` so cold trackers return to zero-syscall `Tracked::clean()`. - **Exactness & safety invariants:** - `Tracked::arm` acquires `GUARDS` before `Saved` (matching global lock order) and atomically demotes any watched page in the armed range back to `PAGE_READONLY` (polling pending writes first) so `on_write` always captures `Changed::save` pre-write bytes before concurrent CPU writes land. - `Tracked::changed` performs a non-resetting `GetWriteWatch(0, ...)` peek on watched pages so `Shadow::copy_back_marked` / `Shadow::copy_back_page` never falsely drop GPU writes on untouched hot pages. - `Tracked::taken`, `track(..., copy=false)`, `title_memory_remapped`, `title_memory_aliased`, and `Drop for Tracked` all cleanly demote/clear watched state with zero lost writes. ### Benchmarks (`--release`, Windows 11 x64, Ryzen 9 5900X + NVIDIA GeForce RTX 3080 Ti) **1. End-to-end 8-thread CPU writers + real D3D12 `Shadow::update` on RTX 3080 Ti** (`512` hot pages = 32 MiB × 100 frames, `cargo test --release --locked -p victory-gpu -- watch::tests::bench_multithreaded_shadow_refresh_on_host_gpu --ignored --nocapture`): | Metric | Pre-change (`PAGE_READONLY` + VEH) | Post-change (Batched `MEM_WRITE_WATCH`) | Gain | |---|---:|---:|---:| | Title CPU writes (8 threads) | 378.96 ms (3.79 ms/frame) | 16.90 ms (0.17 ms/frame) | **22.4× faster (−95.5%)** | | D3D12 `Shadow::update` (take + 32 MiB copy) | 746.60 ms (7.47 ms/frame) | 633.24 ms (6.33 ms/frame) | **−15.2% (−1.14 ms/frame)** | | Total end-to-end wall time | 1,125.59 ms (11.26 ms/frame) | 650.17 ms (6.50 ms/frame) | **1.73× faster (−42.2%)** | **2. Single-threaded tracking-only A/B** (`256` hot pages = 16 MiB × 100 frames, `cargo test --release --locked -p victory-gpu -- watch::tests::bench_hot_write_watch_vs_guards --ignored --nocapture`): - `PAGE_READONLY` guards + VEH: `88.45 ms` (`0.88 ms/frame`) - Batched `MEM_WRITE_WATCH`: `19.42 ms` (`0.19 ms/frame`) — **4.6× faster** ### Verification (Windows 11 x64, RTX 3080 Ti + WARP, Rust 1.98.1) - `cargo run --locked -p xtask -- policy`: `191 files ok` - `cargo clippy --locked -p victory-gpu --all-targets -- -D warnings`: 0 warnings - `cargo clippy --locked -p victory-gpu --all-targets --all-features -- -D warnings`: 0 warnings - `cargo test --locked -p victory-gpu -- watch::`: **21/21 passed** (2 benchmarks ignored) - `VICTORY_D3D12_WARP=1 cargo test --locked -p victory-gpu --features diagnostics -- watch:: shadow:: bindless:: descriptor::`: **56/56 passed** - RTX 3080 Ti hardware `watch:: shadow:: bindless:: descriptor::`: **55/55 passed** (excluding the pre-existing NVIDIA 1M view-heap test `dynamic_slots_are_held_until_released`)
Desamodeth commented 2026-11-27 22:20:46 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Desamodeth on 2026-11-27T22:20:46Z.


Confirmed a missed write on 222edf70 on Windows. After a hot 64 KiB page gets two quiet 4-byte refreshes, writing its last word produces an empty refresh. The same sequence passes on main (63bcca43). A second reproducer uses two buffer copies sharing a page while a host Writing guard is open.

Cherry-pickable fix and both regression tests. Hardware polling stays active until the read-only guard takes over. All 23 active watch tests passed. A separate local test injected a write between the two polls and verified delivery to both holders.

CPU writes + tracking, median µs/update across six interleaved runs per build (main / PR / fix, 128 pages): all pages written 296.0 / 57.6 / 57.6, every eighth page 43.1 / 18.6 / 18.6, four dense updates followed by two quiet updates 199.5 / 173.8 / 174.2. These timings cover the CPU tracker only. AI-assisted with Codex Astra 6.2 High.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7229249399 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3615#issuecomment-7229249399). Originally posted by [Desamodeth](https://github.com/Desamodeth) on 2026-11-27T22:20:46Z. --- Confirmed a missed write on `222edf70` on Windows. After a hot 64 KiB page gets two quiet 4-byte refreshes, writing its last word produces an empty refresh. The same sequence passes on `main` (`63bcca43`). A second reproducer uses two buffer copies sharing a page while a host `Writing` guard is open. [Cherry-pickable fix and both regression tests](https://github.com/Desamodeth/VIctory/commit/d2d23a3e1d5c3ad52e0b3b30fa87558d7899e0c4). Hardware polling stays active until the read-only guard takes over. All 23 active watch tests passed. A separate local test injected a write between the two polls and verified delivery to both holders. CPU writes + tracking, median µs/update across six interleaved runs per build (**main / PR / fix**, 128 pages): all pages written **296.0 / 57.6 / 57.6**, every eighth page **43.1 / 18.6 / 18.6**, four dense updates followed by two quiet updates **199.5 / 173.8 / 174.2**. These timings cover the CPU tracker only. AI-assisted with Codex Astra 6.2 High.
Texbirds commented 2026-11-27 22:32:19 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Texbirds on 2026-11-27T22:32:19Z.


Awesome catch @Desamodeth — thank you for the reproducers, the clean fix, and the independent benchmark confirmation (296.0 µs → 57.6 µs on 128 pages)!

Cherry-picked d2d23a3e onto the PR branch as 5b8f14e (preserving your authorship) and re-verified locally on Windows 11 x64 (RTX 3080 Ti):

  • cargo run --locked -p xtask -- policy: 191 files ok
  • cargo clippy --locked -p victory-gpu --all-targets -- -D warnings (default & --all-features): 0 warnings
  • cargo test --locked -p victory-gpu -- watch:: shadow::: 33/33 passed (including both new regression tests)
<!-- greyfinch-sync:Marvisak/VIctory:comment:7229411131 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3615#issuecomment-7229411131). Originally posted by [Texbirds](https://github.com/Texbirds) on 2026-11-27T22:32:19Z. --- Awesome catch @Desamodeth — thank you for the reproducers, the clean fix, and the independent benchmark confirmation (`296.0 µs → 57.6 µs` on 128 pages)! Cherry-picked `d2d23a3e` onto the PR branch as `5b8f14e` (preserving your authorship) and re-verified locally on Windows 11 x64 (RTX 3080 Ti): - `cargo run --locked -p xtask -- policy`: `191 files ok` - `cargo clippy --locked -p victory-gpu --all-targets -- -D warnings` (default & `--all-features`): 0 warnings - `cargo test --locked -p victory-gpu -- watch:: shadow::`: 33/33 passed (including both new regression tests)
upipibi commented 2026-11-27 22:55:58 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by upipibi on 2026-11-27T22:55:58Z.


An interaction with #3585 (open, same watch.rs code), read from both heads and not run: each PR is consistent on its own, but merged together, writes to watched pages would be missed on the refresh path.

  • Here, a hot page in Guards::watched is left writable, and its writes are found only by the GetWriteWatch poll inside Tracked::take_split. That poll runs even when the changed set is empty (watch.rs:718-719 at 5b8f14e, has_watched).
  • #3585 (af08b8b) moves a submission's refreshes off take_split. Batch::flush calls shadow::plan (shadow.rs:698), which takes the pages from Tracked::written (shadow.rs:720 → watch.rs:490). That reads only the changed set, and a copy with nothing in it returns Plan::Done(0) (shadow.rs:729-733). take_written (watch.rs:550) then only guards the pages it was given.

With both in, a watched page the title wrote without a fault is not in the changed set. The batch skips it, and the host copy keeps its old bytes. take_split itself still polls, but in #3585 it is only the one-tracker path.

Whichever lands second needs the watched-page poll in Tracked::written, or in plan before its early return, plus a test that refreshes a watched page through Batch::flush. The two PRs also overlap textually over most of take_split and protect_noting.

AI-assisted (Claude Code, Claude Opus 5.5 read both heads and checked the lines).

<!-- greyfinch-sync:Marvisak/VIctory:comment:7229735686 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3615#issuecomment-7229735686). Originally posted by [upipibi](https://github.com/upipibi) on 2026-11-27T22:55:58Z. --- An interaction with #3585 (open, same `watch.rs` code), read from both heads and not run: each PR is consistent on its own, but merged together, writes to watched pages would be missed on the refresh path. - Here, a hot page in `Guards::watched` is left writable, and its writes are found only by the `GetWriteWatch` poll inside `Tracked::take_split`. That poll runs even when the changed set is empty (`watch.rs:718-719` at `5b8f14e`, `has_watched`). - #3585 (`af08b8b`) moves a submission's refreshes off `take_split`. `Batch::flush` calls `shadow::plan` (`shadow.rs:698`), which takes the pages from `Tracked::written` (`shadow.rs:720` → `watch.rs:490`). That reads only the changed set, and a copy with nothing in it returns `Plan::Done(0)` (`shadow.rs:729-733`). `take_written` (`watch.rs:550`) then only guards the pages it was given. With both in, a watched page the title wrote without a fault is not in the changed set. The batch skips it, and the host copy keeps its old bytes. `take_split` itself still polls, but in #3585 it is only the one-tracker path. Whichever lands second needs the watched-page poll in `Tracked::written`, or in `plan` before its early return, plus a test that refreshes a watched page through `Batch::flush`. The two PRs also overlap textually over most of `take_split` and `protect_noting`. AI-assisted (Claude Code, Claude Opus 5.5 read both heads and checked the lines).
Texbirds commented 2026-11-27 22:59:17 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Texbirds on 2026-11-27T22:59:17Z.


Good catch @upipibi — verified against #3585 (af08b8b), your read is spot on.

Since both PRs target main (63bcca4) and are self-contained on their own, no change is needed here right now. If #3585 lands first, I'll rebase #3615 so watch::take_written polls watched pages inside the single batched GUARDS lock round (and add a Batch::flush watched-page regression test). Both optimizations should compose cleanly once combined.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7229778858 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3615#issuecomment-7229778858). Originally posted by [Texbirds](https://github.com/Texbirds) on 2026-11-27T22:59:17Z. --- Good catch @upipibi — verified against #3585 (`af08b8b`), your read is spot on. Since both PRs target `main` (`63bcca4`) and are self-contained on their own, no change is needed here right now. If #3585 lands first, I'll rebase #3615 so `watch::take_written` polls watched pages inside the single batched `GUARDS` lock round (and add a `Batch::flush` watched-page regression test). Both optimizations should compose cleanly once combined.
pickles976 commented 2026-11-28 05:55:17 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by pickles976 on 2026-11-28T05:55:17Z.


Exact head 5b8f14e7b88a468c8a4a84e74e43d612f2a59b7b: deterministic lost pre-write snapshot when the first hot page is promoted concurrently with Tracked::arm.

Linux/Wine 11, 16GiB host. CPU Win32/tracking only, no GPU dispatch. Fresh intended-tree build8.12s. Your existing sequential arming_a_hot_write_watch_page_demotes_it_and_saves_pre_write_bytes passes; the new interleaving below fails with saved=None, expected first word 0xAAAA5555. Production behavior unchanged; only a cfg(test) scheduling hook and regression added.

Interleaving:

  1. Arm thread observes WATCHED_PAGES == 0, pauses before acquiring Saved.
  2. Another thread executes the real take after the third write fault: can_watch still sees an unarmed holder; production promotion succeeds and leaves the page writable.
  3. Arm resumes through its lock-free-global branch, marks Saved armed and returns without demotion.
  4. CPU writes 0xDEADBEEF; no fault occurs and the required old bytes are absent.

This is the path the current sequential test cannot exercise. A global zero count is not synchronization with registration of the first watched page. Conservative correction: serialize arming with promotion under GUARDS even when the count was zero (maintaining GUARDS→Saved lock order), or provide an equivalent proven handshake. A second unsynchronized counter check alone leaves the eligibility-check/publication race. Please retain a concurrent before-image regression before enabling this path in title runs. No title corruption/performance attribution is claimed here.

Evidence .compat-runtime/logs/verify-write-watch-arming-race-20261128T055339Z/: parent 1passed/1failed, isolated child fails the semantic before-image assertion; no timeout. No assets involved.

Test-only hook beside WATCHED_PAGES:

#[cfg(test)]
static LAB_ARM_HOOK: Mutex<Option<Box<dyn Fn() + Send>>> = Mutex::new(None);

At the start of the if WATCHED_PAGES.load(Ordering::Acquire) == 0 branch, before Saved::arm:

#[cfg(test)]
if let Some(hook) = LAB_ARM_HOOK.lock().unwrap().as_ref() {
    hook();
}

The subprocess makes this isolated from other tests' global watched-page state; both rendezvous waits have ten-second deadlines:

    #[test]
    fn arming_during_hot_promotion_keeps_before_image() {
        const CHILD: &str = "VICTORY_LAB_ARM_RACE_CHILD";
        if std::env::var_os(CHILD).is_none() {
            let output = std::process::Command::new(std::env::current_exe().unwrap())
                .env(CHILD, "1")
                .args(["--exact", "watch::tests::arming_during_hot_promotion_keeps_before_image",
                    "--nocapture", "--test-threads=1"])
                .output().unwrap();
            assert!(output.status.success(), "{}\n{}",
                String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr));
            return;
        }
        // Isolated child: unrelated parallel tests cannot change WATCHED_PAGES.
        let p = pool(1);
        let t = track_copy(p, PAGE, true).expect("tracked write-watched pool");
        assert_eq!(t.take(p, p + PAGE), [(p, p + PAGE)]);
        for k in 1..u32::from(HOT_THRESHOLD) {
            // SAFETY: owned pool page, with the normal write-fault handler.
            unsafe { (p as *mut u32).write_volatile(k) };
            assert_eq!(t.take(p, p + PAGE), [(p, p + PAGE)]);
        }
        // The next take promotes it, but arming first observes no watched pages.
        unsafe { (p as *mut u32).write_volatile(0xAAAA_5555) };
        assert_eq!(WATCHED_PAGES.load(Ordering::Acquire), 0);
        let (ready_tx, ready_rx) = std::sync::mpsc::channel();
        let (resume_tx, resume_rx) = std::sync::mpsc::channel();
        let resume_rx = Mutex::new(resume_rx);
        *LAB_ARM_HOOK.lock().unwrap() = Some(Box::new(move || {
            ready_tx.send(()).unwrap();
            resume_rx.lock().unwrap().recv_timeout(std::time::Duration::from_secs(10)).unwrap();
        }));
        std::thread::scope(|scope| {
            let arm = scope.spawn(|| t.arm(p, p + PAGE));
            ready_rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap();
            assert_eq!(t.take(p, p + PAGE), [(p, p + PAGE)]);
            assert!(guards().watched.contains(&(p / PAGE)), "promotion really occurred");
            resume_tx.send(()).unwrap();
            arm.join().unwrap();
        });
        *LAB_ARM_HOOK.lock().unwrap() = None;
        // An armed GPU-write range must retain these pre-write bytes.
        unsafe { (p as *mut u32).write_volatile(0xDEAD_BEEF) };
        let before = t.saved(p / PAGE).map(|bytes| u32::from_le_bytes(bytes[..4].try_into().unwrap()));
        t.disarm();
        drop(t);
        free(p);
        assert_eq!(before, Some(0xAAAA_5555), "arming lost its pre-write snapshot");
    }
<!-- greyfinch-sync:Marvisak/VIctory:comment:7234967536 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3615#issuecomment-7234967536). Originally posted by [pickles976](https://github.com/pickles976) on 2026-11-28T05:55:17Z. --- Exact head `5b8f14e7b88a468c8a4a84e74e43d612f2a59b7b`: deterministic **lost pre-write snapshot** when the first hot page is promoted concurrently with `Tracked::arm`. Linux/Wine 11, 16GiB host. CPU Win32/tracking only, no GPU dispatch. Fresh intended-tree build8.12s. Your existing sequential `arming_a_hot_write_watch_page_demotes_it_and_saves_pre_write_bytes` passes; the new interleaving below fails with `saved=None`, expected first word `0xAAAA5555`. Production behavior unchanged; only a cfg(test) scheduling hook and regression added. Interleaving: 1. Arm thread observes `WATCHED_PAGES == 0`, pauses before acquiring `Saved`. 2. Another thread executes the real `take` after the third write fault: `can_watch` still sees an unarmed holder; production promotion succeeds and leaves the page writable. 3. Arm resumes through its lock-free-global branch, marks `Saved` armed and returns without demotion. 4. CPU writes `0xDEADBEEF`; no fault occurs and the required old bytes are absent. This is the path the current sequential test cannot exercise. A global zero count is not synchronization with registration of the first watched page. Conservative correction: serialize arming with promotion under `GUARDS` even when the count was zero (maintaining GUARDS→Saved lock order), or provide an equivalent proven handshake. A second unsynchronized counter check alone leaves the eligibility-check/publication race. Please retain a concurrent before-image regression before enabling this path in title runs. No title corruption/performance attribution is claimed here. Evidence `.compat-runtime/logs/verify-write-watch-arming-race-20261128T055339Z/`: parent 1passed/1failed, isolated child fails the semantic before-image assertion; no timeout. No assets involved. Test-only hook beside `WATCHED_PAGES`: ```rust #[cfg(test)] static LAB_ARM_HOOK: Mutex<Option<Box<dyn Fn() + Send>>> = Mutex::new(None); ``` At the start of the `if WATCHED_PAGES.load(Ordering::Acquire) == 0` branch, before `Saved::arm`: ```rust #[cfg(test)] if let Some(hook) = LAB_ARM_HOOK.lock().unwrap().as_ref() { hook(); } ``` The subprocess makes this isolated from other tests' global watched-page state; both rendezvous waits have ten-second deadlines: ```rust #[test] fn arming_during_hot_promotion_keeps_before_image() { const CHILD: &str = "VICTORY_LAB_ARM_RACE_CHILD"; if std::env::var_os(CHILD).is_none() { let output = std::process::Command::new(std::env::current_exe().unwrap()) .env(CHILD, "1") .args(["--exact", "watch::tests::arming_during_hot_promotion_keeps_before_image", "--nocapture", "--test-threads=1"]) .output().unwrap(); assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); return; } // Isolated child: unrelated parallel tests cannot change WATCHED_PAGES. let p = pool(1); let t = track_copy(p, PAGE, true).expect("tracked write-watched pool"); assert_eq!(t.take(p, p + PAGE), [(p, p + PAGE)]); for k in 1..u32::from(HOT_THRESHOLD) { // SAFETY: owned pool page, with the normal write-fault handler. unsafe { (p as *mut u32).write_volatile(k) }; assert_eq!(t.take(p, p + PAGE), [(p, p + PAGE)]); } // The next take promotes it, but arming first observes no watched pages. unsafe { (p as *mut u32).write_volatile(0xAAAA_5555) }; assert_eq!(WATCHED_PAGES.load(Ordering::Acquire), 0); let (ready_tx, ready_rx) = std::sync::mpsc::channel(); let (resume_tx, resume_rx) = std::sync::mpsc::channel(); let resume_rx = Mutex::new(resume_rx); *LAB_ARM_HOOK.lock().unwrap() = Some(Box::new(move || { ready_tx.send(()).unwrap(); resume_rx.lock().unwrap().recv_timeout(std::time::Duration::from_secs(10)).unwrap(); })); std::thread::scope(|scope| { let arm = scope.spawn(|| t.arm(p, p + PAGE)); ready_rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap(); assert_eq!(t.take(p, p + PAGE), [(p, p + PAGE)]); assert!(guards().watched.contains(&(p / PAGE)), "promotion really occurred"); resume_tx.send(()).unwrap(); arm.join().unwrap(); }); *LAB_ARM_HOOK.lock().unwrap() = None; // An armed GPU-write range must retain these pre-write bytes. unsafe { (p as *mut u32).write_volatile(0xDEAD_BEEF) }; let before = t.saved(p / PAGE).map(|bytes| u32::from_le_bytes(bytes[..4].try_into().unwrap())); t.disarm(); drop(t); free(p); assert_eq!(before, Some(0xAAAA_5555), "arming lost its pre-write snapshot"); } ```
Texbirds commented 2026-11-28 08:39:01 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Texbirds on 2026-11-28T08:39:01Z.


Great catch @pickles976 — that WATCHED_PAGES == 0 skip was indeed an unsynchronized race against first-time promotion in protect_noting.

Fixed in 3de7653:

  • Removed WATCHED_PAGES and serialized Tracked::arm unconditionally under GUARDS (maintaining GUARDS -> Saved lock order), checking !g.watched.is_empty() before scanning g.watched.range(first..last).
  • Added the concurrent before-image regression test watch::tests::arming_during_hot_promotion_keeps_before_image.

Re-verified locally on Windows 11 x64 (RTX 3080 Ti):

  • cargo run --locked -p xtask -- policy: 191 files ok
  • cargo clippy --locked -p victory-gpu --all-targets -- -D warnings (default & --all-features): 0 warnings
  • cargo test --locked -p victory-gpu -- watch:: shadow::: 34/34 passed
<!-- greyfinch-sync:Marvisak/VIctory:comment:7236719444 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3615#issuecomment-7236719444). Originally posted by [Texbirds](https://github.com/Texbirds) on 2026-11-28T08:39:01Z. --- Great catch @pickles976 — that `WATCHED_PAGES == 0` skip was indeed an unsynchronized race against first-time promotion in `protect_noting`. Fixed in `3de7653`: - Removed `WATCHED_PAGES` and serialized `Tracked::arm` unconditionally under `GUARDS` (maintaining `GUARDS -> Saved` lock order), checking `!g.watched.is_empty()` before scanning `g.watched.range(first..last)`. - Added the concurrent before-image regression test `watch::tests::arming_during_hot_promotion_keeps_before_image`. Re-verified locally on Windows 11 x64 (RTX 3080 Ti): - `cargo run --locked -p xtask -- policy`: `191 files ok` - `cargo clippy --locked -p victory-gpu --all-targets -- -D warnings` (default & `--all-features`): 0 warnings - `cargo test --locked -p victory-gpu -- watch:: shadow::`: 34/34 passed
futurepro62 commented 2026-11-29 18:13:17 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by futurepro62 on 2026-11-29T18:13:17Z.


Full-suite run on NVIDIA, since this PR has no test report yet. Tested exact head 3de7653 (on its base 63bcca4).

Tested

  • NVIDIA GeForce RTX 5070 Ti 16 GB (Blackwell, 32-lane waves only, mesh shaders), driver 621.40, Ryzen 7 9800X3D, Windows 11 Home 26300, Rust 1.98.1 MSVC (pinned), dxil.dll from Windows SDK 10.0.26100 (the loader's default), debug.
  • cargo build --workspace --locked, then cargo test --workspace --locked --no-fail-fast -- --test-threads=4 --skip emit::memory_tests::heap_direct_texture_reads_mark_their_heap_index --skip descriptor::host::tests::dynamic_slots_are_held_until_released --skip memory::tests::lists_share_a_table_and_copies_keep_their_views --skip emit::stride_tests::a_heap_buffer_read_by_element_takes_the_views_stride --skip emit::stride_tests::a_heap_buffer_read_where_no_buffer_view_is_reads_zeros --skip emit::synthetic_tests::gathers_at_a_level_match_the_hardware: 875 passed, 0 failed, 12 ignored.
  • The new tests ran and passed: hot_write_watch_pages_promote_and_cool_without_faulting, hot_write_watch_page_shared_by_two_copies_notifies_both, arming_a_hot_write_watch_page_demotes_it_and_saves_pre_write_bytes, changed_on_hot_write_watch_page_distinguishes_written_from_untouched, non_copy_taken_and_remap_demote_hot_write_watch_pages, hot_write_watch_concurrent_churn_loses_no_writes, quiet_partial_refresh_preserves_the_next_write, hot_page_stays_visible_to_both_holders_while_a_writer_is_open, arming_during_hot_promotion_keeps_before_image.
  • --skip leaves out tests that fail on main 63bcca4 on this card too, not because of this PR: heap_direct_texture_reads_mark_their_heap_index ends the victory-shader test process with 0xc0000005 (#2571), so without the skip the rest of that crate never reports; dynamic_slots_are_held_until_released, lists_share_a_table_and_copies_keep_their_views and the two stride_tests hit the 1,000,000-view heap cap of NVIDIA drivers (#1835, #2317); gathers_at_a_level_match_the_hardware fails on lane 0 (#1744).

Not tested

  • AMD (the tests take the default adapter), a release build, the title (test run only).

AI use

  • Claude Code (Claude Opus 5.5) ran the tests and wrote this report. I checked it before posting.
<!-- greyfinch-sync:Marvisak/VIctory:comment:7260308929 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3615#issuecomment-7260308929). Originally posted by [futurepro62](https://github.com/futurepro62) on 2026-11-29T18:13:17Z. --- Full-suite run on NVIDIA, since this PR has no test report yet. Tested exact head `3de7653` (on its base `63bcca4`). **Tested** - NVIDIA GeForce RTX 5070 Ti 16 GB (Blackwell, 32-lane waves only, mesh shaders), driver 621.40, Ryzen 7 9800X3D, Windows 11 Home 26300, Rust 1.98.1 MSVC (pinned), `dxil.dll` from Windows SDK 10.0.26100 (the loader's default), debug. - `cargo build --workspace --locked`, then `cargo test --workspace --locked --no-fail-fast -- --test-threads=4 --skip emit::memory_tests::heap_direct_texture_reads_mark_their_heap_index --skip descriptor::host::tests::dynamic_slots_are_held_until_released --skip memory::tests::lists_share_a_table_and_copies_keep_their_views --skip emit::stride_tests::a_heap_buffer_read_by_element_takes_the_views_stride --skip emit::stride_tests::a_heap_buffer_read_where_no_buffer_view_is_reads_zeros --skip emit::synthetic_tests::gathers_at_a_level_match_the_hardware`: **875 passed, 0 failed, 12 ignored**. - The new tests ran and passed: `hot_write_watch_pages_promote_and_cool_without_faulting`, `hot_write_watch_page_shared_by_two_copies_notifies_both`, `arming_a_hot_write_watch_page_demotes_it_and_saves_pre_write_bytes`, `changed_on_hot_write_watch_page_distinguishes_written_from_untouched`, `non_copy_taken_and_remap_demote_hot_write_watch_pages`, `hot_write_watch_concurrent_churn_loses_no_writes`, `quiet_partial_refresh_preserves_the_next_write`, `hot_page_stays_visible_to_both_holders_while_a_writer_is_open`, `arming_during_hot_promotion_keeps_before_image`. - `--skip` leaves out tests that fail on main `63bcca4` on this card too, not because of this PR: `heap_direct_texture_reads_mark_their_heap_index` ends the `victory-shader` test process with `0xc0000005` (#2571), so without the skip the rest of that crate never reports; `dynamic_slots_are_held_until_released`, `lists_share_a_table_and_copies_keep_their_views` and the two `stride_tests` hit the 1,000,000-view heap cap of NVIDIA drivers (#1835, #2317); `gathers_at_a_level_match_the_hardware` fails on lane 0 (#1744). **Not tested** - AMD (the tests take the default adapter), a release build, the title (test run only). **AI use** - Claude Code (Claude Opus 5.5) ran the tests and wrote this report. I checked it before posting.
Texbirds commented 2026-11-29 18:24:52 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Texbirds on 2026-11-29T18:24:52Z.


Thank you @futurepro62 for running the full workspace suite on Blackwell (RTX 5070 Ti + 9800X3D, 875 passed, 0 failed at 3de7653, including all 9 new watch regression tests)!

With that hardware pass alongside @Desamodeth's Windows benchmark confirmation, @pickles976's concurrent arming race fix, and green CI, 3de7653 is clean and ready for merge.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7260463455 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3615#issuecomment-7260463455). Originally posted by [Texbirds](https://github.com/Texbirds) on 2026-11-29T18:24:52Z. --- Thank you @futurepro62 for running the full workspace suite on Blackwell (`RTX 5070 Ti` + `9800X3D`, `875 passed, 0 failed` at `3de7653`, including all 9 new `watch` regression tests)! With that hardware pass alongside @Desamodeth's Windows benchmark confirmation, @pickles976's concurrent arming race fix, and green CI, `3de7653` is clean and ready for merge.
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/3615:upstream-pr/3615'
git switch 'upstream-pr/3615'

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