runtime: unlock TitleImagePool across allocate/bind, skip full pages lock-free, and guard bad types/procs (RT-TITLE-IMAGE-POOL-LOCK-AND-GUARDS) #1926

Closed
IlyassRS3 wants to merge 1 commit from upstream-pr/1926 into main
IlyassRS3 commented 2026-11-25 15:54:40 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by IlyassRS3 on 2026-11-25T15:54:40Z.


Item ID: RT-TITLE-IMAGE-POOL-LOCK-AND-GUARDS (claim: #1608, comment 7167409068)

Problem

In leonida::TitleImagePool (runtime/src/vulkan_title_image_pool.h, used to sub-allocate small optimal title textures):

  1. Coarse mutex held across Vulkan driver calls: TitleImagePool::bind() held mutex_ across both allocate(page_size, page->type) (device_.allocate() -> vkAllocateMemory) and bind_image() (vkBindImageMemory), serializing concurrent texture creation on unrelated size classes and already-available pages behind slow page allocation and driver bind calls.
  2. Per-full-page mutex lock on every scan: iterating classes_[stride] called page->take() (locking each page's std::mutex) even on pages that were already completely full.
  3. Premature publication and stale buckets: a newly allocated page was inserted into classes_[stride] before vkBindImageMemory succeeded, and empty expired size-class buckets stayed in classes_.
  4. Missing safety guards and shift UB:
    • req.memoryTypeBits & (1u << page->type) has undefined behavior if allocate() returns a type >= 32, and an incompatible type (not in req.memoryTypeBits) was neither rejected nor freed, allowing a mismatched page to enter the pool.
    • Non-power-of-two req.alignment corrupted (needed + quantum - 1) & ~(quantum - 1) stride rounding.
    • Null image, bind_image, destroy_image, or free_memory were not checked before allocating/destroying.

Fix

  • runtime/src/vulkan_title_image_pool.h:
    • Validate !image, null Vulkan procs, non-power-of-two req.alignment, and zero needed/memoryTypeBits up front before taking mutex_.
    • Track free_slots atomically (std::atomic<std::uint32_t>) on TitleImagePage so bind() skips full pages via has_free() without acquiring each full page's std::mutex.
    • Release TitleImagePool::mutex_ before calling allocate() and bind_image().
    • Validate page->memory && page->type < 32u && (req.memoryTypeBits & (1u << page->type)) immediately after allocate() (letting ~TitleImagePage() free page->memory cleanly on failure so no VRAM leaks).
    • Publish a newly created page into classes_[stride] only after bind_image() returns VK_SUCCESS, pruning expired weak_ptrs (and keeping the already-bound image intact if weak-pointer map insertion throws std::bad_alloc).
    • Guard ~TitleImagePage() and ~PooledTitleImage() against null function pointers/page pointers.
  • runtime/test/vulkan_title_image_pool_test.cpp:
    • Keep all existing alignment, type separation, retirement, reuse, and fallback checks unchanged.
    • Add coverage for null handles/procs, non-power-of-two alignments, out-of-range (type == 32) and incompatible memory types (verifying free_memory is called and no bad page is published), failed bind_image on fresh pages, two non-blocking concurrency proofs verifying mutex_ is released during allocate() and bind_image(), and a 4-thread TSan stress test across 3 size classes and 2 memory types with intermittent bind failures.

Verification

  • AI-assisted: yes
  • GPUs tested: none (macOS host, CPU-only unit tests against Khronos Vulkan-Headers)
  • Game files used: none
  • Commands run:
    • clang++ -std=c++20 -Wall -Wextra -Werror -O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer runtime/test/vulkan_title_image_pool_test.cpp -> PASS
    • clang++ -std=c++20 -Wall -Wextra -Werror -O1 -g -fsanitize=thread -fno-omit-frame-pointer runtime/test/vulkan_title_image_pool_test.cpp -> PASS
    • clang++ -std=c++20 -Wall -Wextra -Werror -O2 runtime/test/vulkan_title_image_pool_test.cpp (x3) -> PASS
    • Downstream syntax check including runtime/src/vulkan_backend.h -> PASS
    • Negative mutation check running the new test against unpatched main:runtime/src/vulkan_title_image_pool.h -> FAILED as expected (exit 1)
    • python3 -I scripts/check_no_game_data.py runtime/src/vulkan_title_image_pool.h runtime/test/vulkan_title_image_pool_test.cpp -> PASS
    • python3 -I tests/test_text_write_line_endings.py -> PASS (3/3)
<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5494660198 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/1926). Originally posted by [IlyassRS3](https://github.com/IlyassRS3) on 2026-11-25T15:54:40Z. --- Item ID: `RT-TITLE-IMAGE-POOL-LOCK-AND-GUARDS` (claim: #1608, comment 7167409068) ## Problem In `leonida::TitleImagePool` (`runtime/src/vulkan_title_image_pool.h`, used to sub-allocate small optimal title textures): 1. **Coarse mutex held across Vulkan driver calls**: `TitleImagePool::bind()` held `mutex_` across both `allocate(page_size, page->type)` (`device_.allocate()` -> `vkAllocateMemory`) and `bind_image()` (`vkBindImageMemory`), serializing concurrent texture creation on unrelated size classes and already-available pages behind slow page allocation and driver bind calls. 2. **Per-full-page mutex lock on every scan**: iterating `classes_[stride]` called `page->take()` (locking each page's `std::mutex`) even on pages that were already completely full. 3. **Premature publication and stale buckets**: a newly allocated page was inserted into `classes_[stride]` before `vkBindImageMemory` succeeded, and empty expired size-class buckets stayed in `classes_`. 4. **Missing safety guards and shift UB**: - `req.memoryTypeBits & (1u << page->type)` has undefined behavior if `allocate()` returns a `type >= 32`, and an incompatible `type` (not in `req.memoryTypeBits`) was neither rejected nor freed, allowing a mismatched page to enter the pool. - Non-power-of-two `req.alignment` corrupted `(needed + quantum - 1) & ~(quantum - 1)` stride rounding. - Null `image`, `bind_image`, `destroy_image`, or `free_memory` were not checked before allocating/destroying. ## Fix - **`runtime/src/vulkan_title_image_pool.h`**: - Validate `!image`, null Vulkan procs, non-power-of-two `req.alignment`, and zero `needed`/`memoryTypeBits` up front before taking `mutex_`. - Track `free_slots` atomically (`std::atomic<std::uint32_t>`) on `TitleImagePage` so `bind()` skips full pages via `has_free()` without acquiring each full page's `std::mutex`. - Release `TitleImagePool::mutex_` before calling `allocate()` and `bind_image()`. - Validate `page->memory && page->type < 32u && (req.memoryTypeBits & (1u << page->type))` immediately after `allocate()` (letting `~TitleImagePage()` free `page->memory` cleanly on failure so no VRAM leaks). - Publish a newly created page into `classes_[stride]` only after `bind_image()` returns `VK_SUCCESS`, pruning expired `weak_ptr`s (and keeping the already-bound image intact if weak-pointer map insertion throws `std::bad_alloc`). - Guard `~TitleImagePage()` and `~PooledTitleImage()` against null function pointers/page pointers. - **`runtime/test/vulkan_title_image_pool_test.cpp`**: - Keep all existing alignment, type separation, retirement, reuse, and fallback checks unchanged. - Add coverage for null handles/procs, non-power-of-two alignments, out-of-range (`type == 32`) and incompatible memory types (verifying `free_memory` is called and no bad page is published), failed `bind_image` on fresh pages, two non-blocking concurrency proofs verifying `mutex_` is released during `allocate()` and `bind_image()`, and a 4-thread TSan stress test across 3 size classes and 2 memory types with intermittent bind failures. ## Verification - **AI-assisted**: yes - **GPUs tested**: none (macOS host, CPU-only unit tests against Khronos Vulkan-Headers) - **Game files used**: none - Commands run: - `clang++ -std=c++20 -Wall -Wextra -Werror -O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer runtime/test/vulkan_title_image_pool_test.cpp` -> PASS - `clang++ -std=c++20 -Wall -Wextra -Werror -O1 -g -fsanitize=thread -fno-omit-frame-pointer runtime/test/vulkan_title_image_pool_test.cpp` -> PASS - `clang++ -std=c++20 -Wall -Wextra -Werror -O2 runtime/test/vulkan_title_image_pool_test.cpp` (x3) -> PASS - Downstream syntax check including `runtime/src/vulkan_backend.h` -> PASS - Negative mutation check running the new test against unpatched `main:runtime/src/vulkan_title_image_pool.h` -> FAILED as expected (exit 1) - `python3 -I scripts/check_no_game_data.py runtime/src/vulkan_title_image_pool.h runtime/test/vulkan_title_image_pool_test.cpp` -> PASS - `python3 -I tests/test_text_write_line_endings.py` -> PASS (3/3)
copilot-pull-request-reviewer[bot] commented 2026-11-25 16:01:18 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by copilot-pull-request-reviewer[bot] on 2026-11-25T16:01:18Z.

Review: COMMENTED


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.

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6060884790 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/1926#pullrequestreview-6060884790). Originally posted by [copilot-pull-request-reviewer[bot]](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-25T16:01:18Z. **Review:** COMMENTED --- 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.
GGandCo commented 2026-11-25 16:32:16 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by GGandCo on 2026-11-25T16:32:16Z.


Native Windows/Intel verification of #1926 (0d7871f50) together with #1920, on main b0f3d3998 plus local integration fixes:

  • Intel UHD Graphics, driver 32.0.101.6314, MSVC 14.51, Vulkan SDK 1.4.363.1.
  • title_va_alias, title_window_plan, title_window_plan_bounds and vulkan_title_image_pool: 4/4 passed.
  • xmem, d3d12_xmem_placed (production batch route, no injected mapping hook), d3d12_host_prefix and d3d12_texture_memory: 4/4 passed with LEONIDA_VK_VALIDATION=1.
  • Focused staged plane/BC-array, aliased-guard and mapped single-byte WB/WC readback cases also passed. Host image copies were disabled; on-demand pipelines enabled.

Combined integration, not an isolated A/B of this PR. No successful retail load or performance improvement claimed. The full existing_heap fixture still has a pre-existing first-render-target device-loss failure on this Intel setup, reproduced before these changes; the focused cases above were run separately. No game data included. AI-assisted with OpenAI Codex.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7168138140 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/1926#issuecomment-7168138140). Originally posted by [GGandCo](https://github.com/GGandCo) on 2026-11-25T16:32:16Z. --- Native Windows/Intel verification of #1926 (0d7871f50) together with #1920, on main b0f3d3998 plus local integration fixes: - Intel UHD Graphics, driver 32.0.101.6314, MSVC 14.51, Vulkan SDK 1.4.363.1. - title_va_alias, title_window_plan, title_window_plan_bounds and vulkan_title_image_pool: 4/4 passed. - xmem, d3d12_xmem_placed (production batch route, no injected mapping hook), d3d12_host_prefix and d3d12_texture_memory: 4/4 passed with LEONIDA_VK_VALIDATION=1. - Focused staged plane/BC-array, aliased-guard and mapped single-byte WB/WC readback cases also passed. Host image copies were disabled; on-demand pipelines enabled. Combined integration, not an isolated A/B of this PR. No successful retail load or performance improvement claimed. The full existing_heap fixture still has a pre-existing first-render-target device-loss failure on this Intel setup, reproduced before these changes; the focused cases above were run separately. No game data included. AI-assisted with OpenAI Codex.
zmasi commented 2026-11-28 22:32:26 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by zmasi on 2026-11-28T22:32:26Z.


#1926 | head 0d7871f50d (merged cleanly with main c7753ed98a) | ctest --test-dir runtime/build -C RelWithDebInfo -R "^(vulkan_title_image_pool|d3d12_texture_memory|d3d12_mapped_plane_async|d3d12_xmem_placed)$" --output-on-failure (LEONIDA_VK_VALIDATION=1) | red on main: building vulkan_title_image_pool_test against main's runtime/src/vulkan_title_image_pool.h fails at line 111: !pool.bind(VK_NULL_HANDLE, VK_NULL_HANDLE, good_req, bind_image, destroy_image, free_memory, no_alloc) | green on PR+main: 4/4 isolated CTests pass on RTX 3090 (vulkan_title_image_pool alignment/type-separation/retirement/reuse/concurrency/guards, d3d12_texture_memory 256 textures: 256 in 1 blocks of 67108864 bytes, d3d12_mapped_plane_async, and d3d12_xmem_placed) with 0 Khronos validation errors; test_text_write_line_endings.py 3/3 and check_no_game_data.py 0 violations | Windows 11, MSVC 19.44, RTX 3090, Vulkan SDK 1.4.363.1 | AI-assisted: yes

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7246807196 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/1926#issuecomment-7246807196). Originally posted by [zmasi](https://github.com/zmasi) on 2026-11-28T22:32:26Z. --- #1926 | head 0d7871f50dea6f4d604ef33891bff14197864063 (merged cleanly with main c7753ed98a56677f10e34078b37eab0540e190ec) | `ctest --test-dir runtime/build -C RelWithDebInfo -R "^(vulkan_title_image_pool|d3d12_texture_memory|d3d12_mapped_plane_async|d3d12_xmem_placed)$" --output-on-failure` (`LEONIDA_VK_VALIDATION=1`) | red on main: building `vulkan_title_image_pool_test` against `main`'s `runtime/src/vulkan_title_image_pool.h` fails at `line 111: !pool.bind(VK_NULL_HANDLE, VK_NULL_HANDLE, good_req, bind_image, destroy_image, free_memory, no_alloc)` | green on PR+main: `4/4` isolated CTests pass on RTX 3090 (`vulkan_title_image_pool` alignment/type-separation/retirement/reuse/concurrency/guards, `d3d12_texture_memory` `256 textures: 256 in 1 blocks of 67108864 bytes`, `d3d12_mapped_plane_async`, and `d3d12_xmem_placed`) with `0` Khronos validation errors; `test_text_write_line_endings.py` `3/3` and `check_no_game_data.py` `0` violations | Windows 11, MSVC 19.44, RTX 3090, Vulkan SDK 1.4.363.1 | AI-assisted: yes
aslan2142 commented 2026-12-01 16:39:00 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by aslan2142 on 2026-12-01T16:39:00Z.


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.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7317962410 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/1926#issuecomment-7317962410). Originally posted by [aslan2142](https://github.com/aslan2142) on 2026-12-01T16:39:00Z. --- 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.

Pull request closed

Sign in to join this conversation.
No reviewers
No labels
No milestone
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.

Reference
ProjectLeonida/mandy!1926
No description provided.