GPU: a copy into title memory snapshots from the bytes it is about to write #3241

Closed
github-bot wants to merge 2 commits from github-bot/gh-3241 into main AGit
Owner

@⁠borosf on GitHub · 2026-11-26 14:19 UTC · original
borosf:vibe/copy-snapshot-bytes-842ca5 → main · +0 −0 · 0 files · 2 commits · closed without merging

A host-to-title copy told the write tracker to keep the destination pages it had taken, and the tracker read each of them back out of the process to do it.

What it did per destination page

copy_mapped wraps every title-destination copy in watch::writing, which marks the pages changed and, for each armed page a tracker had taken, calls Changed::save:

let mut bytes = vec![0u8; PAGE].into_boxed_slice();   // 64 KiB allocation
if crate::host::read_into((page * PAGE) as *const u8, &mut bytes) { ... }  // 64 KiB ReadProcessMemory

A 64 KiB allocation, a 64 KiB zeroing and a 64 KiB ReadProcessMemory — a kernel transition — while the guards' lock is held, to snapshot a page whose new content the caller was holding in the very buffer it was about to copy from. Tracked::refreshed then lays those same bytes over the saved page again after the copy.

What it does now

watch::writing_from(at, len, src) hands the tracker the caller's buffer. Incoming::whole_page decides per page:

  • the copy covers the page whole → the page's bytes after the write are the caller's, so the snapshot is that page of the buffer: one memcpy, no kernel read, no zeroing;
  • the copy covers the page in part (the two ends of every copy) → still read back, which is why the read is spared where it is provably pointless rather than removed.

Keep makes the three states explicit — Nothing, ReadBack, From(...) — so the fault handler's own path (watch.rs's vectored handler), the Writing drop and a remap all keep exactly the behaviour they had.

Why the caller's bytes can stand in for the page

track_as takes a range's pages from runtime_pages, which accepts only mapped pool and view pages; g.holders therefore never contains a hole, so no page here can be one whose read-back would have failed and left nothing saved. That is the property the substitution rests on and the reason it needed no VirtualQuery.

Measured

Intel Arc B580, Windows 11, --release, 64 armed pages of a write-watched pool, 20 rounds:

cargo test --release -p victory-gpu --lib --locked -- --exact --ignored --nocapture \
  watch::tests::a_copy_saves_a_page_without_reading_it_back

read back:      4234 ns per page
from the copy:  1392 ns per page

−67 % on the snapshot a copy pays per destination page. Multiplying that by pages per frame is what the frame line's existing saved counter reports; this PR does not claim a frame-time number for the title.

Not changed, deliberately

The guards' lock is still held across the snapshot. Dropping it is not a free win: the comment at changed records why the save must precede any page being opened — once a page is open another thread's write lands without a fault, and a save after it keeps that write as the page's old bytes. What is removed here is the kernel read, not the lock.

Verification

  • cargo clippy -p victory-gpu --all-targets --locked -- -D warnings — clean.
  • cargo clippy -p victory-gpu --all-targets --all-features --locked -- -D warnings — clean.
  • cargo test -p victory-gpu --lib --locked --no-fail-fast — 230 passed, 2 failed, both the known Intel baseline failures pristine main also fails (descriptor::host::tests::dynamic_slots_are_held_until_released, memory::tests::lists_share_a_table_and_copies_keep_their_views, #1744/#1829).
  • New test watch::tests::a_copy_saves_the_bytes_it_is_about_to_write: two whole pages keep the copy's bytes, the partly covered third page keeps what was there before the copy, and a byte written before arming is still in it.
  • rustfmt --edition 2024 --check, hunk counts against main: watch.rs 39/39, host.rs 85/85 — no new formatting hunks.

The other writing callers (shadow.rs's copy-back and texture uploads, list.rs's uploads) hold their bytes too and are the natural follow-up; they are left out here to keep this to the one path with a measured number.

Synthetic tests only; no game data.

Part of the fifteen gaps claimed for this sweep on #1633. AI-assisted.

**@⁠borosf** on GitHub · 2026-11-26 14:19 UTC · [original](https://github.com/Marvisak/VIctory/pull/3241) `borosf:vibe/copy-snapshot-bytes-842ca5` → `main` · +0 −0 · 0 files · 2 commits · closed without merging A host-to-title copy told the write tracker to keep the destination pages it had taken, and the tracker read each of them back out of the process to do it. ## What it did per destination page `copy_mapped` wraps every title-destination copy in `watch::writing`, which marks the pages changed and, for each armed page a tracker had taken, calls `Changed::save`: ```rust let mut bytes = vec![0u8; PAGE].into_boxed_slice(); // 64 KiB allocation if crate::host::read_into((page * PAGE) as *const u8, &mut bytes) { ... } // 64 KiB ReadProcessMemory ``` A 64 KiB allocation, a 64 KiB zeroing and a 64 KiB `ReadProcessMemory` — a kernel transition — **while the guards' lock is held**, to snapshot a page whose new content the caller was holding in the very buffer it was about to copy from. `Tracked::refreshed` then lays those same bytes over the saved page again after the copy. ## What it does now `watch::writing_from(at, len, src)` hands the tracker the caller's buffer. `Incoming::whole_page` decides per page: - the copy covers the page **whole** → the page's bytes after the write are the caller's, so the snapshot *is* that page of the buffer: one `memcpy`, no kernel read, no zeroing; - the copy covers the page **in part** (the two ends of every copy) → still read back, which is why the read is spared where it is provably pointless rather than removed. `Keep` makes the three states explicit — `Nothing`, `ReadBack`, `From(...)` — so the fault handler's own path (`watch.rs`'s vectored handler), the `Writing` drop and a remap all keep exactly the behaviour they had. ## Why the caller's bytes can stand in for the page `track_as` takes a range's pages from `runtime_pages`, which accepts only mapped pool and view pages; `g.holders` therefore never contains a hole, so no page here can be one whose read-back would have failed and left nothing saved. That is the property the substitution rests on and the reason it needed no `VirtualQuery`. ## Measured Intel Arc B580, Windows 11, `--release`, 64 armed pages of a write-watched pool, 20 rounds: ``` cargo test --release -p victory-gpu --lib --locked -- --exact --ignored --nocapture \ watch::tests::a_copy_saves_a_page_without_reading_it_back read back: 4234 ns per page from the copy: 1392 ns per page ``` **−67 % on the snapshot a copy pays per destination page.** Multiplying that by pages per frame is what the frame line's existing `saved` counter reports; this PR does not claim a frame-time number for the title. ## Not changed, deliberately The guards' lock is still held across the snapshot. Dropping it is not a free win: the comment at `changed` records why the save must precede any page being opened — once a page is open another thread's write lands without a fault, and a save after it keeps that write as the page's old bytes. What is removed here is the kernel read, not the lock. ## Verification - `cargo clippy -p victory-gpu --all-targets --locked -- -D warnings` — clean. - `cargo clippy -p victory-gpu --all-targets --all-features --locked -- -D warnings` — clean. - `cargo test -p victory-gpu --lib --locked --no-fail-fast` — 230 passed, 2 failed, both the known Intel baseline failures pristine `main` also fails (`descriptor::host::tests::dynamic_slots_are_held_until_released`, `memory::tests::lists_share_a_table_and_copies_keep_their_views`, #1744/#1829). - New test `watch::tests::a_copy_saves_the_bytes_it_is_about_to_write`: two whole pages keep the copy's bytes, the partly covered third page keeps what was there before the copy, and a byte written before arming is still in it. - `rustfmt --edition 2024 --check`, hunk counts against `main`: `watch.rs` 39/39, `host.rs` 85/85 — no new formatting hunks. The other `writing` callers (`shadow.rs`'s copy-back and texture uploads, `list.rs`'s uploads) hold their bytes too and are the natural follow-up; they are left out here to keep this to the one path with a measured number. Synthetic tests only; no game data. Part of the fifteen gaps claimed for this sweep on #1633. AI-assisted.
Every host-to-title copy told the write tracker to keep the destination
pages it had taken, and the tracker answered by reading each of them back
out of the process: a 64 KiB allocation, a 64 KiB zeroing and a 64 KiB
`ReadProcessMemory` — a kernel transition — while holding the guards' lock,
for a page whose new content the caller was already holding in the buffer
it was about to copy from. The snapshot was then partly overwritten again
by `Tracked::refreshed` with those same bytes.

`watch::writing_from` hands the tracker the caller's buffer. A page the
copy covers whole keeps those bytes as the page's own: they are what the
page holds the moment the write lands, so nothing is read back. A page the
copy covers in part (the two ends of every copy) is still read back, so
the read is spared where it is provably pointless rather than replaced —
`Keep` says which of the three things a mark does.

The pages a `Tracked` covers are the runtime's own: `track_as` takes them
from `runtime_pages`, which only accepts mapped pool and view pages, so the
caller's bytes stand in for a page that cannot be a hole.

Measured on an Intel Arc B580, `cargo test --release -p victory-gpu --lib
-- --exact --ignored --nocapture
watch::tests::a_copy_saves_a_page_without_reading_it_back`, 64 armed pages
of a write-watched pool, 20 rounds:

    read back:      4234 ns per page
    from the copy:  1392 ns per page

−67 % on the snapshot a copy pays per destination page. The world's copies
are the largest bucket of its frame; how many of their pages reach this
path is what the existing `saved` counter on the frame line reports, and
this change does not claim that number.

The guards' lock is still held across the snapshot. Dropping it would let
another thread's write land between the save and its own, which the comment
at `changed` names as the reason the save comes before any page is opened;
the cost removed here is the kernel read, not the lock.

Verification: `cargo clippy -p victory-gpu --all-targets --locked -- -D
warnings` and the same with `--all-features`, both clean; `cargo test -p
victory-gpu --lib --locked --no-fail-fast` 230 passed, 2 failed — both are
this card's known baseline failures that pristine main also fails
(`descriptor::host::tests::dynamic_slots_are_held_until_released`,
`memory::tests::lists_share_a_table_and_copies_keep_their_views`, #1744).
`rustfmt --edition 2024 --check` hunk counts against main: watch.rs 39/39,
host.rs 85/85. New test `a_copy_saves_the_bytes_it_is_about_to_write` covers
a whole-page copy, a two-page copy and the partly covered page that must
still be read back.

Synthetic tests only; no game data.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 14:27:13 +00:00
Author
Owner

@⁠Dukestar69 on GitHub · 2026-11-26 14:33 UTC · original · reviewed

Reviewed the diff and ran local verification on Windows 11 x64 (cargo test -p victory-gpu --lib watch:: -- --test-threads=1: 16 passed, 1 ignored; cargo clippy -p victory-gpu --all-targets -- -D warnings: clean; cargo xtask policy: 191 files ok).

I cannot approve this as-is because there are two correctness/soundness issues with saving src (the incoming bytes) as the tracker's saved snapshot:

  1. Inverts the 3-way merge in shadow.rs (merge_writeback) and clobbers the copy's own writes:
    Changed::save records the pre-write baseline (efore) matching what the GPU shadow (host) started with before the shader ran. In crates/victory-gpu/src/shadow.rs (copy_back_page, lines 515-523), merge_writeback(&mut title, host, before) decides which bytes the GPU modified by testing host[i] != before[i] and copying host[i] into itle[i].
    If efore is instead set to the new incoming bytes src, then for every byte i that copy_mapped changed (src[i] != old[i]) and the GPU did not touch (host[i] == old[i]), host[i] != before[i] evaluates to rue — so merge_writeback treats old[i] as a GPU write and overwrites the newly copied byte in itle back to old[i].
  2. Unsound userspace dereference of src in copy_mapped:
    copy_mapped explicitly uses ReadProcessMemory (
    ead(src, dst, len)) with a 64 KiB / 4 KiB fallback specifically because src is not guaranteed to be mapped/readable across all len bytes (see host.rs lines 2474-2476 and 2503-2530). Calling unsafe { std::slice::from_raw_parts(src, PAGE) } inside Changed::save dereferences src directly without ReadProcessMemory, which will fault/crash if src contains an unmapped or PAGE_NOACCESS page (and if
    ead fails and itle_dst && !committed(dst, len) returns early, dst was never even written).

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

**@⁠Dukestar69** on GitHub · 2026-11-26 14:33 UTC · [original](https://github.com/Marvisak/VIctory/pull/3241#pullrequestreview-6075895875) · **reviewed** Reviewed the diff and ran local verification on Windows 11 x64 (cargo test -p victory-gpu --lib watch:: -- --test-threads=1: 16 passed, 1 ignored; cargo clippy -p victory-gpu --all-targets -- -D warnings: clean; cargo xtask policy: 191 files ok). I cannot approve this as-is because there are two correctness/soundness issues with saving src (the incoming bytes) as the tracker's saved snapshot: 1. **Inverts the 3-way merge in shadow.rs (merge_writeback) and clobbers the copy's own writes:** Changed::save records the **pre-write** baseline (efore) matching what the GPU shadow (host) started with before the shader ran. In crates/victory-gpu/src/shadow.rs (copy_back_page, lines 515-523), merge_writeback(&mut title, host, before) decides which bytes the GPU modified by testing host[i] != before[i] and copying host[i] into itle[i]. If efore is instead set to the **new** incoming bytes src, then for every byte i that copy_mapped changed (src[i] != old[i]) and the GPU did *not* touch (host[i] == old[i]), host[i] != before[i] evaluates to rue — so merge_writeback treats old[i] as a GPU write and overwrites the newly copied byte in itle back to old[i]. 2. **Unsound userspace dereference of src in copy_mapped:** copy_mapped explicitly uses ReadProcessMemory ( ead(src, dst, len)) with a 64 KiB / 4 KiB fallback specifically because src is not guaranteed to be mapped/readable across all len bytes (see host.rs lines 2474-2476 and 2503-2530). Calling unsafe { std::slice::from_raw_parts(src, PAGE) } inside Changed::save dereferences src directly without ReadProcessMemory, which will fault/crash if src contains an unmapped or PAGE_NOACCESS page (and if ead fails and itle_dst && !committed(dst, len) returns early, dst was never even written). Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).
github-bot closed this pull request 2026-11-26 14:48:10 +00:00
Author
Owner

@⁠borosf on GitHub · 2026-11-26 14:43 UTC · original

Closing as unsound — the review is correct on both points, and I verified both against the code before reverting:

1. It clobbers the copy's own writes in the 3-way merge. merge_writeback's own oracle test (shadow.rs:40-62) defines old as the pre-copy baseline: host[i] == old[i] → keep the title's byte (which the copy just wrote), else take the host's. Tracked::refreshed — the only thing that lays copy bytes over saved — is called solely in the title→host direction (Shadow::copy, shadow.rs:688, title_dst = false). For a title_dst = true Step::Copy, saved must therefore remain the pre-write page bytes. With saved = src, every byte the copy changed and the GPU did not touch (host[i] == true_old[i], old[i] = src[i]) satisfies host[i] != old[i] and gets written back as the pre-copy byte. The copy's write is reverted.

2. src is not safe to dereference. read() uses ReadProcessMemory with a 64 KiB/4 KiB fallback precisely because src may contain unmapped pages (host.rs:2517-2530); std::slice::from_raw_parts(src, PAGE) in Changed::save faults on those. A page inside [at, at+len) being in g.holders says nothing about src at that offset.

Both are structural, not fixable by validating the pointer: the merge needs pre-write bytes, which src cannot provide. Reverted at 0c78456efe2515c09437d6979f19ec837d0e0cff (branch now equals main plus the revert).

Finding worth keeping (measured on Intel Arc B580, --release, 64 armed pages, 20 rounds): the snapshot a title_dst copy pays per destination page is 4,234 ns when read back via ReadProcessMemory (64 KiB alloc + zero + kernel read, under the guards' lock). Any fix must keep saved = pre-write bytes and not dereference src — e.g. snapshot from a validated copy of src made only after read reports the range whole, accepting that the save then follows the write for those pages (which the merge tolerates only where the copy covers the page, since the title byte is already the copy's). That design needs its own review; I am not claiming it here.

Synthetic tests only; no game data.

**@⁠borosf** on GitHub · 2026-11-26 14:43 UTC · [original](https://github.com/Marvisak/VIctory/pull/3241#issuecomment-7195228009) Closing as unsound — the review is correct on both points, and I verified both against the code before reverting: **1. It clobbers the copy's own writes in the 3-way merge.** `merge_writeback`'s own oracle test (shadow.rs:40-62) defines `old` as the pre-copy baseline: `host[i] == old[i]` → keep the title's byte (which the copy just wrote), else take the host's. `Tracked::refreshed` — the only thing that lays copy bytes over `saved` — is called solely in the title→host direction (`Shadow::copy`, shadow.rs:688, `title_dst = false`). For a `title_dst = true` `Step::Copy`, `saved` must therefore remain the **pre-write** page bytes. With `saved = src`, every byte the copy changed and the GPU did not touch (`host[i] == true_old[i]`, `old[i] = src[i]`) satisfies `host[i] != old[i]` and gets written back as the pre-copy byte. The copy's write is reverted. **2. `src` is not safe to dereference.** `read()` uses `ReadProcessMemory` with a 64 KiB/4 KiB fallback precisely because `src` may contain unmapped pages (host.rs:2517-2530); `std::slice::from_raw_parts(src, PAGE)` in `Changed::save` faults on those. A page inside `[at, at+len)` being in `g.holders` says nothing about `src` at that offset. Both are structural, not fixable by validating the pointer: the merge needs pre-write bytes, which `src` cannot provide. Reverted at `0c78456efe2515c09437d6979f19ec837d0e0cff` (branch now equals `main` plus the revert). **Finding worth keeping** (measured on Intel Arc B580, `--release`, 64 armed pages, 20 rounds): the snapshot a `title_dst` copy pays per destination page is **4,234 ns** when read back via `ReadProcessMemory` (64 KiB alloc + zero + kernel read, under the guards' lock). Any fix must keep `saved` = pre-write bytes *and* not dereference `src` — e.g. snapshot from a validated copy of `src` made only after `read` reports the range whole, accepting that the save then follows the write for those pages (which the merge tolerates only where the copy covers the page, since the title byte is already the copy's). That design needs its own review; I am not claiming it here. Synthetic tests only; no game data.
Author
Owner

@⁠borosf on GitHub · 2026-11-26 14:43 UTC · original

Reverted as unsound (see comment): the src-bytes snapshot breaks merge_writeback's baseline and dereferences a possibly-unmapped src. Revert pushed at 0c78456.

**@⁠borosf** on GitHub · 2026-11-26 14:43 UTC · [original](https://github.com/Marvisak/VIctory/pull/3241#issuecomment-7195228503) Reverted as unsound (see comment): the src-bytes snapshot breaks merge_writeback's baseline and dereferences a possibly-unmapped src. Revert pushed at 0c78456.

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No reviewers
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
github/Marvisak--VIctory!3241
No description provided.