Repository navigation
Extract awaitable structures and improve concurrent primitives - #48
Conversation
- Rename AwaitableList to SimpleAwaitableList for clarity - Rename AwaitableStack to ConcurrentAwaitableStack for consistency - Extract SimpleAwaitableStack to src/core/SimpleAwaitableStack.zig - Extract ConcurrentAwaitableStack to src/core/ConcurrentAwaitableStack.zig - Update all references throughout the codebase Naming convention now consistently distinguishes thread-safe (Concurrent*) from non-thread-safe (Simple*) data structures.
Extracted Awaitable.markComplete() into a standalone markComplete() function and added a new polymorphic resumeTask() helper to simplify task resumption. The resumeTask() function accepts *Awaitable, *AnyTask, or *Coroutine, providing a unified interface for marking coroutines as ready throughout the codebase. Replaced all calls to Executor.fromCoroutine().markReady() with the new resumeTask() helper across sync primitives (Mutex, Condition, ResetEvent) and I/O modules (TCP, UDP, File), significantly reducing code duplication and improving readability.
- Add thread-local current_executor tracking in Runtime - Add remote ready queue (next_ready_queue_remote) for cross-thread tasks - Add xev.Async infrastructure for cross-thread notifications - Modify markReady() to detect executor thread and route appropriately: - Same thread: fast path to local ready_queue - Different thread: push to remote queue and notify via async - Initialize remote infrastructure in run() to allow proper error handling - Clean up remote async in deinit() This enables tasks to be safely resumed from different executor threads using lock-free data structures and async notifications, with zero overhead for the common same-thread case.
Add ResumeMode enum to control cross-thread checking in task resumption: - `.local`: Skips executor check (IO callbacks always on same thread) - `.maybe_remote`: Checks executor, uses remote queue if different IO callbacks (tcp, udp, file, timers) use `.local` for fast path. Sync primitives (Mutex, Condition, ResetEvent) use `.maybe_remote` since waiters can belong to different executors. This eliminates unnecessary thread-local checks in the hot path for all IO operations.
WalkthroughRenames AwaitableList→SimpleAwaitableList, adds Simple/Concurrent awaitable stacks, makes ConcurrentAwaitableList mutation methods accept nullable Changes
Sequence Diagram(s)sequenceDiagram
participant IO as I/O callback
participant Runtime as Runtime
participant Exec as Executor
participant LocalQ as LocalReadyQueue
participant RemoteStack as RemoteReadyStack
IO->>Runtime: resumeTask(coro, .local)
note right of Runtime #E8F3FF: resumeTask evaluates ResumeMode
alt mode == local
Runtime->>LocalQ: enqueue coro (local ready)
else mode == maybe_remote
Runtime->>Exec: check current_executor
alt same executor
Exec->>LocalQ: enqueue coro locally
else different executor
Exec->>RemoteStack: push coro (ConcurrentAwaitableStack)
Exec->>Exec: signal remote_wakeup (xev)
end
end
LocalQ->>Runtime: scheduler dequeues ready coro
Runtime->>coro: resume coroutine
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
This change makes the executor parameter optional (?*Executor) in ConcurrentAwaitableList operations, allowing it to work in contexts where no executor is available, such as thread pool callbacks. When executor is null, the code spins without yielding during lock acquisition, which is appropriate for thread pool contexts where cooperative yielding isn't available or needed. All call sites in runtime.zig have been updated to correctly pass the executor parameter. This maintains full compatibility with existing coroutine-based code while enabling new use cases in thread pool contexts.
eb8d685 to
469be79
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
src/core/ConcurrentAwaitableList.zig (2)
284-291: Race: tail is cleared after releasing the mutation lock when removing the last nodeIn the head-removal branch for the final element,
head.store(.sentinel0, .release)clears the mutation bit beforeself.tail = null. Another thread can acquire the lock and push beforetailis reset, leavingtailnull or stale and corrupting the queue.Swap the operations to update
tailbefore clearing the lock (match pop()).Apply this diff:
- // Was only waiter - transition to sentinel0 - // (implicitly releases mutation lock since sentinel0 = 0b00 has no mutation bit) - // .release: publishes tail update and queue empty state - self.head.store(@intFromEnum(State.sentinel0), .release); - self.tail = null; + // Was only waiter - transition to sentinel0 + // Update tail first, then clear the mutation bit via store(.release) + self.tail = null; + // .release: publishes tail update and queue empty state + self.head.store(@intFromEnum(State.sentinel0), .release);
253-268: Over-strict debug assert in remove() breaks valid races (timeouts/select cleanup)
std.debug.assert(awaitable.in_list);can legitimately fail when remove is called speculatively (e.g., timeout callback, double-check fast path, select cleanup). The function is documented to return false if not found.Remove the assert; keep the existing membership test to return false safely.
Apply this diff:
- if (builtin.mode == .Debug) { - std.debug.assert(awaitable.in_list); - } + // Debug note: awaitable may already be removed by a concurrent action (timeout/complete) + // Do not assert; rely on membership checks below to return false safely.src/core/AwaitableList.zig (1)
65-95: remove() can corrupt the list if the item is not in this list; add membership checks and relax debug assertCurrently:
- Asserts
in_list(too strict) and clears it before confirming membership.- Unconditionally rewires pointers, which corrupts the list if
awaitableis not onself.Fix:
- Early-return false if not a member.
- Only clear
in_listwhen actually removing.Apply this diff:
pub fn remove(self: *SimpleAwaitableList, awaitable: *Awaitable) bool { // Handle empty list if (self.head == null) return false; - if (builtin.mode == .Debug) { - std.debug.assert(awaitable.in_list); - awaitable.in_list = false; - } + // Validate membership (minimal check: if no prev, must be head) + if (awaitable.prev == null and self.head != awaitable) return false; + // Optional symmetric check: if no next, must be tail + if (awaitable.next == null and self.tail != awaitable) return false; + if (builtin.mode == .Debug) { + if (!awaitable.in_list) return false; + awaitable.in_list = false; + } // Update prev node's next pointer (or head if removing first node) if (awaitable.prev) |prev_node| { prev_node.next = awaitable.next; } else { // No prev means this is the head self.head = awaitable.next; } // Update next node's prev pointer (or tail if removing last node) if (awaitable.next) |next_node| { next_node.prev = awaitable.prev; } else { // No next means this is the tail self.tail = awaitable.prev; } // Clear pointers awaitable.next = null; awaitable.prev = null; return true; }
🧹 Nitpick comments (4)
src/core/ConcurrentAwaitableStack.zig (1)
15-31: Tighten atomic memory orders in push for perfCurrent ordering is correct but stronger than needed. You can relax without affecting correctness:
- Use
.monotonic(relaxed) for the speculative head load.- Use
.monotonicfor the CAS failure order.Apply:
- const current_head = self.head.load(.acquire); + const current_head = self.head.load(.monotonic); ... - if (self.head.cmpxchgWeak( + if (self.head.cmpxchgWeak( current_head, item, .release, - .acquire, + .monotonic, ) == null) {src/core/AwaitableList.zig (1)
50-56: Minor: redundant null-check after early returnAfter
if (other.head == null) return;,if (other.head) |other_head|is redundant.Apply this diff:
- if (self.tail) |tail| { - tail.next = other.head; - if (other.head) |other_head| { - other_head.prev = tail; - } + if (self.tail) |tail| { + tail.next = other.head; + const other_head = other.head.?; + other_head.prev = tail;src/core/SimpleAwaitableStack.zig (1)
32-47: Optional: add popAll() to mirror ConcurrentAwaitableStack ergonomicsRuntime uses popAll() on the concurrent stack. Adding a similar helper here can simplify drains/moves between local queues.
Proposed addition:
pub fn popAll(self: *SimpleAwaitableStack) SimpleAwaitableStack { const out = SimpleAwaitableStack{ .head = self.head }; self.head = null; return out; }src/runtime.zig (1)
1098-1129: markReady remote path is correct; assert ensures initializationUses TLS to detect same executor; remote path pushes to lock-free stack and notifies. Consider guarding assert with a recoverable path (e.g., lazily initialize) if cross-thread resume can occur before run(), but current model disallows that, so this is acceptable.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (12)
src/core/Awaitable.zig(1 hunks)src/core/AwaitableList.zig(4 hunks)src/core/ConcurrentAwaitableList.zig(6 hunks)src/core/ConcurrentAwaitableStack.zig(1 hunks)src/core/SimpleAwaitableStack.zig(1 hunks)src/file.zig(8 hunks)src/runtime.zig(15 hunks)src/sync/Condition.zig(3 hunks)src/sync/Mutex.zig(2 hunks)src/sync/ResetEvent.zig(2 hunks)src/tcp.zig(8 hunks)src/udp.zig(4 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 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
🔇 Additional comments (20)
src/sync/ResetEvent.zig (1)
51-51: Resume via resumeTask(.maybe_remote) is appropriateThe switch simplifies wakeups and safely handles potential cross-thread resumptions. Looks good.
Also applies to: 89-90
src/sync/Condition.zig (1)
55-55: Signal/broadcast now use resumeTask(.maybe_remote) — LGTMDirect resumption removes executor plumbing and preserves cross-thread safety.
Also applies to: 189-191, 212-214
src/sync/Mutex.zig (1)
29-29: Unlock: resumeTask(.maybe_remote) is the right choiceThe new wake path is correct and consistent with the queue semantics.
Also applies to: 124-126
src/tcp.zig (1)
8-9: Shift to resumeTask(.local) in xev callbacks — consistent and correctUsing .local in these callbacks matches loop-thread execution and removes executor.markReady boilerplate.
Please confirm all xev callbacks in this module always run on the same executor thread. If any can run off-thread, switch those sites to
.maybe_remote.Also applies to: 85-86, 137-139, 197-198, 307-308, 360-361, 405-406, 448-449
src/udp.zig (1)
5-6: UDP callbacks: resumeTask(.local) — LGTMMatches the TCP pattern and should be correct on the loop thread.
Please verify xev UDP callbacks are always invoked on the executor’s loop thread; use
.maybe_remoteif any callback can be off-thread.Also applies to: 61-62, 117-118, 169-170
src/file.zig (1)
8-9: File I/O callbacks: resumeTask(.local) — solid cleanupUniform switch away from executor.markReady improves clarity; .local is correct for loop-thread callbacks.
Also applies to: 59-60, 111-112, 187-188, 235-236, 298-299, 345-346, 383-384
src/core/ConcurrentAwaitableStack.zig (1)
33-38: popAll semantics — LGTMAtomic swap with
.acq_relcorrectly drains and synchronizes with producers; returning a SimpleAwaitableStack is clean.src/core/ConcurrentAwaitableList.zig (2)
120-151: Executor-aware spin yielding looks goodConditional yielding during lock contention avoids TDZ and preserves non-yielding behavior when executor is null. Memory orderings (.acquire/.release) are appropriate for the lock handoff.
307-338: popOrTransition logic is correct and retry-safeTransitions use acq_rel on success and acquire on failure; retry on self-removal races is sound. No changes requested.
src/core/SimpleAwaitableStack.zig (1)
13-30: LGTM: push/pop correctnessPush/pop maintain in_list in Debug and clear next on pop. Matches single-threaded LIFO semantics.
src/core/Awaitable.zig (1)
18-48: Awaitable base type looks solid
- Alignment check for tagged pointers is correct.
- Atomics and cancellation flag with release/acquire semantics are appropriate.
- Embedded ConcurrentAwaitableList default-initialized for per-object waiters.
src/runtime.zig (9)
55-69: Switching to resumeTask(.local) in I/O callback is appropriateEnsures local fast-path without cross-thread checks.
104-124: Remote ready draining logic is correctDrains concurrent remote stack into local next_ready_queue and rearms. Matches run() initialization.
156-203: waitForComplete: robust coroutine/thread paths with double-check and cleanup
- Double-checked state prevents lost wakeups.
- Cancellation path removes from wait list.
- Futex path uses release/acquire pairing.
205-268: timedWaitForComplete: correct timeout/remove integrationTimeout callback removes from wait list and yields with proper error propagation; thread path uses Futex.timedWait.
270-301: markComplete: correct ordering and cross-executor resumption
- Sets state with .release before waking.
- Drains waiters and uses resumeTask(.maybe_remote).
- Wakes futex waiters after coroutine wakeups.
310-332: resumeTask and ResumeMode: clean APIType-agnostic resume with executor-local/remote paths; straightforward and safe.
695-706: Re-exporting core types through runtime is fineImports of Simple/Concurrent stacks/lists centralize public API.
1027-1034: TLS current_executor and remote init in run()TLS setup and ensureRemoteInitialized() before loop are necessary for cross-thread resumption. Good.
1519-1547: select() waiter enqueue/dequeue updated correctlyPushes with executor, defers safe removal for non-ready waiters; aligns with markComplete’s select_waiter handling.
|
@claude address the race identified by coderabbit And also fix remove(), we will probably need to make the in_list a regular field, not debug only tool |
|
Claude finished @lalinsky's task —— View job Race condition fixes completedTasks
SummaryI've addressed all the race conditions identified by CodeRabbit and fixed the 1. Fixed race condition in ConcurrentAwaitableList.remove() (lines 284-291)
2. Removed over-strict assert in ConcurrentAwaitableList.remove()
3. Fixed SimpleAwaitableList.remove() with proper membership checks
4. Made
All tests pass successfully (90/90). |
- Fix race in ConcurrentAwaitableList.remove() where tail was cleared after releasing mutation lock when removing the last node - Remove over-strict debug assert in ConcurrentAwaitableList.remove() that broke valid timeout/cancellation cleanup races - Add proper membership checks in SimpleAwaitableList.remove() to prevent list corruption when removing items not in the list - Make in_list a regular field instead of debug-only to enable reliable membership checks in all builds Co-authored-by: Lukáš Lalinský <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/core/ConcurrentAwaitableList.zig (1)
248-262: Consider simplifying the redundant checks or document the intent.There are two separate checks for whether the awaitable is in the list:
- Lines 248-253: Pointer-based check (
awaitable.prev == null and head != awaitable)- Lines 255-259: Flag-based check (
!awaitable.in_list)The first check serves as an optimization or safety net, but now that
in_listis the authoritative source of truth, this could lead to subtle inconsistencies if the flag and pointers ever disagree (e.g., due to a bug elsewhere).Recommendation: Either document why both checks are necessary, or simplify by checking
in_listfirst and optionally adding pointer checks as assertions for internal consistency.Example refactor:
- // Check if we're actually in the list (using prev/next pointers) - // If prev is null and we're not head, we're not in the list - if (awaitable.prev == null and head != awaitable) { - self.releaseMutationLock(); - return false; // Not in list - } - // Check if not in list (may have been removed by concurrent action) if (!awaitable.in_list) { self.releaseMutationLock(); return false; } + + // Sanity check: if in_list is true, pointers should be consistent + std.debug.assert(awaitable.prev != null or head == awaitable);
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
src/core/Awaitable.zig(1 hunks)src/core/AwaitableList.zig(4 hunks)src/core/ConcurrentAwaitableList.zig(9 hunks)src/core/SimpleAwaitableStack.zig(1 hunks)src/sync/ResetEvent.zig(4 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- src/core/SimpleAwaitableStack.zig
- src/core/Awaitable.zig
- src/sync/ResetEvent.zig
🔇 Additional comments (10)
src/core/AwaitableList.zig (4)
9-9: LGTM: Clear type rename.The rename from
AwaitableListtoSimpleAwaitableListeffectively distinguishes this non-concurrent implementation from concurrent variants introduced elsewhere in the PR.
14-27: LGTM: Defensive double-insertion check.Making
in_lista regular field (rather than debug-only) and unconditionally asserting!awaitable.in_listprovides runtime detection of double-insertion bugs, even in release builds. This aligns with the PR objective to makein_lista regular field.
29-41: LGTM: Proper cleanup on removal.The function correctly clears
in_listand resets linkage pointers, ensuring the awaitable is fully detached from the list.
61-97: LGTM: Addresses double-removal concern.The
in_listcheck (line 66) prevents double-removal, and the membership validations (lines 69, 71) catch scenarios where an awaitable at the head or tail position doesn't belong to this list. This addresses the race/correctness concerns mentioned in the PR comments.Note: The membership checks are best-effort—they won't detect an awaitable in the middle of a different list. For a non-concurrent data structure, this is reasonable. If stronger guarantees are needed, you could traverse the list to confirm membership, though this would change the operation from O(1) to O(n).
src/core/ConcurrentAwaitableList.zig (6)
127-151: LGTM! Conditional yielding based on executor presence.The addition of the optional
executorparameter and conditional yielding (lines 145-147) allows for a no-yield spin path when called from contexts where yielding is not appropriate (e.g., thread pool callbacks). The implementation correctly defaults to spinning withspinLoopHint()when no executor is provided.
168-193: LGTM!in_listis now tracked unconditionally.The
in_listfield is properly set to true when pushing (lines 170-171) and asserted to be false beforehand (line 170). This aligns with the PR objective to makein_lista regular field instead of debug-only.
197-211: LGTM!in_listproperly maintained in pop.The field is correctly asserted (line 210) and cleared (line 211) during removal.
255-262: LGTM! This addresses the race condition.The check at lines 255-259 correctly handles the case where the awaitable was removed by another operation (e.g., cancellation) after we started waiting for the mutation lock but before we acquired it. This prevents double-removal and aligns with the PR objective to address the race condition identified by CodeRabbit.
309-334: LGTM! Consistent API change.The
executorparameter is properly threaded through to thepopcall at line 328.
336-391: Consider adding test coverage for null-executor path.All tests pass a non-null
&runtime.executor. The new null-executor behavior (spinning without yielding) is not exercised in tests. While this might be acceptable if null-executor is only used in specific runtime contexts, adding a test case would improve confidence in the no-yield code path.Example test addition:
test "ConcurrentAwaitableList with null executor" { const testing = std.testing; var list = ConcurrentAwaitableList.init(); var awaitable align(8) = Awaitable{ .kind = .task, .destroy_fn = struct { fn dummy(_: *Runtime, _: *Awaitable) void {} }.dummy, }; // Test push/pop without executor (should not yield) list.push(null, &awaitable); const popped = list.pop(null); try testing.expectEqual(&awaitable, popped); }
- Change in_list from regular field to debug-only field that only exists when builtin.mode == .Debug - Use structural invariants for membership checks: items not in a list have both prev and next set to null after removal - Add missing next/tail membership check to ConcurrentAwaitableList.remove() (was only checking prev/head) - Remove in_list early-return checks from remove() functions - structural checks are sufficient and work in all build modes - Add comprehensive double-remove tests for both SimpleAwaitableList and ConcurrentAwaitableList to verify structural checks work correctly The structural checks provide reliable membership detection: - If prev == null, item must be head (or not in list) - If next == null, item must be tail (or not in list) - If both are null, item is definitely not in list This makes in_list purely a debug-time validation aid rather than a runtime requirement, reducing struct size in release builds.
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
src/core/Awaitable.zig(1 hunks)src/core/AwaitableList.zig(5 hunks)src/core/ConcurrentAwaitableList.zig(10 hunks)src/core/SimpleAwaitableStack.zig(1 hunks)src/sync/ResetEvent.zig(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- src/sync/ResetEvent.zig
- src/core/SimpleAwaitableStack.zig
🔇 Additional comments (8)
src/core/Awaitable.zig (2)
37-41: LGTM: Alignment enforcement for tagged pointers.The compile-time alignment check is essential for the tagged pointer operations used by
ConcurrentAwaitableList. The check ensures the lower 2 bits are available for state/lock encoding.
45-47: LGTM: Cancellation signaling.The cancellation mechanism using atomic store with release ordering is correct. The
.releaseordering ensures the cancellation flag becomes visible to any thread that subsequently loads it.src/core/AwaitableList.zig (3)
9-9: LGTM: Rename to SimpleAwaitableList.The rename clarifies that this is a non-concurrent list implementation, distinguishing it from
ConcurrentAwaitableList.
65-100: Verify remove() membership validation is sufficient.The membership validation logic (lines 69-72) checks pointer consistency, but with
in_listcurrently being debug-only (see comment on Awaitable.zig:26), release builds have no definitive membership tracking. Oncein_listbecomes a regular field, consider adding an explicit check:if (builtin.mode == .Debug or true) { // Will become: if (true) after in_list is regular if (!awaitable.in_list) return false; }This provides an early exit before acquiring locks or traversing pointers.
The current pointer-based validation is correct but could race without the
in_listflag in release builds. The fix for Awaitable.zig:26 will address this.
102-157: LGTM: Comprehensive double-remove test coverage.The test validates:
- Middle element double-remove (lines 137-140)
- Head element double-remove (lines 143-146)
- Tail element double-remove (lines 149-152)
- Final empty state verification (lines 155-156)
This provides strong coverage for the idempotent remove behavior.
src/core/ConcurrentAwaitableList.zig (3)
127-151: LGTM: Optional executor with conditional yielding.The pattern of accepting
?*Executorand conditionally yielding (lines 145-147) is well-designed. This allows:
- Thread pool callbacks to spin without yielding (pass
null)- Coroutine contexts to yield cooperatively (pass executor)
The memory ordering with
.acquireon fetchOr (line 134) correctly synchronizes with the previous lock release.
241-306: Verify remove() membership validation consistency.The membership validation (lines 254-262) mirrors the logic in
SimpleAwaitableList.remove()(lines 69-72), which is good for consistency. However, similar to the non-concurrent version, oncein_listbecomes a regular field (per the fix in Awaitable.zig:26), consider adding an early exit:// After acquiring mutation lock, before pointer traversal if (!awaitable.in_list) { self.releaseMutationLock(); return false; }This reduces contention by releasing the lock faster for non-members.
The tail update ordering comment (lines 286-287) correctly identifies that
tailmust be updated before releasing the mutation lock viastore(.release), ensuring proper visibility.The current implementation is correct, but the suggested optimization becomes possible once
in_listis a regular field.
398-451: LGTM: Thorough double-remove test coverage.The test comprehensively validates idempotent remove behavior across all positions (middle, head, tail) and verifies the final sentinel state. This provides strong confidence in the concurrent remove implementation.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/core/ConcurrentAwaitableList.zig (1)
400-453: Good single-threaded coverage, but consider adding concurrent test.The test correctly validates idempotent removal behavior for head, middle, and tail positions. However, since this is a concurrent data structure and the double-removal protection is meant to prevent races, consider adding a concurrent test where multiple threads attempt to remove the same awaitable simultaneously.
Example concurrent test skeleton:
test "ConcurrentAwaitableList concurrent double remove" { const testing = std.testing; var runtime = try Runtime.init(testing.allocator, .{}); defer runtime.deinit(); var list = ConcurrentAwaitableList.init(); var awaitable = align(8) Awaitable{ .kind = .task, .destroy_fn = ... }; list.push(&runtime.executor, &awaitable); // Spawn multiple threads trying to remove the same awaitable // Only one should succeed, others should return false var threads: [4]std.Thread = undefined; var results = [_]std.atomic.Value(bool){...}; for (&threads, 0..) |*thread, i| { thread.* = try std.Thread.spawn(.{}, struct { fn remove_worker(l: *ConcurrentAwaitableList, a: *Awaitable, result: *std.atomic.Value(bool)) void { result.store(l.remove(null, a), .seq_cst); } }.remove_worker, .{&list, &awaitable, &results[i]}); } for (&threads) |*thread| thread.join(); // Verify exactly one thread succeeded var success_count: usize = 0; for (results) |r| if (r.load(.seq_cst)) success_count += 1; try testing.expectEqual(@as(usize, 1), success_count); }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/core/ConcurrentAwaitableList.zig(10 hunks)
🔇 Additional comments (4)
src/core/ConcurrentAwaitableList.zig (4)
127-153: LGTM: Nullable executor pattern correctly implemented.The conditional yielding logic properly handles both thread pool contexts (null executor) and runtime contexts (non-null executor). When the executor is null, the code appropriately falls back to
std.Thread.yield().
170-170: Consistent nullable executor propagation.The signature changes properly thread the nullable executor through the call chain to
acquireMutationLock(). The pattern is applied consistently acrosspush,pop, andpopOrTransition.Also applies to: 201-201, 316-316
287-293: Correct ordering for tail update before lock release.The explicit comment and implementation correctly update
tail = nullbefore thehead.store()which implicitly releases the mutation lock. The.releasememory order ensures the tail update is visible to future lock acquirers.
129-129: Nullable executor usage is consistent. Allwaiting_listcalls pass a non-nullexecutor; nonullarguments were found.
* Add IOCP backend skeleton with SharedState refcounting Implements bare-bones IOCP backend for Windows with thread-safe SharedState that allows multiple loops to share a single IOCP handle. - Add iocp backend to BackendType enum - Set iocp as default backend for Windows - Implement SharedState with mutex and refcounting - Implement init/deinit with acquire/release semantics - Implement poll() using GetQueuedCompletionStatusEx - Stub wake/submit/cancel with panic for now The IOCP handle is created on first loop init and destroyed when the last loop is deinitialized, enabling one loop per thread pattern. * Add extension function loading with per-family caching Implements lazy loading of Winsock extension functions (AcceptEx, ConnectEx) with thread-safe caching per address family. - Add ExtensionFunctions struct with AcceptEx/ConnectEx pointers - Add extension_cache (HashMap<family, ExtensionFunctions>) - Implement getExtensions() for lazy loading with caching - Load functions via WSAIoctl(SIO_GET_EXTENSION_FUNCTION_POINTER) - Cache key is address family (u16) since functions are STREAM-only - Thread-safe access via SharedState mutex * Implement IOCP backend basic network operations - Add Completion.internal field with backend-specific CompletionData - Implement net_open: create socket and associate with IOCP handle - Implement net_connect: use ConnectEx with pre-binding requirement - Implement net_accept: use AcceptEx with address buffer - Implement poll() completion processing using @fieldParentPtr - Add NetAcceptData for accept-specific address buffer storage All completions now have OVERLAPPED in Completion.internal, with net_accept getting additional buffer space in its per-operation internal field. Processing uses @fieldParentPtr to navigate from OVERLAPPED back to the Completion struct. * Implement wake() for IOCP using QueueUserAPC with alertable waits Each Backend stores a duplicated thread handle obtained during init(). wake() uses QueueUserAPC to queue an APC to the target thread, which interrupts GetQueuedCompletionStatusEx when called with fAlertable=TRUE. When poll() receives WAIT_IO_COMPLETION, it calls processAsyncHandles() to process any pending async notifications. This allows waking a specific loop thread despite sharing the IOCP handle across multiple loops, solving the fundamental issue that you cannot wake a specific waiter with PostQueuedCompletionStatus. * Progres * Add null pointer check for IOCP completion entries Handle cases where lpOverlapped is NULL in IOCP completion entries, which can occur when the IOCP port is closed or in certain error conditions. * Fix IOCP completion handling for immediate operations According to Windows documentation, when WSARecv/WSASend/WSARecvFrom/ WSASendTo succeed immediately (return 0) or return WSA_IO_PENDING, the completion is STILL posted to the IOCP port. Previously we were completing operations twice when they succeeded immediately. Now we only complete immediately on real errors (not WSA_IO_PENDING), and let all successful operations complete via IOCP. Note: Tests still fail on wine due to wine bugs in IOCP implementation, but the logic is correct for real Windows. * Implement cancel() for IOCP backend using CancelIoEx Use Windows CancelIoEx API to cancel running async I/O operations. When an operation is canceled, Windows posts a completion to the IOCP port with ERROR_OPERATION_ABORTED status, which we handle in processCompletion(). Supports cancellation of: - Network operations (connect, accept, recv, send, recvfrom, sendto) - File operations (read, write, sync) Synchronous operations (open, close, etc.) complete immediately and don't need cancellation support. * Fix AcceptEx and ConnectEx immediate completion handling Both AcceptEx and ConnectEx post completions to IOCP even when they succeed immediately (return TRUE). Previously we were completing these operations twice - once synchronously and once via IOCP, which caused crashes. Now we only complete immediately on real errors (not WSA_IO_PENDING), and let all successful operations complete via IOCP. Note: Tests still crash on wine with segfault at address 0x1. This appears to be a wine-specific issue that needs to be debugged on real Windows. * Fix IOCP backend issues and enable proper error handling Fixed three critical bugs in the IOCP backend: 1. **Dangling pointer in getExtensions()**: Changed to return ExtensionFunctions by value instead of pointer to avoid HashMap invalidation issues 2. **Improper error mapping**: Use net.errnoToConnectError/AcceptError/RecvError/SendError instead of error.Unexpected, which properly maps WSA_OPERATION_ABORTED to error.Canceled for cancelled operations 3. **Duplicate IOCP association**: Removed redundant CreateIoCompletionPort call for accepted sockets (already associated in submitAccept) All tests now pass on Wine (52/54, 2 skipped Unix-specific tests). * Fix vectored UDP * Use proper error mapping functions in IOCP submit handlers Replace error.Unexpected with proper error mapping functions (errnoToAcceptError, errnoToRecvError, errnoToSendError, errnoToConnectError) in submit handlers when operations fail immediately. * Populate peer address in AcceptEx completion Call GetAcceptExSockaddrs to parse AcceptEx's address buffer and copy the remote address to caller-provided buffers, handling truncation when the user buffer is smaller than the actual address. * Implement recv/send flags mapping for IOCP backend Add support for MSG_PEEK and MSG_WAITALL flags in WSARecv/WSARecvFrom. MSG_NOSIGNAL from SendFlags is ignored on Windows (no signals). Uses windows.ws2_32.MSG.PEEK and MSG.WAITALL from std library. * Add BackendCapabilities for granular file operation support Replace supports_file_ops boolean with BackendCapabilities struct that allows backends to selectively support individual file operations. - io_uring: all file ops supported - poll/epoll/kqueue: no file ops supported (use thread pool) - iocp: only file_read and file_write supported (async via OVERLAPPED) This allows IOCP to use async ReadFile/WriteFile while delegating synchronous operations (open/close/sync/rename/delete) to thread pool. * Implement async file I/O for IOCP backend Add support for async file read/write operations on Windows using IOCP: - Add postProcessFileHandle() hook to associate file handles with IOCP after they're opened/created in the thread pool - Implement submitFileRead/submitFileWrite using ReadFile/WriteFile APIs - Add completion handlers for file_read and file_write operations - Add nonblocking flag to FileOpenFlags/FileCreateFlags that defaults to true when backend supports async file I/O, ensuring files are opened with FILE_FLAG_OVERLAPPED on Windows - Add capability checks in submitFileOpToThreadPool for all file operations to ensure they're only routed there when unsupported * Cleaner file IO integration * Test IOCP * Fix IOCP setsockopt error handling for socket context updates Check return value of setsockopt calls for SO_UPDATE_CONNECT_CONTEXT and SO_UPDATE_ACCEPT_CONTEXT. On failure, close the socket handle and return the appropriate error using errnoToConnectError/errnoToAcceptError. * Remove files * Simplify * Fixes * Fix
Summary
Refactors runtime internals by extracting awaitable data structures into separate, well-documented modules and improving concurrent task management primitives.
Changes
New Core Data Structures (
src/core/):Awaitable.zig- Base type for all awaitable objects (tasks, futures, etc.) with reference counting and cancellation supportAwaitableList.zig- Non-concurrent doubly-linked list with O(1) operationsConcurrentAwaitableList.zig- Thread-safe FIFO list using tagged pointers with mutation spinlockConcurrentAwaitableStack.zig- Lock-free stack for cross-thread communicationSimpleAwaitableStack.zig- Single-threaded LIFO stackRuntime Improvements (
runtime.zig):resumeTask()function with compile-time optimized resume modes (.localvs.remote)in_listfield debug-only to reduce memory overheadOther Changes:
resumeTask()APIBenefits
Summary by CodeRabbit
New Features
Refactor