runtime: share indirect clamp buffers across queue families and fix safety bugs #1832

Manually merged
github merged 1 commit from gh-pr/1832/head into gh-pr/1832/base 2026-11-26 10:07:36 +00:00
Owner

@⁠IlyassRS3 on GitHub · 2026-11-25 12:46 UTC · original
IlyassRS3:fix/rt-indirect-clamp-sharing-and-safety → main · +478 −21 · 6 files · 1 commits · merged 2026-11-25 19:27 UTC

Item ID: RT-INDIRECT-CLAMP-SHARING-AND-SAFETY
Claim: #1608

Summary

Fixes queue-family sharing and four safety/correctness issues in IndirectArgumentClamp (runtime/src/vulkan_indirect_clamp.h) and its ScratchBuffers overload (runtime/src/vulkan_scratch.h) when indirect clamping runs across graphics and async-compute queues during world rendering:

  1. Multi-queue-family sharing (VK_SHARING_MODE_CONCURRENT) on both scratch chunks and HostArea counter buffers
    • enable_indirect_clamp() previously did not receive state_.families (unlike enable_copy_scratch() 10 lines earlier in runtime/shims/d3d12_vulkan_device.cpp).
    • Added an optional std::vector<std::uint32_t> families = {} parameter to the explicit-usage ScratchBuffers constructor (runtime/src/vulkan_scratch.h), IndirectArgumentClamp, and VulkanContext::enable_indirect_clamp(), and forwarded state_.families from runtime/shims/d3d12_vulkan_device.cpp.
    • IndirectArgumentClamp::make_area() now calls share_across_queue_families(info, families_) on the host-visible counter buffer as well, because direct and async-compute queues copy counter slots into the same HostArea::buffer.
  2. Prevent VkDeviceMemory leak on vkBindBufferMemory retry + strong exception safety in make_area() / Batch::prepare()
    • make_area() looped over candidate host-visible memory types and allocated a new VkDeviceMemory each iteration without freeing the failed allocation when vkBindBufferMemory failed, leaking device memory. Now frees area.memory before retrying, and cleans up area.buffer/area.memory if areas_.push_back or free_slots_.reserve throws.
    • Batch::prepare() now releases the claimed slot if slots_.push_back(slot) throws.
  3. Zero released HostArea counter slots to avoid double-counting on aborted batches
    • IndirectArgumentClamp::release() read the 4 counter words from area.host and pushed the slot onto LIFO free_slots_ without zeroing them. If a later batch reused that slot and was destroyed without submitting to the GPU (e.g., failed replay or failed vkQueueSubmit), ~Batch() called release(slots_, true) and re-added the prior submission's counters.
    • Now clears the 4 counter words (std::memset(words, 0, 4 * sizeof(std::uint32_t))) right after reading them.
  4. Reject non-4-byte-aligned argument_offset and count_offset
    • indirect_clamp.comp reads uint words via BDA (arguments_va + argument_offset, count_va + count_offset). prepare() checked stride % 4, but not argument_offset % 4 or count_offset % 4. Now rejects misaligned offsets cleanly via fallback(...).
  5. Guard areas_[slot.area].buffer read under mutex_
    • Moved out.stats_buffer = ... areas_[slot.area].buffer into the existing std::lock_guard lock(mutex_) block 2 lines below in prepare(), removing the unlocked read of areas_ without adding any extra lock acquisition.

Tests

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

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

  • indirect_clamp_safety_test: PASS under ASan+UBSan, PASS under TSan (0 races), PASS under -O2 (3 consecutive runs), -Wall -Wextra -Werror -Wno-missing-field-initializers.
  • Existing vulkan_scratch_test: PASS under ASan+UBSan.
  • Compile-checked replay_pipeline_compiles_test.cpp and depth24_convert_test.cpp against the updated headers.
  • Mutation check against main's vulkan_indirect_clamp.h + vulkan_scratch.h: fails 11 assertions across sharing mode, vkBindBufferMemory retry leak, stale counter double-count, and misaligned offset acceptance.
  • 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 runtime validation relies on CI / reviewers)
**@⁠IlyassRS3** on GitHub · 2026-11-25 12:46 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1832) `IlyassRS3:fix/rt-indirect-clamp-sharing-and-safety` → `main` · +478 −21 · 6 files · 1 commits · merged 2026-11-25 19:27 UTC Item ID: `RT-INDIRECT-CLAMP-SHARING-AND-SAFETY` Claim: https://git.gtahub.st/github/ubiquitarianism--leonida/issues/1608 ## Summary Fixes queue-family sharing and four safety/correctness issues in `IndirectArgumentClamp` (`runtime/src/vulkan_indirect_clamp.h`) and its `ScratchBuffers` overload (`runtime/src/vulkan_scratch.h`) when indirect clamping runs across graphics and async-compute queues during world rendering: 1. **Multi-queue-family sharing (`VK_SHARING_MODE_CONCURRENT`) on both scratch chunks and `HostArea` counter buffers** - `enable_indirect_clamp()` previously did not receive `state_.families` (unlike `enable_copy_scratch()` 10 lines earlier in `runtime/shims/d3d12_vulkan_device.cpp`). - Added an optional `std::vector<std::uint32_t> families = {}` parameter to the explicit-usage `ScratchBuffers` constructor (`runtime/src/vulkan_scratch.h`), `IndirectArgumentClamp`, and `VulkanContext::enable_indirect_clamp()`, and forwarded `state_.families` from `runtime/shims/d3d12_vulkan_device.cpp`. - `IndirectArgumentClamp::make_area()` now calls `share_across_queue_families(info, families_)` on the host-visible counter buffer as well, because direct and async-compute queues copy counter slots into the same `HostArea::buffer`. 2. **Prevent `VkDeviceMemory` leak on `vkBindBufferMemory` retry + strong exception safety in `make_area()` / `Batch::prepare()`** - `make_area()` looped over candidate host-visible memory types and allocated a new `VkDeviceMemory` each iteration without freeing the failed allocation when `vkBindBufferMemory` failed, leaking device memory. Now frees `area.memory` before retrying, and cleans up `area.buffer`/`area.memory` if `areas_.push_back` or `free_slots_.reserve` throws. - `Batch::prepare()` now releases the claimed slot if `slots_.push_back(slot)` throws. 3. **Zero released `HostArea` counter slots to avoid double-counting on aborted batches** - `IndirectArgumentClamp::release()` read the 4 counter words from `area.host` and pushed the slot onto LIFO `free_slots_` without zeroing them. If a later batch reused that slot and was destroyed without submitting to the GPU (e.g., failed replay or failed `vkQueueSubmit`), `~Batch()` called `release(slots_, true)` and re-added the prior submission's counters. - Now clears the 4 counter words (`std::memset(words, 0, 4 * sizeof(std::uint32_t))`) right after reading them. 4. **Reject non-4-byte-aligned `argument_offset` and `count_offset`** - `indirect_clamp.comp` reads `uint` words via BDA (`arguments_va + argument_offset`, `count_va + count_offset`). `prepare()` checked `stride % 4`, but not `argument_offset % 4` or `count_offset % 4`. Now rejects misaligned offsets cleanly via `fallback(...)`. 5. **Guard `areas_[slot.area].buffer` read under `mutex_`** - Moved `out.stats_buffer = ... areas_[slot.area].buffer` into the existing `std::lock_guard lock(mutex_)` block 2 lines below in `prepare()`, removing the unlocked read of `areas_` without adding any extra lock acquisition. ## Tests Added pure-CPU mock-Vulkan test `runtime/test/indirect_clamp_safety_test.cpp` (registered as CTest `indirect_clamp_safety` under `if(TARGET Vulkan::Headers)` in `runtime/CMakeLists.txt`). Verified locally on macOS arm64 (Apple Clang) using the pinned Khronos `Vulkan-Headers` (`6802bb4733b63ed5efd3adb308a6c885ef180ea1`): - `indirect_clamp_safety_test`: PASS under ASan+UBSan, PASS under TSan (0 races), PASS under `-O2` (3 consecutive runs), `-Wall -Wextra -Werror -Wno-missing-field-initializers`. - Existing `vulkan_scratch_test`: PASS under ASan+UBSan. - Compile-checked `replay_pipeline_compiles_test.cpp` and `depth24_convert_test.cpp` against the updated headers. - Mutation check against `main`'s `vulkan_indirect_clamp.h` + `vulkan_scratch.h`: fails 11 assertions across sharing mode, `vkBindBufferMemory` retry leak, stale counter double-count, and misaligned offset acceptance. - 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 runtime validation relies on CI / reviewers)
Pass device queue families into IndirectArgumentClamp and its ScratchBuffers so both clamped-argument scratch chunks and HostArea counter buffers are created with VK_SHARING_MODE_CONCURRENT when graphics and async-compute families differ (matching enable_copy_scratch).

Also fix four safety/correctness issues in runtime/src/vulkan_indirect_clamp.h:
- Free VkDeviceMemory before retrying the next memory type when vkBindBufferMemory fails in make_area(), and guard vector push_back against allocation failure.
- Zero released HostArea counter words after reading them so a later aborted/unsubmitted batch reusing the same slot never double-counts prior counters.
- Reject non-4-byte-aligned argument_offset and count_offset in prepare() (the compute clamp reads uint32 words via BDA).
- Read areas_[slot.area].buffer under mutex_ in prepare().

Item ID: RT-INDIRECT-CLAMP-SHARING-AND-SAFETY
Claim: https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7162686562
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:07:34 +00:00
github manually merged commit 9428f57da2 into gh-pr/1832/base 2026-11-26 10:07:36 +00:00
Author
Owner

@⁠copilot-pull-request-reviewer[bot] on GitHub · 2026-11-25 12:47 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:47 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1832#pullrequestreview-6057874691) · **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

@⁠potatoe0100 on GitHub · 2026-11-25 13:50 UTC · original

Tested 9428f57da merged onto main 98c2f7777 (clean), native Windows 11 Pro 26H2 (build 26300), NVIDIA GeForce RTX 4060, driver 621.14, VS 2022 (MSVC 19.44) RelWithDebInfo + Ninja.

  • indirect_clamp_safety passes. Full ctest -j 6: all pass apart from xmem_no_write_watch, which failed while another build was running on this PC; xmem failed the same way in the main run under that load.
  • run_gpu_tests.py: 209/263 passed, 53 skipped, identical to main (cs_imgatomic_ext fails on main too).

AI-assisted (Claude)

**@⁠potatoe0100** on GitHub · 2026-11-25 13:50 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1832#issuecomment-7164369989) Tested `9428f57da` merged onto `main` `98c2f7777` (clean), native Windows 11 Pro 26H2 (build 26300), NVIDIA GeForce RTX 4060, driver 621.14, VS 2022 (MSVC 19.44) RelWithDebInfo + Ninja. - `indirect_clamp_safety` passes. Full `ctest -j 6`: all pass apart from `xmem_no_write_watch`, which failed while another build was running on this PC; `xmem` failed the same way in the `main` run under that load. - `run_gpu_tests.py`: 209/263 passed, 53 skipped, identical to `main` (`cs_imgatomic_ext` fails on `main` too). AI-assisted (Claude)
Author
Owner

@⁠Timon360SB on GitHub · 2026-11-25 13:52 UTC · original

Independent verification — Turing and Blackwell

Tested the PR on two NVIDIA architectures under native Windows, comparing the exact merge base against the PR head.

  • Base: 0d80bc5df7c873f40965f34f185cb96913786765
  • Head: 9428f57da22a4693885a5671c61789ddd8bd664d

Environment

Configuration RTX 5070 RTX 2060 SUPER
Architecture Blackwell Turing
VRAM 12 GB 8 GB
NVIDIA driver 621.14 621.14
Windows 11 build 26200 28000
Vulkan device API 1.4.357 1.4.357
Vulkan SDK 1.4.363.0 1.4.363.0
Khronos validation layer 1.4.363 1.4.363
Subgroup size 32 32
Upload memory VRAM / ReBAR System memory / no ReBAR

MSVC 19.44.35230, Ninja Multi-Config, RelWithDebInfo.

Three repetitions per revision, GPU and validation configuration. Validated runs requested core validation, GPU-assisted validation and synchronization validation.

Results

Configuration Base PASS / FAIL / SKIP Head PASS / FAIL / SKIP
RTX 5070, validation off 21 / 0 / 3 21 / 0 / 3
RTX 5070, validation on 24 / 0 / 0 24 / 0 / 0
RTX 2060 SUPER, validation off 21 / 0 / 3 21 / 0 / 3
RTX 2060 SUPER, validation on 24 / 0 / 0 24 / 0 / 0
Total 90 / 0 / 6 90 / 0 / 6

All 24 CTest sessions completed successfully.

Across 192 scheduled test executions: 180 passed, 12 expected skips, 0 failures.

Individual tests

Test Base Head
indirect_clamp 12/12 12/12
indirect_dispatch_count_alloc 12/12 12/12
d3d12_indirect_group_budget 12/12 12/12
d3d12_indirect_dispatch_count 12/12 12/12
d3d12_stateful_indirect_pixels 12/12 12/12
d3d12_stateful_indirect_counted_pixels 12/12 12/12
d3d12_graphics_indirect_heap_resources 12/12 12/12
vk_sync_validation 6/6 6/6

The synchronization validation self-test was skipped when
validation was disabled, as intended.

Reproducible counter difference

One measurable difference was observed in indirect_clamp.

Base:

73 record(s) clamped in 4113 call(s), 1 count(s),
validation errors 0

Head:

72 record(s) clamped in 4113 call(s), 1 count(s),
validation errors 0

This difference reproduced in all 12 executions per revision
across both GPUs and both validation configurations.

The call count and clamped-count total remain unchanged.
In-range records remain bit-identical and the budget
saturation checks continue to pass.

This is consistent with the stale counter-slot
double-counting fix described in the PR, although these
runs do not independently isolate that mechanism.

GPU readback and validation

  • All eight native WARP / Vulkan counted
    ExecuteIndirect(DISPATCH) comparisons passed in every run.
  • All six indirect group budget cases passed in every run.
  • Stateful DRAW and DRAW_INDEXED tests reported
    zero RGBA mismatches across 1,966,080 pixel checks
    in total, including direct and indirect controls.
  • Heap-resource tests confirmed exact VS heap state and
    PS resource payloads across three indirect draws and
    two direct controls per execution.
  • The synchronization validation self-test detected the
    intentional WRITE_AFTER_WRITE hazard without a barrier
    and reported zero errors with the barrier.
  • No unexpected Vulkan validation errors were found
    in the captured test logs.

Conclusion

No regressions observed in the eight selected CTest
scenarios on either Turing or Blackwell.

The reproducible 73-to-72 counter change provides an
additional observable result consistent with the
counter-reset correction.

Coverage limitations: the new indirect_clamp_safety
mock-Vulkan test, fault-injection scenarios, dedicated
multi-queue-family stress testing and the full CTest suite
were not included in this run.

Synthetic tests only. No game files used.

AI-assisted: yes, test automation and result analysis.

**@⁠Timon360SB** on GitHub · 2026-11-25 13:52 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1832#issuecomment-7164417769) ## Independent verification — Turing and Blackwell Tested the PR on two NVIDIA architectures under native Windows, comparing the exact merge base against the PR head. - **Base:** `0d80bc5df7c873f40965f34f185cb96913786765` - **Head:** `9428f57da22a4693885a5671c61789ddd8bd664d` ### Environment | Configuration | RTX 5070 | RTX 2060 SUPER | |---|---|---| | Architecture | Blackwell | Turing | | VRAM | 12 GB | 8 GB | | NVIDIA driver | 621.14 | 621.14 | | Windows 11 build | 26200 | 28000 | | Vulkan device API | 1.4.357 | 1.4.357 | | Vulkan SDK | 1.4.363.0 | 1.4.363.0 | | Khronos validation layer | 1.4.363 | 1.4.363 | | Subgroup size | 32 | 32 | | Upload memory | VRAM / ReBAR | System memory / no ReBAR | MSVC 19.44.35230, Ninja Multi-Config, RelWithDebInfo. Three repetitions per revision, GPU and validation configuration. Validated runs requested core validation, GPU-assisted validation and synchronization validation. ### Results | Configuration | Base PASS / FAIL / SKIP | Head PASS / FAIL / SKIP | |---|---:|---:| | RTX 5070, validation off | 21 / 0 / 3 | 21 / 0 / 3 | | RTX 5070, validation on | 24 / 0 / 0 | 24 / 0 / 0 | | RTX 2060 SUPER, validation off | 21 / 0 / 3 | 21 / 0 / 3 | | RTX 2060 SUPER, validation on | 24 / 0 / 0 | 24 / 0 / 0 | | **Total** | **90 / 0 / 6** | **90 / 0 / 6** | All 24 CTest sessions completed successfully. Across 192 scheduled test executions: **180 passed, 12 expected skips, 0 failures**. ### Individual tests | Test | Base | Head | |---|---:|---:| | `indirect_clamp` | 12/12 | 12/12 | | `indirect_dispatch_count_alloc` | 12/12 | 12/12 | | `d3d12_indirect_group_budget` | 12/12 | 12/12 | | `d3d12_indirect_dispatch_count` | 12/12 | 12/12 | | `d3d12_stateful_indirect_pixels` | 12/12 | 12/12 | | `d3d12_stateful_indirect_counted_pixels` | 12/12 | 12/12 | | `d3d12_graphics_indirect_heap_resources` | 12/12 | 12/12 | | `vk_sync_validation` | 6/6 | 6/6 | The synchronization validation self-test was skipped when validation was disabled, as intended. ### Reproducible counter difference One measurable difference was observed in `indirect_clamp`. Base: ```text 73 record(s) clamped in 4113 call(s), 1 count(s), validation errors 0 ``` Head: ```text 72 record(s) clamped in 4113 call(s), 1 count(s), validation errors 0 ``` This difference reproduced in all 12 executions per revision across both GPUs and both validation configurations. The call count and clamped-count total remain unchanged. In-range records remain bit-identical and the budget saturation checks continue to pass. This is consistent with the stale counter-slot double-counting fix described in the PR, although these runs do not independently isolate that mechanism. ### GPU readback and validation - All eight native WARP / Vulkan counted ExecuteIndirect(DISPATCH) comparisons passed in every run. - All six indirect group budget cases passed in every run. - Stateful DRAW and DRAW_INDEXED tests reported zero RGBA mismatches across 1,966,080 pixel checks in total, including direct and indirect controls. - Heap-resource tests confirmed exact VS heap state and PS resource payloads across three indirect draws and two direct controls per execution. - The synchronization validation self-test detected the intentional WRITE_AFTER_WRITE hazard without a barrier and reported zero errors with the barrier. - No unexpected Vulkan validation errors were found in the captured test logs. ### Conclusion No regressions observed in the eight selected CTest scenarios on either Turing or Blackwell. The reproducible 73-to-72 counter change provides an additional observable result consistent with the counter-reset correction. Coverage limitations: the new `indirect_clamp_safety` mock-Vulkan test, fault-injection scenarios, dedicated multi-queue-family stress testing and the full CTest suite were not included in this run. Synthetic tests only. No game files used. AI-assisted: yes, test automation and result analysis.
Author
Owner

@⁠aslan2142 on GitHub · 2026-11-25 19:27 UTC · original

Merged, thanks! Tested 9428f57da merged onto main with the full Windows suite under Wine (llvmpipe and a RADV iGPU): indirect_clamp_safety is the only change from main, and it passes on both devices. Built against main's headers (families argument dropped, checks made non-fatal), 11 of its checks fail there: the queue-family sharing, the cleanup after a failed bind, the counter zeroing and the offset alignment.

  • Checked on main e48ff0374 + 9428f57da: it merges cleanly; the semantic suite passes (491 files, 6,312 tests, 0 files failed); the 15 docs and writer tests pass; check_no_game_data.py is clean on the 6 changed files.

AI-assisted (Claude Code, Claude Opus 5.5).

**@⁠aslan2142** on GitHub · 2026-11-25 19:27 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1832#issuecomment-7172316649) Merged, thanks! Tested `9428f57da` merged onto `main` with the full Windows suite under Wine (llvmpipe and a RADV iGPU): `indirect_clamp_safety` is the only change from `main`, and it passes on both devices. Built against `main`'s headers (families argument dropped, checks made non-fatal), 11 of its checks fail there: the queue-family sharing, the cleanup after a failed bind, the counter zeroing and the offset alignment. - **Checked on `main` `e48ff0374` + `9428f57da`:** it merges cleanly; the semantic suite passes (491 files, 6,312 tests, 0 files failed); the 15 docs and writer tests pass; `check_no_game_data.py` is clean on the 6 changed files. AI-assisted (Claude Code, Claude Opus 5.5).
This discussion has been locked. Commenting is limited to contributors.
No description provided.