Skip to content

Replace libxev with aio.zig - #136

Merged
lalinsky merged 32 commits into
mainfrom
aio-migration
Nov 16, 2025
Merged

lalinsky merged 32 commits into
mainfrom
aio-migration

Conversation

@lalinsky

@lalinsky lalinsky commented Nov 11, 2025 •

Copy link
Copy Markdown
Owner

TODO

  • BlockingTask cancelation
  • Change how we run executors, start additional ones on demand (full cycle init/register/run/unregister/deinit), the main one is initialized in runtime.init

- 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.)
@coderabbitai

coderabbitai Bot commented Nov 11, 2025 •

Copy link
Copy Markdown
Contributor

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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.

📥 Commits

Reviewing files that changed from the base of the PR and between 47e5e58 and eef01f4.

📒 Files selected for processing (3)
  • build.zig.zon (1 hunks)
  • src/io/test/net.zig (8 hunks)
  • src/net.zig (6 hunks)

Walkthrough

Replaces the vendored libxev subtree with an aio-based integration: removes vendor/libxev files and CI, updates build wiring to use aio, and migrates runtime, executor, I/O, timers, blocking tasks, signals, streams, networking, and filesystem APIs to aio primitives and a new Dir API. (47 words)

Changes

Cohort / File(s) Summary
Build & CI
\.github/workflows/test.yml`, `check.sh`, `vendor/libxev/.github/**``
Remove xev_backend CI matrix/options and xev-specific CI steps; drop -Dxev_backend flags and vendor libxev CI workflows.
Top-level build manifests
\build.zig`, `build.zig.zon``
Rename option xev_backend → backend; switch dependency wiring from local libxev/xev to remote aio package and update imports/registration.
Vendor removal — libxev subtree
\vendor/libxev/**``
Delete entire vendor/libxev: backends (io_uring, epoll, kqueue, iocp, wasi_poll), headers, C API, build scripts, docs, examples, benches, Nix/flake/shell, LICENSE, README, and related tooling.
Runtime & executor
\src/runtime.zig`, `src/core/task.zig`, `src/core/timeout.zig``
Migrate runtime/executor primitives from xev to aio (Executor.loop: aio.Loop, Runtime.thread_pool: aio.ThreadPool, always-present thread pool); adjust spawn options, now(), loop init/shutdown, and timeout internals to use aio.Timer/completions.
Blocking tasks
\src/core/blocking_task.zig``
Replace thread-pool tasks with aio.Work: change stored field to aio.Work, initialize via Work.init, set userdata/completion callback, implement workFunc and completionCallback lifecycle.
I/O core & cancellation
\src/io/base.zig`, `src/io/pipe.zig``
Replace xev I/O model with aio completions: add genericCallback, implement cancelIo using aio.Cancel, adapt waitForIo/timedWaitForIo to aio.Completion semantics and completion.state property; remove custom runIo/IoOperation.
File I/O & Dir API
\src/io/file.zig`, `src/fs.zig`, `src/io/dir.zig``
Migrate File ops to aio ops (FileRead/FileWrite/FileClose); add vectored readVec/writeVec (remove readBuf/writeBuf); remove top-level open/create; add Dir handle API (cwd, openFile, createFile, rename, deleteFile).
Networking & sockets
\src/io/net.zig`, `src/net.zig`, `src/io/test/net.zig``
Replace backend-specific socket code with aio.Net* ops; Handle → aio.Backend.NetHandle; sockaddr/address types → aio.system.net.sockaddr; add vectored net read/write helpers; update createStream/createDatagram to accept Runtime.
Streams & buffers
\src/stream.zig`, `src/io/pipe.zig``
Convert stream read/write to slice-based vectored readVec/writeVec; update buffer mocks, discard/read paths and error mapping to the new vectored API.
Signals & wait
\src/signal.zig`, `src/core/timeout.zig``
Replace xev Async wait/notify with WaitQueue<WaitNode>; remove public WaitContext; implement queue-based wait/add/remove, cancellation, and timeout wiring via Timeout.
Examples & tests
\examples/tcp_client.zig`, `src/io/test/net.zig`, `src/net.zig``
Update Runtime.init thread_pool usage to .{} , adjust tests/examples to use new runtime, Dir API, vectored I/O, and aio.system.net family constants.
Benchmarks & metrics
\benchmarks/`, `vendor/libxev/src/bench/``
Remove many vendor benchmarks and examples; strip runtime metrics printing from repo benchmarks (echo_server, ping_pong); delete vendor bench suite.
Misc vendor tooling
\vendor/libxev/*.envrc`, `vendor/libxev/.gitignore`, `vendor/libxev/nix/**`, `vendor/libxev/flake.nix``
Remove vendor nix/flake/shell, envrc, Dependabot entries, and modified .gitignore (previous ignore entries removed).
Small re-exports
\src/zio.zig``
Commented-out Pipe re-export with TODO to migrate Pipe to aio.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Potential hotspots to inspect closely:

  • src/runtime.zig — executor lifecycle, register/unregister, shutdown ordering, and time/now() sourcing.
  • src/io/base.zig & src/io/file.zig — aio op construction, waitForIo/timedWaitForIo semantics, cancelIo races, vectored IO correctness and EOF/error mapping.
  • src/io/net.zig — sockaddr conversions, memory ownership for addresses, Handle type changes, and correct use of aio Net* ops.
  • src/core/blocking_task.zig & src/core/timeout.zig — aio.Work/Timer userdata ownership, completion lifetimes, and cancellation semantics.
  • src/signal.zig — wait-queue invariants, removal-on-cancel, and broadcast/wakeup correctness.
  • Search for leftover xev references or deleted vendor symbols across the repository.

Possibly related PRs

Poem

Vendored loops let go of shore,
aio steps in to do the chore,
Timers ring and completions sing,
Wait queues queue and networks ping,
CI trimmed, new plumbing walks the floor. 🛠️

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Replace libxev with aio.zig' directly and clearly describes the main change in the changeset—a comprehensive migration from the libxev library to the aio.zig library across the entire codebase.
Description check ✅ Passed The description acknowledges the migration effort and lists concrete TODO items related to the replacement work, indicating it's related to the changeset. While brief, it's not completely off-topic.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

❤️ Share

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

@lalinsky lalinsky changed the title WIP: Migrate to aio.zig Replace libxev with aio.zig Nov 11, 2025
- Use aio.system.net.socklen_t instead of std.posix.socklen_t for Windows compatibility
- Add loop_initialized flag to prevent wake() on deinitialized loops
@lalinsky
lalinsky marked this pull request as ready for review November 12, 2025 07:06

@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: 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.zig still constructs xev.Completion and friends, but the const 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

📥 Commits

Reviewing files that changed from the base of the PR and between 60e33c1 and c509688.

⛔ Files ignored due to path filters (6)
  • vendor/libxev/flake.lock is excluded by !**/*.lock
  • vendor/libxev/website/package-lock.json is excluded by !**/package-lock.json
  • vendor/libxev/website/public/favicon.ico is excluded by !**/*.ico
  • vendor/libxev/website/public/next.svg is excluded by !**/*.svg
  • vendor/libxev/website/public/thirteen.svg is excluded by !**/*.svg
  • vendor/libxev/website/public/vercel.svg is 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.zig
  • src/stack.zig
  • src/io/base.zig
  • src/core/timeout.zig
  • 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/core/blocking_task.zig
  • 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/signal.zig
  • src/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

Comment thread src/fs.zig Resolved
Comment thread src/io/file.zig Resolved
Comment thread src/runtime.zig Outdated
Comment on lines 983 to 986
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){

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.

⚠️ Potential issue | 🔴 Critical

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.

Comment thread src/stack.zig Resolved
Comment thread src/zio.zig
Comment on lines +26 to +27
// TODO: Migrate Pipe to aio
// pub const Pipe = @import("io/pipe.zig").Pipe;

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.

⚠️ Potential issue | 🟠 Major

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.

@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: 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-level error.Canceled from io_uring—an unexpected system event that shouldn't be coerced into error.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

📥 Commits

Reviewing files that changed from the base of the PR and between c509688 and 9994c21.

📒 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: Verify catch unreachable safety during shield.

The shield prevents user cancellation, but can waitForIo produce other errors (e.g., system failures) even within a shield? If there's any edge case where errors can occur, catch unreachable will 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.

Comment thread src/io/file.zig Resolved
Comment thread src/io/file.zig
Comment on lines +172 to +175
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;

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.

⚠️ Potential issue | 🟠 Major

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.

Suggested change
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.

@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: 1

♻️ Duplicate comments (2)
src/runtime.zig (1)

981-984: spawnBlocking still pokes an uninitialized loop

Executor.init leaves loop undefined until run() calls initLoop() and flips loop_initialized true. If someone does Runtime.init() followed by spawnBlocking() (which has been supported), this path hits executor.loop.add(&task.task.work.c) before any executor thread sets up its loop. That dereferences garbage and can crash immediately. You already added loop_initialized to guard wake-ups—put the blocking work through a pending queue (or otherwise defer submission) until the target executor has finished initLoop() and marked the flag. Then drain that queue right after setting loop_initialized in Executor.run().

src/io/file.zig (1)

164-165: Don’t collapse OS cancellations into WriteFailed

Same story on the write side: catching everything and returning error.WriteFailed masks the OS-level error.Canceled that should bubble as error.Unexpected per 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9994c21 and e142f78.

📒 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.zig
  • src/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)

Comment thread src/io/file.zig
Comment on lines +141 to 145
const bytes_read = op.getResult() catch return error.ReadFailed;

// EOF is indicated by 0 bytes read
if (bytes_read == 0) return error.EndOfStream;

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.

⚠️ Potential issue | 🟠 Major

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.

@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

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 over executors.items to fix type mismatch

Your code declares executors: std.ArrayList(*Executor), so executors.items is []*Executor. When you write for (executors.items) |*executor|, Zig binds each element as **Executor instead 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/deinit don't line up with the Runtime/StackPool/ThreadPool types. Looking at the actual code:

  1. StackPool initialization (line 868)

    • stack_pool is assigned .{} in the struct literal but never initialized via a proper init() 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 touches executor.loop before run() initializes it

This is the same problem flagged in the earlier review comment you quoted: spawnBlocking assumes 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.loop is still undefined, so .loop.add(...) is UB immediately. The new loop_initialized: std.atomic.Value(bool) flag is there but not used here.

You need to delay registration of the aio.Work until the target executor’s loop has actually been initialized, e.g.:

  • If loop_initialized is false, push the blocking task onto a per‑executor pending queue instead of calling loop.add directly.
  • When Executor.run finishes initLoop() and flips loop_initialized to true, drain that pending queue and loop.add all pending works.
  • For calls that happen while the loop is already running, you can keep the current fast path and call loop.add directly.

That keeps spawnBlocking safe to call before run() 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 unused stack_pool field

The transition to aio.Loop, loop_initialized, and shutdown_async inside Executor looks coherent:

  • initLoop sets up the loop and shutdown_async, then run toggles loop_initialized and uses it to guard loop.wake() in scheduleTaskRemote.
  • run’s defer block clears loop_initialized before deinitLoop, which is what you want.

One minor smell: Executor has its own stack_pool: StackPool but all stack operations go through self.runtime.stack_pool. If that’s intentional, consider dropping stack_pool from Executor to avoid confusion; if it’s not, wire it in or point AnyTask.create at 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 call rt.now() after Runtime.init() but before run(), 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

📥 Commits

Reviewing files that changed from the base of the PR and between e142f78 and 0716e35.

📒 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 fine

Only the import block changed here; it still pulls in std and the rest of the file compiles independently of xev/aio. Nothing to fix.

src/runtime.zig (3)

7-12: aio import and assert alias look good

Using const assert = std.debug.assert; and importing aio at 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 sense

The updated tests that pass .thread_pool = .{} into Runtime.init and drop the “thread_pool may be null” checks match the new invariant that an aio.ThreadPool is always created. Once the init/deinit issues above are fixed, these tests should be a good smoke check for both the pool and spawnBlocking.

Also applies to: 1345-1352


386-413: The review comment's core claim is wrong—next_executor exists and is actively used.

The grep results show next_executor is 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_index also 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.

@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

♻️ Duplicate comments (1)
src/runtime.zig (1)

944-945: CRITICAL: spawnBlocking dereferences uninitialized loop.

The past review comment is still valid. Calling spawnBlocking before any executor has run hits executor.loop.add() while loop is still undefined (set at line 344 in Executor.init). initLoop() doesn't run until Executor.run() starts (line 569), so this will crash:

var rt = try Runtime.init(allocator, .{});
defer rt.deinit();
_ = try rt.spawnBlocking(someWork, .{}); // CRASH

scheduleTaskRemote has the guard (line 731 checks loop_initialized), but spawnBlocking doesn'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 for now().

@intCast will panic if loop.now() exceeds i64 range (~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

📥 Commits

Reviewing files that changed from the base of the PR and between 0716e35 and d92d922.

📒 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)

@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: 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 in Runtime.run().

The function has two distinct behaviors:

  1. If Executor.current exists (main thread after Runtime.init()), run that executor
  2. 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

📥 Commits

Reviewing files that changed from the base of the PR and between d92d922 and afd3474.

📒 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_lock to synchronize access to the executors list, with debug assertions to catch double-registration bugs.


955-957: The previous review concern about early spawnBlocking calls appears resolved.

A previous review flagged that calling spawnBlocking before run() would crash because initLoop() happened inside run().

In the current code, loop.init() is called in Executor.init() (line 382), and Runtime.init() calls main_executor.init() (line 891), so the loop is fully initialized before Runtime.init() returns. Additionally, shutdown_async is added to the loop during init (line 392), proving that loop.add() is safe on an initialized-but-not-running loop.

Therefore, calling spawnBlocking() after Runtime.init() but before Runtime.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.ThreadPool instead of ?*xev.ThreadPool), and the initialization order properly handles error cases:

  1. Allocate Runtime
  2. Initialize thread pool (with errdefer cleanup)
  3. Pre-allocate executor capacity
  4. 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_pool is now always created (non-optional). The comment at line 1162 documents this change clearly.

Comment thread src/runtime.zig Resolved
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

@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: 1

♻️ Duplicate comments (1)
src/io/file.zig (1)

127-167: Vectored read/write are still masking getResult() errors (incl. OS-level cancellations)

readVec and writeVec currently collapse all op.getResult() failures into error.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.Canceled and other I/O failures, which we’ve already discussed elsewhere in this file. waitForIo is correctly propagating user cancellations via the Cancelable part of the error set, but OS-originated error.Canceled from getResult() now looks like a generic read/write failure instead of something unexpected.

Given the previous guidance and learnings about treating OS-level error.Canceled specially, 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.Error include error.Unexpected; tweak the mapping if your chosen error set differs.)

Also, you’re hard-coding storage: [16]aio.system.iovec(_const) while accepting an arbitrary slices slice. If slices.len can 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, and deleteFile all repeat the same pattern: fetch current task/executor, set userdata/callback, enqueue, then waitForIo. 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

📥 Commits

Reviewing files that changed from the base of the PR and between afd3474 and 910fe92.

📒 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.zig
  • src/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.zig
  • src/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 solid

Re-exporting Dir.cwd and driving file ops through dir.createFile/openFile/deleteFile inside a Runtime.runUntilComplete task 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 now

Grabbing std.fs.cwd() and exposing just the underlying fd into your own Dir type is a straightforward way to get a directory handle into the aio layer. The TODO about avoiding std.fs later is enough; nothing here blocks the migration.

src/io/file.zig (2)

169-185: Close path matches the async model and shields against cancellation

close runs FileClose through the same aio path (task/executor, loop.add, waitForIo) and wraps the wait in beginShield/endShield, then discards both wait and getResult errors. 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-end

All four tests (basic read and write, positional read and write, close operation, and reader and writer interface) now:

  • Acquire a Dir via fs.cwd().
  • Use dir.createFile / dir.openFile / dir.deleteFile instead of the old global helpers.
  • Run inside Runtime.runUntilComplete tasks 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.

Comment thread src/io/file.zig Resolved

@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: 2

📜 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 910fe92 and 999a421.

📒 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 between Runtime.run() and Runtime.spawn().

Runtime.run() can now create executors on demand (lines 949-954), which calls executor.init(), which calls registerExecutor(), which modifies the executors ArrayList under the lock. Meanwhile, Runtime.spawn() at lines 901-902 reads executors.items.len and executors.items[executor_no] WITHOUT holding executors_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:

  1. 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);
 }
  1. Use atomic pointer for single-executor fast path, then fall back to synchronized list for multi-executor.

  2. Document that executor registration must complete before spawn (not viable given current run() API).

Likely an incorrect or invalid review comment.

Comment thread src/runtime.zig Resolved

@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: 1

♻️ Duplicate comments (1)
src/runtime.zig (1)

370-399: CRITICAL: Executor.current set after fallible registerExecutor, causing assertion failure on error path.

Same issue from the previous review. At line 398, Executor.current = self is set AFTER the fallible registerExecutor call at line 394. If registerExecutor fails, the error path calls deinit() (via errdefer in Runtime.init at line 872), which asserts Executor.current == self at 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: available is declared but never accessed.

The available field is initialized to true but 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

📥 Commits

Reviewing files that changed from the base of the PR and between 999a421 and 87c614f.

📒 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 registerExecutor is a nice safety net, and round-robin scheduling in getNextExecutor is straightforward.


946-948: Previous review concern resolved: Loop is now initialized in Executor.init, not in run().

The previous review flagged that spawnBlocking might call executor.loop.add() before the loop is initialized. However, looking at the current code, Executor.init (lines 382-387) now initializes the loop during Runtime.init, so by the time user code calls spawnBlocking, 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_pool is now always initialized. The comment at line 1137 acknowledges this change.


852-915: LGTM: Runtime.init and deinit properly 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 via unregisterExecutor inside Executor.deinit.


956-968: LGTM: Runtime.run supports 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.

Comment thread src/runtime.zig Resolved

@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: 1

📜 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 87c614f and 56f95e4.

📒 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 in getNextExecutor correctly handles index wrap-around through modulo arithmetic.


369-398: Executor initialization follows proper error handling pattern.

The init sequence correctly:

  1. Sets up stack growth with cleanup via errdefer
  2. Initializes the aio loop with cleanup via errdefer
  3. Registers shutdown_async with the loop (safe to call before run())
  4. Registers the executor with the runtime
  5. 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 == self is 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), so loop.wake() can be called anytime after init without needing a separate loop_initialized flag.


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:

  1. Creates the runtime structure
  2. Initializes the thread pool
  3. Reserves capacity for executors
  4. 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_lock before calling executor.deinit() because deinit internally calls unregisterExecutor, which needs to acquire the same lock. Always fetching index 0 works because unregisterExecutor removes 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 call loop.add() immediately. This is demonstrated by the shutdown_async registration at line 391, which also calls loop.add() before run() 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_executor when 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.

Comment thread src/runtime.zig

// Coordination for thread startup
ready: std.Thread.ResetEvent = .{},
available: bool = true,

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.

⚠️ Potential issue | 🟡 Minor

🧩 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 2

Length 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 zig

Length 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 2

Length 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).

@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: 2

🧹 Nitpick comments (1)
src/io/net.zig (1)

563-594: Redundant helper methods for recvmsg/sendmsg variants.

The receiveFromRecvmsg and sendToSendmsg methods 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

📥 Commits

Reviewing files that changed from the base of the PR and between 56f95e4 and 44a8168.

📒 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.* with aio.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 the RuntimeOptions struct definition, where thread_pool: aio.ThreadPool.Options defaults 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 createStreamSocket and createDatagramSocket now require a Runtime parameter and perform async socket creation via aio.NetOpen. This is a breaking API change but necessary for the aio integration.


543-566: receiveFrom implementation looks correct.

The use of NetRecvFrom with 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.address before calling NetBind is 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.err and Writer.err (lines 710, 762) now use aio.NetRecv.Error and aio.NetSend.Error respectively, aligning with the new backend. This is correct for the migration.


1061-1076: netClose properly shields against cancellation.

The beginShield/endShield wrapper (lines 1069-1070) prevents task cancellation during socket cleanup, which is correct. Ignoring errors from both waitForIo and getResult is reasonable for close operations where we want best-effort cleanup.

Comment thread build.zig.zon Resolved
Comment thread src/io/test/net.zig Resolved
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