Repository navigation
Eliminate runtime.executor access in coroutine contexts - #54
Conversation
Replace all uses of runtime.executor with getCurrentTask().getExecutor()
pattern in file, TCP, and UDP operations. This provides cleaner access to
the executor and makes the code more explicit about running in a task context.
Changes:
- file.zig: Update all I/O operations (read, write, pread, pwrite, close)
- tcp.zig: Update TCP operations (accept, connect, read, write, shutdown, close)
- udp.zig: Update UDP operations (read, write, close)
- Pattern: const task = runtime.getCurrentTask() orelse unreachable;
const executor = task.getExecutor();
- Result structs now store task: *AnyTask instead of coro: *Coroutine
Blocking tasks in runtime.zig continue to use runtime.executor directly
since they run in thread pool threads without a current task context.
WalkthroughThis PR refactors async I/O operations across file, TCP, and UDP modules from a global executor model to a per-task executor approach. Result callbacks now store task pointers instead of coroutine pointers, and all event loop interactions use the task's specific executor rather than the runtime's shared executor. Changes
Sequence Diagram(s)sequenceDiagram
participant Task as Current Task
participant Executor as Per-Task Executor
participant XEV as XEV Event System
participant Callback as I/O Callback
rect rgb(200, 220, 255)
note right of Task: New: Per-Task Model
Task->>Task: runtime.getCurrentTask()
Task->>Executor: task.getExecutor()
Executor->>Executor: loop reference
end
rect rgb(255, 220, 200)
note right of XEV: I/O Operation
Executor->>XEV: submit op + callback<br/>(task ptr in result_data)
XEV->>XEV: wait for completion
XEV->>Callback: invoke on completion
end
rect rgb(200, 255, 220)
note right of Executor: New: Per-Task Completion
Callback->>Executor: resumeTask(result_data.task)
Executor->>Task: resume with result
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes The changes span three files (file, TCP, UDP) with consistent but repetitive refactoring patterns (struct field renames, executor retrieval, callback updates). While homogeneous, the scope is substantial with multiple I/O paths per file requiring individual verification of task/executor threading, callback correctness, and event loop wiring. Logic density and structural changes across multiple operations warrant careful review. Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
src/file.zig (2)
269-317: Do not swallow error.Canceled in readBuf; propagate it.The function’s error set includes Cancelable, but error.Canceled gets mapped to ReadFailed. Preserve cancellation semantics.
Apply this diff:
- const bytes_read = result_data.result catch |err| switch (err) { - error.EOF => return error.EndOfStream, - else => return error.ReadFailed, - }; + const bytes_read = result_data.result catch |err| switch (err) { + error.EOF => return error.EndOfStream, + error.Canceled => return error.Canceled, + else => return error.ReadFailed, + };
321-362: Do not swallow error.Canceled in writeBuf; propagate it.Map cancellation explicitly instead of collapsing to WriteFailed.
Apply this diff:
- const bytes_written = result_data.result catch return error.WriteFailed; + const bytes_written = result_data.result catch |err| switch (err) { + error.Canceled => return error.Canceled, + else => return error.WriteFailed, + };src/tcp.zig (2)
338-374: Propagate error.Canceled in writeBuf.Do not collapse cancellation to WriteFailed in an API that includes Cancelable in its error set.
Apply this diff:
- return result_data.result catch return error.WriteFailed; + return result_data.result catch |err| switch (err) { + error.Canceled => return error.Canceled, + else => return error.WriteFailed, + };
379-425: Propagate error.Canceled in readBuf.Preserve cancellation; map EOF and 0-length as you do, but return error.Canceled when applicable.
Apply this diff:
- const n = result_data.result catch |err| switch (err) { - error.EOF => return error.EndOfStream, - else => return error.ReadFailed, - }; + const n = result_data.result catch |err| switch (err) { + error.EOF => return error.EndOfStream, + error.Canceled => return error.Canceled, + else => return error.ReadFailed, + };
🧹 Nitpick comments (2)
src/file.zig (1)
36-87: Clarify task-context requirement in docs.Public methods now assume a current task (orelse unreachable). Add a brief note to these APIs stating they must be called from a runtime task.
Also applies to: 89-140, 166-214, 216-264, 268-317, 321-362, 364-411
src/udp.zig (1)
33-91: Verify cross-loop safety for xev.UDP.Same concern as TCP: confirm whether using different loops per call is supported.
Also applies to: 93-145, 147-194
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
src/file.zig(19 hunks)src/tcp.zig(14 hunks)src/udp.zig(9 hunks)
🔇 Additional comments (10)
src/file.zig (2)
37-87: Per-task executor refactor looks solid.Using task.getExecutor(), passing &executor.loop, and resuming via resumeTask(result_data.task, .local) is consistent and clear. Nice cleanup from global executor usage.
Also applies to: 90-140, 166-214, 216-264
369-411: Close path: good shielding + per-task executor.Fetching the task inside beginShield/endShield and awaiting completion on the executor is correct; cancellation cannot leak. LGTM.
src/tcp.zig (5)
67-112: TcpListener.accept: per-task executor usage is correct.Result struct/task pointer and local resume are consistent; waiting on executor is correct.
119-161: TcpListener.close: shielded close with per-task executor is correct.Pattern matches file.close; safe against cancellation.
179-228: TcpStream.connect: looks good.Per-task executor, result propagation, and error mapping align with the new model.
290-333: TcpStream.shutdown: looks good.Per-task executor, callback resume, and shieldless mapping to Unexpected are consistent with existing conventions.
234-259: Verify cross-loop safety for xev handles — concern is valid but unconfirmed.Your review correctly identifies that the code retrieves the executor per-call (lines 339, 380, 291, etc.) and passes its loop to xev operations, meaning the same
xev.TCPhandle can be driven from different executors' loops across sequential I/O calls.The pattern is:
read()→ getsexecutor1.loop→ submits to loopwrite()→ (if called from different task) getsexecutor2.loop→ submits to different looplibxev's design requires "Completions must only be added to one event loop at a time", and the code satisfies this (each call creates a fresh completion). However, whether xev.TCP handles themselves safely support multi-loop operations across calls is not explicitly documented. The xev design philosophy emphasizes per-loop/per-thread usage but doesn't definitively address handle portability.
The code's intent (fetching executor per-call rather than storing it) suggests this was intentional, but without explicit xev confirmation, implement a safety mechanism: store the owning executor on creation and assert/lock on each operation, or verify with xev maintainers that TCP handles are loop-portable.
src/udp.zig (3)
34-91: UdpSocket.read: refactor looks good.Task-bound executor, sender_addr capture, and resume flow are correct.
94-145: UdpSocket.write: refactor looks good.Per-task executor usage and callback/result flow LGTM.
152-194: UdpSocket.close: good shielding and wait semantics.Pattern matches TCP/file; safe against cancellation.
* Add NetPoll operation for socket readiness detection
Adds a new NetPoll completion type that allows checking socket
readiness without performing actual I/O operations. This is useful
for integrating with external libraries (like libpq) that do their
own recv/send syscalls but need async poll integration.
API:
- NetPoll.init(handle, events) where events specify .recv and/or .send
- Returns Error!void on completion (socket is ready when successful)
- Treated as .send_or_recv type to allow concurrent operations
Implementation across all backends:
- epoll: Uses EPOLLIN/EPOLLOUT flags
- poll: Uses POLLIN/POLLOUT flags
- kqueue: Uses EVFILT_READ/EVFILT_WRITE filters (prefers READ if both)
- io_uring: Uses IORING_OP_POLL_ADD native operation
- iocp: Uses zero-length WSARecv/WSASend for async readiness
Testing:
- Added poll_server.zig test that injects NetPoll before all recv/send
- All non-IPv6 tests pass on epoll, poll, and io_uring backends
* Simplify NetPoll API: use enum instead of bool flags
Changed NetPoll.Events from a packed struct with recv/send bools
to a simple Event enum with .recv and .send variants. This ensures
only one event type can be polled at a time, which:
- Simplifies the API (NetPoll.init(sock, .recv) instead of .{.recv=true})
- Works better with kqueue which can only register one filter at a time
- Removes ambiguity about what happens when both flags are set
- Makes backend implementations cleaner and more explicit
Also fixed event matching in epoll/poll/kqueue backends to properly
check if the requested event is actually ready before completing,
preventing spurious wakeups from completing the poll operation.
* Fix NetPoll to handle POLLHUP/EPOLLERR/EOF as ready state
The previous event matching logic would cause infinite requeuing when
poll/epoll returned error conditions (POLLHUP, POLLERR, EPOLLHUP, EPOLLERR)
or when kqueue returned EOF, because these weren't in the requested event
mask but also weren't being treated as completion conditions.
For NetPoll, these conditions should complete successfully because they
indicate the socket is "ready" - the next I/O operation will complete
immediately (possibly with an error/EOF). This matches the use case of
checking readiness before handing off to an external library.
Changes:
- poll/epoll: Check for HUP/ERR flags and complete immediately
- kqueue: Only treat EV_ERROR as error; EOF completes successfully
* Fix kqueue: use local EV_ERROR constant instead of std.c.EV_ERROR
std.c.EV_ERROR doesn't exist - use the local EV_ERROR constant
that's already defined at the top of the kqueue backend file.
* Use handleKqueueError for NetPoll error handling
Reuse handleKqueueError so we only fail on real socket errors
(SO_ERROR != 0), treating EOF as readiness. This is consistent
with the other net_* ops and avoids passing invalid errno values
when event.data == 0.
* Fix IOCP: use stack dummy byte instead of undefined for zero-length buffer
Changed WSABUF initialization from .buf = undefined to use a pointer to
a local dummy variable to avoid passing undefined values across the FFI
boundary to the Windows kernel. Since the buffer length is 0, the kernel
won't access the memory, but the pointer should still be a valid defined
value. The dummy variable's lifetime covers the entire WSA call.
Replace all uses of runtime.executor with getCurrentTask().getExecutor() pattern in file, TCP, and UDP operations. This provides cleaner access to the executor and makes the code more explicit about running in a task context.
Changes:
Blocking tasks in runtime.zig continue to use runtime.executor directly since they run in thread pool threads without a current task context.
Summary by CodeRabbit