GPU: transition host copies of title memory between shader writes and reads #334

Closed
github-bot wants to merge 2 commits from gh-pr/334/head into gh-pr/334/base
Owner

@⁠realhenners on GitHub · 2026-11-24 02:21 UTC · original
realhenners:fix/buffer-copy-states → main · +538 −32 · 3 files · 2 commits · closed without merging

Refs #199, #264 (NVIDIA: vertex buffer in UNORDERED_ACCESS at a draw, barrier before-state mismatches, then DXGI_ERROR_DEVICE_HUNG entering the world).

Cause

Host copies of title buffers (shadow.rs) are created in COMMON (host.rs, shared_buffer) and never transitioned: they relied on implicit promotion. Promotion from COMMON lets a buffer be either written (UAV) or read in a list, not written and then read as vertices. The world's 174 MB heap (title buffer 0x19b10000+0xae00000 in #199) is both.

On top of that, indirect.rs recorded fixed barriers on the argument buffer: UNORDERED_ACCESS -> INDIRECT_ARGUMENT before every ExecuteIndirect, and done() moved it back to UNORDERED_ACCESS after. Because the arguments live in the same heap as the vertices, every indirect draw left the vertex data explicitly in UNORDERED_ACCESS. That matches both reports: the vertex buffer in UAV at DrawIndexedInstanced (#199, #264 id 538), and barriers whose before state was UAV while the buffer was in VERTEX_AND_CONSTANT_BUFFER (#264 id 527, 131 times).

Change

  • BufferStates (host.rs): per list, the state of each host copy it uses: its first state and its current one. Reads (vertex, index, constant, shader resource, indirect arguments) use GENERIC_READ, shader writes UNORDERED_ACCESS, with a transition wherever the use changes.
  • The list's prelude (already used for textures) moves each buffer from COMMON to its first state, and HostList::close moves it back to COMMON. State never leaks into the next list of the same ExecuteCommandLists.
  • Use sites in draw.rs: vertex and index buffers, root views, and buffer views in tables (readable: UAV views write, others read).
  • indirect.rs: the clamp asks for the write state; the new indirect::execute asks for the read state and records ExecuteIndirect. This replaces the fixed UAV <-> INDIRECT_ARGUMENT barriers and done().

Shortcuts, also commented in the code: buffers read only through directly indexed heaps are not tracked. A single command that both writes a buffer through a UAV and reads it as vertices, indices or arguments leaves it in the read state, because D3D12 has no legal state for both.

Tests

  • host::tests::buffer_states_transition_between_writes_and_reads: the state logic (no GPU).
  • host::tests::debug_layer_accepts_buffers_written_then_read_as_vertices: on the real host device with the D3D12 debug layer (run in a child process, since the layer is process-wide). Two lists submitted together use one shared buffer the way the world uses its heap: plain draw → argument clamp + ExecuteIndirect → draw, then a list that starts with an indirect draw. It asserts the debug layer reports no errors. It skips without a debug layer or a GPU.
    • With main's indirect.rs barriers, the test fails with id 527 (barrier before state UNORDERED_ACCESS vs the buffer's actual INDIRECT_ARGUMENT).
    • With this branch's end-of-list return to COMMON disabled, it also fails with id 527. The test therefore guards the cross-list handoff.

cargo test --workspace, cargo test -p victory-gpu --features diagnostics, cargo build -p victory --features diagnostics and cargo xtask policy pass. Clippy on victory-gpu adds no warnings.

Not tested / limits

  • Not run with the title. I have no game dump, so I can't show the world entering without the hang. I'd be grateful if the reporters of #199 / #264 could try this branch with VICTORY_D3D12_DEBUG=1 on their NVIDIA cards.
  • On my machine (Windows 11 26300, RTX 4070 Ti, driver 32.0.16.1742), the debug layer, even with GPU-based validation, does not report a vertex buffer drawn while explicitly in UNORDERED_ACCESS. So the test cannot show #199's id 538 message disappearing, only the barrier consistency (527) and the state logic.
  • Whether the missing transition alone causes the DEVICE_HUNG is unproven. A transition from UAV to a read state also makes the shader writes visible to the input assembler, so stale or garbage vertex data is a plausible way to a hang, but #199's comment from an RTX 5080 run hung in a compute dispatch instead (closer to #97).

AI use: Claude Code (Claude Opus 5.5) found the cause, wrote the change and tests, ran them on the GPU above, and drafted this description.

🤖 Generated with Claude Code

**@⁠realhenners** on GitHub · 2026-11-24 02:21 UTC · [original](https://github.com/Marvisak/VIctory/pull/334) `realhenners:fix/buffer-copy-states` → `main` · +538 −32 · 3 files · 2 commits · closed without merging Refs #199, #264 (NVIDIA: vertex buffer in `UNORDERED_ACCESS` at a draw, barrier before-state mismatches, then `DXGI_ERROR_DEVICE_HUNG` entering the world). ## Cause Host copies of title buffers (`shadow.rs`) are created in `COMMON` (`host.rs`, `shared_buffer`) and never transitioned: they relied on implicit promotion. Promotion from `COMMON` lets a buffer be *either* written (UAV) *or* read in a list, not written and then read as vertices. The world's 174 MB heap (`title buffer 0x19b10000+0xae00000` in #199) is both. On top of that, `indirect.rs` recorded fixed barriers on the argument buffer: `UNORDERED_ACCESS -> INDIRECT_ARGUMENT` before every `ExecuteIndirect`, and `done()` moved it **back to `UNORDERED_ACCESS`** after. Because the arguments live in the same heap as the vertices, every indirect draw left the vertex data explicitly in `UNORDERED_ACCESS`. That matches both reports: the vertex buffer in UAV at `DrawIndexedInstanced` (#199, #264 id 538), and barriers whose before state was UAV while the buffer was in `VERTEX_AND_CONSTANT_BUFFER` (#264 id 527, 131 times). ## Change - `BufferStates` (host.rs): per list, the state of each host copy it uses: its first state and its current one. Reads (vertex, index, constant, shader resource, indirect arguments) use `GENERIC_READ`, shader writes `UNORDERED_ACCESS`, with a transition wherever the use changes. - The list's prelude (already used for textures) moves each buffer from `COMMON` to its first state, and `HostList::close` moves it back to `COMMON`. State never leaks into the next list of the same `ExecuteCommandLists`. - Use sites in `draw.rs`: vertex and index buffers, root views, and buffer views in tables (`readable`: UAV views write, others read). - `indirect.rs`: the clamp asks for the write state; the new `indirect::execute` asks for the read state and records `ExecuteIndirect`. This replaces the fixed `UAV <-> INDIRECT_ARGUMENT` barriers and `done()`. Shortcuts, also commented in the code: buffers read only through directly indexed heaps are not tracked. A single command that both writes a buffer through a UAV and reads it as vertices, indices or arguments leaves it in the read state, because D3D12 has no legal state for both. ## Tests - `host::tests::buffer_states_transition_between_writes_and_reads`: the state logic (no GPU). - `host::tests::debug_layer_accepts_buffers_written_then_read_as_vertices`: on the real host device with the D3D12 debug layer (run in a child process, since the layer is process-wide). Two lists submitted together use one shared buffer the way the world uses its heap: plain draw → argument clamp + `ExecuteIndirect` → draw, then a list that starts with an indirect draw. It asserts the debug layer reports no errors. It skips without a debug layer or a GPU. - With `main`'s `indirect.rs` barriers, the test fails with **id 527** (barrier before state `UNORDERED_ACCESS` vs the buffer's actual `INDIRECT_ARGUMENT`). - With this branch's end-of-list return to `COMMON` disabled, it also fails with id 527. The test therefore guards the cross-list handoff. `cargo test --workspace`, `cargo test -p victory-gpu --features diagnostics`, `cargo build -p victory --features diagnostics` and `cargo xtask policy` pass. Clippy on `victory-gpu` adds no warnings. ## Not tested / limits - **Not run with the title.** I have no game dump, so I can't show the world entering without the hang. I'd be grateful if the reporters of #199 / #264 could try this branch with `VICTORY_D3D12_DEBUG=1` on their NVIDIA cards. - On my machine (Windows 11 26300, RTX 4070 Ti, driver 32.0.16.1742), the debug layer, even with GPU-based validation, **does not report** a vertex buffer drawn while explicitly in `UNORDERED_ACCESS`. So the test cannot show #199's id 538 message disappearing, only the barrier consistency (527) and the state logic. - Whether the missing transition alone causes the `DEVICE_HUNG` is unproven. A transition from UAV to a read state also makes the shader writes visible to the input assembler, so stale or garbage vertex data is a plausible way to a hang, but #199's comment from an RTX 5080 run hung in a compute dispatch instead (closer to #97). AI use: Claude Code (Claude Opus 5.5) found the cause, wrote the change and tests, ran them on the GPU above, and drafted this description. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Host copies of title buffers start in the common state and relied on
implicit promotion, which allows a buffer to be written (unordered access)
or read in a list, not both. The world's 174 MB heap is both: the argument
clamp and title passes write it, draws read vertices and indices from it.
indirect.rs also moved the argument buffer from unordered access to
indirect arguments and back after every execution, whatever state the
buffer was really in.

Each list now tracks the state of every host copy it uses (BufferStates):
reads (vertex, index, constant, shader resource, arguments) in GENERIC_READ,
shader writes in UNORDERED_ACCESS, with a transition where the use changes.
The list's prelude moves each buffer from common to its first state and the
list moves it back before closing, so state never leaks into the next list
of a submission. indirect::execute replaces the fixed UAV <-> INDIRECT_ARGUMENT
barriers.

Refs #199, #264.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review of #334 (r4tedx, QemmHD): buffer_state kept whatever state was asked
for last, so a dispatch writing a copy through a table UAV and reading the
same copy through an SRV or root view listed after it ran its writes in
GENERIC_READ, and nothing then separated those writes from a later vertex
or index read. One host copy backs most of the title's buffers, so this is
likely.

BufferStates now counts commands (State::bind and the argument clamp start
one) and remembers which command last wrote each copy: a read asked for in
that command leaves the copy in UNORDERED_ACCESS, in either binding order.
The next command's read transitions it as before.

The debug-layer test's child process unsets VICTORY_D3D12_DEBUG: with it
set in a diagnostics build, Host::execute drained the message queue before
the test read it (Hiiva). With the closing return to COMMON disabled, the
test now fails with id 527 in that configuration too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 03:59:40 +00:00
github-bot closed this pull request 2026-11-26 03:59:40 +00:00
Author
Owner

@⁠EduAzevedo on GitHub · 2026-11-24 02:33 UTC · original

Tested af2aecf on NVIDIA GeForce RTX 2070 SUPER (Turing), driver 610.88, Windows 11 (10.0.26200), native D3D12: the state errors are gone; the world hang is not.

  • cargo test -p victory-gpu: 45 passed, including buffer_states_transition_between_writes_and_reads and debug_layer_accepts_buffers_written_then_read_as_vertices on this card.
  • Diagnostics build with VICTORY_D3D12_DEBUG=1 VICTORY_D3D12_DRED=1, empty cache, boot → first mission's intro, counts from the full log file:
Debug layer errors main d2a4bae (3 runs) this PR
IASetVertexBuffers on a title buffer in UNORDERED_ACCESS 72 / 157 / 52 0
Barrier before state does not match (UNORDERED_ACCESS) 149 / 216 / 74 0

The errors left in the run are the known ones: 114× Wave64 compute refused (#54), the 1,310,720 > 1,000,000 shader-visible heap (#16), and the two texture formats of #55.

The world still ends in DXGI_ERROR_DEVICE_HUNG, about 4 minutes after start. DRED: one list stopped at command 175 of 413 on a DispatchMesh (op 42), every other unfinished list at command 0, as on main (#71). So on Turing this PR fixes the resource-state validation but is not the cause of the hang.

AI-assisted.

**@⁠EduAzevedo** on GitHub · 2026-11-24 02:33 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7120257521) Tested `af2aecf` on **NVIDIA GeForce RTX 2070 SUPER (Turing)**, driver 610.88, Windows 11 (10.0.26200), native D3D12: **the state errors are gone; the world hang is not.** - `cargo test -p victory-gpu`: 45 passed, including `buffer_states_transition_between_writes_and_reads` and `debug_layer_accepts_buffers_written_then_read_as_vertices` on this card. - Diagnostics build with `VICTORY_D3D12_DEBUG=1 VICTORY_D3D12_DRED=1`, empty cache, boot → first mission's intro, counts from the full log file: | Debug layer errors | `main` `d2a4bae` (3 runs) | this PR | |---|---|---| | `IASetVertexBuffers` on a title buffer in `UNORDERED_ACCESS` | 72 / 157 / 52 | **0** | | Barrier before state does not match (`UNORDERED_ACCESS`) | 149 / 216 / 74 | **0** | The errors left in the run are the known ones: 114× Wave64 compute refused (#54), the 1,310,720 > 1,000,000 shader-visible heap (#16), and the two texture formats of #55. The world still ends in `DXGI_ERROR_DEVICE_HUNG`, about 4 minutes after start. DRED: one list stopped at command 175 of 413 on a `DispatchMesh` (op 42), every other unfinished list at command 0, as on `main` (#71). So on Turing this PR fixes the resource-state validation but is not the cause of the hang. AI-assisted.
Author
Owner

@⁠noxite-four-life on GitHub · 2026-11-24 02:58 UTC · original

Tested on a real RTX 5070 Laptop GPU with a GTA VI dump (the game run you asked for). With this PR applied (on main + #205), VICTORY_D3D12_DEBUG=1 reports 0 of the barrier/state errors this PR targets — the id 527/538 before state / RESOURCE_BARRIER UNORDERED_ACCESS mismatches are gone, and the title reaches the opening cutscene.

It doesn't get the world rendering on its own — a device-removal still happens later from other causes (compute PSOs refused for Wave64 on this 32-lane card, since fixed by #189; plus remaining untranslated geometry shaders). But the buffer-state transitions this PR adds are clean on NVIDIA, so the barrier side is resolved. Thanks for the fix.

**@⁠noxite-four-life** on GitHub · 2026-11-24 02:58 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7120649744) Tested on a real **RTX 5070 Laptop GPU** with a GTA VI dump (the game run you asked for). With this PR applied (on `main` + #205), `VICTORY_D3D12_DEBUG=1` reports **0** of the barrier/state errors this PR targets — the id 527/538 `before state` / `RESOURCE_BARRIER UNORDERED_ACCESS` mismatches are gone, and the title reaches the opening cutscene. It doesn't get the world rendering on its own — a device-removal still happens later from other causes (compute PSOs refused for Wave64 on this 32-lane card, since fixed by #189; plus remaining untranslated geometry shaders). But the buffer-state transitions this PR adds are clean on NVIDIA, so the barrier side is resolved. Thanks for the fix.
Author
Owner

@⁠r4tedx on GitHub · 2026-11-24 03:11 UTC · original

Review note. I built this on main (d2a4bae) and ran cargo test -p victory-gpu on an RTX 5070: passes. (The debug-layer test printed "skipped" here; the layer is not installed on this machine, so I could not run it.) Of the open PRs for the vertex-buffer-in-UAV-state errors of #199 / #264, this one looks like the one to give testers; #367 does the same job and the two conflict.

One case where a write loses to a read within a single command. bind handles tables before root views, and buffer_state records and transitions to whatever was asked last:

  • readable (a table UAV): list.buffer_state(&shadow.buffer, BUFFER_WRITE)
  • then root_view (a root SRV of the same host copy): list.buffer_state(&shadow.buffer, BUFFER_READ)

So a dispatch that writes a host copy through a table UAV and also reads it through a root SRV gets a WRITE to READ barrier just before it runs, and writes the copy while it is in GENERIC_READ. The next read needs no transition either, so nothing separates those writes from a later vertex or index read of the same copy, which is the situation this PR exists to prevent. With one 174 MiB heap backing most of the title's buffers, one copy being both read and written by the same dispatch seems likely.

Would letting the write state win within one command (or a combined state for copies used both ways) work here?

From synthetic tests and reading only; I have no copy of the title.

**@⁠r4tedx** on GitHub · 2026-11-24 03:11 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7120854893) Review note. I built this on `main` (`d2a4bae`) and ran `cargo test -p victory-gpu` on an RTX 5070: passes. (The debug-layer test printed "skipped" here; the layer is not installed on this machine, so I could not run it.) Of the open PRs for the vertex-buffer-in-UAV-state errors of #199 / #264, this one looks like the one to give testers; #367 does the same job and the two conflict. One case where a write loses to a read within a single command. `bind` handles tables before root views, and `buffer_state` records and transitions to whatever was asked last: - `readable` (a table UAV): `list.buffer_state(&shadow.buffer, BUFFER_WRITE)` - then `root_view` (a root SRV of the same host copy): `list.buffer_state(&shadow.buffer, BUFFER_READ)` So a dispatch that writes a host copy through a table UAV and also reads it through a root SRV gets a WRITE to READ barrier just before it runs, and writes the copy while it is in GENERIC_READ. The next read needs no transition either, so nothing separates those writes from a later vertex or index read of the same copy, which is the situation this PR exists to prevent. With one 174 MiB heap backing most of the title's buffers, one copy being both read and written by the same dispatch seems likely. Would letting the write state win within one command (or a combined state for copies used both ways) work here? From synthetic tests and reading only; I have no copy of the title.
Author
Owner

@⁠justlovett0 on GitHub · 2026-11-24 03:35 UTC · original

Tested on the #348 machine, stacked with #175 (Agility) + #346 (rectangles): the world-entry GPU hang persists here, and the dominant gap on this NVIDIA card looks like the wave64 compute refusals (#71), not buffer states.

Setup: Windows 10 21H2 19044.7846, RTX 3080 10 GB (32.0.15.9649), Ryzen 9 7900X, 32 GB. This PR's head af2aecf + #175 + #346 (one conflict in indirect.rs, resolved as described on #346). Release, v1.0.2.1, no input.

  • Menus and loading screen render, no faults, no root-signature refusals; by frame 2048: 9,638/9,638 draws, 1,024/1,024 dispatches.
  • At the first world frames: 103 host pipeline refused (0x80070057) – all compute, matching #71's 77–78 (the WaveSize(64) programs on a 32-lane host).
  • Then DXGI_ERROR_DEVICE_HUNG after a submission of 33 lists (~99 s in) – same pattern as without this PR (32 lists).

So on this machine the state tracking alone does not prevent the hang; with #233 stacked (wave64 split) the refusals drop to 1 and the failure changes shape (a crash in nvgpucomp64.dll while creating large split compute pipelines, then a hang on a 7-list mesh-heavy submission) – details on #233. No regression attributable to this PR was observed in the menus/loading; the draw/dispatch counts differ between runs partly because the world entry timing differs.

Integration note: #346 also reworks indirect.rs; the resolution I used gives clamp_uav the buffer parameter for buffer_state(..., BUFFER_WRITE) and replaces bound's fixed transition with buffer_state(..., BUFFER_READ).

AI use: Qwen Code (underlying model name not disclosed by the tool) built and ran the stack and drafted this comment at the user's request; counts are from the run log.

**@⁠justlovett0** on GitHub · 2026-11-24 03:35 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7121242777) Tested on the #348 machine, stacked with #175 (Agility) + #346 (rectangles): **the world-entry GPU hang persists here**, and the dominant gap on this NVIDIA card looks like the wave64 compute refusals (#71), not buffer states. **Setup:** Windows 10 21H2 19044.7846, RTX 3080 10 GB (32.0.15.9649), Ryzen 9 7900X, 32 GB. This PR's head `af2aecf` + #175 + #346 (one conflict in `indirect.rs`, resolved as described on #346). Release, v1.0.2.1, no input. - Menus and loading screen render, no faults, no root-signature refusals; by frame 2048: 9,638/9,638 draws, 1,024/1,024 dispatches. - At the first world frames: **103 `host pipeline refused (0x80070057)` – all compute**, matching #71's 77–78 (the `WaveSize(64)` programs on a 32-lane host). - Then `DXGI_ERROR_DEVICE_HUNG` after a submission of 33 lists (~99 s in) – same pattern as without this PR (32 lists). So on this machine the state tracking alone does not prevent the hang; with #233 stacked (wave64 split) the refusals drop to 1 and the failure changes shape (a crash in `nvgpucomp64.dll` while creating large split compute pipelines, then a hang on a 7-list mesh-heavy submission) – details on #233. No regression attributable to this PR was observed in the menus/loading; the draw/dispatch counts differ between runs partly because the world entry timing differs. Integration note: #346 also reworks `indirect.rs`; the resolution I used gives `clamp_uav` the buffer parameter for `buffer_state(..., BUFFER_WRITE)` and replaces `bound`'s fixed transition with `buffer_state(..., BUFFER_READ)`. AI use: Qwen Code (underlying model name not disclosed by the tool) built and ran the stack and drafted this comment at the user's request; counts are from the run log.
Author
Owner

@⁠miniongk on GitHub · 2026-11-24 03:43 UTC · original

Combination check on RTX 5080 / driver 621.24 / Windows 11 26300, local Xbox Series 1.0.2.1: a5ba4a4 (#320) merged cleanly with af2aecf (this PR), with no source edits.

  • cargo test --workspace exited successfully.
  • The native run reached the world with zero host-pipeline refusals.
  • It still ended in DXGI_ERROR_DEVICE_HUNG, with DRED implicating indirect execution and mesh dispatch.

So the buffer transition work and the console-flow work together do not resolve #97 on this setup. This is a negative compatibility result, not a failure of either targeted test suite. Only aggregate counts and error classes shared. AI-assisted (Kimi Code).

**@⁠miniongk** on GitHub · 2026-11-24 03:43 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7121358276) Combination check on RTX 5080 / driver 621.24 / Windows 11 26300, local Xbox Series 1.0.2.1: `a5ba4a4` (#320) merged cleanly with `af2aecf` (this PR), with no source edits. - `cargo test --workspace` exited successfully. - The native run reached the world with zero host-pipeline refusals. - It still ended in `DXGI_ERROR_DEVICE_HUNG`, with DRED implicating indirect execution and mesh dispatch. So the buffer transition work and the console-flow work together do not resolve #97 on this setup. This is a negative compatibility result, not a failure of either targeted test suite. Only aggregate counts and error classes shared. AI-assisted (Kimi Code).
Author
Owner

@⁠Mesrine67 on GitHub · 2026-11-24 03:48 UTC · original

Tested commit af2aecf on Windows 11 build 26300 with an AMD Radeon RX 6750 XT (driver 32.0.21045.29003), using the default D3D12 adapter.

cargo test --locked -p victory-gpu -- --test-threads=1: 45 passed, 0 failed, 1 benchmark ignored. The debug-layer child test host::tests::debug_layer_accepts_buffers_written_then_read_as_vertices ran (no skip message) and passed; the state-machine unit test also passed.

This confirms the PR's synthetic state-transition scenario on this AMD system. It does not test the GTA VI executable or the same-command case where a single host copy is referenced through both read and UAV descriptors.

**@⁠Mesrine67** on GitHub · 2026-11-24 03:48 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7121445670) Tested commit `af2aecf` on Windows 11 build 26300 with an AMD Radeon RX 6750 XT (driver 32.0.21045.29003), using the default D3D12 adapter. `cargo test --locked -p victory-gpu -- --test-threads=1`: **45 passed, 0 failed, 1 benchmark ignored**. The debug-layer child test `host::tests::debug_layer_accepts_buffers_written_then_read_as_vertices` ran (no skip message) and passed; the state-machine unit test also passed. This confirms the PR's synthetic state-transition scenario on this AMD system. It does not test the GTA VI executable or the same-command case where a single host copy is referenced through both read and UAV descriptors.
Author
Owner

@⁠QemmHD on GitHub · 2026-11-24 05:11 UTC · original

Tested af2aecf on main d2a4bae, native Windows 11, RTX 4070 SUPER, driver 621.24.

  • cargo test --workspace --locked: 266 passed, 0 failed, 4 ignored; no new clippy warnings. The state test passes; the debug-layer test prints no D3D12 debug layer; skipped (Graphics Tools not installed here).
  • Beyond the root-view case: readable (draw.rs:1085/1087) and buffer_state (host.rs:1349) keep the last state asked for. With one host copy per title heap, a table that reads one sub-range through an SRV and writes another through a UAV of the same copy runs its UAV writes in GENERIC_READ whenever the SRV is listed last. Collecting the command's states and letting the write state win would make it order-independent. Conflicts with #479.

No game data used.

AI-assisted (Claude Code, Claude Opus 5.5).
Discord: bigpeppa.

**@⁠QemmHD** on GitHub · 2026-11-24 05:11 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7122711259) Tested `af2aecf` on `main` `d2a4bae`, native Windows 11, RTX 4070 SUPER, driver 621.24. - `cargo test --workspace --locked`: 266 passed, 0 failed, 4 ignored; no new clippy warnings. The state test passes; the debug-layer test prints `no D3D12 debug layer; skipped` (Graphics Tools not installed here). - Beyond the root-view case: `readable` (`draw.rs:1085/1087`) and `buffer_state` (`host.rs:1349`) keep the last state asked for. With one host copy per title heap, a table that reads one sub-range through an SRV and writes another through a UAV of the same copy runs its UAV writes in GENERIC_READ whenever the SRV is listed last. Collecting the command's states and letting the write state win would make it order-independent. Conflicts with #479. No game data used. AI-assisted (Claude Code, Claude Opus 5.5). Discord: bigpeppa.
Author
Owner

@⁠r4tedx on GitHub · 2026-11-24 05:55 UTC · original

A pointer for readers of the report above, since its last paragraph mentions #233: what happened with #233 stacked was narrowed down on that PR afterwards. The one compute pipeline the driver refused there (c4183d3cbee28e8e, E_OUTOFMEMORY) comes from a module that fails dxil.dll validation, in a class main emits too (compute image_sample lowered to dx.op.sample, #201; #180 fixes it), and newer drivers (616.92, 621.x) create that pipeline. The other hashes in that report are not programs #233 translates. That the first-chance exception in nvgpucomp64.dll and the refusal are linked is likely but not proven. Details: #233

Nothing here is about #334 itself. AI-assisted (Claude Code).

**@⁠r4tedx** on GitHub · 2026-11-24 05:55 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7123399139) A pointer for readers of [the report above](https://git.gtahub.st/github/Marvisak--VIctory/pulls/334), since its last paragraph mentions #233: what happened with #233 stacked was narrowed down on that PR afterwards. The one compute pipeline the driver refused there (`c4183d3cbee28e8e`, `E_OUTOFMEMORY`) comes from a module that fails `dxil.dll` validation, in a class `main` emits too (compute `image_sample` lowered to `dx.op.sample`, #201; #180 fixes it), and newer drivers (616.92, 621.x) create that pipeline. The other hashes in that report are not programs #233 translates. That the first-chance exception in `nvgpucomp64.dll` and the refusal are linked is likely but not proven. Details: https://git.gtahub.st/github/Marvisak--VIctory/pulls/233 Nothing here is about #334 itself. AI-assisted (Claude Code).
Author
Owner

@⁠colehammond65 on GitHub · 2026-11-24 06:25 UTC · original · edited 2026-11-24 06:27 UTC

RTX 4080 / Windows 10 A/B: the world hang remains; debug-layer state errors could not be measured

Environment

  • Windows 10 Pro, build 26300
  • AMD Ryzen 7 5800X, 32 GB RAM
  • NVIDIA GeForce RTX 4080 16 GB, driver 32.0.16.2135
  • Rust 1.98.1, diag profile with diagnostics
  • Xbox Series X mode, title 1.0.2.1
  • Baseline: main + PR #175 at 19aec59
  • Test branch: PR #334 at af2aecf + PR #175, merge 9c2d98b
  • Both used Agility SDK 1.620.2

Important limitation

This Windows build reports Feature name GraphicsTools is unknown. The app-local Agility SDK loads correctly, but D3D12GetDebugInterface still returns 0x887A002D. The PR's debug-layer child test also prints no D3D12 debug layer; skipped.

So this run cannot confirm whether error IDs 527/538 disappeared. It can confirm whether the device removal remains. DRED was enabled; GPU timing and GPU-based validation were not.

Method

Two runs per variant, each with a new empty cache, the same profile/data directory, and the same scripted Enter schedule from 8 through 47 seconds. Run order was baseline, #334, #334, baseline. Each run stopped on process exit or at an eight-minute timeout.

Results

Metric Baseline + #175 #334 + #175
Runs 2 2
Total survival 132.7–183.5 s 162.7–194.1 s
World-entry proxy 58.1–67.9 s 59.7–59.8 s
Exit code 0x887A0005 0x887A0005
Device-removed reason 0x887A0006 0x887A0006
Lists in failed submission 29–32 11–30
Stopped command EXECUTE_INDIRECT (op 5) or DISPATCH_MESH (op 42) DISPATCH_MESH (op 42) or EXECUTE_INDIRECT (op 5)
Page fault / freed allocation none / none none / none
Median world frame time 1671–2048 ms 1233–2049 ms
Peak working set 10.46–11.36 GiB 11.72–12.82 GiB
Peak private commit 20.37–22.69 GiB 21.48–22.12 GiB
Minimum system commit headroom 7.14–9.44 GiB 7.13–7.94 GiB

The survival and frame-time ranges overlap. Two runs per variant are not enough to claim a performance improvement or regression.

All four runs reached the world and then lost the device. None reported a page fault or a freed allocation. Commit headroom stayed above 7 GiB, so these particular failures were not commit exhaustion.

The largest shader-translation gaps were the same in both variants: lane masks read as data, selects on untracked masks, addresses in non-root SGPRs, and structured buffers of unknown stride.

Source-only verification

  • Baseline + #175: 266 passed, 0 failed, 4 ignored with serial test execution.
  • #334 + #175: 268 passed, 0 failed, 4 ignored with serial test execution.
  • The new buffer-state unit test passed. The debug-layer child test skipped because the layer is unavailable.
  • The parallel victory-shader suite crashes on this host; the same suite passes serially.

Conclusion

PR #334 did not prevent the RTX 4080 world-load device removal in this test. The failure still lands in indirect execution or mesh dispatch, without a page fault. The targeted D3D12 state-error removal remains unverified here because the debug layer cannot be installed on this Windows build.

A debug-layer-equipped tester is still needed to confirm the 527/538 result. No game files, paths, screenshots, shader dumps, or proprietary data are included in this report. AI-assisted testing and reporting; I ran the tests.

**@⁠colehammond65** on GitHub · 2026-11-24 06:25 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7123911055) · edited 2026-11-24 06:27 UTC ## RTX 4080 / Windows 10 A/B: the world hang remains; debug-layer state errors could not be measured ### Environment - Windows 10 Pro, build 26300 - AMD Ryzen 7 5800X, 32 GB RAM - NVIDIA GeForce RTX 4080 16 GB, driver 32.0.16.2135 - Rust 1.98.1, `diag` profile with `diagnostics` - Xbox Series X mode, title 1.0.2.1 - Baseline: `main` + PR #175 at `19aec59` - Test branch: PR #334 at `af2aecf` + PR #175, merge `9c2d98b` - Both used Agility SDK 1.620.2 ### Important limitation This Windows build reports `Feature name GraphicsTools is unknown`. The app-local Agility SDK loads correctly, but `D3D12GetDebugInterface` still returns `0x887A002D`. The PR's debug-layer child test also prints `no D3D12 debug layer; skipped`. So this run **cannot confirm whether error IDs 527/538 disappeared**. It can confirm whether the device removal remains. DRED was enabled; GPU timing and GPU-based validation were not. ### Method Two runs per variant, each with a new empty cache, the same profile/data directory, and the same scripted Enter schedule from 8 through 47 seconds. Run order was baseline, #334, #334, baseline. Each run stopped on process exit or at an eight-minute timeout. ### Results | Metric | Baseline + #175 | #334 + #175 | |---|---:|---:| | Runs | 2 | 2 | | Total survival | 132.7–183.5 s | 162.7–194.1 s | | World-entry proxy | 58.1–67.9 s | 59.7–59.8 s | | Exit code | `0x887A0005` | `0x887A0005` | | Device-removed reason | `0x887A0006` | `0x887A0006` | | Lists in failed submission | 29–32 | 11–30 | | Stopped command | `EXECUTE_INDIRECT` (op 5) or `DISPATCH_MESH` (op 42) | `DISPATCH_MESH` (op 42) or `EXECUTE_INDIRECT` (op 5) | | Page fault / freed allocation | none / none | none / none | | Median world frame time | 1671–2048 ms | 1233–2049 ms | | Peak working set | 10.46–11.36 GiB | 11.72–12.82 GiB | | Peak private commit | 20.37–22.69 GiB | 21.48–22.12 GiB | | Minimum system commit headroom | 7.14–9.44 GiB | 7.13–7.94 GiB | The survival and frame-time ranges overlap. Two runs per variant are not enough to claim a performance improvement or regression. All four runs reached the world and then lost the device. None reported a page fault or a freed allocation. Commit headroom stayed above 7 GiB, so these particular failures were not commit exhaustion. The largest shader-translation gaps were the same in both variants: lane masks read as data, selects on untracked masks, addresses in non-root SGPRs, and structured buffers of unknown stride. ### Source-only verification - Baseline + #175: 266 passed, 0 failed, 4 ignored with serial test execution. - #334 + #175: 268 passed, 0 failed, 4 ignored with serial test execution. - The new buffer-state unit test passed. The debug-layer child test skipped because the layer is unavailable. - The parallel `victory-shader` suite crashes on this host; the same suite passes serially. ### Conclusion PR #334 **did not prevent the RTX 4080 world-load device removal** in this test. The failure still lands in indirect execution or mesh dispatch, without a page fault. The targeted D3D12 state-error removal remains unverified here because the debug layer cannot be installed on this Windows build. A debug-layer-equipped tester is still needed to confirm the 527/538 result. No game files, paths, screenshots, shader dumps, or proprietary data are included in this report. AI-assisted testing and reporting; I ran the tests.
Author
Owner

@⁠walterwallaceson on GitHub · 2026-11-24 06:47 UTC · original

Tested af2aecf on Windows 10 22H2 (19045.6466), RTX 3070, NVIDIA 621.14, Ryzen 5 5600X, diagnostics build (--profile diag --features diagnostics), VICTORY_D3D12_DEBUG=1, VICTORY_D3D12_DRED=1. Stacked on #175, #233 + #320 + #439 (f653ea4), #55, #89 and #336, all merged cleanly; the only change between the two runs is this PR.

without #334 with #334
debug layer: vertex buffer in UNORDERED_ACCESS (IASetVertexBuffers, the 0xae00000-byte title buffer) 27 0
debug layer: ResourceBarrier before-state mismatches 43 0
device removed ~1 min 20 s into the world load, 0x887A0006; the debug layer's last error is the vertex buffer one ~2.5 min into the world load, DXGI_ERROR_DEVICE_HUNG, no debug-layer error before it
DRED: where it stopped indirect mesh draw, command 3 of 70 mesh draw, command 370 of 408

So on this machine it clears both message kinds from #264, and the removal moves later and loses its debug-layer error, but the world still hangs. In both runs the draw DRED stops on reads user data whose heap slots are null (u8, u9, and u10 in the second run), after the dynamic descriptor slots ran out ~8 s into the world load, so the remaining hang looks like the #392 / #483 class rather than buffer states. One run each.

With #493 + #483 added on top of this, the device is no longer removed at all in ~5.5 min in the world (details on #493).

cargo test --workspace: victory-gpu 50 passed; otherwise only the known Windows 10 failures.

No game data in this report.

AI-assisted (Claude Code); everything above was run on my machine.

**@⁠walterwallaceson** on GitHub · 2026-11-24 06:47 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7124292609) Tested af2aecf on Windows 10 22H2 (19045.6466), RTX 3070, NVIDIA 621.14, Ryzen 5 5600X, diagnostics build (`--profile diag --features diagnostics`), `VICTORY_D3D12_DEBUG=1`, `VICTORY_D3D12_DRED=1`. Stacked on #175, #233 + #320 + #439 (f653ea4), #55, #89 and #336, all merged cleanly; the only change between the two runs is this PR. | | without #334 | with #334 | |---|---|---| | debug layer: vertex buffer in `UNORDERED_ACCESS` (`IASetVertexBuffers`, the 0xae00000-byte title buffer) | 27 | 0 | | debug layer: `ResourceBarrier` before-state mismatches | 43 | 0 | | device removed | ~1 min 20 s into the world load, `0x887A0006`; the debug layer's last error is the vertex buffer one | ~2.5 min into the world load, `DXGI_ERROR_DEVICE_HUNG`, no debug-layer error before it | | DRED: where it stopped | indirect mesh draw, command 3 of 70 | mesh draw, command 370 of 408 | So on this machine it clears both message kinds from #264, and the removal moves later and loses its debug-layer error, but the world still hangs. In both runs the draw DRED stops on reads user data whose heap slots are null (`u8`, `u9`, and `u10` in the second run), after the dynamic descriptor slots ran out ~8 s into the world load, so the remaining hang looks like the #392 / #483 class rather than buffer states. One run each. With #493 + #483 added on top of this, the device is no longer removed at all in ~5.5 min in the world (details on #493). `cargo test --workspace`: `victory-gpu` 50 passed; otherwise only the known Windows 10 failures. No game data in this report. AI-assisted (Claude Code); everything above was run on my machine.
Author
Owner

@⁠erLCoder on GitHub · 2026-11-24 06:26 UTC · original · edited 2026-11-24 06:48 UTC

Tested af2aecf6c130e6c931b9ca58a15718530c16c3ba on Windows 10 Enterprise 22H2, GTX 1660 Ti (Turing), NVIDIA 581.42, Rust 1.98.1.

cargo test --offline --locked -p victory-gpu --features diagnostics --lib host::tests -- --nocapture --test-threads=1 passed 4/4. The state-transition unit test passed, and the debug-layer child test ran direct and indirect draws without reporting D3D12 errors or a skip.

The check above was synthetic.

Follow-up, game run on the same PC. Tested one Series X run with #334 (af2aecf), #89 (081afbd), #152 (18b2716), and #439 (e6936e3, including #233/#320), plus Agility SDK 1.620.2 and local logging. DRED was enabled; the D3D12 debug layer was off for this game run. The scene HUD appeared on a black background around eight minutes in. The process ended at about 8m37s with DXGI_ERROR_DEVICE_HUNG (0x887A0006). DRED recorded 25 submitted lists and stopped at command 2554 of 3634 (op 42, DispatchMesh) in one list. Just before removal, DirectStorage had finished 66,425 reads with no errors or pending reads. The previous synthetic barrier test passed; this stacked run does not isolate #334 or identify the cause of device removal.

AI-assisted report.

**@⁠erLCoder** on GitHub · 2026-11-24 06:26 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7123937404) · edited 2026-11-24 06:48 UTC Tested af2aecf6c130e6c931b9ca58a15718530c16c3ba on Windows 10 Enterprise 22H2, GTX 1660 Ti (Turing), NVIDIA 581.42, Rust 1.98.1. `cargo test --offline --locked -p victory-gpu --features diagnostics --lib host::tests -- --nocapture --test-threads=1` passed 4/4. The state-transition unit test passed, and the debug-layer child test ran direct and indirect draws without reporting D3D12 errors or a skip. The check above was synthetic. **Follow-up, game run on the same PC.** Tested one Series X run with #334 (`af2aecf`), #89 (`081afbd`), #152 (`18b2716`), and #439 (`e6936e3`, including #233/#320), plus Agility SDK 1.620.2 and local logging. DRED was enabled; the D3D12 debug layer was off for this game run. The scene HUD appeared on a black background around eight minutes in. The process ended at about 8m37s with `DXGI_ERROR_DEVICE_HUNG` (`0x887A0006`). DRED recorded 25 submitted lists and stopped at command 2554 of 3634 (op 42, `DispatchMesh`) in one list. Just before removal, DirectStorage had finished 66,425 reads with no errors or pending reads. The previous synthetic barrier test passed; this stacked run does not isolate #334 or identify the cause of device removal. AI-assisted report.
Author
Owner

@⁠Hiiva on GitHub · 2026-11-24 10:14 UTC · original

Validated af2aecf with the D3D12 debug layer and GBV on Microsoft's WARP adapter (vendor 0x1414, software flag 0x2). The sequential buffer-state scenario passes, including submitting the two recorded lists in reverse order and resetting/reusing one list.

There is a hole in the current regression test: Host::execute calls log_messages(), which clears the information queue before the test reads it. I changed the test to collect errors through ID3D12InfoQueue1 callbacks so execution cannot erase the evidence. With the closing return-to-COMMON temporarily disabled, this test reliably fails with id 527 (COMMON before-state versus GENERIC_READ). Restoring the transition makes it pass. The test also keeps errors reported while recording.

Integration with #493 needs a BUFFER_READ state call in root_srv_table's shadow.refresh branch, because bounded root SRVs bypass root_view(). The source and test changes are at github.com/Hiiva/VIctory@0c2a559 . Diagnostics all-target clippy passes with warnings denied.

This checks sequential writes and reads. Simultaneous SRV/UAV uses of one backing resource still need a separate solution; the alias work does not change that. No title-run success claim from this synthetic test.

**@⁠Hiiva** on GitHub · 2026-11-24 10:14 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7128511903) Validated af2aecf with the D3D12 debug layer and GBV on Microsoft's WARP adapter (vendor 0x1414, software flag 0x2). The sequential buffer-state scenario passes, including submitting the two recorded lists in reverse order and resetting/reusing one list. There is a hole in the current regression test: Host::execute calls log_messages(), which clears the information queue before the test reads it. I changed the test to collect errors through ID3D12InfoQueue1 callbacks so execution cannot erase the evidence. With the closing return-to-COMMON temporarily disabled, this test reliably fails with id 527 (COMMON before-state versus GENERIC_READ). Restoring the transition makes it pass. The test also keeps errors reported while recording. Integration with #493 needs a BUFFER_READ state call in root_srv_table's shadow.refresh branch, because bounded root SRVs bypass root_view(). The source and test changes are at https://github.com/Hiiva/VIctory/commit/0c2a559 . Diagnostics all-target clippy passes with warnings denied. This checks sequential writes and reads. Simultaneous SRV/UAV uses of one backing resource still need a separate solution; the alias work does not change that. No title-run success claim from this synthetic test.
Author
Owner

@⁠andrewpozdnakov7-jpg on GitHub · 2026-11-24 10:46 UTC · original

I checked the buffer UAV clear follow-up from #771 against this PR. The texture-clear commit d359499 merges cleanly with af2aecf.

With d359499 alone, neither guest clear changes its buffer. With the patch below, both guest entry points clear only the three elements selected by a typed UAV (FirstElement = 2, NumElements = 3). The R32_UINT buffer reads [1, 2, 41, 41, 41, 6] and the R32_FLOAT buffer reads [1, 2, 0.5, 0.5, 0.5, 6] after submission.

I also copied the integer buffer to native readback before and after the guest clear in the same list. The first copy saw the original values and the second saw the clear. Removing the call to this PR's buffer_state(..., BUFFER_WRITE) makes the regression fail at the state assertion, where the buffer remains in GENERIC_READ.

The follow-up reuses the native descriptor construction and the existing shadow refresh/copy-back path. The patch applies after combining d359499 and af2aecf.

A 2-by-2 texture UAV control also read back all four expected texels. The diagnostics suite passed 55 tests, with the focused WARP test run separately. Library Clippy passed with warnings denied.

AI-assisted. Verified on WARP with synthetic data. The SDK debug layer was unavailable on this machine.

Incremental production patch
diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs
--- a/crates/victory-gpu/src/descriptor/host.rs
+++ b/crates/victory-gpu/src/descriptor/host.rs
@@ -280,39 +280,37 @@ impl HostHeap {
 
     /// Makes a matched native UAV pair from the CPU view. The GPU slot is
     /// held until list reset like the descriptors in a fresh table.
-    pub(crate) fn clear_texture_uav(
+    pub(crate) fn clear_uav(
         &self,
         list: &crate::host::HostList,
-        texture: &ID3D12Resource,
-        words: Option<&[u32; 10]>,
-    ) -> Option<(u32, D3D12_GPU_DESCRIPTOR_HANDLE, D3D12_CPU_DESCRIPTOR_HANDLE)> {
-        let mut desc = words.map(uav_desc);
-        if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) {
-            return None;
-        }
+        view: &View,
+    ) -> Option<(
+        u32,
+        D3D12_GPU_DESCRIPTOR_HANDLE,
+        D3D12_CPU_DESCRIPTOR_HANDLE,
+        ID3D12Resource,
+    )> {
         let device = &host()?.device;
         let cpu = list.clear_uav_cpu()?;
+        let resource = make(view, cpu)??;
         let slot = self.dynamic(1)?;
         // SAFETY: both handles name live heap slots. Copy from the
         // CPU-only heap to the shader-visible heap.
         let gpu = unsafe {
-            device.CreateUnorderedAccessView(
-                texture,
-                None::<&ID3D12Resource>,
-                desc.as_ref().map(std::ptr::from_ref),
-                cpu,
-            );
             device.CopyDescriptorsSimple(
-                1, self.cpu(slot), cpu, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
+                1,
+                self.cpu(slot),
+                cpu,
+                D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
             );
             D3D12_GPU_DESCRIPTOR_HANDLE {
                 ptr: self.heap.GetGPUDescriptorHandleForHeapStart().ptr
                     + u64::from(slot) * u64::from(self.step),
             }
         };
-        // The list's texture state retains the resource through execution.
+        // The list's texture state or deferred buffer steps retain the resource.
         self.keep(slot, None);
-        Some((slot, gpu, cpu))
+        Some((slot, gpu, cpu, resource))
     }
 
 
@@ -526,8 +524,8 @@ fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> {
         crate::resource::element(desc.Format.0 as u32)?.0
     };
     Some((
-        base + buffer.FirstElement * element,
-        u64::from(buffer.NumElements) * element,
+        base.checked_add(buffer.FirstElement.checked_mul(element)?)?,
+        u64::from(buffer.NumElements).checked_mul(element)?,
     ))
 }
 
diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs
--- a/crates/victory-gpu/src/draw.rs
+++ b/crates/victory-gpu/src/draw.rs
@@ -439,8 +439,8 @@ impl State {
         }
     }
 
-    /// Records a clear of a resource-backed texture UAV in the bound heap.
-    pub(crate) fn clear_texture_uav(
+    /// Records a clear of a resource-backed UAV in the bound heap.
+    pub(crate) fn clear_uav(
         &mut self,
         list: &HostList,
         gpu: u64,
@@ -457,35 +457,59 @@ impl State {
         if heap.index(gpu).is_none() {
             return;
         }
-        let (Some(View::Unordered(cpu_resource, _, words)), Some(View::Unordered(gpu_resource, _, _))) =
-            (crate::descriptor::view(cpu), crate::descriptor::view(gpu))
+        let (
+            Some(view @ View::Unordered(cpu_resource, _, words)),
+            Some(View::Unordered(gpu_resource, _, _)),
+        ) = (crate::descriptor::view(cpu), crate::descriptor::view(gpu))
         else {
             return;
         };
         if cpu_resource != resource as usize || gpu_resource != cpu_resource {
             return;
         }
-        let (Some(texture), Some(native_heap)) =
-            (crate::resource::host_resource(resource), heap.host())
-        else {
-            return;
+        let buffer = if let Some((data, size)) = crate::resource::buffer_bytes(resource) {
+            let base = data as u64;
+            if words.is_none_or(|desc| desc[1] != D3D12_UAV_DIMENSION_BUFFER.0 as u32) {
+                return;
+            }
+            let Some((address, len)) = crate::descriptor::host::buffer_range(&view) else {
+                return;
+            };
+            if len == 0
+                || (address - base)
+                    .checked_add(len)
+                    .is_none_or(|end| end > size)
+            {
+                return;
+            }
+            let Some(shadow) = crate::shadow::find(base, size) else {
+                return;
+            };
+            Some((shadow, address, len))
+        } else {
+            None
         };
-        let Some((slot, gpu, cpu)) = native_heap.clear_texture_uav(list, texture, words.as_ref())
-        else {
+        let Some((slot, gpu, cpu, native)) = heap.host().and_then(|h| h.clear_uav(list, &view)) else {
             return;
         };
         self.dynamic.push((heap_id, slot, 1));
         self.bind_heaps(list);
-        crate::list::ensure_state(list, resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32);
-        // SAFETY: matched views, a live texture in UAV state, and the
-        // shader-visible descriptor's heap is bound on this list.
+        if let Some((shadow, address, len)) = buffer {
+            shadow.refresh(list, address, len);
+            shadow.gpu_writes(list, address, len);
+            list.buffer_state(&native, crate::host::BUFFER_WRITE);
+        } else {
+            crate::list::ensure_state(list, resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32);
+        }
+        // SAFETY: both views name the same live resource in UAV state,
+        // and the shader-visible descriptor's heap is bound on this list.
         unsafe {
             match value {
                 UavClear::Uint(values) => {
-                    list.list.ClearUnorderedAccessViewUint(gpu, cpu, texture, &values, rects);
+                    list.list.ClearUnorderedAccessViewUint(gpu, cpu, &native, &values, rects);
                 }
                 UavClear::Float(values) => {
-                    list.list.ClearUnorderedAccessViewFloat(gpu, cpu, texture, &values, rects);
+                    list.list.ClearUnorderedAccessViewFloat(gpu, cpu, &native, &values, rects);
                 }
             }
         }
diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs
--- a/crates/victory-gpu/src/list.rs
+++ b/crates/victory-gpu/src/list.rs
@@ -762,7 +762,7 @@ extern "system" fn clear_dsv(
     let _ = (this, handle, flags, depth, stencil, count, rects);
 }
 
-/// Clear a resource-backed texture with a matching bound GPU UAV and CPU UAV.
+/// Clear a resource-backed UAV with matching bound GPU and CPU descriptors.
 #[cfg(windows)]
 fn clear_uav(
     this: This,
@@ -779,7 +779,7 @@ fn clear_uav(
         // SAFETY: the title passes count rectangles in the host's layout.
         unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) }
     };
-    with_state(this, |list, state| state.clear_texture_uav(list, gpu, cpu, resource, value, rects));
+    with_state(this, |list, state| state.clear_uav(list, gpu, cpu, resource, value, rects));
 }
 
 extern "system" fn clear_uav_uint(
**@⁠andrewpozdnakov7-jpg** on GitHub · 2026-11-24 10:46 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7129222811) I checked the buffer UAV clear follow-up from #771 against this PR. The texture-clear commit `d359499` merges cleanly with `af2aecf`. With `d359499` alone, neither guest clear changes its buffer. With the patch below, both guest entry points clear only the three elements selected by a typed UAV (`FirstElement = 2`, `NumElements = 3`). The `R32_UINT` buffer reads `[1, 2, 41, 41, 41, 6]` and the `R32_FLOAT` buffer reads `[1, 2, 0.5, 0.5, 0.5, 6]` after submission. I also copied the integer buffer to native readback before and after the guest clear in the same list. The first copy saw the original values and the second saw the clear. Removing the call to this PR's `buffer_state(..., BUFFER_WRITE)` makes the regression fail at the state assertion, where the buffer remains in `GENERIC_READ`. The follow-up reuses the native descriptor construction and the existing shadow refresh/copy-back path. The patch applies after combining `d359499` and `af2aecf`. A 2-by-2 texture UAV control also read back all four expected texels. The diagnostics suite passed 55 tests, with the focused WARP test run separately. Library Clippy passed with warnings denied. AI-assisted. Verified on WARP with synthetic data. The SDK debug layer was unavailable on this machine. <details> <summary>Incremental production patch</summary> ```diff diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -280,39 +280,37 @@ impl HostHeap { /// Makes a matched native UAV pair from the CPU view. The GPU slot is /// held until list reset like the descriptors in a fresh table. - pub(crate) fn clear_texture_uav( + pub(crate) fn clear_uav( &self, list: &crate::host::HostList, - texture: &ID3D12Resource, - words: Option<&[u32; 10]>, - ) -> Option<(u32, D3D12_GPU_DESCRIPTOR_HANDLE, D3D12_CPU_DESCRIPTOR_HANDLE)> { - let mut desc = words.map(uav_desc); - if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) { - return None; - } + view: &View, + ) -> Option<( + u32, + D3D12_GPU_DESCRIPTOR_HANDLE, + D3D12_CPU_DESCRIPTOR_HANDLE, + ID3D12Resource, + )> { let device = &host()?.device; let cpu = list.clear_uav_cpu()?; + let resource = make(view, cpu)??; let slot = self.dynamic(1)?; // SAFETY: both handles name live heap slots. Copy from the // CPU-only heap to the shader-visible heap. let gpu = unsafe { - device.CreateUnorderedAccessView( - texture, - None::<&ID3D12Resource>, - desc.as_ref().map(std::ptr::from_ref), - cpu, - ); device.CopyDescriptorsSimple( - 1, self.cpu(slot), cpu, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + 1, + self.cpu(slot), + cpu, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, ); D3D12_GPU_DESCRIPTOR_HANDLE { ptr: self.heap.GetGPUDescriptorHandleForHeapStart().ptr + u64::from(slot) * u64::from(self.step), } }; - // The list's texture state retains the resource through execution. + // The list's texture state or deferred buffer steps retain the resource. self.keep(slot, None); - Some((slot, gpu, cpu)) + Some((slot, gpu, cpu, resource)) } @@ -526,8 +524,8 @@ fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> { crate::resource::element(desc.Format.0 as u32)?.0 }; Some(( - base + buffer.FirstElement * element, - u64::from(buffer.NumElements) * element, + base.checked_add(buffer.FirstElement.checked_mul(element)?)?, + u64::from(buffer.NumElements).checked_mul(element)?, )) } diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -439,8 +439,8 @@ impl State { } } - /// Records a clear of a resource-backed texture UAV in the bound heap. - pub(crate) fn clear_texture_uav( + /// Records a clear of a resource-backed UAV in the bound heap. + pub(crate) fn clear_uav( &mut self, list: &HostList, gpu: u64, @@ -457,35 +457,59 @@ impl State { if heap.index(gpu).is_none() { return; } - let (Some(View::Unordered(cpu_resource, _, words)), Some(View::Unordered(gpu_resource, _, _))) = - (crate::descriptor::view(cpu), crate::descriptor::view(gpu)) + let ( + Some(view @ View::Unordered(cpu_resource, _, words)), + Some(View::Unordered(gpu_resource, _, _)), + ) = (crate::descriptor::view(cpu), crate::descriptor::view(gpu)) else { return; }; if cpu_resource != resource as usize || gpu_resource != cpu_resource { return; } - let (Some(texture), Some(native_heap)) = - (crate::resource::host_resource(resource), heap.host()) - else { - return; + let buffer = if let Some((data, size)) = crate::resource::buffer_bytes(resource) { + let base = data as u64; + if words.is_none_or(|desc| desc[1] != D3D12_UAV_DIMENSION_BUFFER.0 as u32) { + return; + } + let Some((address, len)) = crate::descriptor::host::buffer_range(&view) else { + return; + }; + if len == 0 + || (address - base) + .checked_add(len) + .is_none_or(|end| end > size) + { + return; + } + let Some(shadow) = crate::shadow::find(base, size) else { + return; + }; + Some((shadow, address, len)) + } else { + None }; - let Some((slot, gpu, cpu)) = native_heap.clear_texture_uav(list, texture, words.as_ref()) - else { + let Some((slot, gpu, cpu, native)) = heap.host().and_then(|h| h.clear_uav(list, &view)) else { return; }; self.dynamic.push((heap_id, slot, 1)); self.bind_heaps(list); - crate::list::ensure_state(list, resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32); - // SAFETY: matched views, a live texture in UAV state, and the - // shader-visible descriptor's heap is bound on this list. + if let Some((shadow, address, len)) = buffer { + shadow.refresh(list, address, len); + shadow.gpu_writes(list, address, len); + list.buffer_state(&native, crate::host::BUFFER_WRITE); + } else { + crate::list::ensure_state(list, resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32); + } + // SAFETY: both views name the same live resource in UAV state, + // and the shader-visible descriptor's heap is bound on this list. unsafe { match value { UavClear::Uint(values) => { - list.list.ClearUnorderedAccessViewUint(gpu, cpu, texture, &values, rects); + list.list.ClearUnorderedAccessViewUint(gpu, cpu, &native, &values, rects); } UavClear::Float(values) => { - list.list.ClearUnorderedAccessViewFloat(gpu, cpu, texture, &values, rects); + list.list.ClearUnorderedAccessViewFloat(gpu, cpu, &native, &values, rects); } } } diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -762,7 +762,7 @@ extern "system" fn clear_dsv( let _ = (this, handle, flags, depth, stencil, count, rects); } -/// Clear a resource-backed texture with a matching bound GPU UAV and CPU UAV. +/// Clear a resource-backed UAV with matching bound GPU and CPU descriptors. #[cfg(windows)] fn clear_uav( this: This, @@ -779,7 +779,7 @@ fn clear_uav( // SAFETY: the title passes count rectangles in the host's layout. unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) } }; - with_state(this, |list, state| state.clear_texture_uav(list, gpu, cpu, resource, value, rects)); + with_state(this, |list, state| state.clear_uav(list, gpu, cpu, resource, value, rects)); } extern "system" fn clear_uav_uint( ``` </details>
Author
Owner

@⁠fuzeofficlal on GitHub · 2026-11-24 10:49 UTC · original

I checked Hiiva's bounded-root read transition on a combined af2aecf (#334) + c48b240 (#493) stack. The synthetic command list went through VIctory's actual root_srv_table binding on RTX 5090 and WARP. A first read returned 41, then a separate UAV dispatch wrote 89 and a second read through the same cached descriptor slot returned 89. A null view returned zero and left the separately tracked buffer in its write state. Both adapters reported zero D3D12 errors, and both diagnostics suites passed 55 tests with one benchmark ignored.

Source follow-up 277c20d retains the read transition from Hiiva's integration, including on cache hits, and applies it only when the table has a backing buffer. The probe covers sequential dispatches and the null-view control.

**@⁠fuzeofficlal** on GitHub · 2026-11-24 10:49 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7129288054) I checked Hiiva's bounded-root read transition on a combined `af2aecf` (#334) + `c48b240` (#493) stack. The synthetic command list went through VIctory's actual `root_srv_table` binding on RTX 5090 and WARP. A first read returned 41, then a separate UAV dispatch wrote 89 and a second read through the same cached descriptor slot returned 89. A null view returned zero and left the separately tracked buffer in its write state. Both adapters reported zero D3D12 errors, and both diagnostics suites passed 55 tests with one benchmark ignored. [Source follow-up `277c20d`](https://github.com/fuzeofficlal/VIctory/commit/277c20d626cf1dde16d2e0724662d9bda2a67849) retains the read transition from [Hiiva's integration](https://github.com/Hiiva/VIctory/commit/0c2a55913bcad1e1e977a53db76f140f2f4dc880), including on cache hits, and applies it only when the table has a backing buffer. The probe covers sequential dispatches and the null-view control.
Author
Owner

@⁠dcastell1 on GitHub · 2026-11-24 11:34 UTC · original

Verified as part of the world-stack several testers are using, on NVIDIA GeForce RTX 5090, driver 621.24, Windows 11 10.0.26300, Rust 1.98.1, MSVC 14.44.35207, debug build:

main@ffe310e (342 passed, 0 failed, 6 ignored)
+ this PR
+ #24 (indirect mesh dispatches)
+ MIN_DYNAMIC = 1 << 18 (issue #747)
cargo test --workspace  ->  346 passed; 0 failed; 6 ignored   (exit 0)

So on Blackwell the stack builds and the workspace is green with it applied; #413 is the one that does not apply to current main (it is marked conflicting). What I cannot answer from here is the G-buffer effect — this box has no retail package, so the frame counts have to come from a machine that runs the title.

AI-assisted (opencode): applied the stack to a built tree, ran the suite, reverted it.

**@⁠dcastell1** on GitHub · 2026-11-24 11:34 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7130276724) Verified as part of the world-stack several testers are using, on **NVIDIA GeForce RTX 5090, driver 621.24, Windows 11 10.0.26300, Rust 1.98.1, MSVC 14.44.35207, debug build**: ``` main@ffe310e (342 passed, 0 failed, 6 ignored) + this PR + #24 (indirect mesh dispatches) + MIN_DYNAMIC = 1 << 18 (issue #747) cargo test --workspace -> 346 passed; 0 failed; 6 ignored (exit 0) ``` So on Blackwell the stack builds and the workspace is green with it applied; #413 is the one that does not apply to current main (it is marked conflicting). What I cannot answer from here is the G-buffer effect — this box has no retail package, so the frame counts have to come from a machine that runs the title. AI-assisted (opencode): applied the stack to a built tree, ran the suite, reverted it.
Author
Owner

@⁠Hiiva on GitHub · 2026-11-24 11:38 UTC · original

Two additional buffer-coherence regressions are fixed in my integration of this PR.

  1. Descriptor construction selected a shadow using the full resource range, while draw preparation selected it again using the smaller view range. A nested registered buffer could make the second lookup choose a different host copy. The descriptor now retains its exact shadow, bounded byte window, and read/write class. Refresh, state transitions, and copyback follow that binding, including alias-only structured views. Root SRV cache keys also include the actual resource identity, offset, and visible length.
  2. A bounded root SRV exposed its full complete-dword window but refreshed only the first 1 MiB. It now refreshes the exact exposed range; null and misaligned bindings retain zero-read behavior.

Synthetic red/green evidence on WARP and RTX 4080:

  • Restoring the old address lookup leaves CPU output word 32 at 0xA5A5A5A5 instead of the GPU-written 1000. The retained-owner version passes for raw and alias-only views, including neighbors, replacement, nulling, and retirement.
  • The old root SRV refresh returns stale 0xCDCDCDCD beyond 2 MiB. The fixed path passes two CPU-write generations, reads across the old cutoff, end/OOB checks, and neighbor preservation.
  • Debug layer and GBV were enabled, with persistent error callbacks empty on both adapters. The combined integration passes 95 GPU tests and 208 shader tests, with four ignored tests and no failures. These are synthetic results; a new title run is pending.

Source commits:

All fixtures use synthetic shaders and buffers. No title assets or captured shaders are included.

**@⁠Hiiva** on GitHub · 2026-11-24 11:38 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7130349890) Two additional buffer-coherence regressions are fixed in my integration of this PR. 1. Descriptor construction selected a shadow using the full resource range, while draw preparation selected it again using the smaller view range. A nested registered buffer could make the second lookup choose a different host copy. The descriptor now retains its exact shadow, bounded byte window, and read/write class. Refresh, state transitions, and copyback follow that binding, including alias-only structured views. Root SRV cache keys also include the actual resource identity, offset, and visible length. 2. A bounded root SRV exposed its full complete-dword window but refreshed only the first 1 MiB. It now refreshes the exact exposed range; null and misaligned bindings retain zero-read behavior. Synthetic red/green evidence on WARP and RTX 4080: - Restoring the old address lookup leaves CPU output word 32 at 0xA5A5A5A5 instead of the GPU-written 1000. The retained-owner version passes for raw and alias-only views, including neighbors, replacement, nulling, and retirement. - The old root SRV refresh returns stale 0xCDCDCDCD beyond 2 MiB. The fixed path passes two CPU-write generations, reads across the old cutoff, end/OOB checks, and neighbor preservation. - Debug layer and GBV were enabled, with persistent error callbacks empty on both adapters. The combined integration passes 95 GPU tests and 208 shader tests, with four ignored tests and no failures. These are synthetic results; a new title run is pending. Source commits: - [Descriptor ownership](https://github.com/Hiiva/VIctory/commit/17671c9b20b7f25fac2d468e07923326d2569263) - [Complete root SRV refresh](https://github.com/Hiiva/VIctory/commit/e22d46a) - [Validated integration](https://github.com/Hiiva/VIctory/commit/28924e83c5e485725b0f237349e911fea0143319) All fixtures use synthetic shaders and buffers. No title assets or captured shaders are included.
Author
Owner

@⁠realhenners on GitHub · 2026-11-24 12:41 UTC · original

Thanks, everyone, for the runs and the review.

Results so far, as I read them: with this PR, the debug-layer errors it targets drop to 0 in real title runs on NVIDIA (EduAzevedo, RTX 2070 SUPER: 52–157 vertex-buffer-in-UAV and 74–216 before-state mismatches per run on main; walterwallaceson, RTX 3070: 27 and 43). The world hang remains, and the runs point elsewhere: Wave64 compute refused on 32-lane hosts (#71, #189/#233) and dynamic descriptor slots running out (#392/#483/#493, #747). So this PR fixes the resource states, not the hang, as the description said.

Pushed c99e429, rebased onto ffe310e:

  • A command that writes a copy keeps it writable (r4tedx, QemmHD). BufferStates now counts commands (State::bind and the argument clamp each start one) and remembers which command last asked to write each copy. A read requested in that same command leaves the copy in UNORDERED_ACCESS, whichever view is bound first. The next command's read transitions it as before, so the writes are still separated from later vertex and index reads. New unit test: buffer_states_keep_a_command_writing. One known limit is in the code comment: if a single command writes a copy and also reads it as vertices, indices or arguments, it reads them in the write state, because D3D12 has no state that is both.
  • The debug-layer test can no longer be emptied by Host::execute (Hiiva). Rather than switching to callbacks, the child process unsets VICTORY_D3D12_DEBUG, so the host never takes over the message queue. With the closing return to COMMON disabled, the test now fails with id 527 in a diagnostics build with VICTORY_D3D12_DEBUG=1 set (checked on an RTX 4070 Ti), and it passes with the transition restored.

cargo test --workspace passes on ffe310e plus this branch. Clippy on victory-gpu (with and without diagnostics) is clean, and so is cargo xtask policy.

On #493: bounded root SRVs that bypass root_view will need the same buffer_state(..., BUFFER_READ) call, as Hiiva noted. Whichever PR lands second should add it.

AI use: Claude Code (Claude Opus 5.5) made the changes and drafted this reply; the tests ran on my machine.

**@⁠realhenners** on GitHub · 2026-11-24 12:41 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7131791308) Thanks, everyone, for the runs and the review. **Results so far, as I read them:** with this PR, the debug-layer errors it targets drop to 0 in real title runs on NVIDIA (EduAzevedo, RTX 2070 SUPER: 52–157 vertex-buffer-in-UAV and 74–216 before-state mismatches per run on `main`; walterwallaceson, RTX 3070: 27 and 43). The world hang remains, and the runs point elsewhere: Wave64 compute refused on 32-lane hosts (#71, #189/#233) and dynamic descriptor slots running out (#392/#483/#493, #747). So this PR fixes the resource states, not the hang, as the description said. **Pushed `c99e429`, rebased onto `ffe310e`:** - **A command that writes a copy keeps it writable** (r4tedx, QemmHD). `BufferStates` now counts commands (`State::bind` and the argument clamp each start one) and remembers which command last asked to write each copy. A read requested in that same command leaves the copy in `UNORDERED_ACCESS`, whichever view is bound first. The next command's read transitions it as before, so the writes are still separated from later vertex and index reads. New unit test: `buffer_states_keep_a_command_writing`. One known limit is in the code comment: if a single command writes a copy and also reads it as vertices, indices or arguments, it reads them in the write state, because D3D12 has no state that is both. - **The debug-layer test can no longer be emptied by `Host::execute`** (Hiiva). Rather than switching to callbacks, the child process unsets `VICTORY_D3D12_DEBUG`, so the host never takes over the message queue. With the closing return to `COMMON` disabled, the test now fails with id 527 in a diagnostics build with `VICTORY_D3D12_DEBUG=1` set (checked on an RTX 4070 Ti), and it passes with the transition restored. `cargo test --workspace` passes on `ffe310e` plus this branch. Clippy on `victory-gpu` (with and without `diagnostics`) is clean, and so is `cargo xtask policy`. On #493: bounded root SRVs that bypass `root_view` will need the same `buffer_state(..., BUFFER_READ)` call, as Hiiva noted. Whichever PR lands second should add it. AI use: Claude Code (Claude Opus 5.5) made the changes and drafted this reply; the tests ran on my machine.
Author
Owner

@⁠MichaelSmithAI on GitHub · 2026-11-24 15:02 UTC · original

We checked the current #334 changes on a staged build that also has root-view bounds and indirect rectangle handling. On an RTX 4090 with Wine/vkd3d-proton 3.2, two command lists used the same backing buffer for vertex data and clamped indirect arguments. The second list cleared the target before drawing its indirect triangle, so an old image could not satisfy the check. Readback showed a red pixel inside the triangle and a black pixel outside it.

All 11 focused controls passed. The broader GPU suite had 89 passes, one ignored test and the previously observed Wine empty-pipeline-library failure. This is local rendering evidence for the combination. The native tester results above cover debug-layer warning suppression. Whether the change affects the RTX 3060 endpoint in #1001 still needs a comparison on that setup.

**@⁠MichaelSmithAI** on GitHub · 2026-11-24 15:02 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7135347601) We checked the current #334 changes on a staged build that also has root-view bounds and indirect rectangle handling. On an RTX 4090 with Wine/vkd3d-proton 3.2, two command lists used the same backing buffer for vertex data and clamped indirect arguments. The second list cleared the target before drawing its indirect triangle, so an old image could not satisfy the check. Readback showed a red pixel inside the triangle and a black pixel outside it. All 11 focused controls passed. The broader GPU suite had 89 passes, one ignored test and the previously observed Wine empty-pipeline-library failure. This is local rendering evidence for the combination. The native tester results above cover debug-layer warning suppression. Whether the change affects the RTX 3060 endpoint in #1001 still needs a comparison on that setup.
Author
Owner

@⁠bunbeans2-arch on GitHub · 2026-11-24 19:32 UTC · original

Tested c99e429 on an AMD Radeon RX 9070 XT (RDNA4), driver 32.0.32015.7029, Windows 11 Pro build 22631. Native D3D12, diagnostics build, VICTORY_D3D12_DEBUG=1. A retail title ran 300 s each time: boot, then a story save loading into the game world. As far as I can see, this is the first in-title run on AMD in this thread; the AMD report above is the synthetic test.

Debug-layer errors without this PR with this PR
total 76 0
id 527, ResourceBarrier before state UNORDERED_ACCESS mismatch 46 0
id 538, IASetVertexBuffers on a resource in UNORDERED_ACCESS 30 0
device removed / hung 0 / 0 0 / 0

A second run with this PR, on a build one translator change older, also logged 0 debug-layer errors in 300 s. A 600 s run with this PR and the debug layer off logged no device removal.

Caveat: this is not a single-variable A/B. Both builds sit on a local stack of other open translator PRs, and the run with this PR also has one more local translator change: 1835 shaders translated against 1682. More translated shaders should mean more buffer uses, not fewer, so I read the drop to 0 as this PR's doing.

AI-assisted (Claude); the runs were on my machine.

**@⁠bunbeans2-arch** on GitHub · 2026-11-24 19:32 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7142246284) Tested `c99e429` on an **AMD Radeon RX 9070 XT (RDNA4)**, driver 32.0.32015.7029, Windows 11 Pro build 22631. Native D3D12, diagnostics build, `VICTORY_D3D12_DEBUG=1`. A retail title ran 300 s each time: boot, then a story save loading into the game world. As far as I can see, this is the first in-title run on AMD in this thread; the AMD report above is the synthetic test. | Debug-layer errors | without this PR | with this PR | |---|---|---| | total | 76 | **0** | | id 527, `ResourceBarrier` before state `UNORDERED_ACCESS` mismatch | 46 | **0** | | id 538, `IASetVertexBuffers` on a resource in `UNORDERED_ACCESS` | 30 | **0** | | device removed / hung | 0 / 0 | 0 / 0 | A second run with this PR, on a build one translator change older, also logged 0 debug-layer errors in 300 s. A 600 s run with this PR and the debug layer off logged no device removal. Caveat: this is not a single-variable A/B. Both builds sit on a local stack of other open translator PRs, and the run with this PR also has one more local translator change: 1835 shaders translated against 1682. More translated shaders should mean more buffer uses, not fewer, so I read the drop to 0 as this PR's doing. AI-assisted (Claude); the runs were on my machine.
Author
Owner

@⁠Bladureau on GitHub · 2026-11-24 19:58 UTC · original

Tested c99e429 in the title on an RTX 4060 Laptop (8 GB, 32-lane waves), with the D3D12 debug layer on. The state errors are gone.

Setup: Windows 11 Pro 26300, NVIDIA GeForce RTX 4060 Laptop GPU 8 GB (driver 617.14), i7-13650HX, 32 GB. Title exe BLAKE3 b99f876b74d4a77f… (1.0.2.1). I merged this PR onto main ffe310e and #578 (fb7facd), both cleanly. #578 is there so the run is not cut short by the wave64 hang, which ends every world run on this card within 38–217 s on main. Diag build, VICTORY_D3D12_DEBUG=1, VICTORY_D3D12_DRED=1. I played into the first mission's intro by hand.

main ffe310e (2 runs, debug layer on) main + #578 + this PR
id 527 (barrier before-state mismatch) 137, 31 0
id 538 (vertex buffer in UNORDERED_ACCESS) 125, 18 0
Other debug-layer errors 622 (wave64 pipelines), 599, 232 (the removal) only 599 (×2, a texture format with ALLOW_UNORDERED_ACCESS, in every run)
Device removal after 217 s and 38 s in the world none in about 215 s in the world (closed by me)

cargo test -p victory-gpu -- --test-threads=1 gives 56 passed. That includes debug_layer_accepts_buffers_written_then_read_as_vertices, which ran here with the debug layer and was not skipped.

I had opened #1507 and #1527 for the same two errors. This PR covers more (shader writes, table views) and has a test, so I am closing mine in favour of it.

**@⁠Bladureau** on GitHub · 2026-11-24 19:58 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7142860514) Tested `c99e429` in the title on an **RTX 4060 Laptop (8 GB, 32-lane waves)**, with the D3D12 debug layer on. The state errors are gone. **Setup:** Windows 11 Pro 26300, NVIDIA GeForce RTX 4060 Laptop GPU 8 GB (driver 617.14), i7-13650HX, 32 GB. Title exe BLAKE3 `b99f876b74d4a77f…` (1.0.2.1). I merged this PR onto `main` `ffe310e` and #578 (`fb7facd`), both cleanly. #578 is there so the run is not cut short by the wave64 hang, which ends every world run on this card within 38–217 s on `main`. Diag build, `VICTORY_D3D12_DEBUG=1`, `VICTORY_D3D12_DRED=1`. I played into the first mission's intro by hand. | | `main` `ffe310e` (2 runs, debug layer on) | `main` + #578 + this PR | |---|---|---| | id 527 (barrier before-state mismatch) | 137, 31 | **0** | | id 538 (vertex buffer in `UNORDERED_ACCESS`) | 125, 18 | **0** | | Other debug-layer errors | 622 (wave64 pipelines), 599, 232 (the removal) | only 599 (×2, a texture format with `ALLOW_UNORDERED_ACCESS`, in every run) | | Device removal | after 217 s and 38 s in the world | none in about 215 s in the world (closed by me) | `cargo test -p victory-gpu -- --test-threads=1` gives 56 passed. That includes `debug_layer_accepts_buffers_written_then_read_as_vertices`, which ran here with the debug layer and was not skipped. I had opened #1507 and #1527 for the same two errors. This PR covers more (shader writes, table views) and has a test, so I am closing mine in favour of it.
Author
Owner

@⁠HocotateGuy15 on GitHub · 2026-11-24 20:19 UTC · original

Retested on RTX 3070 / driver 610.88 / Windows 10 19045.7846 with the D3D12 debug layer and DRED enabled. I applied the GPU changes from #334 at c99e429 to the #175 Agility SDK build at 19aec59 (one bind-signature conflict resolved to preserve the older function signature). GPU unit tests: 46 passed, 1 ignored.

The baseline diagnostics log had 105 entries containing "specified by transition barrier does not". The patched run had zero. The cutscene still ran at about 1 FPS (1,732 ms/frame reported) and exited with DXGI_ERROR_DEVICE_HUNG after an 11-list submission. One incomplete DRED breadcrumb reached 708/856. There were 121 D3D12 id 622 entries for compute shaders requesting 64 lanes on the 32-lane device.

This verifies that the patch cleared the observed barrier errors on this setup. The cutscene hang remains open. Related baseline: #1096. AI-assisted test setup and log analysis.

**@⁠HocotateGuy15** on GitHub · 2026-11-24 20:19 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7143378922) Retested on RTX 3070 / driver 610.88 / Windows 10 19045.7846 with the D3D12 debug layer and DRED enabled. I applied the GPU changes from #334 at c99e429 to the #175 Agility SDK build at 19aec59 (one bind-signature conflict resolved to preserve the older function signature). GPU unit tests: 46 passed, 1 ignored. The baseline diagnostics log had 105 entries containing "specified by transition barrier does not". The patched run had zero. The cutscene still ran at about 1 FPS (1,732 ms/frame reported) and exited with DXGI_ERROR_DEVICE_HUNG after an 11-list submission. One incomplete DRED breadcrumb reached 708/856. There were 121 D3D12 id 622 entries for compute shaders requesting 64 lanes on the 32-lane device. This verifies that the patch cleared the observed barrier errors on this setup. The cutscene hang remains open. Related baseline: #1096. AI-assisted test setup and log analysis.
Author
Owner

@⁠Marvisak on GitHub · 2026-11-25 00:15 UTC · original

Automated triage for the maintainers.

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

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


Generated by Claude Code

**@⁠Marvisak** on GitHub · 2026-11-25 00:15 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7148314375) <!-- victory-triage v1 head=c99e4290b628a3842ec558e500d7d1c5a75d213f verdict=needs-rebase at=2026-11-25T00:13:20Z --> Automated triage for the maintainers. **Needs rebase.** This PR does not merge cleanly into current `main` (ac2525d). Conflicting files: `crates/victory-gpu/src/draw.rs`, `crates/victory-gpu/src/host.rs`. The content has not been reviewed yet; it will be once the branch is rebased onto `main`. --- _Generated by [Claude Code](https://claude.ai/code)_
Author
Owner

@⁠Venom2054 on GitHub · 2026-11-25 11:06 UTC · original

Follow-up on the same-command limitation in c99e429: I reproduced UAV/indirect argument aliasing with a synthetic GPU test and prepared the focused patch below.

RTX 5070 Ti 16 GB, NVIDIA 621.01, i7-14700, 32 GB RAM, Windows 11 Pro 26200. Native D3D12.

When the command being prepared declares a UAV write to the argument or count allocation, the patch copies the bounded argument bytes and optional count on the GPU into a separate DEFAULT-heap buffer. The source transitions through the existing tracker and is restored to UAV before execution. One buffer per host list is reused between commands and grown when needed; earlier allocations remain held by the tracker. Commands without that overlap retain the direct path. This preserves the write-wins rule.

Synthetic validation:

  • Before the change, the new aliasing test failed with debug-layer IDs 527 and 538. Afterward, it passes with correct readback on the RTX 5070 Ti and WARP.
  • The producer generates arguments/count on the GPU. Two indirect executions cover no count, a count in the argument allocation, a separate writable count allocation, zero count, count above the maximum, and a shader that writes only the separate count allocation. Readback checks actual work, not just error suppression.
  • Another test checks invalid copy ranges/alignment/overflow are rejected before recording and preserves the direct read-only path.
  • On an isolated source snapshot of exact PR head c99e429 plus the attached patch: 58 GPU tests passed, 0 failed, 1 ignored on WARP with the debug layer; the aliasing test also passes on hardware. GPU Clippy passes with and without diagnostics, including all targets and -D warnings.

Title evidence on my combined local stack: a 366.3-second debug-layer run, manually stopped, logged 0 ID 527 and 0 ID 538, with no logged device removal/hang. The new argument-copy path activated. An earlier adaptation of #334 without this follow-up logged 1718 ID 538 indirect-argument errors in 145.0 seconds. My preceding build without #334 logged 1508 ID 527 and 1158 ID 538 vertex-buffer errors in 345.7 seconds. These are combined-stack observations, not a controlled single-variable A/B or performance benchmark.

The new title run still has major visual corruption and poor frame times, 228 shader-translation refusal events, and other debug messages (four ID 645 capability probes and one ID 1419 sampler/root-signature issue). This is not a complete rendering or stability fix. The parent PR's untracked directly indexed views and same-command UAV/vertex/index sharing remain outside this patch.

Integration details for newer main: keep root UAVs tracked as writes, preserve the current clamp implementation, and adapt capture::read_indirect to the same tracker instead of fixed before-state barriers. In my current-main integration, capture receives the actual copied argument/count resources. The attached patch targets exactly c99e429, not a rebase onto current main; it contains only this follow-up and its synthetic tests. The larger local integration passes 757 workspace tests (0 failed, 11 ignored), 171 GPU tests with the debug layer (0 failed, 3 ignored), Clippy, build and asset policy.

Patch against c99e429 (synthetic fixtures only)
--- a/crates/victory-gpu/src/host.rs
+++ b/crates/victory-gpu/src/host.rs
@@ -378,6 +378,204 @@
             let code = code.unwrap();
             std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize())
                 .to_vec()
+        }
+    }
+
+    /// Indirect arguments and their count may share the host allocation
+    /// the dispatched shader writes. GPU-generated arguments must be read
+    /// in INDIRECT_ARGUMENT while those shader writes remain legal UAVs.
+    #[test]
+    fn indirect_arguments_can_share_a_shader_written_buffer() {
+        use windows::core::s;
+        if in_child("indirect_arguments_can_share_a_shader_written_buffer") {
+            return;
+        }
+        let mut layer: Option<ID3D12Debug> = None;
+        // SAFETY: enable validation before this child creates a device.
+        if unsafe { D3D12GetDebugInterface(&mut layer) }.is_err() {
+            eprintln!("no D3D12 debug layer; skipped");
+            return;
+        }
+        // SAFETY: no device exists in this child yet.
+        unsafe { layer.unwrap().EnableDebugLayer() };
+        let Some(host) = host() else {
+            eprintln!("no host device; skipped");
+            return;
+        };
+        let messages: ID3D12InfoQueue = host.device.cast().unwrap();
+        const SOURCE: &str = r#"
+            #define RS "RootConstants(num32BitConstants=3, b0), UAV(u0), UAV(u1)"
+            cbuffer Mode : register(b0) { uint produce; uint groups; uint count; };
+            RWByteAddressBuffer args : register(u0);
+            RWByteAddressBuffer counter : register(u1);
+            [RootSignature(RS)] [numthreads(1, 1, 1)]
+            void main() {
+                if (produce != 0) {
+                    args.Store3(64, uint3(groups, 1, 1));
+                    args.Store3(80, uint3(5, 1, 1));
+                    counter.Store(128, count);
+                } else {
+                    uint ignored;
+                    args.InterlockedAdd(0, 1, ignored);
+                    counter.InterlockedAdd(4, 1, ignored);
+                }
+            }
+            [RootSignature(RS)] [numthreads(1, 1, 1)]
+            void count_only() {
+                uint ignored;
+                counter.InterlockedAdd(4, 1, ignored);
+            }
+        "#;
+        let code = compile(SOURCE, s!("main"), s!("cs_5_1"));
+        let counter_code = compile(SOURCE, s!("count_only"), s!("cs_5_1"));
+        // SAFETY: the shader contains its root signature; live bytecode
+        // and descriptors are read synchronously during object creation.
+        let (root, pso, counter_pso, signature): (_, _, _, ID3D12CommandSignature) = unsafe {
+            let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).unwrap();
+            let pso: ID3D12PipelineState = host
+                .device
+                .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
+                    pRootSignature: std::mem::transmute_copy(&root),
+                    CS: D3D12_SHADER_BYTECODE {
+                        pShaderBytecode: code.as_ptr().cast(),
+                        BytecodeLength: code.len(),
+                    },
+                    ..Default::default()
+                })
+                .unwrap();
+            let counter_pso: ID3D12PipelineState = host
+                .device
+                .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
+                    pRootSignature: std::mem::transmute_copy(&root),
+                    CS: D3D12_SHADER_BYTECODE {
+                        pShaderBytecode: counter_code.as_ptr().cast(),
+                        BytecodeLength: counter_code.len(),
+                    },
+                    ..Default::default()
+                })
+                .unwrap();
+            let argument = D3D12_INDIRECT_ARGUMENT_DESC {
+                Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH,
+                ..Default::default()
+            };
+            let mut signature = None;
+            host.device
+                .CreateCommandSignature(
+                    &D3D12_COMMAND_SIGNATURE_DESC {
+                        ByteStride: 16,
+                        NumArgumentDescs: 1,
+                        pArgumentDescs: &argument,
+                        ..Default::default()
+                    },
+                    None::<&ID3D12RootSignature>,
+                    &mut signature,
+                )
+                .unwrap();
+            (root, pso, counter_pso, signature.unwrap())
+        };
+        // No count, an aliased count, a separate count, zero work, and a
+        // count above the maximum. Two executions also check fresh copies.
+        for (count_kind, count, expected, count_only) in [
+            (-1, 1, 17, false),
+            (0, 1, 7, false),
+            (1, 1, 7, false),
+            (1, 0, 0, false),
+            (1, 3, 17, false),
+            (1, 1, 7, true),
+        ] {
+            let (args, data) = host.shared_buffer(256).unwrap();
+            let (counter, counter_data) = if count_kind == 0 {
+                (args.clone(), data)
+            } else {
+                host.shared_buffer(256).unwrap()
+            };
+            let list = host.new_list().unwrap();
+            // SAFETY: mapped allocations, before the GPU uses them.
+            unsafe {
+                std::ptr::write_bytes(data, 0, 256);
+                std::ptr::write_bytes(counter_data, 0, 256);
+                messages.ClearStoredMessages();
+            }
+            let bind = |produce: u32, groups: u32| {
+                list.begin_command();
+                if produce != 0 || !count_only {
+                    list.buffer_state(&args, BUFFER_WRITE);
+                }
+                list.buffer_state(&counter, BUFFER_WRITE);
+                let constants = [produce, groups, count];
+                // SAFETY: open list, live pipeline and buffers.
+                unsafe {
+                    list.list.SetComputeRootSignature(&root);
+                    list.list.SetPipelineState(if produce == 0 && count_only {
+                        &counter_pso
+                    } else {
+                        &pso
+                    });
+                    list.list
+                        .SetComputeRoot32BitConstants(0, 3, constants.as_ptr().cast(), 0);
+                    list.list
+                        .SetComputeRootUnorderedAccessView(1, args.GetGPUVirtualAddress());
+                    list.list
+                        .SetComputeRootUnorderedAccessView(2, counter.GetGPUVirtualAddress());
+                }
+            };
+            for groups in [3, 4] {
+                bind(1, groups);
+                // SAFETY: producer writes the argument records on the GPU.
+                unsafe { list.list.Dispatch(1, 1, 1) };
+                assert!(crate::indirect::bound(
+                    &list,
+                    &args,
+                    // SAFETY: the argument buffer remains alive through execution.
+                    unsafe { args.GetGPUVirtualAddress() } + 64,
+                    (2, 16, 2),
+                ));
+                bind(0, 0);
+                crate::indirect::execute(
+                    &list,
+                    &signature,
+                    (16, 2),
+                    (&args, 64),
+                    (count_kind >= 0).then_some((&counter, 128)),
+                )
+                .expect("indirect execution");
+            }
+            list.close();
+            host.execute(&[&list]);
+            let mut errors = Vec::new();
+            // SAFETY: bounded message buffers; GPU work has completed
+            // before reading either mapped result.
+            unsafe {
+                for i in 0..messages.GetNumStoredMessages() {
+                    let mut size = 0;
+                    messages.GetMessage(i, None, &mut size).unwrap();
+                    let mut bytes = vec![0u64; size.div_ceil(8)];
+                    let m = bytes.as_mut_ptr().cast::<D3D12_MESSAGE>();
+                    messages.GetMessage(i, Some(m), &mut size).unwrap();
+                    if (*m).Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 {
+                        let text = std::slice::from_raw_parts(
+                            (*m).pDescription,
+                            (*m).DescriptionByteLength,
+                        );
+                        errors.push(format!(
+                            "id {}: {}",
+                            (*m).ID.0,
+                            String::from_utf8_lossy(text)
+                        ));
+                    }
+                }
+                assert!(
+                    errors.is_empty(),
+                    "count kind {count_kind}, count {count}: {errors:?}"
+                );
+                assert_eq!(
+                    data.cast::<u32>().read_volatile(),
+                    if count_only { 0 } else { expected }
+                );
+                assert_eq!(counter_data.cast::<u32>().add(1).read_volatile(), expected);
+                assert_eq!(data.cast::<u32>().add(16).read_volatile(), 4);
+                assert_eq!(counter_data.cast::<u32>().add(32).read_volatile(), count);
+            }
         }
     }
 
@@ -593,7 +791,7 @@
         let indirect = |list: &HostList| {
             assert!(crate::indirect::bound(list, &buffer, gpu + 256, (0, 16, 1)));
             bind(list);
-            crate::indirect::execute(list, &signature, 1, (&buffer, 256), None);
+            crate::indirect::execute(list, &signature, (16, 1), (&buffer, 256), None).unwrap();
         };
         // A list that draws, draws indirectly, draws; then one that starts
         // with an indirect draw, submitted together.
@@ -655,6 +853,9 @@
     states: Mutex<States>,
     /// The states of the host copies of title memory the list uses.
     buffers: Mutex<BufferStates<ID3D12Resource>>,
+    /// Reused between indirect commands; the GPU copies argument bytes
+    /// here when their original allocation must remain shader-writable.
+    indirect_copy: Mutex<Option<ID3D12Resource>>,
     /// The list that runs those transitions just before this one.
     prelude: (ID3D12CommandAllocator, ID3D12GraphicsCommandList),
     /// The pipelines the list binds, for reports of slow submissions.
@@ -706,7 +907,9 @@
 ///
 /// shortcut: buffers read only through directly indexed heaps are not
 /// tracked, and a command that both writes a buffer and reads it as
-/// vertices, indices or arguments reads them in the write state.
+/// vertices or indices reads them in the write state. Indirect arguments
+/// and counts are copied to separate storage when their command writes
+/// the original allocation.
 pub(crate) struct BufferStates<R> {
     /// First state, current state, the command that last wrote it.
     by_copy: std::collections::HashMap<usize, (u32, u32, Option<u64>, R)>,
@@ -923,6 +1126,7 @@
                 scratch: Mutex::default(),
                 states: Mutex::default(),
                 buffers: Mutex::default(),
+                indirect_copy: Mutex::default(),
                 prelude: (prelude_allocator, prelude),
                 pipelines: Mutex::default(),
                 budget: OnceLock::new(),
@@ -1409,6 +1613,67 @@
             // SAFETY: an open list and a buffer the list holds.
             unsafe { self.list.ResourceBarrier(&[barrier]) };
         }
+    }
+
+    /// Whether the command being bound writes this allocation through a UAV.
+    pub(crate) fn buffer_written_by_command(&self, buffer: &ID3D12Resource) -> bool {
+        let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
+        buffers
+            .by_copy
+            .get(&(buffer.as_raw() as usize))
+            .is_some_and(|(_, _, wrote, _)| *wrote == Some(buffers.command))
+    }
+
+    /// GPU-only storage for one indirect command's arguments and count.
+    /// Commands in this list consume their copy before the next overwrites
+    /// it. The buffer tracker keeps older allocations alive if it grows.
+    pub(crate) fn indirect_copy(&self, size: u64) -> Option<ID3D12Resource> {
+        let mut copy = self.indirect_copy.lock().unwrap_or_else(|e| e.into_inner());
+        if let Some(buffer) = &*copy
+            // SAFETY: a descriptor query on an owned, live resource.
+            && unsafe { buffer.GetDesc() }.Width >= size
+        {
+            return Some(buffer.clone());
+        }
+        let desc = D3D12_RESOURCE_DESC {
+            Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
+            Width: size.max(1).checked_next_multiple_of(64 << 10)?,
+            Height: 1,
+            DepthOrArraySize: 1,
+            MipLevels: 1,
+            SampleDesc: DXGI_SAMPLE_DESC {
+                Count: 1,
+                Quality: 0,
+            },
+            Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
+            ..Default::default()
+        };
+        let heap = D3D12_HEAP_PROPERTIES {
+            Type: D3D12_HEAP_TYPE_DEFAULT,
+            ..Default::default()
+        };
+        let mut buffer: Option<ID3D12Resource> = None;
+        // SAFETY: ordinary resource creation; descriptors and out pointer
+        // are valid through the call. Its states belong to the list tracker.
+        unsafe {
+            host()?
+                .device
+                .CreateCommittedResource(
+                    &heap,
+                    D3D12_HEAP_FLAG_NONE,
+                    &desc,
+                    D3D12_RESOURCE_STATE_COMMON,
+                    None,
+                    &mut buffer,
+                )
+                .ok()?;
+        }
+        let buffer = buffer?;
+        name(&buffer, || {
+            format!("indirect argument copy {:#x}", desc.Width)
+        });
+        *copy = Some(buffer.clone());
+        Some(buffer)
     }
 
     /// At submission: the list that moves each texture this list uses from
--- a/crates/victory-gpu/src/indirect.rs
+++ b/crates/victory-gpu/src/indirect.rs
@@ -176,6 +176,80 @@
     true
 }
 
+/// The actual argument bytes consumed by an execution, also used by
+/// diagnostics. A command may have written the original allocation again.
+pub(crate) struct Arguments {
+    pub(crate) args: (ID3D12Resource, u64),
+    pub(crate) counter: Option<(ID3D12Resource, u64)>,
+}
+
+/// A shader UAV and indirect arguments cannot use the same allocation in
+/// one command. Copy just the bounded argument range and optional count on
+/// the GPU, then restore the original UAVs before the command executes.
+fn arguments(
+    list: &HostList,
+    (stride, max): (u32, u32),
+    (args, offset): (&ID3D12Resource, u64),
+    counter: Option<(&ID3D12Resource, u64)>,
+) -> Option<Arguments> {
+    let write_args = list.buffer_written_by_command(args);
+    let write_count = counter.is_some_and(|(c, _)| list.buffer_written_by_command(c));
+    if !write_args && !write_count {
+        return Some(Arguments {
+            args: (args.clone(), offset),
+            counter: counter.map(|(c, at)| (c.clone(), at)),
+        });
+    }
+    let len = u64::from(stride) * u64::from(max.max(1));
+    let fits = |buffer: &ID3D12Resource, at: u64, bytes: u64| {
+        // SAFETY: a descriptor query on a resource the caller keeps alive.
+        let desc = unsafe { buffer.GetDesc() };
+        at.is_multiple_of(4) && at.checked_add(bytes).is_some_and(|end| end <= desc.Width)
+    };
+    if stride == 0
+        || !stride.is_multiple_of(4)
+        || !fits(args, offset, len)
+        || counter.is_some_and(|(c, at)| !fits(c, at, 4))
+    {
+        return None;
+    }
+    let copy = list.indirect_copy(len.checked_add(if counter.is_some() { 4 } else { 0 })?)?;
+    // This copy is a separate command from the shader use being prepared,
+    // so it can leave UAV even when that use just declared the same buffer.
+    list.begin_command();
+    list.buffer_state(args, BUFFER_READ);
+    if let Some((c, _)) = counter {
+        list.buffer_state(c, BUFFER_READ);
+    }
+    list.buffer_state(&copy, D3D12_RESOURCE_STATE_COPY_DEST.0 as u32);
+    // SAFETY: checked source ranges and a separate, sufficiently large
+    // destination. Transitions order earlier shader writes before copying.
+    unsafe {
+        list.list.CopyBufferRegion(&copy, 0, args, offset, len);
+        if let Some((c, at)) = counter {
+            list.list.CopyBufferRegion(&copy, len, c, at, 4);
+        }
+    }
+    list.buffer_state(&copy, BUFFER_READ);
+    if write_args {
+        list.buffer_state(args, BUFFER_WRITE);
+    }
+    if write_count {
+        list.buffer_state(counter.unwrap().0, BUFFER_WRITE);
+    }
+    #[cfg(feature = "diagnostics")]
+    {
+        static ONCE: std::sync::Once = std::sync::Once::new();
+        ONCE.call_once(|| {
+            tracing::info!("Indirect arguments copied away from a shader-written host buffer")
+        });
+    }
+    Some(Arguments {
+        args: (copy.clone(), 0),
+        counter: counter.map(|_| (copy, len)),
+    })
+}
+
 /// Runs `max` records of `signature` from `args` (a host copy of title
 /// memory) at `offset`, with their count at `counter` if there is one: both
 /// read as arguments, after whatever wrote them (the clamp, or the draw's
@@ -183,10 +257,13 @@
 pub(crate) fn execute(
     list: &HostList,
     signature: &ID3D12CommandSignature,
-    max: u32,
+    (stride, max): (u32, u32),
     (args, offset): (&ID3D12Resource, u64),
     counter: Option<(&ID3D12Resource, u64)>,
-) {
+) -> Option<Arguments> {
+    let prepared = arguments(list, (stride, max), (args, offset), counter)?;
+    let (args, offset) = (&prepared.args.0, prepared.args.1);
+    let counter = prepared.counter.as_ref().map(|(c, at)| (c, *at));
     list.buffer_state(args, BUFFER_READ);
     if let Some((c, _)) = counter {
         list.buffer_state(c, BUFFER_READ);
@@ -203,6 +280,7 @@
             counter.map_or(0, |(_, at)| at),
         )
     };
+    Some(prepared)
 }
 
 fn uav_barrier() -> D3D12_RESOURCE_BARRIER {
@@ -217,6 +295,44 @@
 
 #[cfg(test)]
 mod tests {
+    /// Invalid source ranges must not record copies or disturb the pending
+    /// shader-write declaration. Read-only arguments keep their original
+    /// resource and offset; copies are needed only for a simultaneous UAV.
+    #[test]
+    fn argument_snapshots_validate_ranges_before_recording() {
+        use super::*;
+        let Some(host) = host() else { return };
+        let (buffer, _) = host.shared_buffer(256).unwrap();
+        let list = host.new_list().unwrap();
+        list.begin_command();
+        let direct = arguments(&list, (16, 2), (&buffer, 64), None).unwrap();
+        assert_eq!(direct.args, (buffer.clone(), 64));
+        list.buffer_state(&buffer, BUFFER_WRITE);
+        for (stride, max, at, count) in [
+            (0, 1, 64, None),
+            (6, 1, 64, None),
+            (16, 2, 240, None),
+            (16, 1, u64::MAX - 3, None),
+            (16, 1, 65, None),
+            (16, 1, 64, Some(253)),
+            (16, 1, 64, Some(256)),
+            (16, u32::MAX, 64, None),
+        ] {
+            assert!(
+                arguments(
+                    &list,
+                    (stride, max),
+                    (&buffer, at),
+                    count.map(|at| (&buffer, at))
+                )
+                .is_none()
+            );
+            assert!(list.buffer_written_by_command(&buffer));
+        }
+        list.close();
+        host.execute(&[&list]);
+    }
+
     /// The clamp compiles with the system's compiler and the host takes it.
     #[test]
     fn argument_clamp_builds() {
--- a/crates/victory-gpu/src/draw.rs
+++ b/crates/victory-gpu/src/draw.rs
@@ -1044,13 +1044,16 @@
         list.note_op(|| {
             self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH)
         });
-        crate::indirect::execute(
+        if crate::indirect::execute(
             list,
             &signature,
-            max,
+            (stride, max),
             (&args.buffer, args.offset(arguments)),
             counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))),
-        );
+        ).is_none() {
+            why("could not copy aliased indirect arguments");
+            return false;
+        }
         if kind == DISPATCH {
             DISPATCHED.fetch_add(1, Ordering::Relaxed);
         } else {

Prepared and validated with OpenAI Codex. No game assets, captured shaders, screenshots, raw logs or private paths are included. Feel free to incorporate the fix and tests into this PR.
mi

**@⁠Venom2054** on GitHub · 2026-11-25 11:06 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7160592454) Follow-up on the same-command limitation in `c99e429`: I reproduced UAV/indirect argument aliasing with a synthetic GPU test and prepared the focused patch below. RTX 5070 Ti 16 GB, NVIDIA 621.01, i7-14700, 32 GB RAM, Windows 11 Pro 26200. Native D3D12. When the command being prepared declares a UAV write to the argument or count allocation, the patch copies the bounded argument bytes and optional count on the GPU into a separate DEFAULT-heap buffer. The source transitions through the existing tracker and is restored to UAV before execution. One buffer per host list is reused between commands and grown when needed; earlier allocations remain held by the tracker. Commands without that overlap retain the direct path. This preserves the write-wins rule. Synthetic validation: - Before the change, the new aliasing test failed with debug-layer IDs 527 and 538. Afterward, it passes with correct readback on the RTX 5070 Ti and WARP. - The producer generates arguments/count on the GPU. Two indirect executions cover no count, a count in the argument allocation, a separate writable count allocation, zero count, count above the maximum, and a shader that writes only the separate count allocation. Readback checks actual work, not just error suppression. - Another test checks invalid copy ranges/alignment/overflow are rejected before recording and preserves the direct read-only path. - On an isolated source snapshot of exact PR head `c99e429` plus the attached patch: **58 GPU tests passed, 0 failed, 1 ignored** on WARP with the debug layer; the aliasing test also passes on hardware. GPU Clippy passes with and without diagnostics, including all targets and `-D warnings`. Title evidence on my combined local stack: a **366.3-second debug-layer run**, manually stopped, logged **0 ID 527 and 0 ID 538**, with no logged device removal/hang. The new argument-copy path activated. An earlier adaptation of #334 without this follow-up logged 1718 ID 538 indirect-argument errors in 145.0 seconds. My preceding build without #334 logged 1508 ID 527 and 1158 ID 538 vertex-buffer errors in 345.7 seconds. These are combined-stack observations, not a controlled single-variable A/B or performance benchmark. The new title run still has major visual corruption and poor frame times, 228 shader-translation refusal events, and other debug messages (four ID 645 capability probes and one ID 1419 sampler/root-signature issue). This is not a complete rendering or stability fix. The parent PR's untracked directly indexed views and same-command UAV/vertex/index sharing remain outside this patch. Integration details for newer main: keep root UAVs tracked as writes, preserve the current clamp implementation, and adapt `capture::read_indirect` to the same tracker instead of fixed before-state barriers. In my current-main integration, capture receives the actual copied argument/count resources. The attached patch targets **exactly `c99e429`**, not a rebase onto current main; it contains only this follow-up and its synthetic tests. The larger local integration passes 757 workspace tests (0 failed, 11 ignored), 171 GPU tests with the debug layer (0 failed, 3 ignored), Clippy, build and asset policy. <details> <summary>Patch against c99e429 (synthetic fixtures only)</summary> ```diff --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -378,6 +378,204 @@ let code = code.unwrap(); std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()) .to_vec() + } + } + + /// Indirect arguments and their count may share the host allocation + /// the dispatched shader writes. GPU-generated arguments must be read + /// in INDIRECT_ARGUMENT while those shader writes remain legal UAVs. + #[test] + fn indirect_arguments_can_share_a_shader_written_buffer() { + use windows::core::s; + if in_child("indirect_arguments_can_share_a_shader_written_buffer") { + return; + } + let mut layer: Option<ID3D12Debug> = None; + // SAFETY: enable validation before this child creates a device. + if unsafe { D3D12GetDebugInterface(&mut layer) }.is_err() { + eprintln!("no D3D12 debug layer; skipped"); + return; + } + // SAFETY: no device exists in this child yet. + unsafe { layer.unwrap().EnableDebugLayer() }; + let Some(host) = host() else { + eprintln!("no host device; skipped"); + return; + }; + let messages: ID3D12InfoQueue = host.device.cast().unwrap(); + const SOURCE: &str = r#" + #define RS "RootConstants(num32BitConstants=3, b0), UAV(u0), UAV(u1)" + cbuffer Mode : register(b0) { uint produce; uint groups; uint count; }; + RWByteAddressBuffer args : register(u0); + RWByteAddressBuffer counter : register(u1); + [RootSignature(RS)] [numthreads(1, 1, 1)] + void main() { + if (produce != 0) { + args.Store3(64, uint3(groups, 1, 1)); + args.Store3(80, uint3(5, 1, 1)); + counter.Store(128, count); + } else { + uint ignored; + args.InterlockedAdd(0, 1, ignored); + counter.InterlockedAdd(4, 1, ignored); + } + } + [RootSignature(RS)] [numthreads(1, 1, 1)] + void count_only() { + uint ignored; + counter.InterlockedAdd(4, 1, ignored); + } + "#; + let code = compile(SOURCE, s!("main"), s!("cs_5_1")); + let counter_code = compile(SOURCE, s!("count_only"), s!("cs_5_1")); + // SAFETY: the shader contains its root signature; live bytecode + // and descriptors are read synchronously during object creation. + let (root, pso, counter_pso, signature): (_, _, _, ID3D12CommandSignature) = unsafe { + let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).unwrap(); + let pso: ID3D12PipelineState = host + .device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: code.as_ptr().cast(), + BytecodeLength: code.len(), + }, + ..Default::default() + }) + .unwrap(); + let counter_pso: ID3D12PipelineState = host + .device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: counter_code.as_ptr().cast(), + BytecodeLength: counter_code.len(), + }, + ..Default::default() + }) + .unwrap(); + let argument = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, + ..Default::default() + }; + let mut signature = None; + host.device + .CreateCommandSignature( + &D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: 16, + NumArgumentDescs: 1, + pArgumentDescs: &argument, + ..Default::default() + }, + None::<&ID3D12RootSignature>, + &mut signature, + ) + .unwrap(); + (root, pso, counter_pso, signature.unwrap()) + }; + // No count, an aliased count, a separate count, zero work, and a + // count above the maximum. Two executions also check fresh copies. + for (count_kind, count, expected, count_only) in [ + (-1, 1, 17, false), + (0, 1, 7, false), + (1, 1, 7, false), + (1, 0, 0, false), + (1, 3, 17, false), + (1, 1, 7, true), + ] { + let (args, data) = host.shared_buffer(256).unwrap(); + let (counter, counter_data) = if count_kind == 0 { + (args.clone(), data) + } else { + host.shared_buffer(256).unwrap() + }; + let list = host.new_list().unwrap(); + // SAFETY: mapped allocations, before the GPU uses them. + unsafe { + std::ptr::write_bytes(data, 0, 256); + std::ptr::write_bytes(counter_data, 0, 256); + messages.ClearStoredMessages(); + } + let bind = |produce: u32, groups: u32| { + list.begin_command(); + if produce != 0 || !count_only { + list.buffer_state(&args, BUFFER_WRITE); + } + list.buffer_state(&counter, BUFFER_WRITE); + let constants = [produce, groups, count]; + // SAFETY: open list, live pipeline and buffers. + unsafe { + list.list.SetComputeRootSignature(&root); + list.list.SetPipelineState(if produce == 0 && count_only { + &counter_pso + } else { + &pso + }); + list.list + .SetComputeRoot32BitConstants(0, 3, constants.as_ptr().cast(), 0); + list.list + .SetComputeRootUnorderedAccessView(1, args.GetGPUVirtualAddress()); + list.list + .SetComputeRootUnorderedAccessView(2, counter.GetGPUVirtualAddress()); + } + }; + for groups in [3, 4] { + bind(1, groups); + // SAFETY: producer writes the argument records on the GPU. + unsafe { list.list.Dispatch(1, 1, 1) }; + assert!(crate::indirect::bound( + &list, + &args, + // SAFETY: the argument buffer remains alive through execution. + unsafe { args.GetGPUVirtualAddress() } + 64, + (2, 16, 2), + )); + bind(0, 0); + crate::indirect::execute( + &list, + &signature, + (16, 2), + (&args, 64), + (count_kind >= 0).then_some((&counter, 128)), + ) + .expect("indirect execution"); + } + list.close(); + host.execute(&[&list]); + let mut errors = Vec::new(); + // SAFETY: bounded message buffers; GPU work has completed + // before reading either mapped result. + unsafe { + for i in 0..messages.GetNumStoredMessages() { + let mut size = 0; + messages.GetMessage(i, None, &mut size).unwrap(); + let mut bytes = vec![0u64; size.div_ceil(8)]; + let m = bytes.as_mut_ptr().cast::<D3D12_MESSAGE>(); + messages.GetMessage(i, Some(m), &mut size).unwrap(); + if (*m).Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 { + let text = std::slice::from_raw_parts( + (*m).pDescription, + (*m).DescriptionByteLength, + ); + errors.push(format!( + "id {}: {}", + (*m).ID.0, + String::from_utf8_lossy(text) + )); + } + } + assert!( + errors.is_empty(), + "count kind {count_kind}, count {count}: {errors:?}" + ); + assert_eq!( + data.cast::<u32>().read_volatile(), + if count_only { 0 } else { expected } + ); + assert_eq!(counter_data.cast::<u32>().add(1).read_volatile(), expected); + assert_eq!(data.cast::<u32>().add(16).read_volatile(), 4); + assert_eq!(counter_data.cast::<u32>().add(32).read_volatile(), count); + } } } @@ -593,7 +791,7 @@ let indirect = |list: &HostList| { assert!(crate::indirect::bound(list, &buffer, gpu + 256, (0, 16, 1))); bind(list); - crate::indirect::execute(list, &signature, 1, (&buffer, 256), None); + crate::indirect::execute(list, &signature, (16, 1), (&buffer, 256), None).unwrap(); }; // A list that draws, draws indirectly, draws; then one that starts // with an indirect draw, submitted together. @@ -655,6 +853,9 @@ states: Mutex<States>, /// The states of the host copies of title memory the list uses. buffers: Mutex<BufferStates<ID3D12Resource>>, + /// Reused between indirect commands; the GPU copies argument bytes + /// here when their original allocation must remain shader-writable. + indirect_copy: Mutex<Option<ID3D12Resource>>, /// The list that runs those transitions just before this one. prelude: (ID3D12CommandAllocator, ID3D12GraphicsCommandList), /// The pipelines the list binds, for reports of slow submissions. @@ -706,7 +907,9 @@ /// /// shortcut: buffers read only through directly indexed heaps are not /// tracked, and a command that both writes a buffer and reads it as -/// vertices, indices or arguments reads them in the write state. +/// vertices or indices reads them in the write state. Indirect arguments +/// and counts are copied to separate storage when their command writes +/// the original allocation. pub(crate) struct BufferStates<R> { /// First state, current state, the command that last wrote it. by_copy: std::collections::HashMap<usize, (u32, u32, Option<u64>, R)>, @@ -923,6 +1126,7 @@ scratch: Mutex::default(), states: Mutex::default(), buffers: Mutex::default(), + indirect_copy: Mutex::default(), prelude: (prelude_allocator, prelude), pipelines: Mutex::default(), budget: OnceLock::new(), @@ -1409,6 +1613,67 @@ // SAFETY: an open list and a buffer the list holds. unsafe { self.list.ResourceBarrier(&[barrier]) }; } + } + + /// Whether the command being bound writes this allocation through a UAV. + pub(crate) fn buffer_written_by_command(&self, buffer: &ID3D12Resource) -> bool { + let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner()); + buffers + .by_copy + .get(&(buffer.as_raw() as usize)) + .is_some_and(|(_, _, wrote, _)| *wrote == Some(buffers.command)) + } + + /// GPU-only storage for one indirect command's arguments and count. + /// Commands in this list consume their copy before the next overwrites + /// it. The buffer tracker keeps older allocations alive if it grows. + pub(crate) fn indirect_copy(&self, size: u64) -> Option<ID3D12Resource> { + let mut copy = self.indirect_copy.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(buffer) = &*copy + // SAFETY: a descriptor query on an owned, live resource. + && unsafe { buffer.GetDesc() }.Width >= size + { + return Some(buffer.clone()); + } + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1).checked_next_multiple_of(64 << 10)?, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let mut buffer: Option<ID3D12Resource> = None; + // SAFETY: ordinary resource creation; descriptors and out pointer + // are valid through the call. Its states belong to the list tracker. + unsafe { + host()? + .device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + .ok()?; + } + let buffer = buffer?; + name(&buffer, || { + format!("indirect argument copy {:#x}", desc.Width) + }); + *copy = Some(buffer.clone()); + Some(buffer) } /// At submission: the list that moves each texture this list uses from --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -176,6 +176,80 @@ true } +/// The actual argument bytes consumed by an execution, also used by +/// diagnostics. A command may have written the original allocation again. +pub(crate) struct Arguments { + pub(crate) args: (ID3D12Resource, u64), + pub(crate) counter: Option<(ID3D12Resource, u64)>, +} + +/// A shader UAV and indirect arguments cannot use the same allocation in +/// one command. Copy just the bounded argument range and optional count on +/// the GPU, then restore the original UAVs before the command executes. +fn arguments( + list: &HostList, + (stride, max): (u32, u32), + (args, offset): (&ID3D12Resource, u64), + counter: Option<(&ID3D12Resource, u64)>, +) -> Option<Arguments> { + let write_args = list.buffer_written_by_command(args); + let write_count = counter.is_some_and(|(c, _)| list.buffer_written_by_command(c)); + if !write_args && !write_count { + return Some(Arguments { + args: (args.clone(), offset), + counter: counter.map(|(c, at)| (c.clone(), at)), + }); + } + let len = u64::from(stride) * u64::from(max.max(1)); + let fits = |buffer: &ID3D12Resource, at: u64, bytes: u64| { + // SAFETY: a descriptor query on a resource the caller keeps alive. + let desc = unsafe { buffer.GetDesc() }; + at.is_multiple_of(4) && at.checked_add(bytes).is_some_and(|end| end <= desc.Width) + }; + if stride == 0 + || !stride.is_multiple_of(4) + || !fits(args, offset, len) + || counter.is_some_and(|(c, at)| !fits(c, at, 4)) + { + return None; + } + let copy = list.indirect_copy(len.checked_add(if counter.is_some() { 4 } else { 0 })?)?; + // This copy is a separate command from the shader use being prepared, + // so it can leave UAV even when that use just declared the same buffer. + list.begin_command(); + list.buffer_state(args, BUFFER_READ); + if let Some((c, _)) = counter { + list.buffer_state(c, BUFFER_READ); + } + list.buffer_state(&copy, D3D12_RESOURCE_STATE_COPY_DEST.0 as u32); + // SAFETY: checked source ranges and a separate, sufficiently large + // destination. Transitions order earlier shader writes before copying. + unsafe { + list.list.CopyBufferRegion(&copy, 0, args, offset, len); + if let Some((c, at)) = counter { + list.list.CopyBufferRegion(&copy, len, c, at, 4); + } + } + list.buffer_state(&copy, BUFFER_READ); + if write_args { + list.buffer_state(args, BUFFER_WRITE); + } + if write_count { + list.buffer_state(counter.unwrap().0, BUFFER_WRITE); + } + #[cfg(feature = "diagnostics")] + { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::info!("Indirect arguments copied away from a shader-written host buffer") + }); + } + Some(Arguments { + args: (copy.clone(), 0), + counter: counter.map(|_| (copy, len)), + }) +} + /// Runs `max` records of `signature` from `args` (a host copy of title /// memory) at `offset`, with their count at `counter` if there is one: both /// read as arguments, after whatever wrote them (the clamp, or the draw's @@ -183,10 +257,13 @@ pub(crate) fn execute( list: &HostList, signature: &ID3D12CommandSignature, - max: u32, + (stride, max): (u32, u32), (args, offset): (&ID3D12Resource, u64), counter: Option<(&ID3D12Resource, u64)>, -) { +) -> Option<Arguments> { + let prepared = arguments(list, (stride, max), (args, offset), counter)?; + let (args, offset) = (&prepared.args.0, prepared.args.1); + let counter = prepared.counter.as_ref().map(|(c, at)| (c, *at)); list.buffer_state(args, BUFFER_READ); if let Some((c, _)) = counter { list.buffer_state(c, BUFFER_READ); @@ -203,6 +280,7 @@ counter.map_or(0, |(_, at)| at), ) }; + Some(prepared) } fn uav_barrier() -> D3D12_RESOURCE_BARRIER { @@ -217,6 +295,44 @@ #[cfg(test)] mod tests { + /// Invalid source ranges must not record copies or disturb the pending + /// shader-write declaration. Read-only arguments keep their original + /// resource and offset; copies are needed only for a simultaneous UAV. + #[test] + fn argument_snapshots_validate_ranges_before_recording() { + use super::*; + let Some(host) = host() else { return }; + let (buffer, _) = host.shared_buffer(256).unwrap(); + let list = host.new_list().unwrap(); + list.begin_command(); + let direct = arguments(&list, (16, 2), (&buffer, 64), None).unwrap(); + assert_eq!(direct.args, (buffer.clone(), 64)); + list.buffer_state(&buffer, BUFFER_WRITE); + for (stride, max, at, count) in [ + (0, 1, 64, None), + (6, 1, 64, None), + (16, 2, 240, None), + (16, 1, u64::MAX - 3, None), + (16, 1, 65, None), + (16, 1, 64, Some(253)), + (16, 1, 64, Some(256)), + (16, u32::MAX, 64, None), + ] { + assert!( + arguments( + &list, + (stride, max), + (&buffer, at), + count.map(|at| (&buffer, at)) + ) + .is_none() + ); + assert!(list.buffer_written_by_command(&buffer)); + } + list.close(); + host.execute(&[&list]); + } + /// The clamp compiles with the system's compiler and the host takes it. #[test] fn argument_clamp_builds() { --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1044,13 +1044,16 @@ list.note_op(|| { self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH) }); - crate::indirect::execute( + if crate::indirect::execute( list, &signature, - max, + (stride, max), (&args.buffer, args.offset(arguments)), counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))), - ); + ).is_none() { + why("could not copy aliased indirect arguments"); + return false; + } if kind == DISPATCH { DISPATCHED.fetch_add(1, Ordering::Relaxed); } else { ``` </details> Prepared and validated with OpenAI Codex. No game assets, captured shaders, screenshots, raw logs or private paths are included. Feel free to incorporate the fix and tests into this PR. mi
Author
Owner

@⁠realhenners on GitHub · 2026-11-25 23:18 UTC · original

Closing this in favour of 315cea1 on main, which fixes the same two errors from #199 / #264 by a different route: the clamp now writes into the list's own argument buffer, so the title's 174 MB heap is never explicitly moved to UNORDERED_ACCESS, and title copies stay in COMMON, promoted by each use and ordered by UAV barriers. Rebasing this PR's per-list tracker on top would cut across that design.

Thanks to everyone who tested it in the title. Across NVIDIA and AMD runs it took ids 527/538 to 0, which helped pin down the cause.

If a driver or GPU-based validation ever objects to the promotion shortcut noted in indirect.rs (a buffer written through a UAV and then read by the input assembler in the same submission), the tracker here (state per list, a prelude from COMMON, back to COMMON before close, writes winning within a command) is the "per-list tracked buffer states" that note mentions, and I'm happy to bring it back on top of current main. The old head stays on my fork at c99e429.

**@⁠realhenners** on GitHub · 2026-11-25 23:18 UTC · [original](https://github.com/Marvisak/VIctory/pull/334#issuecomment-7177385862) Closing this in favour of 315cea1 on `main`, which fixes the same two errors from #199 / #264 by a different route: the clamp now writes into the list's own argument buffer, so the title's 174 MB heap is never explicitly moved to `UNORDERED_ACCESS`, and title copies stay in `COMMON`, promoted by each use and ordered by UAV barriers. Rebasing this PR's per-list tracker on top would cut across that design. Thanks to everyone who tested it in the title. Across NVIDIA and AMD runs it took ids 527/538 to 0, which helped pin down the cause. If a driver or GPU-based validation ever objects to the promotion shortcut noted in `indirect.rs` (a buffer written through a UAV and then read by the input assembler in the same submission), the tracker here (state per list, a prelude from `COMMON`, back to `COMMON` before close, writes winning within a command) is the "per-list tracked buffer states" that note mentions, and I'm happy to bring it back on top of current `main`. The old head stays on my fork at `c99e429`.

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!334
No description provided.