Skip to content

GPU: a deferred copy of memory the submission's shaders write runs after the copy-backs - #2810

Open
kotekompotek wants to merge 4 commits into
Marvisak:mainfrom
kotekompotek:gpu/deferred-copy-after-gpu-writes
Open

kotekompotek wants to merge 4 commits into
Marvisak:mainfrom
kotekompotek:gpu/deferred-copy-after-gpu-writes

Conversation

@kotekompotek

@kotekompotek kotekompotek commented Nov 25, 2026 •

Copy link
Copy Markdown

Summary

Fixes #2781.

A title CopyBufferRegion (or buffer CopyResource) recorded behind a dispatch ran its deferred CPU copy at submission preparation — before ExecuteCommandLists — while the shader's writes reach title memory only in the post-fence copy-back. The copy therefore carried stale bytes. Symmetrically, a copy writing a destination the shaders also wrote had its result overwritten by the copy-back.

Deferred copies/fills now check the title ranges the submission's lists have declared GPU-written so far (Batch::gpu_writes, shared across all lists of the submission, so a copy in a later list sees an earlier list's writes). A copy touching a written range is queued on Batch::late and runs after the copy-backs but before the bottom-of-pipe writes that signal completion to the title. A copy recorded before the write in step order still runs at once, matching the console's asynchronous GPU ordering.

Behaviour changes to state

  • Unmapped source pages are now copied as zeros. Before, the copy was skipped unless both ranges were committed. copy_mapped writes zeros for unmapped source pages, and stops at the first unmapped page of the destination. This is the buffer copies' existing fallback, now shared by CopyMemoryToMemoryX.
  • Overlap. The pre-change direct path used std::ptr::copy (memmove). The deferred path copies through the process-memory read/write pair, which makes no promise for overlapping source and destination. Overlapping copies are already undefined behaviour for the console API this implements (CopyMemoryToMemoryX is the title's memcpy), so no overlap handling is added; non-overlapping copies are unaffected.

Later commits on this head

  • 2180802 — chained deferral: later copies touching a pending deferred range (either end) defer in order; Step::Fill stays at record time (its destination is the list's own upload memory); a GpuWrite over a pending destination clips the deferred copy.
  • 889d785 — CopyMemoryToMemoryX goes through defer_copy like the buffer copies; the last unconditional Step::Run/HostList::defer users are removed.
  • e2a68d9 — same-submission reads: Host::execute splits ExecuteCommandLists before a reader's segment and runs pending late copies/refreshes in between, so a reader in a later list sees the copy's bytes (a reader in the same list still sees stale bytes — no split point inside one list's step walk; stated in the test). Deferred sources are tracked and later writers to them defer in order (late_sourced).

Test plan

  • host::copy_order::a_copy_past_a_gpu_write_sees_what_it_wrote — end-to-end through Host::execute.
  • host::copy_order::deferred_copies_chain_and_a_later_gpu_write_wins — chained copies, fills, GPU-write clipping.
  • host::copy_order::a_late_copy_keeps_its_source_until_it_reads_it — source protection.
  • host::copy_order::a_read_of_a_late_copy_sees_it_in_a_split_submission — split submissions; documents the same-list limit.
  • cargo clippy -p victory-gpu --all-targets clean
  • In-title verification of the GPU: deferred CopyBufferRegion can read stale CPU memory before preceding GPU writes complete #2781 scenario (no direct report yet)

Generated with Devin

@Venom2054

Copy link
Copy Markdown

I ran the five-case guest CopyBufferRegion test from 34fc326c twice on this PR's head, 9ba6303, using a physical RTX 5070 Ti (driver 621.01) with the D3D12 debug layer enabled. All five cases passed both times.

Destination word (hex) #2608 head 5bf6464 Fix 34fc326 This PR 9ba6303
Producer then copy in one list 11223344 55667788 55667788
Two lists in one submission 11223344 55667788 55667788
Separate submissions 55667788 55667788 55667788
Copy from a disjoint range aabbccdd aabbccdd aabbccdd
Copy before the producer 11223344 11223344 11223344

I used the same guest test and controls on all three revisions. 5bf6464 is the parent of 34fc326. This PR branches from 13f91ca. The GPU and CPU source checks returned 55667788, adjacent sentinels stayed intact, and the device remained healthy. Debug message 1419 was already queued before the cases began. This verifies four-byte buffer-copy ordering on hardware. The in-game effect on BVH construction and lighting remains unmeasured.

@fuzeofficlal

Copy link
Copy Markdown
Contributor

Verified 9ba63034 on Windows 11 (RTX 5090 + WARP, --features diagnostics):

One ordering edge case worth flagging in the same Batch submission: batch.late defers a copy whose src or dst overlaps batch.gpu_writes, but does not record the deferred copy's own dst range (B) as pending for later ops in the same batch (gpu_written only checks batch.gpu_writes). When B, C, D are disjoint from shader-written A, three same-batch sequences can still run out of recording order:

  1. shader1 writes A -> Copy(dst=B, src=A) [deferred to batch.late] -> Copy(dst=C, src=B): gpu_written(B) is false, so B -> C executes eagerly before A -> B runs, copying stale B into C.
  2. shader1 writes A -> Copy(dst=B, src=A) [deferred] -> shader2 reads B (Step::Refresh(B) / Step::Fill): Refresh runs in batch.flush() before ExecuteCommandLists, while A -> B runs after copy-back, so shader2 sees stale B.
  3. shader1 writes A -> Copy(dst=B, src=A) [deferred] -> Copy(dst=B, src=D): D -> B runs eagerly, then batch.late runs A -> B afterward and overwrites D's data.

Tracking deferred dst ranges (so subsequent copies touching B also defer in order, and a shader read of B forces a batch split/flush) would close all three chains.

…ter the copy-backs

A title CopyBufferRegion recorded behind a dispatch reads its source at
submission preparation, before the lists run: the shader's bytes reach
title memory only in the post-fence copy-back, so the copy carried old
data (issue Marvisak#2781). A copy whose destination they write was likewise
overwritten by the copy-back.

Deferred copies and fills now check the title ranges the submission's
lists declared GPU-written so far (recorded per shared batch, so a copy
in a later list sees an earlier list's writes): one touching a written
range runs late, after the copy-backs and before the bottom-of-pipe
writes that signal completion to the title. Copies in step order before
the write still run at once, matching the console's asynchronous GPU.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@kotekompotek
kotekompotek force-pushed the gpu/deferred-copy-after-gpu-writes branch from 9ba6303 to bcd9329 Compare November 25, 2026 22:48

@AwsAli05 AwsAli05 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The late-copy check misses dependencies through an earlier late copy. I added a final pool 1 -> pool 3 to the existing copy-order fixture at bcd9329, after it recorded pool 0 -> pool 1. Pool 0 is the GPU-written range. On the RTX 5070 Ti, pool 1 correctly received 0xBB, while pool 3 received its old 0x00 instead of 0xBB.

The second copy runs during preparation because neither of its ranges is in gpu_writes. A pending late copy's destination needs to participate in the dependency check so later consumers wait too. Please add the chained-copy regression alongside the direct cases.

AI-assisted review and local synthetic test.

@HLVM04

HLVM04 commented Nov 25, 2026

Copy link
Copy Markdown

An in-title count for the open "in-title verification" item, from the fork (fxceless/victory-fork), not this PR's code. The fork has the same order: Host::submit runs each list's deferred CPU copies (run_deferred -> copy_mapped) before ExecuteCommandLists, and shader writes reach title memory only later.

RTX 5070 Ti, Series S profile, one instrumented 200 s run:

  • About 2,000 title buffer copies read a source that shaders in an earlier list of the same submission write. All of them came during loading (about 58-86 s in).
  • About 25% of those also have their destination read by shaders later in the same submission. So the chained case raised in the review above (a late copy's destination counting as pending for later readers) does occur in the title, not only in synthetic tests.
  • A local change of ours with the same idea (hold such copies until the submission's writes have landed; fills left as they are, since their destination is the list's own upload memory) cost no measurable frame time. It did not fix the intermittent black character skin we were chasing (fine in 4 of 6 runs with it, 2 of 6 without, which is not significant).

One run for the counts, so they will vary with the scene.

@kotekompotek

Copy link
Copy Markdown
Author

Useful data — thanks for instrumenting it in-title. The ~25% chained rate is exactly the case the gpu_writes/late ordering covers: a late copy's destination stays pending for later readers because the copy runs after the copy-backs but before the writes that signal completion, so the chain can't read back a not-yet-written destination. Good to hear the same idea costs nothing measurable at 60 fps — matches the expectation (the deferred list just reorders work the submitting thread already did).

The black-skin chase being unaffected is consistent with this fix's scope — it only removes stale reads at submission boundaries, not visual artifacts with other causes.

Airamek added a commit to Airamek/VIctory that referenced this pull request Nov 26, 2026
Port of Marvisak#2810 mechanism (no knobs in the PR). A
deferred title copy or fill touching a range the submission's shaders
write no longer runs at submission time (its source is still old, its
destination would lose the GPUs bytes): Batch records Step::GpuWrite
ranges, such copies park in Pending::late, and complete() drains them
via copy_mapped after run_back, before bottom-of-pipe writes. This
fixes the open defer_resolve gap (stale source reads and clobbered
destinations in the async world); new copy_order test proves source,
destination and untouched paths.

Adapted to our async completion split (late travels on Pending from
execute_inner to complete) and our defer_host signature; test drains
the submission before volatile reads.

Gates: cargo test --workspace --locked green (except pre-existing
victory-hle dstorage page-list failure, fails on clean base too;
known parallel timing/GPU flakes observed and cleared on re-runs, all
pass in isolation); clippy -D warnings clean; xtask policy clean.

Hygiene: worktree hunks verified mine (host.rs only, Marvisak#2810 scope).

Marvisak commented Nov 26, 2026 •

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

Thanks for 889d785. copy_memory (CopyMemoryToMemoryX, list.rs) now records through HostList::defer_copy, so it gets the same gpu_written/late_pending ordering as the buffer copies, and the write-watch guard of copy_mapped. Step::Run and HostList::defer lose their last caller and are removed. a_memory_copy_past_a_gpu_write_sees_what_it_wrote covers the call through the real list entry point. That part reads right.

Two behaviour changes come with it. Please state them in the description:

  • Unmapped source pages are now copied as zeros. Before, the copy was skipped unless both ranges were committed. copy_mapped now writes zeros for unmapped source pages, and stops at the first unmapped page of the destination.
  • Overlap. The old code used std::ptr::copy, which is overlap-safe. copy_mapped goes through ReadProcessMemory, which makes no promise for overlapping source and destination. If the title can call CopyMemoryToMemoryX on overlapping ranges, that needs handling.

The two gaps from the last triage are still open on this head (Batch in host.rs):

  • A read in the same submission still sees stale bytes. A Refresh/Heap/Memory range over a deferred destination goes to late_refresh, which runs after ExecuteCommandLists. A shader later in the same submission that reads that destination still reads the old shadow. Splitting the batch at that point would fix it. HLVM04's count in the thread shows this chain occurs in the title (about 25% of such copies).
  • The deferred copy's source is not protected. A copy deferred because of its destination reads its source after the lists run. A later Step::Copy that writes that source, with neither range GPU-written or pending, still runs at once. Recording deferred sources as pending for later writers would close it.

Tests that fail on this head for those two sequences, and pass with the fix, would change the verdict.

CI: passing.


Generated by Claude Code

Two review findings on the deferral:

- A fill writes the list's own upload memory, which its commands read
  while it runs: deferring one past ExecuteCommandLists leaves the GPU
  reading memory the fill never reached. Fills copy at once again; a
  source the shaders write stays old there, as it was before the
  deferral existed.

- A deferred copy's title destination was not recorded as pending, so a
  later copy reading or overwriting it ran early (with the stale bytes),
  and a later refresh of it refreshed before its bytes landed. The
  pending destinations are now tracked: a copy touching one defers in
  order behind it, a refresh touching one runs just after the late
  copies, and a GPU write recorded over one keeps the shader's bytes
  (the deferred copy's covered part is dropped, as on the console where
  the later write wins).

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@kotekompotek

Copy link
Copy Markdown
Author

Both findings addressed in 2180802:

  • Step::Fill no longer defers — back to an unconditional copy_mapped at record time. A fill's destination is the list's own upload memory, read by its commands while it runs; it cannot wait for the copy-backs. A GPU-written source stays old, as before the deferral.
  • Chained deferral — Batch now tracks each deferred copy's title destination as pending. A later Step::Copy whose source or destination touches a pending range defers in order behind it (so it reads the deferred bytes, and the later write still wins by ordering). A later Step::Refresh/Heap/Memory range touching one is queued in late_refresh and runs right after the late copies. And a Step::GpuWrite recorded over a pending destination clips the covered part of the deferred copy — console order has the later shader write win.

copy_order gained deferred_copies_chain_and_a_later_gpu_write_wins, which discriminates all three: the chained copy reads 0xBB (not the stale pool byte), the fill lands 0xAA (old source — proving it ran at record time), and the range written by a later GpuWrite keeps the shader's 0xEE.

@kotekompotek

Copy link
Copy Markdown
Author

CI failure on 2180802 is a pre-existing flake, not this change: frame::tests::waits_end_on_ticks_and_count_frames polls the origin with a zero time-out twice in a row, and a host that wakes the thread a whole 2 ms tick late between the asks makes the second one return S_OK (the failure's left/right). #3080 hardens it.

It was the last step writing title memory outside the deferred copies,
so it read a source the submission's shaders write before the copy-backs
and lost a destination to them; chaining past a deferred copy's
destination did not reach it either. Routed through defer_copy it orders
like the buffer copies, its write is guarded from the write-watch like
theirs, and its unmapped pages fall back the same way. The title-memory
step kind is gone with it.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@kotekompotek

Copy link
Copy Markdown
Author

889d785 — same defect, adjacent callsite: CopyMemoryToMemoryX ran as the only step kind that writes title memory outside the deferred copies, so it read a GPU-written source stale, lost a GPU-written destination, and did not chain past a deferred copy's destination. It now goes through defer_copy, which also guards its write from the write-watch and gives its unmapped pages the buffer copies' fallback; the now-unused title-memory step kind is removed. a_memory_copy_past_a_gpu_write_sees_what_it_wrote covers it through the real list calls.

A read of a deferred copy's destination in the same submission saw the
stale shadow bytes: the copy ran after the whole ExecuteCommandLists.
Tag deferred copies with the list that produced them and refresh notes
with the list that reads them, and split ExecuteCommandLists before a
reader's segment so the copy lands in its shadow first.

A copy writing a deferred copy's source ran eagerly and clobbered the
bytes the deferred one was waiting to take. Track the sources too and
defer a copy whose destination is one.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@kotekompotek

Copy link
Copy Markdown
Author

Both remaining gaps are addressed in e2a68d9:

  • Same-submission reads now see the deferred bytes. Deferred copies carry the run-index of the list that produced them, and each late_refresh note carries the run-index of its reader. Host::execute splits ExecuteCommandLists before a reader's segment and runs the pending late copies and refreshes in between, so a reader in a later list sees the copy's bytes. Phase-run refreshes also skip ranges that segment's shaders write, so they can no longer clobber GPU output. Limit, stated in the test: a reader in the same list as the producer still sees stale bytes — there is no split point inside one list's step walk.
  • Deferred sources are protected. late tracks each deferred copy's source range, and a Step::Copy whose destination touches one defers in order behind it (late_sourced), so the later writer cannot clobber the bytes the deferred copy is waiting to take. clip_late keeps shrinking both the tracked destination and source.

copy_order gained two discriminators: a_late_copy_keeps_its_source_until_it_reads_it (a writer to a deferred source defers; the late copy still reads 0xBB) and a_read_of_a_late_copy_sees_it_in_a_split_submission (samples shadow bytes at each list's boundary: [0x55, 0xBB] across two lists, and documents the same-list limit). All 4 copy_order tests pass; clippy clean.

The other 5 failures in a local -p victory-gpu run reproduce on the base commit on this hardware (GTX 1050-class): a_texture_written_in_one_format…, compute_view_marks_rebind_after_depth_twin_conversion, dynamic_slots_are_held_until_released, lists_share… (the known baseline), and the waits_end_on_ticks… flake.

Steenax6 added a commit to Steenax6/VIctory-NVID that referenced this pull request Nov 26, 2026
… runs settle the flights, a deferred copy keeps its place

The title rewrites its per-draw constants in many small places of blocks
that shaders in the air may write. A page with more than 512 changed runs
made the submitting thread wait for every flight to land, about once a
frame and 12 ms of it in the first room. Such a block now goes up as one
run (VICTORY_MERGE_BLOCK_RUNS, 32) and no page's runs settle the flights:
the census counts 0 settles for it, in the prologue and in the open world.

A title buffer copy left to its landing keeps its place among what reads
and writes its destination (after Marvisak/VIctory pull request Marvisak#2810,
our own design; its four orders are tests here), the copies with
something to send are kept in a list, the write journal is a table by
page, and preparing reads the clock only for the steps it times (after
pull request Marvisak#3096). A census says whose writes are read again, who opens
guards, who touches what shaders write and who asks; a line counts the
copies made ahead of their own submission's shaders.

Runs of 2026-11-26 on an RTX 4070 Ti, quiet machine: first room 69.6 ms a
frame (14.4 fps; 74.7 to 77.4 before), the open world's bedroom 89.5 ms
(94.8 to 95.3 before); pictures right, no error and no device loss.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Steenax6 added a commit to Steenax6/VIctory-NVID that referenced this pull request Nov 26, 2026
…pies, small takes, landings beside the guards

The buffer work: a block the title rewrites in many places under flights
goes up as one run and no page's runs settle the flights
(VICTORY_MERGE_BLOCK_RUNS), a title buffer copy left to its landing
keeps its place among what reads and writes its destination (after
Marvisak/VIctory pull request Marvisak#2810; its orders are tests here), the
copies with something to send are kept in a list, the write journal is a
table by page, and preparing reads the clock only for the steps it times
(after Marvisak#3096). What shaders wrote lands in title memory beside the
guards, through views of our own (VICTORY_LAND_BESIDE, on; `=2` reads
every write back through the title's address and counted none amiss in
the prologue and in the open world): guarded blocks stay read-only and
are counted written. A refresh that no event has touched can be left out
(VICTORY_REFRESH_EVENTS, off until its check form `=2` has run). A view
heap that goes takes with it what the pass over picked buffer views kept
for it (fxceless/victory-fork pull request Marvisak#1276).

The small takes: the host device is made on the adapter the system ranks
first, never a software one, and the log names it (Marvisak#3073); a clear value
the host cannot take is dropped (Marvisak#3065); a raw buffer view's range stays
inside its buffer (fxceless Marvisak#1266); the structure builder turns off when
title memory by address has no copy number left (fxceless Marvisak#1265);
concurrent crash records are kept whole (Marvisak#3092); the title's idle and
lowest threads run below normal (Marvisak#2903); unordered views the title
places in memory get a texture of the host's own; VICTORY_CRASH_DUMP_DIR,
`cargo xtask refusals <log>`, VICTORY_MAP_LEAN and
VICTORY_DSTORAGE_STAGING_MB (off until measured).

A lost host device says its context line by line, a failure on it waits
for the report that names the stopped list, and the tests on the
software adapter run one at a time (they died at random in parallel).

Runs of 2026-11-26 on an RTX 4070 Ti: first room 69.6 ms a frame with
the buffer work (77.4 before) and 68.7 ms with landings beside the guards
(75.5 without, same build). This work lost the host device at the
world's entry in 4 of 9 runs until a list held the targets it binds
(already in the tree); with that, 0 of 6.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@kotekompotek

kotekompotek commented Nov 26, 2026 •

Copy link
Copy Markdown
Author

Both behaviour changes are now stated in the description (unmapped pages copied as zeros; overlap undefined, matching the console API's memcpy semantics). The two gaps were addressed in e2a68d9, pushed after the triage head 889d785: same-submission readers see deferred bytes through split submissions, and deferred sources defer later writers in order - with the discriminating tests listed above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GPU: deferred CopyBufferRegion can read stale CPU memory before preceding GPU writes complete

6 participants