Repository navigation
Redesign Group to use futex-based completion - #187
Conversation
Replace ResetEvent-based completion signaling with a futex on a u32 counter. This simplifies the implementation and prepares for future std.Io.Group compatibility by using a matching IoGroup layout. Changes: - Use IoGroup struct with token (task list) and state (counter + flags) - Track pending tasks with atomic u32 counter instead of ResetEvent - Use Futex.wait/wake for completion synchronization - Extract onGroupTaskComplete to handle counter decrement and wake - Use sentinel states to control spawning during wait/cancel
|
Warning Rate limit exceeded@lalinsky has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 6 minutes and 12 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughCentralizes group-task completion via a new Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~35 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In @src/runtime/group.zig:
- Around line 18-22: Add a compile-time verification that IoGroup truly matches
std.Io.Group by adding a comptime block that, when std.Io.Group is available,
asserts @sizeOf(IoGroup) == @sizeOf(std.Io.Group) and @alignOf(IoGroup) ==
@alignOf(std.Io.Group); place this near the existing State size assertion and
guard it so it only runs when std.Io.Group exists (e.g., using a comptime check
for the declaration) and remove the claim if you cannot perform these checks.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/runtime.zigsrc/runtime/blocking_task.zigsrc/runtime/group.zigsrc/runtime/task.zig
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: 2025-11-04T10:29:56.949Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 118
File: src/core/task.zig:33-115
Timestamp: 2025-11-04T10:29:56.949Z
Learning: In zio's task implementation (src/core/task.zig), the Closure struct intentionally caps result_len and context_len at 4096 bytes (using u12 fields) and alignment at 16 bytes (using u4 padding fields). This is a deliberate design decision to avoid bloating task structures. Users needing larger result or context storage should heap-allocate and pass pointers instead. These limits are more generous than std lib's fixed storage (64 bytes for results, 1024 bytes for args).
<!-- [add_learning]
The task storage limits in zio (4 KiB for result/context, 16-byte alignment) are intentional design constraints to prevent task bloat, not correctness issues. The maintainer's position is that larger data should be heap-allocated.
Applied to files:
src/runtime.zigsrc/runtime/task.zigsrc/runtime/group.zig
📚 Learning: 2025-10-03T11:09:46.846Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 18
File: src/net.zig:18-25
Timestamp: 2025-10-03T11:09:46.846Z
Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.
Applied to files:
src/runtime.zigsrc/runtime/blocking_task.zig
📚 Learning: 2025-09-27T04:41:48.632Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 5
File: src/runtime.zig:257-273
Timestamp: 2025-09-27T04:41:48.632Z
Learning: RefCounter.init() starts with an initial count of 1, not 0. When a task is created in spawn(), the initial count represents the runtime's ownership when stored in self.tasks, and an additional incr() is called for the returned Task(T) handle.
Applied to files:
src/runtime/group.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 (9)
src/runtime/task.zig (1)
78-78: Clean delegation to centralized completion handler.The removal of group-specific completion logic from the task start path is correct. Completion is now handled by
onGroupTaskCompleteinvoked from the runtime scheduler, providing a single point of control for group task lifecycle.src/runtime/blocking_task.zig (2)
13-13: Import added for centralized completion handler.
97-100: Correct delegation to centralized group completion handler.The reference counting model is sound:
- Group holds one reference (incremented at spawn, released by
onGroupTaskComplete)- Runtime holds one reference (released at line 104)
The completion flow correctly handles both references.
src/runtime.zig (2)
31-31: Import added for centralized completion handler.
560-563: Consistent group completion handling in scheduler.The flow matches the blocking task path and correctly manages the group reference before releasing the runtime's reference.
src/runtime/group.zig (4)
64-93: Flag operations use correct atomic orderings.The memory orderings (
.acq_relfor RMW,.acquirefor loads) correctly synchronize flag updates across threads. The TODO at line 85 indicatesfail_fastearly wake isn't implemented yet, which is acceptable for this PR's scope.
117-146: Counter management and error handling are correct.The errdefer chain properly unwinds on errors:
- Counter decrement (line 119)
- Task free (line 131)
- Task list removal (line 140)
The call to
pushUnless(.sentinel1, ...)correctly prevents spawning into a closing group. The errdefer at line 140 safely callsremoveeven ifpushUnlessfailed, assumingremoveis idempotent (returns false for items not in the list).
198-209: Correct atomicity and reference counting in completion handler.The atomic RMW correctly detects the last task (previous value == 1) and wakes all waiters. The conditional release based on
remove()'s return value prevents double-release when racing withcancel(). Reference counting is sound: group releases its reference here, runtime releases its reference after calling this function.
185-191: The code is correct.Futex.waitrespects cancellation shields—whencheckCanceled()is called (before and after the yield intimedWait), it returns early ifshield_count > 0. The shield set bybeginShield()on line 2 ofcancel()preventsFutex.waitfrom returningerror.Canceled, making thecatch unreachableon line 19 safe. The errdefer flow (whenwait()encounters cancellation and callscancel()from its cleanup handler) is protected by this same mechanism.Likely an incorrect or invalid review comment.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In @src/runtime/group.zig:
- Around line 166-189: The Futex.wait call inside cancel should not use `catch
unreachable`; change the error handling to capture the returned error from
Futex.wait(rt, counter_ptr, counter) and explicitly handle it (e.g., assert or
panic with the error value and context) so recoverable failures do not become
undefined behavior; update the cancel function in Group to store the error
result and call a clear panic/assert reporting the error, ensuring shielding via
Runtime.beginShield()/endShield() remains in place while waiting on
group.getCounter().
- Around line 192-203: The race is caused by onGroupTaskComplete decrementing
the counter and waking waiters before removing the awaitable and releasing its
ref; move the removal+release step to occur before the atomic decrement and
Futex.wake: call group.getTasks().remove(&awaitable.group_node) and if true call
rt.releaseAwaitable(awaitable, false) first, then perform the @atomicRmw(u32,
counter_ptr, .Sub, 1, .acq_rel) check and call Futex.wake(rt, counter_ptr,
std.math.maxInt(u32)) if it returns 1; keep same functions (onGroupTaskComplete,
getTasks, remove, releaseAwaitable, getCounter, Futex.wake) and preserve
semantics otherwise.
🧹 Nitpick comments (3)
src/runtime/group.zig (3)
16-23:IoGroup/Statelayout is effectively 64-bit-only right now; make that explicit (or support 32-bit).
Line 35-42 hard-require@sizeOf(State) == @sizeOf(usize); withState { u32, u32 }that won’t hold on 32-bit targets. If 32-bit is intentionally unsupported, add a clear comptime guard/error so failures are obvious.Proposed diff
pub const Group = struct { inner: IoGroup = .{}, pub const init: Group = .{}; + comptime { + // State overlays IoGroup.state (usize). Current design assumes 64-bit. + if (@sizeOf(usize) != 8) { + @compileError("zio Group requires 64-bit (usize=8) for futex counter+flags State overlay"); + } + } + // Interpret inner.token as CompactWaitQueue head
25-63: Pointer-castingIoGroup.token/stateinto other types: add alignment/type invariants to prevent “works by accident”.
getTasks()andgetStatePtr()rely on@ptrCastoverlays (Line 48-54). This is fine when the layout assumptions hold, but it’s brittle across Zig/std changes. At minimum, assert alignment and size invariants so failures are loud.Proposed diff
comptime { std.debug.assert(@sizeOf(State) == @sizeOf(usize)); + std.debug.assert(@alignOf(State) <= @alignOf(usize)); }
64-93: Flags API looks sane; TODO should become a tracked issue.
Atomic Or + atomicLoad w/ acquire is consistent. The fail_fast TODO (Line 85) is easy to forget; consider converting it to a real issue/task if it’s meant to ship later.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/runtime/group.zig
🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: lalinsky
Repo: lalinsky/zio PR: 118
File: src/core/task.zig:33-115
Timestamp: 2025-11-04T10:29:56.949Z
Learning: In zio's task implementation (src/core/task.zig), the Closure struct intentionally caps result_len and context_len at 4096 bytes (using u12 fields) and alignment at 16 bytes (using u4 padding fields). This is a deliberate design decision to avoid bloating task structures. Users needing larger result or context storage should heap-allocate and pass pointers instead. These limits are more generous than std lib's fixed storage (64 bytes for results, 1024 bytes for args).
<!-- [add_learning]
The task storage limits in zio (4 KiB for result/context, 16-byte alignment) are intentional design constraints to prevent task bloat, not correctness issues. The maintainer's position is that larger data should be heap-allocated.
📚 Learning: 2025-10-16T14:33:19.718Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 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/group.zig
📚 Learning: 2026-01-07T13:15:48.677Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 179
File: src/os/windows.zig:424-424
Timestamp: 2026-01-07T13:15:48.677Z
Learning: In `src/os/windows.zig`, WSABUF must be re-exported from `std.os.windows.ws2_32.WSABUF` rather than defined locally because it needs to satisfy `std.Io.Reader` compatibility requirements.
Applied to files:
src/runtime/group.zig
📚 Learning: 2025-11-04T10:29:56.949Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 118
File: src/core/task.zig:33-115
Timestamp: 2025-11-04T10:29:56.949Z
Learning: In zio's task implementation (src/core/task.zig), the Closure struct intentionally caps result_len and context_len at 4096 bytes (using u12 fields) and alignment at 16 bytes (using u4 padding fields). This is a deliberate design decision to avoid bloating task structures. Users needing larger result or context storage should heap-allocate and pass pointers instead. These limits are more generous than std lib's fixed storage (64 bytes for results, 1024 bytes for args).
<!-- [add_learning]
The task storage limits in zio (4 KiB for result/context, 16-byte alignment) are intentional design constraints to prevent task bloat, not correctness issues. The maintainer's position is that larger data should be heap-allocated.
Applied to files:
src/runtime/group.zig
📚 Learning: 2025-09-27T04:41:48.632Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 5
File: src/runtime.zig:257-273
Timestamp: 2025-09-27T04:41:48.632Z
Learning: RefCounter.init() starts with an initial count of 1, not 0. When a task is created in spawn(), the initial count represents the runtime's ownership when stored in self.tasks, and an additional incr() is called for the returned Task(T) handle.
Applied to files:
src/runtime/group.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). (2)
- GitHub Check: test (macos-latest)
- GitHub Check: test (windows-latest)
🔇 Additional comments (2)
src/runtime/group.zig (2)
95-146: The fast-path check already exists—no changes needed.Line 105 has
if (self.isClosed()) return error.Closed;before task creation. This rejects spawns when the group is canceled or failed (both set theclosed_bitviasetCanceled()andsetFailed()), so canceled/failed groups do block new spawns. The sentinel1 check at line 148 is redundant but harmless—a defensive safeguard in case the group transitions between the isClosed() check and the push attempt. The implementation is sound.Likely an incorrect or invalid review comment.
148-164: This concern is addressed by the actual implementation. Thewait()function callsgroup.setClosed()at the very beginning (line 159) before entering the counter loop. This sets aclosed_bitflag using atomic operations with release semantics. Any subsequentspawn()call checksisClosed()with acquire semantics as its first operation (line 105), which will fail witherror.Closeddue to the synchronization guarantees of the atomic acquire-release pair. The race condition you described cannot occur because new spawns are rejected immediately afterwait()begins, not just when it detects counter==0.Likely an incorrect or invalid review comment.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (2)
src/runtime/group.zig (2)
86-86: Track the fail_fast early-wake implementation.The fail_fast flag is set but not yet acted upon. If early termination on first error is a feature you're planning to ship, consider opening an issue to track implementing the early wake logic.
Would you like me to open an issue to track this TODO?
192-197: Thecatch unreachableis safe here, but warrants a comment.Since cancel runs within beginShield/endShield, the Futex.wait on line 196 cannot return error.Canceled. A one-line comment explaining this would help future readers.
📝 Suggested comment
+ // Safe: beginShield prevents cancellation during this wait Futex.wait(rt, counter_ptr, counter) catch unreachable;
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/runtime/group.zig
🧰 Additional context used
🧠 Learnings (9)
📓 Common learnings
Learnt from: lalinsky
Repo: lalinsky/zio PR: 118
File: src/core/task.zig:33-115
Timestamp: 2025-11-04T10:29:56.949Z
Learning: In zio's task implementation (src/core/task.zig), the Closure struct intentionally caps result_len and context_len at 4096 bytes (using u12 fields) and alignment at 16 bytes (using u4 padding fields). This is a deliberate design decision to avoid bloating task structures. Users needing larger result or context storage should heap-allocate and pass pointers instead. These limits are more generous than std lib's fixed storage (64 bytes for results, 1024 bytes for args).
<!-- [add_learning]
The task storage limits in zio (4 KiB for result/context, 16-byte alignment) are intentional design constraints to prevent task bloat, not correctness issues. The maintainer's position is that larger data should be heap-allocated.
📚 Learning: 2025-10-16T14:33:19.718Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 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/group.zig
📚 Learning: 2026-01-07T13:15:48.677Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 179
File: src/os/windows.zig:424-424
Timestamp: 2026-01-07T13:15:48.677Z
Learning: In `src/os/windows.zig`, WSABUF must be re-exported from `std.os.windows.ws2_32.WSABUF` rather than defined locally because it needs to satisfy `std.Io.Reader` compatibility requirements.
Applied to files:
src/runtime/group.zig
📚 Learning: 2025-11-04T10:29:56.949Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 118
File: src/core/task.zig:33-115
Timestamp: 2025-11-04T10:29:56.949Z
Learning: In zio's task implementation (src/core/task.zig), the Closure struct intentionally caps result_len and context_len at 4096 bytes (using u12 fields) and alignment at 16 bytes (using u4 padding fields). This is a deliberate design decision to avoid bloating task structures. Users needing larger result or context storage should heap-allocate and pass pointers instead. These limits are more generous than std lib's fixed storage (64 bytes for results, 1024 bytes for args).
<!-- [add_learning]
The task storage limits in zio (4 KiB for result/context, 16-byte alignment) are intentional design constraints to prevent task bloat, not correctness issues. The maintainer's position is that larger data should be heap-allocated.
Applied to files:
src/runtime/group.zig
📚 Learning: 2025-10-21T10:00:56.962Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 62
File: src/utils/queue.zig:141-147
Timestamp: 2025-10-21T10:00:56.962Z
Learning: In work-stealing queues implemented in src/utils/queue.zig, stealers only modify the victim's head position, never the tail. The tail is exclusively owned by the owner thread, so no atomic acquire operations are needed when the owner reads its own tail.
Applied to files:
src/runtime/group.zig
📚 Learning: 2025-10-21T10:07:03.593Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 62
File: src/utils/queue.zig:109-126
Timestamp: 2025-10-21T10:07:03.593Z
Learning: In src/utils/queue.zig WorkStealingQueue implementation, the owner thread can safely use `.raw` to read its own `tail` atomic value since the owner is always a single thread and only it modifies tail. No ordering is needed when reading your own writes within the same thread.
Applied to files:
src/runtime/group.zig
📚 Learning: 2025-10-15T19:38:44.659Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 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/runtime/group.zig
📚 Learning: 2025-10-10T05:59:17.087Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 41
File: src/udp.zig:79-82
Timestamp: 2025-10-10T05:59:17.087Z
Learning: In UDP socket operations (src/udp.zig), error.Canceled from result_data.result represents OS/IO-level cancellation (e.g., io_uring), not user-requested cancellation. User cancellation is handled by waitForXevCompletion() via try. OS-level error.Canceled should be mapped to error.Unexpected as it represents an unexpected system event.
Applied to files:
src/runtime/group.zig
📚 Learning: 2025-09-27T04:41:48.632Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 5
File: src/runtime.zig:257-273
Timestamp: 2025-09-27T04:41:48.632Z
Learning: RefCounter.init() starts with an initial count of 1, not 0. When a task is created in spawn(), the initial count represents the runtime's ownership when stored in self.tasks, and an additional incr() is called for the returned Task(T) handle.
Applied to files:
src/runtime/group.zig
🔇 Additional comments (4)
src/runtime/group.zig (4)
104-157: Spawn logic is solid.The double-gate pattern (isClosed check + pushUnless sentinel) cleanly prevents races between spawn and wait/cancel. Counter increment before list insertion ensures wait() never exits early. Cleanup paths are correct.
159-176: Wait implementation handles the counter/list race correctly.The cleanup loop (lines 172-175) is necessary: a task can decrement counter to zero and wake waiters before removing itself from the list. Popping stragglers here prevents leaks.
204-215: Clean completion hook design.Centralizing the decrement-wake-remove-release sequence in a single function called from runtime prevents duplication and ensures consistent task accounting. The conditional release (line 212-213) correctly handles the race with cancel().
40-42: This assertion is correct and aligns with documented platform support. The README explicitly lists supported architectures as 64-bit only (x86_64,aarch64,riscv64,loongarch64). The constraint is intentional—theStatestruct's twou32fields (8 bytes) is designed to match 64-bitusize. No action needed.
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Summary
onGroupTaskCompleteto handle counter decrement and wake from runtimeTest plan
./check.shto verify existing Group tests pass./check.sh --fullfor full validation