Skip to content

runtime: BAR-aware memory fallback and bounded KHR/XDXR stage/query pools (RT-VK-MEMORY-FALLBACK-AND-STAGE-POOL-CAPS) - #1874

Open
IlyassRS3 wants to merge 1 commit into
ProjectLeonida:mainfrom
IlyassRS3:fix/vk-memory-fallback-and-stage-pool-caps
Open

IlyassRS3 wants to merge 1 commit into
ProjectLeonida:mainfrom
IlyassRS3:fix/vk-memory-fallback-and-stage-pool-caps

Conversation

@IlyassRS3

Copy link
Copy Markdown
Contributor

Item: RT-VK-MEMORY-FALLBACK-AND-STAGE-POOL-CAPS
Claim: #1608 (comment)

Summary

Fixes three ad-hoc single-type vkAllocateMemory helpers and unbounded per-queue acceleration-structure staging/query pools on the multi-frame world rendering path:

  1. BAR-aware memory fallback and heap-size validation (runtime/src/vulkan_backend.h, runtime/src/vulkan_present_compose.h):

    • Added detail::device_memory_order and detail::host_stage_memory_order over leonida::memory_type_order + resizable_bar() (with a fallback for synthetic zero-heap mocks such as replay_query_edges_test.cpp where memoryHeapCount == 0).
    • PresentComposer::ensure_target: guards zero width/height before vkCreateImage (VUID-VkImageCreateInfo-extent-00944), avoids placing never-mapped RGBA16F compose targets in a 256 MiB non-ReBAR window when pure VRAM is available, skips undersized heaps (VUID-vkAllocateMemory-pAllocateInfo-01713), and retries remaining compatible types (including system RAM and host-only devices) on vkAllocateMemory failure while clearing failed handles before retry.
    • OcclusionResolve::initialize: applies the same BAR-aware ordering, heap-size filtering, OOM retry loop, and cleanup on vkBindBufferMemory failure.
    • VulkanQueue::acquire_stage (KHR TLAS ARRAY_OF_POINTERS and XDXR BLAS-address table staging): prefers DEVICE_LOCAL on Resizable BAR GPUs and system RAM (!DEVICE_LOCAL) on non-ReBAR GPUs so per-frame staging does not exhaust the 256 MiB BAR window, skips undersized heaps, and retries remaining host-visible coherent types on OOM.
  2. Bounded pools, pre-prepare reclamation, and best-fit reuse (runtime/src/vulkan_backend.h):

    • Added VulkanQueue::recycle_completed_khr_pools() so acquire_stage() and allocate_khr_as_queries() reclaim KHR/XDXR stages and postbuild VkQueryPools from already-completed command slots before prepare() allocates fresh ones (previously recycle_finished() ran in acquire() after prepare(), causing steady frame-to-frame traffic to double-allocate).
    • Switched acquire_stage() and allocate_khr_as_queries() to best-fit selection (smallest sufficient pooled entry).
    • Capped khr_stage_pool_ and khr_as_query_pool_ at 8 entries (kMaxPooledKhrStages / kMaxPooledKhrAsQueries), keeping the largest stages/pools and destroying evicted allocations immediately so monotonically growing title_va_aliases tables or TLAS bursts do not accumulate leaked VkDeviceMemory/VkQueryPool handles over sustained streaming.
  3. Regression test (runtime/test/vk_memory_fallback_and_pools_test.cpp, runtime/CMakeLists.txt):

    • Portable CPU/mock Vulkan test covering zero-extent rejection, non-ReBAR BAR avoidance, VRAM -> BAR -> RAM OOM fallback, ReBAR preference/fallback, undersized-heap skipping, host-only devices, synthetic zero-heap mock compatibility, failed-handle clearing, 32-step growing XDXR table & 16-build burst pool caps, 24-step growing KHR postbuild query pool caps, and best-fit + pre-prepare reuse.

Verification

  • AI-assisted: yes
  • GPUs tested: none (CPU/mock Vulkan verification on macOS arm64 with pinned Khronos Vulkan-Headers 6802bb4733b63ed5efd3adb308a6c885ef180ea1)
  • vk_memory_fallback_and_pools_test.cpp:
    • clang++ -std=c++20 -Wall -Wextra -Werror ... -fsanitize=address,undefined -> vk_memory_fallback_and_pools: ok
    • clang++ -std=c++20 -Wall -Wextra -Werror ... -fsanitize=thread -> vk_memory_fallback_and_pools: ok
    • clang++ -std=c++20 -Wall -Wextra -Werror ... -O2 (3 runs) -> vk_memory_fallback_and_pools: ok
  • Existing tests under ASan+UBSan:
    • vk_host_at_aliasing_test.cpp -> vk_host_at_aliasing: ok
    • replay_query_edges_test.cpp -> passed
    • replay_khr_as_copy_postbuild_test.cpp -> passed
  • Mutation test (running the new test against unmodified main vulkan_backend.h and vulkan_present_compose.h): 25 failures reproduced cleanly, exit code 1.
  • Hygiene:
    • python3 -I scripts/check_no_game_data.py runtime/src/vulkan_backend.h runtime/src/vulkan_present_compose.h runtime/test/vk_memory_fallback_and_pools_test.cpp runtime/CMakeLists.txt -> OK
    • python3 -I tests/test_text_write_line_endings.py -> 3 tests OK

…ools

- Replace single-type vkAllocateMemory picks in PresentComposer::ensure_target,
  OcclusionResolve::initialize, and VulkanQueue::acquire_stage with ordered
  memory_type_order + BAR-aware fallback and OOM retry across compatible types,
  enforcing heap-size bounds (VUID-vkAllocateMemory-pAllocateInfo-01713) and
  clearing memory handles on failed allocation attempts.
- Reject zero-extent compose targets in PresentComposer::ensure_target before
  vkCreateImage (VUID-VkImageCreateInfo-extent-00944).
- Reclaim completed slots' KHR/XDXR stages and postbuild query pools before
  prepare() allocates fresh ones, switch pool selection to best-fit, and cap
  khr_stage_pool_ and khr_as_query_pool_ at 8 largest entries so growing world
  streaming tables do not leak VkDeviceMemory/VkQueryPool allocations.

Item: RT-VK-MEMORY-FALLBACK-AND-STAGE-POOL-CAPS
Copilot AI balanced review requested due to automatic review settings November 25, 2026 13:49

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@Timon360SB

Copy link
Copy Markdown
Contributor

Independent verification — Turing and Blackwell

  • Base: 5e95fa2f46d5df1a8397d5ee871add369031d8b6
  • Head: 6fbb6552efae6f8c091777899318d72e111ddcee

Environment

GPU Windows 11 build
RTX 5070 (Blackwell) 26200
RTX 2060 SUPER (Turing) 28000

NVIDIA 621.14, Vulkan SDK 1.4.363.0,
MSVC 19.44.35230, Ninja RelWithDebInfo.

Three repetitions per GPU, revision and validation mode.
The new mock-Vulkan test was run once per system on HEAD.

Results

Test Base Head
vk_presenter_capture_colour 12/12 12/12
vk_binary_occlusion 12/12 12/12
vk_overlapping_occlusion 12/12 12/12
vk_xdxr_postbuild_readback 12/12 12/12
replay_query_edges 12/12 12/12
replay_khr_as_copy_postbuild 12/12 12/12
vk_memory_fallback_and_pools N/A 2/2
Total 72/72 74/74

146 executions: 146 passed, 0 failed, 0 skipped.

Findings

  • The new memory fallback and pool-cap mock test
    passes under Windows/MSVC on both systems.
  • Binary occlusion: 1026 visible, 3 zero and 3 repeated;
    offsets and sentinels exact.
  • Overlapping occlusion: 261 segments summed correctly.
  • XDXR postbuild readback: reported_size=320,
    expected=320, compute_to_host_barriers=1.
  • No VUID diagnostics in the captured logs.
    Validation-layer feature-adjustment warnings were present.

No regressions observed on either architecture.
Allocation fallback and pool limits were covered by the
new mock test; physical BAR exhaustion and long-running
world-rendering workloads were not exercised.

Synthetic tests only. No game files used.
AI-assisted: yes.

@zmasi

zmasi commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

Independent Hardware Verification & Cross-PR Interaction Note (RTX 3090, Windows 11)

  • Tested merge: origin/main (04f484006e) + PR #1874 (6fbb6552ef) — clean 3-way merge (0 conflicts).
  • Environment: NVIDIA GeForce RTX 3090 (24 GB, Resizable BAR), Windows 11, Visual Studio 2022 (MSVC 19.44 RelWithDebInfo), Vulkan SDK + VK_LAYER_KHRONOS_validation 1.4.363.1 (LEONIDA_VK_VALIDATION=1).

Red -> Green Results

  1. Red (vk_memory_fallback_and_pools against origin/main's vulkan_backend.h and vulkan_present_compose.h):
    • Failed as expected (rc=8, vk_memory_fallback_and_pools: 25 failure(s) across zero-extent guard, BAR-aware ordering/OOM retries, undersized-heap filtering, best-fit reuse, and stage/query pool caps).
  2. Green (origin/main 04f484006e + #1874 6fbb6552ef, LEONIDA_VK_VALIDATION=1):
    • 7/7 CTests passed (1.70 s total, 0 Vulkan validation errors):
      • vk_presenter_capture_colour: Passed (0.06 s)
      • vk_overlapping_occlusion: Passed (0.37 s, 261 segments summed; alternating binary results 1/1; resolve inside an active query 4)
      • vk_binary_occlusion: Passed (0.40 s, 1026 visible, 3 zero, 3 repeated)
      • replay_khr_as_copy_postbuild: Passed (0.06 s)
      • replay_query_edges: Passed (0.11 s)
      • vk_xdxr_postbuild_readback: Passed (0.37 s, compute_to_host_barriers=1, reported_size=320, expected=320)
      • vk_memory_fallback_and_pools: Passed (0.10 s)
    • python -m unittest tests/test_ctest_registration.py tests/test_text_write_line_endings.py: 10/10 passed.
    • python -I scripts/check_no_game_data.py across all 4 touched files: passed (0 issues). No game files used.

Heads-Up: Zero-Conflict CI Interaction with Open PR #1681

  • Merging #1874 (6fbb6552ef) + #1681 (86eb22f7e8) onto origin/main (04f484006e) succeeds with zero Git conflicts (git merge-tree / git merge rc=0), but vk_memory_fallback_and_pools fails 2 assertions (rc=8):
    • FAIL: PresentComposer tries VRAM (1) -> BAR (0) -> RAM (2) in order
    • FAIL: OcclusionResolve tries VRAM (1) -> BAR (0) -> RAM (2)
  • Why: #1681 updates leonida::memory_type_order(memory, type_bits, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, size) in runtime/src/vulkan_memory.h so that bar_window_type (DEVICE_LOCAL | HOST_VISIBLE in a <= 256 MiB heap) is placed last after system RAM ({1, 2, 0} on make_non_rebar_props()), reserving the BAR window for the arena. In #1874, detail::device_memory_order calls memory_type_order(..., 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, size) and applies std::stable_partition for device_local && !small_bar, which leaves {1, 2, 0} (VRAM -> RAM -> BAR) unchanged once #1681 is present; when drv.fail_memory_types = {1, 0} is injected, type 2 succeeds on attempt 2 ({1, 2}) instead of {1, 0, 2}.
  • Resolution for whichever PR lands second:
    • If compose targets and occlusion scratch should match #1681 and leave the 256 MiB BAR window to the arena (VRAM -> RAM -> BAR), update those two OOM order checks in vk_memory_fallback_and_pools_test.cpp (fail {1, 2} and expect {1, 2, 0}).
    • Conversely, if never-mapped compose/occlusion allocations intentionally prefer VRAM -> BAR -> RAM before host RAM, detail::device_memory_order needs a second partition pass placing device_local && small_bar ahead of !device_local.

AI-assisted: yes

@OreoFR

OreoFR commented Nov 29, 2026

Copy link
Copy Markdown
Collaborator

Verified by OreoFR — READY

  • Base: main c8bf0e7 + this PR (head 6fbb655) merged with --no-ff
  • Red (main + only this PR's tests): vk_memory_fallback_and_pools fails on main, for example zero width rejected before vkCreateImage, PresentComposer picks pure VRAM (type 1) before 256 MiB BAR (type 0) and PresentComposer falls back to host RAM when VRAM and BAR OOM. The test's CMake registration was kept for the red run.
  • Green (merge): vk_memory_fallback_and_pools passes; ctest (Ninja RelWithDebInfo, all targets, gta6rt launchers excluded) in package p2 = main + runtime: BAR-aware memory fallback and bounded KHR/XDXR stage/query pools (RT-VK-MEMORY-FALLBACK-AND-STAGE-POOL-CAPS) #1874 + d3d12: stage title textures when their format or usage rules out host copies #1894 + vulkan: coalesce equal image layout ranges (VK-IMAGE-LAYOUT-RANGE-COALESCING) #1713 (no shared files): 495 tests, new failures vs main: none (main alone: 494 tests, 5 failures: loader, xs_proxy_mock, xmem_no_write_watch, api_ref_state timeout, xbox_present; xbox_present fails in every package as on main)
  • gta6rt.exe links without the XMA decoder (LEONIDA_CARGO=OFF, LEONIDA_XMA2_DECODER_LIB empty), main + this PR alone; imports unchanged vs main (25 DLLs, 655 functions, no WS2_32)
  • Diff read: no issue (the fallback loops free memory, the pool caps destroy what they evict, and recycling only touches completed tickets).
  • Other runs: Consistent with zmasi's and Timon360SB's runs.
  • Machine: Windows 11, Intel Core Ultra 7 155H, RTX 4070 Laptop 8 GB, NVIDIA 621.40, Python 3.12.10, MSVC 19.44

AI-assisted (Claude Code, Claude Opus 5.5), run for OreoFR.

@fiestorra

Copy link
Copy Markdown
Contributor

Independent verification on this machine (Windows 11, MSVC 19.44.35226): this pull request applies and builds, and its own new test then fails - and the reason is how far main has moved under it, not the hardware.

1. It applies. merge-tree clean; 6fbb6552e cherry-picks onto main dcba958e5 without a conflict. Four files: runtime/CMakeLists.txt, runtime/src/vulkan_backend.h, runtime/src/vulkan_present_compose.h and the new runtime/test/vk_memory_fallback_and_pools_test.cpp.

2. It builds, and the test is not hardware-dependent - its own header says so:

// Uses mock Vulkan device procedures: no Vulkan loader, GPU, or game data needed.

3. The test fails, on two assertions:

1/1 Test #543: vk_memory_fallback_and_pools .....***Failed    0.05 sec
FAIL: PresentComposer tries VRAM (1) -> BAR (0) -> RAM (2) in order
FAIL: OcclusionResolve tries VRAM (1) -> BAR (0) -> RAM (2)
vk_memory_fallback_and_pools: 2 failure(s)

which come from:

expect(drv.alloc_attempts.size() == 3 && drv.alloc_attempts[0].type == 1 &&
       drv.alloc_attempts[1].type == 0 && drv.alloc_attempts[2].type == 2,
       "PresentComposer tries VRAM (1) -> BAR (0) -> RAM (2) in order");

4. Why a clean merge is not a working tree here:

merge-base with main:  5e95fa2f4
main:                  dcba958e5
commits in main since: 2611

runtime/src/vulkan_present_compose.h changed in main since then:
  ba626820e, 096378406, 76262214e …

The pull request carries both the implementation and the test, and the file it implements against has been rewritten in main three times since its base. A textual cherry-pick puts the branch's version beside main's newer code and produces a hybrid that neither side expects - and the test, being mock-based, reports it honestly.

What that means for the author: a rebase will not fix this by itself. The fallback order the test demands has to be reconciled with what vulkan_present_compose.h now does - the patch is 2611 commits old in a file that moved, which is the main-drift case rather than an ordinary conflict.

How it was found: a sweep of open pull requests that replay onto main, building what each test's command[0] says to build and running it through ctest -R. 17 of the 25 in this batch built and passed; this is one of two that did not (the other, #1898, does not compile at all).

Written with an AI assistant.

@merzleckeier

Copy link
Copy Markdown
Contributor

I reproduced the two mock failures on Linux and isolated the change in policy. Stock vk_memory_fallback_and_pools passes at 6fbb6552 on its original history. With 6fbb6552 merged onto main 171af5d93, both failing cases try types 1, 2 (pure VRAM, then system RAM) and succeed on type 2. They never reach the BAR window in those cases.

The shared memory_type_order() in runtime/src/vulkan_memory.h now appends small BAR-window types for requests that don't ask for both DEVICE_LOCAL and HOST_VISIBLE. That rule came from commit 798077b7c in #1681. As a control I restored just the older implementation of memory_type_order() in the merged tree. The original fixture passed with that one substitution.

I also tested updating the fixture to the current policy while keeping the merged runtime unchanged. For both PresentComposer and OcclusionResolve, simulated OOM on VRAM now asserts 1 → 2 with no BAR attempt. Simulated OOM on VRAM and RAM asserts 1 → 2 → 0, so the last-resort BAR allocation is still covered. The complete fixture passed with ASan and UBSan. The comment above detail::device_memory_order() still describes the old BAR-before-RAM order and should match the revised expectation.

Native Vulkan A/B: CachyOS, clang++ 23.1.5, RTX 4070 SUPER (620.73.04) and Radeon 610M/Raphael (RADV 26.3.1), Khronos validation 1.4.363. The same five CTest entries passed on each GPU with each tree, 20/20 overall. These were vk_presenter_capture_colour, vk_binary_occlusion, both vk_overlapping_occlusion variants and vk_xdxr_postbuild_readback. The four device tests reported validation enabled and emitted zero VUIDs in these runs. The forced OOM paths were exercised only in the mock fixture.

AI-assisted: yes (OpenAI Codex).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants