Skip to content

New zio.net API - #65

Merged
lalinsky merged 19 commits into
mainfrom
new-io
Oct 22, 2025
Merged

lalinsky merged 19 commits into
mainfrom
new-io

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 22, 2025 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Cross-platform networking primitives (addressing, connect/listen/accept), buffered stream reader/writer, async I/O helpers, and a new file I/O implementation with streaming interfaces and nanosecond-capable timers.
  • Refactor

    • Examples and demos updated to use unified networking and runtime/task APIs; runtime/executor access streamlined.
  • Removals

    • Legacy TCP module, old file implementation, and the mini-redis example removed.
  • Tests

    • Added integration tests for networking and file I/O (end-to-end connect/listen/read/write).

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

coderabbitai Bot commented Oct 22, 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 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 @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 5eeaef7 and 5fff972.

📒 Files selected for processing (1)
  • src/io/net.zig (1 hunks)

Walkthrough

Large refactor replacing legacy TCP/file modules with a new async I/O layer under src/io/*, introducing IpAddress/Stream/Server, buffered Reader/Writer, runtime I/O primitives, libxev timer APIs, updated examples/benchmarks, and updated runtime/executor accessors. (49 words)

Changes

Cohort / File(s) Summary
I/O core helpers
src/io/base.zig
Add cancelIo, waitForIo, runIo, parametric IoOperation, and sleep — typed runtime-integrated async I/O primitives that manage completions and task resumption.
Network API & tests
src/io/net.zig, src/io/test/net.zig
Add IpAddress/UnixAddress/Address, Server, Stream with listen/connect/accept/read/write/shutdown/close, buffered Reader/Writer, backend netRead/netWrite/netAccept/netConnect implementations and tests exercising listen/accept/connect/read/write.
File I/O relocation
src/io/file.zig, src/file.zig, src/fs.zig
Move File abstraction into src/io/file.zig (init/initFd, read/write/seek/pread/pwrite/readBuf/writeBuf, close, Reader/Writer); delete old src/file.zig; update src/fs.zig call sites to new constructors/signatures.
Public exports / net shim
src/net.zig, src/zio.zig
Remove old TcpStream/TcpListener exports; re-export new io/net types (IpAddress, UnixAddress, Address, Server, Stream); update File export to io/file.zig; add IpAddressList.
Remove legacy TCP
src/tcp.zig
Delete legacy TcpListener/TcpStream, associated Reader/Writer aliases, helper functions and all tests.
Benchmarks & examples
benchmarks/echo_server.zig, examples/tcp_client.zig, examples/tcp_echo_server.zig, examples/tls_demo.zig
Migrate examples/benchmark to IpAddress.parseIp4 / addr.connect / addr.listen, use Stream with buffered Reader/Writer (1KiB buffers), explicit flush/shutdown, and update ResetEvent/task signatures.
Removed example & build update
examples/mini_redis.zig, build.zig
Remove examples/mini_redis.zig and drop its example entry from build.zig.
Runtime / executor
src/runtime.zig
Add getCurrentExecutor() and Executor.getCurrentTask(); change current-task access patterns and remove prior Runtime.getCurrent.
libxev backend APIs
vendor/libxev/src/backend/*.zig
Expose timer_next as public and add timer_next_ns across backends, change accept address storage to sockaddr.storage with @ptrCast(&op.addr), and update completion-size expectations.
New tests / updated tests
src/io/test/net.zig, updated test call sites
Add network tests for new io/net API; update other tests to align with io/net and io/file API 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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰 I hopped through sockets, parsed each byte,
Built streams and buffers through the night,
Timers hum in nanosecond tune,
Readers nibble, writers swoon,
Accept, flush, close — I munch a carrot bright 🥕

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly and concisely summarizes the primary change of the PR, namely introducing the new zio.net API, making it easy for reviewers to understand the focus of the changeset.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

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

❤️ Share

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

@lalinsky

Copy link
Copy Markdown
Owner Author

@claude I don't think we need threadpool for shutdown and close

@claude

claude Bot commented Oct 22, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


Analysis: Threadpool not needed for shutdown and close

  • Read repository guidelines (CLAUDE.md)
  • Examine new I/O implementation files
  • Analyze libxev backend implementations
  • Verify if close/shutdown are truly non-blocking
  • Make final recommendation

Findings

You're absolutely right! Both close() and shutdown() are non-blocking syscalls that return immediately:

In vendor/libxev/src/backend/epoll.zig:

  • Line 773-775: shutdown directly calls posix.shutdown() without checking threadpool flag
  • Line 761-771: close checks threadpool flag but that's only needed for special cases (dup handling)

In vendor/libxev/src/backend/kqueue.zig:

  • Line 828-836: shutdown directly calls posix.system.shutdown()
  • Line 838-841: close directly calls posix.close()

Neither syscall actually blocks - they're synchronous operations that complete immediately. The threadpool is unnecessary overhead here.

Recommendation

Remove the completion.flags.threadpool = true lines from:

  1. src/io/net.zig:495 in netShutdown()
  2. src/io/net.zig:510 in netClose()

Should I go ahead and make these changes?


Branch: new-io | Job Run

@lalinsky

Copy link
Copy Markdown
Owner Author

@claude help me understand dup handling in the epoll backend

@claude

claude Bot commented Oct 22, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


Understanding dup handling in epoll backend

  • Read epoll backend implementation
  • Understand dup handling mechanism
  • Explain the purpose and implementation

The dup handling in the epoll backend is a workaround for a fundamental limitation of epoll.

The Problem

Epoll'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 Solution

When you need multiple concurrent operations on the same fd in epoll, libxev uses dup() to create duplicate file descriptors:

  1. Setting the flag (vendor/libxev/src/watcher/stream.zig:598):

    .epoll => {
        if (options.threadpool)
            c.flags.threadpool = true
        else
            c.flags.dup = true;  // Use dup instead of threadpool
    }
  2. Duplicating the fd (vendor/libxev/src/backend/epoll.zig:1117-1124):

    fn fd_maybe_dup(self: *Completion) error{DupFailed}!posix.fd_t {
        const old_fd = self.fd().?;
        if (!self.flags.dup) return old_fd;
        if (self.flags.dup_fd > 0) return self.flags.dup_fd;
        
        // Dup the fd and cache it
        self.flags.dup_fd = posix.dup(old_fd) catch return error.DupFailed;
        return self.flags.dup_fd;
    }
  3. Using the duped fd (vendor/libxev/src/backend/epoll.zig:468-469):

    // Get the correct fd (duped or original)
    const fd = if (c.flags.dup) c.flags.dup_fd else c.fd();
    const close_dup = c.flags.dup;
  4. Cleanup (vendor/libxev/src/backend/epoll.zig:486-488):

    if (close_dup) {
        posix.close(v);  // Close the duped fd
    }

Why This Matters

  • Each duplicate fd can be registered with epoll independently
  • When the operation completes, the duped fd is automatically closed
  • The original fd remains open and usable
  • This allows multiple concurrent epoll operations on the same underlying file descriptor

Example Use Case

If you want to do both a read and write on the same socket simultaneously:

  • Operation 1: Uses original fd
  • Operation 2: Uses dup(original_fd) → gets a new fd number pointing to the same socket
  • Both can now be registered with epoll separately
  • When Operation 2 completes, the duped fd is closed, but the socket itself stays open

Branch: new-io | Job Run

@lalinsky

Copy link
Copy Markdown
Owner Author

@claude if we only ever do one operation at a time, we don't need the fd duping, right?

@claude

claude Bot commented Oct 22, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


Analyzing fd duping requirement

  • Read repository guidelines
  • Examine new I/O implementation patterns
  • Analyze operation concurrency on file descriptors
  • Provide answer with code references

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 epoll

The 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 dup() the fd to get a new fd number pointing to the same underlying resource, so each operation can register independently.

Your code only does sequential operations

Looking at your I/O implementation in src/io/net.zig, all operations are sequential:

  • netRead() (line 338): Creates a completion, runs it, returns
  • netWrite() (line 390): Creates a completion, runs it, returns
  • netAccept() (line 405): Creates a completion, runs it, returns
  • netConnect() (line 475): Creates a completion, runs it, returns

Each function calls runIo() which uses waitForIo() (src/io/base.zig:22) that blocks until the operation completes (line 28-41).

There's no overlap - only one operation is active on an fd at a time.

The one place you use dup

Currently, you only set the dup flag in one place:

src/io/net.zig:412-414 in netAccept():

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.

Recommendation

You can safely remove the dup flag from netAccept() since:

  1. Your code never runs concurrent operations on the same fd
  2. Each operation completes before the next one starts
  3. The sequential pattern eliminates the need for the epoll workaround

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: new-io | Job Run

@lalinsky

Copy link
Copy Markdown
Owner Author

@claude remove both flags

@claude

claude Bot commented Oct 22, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


Removing unnecessary flags

  • Read current implementation in src/io/net.zig
  • Remove threadpool flags from netShutdown() and netClose()
  • Remove dup flag from netAccept()
  • Run tests and formatting with ./check.sh
  • Commit and push changes

Summary

Removed three unnecessary flags from src/io/net.zig:

  1. Threadpool flags from netShutdown() (src/io/net.zig:495) and netClose() (src/io/net.zig:510)

    • Both close() and shutdown() are non-blocking syscalls that return immediately
    • No need to offload them to the threadpool
  2. Dup flag from netAccept() (src/io/net.zig:412-414)

    • The dup mechanism works around epoll's limitation of only registering an fd once
    • Since operations are sequential (one at a time), there's no concurrent access
    • The workaround is unnecessary in this implementation

All tests passed successfully (110/110).


Branch: new-io | Job Run

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]>
@lalinsky

Copy link
Copy Markdown
Owner Author

@claude completely disable unix socket tests on Windows

And give me a report where do we still use TcpStream and TcpListener

@claude

claude Bot commented Oct 22, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


Disabling Unix socket tests on Windows and finding TcpStream/TcpListener usage

  • Read repository guidelines (CLAUDE.md)
  • Find unix socket tests in the codebase
  • Search for TcpStream/TcpListener usage
  • Disable unix socket tests on Windows
  • Run tests with ./check.sh
  • Commit and push changes
  • Provide usage report

Changes Made

Unix Socket Tests on Windows: Disabled both unix socket tests in src/io/test/net.zig by:

  • Adding const builtin = @import("builtin"); import
  • Replacing if (!std.net.has_unix_sockets) with if (builtin.os.tag == .windows)
  • Tests now completely skip compilation on Windows platform

TcpStream and TcpListener Usage Report

TcpStream Usage

Core Implementation (src/tcp.zig):

  • Line 161: pub const TcpStream = struct { - Main struct definition
  • Lines 169-217: connect() method implementation
  • Lines 225-421: Various I/O methods (read, write, readAll, writeAll, readVec, writeVec, shutdown, close, readBuf, writeBuf)
  • Lines 471-479: Reader/Writer interface implementations
  • Lines 498, 537, 585, 633, 731, 795: Used in test cases

Public API (src/zio.zig):

  • Line 22: pub const TcpStream = @import("tcp.zig").TcpStream; - Exported to users

Internal API (src/net.zig):

  • Line 4: Import for internal use
  • Lines 41, 60-61: tcpConnectToAddress() wrapper function

Examples:

  • examples/tls_demo.zig:12: var stream = try zio.TcpStream.connect(rt, addr);
  • examples/mini_redis.zig:390: Field in struct stream: zio.TcpStream
  • examples/mini_redis.zig:394: Function parameter

TcpListener Usage

Core Implementation (src/tcp.zig):

  • Line 47: pub const TcpListener = struct { - Main struct definition
  • Lines 50-111: Methods (init, bind, listen, accept, close)
  • Lines 19, 679, 770: Used in test cases

Public API (src/zio.zig):

  • Line 21: pub const TcpListener = @import("tcp.zig").TcpListener; - Exported to users

Internal API (src/net.zig):

  • Lines 121, 123: Used in tcpListenToAddress() wrapper
  • Lines 179, 181: Used in another internal function

Examples:

  • examples/mini_redis.zig:464: var listener = try zio.TcpListener.init(addr);

Documentation:

  • README.md:87: Usage example in README

External Files (Not Zig)

  • benchmarks/echo_server_multi.rs:3, 12, 60: Rust tokio TcpStream/TcpListener (comparison benchmarks)
  • benchmarks/echo_server.rs:3, 12, 60: Rust tokio TcpStream/TcpListener (comparison benchmarks)

Summary

Both TcpStream and TcpListener are still actively used throughout the codebase:

  • Core implementation: src/tcp.zig (main definitions and methods)
  • Public exports: src/zio.zig (library API)
  • Internal wrappers: src/net.zig (convenience functions)
  • User-facing: Examples, README documentation
  • Testing: Multiple test cases in tcp.zig
  • External: Rust benchmark files (for comparison, not migration targets)

All tests pass (110/110) on Linux.


Branch: new-io | Job Run

github-actions Bot and others added 3 commits October 22, 2025 16:16
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.
@lalinsky lalinsky changed the title New io New zio.net API Oct 22, 2025
@lalinsky
lalinsky marked this pull request as ready for review October 22, 2025 17:59

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

The 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 timespec

Same 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 kqueue

kqueue 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_verification only 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 print alias to silence warnings.
-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 by Stream.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. Verify timer_next expects 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

📥 Commits

Reviewing files that changed from the base of the PR and between 82e087a and 3f303fc.

📒 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_ns function correctly extends the timer API to support nanosecond granularity, paralleling the existing timer_next millisecond-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_next as public and add timer_next_ns for 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 the linux.kernel_timespec structure.

vendor/libxev/src/backend/wasi_poll.zig (1)

580-606: LGTM! Consistent nanosecond timer support for WASI backend.

The changes expose timer_next publicly and add timer_next_ns for 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: LGTM

Simple, 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 TcpStream or TcpListener across all .zig files. 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 .disarm are appropriate.

src/net.zig (2)

50-65: Host connect loop looks fine.

Retries on ConnectionRefused across 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 ResetEvent sync is solid.


57-67: Client round-trip and verification look good.

Buffered write/flush then readSliceAll and 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/.close ops 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 TcpStream or TcpListener across all Zig files. The new Server and Stream abstractions in src/io/net.zig properly replace the legacy API, and all imports are appropriate for the refactored implementation.

Comment thread examples/tcp_echo_server.zig Resolved
Comment thread src/io/base.zig
Comment on lines +18 to +42
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;
}
}

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

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.

Suggested change
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;
}
}

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

@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

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 errors

Optionally, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3f303fc and d3b6ad7.

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

Comment thread src/io/file.zig Resolved
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: 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 &buffer to 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]:8080 via 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 &*.any to syscalls. Alternatively, replace with std.net.Address to 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3f303fc and ae4ee0e.

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

  1. Rust benchmarks using Tokio (external library)
  2. 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:
    1. Rust benchmarks (tokio::net types)
    2. 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:

  1. Rust benchmarks (benchmarks/echo_server.rs and benchmarks/echo_server_multi.rs) use Tokio's TcpListener/TcpStream—these are external dependencies and not related to the zio project's own TCP module.
  2. README.md (line 87) contains a reference to zio.TcpListener in example code, suggesting there may be outdated documentation.
  3. 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.

Comment thread src/io/file.zig Resolved
Comment thread src/io/net.zig Resolved
Comment thread src/io/net.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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3f303fc and ae4ee0e.

📒 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 valid build-tests cross-compilation target exists in build.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.

@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 (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

📥 Commits

Reviewing files that changed from the base of the PR and between ae4ee0e and efda02b.

📒 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 uses Address.fromStorage(@ptrCast(remote_addr)), which internally applies proper alignment handling via fromStorageIp (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.

@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

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 correctness

Follow-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: port

Also 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 invariants

Current 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 surprises

Add 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

📥 Commits

Reviewing files that changed from the base of the PR and between efda02b and 5eeaef7.

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

The 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 to posix.unexpectedErrno(err)), so mapping .PERM to error.Unexpected in kqueue aligns with existing semantics.

Comment on lines 1617 to 1623
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,
},

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

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