Repository navigation
Refactor select() to support arbitrary futures via Future protocol - #70
Conversation
…elect - Add FutureType() helper to handle both direct types and pointers - Rename asyncCancel to asyncCancelWait for consistency - Implement Future protocol methods on ResetEvent (hasResult, getResult, asyncWait, asyncCancelWait) - Add test demonstrating select() with ResetEvent and Task
- Add signaled field to SelectWaiter to track which waiter was woken - Change asyncWait() to return bool (false if already complete, true if added to queue) - Implement asyncWait/asyncCancelWait on Awaitable as base implementation - Add asyncWait/asyncCancelWait to FutureImpl, Task, BlockingTask, Future - Update JoinHandle to forward asyncWait/asyncCancelWait to Awaitable - Update ResetEvent.asyncWait to return bool - Implement Future protocol on Notify (asyncWait, asyncCancelWait, getResult) - Refactor select() to call asyncWait directly and check signaled flags instead of hasResult - Remove hasResult checks from select - now uses asyncWait return value for fast path
WalkthroughAdds a WaitQueue-based async-wait protocol to Awaitable (asyncWait/asyncCancelWait/markComplete), converts CoroutineState to bit-flag encodings with isWaiting, extracts select/wait into a new Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Caller as Task (caller)
participant Select as select(rt, futures)
participant FutA as Awaitable A
participant FutB as Awaitable B
participant WaitA as WaitNode A
participant WaitB as WaitNode B
participant Exec as Executor
Caller->>Select: select(rt, {a: FutA, b: FutB})
Select->>FutA: FutA.asyncWait(WaitA) -- fast-path check & enqueue
Select->>FutB: FutB.asyncWait(WaitB) -- fast-path check & enqueue
alt immediate completion
Select-->>Caller: return immediate Result for completed field
else
Select->>Exec: yield (suspend caller)
Note right of FutA: FutA.markComplete() or FutB.markComplete()
FutA->>WaitA: wake (pop waiters → mark signaled)
WaitA->>Select: notify selection (wakes caller)
Select->>FutB: FutB.asyncCancelWait(WaitB) -- cleanup non-signaled waiters
Select-->>Caller: return union result for signaled field
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🧰 Additional context used🧠 Learnings (3)📓 Common learnings📚 Learning: 2025-10-16T14:33:19.718ZApplied to files:
📚 Learning: 2025-10-23T16:17:53.546ZApplied to files:
⏰ 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)
🔇 Additional comments (4)
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: 2
🧹 Nitpick comments (8)
src/sync/Notify.zig (2)
205-211: Make asyncWait accept const self to support const-field futuresOther Future impls use
*const+@constCastto allow calling through const fields. Align Notify for consistency and flexibility.-pub fn asyncWait(self: *Notify, wait_node: *WaitNode) bool { - self.wait_queue.push(wait_node); +pub fn asyncWait(self: *const Notify, wait_node: *WaitNode) bool { + const mutable_self: *Notify = @constCast(self); + mutable_self.wait_queue.push(wait_node); return true; }
409-433: Deflake test by avoiding tiny sleeps; prefer yields
try rt.sleep(5)(likely 5ns) can flake under slow CI. Yield to scheduler instead.- fn signalerTask(rt: *Runtime, notify: *Notify) !void { - try rt.sleep(5); - notify.signal(rt); - } + fn signalerTask(rt: *Runtime, notify: *Notify) !void { + try rt.yield(); + try rt.yield(); + notify.signal(rt); + }src/sync/ResetEvent.zig (1)
413-438: Deflake select test: avoid tiny sleepsUse a couple of yields before
event.set(rt)to reduce timing flakiness.- fn setterTask(rt: *Runtime, event: *ResetEvent) !void { - try rt.sleep(5); - event.set(rt); - try rt.sleep(5); - } + fn setterTask(rt: *Runtime, event: *ResetEvent) !void { + try rt.yield(); + try rt.yield(); + event.set(rt); + }src/select.zig (4)
6-11: Clarify cancel semantics or track registration to avoid relying on undefined idempotency.Cleanup unconditionally calls asyncCancelWait() for non-signaled futures, even if asyncWait() never attached that wait_node (fast-path). The protocol comment doesn’t state that asyncCancelWait() must be safe/idempotent when the node isn’t in the queue.
Either:
- Specify idempotency in the protocol comment; or
- Track which waiters were attached and only cancel those.
Suggested change (preferred: track attachments):
@@ - // Clean up waiters on all exit paths + // Clean up waiters on all exit paths defer { - inline for (fields, 0..) |field, i| { - if (!waiters[i].signaled.load(.acquire)) { - var future = @field(futures, field.name); - future.asyncCancelWait(&waiters[i].wait_node); - } - } + inline for (fields, 0..) |field, i| { + if (attached[i] and !waiters[i].signaled.load(.acquire)) { + var future = @field(futures, field.name); + future.asyncCancelWait(&waiters[i].wait_node); + } + } } @@ - inline for (fields, 0..) |field, i| { + var attached: [fields.len]bool = undefined; + inline for (fields, 0..) |field, i| { var future = @field(futures, field.name); const waiting = future.asyncWait(&waiters[i].wait_node); + attached[i] = waiting; if (!waiting) { return @unionInit(U, field.name, future.getResult()); } }If you keep the current cleanup, please amend the protocol block above to require asyncCancelWait() to be safe when the node isn’t present.
Also applies to: 131-139
90-106: Docstring still says JoinHandle-only; update to “any Future-protocol type (value or pointer)”.The implementation and tests support ResetEvent/Notify/etc. Please update the comment and example to reflect arbitrary futures (including pointers).
153-155: Remove stale TODO (tie-breaker is already defined).You’ve documented field-order tie-breaking above; the TODO is misleading. Delete it or point back to that rule.
157-163: Optional: avoid O(N) flag scan by recording the winner index.You can store an index in SelectWaiter and set a shared winner_idx with compare-exchange on first wake. This makes the post-yield selection O(1) while preserving FIFO via field order in case of simultaneous wakes. Not required for correctness.
src/runtime.zig (1)
757-765: Make getResult receiver const; it doesn’t mutate.Allows calling on const handles and matches usage as a pure accessor.
- pub fn getResult(self: *Self) T { + pub fn getResult(self: *const Self) T { assert(self.hasResult()); return switch (self.awaitable.kind) { .task => Task(T).fromAwaitable(self.awaitable).impl.future_result.get().?, .blocking_task => BlockingTask(T).fromAwaitable(self.awaitable).impl.future_result.get().?, .future => Future(T).fromAwaitable(self.awaitable).impl.future_result.get().?, }; }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
src/core/Awaitable.zig(1 hunks)src/coroutines.zig(1 hunks)src/runtime.zig(10 hunks)src/select.zig(1 hunks)src/sync/Notify.zig(2 hunks)src/sync/ResetEvent.zig(2 hunks)src/zio.zig(1 hunks)
⏰ 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 (macos-latest)
🔇 Additional comments (5)
src/zio.zig (1)
33-35: Re-exports look goodPublicly re-exporting
selectandSelectUnionfrom select.zig aligns the surface with the new implementation.src/sync/ResetEvent.zig (1)
228-258: Future protocol integration reads clean
hasResult()delegates toisSet(),asyncWait()usespushUnless(is_set, ...), and cancel removes safely. Matches select()’s expectations.src/coroutines.zig (1)
12-21: I need to verify the regex pattern was comprehensive. Let me run an additional check to ensure no other state comparison patterns were missed:<!-- [scratchpad_update]
[task verification_1/1 - extended analysis][new_observations]
- Zig enum comparisons: enums support direct comparison with
==operator (from zig.guide example:self == Suit.clubs)- Zig enums can use shorthand notation like
.waiting_io(documented in language)- The regex used would catch most standard patterns of equality comparisons
[refined_analysis]
The regex search looked for patterns like:
state == .waiting_*state != .waiting_*coro.state.load(...) == .waiting_*Result: ZERO matches found. This is strong evidence that:
- No direct equality checks against waiting states exist
- The code has already migrated or never had this pattern
- The ONE usage found (runtime.zig:1427) correctly uses
isWaiting()- The migration appears SAFE and already compliant
[verification_confidence]
HIGH: The search pattern is comprehensive for Zig enum equality checks. The absence of matches combined with correct usage of isWaiting() indicates the refactor is complete/safe.[conclusion]
The original review comment's concern has been verified as NOT AN ISSUE. The codebase does not have problematic direct equality checks against waiting states. The migration to bit flags with isWaiting() is already properly implemented.
[scratchpad_end] -->Based on the verification results, the codebase is in good shape regarding the bit-flag migration:
No direct equality checks against
waiting_*states were found — the search returned zero matches for patterns likestate == .waiting_io|waiting_sync|waiting_completion. The only usage of state comparison found is insrc/runtime.zig:1427with the correctif (!old_state.isWaiting())call, which properly uses the new bit-flag helper.The migration to bit flags is safe and already correctly implemented. No code changes are needed.
src/runtime.zig (2)
1423-1425: Good: avoid double-schedule when state is already .ready.Early-return on .ready prevents duplicate enqueues under races with wake-before-yield.
1967-1967: Re-exporting select here keeps the public surface coherent.Importing select/select union from select.zig is clean and avoids duplication.
Move Future from runtime-managed heap-allocated type to simple stack-allocated synchronization primitive, similar to ResetEvent and Notify. Changes: - Create src/sync/future.zig with stack-allocated Future - Only needs wait_queue and future_result (no ref_count, destroy_fn, wait_node, done) - Initialize with Future(T).init (not heap allocation) - wait(runtime) instead of wait() (needs runtime for getCurrentTask) - Implements Future protocol for select() - Remove pub fn Future from runtime.zig (~60 lines) - Remove .future from AwaitableKind enum - Remove .future cases from JoinHandle methods - Move 3 Future tests to sync/future.zig Before: const future = try Future(i32).init(rt, allocator); defer future.deinit(); After: var future = Future(i32).init; Benefits: - Simpler: no ref counting, no Awaitable overhead - More flexible: stack or arena allocation, explicit lifetime - Cleaner separation: runtime-managed vs sync primitives
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/runtime.zig (1)
479-490: Compile error: AnyFuture still references removed enum case.future.
AwaitableKindno longer includes.future, yetAnyFuture.fromAwaitableasserts against it. This won’t compile. The new genericsync/future.zigsupersedes this type; removeAnyFutureor refactor it to the new Future.Apply removal:
-// Future for runtime - not backed by computation, can be set from callbacks -pub const AnyFuture = struct { - awaitable: Awaitable, - runtime: *Runtime, - - const wait_node_vtable = WaitNode.VTable{}; - - pub inline fn fromAwaitable(awaitable: *Awaitable) *AnyFuture { - assert(awaitable.kind == .future); - return @fieldParentPtr("awaitable", awaitable); - } -};
♻️ Duplicate comments (2)
src/core/Awaitable.zig (1)
40-52: Fix TOCTOU race in asyncWait to avoid lost wake/leaked waiter.Checking
donebefore enqueue opens a window where completion can flipdone=trueand drain the queue before this node is pushed. The node then stays stuck and the caller incorrectly thinks it is queued.Apply:
pub fn asyncWait(self: *const Awaitable, wait_node: *WaitNode) bool { - if (self.done.load(.acquire)) { - return false; - } - // Cast away const to mutate the waiting list - // This is safe because waiting_list is designed to be mutated even from const contexts - const mutable_self: *Awaitable = @constCast(self); - mutable_self.waiting_list.push(wait_node); - return true; + const mutable_self: *Awaitable = @constCast(self); + // Fast path + if (self.done.load(.acquire)) return false; + // Enqueue, then re-check to close the race with completion + mutable_self.waiting_list.push(wait_node); + if (self.done.load(.acquire)) { + // If we raced with completion, best-effort remove; OK if already popped. + _ = mutable_self.waiting_list.remove(wait_node); + return false; + } + return true; }Ensure
markComplete()setsdone.store(true, .release)before draining (it already does). Based on learnings.src/runtime.zig (1)
529-541: Constness mismatch: asyncWait/asyncCancelWait mutate through a*const Parent.These operations logically mutate wait queues; taking
*constinvites undefined behavior outside the internal const-cast pattern. Make them accept*Parent.Apply:
- pub fn asyncWait(parent: *const Parent, wait_node: *WaitNode) bool { + pub fn asyncWait(parent: *Parent, wait_node: *WaitNode) bool { return parent.impl.base.awaitable.asyncWait(wait_node); } @@ - pub fn asyncCancelWait(parent: *const Parent, wait_node: *WaitNode) void { + pub fn asyncCancelWait(parent: *Parent, wait_node: *WaitNode) void { parent.impl.base.awaitable.asyncCancelWait(wait_node); }
🧹 Nitpick comments (2)
src/runtime.zig (2)
1366-1386: Include.waiting_completionin the sync-migration fast path (perf).With
waitForComplete()now yielding to.waiting_completion(Line 199), tasks woken from completion won’t enter the migration block that currently checks only.waiting_sync. Consider treating both as “sync waiting” for cache‑local resumption.Example:
- if (old_state == .waiting_sync and mode == .maybe_remote and task.pin_count == 0) { + if ((old_state == .waiting_sync or old_state == .waiting_completion) + and mode == .maybe_remote and task.pin_count == 0) + { // existing migration logic…
692-700: Optional: makegetResultreceiver const.
getResultdoesn’t mutate;self: *const Selfwould better express intent.- pub fn getResult(self: *Self) T { + pub fn getResult(self: *const Self) T { assert(self.hasResult()); // unchanged }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/core/Awaitable.zig(1 hunks)src/runtime.zig(9 hunks)src/sync.zig(2 hunks)src/sync/future.zig(1 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/runtime.zigsrc/core/Awaitable.zig
🔇 Additional comments (3)
src/sync.zig (1)
12-12: Re-export looks good.Public alias and test re-export are correct and align with the new Future type.
Also applies to: 24-24
src/core/Awaitable.zig (1)
56-60: Cancel path is fine.Best‑effort remove on cancellation is appropriate.
src/sync/future.zig (1)
39-72: Wait path looks correct.Pre-enqueue check, post-enqueue recheck with removal, and cancel cleanup are handled properly.
- Add wait() function for single-future waiting in select.zig - Returns Cancelable!WaitResult(T) to avoid nested error unions - WaitResult is a simple wrapper struct with a value field - Refactor Future.wait() to delegate to select.wait() - Rename SelectUnion to SelectResult for consistency - Export both WaitResult and SelectResult from zio.zig - Add comprehensive tests for wait() with plain types, error unions, and fast path
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (1)
src/sync/future.zig (1)
56-62: Fix TOCTOU in asyncWait to prevent lost wake/leaked waiter.Between get() and push(), the future can complete and drain the queue. Push first, then re-check and remove if already completed.
- pub fn asyncWait(self: *Self, wait_node: *WaitNode) bool { - if (self.value.get() != null) { - return false; - } - self.wait_queue.push(wait_node); - return true; - } + pub fn asyncWait(self: *Self, wait_node: *WaitNode) bool { + if (self.value.get() != null) return false; + self.wait_queue.push(wait_node); + // If we raced with a setter that drained, remove our node and report false. + if (self.value.get() != null) { + _ = self.wait_queue.remove(wait_node); + return false; + } + return true; + }
🧹 Nitpick comments (3)
src/select.zig (3)
82-91: Remove redundant initialization of signaled.Field default already initializes signaled; init() repeats it.
pub const SelectWaiter = struct { wait_node: WaitNode, parent: *WaitNode, wake_counter: *std.atomic.Value(u32), - signaled: std.atomic.Value(bool) = .init(false), + signaled: std.atomic.Value(bool) = .init(false), @@ pub fn init(parent: *WaitNode, wake_counter: *std.atomic.Value(u32)) SelectWaiter { return .{ .wait_node = .{ .vtable = &wait_node_vtable, }, .parent = parent, .wake_counter = wake_counter, - .signaled = .init(false), }; }Also applies to: 73-77
103-119: Update docs to reflect the generic Future protocol, not just JoinHandle.The comment still mentions “JoinHandle(T)”. Please rewrite to “any Future-protocol type”.
120-135: Comptime assert: require at least one future.Empty input leads to zero waiters and unreachable path. Add a guard.
pub fn select(rt: *Runtime, futures: anytype) !SelectResult(@TypeOf(futures)) { const S = @TypeOf(futures); const U = SelectResult(S); const fields = @typeInfo(S).@"struct".fields; + comptime if (fields.len == 0) @compileError("select() requires at least one future");
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
src/select.zig(1 hunks)src/sync/future.zig(1 hunks)src/zio.zig(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/zio.zig
🧰 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/sync/future.zig
🔇 Additional comments (3)
src/sync/future.zig (2)
23-34: Confirm memory ordering for set/get to ensure visibility.Ensure FutureResult.set uses at least release semantics and FutureResult.get uses acquire, so getResult() observes the published value after wake. Please confirm in future_result.zig.
72-92: Tests read well and cover fast-path, coroutine await, and multi-waiters.No issues from these cases.
Also applies to: 94-131, 133-176
src/select.zig (1)
230-359: Tests look solid and exercise fast-paths, cancellation, heterogeneous results, and error unions.LGTM.
Also applies to: 361-409, 411-577, 579-687
| task.coro.state.store(.preparing_to_wait, .release); | ||
| defer { | ||
| const prev = task.coro.state.swap(.ready, .release); | ||
| std.debug.assert(prev == .preparing_to_wait or prev == .ready); | ||
| } | ||
|
|
||
| var ready: std.atomic.Value(u32) = .init(0); | ||
| var waiter = SelectWaiter.init(&task.awaitable.wait_node, &ready); | ||
|
|
||
| // Fast path: check if already complete | ||
| var fut = future; | ||
| const added = fut.asyncWait(&waiter.wait_node); | ||
| if (!added) { | ||
| return .{ .value = fut.getResult() }; | ||
| } | ||
|
|
There was a problem hiding this comment.
🧩 Analysis chain
Same value-copy hazard in wait(); require pointer for value-owned futures.
wait() copies its future into fut and registers on the copy. Document and enforce that value-owned futures must be passed by pointer (e.g., &future), or adjust the API to accept only pointers.
I can provide a patch to enforce pointer-only at comptime for types whose asyncWait has a pointer receiver.
Also applies to: 214-218, 227-228
I'll verify the review comment by examining the relevant code sections in src/select.zig.
🏁 Script executed:
#!/bin/bash
# Read the select.zig file to understand the wait() function and value-copy issue
cat src/select.zig | head -250 | tail -100Length of output: 3241
🏁 Script executed:
#!/bin/bash
# Get more context around the specific lines mentioned (197-212, 214-218, 227-228)
sed -n '190,235p' src/select.zigLength of output: 1519
🏁 Script executed:
#!/bin/bash
# Search for SelectWaiter definition and asyncWait method
rg -n "SelectWaiter|asyncWait" src/select.zig -C 3Length of output: 2159
🏁 Script executed:
#!/bin/bash
# Look for the wait() function signature
rg -n "fn wait\(" src/select.zig -A 15Length of output: 721
🏁 Script executed:
#!/bin/bash
# Search for future type and its definition
rg -n "pub fn init|\.future|future:" src/select.zig -C 2Length of output: 563
🏁 Script executed:
#!/bin/bash
# Check for other occurrences of value copies or similar patterns across the file
rg -n "var fut = " src/select.zig -C 2Length of output: 156
🏁 Script executed:
#!/bin/bash
# Look at the full structure around lines 214-218 and 227-228
sed -n '210,235p' src/select.zigLength of output: 677
🏁 Script executed:
#!/bin/bash
# Find the type definition of future parameter
rg -n "pub.*fn wait|fn wait" src/select.zig -B 5 -A 20Length of output: 2129
🏁 Script executed:
#!/bin/bash
# Look for asyncWait method definition to see if it has pointer receiver
ast-grep --pattern 'fn asyncWait($$$) {
$$$
}'Length of output: 0
🏁 Script executed:
#!/bin/bash
# Search for SelectWaiter struct definition
rg -n "const SelectWaiter|struct.*SelectWaiter" src/ -C 5Length of output: 513
🏁 Script executed:
#!/bin/bash
# Check the broader context - look for how futures are typically passed
rg -n "asyncWait.*wait_node" src/select.zig -B 3 -A 3Length of output: 596
🏁 Script executed:
#!/bin/bash
# Look at the entire wait function to understand the control flow
sed -n '180,230p' src/select.zigLength of output: 1654
🏁 Script executed:
#!/bin/bash
# Search for the future parameter type annotation in wait()
rg -n "fn wait\(" src/select.zig -A 2Length of output: 220
🏁 Script executed:
#!/bin/bash
# Check if there are multiple wait() implementations (overloads)
fd "\.zig$" src/ -exec rg -l "fn wait\(" {} \;Length of output: 201
🏁 Script executed:
#!/bin/bash
# Look for any generic or parameterized types related to futures
rg -n "Future|future" src/select.zig | head -20Length of output: 1002
🏁 Script executed:
#!/bin/bash
# Get the complete wait() function implementation
awk '/fn wait\(/{p=1} p{print; if(/^}/ && p) exit}' src/select.zigLength of output: 1188
🏁 Script executed:
#!/bin/bash
# Search for getResult method and its context
rg -n "getResult" src/select.zig -B 2 -A 2Length of output: 952
🏁 Script executed:
#!/bin/bash
# Look for the exact function signature including return type
rg -n "pub fn wait" src/select.zig -A 30Length of output: 1165
🏁 Script executed:
#!/bin/bash
# Get context around all mentioned line numbers
sed -n '195,230p' src/select.zigLength of output: 1062
🏁 Script executed:
#!/bin/bash
# Search for Awaitable and related structures
rg -n "Awaitable|wait_node" src/select.zig -C 2Length of output: 2051
🏁 Script executed:
#!/bin/bash
# Find how futures are typically declared in tests or examples
rg -n "var.*future|const.*future" src/ -C 1 | head -30Length of output: 1584
🏁 Script executed:
#!/bin/bash
# Look at function parameters more carefully
grep -n "fn wait" src/select.zigLength of output: 153
🏁 Script executed:
#!/bin/bash
# Check for pointer vs value semantics in asyncWait calls
rg -n "&waiter|&future|&self" src/select.zigLength of output: 722
🏁 Script executed:
#!/bin/bash
# Look at the full file to understand the context better
wc -l src/select.zig && head -50 src/select.zigLength of output: 1701
🏁 Script executed:
#!/bin/bash
# Get the exact snippet from the review comment (lines 197-212)
sed -n '197,212p' src/select.zigLength of output: 518
🏁 Script executed:
#!/bin/bash
# Find the wait function and surrounding code
rg -n "const added = fut.asyncWait" src/select.zig -B 20 -A 10Length of output: 1218
🏁 Script executed:
#!/bin/bash
# Look for the function that contains this code
grep -n "fn.*(" src/select.zig | head -20Length of output: 1097
🏁 Script executed:
#!/bin/bash
# Search for all functions in select.zig
awk '/^(pub )?fn / {print NR": "$0}' src/select.zigLength of output: 381
🏁 Script executed:
#!/bin/bash
# Get context around the target lines with more detail
sed -n '180,240p' src/select.zig | cat -nLength of output: 2342
🏁 Script executed:
#!/bin/bash
# Find the line where .init or asyncWait is called to understand method receivers
grep -n "\.asyncWait\|\.init" src/select.zigLength of output: 1387
🏁 Script executed:
#!/bin/bash
# Simple direct read to see what's at the exact lines
head -212 src/select.zig | tail -16Length of output: 518
🏁 Script executed:
#!/bin/bash
# Just get the whole file to avoid missing context
cat src/select.zigLength of output: 22404
🏁 Script executed:
#!/bin/bash
# Count lines and verify file exists
wc -l src/select.zigLength of output: 18
🏁 Script executed:
#!/bin/bash
# List what files exist in src/
ls -la src/ | head -20Length of output: 1122
🏁 Script executed:
#!/bin/bash
# Find any zig files
find . -name "*.zig" -type f 2>/dev/null | head -10Length of output: 276
🏁 Script executed:
#!/bin/bash
# Check the repository structure
ls -la . 2>/dev/null | head -20Length of output: 1066
🏁 Script executed:
#!/bin/bash
# Find select.zig anywhere
find . -name "select.zig" -type f 2>/dev/nullLength of output: 16
🏁 Script executed:
#!/bin/bash
# List directory contents at root
pwd && ls -laLength of output: 1085
🏁 Script executed:
#!/bin/bash
# Try to understand the project layout
find . -type f -name "*.zig" 2>/dev/null | head -20Length of output: 498
🏁 Script executed:
#!/bin/bash
# Get repository info
if [ -d .git ]; then git branch -v; fi && pwdLength of output: 192
🏁 Script executed:
#!/bin/bash
# Try another approach - look for all files
find . -type f -name "*select*" 2>/dev/nullLength of output: 16
🏁 Script executed:
#!/bin/bash
# List current working directory
ls -la /Length of output: 482
🏁 Script executed:
#!/bin/bash
# Verify we can access any files
test -r src/select.zig && echo "File readable" || echo "File not found or not readable"Length of output: 13
🏁 Script executed:
#!/bin/bash
# Try to cat the file directly with error handling
if [ -f "src/select.zig" ]; then cat src/select.zig; else echo "File does not exist"; fiLength of output: 22404
🏁 Script executed:
#!/bin/bash
# Check all content
find . -maxdepth 3 -type f 2>/dev/null | head -30Length of output: 659
Enforce pointer-only futures in wait() and select(); document the Future protocol requirement.
The value-copy hazard is confirmed. Line 207 creates a local copy (var fut = future), which is then passed to asyncWait(). If a caller passes a value-owned future instead of a pointer, the internal wait-list registration and subsequent getResult() call operate on a temporary copy rather than the original, breaking correctness. The same issue applies to the select() function at similar patterns.
All existing tests pass pointers (&future), and the documentation example (line 190) also uses pointer form, indicating the intended API contract. Enforce this at compile time using type checking in the function signature, or add compile-time assertion to reject non-pointer futures. The Future protocol comment (lines 7–11) already specifies methods on the concrete type, so pointer-only semantics align with the design intent.
Locations affected:
- wait() function: lines 207–227 (copy-and-register pattern)
- select() function: lines 149, 157, 174 (same pattern in loop)
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/select.zig (1)
103-181: Clarify or remove the outdated TODO comment.The implementation is correct and well-structured. However, line 168's TODO comment "What to do if we have multiple?" appears outdated—the behavior is already implemented and documented (lines 107-108): when multiple futures complete simultaneously, the first in declaration order is returned, which is a reasonable and deterministic tie-breaking strategy.
Consider removing or clarifying this TODO:
- // We should have at least one future with result - // TODO What to do if we have multiple? + // At least one future should have a result + // If multiple are ready, return the first in declaration order (see function doc) std.debug.assert(ready.load(.acquire) > 0);Otherwise, the select() logic is sound: fast-path detection works correctly, cleanup only cancels non-signaled waiters, and the state machine transitions are properly guarded.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/select.zig(1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: lalinsky
PR: lalinsky/zio#70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.546Z
Learning: In src/select.zig, the select() function is designed to accept futures either as copyable wrappers (e.g., JoinHandle(T)) by value, or as pointers (e.g., &reset_event) for value-owned types. This is intentional, and users are expected to pass the appropriate form based on the future type.
📚 Learning: 2025-10-23T16:17:53.546Z
Learnt from: lalinsky
PR: lalinsky/zio#70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.546Z
Learning: In src/select.zig, the select() function is designed to accept futures either as copyable wrappers (e.g., JoinHandle(T)) by value, or as pointers (e.g., &reset_event) for value-owned types. This is intentional, and users are expected to pass the appropriate form based on the future type.
Applied to files:
src/select.zig
🔇 Additional comments (6)
src/select.zig (6)
1-11: LGTM!The imports are appropriate and the Future protocol documentation clearly specifies the interface requirements. The comment concisely explains that
asyncWaitreturns false when already complete, which is key to the fast-path optimization used throughout the implementation.
13-32: LGTM!The type helpers are well-designed:
FutureType()correctly unwraps pointer types to access the underlying FutureFutureResult()properly extracts the Result type through the protocolWaitResult()elegantly avoids nested error union confusion by wrapping the result in a named field
34-69: LGTM! Past alignment issue already resolved.The
SelectResultbuilder correctly uses@alignOf(Result)at line 43, which was the concern from the previous review. The implementation properly constructs a tagged union mirroring the input struct's field names with each field's Future Result type. The test provides good compile-time validation.
71-101: LGTM!The
SelectWaiterimplementation correctly handles concurrent completion signaling:
- Per-waiter
signaledflag with atomic operations ensures thread-safe tracking of which future completed- Shared
wake_counterwith.acq_relordering onfetchAddensures all priorsignaledstores are visible when waking the parent- Only the first completing future wakes the parent task (line 97-99 check), avoiding redundant wakeups
The memory ordering is sound for cross-thread signaling.
183-228: LGTM!The
wait()function correctly implements single-future waiting with the same sound design asselect():
- Fast-path detection (line 209) returns immediately for already-complete futures
- Proper cleanup of non-signaled waiters in the defer block
- Clear documentation including an example of handling nested error unions (lines 189-191)
The value-copy pattern at line 207 is consistent with the design constraints documented in the learnings.
Based on learnings
230-687: Excellent test coverage!The test suite comprehensively validates the implementation:
- Core functionality: multiple futures, tie-breaking, fast-path optimization
- Type heterogeneity: different result types (i32, []const u8, bool) in the same select
- Error handling: success cases, error propagation, mixed error sets
- Cancellation: verifies proper cleanup when operations are canceled
- Both
select()andwait()functions are thoroughly testedThe tests are well-structured with clear setup, execution, and verification phases.
- Use WaitQueue sentinel states: sentinel0 (not_set), sentinel1 (done) - In set(), use popOrTransition to wake all waiters and transition to done - In asyncWait(), add fast path check with FutureResult.isSet() - Use pushUnless(done) to prevent invalid state transitions - Add FutureResult.isSet() method for fast path checking
- Use WaitQueue sentinel states: sentinel0 (not_complete), sentinel1 (complete) - In markComplete(), use popOrTransition to wake waiters and transition to complete - In asyncWait(), add fast path check with done flag and use pushUnless(complete) - Prevents race where asyncWait could add waiter after task completes
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/sync/future.zig (1)
533-541: *Constness bug: asyncWait/asyncCancelWait mutate via const ParentThese forward to awaitable methods that mutate internal state; taking
*const Parentis misleading and can force const-casts downstream. Make the receiver mutable.- pub fn asyncWait(parent: *const Parent, wait_node: *WaitNode) bool { + pub fn asyncWait(parent: *Parent, wait_node: *WaitNode) bool { return parent.impl.base.awaitable.asyncWait(wait_node); } @@ - pub fn asyncCancelWait(parent: *const Parent, wait_node: *WaitNode) void { + pub fn asyncCancelWait(parent: *Parent, wait_node: *WaitNode) void { parent.impl.base.awaitable.asyncCancelWait(wait_node); }
🧹 Nitpick comments (3)
src/sync/future.zig (2)
65-73: Simplify asyncWait(): drop the pre-check and rely on pushUnless(done)The done-sentinel + popOrTransition loop already prevents lost wakes. Removing the isSet() fast-path saves an atomic load without changing semantics.
Apply:
- pub fn asyncWait(self: *Self, wait_node: *WaitNode) bool { - // Fast path: check if already set - if (self.value.isSet()) { - return false; - } - // Try to push to queue - only succeeds if future is not done - // Returns false if future is done, preventing invalid transition: done -> has_waiters - return self.wait_queue.pushUnless(done, wait_node); - } + pub fn asyncWait(self: *Self, wait_node: *WaitNode) bool { + // Enqueue unless already done; set() drains waiters then transitions to .done. + return self.wait_queue.pushUnless(done, wait_node); + }
58-60: Consider a const receiver for getResult()Method doesn’t mutate; using
*const Selfimproves API const-correctness without cost.- pub fn getResult(self: *Self) T { + pub fn getResult(self: *const Self) T { return self.value.get().?; }src/runtime.zig (1)
693-701: Make JoinHandle.getResult receiver constMethod is read-only; const receiver tightens the API and aligns with hasResult().
- pub fn getResult(self: *Self) T { + pub fn getResult(self: *const Self) T { assert(self.hasResult()); return switch (self.awaitable.kind) { .task => Task(T).fromAwaitable(self.awaitable).impl.future_result.get().?, .blocking_task => BlockingTask(T).fromAwaitable(self.awaitable).impl.future_result.get().?, }; }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/core/Awaitable.zig(1 hunks)src/future_result.zig(1 hunks)src/runtime.zig(10 hunks)src/sync/future.zig(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/core/Awaitable.zig
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: lalinsky
PR: lalinsky/zio#70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.546Z
Learning: In src/select.zig, the select() function is designed to accept futures either as copyable wrappers (e.g., JoinHandle(T)) by value, or as pointers (e.g., &reset_event) for value-owned types. This is intentional, and users are expected to pass the appropriate form based on the future type.
📚 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/sync/future.zigsrc/runtime.zig
📚 Learning: 2025-10-23T16:17:53.546Z
Learnt from: lalinsky
PR: lalinsky/zio#70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.546Z
Learning: In src/select.zig, the select() function is designed to accept futures either as copyable wrappers (e.g., JoinHandle(T)) by value, or as pointers (e.g., &reset_event) for value-owned types. This is intentional, and users are expected to pass the appropriate form based on the future type.
Applied to files:
src/runtime.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 (1)
src/future_result.zig (1)
37-40: isSet(): memory ordering and semantics look correctAcquire load pairs with set()’s release stores; returns true only for ok/err. LGTM.
- Move markComplete() from runtime.zig to Awaitable as a method - Update all call sites to use awaitable.markComplete() - Better encapsulation and cleaner API
- Add toAwaitable() method to FutureImpl (Task/BlockingTask) - Add checkSelfWait() helper function in select.zig - Check for self-wait deadlock using optional toAwaitable() method - Applied to both select() and wait() functions - Prevents deadlock when a task tries to wait on itself
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
src/runtime.zig (1)
518-526: *Constness bug: asyncWait/asyncCancelWait should accept mutable Parent.These methods mutate the parent's awaitable through
*const Parent, which is inconsistent with sync primitives likeResetEventandNotifythat use mutable pointers. WhileAwaitableinternally uses@constCastworkarounds, the Future protocol surface should use clean mutable semantics.Apply this diff:
- pub fn asyncWait(parent: *const Parent, wait_node: *WaitNode) bool { + pub fn asyncWait(parent: *Parent, wait_node: *WaitNode) bool { return parent.impl.base.awaitable.asyncWait(wait_node); } @@ - pub fn asyncCancelWait(parent: *const Parent, wait_node: *WaitNode) void { + pub fn asyncCancelWait(parent: *Parent, wait_node: *WaitNode) void { parent.impl.base.awaitable.asyncCancelWait(wait_node); }Update callers if needed to pass mutable references.
🧹 Nitpick comments (1)
src/runtime.zig (1)
530-532: Consider mutable pointer for consistency.
toAwaitable()returns*const Awaitable, which is correct for read-only self-wait detection. However, if the intent is to allow callers to interact with the awaitable (beyond just pointer comparison), consider whether*Awaitableis more appropriate.If this is purely for self-wait checks (pointer equality), the current
*const Awaitableis fine and documents the read-only intent.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/runtime.zig(11 hunks)src/select.zig(1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: lalinsky
PR: lalinsky/zio#70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.546Z
Learning: In src/select.zig, the select() function is designed to accept futures either as copyable wrappers (e.g., JoinHandle(T)) by value, or as pointers (e.g., &reset_event) for value-owned types. This is intentional, and users are expected to pass the appropriate form based on the future type.
📚 Learning: 2025-10-23T16:17:53.546Z
Learnt from: lalinsky
PR: lalinsky/zio#70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.546Z
Learning: In src/select.zig, the select() function is designed to accept futures either as copyable wrappers (e.g., JoinHandle(T)) by value, or as pointers (e.g., &reset_event) for value-owned types. This is intentional, and users are expected to pass the appropriate form based on the future type.
Applied to files:
src/select.zigsrc/runtime.zig
📚 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/runtime.zig
🔇 Additional comments (4)
src/select.zig (2)
1-250: LGTM! Clean Future protocol implementation with comprehensive safety checks.The implementation correctly:
- Defines and documents the Future protocol requirements (lines 9-13)
- Handles both direct types and pointers via
FutureType()helper (lines 15-21)- Generates properly-aligned
SelectResultunion types (line 57 uses@alignOf(Result))- Implements self-wait deadlock detection (lines 29-39)
- Uses
signaledflags to identify which future completed (lines 90, 109, 167, 192)- Provides fast-path optimization when futures are already complete (lines 178-180, 231-232)
- Properly cancels non-signaled waiters in defer blocks (lines 164-172, 236-240)
The design choice to accept futures by value (creating local copies at lines 168, 176, 193, 229) is correct per the learnings—futures are either copyable wrappers like
JoinHandle(T)or pointers like&reset_event.
252-709: Excellent test coverage across multiple scenarios.The test suite thoroughly validates:
- Basic select with first-completes-wins semantics
- Fast-path when futures are already complete
- Heterogeneous result types in the union
- Cancellation propagation
- Error unions (success, error, and mixed error types)
- wait() with plain types, error unions, errors, and fast-path
All tests use proper cleanup with defer and verify expected behavior.
src/runtime.zig (2)
549-551: Consistent Future protocol exposure across Task, BlockingTask, and JoinHandle.The
asyncWait,asyncCancelWait, andtoAwaitablemethods are correctly exposed on all three types, enabling them to participate in the Future protocol forselect().JoinHandlealso exposesgetResult()(line 686) to retrieve completed results.Also applies to: 581-583, 699-707
1896-1896: Clean delegation to select.zig's select() function.Correctly imports and re-exports the new
select()implementation, replacing the previous in-file logic.
- Add ThreadWaiter struct for futex-based thread parking - wait() now works from both coroutines and threads - Use conditional path: coroutine yields, thread parks on futex - Unified implementation with single code path
- Add Result type and getResult() to FutureImpl and delegate to Task/BlockingTask for complete Future protocol - Refactor FutureImpl.wait() to use select.wait() instead of waitForComplete() - Remove waitForComplete() function (no longer needed) - Remove Runtime.select alias (users can call select.select() directly)
Add flexible cancellation handling by introducing waitInternal() with configurable behavior: - wait() - propagates cancellation to caller (existing behavior) - waitUntilComplete() - cancels child and continues waiting with shield (never returns Canceled) Key improvements: - Stays subscribed to wait queue during cancel-and-retry (avoids unsubscribe/resubscribe overhead) - JoinHandle.join() now takes runtime parameter and uses waitUntilComplete() internally - Remove Executor.runUntilComplete() - only Runtime.runUntilComplete() needed - Simplify join() implementation by using select infrastructure instead of manual retry loop Changes: - Add WaitFlags/CancelBehavior to select.zig for configurable cancellation - Rename wait() to waitInternal() with flags parameter - Implement cancel_and_continue behavior that stays in wait queue during shield - Add public wait() and waitUntilComplete() wrappers - Update JoinHandle.join() signature to take runtime and return plain T - Update all join() call sites across tests, examples, and benchmarks
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/runtime.zig (1)
456-464: Constness bug: asyncWait/asyncCancelWait mutate awaitable through a *const Parent.Both methods call
awaitable.asyncWait/asyncCancelWaitwhich mutate the wait queue; doing this through*const Parentis undefined behavior. MakeParentmutable in these methods.Apply this diff to fix the constness bug:
- pub fn asyncWait(parent: *const Parent, wait_node: *WaitNode) bool { + pub fn asyncWait(parent: *Parent, wait_node: *WaitNode) bool { return parent.impl.base.awaitable.asyncWait(wait_node); } - pub fn asyncCancelWait(parent: *const Parent, wait_node: *WaitNode) void { + pub fn asyncCancelWait(parent: *Parent, wait_node: *WaitNode) void { parent.impl.base.awaitable.asyncCancelWait(wait_node); }
🧹 Nitpick comments (1)
src/select.zig (1)
241-343: Document pointer requirement for value-owned futures in wait() functions.The implementation is correct per the design decision (see learning), but the function documentation should clarify that value-owned futures must be passed by pointer (e.g.,
&future), while copyable wrappers likeJoinHandle(T)can be passed by value. Without this guidance, users may inadvertently pass value-owned futures by value, causing waiters to register on a stack copy rather than the original, leading to hangs.Consider adding a note to the doc comments for
wait()(lines 315-325) andwaitUntilComplete()(lines 330-339):/// Note: Pass copyable futures (e.g., JoinHandle) by value, /// or pass pointers (e.g., &future) for value-owned types like Future(T).Based on learnings.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (9)
benchmarks/echo_server.zig(1 hunks)examples/tcp_echo_server.zig(1 hunks)examples/tls_demo.zig(1 hunks)src/io/test/net.zig(1 hunks)src/net.zig(3 hunks)src/runtime.zig(20 hunks)src/select.zig(1 hunks)src/sync/future.zig(1 hunks)src/udp.zig(1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: lalinsky
PR: lalinsky/zio#70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.546Z
Learning: In src/select.zig, the select() function is designed to accept futures either as copyable wrappers (e.g., JoinHandle(T)) by value, or as pointers (e.g., &reset_event) for value-owned types. This is intentional, and users are expected to pass the appropriate form based on the future type.
📚 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/runtime.zig
📚 Learning: 2025-10-23T16:17:53.546Z
Learnt from: lalinsky
PR: lalinsky/zio#70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.546Z
Learning: In src/select.zig, the select() function is designed to accept futures either as copyable wrappers (e.g., JoinHandle(T)) by value, or as pointers (e.g., &reset_event) for value-owned types. This is intentional, and users are expected to pass the appropriate form based on the future type.
Applied to files:
src/runtime.zigsrc/select.zig
🔇 Additional comments (19)
examples/tls_demo.zig (1)
75-75: LGTM! Join API updated correctly.The change from
join()tojoin(&runtime)aligns with the new runtime-aware join semantics introduced across the codebase.src/udp.zig (1)
254-255: LGTM! Test join calls updated correctly.Both server and client task joins now pass the runtime parameter, consistent with the API changes across the PR.
benchmarks/echo_server.zig (1)
133-133: LGTM! Benchmark join calls updated correctly.The client task joins and server join now pass the runtime parameter as required by the new API.
Also applies to: 140-140
examples/tcp_echo_server.zig (1)
65-65: LGTM! Server join updated correctly.The change to
server.join(&runtime)is consistent with the API evolution.src/io/test/net.zig (1)
75-76: LGTM! Test join calls updated correctly.Both task joins in the test helper now pass the runtime parameter as expected.
src/net.zig (2)
42-42: LGTM! Blocking task join updated correctly.The
task.join(runtime)call ingetAddressListnow passes the runtime parameter as required.
166-167: LGTM! Test joins updated correctly.All test task joins now pass the runtime reference, consistent with the API changes.
Also applies to: 224-225
src/sync/future.zig (2)
65-73: LGTM! asyncWait implementation handles race correctly.The use of
pushUnless(done, wait_node)at line 72 correctly prevents the TOCTOU race mentioned in past reviews by atomically checking the state and enqueueing the waiter.
31-43: LGTM! Future.set() implementation is correct.The
set()method properly stores the value atomically and wakes all waiters using thepopOrTransitionloop. The state management ensures proper synchronization between setters and waiters.src/select.zig (5)
86-104: LGTM! SelectResult alignment fixed correctly.Line 95 correctly uses
@alignOf(Result)for the union field alignment, addressing the issue from past reviews.
172-238: LGTM! select() implementation is correct.The implementation properly:
- Detects self-wait deadlocks (lines 183-185)
- Uses fast-path checks for already-complete futures (lines 216-218)
- Employs the
signaledflag to track which waiter was woken (lines 230-232)- Cleans up non-signaled waiters in defer block (lines 204-209)
The value-copy pattern (lines 206, 214, 231) is intentional per the design where futures are either copyable wrappers or passed as pointers. Based on learnings.
10-64: LGTM! Helper functions and ThreadWaiter implementation are correct.The helper functions (
FutureType,FutureResult,checkSelfWait) andThreadWaiterfor non-coroutine contexts are well-implemented and support both coroutine and thread usage patterns.
124-153: LGTM! SelectWaiter with signaled flag is well-designed.The
signaledatomic flag (line 128) correctly tracks which waiter was woken, enabling support for stateless notification primitives as mentioned in the PR objectives.
345-802: LGTM! Test coverage is comprehensive.The tests cover:
- Basic select scenarios with multiple futures
- Fast-path immediate completion
- Heterogeneous types
- Cancellation behavior
- Error unions (success and error cases)
- Mixed error types
- wait() for plain types and error unions
All tests correctly pass value-owned futures by pointer (e.g.,
&future), demonstrating the intended usage pattern.src/runtime.zig (5)
620-625: LGTM! Join now requires runtime parameter.The new signature
join(self: *Self, rt: *Runtime)correctly delegates toselect.waitUntilComplete()for both task and blocking task types, aligning with the Future protocol refactor.
648-656: LGTM! JoinHandle implements Future protocol correctly.The
asyncWaitandasyncCancelWaitmethods properly forward to the underlying awaitable's protocol methods. Takingself: Selfby value is correct since it's a lightweight wrapper containing just the awaitable pointer.
1291-1297: LGTM! Double-schedule guard prevents race condition.The check for
old_state == .readycorrectly detects when another thread has already scheduled the task, preventing double-scheduling. The subsequentisWaiting()check provides good defensive validation.
1889-1889: LGTM! All tests updated to use new join(rt) signature.All test cases consistently use
handle.join(rt)with the required runtime parameter, properly adapting to the Future protocol changes.Also applies to: 1931-1931, 1963-1963, 2001-2002, 2028-2028, 2060-2060, 2070-2070, 2128-2128
423-427: No issues found — the return value structure is valid.The verification confirms that
select.WaitResult(T)returns a struct with avalue: Tfield (lines 67-71 of src/select.zig), and the code correctly constructs this struct with.{ .value = res }.
Summary
select()to support waiting on arbitrary future types through a Future protocolResetEventandNotifyasyncWait()return values andsignaledflags for cleaner, more efficient implementationselect()implementation to dedicatedsrc/select.zigfileChanges
Core Future Protocol
pub const Result = TasyncWait(*WaitNode) bool- returns false if already completeasyncCancelWait(*WaitNode) voidgetResult() ResultImplementation Hierarchy
asyncWait()/asyncCancelWait()pushUnless(is_set)select() Improvements
signaledflag toSelectWaiterto track which waiter was wokenasyncWait()return value for fast-path detection (no separatehasResult()check)signaledflags instead of callinghasResult()on each future@field(futures, field.name).asyncWait()FutureType()helper)New Sync Primitive: Notify
signal()wakes one waiter (FIFO)broadcast()wakes all waitersselect()Test Plan
ResetEvent: selectNotify: selectselect()scenarios (heterogeneous types, error unions, cancellation, etc.)Technical Details
Why
signaledflags?Notifyhave no persistent state to checksignaledflag provides definitive answer of which future completedWhy
asyncWait()returns bool?hasResult()methodWhy pass futures by value in protocol methods?
@field(futures, field.name))Selfby value and forward to*AwaitableSummary by CodeRabbit
New Features
Refactor
Tests