runtime: fix deadlock, dropped timestamps, and stop races in GPU label Completions #1836

Open
github-bot wants to merge 1 commit from github-bot/gh-1836 into main AGit
Owner

@⁠IlyassRS3 on GitHub · 2026-11-25 12:54 UTC · original
IlyassRS3:fix/rt-gpu-labels-completions-safety → main · +586 −58 · 3 files · 1 commits · open

Item ID: RT-GPU-LABELS-COMPLETIONS-SAFETY
Claim: #1608

Summary

Fixes a reproducible lock-order deadlock, dropped GPU timestamp queries, unnecessary query-pool/timestamp commands for non-timestamp labels, and shutdown races in leonida::label::Completions (runtime/src/vulkan_gpu_labels.h):

  1. Eliminate Completions::mutex_ <-> VulkanContext::resource_mutex_ deadlock in Completions::run()
    • run() previously held Completions::mutex_ across publish(b) -> store_value() -> value_sink::arena() -> write_arena_value() -> VulkanContext::is_sparse_va() (which acquires std::shared_lock(resource_mutex_), runtime/src/vulkan_backend.h:1915) and kernel_writes::begin_write().
    • Meanwhile VulkanQueue::execute() holds std::shared_lock(resource_mutex_) while calling gpu_labels_.begin_record() and gpu_labels_.record() (which acquire Completions::mutex_). Any concurrent resource registration/destruction waiting on std::unique_lock(resource_mutex_) blocks new shared readers and deadlocks all three threads.
    • run() now swaps pending_ into a local batch list, releases mutex_ before polling vkGetFenceStatus and running publish(), then re-acquires mutex_ to accumulate errors_/expired_, recycle completed batches, and preserve FIFO ordering of still-pending batches before newly arrived ones (looping immediately without sleeping when closing_ becomes true or new batches arrived while unlocked).
  2. Pass VK_QUERY_RESULT_WAIT_BIT for signaled timestamp labels
    • Even after vkGetFenceStatus == VK_SUCCESS, Vulkan allows vkGetQueryPoolResults without VK_QUERY_RESULT_WAIT_BIT to return VK_NOT_READY, which previously incremented errors_ and silently dropped the timestamp label. Because every recorded timestamp query in the batch has already executed once its fence signals, passing VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT safely waits for writeback visibility without risk of hanging.
  3. Skip timestamp query pools for clock != 1 labels
    • record() unconditionally allocated a VkQueryPool and emitted vkCmdResetQueryPool + vkCmdWriteTimestamp(BOTTOM_OF_PIPE) even for clock == 0 (immediate value) and clock == 2 (system QPC) labels that never read a Vulkan query. Storing a per-entry dense query index (no_query for clock != 1) avoids query-pool bloat, unnecessary pipeline stalls, and invalid timestamp commands on queue families with timestampValidBits == 0.
  4. Fix shutdown concurrency and exception safety (stop(), ~Completions(), initialize())
    • Track stopping_ under mutex_ so concurrent stop(dev) calls wait cleanly for teardown to finish instead of racing on worker_.join() / vkDestroyFence / vkDestroyQueryPool.
    • Reject new record() and submit_fence() calls once stopping_ is set (before vkDeviceWaitIdle), move worker_ out under lock before joining, read device_ under lock in ~Completions(), and reset device_ if std::thread construction throws in initialize().

Tests

Added pure-CPU mock-Vulkan test runtime/test/gpu_label_completions_test.cpp (registered as CTest gpu_label_completions under if(TARGET Vulkan::Headers) in runtime/CMakeLists.txt).

Verified locally on macOS arm64 (Apple Clang) with the pinned Khronos Vulkan-Headers (6802bb4733b63ed5efd3adb308a6c885ef180ea1):

  • gpu_label_completions_test: PASS under ASan+UBSan, PASS under TSan (0 races), PASS under -O2 (3 consecutive runs), -Wall -Wextra -Werror -Wno-missing-field-initializers.
  • Mutation check against main's runtime/src/vulkan_gpu_labels.h: Test 1 reproducibly deadlocks (4 s timeout under TSan).
  • Compile-checked replay_pipeline_compiles_test.cpp against the updated header.
  • Hygiene: python3 -I scripts/check_no_game_data.py ... and python3 -I tests/test_text_write_line_endings.py pass.

Disclosure

  • AI-assisted: yes
  • GPUs tested: none (macOS arm64 host; CPU mock-Vulkan tests verified under ASan/UBSan/TSan; Windows/MSVC + real GPU tests including gpu_label_store and xbox_gpu_label_completion rely on CI / reviewers)
**@⁠IlyassRS3** on GitHub · 2026-11-25 12:54 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1836) `IlyassRS3:fix/rt-gpu-labels-completions-safety` → `main` · +586 −58 · 3 files · 1 commits · open Item ID: `RT-GPU-LABELS-COMPLETIONS-SAFETY` Claim: https://git.gtahub.st/github/ubiquitarianism--leonida/issues/1608 ## Summary Fixes a reproducible lock-order deadlock, dropped GPU timestamp queries, unnecessary query-pool/timestamp commands for non-timestamp labels, and shutdown races in `leonida::label::Completions` (`runtime/src/vulkan_gpu_labels.h`): 1. **Eliminate `Completions::mutex_` <-> `VulkanContext::resource_mutex_` deadlock in `Completions::run()`** - `run()` previously held `Completions::mutex_` across `publish(b)` -> `store_value()` -> `value_sink::arena()` -> `write_arena_value()` -> `VulkanContext::is_sparse_va()` (which acquires `std::shared_lock(resource_mutex_)`, `runtime/src/vulkan_backend.h:1915`) and `kernel_writes::begin_write()`. - Meanwhile `VulkanQueue::execute()` holds `std::shared_lock(resource_mutex_)` while calling `gpu_labels_.begin_record()` and `gpu_labels_.record()` (which acquire `Completions::mutex_`). Any concurrent resource registration/destruction waiting on `std::unique_lock(resource_mutex_)` blocks new shared readers and deadlocks all three threads. - `run()` now swaps `pending_` into a local batch list, releases `mutex_` before polling `vkGetFenceStatus` and running `publish()`, then re-acquires `mutex_` to accumulate `errors_`/`expired_`, recycle completed batches, and preserve FIFO ordering of still-pending batches before newly arrived ones (looping immediately without sleeping when `closing_` becomes true or new batches arrived while unlocked). 2. **Pass `VK_QUERY_RESULT_WAIT_BIT` for signaled timestamp labels** - Even after `vkGetFenceStatus == VK_SUCCESS`, Vulkan allows `vkGetQueryPoolResults` without `VK_QUERY_RESULT_WAIT_BIT` to return `VK_NOT_READY`, which previously incremented `errors_` and silently dropped the timestamp label. Because every recorded timestamp query in the batch has already executed once its fence signals, passing `VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT` safely waits for writeback visibility without risk of hanging. 3. **Skip timestamp query pools for `clock != 1` labels** - `record()` unconditionally allocated a `VkQueryPool` and emitted `vkCmdResetQueryPool` + `vkCmdWriteTimestamp(BOTTOM_OF_PIPE)` even for `clock == 0` (immediate value) and `clock == 2` (system QPC) labels that never read a Vulkan query. Storing a per-entry dense query index (`no_query` for `clock != 1`) avoids query-pool bloat, unnecessary pipeline stalls, and invalid timestamp commands on queue families with `timestampValidBits == 0`. 4. **Fix shutdown concurrency and exception safety (`stop()`, `~Completions()`, `initialize()`)** - Track `stopping_` under `mutex_` so concurrent `stop(dev)` calls wait cleanly for teardown to finish instead of racing on `worker_.join()` / `vkDestroyFence` / `vkDestroyQueryPool`. - Reject new `record()` and `submit_fence()` calls once `stopping_` is set (before `vkDeviceWaitIdle`), move `worker_` out under lock before joining, read `device_` under lock in `~Completions()`, and reset `device_` if `std::thread` construction throws in `initialize()`. ## Tests Added pure-CPU mock-Vulkan test `runtime/test/gpu_label_completions_test.cpp` (registered as CTest `gpu_label_completions` under `if(TARGET Vulkan::Headers)` in `runtime/CMakeLists.txt`). Verified locally on macOS arm64 (Apple Clang) with the pinned Khronos `Vulkan-Headers` (`6802bb4733b63ed5efd3adb308a6c885ef180ea1`): - `gpu_label_completions_test`: PASS under ASan+UBSan, PASS under TSan (0 races), PASS under `-O2` (3 consecutive runs), `-Wall -Wextra -Werror -Wno-missing-field-initializers`. - Mutation check against `main`'s `runtime/src/vulkan_gpu_labels.h`: Test 1 reproducibly deadlocks (4 s timeout under TSan). - Compile-checked `replay_pipeline_compiles_test.cpp` against the updated header. - Hygiene: `python3 -I scripts/check_no_game_data.py ...` and `python3 -I tests/test_text_write_line_endings.py` pass. ## Disclosure - **AI-assisted**: yes - **GPUs tested**: none (macOS arm64 host; CPU mock-Vulkan tests verified under ASan/UBSan/TSan; Windows/MSVC + real GPU tests including `gpu_label_store` and `xbox_gpu_label_completion` rely on CI / reviewers)
Fix four correctness and concurrency bugs in leonida:🏷️:Completions (runtime/src/vulkan_gpu_labels.h):
- Release mutex_ in run() before polling vkGetFenceStatus and calling publish()/store_value() (eliminates a 3-thread reader-writer deadlock between Completions::mutex_ and VulkanContext::resource_mutex_ via value_sink::arena() -> is_sparse_va(), and avoids holding mutex_ across kernel_writes::begin_write() and Vulkan queries).
- Pass VK_QUERY_RESULT_WAIT_BIT alongside VK_QUERY_RESULT_64_BIT in publish() once the batch fence has signaled VK_SUCCESS, preventing deferred-writeback drivers from dropping completed timestamp labels with VK_NOT_READY.
- Only allocate timestamp VkQueryPools and record vkCmdResetQueryPool/vkCmdWriteTimestamp for clock == 1 labels; clock == 0 (immediate) and clock == 2 (QPC) labels skip query pools completely.
- Guard stop(), ~Completions(), initialize(), record(), submit_fence(), and submitted() against concurrent stop() double-join/double-destroy, in-flight recordings after teardown begins, and thread-creation failure.

Item ID: RT-GPU-LABELS-COMPLETIONS-SAFETY
Claim: https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7162941588
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:07:44 +00:00
Author
Owner

@⁠copilot-pull-request-reviewer[bot] on GitHub · 2026-11-25 12:54 UTC · original · reviewed

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

**@⁠copilot-pull-request-reviewer[bot]** on GitHub · 2026-11-25 12:54 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1836#pullrequestreview-6057983561) · **reviewed** Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
Author
Owner

@⁠GGandCo on GitHub · 2026-11-25 13:30 UTC · original

Native Windows 11 / Intel UHD Graphics 101.6314 data point: applied 8de0dc933 privately onto main98c2f7777 alongside local compatibility changes and PR1849. Built with MSVC RelWithDebInfo. gpu_label_completions, gpu_label_store and xbox_gpu_label_completion pass; the two real-GPU label tests also pass with LEONIDA_VK_VALIDATION=1. This is a combined integration result, not an isolated before/after or game-boot claim. AI-assisted (OpenAI Codex).

**@⁠GGandCo** on GitHub · 2026-11-25 13:30 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1836#issuecomment-7163876802) Native Windows 11 / Intel UHD Graphics 101.6314 data point: applied 8de0dc933 privately onto main98c2f7777 alongside local compatibility changes and PR1849. Built with MSVC RelWithDebInfo. gpu_label_completions, gpu_label_store and xbox_gpu_label_completion pass; the two real-GPU label tests also pass with LEONIDA_VK_VALIDATION=1. This is a combined integration result, not an isolated before/after or game-boot claim. AI-assisted (OpenAI Codex).
Author
Owner

@⁠mrgenty on GitHub · 2026-11-26 22:04 UTC · original

Windows/MSVC on a real GPU, since the description leaves that to reviewers: RTX 3060, NVIDIA 621.24, Windows 11, MSVC 19.44.35230, head 8de0dc93 merged onto main fac8b4bb, built with MSVC /fsanitize=address (#1608 RT-ASAN-WINDOWS).

  • It compiles clean with MSVC. gpu_label_completions, gpu_label_store and xbox_gpu_label_completion pass, the last two also with LEONIDA_VK_VALIDATION=1 and no validation message.
  • xbox_gpu_label_test.exe run 1,000 times, 16 at a time: no hang, no failure, max 9.8 s.
  • The full runtime suite under ASan with ctest -j 4: no ASan report and no timeout. xbox_present and d3d12_set_descriptor_heaps fail, but they fail the same way on plain main fac8b4bb without ASan, so not from this PR.

One possibly related observation: on main 8564bb48 under ASan, xbox_gpu_label_completion hit its 20 s timeout once in three full -j 4 runs. Its output stopped after the first label-path list calls, before "GPU completion values … passed". That would fit the Completions::mutex_ / resource_mutex_ deadlock this fixes, but I could not reproduce it without the PR either (0 hangs in 1,000 stressed runs), so I can't confirm this PR fixes it.

**@⁠mrgenty** on GitHub · 2026-11-26 22:04 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1836#issuecomment-7204336054) Windows/MSVC on a real GPU, since the description leaves that to reviewers: RTX 3060, NVIDIA 621.24, Windows 11, MSVC 19.44.35230, head `8de0dc93` merged onto `main` `fac8b4bb`, built with MSVC `/fsanitize=address` (#1608 RT-ASAN-WINDOWS). - It compiles clean with MSVC. `gpu_label_completions`, `gpu_label_store` and `xbox_gpu_label_completion` pass, the last two also with `LEONIDA_VK_VALIDATION=1` and no validation message. - `xbox_gpu_label_test.exe` run 1,000 times, 16 at a time: no hang, no failure, max 9.8 s. - The full runtime suite under ASan with `ctest -j 4`: no ASan report and no timeout. `xbox_present` and `d3d12_set_descriptor_heaps` fail, but they fail the same way on plain `main` `fac8b4bb` without ASan, so not from this PR. One possibly related observation: on `main` `8564bb48` under ASan, `xbox_gpu_label_completion` hit its 20 s timeout once in three full `-j 4` runs. Its output stopped after the first label-path list calls, before "GPU completion values … passed". That would fit the `Completions::mutex_` / `resource_mutex_` deadlock this fixes, but I could not reproduce it without the PR either (0 hangs in 1,000 stressed runs), so I can't confirm this PR fixes it.
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/1836/head:github-bot/gh-1836'
git switch 'github-bot/gh-1836'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-1836'
git switch 'github-bot/gh-1836'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-1836'
git switch 'github-bot/gh-1836'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-1836'
git switch 'main'
git merge --squash 'github-bot/gh-1836'
git switch 'main'
git merge --ff-only 'github-bot/gh-1836'
git switch 'main'
git merge 'github-bot/gh-1836'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.