Repository navigation
runtime: make QueueHolds pump handoff race-free, exception-safe, and per-instance (RT-QUEUE-HOLDS-PUMP-SAFETY) - #1783
Conversation
…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
lixonik
left a comment
There was a problem hiding this comment.
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.
| ~ActiveGuard() { | ||
| if (!active) return; | ||
| std::lock_guard lock(self->mutex_); | ||
| self->pump_active_ = false; |
There was a problem hiding this comment.
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?
|
Thank you @lixonik for the GCC/UBSan verification and for catching that concurrent-handoff-on-throw edge case! Fixed in
Also noted on AI-assisted. |
tiguan26
left a comment
There was a problem hiding this comment.
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).
|
#1783 | head eee02b7 (merged cleanly with main d48a957) | |
lixonik
left a comment
There was a problem hiding this comment.
Re-reviewed eee02b769 and verified the concurrent-handoff-on-throw fix.
Code audit:
runtime/src/queue_holds.h:pump_ready()andrun_barriers()cleanly capturefirst_error(std::exception_ptr), skip holders that already threw during the current pump viafailed_holders, continue draining sibling holders/barriers and honoring concurrentdirty_handoffs undermutex_before clearingpump_active_and rethrowingfirst_error. Per-instancePumpScopereplaces the globalthread_local bool.
Verification at eee02b769 (Windows 11, MSVC 19.44, Ninja Release, LEONIDA_VK_VALIDATION=1):
- Built
queue_holds_testandd3d12_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).
|
Verified by OreoFR
AI-assisted (Claude Code, Claude Opus 5.5). |
|
Verified by OreoFR: link check
AI-assisted (Claude Code, Claude Opus 5.5), run for OreoFR. |
|
Merged after OreoFR's red/green check (check: green with this PR merged onto AI-assisted (Claude Code, Claude Opus 5.5), merged for MoonEyes. |
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).RT-QUEUE-HOLDS-PUMP-SAFETYRoot causes
pump_ready():Previously a thread finishing a pump pass executed
pump.unlock()(release) followed bydirty_.load(memory_order_acquire), while a concurrent caller wrotedirty_.store(true, memory_order_release)followed by a failingtry_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 observedirty_ == falsebefore unlocking while the arriving thread'stry_to_lock()fails before the unlock becomes visible, leaving ready held batches or deferred Presents stalled.in_pump()was manually set totruebeforesnapshot()/discard_waiting_on()/release_ready()/run_barriers()and reset tofalseafterwards. Any thrown exception (e.g.std::bad_allocinsidesnapshot()or a holder/barrier callback) leftin_pump()permanentlytrueon that thread, silently turning all laterpump_ready()andremove_fence()calls on that thread into no-ops.thread_local boolshared acrossQueueHoldsinstances:A nested
pump_ready()orremove_fence()on a secondQueueHoldsinstance while pumping a first instance on the same thread sawin_pump() == trueand returned without pumping or discarding.Changes
runtime/src/queue_holds.h:dirty_andpump_active_under the leafmutex_(preserving strictpump_mutex_->mutex_lock ordering) with an RAIIActiveGuard, eliminating the Store-Load lost-wakeup race.static thread_local boolwith a zero-allocation,noexcept, stack-intrusive RAIIPumpScopechain keyed byconst QueueHolds*, makingin_pump()both exception-safe and per-instance.runtime/test/queue_holds_test.cpp&runtime/CMakeLists.txt:queue_holdsCTest covering cross-queue Wait-before-Signal chains + Present barriers, exception unwinding inrelease_ready()/Barrier::fn/remove_fence(), nested independentQueueHoldsinstances,detach()/cancel_after()synchronization, and a 4-thread high-contention pump handoff stress test (24,000 held ops + 3,000 barriers).Verification
clang++ -std=c++20 -Wall -Wextra -Werror -fsanitize=address,undefined -O1 runtime/test/queue_holds_test.cpp— passclang++ -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 passqueue_holds_test.cppagainst unpatchedmain:runtime/src/queue_holds.h— fails ontest_exception_safety_does_not_wedge_thread(ran == 1 && !holds.any_held()), confirming regression coveragepython3 -I scripts/check_no_game_data.py runtime/src/queue_holds.h runtime/test/queue_holds_test.cpp runtime/CMakeLists.txt— passpython3 -I tests/test_text_write_line_endings.py— 3/3 pass