Skip to content

Zig 0.15 - #2

Merged
lalinsky merged 28 commits into
mainfrom
zig-0.15
Oct 3, 2025
Merged

lalinsky merged 28 commits into
mainfrom
zig-0.15

Conversation

@lalinsky

@lalinsky lalinsky commented Sep 26, 2025 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Stream reader/writer abstractions added across File and TCP with explicit buffering; delimiter-based line reads; TLS client now uses separate reader/writer interfaces and logs handshake completion; File gains seek/position tracking.
  • Refactor

    • Examples and servers adopt explicit I/O buffering and flush semantics; build system moved to module-based artifacts; coroutine context handling improved; Windows calling convention standardized.
  • Tests

    • Expanded coverage for stream reader/writer behaviors, splat/vector writes, and interleaved operations; test runner logging/capture centralized.
  • Chores

    • CI/tooling bumped to Zig 0.15.1; test build/run target and timeout added; vendor build manifests updated.

Apply ArrayList API changes to fix compilation with newer Zig versions:
- Use .empty initializer instead of .init()
- Pass allocator to deinit(), append(), and toOwnedSlice()
This implements the new std.io.Reader/Writer streaming interface while
maintaining API compatibility with std.fs.File patterns.

Key changes:
- Add TcpStream.Reader/Writer wrapper structs with VTable implementation
- Use @fieldParentPtr pattern for context association
- Implement all streaming functions: stream, discard, readVec, drain, flush
- Proper error mapping from TCP errors to standard I/O error set
- Update examples to use new delimiter methods (takeDelimiterExclusive)
- Follow std.fs.File naming: reader(buffer) and writer(buffer)

The new interface provides better performance through built-in buffering
and integrates seamlessly with the Zig 0.15 I/O ecosystem.
@coderabbitai

coderabbitai Bot commented Sep 26, 2025 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

Walkthrough

Adds Zig 0.15-style io.StreamReader/io.StreamWriter generics, wires TcpStream and File to explicit per-stream buffers and readBuf/writeBuf hooks, updates examples (tcp, tls) to use the new interfaces, refactors vendor allocator usage and iocp changes, adjusts coroutine clobbers and Windows callconv, and centralizes test-runner logging.

Changes

Cohort / File(s) Summary
Core streaming types
src/io.zig
Adds generic StreamReader(T) and StreamWriter(T) factories, ReadBuffer/WriteBuffer-backed implementations, splat/vector write logic, BufferStream mock, and comprehensive tests.
TcpStream integration
src/tcp.zig
Adds nested TcpStream.Reader / TcpStream.Writer, reader(self, buffer) / writer(self, buffer), readBuf/writeBuf low-level APIs, and rewires stream read/write paths and tests to use the streaming interfaces.
File streaming integration
src/file.zig
Adds position field, switches to pread/pwrite with internal position tracking, seek, readBuf/writeBuf, exposes Reader/Writer via io.StreamReader/StreamWriter, and adds tests.
Examples: TCP client & echo server
examples/tcp_client.zig, examples/tcp_echo_server.zig
Introduces explicit read_buffer/write_buffer (4096), constructs reader(&read_buffer) / writer(&write_buffer), replaces old calls with reader.interface.* / writer.interface.* (e.g., takeDelimiterExclusive, write/writeAll via interface), and adjusts EndOfStream/error handling.
Example: TLS demo
examples/tls_demo.zig
Adds separate tcp/tls read/write buffers, obtains TCP reader/writer interfaces and passes them to std.crypto.tls.Client.init (now takes reader & writer interfaces and buffer options), uses tls_client.reader/tls_client.writer, adds explicit flushes and handshake logging.
Vendor: libxev build & ArrayList allocator use
vendor/libxev/build.zig, vendor/libxev/build.zig.zon
Converts ArrayList usage to explicit allocator-first init (empty + append(alloc,...), toOwnedSlice(alloc), deinit(alloc)); updates manPages/bench/examples paths and updates version bound to Zig 0.15.1.
Vendor: iocp backend
vendor/libxev/src/backend/iocp.zig
Adjusts overlapped I/O result mapping to distinguish pread/pwrite, maps HANDLE_EOF to error.EOF, and uses const casts for WSABUF buffer pointers in vectored paths.
Vendor: Windows bindings
vendor/libxev/src/windows.zig
Changes several kernel32 externs (e.g., DeleteFileW, GetProcessId, CreateJobObjectA, AssignProcessToJobObject, SetInformationJobObject) from callconv(windows.WINAPI) to callconv(.winapi).
Build system / packaging
build.zig, check.sh
Replaces .root_source_file usage with createModule/addModule, moves to addLibrary(... .linkage = .static), adds build-tests step; check.sh now runs zig build build-tests and executes the test binary under a timeout.
Coroutines / context switch
src/coroutines.zig
Replaces inline clobber lists with structured per-arch clobber maps (expanded registers, SIMD, FP state); uses @enumFromInt(stack_alignment) for allocation alignment.
Test runner / logging
test_runner.zig
Adds pub const std_options and customLogFn; replaces captured ArrayList logs with LogCapture using a capture_writer: ?*std.Io.Writer, centralizes printing via std.debug.print, simplifies Printer usage, and removes per-test setup helper.
Workflows & CI
.github/workflows/test.yml, .github/workflows/claude.yml, vendor/libxev/.github/workflows/test.yml
Bumps Setup Zig action and pinned Zig versions from 0.14.x to 0.15.1, updates actions/checkout and cache action versions in vendor CI, and updates Zig download references.
Docs & misc
vendor/libxev/README.md, vendor/libxev/flake.nix, vendor/libxev/src/bench/async_pummel_1.zig
Docs formatting and Zig version notes updated; nix inputs updated to nixos-25.05 and Zig 0.15.1; async_pummel sleep call switched to std.Thread.sleep(0).

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor App as Example App
  participant TS as TcpStream
  participant R as TcpStream.Reader
  participant W as TcpStream.Writer
  rect rgba(220,235,245,0.6)
    App->>TS: reader(&read_buffer)
    TS-->>App: Reader (with interface)
    App->>TS: writer(&write_buffer)
    TS-->>App: Writer (with interface)
  end
  rect rgba(235,245,220,0.6)
    App->>W: interface.writeAll("msg") / interface.write("\n")
    W->>TS: drain / flush -> writeBuf
    TS-->>W: write result
    App->>R: interface.takeDelimiterExclusive('\n')
    R->>TS: readVec -> readBuf
    TS-->>R: bytes / EndOfStream
    R-->>App: slice or EndOfStream
  end
Loading
sequenceDiagram
  autonumber
  actor App as TLS Demo
  participant TS as TcpStream
  participant TR as Tcp Reader iface
  participant TW as Tcp Writer iface
  participant TLS as std.crypto.tls.Client
  rect rgba(220,235,245,0.6)
    App->>TS: reader(&tcp_read_buffer) / writer(&tcp_write_buffer)
    TS-->>App: TR / TW
    App->>TLS: Client.init(TR.interface, TW.interface, {read_buffer, write_buffer, ...})
    TLS-->>App: tls_client (with reader/writer)
  end
  rect rgba(235,245,220,0.6)
    App->>TLS: tls_client.writer.writeAll("...")
    TLS->>TW: encrypted drain/flush -> writeBuf
    TLS->>TR: encrypted read -> TR.interface.readVec / takeDelimiterExclusive
    TR-->>TLS: bytes
    TLS-->>App: decrypted bytes via reader API
  end
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

Poem

I buffered my carrots, both read and both write,
New readers and writers now hop into sight.
TLS shook my paw, then flushed through the night,
CI bumped to .15 — bindings snug and tight.
Logs nest in a writer; tests hum, soft and bright. 🥕🐇

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title Check ❓ Inconclusive The provided title “Zig 0.15” does reference the version at the heart of this pull request, but it is overly terse and lacks an action or context describing what the changes actually do. It does not clearly state that the code base is being upgraded or adapted to Zig 0.15, making it less informative for someone scanning the repository history. Consider renaming the title to a short sentence that clearly states the main change, for example “Upgrade project to Zig 0.15” or “Migrate zio to Zig 0.15 streaming APIs,” to improve clarity and context.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9f23c00 and c312dbb.

⛔ Files ignored due to path filters (1)
  • vendor/libxev/flake.lock is excluded by !**/*.lock
📒 Files selected for processing (6)
  • vendor/libxev/.github/workflows/test.yml (5 hunks)
  • vendor/libxev/README.md (3 hunks)
  • vendor/libxev/build.zig (6 hunks)
  • vendor/libxev/build.zig.zon (1 hunks)
  • vendor/libxev/flake.nix (2 hunks)
  • vendor/libxev/src/bench/async_pummel_1.zig (1 hunks)

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
examples/tcp_echo_server.zig (1)

12-13: Consider configurable or dynamic buffer sizes

The fixed 4096-byte buffers may not be optimal for all use cases. Consider making these configurable via constants or runtime parameters to allow tuning based on expected message sizes and memory constraints.

+const READ_BUFFER_SIZE = 4096;
+const WRITE_BUFFER_SIZE = 4096;
+
 fn handleClient(in_stream: zio.TcpStream) !void {
     var stream = in_stream;
     defer stream.close();

     defer stream.shutdown() catch |err| {
         std.log.err("Failed to shutdown client connection: {}", .{err});
     };

-    var read_buffer: [4096]u8 = undefined;
-    var write_buffer: [4096]u8 = undefined;
+    var read_buffer: [READ_BUFFER_SIZE]u8 = undefined;
+    var write_buffer: [WRITE_BUFFER_SIZE]u8 = undefined;
examples/tcp_client.zig (1)

19-20: Consider flushing the writer after message completion

After writing the complete message with newline, consider explicitly flushing the writer to ensure the data is sent immediately. This is particularly important for client applications where latency matters.

     _ = try writer.interface.write(message);
     _ = try writer.interface.write("\n");
+    try writer.interface.flush();
src/tcp.zig (1)

364-376: Consider consistent error handling across read operations

The error mapping for TCP read errors to io.Reader errors is repeated in multiple places. Consider extracting this into a common helper function to ensure consistency and maintainability.

+        fn mapReadError(err: anyerror) std.io.Reader.Error {
+            return switch (err) {
+                error.Canceled => error.ReadFailed,
+                error.ConnectionResetByPeer => error.ReadFailed,
+                error.EOF => error.EndOfStream,
+                error.Unexpected => error.ReadFailed,
+                else => |e| e,
+            };
+        }
+
         fn stream(io_reader: *std.io.Reader, w: *std.io.Writer, limit: std.io.Limit) std.io.Reader.StreamError!usize {
             const r: *Reader = @alignCast(@fieldParentPtr("interface", io_reader));
             const dest = limit.slice(try w.writableSliceGreedy(1));
-            const n = r.tcp_stream.read(dest) catch |err| switch (err) {
-                error.Canceled => return error.ReadFailed,
-                error.ConnectionResetByPeer => return error.ReadFailed,
-                error.EOF => return error.EndOfStream,
-                error.Unexpected => return error.ReadFailed,
-                else => |e| return e,
-            };
+            const n = r.tcp_stream.read(dest) catch |err| return mapReadError(err);

Also applies to: 419-425

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a108a52 and 63bbc31.

📒 Files selected for processing (4)
  • examples/tcp_client.zig (1 hunks)
  • examples/tcp_echo_server.zig (1 hunks)
  • src/tcp.zig (1 hunks)
  • vendor/libxev/build.zig (5 hunks)
🧰 Additional context used
🪛 GitHub Actions: CI
vendor/libxev/build.zig

[error] 297-297: struct 'array_list.ArrayListAligned(*Build.Step,null)' has no member named 'empty'.

🔇 Additional comments (9)
examples/tcp_echo_server.zig (2)

19-23: LGTM! Clean error handling pattern

The switch expression properly handles EndOfStream separately from other errors, maintaining clear control flow for the normal connection termination case.


26-27: Confirm buffered writer fully writes data
examples/tcp_echo_server.zig:26-27: verify that writer.interface.write handles partial writes internally or switch to an API that guarantees writing the entire buffer (e.g., writeAll).

examples/tcp_client.zig (2)

12-15: LGTM! Consistent buffer initialization

The buffer initialization follows the same pattern as the echo server, maintaining consistency across examples.


24-25: LGTM! Clear and concise reader interface usage

The migration to takeDelimiterExclusive provides a cleaner API for line-based protocols.

vendor/libxev/build.zig (1)

174-174: LGTM! Proper allocator usage throughout

The changes correctly pass the allocator to all ArrayList operations (deinit, append, toOwnedSlice), following Zig 0.15's explicit allocator management patterns.

Also applies to: 211-211, 214-214, 224-224, 290-290, 293-293, 298-298, 318-318, 324-324

src/tcp.zig (4)

343-362: LGTM! Well-structured Reader implementation

The Reader struct properly encapsulates the TCP stream with a buffered interface, following std.io patterns. The vtable initialization with stream, discard, and readVec functions provides the necessary io.Reader interface implementation.


481-494: LGTM! Proper buffer flushing implementation

The flush implementation correctly writes any buffered data and resets the buffer position, following expected Writer interface semantics.


498-504: LGTM! Clean public API design

The reader and writer factory methods provide a clean interface for creating buffered I/O instances, following the pattern established by std.fs.File.


378-397: Potential infinite loop in discard function

The discard function may enter an infinite loop if read returns 0 without EOF error. Add protection against this case.

         fn discard(io_reader: *std.io.Reader, limit: std.io.Limit) std.io.Reader.Error!usize {
             const r: *Reader = @alignCast(@fieldParentPtr("interface", io_reader));
             // Use the buffer as temporary storage for discarded data
             var total_discarded: usize = 0;
             const remaining = @intFromEnum(limit);

             while (total_discarded < remaining) {
                 const to_read = @min(remaining - total_discarded, io_reader.buffer.len);
                 const n = r.tcp_stream.read(io_reader.buffer[0..to_read]) catch |err| switch (err) {
                     error.Canceled => return error.ReadFailed,
                     error.ConnectionResetByPeer => return error.ReadFailed,
                     error.EOF => return error.EndOfStream,
                     error.Unexpected => return error.ReadFailed,
                     else => |e| return e,
                 };
-                if (n == 0) break;
+                if (n == 0) return error.EndOfStream;
                 total_discarded += n;
             }
             return total_discarded;
         }

Likely an incorrect or invalid review comment.

Comment thread vendor/libxev/build.zig Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/runtime.zig (1)

136-179: Consider memory safety in list operations.

The custom linked list implementation looks correct, but ensure proper null checks when manipulating the list to avoid potential crashes.

Consider adding debug assertions to validate list integrity:

 pub fn push(self: *AnyTaskList, task: *AnyTask) void {
+    std.debug.assert(task.next == null); // Ensure task isn't already in a list
     task.next = null;
     if (self.tail) |tail| {
         tail.next = task;
         self.tail = task;
     } else {
         self.head = task;
         self.tail = task;
     }
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 63bbc31 and 8396327.

📒 Files selected for processing (5)
  • .github/workflows/test.yml (1 hunks)
  • build.zig (3 hunks)
  • src/coroutines.zig (3 hunks)
  • src/runtime.zig (9 hunks)
  • src/tcp.zig (2 hunks)
🧰 Additional context used
🪛 GitHub Actions: CI
src/tcp.zig

[error] 506-506: Pointless discard of function parameter '_ = buffer' in Zig 0.14 interface. This discard causes a compilation error.


[error] 515-515: Pointless discard of function parameter '_ = buffer' in Zig 0.14 interface. This discard causes a compilation error.

🔇 Additional comments (14)
src/coroutines.zig (3)

139-139: LGTM: Updated to new Zig 0.15 structured clobber syntax

The change from tuple-based to struct-based clobber lists aligns with Zig 0.15's new asm syntax. This structured approach using .{ .register = true } format is more explicit and follows the new Zig conventions for inline assembly.


158-158: LGTM: Updated to new Zig 0.15 structured clobber syntax

The aarch64 clobber list has been updated to match the new structured syntax, maintaining the same register preservation behavior while conforming to Zig 0.15's assembly conventions.


256-256: LGTM: Updated for Zig 0.15 alignment API changes

The change to @enumFromInt(stack_alignment) aligns with Zig 0.15's new alignment handling where alignments are expected to be provided as enum values rather than direct integers. This maintains the same 16-byte stack alignment behavior while conforming to the new API.

.github/workflows/test.yml (1)

23-23: LGTM! CI aligned with Zig 0.15 upgrade.

The workflow correctly updates to Zig 0.15.1, which aligns with the PR's objective to support Zig 0.15's new streaming interface and module system changes.

build.zig (4)

12-21: LGTM! Correct migration to Zig 0.15's module-based API.

The library creation properly uses the new module-based approach with root_module and createModule, which is required for Zig 0.15+.


45-54: LGTM! Module-based executable creation.

The example executables correctly use the new module system with root_module and properly import the zio module.


59-65: LGTM! Test configuration uses module system.

Tests are properly configured with the module-based approach, maintaining consistency with the library setup.


32-34: Confirm Zig 0.14.x compatibility
No references to Zig <0.15 in CI or docs—ensure the build still succeeds on Zig 0.14.x (with examples disabled) and add a CI job or README note to document/test this.

src/tcp.zig (3)

8-10: LGTM! Version detection for compatibility.

The version compatibility check is correctly implemented to support both Zig 0.14 and 0.15+.


348-432: LGTM! Well-structured Reader implementation.

The Reader struct correctly implements the new Zig 0.15 streaming interface with proper vtable setup and error handling.


452-483: Critical: Handle partial writes correctly in drain function.

The current implementation returns early on partial write (line 479), potentially dropping unwritten bytes. This could lead to data loss.

Apply this fix to handle partial writes properly:

 fn drain(io_writer: *std.io.Writer, data: []const []const u8, splat: usize) std.io.Writer.Error!usize {
     const w: *Writer = @alignCast(@fieldParentPtr("interface", io_writer));
 
     // First, write any buffered data
     if (io_writer.end > 0) {
         _ = w.tcp_stream.write(io_writer.buffer[0..io_writer.end]) catch |err| switch (err) {
             error.BrokenPipe => return error.WriteFailed,
             error.Canceled => return error.WriteFailed,
             error.ConnectionResetByPeer => return error.WriteFailed,
             error.Unexpected => return error.WriteFailed,
             else => |e| return e,
         };
         io_writer.end = 0;
     }
 
     // Then write the provided data
     var total_written: usize = 0;
     for (data) |slice| {
         for (0..@max(1, splat)) |_| {
-            const n = w.tcp_stream.write(slice) catch |err| switch (err) {
-                error.BrokenPipe => return error.WriteFailed,
-                error.Canceled => return error.WriteFailed,
-                error.ConnectionResetByPeer => return error.WriteFailed,
-                error.Unexpected => return error.WriteFailed,
-                else => |e| return e,
-            };
-            total_written += n;
-            if (n < slice.len) return total_written;
+            var written: usize = 0;
+            while (written < slice.len) {
+                const n = w.tcp_stream.write(slice[written..]) catch |err| switch (err) {
+                    error.BrokenPipe => return error.WriteFailed,
+                    error.Canceled => return error.WriteFailed,
+                    error.ConnectionResetByPeer => return error.WriteFailed,
+                    error.Unexpected => return error.WriteFailed,
+                    else => |e| return e,
+                };
+                if (n == 0) break; // No progress, return what we've written
+                written += n;
+            }
+            total_written += written;
         }
     }
     return total_written;
 }
src/runtime.zig (3)

53-59: LGTM! Clean refactor to direct AnyTask structure.

The simplified AnyTask structure with direct fields and integrated linked list node is cleaner than the previous wrapper approach.


229-242: LGTM! Task lifecycle management improved.

The spawn function correctly initializes tasks with the new structure and properly manages reference counting.


336-339: LGTM! Clean parent pointer retrieval.

The taskPtrFromCoroPtr function correctly uses @fieldParentPtr to retrieve the AnyTask from its embedded Coroutine field.

Comment thread src/tcp.zig Resolved
Comment thread src/tcp.zig Resolved
Simplify build system by removing conditional compilation logic that
attempted to support both Zig 0.14 and 0.15. Since we now target only
Zig 0.15, the conditional logic was causing "pointless discard" warnings
and unnecessary complexity.

Changes:
- Remove version detection in tcp.zig and build.zig
- Use only Zig 0.15 streaming I/O interface
- Remove unused builtin imports
- Unconditionally build examples

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

🧹 Nitpick comments (3)
build.zig (2)

13-17: Deduplicate module options to avoid drift

The same root_source_file/target/optimize tuple is repeated 3×. Extract once to reduce maintenance risk.

Add once near the top (e.g., after Line 6):

const zio_root = b.path("src/zio.zig");

Then update the occurrences:

-            .root_source_file = b.path("src/zio.zig"),
+            .root_source_file = zio_root,
-        .root_source_file = b.path("src/zio.zig"),
+        .root_source_file = zio_root,
-            .root_source_file = b.path("src/zio.zig"),
+            .root_source_file = zio_root,

Also applies to: 24-28, 55-59


39-51: Expose runnable steps for examples (run, run-server, run-client)

You capture the desired step names in the examples table but don’t define steps. Add run steps per example.

Apply this within the loop:

     for (examples) |example| {
         const exe = b.addExecutable(.{
             .name = example.name,
             .root_module = b.createModule(.{
                 .root_source_file = b.path(example.file),
                 .target = target,
                 .optimize = optimize,
             }),
         });
         exe.root_module.addImport("zio", zio);
         b.installArtifact(exe);
+
+        const run_cmd = b.addRunArtifact(exe);
+        run_cmd.step.dependOn(b.getInstallStep());
+        const run_step = b.step(example.step, example.desc);
+        run_step.dependOn(&run_cmd.step);
     }
src/tcp.zig (1)

365-398: Optional: honor Reader's internal buffer in stream.

Consider consuming any bytes staged in io_reader.buffer before issuing a new socket read, and setting/using seek/end consistently in readVec. This would make the buffering fields effective.

Also applies to: 400-428, 449-496

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8396327 and 19a8ab6.

📒 Files selected for processing (2)
  • build.zig (2 hunks)
  • src/tcp.zig (2 hunks)
🧰 Additional context used
🪛 GitHub Actions: CI
src/tcp.zig

[error] 373-373: Zig compile error: mismatched error set in destination. 'else => |e| return e' references a larger error set (e.g., AccessDenied, BrokenPipe, ConnectionRefused, etc.) not present in the expected 'error{EndOfStream,ReadFailed,WriteFailed}' set.


[error] 392-392: Zig compile error: mismatched error set in destination. 'else => |e| return e' references a larger error set not present in the expected 'error{EndOfStream,ReadFailed}' set.


[error] 414-414: Zig compile error: mismatched error set in destination. 'else => |e| return e' references a larger error set not present in the expected 'error{EndOfStream,ReadFailed}' set.


[error] 459-459: Zig compile error: mismatched error set in destination. 'else => |e| return e' references a larger error set not present in the expected 'error{WriteFailed}' set.


[error] 491-491: Zig compile error: mismatched error set in destination. 'else => |e| return e' references a larger error set not present in the expected 'error{WriteFailed}' set.

🔇 Additional comments (7)
build.zig (2)

43-47: Correct use of root_module for executables

Switching examples to module-based construction is aligned with 0.15 build APIs.


55-59: Tests migrated to module-based addTest — looks good

Using .root_module = b.createModule(...) for unit tests is the right pattern; xev import added below ensures resolution.

src/tcp.zig (5)

344-364: Reader interface wiring looks good.

Constructor sets vtable, buffer, and indices coherently for Zig 0.15+.


431-447: Writer interface wiring looks good.

Constructor sets vtable and buffer state coherently for Zig 0.15+.


498-505: Zig 0.15+ Reader/Writer accessors look correct.

Public accessors delegate to the new buffered interfaces as intended.


449-480: Partial write handling was flagged previously.

Prior review already raised the early-return on partial write. The diff above buffers the remainder to avoid data loss and aligns with Writer semantics.


507-518: No usages of 0.14 adapters found in codebase
Search found no references to readFn, writeFn, GenericReader, or GenericWriter outside of src/tcp.zig; no action required.

Comment thread build.zig Resolved
Comment thread src/tcp.zig Resolved
Comment thread src/tcp.zig Resolved
Comment thread src/tcp.zig Resolved
Comment thread src/tcp.zig Resolved
Comment thread src/tcp.zig Resolved
Use robust error mapping that works across all platforms:
- EOF -> EndOfStream (only special case with semantic meaning)
- All other errors -> ReadFailed/WriteFailed (generic failures)

This avoids platform-specific error assumptions and ensures
compatibility with macOS, Linux, and Windows.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 19a8ab6 and 164c280.

📒 Files selected for processing (1)
  • src/tcp.zig (2 hunks)
🔇 Additional comments (2)
src/tcp.zig (2)

440-457: Preserve buffered bytes on partial writes in Writer.drain()

Discarding the return value of write and zeroing io_writer.end drops any bytes left in the buffer when the OS reports a short write. That’s silent data loss. Capture the count, shift the remainder forward, and bail out so the caller can retry.

-            // First, write any buffered data
-            if (io_writer.end > 0) {
-                _ = w.tcp_stream.write(io_writer.buffer[0..io_writer.end]) catch |err| switch (err) {
-                    else => return error.WriteFailed,
-                };
-                io_writer.end = 0;
-            }
-
-            // Then write the provided data
-            var total_written: usize = 0;
+            var total_written: usize = 0;
+
+            // First, write any buffered data
+            if (io_writer.end > 0) {
+                const wrote = w.tcp_stream.write(io_writer.buffer[0..io_writer.end]) catch |err| switch (err) {
+                    else => return error.WriteFailed,
+                };
+                if (wrote < io_writer.end) {
+                    const remaining = io_writer.end - wrote;
+                    std.mem.copyForwards(u8, io_writer.buffer[0..remaining], io_writer.buffer[wrote..io_writer.end]);
+                    io_writer.end = remaining;
+                    return total_written;
+                }
+                io_writer.end = 0;
+            }
+
+            // Then write the provided data

465-469: Flush must loop until the buffer is empty

flush has the same short-write bug: a partial write zeros io_writer.end and drops remaining bytes. Loop until everything is sent (or propagate WriteFailed) and shift the leftover tail forward when needed.

-            if (io_writer.end > 0) {
-                _ = w.tcp_stream.write(io_writer.buffer[0..io_writer.end]) catch |err| switch (err) {
-                    else => return error.WriteFailed,
-                };
-                io_writer.end = 0;
-            }
+            while (io_writer.end > 0) {
+                const wrote = w.tcp_stream.write(io_writer.buffer[0..io_writer.end]) catch |err| switch (err) {
+                    else => return error.WriteFailed,
+                };
+                if (wrote == 0) return error.WriteFailed;
+                if (wrote < io_writer.end) {
+                    const remaining = io_writer.end - wrote;
+                    std.mem.copyForwards(u8, io_writer.buffer[0..remaining], io_writer.buffer[wrote..io_writer.end]);
+                    io_writer.end = remaining;
+                } else {
+                    io_writer.end = 0;
+                }
+            }

Comment thread src/tcp.zig Resolved
Update callconv(windows.WINAPI) to callconv(.winapi) to match Zig 0.15
Windows API changes. This enables successful cross-compilation for
Windows targets.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b52663d and 7f6528f.

📒 Files selected for processing (4)
  • build.zig (3 hunks)
  • src/coroutines.zig (3 hunks)
  • src/runtime.zig (4 hunks)
  • src/tcp.zig (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/runtime.zig
🧰 Additional context used
🪛 GitHub Actions: CI
src/tcp.zig

[error] 120-120: duplicate struct member name 'ReadError'.


[error] 121-121: duplicate struct member name 'WriteError'.

🔇 Additional comments (3)
src/tcp.zig (3)

533-538: Flush must drain the buffer safely

flush has the same partial-write problem: a short write clears the buffer and loses bytes. Loop until the buffer is empty (or fail), shifting any unwritten suffix forward after each write.

-            if (io_writer.end > 0) {
-                _ = w.tcp_stream.write(io_writer.buffer[0..io_writer.end]) catch |err| switch (err) {
-                    else => return error.WriteFailed,
-                };
-                io_writer.end = 0;
-            }
+            while (io_writer.end > 0) {
+                const written = w.tcp_stream.write(io_writer.buffer[0..io_writer.end]) catch |err| switch (err) {
+                    else => return error.WriteFailed,
+                };
+                if (written == 0) return error.WriteFailed;
+                if (written < io_writer.end) {
+                    const remaining = io_writer.end - written;
+                    std.mem.copy(
+                        u8,
+                        io_writer.buffer[0..remaining],
+                        io_writer.buffer[written..io_writer.end],
+                    );
+                    io_writer.end = remaining;
+                } else {
+                    io_writer.end = 0;
+                }
+            }

509-526: Preserve buffered data on partial writes

When flushing the buffered bytes you ignore the returned byte count and zero end, so any short write silently drops data. Handle the partial case by keeping the unwritten suffix in the buffer before reporting back to the caller.

             if (io_writer.end > 0) {
-                _ = w.tcp_stream.write(io_writer.buffer[0..io_writer.end]) catch |err| switch (err) {
+                const written = w.tcp_stream.write(io_writer.buffer[0..io_writer.end]) catch |err| switch (err) {
                     else => return error.WriteFailed,
                 };
-                io_writer.end = 0;
+                if (written < io_writer.end) {
+                    const remaining = io_writer.end - written;
+                    std.mem.copy(
+                        u8,
+                        io_writer.buffer[0..remaining],
+                        io_writer.buffer[written..io_writer.end],
+                    );
+                    io_writer.end = remaining;
+                    return 0;
+                }
+                io_writer.end = 0;
             }
 
             // Then write the provided data
             var total_written: usize = 0;
             for (data) |slice| {
                 for (0..@max(1, splat)) |_| {
                     const n = w.tcp_stream.write(slice) catch |err| switch (err) {
                         else => return error.WriteFailed,
                     };
                     total_written += n;
-                    if (n < slice.len) return total_written;
+                    if (n < slice.len) {
+                        const tail = slice[n..];
+                        const space = io_writer.buffer.len - io_writer.end;
+                        const to_copy = @min(tail.len, space);
+                        if (to_copy > 0) {
+                            std.mem.copy(
+                                u8,
+                                io_writer.buffer[io_writer.end..][0..to_copy],
+                                tail[0..to_copy],
+                            );
+                            io_writer.end += to_copy;
+                            total_written += to_copy;
+                        }
+                        return total_written;
+                    }
                 }
             }
             return total_written;

444-458: Fix discard limit handling

std.io.Limit is a tagged union, so @intFromEnum(limit) only yields the tag (0 for .none, 1 for .bytes). That makes .none return immediately and .bytes stop after a single byte, breaking discard semantics and hanging callers that expect an unbounded drain. Switch on the union payload and track the remaining byte budget explicitly.

             var total_discarded: usize = 0;
-            const remaining = @intFromEnum(limit);
-
-            while (total_discarded < remaining) {
-                const to_read = @min(remaining - total_discarded, io_reader.buffer.len);
-                const n = r.tcp_stream.read(io_reader.buffer[0..to_read]) catch |err| switch (err) {
+            const maybe_remaining: ?usize = switch (limit) {
+                .none => null,
+                .bytes => |count| count,
+            };
+
+            while (true) {
+                if (maybe_remaining) |remaining| {
+                    if (total_discarded >= remaining) break;
+                }
+                const max_chunk = if (maybe_remaining) |remaining|
+                    @min(remaining - total_discarded, io_reader.buffer.len)
+                else
+                    io_reader.buffer.len;
+                if (max_chunk == 0) break;
+                const n = r.tcp_stream.read(io_reader.buffer[0..max_chunk]) catch |err| switch (err) {
                     error.EOF => return error.EndOfStream,
                     else => return error.ReadFailed,
                 };
                 if (n == 0) break;
                 total_discarded += n;
             }

Comment thread src/tcp.zig Resolved
Comment thread src/tcp.zig Resolved
…erface

- Fix Reader.stream: Add missing EOF detection when n == 0
- Fix Reader.readVec: Use proper writableVector pattern from std library
- Fix Writer.drain: Use io_writer.consume() for correct partial write handling
- Fix Writer.flush: Loop with consume() until all buffered data is written
- Update TLS demo: Use new streaming interface with proper buffer management

Resolves TLS handshake hanging issues and ensures compatibility with std I/O patterns.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7f6528f and 969a230.

📒 Files selected for processing (2)
  • examples/tls_demo.zig (3 hunks)
  • src/tcp.zig (2 hunks)
🔇 Additional comments (1)
src/tcp.zig (1)

445-460: Restore correct limit handling in Reader.discard
std.io.Limit is a tagged union; @intFromEnum(limit) only yields the tag index (0 or 1). As written, .none exits immediately (discarding nothing) and .bytes stops after a single byte, so callers never discard the requested amount. Please switch on the limit, carry the payload for the .bytes variant, and treat .none as unbounded.

-            var total_discarded: usize = 0;
-            const remaining = @intFromEnum(limit);
-
-            while (total_discarded < remaining) {
-                const to_read = @min(remaining - total_discarded, io_reader.buffer.len);
-                const n = r.tcp_stream.read(io_reader.buffer[0..to_read]) catch |err| switch (err) {
-                    error.EOF => return error.EndOfStream,
-                    else => return error.ReadFailed,
-                };
-                if (n == 0) break;
-                total_discarded += n;
-            }
-            return total_discarded;
+            var total_discarded: usize = 0;
+            const maybe_remaining: ?usize = switch (limit) {
+                .none => null,
+                .bytes => |count| count,
+            };
+
+            while (true) {
+                if (maybe_remaining) |remaining| {
+                    if (total_discarded >= remaining) break;
+                }
+                const chunk_len = if (maybe_remaining) |remaining|
+                    @min(remaining - total_discarded, io_reader.buffer.len)
+                else
+                    io_reader.buffer.len;
+                if (chunk_len == 0) break;
+                const n = r.tcp_stream.read(io_reader.buffer[0..chunk_len]) catch |err| switch (err) {
+                    error.EOF => return error.EndOfStream,
+                    else => return error.ReadFailed,
+                };
+                if (n == 0) break;
+                total_discarded += n;
+            }
+            return total_discarded;

Comment thread src/tcp.zig Resolved
Resolved conflicts in build.zig, src/runtime.zig, and src/tcp.zig by:
- Preserving Zig 0.15 API changes (createModule pattern)
- Keeping new awaitable-based task architecture from main
- Maintaining Zig 0.15 streaming interface (Reader/Writer)
- Removing deprecated Zig 0.14 compatibility functions
- Replace deprecated FixedBufferAllocator with GeneralPurposeAllocator
- Use std.Io.Writer.Allocating instead of ArrayList for log buffer
- Implement log capture using std.Io.Writer pointer swapping
- Add custom logFn in std_options for compile-time logging override
- Show full test names instead of shortened paths
- Capture logs during test execution, only display for failed tests
- Add TEST_LOG_CAPTURE environment variable to control capture behavior

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (2)
src/tcp.zig (2)

525-541: Fix std.io.Limit handling in discard() (current code misuses @intFromEnum).

@intFromEnum(limit) yields the tag, not the byte count; .bytes is ignored and .none can loop incorrectly. Replace with an explicit switch and bounded/unbounded loop.

Apply this diff:

-        // Use the buffer as temporary storage for discarded data
-        var total_discarded: usize = 0;
-        const remaining = @intFromEnum(limit);
-
-        while (total_discarded < remaining) {
-            const to_read = @min(remaining - total_discarded, io_reader.buffer.len);
-            const n = r.tcp_stream.read(io_reader.buffer[0..to_read]) catch |err| switch (err) {
-                error.EOF => return error.EndOfStream,
-                else => return error.ReadFailed,
-            };
-            if (n == 0) break;
-            total_discarded += n;
-        }
-        return total_discarded;
+        // Use the buffer as temporary storage for discarded data
+        var total_discarded: usize = 0;
+        const maybe_remaining: ?usize = switch (limit) {
+            .none => null,
+            .bytes => |count| count,
+        };
+
+        while (true) {
+            if (maybe_remaining) |remaining| {
+                if (total_discarded >= remaining) break;
+            }
+            const max_chunk = if (maybe_remaining) |remaining|
+                @min(remaining - total_discarded, io_reader.buffer.len)
+            else
+                io_reader.buffer.len;
+            if (max_chunk == 0) break;
+            const n = r.tcp_stream.read(io_reader.buffer[0..max_chunk]) catch |err| switch (err) {
+                error.EOF => return error.EndOfStream,
+                else => return error.ReadFailed,
+            };
+            if (n == 0) break;
+            total_discarded += n;
+        }
+        return total_discarded;

588-617: Drain: guard empty data and honor splat; avoid underflow on last-element access.

  • data[data.len - 1] traps when data.len == 0.
  • Current code ignores splat repetitions; it should attempt repeated writes of the last slice.

Apply this diff:

             // Then write the provided data
             for (data[0..data.len -| 1]) |slice| {
                 if (slice.len == 0) continue;
                 const n = w.tcp_stream.write(slice) catch |err| switch (err) {
                     else => return error.WriteFailed,
                 };
                 return io_writer.consume(n);
             }
 
             // Handle splat pattern (last element repeated)
+            if (data.len == 0) return 0; // prevent underflow on data.len - 1
             const pattern = data[data.len - 1];
-            if (pattern.len == 0 or splat == 0) return 0;
-
-            const n = w.tcp_stream.write(pattern) catch |err| switch (err) {
-                else => return error.WriteFailed,
-            };
-            return io_writer.consume(n);
+            if (pattern.len == 0 or splat == 0) return 0;
+            var total: usize = 0;
+            for (0..splat) |_| {
+                const n = w.tcp_stream.write(pattern) catch |err| switch (err) {
+                    else => return error.WriteFailed,
+                };
+                total += io_writer.consume(n);
+                if (n < pattern.len) break; // partial; let caller retry
+            }
+            return total;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 969a230 and 50bd9cd.

📒 Files selected for processing (8)
  • .github/workflows/test.yml (1 hunks)
  • build.zig (3 hunks)
  • examples/tcp_client.zig (1 hunks)
  • examples/tcp_echo_server.zig (1 hunks)
  • examples/tls_demo.zig (3 hunks)
  • src/coroutines.zig (3 hunks)
  • src/tcp.zig (2 hunks)
  • test_runner.zig (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/coroutines.zig
  • .github/workflows/test.yml
  • build.zig
  • examples/tcp_echo_server.zig
  • examples/tcp_client.zig
🔇 Additional comments (6)
src/tcp.zig (3)

513-523: Reader.stream mapping looks correct.

EOF maps to EndOfStream; other errors to ReadFailed; advances writer correctly.


619-630: Flush handles partial writes and error mapping correctly.

Looping on buffered() with mapped errors is good.


543-567: Verify writableVector unpacking and end-pointer update

Confirm that io_reader.writableVector(&vecs, data) returns a tuple matching the destructuring (dest_n, data_size), and that io_reader.end += n - data_size cannot exceed the internal buffer length.

test_runner.zig (3)

36-44: Fallback write path OK, but ensure writer.print exists.

If capture_writer.print is not available in your std.io.Writer, replace with std.fmt.format(writer, scope_prefix ++ format ++ "\n", args).


286-294: Slow test display looks good.

Formatting via Printer is straightforward.


23-24: Fix std.io casing and validate writer API

  • Change all std.Io.Writer references to std.io.Writer, for example:
    -    capture_writer: ?*std.Io.Writer = null,
    +    capture_writer: ?*std.io.Writer = null,
    -    pub fn startCapture(self: *@This(), writer: *std.Io.Writer) void {
    +    pub fn startCapture(self: *@This(), writer: *std.io.Writer) void {
    -    var log_buffer: std.Io.Writer.Allocating = .init(allocator);
    +    var log_buffer: std.io.Writer.Allocating = .init(allocator);
  • Verify that std.io.Writer.Allocating exists in your Zig version and that the writer supports .print(...); if not, replace calls with std.fmt.format(writer, ...) or writer.writeAll(...).

Comment thread examples/tls_demo.zig Resolved
Comment thread test_runner.zig Resolved
Rewrites TcpStream Reader/Writer to properly support Zig 0.15's new
std.Io.Reader/Writer VTable-based interface. Adds readVec/writeVec methods
using xev's vectored I/O (max 2 buffers) and fixes critical bugs:
- Remove non-existent consume() calls (doesn't exist in 0.15)
- Fix Writer.drain() to continue after flushing buffer instead of early return
- Use direct field manipulation for partial writes
- Use xev async primitives instead of coroutine wrappers in vtable functions

All tests pass.

@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 (2)
src/tcp.zig (2)

674-703: Critical: Prevent underflow in Writer.drain when data is empty

Line 699 accesses data[data.len - 1] without checking if data.len == 0. If the writer is flushing only its internal buffer (with data being empty), this causes an underflow and runtime trap.

Apply this fix:

     // Write from data slices (all but last)
-    for (data[0 .. data.len - 1]) |slice| {
+    if (data.len == 0) return 0;
+    for (data[0..data.len - 1]) |slice| {
         if (slice.len == 0) continue;
         return w.tcp_stream.write(slice) catch return error.WriteFailed;
     }
 
     // Handle splat pattern (last element repeated)
     const pattern = data[data.len - 1];
     if (pattern.len == 0 or splat == 0) return 0;

Based on past review comments flagging this exact issue.


617-633: Critical: Fix incorrect limit handling in Reader.discard()

The @intFromEnum(limit) at line 621 only yields the enum tag value (0 for .none, 1 for .bytes), not the actual byte count from the .bytes union field. This causes:

  • For .bytes(n), the loop stops after 1 byte instead of n bytes
  • For .none, the loop condition is broken

Apply this fix:

 fn discard(io_reader: *std.io.Reader, limit: std.io.Limit) std.io.Reader.Error!usize {
     const r: *Reader = @alignCast(@fieldParentPtr("interface", io_reader));
-    // Use the buffer as temporary storage for discarded data
     var total_discarded: usize = 0;
-    const remaining = @intFromEnum(limit);
 
-    while (total_discarded < remaining) {
-        const to_read = @min(remaining - total_discarded, io_reader.buffer.len);
+    while (true) {
+        const to_read = switch (limit) {
+            .none => io_reader.buffer.len,
+            .bytes => |max_bytes| blk: {
+                if (total_discarded >= max_bytes) return total_discarded;
+                break :blk @min(max_bytes - total_discarded, io_reader.buffer.len);
+            },
+        };
+        if (to_read == 0) break;
         const n = r.tcp_stream.read(io_reader.buffer[0..to_read]) catch |err| switch (err) {
             error.EOF => return error.EndOfStream,
             else => return error.ReadFailed,
         };
         if (n == 0) break;
         total_discarded += n;
     }
     return total_discarded;
 }

Based on past review comments flagging this exact issue.

🧹 Nitpick comments (2)
src/tcp.zig (2)

443-446: Consider narrowing the error set propagation.

The else => err branch propagates the entire xev.ReadError set. While this is permissible since ReadError is currently anyerror, best practice would be to map unexpected errors to a known error variant for clearer error handling by callers.

Consider applying this pattern:

 return result_data.result catch |err| switch (err) {
     error.EOF => 0,
-    else => err,
+    error.Canceled,
+    error.ConnectionResetByPeer,
+    error.Unexpected => err,
+    else => error.Unexpected,
 };

490-490: Consider narrowing the error set propagation.

Similar to readVec, this directly returns the xev.WriteError set. For consistency and clearer error contracts, consider mapping to known error variants.

Consider applying this pattern:

-return result_data.result;
+return result_data.result catch |err| switch (err) {
+    error.BrokenPipe,
+    error.Canceled,
+    error.ConnectionResetByPeer,
+    error.Unexpected => err,
+    else => error.Unexpected,
+};
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 50bd9cd and 27cad3f.

📒 Files selected for processing (1)
  • src/tcp.zig (2 hunks)
🔇 Additional comments (3)
src/tcp.zig (3)

603-615: LGTM: Reader.stream and Reader.readVec implementations are correct.

Both methods properly:

  • Map TCP errors to the std.io.Reader error set
  • Handle EOF/EndOfStream conditions
  • Manage buffer state and advancement
  • Integrate with the Zig 0.15 streaming interface

Also applies to: 635-653


705-722: LGTM: Writer.flush implementation is correct.

The flush method properly:

  • Loops until the buffer is completely drained
  • Maps write errors to WriteFailed
  • Prevents spinning on zero progress
  • Handles partial writes by shifting remaining data

725-732: LGTM: Reader/Writer accessor methods are correct.

Both accessor methods properly delegate to the respective init functions with the required buffer parameter, matching the Zig 0.15 streaming interface requirements.

- Add private readBuf() function accepting xev.ReadBuffer directly
- Convert xev errors: EOF -> EndOfStream, n==0 -> EndOfStream, others -> ReadFailed
- Reimplement read() and readVec() using readBuf()
- Remove readv(), readvAll(), readAtLeast() - keep readAll() for convenience
- Update Reader interface to use readBuf() directly in stream(), discard(), readVec()
- Optimize Reader.readVec() to write directly into native OS vector structures
  (POSIX iovec or Windows WSABUF) using writableVectorPosix/Wsa
- Update echo server to use Reader/Writer streaming interface
- Remove obsolete tests for deleted functions
- All 24 tests passing
- Add private writeBuf() function accepting xev.WriteBuffer directly
- Convert all write errors to error.WriteFailed for std.io.Writer compatibility
- Reimplement write() and writeVec() using writeBuf()
- Remove writev() and writevAll() - no longer needed
- Update Writer.drain() and Writer.flush() to use writeBuf() directly
- Remove tests for deleted writev/writevAll functions
- All 22 tests passing
- Symmetric with readBuf() implementation for consistency
The drain() function was only writing the pattern once, ignoring the
splat count. This fix implements the correct behavior:
- Writes all data slices except the last
- Writes the last slice (pattern) exactly splat times

Implementation uses vectored I/O when possible (within xev's 2-buffer
limit) and falls back to sequential writes for larger splat counts.

Also adds comprehensive test coverage for splat functionality with
both multi-element and single-element patterns.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (2)
examples/tls_demo.zig (1)

30-35: Security: Remove .no_verification for production use.

The TLS client is initialized with .ca = .no_verification, which disables certificate verification. While acceptable for a demo, this must not be used in production. Consider using the OS trust store or bundled CA certificates, and gate any "no verification" mode behind an explicit environment variable or configuration flag.

Based on past review comments.

src/tcp.zig (1)

469-484: Critical: Fix incorrect limit handling in Reader.discard.

Line 473 uses @intFromEnum(limit), which only yields the enum tag (0 for .none, 1 for .bytes), not the actual byte count. This breaks bounded discards and causes unbounded discards to stop after 1 byte.

Based on past review comments (already flagged but not yet resolved in the code).

Apply this fix:

         fn discard(io_reader: *std.io.Reader, limit: std.io.Limit) std.io.Reader.Error!usize {
             const r: *Reader = @alignCast(@fieldParentPtr("interface", io_reader));
-            // Use the buffer as temporary storage for discarded data
             var total_discarded: usize = 0;
-            const remaining = @intFromEnum(limit);
 
-            while (total_discarded < remaining) {
-                const to_read = @min(remaining - total_discarded, io_reader.buffer.len);
+            const maybe_remaining: ?usize = switch (limit) {
+                .none => null,
+                .bytes => |count| count,
+            };
+
+            while (true) {
+                if (maybe_remaining) |remaining| {
+                    if (total_discarded >= remaining) break;
+                }
+                const max_chunk = if (maybe_remaining) |remaining|
+                    @min(remaining - total_discarded, io_reader.buffer.len)
+                else
+                    io_reader.buffer.len;
+                if (max_chunk == 0) break;
-                const n = r.tcp_stream.readBuf(.{ .slice = io_reader.buffer[0..to_read] }) catch |err| switch (err) {
+                const n = r.tcp_stream.readBuf(.{ .slice = io_reader.buffer[0..max_chunk] }) catch |err| switch (err) {
                     error.EndOfStream => break,
                     else => return error.ReadFailed,
                 };
+                if (n == 0) break;
                 total_discarded += n;
             }
             return total_discarded;
         }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 27cad3f and c76dd33.

📒 Files selected for processing (5)
  • .github/workflows/claude.yml (1 hunks)
  • examples/tcp_client.zig (1 hunks)
  • examples/tcp_echo_server.zig (1 hunks)
  • examples/tls_demo.zig (2 hunks)
  • src/tcp.zig (12 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • examples/tcp_client.zig
  • examples/tcp_echo_server.zig
🧰 Additional context used
🪛 GitHub Actions: CI
src/tcp.zig

[error] 578-578: no field named 'base' in struct 'os.windows.ws2_32.WSABUF'. Zig build failed during Windows WSABUF initialization.

🔇 Additional comments (18)
.github/workflows/claude.yml (1)

36-36: LGTM! CI toolchain updated to match Zig 0.15.

The version bump from 0.14.1 to 0.15.1 aligns with the PR's objective to adopt Zig 0.15 streaming interfaces and ensures CI runs with the correct toolchain.

examples/tls_demo.zig (2)

18-29: Buffer allocation for streaming interfaces is correct.

The addition of separate buffers for TCP stream I/O (tcp_read_buffer, tcp_write_buffer) and TLS internal operations (tls_read_buffer, tls_write_buffer) aligns with the new Zig 0.15 streaming interface design. The 32KB size is reasonable for typical TLS operations.


46-51: TLS I/O operations use the new streaming interface correctly.

The calls to tls_client.writer.writeAll(...) and tls_client.reader.readSliceShort(...) properly utilize the new Zig 0.15 streaming interface exposed by the TLS client.

src/tcp.zig (15)

27-38: Echo server updated correctly for new streaming interface.

The echo server now uses explicit read/write buffers and the new reader/writer interfaces. The EndOfStream handling in the loop (lines 33-36) is correct, breaking on EndOfStream and propagating other errors.


214-231: Read methods correctly handle EndOfStream and support readAll.

The read method (lines 214-218) correctly maps EndOfStream to zero bytes, following standard I/O conventions. The new readAll method (lines 223-231) loops until the buffer is full or EOF, which is the expected behavior.


235-248: Write methods correctly implemented with writeAll support.

The write method (lines 235-237) delegates to writeBuf, and writeAll (lines 241-248) correctly loops until all bytes are written, handling partial writes properly.


252-264: Vectored I/O methods added for readVec and writeVec.

The readVec and writeVec methods (lines 252-264) correctly delegate to readBuf and writeBuf with xev's vectored buffer format. The zero-length check prevents unnecessary system calls.


310-347: writeBuf implementation correctly maps errors to Writer.Error.

The private writeBuf method (lines 310-347) correctly wraps xev's write operation and maps all write errors to error.WriteFailed at line 346, conforming to the std.io.Writer.Error interface.


351-391: readBuf implementation correctly maps errors and handles EOF.

The private readBuf method (lines 351-391) correctly maps xev read errors to std.io.Reader.Error at lines 385-390. EOF is mapped to EndOfStream, and zero bytes read also returns EndOfStream (line 389), which is correct.


439-467: Reader.stream implementation is correct.

The stream method (lines 459-467) correctly implements the streaming interface by reading into the writer's writable slice and advancing the writer. The error handling uses try, which propagates Reader.Error correctly.


486-506: Reader.readVec correctly handles vectored reads.

The readVec method (lines 486-506) correctly builds an xev.ReadBuffer from the destination vectors using platform-specific helpers (writableVectorWsa for Windows, writableVectorPosix for POSIX). It properly updates io_reader.end when reading into the internal buffer (lines 501-503).


509-525: Writer initialization is correct.

The Writer.init method (lines 513-525) correctly initializes the writer with the vtable pointing to drain and flush methods and sets up the buffer.


527-640: Writer.drain implementation handles vectored writes correctly.

The drain method (lines 527-640) implements a sophisticated strategy for vectored writes:

  • Lines 531-571: Builds up to 2 vectors from buffered data, first data slice, and splat pattern
  • Lines 574-615: Performs vectored write and handles partial writes
  • Lines 617-639: Falls back to sequential writes for remaining slices

The logic correctly handles partial writes and buffer management.


642-659: Writer.flush correctly handles partial writes.

The flush method (lines 642-659) loops until the entire buffer is drained (line 645), handles partial writes by shifting remaining data (lines 651-654), and guards against zero-progress with an error (line 649). This implementation is robust.


663-669: Reader and writer factory methods are correctly implemented.

The reader and writer methods (lines 663-669) provide clean factory functions that return the new Reader and Writer types initialized with the provided buffers.


672-709: Basic echo server test updated correctly for new interfaces.

The test at lines 672-709 correctly uses writeAll and readAll for the client, demonstrating that the basic read/write methods work with the new streaming infrastructure.


711-757: Writer splat test correctly validates splat functionality.

The test at lines 711-757 validates the splat feature by writing ["ba", "na"] with splat=3, expecting "bananana". This correctly exercises the Writer.drain splat logic.


759-805: Single-element splat test validates edge case.

The test at lines 759-805 validates the single-element splat case (["hello"] repeated 3 times), ensuring the Writer.drain method handles this edge case correctly.

Comment thread src/tcp.zig Resolved
The TLS Client's writer.flush() only encrypts buffered plaintext data
into the TCP writer's buffer but doesn't flush the TCP buffer to the
network. Both layers must be flushed explicitly to send the data.

This matches the pattern used in Zig's stdlib HTTP client implementation.
Simplifies vectored I/O construction by using the existing fromSlices helper
instead of manually building WSABUF/iovec structures. This fixes Windows
compatibility with Zig 0.15 where WSABUF fields changed from .base/.len to
.buf/.len.
Refactors drain() to match the implementation pattern from std.fs.File.Writer:
- Build up to 2 iovecs with buffered + data + splat
- Single write operation using WriteBuffer.fromSlices()
- Use io_writer.consume() for buffer accounting
- Add single-character splat optimization using temporary buffer

This eliminates manual buffer management and fallback loops, making the code
significantly cleaner and more maintainable.

@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 (2)
src/tcp.zig (2)

527-585: Potential underflow if data is empty.

Line 549 accesses data[data.len - 1] without checking if data.len > 0. If data is an empty slice (which could happen if drain is called with no data to write), this will underflow and trap at runtime.

Add an early guard:

         fn drain(io_writer: *std.io.Writer, data: []const []const u8, splat: usize) std.io.Writer.Error!usize {
             const w: *Writer = @alignCast(@fieldParentPtr("interface", io_writer));
             const buffered = io_writer.buffered();
+            
+            // Handle empty data case
+            if (data.len == 0) {
+                if (buffered.len > 0) {
+                    const n = try w.tcp_stream.writeBuf(.{ .slice = buffered });
+                    return io_writer.consume(n);
+                }
+                return 0;
+            }
 
             var vecs: [2][]const u8 = undefined;
             var len: usize = 0;

469-484: Critical: Fix incorrect limit handling in discard().

Line 473 uses @intFromEnum(limit) which only returns the union tag value (0 for .none, 1 for .bytes), not the actual byte count. This breaks the discard logic:

  • For .bytes(n), remaining becomes 1 instead of n, discarding only 1 byte
  • For .none, remaining becomes 0, discarding nothing instead of unlimited

This bug was previously flagged and needs to be fixed.

Apply this fix:

-        fn discard(io_reader: *std.io.Reader, limit: std.io.Limit) std.io.Reader.Error!usize {
-            const r: *Reader = @alignCast(@fieldParentPtr("interface", io_reader));
-            // Use the buffer as temporary storage for discarded data
-            var total_discarded: usize = 0;
-            const remaining = @intFromEnum(limit);
-
-            while (total_discarded < remaining) {
-                const to_read = @min(remaining - total_discarded, io_reader.buffer.len);
-                const n = r.tcp_stream.readBuf(.{ .slice = io_reader.buffer[0..to_read] }) catch |err| switch (err) {
-                    error.EndOfStream => break,
-                    else => return error.ReadFailed,
-                };
-                total_discarded += n;
-            }
-            return total_discarded;
-        }
+        fn discard(io_reader: *std.io.Reader, limit: std.io.Limit) std.io.Reader.Error!usize {
+            const r: *Reader = @alignCast(@fieldParentPtr("interface", io_reader));
+            var total_discarded: usize = 0;
+
+            const maybe_remaining: ?usize = switch (limit) {
+                .none => null,
+                .bytes => |count| count,
+            };
+
+            while (true) {
+                if (maybe_remaining) |remaining| {
+                    if (total_discarded >= remaining) break;
+                }
+                const max_chunk = if (maybe_remaining) |remaining|
+                    @min(remaining - total_discarded, io_reader.buffer.len)
+                else
+                    io_reader.buffer.len;
+                if (max_chunk == 0) break;
+                const n = r.tcp_stream.readBuf(.{ .slice = io_reader.buffer[0..max_chunk] }) catch |err| switch (err) {
+                    error.EndOfStream => break,
+                    else => return error.ReadFailed,
+                };
+                if (n == 0) break;
+                total_discarded += n;
+            }
+            return total_discarded;
+        }
🧹 Nitpick comments (1)
src/tcp.zig (1)

156-157: Narrow error sets for better type safety.

Defining ReadError and WriteError as anyerror is overly broad. Consider defining explicit error sets that match the actual errors returned by the underlying xev operations:

-pub const ReadError = anyerror;
-pub const WriteError = anyerror;
+pub const ReadError = error{
+    Canceled,
+    ConnectionResetByPeer,
+    EOF,
+    Unexpected,
+};
+pub const WriteError = error{
+    BrokenPipe,
+    Canceled,
+    ConnectionResetByPeer,
+    Unexpected,
+};

This provides better type safety and makes the API contract clearer.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c76dd33 and 8ab8dce.

📒 Files selected for processing (2)
  • examples/tls_demo.zig (2 hunks)
  • src/tcp.zig (12 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/tls_demo.zig
🔇 Additional comments (18)
src/tcp.zig (18)

2-2: LGTM!

The builtin import is correctly added to support OS-specific logic in the vectored I/O implementation.


27-38: LGTM!

The echo server correctly adopts the Zig 0.15 Reader/Writer interface with explicit buffers. The streaming pattern with EndOfStream handling and final flush is appropriate.


213-218: LGTM!

The read() method correctly converts EndOfStream to a zero return value, following the standard library convention where 0 indicates EOF.


220-231: LGTM!

The readAll() implementation correctly handles partial reads and EOF, following the standard pattern of looping until the buffer is filled or the stream ends.


233-237: LGTM!

The write() method correctly delegates to writeBuf() with a simple slice wrapper.


239-248: LGTM!

The writeAll() implementation correctly handles partial writes, following the standard pattern of looping until all data is written.


250-256: LGTM!

The readVec() method correctly implements vectored I/O with proper empty-slice handling and appropriate error types.


258-264: LGTM!

The writeVec() method correctly implements vectored I/O with proper empty-slice handling and appropriate error types.


266-308: LGTM!

The shutdown() method correctly implements the asynchronous shutdown pattern with appropriate error types.


310-347: LGTM!

The writeBuf() private method correctly implements low-level writes with appropriate error mapping to std.io.Writer.Error.


349-391: LGTM!

The readBuf() private method correctly implements low-level reads with appropriate error mapping to std.io.Reader.Error. The handling of EOF and zero-byte reads as EndOfStream is correct.


459-467: LGTM!

The stream() method correctly implements the streaming interface, reading data and advancing the writer appropriately.


486-506: LGTM!

The readVec() method correctly implements vectored reads with OS-specific handling and proper buffer management for internal buffering.


587-604: LGTM!

The flush() method correctly handles partial writes by looping until the buffer is empty, with proper buffer shifting on partial writes. The zero-progress guard is appropriate.


607-614: LGTM!

The reader() and writer() accessor methods correctly delegate to the respective init() constructors, providing a clean public API for the Zig 0.15 streaming interface.


617-654: LGTM!

The basic echo test correctly uses the updated API with writeAll() and readAll() methods.


656-702: LGTM!

The Writer splat handling test correctly verifies the splat functionality with proper setup, execution, and validation of the expected "bananana" output.


704-750: LGTM!

The Writer splat with single element test correctly verifies the splat functionality for single-element patterns, expecting "hellohellohello" output.

Creates a new io.zig module with generic StreamReader and StreamWriter
implementations that work with any type implementing readBuf/writeBuf methods.

Changes:
- Create src/io.zig with generic StreamReader(T) and StreamWriter(T)
- Make TcpStream.readBuf/writeBuf public
- Add File.readBuf/writeBuf methods
- Update TcpStream to use generic reader/writer (reduces ~170 lines)
- Add File.reader/writer methods using generic implementations
- Add test for File reader/writer with splat functionality

This enables code reuse between TCP and File I/O, with a single implementation
of complex features like vectored I/O and single-character splat optimization.
Any future types (UDP, pipes, etc.) can use the same reader/writer by
implementing readBuf/writeBuf.
- Change readBuf signature to take *xev.ReadBuffer instead of by value
  - Required to properly support .array variant which needs mutation
  - File and TcpStream callbacks now copy .array data back to caller's buffer
  - TcpStream.read() and File read methods updated to pass pointer

- Change StreamReader/StreamWriter to use *T instead of *const T
  - TcpStream.reader/writer and File.reader/writer use @constcast when calling init
  - Actual streams don't mutate themselves (mutation happens via runtime/event loop)
  - Mock BufferStream needs mutation for synchronous operation

- Add BufferStream mock type for testing
  - In-memory buffer implementation for cross-platform testing
  - Implements readBuf/writeBuf for StreamReader/StreamWriter compatibility
  - Returns error.EndOfStream on EOF (not 0)

- Add 11 comprehensive tests covering:
  - Basic write and read operations
  - writeSplat with patterns, single element, single character optimization
  - writeVec with multiple slices
  - Flush behavior
  - EOF handling (readSliceShort catches EndOfStream and returns 0)
  - Partial reads then EOF
  - Discard bytes
  - Interleaved read/write operations
  - Empty writes

All tests pass
WSABUF.buf requires [*]u8 (mutable pointer) even though WSASend doesn't
modify the data. Cast away const to satisfy Windows API requirements.

This fixes compilation error when building for Windows target:
error: expected type '[*]u8', found '[*]const u8'

The cast is safe because WSASend only reads from the buffer.

@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

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ff954a5 and bad6f94.

📒 Files selected for processing (5)
  • src/coroutines.zig (3 hunks)
  • src/file.zig (4 hunks)
  • src/io.zig (1 hunks)
  • src/tcp.zig (12 hunks)
  • vendor/libxev/src/backend/iocp.zig (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • vendor/libxev/src/backend/iocp.zig

Comment thread src/coroutines.zig Resolved
Comment thread src/io.zig Resolved
Comment thread src/io.zig Resolved
)

Windows overlapped I/O (required for IOCP) doesn't maintain file position
automatically. All read/write operations were using uninitialized offset
values in the OVERLAPPED structure, causing unpredictable behavior.

Changes:

1. Add position tracking to File struct (src/file.zig)
   - Track position starting at 0 (POSIX-compatible)
   - Convert read/write to use pread/pwrite with tracked position
   - Add seek() method for manual position control
   - Update position after each successful operation

2. Fix libxev IOCP backend bugs (vendor/libxev/src/backend/iocp.zig)
   - Fix pread error handler returning .read instead of .pread
   - Fix pwrite error handler returning .write instead of .pwrite
   - Add HANDLE_EOF handling for pread operations

3. Add build-tests step for cross-compilation testing (build.zig)

The solution uses pread/pwrite everywhere with manual position tracking,
which works consistently across all platforms and eliminates Windows's
uninitialized offset issue entirely.

All tests pass on both Linux (native) and Windows (wine): 37/37
34fa508 windows: fix zig 0.15 callconv
d5a191d bench: fix Zig 0.15 errors
2e57f0d update ci to Zig 0.15
4e6592b build(deps): bump actions/checkout from 4 to 5 (#187)
96a08cd build: update for Zig 0.15.1
ae62fb5 build(deps): bump namespacelabs/nscloud-cache-action from 1.2.12 to 1.2.18 (#192)
9d299bc build(deps): bump namespacelabs/nscloud-cache-action
a5519f1 build(deps): bump actions/checkout from 4 to 5

git-subtree-dir: vendor/libxev
git-subtree-split: 34fa50878aec6e5fa8f532867001ab3c36fae23e

@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

🧹 Nitpick comments (3)
src/file.zig (3)

244-294: Consider preserving more error detail.

The implementation correctly tracks position and handles xev.ReadBuffer types. However, error mapping at lines 288-291 converts all non-EOF errors to ReadFailed, losing diagnostic information.

If diagnostic context matters, consider preserving error types or logging:

     const bytes_read = result_data.result catch |err| switch (err) {
         error.EOF => return error.EndOfStream,
-        else => return error.WriteFailed,
+        else => |e| {
+            std.log.warn("readBuf failed: {}", .{e});
+            return error.ReadFailed;
+        },
     };

296-337: LGTM, but consider preserving error detail.

The implementation is correct and symmetric with readBuf(). Same optional improvement applies: error mapping at line 334 discards specific error types.

If needed:

-    const bytes_written = result_data.result catch return error.WriteFailed;
+    const bytes_written = result_data.result catch |e| {
+        std.log.warn("writeBuf failed: {}", .{e});
+        return error.WriteFailed;
+    };

531-585: Test provides basic coverage; consider edge cases.

The test validates the happy path for reader/writer interfaces. For more robust validation, consider adding tests for:

  • Partial reads/writes when buffer is smaller than data
  • Seek integration with streaming interface
  • Error conditions (e.g., reading from write-only file)
  • Flush behavior with unfilled buffer
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bad6f94 and 9f23c00.

📒 Files selected for processing (4)
  • build.zig (3 hunks)
  • check.sh (1 hunks)
  • src/file.zig (6 hunks)
  • vendor/libxev/src/backend/iocp.zig (3 hunks)
🔇 Additional comments (11)
build.zig (5)

11-19: LGTM! Correct Zig 0.15 API migration.

The migration to addLibrary with root_module created via createModule and explicit .linkage = .static is correct for Zig 0.15.

Note: A previous review flagged a missing libxev declaration in build.zig.zon. Since that file is not provided in the current review, verify separately that build.zig.zon contains the required dependency entry.


24-29: LGTM! Module creation for dependency injection.

The separate module creation allows examples and tests to import zio correctly. The API usage is appropriate for Zig 0.15.


43-60: LGTM! Consistent API usage for executables.

The example executables correctly use createModule with the same pattern as the library, maintaining consistency across the build script.


63-71: LGTM! Test configuration with custom runner.

The test creation follows the same createModule pattern, and the custom test runner aligns with the PR objective of centralizing test-runner logging.


76-79: LGTM! Useful addition for cross-compilation.

The new build-tests step is a valuable ergonomic improvement that enables building tests for cross-compilation targets where execution on the host isn't possible.

vendor/libxev/src/backend/iocp.zig (3)

1089-1091: LGTM! Correct error handling for pread.

The result variant now correctly matches the operation type (.pread instead of .read), and adding HANDLE_EOF => error.EOF properly handles end-of-file conditions for positioned reads.


1120-1120: LGTM! Correct error handling for pwrite.

The result variant now correctly matches the operation type (.pwrite instead of .write). Note that unlike pread, no HANDLE_EOF case is needed here, as write operations don't encounter end-of-file conditions.


1560-1564: LGTM! Necessary const cast for Windows API.

The comment clearly explains why @constCast is required: Windows WSABUF.buf is typed as [*]u8 (non-const) even though WSASend doesn't modify the buffer. This is a standard pattern when interfacing with C APIs that don't use const correctly, and the cast is safe here since the data is only read during send operations.

src/file.zig (3)

30-77: LGTM!

The switch from read to pread with manual position tracking is implemented correctly. Position is only updated after a successful read, preventing corruption on errors.


79-126: LGTM!

The write implementation mirrors the read logic correctly, using pwrite with tracked position and updating only on success.


381-391: Verified StreamReader/StreamWriter compatibility.
io.StreamReader and io.StreamWriter are exported in src/io.zig and correctly invoke File’s readBuf/writeBuf.

Comment thread check.sh
Comment on lines +74 to +75
zig build build-tests
timeout 30s ./zig-out/bin/test

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

Provide a fallback when timeout is unavailable.

timeout ships with GNU coreutils, so the script now exits with command not found on standard macOS setups where only BSD utilities are present. That’s a regression for anyone running the checks locally. Please gate the call with a command -v check (fall back to gtimeout or no timeout) so the script still works outside CI.

-zig build build-tests
-timeout 30s ./zig-out/bin/test
+zig build build-tests
+if command -v timeout >/dev/null 2>&1; then
+    timeout 30s ./zig-out/bin/test
+elif command -v gtimeout >/dev/null 2>&1; then
+    gtimeout 30s ./zig-out/bin/test
+else
+    ./zig-out/bin/test
+fi
📝 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
zig build build-tests
timeout 30s ./zig-out/bin/test
zig build build-tests
if command -v timeout >/dev/null 2>&1; then
timeout 30s ./zig-out/bin/test
elif command -v gtimeout >/dev/null 2>&1; then
gtimeout 30s ./zig-out/bin/test
else
./zig-out/bin/test
fi
🤖 Prompt for AI Agents
In check.sh around lines 74 to 75, the script unconditionally calls `timeout`
which fails on macOS where BSD coreutils are used; update the script to detect
available timeout variants and fall back gracefully: check `command -v timeout`
first, then `command -v gtimeout`, and if neither exists run the test binary
without a timeout; replace the direct `timeout 30s ./zig-out/bin/test`
invocation with logic that selects the available command (or no timeout) before
executing the test so the script works locally and in CI.

Comment thread src/file.zig
Comment on lines +11 to +14
/// File position for sequential read/write operations.
/// On Windows with overlapped I/O, we track this ourselves since the OS doesn't.
/// Starts at 0, matching POSIX behavior for newly opened files.
position: u64 = 0,

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.

🛠️ Refactor suggestion | 🟠 Major

🧩 Analysis chain

Verify thread-safety of position tracking.

The position field is mutated by read(), write(), readBuf(), writeBuf(), and seek() without synchronization. If multiple coroutines can call these methods concurrently on the same File instance, race conditions will occur (e.g., two reads could use the same offset, or position updates could be lost).

Confirm whether:

  1. File instances are intended for single-coroutine use only, or
  2. Synchronization (e.g., mutex) is needed around position access

🏁 Script executed:

#!/bin/bash
# Search for concurrent File usage patterns or documentation about thread-safety
rg -nP --type=zig -C3 '\bFile\b.*concurrent|thread.*safe|mutex|lock' 

Length of output: 68339


🏁 Script executed:

#!/bin/bash
# Locate the File struct definition and surrounding documentation in src/file.zig
rg -nP --type=zig 'pub\s+const\s+File\s*=' -C10 src/file.zig

Length of output: 713


🏁 Script executed:

#!/bin/bash
# Locate xev.File definition and surrounding docs in vendor/libxev/src/watcher/file.zig
rg -nP --type=zig 'pub\s+const\s+File\s*=' -C10 vendor/libxev/src/watcher/file.zig

Length of output: 0


🏁 Script executed:

#!/bin/bash
# Broad search for File definition in vendor/libxev
rg -nP --type=zig 'pub\s+const\s+File' -n vendor/libxev

Length of output: 251


Document or guard File.position thread-safety
position (lines 11–14) is mutated by read(), write(), seek(), etc., with no synchronization; concurrent calls will race. Either protect position (e.g., mutex or atomic) or clearly document that File is single-coroutine only.

🤖 Prompt for AI Agents
In src/file.zig around lines 11 to 14, the File.position field is mutated by
read/write/seek without synchronization which causes races; fix by either making
position thread-safe (change to an atomic(u64) and use atomic
loads/stores/fetch-add where appropriate, or add a mutex/lock around every
access and update in read/write/seek/seek-relative operations) or clearly
document API invariants (add a prominent comment and public docs stating File is
not safe for concurrent use and require callers to serialize access); implement
one of these approaches consistently across all methods that touch position.

Comment thread src/file.zig
Comment on lines +131 to 150
pub fn seek(self: *File, offset: i64, whence: std.fs.File.SeekableStream.SeekFrom) !u64 {
const new_pos: u64 = switch (whence) {
.start => blk: {
if (offset < 0) return error.InvalidOffset;
break :blk @intCast(offset);
},
.current => blk: {
const current: i64 = @intCast(self.position);
const result = current + offset;
if (result < 0) return error.InvalidOffset;
break :blk @intCast(result);
},
.end => {
// Seeking from end requires getting file size, which we don't support yet
return error.Unsupported;
},
};
self.position = new_pos;
return new_pos;
}

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

Integer overflow risk in seek from current position.

Line 138 casts self.position (u64) to i64. If position exceeds std.math.maxInt(i64) (~9 exabytes), the cast will overflow and produce incorrect results.

Consider this safer implementation:

         .current => blk: {
-            const current: i64 = @intCast(self.position);
-            const result = current + offset;
-            if (result < 0) return error.InvalidOffset;
-            break :blk @intCast(result);
+            if (offset < 0) {
+                const abs_offset: u64 = @intCast(-offset);
+                if (abs_offset > self.position) return error.InvalidOffset;
+                break :blk self.position - abs_offset;
+            } else {
+                const abs_offset: u64 = @intCast(offset);
+                break :blk self.position + abs_offset;
+            }
         },

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/file.zig around lines 131 to 150, the code unsafely casts self.position
(u64) to i64 which can overflow if position > std.math.maxInt(i64); before
casting, check if self.position is greater than std.math.maxInt(i64) and return
an appropriate error (e.g., error.InvalidOffset or error.Unsupported), then
safely cast to i64 and compute result = current + offset while preserving the
existing negative-check; ensure any arithmetic that could overflow is guarded by
these bounds checks so the seek-from-current branch cannot produce an incorrect
wraparound.

@lalinsky
lalinsky merged commit 10154a5 into main Oct 3, 2025
@lalinsky
lalinsky deleted the zig-0.15 branch October 3, 2025 07:48
dimenus pushed a commit to dimenus/zio that referenced this pull request Nov 14, 2026
…a race sibling's cancel cannot hide a lost one (round 4, finding 2)

## Problem

Round 4 of the outside review (of 0c0b061), finding 2. The op model's end
gave every waiting op its readiness at once. In a race group with
receives R1 and R2, if R1's registration was lost, R2 completed, the race
cancelled R1, and R1's `Canceled` was accepted as a sibling's cancel. The
proof was also counted when given, not when it worked, and the end's
settle still ran the random in-poll actions (closes, cancels,
follow-ups).

## Measured (ran)

Mutant RM2, "a race member's park does not register": in `submitSimDgram`
the second parked member of a group skips `dgramPark` (the first keeps
its registration, as in the review's sequence). RM, which strands every
member, is killed mid-run by the wake obligation already (seed 1, step
101), so it never reaches the end.

| run | old end (all at once) | new end (one at a time) |
|---|---|---|
| default length (8 seeds x 5000) | KILLED mid-run, seed 1 step 1800 | KILLED mid-run, seed 1 step 1800 |
| the end alone (`ZIO_OP_MODEL_STEPS=0`), 3 runs | SURVIVED, 3 of 3 | KILLED, 3 of 3: `seed 1 step 0: d_recv op #1 still waits on a socket with 1 datagrams queued` |

The "old end" here is the old procedure with the end groups below added,
so both columns prove the same ops.

## Changes (src/sim_op_model_test.zig)

- **End groups:** the end empties the queues (each a checked layer
  receive), then submits race groups of two waiting receives on sockets
  with nothing queued or waiting, so the proof has race members to prove
  (`end_groups`, required non-zero; 10 at the default length).
- **One at a time:** one waiting op is given what it waits for, and the
  clock settles before the next. A proof counts only when that op
  completes from it; a proving op that ends `Canceled` fails. The proof is
  recorded by the op's own completion, because its slot can be freed and
  reused by the time the settle ends.
- **No random actions during the proof:** `inBatch` and the group
  callback's follow-ups are off.
- A replay with `ZIO_OP_MODEL_STEPS` is a diagnostic: the counter floors
  and the probes are skipped (as for `ZIO_OP_MODEL_SEED`).

Two test bugs on the way, fixed above: the first version read the proven
op through its slot after a follow-up had reused it ("op lalinsky#5 ... group
null still waits", where op lalinsky#2 had been given and completed); follow-ups
are now off in the proof, and the proof is recorded at completion.

## Benefits

- A lost registration of a race member is found when that member is the
  one given readiness; a cancelled sibling is no longer counted as proven.

## Alternatives rejected, and what this depends on

- **Prove every member of a race group.** Once one completes, the race
  cancels the rest by design; the one-at-a-time order proves the member
  chosen, and the others are only cancelled.
- **A sim accessor that lists registered ops.** It would check the sim
  against itself; readiness checks behaviour.
- Depends on: a race member that completes cancels its siblings at once
  (`Group.groupCallback`), so the next waiting op chosen is never a member
  of a group already proven.

## Statistics

- src/sim_op_model_test.zig: about +90 -30.
- Sim tests (`-Dtest-filter="sim: "`): 224 of 224 passed, 2 skipped (with
  the next commit's test).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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