Repository navigation
Conversation
Add address field to Stream struct and populate it with the peer
(remote) address for both connect and accept operations.
Changes:
- Add address: Address field to Stream struct
- Populate address in netConnectIp and netConnectUnix with the
address being connected to
- Populate address in netAccept by extracting peer address from
completion:
- POSIX backends (epoll/io_uring/kqueue): Read from
completion.op.accept.addr
- Windows IOCP: Use GetAcceptExSockaddrs to parse storage buffer
- WASI: Use unspecified address (no peer info available)
- Make UnixAddress.un conditional on std.net.has_unix_sockets
to support Windows without Unix sockets
- Add unreachable guards in Unix socket functions when not supported
- Skip Unix socket tests on platforms without support
- Fix setsockopt call to use sock instead of fd on Windows
- Fix WSABUF field names (.buf/.len) and add @intcast for Windows
The address field represents the peer (remote) address in all cases,
matching std library semantics.
|
Warning Rate limit exceeded@lalinsky has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 6 minutes and 43 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (1)
WalkthroughLarge refactor replacing legacy TCP/file modules with a new async I/O layer under Changes
Sequence Diagram(s)sequenceDiagram
participant App as Application
participant RT as Runtime/Executor
participant IOBase as src/io/base (runIo)
participant Net as src/io/net (IpAddress/Server/Stream)
participant Backend as libxev Backend
App->>Net: IpAddress.parseIp4(...)\naddr.listen(rt)
Net->>IOBase: runIo(rt, completion, "listen")
IOBase->>RT: yield / waitForIo
RT->>Backend: schedule listen completion
Backend-->>IOBase: completion callback (fd, addr)
IOBase-->>RT: resume task (Server returned)
RT-->>App: Server
App->>Net: server.accept(rt)
Net->>IOBase: runIo(rt, completion, "accept")
IOBase->>RT: waitForIo
Backend-->>IOBase: accept callback (peer fd, peer addr)
IOBase-->>App: Stream (peer)
App->>Net: stream.reader(rt, buf)\nstream.writer(rt, buf)
App->>Net: writer.interface.writeAll(data)\nwriter.interface.flush()
Net->>IOBase: runIo(rt, completion, "write")
Backend-->>IOBase: write completed
App->>Net: reader.interface.readSliceAll()
Net->>IOBase: runIo(rt, completion, "read")
Backend-->>IOBase: data ready -> IOBase returns bytes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
@claude I don't think we need threadpool for shutdown and close |
|
Claude finished @lalinsky's task —— View job Analysis: Threadpool not needed for shutdown and close
FindingsYou're absolutely right! Both In
In
Neither syscall actually blocks - they're synchronous operations that complete immediately. The threadpool is unnecessary overhead here. RecommendationRemove the
Should I go ahead and make these changes? Branch: |
|
@claude help me understand dup handling in the epoll backend |
|
Claude finished @lalinsky's task —— View job Understanding dup handling in epoll backend
The dup handling in the epoll backend is a workaround for a fundamental limitation of epoll. The ProblemEpoll's limitation: You can only register a file descriptor (fd) with epoll once. If you try to register the same fd multiple times (for different operations like simultaneous read + write), you get an error. This is different from other backends like kqueue and io_uring, which allow multiple operations on the same fd simultaneously. The SolutionWhen you need multiple concurrent operations on the same fd in epoll, libxev uses
Why This Matters
Example Use CaseIf you want to do both a read and write on the same socket simultaneously:
Branch: |
|
@claude if we only ever do one operation at a time, we don't need the fd duping, right? |
|
Claude finished @lalinsky's task —— View job Analyzing fd duping requirement
Answer: Yes, you're absolutely right!If you only ever do one operation at a time on a file descriptor, you don't need fd duping. Why fd duping exists in epollThe dup mechanism exists to work around epoll's fundamental limitation: you can only register an fd with epoll once. When you try to do concurrent operations on the same fd (e.g., simultaneous read + write, or multiple accept calls), epoll fails because the fd is already registered. The workaround is to Your code only does sequential operationsLooking at your I/O implementation in
Each function calls There's no overlap - only one operation is active on an fd at a time. The one place you use dupCurrently, you only set the dup flag in one place:
if (xev.backend == .epoll) {
completion.flags.dup = true;
}Since accept operations are also sequential (one at a time on the server socket), this dup is unnecessary. RecommendationYou can safely remove the dup flag from
The dup mechanism is only needed when you have truly concurrent operations (e.g., a streaming protocol doing simultaneous bidirectional I/O), which isn't the case in your implementation. Branch: |
|
@claude remove both flags |
|
Claude finished @lalinsky's task —— View job Removing unnecessary flags
SummaryRemoved three unnecessary flags from
All tests passed successfully (110/110). Branch: |
Since close() and shutdown() are non-blocking syscalls that return immediately, there's no need to use the threadpool flag for them. Similarly, since we only ever do one operation at a time on each file descriptor, we don't need the dup flag workaround for epoll's limitation of registering an fd only once. Co-authored-by: Lukáš Lalinský <[email protected]>
|
@claude completely disable unix socket tests on Windows And give me a report where do we still use TcpStream and TcpListener |
|
Claude finished @lalinsky's task —— View job Disabling Unix socket tests on Windows and finding TcpStream/TcpListener usage
Changes MadeUnix Socket Tests on Windows: Disabled both unix socket tests in
TcpStream and TcpListener Usage ReportTcpStream UsageCore Implementation (
Public API (
Internal API (
Examples:
TcpListener UsageCore Implementation (
Public API (
Internal API (
Examples:
Documentation:
External Files (Not Zig)
SummaryBoth
All tests pass (110/110) on Linux. Branch: |
Use builtin.os.tag check to completely skip unix socket tests on Windows platform instead of relying on std.net.has_unix_sockets. Co-authored-by: Lukáš Lalinský <[email protected]>
Remove TcpListener and TcpStream in favor of a unified Stream interface. Connections are now created via IpAddress.connect() and IpAddress.listen(). Simplifies API by using single-buffer read/write instead of vectored I/O, and adds convenience methods readAll/writeAll. Updates tests to use Channel for synchronization and dynamic port allocation.
There was a problem hiding this comment.
Actionable comments posted: 12
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
vendor/libxev/src/backend/epoll.zig (1)
838-892: FD leak when dup flag is used in stop_completion()When deleting a completion (no event delivered), epoll_ctl DEL is issued but a dup_fd (if used) isn’t closed, leaking FDs. Close dup_fd after DEL and reset it.
fn stop_completion(self: *Loop, completion: *Completion) void { const maybe_fd = if (completion.flags.dup) completion.flags.dup_fd else completion.fd(); if (maybe_fd) |fd| { posix.epoll_ctl( self.fd, linux.EPOLL.CTL_DEL, fd, null, ) catch unreachable; + if (completion.flags.dup and completion.flags.dup_fd > 0) { + posix.close(completion.flags.dup_fd); + completion.flags.dup_fd = 0; + } } else switch (completion.op) { .timer => |*v| { const c = v.c; if (c.flags.state == .active) { self.timers.remove(v); } ... } if (completion.flags.state == .active) self.active -= 1; completion.flags.state = .dead; }
🧹 Nitpick comments (10)
src/runtime.zig (1)
2022-2025: Explicit current-executor access: good API; minor polishThe Runtime.getCurrentTask re-route via getCurrentExecutor is clearer and safer. Consider marking getCurrentExecutor as inline for hot paths.
- pub fn getCurrentExecutor(self: *Runtime) ?*Executor { + pub inline fn getCurrentExecutor(self: *Runtime) ?*Executor { _ = self; return Runtime.current_executor; }Also applies to: 2027-2030
vendor/libxev/src/backend/kqueue.zig (1)
667-690: Unify timer API and normalize timespec
- Receiver type differs from epoll (Loop vs *Loop). Recommend using *Loop here too for cross-backend consistency.
- Both timer_next and timer_next_ns should normalize nsec with carry to keep timespec valid.
- pub fn timer_next(self: Loop, next_ms: u64) posix.timespec { + pub fn timer_next(self: *Loop, next_ms: u64) posix.timespec { const max: posix.timespec = .{ .sec = std.math.maxInt(isize), .nsec = std.math.maxInt(isize) }; - const next_s = std.math.cast(isize, next_ms / std.time.ms_per_s) orelse return max; - const next_ns = std.math.cast(isize, (next_ms % std.time.ms_per_s) * std.time.ns_per_ms) orelse return max; - return .{ - .sec = std.math.add(isize, self.cached_now.sec, next_s) catch return max, - .nsec = std.math.add(isize, self.cached_now.nsec, next_ns) catch return max, - }; + const add_s_u = next_ms / std.time.ms_per_s; + const add_ns_u = (next_ms % std.time.ms_per_s) * std.time.ns_per_ms; + const nsec_total = (@as(u64, @intCast(self.cached_now.nsec)) + add_ns_u); + const carry = nsec_total / std.time.ns_per_s; + const nsec_final_u = nsec_total % std.time.ns_per_s; + const sec_total_u = (@as(u64, @intCast(self.cached_now.sec)) + add_s_u + carry); + if (sec_total_u > @as(u64, @intCast(std.math.maxInt(isize)))) return max; + return .{ .sec = @intCast(sec_total_u), .nsec = @intCast(nsec_final_u) }; } - pub fn timer_next_ns(self: Loop, next_ns: u64) posix.timespec { + pub fn timer_next_ns(self: *Loop, next_ns: u64) posix.timespec { const max: posix.timespec = .{ .sec = std.math.maxInt(isize), .nsec = std.math.maxInt(isize) }; - const next_s = std.math.cast(isize, next_ns / std.time.ns_per_s) orelse return max; - const next_nsec = std.math.cast(isize, next_ns % std.time.ns_per_s) orelse return max; - return .{ - .sec = std.math.add(isize, self.cached_now.sec, next_s) catch return max, - .nsec = std.math.add(isize, self.cached_now.nsec, next_nsec) catch return max, - }; + const add_s_u = next_ns / std.time.ns_per_s; + const add_ns_u = next_ns % std.time.ns_per_s; + const nsec_total = (@as(u64, @intCast(self.cached_now.nsec)) + add_ns_u); + const carry = nsec_total / std.time.ns_per_s; + const nsec_final_u = nsec_total % std.time.ns_per_s; + const sec_total_u = (@as(u64, @intCast(self.cached_now.sec)) + add_s_u + carry); + if (sec_total_u > @as(u64, @intCast(std.math.maxInt(isize)))) return max; + return .{ .sec = @intCast(sec_total_u), .nsec = @intCast(nsec_final_u) }; }Also applies to: 691-712
vendor/libxev/src/backend/epoll.zig (2)
262-285: Expose timer_next(_ns): normalize timespecSame suggestion as kqueue: normalize nsec with carry to preserve valid timespec values.
- pub fn timer_next(self: *Loop, next_ms: u64) posix.timespec { + pub fn timer_next(self: *Loop, next_ms: u64) posix.timespec { const max: posix.timespec = .{ .sec = std.math.maxInt(isize), .nsec = std.math.maxInt(isize) }; - const next_s = std.math.cast(isize, next_ms / std.time.ms_per_s) orelse return max; - const next_ns = std.math.cast(isize, (next_ms % std.time.ms_per_s) * std.time.ns_per_ms) orelse return max; - return .{ - .sec = std.math.add(isize, self.cached_now.sec, next_s) catch return max, - .nsec = std.math.add(isize, self.cached_now.nsec, next_ns) catch return max, - }; + const add_s_u = next_ms / std.time.ms_per_s; + const add_ns_u = (next_ms % std.time.ms_per_s) * std.time.ns_per_ms; + const nsec_total = (@as(u64, @intCast(self.cached_now.nsec)) + add_ns_u); + const carry = nsec_total / std.time.ns_per_s; + const nsec_final_u = nsec_total % std.time.ns_per_s; + const sec_total_u = (@as(u64, @intCast(self.cached_now.sec)) + add_s_u + carry); + if (sec_total_u > @as(u64, @intCast(std.math.maxInt(isize)))) return max; + return .{ .sec = @intCast(sec_total_u), .nsec = @intCast(nsec_final_u) }; } - pub fn timer_next_ns(self: *Loop, next_ns: u64) posix.timespec { + pub fn timer_next_ns(self: *Loop, next_ns: u64) posix.timespec { const max: posix.timespec = .{ .sec = std.math.maxInt(isize), .nsec = std.math.maxInt(isize) }; - const next_s = std.math.cast(isize, next_ns / std.time.ns_per_s) orelse return max; - const next_nsec = std.math.cast(isize, next_ns % std.time.ns_per_s) orelse return max; - return .{ - .sec = std.math.add(isize, self.cached_now.sec, next_s) catch return max, - .nsec = std.math.add(isize, self.cached_now.nsec, next_nsec) catch return max, - }; + const add_s_u = next_ns / std.time.ns_per_s; + const add_ns_u = next_ns % std.time.ns_per_s; + const nsec_total = (@as(u64, @intCast(self.cached_now.nsec)) + add_ns_u); + const carry = nsec_total / std.time.ns_per_s; + const nsec_final_u = nsec_total % std.time.ns_per_s; + const sec_total_u = (@as(u64, @intCast(self.cached_now.sec)) + add_s_u + carry); + if (sec_total_u > @as(u64, @intCast(std.math.maxInt(isize)))) return max; + return .{ .sec = @intCast(sec_total_u), .nsec = @intCast(nsec_final_u) }; }Also applies to: 286-306
761-771: Thread pool for close(): likely unnecessary; align with kqueuekqueue performs close synchronously; epoll conditionally schedules .close on the thread pool. Suggest removing the thread-pool branch here for consistency and to simplify shutdown.
- .close => |v| res: { - if (completion.flags.threadpool) { - if (self.thread_schedule(completion)) |_| - return - else |err| - break :res .{ .close = err }; - } - - posix.close(v.fd); - break :res .{ .close = {} }; - }, + .close => |v| res: { + posix.close(v.fd); + break :res .{ .close = {} }; + },examples/tls_demo.zig (1)
9-13: API migration: looks good; two optional hardening tweaks
- Avoid hardcoding IPs; when DNS lands, prefer host-based connect for resilience.
- Consider graceful shutdown of the TCP stream after TLS I/O (e.g., shutdown before close) to avoid half-closed ambiguity.
- var stream = try addr.connect(rt); - defer stream.close(rt); + var stream = try addr.connect(rt); + defer stream.shutdown(rt, .both) catch |err| std.log.warn("shutdown: {}", .{err}); + defer stream.close(rt);Note: keep
.no_verificationonly for demos; default to system CAs in real examples.examples/tcp_client.zig (1)
5-12: Client example: solid; small nit
- Good switch to IpAddress/connect and explicit flush + shutdown.
- Remove unused
-const print = std.debug.print; @@ fn clientTask(rt: *zio.Runtime) !void { std.log.info("Connecting to 127.0.0.1:8080...", .{}); const addr = try zio.net.IpAddress.parseIp4("127.0.0.1", 8080); var stream = try addr.connect(rt); defer stream.close(rt); defer stream.shutdown(rt, .both) catch |err| std.log.err("Shutdown error: {}", .{err}); @@ try writer.interface.flush(); @@ - var task = try runtime.spawn(clientTask, .{&runtime}, .{}); + var task = try runtime.spawn(clientTask, .{&runtime}, .{});Also applies to: 22-23, 43-44
examples/tcp_echo_server.zig (1)
11-12: Verify format placeholder for address.
{f}is uncommon for structured types; if not intentionally supported byStream.address.format, prefer{}.Apply if
{f}isn’t supported:- std.log.info("Client connected from {f}", .{stream.address}); + std.log.info("Client connected from {}", .{stream.address});src/io/test/net.zig (1)
51-67: Consider TaskGroup for symmetric join.You already left a TODO. Using a TaskGroup will simplify wait/join and failure propagation.
I can draft a minimal TaskGroup helper matching your Runtime API.
src/io/base.zig (1)
78-86: Confirm timer units.Param is
duration_ms, but backends mention nanosecond timers. Verifytimer_nextexpects milliseconds; if it expects ns, convert.Potential fix if ns required:
- var completion: xev.Completion = .{ .op = .{ .timer = .{ - .next = executor.loop.timer_next(duration_ms), - } } }; + var completion: xev.Completion = .{ .op = .{ .timer = .{ + .next = executor.loop.timer_next(duration_ms * 1_000_000), + } } };src/net.zig (1)
13-25: Public IpAddressList is unused here.If not planned for immediate use, consider keeping it internal or adding a usage site to justify API surface.
Would you like a follow-up PR to wire it into DNS helpers?
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (18)
benchmarks/echo_server.zig(4 hunks)build.zig(0 hunks)examples/mini_redis.zig(0 hunks)examples/tcp_client.zig(3 hunks)examples/tcp_echo_server.zig(2 hunks)examples/tls_demo.zig(1 hunks)src/io/base.zig(1 hunks)src/io/net.zig(1 hunks)src/io/test/net.zig(1 hunks)src/net.zig(5 hunks)src/runtime.zig(2 hunks)src/tcp.zig(0 hunks)src/zio.zig(0 hunks)vendor/libxev/src/backend/epoll.zig(2 hunks)vendor/libxev/src/backend/io_uring.zig(2 hunks)vendor/libxev/src/backend/iocp.zig(1 hunks)vendor/libxev/src/backend/kqueue.zig(2 hunks)vendor/libxev/src/backend/wasi_poll.zig(2 hunks)
💤 Files with no reviewable changes (4)
- src/zio.zig
- build.zig
- examples/mini_redis.zig
- src/tcp.zig
🔇 Additional comments (16)
vendor/libxev/src/backend/iocp.zig (1)
470-473: LGTM! Clean nanosecond timer extension.The
timer_next_nsfunction correctly extends the timer API to support nanosecond granularity, paralleling the existingtimer_nextmillisecond-based function. The implementation is straightforward and consistent with the IOCP backend's approach of adding to the cached timestamp.vendor/libxev/src/backend/io_uring.zig (1)
321-369: LGTM! Excellent overflow protection and API consistency.The changes expose
timer_nextas public and addtimer_next_nsfor nanosecond-based timing. Both functions include robust overflow handling with graceful fallback to maximum values. The nanosecond function correctly splits the input into seconds and nanoseconds components for thelinux.kernel_timespecstructure.vendor/libxev/src/backend/wasi_poll.zig (1)
580-606: LGTM! Consistent nanosecond timer support for WASI backend.The changes expose
timer_nextpublicly and addtimer_next_nsfor nanosecond granularity. Both functions correctly fetch the monotonic clock time and add the specified duration. The TODO comments regarding overflow handling are consistent with the existing pattern in this backend.src/runtime.zig (2)
1172-1175: Executor.getCurrentTask: LGTMSimple, correct conversion from current_coroutine to AnyTask.
1-10: Scan complete: No legacy TcpStream/TcpListener references found in Zig codebase.The verification scan found zero references to
TcpStreamorTcpListeneracross all.zigfiles. References that appeared were in documentation (README.md) and Rust benchmark files, not in the Zig source code itself. The migration away from these legacy APIs is complete.examples/tcp_echo_server.zig (2)
7-9: Good: shutdown before close.The defer ordering ensures shutdown runs before close. LGTM.
47-52: Accept + errdefer is correct.
errdefer stream.close(rt)protects spawn failure. LGTM.src/io/test/net.zig (1)
102-109: Windows skip for Unix sockets.Guard looks right and matches the PR ask. LGTM.
src/io/base.zig (1)
56-62: Callback wiring looks solid.
resumeTask(self.task, .local)on completion and.disarmare appropriate.src/net.zig (2)
50-65: Host connect loop looks fine.Retries on
ConnectionRefusedacross all addrs, returns first success. LGTM.
114-168: No legacy TcpStream/TcpListener references remain in the Zig codebase.The sweep confirms successful cleanup. All references in search results are either external dependencies (vendor/libxev with differently-capitalized
TCPStream), outdated documentation (README.md), or unrelated Rust benchmarks. The test code shown uses the new streaming API throughout.benchmarks/echo_server.zig (3)
18-25: Echo loop is correct with buffered I/O.
reader.interface.stream(...); flush()per iteration is fine for the benchmark.
28-47: Server lifecycle is clean.Listen/accept/spawn pattern with
ResetEventsync is solid.
57-67: Client round-trip and verification look good.Buffered write/flush then
readSliceAlland bytewise check are appropriate.Also applies to: 81-88
src/io/net.zig (2)
120-166: Close/shutdown path: confirm nonblocking semantics and shield scope.Looks correct with
beginShield/endShield, but double‑check xev guarantees that.shutdown/.closeops never block the executor thread. No threadpool seems necessary if xev completes them asynchronously.Would you like a workload test to hammer open/close under epoll/io_uring/IOCP?
Also applies to: 206-215, 543-554
1-6: Legacy TcpStream/TcpListener successfully removed.Comprehensive codebase scan confirms zero remaining usages of
TcpStreamorTcpListeneracross all Zig files. The newServerandStreamabstractions insrc/io/net.zigproperly replace the legacy API, and all imports are appropriate for the refactored implementation.
| pub fn waitForIo(rt: *Runtime, completion: *xev.Completion) !void { | ||
| var canceled = false; | ||
|
|
||
| var executor = rt.getCurrentExecutor() orelse @panic("no active executor"); | ||
| executor.loop.add(completion); | ||
|
|
||
| while (completion.state() == .active) { | ||
| executor.yield(.ready, .waiting_io, .allow_cancel) catch |err| switch (err) { | ||
| error.Canceled => { | ||
| if (!canceled) { | ||
| cancelIo(rt, completion); | ||
| canceled = true; | ||
| } | ||
| executor = rt.getCurrentExecutor() orelse @panic("no active executor"); | ||
| continue; | ||
| }, | ||
| }; | ||
| std.debug.assert(completion.state() == .dead); | ||
| break; | ||
| } | ||
|
|
||
| if (canceled) { | ||
| return error.Canceled; | ||
| } | ||
| } |
There was a problem hiding this comment.
Cancellation can loop indefinitely; disallow further cancels after issuing one.
If yield(.allow_cancel) keeps returning error.Canceled, this loop may never reach .dead. After sending cancelIo once, continue waiting with cancel disabled.
Apply:
pub fn waitForIo(rt: *Runtime, completion: *xev.Completion) !void {
- var canceled = false;
+ var canceled = false;
+ var allow_cancel = true;
var executor = rt.getCurrentExecutor() orelse @panic("no active executor");
executor.loop.add(completion);
- while (completion.state() == .active) {
- executor.yield(.ready, .waiting_io, .allow_cancel) catch |err| switch (err) {
+ while (completion.state() == .active) {
+ executor.yield(.ready, .waiting_io, if (allow_cancel) .allow_cancel else .disallow_cancel) catch |err| switch (err) {
error.Canceled => {
- if (!canceled) {
+ if (!canceled) {
cancelIo(rt, completion);
canceled = true;
+ allow_cancel = false;
}
executor = rt.getCurrentExecutor() orelse @panic("no active executor");
continue;
},
};
std.debug.assert(completion.state() == .dead);
break;
}
if (canceled) {
return error.Canceled;
}
}📝 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.
| pub fn waitForIo(rt: *Runtime, completion: *xev.Completion) !void { | |
| var canceled = false; | |
| var executor = rt.getCurrentExecutor() orelse @panic("no active executor"); | |
| executor.loop.add(completion); | |
| while (completion.state() == .active) { | |
| executor.yield(.ready, .waiting_io, .allow_cancel) catch |err| switch (err) { | |
| error.Canceled => { | |
| if (!canceled) { | |
| cancelIo(rt, completion); | |
| canceled = true; | |
| } | |
| executor = rt.getCurrentExecutor() orelse @panic("no active executor"); | |
| continue; | |
| }, | |
| }; | |
| std.debug.assert(completion.state() == .dead); | |
| break; | |
| } | |
| if (canceled) { | |
| return error.Canceled; | |
| } | |
| } | |
| pub fn waitForIo(rt: *Runtime, completion: *xev.Completion) !void { | |
| var canceled = false; | |
| var allow_cancel = true; | |
| var executor = rt.getCurrentExecutor() orelse @panic("no active executor"); | |
| executor.loop.add(completion); | |
| while (completion.state() == .active) { | |
| executor.yield(.ready, .waiting_io, if (allow_cancel) .allow_cancel else .disallow_cancel) catch |err| switch (err) { | |
| error.Canceled => { | |
| if (!canceled) { | |
| cancelIo(rt, completion); | |
| canceled = true; | |
| allow_cancel = false; | |
| } | |
| executor = rt.getCurrentExecutor() orelse @panic("no active executor"); | |
| continue; | |
| }, | |
| }; | |
| std.debug.assert(completion.state() == .dead); | |
| break; | |
| } | |
| if (canceled) { | |
| return error.Canceled; | |
| } | |
| } |
- Move src/file.zig to src/io/file.zig for better organization - Use runIo() from io/base.zig instead of manual callbacks (~90 lines removed) - Remove xev.File wrapper, store fd directly - File methods now take Runtime as parameter instead of storing it - Update imports in fs.zig and zio.zig - Clean up unused imports (AnyTask, Executor, resumeTask, Coroutine) - Use fully qualified names in tests (std.testing.*)
…ort test - Add getPort() checks to parseIp4, parseIp6, parseIp, and parseIpAndPort tests - Fix parseIpAndPort test to use bracketed IPv6 format [::1]:8080 instead of parseIp
Add early return check for empty data slice to prevent underflow when accessing data[data.len - 1] and data[0..data.len - 1]. Compute last_index safely when data.len > 0.
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/fs.zig (1)
15-26: Docs/API mismatch: runtime unused; deinit() mention is stale; enumerate Unsupported error.
- runtime is ignored in openFile/createFile; either drop it or note “currently unused”.
- Return docs should not mention deinit() (there’s no deinit on File).
- List error.Unsupported when flags.lock != .none.
Apply doc fix:
@@ -/// ## Parameters -/// - `runtime`: The ZIO runtime instance for async operations +/// ## Parameters +/// - `runtime`: (currently unused) reserved for future integration @@ -/// ## Returns -/// A File instance that must be closed with `close()` and freed with `deinit()` +/// ## Returns +/// A File instance that must be closed with `close()` @@ -/// ## Errors -/// - `FileNotFound`: File doesn't exist -/// - `AccessDenied`: Insufficient permissions to access the file -/// - Platform-specific file system errors +/// ## Errors +/// - `FileNotFound`: File doesn't exist +/// - `AccessDenied`: Insufficient permissions to access the file +/// - `Unsupported`: File locking requested (`flags.lock != .none`) +/// - Platform-specific file system errorsOptionally, consider removing the runtime parameter from these wrappers in a follow-up API pass.
Also applies to: 27-34, 45-51, 51-58
🧹 Nitpick comments (5)
src/fs.zig (3)
83-91: Windows: include FILE_ATTRIBUTE_NORMAL with FILE_FLAG_OVERLAPPED.Safer, more conventional CreateFileW usage:
Apply:
- windows.FILE_FLAG_OVERLAPPED, + windows.FILE_ATTRIBUTE_NORMAL | windows.FILE_FLAG_OVERLAPPED,
134-142: Same fix for CreateFileW in createFileWindows.Apply:
- windows.FILE_FLAG_OVERLAPPED, + windows.FILE_ATTRIBUTE_NORMAL | windows.FILE_FLAG_OVERLAPPED,
158-166: Ownership transfer from std.fs.File to zio.File.The Unix wrappers construct File from std.fs.File and intentionally do not close std_file, implying ownership transfer. Add a short comment to make this explicit to avoid accidental double-closes in future edits.
- const std_file = try std.fs.cwd().openFile(path, flags); + const std_file = try std.fs.cwd().openFile(path, flags); + // Ownership note: we transfer the handle into zio.File; do not close std_file here.Also applies to: 168-176
src/io/file.zig (2)
31-43: Concurrent I/O on the same File can corrupt position.position is updated without synchronization; parallel read/write calls will race and overlap. Either:
- Serialize operations per File (e.g., an internal async mutex/in-flight guard), or
- Document the non-concurrency guarantee and assert in debug builds, or
- Require positional I/O (pread/pwrite) for parallelism and keep read/write single-flight.
If you choose to document-only, add a debug guard:
+ in_flight: bool = false, @@ - pub fn read(self: *File, rt: *Runtime, buffer: []u8) !usize { + pub fn read(self: *File, rt: *Runtime, buffer: []u8) !usize { + if (builtin.mode == .Debug) { + std.debug.assert(@atomicRmw(bool, &self.in_flight, .Xchg, true, .seq_cst) == false); + defer @atomicStore(bool, &self.in_flight, false, .release); + } var completion: xev.Completion = .{ .op = .{(Replicate for write/readBuf/writeBuf.) Alternatively, implement a small per-handle mutex for release builds.
Also applies to: 45-57, 132-146
148-160: Optionally invalidate the handle after close.Not required, but setting the handle to an invalid sentinel (and/or a closed flag) helps catch accidental reuse after close.
pub fn close(self: *File, rt: *Runtime) void { @@ - runIo(rt, &completion, "close") catch {}; + runIo(rt, &completion, "close") catch {}; + // Optional: mark closed for debug-safety + self.position = 0; + // self.fd = if (builtin.os.tag == .windows) @as(Handle, std.os.windows.INVALID_HANDLE_VALUE) else @as(Handle, std.os.invalid_fd); }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/file.zig(0 hunks)src/fs.zig(6 hunks)src/io/file.zig(1 hunks)src/zio.zig(1 hunks)
💤 Files with no reviewable changes (1)
- src/file.zig
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-15T08:14:58.308Z
Learnt from: CR
PR: lalinsky/zio#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-15T08:14:58.308Z
Learning: To test Windows builds on Linux, run: zig build build-tests -Dtarget=x86_64-windows && wine zig-out/bin/test.exe
Applied to files:
src/fs.zig
🔇 Additional comments (1)
src/zio.zig (1)
17-17: Verification complete: no legacy imports or TCP type stragglers found.
- ✓ No direct imports of "file.zig".File remain in Zig source
- ✓ All TcpListener/TcpStream usages removed from codebase; new API (Stream, IpAddress, helper functions) in place via net.zig re-exports
The import-path change and TCP type migration are clean.
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/fs.zig (1)
178-212: Tests: same slice vs pointer issues as in io/file.zig.Fix passing
&bufferto use slices.- _ = try file.write(rt, write_data); + _ = try file.write(rt, write_data); @@ - const bytes_read = try read_file.read(rt, &buffer); + const bytes_read = try read_file.read(rt, buffer[0..]);
♻️ Duplicate comments (8)
src/io/test/net.zig (1)
41-49: IPv6 case added correctly.The test now exercises
[::1]:8080via parseIpAndPort and checks port/family. Looks good.src/io/net.zig (7)
7-7: Use SOCKET on Windows; drop ptr casts.WSASocketW returns SOCKET. Using HANDLE + ptr-casts is incorrect and breaks IOCP paths.
-const Handle = if (xev.backend == .iocp) std.os.windows.HANDLE else std.posix.socket_t; +const Handle = if (xev.backend == .iocp) std.os.windows.ws2_32.SOCKET else std.posix.socket_t; @@ fn createStreamSocket(family: std.posix.sa_family_t) !Handle { if (builtin.os.tag == .windows) { - return try std.os.windows.WSASocketW(family, std.posix.SOCK.STREAM, 0, null, 0, std.os.windows.ws2_32.WSA_FLAG_OVERLAPPED); + return try std.os.windows.ws2_32.WSASocketW( + family, + std.posix.SOCK.STREAM, + 0, null, 0, + std.os.windows.ws2_32.WSA_FLAG_OVERLAPPED, + ); } else { @@ - const sock = if (xev.backend == .iocp) @as(std.os.windows.ws2_32.SOCKET, @ptrCast(fd)) else fd; + const sock = fd; @@ - const sock = if (xev.backend == .iocp) @as(std.os.windows.ws2_32.SOCKET, @ptrCast(fd)) else fd; + const sock = fd;Also applies to: 309-317, 323-324, 352-353
335-337: Cast backlog to c_int for listen().listen expects c_int; options.kernel_backlog is u31.
- try std.posix.listen(sock, options.kernel_backlog); + try std.posix.listen(sock, @as(c_int, @intCast(options.kernel_backlog))); @@ - try std.posix.listen(sock, options.kernel_backlog); + try std.posix.listen(sock, @as(c_int, @intCast(options.kernel_backlog)));Also applies to: 359-361
370-376: Pass sockaddr, not the union; avoid @ptrCast.Use &addr.any with initPosix.
- try netConnect(rt, fd, .initPosix(@ptrCast(&addr))); + try netConnect(rt, fd, .initPosix(&addr.any));
399-411: addBuf always returns error; success path missing.This makes every write fail.
fn addBuf(buf: *xev.WriteBuffer, data: []const u8) !void { if (buf.vectors.len < buf.vectors.data.len) { buf.vectors.data[buf.vectors.len] = if (xev.backend == .iocp) .{ .buf = @constCast(data.ptr), .len = @intCast(data.len), } else .{ .base = data.ptr, .len = data.len, }; buf.vectors.len += 1; - } - return error.BufferFull; + return; + } + return error.BufferFull; }
442-455: Write vectors uninitialized; send reads garbage.Allocate vector storage before fillBuf.
pub fn netWrite(rt: *Runtime, fd: Handle, header: []const u8, data: []const []const u8, splat: usize) !usize { var splat_buf: [64]u8 = undefined; - var buf: xev.WriteBuffer = .{ .vectors = .{ .data = undefined, .len = 0 } }; + var vec_storage: [64]xev.WriteBuffer.Vector = undefined; // tune capacity + var buf: xev.WriteBuffer = .{ .vectors = .{ .data = &vec_storage, .len = 0 } }; fillBuf(&buf, header, data, splat, &splat_buf);
467-485: Avoid ABI-unsafe reinterpret casts when building Address.Assign the sockaddr value directly.
- const sockaddr = completion.op.accept.addr; - break :blk switch (sockaddr.family) { - std.posix.AF.INET => Address{ - .ip = .{ .in = @as(*const std.net.Ip4Address, @ptrCast(@alignCast(&sockaddr))).* }, - }, - std.posix.AF.INET6 => Address{ - .ip = .{ .in6 = @as(*const std.net.Ip6Address, @ptrCast(@alignCast(&sockaddr))).* }, - }, - std.posix.AF.UNIX => { - if (!std.net.has_unix_sockets) unreachable; - break :blk Address{ - .unix = .{ .un = @as(*const std.posix.sockaddr.un, @ptrCast(@alignCast(&sockaddr))).* }, - }; - }, - else => unreachable, - }; + const sockaddr = completion.op.accept.addr; + break :blk Address{ .any = sockaddr }; @@ - break :blk switch (remote_addr.family) { - std.posix.AF.INET => Address{ - .ip = .{ .in = @as(*const std.net.Ip4Address, @ptrCast(@alignCast(remote_addr))).* }, - }, - std.posix.AF.INET6 => Address{ - .ip = .{ .in6 = @as(*const std.net.Ip6Address, @ptrCast(@alignCast(remote_addr))).* }, - }, - else => unreachable, - }; + break :blk Address{ .any = remote_addr.* };Also applies to: 504-511
52-70: Union aliasing between sockaddr and Ip/Unix Address needs safety checks.If you keep extern unions, add comptime size/alignment asserts and consistently pass
&*.anyto syscalls. Alternatively, replace withstd.net.Addressto avoid aliasing pitfalls.comptime { std.debug.assert(@sizeOf(std.posix.sockaddr.storage) <= @sizeOf(IpAddress)); std.debug.assert(@alignOf(std.posix.sockaddr.storage) <= @alignOf(IpAddress)); std.debug.assert(@sizeOf(std.posix.sockaddr.storage) <= @sizeOf(Address)); }Also applies to: 129-149
🧹 Nitpick comments (4)
src/io/test/net.zig (1)
108-115: Pre‑unlink the Unix socket path to avoid bind(EADDRINUSE).If a prior crash leaves the path behind, bind can fail. Unlink before listen in addition to the deferred cleanup.
test "UnixAddress: listen/accept/connect/read/write" { if (builtin.os.tag == .windows) return error.SkipZigTest; const path = "/tmp/zio-test-socket"; - defer std.fs.deleteFileAbsolute(path) catch {}; + // Ensure stale path doesn't break bind() + std.fs.deleteFileAbsolute(path) catch {}; + defer std.fs.deleteFileAbsolute(path) catch {};src/io/file.zig (1)
62-81: Support seek from end (optional, but useful).seek(.end, …) returns Unsupported. Consider implementing file size lookup (fstat/GetFileSizeEx) so sequential I/O can reposition relative to EOF.
src/fs.zig (2)
23-27: Docs mention deinit(), but File has no deinit.Adjust return/cleanup docs to say “must be closed with close()”.
-/// A File instance that must be closed with `close()` and freed with `deinit()` +/// A File instance that must be closed with `close()`Also applies to: 46-51
27-34: runtime parameter is unused.Consider removing it from fs.openFile/createFile or thread it through if you plan to use it later.
Also applies to: 51-58
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
src/file.zig(0 hunks)src/fs.zig(6 hunks)src/io/file.zig(1 hunks)src/io/net.zig(1 hunks)src/io/test/net.zig(1 hunks)src/zio.zig(1 hunks)
💤 Files with no reviewable changes (1)
- src/file.zig
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-15T08:14:58.308Z
Learnt from: CR
PR: lalinsky/zio#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-15T08:14:58.308Z
Learning: To test Windows builds on Linux, run: zig build build-tests -Dtarget=x86_64-windows && wine zig-out/bin/test.exe
Applied to files:
src/fs.zig
🔇 Additional comments (3)
src/zio.zig (1)
17-17: Re‑export path update looks good.File now points to io/file.zig. No further issues.
src/fs.zig (2)
1-212: This review comment is not applicable to src/fs.zig.The file under review is a file system module (fs.zig) focused on opening and creating files using platform-specific APIs (CreateFileW on Windows, std.fs on Unix). It contains no epoll, dup/dup2, or accept4 operations—these are networking/I/O concerns, not file system concerns.
The codebase scan found a single CLOEXEC reference in src/io/net.zig:313 (socket flag setup), which is correct and expected for async I/O operations on Unix. The fs.zig implementation uses appropriate platform APIs (FILE_FLAG_OVERLAPPED on Windows, standard Unix file operations), with no relevant file descriptor manipulation patterns that require the verification requested.
Likely an incorrect or invalid review comment.
1-212: <!-- [scratchpad_update]
[task verify_tcp_usage - continuing]
Web search indicates the lalinsky/zio project description mentions TCP/UDP support, but the search results are about general Zig TCP examples and other projects, not specifically about tcp.zig in the lalinsky/zio repo.[observations]
- lalinsky/zio project description mentions "Network I/O, supports TCP/UDP sockets"
- Multiple general Zig TCP examples online but no specific tcp.zig reference
- The README.md in the output showed zio.TcpListener reference (line 87)
- Need to check if tcp.zig actually exists in the src directory
[analysis]
The web search didn't give me the current state of the zio repository regarding tcp.zig. Need to search the repository files directly to check if tcp.zig exists or if it was removed.[pending]
- Check if src/tcp.zig file exists
- Check if there are any remaining references in src/*.zig files
- Check if the README example is outdated
[actions]
Run filesystem search for tcp.zig and check src directory structure, check README.md content
[scratchpad_end] --><!-- [scratchpad_update]
[task verify_tcp_usage - continuing]
The web search didn't provide specific details about the zio repository file structure. Need to directly inspect the repository files using shell commands.[observations]
- README.md shows zio.TcpListener at line 87 in the original search output
- File under review (src/fs.zig) has only filesystem operations
- No tcp.zig import found in the ripgrep output from Zig files
[analysis]
The file under review is src/fs.zig which contains only filesystem operations. The review comment is asking about remaining TCP/TcpListener usages. The ripgrep search found:
- Rust benchmarks using Tokio (external library)
- README.md with zio.TcpListener reference
Since there are no TCP references in the file being reviewed (src/fs.zig), I need to determine:
- Is the README.md outdated?
- Was tcp.zig removed?
- What is the context of this code review?
[pending]
- Check actual structure of src directory to see if tcp.zig exists
- Check if README.md needs updating
[actions]
Use shell to list src directory and check for tcp.zig file existence
[scratchpad_end] --><!-- [scratchpad_update]
[task verify_tcp_usage - continuing]
Web search without results. Need to directly query the repository using shell commands to determine if tcp.zig exists and what's in src directory.[observations]
- No results from specific site search for tcp.zig
- The review comment asks for "Where are TcpStream/TcpListener still used" and "Report stragglers"
- The ripgrep search found only:
- Rust benchmarks (tokio::net types)
- README.md line 87 with zio.TcpListener reference
[analysis]
The file under review (src/fs.zig) is purely file I/O operations with no TCP code. The review comment appears to be asking for a verification of where TCP functionality remains after removal/refactoring. The ripgrep search is the source data - need to analyze what it actually tells us.[pending]
- Examine if README needs updating (obsolete zio.TcpListener reference)
- Determine if this review comment is misdirected (for fs.zig file which has no TCP code)
[actions]
Use shell to check README.md content and verify if zio.TcpListener reference is from an outdated example in documentation
[scratchpad_end] -->Based on the ripgrep script results provided, the analysis is clear:
The review comment is checking for remaining TCP/TcpListener usage after apparent removal or refactoring.
Looking at the output:
- Rust benchmarks (
benchmarks/echo_server.rsandbenchmarks/echo_server_multi.rs) use Tokio's TcpListener/TcpStream—these are external dependencies and not related to the zio project's own TCP module.- README.md (line 87) contains a reference to
zio.TcpListenerin example code, suggesting there may be outdated documentation.- No Zig source files contain imports of
"tcp.zig"or usage of zio's TcpStream/TcpListener.The file under review (
src/fs.zig) contains only file system operations and is unrelated to TCP functionality.
The README.md example at line 87 is likely outdated documentation that references zio.TcpListener, which no longer exists in the src directory.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (9)
src/io/test/net.zig (1)
41-49: IPv6 case added for parseIpAndPort.The bracketed “[::1]:8080” path is now exercised. Thanks for addressing this.
src/io/net.zig (8)
7-7: Windows socket handle type; WSASocketW namespace.Use SOCKET for IOCP, not HANDLE; call WSASocketW from ws2_32. This avoids UB and ptr‑casts later.
Apply:
-const Handle = if (xev.backend == .iocp) std.os.windows.HANDLE else std.posix.socket_t; +const Handle = if (xev.backend == .iocp) std.os.windows.ws2_32.SOCKET else std.posix.socket_t; fn createStreamSocket(family: std.posix.sa_family_t) !Handle { if (builtin.os.tag == .windows) { - return try std.os.windows.WSASocketW(family, std.posix.SOCK.STREAM, 0, null, 0, std.os.windows.ws2_32.WSA_FLAG_OVERLAPPED); + return try std.os.windows.ws2_32.WSASocketW( + family, + std.posix.SOCK.STREAM, + 0, + null, + 0, + std.os.windows.ws2_32.WSA_FLAG_OVERLAPPED, + ); } else {Also applies to: 309-312
323-324: Drop unsafe HANDLE→SOCKET ptr casts.Once Handle is SOCKET on IOCP, pass fd directly.
- const sock = if (xev.backend == .iocp) @as(std.os.windows.ws2_32.SOCKET, @ptrCast(fd)) else fd; + const sock = fd;(Apply in both places.)
Also applies to: 352-353
335-337: Cast backlog to c_int for listen().Avoid signature mismatch and UB where c_int != u31.
- try std.posix.listen(sock, options.kernel_backlog); + try std.posix.listen(sock, @as(c_int, @intCast(options.kernel_backlog)));(Apply in both places.)
Also applies to: 359-361
374-375: Unsafe @ptrCast in netConnectIp; pass sockaddr.Send &addr.any to .initPosix.
- try netConnect(rt, fd, .initPosix(@ptrCast(&addr))); + try netConnect(rt, fd, .initPosix(&addr.any));
399-411: addBuf() always returns error (logic bug).Add success return after appending.
if (buf.vectors.len < buf.vectors.data.len) { buf.vectors.data[buf.vectors.len] = if (xev.backend == .iocp) .{ .buf = @constCast(data.ptr), .len = @intCast(data.len), } else .{ .base = data.ptr, .len = data.len, }; buf.vectors.len += 1; - } - return error.BufferFull; + return; + } + return error.BufferFull;
442-446: Write vectors storage is undefined; send will read garbage.Provide actual storage for iovecs/WSABUF.
pub fn netWrite(rt: *Runtime, fd: Handle, header: []const u8, data: []const []const u8, splat: usize) !usize { var splat_buf: [64]u8 = undefined; - var buf: xev.WriteBuffer = .{ .vectors = .{ .data = undefined, .len = 0 } }; + var vec_storage: [64]xev.WriteBuffer.Vector = undefined; // tune if needed + var buf: xev.WriteBuffer = .{ .vectors = .{ .data = &vec_storage, .len = 0 } }; fillBuf(&buf, header, data, splat, &splat_buf);
467-485: ABI‑unsafe addr casts in accept(); assign sockaddr directly.Populate Address.any instead of reinterpret casting to Ip4/6/un.
- const sockaddr = completion.op.accept.addr; - break :blk switch (sockaddr.family) { - std.posix.AF.INET => Address{ - .ip = .{ .in = @as(*const std.net.Ip4Address, @ptrCast(@alignCast(&sockaddr))).* }, - }, - std.posix.AF.INET6 => Address{ - .ip = .{ .in6 = @as(*const std.net.Ip6Address, @ptrCast(@alignCast(&sockaddr))).* }, - }, - std.posix.AF.UNIX => { - if (!std.net.has_unix_sockets) unreachable; - break :blk Address{ - .unix = .{ .un = @as(*const std.posix.sockaddr.un, @ptrCast(@alignCast(&sockaddr))).* }, - }; - }, - else => unreachable, - }; + const sockaddr = completion.op.accept.addr; + break :blk Address{ .any = sockaddr }; @@ - break :blk switch (remote_addr.family) { - std.posix.AF.INET => Address{ - .ip = .{ .in = @as(*const std.net.Ip4Address, @ptrCast(@alignCast(remote_addr))).* }, - }, - std.posix.AF.INET6 => Address{ - .ip = .{ .in6 = @as(*const std.net.Ip6Address, @ptrCast(@alignCast(remote_addr))).* }, - }, - else => unreachable, - }; + break :blk Address{ .any = remote_addr.* };Also applies to: 504-512
13-33: Union overlay risk between sockaddr and Ip/Unix types.**This relies on layout aliasing. Either switch to std.net.Address or add comptime size/alignment asserts and consistently drive syscalls from .any.
Suggested guard:
comptime { std.debug.assert(@sizeOf(std.posix.sockaddr) <= @sizeOf(IpAddress)); std.debug.assert(@alignOf(std.posix.sockaddr) <= @alignOf(IpAddress)); std.debug.assert(@sizeOf(std.posix.sockaddr) <= @sizeOf(Address)); std.debug.assert(@alignOf(std.posix.sockaddr) <= @alignOf(Address)); }Also applies to: 129-149
🧹 Nitpick comments (6)
src/fs.zig (2)
27-34: Docs drift: deinit mention and runtime param.
- The comment says “must be closed with close() and freed with deinit()” but File has no deinit(). Update to just “close(rt)”.
- Note that openFile/createFile ignore runtime (kept for API symmetry). Clarify in docs to avoid confusion.
158-166: Clarify ownership when wrapping std.fs.File.File.init(std_file) consumes the handle; the std_file must not be closed separately. Add a brief note to prevent double‑close mistakes.
Also applies to: 174-176
src/io/test/net.zig (1)
69-73: Consider TaskGroup for join symmetry.Replace manual join of two tasks with a TaskGroup to simplify orchestration.
src/io/file.zig (2)
19-23: Explicitly document ownership in init().State that File.init(std_file) takes ownership of std_file.handle.
74-77: Seek from end not supported.Optional: implement via current file size (std.fs.File.stat) or document limitation prominently.
src/io/net.zig (1)
534-556: Shutdown/close path: confirm non‑blocking behavior across backends.Are shutdown/close internally non‑blocking for epoll/kqueue (no threadpool)? If any backend can block, route via a dedicated threadpool or document guarantees.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
src/file.zig(0 hunks)src/fs.zig(6 hunks)src/io/file.zig(1 hunks)src/io/net.zig(1 hunks)src/io/test/net.zig(1 hunks)src/zio.zig(1 hunks)
💤 Files with no reviewable changes (1)
- src/file.zig
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-15T08:14:58.308Z
Learnt from: CR
PR: lalinsky/zio#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-15T08:14:58.308Z
Learning: To test Windows builds on Linux, run: zig build build-tests -Dtarget=x86_64-windows && wine zig-out/bin/test.exe
Applied to files:
src/fs.zig
🔇 Additional comments (7)
src/zio.zig (2)
17-17: Re-export path change looks good.File now points to io/file.zig.File; public surface preserved.
17-17: Migration audit complete—no remaining legacy TCP API usage.Verification confirms zero TcpStream, TcpListener, or tcp.zig imports in the main source tree. Only TCP references are in the vendored libxev dependency (external) and example programs (expected). The migration is finished.
src/fs.zig (1)
194-196: Nice end‑to‑end fs test.Covers write/read/close on the async API; good.
Also applies to: 202-205
src/io/test/net.zig (1)
51-55: Windows skip for Unix sockets.Using error.SkipZigTest cleanly disables Unix socket tests on Windows.
Also applies to: 108-115
src/io/file.zig (1)
148-160: close() shielding matches std pattern.Ignoring close errors and shielding is appropriate here.
src/io/net.zig (2)
457-465: Epoll accept + dup semantics.Please document how accepted fds are integrated w.r.t. dup/dup2 across epoll backend (especially if handing sockets to different tasks). Any required FD flags set before returning?
558-560: Verify Windows test execution manually.The codebase contains SOCKET changes in
src/io/net.zig(conditional Windows handle types at lines 7, 323, 352) and a validbuild-testscross-compilation target exists inbuild.zig. The provided script references correct learnings, but Windows test validation cannot be performed in this sandbox environment. Manually run the test command on a system with zig and wine available, or configure CI/CD to validate Windows targets before merging.
The accept operation used posix.sockaddr (16 bytes) to store peer addresses, but IPv6 addresses require sockaddr_in6 (28 bytes). The kernel respects the addr_size parameter, so IPv6 addresses were truncated to 16 bytes, resulting in corrupted address data. Changes: - Change accept.addr from sockaddr to sockaddr.storage (128 bytes) - Update addr_size to match sockaddr.storage size - Add @ptrCast when passing to system calls expecting *sockaddr - Update Completion size tests to reflect larger struct size - io_uring: 152 -> 184 bytes (+32) - epoll: 208 -> 240 bytes (+32) Affects: io_uring, epoll, and kqueue backends on Linux/BSD/macOS
Fixed two places where IPv6 addresses were truncated: 1. netListenIp getsockname: Used IpAddress union (16 bytes) instead of sockaddr.storage (128 bytes), causing IPv6 addresses to be truncated when retrieving the actual bound address after listen(). 2. netAccept: Simplified address extraction from libxev completions now that they use sockaddr.storage. Changes: - Add Address.fromStorage() and Address.fromStorageIp() helper functions to safely convert sockaddr.storage to Address/IpAddress types - Use sockaddr.storage in netListenIp for getsockname - Simplify netAccept to use the new helper functions - Add IPv6 listen/accept/connect test (skips if IPv6 unavailable) The corrupted addresses like [::aaaa:aaaa:aaaa:aaaa] were caused by reading uninitialized memory beyond the truncated address data.
The log was printed both on EndOfStream error and after the loop, causing redundant output. Now only logs once after the loop exits.
Once we receive error.Canceled and initiate IO cancellation via cancelIo(), we should wait uninterrupted for the IO operation to complete. This adds cancellation shielding so that subsequent yields in the wait loop don't throw error.Canceled again. Changes: - Add shielded flag to track if we've started shielding - Use defer if (shielded) rt.endShield() to ensure cleanup - Call rt.beginShield() when handling first error.Canceled - This shields all subsequent yields until the function exits This prevents unnecessary noise from repeated cancellation signals while waiting for IO to finish canceling.
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 (1)
vendor/libxev/src/backend/kqueue.zig (1)
1669-1674: recvfrom uses sockaddr (16B) — too small for IPv6; use sockaddr.storage.Current addr/len truncates IPv6 peer addresses and risks UB.
Apply:
@@ - recvfrom: struct { - fd: posix.fd_t, - buffer: ReadBuffer, - addr: posix.sockaddr = undefined, - addr_size: posix.socklen_t = @sizeOf(posix.sockaddr), - }, + recvfrom: struct { + fd: posix.fd_t, + buffer: ReadBuffer, + addr: posix.sockaddr.storage = undefined, + addr_size: posix.socklen_t = @sizeOf(posix.sockaddr.storage), + },And update perform paths:
@@ - } else posix.recvfrom(op.fd, v, 0, &op.addr, &op.addr_size), + } else posix.recvfrom(op.fd, v, 0, @ptrCast(&op.addr), &op.addr_size), @@ - .name = @ptrCast(&op.addr), + .name = @ptrCast(&op.addr),This mirrors your accept path and matches epoll/io_uring.
Also applies to: 1308-1336
♻️ Duplicate comments (5)
src/io/net.zig (5)
7-7: Windows type mismatch: use SOCKET, drop ptr casts.WSASocketW returns SOCKET; using HANDLE and ptr-casting is unsafe and breaks IOCP paths. Switch Handle to SOCKET and remove the casts.
-const Handle = if (xev.backend == .iocp) std.os.windows.HANDLE else std.posix.socket_t; +const Handle = if (xev.backend == .iocp) std.os.windows.ws2_32.SOCKET else std.posix.socket_t; @@ - if (builtin.os.tag == .windows) { - return try std.os.windows.WSASocketW(family, std.posix.SOCK.STREAM, 0, null, 0, std.os.windows.ws2_32.WSA_FLAG_OVERLAPPED); + if (builtin.os.tag == .windows) { + return try std.os.windows.ws2_32.WSASocketW( + family, + std.posix.SOCK.STREAM, + 0, + null, + 0, + std.os.windows.ws2_32.WSA_FLAG_OVERLAPPED, + ); } else { var flags: u32 = std.posix.SOCK.STREAM | std.posix.SOCK.CLOEXEC; if (xev.backend != .io_uring) flags |= std.posix.SOCK.NONBLOCK; return try std.posix.socket(family, flags, 0); } @@ - const sock = if (xev.backend == .iocp) @as(std.os.windows.ws2_32.SOCKET, @ptrCast(fd)) else fd; + const sock = fd; @@ - const sock = if (xev.backend == .iocp) @as(std.os.windows.ws2_32.SOCKET, @ptrCast(fd)) else fd; + const sock = fd;Also applies to: 334-342, 348-349, 377-378
360-362: Cast backlog to c_int when calling listen().listen expects c_int; kernel_backlog is u31.
- try std.posix.listen(sock, options.kernel_backlog); + try std.posix.listen(sock, @as(c_int, @intCast(options.kernel_backlog))); @@ - try std.posix.listen(sock, options.kernel_backlog); + try std.posix.listen(sock, @as(c_int, @intCast(options.kernel_backlog)));Also applies to: 384-386
399-401: Unsafe cast to .initPosix; pass &addr.any.Do not @ptrCast the union; use the sockaddr field.
- try netConnect(rt, fd, .initPosix(@ptrCast(&addr))); + try netConnect(rt, fd, .initPosix(&addr.any));
424-436: addBuf() always returns error; success path missing.This makes every write path fail. Return on success.
fn addBuf(buf: *xev.WriteBuffer, data: []const u8) !void { if (buf.vectors.len < buf.vectors.data.len) { buf.vectors.data[buf.vectors.len] = if (xev.backend == .iocp) .{ .buf = @constCast(data.ptr), .len = @intCast(data.len), } else .{ .base = data.ptr, .len = data.len, }; buf.vectors.len += 1; + return; } return error.BufferFull; }
221-229: Guard against zero-progress in writeAll().Avoid infinite loop when write returns 0.
while (offset < buf.len) { const n = try self.write(rt, buf[offset..]); + if (n == 0) return error.UnexpectedWriteZero; offset += n; }
🧹 Nitpick comments (1)
src/io/net.zig (1)
129-174: Optional: reduce aliasing risk in Address.fromStorage{Ip}.Directly reinterpreting storage as Ip4/6 is fragile. Using std.net.Address.initPosix() would be safer and consistent with the IOCP fix.
Example:
- fn fromStorageIp(storage: *const std.posix.sockaddr.storage) IpAddress { - const sockaddr: *const std.posix.sockaddr = @ptrCast(storage); - return switch (sockaddr.family) { - std.posix.AF.INET => IpAddress{ .in = @as(*const std.net.Ip4Address, @ptrCast(@alignCast(sockaddr))).* }, - std.posix.AF.INET6 => IpAddress{ .in6 = @as(*const std.net.Ip6Address, @ptrCast(@alignCast(sockaddr))).* }, - else => unreachable, - }; - } + fn fromStorageIp(storage: *const std.posix.sockaddr.storage) IpAddress { + const std_addr = std.net.Address.initPosix(@ptrCast(@alignCast(storage))); + return IpAddress.fromStd(std_addr); + }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
src/io/net.zig(1 hunks)src/io/test/net.zig(1 hunks)vendor/libxev/src/backend/epoll.zig(5 hunks)vendor/libxev/src/backend/io_uring.zig(5 hunks)vendor/libxev/src/backend/kqueue.zig(4 hunks)
🧰 Additional context used
🪛 GitHub Actions: CI
src/io/net.zig
[error] 513-513: Zig compiler error: @ptrCast increases pointer alignment in 'src/io/net.zig:513'. Use @aligncast to assert pointer alignment. Command failed: zig build examples.
🔇 Additional comments (3)
src/io/test/net.zig (1)
51-55: Tests look solid; Windows guard and IPv6 paths covered.No issues spotted; good end-to-end listen/accept/connect/read/write coverage.
Also applies to: 108-116, 117-128
src/io/net.zig (2)
559-561: Legacy type removal verified successfully.Searched the codebase for TcpStream/TcpListener references. Results: no Zig source files contain these legacy types. The only match is a documentation example in README.md:87, which is acceptable. The test file at src/io/net.zig correctly imports test/net.zig. Removal is complete.
492-514: Review comment is incorrect; proposed fix references non-existent function.The review proposes using
std.net.Address.initPosix(), but this function does not exist in the Zig standard library or the codebase. The current code at line 513 already correctly usesAddress.fromStorage(@ptrCast(remote_addr)), which internally applies proper alignment handling viafromStorageIp(line 136-142). The existing helper functions use@ptrCast(@alignCast(...))to safely handle alignment concerns, so no changes are required.Likely an incorrect or invalid review comment.
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/net.zig (1)
27-30: Doc comment drift.The comment still references “AddressList.deinit()”. If returning std.net.AddressList, say “Call std.net.AddressList.deinit()”.
vendor/libxev/src/backend/kqueue.zig (1)
1307-1316: Recvfrom call-sites: cast storage to sockaddr for syscall ABI correctnessFollow-up to the storage change: ensure calls use @ptrCast(&op.addr) consistently to match *sockaddr.
Apply:
- } else posix.recvfrom(op.fd, v, 0, &op.addr, &op.addr_size), - .array => |*v| posix.recvfrom(op.fd, v, 0, &op.addr, &op.addr_size), + } else posix.recvfrom(op.fd, v, 0, @ptrCast(&op.addr), &op.addr_size), + .array => |*v| posix.recvfrom(op.fd, v, 0, @ptrCast(&op.addr), &op.addr_size),Also applies to: 1316-1321
♻️ Duplicate comments (1)
src/net.zig (1)
35-43: Return type mismatch with std.net.getAddressList result.std.net.getAddressList returns a value, but the signature returns a pointer, making this uncompilable.
-pub fn getAddressList( +pub fn getAddressList( runtime: *Runtime, allocator: std.mem.Allocator, name: []const u8, port: u16, -) !*std.net.AddressList { +) !std.net.AddressList { var task = try runtime.spawnBlocking( std.net.getAddressList, .{ allocator, name, port }, ); defer task.deinit(); - return try task.join(); + return try task.join(); }No call-site changes needed; list.deinit() still works on a value receiver.
🧹 Nitpick comments (9)
src/io/test/net.zig (4)
51-55: Use a unique temp path for the Unix socket to avoid cross-test collisions.Hardcoding "/tmp/socket" can clash under parallel runs. Prefer a per-test temp dir + file.
- const addr = try UnixAddress.init("/tmp/socket"); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const path = try std.fs.path.join(std.testing.allocator, &.{ tmp.dir_path.?, "socket" }); + defer std.testing.allocator.free(path); + const addr = try UnixAddress.init(path);
57-73: Join orchestration: replace ad-hoc joins with TaskGroup (noted TODO).Using a TaskGroup will simplify fan-out/fan-in and ensure both tasks are awaited even on early errors.
I can sketch a minimal TaskGroup-based variant if helpful.
102-106: Drop thread pool here; it isn’t needed for this test.No DNS/blocking work occurs in checkListen. Use default runtime options to reduce overhead and exercise the non-threadpool path.
- var runtime = try Runtime.init(std.testing.allocator, .{ .thread_pool = .{ .enabled = true } }); + var runtime = try Runtime.init(std.testing.allocator, .{});
108-115: Avoid fixed socket path to prevent leaks/collisions.“/tmp/zio-test-socket” can linger or collide; reuse the temp-dir pattern from above.
- const path = "/tmp/zio-test-socket"; - defer std.fs.deleteFileAbsolute(path) catch {}; - - const addr = try UnixAddress.init(path); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const sock = try std.fs.path.join(std.testing.allocator, &.{ tmp.dir_path.?, "sock" }); + defer std.testing.allocator.free(sock); + const addr = try UnixAddress.init(sock);src/net.zig (3)
13-25: Unused IpAddressList type.Defined but unused; either wire getAddressList to return this wrapper or remove it to avoid confusion.
51-63: Try all addresses robustly; broaden retryable errors and simplify flow.Current pattern handles only ConnectionRefused. Add common transient errors and avoid “return … catch … continue” for clarity.
- for (list.addrs) |addr| { - return IpAddress.fromStd(addr).connect(rt) catch |err| switch (err) { - error.ConnectionRefused => { - continue; - }, - else => return err, - }; - } - return error.ConnectionRefused; + var last_err: anyerror = error.ConnectionRefused; + for (list.addrs) |addr| { + const ip = IpAddress.fromStd(addr); + const stream = ip.connect(rt) catch |err| switch (err) { + error.ConnectionRefused, + error.AddressNotAvailable, + error.NetworkUnreachable, + error.ConnectionTimedOut, + => { + last_err = err; + continue; + }, + else => return err, + }; + return stream; + } + return last_err;
170-180: Trim debug prints in tests.The std.debug.print lines add noise to test output; consider removing unless diagnosing flakes.
- std.debug.print("Server listening on port {}\n", .{server.address.ip.getPort()}); + // debug: server.address.ip.getPort() ... - std.debug.print("Client connecting to port {}\n", .{port}); + // debug: portAlso applies to: 193-206
vendor/libxev/src/backend/kqueue.zig (2)
667-689: Deduplicate and normalize: make timer_next call timer_next_ns and preserve timespec invariantsCurrent code duplicates math and may leave nsec ≥ 1e9. Reuse the ns helper and normalize via that path.
Apply:
-pub fn timer_next(self: Loop, next_ms: u64) posix.timespec { - // Get the timestamp of the absolute time that we'll execute this timer. - // There are lots of failure scenarios here in math. If we see any - // of them we just use the maximum value. - const max: posix.timespec = .{ - .sec = std.math.maxInt(isize), - .nsec = std.math.maxInt(isize), - }; - - const next_s = std.math.cast(isize, next_ms / std.time.ms_per_s) orelse - return max; - const next_ns = std.math.cast( - isize, - (next_ms % std.time.ms_per_s) * std.time.ns_per_ms, - ) orelse return max; - - return .{ - .sec = std.math.add(isize, self.cached_now.sec, next_s) catch - return max, - .nsec = std.math.add(isize, self.cached_now.nsec, next_ns) catch - return max, - }; -} +pub fn timer_next(self: Loop, next_ms: u64) posix.timespec { + const max: posix.timespec = .{ + .sec = std.math.maxInt(isize), + .nsec = std.math.maxInt(isize), + }; + const delta_ns = std.math.mul(u64, next_ms, std.time.ns_per_ms) catch return max; + return self.timer_next_ns(delta_ns); +}
691-712: Normalize carry in timer_next_ns to keep nsec < 1e9 and avoid overflow surprisesAdd carry handling from nsec into sec with saturating checks.
Apply:
pub fn timer_next_ns(self: Loop, next_ns: u64) posix.timespec { @@ - const next_s = std.math.cast(isize, next_ns / std.time.ns_per_s) orelse - return max; - const next_nsec = std.math.cast(isize, next_ns % std.time.ns_per_s) orelse - return max; - - return .{ - .sec = std.math.add(isize, self.cached_now.sec, next_s) catch - return max, - .nsec = std.math.add(isize, self.cached_now.nsec, next_nsec) catch - return max, - }; + const next_s = std.math.cast(isize, next_ns / std.time.ns_per_s) orelse return max; + const next_nsec = std.math.cast(isize, next_ns % std.time.ns_per_s) orelse return max; + + var sec = std.math.add(isize, self.cached_now.sec, next_s) catch return max; + var nsec = std.math.add(isize, self.cached_now.nsec, next_nsec) catch return max; + if (nsec >= std.time.ns_per_s) { + const carry: isize = @intCast(nsec / std.time.ns_per_s); + sec = std.math.add(isize, sec, carry) catch return max; + nsec = @intCast(nsec % std.time.ns_per_s); + } + return .{ .sec = sec, .nsec = nsec }; }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
examples/tcp_echo_server.zig(2 hunks)src/io/base.zig(1 hunks)src/io/test/net.zig(1 hunks)src/net.zig(5 hunks)vendor/libxev/src/backend/kqueue.zig(5 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- src/io/base.zig
- examples/tcp_echo_server.zig
🔇 Additional comments (4)
src/net.zig (2)
67-69: tcpConnectToAddress looks good.
6-11: No lingering TcpStream/TcpListener or deprecated alias usages detected.vendor/libxev/src/backend/kqueue.zig (2)
1166-1176: Accept: ptrCast to sockaddr from sockaddr.storage is correctThe switch to posix.sockaddr.storage and passing @ptrCast(&op.addr) to accept(2) matches Zig’s posix API expectations. LGTM.
1476-1483: No action needed: PERM→error.Unexpected is consistent
All other backends treat an EPERM on shutdown as “unexpected” (epoll and IOCP return the raw posix.shutdown error, io_uring and wasi_poll fall back toposix.unexpectedErrno(err)), so mapping.PERMtoerror.Unexpectedin kqueue aligns with existing semantics.
| accept: struct { | ||
| socket: posix.socket_t, | ||
| addr: posix.sockaddr = undefined, | ||
| addr_size: posix.socklen_t = @sizeOf(posix.sockaddr), | ||
| addr: posix.sockaddr.storage = undefined, | ||
| addr_size: posix.socklen_t = @sizeOf(posix.sockaddr.storage), | ||
| flags: u32 = posix.SOCK.CLOEXEC, | ||
| }, | ||
|
|
There was a problem hiding this comment.
Accept uses sockaddr.storage (good); align recvfrom to storage for full address support
Accept now uses posix.sockaddr.storage, but recvfrom still uses posix.sockaddr with @sizeof(posix.sockaddr). That may truncate IPv6/Unix addresses. Recommend moving recvfrom to sockaddr.storage and updating call sites.
Apply:
@@
- recvfrom: struct {
+ recvfrom: struct {
fd: posix.fd_t,
buffer: ReadBuffer,
- addr: posix.sockaddr = undefined,
- addr_size: posix.socklen_t = @sizeOf(posix.sockaddr),
+ addr: posix.sockaddr.storage = undefined,
+ addr_size: posix.socklen_t = @sizeOf(posix.sockaddr.storage),
},And update perform recvfrom calls (slice/array branches) to pass a sockaddr pointer:
@@
- } else posix.recvfrom(op.fd, v, 0, &op.addr, &op.addr_size),
- .array => |*v| posix.recvfrom(op.fd, v, 0, &op.addr, &op.addr_size),
+ } else posix.recvfrom(op.fd, v, 0, @ptrCast(&op.addr), &op.addr_size),
+ .array => |*v| posix.recvfrom(op.fd, v, 0, @ptrCast(&op.addr), &op.addr_size),The vectored recvmsg branch already uses @ptrCast(&op.addr).
Committable suggestion skipped: line range outside the PR's diff.
Refactored address conversion functions to use byte slices and memcpy instead of pointer casts to avoid alignment panics on Windows. The GetAcceptExSockaddrs function on Windows can return pointers with alignment 2, but sockaddr.storage requires alignment 8. Also added Unix socket availability check in UnixAddress.format() since Windows doesn't support Unix sockets.
Summary by CodeRabbit
New Features
Refactor
Removals
Tests