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

Open
opened 2026-11-26 21:19:10 +01:00 by 4ld0 · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/ubiquitarianism/leonida/pull/1836
Author: @IlyassRS3
Created: 11/25/2026
Status: 🔄 Open

Base: main ← Head: fix/rt-gpu-labels-completions-safety


📝 Commits (1)

  • 8de0dc9 runtime: fix deadlock, dropped timestamps, and stop races in GPU label Completions

📊 Changes

3 files changed (+586 additions, -58 deletions)

View changed files

📝 runtime/CMakeLists.txt (+13 -0)
📝 runtime/src/vulkan_gpu_labels.h (+170 -58)
➕ runtime/test/gpu_label_completions_test.cpp (+403 -0)

📄 Description

Item ID: RT-GPU-LABELS-COMPLETIONS-SAFETY
Claim: https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7162941588

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)

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/ubiquitarianism/leonida/pull/1836 **Author:** [@IlyassRS3](https://github.com/IlyassRS3) **Created:** 11/25/2026 **Status:** 🔄 Open **Base:** `main` ← **Head:** `fix/rt-gpu-labels-completions-safety` --- ### 📝 Commits (1) - [`8de0dc9`](https://github.com/ubiquitarianism/leonida/commit/8de0dc933705544996b5dbd170a2536756f83081) runtime: fix deadlock, dropped timestamps, and stop races in GPU label Completions ### 📊 Changes **3 files changed** (+586 additions, -58 deletions) <details> <summary>View changed files</summary> 📝 `runtime/CMakeLists.txt` (+13 -0) 📝 `runtime/src/vulkan_gpu_labels.h` (+170 -58) ➕ `runtime/test/gpu_label_completions_test.cpp` (+403 -0) </details> ### 📄 Description Item ID: `RT-GPU-LABELS-COMPLETIONS-SAFETY` Claim: https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7162941588 ## 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) --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
Sign in to join this conversation.
No labels
bug
pull-request
No milestone
No project
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
starred/leonida#1848
No description provided.