Skip to content

Runtime: dispatch FenceWaitDispatcher callbacks outside mutex and wake blocked waits on device lost - #1933

Merged
ItsNotRexed merged 1 commit into
ItsNotRexed:mainfrom
emirhan-karaca:fix/fence-dispatcher-deadlock-and-device-lost
Nov 22, 2026
Merged

ItsNotRexed merged 1 commit into
ItsNotRexed:mainfrom
emirhan-karaca:fix/fence-dispatcher-deadlock-and-device-lost

Conversation

@emirhan-karaca

Copy link
Copy Markdown
Contributor

Claimed in #1745 (claim).

What and why

FenceWaitDispatcher (runtime/src/vulkan_backend.h:496-623) had three concurrency / device-lost bugs:

  1. Re-entrant callback deadlock in run() and cancel(): Both run() (on normal completion and VK_ERROR_DEVICE_LOST) and cancel() invoked e.callback() and signal_event_(e.event_handle) while holding mutex_. Any callback that calls enqueue(), enqueue_callback(), or cancel() (for example, releasing a Fence whose ~Fence() calls cancel_fence_waits()) deadlocked immediately on the non-recursive std::mutex.
  2. device_lost_ wakeup / teardown hang: signal_wakeup_locked() returned early when device_lost_ was already set, and VulkanContext::mark_device_lost() did not wake FenceWaitDispatcher. If a queue submission marked device_lost_ while run() was already blocked inside vkWaitSemaphores(..., UINT64_MAX) on an unsignaled timeline semaphore, pending waits stayed stuck and cancel() / stop() (thread_.join()) could hang indefinitely.
  3. vkGetSemaphoreCounterValue VK_ERROR_DEVICE_LOST spin: In run(), std::erase_if returned false when vkGetSemaphoreCounterValue failed with VK_ERROR_DEVICE_LOST, leaving the already-signaled entry in pending_ forever and spinning vkWaitSemaphores.

Changes

  • runtime/src/vulkan_backend.h (FenceWaitDispatcher & VulkanContext::mark_device_lost()):
    • Moved ready, cancelled, and device-lost Entry items into a local vector under mutex_ and dispatched callbacks / signal_event_ outside mutex_ via dispatch_entries().
    • Checked stop_ || device_lost_ under mutex_ in enqueue() / enqueue_callback() so late arrivals dispatch immediately outside mutex_ without racing notify_device_lost().
    • Removed the device_lost_ early return from signal_wakeup_locked(), added FenceWaitDispatcher::notify_device_lost() called from VulkanContext::mark_device_lost(), and checked device_lost_ in run()'s wait predicate and post-wait path so blocked waits wake and drain promptly.
    • Handled vkGetSemaphoreCounterValue(...) == VK_ERROR_DEVICE_LOST in run() by marking device_lost_, draining all remaining pending_ entries outside mutex_, and exiting cleanly.
  • runtime/test/vk_fence_dispatcher_sync_test.cpp + runtime/CMakeLists.txt (vk_fence_dispatcher_sync, SKIP_RETURN_CODE 77):
    1. Re-entrant completion callback in run() calling both enqueue_fence_callback() and cancel_fence_waits().
    2. Re-entrant callback in cancel() calling enqueue_fence_callback() on another fence.
    3. mark_device_lost() waking a run() thread actively blocked inside vkWaitSemaphores(..., UINT64_MAX), completing its pending callback, and completing cancel() + teardown (stop()).
    4. vkGetSemaphoreCounterValue returning VK_ERROR_DEVICE_LOST draining pending waits, marking device_lost_, and exiting without spinning (2 counter calls).

Verification (synthetic tests only, no game data)

Built on Windows 11 with MinGW-w64 g++ 16.2.0 (-std=c++20 -O2 -Wall -Wextra, Vulkan-Headers 1.4.363.0, 0 warnings in touched/new code):

  • Intel(R) UHD Graphics (0x8086:0xa7a8, driver 101.7092, Vulkan 1.4.323): vk_fence_dispatcher_sync_test 3/3 PASS (0 validation errors).
  • NVIDIA GeForce RTX 5050 Laptop GPU (driver 621.24): vk_fence_dispatcher_sync_test 3/3 PASS (0 validation errors).
  • Negative control (origin/main 6a6704df FenceWaitDispatcher): deterministically fails vk_fence_dispatcher_sync_test at line 126: wait_flag(mu, cv, first_ran) (exit=1, re-entrant callback deadlock under mutex_).

AI-assisted.

@JavierBlanco23

Copy link
Copy Markdown
Contributor

Tested b01bed6e on NVIDIA GeForce RTX 5080, driver 616.56, Windows 11 (MSVC 19.44, Ninja): pass.

  • cmake --build runtime/build --target vk_fence_dispatcher_sync_test
  • vk_fence_dispatcher_sync_test.exe: vk_fence_dispatcher_sync_test: ok (re-entrant run()/cancel() callbacks, mark_device_lost() wakeup + teardown, and vkGetSemaphoreCounterValue DEVICE_LOST drain in 2 calls all passed).

@tumbione

Copy link
Copy Markdown
Contributor

Tested b01bed6e on NVIDIA GeForce RTX 5090, driver 616.56, Windows 11 (10.0.26300): pass

Built with scripts/build_runtime.ps1 (MSVC, VS 2022 Build Tools, Ninja, RelWithDebInfo, Vulkan SDK 1.4.363.0); /W4 gives no warnings in vk_fence_dispatcher_sync_test.cpp or vulkan_backend.h.

Run Result
vk_fence_dispatcher_sync_test, 10 runs pass 10/10 (all four stages ok, DEVICE_LOST drains without spin (2 calls))
Same, LEONIDA_VK_VALIDATION=1, implicit layers off, 5 runs pass 5/5, validation on, 0 VUIDs
Full ctest 2 failed of 114, both identical to main 6a6704df here: d3d12_compute (line 515: ... device_proxy_ref_count(device.p) == 1, #1898) and d3d12_draw (fence signal 21 is not above 30, #1807). vk_fence_dispatcher_sync, d3d12_fence_timing, d3d12_fence_events and d3d12_fence_waiter pass
Full ctest, LEONIDA_VK_VALIDATION=1, implicit layers off same two failures; the only VUID in the run is VUID-vkDestroyPipeline-pipeline-00765 inside d3d12_draw
Negative control: runtime/src/vulkan_backend.h from 6a6704df, only this test rebuilt, 3 runs does not pass, 3/3, but not the way the description says: with MSVC the process ends with exit code 0xC0000409 and prints nothing, where the MinGW run reports line 126: wait_flag(mu, cv, first_ran). Passes again with this branch's header

I did not look into why the MSVC failure is a fast-fail exit and not the test's own line-126 message; I only note that the control fails on both toolchains.

No game data involved. AI-assisted (Claude Code): it built the tree and ran everything above on this machine.

@XFlawless1

Copy link
Copy Markdown
Contributor

Tested b01bed6 natively on Windows with NVIDIA and AMD: pass, no regressions. There is one ordering question from the code read, below.

Setup: Windows 11 Pro 10.0.26300, MSVC 19.44.35230 (VS 2022 Build Tools), Vulkan SDK 1.4.363.0, scripts/build_runtime.ps1 (Ninja, RelWithDebInfo). Two GPUs, each selected with LEONIDA_VK_DEVICE:

  • NVIDIA GeForce RTX 5080, driver 621.14 (Vulkan 1.4.357)
  • AMD Radeon iGPU, Ryzen 7 9800X3D (RDNA2, 0x13C0), driver 32.0.21042.62 (Vulkan 1.4.315)

VK_LOADER_LAYERS_DISABLE=~implicit~. Full ctest -j1, with this PR merged onto main 6a6704df, compared with 6a6704df alone on the same PC.

Code read:

  • FenceWaitDispatcher's device_lost_ is a reference to the context's atomic. So mark_device_lost() → notify_device_lost() wakes run() on the same flag the cv_ predicate reads. Good.

  • One thing to look at: run() now moves ready entries out of pending_ and calls them with mutex_ released. A concurrent cancel(sem) from ~Fence then finds no entries for sem. With waiting_ false it also doesn't wait on epoch_cv_, so it can return while those callbacks are still being dispatched. Before this PR they ran under mutex_, so cancel() couldn't return until they were done.

    • The enqueue_fence_callback lambda holds its waiter by shared_ptr, so that path is safe.
    • The SetEventOnCompletion path calls signal_event_(handle) with the app's event handle. An app that releases the fence and then closes the event could get a SetEvent on a closed handle, or on one Windows has already reused.
    • One fix: cancel() waits until an in-progress dispatch has finished, using a dispatch counter or epoch next to waiting_. Dispatch would still happen outside the lock.

    None of the tests here hit this. It needs a fence released in the window between "ready" and "dispatched".

AI-assisted (Claude Code).

@JRamos1993

Copy link
Copy Markdown
Contributor

Tested b01bed6, merged onto main 4eb6155 (no conflicts), on an RTX 5090 (driver 616.92), Windows 11, MSVC 19.44, Vulkan SDK 1.4.363, fresh RelWithDebInfo build:

One question from reading it. Before this PR, run() fired ready callbacks and SetEvents under mutex_. Since cancel(sem) also takes mutex_, nothing for sem could fire after cancel returned. Now run() moves ready entries into the local ready, unlocks, then dispatches.

A cancel(sem) that lands in that window finds no pending entry for sem and waiting_ == false, so it returns at once while run() is still about to call signal_event_(e.event_handle). Through ~Fence() → cancel_fence_waits(), an app that releases the fence and then closes its event could see SetEvent reach a closed (or reused) handle.

The callback entries are fine: the lambdas own a shared_ptr<FenceWaiter>. Would an in-flight dispatch count that cancel() waits on keep the old guarantee?

AI-assisted (Claude Code).

@ezwinxdlmao

Copy link
Copy Markdown
Contributor

Tested b01bed6 on an NVIDIA GeForce RTX 3050 Laptop GPU, driver 32.0.16.2101, Windows 11, native MSVC (VS 2022 Build Tools, Ninja, RelWithDebInfo): pass.

  • LEONIDA_VK_VALIDATION=1 vk_fence_dispatcher_sync_test: every case ok, exit 0. That includes the re-entrant callbacks in run() and cancel(), mark_device_lost() waking a blocked wait with clean teardown, and DEVICE_LOST from vkGetSemaphoreCounterValue draining without a spin (2 calls).
  • Full ctest -j3: 112/114. The two failures are d3d12_compute (device_proxy_ref_count(device.p) == 1, line 515) and d3d12_draw (bundle blend pixel 127,0,127,255; TEST-266). Both fail identically at this PR's merge base 6a6704df on the same GPU.

AI-assisted (Claude Code).

@ItsNotRexed
ItsNotRexed merged commit 8b61d26 into ItsNotRexed:main Nov 22, 2026
10 of 11 checks passed
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.

7 participants