Skip to content

GPU: run submissions asynchronously on a host fence timeline - #595

Open
wbkepler wants to merge 1 commit into
Marvisak:mainfrom
wbkepler:gpu/async-submissions
Open

wbkepler wants to merge 1 commit into
Marvisak:mainfrom
wbkepler:gpu/async-submissions

Conversation

@wbkepler

@wbkepler wbkepler commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Host::execute used to submit, signal, then WaitForSingleObject(INFINITE) on every submission before copying shader-written ranges back and doing the bottom-of-pipe writes. Each world frame has about 150 submissions, all fully serialized, so the CPU and GPU never overlapped. This PR runs them on an asynchronous GPU timeline.

  • Timeline (timeline.rs): each submission signals the next host fence value and is pushed with its work and the title memory its GPU work touches:

    • shader writes, by host copy;
    • bottom-of-pipe write targets;
    • reads (refreshed ranges, texture memory).

    Submissions are finished strictly in order, one thread at a time. Finishing a submission means: copy-back, then its bottom-of-pipe writes, then the title fence signals queued behind it. Signals run under the entries lock, so a signal queued later can never overtake them.

  • Completion thread (victory-gpu-finisher): waits on the host fence for the oldest submission and finishes it. Title fences and bottom-of-pipe memory therefore move on their own, which covers titles that wait on events or poll memory.

  • Queue Signal/Signal2X: the fence is AddRef'd and set once every earlier submission has finished, or at once if none is in flight.

  • Lists reset while they run (D3D12 allows a reset right after submission; titles record the next frame into their lists while the GPU runs this one): the reset no longer waits.

    • What the running submission uses goes to the timeline and is released once it has finished: allocator, prelude, upload/scratch memory, kept objects and textures, the indirect budget word, and the title's list uploads.
    • The list records into fresh ones. Allocators, preludes and scratch chunks come from spares (Retired, SPARE_*).
    • A list a running submission names stays pinned: dropping it still waits.
  • Sync points. The thread that needs a submission finished waits for that one only:

    • A later submission's CPU-side steps (Batch::settle):

      • a step that reads title memory an in-flight submission's GPU work writes: Fill, Copy source, rectangle expansion, texture staging refresh, and the GpuWrite snapshot;
      • a step that writes title memory an in-flight submission reads or writes: Copy destination, CopyMemoryToMemoryX;
      • a Refresh overlapping an in-flight submission's shader writes through the same copy waits only if the write journal shows a title write in the overlap since the copy took it (Timeline::refresh_conflict, Shadow::stale). Overlaps with bottom-of-pipe targets or with shader writes through another copy always wait.

      In-flight shader-write ranges on one copy never overlap, which keeps the per-copy snapshot/pending bookkeeping sound.

    • Resubmitting a recording that is still running, page-mapping batches, swap-chain resizes, a blocking (null-event) SetEventOnCompletion, capture readbacks, and more than 16 submissions in flight.

  • Device removal is detected when a submission is finished. The DRED report covers the lists of every submission still in flight. A failed Signal ends the run instead of leaving a wait that never returns.

  • VICTORY_GPU_TIMING (diagnostics) stays synchronous: each list is waited for and timed.

What stays synchronous, and why

  • Present drains the frame (// shortcut: in Host::present). A title may treat a present as the GPU being done with the frame. In the world the GPU has usually finished by then (about 0 ms waited at present), so this costs little now; letting one frame run on is a follow-up.
  • Copy-back still uses the CPU snapshot and diff, now on the completion thread. The world frame is now bound by CPU preparation (title-memory copies on the submitting thread, about 240 ms of about 267). That is the next target: shadow buffers in VRAM and dirty tracking on the GPU.
  • Diagnostics only: after a running list is reset, a slow-submission or removal report about its earlier submission names the new recording's pipelines and notes.

Test evidence

  • 5 new tests:
    • timeline: submissions finish in order and signals follow their work; conflicts pick the newest overlapping submission; a refresh waits only for title-written overlaps, with labels and other copies always counting.
    • host (on the host device): a list reset while it runs records into fresh memory and both bottom-of-pipe writes land; a queued signal sees an earlier submission's write; a later submission's fill of memory an earlier one writes sees the written value.
  • Gate: cargo clippy --workspace --all-targets, cargo clippy -p victory --features diagnostics --all-targets (no new warnings), cargo test --workspace and cargo xtask policy all pass. New and changed code is rustfmt-clean.
  • Live: RTX 5090, diagnostics build, VICTORY_D3D12_DRED=1, 7-minute runs (menus → about 60 s loading → world). Each build is GPU: refuse wave64 mesh and compute programs on hosts without 64-lane waves #578 (refuse wave64 programs on 32-lane hosts, which ends the NVIDIA device removals) with or without this PR:
#578 alone + this PR
World ms/frame, median / mean (67 lines) 283 / 319 267 / 286
Waiting for the GPU per frame, median 79 ms 1 ms
Preparing per frame, median 148 ms 241 ms (now the bottleneck)
Copying back per frame, median 40 ms 43 ms (on the completion thread)
Device removal in 7 minutes none none (3 runs at the stages of this PR, none removed)
  • Menus and loading render normally, at a steady 30 fps (the title's cap).
  • What the stages bought, measured with local-only counters: the first stage alone (no win: 300 ms median) waited about 52 times per frame when lists were reset right after submission, which dominated. Retiring the running list's memory brought those waits to 0.2 per frame. The remaining waits are refreshes (about 6 per frame, about 50 ms) and shader-write snapshots on the shared heap (about 1–2 per frame, about 20 ms).
  • Before GPU: refuse wave64 mesh and compute programs on hosts without 64-lane waves #578, against upstream/main, menus also became steady (22–42 fps with dips to 4–10 became a steady 30). The world was dominated by the wave64 hangs then.

🤖 Generated with Claude Code

@wbkepler
wbkepler marked this pull request as ready for review November 24, 2026 06:24
@Nixitov

Nixitov commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Tested stacked on the RTX 5070 after #493 + #483 + #581 (the pair that stops the world hang here), and it runs: 2.0-2.5 fps in the world, no device removal.

Setup: Windows 11 Pro 26200.9974, RTX 5070, driver 617.14, in-box D3D12 10.0.26100.9818; d2a4bae + #493 + #483 + #581 + this PR, merged in that order (clean), release build.

without #595 with #595
world fps 1.8-2.0 2.0-2.5
GPU time in the frame line ~320 ms 12-35 ms
draws/frame 500-1207 up to 1907
device removals in 2.5 min 0 0

The frame line now reads 381.8 preparing: copies 254.9 ms 231.5 MB, textures 17.6 ms 142.9 MB; 12.5 on the GPU; 92.5 copying back, so after this PR the world is limited by the copies into and out of title memory (the one-address-space work in the roadmap), not by the GPU or by submission serialisation. Nothing else regressed in the run.

No game files; only timings and counts.

AI-assisted (DeepSeek V4.1 Flash coding agent).

@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown

@wbkepler I ran a native-fence-gated #595 + #562 integration. Reset dropped the draw state while its native work was still pending. Without the fix, WARP reported all 65,536 descriptor slots available before the fence. Transferring the shared and list-local leases to the retired recording preserved both GPU outputs. A separate two-submission test showed that later CPU detiling could rewrite shared texture staging while an earlier GPU copy still needed it. Waiting before rewriting the changed staging kept both outputs correct. Both fixes passed AMD, NVIDIA and WARP with full GPU validation. The deliberate WARP mutations failed both regressions.

The integration branch carries the fixes separately at bc49373 and 70628dd and finishes at 5b11a40. Set VICTORY_TABLE_TEST_ADAPTER to amd, nvidia or warp, set VICTORY_TABLE_TEST_AGILITY to the Agility x64 DLL directory and VICTORY_TABLE_TEST_DXC to dxc.exe. Run cargo test -p victory-gpu --features diagnostics reset_holds_descriptor_ranges_until_native_fence -- --ignored --nocapture and repeat for changed_texture_upload_waits_for_older_gpu_reader with legacy GPU timing off.

The #185 composition at 4ef3ddd passes its direct-SRV checks on all three adapters when that work stays synchronous. For #387, the existing producer → copy → CPU staging → GPU reader fixture passes at df2276b. Removing only the intermediate CPU handoff makes the consumer read 13 instead of 500, even though final copyback still reaches 500. This is a separate intra-submission boundary to preserve when resolving the merge. I'd be glad to fold the two validated fixes into your branch with you.

@wbkepler

Copy link
Copy Markdown
Contributor Author

Thanks @aycow for the thorough AMD/NVIDIA/WARP validation and both fixes! Folded both into gpu/async-submissions (adapted to #595 standalone without #562's SharedTable/DynamicRange, with co-author credit):

  1. Dynamic descriptor leases held until async fence completion (from bc49373): moved dynamic slot leases out of draw::State into HostList's Deferred (DynamicLease via HostList::keep_dynamic), so resetting an in-flight list hands its leased descriptor slots to Retired and only releases them once the submission finishes on the native host fence. Added submissions::dynamic_descriptor_leases_stay_held_until_async_submission_finishes.
  2. Wait for in-flight readers before overwriting shared texture staging (from 70628dd): tracked Touches::staging in timeline.rs with Timeline::staging_conflict, added Batch::settle_staging, and updated texture::Staging::refresh to snapshot changed bytes and invoke before_write right before detile(). Added staging_conflict coverage in timeline::tests.

Gate: cargo clippy -p victory-gpu --all-targets (0 new warnings), cargo test -p victory-gpu --lib, and cargo xtask policy (151 files ok).

@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown

@wbkepler Thanks for carrying the lifetime fixes into c89f08f and for the credit. I published the tested #595/#387 composition at 3847bf0 with that revision in its ancestry. CPU-dependent intermediate copies wait and copy back before the next staging fill. The last GPU-only batch can stay asynchronous. Its native fence owns continuations, descriptor leases, and staging through completion.

The 21 ordered-copy cases and inherited retirement/staging controls passed on AMD, RTX 5070 Laptop and WARP with full GBV. I also fixed the wait helper's handling of Win32 WAIT_FAILED and an early event. The code checks actual fence progress, with the existing DRED path on removal. The native held-fence test passed on all three adapters. The mutation reproduced early return on WARP.

For #185, exact selected slots could go asynchronous once native heap/slot generations are leased under the descriptor mutation lock and backing ranges stay protected through the fence. Current direct-SRV refresh records alone don't hold that proof. Composition and reproduction

@Nixitov

Nixitov commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Follow-up on the same machine after two CPU-side changes stacked on this PR (not part of it), world scene, release build:

before today after the copies work
frame 1.8-2.5 fps 4.2-4.5 fps (up to 8.7 in the credits scene)
copies 237-305 ms/frame 25-60 ms
copying back 85-155 ms/frame 7-73 ms
title copies per frame 10-44k 4.2k

The single submission is now the thing the frame waits on: the main thread prepares, submits, then waits for this PR's completion (which includes the shader results copied back into title memory) before preparing the next one. Nothing here reads wrong; the wait is just the pipeline's length now.

No game files; only timings.

AI-assisted (DeepSeek V4.1 Flash coding agent).

@Slaktarn700

Copy link
Copy Markdown

Tested this on Linux: RX 9070 XT, RADV / Mesa 26.3.1, Proton Experimental (vkd3d-proton 3.2), diagnostics build. Base was main ffe310e plus proton-fixes and #454, with the watchdog disabled.

It works: GPU time per world frame dropped from 200–350 ms (synchronous) to a few ms.

But on its own it hangs the GPU about 6–9 s into the world. That happened three times out of three. Each time it was ring gfx_0.0.0 timeout with no VM fault, and submissions grew from 0.45 s to 1.1 s to 2 s before the kernel reset. RADV's hang report showed a mesh + pixel pipeline bound and no fault. The cause is shader loops spinning on data the asynchronous path hasn't made available yet. They run to LOOP_LIMIT (2^20) in every lane:

So #595 likely needs #452 to land first, or with it.

One thing to retire when this meets #282: #282 adds a per-list arguments buffer (Arguments, for the rectangle expansion), which reset reuses (filled/used = 0). With submissions in flight, a list reset while it runs would rewrite arguments its running submission still reads. On my merge I moved it into Retired next to scratch and the budget, and reset it in place only when the list isn't running.

Two smaller notes from the merge:

AI-assisted (Claude Code).

@mercuryVM mercuryVM left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Tested c89f08f on Windows 11, RTX 5070, MSVC: builds; cargo test -p victory-gpu -- --test-threads=1 49 passed, 0 failed, 1 ignored (all 6 new tests pass). I ran single-threaded, so the parallel hang in finding 3 was not exercised.

I read this for ordering, sync points, lifetimes and locks.

What holds:

  • Copy-back, then bottom-of-pipe writes, then title signals, with signals queued under the entries lock.
  • Signal and Signal2X hold an AddRef until they are set.
  • Lock order has no cycle: submitted, then finishing, then entries; the finisher doesn't take submitted.
  • These sync points all wait correctly: Copy source and destination, Fill, rect expansion, GpuWrite, texture staging, page mappings, swap-chain resize, present, capture, and the limit of 16 in flight.
  • Allocators, preludes, scratch and kept objects are released behind their fence.
  • A failed Signal calls fail, so no wait is left hanging.

One data-correctness problem:

  1. The per-copy snapshot goes stale while another submission on the same copy is in flight (shadow.rs:166-170, 257-262).
    • before is released only when pending is empty, and copy_back never refreshes before for the range it just synced. writing() returns early when the hull is unchanged.
    • Scenario:
      • S1 writes range A of copy C. S2 writes a disjoint range B of C and is still in flight, so the snapshot survives S1's copy-back.
      • S3 declares A again. Its "before" for A is the bytes from before S1.
      • While S3 runs, the title writes byte x in A, which S1 wrote and S3 doesn't touch.
      • At S3's copy-back, h != o and t != h, so the GPU's older value overwrites the title's write.
    • This is the lost-write case the diff copy-back exists to prevent, and it becomes common now that the world heap always has something in flight.
    • Fix: at the end of copy_back, when pending is still non-empty, copy host[from..to] into the matching part of before. Or have writing() always re-take [from, to), which is safe because settle guarantees no writer of that range is in flight.

Also:

  1. Mark-clean race, much wider now (shadow.rs:216 vs 243-248). Title memory is read before the write-journal timestamp now is taken. A title write between the two is stamped copied = now and never recopied. Copy-back now runs on the finisher thread at the same time as the title, so this window is open all the time. Fix: take the timestamp before read_into.
  2. A test can hang (host.rs ~2685-2697). dynamic_descriptor_leases_stay_held_until_async_submission_finishes gates the shared queue with queue.Wait(gate, 1) and signals the gate only after its own execute returns. Another host test submitting behind the gate in parallel can block in settle while holding submitted. Serialize the host tests, or signal the gate from another thread.
  3. Two tests probably don't take the path they name (host.rs ~2571, ~2617). The lists are tiny and usually finish before the reset() or the second execute. The gate trick from 3 would force the path. (The description says 5 tests; there are 6.)
  4. Nit: conflict(writing = true) also waits for in-flight GPU reads, but those read the host copy taken at their own submission, so a write to title memory doesn't need to wait for them.
  5. Nit: DynamicLease now drops later, on the finisher. release_dynamic matches the heap by address, so a heap freed and replaced at the same address in between gets the wrong slots released. A generation number or an Arc would fix it.

It conflicts with current upstream main in draw.rs, host.rs and texture.rs, so it isn't merged into our fork.

AI-assisted (Claude Code).

wbkepler added a commit to wbkepler/VIctory that referenced this pull request Nov 24, 2026
…ark-clean race, and make gated tests deadlock-free (Marvisak#595)
@aycow

aycow commented Nov 24, 2026 •

Copy link
Copy Markdown

@wbkepler I tested a current-main #595/#562 composition at e8dbc98, using ba55d3c, #562 05c3757, and #336's actual pool size. Both shared and list-local descriptor ownership retire on the proven fence. The four native gated cases plus the disjoint shadow snapshot case passed in default Windows adapter mode and WARP. These runs used validation off. The full #185/#387 composition remains separate. For #509, reset must detach each recording's query page and operation metadata together so pending collection reads the old generation after its fence.

Follow-up on the same production head: the five cases passed on explicitly selected AMD Radeon Graphics, RTX 5070 Laptop, and WARP with Agility 1.620.2, full GPU-based validation and state tracking, and zero warning/error callbacks. Test-only adapter harness. Run the ignored host::submissions::full_gbv_async_gate_suite with diagnostics enabled, VICTORY_ASYNC_TEST_GBV=1, the Agility DLL path in VICTORY_TABLE_TEST_AGILITY, and VICTORY_TABLE_TEST_ADAPTER set to amd, nvidia, or warp.

The ordered-copy follow-up now includes #387 489c9bf and #562 9ca0533. All 21 ordered-copy cases, the held-fence wait check, and the CBV/mixed-table readbacks at widths 1, 16, 178 and 256 passed on explicit AMD, NVIDIA and WARP with full GPU-based validation. The WARP mutation showed why the CBV key must include native recording segment identity. An ordered copy can move the later draw to a new continuation whose local count is also zero. #185's directly indexed descriptor generations still need fence-owned snapshots before its async path can be validated.

simnJS added a commit to MiamiGame/XTP that referenced this pull request Nov 24, 2026
Port of VIctory #595 (five commits: run submissions asynchronously on a
host fence timeline; a refresh waits for an earlier submission only if
the title wrote the overlap; a list reset while it runs records into
fresh memory; formatting; dynamic descriptor leases and texture staging
waits).

Submissions are no longer waited for. Each signals the next host fence
value and joins a timeline (host/timeline.rs). Once the GPU has run it,
it is finished in submission order: GPU copy destinations and
shader-written ranges written back into title memory, then its
bottom-of-pipe writes, then the title fence signals queued behind it. A
completion thread (xtp-gpu-finisher) finishes submissions as soon as the
fence reaches them. A thread that needs one finished first waits for
that one only:
- a later step that reads title memory an earlier submission's GPU work
  writes, or writes memory it reads or writes;
- a refresh through the same host copy only if the title wrote the
  overlap since the copy took it (Shadow::stale);
- a texture staging buffer an earlier GPU copy still reads;
- a list submitted again while it runs, more than 16 submissions in
  flight, page mappings, swap chain resizes, blocking fence waits and
  the present (which drains the frame).
A list reset while it runs hands its allocator, prelude, scratch and
upload memory, kept objects and textures, dynamic descriptor leases,
budget word and title uploads to the timeline, and records into fresh
or spare ones.

XTP: merged by hand onto gpu-frame (G1-G4).
- GPU buffer copies (G3) go back on the completion thread too, merged
  per host copy and before shader-written ranges, as in G3. They count
  as GPU writes for later steps. A GPU copy into a range an earlier
  submission's shaders write through the same copy waits for it: that
  one's write-back is told from a snapshot of the copy.
- The frame-rate line keeps preparing, GPU and copying back, and adds
  the title's waiting and the overlap. Preparing leaves out the waits
  inside it. The GPU time is measured until each submission was seen
  done. The longest submission is counted when it finishes.
- XTP_SYNC_SUBMIT=1 brings back synchronous submission for bisecting
  (gpu.md risk 2): each submission waited for and finished in execute,
  no completion thread.
- Host fence waits go in 500 ms slices that check for device removal and
  warn every 5 s (as xcl's fence waits do); a removed device ends the
  run with the device-removed data of every submission in flight.
- Timeline entries carry merged ranges, and refresh conflicts are looked
  up through them first (G3 records thousands of copies per frame).
- Texture refreshes are not copied and hashed a second time before
  detiling (#595's last commit did): a title write meanwhile is detiled
  again at the next check.
- Tests on WARP: completion order, write-back after the GPU work, fence
  signals, list memory retirement, dynamic descriptor leases, the waits
  (and the refresh that does not wait), the synchronous path.

Co-authored-by: wrothgaril <211408787+wrothgaril@users.noreply.github.com>
Co-authored-by: asc <aydanscowan@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Ported from Marvisak/VIctory#595 (head c89f08fe866dab895998df79e7c65b6f091f5d95) by wbkepler
@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown

@wbkepler A held-fence reader regression on current main plus ba55d3c found an independent backing-lifetime issue: a later CPU refresh changed an earlier queued read from 11 to 29. The narrow control waits for overlapping readers before refreshing. It preserved 11 and 29 and passed the disjoint-writer replay on AMD, NVIDIA and WARP with full GPU validation. Explicit adapter harness. The mark-clean source samples its generation before reading title memory. #185 still needs complete direct descriptor coverage and native slot ownership through the fence.

@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown

The new synthetic CPU-inside-UAV reproductions for #185/#387 exercise a CPU update after list recording, a real UAV write, and a different CPU write after the snapshot. Synchronous fixes landed on those branches. At exact ba55d3c, this cannot be ported as removal of pending ranges: older in-flight writers still need those exclusions, and the held-reader regression reported above demonstrates why older readers need protection too. The safe integration point is after refresh preparation for the current declarations, separately from completion-owned earlier intervals. Direct descriptor/heap generations and backing bytes still need fence ownership before a composition can be validated.

@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown

The prior timestamp-generation work is now an independently validated #509 composition with exact #509 and current #595 plus the confirmed-fence guard, free of #387/#562 dependencies. The held-fence/replay regression and one-submit smoke pass AMD/NVIDIA/WARP with full GBV. This isolates census lifetime work from the shadow data/descriptor ownership cases.

wbkepler added a commit to wbkepler/VIctory that referenced this pull request Nov 24, 2026
…ark-clean race, and make gated tests deadlock-free (Marvisak#595)
@wbkepler
wbkepler force-pushed the gpu/async-submissions branch from ba55d3c to e6694e4 Compare November 24, 2026 20:33
@wbkepler

Copy link
Copy Markdown
Contributor Author

@mercuryVM thanks for the careful review (written against c89f08f). The branch is now rebased onto current main (ffe310e) as e6694e4; the only conflict was draw.rs (kept upstream's table_failed, the dynamic leases stay on the host list as DynamicLease), and host.rs / texture.rs merged cleanly, including upstream's new defer_fill for texture-region staging and the CPU-written texture uploads before CopyResource / CopyTextureRegion.

Where each finding stands at the rebased head:

  1. Stale snapshot across in-flight submissions: fixed. Shadow::writing now re-takes [from, to) from the copy even when the hull did not grow, and copy_back updates the snapshot for every piece it syncs, so a disjoint submission keeping before alive no longer holds pre-S1 bytes. shadow::tests::snapshot_stays_fresh_across_disjoint_in_flight_submissions is your S1/S2/S3 scenario.
  2. Mark-clean race: fixed. The write-journal timestamp is taken before read_into, so a title write during the read gets a later stamp and is recopied.
  3. Test hang: fixed. Host::execute_gated arms the gate inside the submission lock right before ExecuteCommandLists, gated tests share a GATE_LOCK, the Gate guard always signals on drop, and nothing a gated test does before release() takes submitted.
  4. Tests not taking their path: the reset test and the read-after-write test now use the same gate, so the first submission is really in flight (the reset test asserts list.running()).
  5. writing = true also waits for in-flight GPU reads: agreed, that is conservative. It costs a wait but can't be wrong, so I'd like to narrow it in a follow-up rather than here.
  6. DynamicLease matched by heap address: fixed. Heaps get a monotonic id (NEXT_HEAP_ID), SHADER_HEAPS records it, and release_dynamic matches by id, so a heap replaced at the same address isn't touched.

New in the rebase (e6694e4): upstream now gives view heaps 2^18 dynamic slots where the host allows it, so the lease test now leases every 2^16 run until none is left, rather than assuming one run fills the heap.

Verified: cargo clippy -p victory-gpu --all-targets -D warnings, cargo clippy -p victory --features diagnostics --all-targets -D warnings, cargo test -p victory-gpu (57 passed, 0 failed, 1 ignored, run in parallel with no hang) and cargo xtask policy.

AI-assisted (Claude Code); checked on Windows 11 / RTX 5090.

@wbkepler

Copy link
Copy Markdown
Contributor Author

Pushed 7465030, which fixes the repeated-list prelude hazard on the async path. Credit to @ESAT586: #1414 has the analysis of the bug on main. When the same HostList appears twice in one Host::execute, the second prelude recording resets the allocator and list that the first, not yet executed, prelude still uses.

#1414 fixes main's synchronous loop with a fence wait between duplicate-free chunks. That CPU wait would undo the async design here, so #595 handles it differently:

  • Repeat within one submission: the second and later occurrences record their prelude into a spare allocator and list from the existing fence-retired SPARE_PRELUDES pool (fresh_prelude). The Pending submission keeps that spare. complete() resets it and returns it to the pool once the fence has passed. Each run gets its own barriers (real → start for the first, end → start for the repeat).
  • Same list twice in one ExecuteCommandLists: the repeat starts a new ExecuteCommandLists call on the same queue, so queue order serializes the two runs. There is no CPU wait.
  • Across in-flight submissions: unchanged. Before re-recording, execute still settles only that list's own last fence value, and a list reset while running swaps in a fresh prelude through Retired. There is still no global wait per submission.
  • Test: a_list_named_twice_in_a_submission_has_two_preludes submits [&list, &list] behind a gate fence (execute_gated) so it stays in flight. It checks that the pending submission holds exactly one spare prelude. After draining, it checks that the texture ends in COPY_SOURCE and that the device was not removed.

Gate: cargo clippy -p victory-gpu --all-targets -D warnings, cargo clippy -p victory --features diagnostics --all-targets -D warnings, cargo test -p victory-gpu (58 passed) and cargo xtask policy all pass.

AI-assisted (Claude Code); checked on Windows 11 / RTX 5090.

@Jitheswar

Copy link
Copy Markdown

A review of 7465030 against what the title's submission thread does (traced in #1118, comment), plus a few correctness points. File:line refers to 7465030.

Why it matters for the Prestream watchdog (#1118). The title submits from one thread (+0x2481e90). For each batch it calls ExecuteX, then PresentX, then Signal, and only then gives ring slots back to the producers that main waits on. On main, ExecuteX blocks until the GPU finishes. With this PR it doesn't, but:

  • Host::present calls self.drain() right after Present (host.rs:2246), so the same thread now waits for the whole frame's GPU work inside PresentX. The comment there anticipates relaxing this "once titles are known to wait for their fences instead". This title does: it signals its fences (queue slot 16) from that thread and polls them.
  • At IN_FLIGHT = 16 (host.rs:511, 757-761), ExecuteX settles the oldest submission on the title's thread. World frames make far more than 16 submissions, so a slow one still blocks that thread.

So the stall moves from ExecuteX to PresentX. Letting one frame run on (waiting at present for frame N-1, not N), and keeping the cap's wait off the title's thread, would let this PR address #1118.

Correctness points:

  1. timeline.rs:169-200 (refresh_conflict) checks labels and shaders but not reads. A later submission's Step::Refresh can rewrite a host copy (Shadow::update, shadow.rs:284-316) while an in-flight submission's GPU work still reads it.
  2. host.rs:925-935 (wait_gpu) ignores the WaitForSingleObject result. On WAIT_FAILED, settle returns without copy_back, and the title reads stale memory.
  3. host.rs:1010-1012, fence.rs:88-134: bottom-of-pipe writes store the fence value with a non-atomic write_unaligned, which races CPU polls, and they don't wake SetEventOnCompletion waiters (only Fence::Signal does). GPU: fence waits, direct memory-write wakes, queue timeline and host list pool #32 covers the same wake; a merged fix would need one of the two.
  4. fence.rs:88-110: a null-event SetEventOnCompletion drains once and then returns E_NOTIMPL if the value is still short (for example, waiting for a later CPU signal).

Tests: on an RTX 3050 6 GB (Linux, Proton 11, vkd3d-proton) with a real device, victory-gpu gives 56 passed / 2 failed on this PR and 48 / 2 on ffe310e, with the same two failures. So there are no regressions, and the async host tests do run there. They don't under plain wine (no device: they return early). The PR now conflicts with 70564ae in descriptor.rs, draw.rs, host.rs, lib.rs, shadow.rs and texture.rs.

Would a rebase onto 70564ae that includes the one-frame present and an off-thread cap help? We can open it as a PR against your branch.

AI-assisted review (Claude Code, Codex, Antigravity). No game data.

@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown

The held-fence reader control in our earlier integration independently reproduced the refresh-conflict issue on 7465030: an earlier queued read of 11 saw the later CPU refresh to 29 until the reader was protected. The historical census composition 6e79490 also checks reset/replay and counts repeated recordings with ambiguous timestamp spans suppressed. With the current renderer conflicts and the rebase offered here, I will keep #509 independently mergeable and use those controls against a new submission integration when available. The checks should use actual fence completion before mapping old readback.

AI-assisted using Codex.

Submissions are no longer waited for: each signals the next host fence
value and joins a timeline of up to 16 in flight, finished in order (copy
back, then bottom-of-pipe writes, then title fence signals) by a finisher
thread or whichever thread first needs one. Allocators, preludes, scratch,
kept objects, twins, dynamic descriptor leases and retired heap resources
are released behind their submission's fence. A step touching title memory,
host copies or texture staging waits only for in-flight submissions that
write (or read) it.

Rebased onto the page table, bindless heap views, twins and change journal:
a list's after-run work and missed-memory checks move into the pending
submission; bindless texture uploads, view heap refreshes and page table
refreshes wait for in-flight writers like other steps, a page table is
rewritten only with no reader in flight, and a page table user counts as
writing every copy it names.

A list named again in one submission gets its own prelude, and what its
steps write into the list's own memory (upload memory, scratch, budget
word) goes into an upload buffer of the submission that the repeat's
prelude copies in on the GPU, so each run reads its own data with no CPU
wait. List memory is a CPU-visible custom heap the GPU can copy into.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@wbkepler
wbkepler force-pushed the gpu/async-submissions branch from 7465030 to dfac3b4 Compare November 24, 2026 22:09
@wbkepler

Copy link
Copy Markdown
Contributor Author

Rebased onto 70564ae as one commit, dfac3b4. Upstream still waits for every submission on the CPU, so the timeline design still applies.

Conflicts that needed more than a merge

  • After-run work: upstream's Deferred::after and missed closures now run when a submission completes. They are stored as Arcs so they stay valid if the list is reset. missed is still checked per run, and a range goes back only if no run that declared it read uncopied memory; otherwise it is kept with keep_writes.
  • Shadow snapshots: the snapshot is now upstream's segment model. The fresh-snapshot fixes from this PR were reapplied on top of it. The "compared once" piece set now resets after each submission's copy-back (Shadow::submission_done), because several submissions can share one snapshot. stale() now asks the new Tracked change set (Tracked::any_changed).
  • New upstream submission-time paths now wait for in-flight GPU work like the existing steps:
    • bindless texture uploads (upload_changed): title-memory read and staging rewrite;
    • Step::Heap and Step::Memory refreshes, which are also recorded as reads;
    • a page table is rewritten only once no in-flight submission reads it.
    • Shortcut: a submission whose shaders use the page table counts as writing every copy the table names. This is correct, but it can serialize page-table-heavy frames more than necessary.
  • Retired resources: these now go with the next submission and are dropped when it completes, which replaces the global release_retired() after each submission.
  • Dynamic slots: root views, unordered-access clears and fresh tables all lease through keep_dynamic. This includes slots on our own memory heap (memory::OURS_ID).
  • Other: twins are retired with the list. The listed-frame dump settles its submission first.

Repeated list in one submission: upload memory and budget
A second occurrence's steps no longer write into the list's own memory (Fill destinations, scratch written by host steps, the budget word). The bytes go into an upload buffer that belongs to the pending submission, and the repeat's prelude copies them in with CopyBufferRegion. That copy runs in queue order after the first run, so there is no CPU wait. List upload and scratch memory now lives in a CPU-visible custom heap (write-combine, L0, COMMON) so the GPU can copy into it. defer_host now also declares the list memory it writes.

New test a_repeated_list_reads_its_own_upload_memory: a list, then a list whose step changes the uploaded title word, then the first list again. The GPU sees the first value between the two runs and the second value after the repeat. A list in two in-flight submissions was already waited for in execute.

Verification

  • cargo clippy (victory-gpu, and victory with diagnostics) passes with -D warnings.
  • cargo test -p victory-gpu: 85 passed. Two tests fail identically on plain upstream/main on this host because the view heap here is smaller than they assume: dynamic_slots_are_held_until_released and lists_share_a_table_and_copies_keep_their_views.
  • cargo xtask policy passes.

AI-assisted (Claude Code); checked on Windows 11 / RTX 5090.

@aycow

aycow commented Nov 24, 2026 •

Copy link
Copy Markdown

@wbkepler I independently checked the current-main rebase dfac3b4 on local AMD Radeon Graphics 32.0.22042.1 and WARP. With the census disabled, host::submissions::a_repeated_list_reads_its_own_upload_memory reproducibly returns [0, 0x22222222] on AMD, where the expected first word is 0x11111111. WARP returns both expected words. The result is the same on standalone #595 and a local #509 composition, with the same standalone startup-probe correction. The composition’s census-specific 100 ms held-fence, reset/resubmit and repeated-recording attribution tests separately pass on AMD and WARP with full GBV and keep the same native submission counts.

AI-assisted using Codex.

Follow-up on the AMD replay reproduction. With native inbox D3D12, the failure persisted with standard readback, independent outputs, an explicit source transition, and a held fence. Omitting replay passed. Waiting for confirmed native fence completion immediately before a group reuses the command-list recording restored both words. Local af0acb0 keeps ordinary submissions and the final group asynchronous, polls when the event does not confirm completion, and treats device removal as failure. All six submission tests passed on AMD and WARP. Agility 1.620.2 full GBV accepted the original and corrected held replay, so the observable wrong result is specific to the inbox AMD comparison. D3D12 recording reuse contract

@Jitheswar

Copy link
Copy Markdown

Thanks for the rebase. The present point from my review is now a one-commit PR against gpu/async-submissions on top of dfac3b4: wbkepler#5. A present waits for the previous frame's submissions, the copy list keeps the presented texture, and the black-frame probe is read one present later. It includes a gated synthetic test and was checked on an RTX 3050 with a real device (same 10 failures as plain 70564ae; per-frame GPU wait on the title's thread ~2-3 ms → <0.5 ms in the menus). The refresh_conflict reads hole (which @aycow also reproduced) is not in it. AI-assisted (Claude Code).

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

Needs rebase. This PR does not merge cleanly into current main (ac2525d). Conflicting files: crates/victory-gpu/src/descriptor.rs.

The content has not been reviewed yet; it will be once the branch is rebased onto main.


Generated by Claude Code

@slatefield

Copy link
Copy Markdown
Contributor

Rebased this onto current main (4118f33) since it has the needs-rebase label: the commit kept with your authorship and message, five conflict regions resolved (the inlined shader_slot in descriptor.rs, the scratch-chunk shape and spare pool in host.rs, update_busy beside stale/submission_done in shadow.rs), main's added tests adapted to host.drain(). One design call: scratch stays on your list_buffer (L0 custom heap) rather than main's upload_buffer, since a repeated list's prelude copies into it and an upload-heap resource cannot be a copy destination. Windows-target clippy clean both feature sets, native tests green, timeline.rs compiled and its tests pass natively.

It is open as #1923 so the maintainer can take a ready branch. If you would rather update this PR yourself, reset gpu/async-submissions to 4f1228c1fd62cb9836927d262d7049b7b3e889ee and I will close mine.

Two things from the review thread I carried into #1923's description rather than fixing here: refresh_conflict ignoring in-flight GPU reads, and the AMD inbox a_repeated_list_reads_its_own_upload_memory failure. Also worth pairing this with #32 (ID3D12CommandQueue::Wait is a no-op on main, and the synchronous wait is what hides it today).

geiyiliyabumo pushed a commit to geiyiliyabumo/VIctory that referenced this pull request Nov 25, 2026
GPU: Bind bounded buffer reads selected by a root constant
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.

8 participants