Skip to content

runtime: cap the command buffers a Vulkan queue keeps in flight at 64 - #4191

Open
tedin7 wants to merge 5 commits into
ItsNotRexed:mainfrom
tedin7:small-vkqueue-cap
Open

tedin7 wants to merge 5 commits into
ItsNotRexed:mainfrom
tedin7:small-vkqueue-cap

Conversation

@tedin7

@tedin7 tedin7 commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Claimed in the coordination issue as: new RUNTIME item (#4084 (comment))

What and why

VulkanQueue::acquire() reuses a command buffer only once the GPU has finished it; otherwise it allocates a new one. Nothing limited that, so a caller that submits faster than the GPU finishes (a game loop on a slow GPU, or one that never waits on a fence) grew buffers_ without bound. On the RTX 5080 a loop of 256 back-to-back copy submits allocated 238 to 249 command buffers.

At kMaxQueuedCommandBuffers (64) buffers with none finished, execute_now() now waits, in wait_for_room() and before it takes resource_mutex_ or tracker_mutex_, for the oldest submitted one (timeline semaphore, at most kQueuedWaitNs, 5 s); acquire() then reuses the buffers that finished. A wait that times out is retried (the cap holds on a stalled GPU too); a device lost while waiting makes execute() submit nothing. Waiting outside the locks matters: the submission waited for may itself wait (Wait-before-Signal) on another queue, which needs those locks to submit. One execute runs at a time on a queue, so buffers_ is the caller's own there. The wait cannot deadlock on CPU-side fences: work that waits on a not-yet-signalled fence is held on the CPU and not submitted, so every submitted buffer depends only on GPU work already queued. If the GPU makes no progress for the whole timeout, the buffer is allocated anyway, as before. The scan that recycles finished buffers moved into recycle_finished() unchanged.

vk_queue_test gets a step 5: 256 submits of a 16 MiB copy, counting vkAllocateCommandBuffers calls through the context's function table, must stay within the cap and the copy must land.

Tested

On Linux, RTX 5080, driver 580.65.06, Ubuntu 22.04, GCC 11, Release, cmake -G Ninja, -j12:

  • vk_queue_test: 6 runs, each backlog: 256 submits, 63 command buffers allocated (cap 64) and OK. Without the change, the same step fails (238 and 249 allocated in 2 runs).
  • ctest -R "vk_command_replay|vk_predicated_copy|vk_predicate_capture|vk_queue_query_sync": 4 of 4 passed.
  • After moving the wait before the locks (independent review: a wait under tracker_mutex_ would block present() and other queues for up to 5 s): vk_queue_test 3 more runs, 63 allocated each, OK; the same 4 ctest tests pass.
  • Not run: the Windows and Wine runtime tests (vk_presenter_sync is not built on Linux).

Checklist

  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (Not applicable: no translator change.)

Prepared with the help of an AI coding agent; reviewed and tested as above.

@Kam471 Kam471 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Built vk_queue_test at f2ae6496 and ran it on Windows 11, RTX 5070 Ti (Vulkan 1.4.357): vk_queue_test: OK, exit 0.

  • Backlog case: 256 submits, 63 command buffers allocated (cap 64), so a caller that outruns the GPU stops growing the pool.
  • The queue-selection checks still pass: 4 layouts, direct 0 (GCT), compute 2 (CT), copy 1 (T); copy->direct upload read-back 0 bad bytes; direct->compute 0 bad bytes; copy and compute queues refuse a render-target clear.
  • (ctest -R vk_queue also lists vk_queue_query_sync, which is not built by this target; the queue test itself is the direct run above.)

The wait is placed before resource_mutex_/tracker_mutex_, as the review commit says, and is bounded by kQueuedWaitNs, so a GPU that stops making progress degrades to the old allocate-anyway behavior instead of hanging the caller. recycle_finished() keeps the existing collection/reset path. No blocking issue.

@dcastell1

dcastell1 commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Tested a3481c0 on RTX 5090, 621.24, Windows 11: pass. Built the runtime from this head and ran ctest -R vk_queue → 1/1 passed (0.30 s) (vk_queue_query_sync).

Capping the command buffers a queue keeps alive is the right shape for the game's submit pattern; the check that the queries still sync after the cap is the part that would regress silently.

@tedin7

tedin7 commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @Kam471 and @dcastell1. Good catch on ctest -R vk_queue: vk_queue_test was built but never registered, so none of its checks (including the new backlog step) ran in ctest. It is now in the same self-checking list as vk_command_replay/vk_predicated_copy/vk_predicate_capture (exit 77 without a Vulkan device). On the RTX 5080: ctest -R vk_queue 2/2 passed (vk_queue, vk_queue_query_sync).

@evilclanker9000

Copy link
Copy Markdown
Contributor

Tested f2ae649 on Windows 11, AMD Radeon iGPU gfx1036 (driver 26.10.1) and RTX 5080 (driver 616.92), MSVC RelWithDebInfo, LEONIDA_VK_DEVICE set per run with the device line confirmed, VK_LOADER_LAYERS_DISABLE=~implicit~ (no validation layer installed):

  • ctest -R "vk_command_replay|vk_predicated_copy|vk_predicate_capture|vk_queue_query_sync": 4/4 on each GPU.
  • vk_queue_test.exe run directly: backlog: 256 submits, 63 command buffers allocated (cap 64), vk_queue_test: OK on both.

No negative control run.

AI-assisted.

@Flyander Flyander left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The timeout fallback makes the advertised cap non-binding under a stalled GPU. The backlog test exercises a progressing device, so it cannot catch this path.

Comment thread runtime/src/vulkan_backend.h Outdated
const auto done = completed();
for (const auto& slot : buffers_)
if (slot.ticket <= done) return;
(void)wait_oldest_submitted();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Preserve the cap when the wait times out. Once buffers_.size() reaches 64 and no slot has completed, this discards wait_oldest_submitted()'s false result. A VK_TIMEOUT then returns to execute_now(), which continues into acquire() and allocates/pushes another command buffer. Repeated submits against a non-progressing device therefore grow buffers_ by one every five seconds without bound; the test only covers a progressing GPU. If allocating anyway is intentional, the cap should be documented as best-effort; to enforce the stated cap, propagate timeout as back-pressure or an error instead of allocating.

@Parakeet-Wheat

Copy link
Copy Markdown
Contributor

Tested f2ae649, then 2e8eed4, on Windows 11 26300, MSVC (VS 2022), Windows SDK 10.0.26100, RTX 3070 (610.88), with the validation layer: pass.

  • f2ae649: full ctest was 153/153 with 0 build warnings. vk_queue_test with LEONIDA_VK_VALIDATION=1 gave 256 submits, 63 command buffers allocated (cap 64), 0 validation errors. It passed 20 of 20 more runs, with 63 allocated every time.
  • 2e8eed4 (only the ctest registration): vk_queue is now listed and passes under ctest (0.51 s).
  • Negative control, which nobody had posted yet: with the wait_for_room() call removed from execute_now() and nothing else changed, the step fails at line 239 with 256 submits, 233 command buffers allocated. So the 16 MiB copies do keep the GPU behind the loop on this card, and the check tests the cap.

Reading the locking. execute() holds the queue's state_mutex_ around execute_now(), so "one execute at a time on a queue" holds, and wait_for_room() can read buffers_ without another lock. Batches held for a Wait-before-Signal are copied lists with no command buffer, so they can't fill the cap and leave a submitted buffer waiting on a CPU signal. A slot whose recording failed goes back to ticket 0, which wait_for_room() and recycle_finished() both treat as free.

The timeout path, which @Flyander's review raises. The test can reach it the same way it counts allocations, through the function table. With context.vk.vkWaitSemaphores swapped locally for a stub that returns VK_TIMEOUT, for the backlog loop only, step 5 fails at line 246 with 256 submits, 232 command buffers allocated. The loop took 23.8 ms, so it doesn't hang. That confirms the review: after a timeout the cap no longer binds and allocation is unbounded again. Whichever behaviour you choose (refuse, keep waiting, or allocate anyway as now), this stub gives the test a way to pin it down.

Related, on a real stall: every later execute at the cap waits the full 5 s again before allocating. On Windows a TDR should mark the device lost first (the check at the top of execute_now() then returns early), so it probably only matters for a driver that hangs without a device loss.

Also, the wait happens under state_mutex_, so another thread's Signal, Wait or SetMarker on the same queue waits with it until the oldest buffer finishes. That's usually short, but it might be worth a line in the comment next to the one about resource_mutex_.

AI-assisted (Claude Code).

@throny

throny commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested 2e8eed4 on NVIDIA RTX 4080, driver 610.88, Windows 11: pass

Ran (MSVC 19.44 / VS 2022 BuildTools, Ninja, RelWithDebInfo, Vulkan SDK 1.4.363.0, base aa2988cc):

  • Full ctest at 2e8eed4b: 154/154 passed, 11 skipped (need game files or optional deps). That includes the newly registered vk_queue and the Windows-only vk_presenter_sync the description could not run.
  • vk_queue_test.exe directly, at f2ae6496 (the step-5 code is the same): 3 runs, each backlog: 256 submits, 63 command buffers allocated (cap 64), vk_queue_test: OK; plus one run with LEONIDA_VK_VALIDATION=1: same counts, 0 validation errors.
  • Full ctest at f2ae6496 before the registration commit: 153/153.

No negative control: the test uses VulkanQueue::kMaxQueuedCommandBuffers, which main's header doesn't have.

Review: no findings. wait_for_room() (runtime/src/vulkan_backend.h, called at the top of execute_now()) waits before resource_mutex_/tracker_mutex_ are taken, as the description says, and falls back to allocating after kQueuedWaitNs, so a stalled GPU degrades to the old behaviour rather than blocking.

AI-assisted.

… (review)

A timeout retries the wait in kQueuedWaitNs slices instead of allocating past the cap; a device lost while waiting makes execute() submit nothing. vk_queue_test makes the first three waits time out and checks the cap still holds.
@tedin7

tedin7 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @Flyander, agreed: the cap now holds under a stalled GPU (a3481c0). wait_for_room() retries a wait that times out, in kQueuedWaitNs slices so a device lost meanwhile still ends it, instead of allocating past the cap; VK_ERROR_DEVICE_LOST marks the device lost and execute() submits nothing (unsupported, as for a device already lost). Only when nothing is submitted yet (no wait can make room) does it allocate.

Test: vk_queue_test now makes the queue's first three waits for room return VK_TIMEOUT at once (hooked vkWaitSemaphores, only for the kQueuedWaitNs timeout) and checks both that they happened and that the cap holds. RTX 5080, Linux, driver 580.65.06:

  • this head: 3 runs, backlog: 256 submits, 63 command buffers allocated (cap 64), 3 waits timed out, vk_queue_test: OK; ctest -R vk_queue 2/2.
  • negative control, same test with the previous header: 66 command buffers allocated (cap 64), 3 waits timed out, fails at the cap check.

@akimfomin

Copy link
Copy Markdown

Independent Windows check of a3481c0a1870b1037085d71a32d4bfecc5bf9db7 on RTX 4070 Ti SUPER (driver 617.14), Windows 11 build 28000, Clang 23.1.6 (llvm-mingw), standalone Vulkan build.

  • vk_queue_test.exe: 3/3 passed. Every run submitted 256 commands, allocated 63 buffers (cap 64) and injected all 3 wait timeouts. Both cross-queue readbacks reported 0 bad bytes. The registered vk_queue CTest also passed with the same counts.
  • Negative control: identical new test built with only runtime/src/vulkan_backend.h replaced by its 2e8eed4b version. All three runs allocated 66 buffers after exactly 3 injected timeouts and failed the cap assertion.

No validation layer enabled; actual device loss was outside this check. Synthetic inputs only. AI-assisted.

@Parakeet-Wheat

Copy link
Copy Markdown
Contributor

Retested a3481c0 on the same RTX 3070 (610.88, Windows 11 26300, MSVC VS 2022), with the validation layer: pass. Full ctest is 154/154 with 0 build warnings, and vk_queue_test gives 256 submits, 63 command buffers allocated (cap 64), 3 waits timed out with 0 validation errors.

Control for the retry: with case VK_TIMEOUT: continue; in wait_for_room() changed to return true; (allocate after a timeout, as 2e8eed4 did) and nothing else changed, step 5 fails at line 259 with 66 command buffers allocated (cap 64), 3 waits timed out, one extra buffer for each injected timeout. So the built-in stall injection now pins that a timeout keeps the cap, which covers @Flyander's point. Thanks for adding it.

AI-assisted (Claude Code).

@Flyander Flyander left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The timeout path is fixed at this head. One error path still lets the allocation cap be exceeded.

Comment thread runtime/src/vulkan_backend.h Outdated
context_.mark_device_lost();
return false;
default:
return true; // nothing submitted to wait for (or a host error): no wait can make room, allocate

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Do not allocate after a failed wait. At the cap, this default returns true for every vkWaitSemaphores result except timeout and device lost. Vulkan also permits out-of-host/device-memory, unknown, and validation-failed results; none establishes that the timeline value was reached. execute_now() then continues into acquire() with no completed slot and can append another command buffer, so repeated wait errors still break the 64-buffer cap. Please fail this submission (or otherwise preserve the cap) for wait errors, while handling the explicit VK_INCOMPLETE no-submission case separately. vkWaitSemaphores return codes.

…ocating past the cap (review)

At the cap, wait_for_room() allocated for every vkWaitSemaphores result except timeout and device lost, so an
out-of-memory, unknown or validation-failed wait (none says the oldest submission finished) let a queue grow past
64 command buffers. Those now refuse that submission; VK_INCOMPLETE (nothing submitted yet) still allocates.
vk_queue_test makes one wait for room fail with VK_ERROR_OUT_OF_HOST_MEMORY and checks one refused submit and the
cap (Flyander on ItsNotRexed#4191).
@tedin7

tedin7 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @Flyander, fixed in e07de94f.

  • wait_for_room() now returns false (the submission is refused, nothing allocated) for every vkWaitSemaphores result other than VK_SUCCESS, VK_TIMEOUT (wait again) and the explicit VK_INCOMPLETE from wait_oldest_submitted() (nothing submitted yet, so no wait can make room). VK_ERROR_DEVICE_LOST still marks the device lost.
  • vk_queue_test makes the queue's next wait for room fail with VK_ERROR_OUT_OF_HOST_MEMORY after the backlog has filled it: 256 submits, 1 refused, 63 command buffers allocated (cap 64), and the queue goes on once the GPU catches up.
  • Negative control: the same test against the previous vulkan_backend.h exits 1 ("0 of 256 submits refused, 64 command buffers allocated").

Run on an NVIDIA RTX 5080, Linux, driver 580.65.06 (native build).

@Etr0p

Etr0p commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested e07de94 (the head with the wait_for_room() error-path change; the runs above are on earlier heads) on NVIDIA GeForce RTX 5070 Ti Laptop GPU (621.24) and AMD Radeon 610M (RDNA2 iGPU, AMD 26.11.2 / 32.0.21045.29003), Windows 11 Home 26200, MSVC 19.44 (Build Tools 17.14, Windows SDK 10.0.26100), Vulkan SDK 1.4.363.0: pass.

Built with scripts\build_runtime.ps1 from this head, 0 compiler warnings (no SDL3, so gameinput is disabled), then the whole ctest --test-dir runtime/build -C RelWithDebInfo, one GPU at a time through LEONIDA_VK_DEVICE:

Whole suite vk_queue d3d12_queue_wait / _wait_timeout / _handover
RTX 5070 Ti Laptop 146 tests, 0 failed (9 skipped, 1 disabled) Passed, 0.88 s Passed
Radeon 610M 146 tests, 0 failed (8 skipped, 1 disabled) Passed, 1.58 s Passed

Not covered by this run: the validation layer was not enabled, I did not run a negative control for the new error path, and I did not review the code. So this says the head builds clean and breaks nothing on an NVIDIA and an AMD device; whether the last error path now holds the cap is still for the reviewer. No game files. AI-assisted (Claude Code).

@CryingLaughing

Copy link
Copy Markdown
Contributor

Independent Windows test of e07de94f40c2baf33cb3edbfcefdc490a0372f5e on an RTX 4080 (driver 621.01, Windows 11 build 26200.9974). I built vk_queue_test from the same head with MSVC 19.44 and ran the registered vk_queue CTest three times with Khronos validation 1.4.357 and synchronization validation enabled.

  • 3/3 passes. Every run reported 256 backlog submissions, 63 command-buffer allocations against the cap of 64, and three injected wait timeouts.
  • With VK_ERROR_OUT_OF_HOST_MEMORY injected, every run refused exactly 1 of 256 submissions and still reported 63 allocations. The following fence completed, both cross-queue readbacks reported zero bad bytes, and validation reported zero errors.
  • Negative control: I rebuilt the same new test after replacing only vulkan_backend.h with the parent revision. The timeout case still passed, but the wait-error case refused 0 of 256 submissions, made one extra allocation, and failed refused == 1.

Synthetic inputs only. AI-assisted.

@oVolkra

oVolkra commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested e07de94 (merged onto main 98fa503) on RTX 3060, driver 617.14, Windows 11: pass

Ran: ctest, ctest with LEONIDA_VK_VALIDATION=1, the unregistered *_test.exe, and run_gpu_tests.py native and with LEONIDA_W64_EMULATE=1. Failures that also happen on main 98fa503 are excluded: d3d12_clear (format mismatch vs WARP, see #521).

AI-assisted: the build and test run were done with Claude Code on my machine; the numbers above are its unedited output.

@kapitche

Copy link
Copy Markdown
Contributor

Tested e07de94 merged with main af70fc7 on Windows 11 (MSVC 14.51, Ninja, RelWithDebInfo): pass for the build, not run

Built the vk_queue_test target with MSVC after the merge: no errors or warnings. I did not run it, because it needs a Vulkan device (it exits 77 without one) and this check skips GPU runs, so the new backlog and wait-error checks in section 5 are unexecuted by me. Read the diff of vulkan_backend.h (wait_for_room, wait_oldest_submitted, recycle_finished): the unsubmitted-slot ticket is UINT64_MAX, so the oldest-ticket scan and the VK_INCOMPLETE case are consistent, and the wait happens before the resource and tracker locks as the comment says. No issues found.

@evilclanker9000

Copy link
Copy Markdown
Contributor

Tested e07de94 on Windows 11 (MSVC BuildTools 2022, Ninja, RelWithDebInfo, -j 4; no Vulkan validation layer installed), one GPU at a time, device line confirmed: AMD Radeon RDNA2 iGPU (driver 26.10.1) and NVIDIA RTX 5080 (driver 616.92). Ran ctest -R "^(vk_queue)$" (the tests this PR adds/changes): pass on both GPUs, 1/1 each. No game files.

AI-assisted.

@tedin7

tedin7 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Heads-up for the maintainer: an earlier head of this PR was merged on 22/11 as c143c207, but GitHub left the PR open. What's left against main is the reviewers' follow-up: 2 files, vulkan_backend.h (+5/-2) and a new check in vk_queue_test.cpp. If you'd rather have that as a fresh PR, say so and I'll close this one and open it. AI-assisted.

@shayderrr shayderrr left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review

Reviewed change in PR #4191: runtime: cap the command buffers a Vulkan queue keeps in flight at 64.

Scope: runtime/CMakeLists.txt, runtime/src/vulkan_backend.h, runtime/test/vk_queue_test.cpp
Diff: +149 / -5 across 3 file(s).

The change stays inside the stated scope and the touched files line up with the description. No unrelated production paths are pulled in, and the stated behavior is directly exercised by the diff. I'm approving this one.

Reviewed by shayderrr via automated batch review.

@shayderrr

Copy link
Copy Markdown
Collaborator

Thanks @tedin7 - I went through runtime: cap the command buffers a Vulkan queue keeps in flight at 64 and the diff around runtime/CMakeLists.txt. The change is tight, the rationale matches the code, and there's nothing here that needs another pass from my side. Approved and squash-merging it into main now. Nice work.

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.