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

Open
github-bot wants to merge 2 commits from github-bot/gh-1783 into main AGit
Owner

@⁠IlyassRS3 on GitHub · 2026-11-25 12:04 UTC · original
IlyassRS3:fix/rt-queue-holds-pump-safety → main · +631 −23 · 3 files · 2 commits · open

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).

  • Coordination item: RT-QUEUE-HOLDS-PUMP-SAFETY
  • Claim: #1608

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
**@⁠IlyassRS3** on GitHub · 2026-11-25 12:04 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1783) `IlyassRS3:fix/rt-queue-holds-pump-safety` → `main` · +631 −23 · 3 files · 2 commits · open ## 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`). - **Coordination item**: `RT-QUEUE-HOLDS-PUMP-SAFETY` - **Claim**: https://git.gtahub.st/github/ubiquitarianism--leonida/issues/1608 ### 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`](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/test/queue_holds_test.cpp) & [`runtime/CMakeLists.txt`](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
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
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:05:04 +00:00
Author
Owner

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

@⁠lixonik on GitHub · 2026-11-25 12:13 UTC · original · reviewed

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.

**@⁠lixonik** on GitHub · 2026-11-25 12:13 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1783#pullrequestreview-6057393964) · **reviewed** 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.
@ -170,0 +175,4 @@
~ActiveGuard() {
if (!active) return;
std::lock_guard lock(self->mutex_);
self->pump_active_ = false;
Author
Owner

@⁠lixonik on GitHub · 2026-11-25 12:13 UTC · original

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?

**@⁠lixonik** on GitHub · 2026-11-25 12:13 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1783#discussion_r4694707091) 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?
Author
Owner

@⁠IlyassRS3 on GitHub · 2026-11-25 12:28 UTC · original

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.

**@⁠IlyassRS3** on GitHub · 2026-11-25 12:28 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1783#issuecomment-7162424898) 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.
Author
Owner

@⁠tiguan26 on GitHub · 2026-11-25 20:01 UTC · original · approved these changes

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).

**@⁠tiguan26** on GitHub · 2026-11-25 20:01 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1783#pullrequestreview-6064142215) · **approved these changes** 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).
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/1783/head:github-bot/gh-1783'
git switch 'github-bot/gh-1783'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-1783'
git switch 'github-bot/gh-1783'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-1783'
git switch 'github-bot/gh-1783'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-1783'
git switch 'main'
git merge --squash 'github-bot/gh-1783'
git switch 'main'
git merge --ff-only 'github-bot/gh-1783'
git switch 'main'
git merge 'github-bot/gh-1783'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.