Skip to content

GPU: preserve execution ordering for buffer copies - #387

Open
aycow wants to merge 14 commits into
Marvisak:mainfrom
aycow:fix/gpu-buffer-copy-ordering
Open

aycow wants to merge 14 commits into
Marvisak:mainfrom
aycow:fix/gpu-buffer-copy-ordering

Conversation

@aycow

@aycow aycow commented Nov 24, 2026 •

Copy link
Copy Markdown

Change

A title buffer copy or unaligned root CBV can read CPU staging before an earlier GPU write in the same title command list has run. The recording now cuts at a read of a known overlapping producer. Submission preparation completes the producer group before filling the dependent staging buffer. Unrelated work still batches.

The planner checks alias byte ranges for the dependency and whole pages for potentially withheld writes. For a staged reader after the last computed-address list, the host checks the mapping marks after the native fence. It publishes the prefix before preparing that reader only if no mapping missed and frame-level withholding is inactive. Otherwise the reader stages from published title memory. Actual withheld pages also guard against ordinary copyback through the same shadow.

An ordered buffer copy can now precede a refresh of the same shadow. On a miss, the fenced GPU ranges stay private and the refresh runs around them. Only the bytes the kernel reports writing to the title destination are reflected in those ranges, including writes through a known physical alias. Opaque host writes remain grouped.

A direct buffer-only root-CBV reader can now stage from a fenced producer before a later computed dispatch. This retains the address-map layout used by the producer and tracks the reader's derived buffer outputs through the final miss decision. Exact-range and marked-page copyback both hold those outputs on a miss. Independent writes still publish.

The interleaved path requires a single ordinary direct dispatch with known buffer outputs and a later buffer-only computed phase. Untracked readbacks, texture or dynamic descriptor effects, ambiguous shadow ownership, and replays across the phase boundary keep the original scheduling. These cases can still read the earlier published value. The PR leaves those paths available and does not change the scope of the title-memory miss policy.

An eligible staged read adds a native fence. Title workload frequency and cost remain unmeasured.

Synthetic validation

The current-main control at 13f91ca read 11 after a producer wrote 29. The revised title queue's CopyBufferRegion and all staged-CBV controls read 29. The plain WARP run required a device and passed 201 diagnostics GPU tests, with one ignored. Strict GPU diagnostics Clippy passed.

AMD Radeon Graphics, GeForce RTX 5070 Laptop GPU, and WARP passed the staged CBV, real title buffer copy, and write-withholding controls with full GPU-based validation. The native validation used a local Agility 1.620.2 adapter setup and startup sampler workaround. Neither is part of this PR.

On 53e5ee0, the computed fixture passed on AMD Radeon Graphics, GeForce RTX 5070 Laptop GPU, and WARP with full GPU-based validation. The staged root CBV and CPU copy both read 29 after a clean producer and 11 after a fresh miss or inherited withholding. The same-page refresh regression also preserved 29 for the native consumer and 55 from the neighboring CPU copy while withholding the computed dword from title memory. The hardware setup used Agility 1.620.2 with local startup compatibility adjustments for sampler validation and descriptor heap probing.

On f66fc14, the clean overlapping-copy case delivered 29 to the copied dword and the native consumer. After a miss, the private consumer retained 29, the neighboring CPU copy reached it as 55, and title memory retained 11 at the withheld source. AMD Radeon Graphics, GeForce RTX 5070 Laptop GPU, and WARP passed with the same full GPU-based validation setup. Additional controls cover physical aliases, same-value CPU overwrites, and unmapped destinations.

On be723f7, AMD Radeon Graphics, NVIDIA RTX 5070 Laptop GPU, and WARP passed six focused tests each with full GPU-based validation. The translated GFX10 root-CBV fixture validated its emitted DXIL and used the normal binding and dispatch path. All three native stages read 29. A clean run published [29, 29, 29]. A data-dependent late miss left title memory at [11, 0, 0] for both exact and page-marked derived writes, kept the unrelated output at 29, and caused the next refresh to discard the private value. A readback completion handler disabled private staging.

The WARP submission-count control measured one native submission for disjoint work, and two for each dependent read. Closed-list replay reproduced the correct copied value. Tests include the same-page withholding case and the opaque-address case. The checks use original synthetic data. Title frame time remains unmeasured.

$env:VICTORY_TEST_ORDERING_REQUIRE_GPU = '1'
$env:VICTORY_D3D12_WARP = '1'
cargo test --locked -p victory-gpu --features diagnostics --lib a_gpu_producer_feeds_the_real_root_cbv_staging_path -- --nocapture --test-threads=1
cargo test --locked -p victory-gpu --features diagnostics --lib title_copy_buffer_region_reads_its_earlier_gpu_producer -- --nocapture --test-threads=1
cargo test --locked -p victory-gpu --features diagnostics --lib host::withholding:: -- --test-threads=1
cargo test --locked -p victory-gpu --features diagnostics --lib computed_tail_reads_after_the_fence_without_publishing_a_miss -- --ignored --nocapture --test-threads=1
cargo test --locked -p victory-gpu --features diagnostics --lib computed_tail_preserves_the_private_producer_across_a_page_refresh -- --ignored --nocapture --test-threads=1
cargo test --locked -p victory-gpu --features diagnostics --lib translated_root_cbv_writes_stay_private_on_late_miss -- --ignored --nocapture --test-threads=1
cargo test --locked -p victory-gpu --features diagnostics --lib translated_root_cbv_writes_publish_without_late_miss -- --ignored --nocapture --test-threads=1
cargo test --locked -p victory-gpu --features diagnostics --lib a_readback_sink_disables_private_staging -- --ignored --nocapture --test-threads=1

The existing branch history retains the earlier continuation and copyback work, including jeremygold02's independent WARP validation. This revision uses main's current command-list segmentation and copyback. Earlier validation · Previous head

AI-assisted using OpenAI Codex.

@jeremygold02

Copy link
Copy Markdown
Contributor

Thanks @aycow for the execution-order regression coverage. I tested head b5d18276f5160fa60ac49c1f3c34ea2bbf8059a6 with the buffer-copy GPU tests:

$env:VICTORY_TEST_BUFFER_COPY='1'; $env:VICTORY_D3D12_WARP='1'; cargo test --locked -p victory-gpu --features diagnostics --lib list::buffer_copy_tests:: -- --test-threads=1

Result: 17 passed, 0 failed (46 filtered out). The cases cover ordered copies across lists/submissions, CPU/GPU staging handoffs, overlapping and disjoint ranges, copyback, and resource lifetime. I also tried the optional GPU-based-validation flag, but its debug-layer initialization was unavailable (0x887A002D); the test suite passed with that optional mode disabled.

@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown
Author

Thanks, @jeremygold02, for independently running all 17 buffer-copy tests on WARP and for including the exact command and head. The 0x887A002D detail also helps distinguish this run from the separate Agility SDK GPU-validation pass. I’m following up on the dirty-copy timing to see how much is spent refreshing source bytes, waiting for GPU completion, and copying writes back.

@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown
Author

Thanks again for the independent WARP run. The draft now includes df2276b, which speeds up dirty-buffer copyback while preserving the bytewise merge when the title changed memory after the GPU snapshot.

In eight alternating optimized AMD samples per revision, median total time for 128 dirty 1 MiB copies fell from 191.12 to 102.55 ms. The sparse workload fell from 90.72 to 73.77 ms. Both revisions produced matching outputs and byte counts. All 18 focused cases passed on AMD, NVIDIA, and WARP with the D3D12 debug layer and full GPU-based validation. The actual #322 composition also passed its mapping controls and the copy cases.

Could an independent tester run a controlled in-game A/B of b5d1827 and df2276b with the same integration stack, scene, settings, and diagnostics flags? Total submission time, copyback time and bytes, and frames completed before any device removal would help distinguish the copyback gain from timing variance.

edsuuu referenced this pull request in edsuuu/VI-BR-PORT Nov 24, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
edsuuu referenced this pull request in edsuuu/VI-BR-PORT Nov 24, 2026
Since #387 a title list's state accessor (`with_state`) goes through the
list being recorded, which after a title buffer copy opens a new native
continuation. Taking back and lending dynamic descriptor slots run at
submission, after the title closed the list: for a list whose last
command was a buffer copy they opened an empty continuation that was
submitted open. ExecuteCommandLists then removed the device
(DXGI_ERROR_INVALID_CALL; debug layer: "Command lists must be closed
before execution"), 13 s into every run on an RTX 4060 Ti.

They now lock the draw state directly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@aycow
aycow force-pushed the fix/gpu-buffer-copy-ordering branch from df2276b to 489c9bf Compare November 24, 2026 16:33
edsuuu referenced this pull request in edsuuu/VI-BR-PORT Nov 24, 2026
The tester tree (upstream main ffe310e plus its PRs, update 8; see its
INTEGRATION.md) ran 11-25 minutes in the world on an RTX 5070 without a
device removal. Where both sides carry the same PR (the wave64 stack
#223/#233/#320 with #439 and #180, #454, #336, #259, #331 and others), the
tester tree's newer head is taken; our own work and the PRs only we
merged are kept.

Conflicts, file by file:

- descriptor/host.rs: the tester layout (`spare`, the guard slot after the
  dynamic slots, `free_table`, the capped sampler heap). A capped view
  heap keeps `capped_reserve()` dynamic slots, now 2^18 by default (the
  tester measurement, and our 91fed158), still `VICTORY_DYNAMIC_SLOTS` in
  diagnostics builds; uncapped hosts keep our 2^19. Our slot statistics
  (TAKEN/PEAK/SHORT), the bindless plan cache (`CommittedRegions`,
  `timed_valid_title_address`, `timed_find`, `title_bounds`) and the
  revision triple are kept beside the tester's `guard_slot`.
- Buffer states: the tester tree's buffer-state tracker (#334: every list
  moves host copies of title memory between GENERIC_READ and
  UNORDERED_ACCESS and back to common before it closes) and depth twins
  (#469) are taken. #40's enhanced/legacy indirect barriers (the indirect
  prelude, `use_indirect_buffers`, the title buffer handoff mirrored in
  `host_barrier`) cannot share buffers with that tracker and are dropped;
  #40's argument checks (`byte_len`, exact spans, overflow-safe clamp
  shader, aligned counts) stay. `indirect::bound` and #282's
  `rectangles` go through `buffer_state`, and `indirect::execute` (#334)
  replaces `done`. #178's DXC fallback compiles both of our passes.
  Our segments (#387: `close` ends the segment, `close_native` closes a
  native list) carry the tracker: each native list returns its buffers
  to common and its twins to their depth targets, and each prelude also
  holds our texture uploads.
- shadow.rs: our write flow (`queue_write`, one `snapshot` after the
  batch's refreshes, `finish_writes`, the unchanged-page cache) with
  #261's copy-back that also gives the snapshot the title's bytes; its
  tests run through our flow.
- pipeline/make.rs: #275's per-frame budget and per-pipeline wake pair,
  with our compute waits (a dispatch waits for its pipeline, up to 20 s).
- pipeline/library.rs: the tester version (#347, #275's saver thread);
  our concurrent-write test kept. shader_cache.rs: our byte-returning
  cache API with #358's "translated, only not kept".
- draw.rs: #493's root SRV tables; where no table can stand in, our
  drop of a draw whose root view is unset or outside title buffers. Our
  refusal of a table offset past the capped heap stays.
- resource.rs: `HostTexture` has both our `staged` generation and the
  depth twin.
- Shaders: the tester's lower.rs for the wave64 stack, #160's image
  sampling (it covers our #73 and #136 sample forms) and #453/#587; kept
  from our side: #136's preference for an image or buffer use of a
  descriptor read as data and its `s_buffer_` arm, #422's nearest-even
  narrowing (also for #169's d16 loads and #453's interpolation), #452's
  spin-wait limit, #391's LDS limit, #302's spilled root arguments (now in
  `NativeProgram::translation_ir`), #136's PSV0 interpolation beside the
  tester's row harmonisation. split_tests.rs, lane_read_loop_tests.rs and
  docs/wave64-on-wave32.md are the tester versions (the same PRs at newer
  heads).
- Tests: #483's heap guard dwords filled in our GPU tests of #200
  (v_div_scale) and #437 (scalar loads from a raw view), which read
  through the guard slot otherwise; #334's debug-layer test passes an
  offset to our `indirect::bound`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The CPU may change constants inside a broad UAV declaration during submission preparation. Refresh them before GPU execution and keep an accurate copyback baseline.

Reported-by: Kevin Pratap Sidhu <pratapkevin8@gmail.com>

Reference: KevinPratap@7a03753
@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown
Author

Published 709647f on this branch, following @KevinPratap's #1322 repro. Current UAV declarations are now recorded during preparation and snapshotted before execution, after synchronous CPU refreshes. The focused fixture changed the observed constant from 11 to 43 and preserved the GPU write (77) and later CPU write (61). All 19 buffer-ordering tests passed on each of AMD Radeon Graphics, RTX 5070 Laptop and WARP with full GBV. Both workspace Clippy configurations passed. Duff's changed-byte concurrent copyback work (#1024) remains a separate candidate for measuring fragmented writes.

@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown
Author

I tested a new byte-precise candidate composed on 709647f, retaining Duff's authored change. SIMD comparison, a 4 KiB fallback for inaccessible neighbors, and fewer journal operations passed all 23 tests on AMD Radeon Graphics, RTX 5070 Laptop and WARP with full GBV. The partially mapped fixture preserved all 1,008 valid writes and took 2.786 ms of CPU copyback.

For five alternating optimized Windows samples over 4 MiB, old byte runs versus this candidate were 6.713→2.217 ms dense, 4.234→1.658 ms sparse, and 784.636→634.196 ms fragmented. The changed-byte candidate remains separate from this draft because fragmented workloads still need one guarded kernel write per run. A protection query or VirtualLock is insufficient to guarantee the saved destination mapping survives through direct stores. The synchronous ordering fix on the draft stays independently reviewable.

Use the existing title-byte dependency planner when a submission records shader-side buffer writes, including submits without buffer-copy continuations. Split at overlapping staged reads and retain a single native submission for non-overlapping work.
@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown
Author

Published 0899b7d to this PR. Exact rgarage and 709647f both reproduced stale staged root and table constants (11) when an earlier closed list in the same submission wrote 29. The normal path had bypassed title-byte dependency planning when no buffer-copy continuation existed. The fix uses that planner for recorded GPU writes and splits only when the later staging read overlaps. Both staged routes now read 29, and the permanent regression verifies two native calls for overlapping work and one for unrelated work.

All 20 buffer-ordering tests plus the nine material staging controls passed on each of AMD and NVIDIA hardware and WARP with full GBV. Both strict workspace Clippy configurations and asset policy passed. This resolves the ordinary two-list case. The title colour operand source, copies inside one native list, and the separate concurrent-write copyback cost are still open.

@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown
Author

The new diagnostics composition passed its allocation/reset control on AMD and WARP. The independent 4 MiB CPU reconciliation profile found that 131,072 checked writes took 1,805.63 ms with Win32 and 114.69 ms with the native primitive already under review in #1215. Replay into an explicitly owned fixture mapping took 2.50 ms, and the metadata-only control took 2.18 ms. The direct path depends on ownership of the mapping and its protection. The guard and partial-mapping behavior of a general write backend remains under review, so #387 stays in draft. Contributor coordination and protection result.

AI-assisted using Codex.

Marvisak commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

Still needs work. The only push since the last triage is 86c3887, a merge of current main that keeps the recorded copyback layout. The branch merges cleanly and CI (check) passes. None of the three earlier asks has been addressed yet:

  • Split. The interleaved private-staging path is still in this PR: interleaved_reader, Batch::allow_private_reader/stage_private/preserve_gpu_writes, and draw/interleaved_tests.rs. Please limit this PR to the ordering cut and submission split (list.rs, cpu_read_boundaries, computed_tail) and put the rest in a follow-up.
  • Title cost. There is still no in-game before/after for the fence and CPU wait each dependent read adds (submissions per frame, submission time, number of cuts in a fixed scene).
  • Failure mode. Host::require_batch_fence still calls fail, while a failed wait in main's submit loop only logs. Please make the two consistent or explain why the split path has to abort.

yumaste's report (a later CPU CopyBufferRegion into a dword the GPU wrote earlier in the same list or submission loses to the GPU copyback) looks like the same planner gap from the destination side. It would be worth folding in or answering here.


Generated by Claude Code

@aycow

aycow commented Nov 25, 2026 •

Copy link
Copy Markdown
Author

I reproduced the remaining ordering defect on upstream 42363ab using WARP with the preview Agility runtime, debug layer, and full GPU-based validation. In the same command list a GPU producer wrote 29, but the title CopyBufferRegion and the staged unaligned root CBV received the earlier value 11. The aligned root CBV and the separately submitted unaligned control both received 29. The draft’s continuation planner predates current bindless and computed-address dependencies, and the same-list staging path still needs a fix. The branch remains a conflicted draft while that ordering and ownership are unresolved.

Current-main recheck at 67e8ae1: WARP still observed [29,29,11,11] for the aligned same-list, unaligned separate-submission, unaligned same-batch, and unaligned same-list controls. The title CopyBufferRegion also returned 11 after its producer wrote 29. The existing wait segments do not provide this staging handoff, and the old draft conflicts with the current submission and texture code. The branch remains a draft pending a fix that honors current write withholding and copyback ownership.

Exercise the live unaligned root CBV route and the title CopyBufferRegion thunk, with direct-aligned and separately submitted controls. Keep the known failing tests opt-in.
@aycow

aycow commented Nov 25, 2026

Copy link
Copy Markdown
Author

Updated #387 at 4be4f82 with the current-main ordering fix. The original same-list and same-batch staged reads now return 29 instead of 11, and the title buffer copy returns the producer's 29 through the real queue. AMD, NVIDIA, and WARP passed the focused controls with full GPU-based validation. The WARP suite passed 201 tests and strict GPU Clippy passed.

A dependency can split a submission only when earlier copyback is safe. The new controls keep disjoint work batched and block a cut across potentially withheld pages or opaque computed-address writes. The PR description lists the reproduction and the remaining staging limitation for those batches.

Check mapping misses after the last computed list and before publishing its data to a dependent CPU fill or buffer copy. Keep page refreshes in one batch when they can replace a private producer. Suppress ordinary copyback that overlaps actual withheld pages of the same shadow.
After a miss at the final computed-address boundary, protect fenced writer ranges from whole-page refreshes. Forward only destination spans the kernel reports delivering, including through known title mappings, and update comparison snapshots for those spans. Keep opaque host writes grouped.
Stage a dependent root CBV privately only across bounded buffer dispatches with known outputs. Keep the prefix address-map layout and suppress both marked-page and exact-range writes derived from the private input until the full submission decides whether to publish. Preserve independent writes and use the original schedule when effects cannot be tracked.
@yumaste

yumaste commented Nov 25, 2026

Copy link
Copy Markdown

I tested a related ordering case on this PR's head (be723f7). A guest CopyBufferRegion reads from a separate CPU buffer and overwrites a dword previously written by the GPU. The GPU copy-back wins when both commands are in one list or in two lists in the same submission. Separate submissions preserve the later CPU copy.

yumaste/VIctory@b65714d extends the existing guarded submission boundary to overlaps with the copy destination. With the patch, the destination holds the CPU value in all three layouts. The planner test also checks that a potentially withheld write on the same page still prevents an early boundary.

The guest-entry regression passes on Microsoft WARP and on the default hardware adapter. The standard WARP diagnostics suite passed 205 tests with 9 ignored, and strict GPU Clippy passed. An explicit run of eight ignored draw tests had the same seven failures on the PR head and on the patched branch in my setup. All buffers were synthetic. AI-assisted with Codex.

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.

4 participants