Repository navigation
Move task registry to global Runtime storage with sentinel-based shutdown - #59
Conversation
- Set num_executors to null for auto-detection - Will use CPU count instead of single-threaded mode - Better utilization of available hardware
This commit fixes critical race conditions that occurred in the multi-threaded async runtime when tasks could be woken by another thread before they actually yielded, leading to deadlocks. ## Race Conditions Fixed 1. **Wake-before-yield race**: Tasks could be resumed (state set to .ready) after preparing to wait but before the yield() call. The unconditional state.store() in yield() would then overwrite .ready with .waiting, leaving the task stuck. 2. **Invalid mutex state transitions**: Mutex.lock() could transition directly from unlocked -> has_waiters, skipping the locked_once state. This occurred when unlock() happened between tryTransition() check and push() to wait queue. 3. **Invalid ResetEvent state transitions**: Similar issue where ResetEvent could transition from is_set -> has_waiters, skipping the unset state. 4. **popOrTransition sentinel state**: When popping the last waiter, popOrTransition() would transition to hardcoded sentinel0 instead of the specified to_sentinel. ## Solution ### 1. Added .preparing_to_wait state (src/coroutines.zig) - New intermediate state between .ready and .waiting - Allows detection of early wakeup via atomic CAS ### 2. Atomic CAS in yield() (src/runtime.zig) - Modified yield() to take expected_state and desired_state parameters - Performs atomic CAS: if state is not expected_state, check if .ready (early wakeup) - If woken early (.ready), skip suspend; if unexpected state, panic - Updated all yield() callers to pass expected states ### 3. New ConcurrentQueue operations (src/utils/concurrent_queue.zig) - pushOrTransition(from, to, item): Push item OR transition from->to atomically * Used by Mutex to prevent unlocked->has_waiters invalid transition - pushUnless(forbidden, item): Push item unless in forbidden state * Used by ResetEvent to prevent is_set->has_waiters invalid transition - Fixed popOrTransition() to use to_sentinel when emptying queue ### 4. Updated sync primitives - Mutex.lock(): Use pushOrTransition() for atomic lock acquisition (src/sync/Mutex.zig) - ResetEvent.wait/timedWait(): Use pushUnless() to avoid invalid transitions (src/sync/ResetEvent.zig) - Condition.wait/timedWait(): Updated to use atomic yield pattern (src/sync/Condition.zig) - All primitives now use .ready -> .preparing_to_wait -> .waiting flow ## Testing All 105 tests pass. The ping-pong benchmark that previously deadlocked now runs successfully without any race conditions.
Add a spin loop that runs the event loop in non-blocking mode before blocking when the ready queue is empty. This significantly reduces latency for high-frequency cross-thread task scheduling. ## Problem When an executor's ready queue is empty, it blocks in `loop.run(.once)` waiting for I/O. If another thread schedules a task remotely and calls notify(), the sleeping executor must go through kernel wakeup, which adds 5-20 microseconds of latency per wakeup. For workloads like ping-pong with frequent cross-thread messaging, this kernel wakeup latency dominated performance, causing 30x+ slowdown compared to single-threaded execution. ## Solution Before blocking, spin up to 100 iterations running `loop.run(.no_wait)`: - Checks for I/O completions (non-blocking poll) - Processes async wakeup events if fired - Checks remote ready queue after each iteration - Only blocks if still no work after spinning This catches remote tasks within microseconds instead of waiting for kernel wakeup, while still allowing I/O to progress during the spin. ## Results Multi-threaded ping-pong benchmark (1M round trips): - Before: 9858ms (101K rounds/sec) - After: 4385ms (228K rounds/sec) - Improvement: 2.25x faster The spin loop eliminated most kernel wakeup latency, more than doubling throughput for high-frequency cross-thread workloads.
Replace std.Thread.Mutex with atomic spinlock using mutation bit (0b10) in the head pointer. This reduces the queue size from 24 bytes to 16 bytes while maintaining all race condition protections. Changes: - Remove mutex field, use mutation bit spinlock pattern instead - Restore acquireMutationLock/releaseMutationLock methods - Update all operations (push, pop, remove, etc.) to use spinlock - Remove CompactConcurrentQueue variant (no longer needed) - Keep all race condition fixes (pushUnless, pushOrTransition, popOrTransition) The lock-free design uses fetchOr/fetchAnd atomic operations with proper memory ordering (.acquire/.release) to protect the non-atomic tail pointer and doubly-linked list updates. All 101 tests pass, including concurrent stress tests.
Clear item pointers while holding the mutation lock instead of after releasing it. This prevents concurrent remove() calls from racing on the same item's prev/next pointers, and ensures double-remove attempts properly fail the early exit checks.
Extract common push logic into pushInternal() helper function. This eliminates ~70 lines of duplicated code across push(), pushUnless(), and pushOrTransition().
…down Replace per-Executor task queues with a single global task registry in Runtime. Remove accepting_spawns and global_task_count atomics in favor of sentinel state encoding for closed state. Create AnyTaskList wrapper with add(), remove(), close(), isEmpty(), isClosed(), and pop() methods. Key changes: - Sentinel states: sentinel0 (empty/open), sentinel1 (empty/closed) - Atomic transition to closed state ensures only one executor triggers shutdown - All executors can safely call maybeShutdown() via atomic CAS - Shutdown check added at start of Executor.run() to handle empty task list - Simplified shutdown logic with extracted maybeShutdown() helper
WalkthroughThis PR consolidates task lifecycle management through a new Changes
Sequence Diagram(s)sequenceDiagram
participant Task as Task/Awaitable
participant Executor
participant Queue as ConcurrentQueue
participant Coro as Coroutine
rect rgb(200, 220, 240)
Note over Task,Coro: Old: Simple push-and-yield (potential lost wakeup)
Task->>Coro: check state (ready/waiting)
Task->>Queue: push(wait_node)
Task->>Executor: yield(.waiting, .no_cancel)
Executor-->>Task: (may resume after push)
end
rect rgb(240, 220, 200)
Note over Task,Coro: New: Atomic transition preventing lost wakeups
Task->>Coro: state.store(.preparing_to_wait)
Task->>Queue: pushOrTransition(.preparing_to_wait, .ready, node)<br/>or pushUnless(.ready, node)
alt Pushed successfully
Task->>Executor: yield(.preparing_to_wait, .waiting, .no_cancel)
Executor->>Coro: state transition attempt
else Already set/transitioned
Task-->>Task: Return immediately (ready)
end
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Rationale: Heterogeneous, high-density changes across multiple subsystems—introduction of Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/runtime.zig (1)
1292-1297: Defensive error handling for remote wakeup notification.The code checks if
remote_initializedbefore callingnotify(), and logs a warning if notification fails. This is defensive:
- The task is already in the remote queue, so the failure is not critical
- The warning helps diagnose issues in production
However, consider whether debug printing is appropriate here, as it could be verbose under high contention or in failure scenarios.
If verbose warnings are a concern, you could:
- Rate-limit the warning (log once per N failures)
- Use a metric counter instead of printing
- Log at a lower level (e.g., trace instead of warn)
But this is a minor point—the current approach is reasonable for initial deployment.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (11)
benchmarks/concurrent_queue_bench.zig(1 hunks)benchmarks/echo_server.zig(1 hunks)benchmarks/ping_pong.zig(1 hunks)src/core/ConcurrentAwaitableList.zig(1 hunks)src/coroutines.zig(3 hunks)src/runtime.zig(25 hunks)src/sync/Condition.zig(4 hunks)src/sync/Mutex.zig(2 hunks)src/sync/ResetEvent.zig(5 hunks)src/utils.zig(0 hunks)src/utils/concurrent_queue.zig(8 hunks)
💤 Files with no reviewable changes (1)
- src/utils.zig
🔇 Additional comments (35)
benchmarks/ping_pong.zig (1)
27-27: LGTM! Explicit runtime configuration.The change to explicitly pass
.num_executors = nullis consistent with the broader pattern across benchmarks and makes the configuration intent clear.src/core/ConcurrentAwaitableList.zig (1)
146-146: LGTM! Updated yield signature for new state machine.The yield call now correctly includes both
expected_stateanddesired_stateparameters (both.readyin this spin-wait context), aligning with the updated coroutine state machine semantics across the codebase.benchmarks/echo_server.zig (1)
188-188: LGTM! Consistent with other benchmarks.The explicit runtime configuration matches the pattern established in other benchmark files.
benchmarks/concurrent_queue_bench.zig (4)
174-175: LGTM! Simplified output after CompactConcurrentQueue removal.The consolidated size reporting for
ConcurrentQueueandStandardNodecorrectly reflects the removal of the compact queue variant.
179-179: LGTM! Updated benchmark naming.The label now accurately reflects that only
ConcurrentQueueis being benchmarked.
181-181: Excellent improvement! Adaptive thread count.Using
std.Thread.getCpuCount()instead of a hardcoded value makes the benchmark adapt to the actual system configuration, providing more meaningful results across different machines.
187-187: LGTM! Consistent naming.The concurrent benchmark label correctly identifies the queue type being tested.
src/sync/Mutex.zig (3)
31-31: LGTM! Migration to ConcurrentQueue.The replacement of
CompactConcurrentQueuewithConcurrentQueueis consistent with the broader refactoring across the codebase and aligns with the new queue APIs (pushOrTransition, etc.).Also applies to: 39-39, 41-41
77-87: Excellent race prevention with preparing_to_wait state!The new atomic state machine correctly prevents the race where the mutex is unlocked between the tryTransition check and queue enqueue. The three-step approach is sound:
- Transition to
preparing_to_waitbefore any queue operations- Use
pushOrTransitionto atomically either enqueue or acquire if unlocked- Restore
readystate if the mutex was acquired via transitionThis prevents the problematic state progression:
unlocked -> has_waiters(skippinglocked_once), which could lead to lost wakeups.
91-91: LGTM! Updated yield with atomic state transition.The yield now correctly passes
expected_state: .preparing_to_waitanddesired_state: .waiting, ensuring the CAS inside yield will detect early wakeups (if state was changed frompreparing_to_waitbefore suspension) and avoid unnecessary suspension.src/coroutines.zig (3)
11-16: LGTM! New state machine properly supports atomic wait/wake protocol.The addition of
preparing_to_waitstate enables a lost-wakeup-free protocol:
- Task transitions to
preparing_to_waitbefore enqueueing- If woken early, the atomic CAS in
yield()will fail and skip suspension- Otherwise, atomically transitions
preparing_to_wait → waitingThis is a well-known pattern for preventing race conditions in wait queues.
402-402: LGTM! Atomic state field enables safe concurrent state transitions.Wrapping the state in
std.atomic.Valueallows lock-free coordination between the yielding task and the waker, which is essential for the new wait/wake protocol introduced in this PR.
421-421: LGTM! Atomic store with proper memory ordering.Using
.releaseordering ensures that all writes made by the coroutine function are visible before the state becomes.dead, which is correct for this synchronization point.src/sync/Condition.zig (3)
57-60: LGTM! Migration to ConcurrentQueue completed.The switch from
CompactConcurrentQueuetoConcurrentQueuealigns with the broader architectural changes in this PR. The new queue type provides thepushUnlessandpushOrTransitionAPIs needed for the atomic wait/wake protocol.
90-107: LGTM! Correct implementation of the new wait protocol.The sequence is correct:
- Atomically set state to
preparing_to_wait(Line 91)- Enqueue to wait queue (Line 94)
- Release mutex (Line 97)
- Atomic yield with CAS
preparing_to_wait → waiting(Line 101)If a signal arrives between enqueue and yield, the CAS will fail and the task won't suspend, preventing lost wakeups.
130-172: LGTM! Timed wait follows the same pattern.The
timedWaitimplementation correctly mirrors the atomic state transition protocol used inwait(), with the added timeout callback mechanism.src/sync/ResetEvent.zig (4)
52-55: LGTM! Consistent migration to ConcurrentQueue.
59-66: LGTM! Clear documentation of sentinel states.The comments clearly explain the state encoding using ConcurrentQueue sentinels:
sentinel0= unsetsentinel1= set- pointer = waiting (has waiters)
124-142: LGTM! Correct use ofpushUnlessto prevent invalid state transitions.The
pushUnless(is_set, ...)ensures that we only enqueue if the event is not already set. This prevents the invalid transitionis_set → has_waitersand handles the race where the event is set between the initial check and the enqueue.If
pushUnlessreturns false (event was set), the code correctly resets the task state to.readyand returns immediately.
174-215: LGTM! Timed wait correctly implements the same protocol.src/utils/concurrent_queue.zig (5)
200-228: LGTM! Good refactoring to separate concerns.Extracting
pushInternalmakes the code more maintainable and allows the newpushUnlessandpushOrTransitionmethods to reuse the enqueue logic after their respective checks/transitions.
230-283: LGTM! New APIs enable atomic wait/wake protocols.The new methods are well-designed:
pushUnless: Conditionally pushes unless in a forbidden state (e.g., don't add waiters if already signaled)pushOrTransition: Atomically either transitions state or pushes item, preventing invalid state transitions (e.g., unlocked → has_waiters without going through locked_once)PushOrTransitionResult: Clear enum for distinguishing the outcomeThese primitives enable the synchronization primitives (ResetEvent, Mutex, etc.) to implement correct, race-free wait/wake logic.
165-186: LGTM! Yielding prevents live-lock in contention.The addition of
std.Thread.yield()on spin overflow (Line 182) is important for multi-threaded scenarios where multiple threads may be contending for the mutation lock. Without yielding, high-priority threads could starve lower-priority threads.The comment accurately describes the behavior.
357-395: LGTM! Defensive pointer saving prevents race conditions.Lines 357-363 save the
prevandnextpointers before clearing them, then use the saved values for the removal logic. This prevents data races if another thread concurrently callsremove()on the same item—the second call will see null pointers and fail the early exit checks at lines 342-350.This is a good defensive programming practice for lock-free data structures.
406-456: LGTM! Complex but correct state-aware pop operation.The
popOrTransitionlogic handles multiple cases:
- From sentinel → transition to target sentinel (Lines 413-416)
- Already at target sentinel → no-op (Lines 419-422)
- Unexpected sentinel → defensive null return (Lines 425-430)
- Has items → pop and transition/update accordingly (Lines 432-455)
The defensive checks at lines 419-430 improve robustness. The logic is complex but appears correct for the sentinel-based state encoding used throughout the PR.
src/runtime.zig (10)
411-468: LGTM! Well-designed global task registry with sentinel-based shutdown.The
AnyTaskListencapsulates the task lifecycle management with clear state encoding:
sentinel0(empty_open): No tasks, accepting spawnssentinel1(empty_closed): No tasks, runtime shutting down- Pointer: Has tasks, accepting spawns
Key methods are well-designed:
add()returnserror.Closedif shutting down (prevents spawns during shutdown)close()is idempotent and returnserror.NotEmptyif tasks remainremove(),isEmpty(),isClosed(),pop()provide the complete lifecycle APIThis is a significant improvement over separate atomic counters, as it combines spawn gating and task tracking in one lock-free structure.
182-202: LGTM! Correct integration of atomic wait protocol in waitForComplete.The sequence properly implements the new protocol:
- Transition to
preparing_to_wait(Line 183)- Enqueue to wait list (Line 185)
- Double-check completion (Lines 188-194) with state rollback on early completion
- Atomic yield
preparing_to_wait → waiting(Line 198)The double-check with rollback to
.ready(Line 192) correctly handles the race where completion happens during enqueue.
330-359: LGTM! Atomic state swap elegantly handles the waiting/preparing_to_wait distinction.The logic is correct:
- Atomically swap to
.readyand observe old state (Line 346)- If old state was
.waiting, the task is suspended—schedule it (Line 351)- If old state was
.preparing_to_wait, the task hasn't yielded yet—it will observe.readyand skip suspension, so no scheduling needed (Lines 352-354)- Otherwise, unexpected state—panic (Lines 356-358)
This correctly implements the protocol where a task in
preparing_to_waitcan be woken before it suspends.
1035-1089: LGTM! Atomic CAS prevents lost wakeups in yield.The critical CAS at lines 1052-1061:
- Attempts
expected_state → desired_statetransition- On failure with
actual_state == .ready, skips suspension (early wakeup case)- On failure with unexpected state, panics (bug detection)
This ensures that if
resumeTask()sets the state to.readyafter we setpreparing_to_waitbut before we yield, the CAS fails and we don't suspend—preventing a lost wakeup.The panic on unexpected states (Line 1059) is appropriate for catching bugs during development.
1148-1163: LGTM! Clean shutdown helper with correct race handling.The
maybeShutdown()helper encapsulates the shutdown logic:
- Check if task list is empty (Line 1149)
- Try to close registry (atomic
empty_open → empty_closedtransition, Line 1151)- On success, set shutdown flag and wake all executors (Lines 1153-1158)
- On failure (race with task addition or concurrent close), do nothing (Lines 1159-1161)
The
if (self.runtime_ptr.tasks.close())idiom correctly handles races:
- If another executor closes first, this one sees
empty_closedandclose()returns success (idempotent per AnyTaskList.close() docs)- If tasks were added,
close()returnserror.NotEmptyand shutdown is aborted
997-999: LGTM! Spawn correctly registers task with shutdown check.Adding to the global registry (Line 998) with
errdefercleanup (Line 999) ensures:
- Spawn fails with
error.Closedif runtime is shutting down (viaAnyTaskList.add())- If subsequent spawn operations fail (e.g., scheduling), task is removed from registry
This maintains the invariant that all tasks in the registry are either running or scheduled.
1180-1182: LGTM! Immediate shutdown check prevents hang on empty start.Calling
maybeShutdown()at executor startup ensures that if the runtime is started with no tasks, it immediately transitions to shutdown rather than blocking indefinitely in the event loop. This is a nice usability improvement.
1226-1232: LGTM! Task completion cleanup and shutdown check.After marking a task complete, the code:
- Removes it from the global registry (Line 1227)
- Releases the runtime's reference (Line 1228)
- Checks if this was the last task and maybe initiates shutdown (Line 1232)
This ensures the runtime shuts down cleanly when all tasks complete.
1645-1648: LGTM! Deinit properly drains remaining tasks.The cleanup loop ensures all tasks remaining in the registry are released, preventing memory leaks. This handles the case where the runtime is deinitialized while tasks are still registered (e.g., due to external shutdown).
1667-1670: LGTM! Spawn methods correctly check shutdown state.Both
spawn()andspawnBlocking()checktasks.isClosed()before attempting to spawn, returningerror.RuntimeShutdownif the runtime is shutting down. This prevents new tasks from being created during shutdown, which could cause hangs or undefined behavior.Also applies to: 1697-1700
Summary
This PR refactors the task registry from per-Executor local storage to a single global registry in
Runtime, using ConcurrentQueue sentinel states to encode the closed state. This simplifies shutdown coordination and eliminates the need for separateaccepting_spawnsandglobal_task_countatomic fields.Key Changes
AnyTaskListwrapper type with methods:add(),remove(),close(),isEmpty(),isClosed(),pop()Runtime.global_task_countandRuntime.accepting_spawnsatomicsExecutor.taskstoRuntime.taskssentinel0(0b00) = empty/opensentinel1(0b01) = empty/closedsentinel1ensures only one executor successfully triggers shutdown, making it safe for all executors to callmaybeShutdown()Executor.run()to handle the case where runtime starts with no tasksmaybeShutdown()helper functionBenefits
Test plan
Summary by CodeRabbit
Release Notes