Skip to content

Runtime: keep a resource released while a queue holds work until that work is submitted (D3D-203) - #4557

Open
requiemsnkrp wants to merge 1 commit into
ItsNotRexed:mainfrom
requiemsnkrp:d3d-203-queue-retire
Open

requiemsnkrp wants to merge 1 commit into
ItsNotRexed:mainfrom
requiemsnkrp:d3d-203-queue-retire

Conversation

@requiemsnkrp

Copy link
Copy Markdown

What and why

D3D-203 (claim). The out-of-order case the item names is already handled on main by @kovaaper's #1654: each submission takes a device-wide ticket on its own queue's timeline and only the completed prefix retires (retire_tickets_test covers "A gated, B finishes first"). One hole remained: work a queue holds on the CPU (Wait-before-Signal, queue_holds.h, whose docs already said "D3D-203"). A held batch has no ticket yet and names resources by COM pointer, looked up only at replay.

Failure on main (reproduced): queue A Wait(F,1) (F signalled by the CPU later), then ExecuteCommandLists reading R → held. Queue B submits and completes. Release(R) → remove_resource at once; R's image and memory go after B's next completed submission. The CPU signals F; A's batch can't find R: [rt] d3d12: a held ExecuteCommandLists failed when it was released (result 2); nothing was submitted. With a new resource at the same address, the batch would use that one instead.

Change

  • queue_holds.h: each held operation gets a sequence number (held_added / held_removed); after_held(release) parks a release until every operation held at that moment, on any queue, is submitted or dropped (later holds don't delay it); run_released() runs ready releases with no queue lock held (end of pump_ready(), ~VulkanQueue). Nothing held: one atomic load; no per-command work or allocation.
  • vulkan_backend.h: an operation is marked done only after run(), so its ticket exists first (also on fence release / queue destruction). DeferredDeletionQueue::size(), VulkanContext::deferred_destructions() for tests.
  • d3d12_com_object.h: Object::Release calls Derived::final_release (default: delete).
  • d3d12_vulkan_device.cpp: Resource::final_release parks the whole object (ID, registration, Vulkan objects all stay valid — a held batch also reaches resources through descriptors and must not see a reused address); ~Resource then runs unchanged and its objects get tickets after the held submissions. Dropped held work (queue destroyed, fence released, device lost) releases its parked resources; a parked resource keeps its device reference, so shutdown still drains normally.
  • Test hook rt::d3d12::deferred_destruction(device) → {kept, waiting}. Docs: docs/d3d12_vulkan.md §4.4 "Deferred destruction across queues" replaces the "not pinned, D3D-203" note.

Tested (NVIDIA GeForce RTX 3060, Windows 11, MSVC 19.51, Vulkan SDK 1.4.363.0, LEONIDA_VK_VALIDATION=1 + sync validation)

New released_while_held in d3d12_queue_handover_test (A = DIRECT gated by a CPU-signalled Wait, B = COPY); readback matches byte for byte:

released while held, after 4 completed submissions on queue B: kept 2, waiting 0
CPU Signal (held batch submitted): kept 0, waiting 2
after the held batch completed and 2 more submissions on queue B: kept 0, waiting 0
Vulkan layer: 372 cases passed, every one exact
Host D3D12 (NVIDIA GeForce RTX 3060): 369 cases passed, every one exact
  • Negative control (parking replaced by an immediate delete, i.e. main's behaviour): kept 0, waiting 0, the check fails, stderr shows the "held ExecuteCommandLists failed" line above.
  • The never-signalled-fence and released-fence cases now also check that a resource only the dropped batch names is kept, then destroyed with it. New CPU test queue_holds_test: removal in any order across queues, later holds ignored, each release runs once.
  • 0 validation errors here and in 68 queue/fence/vk_/d3d12_ tests run under validation. Full ctest (no window tests): 142/142 vs 141/141 on main 03b09a0 (the new queue_holds).
  • Runtime: bindless flushes replace the set instead of waiting for the device (D3D-314) #2756 (D3D-314, mine): ticket semantics unchanged, no new conflict (git merge-tree).

Open (not in this PR)

  • A default-heap buffer's arena range returns to the allocator when the resource is destroyed; the next buffer placed there is zero-filled by the CPU, possibly while the GPU still uses it (single queue too, predates this).
  • Heaps, PSOs and query heaps are destroyed immediately (as D3D12 lets the layer require).
  • While held work exists, a release waits for every queue's held operations, so a fence nobody signals keeps such resources until its queue is destroyed (documented).

No game files. AI-assisted (Claude).

…submitted (D3D-203)

Since ItsNotRexed#1654 the deletion queue retires a released resource's Vulkan objects on the completed prefix of
device-wide submission tickets, so queues that complete out of submission order no longer free early. Work a
queue holds on the CPU (Wait-before-Signal, queue_holds.h) has no ticket and names resources by ID, resolved
when it is replayed: a resource released after B's later work completed was destroyed (and unregistered at
once), and the held batch then failed with result 2 (unresolved resource), or resolved a reused address.

- queue_holds.h: every held operation takes a place (held_added / held_removed, replacing held_changed);
  after_held() parks a release until every operation held at that moment, on any queue, has run or been
  dropped (later holds do not delay it); run_released() runs ready releases with no queue lock held, at the
  end of pump_ready() and from ~VulkanQueue. One atomic load when nothing is held.
- vulkan_backend.h: VulkanQueue gives each Deferred op its place, returns it after run() (so the submission is
  recorded first), on fence release and at teardown; DeferredDeletionQueue::size() and
  VulkanContext::deferred_destructions() for tests.
- d3d12_com_object.h: Object::Release calls Derived::final_release (default: delete). Resource::final_release
  parks the whole object through after_held(), so its ID, binding and Vulkan objects stay; ~Resource then runs
  as before and its objects take tickets after the held submissions.
- d3d12_com.h / d3d12_vulkan_device.cpp: rt::d3d12::deferred_destruction(device) {kept, waiting} for tests.
- queue_holds_test (CPU): out-of-order removal across queues, later holds ignored, runs once.
- d3d12_queue_handover_test: queue A holds stage[0] -> readback behind a CPU-signalled Wait, queue B's later
  work completes four times, stage[0] is released in between: kept 2, waiting 0; the CPU Signal submits A's
  batch (kept 0, waiting 2), the readback is exact, two more B rounds destroy the objects (0/0). The
  never-signalled and released-fence cases check a resource only the dropped batch names is kept, then
  destroyed with it. With the parking disabled the case finds both destroyed before the Signal and the batch
  fails with result 2. RTX 3060 / 617.14, LEONIDA_VK_VALIDATION=1 (sync validation): 372 layer cases, 0 errors.
- docs/d3d12_vulkan.md 4.4: deferred destruction across queues, what is still not covered.

AI-assisted.

@Kam471 Kam471 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Built and ran both tests at bd1d2b53 on Windows 11, RTX 5070 Ti: exit 0 for both.

  • d3d12_queue_handover_test: Vulkan layer 372 cases passed, every one exact; Host D3D12 (NVIDIA GeForce RTX 5070 Ti) 369 cases passed, every one exact. The held-resource scenarios report released while held, after 4 completed submissions on queue B: kept 2, waiting 0, then CPU Signal (held batch submitted): kept 0, waiting 2, then kept 0, waiting 0 after the batch completes. A never-signaled fence is held, does not affect other queues, and destroys without a hang (with the diagnostic naming the waiter).
  • queue_holds_test: releases waited for the operations held before them, in any completion order, and ran once.

git diff --check clean.

@justr4mzi

Copy link
Copy Markdown
Contributor

Verified bd1d2b53 on Windows 11 25H2 + AMD Radeon RX 6700 XT (gfx1031, Adrenalin 26.11.2, Vulkan 1.4.315, MSVC 19.44.35230.0 RelWithDebInfo).

Hardware & validation results (LEONIDA_VK_VALIDATION=1)

  • Built [15/15] (retire_tickets_test, queue_holds_test, d3d12_queue_handover_test) with 0 compiler warnings.
  • ctest -R "queue_holds|d3d12_queue_handover|retire_tickets" --output-on-failure:
    • Standard: 3/3 passed (8.14 s: retire_tickets 0.03s, queue_holds 0.03s, d3d12_queue_handover 7.91s).
    • LEONIDA_VK_VALIDATION=1 + VK_LAYER_KHRONOS_validation: 3/3 passed (7.65 s).
  • Direct queue_holds_test.exe: releases waited for the operations held before them, in any completion order, and ran once (rc=0).
  • Direct d3d12_queue_handover_test.exe (LEONIDA_VK_VALIDATION=1, 0 validation errors, rc=0):
    • released while held, after 4 completed submissions on queue B: kept 2, waiting 0
    • CPU Signal (held batch submitted): kept 0, waiting 2
    • after the held batch completed and 2 more submissions on queue B: kept 0, waiting 0
    • Vulkan layer: 372 cases passed, every one exact
    • Host D3D12 (AMD Radeon RX 6700 XT): 369 cases passed, every one exact

Code, docs & hygiene checks

  • Audited runtime/src/queue_holds.h and runtime/src/vulkan_backend.h: held_removed(op.place) runs after run(op), run_released() executes only outside pump_mutex_ / queue state_mutex_ (in_pump() resets beforehand), and detach() triggers pump_ready() even when ~VulkanQueue dropped its held entries.
  • All 7 tests/test_docs_*.py suites: 7/7 passed; python -I scripts/check_no_game_data.py (rc=0); git diff --check clean.

AI-assisted (Gemini, Antigravity).

@Kam471 Kam471 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Coordination note: #4570 (queue_holds_release_test) also edits runtime/src/queue_holds.h and the same execute_lists/Signal paths in runtime/src/vulkan_backend.h. It fixes the pending()-then-hold() window against remove_fence, which is complementary to this PR's place accounting, but the two overlap textually. Whichever lands first, the other needs a rebase and a fresh run; #4570 was verified independently at 299c98f1 (queue_holds_release_test passes).

@pwu2775-dev

Copy link
Copy Markdown
Contributor

Tested bd1d2b5 on NVIDIA GeForce RTX 4070 (driver 617.42), Windows 11 (26300), MSVC 19.44, scripts/build_runtime.ps1 (Ninja), RelWithDebInfo: pass. ctest 155/155 (GameInput disabled, no SDL3), including the new d3d12_queue_handover and queue_holds tests.

I also read queue_holds.h: held_added, held_removed and after_held take their snapshot and do the outstanding_.empty() check under the same mutex_, so the "operations held at that moment" set is consistent. No review points beyond that.

AI-assisted: read together with Codex (gpt-6.1-terra); I checked the snapshot logic against the code.

@Exopus-0x65f7ad0

Copy link
Copy Markdown
Contributor

Tested bd1d2b53 on Windows 11 (26300), RTX 5060 Ti / 621.14, MSVC 14.51 (VS 2026), Vulkan SDK 1.4.363.0, RelWithDebInfo, clean build with -DLEONIDA_LLVM_MC (translated-shader D3D12 gate tests included), full LEONIDA_VK_VALIDATION=1 ctest -j4: 146/146 passed, 0 VUIDs, 0 build errors. AI-assisted (Claude Code).

@memorypressure

Copy link
Copy Markdown

Merged cleanly into main 3faac55; all docs suites pass and the C++ was reviewed statically only. The place bookkeeping checks out: held_/outstanding_ mutate only under the leaf lock, the oldest-place release condition is exact including the empty (UINT64_MAX) case, and every death path for a held operation returns its place — release_ready, discard_waiting_on and teardown all covered, so no parked release wedges. One consequence to note: a release unblocked by a dropped batch runs at the next pump rather than immediately — deferred, not lost. It conflicts pairwise with #4561 in vulkan_backend.h; docs-file overlap with #3634 auto-merges. RTX 3060 counts not reproduced. Checks pending. AI-assisted: yes. Tested on Linux (RTX 5080 host, CPU-only review).

@Parakeet-Wheat

Copy link
Copy Markdown
Contributor

Tested bd1d2b5 (on its base main 03b09a08) on an RTX 3070 (610.88, Windows 11 26300, MSVC VS 2022, Ninja RelWithDebInfo, Vulkan SDK 1.4.363 layers), with LEONIDA_VK_VALIDATION=1: pass. Full ctest is 155/155. d3d12_queue_handover_test gives the same kept 2, waiting 0 → kept 0, waiting 2 → kept 0, waiting 0 sequence, with 372 cases on the layer and 369 on host D3D12 (RTX 3070), every one exact. queue_holds_test passes.

What I can add is controls. Each one is a single change, rebuilt with queue_holds_test and d3d12_queue_handover_test, then restored:

Change queue_holds_test d3d12_queue_handover_test
Resource::final_release deletes at once (main's behaviour) pass exit 0xC0000005 (access violation): kept 0, waiting 0; lines 446, 480, 539
held_removed: parked releases wait for every hold (outstanding_.empty()), not only the earlier ones exit 6 pass
report_held_at_teardown doesn't give the places back pass fails: line 454, plus 480 and 524
~VulkanQueue without run_released() pass fails: line 454
discard_waiting_on (fence released) doesn't give the place back pass fails: line 487, 524
pump_ready without its final run_released() pass fails: lines 487, 553
release_ready: held_removed(op.place) before run(op) pass pass

So every bookkeeping path is pinned, and the first row is stronger than the description's negative control. With an immediate delete, the held batch didn't just log failed when it was released here: the test process crashed with an access violation. That's the use-after-free this PR prevents, not only a lost submission.

The last row is the one ordering the tests can't see, and on one thread it can't matter: run_released() only happens at the end of pump_ready(), after release_ready() returns. It does matter with two threads. If held_removed() came first, another thread finishing its own pump_ready() (a Signal on another queue, or another queue's destructor) could run run_released() and delete the resource while this thread is still replaying the batch that names it. The code has it in the safe order, and the comment above release_ready() says so. A two-thread test would be needed to pin it, so a short note at the call site ("must stay after run(op)") may be the practical guard.

On "a release unblocked by a dropped batch runs at the next pump" (from the review above): at this head, both drop paths run it at once. remove_fence() ends with pump_ready(), and ~VulkanQueue calls run_released() itself. The ~VulkanQueue, fence-drop and pump_ready rows above show the tests check exactly that (lines 454, 487).

AI-assisted (Claude Code).

@gertify

gertify commented Nov 23, 2026

Copy link
Copy Markdown

Tested bd1d2b5 on NVIDIA GeForce RTX 4080, driver 617.42: d3d12_queue_handover_test exits 0. The released-while-held case prints "kept 2, waiting 0" while the batch is held, "kept 0, waiting 2" after the CPU Signal, and "kept 0, waiting 0" after the held batch completes and 2 more submissions on queue B. It prints "Vulkan layer: 372 cases passed, every one exact" and "Host D3D12 (NVIDIA GeForce RTX 4080): 369 cases passed, every one exact". queue_holds_test exits 0 with "releases waited for the operations held before them, in any completion order, and ran once". The immediate-delete control from the description was not run, and this run had no validation layer.

AI-assisted.

@kovaaper

Copy link
Copy Markdown
Contributor

Nice catch! Thanks for finding and fixing this edge case that I missed in my original implementation.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants