Skip to content

runtime: make QueueHolds pump handoff race-free, exception-safe, and per-instance (RT-QUEUE-HOLDS-PUMP-SAFETY) - #1783

Open
IlyassRS3 wants to merge 2 commits into
ProjectLeonida:mainfrom
IlyassRS3:fix/rt-queue-holds-pump-safety
Open

IlyassRS3 wants to merge 2 commits into
ProjectLeonida:mainfrom
IlyassRS3:fix/rt-queue-holds-pump-safety

Conversation

@IlyassRS3

Copy link
Copy Markdown
Contributor

Summary

Fixes three concurrency/deadlock bugs in runtime/src/queue_holds.h (the cross-queue Wait-before-Signal and Present barrier scheduler) and adds a standalone portable unit + concurrency stress test suite (runtime/test/queue_holds_test.cpp).

Root causes

  1. Lost-wakeup race in pump_ready():
    Previously a thread finishing a pump pass executed pump.unlock() (release) followed by dirty_.load(memory_order_acquire), while a concurrent caller wrote dirty_.store(true, memory_order_release) followed by a failing try_to_lock(). Under the C++ memory model (and on weakly ordered architectures such as ARM64), a release store followed by an acquire load permits Store-Load reordering: the exiting thread can observe dirty_ == false before unlocking while the arriving thread's try_to_lock() fails before the unlock becomes visible, leaving ready held batches or deferred Presents stalled.
  2. Permanent per-thread hang on exception:
    in_pump() was manually set to true before snapshot() / discard_waiting_on() / release_ready() / run_barriers() and reset to false afterwards. Any thrown exception (e.g. std::bad_alloc inside snapshot() or a holder/barrier callback) left in_pump() permanently true on that thread, silently turning all later pump_ready() and remove_fence() calls on that thread into no-ops.
  3. Process-wide thread_local bool shared across QueueHolds instances:
    A nested pump_ready() or remove_fence() on a second QueueHolds instance while pumping a first instance on the same thread saw in_pump() == true and returned without pumping or discarding.

Changes

  • runtime/src/queue_holds.h:
    • Serialize dirty_ and pump_active_ under the leaf mutex_ (preserving strict pump_mutex_ -> mutex_ lock ordering) with an RAII ActiveGuard, eliminating the Store-Load lost-wakeup race.
    • Replace the manual static thread_local bool with a zero-allocation, noexcept, stack-intrusive RAII PumpScope chain keyed by const QueueHolds*, making in_pump() both exception-safe and per-instance.
  • runtime/test/queue_holds_test.cpp & runtime/CMakeLists.txt:
    • Register portable queue_holds CTest covering cross-queue Wait-before-Signal chains + Present barriers, exception unwinding in release_ready() / Barrier::fn / remove_fence(), nested independent QueueHolds instances, detach() / cancel_after() synchronization, and a 4-thread high-contention pump handoff stress test (24,000 held ops + 3,000 barriers).

Verification

  • AI-assisted: yes
  • GPUs tested: none (portable standard-library C++20 runtime header + test, verified locally on macOS Apple Silicon ARM64 with Clang; Windows MSVC build / Vulkan queue integration tests rely on Windows CI).
  • Commands run:
    • clang++ -std=c++20 -Wall -Wextra -Werror -fsanitize=address,undefined -O1 runtime/test/queue_holds_test.cpp — pass
    • clang++ -std=c++20 -Wall -Wextra -Werror -fsanitize=thread -O1 runtime/test/queue_holds_test.cpp — pass (zero data races)
    • clang++ -std=c++20 -Wall -Wextra -Werror -O2 runtime/test/queue_holds_test.cpp (5 consecutive runs) — 5/5 pass
    • Mutation test compiling queue_holds_test.cpp against unpatched main:runtime/src/queue_holds.h — fails on test_exception_safety_does_not_wedge_thread (ran == 1 && !holds.any_held()), confirming regression coverage
    • python3 -I scripts/check_no_game_data.py runtime/src/queue_holds.h runtime/test/queue_holds_test.cpp runtime/CMakeLists.txt — pass
    • python3 -I tests/test_text_write_line_endings.py — 3/3 pass

…per-instance

Fix three bugs in runtime/src/queue_holds.h (the cross-queue Wait-before-Signal
and Present barrier scheduler):

1. Lost-wakeup handoff race in pump_ready(): previously a thread exiting
   pump_ready() called pump.unlock() (release) followed by dirty_.load(acquire),
   while a concurrent caller wrote dirty_.store(true, release) followed by a
   failing pump_mutex_.try_lock(). Under the C++ memory model and on weak
   architectures (ARM64), a release followed by an acquire does not prevent
   Store-Load reordering, allowing both threads to exit with dirty_ == true
   and ready batches/presents stuck indefinitely. Serialize dirty_ and
   pump_active_ transitions under the leaf mutex_ (preserving strict
   pump_mutex_ -> mutex_ lock ordering).
2. Exception-safety deadlock: in_pump() was toggled manually around
   discard_waiting_on(), release_ready(), and run_barriers(); any exception
   left in_pump() permanently true on that thread, silently suppressing every
   future pump_ready() and remove_fence(). Use an RAII PumpScope and
   ActiveGuard so state always unwinds cleanly.
3. Cross-instance collision: in_pump() used a single process-wide
   thread_local bool shared across all QueueHolds instances, causing a nested
   pump_ready()/remove_fence() on a second instance to be skipped. Track
   re-entrancy per instance with a stack-allocated intrusive PumpScope chain.

Add portable unit and concurrency stress suite runtime/test/queue_holds_test.cpp.

Item: RT-QUEUE-HOLDS-PUMP-SAFETY
Copilot AI balanced review requested due to automatic review settings November 25, 2026 12:04

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.

@lixonik lixonik 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.

Independent CPU verification at 3e6e229a. The standalone queue_holds_test passed with GCC and UBSan under Ubuntu/WSL. I reproduced an additional case that combines a concurrent handoff with a throwing holder, described inline. A three-way merge of this head with #680 also conflicts in queue_holds.h and queue_holds_test.cpp, so those changes will need coordination if both proceed.

AI-assisted. Synthetic holders only.

Comment thread runtime/src/queue_holds.h
~ActiveGuard() {
if (!active) return;
std::lock_guard lock(self->mutex_);
self->pump_active_ = false;

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.

A dirty handoff can still be left pending if the active pump throws. I used a latch to hold thread A inside release_ready(). While it was inside, thread B registered an after_held callback. B set dirty_ and returned through the pump_active_ path. I then let A throw and unwind. The callback count was still zero after both calls returned. An explicit later pump_ready() ran it once. This reproduced on the base and on this head, and differs from the sequential exception test because the incoming work has already requested a pump. Could the unwind path preserve that handoff, or explicitly document that concurrently queued work needs a fresh pump after an exception?

@IlyassRS3

Copy link
Copy Markdown
Contributor Author

Thank you @lixonik for the GCC/UBSan verification and for catching that concurrent-handoff-on-throw edge case!

Fixed in eee02b769:

  • QueueHolds::pump_ready() and run_barriers() now capture the first exception (std::exception_ptr), skip any Holder that already threw during the current pump (preventing a throwing holder from spinning on re-entrant pump_ready()), drain sibling holders and barriers, and keep honouring any concurrent dirty_ handoff before clearing pump_active_ and rethrowing first_error.
  • Added test_concurrent_handoff_preserved_on_throw() in runtime/test/queue_holds_test.cpp covering the latch-held after_held handoff you described, concurrent sibling-holder signal handoff, barrier-throw handoff, and an adversarial re-entrant throwing holder.
  • Re-verified on macOS arm64 (clang++ -std=c++20 -Wall -Wextra -Werror) under ASan+UBSan, TSan (0 races), and -O2 × 3.

Also noted on #680 (RT-QUEUE-HOLDS-REENTRY): if #680 lands first (adding re-entrant detach/cancel_after), I will rebase this PR cleanly on top to keep both the re-entrant detach/cancel_after paths and the mutex_-serialized pump_active_ / dirty_ handoff fix.

AI-assisted.

@tiguan26 tiguan26 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.

Approving. Merged into current main (e48ff03) with no conflicts. I built queue_holds_test natively (clang 19, Linux) and ran it 3 times plain and 3 times under ThreadSanitizer: all pass, with no TSan reports. Against main's queue_holds.h the same test fails (line 162, the exception case), so it does exercise the new code.

The new handoff is right. dirty_ and pump_active_ are read and written only under mutex_, so a caller either becomes the pumper or leaves dirty_ for one that has not yet checked it. The release-store / acquire-load window the description names can no longer drop a wakeup. The lock order (pump_mutex_ then the leaf mutex_) is the one detach, cancel_after and remove_fence already use. A per-instance PumpScope instead of one thread_local flag also fixes nested instances.

One note for whoever links this to the post-story-load stall: on x86 with MSVC's std::mutex (SRWLock, whose release is an interlocked op) and under Wine, the old pattern would rarely if ever lose a wakeup in practice. So this is correct hardening, but probably not the cause of that stall on its own. The stall reports show list-value gates timing out while writes stay unlanded, which points at held work or an unlanded written fence instead.

AI-assisted (Claude).

@zmasi

zmasi commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

#1783 | head eee02b7 (merged cleanly with main d48a957) | ctest --test-dir runtime/build -C RelWithDebInfo -R "^(queue_holds|d3d12_present)$" --output-on-failure (LEONIDA_VK_VALIDATION=1) | red on main: queue_holds fails at line 162: ran == 1 && !holds.any_held() (test_exception_safety_does_not_wedge_thread leaves in_pump() wedged after exception unwinding) | green on PR+main: 2/2 CTests pass (queue_holds unit/exception/nested-instance/4-thread 24k-op stress + d3d12_present 70-frame Xbox-ABI swapchain present/resize/failure-recovery) 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

@lixonik lixonik 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.

Re-reviewed eee02b769 and verified the concurrent-handoff-on-throw fix.

Code audit:

  • runtime/src/queue_holds.h: pump_ready() and run_barriers() cleanly capture first_error (std::exception_ptr), skip holders that already threw during the current pump via failed_holders, continue draining sibling holders/barriers and honoring concurrent dirty_ handoffs under mutex_ before clearing pump_active_ and rethrowing first_error. Per-instance PumpScope replaces the global thread_local bool.

Verification at eee02b769 (Windows 11, MSVC 19.44, Ninja Release, LEONIDA_VK_VALIDATION=1):

  • Built queue_holds_test and d3d12_present_test.
  • ctest -R '^(queue_holds|d3d12_present)$': 2/2 passed (0 validation errors).
  • python -I scripts/check_no_game_data.py: passed.

GPUs tested: NVIDIA GeForce RTX 5070 12 GB (Windows 11, driver 610.88, Vulkan 1.4.341, VK_LAYER_KHRONOS_validation 1.4.363).

AI-assisted (Antigravity, Gemini).

@OreoFR

OreoFR commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

Verified by OreoFR

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

@OreoFR

OreoFR commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

Verified by OreoFR: link check

  • main 59e65849b + this PR (head eee02b769, the head verified earlier) merged with --no-ff, built without the XMA decoder (LEONIDA_CARGO=OFF, no LEONIDA_XMA2_DECODER_LIB: configure reports the XMA2 and Opus decoders not built), RelWithDebInfo, Ninja, MSVC 19.44.35230 (VS 2022 BuildTools), LEONIDA_REQUIRE_VULKAN=ON
  • gta6rt.exe links; imports unchanged vs main built the same way (dumpbin /imports: 25 DLLs, 655 functions, no WS2_32)
  • gta6rt was not launched.

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

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.

6 participants