Repository navigation
Refactor wait queues to use WaitNode abstraction - #52
Conversation
Introduces a new WaitNode type to separate "what can be waited on" (Awaitable) from "what participates in wait queues" (WaitNode). Key changes: - Replace Awaitable-specific data structures with generic versions - Remove executor parameter from ConcurrentQueue methods - Use vtable-based polymorphic wake instead of switch statements - Simplify SelectWaiter to contain WaitNode directly - Remove select_waiter from AwaitableKind enum - Make Executor.yield gracefully return when not in coroutine Benefits: - Better separation of concerns - More reusable generic data structures - Cleaner API without threading executor parameters - Reduced coupling between components
WalkthroughReplaces intrusive Awaitable-linked wait lists with a WaitNode-based model and new concurrent/single-threaded queue/stack primitives; removes legacy awaitable list/stack modules and rewires runtime, sync primitives, and task/future initialization to use WaitNode + ConcurrentQueue/ConcurrentStack for waiting and wake logic. Changes
Sequence Diagram(s)sequenceDiagram
participant Task as Task
participant Awaitable as Awaitable
participant WaitNode as WaitNode
participant Queue as ConcurrentQueue(WaitNode)
participant Executor as Executor
participant VTable as WaitNode.VTable
Note over Task,Awaitable: initialization
Task->>Awaitable: set awaitable.wait_node.vtable
Note over Task,Queue: wait path
Task->>Queue: push(&awaitable.wait_node)
Note over Executor,Queue: wake path
Executor->>Queue: pop()
Queue-->>Executor: wait_node*
Executor->>WaitNode: wait_node.wake()
WaitNode->>VTable: vtable.wake(wait_node)
VTable-->>Task: resume / wake callback
sequenceDiagram
participant Caller as Caller
participant Mutex as Mutex
participant Task as Task
participant WaitNode as WaitNode
participant Queue as ConcurrentQueue(WaitNode)
participant Executor as Executor
Caller->>Mutex: lock() (fast path fails)
Task->>Mutex: prepare &awaitable.wait_node
Task->>Queue: push(&awaitable.wait_node)
Caller->>Mutex: unlock()
Mutex->>Queue: popOrTransition(...)
Queue-->>Mutex: wait_node*
Mutex->>WaitNode: wait_node.wake()
WaitNode-->>Task: wake -> attempt reacquire or resume
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🔇 Additional comments (21)
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/utils/simple_stack.zig (1)
1-13: Document the complexity ofprependByMoving.The module documentation mentions O(1) push and pop, but
prependByMovingis O(n) where n is the length of the other stack (it must traverse to find the tail). Consider adding this to the documentation for completeness.Apply this diff:
//! Generic simple singly-linked stack (LIFO) for single-threaded use. //! -//! Provides O(1) push and pop operations. +//! Provides O(1) push and pop operations. The prependByMoving operation is O(n) +//! where n is the length of the stack being prepended. //!
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (13)
src/core/Awaitable.zig(3 hunks)src/core/ConcurrentAwaitableStack.zig(0 hunks)src/core/SimpleAwaitableList.zig(0 hunks)src/core/SimpleAwaitableStack.zig(0 hunks)src/core/WaitNode.zig(1 hunks)src/runtime.zig(24 hunks)src/sync/Condition.zig(6 hunks)src/sync/Mutex.zig(3 hunks)src/sync/ResetEvent.zig(7 hunks)src/utils/concurrent_queue.zig(1 hunks)src/utils/concurrent_stack.zig(1 hunks)src/utils/simple_queue.zig(1 hunks)src/utils/simple_stack.zig(1 hunks)
💤 Files with no reviewable changes (3)
- src/core/SimpleAwaitableStack.zig
- src/core/SimpleAwaitableList.zig
- src/core/ConcurrentAwaitableStack.zig
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-10-15T19:38:44.642Z
Learnt from: lalinsky
PR: lalinsky/zio#47
File: src/sync/Mutex.zig:237-237
Timestamp: 2025-10-15T19:38:44.642Z
Learning: In the `unlock` method of `src/sync/Mutex.zig`, the `runtime` parameter is intentionally retained (marked with `_ = runtime;`) for API consistency and future-proofing, even though it's not currently used in the implementation.
Applied to files:
src/sync/Mutex.zig
📚 Learning: 2025-10-16T14:33:19.679Z
Learnt from: lalinsky
PR: lalinsky/zio#48
File: src/core/ConcurrentAwaitableList.zig:254-269
Timestamp: 2025-10-16T14:33:19.679Z
Learning: In the zio repository's `src/core/ConcurrentAwaitableList.zig` and `src/core/Awaitable.zig`, the `in_list` field should remain debug-only (conditional compilation with `builtin.mode == .Debug`). Double-removal detection in `ConcurrentAwaitableList.remove()` uses pointer-based checks (comparing `prev`/`next` against `head`/`tail`) rather than relying on a regular `in_list` field.
Applied to files:
src/sync/ResetEvent.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: test (windows-latest)
🔇 Additional comments (52)
src/utils/simple_stack.zig (2)
27-44: LGTM! Clean implementation with good debug safety.The push and pop implementations are correct with appropriate Debug-mode assertions to catch double-insertion bugs. The clearing of
nextpointers on pop prevents dangling references.
46-61: LGTM! Correct implementation of prepending.The traversal to find the tail is necessary for a singly-linked list. The in_list debug tracking correctly remains true for moved items (they transition from other's list to self's list).
src/utils/concurrent_stack.zig (2)
19-36: LGTM! Correct lock-free push implementation.The memory ordering is sound:
.acquireload ensures visibility of previous pushes.releaseon successful CAS publishes the new item and its chain.acquireon failure ensures the retry sees the updated head
38-43: LGTM! Correct atomic drain operation.The
.acq_relordering ensures the caller sees all pushed items and properly publishes the empty state. The returnedSimpleStackcorrectly takes ownership of the drained items in LIFO order.src/core/WaitNode.zig (2)
12-20: LGTM! Clean vtable design.The no-op
defaultWakeis reasonable for this abstraction. Concrete types usingWaitNodewill provide appropriate wake implementations through their vtables.
5-10: LGTM! Well-designed intrusive queue node.The fields support doubly-linked queue operations (O(1) removal), and the Debug-only
in_listprovides safety without runtime overhead in release builds. The vtable delegation inwake()is clean and efficient.Also applies to: 22-25
src/sync/Condition.zig (4)
57-60: LGTM! Clean transition to WaitNode-based queue.The import additions and type change align with the refactoring objectives. The
.emptyinitialization is appropriate for the new queue type.
86-107: LGTM! Correct WaitNode integration in wait().The changes from
awaitabletowait_nodeare consistent. The cancellation handling correctly attempts removal and reacquires the mutex before returning, maintaining the invariant that the mutex is held on return.
121-167: LGTM! Correct timeout handling with WaitNode.The
TimeoutContextsimplification (removing executor field) is appropriate since wake behavior is now encapsulated in the WaitNode vtable. The timeout vs. signal race handling via removal attempt is correct.
184-211: LGTM! Simplified signal/broadcast with WaitNode wake.The unused
runtimeparameter is appropriately marked. The wake logic is now encapsulated in the WaitNode vtable, eliminating the need to directly schedule tasks. Bothsignal()andbroadcast()correctly pop and wake the appropriate nodes.src/sync/Mutex.zig (3)
30-42: LGTM! Consistent queue type migration.The import additions and queue type change to
ConcurrentQueue(WaitNode)are correct. The initialization with.sentinel1(unlocked state) maintains the proper initial state for the mutex.
66-93: LGTM! Correct cancellation handling in lock().The WaitNode integration is correct. The cancellation logic properly handles the race: if removal from the queue fails, the task already inherited the lock and must release it before returning the error, maintaining the invariant that the mutex is not held on error return.
120-127: LGTM! Clean wake delegation to WaitNode.The transition from resuming tasks to calling
wait_node.wake()is correct. The unusedruntimeparameter is appropriately marked and retained for API consistency. Based on learnings.src/core/Awaitable.zig (3)
5-6: LGTM! Clean import transition to WaitNode-based abstractions.The imports properly reflect the architectural shift from Awaitable-specific collections to generic WaitNode-based queues.
24-28: LGTM! WaitNode integration enables cleaner polymorphic wakeup.The wait_node field enables vtable-based wake dispatch, and the atomic state field provides proper memory ordering for the pending/complete lifecycle.
33-34: LGTM! Queue type transition aligns with the refactor.The waiting_list now holds WaitNode entries instead of Awaitable entries, separating concerns between what can be waited on versus what participates in wait queues.
src/utils/simple_queue.zig (4)
29-44: LGTM! Push operation correctly maintains FIFO semantics.The method properly updates both head and tail pointers, handles the empty list case, and enforces membership tracking in debug mode.
46-60: LGTM! Pop operation correctly removes from head.The method maintains FIFO order by popping from the head, properly updates the queue structure for both single-element and multi-element cases, and cleans up pointers on the removed node.
62-78: LGTM! Concatenation efficiently moves nodes between queues.The method correctly handles both empty and non-empty queue cases, updates all necessary pointers, and properly empties the source queue.
80-115: LGTM! Remove operation with robust membership validation.The method correctly validates membership using pointer-based checks (consistent with retrieved learnings about debug-only in_list), handles all removal cases (head, tail, middle), and properly maintains queue invariants.
Based on learnings
src/sync/ResetEvent.zig (5)
52-55: LGTM! Queue type transition to WaitNode-based abstraction.The wait_queue field correctly uses the new ConcurrentQueue(WaitNode) type, and the .empty initialization provides clean syntax.
84-92: LGTM! Wake path correctly migrated to WaitNode.wake().The set() method now uses the polymorphic wait_node.wake() dispatch instead of direct task resumption. The runtime parameter is correctly marked as unused since wakeup logic is now encapsulated in the WaitNode vtable.
124-139: LGTM! Wait path correctly operates on WaitNode entries.The wait() method properly enqueues the task's wait_node, handles cancellation removal, and validates membership using the wait_node's in_list field in debug mode.
165-175: LGTM! Timed wait setup migrated to WaitNode references.The timeout context correctly holds WaitNode references for the callback to remove from the queue on timeout, maintaining the same timeout semantics with the new abstraction.
185-202: LGTM! Timeout and cancellation handling properly migrated.The timeout callback and cancellation paths correctly operate on WaitNode entries, and debug assertions validate proper queue membership tracking.
src/utils/concurrent_queue.zig (10)
55-84: LGTM! Tagged pointer state encoding is well-designed.The State enum correctly encodes two sentinel states and pointer values using the lower 2 bits, with bit 1 serving as a mutation lock. The alignment assertion on line 81 ensures pointers are properly aligned for this encoding scheme.
98-101: LGTM! State read uses correct memory ordering.The .acquire ordering ensures visibility of prior state transitions and queue modifications, which is essential for reading the current state safely.
109-124: LGTM! State transition uses appropriate memory ordering.The .acq_rel ordering on successful CAS provides bidirectional synchronization, which is correct for both acquiring previous state and releasing new state to other threads.
146-170: LGTM! Mutation lock acquisition with proper memory ordering and yielding.The .acquire ordering on fetchOr (line 151) correctly synchronizes with the previous lock release, ensuring visibility of queue modifications. The hybrid yield strategy (lines 162-166) supports both coroutine and thread contexts.
177-182: LGTM! Lock release with correct memory ordering.The .release ordering on fetchAnd (line 180) properly publishes all modifications made while holding the lock, making them visible to future acquireMutationLock calls. The assertion validates lock ownership.
187-214: LGTM! Push operation with correct concurrency control.The method properly acquires the mutation lock, handles both empty and non-empty queue cases, and uses .release ordering (line 202) to publish the new queue state when transitioning from sentinel to pointer.
218-256: LGTM! Pop operation with proper empty-queue handling.The method correctly handles both the last-element case (transitions to sentinel0) and the multi-element case (updates head pointer). Both code paths use .release stores (lines 245, 251) to publish updates and implicitly release the mutation lock.
260-325: LGTM! Remove operation with comprehensive membership validation.The method properly validates membership using pointer-based checks (lines 272-281), handles all removal positions (head, tail, middle), and uses .release stores (lines 302, 309) to publish updates when modifying the head pointer.
333-358: LGTM! popOrTransition correctly handles cancellation races.The retry loop (line 337) properly handles the race where waiters remove themselves via cancellation between the empty check and pop attempt, ensuring eventual progress to either transition the state or pop a remaining item.
362-801: LGTM! Comprehensive test suite covers concurrent scenarios.The test suite includes basic operations, state transitions, double removal detection, and several concurrent stress tests with heavy contention. This provides good coverage for validating the lock-free queue's correctness under concurrent access.
src/runtime.zig (17)
698-703: LGTM! Imports updated for generic data structures.The new imports introduce WaitNode and generic concurrent/simple stacks and queues, replacing the previous Awaitable-specific collections.
712-714: LGTM! Alignment assertion ensures tagged pointer compatibility.The compile-time assertion verifies WaitNode has 8-byte alignment, which is necessary for using the lower bits as tags in the concurrent queue's tagged pointer encoding.
323-341: LGTM! VTable-based wake mechanism for tasks.The wait_node_vtable (lines 323-325) enables polymorphic wakeup via the waitNodeWake callback, which correctly extracts the awaitable and resumes the task with .maybe_remote mode. The fromWaitNode helper (lines 337-341) provides clean reverse lookup.
361-361: LGTM! Empty vtable for blocking tasks.AnyBlockingTask uses an empty vtable since blocking tasks are woken via the generic markComplete path rather than needing custom wake behavior.
98-143: LGTM! Blocking completion handling migrated to WaitNode.The threadPoolCallback (line 98) correctly pushes the awaitable's wait_node, and drainBlockingCompletions (lines 136-143) properly extracts the awaitable via @fieldParentPtr before marking complete.
173-185: LGTM! waitForComplete correctly uses WaitNode entries.The method properly enqueues the task's wait_node (line 173), handles double-check removal (line 179), and cleans up on cancellation (line 185), maintaining the same wait semantics with the new abstraction.
217-247: LGTM! Timed wait properly migrated to WaitNode.The timeout context correctly holds WaitNode references (lines 226-227), the timeout callback removes the wait_node (line 241), and cancellation cleanup operates on wait_node (line 247). All semantics preserved with the new abstraction.
270-276: LGTM! markComplete uses polymorphic wake dispatch.The executor parameter is correctly marked unused (line 270) since wakeup is now handled via wait_node.wake() (line 276), which uses the vtable to dispatch to the appropriate wake implementation.
727-737: LGTM! Executor queues migrated to WaitNode-based stacks.The ready queues (lines 727-728, 731) and blocking completions (line 737) now use generic WaitNode-based stacks, replacing the previous Awaitable-specific collections.
883-883: LGTM! yield() now returns gracefully outside coroutine context.The early return when current_coroutine is null (line 883) prevents panics when yield() is called outside a coroutine context, improving robustness as stated in the PR objectives.
1351-1373: LGTM! SelectWaiter simplified to contain only WaitNode.The refactored SelectWaiter (line 1351) contains just the wait_node field instead of a full Awaitable, with an init() method (lines 1359-1366) for clean construction. The waitNodeWake callback (lines 1368-1372) correctly sets the ready flag and resumes the task.
1382-1382: Verify public exposure of current_executor TLS.The current_executor field is now publicly exposed (pub threadlocal). While the PR summary mentions this change, consider whether exposing thread-local state is necessary for the API. This could increase coupling between the runtime and external code.
Can you confirm this visibility change is intentional and describe the use case requiring public access to the current_executor TLS?
829-831: LGTM! Task spawn correctly enqueues wait_node.The spawn method properly pushes the task's wait_node to the ready queue (line 848), maintaining FIFO semantics with the new WaitNode-based abstraction.
909-910: LGTM! yield() correctly pops and converts WaitNode to task.The yield method properly pops a wait_node from the ready queue (line 909) and converts it to an AnyTask using fromWaitNode (line 910) before switching contexts.
1054-1055: LGTM! Run loop correctly processes WaitNode-based ready queue.The run loop properly pops wait_node entries (line 1054) and converts them to tasks using fromWaitNode (line 1055) for execution.
1557-1572: LGTM! select() correctly uses WaitNode for multi-wait.The select implementation properly initializes SelectWaiter with wait_node (line 1557), enqueues wait_node entries (line 1564), and removes them on exit (line 1572), maintaining the same select semantics with the new abstraction.
492-494: LGTM! Future initialization properly sets up wait_node vtable.The Future.init method correctly initializes the wait_node field with the appropriate vtable (lines 492-494), enabling polymorphic wake dispatch.
Adds ThreadWaiter as a new WaitNode type for external threads waiting on Awaitables. This unifies the wake mechanism and enables cleaner semantics by changing Awaitable.state (u32) to Awaitable.done (bool). Key changes: - Add ThreadWaiter struct with its own futex_state for parking - Change Awaitable.state to Awaitable.done (bool is more semantic) - Update waitForComplete thread path to use ThreadWaiter - Update timedWaitForComplete thread path to use ThreadWaiter - Remove direct Futex.wake from markComplete (unified wake via WaitNode) - Update all state comparisons to use done flag Benefits: - Unified wake mechanism - everything through WaitNode.wake() - More semantic - done (bool) vs state (u32 with magic values) - Clean separation - futex is ThreadWaiter's concern, not Awaitable's - Foundation for making other types Awaitable (ResetEvent, etc.) - Enables external threads to wait on any Awaitable type
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (2)
src/runtime.zig (2)
372-372: Consider adding clarifying comments for empty vtables.The empty
wait_node_vtableforAnyBlockingTaskandAnyFutureis correct since these are never added to ready queues—they only participate inwaiting_liststructures and are woken viamarkComplete(). However, this reasoning is subtle and a brief comment would help future maintainers understand why nowakefunction is needed.Example:
- const wait_node_vtable = WaitNode.VTable{}; + // Empty vtable: BlockingTask is never in ready queues, only waiting lists. + // Woken via markComplete() which drains waiting_list directly. + const wait_node_vtable = WaitNode.VTable{};Also applies to: 392-392
723-725: Consider adding a descriptive message to the alignment assertion.The alignment check is important for correctness, but the assertion would benefit from explaining why 8-byte alignment is required (e.g., for lock-free data structures or atomic operations).
-comptime { - std.debug.assert(@alignOf(WaitNode) == 8); -} +comptime { + // WaitNode requires 8-byte alignment for lock-free intrusive data structures + std.debug.assert(@alignOf(WaitNode) == 8); +}
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/core/Awaitable.zig(2 hunks)src/runtime.zig(26 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-16T14:33:19.718Z
Learnt from: lalinsky
PR: lalinsky/zio#48
File: src/core/ConcurrentAwaitableList.zig:254-269
Timestamp: 2025-10-16T14:33:19.718Z
Learning: In the zio repository's `src/core/ConcurrentAwaitableList.zig` and `src/core/Awaitable.zig`, the `in_list` field should remain debug-only (conditional compilation with `builtin.mode == .Debug`). Double-removal detection in `ConcurrentAwaitableList.remove()` uses pointer-based checks (comparing `prev`/`next` against `head`/`tail`) rather than relying on a regular `in_list` field.
Applied to files:
src/core/Awaitable.zig
🔇 Additional comments (23)
src/core/Awaitable.zig (5)
5-6: LGTM! Clean import additions for the WaitNode abstraction.The new imports align with the refactoring objectives and replace the previous Awaitable-specific collection types.
24-24: LGTM! Central field for the WaitNode abstraction.This field enables vtable-based polymorphic wake behavior and participation in generic wait queues.
26-27: LGTM! Simplified completion tracking.The boolean
doneflag is clearer than the previous state model and provides the necessary memory ordering guarantees via atomic operations.
32-33: LGTM! Generic queue improves reusability.Replacing the Awaitable-specific list with a generic
ConcurrentQueue(WaitNode)achieves better separation of concerns and code reuse.
35-39: LGTM! Clear cancellation API with correct memory ordering.The method correctly uses
.releasesemantics to ensure the cancellation flag is visible to the thread that will consume it inyield().src/runtime.zig (18)
98-98: LGTM! Consistent with WaitNode-based queues.The blocking completion path now correctly pushes the
wait_nodeinstead of the awaitable, aligning with the new abstraction.
136-143: LGTM! Correct conversion from WaitNode back to Awaitable.The use of
@fieldParentPtrto retrieve the awaitable from the embeddedwait_nodeis safe and follows Zig idioms.
157-207: LGTM! Robust wait implementation with proper synchronization.The double-check pattern (lines 159, 175, 196) correctly prevents lost wakeups. The memory ordering (
.acquireondone.load()) pairs properly with the.releaseinmarkComplete(). The thread path usingThreadWaiterwith futex-based parking is a clean solution for external threads.
214-277: LGTM! Timed wait correctly extends the basic wait pattern.The timeout handling via
TimeoutContextand the thread path usingFutex.timedWaitare both implemented correctly. The callback-based timeout handling (line 246) allows proper cleanup of the wait queue.
283-292: LGTM! Correct completion signaling with proper memory ordering.The
.releasestore todone(line 286) ensures all prior writes are visible before waking waiters. The vtable-basedwake()calls provide clean polymorphism. The unusedexecutorparameter is intentional per the PR objectives.
334-352: LGTM! Clean vtable-based polymorphism for task wakeups.The
wait_node_vtableenables WaitNode to wake tasks across executors using.maybe_remotemode (line 340). ThefromWaitNode()helper correctly navigates the structure hierarchy via chained@fieldParentPtrcalls.
503-505: LGTM! Consistent wait_node initialization across all awaitable types.All three awaitable types (Future, BlockingTask, Task) correctly initialize their embedded
wait_nodewith the appropriate vtable, enabling polymorphic wake behavior.Also applies to: 587-589, 840-842
640-640: LGTM! Simplified completion check.Using the
doneflag with.acquireordering is clearer than the previous state-based approach and ensures proper visibility of the result.
710-714: LGTM! Generic collections improve code reuse.The imports of generic
ConcurrentStack,SimpleStack,SimpleQueue, andConcurrentQueueachieve the PR objective of replacing Awaitable-specific collections with reusable structures.
738-748: LGTM! Queue types correctly updated to WaitNode-based.The distinction between concurrent stacks (for cross-thread communication) and simple stacks (for single-threaded ready queues) is maintained, now with the cleaner WaitNode abstraction.
894-894: LGTM! More forgiving API for yield() outside coroutines.The graceful return when
current_coroutineis null (instead of panicking) aligns with the PR objectives and makes the API safer. This matches the pattern used inRuntime.yield()at line 1487.
911-911: LGTM! Consistent WaitNode usage in scheduler paths.The ready queue operations correctly push/pop
wait_nodeand usefromWaitNode()for safe conversion back toAnyTask.Also applies to: 920-921, 1065-1066
1133-1133: LGTM! All markReady paths updated consistently.Both local and remote ready queue paths correctly push the task's
wait_node, maintaining consistency across thread boundaries.Also applies to: 1140-1140, 1148-1148
1361-1384: LGTM! SelectWaiter simplified with WaitNode.The refactored
SelectWaiteris cleaner—it only needs aWaitNodeand a task reference instead of a fullAwaitable. Theinit()function and vtable-basedwaitNodeWake()provide clear initialization and wake semantics.
1387-1409: LGTM! Clean futex-based thread waiting implementation.The
ThreadWaiterprovides a clean abstraction for external threads to wait on awaitables. The futex-based implementation with correct memory ordering (.releaseon store, line 1406) pairs properly with the wait loops inwaitForComplete()andtimedWaitForComplete().
1418-1418: LGTM! Public access to current_executor enables cleaner APIs.Making
current_executorpublic supports the PR objective of removing executor parameters from methods by allowing internal access to the current executor via this threadlocal.
1593-1593: LGTM! Select implementation correctly updated to WaitNode-based.The
select()implementation properly uses the newSelectWaiter.init()API and works withwait_nodereferences throughout, maintaining correct registration and cleanup semantics.Also applies to: 1600-1600, 1608-1608
157-292: Excellent refactoring quality overall.The WaitNode-based refactoring demonstrates strong systems programming:
- Correct synchronization: Double-check patterns prevent lost wakeups (lines 175, 196, 225, 266), and memory ordering is sound (
.release/.acquirepairs).- Clean abstractions: WaitNode vtables provide polymorphism without overhead, and generic collections replace specialized ones.
- Thread safety: Both coroutine and thread waiting paths (
ThreadWaiter) are correctly implemented with futex-based parking.The refactoring achieves its stated goals: clearer separation of concerns, more reusable data structures, and reduced coupling.
Also applies to: 1361-1409
Introduces two convenience methods to simplify common patterns: - Runtime.getCurrentTask(): Returns the currently executing task using the threadlocal current_executor, supporting multiple executors - AnyTask.getExecutor(): Returns the executor that owns a task Updates all call sites in waitForComplete(), timedWaitForComplete(), select(), and sync primitives (Mutex, Condition, ResetEvent) to use these helpers instead of manual conversions. Benefits: - Cleaner, more readable code - Consistent pattern across the codebase - Preparation for multi-executor support
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/runtime.zig (1)
281-290: Consider removing the unused executor parameter.The
executorparameter is now unused sincewait_node.wake()handles polymorphic wakeup internally. Consider removing it to simplify the API unless it's retained for compatibility or future-proofing.Apply this diff if removal is desired:
-pub fn markComplete(awaitable: *Awaitable, executor: ?*Executor) void { - _ = executor; +pub fn markComplete(awaitable: *Awaitable) void {Note: This would require updating all call sites.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/runtime.zig(26 hunks)src/sync/Condition.zig(6 hunks)src/sync/Mutex.zig(3 hunks)src/sync/ResetEvent.zig(7 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- src/sync/Condition.zig
- src/sync/ResetEvent.zig
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-15T19:38:44.659Z
Learnt from: lalinsky
PR: lalinsky/zio#47
File: src/sync/Mutex.zig:237-237
Timestamp: 2025-10-15T19:38:44.659Z
Learning: In the `unlock` method of `src/sync/Mutex.zig`, the `runtime` parameter is intentionally retained (marked with `_ = runtime;`) for API consistency and future-proofing, even though it's not currently used in the implementation.
Applied to files:
src/sync/Mutex.zig
🔇 Additional comments (20)
src/sync/Mutex.zig (4)
30-31: LGTM: Clean import updates.The new imports for
WaitNodeandConcurrentQueuecorrectly replace the previous Awaitable-specific data structures.
39-43: LGTM: Queue type correctly updated.The queue field and state alias have been properly updated to use
ConcurrentQueue(WaitNode)while preserving the sentinel-based lock state encoding.
67-68: LGTM: Lock method correctly adapted to WaitNode API.The method now uses
getCurrentTask()and operates onwait_nodeinstead ofawaitabledirectly. The fast path, slow path, and cancellation handling all remain functionally correct.Also applies to: 77-77, 82-82
120-120: LGTM: Unlock method correctly uses WaitNode wake mechanism.The method now uses
popOrTransitionandwait_node.wake()for polymorphic wakeup. The runtime parameter is intentionally retained for API consistency, as noted in previous reviews. Based on learnings.Also applies to: 123-125
src/runtime.zig (16)
98-98: LGTM: Blocking completions correctly adapted to WaitNode.The pattern of pushing
wait_node, draining it atomically, and converting back toawaitablevia@fieldParentPtris correct and maintains the original semantics.Also applies to: 136-143
159-206: LGTM: waitForComplete correctly implements dual-path waiting.The coroutine path uses the task's embedded
wait_node, while the thread path creates aThreadWaiterwith its ownwait_nodeand futex. Both approaches correctly handle the done flag race condition.
213-275: LGTM: Timed wait correctly adapted to WaitNode.Both the coroutine path (with timeout callbacks) and thread path (with futex timedWait) properly handle the
wait_nodeabstraction and race conditions.
332-360: LGTM: AnyTask vtable and helpers correctly implement WaitNode interface.The vtable wiring (
wait_node_vtable→waitNodeWake→resumeTask) and thefromWaitNodehelper with kind assertion are both correct.
375-375: LGTM: Empty vtables appropriate for BlockingTask and Future.The empty
wait_node_vtableforAnyBlockingTaskandAnyFutureis correct since these types complete via different mechanisms (blocking completion queue and explicitmarkCompleterespectively) rather than direct task resumption.Also applies to: 395-395
506-508: LGTM: Initialization correctly wires wait_node vtables.Both
FutureandBlockingTaskinitialization properly sets thewait_node.vtablefield.Also applies to: 590-592
713-728: LGTM: Generic data structures properly imported with alignment check.The consolidated imports replace Awaitable-specific structures, and the compile-time alignment assertion for
WaitNodeis good defensive programming for lock-free data structure safety.
741-751: LGTM: Executor queues consistently updated to WaitNode-based.All scheduling queues now use generic
WaitNode-based structures while maintaining the original semantics (local vs. concurrent).
896-897: LGTM: Improved error handling in yield.The change to return gracefully when
current_coroutineis null (instead of panicking) improves the API's safety and usability, aligning with the PR's stated objective.
843-845: LGTM: Task spawning and queue operations correctly use WaitNode.The spawn method properly initializes the
wait_node.vtable, and all queue push/pop operations correctly operate onwait_nodewith appropriate conversions viafromWaitNode.Also applies to: 862-862, 914-914, 923-924
1068-1069: LGTM: Run loop correctly processes WaitNode queue.The main execution loop properly pops
wait_nodeand converts toAnyTaskviafromWaitNode.
1136-1136: LGTM: markReady correctly uses WaitNode for all paths.Both local and remote ready paths correctly push
wait_nodeto the appropriate queues, maintaining the original cross-thread safety semantics.Also applies to: 1143-1143, 1151-1151
1365-1387: LGTM: SelectWaiter correctly simplified to use WaitNode.The refactored
SelectWaiternow holds only aWaitNodeinstead of a fullAwaitable, reducing coupling as stated in the PR objectives. The vtable wiring correctly sets the ready flag and resumes the task.
1389-1412: LGTM: ThreadWaiter correctly implements futex-based thread parking.The
ThreadWaitertype properly encapsulates the futex-based parking mechanism for external threads. The vtable wake callback correctly updates the futex state and wakes the waiting thread.
1421-1421: LGTM: current_executor appropriately made public.Making
current_executorpublic enables internal components (likeConcurrentQueue) to access the thread-local executor without passing it as a parameter, aligning with the PR's goal of removing executor parameters.
1530-1534: LGTM: getCurrentTask correctly implemented.The method properly retrieves the current task via the public
current_executorthread-local, returningnullwhen not in a coroutine context.
Summary
This PR introduces a new
WaitNodeabstraction to separate concerns between "what can be waited on" (Awaitable) and "what participates in wait queues" (WaitNode). This simplifies the architecture and makes the codebase more maintainable.Key changes:
WaitNodetype with vtable-based polymorphic wake behaviorRuntime.current_executorinternallySelectWaiterto containWaitNodedirectly instead of a fullAwaitableselect_waiterfromAwaitableKindenum (no longer needed)Executor.yield()gracefully return when not in coroutine context instead of panickingexecutorfields inTimeoutContextstructsBenefits:
Test plan
Summary by CodeRabbit
Refactor
New Features