Skip to content

Refactor wait queues to use WaitNode abstraction - #52

Merged
lalinsky merged 4 commits into
mainfrom
refactor/waitnode-abstraction
Oct 18, 2025
Merged

lalinsky merged 4 commits into
mainfrom
refactor/waitnode-abstraction

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 18, 2025 •

Copy link
Copy Markdown
Owner

Summary

This PR introduces a new WaitNode abstraction 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:

  • Introduced WaitNode type with vtable-based polymorphic wake behavior
  • Replaced Awaitable-specific data structures (SimpleAwaitableList, ConcurrentAwaitableStack, etc.) with generic versions (SimpleQueue, ConcurrentQueue, etc.)
  • Removed executor parameter from ConcurrentQueue methods - now uses Runtime.current_executor internally
  • Simplified SelectWaiter to contain WaitNode directly instead of a full Awaitable
  • Removed select_waiter from AwaitableKind enum (no longer needed)
  • Made Executor.yield() gracefully return when not in coroutine context instead of panicking
  • Cleaned up unused executor fields in TimeoutContext structs

Benefits:

  • Better separation of concerns between waiting and wait queue participation
  • More reusable, generic data structures
  • Cleaner API without threading executor parameters everywhere
  • Reduced coupling between components
  • Simpler polymorphism via vtables instead of switch statements on kind

Test plan

  • All 97 existing tests pass
  • check.sh passes (format, tests, build)
  • No behavior changes - pure refactoring

Summary by CodeRabbit

  • Refactor

    • Unified wait/wake mechanism for more reliable task signaling and simpler completion tracking across the runtime.
    • Synchronization primitives (Mutex, Condition, ResetEvent) and task/join flows updated to use the new wake path while preserving cancellation semantics.
  • New Features

    • Added generic concurrent and single-threaded queue/stack utilities and a lightweight wait-node abstraction to support richer concurrency patterns and easier wait-queue management.

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
@coderabbitai

coderabbitai Bot commented Oct 18, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Replaces 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

Cohort / File(s) Summary
Awaitable core
src/core/Awaitable.zig
Removed intrusive next/prev and old waiting_list; added wait_node: WaitNode, done: std.atomic.Value(bool), waiting_list: ConcurrentQueue(WaitNode) = .empty; removed in_list debug flag and select_waiter variant; added pub fn requestCancellation.
Wait node
src/core/WaitNode.zig
New WaitNode API with VTable (wake function), pub fn wake(self: *WaitNode), and queue-participation fields (prev, next, in_list) plus default wake implementation.
Removed legacy lists/stacks
src/core/ConcurrentAwaitableStack.zig, src/core/SimpleAwaitableList.zig, src/core/SimpleAwaitableStack.zig
Deleted legacy concurrent/single-threaded awaitable list/stack modules and their public APIs and tests.
New concurrent primitives
src/utils/concurrent_queue.zig, src/utils/concurrent_stack.zig
Added ConcurrentQueue(T) (tagged-pointer + mutation lock FIFO) with push/pop/remove/popOrTransition and tests; added ConcurrentStack(T) (lock-free CAS LIFO) with push/popAll.
New simple primitives
src/utils/simple_queue.zig, src/utils/simple_stack.zig
Added single-threaded SimpleQueue(T) (doubly-linked FIFO) and SimpleStack(T) (singly-linked LIFO) utilities with push/pop/concat/remove/prepend APIs and debug invariants.
Runtime integration
src/runtime.zig
Rewired runtime wait/select/join/markComplete to use WaitNode entries and vtable wake paths; made Runtime.threadlocal current_executor public; updated Task/BlockingTask/Future/SelectWaiter/JoinHandle initialization and wake logic to use wait_node and done flag.
Sync primitives
src/sync/Condition.zig, src/sync/Mutex.zig, src/sync/ResetEvent.zig
Replaced ConcurrentAwaitableList with ConcurrentQueue(WaitNode) for wait queues; wait/timedWait/signal/broadcast/unlock/set now enqueue/dequeue wait_node and call wait_node.wake().

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
Loading
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
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

Poem

🐰
I nudged a node where lists once lay,
Queues hum softly as waiters sway,
Stacks hop CAS, tails tucked in line,
Vtables wake at signaling time,
A rabbit nods — the runtime’s fine.

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "Refactor wait queues to use WaitNode abstraction" directly and accurately summarizes the primary change in this changeset. The PR's core purpose is to introduce a new WaitNode abstraction and refactor wait queue infrastructure across multiple modules (Awaitable, Condition, Mutex, ResetEvent, and runtime) to use this abstraction instead of Awaitable-specific data structures. The title correctly identifies both the nature of the change (refactor) and its focus (wait queues using WaitNode), making it clear and specific enough for a teammate scanning history to understand the architectural shift being made.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/waitnode-abstraction

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between af75f6b and f39ebf6.

📒 Files selected for processing (1)
  • src/runtime.zig (27 hunks)
🔇 Additional comments (21)
src/runtime.zig (21)

98-98: LGTM: Blocking completions refactored to WaitNode.

The blocking completions flow is correctly updated to push/pop WaitNode and reconstruct the Awaitable via @fieldParentPtr. The conversion logic is sound.

Also applies to: 136-140


215-274: LGTM: Timed wait correctly handles futex errors.

The timed waiting logic is properly refactored to use WaitNode and correctly uses try with std.Thread.Futex.timedWait, which can return timeout errors. The TimeoutContext simplification (removing unused executor field) aligns with the PR objectives.


281-289: LGTM: markComplete refactored to use WaitNode abstraction.

The wake-all logic is correctly updated to use polymorphic wait_node.wake() calls. Memory ordering is sound: release store on done pairs with acquire loads in waiters.


331-359: LGTM: AnyTask gains WaitNode vtable and helpers.

The vtable-based polymorphic wake callback is correctly implemented. The waitNodeWake callback properly converts from WaitNode back to Awaitable and resumes the task. Helper methods fromWaitNode and getExecutor are straightforward and useful.


505-507: LGTM: Future initialization includes WaitNode setup.

The wait_node initialization with the appropriate vtable is correctly placed in the Future.init method.


589-591: LGTM: BlockingTask initialization includes WaitNode setup.

Consistent with the WaitNode refactor, the vtable is properly initialized.


642-642: LGTM: hasResult uses done flag.

The completion check correctly uses the done atomic flag with acquire semantics.


711-727: LGTM: Generic data structure imports and alignment assertion.

The new imports for WaitNode-based generic data structures are appropriate. The compile-time alignment check ensures WaitNode meets alignment requirements (likely for atomic operations or pointer tagging).


740-750: LGTM: Executor queues refactored to WaitNode-based.

The ready queues and blocking completions are correctly updated to use generic SimpleStack(WaitNode) and ConcurrentStack(WaitNode), aligning with the PR objectives of using reusable generic data structures.


842-844: LGTM: spawn() updated for WaitNode.

Task initialization and ready queue operations correctly use the WaitNode abstraction.

Also applies to: 861-861


896-896: LGTM: yield() now returns gracefully outside coroutine context.

The early return when current_coroutine is null (line 896) prevents panics and aligns with the stated PR objective. This makes the API more forgiving when called from non-coroutine contexts.


913-913: LGTM: yield() queue operations use WaitNode.

The ready queue push/pop operations are correctly updated to work with WaitNode and use fromWaitNode for reconstruction.

Also applies to: 922-923


1067-1068: LGTM: Run loop correctly uses WaitNode.

The main execution loop properly pops WaitNode entries and converts them to tasks. The completion path correctly calls markComplete which now handles WaitNode wakeups internally.

Also applies to: 1087-1087


1135-1150: LGTM: markReady() uses WaitNode for queue operations.

All paths (local, maybe_remote) correctly push the task's wait_node to the appropriate ready queue.


1364-1386: LGTM: SelectWaiter simplified to hold WaitNode directly.

This is a significant improvement. SelectWaiter no longer needs to embed a full Awaitable—it just holds a WaitNode with a custom wake callback. The init() method provides a clean construction API. The wake callback correctly marks ready=true and resumes the task.


1388-1411: LGTM: ThreadWaiter provides futex-based thread parking.

The new ThreadWaiter abstraction cleanly handles external thread waiting using futex. The wake callback correctly updates the futex state with release semantics and wakes the waiting thread. This separates thread-based waiting from coroutine-based waiting.


1420-1420: LGTM: current_executor made public.

Making the threadlocal current_executor public enables external code to check executor context, which may be necessary for the WaitNode abstraction to work correctly across modules.


1527-1533: LGTM: getCurrentTask uses threadlocal executor.

The updated implementation uses Runtime.current_executor threadlocal, which is more flexible and enables future multi-executor support. The null-safe fallback is appropriate.


1596-1617: LGTM: select() correctly uses SelectWaiter and WaitNode.

The select implementation properly constructs SelectWaiters using the new init() method and adds their wait_nodes to waiting lists. The defer cleanup correctly removes non-ready waiters.


374-374: No issues found—empty vtables are safe.

The WaitNode.VTable struct has a default value for its wake field: wake: *const fn (self: *WaitNode) void = defaultWake. When AnyBlockingTask and AnyFuture use empty vtables (WaitNode.VTable{}), they automatically receive the defaultWake function, which is a safe no-op. There is no risk of null function pointers or missing wake callbacks.


201-204: Based on the Zig standard library documentation, Futex.wait() blocks the caller until either the value at ptr changes, the caller is unblocked by wake(), or the caller is unblocked spuriously. The return type is error{Timeout}!void, not a broader error union.

The Futex implementation handles EINTR (interrupt) internally by continuing the wait loop, so callers do not need to handle this case. The code at lines 201–204 in src/runtime.zig is correct: the loop properly re-checks the done flag before waiting, which handles both spurious wakeups and ensures the flag is checked after any platform-specific interruption.


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/utils/simple_stack.zig (1)

1-13: Document the complexity of prependByMoving.

The module documentation mentions O(1) push and pop, but prependByMoving is 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

📥 Commits

Reviewing files that changed from the base of the PR and between 6c76bd4 and 506399b.

📒 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 next pointers 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:

  • .acquire load ensures visibility of previous pushes
  • .release on successful CAS publishes the new item and its chain
  • .acquire on failure ensures the retry sees the updated head

38-43: LGTM! Correct atomic drain operation.

The .acq_rel ordering ensures the caller sees all pushed items and properly publishes the empty state. The returned SimpleStack correctly takes ownership of the drained items in LIFO order.

src/core/WaitNode.zig (2)

12-20: LGTM! Clean vtable design.

The no-op defaultWake is reasonable for this abstraction. Concrete types using WaitNode will 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_list provides safety without runtime overhead in release builds. The vtable delegation in wake() 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 .empty initialization is appropriate for the new queue type.


86-107: LGTM! Correct WaitNode integration in wait().

The changes from awaitable to wait_node are 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 TimeoutContext simplification (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 runtime parameter is appropriately marked. The wake logic is now encapsulated in the WaitNode vtable, eliminating the need to directly schedule tasks. Both signal() and broadcast() 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 unused runtime parameter 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

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/runtime.zig (2)

372-372: Consider adding clarifying comments for empty vtables.

The empty wait_node_vtable for AnyBlockingTask and AnyFuture is correct since these are never added to ready queues—they only participate in waiting_list structures and are woken via markComplete(). However, this reasoning is subtle and a brief comment would help future maintainers understand why no wake function 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

📥 Commits

Reviewing files that changed from the base of the PR and between 506399b and 63871ad.

📒 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 done flag 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 .release semantics to ensure the cancellation flag is visible to the thread that will consume it in yield().

src/runtime.zig (18)

98-98: LGTM! Consistent with WaitNode-based queues.

The blocking completion path now correctly pushes the wait_node instead of the awaitable, aligning with the new abstraction.


136-143: LGTM! Correct conversion from WaitNode back to Awaitable.

The use of @fieldParentPtr to retrieve the awaitable from the embedded wait_node is 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 (.acquire on done.load()) pairs properly with the .release in markComplete(). The thread path using ThreadWaiter with 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 TimeoutContext and the thread path using Futex.timedWait are 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 .release store to done (line 286) ensures all prior writes are visible before waking waiters. The vtable-based wake() calls provide clean polymorphism. The unused executor parameter is intentional per the PR objectives.


334-352: LGTM! Clean vtable-based polymorphism for task wakeups.

The wait_node_vtable enables WaitNode to wake tasks across executors using .maybe_remote mode (line 340). The fromWaitNode() helper correctly navigates the structure hierarchy via chained @fieldParentPtr calls.


503-505: LGTM! Consistent wait_node initialization across all awaitable types.

All three awaitable types (Future, BlockingTask, Task) correctly initialize their embedded wait_node with the appropriate vtable, enabling polymorphic wake behavior.

Also applies to: 587-589, 840-842


640-640: LGTM! Simplified completion check.

Using the done flag with .acquire ordering 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, and ConcurrentQueue achieve 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_coroutine is null (instead of panicking) aligns with the PR objectives and makes the API safer. This matches the pattern used in Runtime.yield() at line 1487.


911-911: LGTM! Consistent WaitNode usage in scheduler paths.

The ready queue operations correctly push/pop wait_node and use fromWaitNode() for safe conversion back to AnyTask.

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 SelectWaiter is cleaner—it only needs a WaitNode and a task reference instead of a full Awaitable. The init() function and vtable-based waitNodeWake() provide clear initialization and wake semantics.


1387-1409: LGTM! Clean futex-based thread waiting implementation.

The ThreadWaiter provides a clean abstraction for external threads to wait on awaitables. The futex-based implementation with correct memory ordering (.release on store, line 1406) pairs properly with the wait loops in waitForComplete() and timedWaitForComplete().


1418-1418: LGTM! Public access to current_executor enables cleaner APIs.

Making current_executor public 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 new SelectWaiter.init() API and works with wait_node references 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/.acquire pairs).
  • 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

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/runtime.zig (1)

281-290: Consider removing the unused executor parameter.

The executor parameter is now unused since wait_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

📥 Commits

Reviewing files that changed from the base of the PR and between 63871ad and af75f6b.

📒 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 WaitNode and ConcurrentQueue correctly 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 on wait_node instead of awaitable directly. 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 popOrTransition and wait_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 to awaitable via @fieldParentPtr is 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 a ThreadWaiter with its own wait_node and 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_node abstraction and race conditions.


332-360: LGTM: AnyTask vtable and helpers correctly implement WaitNode interface.

The vtable wiring (wait_node_vtable → waitNodeWake → resumeTask) and the fromWaitNode helper with kind assertion are both correct.


375-375: LGTM: Empty vtables appropriate for BlockingTask and Future.

The empty wait_node_vtable for AnyBlockingTask and AnyFuture is correct since these types complete via different mechanisms (blocking completion queue and explicit markComplete respectively) rather than direct task resumption.

Also applies to: 395-395


506-508: LGTM: Initialization correctly wires wait_node vtables.

Both Future and BlockingTask initialization properly sets the wait_node.vtable field.

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 WaitNode is 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_coroutine is 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 on wait_node with appropriate conversions via fromWaitNode.

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_node and converts to AnyTask via fromWaitNode.


1136-1136: LGTM: markReady correctly uses WaitNode for all paths.

Both local and remote ready paths correctly push wait_node to 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 SelectWaiter now holds only a WaitNode instead of a full Awaitable, 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 ThreadWaiter type 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_executor public enables internal components (like ConcurrentQueue) 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_executor thread-local, returning null when not in a coroutine context.

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.

1 participant