Skip to content

Implement std.Io.select - #158

Merged
lalinsky merged 1 commit into
zig-0.16from
stdio-select
Dec 11, 2025
Merged

lalinsky merged 1 commit into
zig-0.16from
stdio-select

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Summary

  • Add selectAwaitables function in select.zig for runtime select on type-erased *Awaitable slice
  • Implement selectImpl in stdio.zig using the new function
  • Max 64 futures supported (stack-allocated waiters)

Test plan

  • Run ./check.sh - all tests pass
  • New test verifies io.select works with async futures

@coderabbitai

coderabbitai Bot commented Dec 11, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

A new public selectAwaitables function enables selecting among up to 64 type-erased Awaitable pointers, returning the index of the first to complete. The stdio.zig selectImpl now delegates to this function. A test validates async selection behavior.

Changes

Cohort / File(s) Change Summary
Public awaitable selection API
src/select.zig
Added selectAwaitables(rt: *Runtime, awaitables: []const *Awaitable) Cancelable!usize function that waits on type-erased awaitable objects with a 64-awaitable limit, handles cleanup/cancellation for non-winners, and returns the first-to-complete index. Includes fast path for immediate completion.
stdio select implementation
src/stdio.zig
Implemented selectImpl to extract runtime from userdata, cast futures to an Awaitable array, and delegate to select.selectAwaitables. Added "Io: select" test validating async selection between fast and slow tasks with scheduling and cancellation guards.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • src/select.zig: The new selectAwaitables function introduces logic for managing type-erased awaitables, per-wait structures, waiter registration, and cleanup paths. The cancellation and yield-to-executor flow needs careful verification.
  • src/stdio.zig: The selectImpl delegation is straightforward, but the test logic (scheduling between fast/slow tasks with cancellation) should be validated for correctness.

Possibly related PRs

Poem

🔮 Many awaitables line up to race,
Type-erased, waiting in select's embrace,
Winner takes all, the first to complete,
Cancelation tidy—no leaks, oh so neat. ✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Implement std.Io.select' directly matches the main change: implementing the std.Io.select functionality through selectAwaitables and selectImpl.
Description check ✅ Passed The description clearly outlines what was added (selectAwaitables, selectImpl), explains the 64-futures limit, and documents the test plan including verification that io.select works.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch stdio-select

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

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Dec 11, 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 (2)
src/stdio.zig (1)

927-958: Io: select test exercises the new path well; optional: add a case where the slow branch wins

This test does a good job driving the new std.Io.select implementation through:

  • async futures backed by zio’s runtime
  • mixing a plain i32 result (fastTask) and an !i32 (slowTask)
  • asserting that .fast wins and that the union tag matches.

Right now the .slow arm only runs if something is broken. If you ever care about coverage on the slow path, consider a second test that intentionally makes the slow task win (e.g. flip which future is “fast”) so that branch is exercised in a non-failure scenario. Not mandatory, but it would make the test suite more symmetric.

src/select.zig (1)

10-10: selectAwaitables mirrors select() semantics; consider guarding the empty-slice case

The new selectAwaitables implementation lines up with the existing select logic:

  • Uses SelectWaiter and the shared winner atomic the same way.
  • Enforces a 64‑awaitable cap with a panic, which matches the “stack-allocated waiters” design you outlined.
  • Registers each awaitable via asyncWait, supports the fast path when asyncWait returns false, and cleans up pending waits via asyncCancelWait in the defer.
  • Requires an active task and uses the same task state transitions and executor.yield pattern as select / waitInternal.

One edge case worth calling out: if awaitables.len == 0, the registration loop is skipped, you still call executor.yield, and winner remains NO_WINNER, which will trip the assert at the end. That’s probably a programmer error, but you might want an explicit guard for a clearer failure:

 pub fn selectAwaitables(rt: *Runtime, awaitables: []const *Awaitable) Cancelable!usize {
     const max_awaitables = 64;
-    if (awaitables.len > max_awaitables) {
-        @panic("selectAwaitables: too many awaitables (max 64)");
-    }
+    if (awaitables.len == 0) {
+        @panic("selectAwaitables: at least one awaitable is required");
+    }
+    if (awaitables.len > max_awaitables) {
+        @panic("selectAwaitables: too many awaitables (max 64)");
+    }

Not a blocker, but it would fail faster and more explicitly if someone ever misuses the API.

Also applies to: 382-433

📜 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 7d5b525 and c12c3be.

📒 Files selected for processing (2)
  • src/select.zig (2 hunks)
  • src/stdio.zig (2 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/stdio.zig
  • src/select.zig
🧠 Learnings (2)
📓 Common learnings
Learnt from: lalinsky
Repo: lalinsky/zio PR: 70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.575Z
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.575Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.575Z
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/stdio.zig
  • src/select.zig
🔇 Additional comments (1)
src/stdio.zig (1)

226-230: selectImpl wiring looks correct and matches existing casting patterns

Casting []const *std.Io.AnyFuture to []const *Awaitable and delegating to select.selectAwaitables is consistent with how awaitOrCancel already treats AnyFuture (via @ptrCast(@alignCast(any_future))). The implementation is minimal and does exactly what std.Io’s vtable.select needs here. I don’t see any correctness issues.

@lalinsky
lalinsky merged commit 4563421 into zig-0.16 Dec 11, 2025
@lalinsky
lalinsky deleted the stdio-select branch December 11, 2025 16:27
@coderabbitai coderabbitai Bot mentioned this pull request Jan 9, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Apr 16, 2026
1 of 4 tasks
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