runtime: use shared_mutex, destroy duplicates unlocked, and harden GraphicsShaderModules (RT-GRAPHICS-SHADER-MODULES-LOCK-AND-GUARDS) #1932

Closed
leonida/mandy
quietfold wants to merge 0 commits from fix/rt-graphics-shader-modules-lock-and-guards into main

Pull request closed

This pull request cannot be reopened because the branch was deleted.

quietfold commented 2026-11-25 16:06:09 +00:00

Item ID: RT-GRAPHICS-SHADER-MODULES-LOCK-AND-GUARDS (claim: #1608, comment 7167546476)

Problem

In leonida::GraphicsShaderModules (runtime/src/vulkan_graphics_shader_modules.h, used by DeviceState::graphics_modules when compiling graphics PSOs across parallel pipeline workers):

  1. vkDestroyShaderModule invoked while holding mutex_: on a concurrent duplicate creation race, acquire() did std::lock_guard lock(mutex_); if (auto found = find_locked(hash, words)) return found;. Returning found destroyed the local result (~Module() -> vkDestroyShaderModule) before lock was released, running driver destruction under the global module cache lock.
  2. Exclusive lock on read-only cache hits: std::mutex serialized parallel PipelineWorkers threads even on pure cache hits when multiple graphics PSOs share a vertex or pixel shader.
  3. Cross-device handle aliasing: find_locked() matched only hash and SPIR-V words without checking live->device == device.
  4. Missing guards and dead bucket buildup:
    • Null create or destroy function pointers were not rejected (leading to null dereference on create or in ~Module()).
    • If create() returned VK_SUCCESS with VK_NULL_HANDLE, a null handle was cached and returned.
    • Expired weak_ptr entries in a hot hash bucket were not pruned until every 1024th creation.

Fix

  • runtime/src/vulkan_graphics_shader_modules.h:
    • Switch mutex_ to std::shared_mutex, taking std::shared_lock on the read fast path and std::unique_lock only on miss/insert.
    • Scope the std::unique_lock before returning an existing Reference so any losing duplicate Module runs vkDestroyShaderModule completely outside the cache lock.
    • Check live->device == device in find_locked().
    • Reject empty words, null create/destroy, and VK_SUCCESS with VK_NULL_HANDLE; guard ~Module() against null destroy.
    • Prune expired entries in the target hash bucket on insert (in addition to periodic full sweeps), and keep a newly created valid Module even if weak-pointer map insertion throws std::bad_alloc.
  • runtime/test/vulkan_graphics_shader_modules_test.cpp & runtime/CMakeLists.txt:
    • Add portable CPU-only CTest vulkan_graphics_shader_modules covering null/error guards, deduplication, cross-device isolation, expiration/re-creation, a concurrency test proving vkDestroyShaderModule on a losing duplicate runs outside the cache lock, and a 4-thread TSan stress test.

Verification

  • AI-assisted: yes
  • GPUs tested: none (macOS host, CPU-only unit + concurrency tests against Khronos Vulkan-Headers)
  • Game files used: none
  • Commands run:
    • clang++ -std=c++20 -Wall -Wextra -Werror -O1 -g -fsanitize=address,undefined runtime/test/vulkan_graphics_shader_modules_test.cpp -> PASS
    • clang++ -std=c++20 -Wall -Wextra -Werror -O1 -g -fsanitize=thread runtime/test/vulkan_graphics_shader_modules_test.cpp -> PASS
    • clang++ -std=c++20 -Wall -Wextra -Werror -O2 runtime/test/vulkan_graphics_shader_modules_test.cpp (x3) -> PASS
    • Negative mutation check running the new test against unpatched main:runtime/src/vulkan_graphics_shader_modules.h -> FAILED as expected
    • python3 -I scripts/check_no_game_data.py runtime/src/vulkan_graphics_shader_modules.h runtime/test/vulkan_graphics_shader_modules_test.cpp runtime/CMakeLists.txt -> PASS
    • python3 -I tests/test_text_write_line_endings.py -> PASS (3/3)
Item ID: `RT-GRAPHICS-SHADER-MODULES-LOCK-AND-GUARDS` (claim: #1608, comment 7167546476) ## Problem In `leonida::GraphicsShaderModules` (`runtime/src/vulkan_graphics_shader_modules.h`, used by `DeviceState::graphics_modules` when compiling graphics PSOs across parallel pipeline workers): 1. **`vkDestroyShaderModule` invoked while holding `mutex_`**: on a concurrent duplicate creation race, `acquire()` did `std::lock_guard lock(mutex_); if (auto found = find_locked(hash, words)) return found;`. Returning `found` destroyed the local `result` (`~Module()` -> `vkDestroyShaderModule`) before `lock` was released, running driver destruction under the global module cache lock. 2. **Exclusive lock on read-only cache hits**: `std::mutex` serialized parallel `PipelineWorkers` threads even on pure cache hits when multiple graphics PSOs share a vertex or pixel shader. 3. **Cross-device handle aliasing**: `find_locked()` matched only `hash` and SPIR-V `words` without checking `live->device == device`. 4. **Missing guards and dead bucket buildup**: - Null `create` or `destroy` function pointers were not rejected (leading to null dereference on create or in `~Module()`). - If `create()` returned `VK_SUCCESS` with `VK_NULL_HANDLE`, a null handle was cached and returned. - Expired `weak_ptr` entries in a hot hash bucket were not pruned until every 1024th creation. ## Fix - **`runtime/src/vulkan_graphics_shader_modules.h`**: - Switch `mutex_` to `std::shared_mutex`, taking `std::shared_lock` on the read fast path and `std::unique_lock` only on miss/insert. - Scope the `std::unique_lock` before returning an existing `Reference` so any losing duplicate `Module` runs `vkDestroyShaderModule` completely outside the cache lock. - Check `live->device == device` in `find_locked()`. - Reject empty `words`, null `create`/`destroy`, and `VK_SUCCESS` with `VK_NULL_HANDLE`; guard `~Module()` against null `destroy`. - Prune expired entries in the target hash bucket on insert (in addition to periodic full sweeps), and keep a newly created valid `Module` even if weak-pointer map insertion throws `std::bad_alloc`. - **`runtime/test/vulkan_graphics_shader_modules_test.cpp`** & **`runtime/CMakeLists.txt`**: - Add portable CPU-only CTest `vulkan_graphics_shader_modules` covering null/error guards, deduplication, cross-device isolation, expiration/re-creation, a concurrency test proving `vkDestroyShaderModule` on a losing duplicate runs outside the cache lock, and a 4-thread TSan stress test. ## Verification - **AI-assisted**: yes - **GPUs tested**: none (macOS host, CPU-only unit + concurrency tests against Khronos Vulkan-Headers) - **Game files used**: none - Commands run: - `clang++ -std=c++20 -Wall -Wextra -Werror -O1 -g -fsanitize=address,undefined runtime/test/vulkan_graphics_shader_modules_test.cpp` -> PASS - `clang++ -std=c++20 -Wall -Wextra -Werror -O1 -g -fsanitize=thread runtime/test/vulkan_graphics_shader_modules_test.cpp` -> PASS - `clang++ -std=c++20 -Wall -Wextra -Werror -O2 runtime/test/vulkan_graphics_shader_modules_test.cpp` (x3) -> PASS - Negative mutation check running the new test against unpatched `main:runtime/src/vulkan_graphics_shader_modules.h` -> FAILED as expected - `python3 -I scripts/check_no_game_data.py runtime/src/vulkan_graphics_shader_modules.h runtime/test/vulkan_graphics_shader_modules_test.cpp runtime/CMakeLists.txt` -> PASS - `python3 -I tests/test_text_write_line_endings.py` -> PASS (3/3)
copilot-pull-request-reviewer[bot] reviewed 2026-11-25 16:21:00 +00:00
copilot-pull-request-reviewer[bot] left a comment
No description provided.
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.
zmasi commented 2026-11-28 12:17:35 +00:00

#1932 | head 64572cfd9e684a9a0807f5bac5ddbf105c890419 (merged cleanly with main d48a957bb9988afce424552a3c0c8d01ef12320f) | ctest --test-dir runtime/build -C RelWithDebInfo -R "^(vulkan_graphics_shader_modules|d3d12_multi_viewport)$" --output-on-failure (LEONIDA_VK_VALIDATION=1) | red on main: vulkan_graphics_shader_modules crashes (SEGFAULT dereferencing null create proc) | green on PR+main: 2/2 CTests pass (vulkan_graphics_shader_modules dedup/cross-device/unlock-on-destroy/concurrency + d3d12_multi_viewport 4/4 exact vs host D3D12) on RTX 3090 with 0 Khronos validation errors; check_no_game_data.py 0 violations | Windows 11, MSVC 19.44, RTX 3090, Vulkan SDK 1.4.363.1 | AI-assisted: yes

#1932 | head 64572cfd9e684a9a0807f5bac5ddbf105c890419 (merged cleanly with main d48a957bb9988afce424552a3c0c8d01ef12320f) | `ctest --test-dir runtime/build -C RelWithDebInfo -R "^(vulkan_graphics_shader_modules|d3d12_multi_viewport)$" --output-on-failure` (`LEONIDA_VK_VALIDATION=1`) | red on main: `vulkan_graphics_shader_modules` crashes (`SEGFAULT` dereferencing null `create` proc) | green on PR+main: 2/2 CTests pass (`vulkan_graphics_shader_modules` dedup/cross-device/unlock-on-destroy/concurrency + `d3d12_multi_viewport` 4/4 exact vs host D3D12) on RTX 3090 with `0` Khronos validation errors; `check_no_game_data.py` `0` violations | Windows 11, MSVC 19.44, RTX 3090, Vulkan SDK 1.4.363.1 | AI-assisted: yes
enlight3d commented 2026-11-29 15:19:22 +00:00

RUN #1932 (GraphicsShaderModules: shared_mutex, destroy duplicates unlocked, guards)

  • Heads: PR head 64572cfd9e684a9a0807f5bac5ddbf105c890419, main bd643e46e784daf6bf3a45d09f0ec20e669c4ddb.
  • Merged locally with main (git merge --no-ff), no conflicts, nothing pushed.
  • Commands:
    • cmake -S runtime -B runtime/build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DLEONIDA_REQUIRE_VULKAN=ON
    • cmake --build runtime/build -j 6 --target vulkan_graphics_shader_modules_test d3d12_multi_viewport_test gta6rt
    • ctest --test-dir runtime/build -C RelWithDebInfo -R "^(vulkan_graphics_shader_modules|d3d12_multi_viewport)$" --output-on-failure -j1 (once as is, once with LEONIDA_VK_VALIDATION=1)
  • Red (behavioural): the PR's test and CMake registration kept, runtime/src/vulkan_graphics_shader_modules.h reverted to main's version. It builds against main's header, and vulkan_graphics_shader_modules crashes (SegFault, as in the earlier run on main). d3d12_multi_viewport (uses the header through the D3D12 layer) still passes.
  • Green (PR merged into main): 2 of 2 pass (vulkan_graphics_shader_modules is CPU-only; d3d12_multi_viewport ran on the GPU, not skipped), both without and with LEONIDA_VK_VALIDATION=1.
  • Link: gta6rt.exe built from the merged tree has no new imports vs main (693 DLL!symbol entries, identical list, from dumpbin /imports).
  • Machine: RTX 3090 24 GB, NVIDIA 621.40, Windows 11 Pro 10.0.26300, MSVC 19.44.
  • Prep notes by TheGeogeo's review session.
RUN #1932 (GraphicsShaderModules: shared_mutex, destroy duplicates unlocked, guards) - Heads: PR head `64572cfd9e684a9a0807f5bac5ddbf105c890419`, main `bd643e46e784daf6bf3a45d09f0ec20e669c4ddb`. - Merged locally with main (`git merge --no-ff`), no conflicts, nothing pushed. - Commands: - `cmake -S runtime -B runtime/build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DLEONIDA_REQUIRE_VULKAN=ON` - `cmake --build runtime/build -j 6 --target vulkan_graphics_shader_modules_test d3d12_multi_viewport_test gta6rt` - `ctest --test-dir runtime/build -C RelWithDebInfo -R "^(vulkan_graphics_shader_modules|d3d12_multi_viewport)$" --output-on-failure -j1` (once as is, once with `LEONIDA_VK_VALIDATION=1`) - Red (behavioural): the PR's test and CMake registration kept, `runtime/src/vulkan_graphics_shader_modules.h` reverted to main's version. It builds against main's header, and `vulkan_graphics_shader_modules` crashes (`SegFault`, as in the earlier run on main). `d3d12_multi_viewport` (uses the header through the D3D12 layer) still passes. - Green (PR merged into main): 2 of 2 pass (`vulkan_graphics_shader_modules` is CPU-only; `d3d12_multi_viewport` ran on the GPU, not skipped), both without and with `LEONIDA_VK_VALIDATION=1`. - Link: gta6rt.exe built from the merged tree has no new imports vs main (693 DLL!symbol entries, identical list, from `dumpbin /imports`). - Machine: RTX 3090 24 GB, NVIDIA 621.40, Windows 11 Pro 10.0.26300, MSVC 19.44. - Prep notes by TheGeogeo's review session.
fiestorra commented 2026-11-30 11:54:15 +00:00

Independent verification on this machine (Windows 11, RTX 4090, MSVC 19.44.35226), with a negative control that bites.

1. It applies and builds. merge-tree clean onto main d367675c7; one source file plus its test.

2. With the branch: ctest -R '^vulkan_graphics_shader_modules' -> 100% tests passed, 0 failed out of 1.

3. The control - revert only the source, keep the test:

git checkout origin/main -- <the changed source>
cmake --build … --target vulkan_graphics_shader_modules_test
ctest -R '^vulkan_graphics_shader_modules'
0% tests passed, 1 tests failed out of 1

The test does not survive the revert, so it observes the change. I did not capture the failing line on this run - the target has a single test and it went from green to red, which is the fact the control exists to establish.

What I did not test: the rest of the module-resolution path, and whether the modules the change produces are the ones the console's API expects.

Why I am commenting: I verify open pull requests that replay onto current main, build the binaries their tests name, run them, then revert only the source change. 34 controls so far: 27 bite.

Written with an AI assistant.

Independent verification on this machine (Windows 11, RTX 4090, MSVC 19.44.35226), with a negative control that bites. **1. It applies and builds.** `merge-tree` clean onto `main` `d367675c7`; one source file plus its test. **2. With the branch:** `ctest -R '^vulkan_graphics_shader_modules'` -> **100% tests passed, 0 failed out of 1**. **3. The control - revert only the source, keep the test:** ``` git checkout origin/main -- <the changed source> cmake --build … --target vulkan_graphics_shader_modules_test ctest -R '^vulkan_graphics_shader_modules' 0% tests passed, 1 tests failed out of 1 ``` **The test does not survive the revert**, so it observes the change. **I did not capture the failing line** on this run - the target has a single test and it went from green to red, which is the fact the control exists to establish. **What I did not test:** the rest of the module-resolution path, and whether the modules the change produces are the ones the console's API expects. **Why I am commenting:** I verify open pull requests that replay onto current `main`, build the binaries their tests name, run them, then revert **only** the source change. **34 controls so far: 27 bite.** Written with an AI assistant.
merzleckeier commented 2026-11-30 12:53:49 +00:00

A nonmatching lookup can still call the destroy callback under the cache mutex. I tested 64572cfd merged into 497bdd039 (tree a7db4fbb) on CachyOS with Clang 23.1.5. CPU mocks only.

MEASURED. I put a scheduling checkpoint just after weak_ptr::lock() in find_locked. It holds the lookup at a live entry that will fail the key comparison. I then released the external owner, leaving the lookup’s temporary live as the last strong reference. When the mismatched entry was dismissed, its destroy callback paused. An unrelated acquisition reached its create callback in every trial, but its insertion completed only after I released the destroy callback. This happened in 3/3 trials for a device mismatch and 3/3 for a word mismatch on the same device with a locally forced hash collision. When I kept the external owner until after the lookup returned, all 6 control insertions completed while the destroy callback was still paused.

The full checked-in test passed with the PR. I also extracted just its existing duplicate-create race (case 4). It passed 3/3 with this PR and 3/3 with the unmodified main header. On main, the new result is declared before the lock_guard, so the guard is destroyed first when returning the existing entry. The remaining path above instead releases the nonmatching reference inside the lookup’s lock scope. Lookup lock · Temporary reference

AI-assisted with OpenAI Codex. Results independently checked against the raw logs.

**A nonmatching lookup can still call the destroy callback under the cache mutex.** I tested `64572cfd` merged into `497bdd039` (tree `a7db4fbb`) on CachyOS with Clang 23.1.5. CPU mocks only. **MEASURED.** I put a scheduling checkpoint just after `weak_ptr::lock()` in `find_locked`. It holds the lookup at a live entry that will fail the key comparison. I then released the external owner, leaving the lookup’s temporary `live` as the last strong reference. When the mismatched entry was dismissed, its destroy callback paused. An unrelated acquisition reached its create callback in every trial, but its insertion completed only after I released the destroy callback. This happened in 3/3 trials for a device mismatch and 3/3 for a word mismatch on the same device with a locally forced hash collision. When I kept the external owner until after the lookup returned, all 6 control insertions completed while the destroy callback was still paused. The full checked-in test passed with the PR. I also extracted just its existing duplicate-create race (case 4). It passed 3/3 with this PR and 3/3 with the unmodified `main` header. On `main`, the new `result` is declared before the `lock_guard`, so the guard is destroyed first when returning the existing entry. The remaining path above instead releases the nonmatching reference inside the lookup’s lock scope. [Lookup lock](https://github.com/ProjectLeonida/mandy/blob/64572cfd9e684a9a0807f5bac5ddbf105c890419/runtime/src/vulkan_graphics_shader_modules.h#L35-L38) · [Temporary reference](https://github.com/ProjectLeonida/mandy/blob/64572cfd9e684a9a0807f5bac5ddbf105c890419/runtime/src/vulkan_graphics_shader_modules.h#L69-L76) AI-assisted with OpenAI Codex. Results independently checked against the raw logs.
aslan2142 commented 2026-12-01 16:39:10 +00:00

Closing this PR because the legacy C++ Vulkan runtime (and legacy Python shader compiler) is now considered deprecated in favor of the new Rust Vulkan runtime (in progress) and the Rust DX12 runtime (d3d12/) available now. Thank you for the contribution! If you believe this PR was closed by mistake (for example, if it still applies to active tools, d3d12/, or general docs), please feel free to reopen it.

Closing this PR because the legacy C++ Vulkan runtime (and legacy Python shader compiler) is now considered deprecated in favor of the new Rust Vulkan runtime (in progress) and the Rust DX12 runtime (`d3d12/`) available now. Thank you for the contribution! If you believe this PR was closed by mistake (for example, if it still applies to active tools, `d3d12/`, or general docs), please feel free to reopen it.
Sign in to join this conversation.
No description provided.