Skip to content

Runtime: retain D3D12 fence semaphores across queued and in-flight GPU work - #3969

Open
pmilewsskiedu-gif wants to merge 1 commit into
ItsNotRexed:mainfrom
pmilewsskiedu-gif:fix/d3d12-fence-semaphore-lifetime-20261122
Open

pmilewsskiedu-gif wants to merge 1 commit into
ItsNotRexed:mainfrom
pmilewsskiedu-gif:fix/d3d12-fence-semaphore-lifetime-20261122

Conversation

@pmilewsskiedu-gif

@pmilewsskiedu-gif pmilewsskiedu-gif commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Correctness defect

On current main aa2988c, ID3D12CommandQueue::Wait(fence, 1) stores a raw VkSemaphore in VulkanQueue::waits_. Releasing the last COM reference to that fence immediately calls vkDestroySemaphore from VulkanFence::~VulkanFence, even when the queue has not submitted its wait yet or a signal/wait is already in-flight. The next queue submission can reference a destroyed semaphore. No game files are involved.

The identical 48-iteration synthetic host D3D12 WARP scenario (fence created with initial value 1, Wait(fence, 1), release fence, then submit Signal(done, n)) completes 48/48. On unmodified Leonida main, with RTX 4060 Ti Vulkan validation enabled, a hooked vkQueueSubmit detects a previously destroyed wait handle on iteration 0: test exits 1, destroyed use=1. The hook rejects that invalid call before reaching the real driver, so this is a deterministic API-lifetime negative control, not an observed GPU memory corruption or a real Vulkan VUID.

Production fix

  • Decouple the underlying Vulkan timeline semaphore lifetime from the D3D12 COM fence object using a shared timeline owner. Destroy the Vulkan semaphore only when no queue can reference it, without blocking the fence destructor on device/queue idle.
  • Retain owners for pending, held (Runtime: queue Wait before Signal — hold the batch until its Signal is submitted, so layouts follow dependency order across queues #2951), and submitted GPU waits/signals, including on sparse-bind submissions. Release submitted owners only after that queue's own progress timeline ticket completes or its queue is destroyed after idle.
  • Keep pending wait ownership across retryable vkQueueSubmit failures; keep COM Release event cancellation and CPU deferred-signal callback lifetime safe. Preserve the current cross-queue Wait-before-Signal scheduling and existing CPU fence ordering.

Verification

  • Exact final synthetic test built on original upstream aa2988cc in a separate detached baseline worktree: RED, exit 1, first invalid queued wait detected; native WARP comparison passes.
  • Patched RTX 4060 Ti, Vulkan validation enabled, Medal disabled: GREEN, exit 0, zero counted Vulkan validation errors. Exercises 48 released-fence waits, synthetic one-shot VK_ERROR_OUT_OF_HOST_MEMORY queue-submit failure and higher-value retry, concurrent two-queue waits on a released fence, unsubmitted-queue cleanup, and an actual queued GPU signal stalled behind a host-signaled Vulkan timeline gate to check there is no premature destruction and eventual retirement.
  • Final patched full regression under RTX validation 12/12 consecutive runs PASS.
  • MSVC 19.44 / Vulkan SDK 1.4.363 / Ninja focused targets build; 9/9 CTests PASS (0 failures): vk_queue_query_sync, d3d12_multithread, d3d12_queue_wait, d3d12_queue_wait_timeout, d3d12_queue_handover, d3d12_buffer_tiles, d3d12_fence_timing, d3d12_fence_events, d3d12_fence_lifetime. git diff --check clean.

Original commit: a36918b4965443f8c2fcd832233d03e0b92d1aaa. Four project files, +378/-21. Base aa2988cc. Coordination claim before implementation: #3796 (comment) (claims carried forward to #3918). Independent from still-open #3789 transient Signal retry and existing #655/#770 placed alias ownership; preserves the current-main held-queue behavior (PR #2951 itself is OPEN) and merged #1161 CPU/GPU ordering.

Limitations: The Vulkan OOM is synthetically injected before driver execution; physical device OOM and other GPU vendors were not tested. No full-suite claim or authentic game execution; GTA VI title executable remains unavailable. No proprietary game code, shaders, logs, keys, assets, executable or disassembly. AI-assisted implementation and testing.

@Flyander Flyander 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.

Reviewed the fence lifetime ownership paths: pending waits, deferred operations, successful queue submissions, sparse binds, retries, and per-queue retirement are all represented in the diff. The new synthetic test covers released fences, retry, cross-queue use, and a deliberately stalled in-flight signal. I found no additional blocker in this change.

@rafaelpssz

Copy link
Copy Markdown
Contributor

Tested a36918b4 on Windows 11, RTX 3060 (driver 616.64), Vulkan SDK 1.4.363.1, built with clang-cl + xwin (RelWithDebInfo). No game files.

  • d3d12_fence_lifetime_test: exit 0. Native WARP gives 48/48 released-fence pending waits completed, the in-flight fence has no early destruction, retired after GPU gate released and queue idle, and the release case reports 51 timelines retired, no stale handles; validation=0. The same with LEONIDA_VK_VALIDATION=1.
  • d3d12_vulkan_device_test: exit 0.
  • Red: with runtime/src/vulkan_backend.h and runtime/shims/d3d12_com.cpp from the base aa2988cc (rest at head), the test exits 1 with queue signal failed at iteration 0, destroyed use=1. That is the same negative control you saw on the RTX 4060 Ti, now on a second NVIDIA card.

@theswiss24

Copy link
Copy Markdown

Tested a36918b4 (contains main aa2988cc) on NVIDIA GeForce RTX 4070, driver 621.24, Windows 11 (26300), MSVC from Visual Studio 2026 (Ninja, RelWithDebInfo), Vulkan SDK 1.4.363.1: pass.

LEONIDA_VK_VALIDATION=1 d3d12_fence_lifetime_test.exe, exit 0:

native WARP: 48/48 released-fence pending waits completed
device: NVIDIA GeForce RTX 4070 (validation on)
in-flight fence: no early destruction, retired after GPU gate released and queue idle
fence release lifetime: 51 timelines retired, no stale handles; validation=0

I did not run the negative control on unpatched main. No game files.

AI-assisted (Claude Code).

@Vonsek

Vonsek commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Tested a36918b on Windows 11, AMD Radeon iGPU gfx1036 (driver 26.10.1) and RTX 5080 (driver 616.92): ctest -R "^(vk_queue_query_sync|d3d12_multithread|d3d12_queue_wait|d3d12_queue_wait_timeout|d3d12_queue_handover|d3d12_buffer_tiles|d3d12_fence_timing|d3d12_fence_events|d3d12_fence_lifetime)$" (MSVC, RelWithDebInfo, LEONIDA_VK_DEVICE set per run, device line confirmed, VK_LOADER_LAYERS_DISABLE=~implicit~) — pass on both, 9/9 each.

No Vulkan validation layer is installed here, so no VUID check was possible. No negative control run.

AI-assisted.

@0xTehuti 0xTehuti 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.

Independent Hardware Verification & Review: PR #3969

Environment & Testbed

  • OS: Windows 11 Pro x64 (Build 26100.1742)
  • GPU: NVIDIA GeForce RTX 2070 SUPER (TU104 Turing, 8192 MB VRAM)
  • Driver: NVIDIA Game Ready Driver 595.79 (Vulkan 1.4.304)
  • Toolchain: MSVC 19.44.35225.0 (VS 2022 Community), Ninja 1.13, CMake 4.4, Windows SDK 10.0.26100.0, Vulkan Headers 1.4.363
  • Validation Layers: VK_LAYER_KHRONOS_validation active via LEONIDA_VK_VALIDATION=1

Test Execution & Results

1. Native Fence Lifetime Test (d3d12_fence_lifetime_test.exe)

  • Native Host WARP Reference: 48/48 released-fence pending waits completed successfully.
  • RTX 2070 SUPER Native Run: PASS. All 51 timelines retired, 0 stale handles, 0 validation errors.
  • RTX 2070 SUPER under Vulkan Validation (LEONIDA_VK_VALIDATION=1):
    • 5/5 consecutive regression runs PASS (exit code 0).
    • Verified scenarios:
      1. 48 released-fence pending wait iterations.
      2. Synthetic VK_ERROR_OUT_OF_HOST_MEMORY injection during vkQueueSubmit verifying retry preservation of pending guest waits.
      3. Concurrent multi-queue waits on a shared released fence.
      4. Unsubmitted queue destruction releasing held timelines.
      5. In-flight GPU signal stalled behind a host timeline semaphore gate verifying deferred destruction until GPU gate release and queue idle.

2. Full CTest Synchronization Suite

Executed with Vulkan validation active (ctest --test-dir runtime/build --output-on-failure -V -R "^(d3d12_fence_|d3d12_queue_|d3d12_multithread|vk_queue_query_sync|d3d12_buffer_tiles)"):

  • vk_queue_query_sync: PASSED (0.39s)
  • d3d12_multithread: PASSED (0.31s)
  • d3d12_queue_wait: PASSED (1.29s)
  • d3d12_queue_wait_timeout: PASSED (0.77s)
  • d3d12_queue_handover: PASSED (6.35s)
  • d3d12_buffer_tiles: PASSED (0.09s)
  • d3d12_fence_timing: PASSED (2.12s)
  • d3d12_fence_events: PASSED (0.86s)
  • d3d12_fence_lifetime: PASSED (0.25s)
  • d3d12_fence_waiter: PASSED (0.03s)

Overall pass rate: 10/10 tests passed (100%), 0 failures, 0 Vulkan validation errors.


Code Review & Correctness Assessment

  1. Decoupled Timeline Lifetime (runtime/src/vulkan_backend.h, runtime/shims/d3d12_com.cpp):
    • VulkanFence::Timeline safely wraps the native VkSemaphore in an atomic shared owner (std::shared_ptr<Timeline>).
    • Releasing the D3D12 COM fence wrapper drops the COM ownership without blocking the CPU thread on queue idle or prematurely destroying the underlying Vulkan semaphore.
  2. Queue Lifecycle Retention (VulkanQueue::in_flight_fences_, wait_lifetimes_):
    • Queue wait, signal, and sparse-bind paths correctly capture shared owners into wait_lifetimes_ and promote them to in_flight_fences_ tied to the queue's internal progress ticket.
    • Retired tickets pop cleanly during command buffer recycling (collect_fences) and queue destruction.
    • Retries on transient submission failure preserve pending wait lifetimes.
  3. Repository Conventions & Quality:
    • Code adheres strictly to repository standards; git diff --check is completely clean with no trailing whitespace or style deviations.

Disclosures & Compliance

  • Clean-room verification: Zero game assets, shaders, binaries, dumps, or private keys used.
  • AI-assisted testing and verification: Verified and audited autonomously using Antigravity on RTX 2070 SUPER hardware.

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.

6 participants