Skip to content

Implement std.Io.Group operations - #154

Merged
lalinsky merged 4 commits into
stdiofrom
stdio-group
Dec 7, 2025
Merged

lalinsky merged 4 commits into
stdiofrom
stdio-group

Conversation

@lalinsky

@lalinsky lalinsky commented Dec 7, 2025

Copy link
Copy Markdown
Owner

Summary

  • Add Closure.Start tagged union for regular vs group task functions
  • Update AnyTask and AnyBlockingTask to handle group start functions
  • Add standalone groupWait and groupCancel functions in group.zig
  • Make Group.wait/cancel compatible with std.Io.Group (idempotent, clears token)
  • Implement groupAsyncImpl, groupConcurrentImpl, groupWaitImpl, groupCancelImpl
  • Add comptime assertions for std.Io.Group binary compatibility
  • Add CompactWaitQueue.fromPtr/fromInt helper functions
  • Add tests for std.Io.Group async/wait, concurrent/wait, and cancel

Test plan

  • All existing tests pass (186 tests)
  • New Group tests pass: Io: Group async/wait, Io: Group concurrent/wait, Io: Group cancel

- Add Closure.Start tagged union for regular vs group task functions
- Update AnyTask and AnyBlockingTask to handle group start functions
- Add standalone groupWait and groupCancel functions in group.zig
- Make Group.wait/cancel compatible with std.Io.Group (idempotent, clears token)
- Implement groupAsyncImpl, groupConcurrentImpl, groupWaitImpl, groupCancelImpl
- Add comptime assertions for std.Io.Group binary compatibility
- Add CompactWaitQueue.fromPtr/fromInt helper functions
- Add tests for std.Io.Group async/wait, concurrent/wait, and cancel
@coderabbitai

coderabbitai Bot commented Dec 7, 2025 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The PR refactors task start callbacks from direct function pointers to a discriminated Closure.Start union, enabling both regular and group start semantics. Related changes update blocking task creation, group wait/cancel APIs, group orchestration in stdio, and add wait queue constructors for external initialization.

Changes

Cohort / File(s) Summary
Task and Closure Core
src/core/task.zig, src/core/blocking_task.zig
Introduces Closure.Start union with .regular (fn(context, result)) and .group (fn(group, context)) variants. Replaces function pointer start field with union type. Updates AnyTask.create and AnyBlockingTask.create signatures, and refactors task wrapper initialization to use .{.regular = &Wrapper.start} pattern.
Group API Refactoring
src/core/group.zig
Makes getList() public. Changes wait() to return Cancelable!void instead of void. Introduces public helpers groupWait() and groupCancel() that delegate actual logic. Updates test calls to handle try and catch for cancellation.
Stdio Group Orchestration
src/stdio.zig
Implements groupConcurrentImpl(), groupAsyncImpl(), groupWaitImpl(), and groupCancelImpl() with runtime-based task scheduling. Adds compile-time checks for binary compatibility between std and zio group structures. Replaces placeholder panics with functional group orchestration. Adds tests for Io group async/wait, concurrent/wait, and cancel scenarios.
Wait Queue Utilities
src/utils/wait_queue.zig
Adds public constructors fromPtr(*anyopaque) and fromInt(usize) to CompactWaitQueue for external initialization.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • src/stdio.zig — The group orchestration implementation is the heaviest lift here. groupConcurrentImpl involves runtime state validation, executor selection, AnyTask construction with group variant, awaitable registration, ref count management, and task scheduling. This needs careful verification of the orchestration flow.
  • src/core/group.zig — The API change where wait() now returns Cancelable!void instead of void is a breaking change that affects calling patterns. The delegation to groupWait() and groupCancel() helpers should be checked for correctness.
  • src/core/task.zig + src/core/blocking_task.zig — The Closure.Start union introduction and discriminated dispatch logic are pervasive but relatively mechanical. However, verify that all task creation call sites properly wrap the function pointer in the .regular variant and that group-variant paths are wired correctly.

Possibly related PRs

Poem

Tasks trade their bare pointers for unions of grace,
Groups find their rhythm in a scheduled space,
Closures dance regular, then group-wise they leap,
While wait queues now wake from their constructors deep. 🚀

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title directly matches the PR's core objective: implementing std.Io.Group operations across multiple files and APIs.
Description check ✅ Passed The description clearly outlines all major changes—Closure.Start union, task/blocking task updates, group functions, stdio implementations, helper functions, and tests—all present in the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@lalinsky

lalinsky commented Dec 7, 2025

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Dec 7, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/core/group.zig (1)

68-69: Unused group parameter in groupWait.

The group parameter is passed but immediately discarded with _ = group;. If it's not needed, consider removing it from the signature. If it's reserved for future use, a brief comment would clarify the intent.

-pub fn groupWait(rt: *Runtime, group: *Group, list: *CompactWaitQueue(GroupNode)) Cancelable!void {
-    _ = group;
+pub fn groupWait(rt: *Runtime, _: *Group, list: *CompactWaitQueue(GroupNode)) Cancelable!void {

Or if you plan to use it later, keep it as-is with a comment.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 192773b and 2556650.

📒 Files selected for processing (5)
  • src/core/blocking_task.zig (3 hunks)
  • src/core/group.zig (5 hunks)
  • src/core/task.zig (5 hunks)
  • src/stdio.zig (5 hunks)
  • src/utils/wait_queue.zig (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.zig

📄 CodeRabbit inference engine (CLAUDE.md)

Use zig env to get the path to the Zig standard library when needed

Files:

  • src/core/task.zig
  • src/utils/wait_queue.zig
  • src/stdio.zig
  • src/core/group.zig
  • src/core/blocking_task.zig
🧠 Learnings (9)
📓 Common learnings
Learnt from: CR
Repo: lalinsky/zio PR: 0
File: src/lib/coro/CLAUDE.md:0-0
Timestamp: 2025-11-30T10:31:51.380Z
Learning: Applies to src/lib/coro/**/*.zig : Avoid dependencies on `std.posix` as Zig 0.16 is removing it - create custom wrappers instead
Learnt from: CR
Repo: lalinsky/zio PR: 0
File: src/lib/aio/CLAUDE.md:0-0
Timestamp: 2025-11-30T10:31:40.830Z
Learning: Applies to src/lib/aio/**/*.zig : Don't depend on `std.posix` in Zig code; create custom wrappers instead as Zig 0.16 will remove it
📚 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/core/task.zig
  • src/stdio.zig
  • src/core/blocking_task.zig
📚 Learning: 2025-11-30T10:31:51.380Z
Learnt from: CR
Repo: lalinsky/zio PR: 0
File: src/lib/coro/CLAUDE.md:0-0
Timestamp: 2025-11-30T10:31:51.380Z
Learning: Applies to src/lib/coro/**/*.zig : Avoid dependencies on `std.posix` as Zig 0.16 is removing it - create custom wrappers instead

Applied to files:

  • src/core/task.zig
  • src/stdio.zig
📚 Learning: 2025-11-30T10:31:51.380Z
Learnt from: CR
Repo: lalinsky/zio PR: 0
File: src/lib/coro/CLAUDE.md:0-0
Timestamp: 2025-11-30T10:31:51.380Z
Learning: Applies to src/lib/coro/**/*.zig : Do not assume knowledge of std APIs - verify with current Zig documentation instead

Applied to files:

  • src/core/task.zig
  • src/stdio.zig
📚 Learning: 2025-11-30T10:31:40.830Z
Learnt from: CR
Repo: lalinsky/zio PR: 0
File: src/lib/aio/CLAUDE.md:0-0
Timestamp: 2025-11-30T10:31:40.830Z
Learning: Applies to src/lib/aio/**/*.zig : Don't depend on `std.posix` in Zig code; create custom wrappers instead as Zig 0.16 will remove it

Applied to files:

  • src/stdio.zig
📚 Learning: 2025-11-30T10:31:40.830Z
Learnt from: CR
Repo: lalinsky/zio PR: 0
File: src/lib/aio/CLAUDE.md:0-0
Timestamp: 2025-11-30T10:31:40.830Z
Learning: Applies to src/lib/aio/**/*.zig : Don't assume you know how Zig std APIs work; verify current behavior instead of relying on outdated information

Applied to files:

  • src/stdio.zig
📚 Learning: 2025-11-30T10:31:31.222Z
Learnt from: CR
Repo: lalinsky/zio PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-30T10:31:31.222Z
Learning: Applies to **/*.zig : Use `zig env` to get the path to the Zig standard library when needed

Applied to files:

  • src/stdio.zig
📚 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/core/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/core/group.zig
  • src/core/blocking_task.zig
🔇 Additional comments (14)
src/utils/wait_queue.zig (1)

650-658: LGTM - useful constructors for external state reconstruction.

These helpers enable creating a CompactWaitQueue from raw pointers or integers stored externally (like std.Io.Group.token). The lack of validation is fine here since these are internal primitives where the caller owns the responsibility.

src/core/group.zig (3)

70-88: Clean cancellation handling in groupWait.

The pattern of pushing the current node back before entering shield mode and calling groupCancel ensures no tasks are leaked. The shield prevents recursive cancellation during cleanup. Solid implementation.


91-117: Solid two-phase cancel implementation.

The outer while(true) loop handles the edge case where tasks are added to the group while cancellation is in progress. The two-phase approach (request cancellation first, then wait for completion) is the right pattern. Using waitUntilComplete (uncancelable) ensures the cancel operation always completes.


38-50: Good idempotent design for wait and cancel.

Clearing group.token before delegating ensures these methods are idempotent - calling them multiple times is safe. The token-to-list reconstruction via fromPtr correctly recovers the queue state.

src/core/blocking_task.zig (2)

85-93: Switch on Closure.Start variant handles both paths correctly.

The .regular path maintains the existing behavior. The .group path correctly accesses the group from awaitable.group_node.group. The .? unwrap is safe here because group tasks are only created via groupConcurrentImpl which sets group_node.group before scheduling.


190-194: Correct adaptation to new Closure.Start type.

Wrapping the start function in .{ .regular = ... } maintains the existing behavior for regular blocking tasks while enabling the new group-aware path.

src/stdio.zig (5)

47-74: Thorough binary compatibility checks.

These comptime assertions catch ABI mismatches at compile time rather than causing subtle runtime corruption. Checking size, alignment, field offsets, and field sizes covers all the bases. Good defensive programming.


166-205: groupConcurrentImpl implementation looks solid.

The sequence is correct: create task → register awaitable → set group reference → add to group list → increment ref count → schedule. The @ptrCast on line 184 is necessary because the std.Io callback signature uses *std.Io.Group while zio internally uses *anyopaque.

One observation: after zio_grp.getList().push() on line 198, there's no errdefer to remove from the list. However, since ref_count.incr() is infallible and scheduleTask doesn't return errors, this isn't an issue in practice.


159-164: Sync fallback in groupAsyncImpl ensures reliability.

If concurrent scheduling fails (e.g., runtime shutting down), falling back to synchronous execution ensures the work still gets done. This matches the existing pattern in asyncImpl.


207-219: groupWaitImpl and groupCancelImpl correctly delegate to zio internals.

The catch {} on line 211 silently handles cancellation, which matches the expected behavior - groupWait in std.Io returns void, not an error. The list reconstruction from token works correctly.


1344-1441: Good test coverage for the new Group operations.

The three tests cover async/wait, concurrent/wait, and cancel paths through the std.Io interface. The cancel test verifies that cancellation completes quickly rather than waiting for the full sleep duration.

src/core/task.zig (3)

30-35: Clean discriminated union for task start semantics.

The Start union is a good design choice - it makes the two task modes explicit at the type level rather than overloading a single function signature. The regular and group variants have clearly different signatures matching their respective use cases.


304-312: startFn correctly dispatches based on task type.

The switch handles both variants appropriately. The .? unwrap on group_node.group is safe because the group reference is set by groupConcurrentImpl before the task is scheduled.


415-423: Backward-compatible wrapping in Task.create.

Existing code using Task.create continues to work unchanged since the internal wrapper uses the .regular variant.

- Use state field as counter + flags (bits 62-63 for canceled/failed)
- Use context field as ResetEvent for waiters
- Early signal when task returns error (sets canceled or failed flag)
- ResetEvent now uses CompactWaitQueue to fit in single pointer
- Simplify groupWait to use ResetEvent.wait()
- Add fail_fast_flag (bit 61) to Group state encoding
- Add setFailFast() and isFailFast() methods
- setFailed()/setCanceled() now signal event early only if fail_fast is set
- Default behavior: wait for all tasks regardless of errors
Add Closure.call() method that handles both regular and group cases,
including counter decrement and event signaling for group tasks.
Both AnyTask.startFn and blocking_task.workFunc now use this shared method.
@lalinsky
lalinsky merged commit b6d4424 into stdio Dec 7, 2025
@lalinsky
lalinsky deleted the stdio-group branch December 7, 2025 11:05
lalinsky added a commit that referenced this pull request Dec 7, 2025
* Implement std.Io.Group operations

- Add Closure.Start tagged union for regular vs group task functions
- Update AnyTask and AnyBlockingTask to handle group start functions
- Add standalone groupWait and groupCancel functions in group.zig
- Make Group.wait/cancel compatible with std.Io.Group (idempotent, clears token)
- Implement groupAsyncImpl, groupConcurrentImpl, groupWaitImpl, groupCancelImpl
- Add comptime assertions for std.Io.Group binary compatibility
- Add CompactWaitQueue.fromPtr/fromInt helper functions
- Add tests for std.Io.Group async/wait, concurrent/wait, and cancel

* Improve Group implementation with counter-based waiting

- Use state field as counter + flags (bits 62-63 for canceled/failed)
- Use context field as ResetEvent for waiters
- Early signal when task returns error (sets canceled or failed flag)
- ResetEvent now uses CompactWaitQueue to fit in single pointer
- Simplify groupWait to use ResetEvent.wait()

* Add fail_fast flag for early exit on task error

- Add fail_fast_flag (bit 61) to Group state encoding
- Add setFailFast() and isFailFast() methods
- setFailed()/setCanceled() now signal event early only if fail_fast is set
- Default behavior: wait for all tasks regardless of errors

* Unify Closure.start calling for tasks and blocking tasks

Add Closure.call() method that handles both regular and group cases,
including counter decrement and event signaling for group tasks.
Both AnyTask.startFn and blocking_task.workFunc now use this shared method.
lalinsky added a commit that referenced this pull request Dec 7, 2025
* Implement std.Io.Group operations

- Add Closure.Start tagged union for regular vs group task functions
- Update AnyTask and AnyBlockingTask to handle group start functions
- Add standalone groupWait and groupCancel functions in group.zig
- Make Group.wait/cancel compatible with std.Io.Group (idempotent, clears token)
- Implement groupAsyncImpl, groupConcurrentImpl, groupWaitImpl, groupCancelImpl
- Add comptime assertions for std.Io.Group binary compatibility
- Add CompactWaitQueue.fromPtr/fromInt helper functions
- Add tests for std.Io.Group async/wait, concurrent/wait, and cancel

* Improve Group implementation with counter-based waiting

- Use state field as counter + flags (bits 62-63 for canceled/failed)
- Use context field as ResetEvent for waiters
- Early signal when task returns error (sets canceled or failed flag)
- ResetEvent now uses CompactWaitQueue to fit in single pointer
- Simplify groupWait to use ResetEvent.wait()

* Add fail_fast flag for early exit on task error

- Add fail_fast_flag (bit 61) to Group state encoding
- Add setFailFast() and isFailFast() methods
- setFailed()/setCanceled() now signal event early only if fail_fast is set
- Default behavior: wait for all tasks regardless of errors

* Unify Closure.start calling for tasks and blocking tasks

Add Closure.call() method that handles both regular and group cases,
including counter decrement and event signaling for group tasks.
Both AnyTask.startFn and blocking_task.workFunc now use this shared method.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant