Repository navigation
Replace libxev with aio.zig - #136
Conversation
- Add aio.zig as dependency - Replace xev.Loop with aio.Loop in Executor - Replace xev.Async with aio.Async - Update callback signatures for aio - Update waitForIo and timedWaitForIo for aio.Completion - Remove xev-specific runIo function (needs rewrite for aio typed completions) Status: Basic structure updated, but I/O operations need to be migrated to use aio's typed completion model (FileRead, NetConnect, etc.)
|
Warning Rate limit exceeded@lalinsky has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 7 minutes and 32 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 (3)
WalkthroughReplaces the vendored libxev subtree with an aio-based integration: removes vendor/libxev files and CI, updates build wiring to use Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Potential hotspots to inspect closely:
Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
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: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/io/pipe.zig (1)
31-86: Pipe still depends on xev and breaks the build
io/pipe.zigstill constructsxev.Completionand friends, but theconst xev = …import vanished and libxev is gone from the build. As soon as anything pulls this module in, compilation fails. Please finish the port to the aio equivalents (or temporarily keep the xev import) before landing, otherwise Pipe is unusable in the aio world.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (6)
vendor/libxev/flake.lockis excluded by!**/*.lockvendor/libxev/website/package-lock.jsonis excluded by!**/package-lock.jsonvendor/libxev/website/public/favicon.icois excluded by!**/*.icovendor/libxev/website/public/next.svgis excluded by!**/*.svgvendor/libxev/website/public/thirteen.svgis excluded by!**/*.svgvendor/libxev/website/public/vercel.svgis excluded by!**/*.svg
📒 Files selected for processing (68)
.github/workflows/test.yml(1 hunks)build.zig(2 hunks)build.zig.zon(1 hunks)check.sh(0 hunks)examples/tcp_client.zig(1 hunks)src/core/blocking_task.zig(4 hunks)src/core/task.zig(1 hunks)src/core/timeout.zig(3 hunks)src/fs.zig(5 hunks)src/io/base.zig(5 hunks)src/io/file.zig(3 hunks)src/io/net.zig(19 hunks)src/io/pipe.zig(1 hunks)src/io/test/net.zig(2 hunks)src/net.zig(3 hunks)src/runtime.zig(18 hunks)src/signal.zig(10 hunks)src/stack.zig(1 hunks)src/stream.zig(10 hunks)src/zio.zig(1 hunks)vendor/libxev/.envrc(0 hunks)vendor/libxev/.github/dependabot.yml(0 hunks)vendor/libxev/.github/workflows/test.yml(0 hunks)vendor/libxev/.gitignore(0 hunks)vendor/libxev/LICENSE(0 hunks)vendor/libxev/README.md(0 hunks)vendor/libxev/build.zig(0 hunks)vendor/libxev/build.zig.zon(0 hunks)vendor/libxev/docs/xev-c.7.scd(0 hunks)vendor/libxev/docs/xev-faq.7.scd(0 hunks)vendor/libxev/docs/xev-zig.7.scd(0 hunks)vendor/libxev/docs/xev.7.scd(0 hunks)vendor/libxev/docs/xev_completion_state.3.scd(0 hunks)vendor/libxev/docs/xev_completion_zero.3.scd(0 hunks)vendor/libxev/docs/xev_threadpool.3.scd(0 hunks)vendor/libxev/examples/_basic.c(0 hunks)vendor/libxev/examples/_basic.zig(0 hunks)vendor/libxev/examples/async.c(0 hunks)vendor/libxev/examples/million-timers.c(0 hunks)vendor/libxev/examples/threadpool.c(0 hunks)vendor/libxev/flake.nix(0 hunks)vendor/libxev/include/xev.h(0 hunks)vendor/libxev/nix/package.nix(0 hunks)vendor/libxev/shell.nix(0 hunks)vendor/libxev/src/ThreadPool.zig(0 hunks)vendor/libxev/src/api.zig(0 hunks)vendor/libxev/src/backend.zig(0 hunks)vendor/libxev/src/backend/epoll.zig(0 hunks)vendor/libxev/src/backend/io_uring.zig(0 hunks)vendor/libxev/src/backend/iocp.zig(0 hunks)vendor/libxev/src/backend/kqueue.zig(0 hunks)vendor/libxev/src/backend/wasi_poll.zig(0 hunks)vendor/libxev/src/bench/async1.zig(0 hunks)vendor/libxev/src/bench/async2.zig(0 hunks)vendor/libxev/src/bench/async4.zig(0 hunks)vendor/libxev/src/bench/async8.zig(0 hunks)vendor/libxev/src/bench/async_pummel_1.zig(0 hunks)vendor/libxev/src/bench/async_pummel_2.zig(0 hunks)vendor/libxev/src/bench/async_pummel_4.zig(0 hunks)vendor/libxev/src/bench/async_pummel_8.zig(0 hunks)vendor/libxev/src/bench/million-timers.zig(0 hunks)vendor/libxev/src/bench/ping-pongs.zig(0 hunks)vendor/libxev/src/bench/ping-udp1.zig(0 hunks)vendor/libxev/src/bench/udp_pummel_1v1.zig(0 hunks)vendor/libxev/src/c_api.zig(0 hunks)vendor/libxev/src/darwin.zig(0 hunks)vendor/libxev/src/debug.zig(0 hunks)vendor/libxev/src/dynamic.zig(0 hunks)
💤 Files with no reviewable changes (49)
- vendor/libxev/.gitignore
- vendor/libxev/LICENSE
- vendor/libxev/docs/xev-zig.7.scd
- check.sh
- vendor/libxev/src/bench/async_pummel_4.zig
- vendor/libxev/src/bench/async_pummel_8.zig
- vendor/libxev/README.md
- vendor/libxev/shell.nix
- vendor/libxev/flake.nix
- vendor/libxev/src/backend.zig
- vendor/libxev/examples/async.c
- vendor/libxev/.github/dependabot.yml
- vendor/libxev/src/debug.zig
- vendor/libxev/src/bench/async_pummel_1.zig
- vendor/libxev/nix/package.nix
- vendor/libxev/docs/xev_completion_zero.3.scd
- vendor/libxev/.envrc
- vendor/libxev/src/api.zig
- vendor/libxev/examples/threadpool.c
- vendor/libxev/src/bench/async8.zig
- vendor/libxev/src/bench/million-timers.zig
- vendor/libxev/src/bench/async2.zig
- vendor/libxev/examples/million-timers.c
- vendor/libxev/docs/xev.7.scd
- vendor/libxev/build.zig
- vendor/libxev/docs/xev_threadpool.3.scd
- vendor/libxev/src/bench/ping-udp1.zig
- vendor/libxev/src/bench/udp_pummel_1v1.zig
- vendor/libxev/src/bench/ping-pongs.zig
- vendor/libxev/src/bench/async1.zig
- vendor/libxev/src/bench/async4.zig
- vendor/libxev/.github/workflows/test.yml
- vendor/libxev/src/bench/async_pummel_2.zig
- vendor/libxev/docs/xev-c.7.scd
- vendor/libxev/src/backend/epoll.zig
- vendor/libxev/docs/xev_completion_state.3.scd
- vendor/libxev/src/backend/io_uring.zig
- vendor/libxev/build.zig.zon
- vendor/libxev/src/darwin.zig
- vendor/libxev/src/dynamic.zig
- vendor/libxev/docs/xev-faq.7.scd
- vendor/libxev/examples/_basic.c
- vendor/libxev/examples/_basic.zig
- vendor/libxev/src/backend/iocp.zig
- vendor/libxev/src/ThreadPool.zig
- vendor/libxev/src/c_api.zig
- vendor/libxev/src/backend/wasi_poll.zig
- vendor/libxev/include/xev.h
- vendor/libxev/src/backend/kqueue.zig
🧰 Additional context used
🧠 Learnings (5)
📚 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/blocking_task.zigsrc/stack.zigsrc/io/base.zigsrc/core/timeout.zigsrc/runtime.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/blocking_task.zigsrc/runtime.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/signal.zigsrc/io/base.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.zig
📚 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/runtime.zig
| const executor_id = self.next_executor.fetchAdd(1, .monotonic) % self.executors.items.len; | ||
| self.executors.items[executor_id].loop.add(&task.task.work.c); | ||
|
|
||
| return JoinHandle(Result){ |
There was a problem hiding this comment.
Fix spawnBlocking before the event loops go live.
If someone calls spawnBlocking before any executor has run (previously supported, same as spawn), executor.loop is still uninitialized because initLoop() happens inside Executor.run(). Hitting .loop.add(&task.task.work.c) at this point dereferences garbage and blows up immediately—try:
var rt = try Runtime.init(allocator, .{});
defer rt.deinit();
_ = try rt.spawnBlocking(someWork, .{});Please delay registering the work until the target executor’s loop has actually been initialized (e.g. stash pending work until loop_initialized flips true, or route it through a running executor).
🤖 Prompt for AI Agents
In src/runtime.zig around lines 983 to 986, spawnBlocking currently calls
executor.loop.add(...) before Executor.run() has called initLoop(), which can
dereference uninitialized loop state; change spawnBlocking to check the target
executor's loop_initialized flag and, if it's not true, append the task to a
per-executor pending queue (safely under the existing executor lock or an
atomic/lock-free structure) instead of calling loop.add; when initLoop() runs in
Executor.run(), flip loop_initialized and drain the pending queue into loop.add
so pending tasks get registered once the loop is initialized. Ensure
memory/ownership and synchronization around the pending queue are correct and
that any early-return error paths still clean up tasks.
| // TODO: Migrate Pipe to aio | ||
| // pub const Pipe = @import("io/pipe.zig").Pipe; |
There was a problem hiding this comment.
Pipe re-export disappears without replacement
Commenting out pub const Pipe yanks the pipe API from the public surface. Any consumer doing zio.Pipe now fails to compile, and we don’t provide an aio-backed substitute yet. Either finish the aio migration for io/pipe.zig or leave the existing export in place until its replacement lands; otherwise, this PR ships a regression in functionality.
🤖 Prompt for AI Agents
In src/zio.zig around lines 26-27, the PR commented out the public re-export of
Pipe which removes the pipe API from the public surface and breaks consumers
using zio.Pipe; restore backward compatibility by either re-enabling the
original export (re-add the line exporting @import("io/pipe.zig").Pipe) until a
complete aio-backed replacement is implemented, or implement and export a
drop-in aio-backed substitute under the same public name (pub const Pipe) so
existing callers continue to compile; ensure the export is public and its
type/signature matches the previous API.
In readVec(), changed error handling to propagate error.Canceled
upward instead of converting it to error.ReadFailed. This preserves
cancellation semantics for the caller.
In close(), changed catch {} to catch unreachable for waitForIo()
since the operation is shielded from cancellation.
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
src/io/file.zig (1)
149-155: Don't mask OS-level cancellation as ReadFailed.Line 150 correctly propagates user-requested cancellation. However,
op.getResult()can return OS-levelerror.Canceledfrom io_uring—an unexpected system event that shouldn't be coerced intoerror.ReadFailed. Callers need to distinguish between genuine I/O failures and unexpected OS cancellations.Based on learnings
Handle OS-level cancellation explicitly:
executor.loop.add(&op.c); try waitForIo(rt, &op.c); - const bytes_read = op.getResult() catch return error.ReadFailed; + const bytes_read = op.getResult() catch |err| switch (err) { + error.Canceled => return error.Unexpected, + else => return error.ReadFailed, + }; // EOF is indicated by 0 bytes read if (bytes_read == 0) return error.EndOfStream;
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/io/file.zig(3 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 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/io/file.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 (windows-latest, native)
- GitHub Check: test (ubuntu-latest, riscv64-linux, qemu-riscv64-static)
🔇 Additional comments (3)
src/io/file.zig (3)
1-34: Migration setup looks solid.The import changes and File struct setup correctly establish the aio-based I/O foundation. Position tracking is properly initialized for sequential operations.
180-196: Verifycatch unreachablesafety during shield.The shield prevents user cancellation, but can
waitForIoproduce other errors (e.g., system failures) even within a shield? If there's any edge case where errors can occur,catch unreachablewill panic.Consider changing to:
executor.loop.add(&op.c); - waitForIo(rt, &op.c) catch unreachable; + waitForIo(rt, &op.c) catch |err| { + std.log.err("close waitForIo failed unexpectedly: {}", .{err}); + return; + };Or confirm that shield semantics truly guarantee no errors from
waitForIo.
211-359: Test coverage looks good.The tests exercise basic operations, positional I/O, close semantics, and streaming interfaces. Proper cleanup with defer patterns.
| executor.loop.add(&op.c); | ||
| try waitForIo(rt, &op.c); | ||
|
|
||
| const bytes_written = runIo(rt, &completion, "pwrite") catch return error.WriteFailed; | ||
| const bytes_written = op.getResult() catch return error.WriteFailed; |
There was a problem hiding this comment.
Don't mask OS-level cancellation as WriteFailed.
Same issue as readVec: OS-level error.Canceled from getResult() is being coerced into error.WriteFailed. Handle it explicitly.
Based on learnings
executor.loop.add(&op.c);
try waitForIo(rt, &op.c);
- const bytes_written = op.getResult() catch return error.WriteFailed;
+ const bytes_written = op.getResult() catch |err| switch (err) {
+ error.Canceled => return error.Unexpected,
+ else => return error.WriteFailed,
+ };
self.position += bytes_written;
return bytes_written;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| executor.loop.add(&op.c); | |
| try waitForIo(rt, &op.c); | |
| const bytes_written = runIo(rt, &completion, "pwrite") catch return error.WriteFailed; | |
| const bytes_written = op.getResult() catch return error.WriteFailed; | |
| executor.loop.add(&op.c); | |
| try waitForIo(rt, &op.c); | |
| const bytes_written = op.getResult() catch |err| switch (err) { | |
| error.Canceled => return error.Unexpected, | |
| else => return error.WriteFailed, | |
| }; |
🤖 Prompt for AI Agents
In src/io/file.zig around lines 172 to 175, the call to op.getResult() currently
catches any error and returns error.WriteFailed, which incorrectly masks an
OS-level error.Canceled; change the error handling to explicitly check for
error.Canceled and propagate that error (return error.Canceled) while only
mapping other non-canceled failures to error.WriteFailed, e.g., by using a
switch or if-defer that distinguishes error.Canceled from other errors and
returns the appropriate error code.
Removed verbose debug logging statements from File.write() that were flooding production I/O output. Kept error logging for actual failures.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
src/runtime.zig (1)
981-984: spawnBlocking still pokes an uninitialized loop
Executor.initleavesloopundefined untilrun()callsinitLoop()and flipsloop_initializedtrue. If someone doesRuntime.init()followed byspawnBlocking()(which has been supported), this path hitsexecutor.loop.add(&task.task.work.c)before any executor thread sets up its loop. That dereferences garbage and can crash immediately. You already addedloop_initializedto guard wake-ups—put the blocking work through a pending queue (or otherwise defer submission) until the target executor has finishedinitLoop()and marked the flag. Then drain that queue right after settingloop_initializedinExecutor.run().src/io/file.zig (1)
164-165: Don’t collapse OS cancellations into WriteFailedSame story on the write side: catching everything and returning
error.WriteFailedmasks the OS-levelerror.Canceledthat should bubble aserror.Unexpectedper the prior guidance. That regression breaks downstream error handling.Apply this patch:
- const bytes_written = op.getResult() catch return error.WriteFailed; + const bytes_written = op.getResult() catch |err| switch (err) { + error.Canceled => return error.Unexpected, + else => return error.WriteFailed, + };Based on learnings
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (8)
.github/workflows/test.yml(1 hunks)build.zig(2 hunks)build.zig.zon(1 hunks)src/core/task.zig(1 hunks)src/core/timeout.zig(3 hunks)src/io/file.zig(3 hunks)src/runtime.zig(18 hunks)src/zio.zig(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- src/core/task.zig
- src/zio.zig
- .github/workflows/test.yml
🧰 Additional context used
🧠 Learnings (5)
📚 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/io/file.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/io/file.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.zig
📚 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/runtime.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.zigsrc/core/timeout.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). (3)
- GitHub Check: test (ubuntu-latest, aarch64-linux, qemu-aarch64-static)
- GitHub Check: test (ubuntu-latest, riscv64-linux, qemu-riscv64-static)
- GitHub Check: test (windows-latest, native)
| const bytes_read = op.getResult() catch return error.ReadFailed; | ||
|
|
||
| // EOF is indicated by 0 bytes read | ||
| if (bytes_read == 0) return error.EndOfStream; | ||
|
|
There was a problem hiding this comment.
Preserve cancellation instead of downgrading to ReadFailed
If the IO op returns error.Canceled we must propagate it so callers can tell user cancellation/timeouts apart from real read failures. Right now the catch turns every failure into error.ReadFailed, undoing the earlier fix. Please restore the special-case handling for error.Canceled.
Apply this patch:
- const bytes_read = op.getResult() catch return error.ReadFailed;
+ const bytes_read = op.getResult() catch |err| switch (err) {
+ error.Canceled => return err,
+ else => return error.ReadFailed,
+ };Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In src/io/file.zig around lines 141 to 145, the current catch maps all
op.getResult() failures to error.ReadFailed which hides error.Canceled; change
the error handling to preserve cancellation by checking the caught error and
returning it if it equals error.Canceled, otherwise return error.ReadFailed so
callers can distinguish user cancellations/timeouts from real read failures;
keep the EOF handling (bytes_read == 0 => error.EndOfStream) unchanged.
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 (2)
src/runtime.zig (2)
885-903: Remove*from for-loop bindings overexecutors.itemsto fix type mismatchYour code declares
executors: std.ArrayList(*Executor), soexecutors.itemsis[]*Executor. When you writefor (executors.items) |*executor|, Zig binds each element as**Executorinstead of*Executor, causing the field-access errors.Fix all occurrences by removing the
*:- for (self.executors.items) |*exec| { - exec.deinit(); - } + for (self.executors.items) |exec| { + exec.deinit(); + }- for (self.executors.items) |*executor| { - executor.shutdown_async.notify(); - } + for (self.executors.items) |executor| { + executor.shutdown_async.notify(); + }Also fix these locations (same pattern):
- Line 989:
for (self.executors.items[1..], 1..) |*executor, i|→|executor, i|- Line 994:
for (self.executors.items[1..]) |*executor|→|executor|- Line 1002:
for (self.executors.items[1..]) |*executor|→|executor|- Line 1137:
for (self.executors.items) |*executor|→|executor|
63-72: All three issues confirmed in the code. Here's the rewritten comment:Fix Runtime struct initialization: StackPool, atomics, and ThreadPool lifetime
Right now
Runtime.init/deinitdon't line up with theRuntime/StackPool/ThreadPooltypes. Looking at the actual code:
StackPool initialization (line 868)
stack_poolis assigned.{}in the struct literal but never initialized via a properinit()call.- Later code calls
self.stack_pool.deinit(), so the pool must be initialized first.Change the struct literal initialization and add the init call:
self.* = .{ .allocator = allocator, .options = options, .thread_pool = undefined, .main_executor = undefined, .stack_pool = undefined,
.last_used_executor_index = std.atomic.Value(usize).init(0),.shutting_down = std.atomic.Value(bool).init(false),};
try self.thread_pool.init(allocator, options.thread_pool);
errdefer self.thread_pool.deinit();try self.stack_pool.init(options.stack_pool);
errdefer self.stack_pool.deinit();
2. **`last_used_executor_index` and `shutting_down` never initialized** - Both atomic fields lack defaults in the struct definition and aren't set in the struct literal. - They'll contain garbage at runtime and break round-robin scheduling and shutdown logic. The struct literal change above initializes both atomics to known values. 3. **ThreadPool lifetime: don't `destroy` a by‑value field** - `thread_pool: aio.ThreadPool` is an embedded field in `Runtime`, not a heap allocation. - `deinit` currently does `allocator.destroy(self.thread_pool);` which is wrong—`destroy` is for pointers. Remove the incorrect destroy call (lines 905-906): ```diff self.thread_pool.deinit(); - allocator.destroy(self.thread_pool); self.stack_pool.deinit();These fixes wire up the ownership model and clear the initialization errors.
♻️ Duplicate comments (1)
src/runtime.zig (1)
946-973: spawnBlocking still touchesexecutor.loopbeforerun()initializes itThis is the same problem flagged in the earlier review comment you quoted:
spawnBlockingassumes the target executor’s loop is live:const executor_id = self.last_used_executor_index.fetchAdd(1, .monotonic) % self.executors.items.len; self.executors.items[executor_id].loop.add(&task.task.work.c);If a user does:
var rt = try Runtime.init(allocator, .{}); defer rt.deinit(); _ = try rt.spawnBlocking(blockingWork, .{});before any executor has called
run()/initLoop(),executor.loopis still undefined, so.loop.add(...)is UB immediately. The newloop_initialized: std.atomic.Value(bool)flag is there but not used here.You need to delay registration of the
aio.Workuntil the target executor’s loop has actually been initialized, e.g.:
- If
loop_initializedisfalse, push the blocking task onto a per‑executor pending queue instead of callingloop.adddirectly.- When
Executor.runfinishesinitLoop()and flipsloop_initializedtotrue, drain that pending queue andloop.addall pending works.- For calls that happen while the loop is already running, you can keep the current fast path and call
loop.adddirectly.That keeps
spawnBlockingsafe to call beforerun()and matches the previous behavior. Given it’s a crash‑on‑first‑use bug, I’d fix this before merging, even if the TODO list still has other blocking‑task items.Also applies to: 1345-1367
🧹 Nitpick comments (2)
src/runtime.zig (2)
295-323: Executor.loop / loop_initialized wiring mostly sane, but unusedstack_poolfieldThe transition to
aio.Loop,loop_initialized, andshutdown_asyncinsideExecutorlooks coherent:
initLoopsets up the loop andshutdown_async, thenruntogglesloop_initializedand uses it to guardloop.wake()inscheduleTaskRemote.run’sdeferblock clearsloop_initializedbeforedeinitLoop, which is what you want.One minor smell:
Executorhas its ownstack_pool: StackPoolbut all stack operations go throughself.runtime.stack_pool. If that’s intentional, consider droppingstack_poolfromExecutorto avoid confusion; if it’s not, wire it in or pointAnyTask.createat the executor’s pool instead. This is cosmetic, so it can wait.Also applies to: 569-581, 730-739
1143-1147: now() using loop time is fine but only valid once the main loop exists
Runtime.now()now returns:pub fn now(self: *Runtime) i64 { return @intCast(self.executors.items[0].loop.now()); }and the
now()test calls it from within a coroutine while the runtime is running, which is fine.Just be aware that this is undefined before executor 0 has called
run()/initLoop(). If you expect users to callrt.now()afterRuntime.init()but beforerun(), you may want a defensive check or a fallback (e.g.std.time.milliTimestamp()) for that case; otherwise, documenting “only valid while the runtime is running” is enough.Also applies to: 1419-1434
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
.github/workflows/test.yml(1 hunks)build.zig.zon(1 hunks)src/core/task.zig(1 hunks)src/runtime.zig(17 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- .github/workflows/test.yml
- build.zig.zon
🧰 Additional context used
🧠 Learnings (4)
📚 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.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.zig
📚 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/runtime.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.zig
🪛 GitHub Actions: CI
src/runtime.zig
[error] 868-868: missing struct field: config in StackPool initialization. The runtime stack pool is initialized with fields that do not match the StackPool struct declaration (config, mutex, head, tail, pool_size).
[error] 966-966: no field named 'next_executor' in struct 'runtime.Runtime'.
[error] 1161-1161: type '**runtime.Executor' does not support field access. (attempted to access executor.shutdown_async via field access)
🔇 Additional comments (4)
src/core/task.zig (1)
4-6: Import cleanup in task.zig is fineOnly the import block changed here; it still pulls in
stdand the rest of the file compiles independently of xev/aio. Nothing to fix.src/runtime.zig (3)
7-12: aio import andassertalias look goodUsing
const assert = std.debug.assert;and importingaioat top-level matches the rest of the file’s usage. No issues here.
1185-1193: Tests: thread_pool options and always‑present pool behavior make senseThe updated tests that pass
.thread_pool = .{}intoRuntime.initand drop the “thread_pool may be null” checks match the new invariant that anaio.ThreadPoolis always created. Once the init/deinit issues above are fixed, these tests should be a good smoke check for both the pool andspawnBlocking.Also applies to: 1345-1352
386-413: The review comment's core claim is wrong—next_executorexists and is actively used.The grep results show
next_executoris being called successfully at lines 927, 931, and 966 with.fetchAdd(). If the field didn't exist, this code wouldn't compile. Meanwhile,last_used_executor_indexalso exists at line 848.Both fields coexist in the struct. The review presents this as a "non-existent field" error, but you're actually looking at a working implementation that has both the old field name and a newly added one. If the intent is to refactor toward the new name, that's a separate discussion—but don't treat this as a broken compilation error.
Likely an incorrect or invalid review comment.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/runtime.zig (1)
944-945: CRITICAL: spawnBlocking dereferences uninitialized loop.The past review comment is still valid. Calling
spawnBlockingbefore any executor has run hitsexecutor.loop.add()whileloopis still undefined (set at line 344 inExecutor.init).initLoop()doesn't run untilExecutor.run()starts (line 569), so this will crash:var rt = try Runtime.init(allocator, .{}); defer rt.deinit(); _ = try rt.spawnBlocking(someWork, .{}); // CRASH
scheduleTaskRemotehas the guard (line 731 checksloop_initialized), butspawnBlockingdoesn't. Either check the flag and queue pending work, or initialize the loop earlier.
🧹 Nitpick comments (1)
src/runtime.zig (1)
1120-1122: Consider documented bounds or saturating cast fornow().
@intCastwill panic ifloop.now()exceedsi64range (~292 years of uptime). Either document the assumption that uptime will never exceed this, or use@min(loop.now(), std.math.maxInt(i64))for a saturating cast to avoid the panic in extreme edge cases.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/runtime.zig(17 hunks)
🧰 Additional context used
🧠 Learnings (4)
📚 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.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.zig
📚 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/runtime.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.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). (3)
- GitHub Check: test (windows-latest, native)
- GitHub Check: test (ubuntu-latest, riscv64-linux, qemu-riscv64-static)
- GitHub Check: test (ubuntu-latest, aarch64-linux, qemu-aarch64-static)
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
src/runtime.zig (2)
363-363: Clarify the purpose of two threadlocal executor references.There are two threadlocal variables tracking the current executor:
Executor.current(this line, set at lines 397-398, used at line 973)Runtime.current_executor(line 869, used everywhere else in the codebase)Having both is confusing. Consider documenting why both are needed, or consolidating to a single threadlocal if one is redundant.
972-984: Document the two execution modes inRuntime.run().The function has two distinct behaviors:
- If
Executor.currentexists (main thread afterRuntime.init()), run that executor- Otherwise, create a temporary executor, run it, and clean it up
This flexibility is useful for custom threading models, but the behavior isn't obvious from the code. Add a doc comment explaining when each path is taken and why.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/runtime.zig(14 hunks)
🧰 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-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.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.zig
📚 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/runtime.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.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 (windows-latest, native)
- GitHub Check: test (ubuntu-latest, aarch64-linux, qemu-aarch64-static)
🔇 Additional comments (4)
src/runtime.zig (4)
293-317: Good: Proper synchronization for executor registration.The new register/unregister functions correctly use
executors_lockto synchronize access to the executors list, with debug assertions to catch double-registration bugs.
955-957: The previous review concern about earlyspawnBlockingcalls appears resolved.A previous review flagged that calling
spawnBlockingbeforerun()would crash becauseinitLoop()happened insiderun().In the current code,
loop.init()is called inExecutor.init()(line 382), andRuntime.init()callsmain_executor.init()(line 891), so the loop is fully initialized beforeRuntime.init()returns. Additionally,shutdown_asyncis added to the loop during init (line 392), proving thatloop.add()is safe on an initialized-but-not-running loop.Therefore, calling
spawnBlocking()afterRuntime.init()but beforeRuntime.run()should now be safe.Can you confirm this resolves the previous concern? If there are still initialization-order issues with aio that differ from xev, please let me know.
871-895: Initialization sequence looks correct.The thread pool is now always present (
aio.ThreadPoolinstead of?*xev.ThreadPool), and the initialization order properly handles error cases:
- Allocate Runtime
- Initialize thread pool (with errdefer cleanup)
- Pre-allocate executor capacity
- Initialize main executor (which self-registers)
Each step has proper errdefer cleanup.
1154-1166: Tests updated correctly for always-present thread pool.The test correctly reflects the API change where
thread_poolis now always created (non-optional). The comment at line 1162 documents this change clearly.
Extract file operations into Dir type and move platform-specific logic to io/dir.zig. Tests now use Dir.cwd() for file operations. Changes: - Add io/dir.zig with Dir type containing openFile, createFile, rename, and deleteFile methods using aio operations - Simplify fs.zig to expose Dir.cwd as a public API - Update all file.zig tests to use dir.createFile/openFile/deleteFile - Fix Dir methods to take self: Dir instead of self: *Dir
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
src/io/file.zig (1)
127-167: Vectored read/write are still masking getResult() errors (incl. OS-level cancellations)
readVecandwriteVeccurrently collapse allop.getResult()failures intoerror.ReadFailed/error.WriteFailed:const bytes_read = op.getResult() catch return error.ReadFailed; ... const bytes_written = op.getResult() catch return error.WriteFailed;This loses the distinction between OS-level
error.Canceledand other I/O failures, which we’ve already discussed elsewhere in this file.waitForIois correctly propagating user cancellations via theCancelablepart of the error set, but OS-originatederror.CanceledfromgetResult()now looks like a generic read/write failure instead of something unexpected.Given the previous guidance and learnings about treating OS-level
error.Canceledspecially, it would be better to preserve that information and only coerce the rest:- const bytes_read = op.getResult() catch return error.ReadFailed; + const bytes_read = op.getResult() catch |err| switch (err) { + error.Canceled => return error.Unexpected, // OS-level cancel + else => return error.ReadFailed, + }; ... - const bytes_written = op.getResult() catch return error.WriteFailed; + const bytes_written = op.getResult() catch |err| switch (err) { + error.Canceled => return error.Unexpected, // OS-level cancel + else => return error.WriteFailed, + };(Assuming
std.Io.Reader.Error/std.Io.Writer.Errorincludeerror.Unexpected; tweak the mapping if your chosen error set differs.)Also, you’re hard-coding
storage: [16]aio.system.iovec(_const)while accepting an arbitraryslicesslice. Ifslices.lencan exceed 16, it’s worth double-checking aio’s expectations and either asserting or documenting that limit.
🧹 Nitpick comments (1)
src/io/dir.zig (1)
16-72: Consider a small helper for repeated aio op setup
openFile,createFile,rename, anddeleteFileall repeat the same pattern: fetch current task/executor, setuserdata/callback, enqueue, thenwaitForIo. It’s easy to keep them in sync now, but any change to the plumbing (e.g. different callback, shielding, or metrics) will need 4 edits.A tiny helper like
fn runFsOp(rt: *Runtime, task: *Task, executor: *Executor, c: *aio.Completion) !void { ... }(or similar) would trim duplication and keep behavior aligned across all Dir methods.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
src/fs.zig(2 hunks)src/io/dir.zig(1 hunks)src/io/file.zig(12 hunks)
🧰 Additional context used
🧠 Learnings (4)
📓 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/fs.zigsrc/io/file.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/fs.zigsrc/io/file.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/io/file.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). (3)
- GitHub Check: test (ubuntu-latest, riscv64-linux, qemu-riscv64-static)
- GitHub Check: test (windows-latest, native)
- GitHub Check: test (ubuntu-latest, aarch64-linux, qemu-aarch64-static)
🔇 Additional comments (4)
src/fs.zig (1)
7-12: Dir-based fs surface and test wiring look solidRe-exporting
Dir.cwdand driving file ops throughdir.createFile/openFile/deleteFileinside aRuntime.runUntilCompletetask is consistent with the new aio-based Dir/File APIs. Files are closed before deletion and the runtime is properly deinitialized, so this is a clean integration point for the new backend.Also applies to: 20-39
src/io/dir.zig (1)
11-14: cwd() wrapper is reasonable for nowGrabbing
std.fs.cwd()and exposing just the underlyingfdinto your own Dir type is a straightforward way to get a directory handle into the aio layer. The TODO about avoidingstd.fslater is enough; nothing here blocks the migration.src/io/file.zig (2)
169-185: Close path matches the async model and shields against cancellation
closerunsFileClosethrough the same aio path (task/executor, loop.add, waitForIo) and wraps the wait inbeginShield/endShield, then discards both wait andgetResulterrors. That lines up with the “ignore close errors” behavior from Zig’s std lib while still going through the runtime’s cancellation model.No changes needed here.
200-353: Tests now exercise the aio + Dir-based file API end-to-endAll four tests (
basic read and write,positional read and write,close operation, andreader and writer interface) now:
- Acquire a
Dirviafs.cwd().- Use
dir.createFile/dir.openFile/dir.deleteFileinstead of the old global helpers.- Run inside
Runtime.runUntilCompletetasks and close files before deleting them.This gives you good coverage of the new async paths, including positional IO and the streaming interfaces. Looks good.
There was a problem hiding this comment.
Actionable comments posted: 2
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
benchmarks/echo_server.zig(0 hunks)benchmarks/ping_pong.zig(0 hunks)src/runtime.zig(14 hunks)
💤 Files with no reviewable changes (2)
- benchmarks/ping_pong.zig
- benchmarks/echo_server.zig
🧰 Additional context used
🧠 Learnings (8)
📓 Common learnings
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.
📚 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.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.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/runtime.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.zig
📚 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/runtime.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.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.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). (3)
- GitHub Check: test (windows-latest, native)
- GitHub Check: test (ubuntu-latest, riscv64-linux, qemu-riscv64-static)
- GitHub Check: test (ubuntu-latest, aarch64-linux, qemu-aarch64-static)
🔇 Additional comments (1)
src/runtime.zig (1)
943-955: CRITICAL: Data race betweenRuntime.run()andRuntime.spawn().
Runtime.run()can now create executors on demand (lines 949-954), which callsexecutor.init(), which callsregisterExecutor(), which modifies theexecutorsArrayList under the lock. Meanwhile,Runtime.spawn()at lines 901-902 readsexecutors.items.lenandexecutors.items[executor_no]WITHOUT holdingexecutors_lock. This is a data race on the ArrayList's internal state.The PR objectives mention "start additional executors on demand"—this has already been implemented here, but the unsynchronized reads flagged in the previous review (lines 901-902, 956-957, etc.) are now actively racy, not just future concerns.
Pick one fix strategy:
- Acquire lock for all reads (safe but may hurt spawn throughput):
pub fn spawn(self: *Runtime, func: anytype, args: meta.ArgsType(func), options: SpawnOptions) !JoinHandle(meta.ReturnType(func)) { if (self.tasks.isClosed()) { return error.RuntimeShutdown; } + self.executors_lock.lock(); + defer self.executors_lock.unlock(); const executor_no = self.next_executor.fetchAdd(1, .monotonic) % self.executors.items.len; const executor = self.executors.items[executor_no]; - + return executor.spawn(func, args, options); }
Use atomic pointer for single-executor fast path, then fall back to synchronized list for multi-executor.
Document that executor registration must complete before spawn (not viable given current
run()API).Likely an incorrect or invalid review comment.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
src/runtime.zig (1)
370-399: CRITICAL:Executor.currentset after fallibleregisterExecutor, causing assertion failure on error path.Same issue from the previous review. At line 398,
Executor.current = selfis set AFTER the fallibleregisterExecutorcall at line 394. IfregisterExecutorfails, the error path callsdeinit()(via errdefer inRuntime.initat line 872), which assertsExecutor.current == selfat line 402—but the threadlocal was never set, so the assert crashes.Move the threadlocal assignment before
registerExecutor:self.shutdown_async.c.callback = shutdownCallback; self.loop.add(&self.shutdown_async.c); +std.debug.assert(Executor.current == null); +Executor.current = self; +errdefer Executor.current = null; + try registerExecutor(self.runtime, self); errdefer unregisterExecutor(self.runtime, self); - -std.debug.assert(Executor.current == null); -Executor.current = self;
🧹 Nitpick comments (1)
src/runtime.zig (1)
360-360: Unused field:availableis declared but never accessed.The
availablefield is initialized totruebut is never read or modified anywhere in this file. Is this intended for future use (per the TODO items in the PR description about executor lifecycle), or is it leftover from development?If it's for future use, add a comment explaining its purpose. Otherwise, remove it to avoid confusion.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/runtime.zig(13 hunks)
🧰 Additional context used
🧠 Learnings (7)
📚 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.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.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/runtime.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.zig
📚 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/runtime.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.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.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). (3)
- GitHub Check: test (ubuntu-latest, riscv64-linux, qemu-riscv64-static)
- GitHub Check: test (windows-latest, native)
- GitHub Check: test (ubuntu-latest, aarch64-linux, qemu-aarch64-static)
🔇 Additional comments (6)
src/runtime.zig (6)
286-319: LGTM: Executor lifecycle helpers are well-structured.The register/unregister/getNext functions properly synchronize access to the executors list with the lock. The Debug-mode duplicate check in
registerExecutoris a nice safety net, and round-robin scheduling ingetNextExecutoris straightforward.
946-948: Previous review concern resolved: Loop is now initialized inExecutor.init, not inrun().The previous review flagged that
spawnBlockingmight callexecutor.loop.add()before the loop is initialized. However, looking at the current code,Executor.init(lines 382-387) now initializes the loop duringRuntime.init, so by the time user code callsspawnBlocking, the loop is ready.
1088-1094: LGTM:now()correctly delegates to per-executor loop time.The logic properly checks for a local executor first, then falls back to the main executor. Since loops are initialized in
Executor.init,loop.now()calls are safe.
1129-1272: LGTM: Tests updated for always-present thread pool and aio-based runtime.The test suite covers basic runtime operations (spawn, spawnBlocking, cancel, sleep, time) and correctly reflects that
thread_poolis now always initialized. The comment at line 1137 acknowledges this change.
852-915: LGTM:Runtime.initanddeinitproperly manage lifecycle.The init sequence has correct errdefer chains for cleanup on failure. The deinit pattern (lines 888-899) correctly releases the lock before calling
executor.deinit(), avoiding holding the lock during potentially blocking operations. The executor removal is handled viaunregisterExecutorinsideExecutor.deinit.
956-968: LGTM:Runtime.runsupports temporary executor pattern for dynamic lifecycle.The logic at lines 962-967 creates a temporary executor (not the main_executor) when called from outside an executor thread. This executor is registered during init, runs the event loop, then unregistered during deinit. This pattern aligns with the PR objective about starting executors on demand with full lifecycle.
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
build.zig.zon(1 hunks)src/runtime.zig(13 hunks)
🧰 Additional context used
🧠 Learnings (7)
📚 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.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.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/runtime.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.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.zig
📚 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/runtime.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.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). (3)
- GitHub Check: test (ubuntu-latest, riscv64-linux, qemu-riscv64-static)
- GitHub Check: test (windows-latest, native)
- GitHub Check: test (ubuntu-latest, aarch64-linux, qemu-aarch64-static)
🔇 Additional comments (15)
build.zig.zon (1)
13-16: Dependency migration looks clean.The switch from libxev to aio.zig is syntactically correct, with proper URL and hash format. The version (0.4.0) matches the project version, and the commit hash provides reproducible builds.
src/runtime.zig (14)
8-9: Import migration to aio complete.Clean switch from xev to aio. The new import is used consistently throughout the file.
63-63: Thread pool now always present.Changing from optional to always-present thread pool configuration is consistent with the aio model. The test at line 1134 confirms this is intentional ("ThreadPool is always created (no need to check)").
286-319: Executor registration functions are thread-safe.The three new functions properly synchronize access to the executor list with
executors_lock. The round-robin selection ingetNextExecutorcorrectly handles index wrap-around through modulo arithmetic.
369-398: Executor initialization follows proper error handling pattern.The init sequence correctly:
- Sets up stack growth with cleanup via errdefer
- Initializes the aio loop with cleanup via errdefer
- Registers shutdown_async with the loop (safe to call before run())
- Registers the executor with the runtime
- Sets the threadlocal current executor
Each fallible operation has a matching errdefer for cleanup. The loop is ready to accept work immediately after init() completes, so spawnBlocking can be called before run() starts.
400-409: Cleanup sequence is correct.The deinit properly reverses the init sequence: clears threadlocal, unregisters executor, deinits loop, and cleans up stack growth. The assertion that
Executor.current == selfis valid because each executor is bound to its thread and deinit() is only called on fully initialized executors.
652-655: Event loop run mode selection looks good.The logic correctly chooses between non-blocking polling (when work is available or spinning) and blocking mode (when idle). The spin count threshold of 16 provides a reasonable balance between responsiveness and CPU usage.
740-741: Loop wake() is safe without initialization check.Unlike the old xev code, aio.Loop is fully initialized in
Executor.init()(line 381), soloop.wake()can be called anytime after init without needing a separateloop_initializedflag.
833-847: Runtime structure properly supports multi-executor model.The new fields enable the runtime to manage multiple executors with round-robin scheduling. The executor list is protected by
executors_lock, and the main_executor is stored inline for efficiency.
849-872: Runtime initialization correctly heap-allocates and sequences setup.Heap allocation is appropriate here since executors need stable pointers back to the runtime. The initialization sequence properly:
- Creates the runtime structure
- Initializes the thread pool
- Reserves capacity for executors
- Initializes the main executor (which registers itself)
Error handling via errdefer ensures proper cleanup on failure.
885-896: Executor cleanup pattern avoids deadlock.The loop correctly releases
executors_lockbefore callingexecutor.deinit()because deinit internally callsunregisterExecutor, which needs to acquire the same lock. Always fetching index 0 works becauseunregisterExecutorremoves the executor from the list.
943-945: spawnBlocking safely adds work before executor runs.With aio, the loop is fully initialized in
Executor.init()(line 381), making it safe to callloop.add()immediately. This is demonstrated by the shutdown_async registration at line 391, which also callsloop.add()beforerun()is ever called.
959-964: Local executor pattern handles thread-local execution correctly.Creating a new executor for threads without one is appropriate. The executor properly registers itself during init and unregisters during deinit, so the lifecycle is managed correctly.
1085-1091: Time source correctly uses executor loop's cached time.Using the event loop's cached monotonic time avoids system calls. The fallback to
main_executorwhen not on an executor thread ensures time is always available.
1126-1268: Test coverage validates core runtime functionality.The tests cover key scenarios: thread pool lifecycle, blocking tasks, type conversions, time measurement, and cancellation. They provide good smoke testing for the aio migration.
|
|
||
| // Coordination for thread startup | ||
| ready: std.Thread.ResetEvent = .{}, | ||
| available: bool = true, |
There was a problem hiding this comment.
🧩 Analysis chain
Unused field declaration.
The available field is initialized to true but doesn't appear to be read or modified anywhere in this file. If it's truly unused, consider removing it. If it's meant for future use, add a TODO comment explaining its purpose.
Run this script to verify the field is unused:
🏁 Script executed:
#!/bin/bash
# Search for any usage of the available field
rg -n 'available' --type zig -C 2Length of output: 19249
I need a more targeted search to confirm whether the available field is accessed anywhere as a struct member.
Wait, I need the codebase for that. Let me correct that:
🏁 Script executed:
#!/bin/bash
# Search for direct field access patterns on the available field
# Look for patterns like .available, ->available, self.available, or executor.available
rg -n '\.available\s*[=!<>|&]|->available|self\.available' --type zigLength of output: 0
🏁 Script executed:
#!/bin/bash
# Look for field access patterns on available field within Executor
# Search in src/runtime.zig specifically for the Executor struct usage
rg -n 'available' src/runtime.zig -B 2 -A 2Length of output: 939
Let me verify if the available field is accessed anywhere else in the codebase, or if there's any struct introspection/debugging code that might use it.
---
🏁 Script executed:
```shell
#!/bin/bash
# Search entire codebase for Executor field accesses beyond the struct definition
# Look for patterns like executor.available, thread_executor.available, etc.
rg -n '(executor|self|thread_executor)\s*\.\s*available' --type zig
Length of output: 0
Remove unused available field.
The field at line 359 is declared but never accessed anywhere in the codebase—no reads, no writes, no assignments. Multiple pattern searches confirm this is dead code. Delete it.
🤖 Prompt for AI Agents
In src/runtime.zig around line 359, the struct field declaration "available:
bool = true," is dead code (never read or written); remove this field from the
struct definition and update surrounding punctuation/formatting as needed so the
struct remains syntactically valid (remove the line and any dangling comma or
adjust the previous/next line commas).
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
src/io/net.zig (1)
563-594: Redundant helper methods for recvmsg/sendmsg variants.The
receiveFromRecvmsgandsendToSendmsgmethods just delegate to their recvfrom/sendto counterparts. If aio genuinely handles both the same way, consider removing these helpers to reduce code clutter.If these are truly identical under aio, you could remove the redundant methods:
- fn receiveFromRecvmsg(self: Socket, rt: *Runtime, buf: []u8) !ReceiveFromResult { - // aio handles this the same way as recvfrom - return self.receiveFromRecvfrom(rt, buf); - } - - fn sendToSendmsg(self: Socket, rt: *Runtime, addr: Address, data: []const u8) !usize { - // aio handles this the same way as sendto - return self.sendToSendto(rt, addr, data); - }
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
build.zig.zon(1 hunks)src/io/net.zig(23 hunks)src/io/test/net.zig(7 hunks)src/net.zig(5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/net.zig
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
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.
🪛 GitHub Actions: CI
build.zig.zon
[error] 15-15: Command failed: zig build -Dtarget=riscv64-linux. Hash mismatch: manifest declares 'aio-0.4.0-vB_rkUd6HusFjMrwOpkxjv1kXHcTJy1PgYtI_Byk6A29' but the fetched package has 'aio-0.4.0-k5779sDPBQBsdMHtiMYC1soCR4lmAaaDqNdBwOBmMIl4'.
🔇 Additional comments (11)
src/io/test/net.zig (2)
17-108: Address family constant migration looks correct.The systematic replacement of
std.posix.AF.*withaio.system.net.AF.*is consistent throughout all test assertions. Once the missing import is added, this should work correctly.
155-155: Thread pool configuration is correctly initialized.The change to
.thread_pool = .{}properly matches theRuntimeOptionsstruct definition, wherethread_pool: aio.ThreadPool.Optionsdefaults to.{}. This empty struct initialization is valid and consistent across the codebase.src/io/net.zig (9)
7-12: Migration to aio backend looks clean.The imports are properly organized and the Handle type is correctly aliased to
aio.Backend.NetHandle. Good foundation for the rest of the migration.
632-650: New readBuf method provides low-level vectorized I/O access.The implementation correctly maps EOF to 0 for stream semantics (lines 646-649). This aligns with standard read behavior where 0 indicates end-of-stream rather than an error.
670-684: New writeBuf method completes the vectorized I/O pair.Implementation follows the same pattern as readBuf. The direct WriteBuf access gives users control over scatter-gather I/O without buffer management overhead.
799-825: Socket creation migrated to async operations.Both
createStreamSocketandcreateDatagramSocketnow require aRuntimeparameter and perform async socket creation viaaio.NetOpen. This is a breaking API change but necessary for the aio integration.
543-566: receiveFrom implementation looks correct.The use of
NetRecvFromwith proper address handling and result structure is good. The peer address length is properly initialized and updated by the operation.
929-990: fillBuf handles complex scatter-gather logic correctly.The function properly handles header prepending, data slice aggregation, and pattern splatting with single-byte optimization. The max_len checks throughout prevent buffer overruns. Complex but appears correct.
486-501: Socket.bind correctly handles address updates.The address copy to
self.addressbefore callingNetBindis necessary because the operation updates the address with the actual bound address (important when binding to port 0 for automatic allocation). Good.
710-710: Error types updated for aio migration.
Reader.errandWriter.err(lines 710, 762) now useaio.NetRecv.Errorandaio.NetSend.Errorrespectively, aligning with the new backend. This is correct for the migration.
1061-1076: netClose properly shields against cancellation.The
beginShield/endShieldwrapper (lines 1069-1070) prevents task cancellation during socket cleanup, which is correct. Ignoring errors from bothwaitForIoandgetResultis reasonable for close operations where we want best-effort cleanup.
TODO