Skip to content

Add vectored I/O (readv/writev) support to libxev - #11

Merged
lalinsky merged 7 commits into
mainfrom
feature/libxev-vectored-io
Sep 29, 2025
Merged

lalinsky merged 7 commits into
mainfrom
feature/libxev-vectored-io

Conversation

@lalinsky

@lalinsky lalinsky commented Sep 28, 2025 •

Copy link
Copy Markdown
Owner

Summary

This PR adds comprehensive vectored I/O support to libxev, enabling efficient scatter-gather operations across all supported backends.

Changes

  • Add vectors variant to ReadBuffer and WriteBuffer unions
  • Implement vectored I/O in all 5 backends:
    • io_uring: Uses prep_readv/prep_writev for optimal performance
    • epoll: Uses posix.readv/writev/preadv/pwritev
    • kqueue: Uses posix.readv/writev/preadv/pwritev
    • IOCP: Uses WSASend/WSARecv with multiple WSABUF structures
    • wasi_poll: Uses native iovec support
  • Update all high-level watchers (File, Stream, TCP, UDP) to support vectors
  • Add proper partial write handling for vectored operations
  • Add comprehensive test coverage for vectored file I/O
  • Dynamic API intentionally excludes vectors (common subset design)

Features

✅ Unified API across platforms
✅ Zero-copy operations
✅ Optimal backend-specific implementations
✅ Backward compatible
✅ Comprehensive test coverage
✅ Proper partial write handling

Usage Example

// Create vectors pointing to your data
var vectors = [_]std.posix.iovec_const{
    .{ .base = buf1.ptr, .len = buf1.len },
    .{ .base = buf2.ptr, .len = buf2.len },
    .{ .base = buf3.ptr, .len = buf3.len },
};

// Use with any libxev watcher
file.write(&loop, &completion, .{ .vectors = &vectors }, ...);
tcp.write(&loop, &completion, .{ .vectors = &vectors }, ...);
udp.send(&loop, &completion, .{ .vectors = &vectors }, ...);

Test Plan

  • All backends compile successfully
  • Vectored file I/O test passes
  • Existing tests remain unaffected
  • Partial write handling works correctly
  • Dynamic API properly excludes vectors

Performance Benefits

Vectored I/O provides significant performance benefits for applications that need to:

  • Send/receive data from multiple non-contiguous buffers
  • Avoid memory copying operations
  • Implement efficient protocol serialization
  • Handle scatter-gather network operations

The implementation uses the most efficient vectored I/O mechanism available on each platform while providing a unified high-level API.

Summary by CodeRabbit

  • New Features

    • Added vectored (multi-buffer) I/O support across all backends and watcher paths; buffer types gain multi-buffer constructors.
  • Bug Fix / Behavior

    • Dynamic wrappers updated: dynamic API explicitly rejects vectored buffers; new fromSlices helpers added for constructing multi-buffer buffers.
  • Tests / CI

    • CI and check script now run the bundled library's unit tests as an additional test stage.

This commit adds comprehensive vectored I/O support to libxev, enabling
efficient scatter-gather operations across all supported backends.

Changes:
- Add `vectors` variant to ReadBuffer and WriteBuffer unions
- Implement vectored I/O in all 5 backends:
  * io_uring: Uses prep_readv/prep_writev for optimal performance
  * epoll: Uses posix.readv/writev/preadv/pwritev
  * kqueue: Uses posix.readv/writev/preadv/pwritev
  * IOCP: Uses WSASend/WSARecv with multiple WSABUF structures
  * wasi_poll: Uses native iovec support
- Update all high-level watchers (File, Stream, TCP, UDP) to support vectors
- Add proper partial write handling for vectored operations
- Add comprehensive test coverage for vectored file I/O
- Dynamic API intentionally excludes vectors (common subset design)

The implementation provides a unified API across platforms while using
the most efficient vectored I/O mechanism available on each backend.
Existing code remains fully backward compatible.

Usage:
```zig
var vectors = [_]std.posix.iovec_const{
    .{ .base = buf1.ptr, .len = buf1.len },
    .{ .base = buf2.ptr, .len = buf2.len },
};
file.write(&loop, &completion, .{ .vectors = &vectors }, ...);
```
@coderabbitai

coderabbitai Bot commented Sep 28, 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 19 minutes and 32 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 6df26aa and 9693428.

📒 Files selected for processing (6)
  • vendor/libxev/src/backend/epoll.zig (6 hunks)
  • vendor/libxev/src/backend/io_uring.zig (9 hunks)
  • vendor/libxev/src/backend/iocp.zig (10 hunks)
  • vendor/libxev/src/backend/kqueue.zig (8 hunks)
  • vendor/libxev/src/backend/wasi_poll.zig (8 hunks)
  • vendor/libxev/src/dynamic.zig (4 hunks)

Walkthrough

Adds vectored I/O support across backends by introducing ReadBuffer.vectors and WriteBuffer.vectors variants with fromSlices helpers, wiring those variants to vectored syscalls / backend APIs (readv/preadv/writev/pwritev, io_uring prep_readv/prep_writev, WSABUF for IOCP), and runs vendor/libxev tests in CI.

Changes

Cohort / File(s) Summary of Changes
POSIX & io_uring backends
vendor/libxev/src/backend/epoll.zig, vendor/libxev/src/backend/kqueue.zig, vendor/libxev/src/backend/wasi_poll.zig, vendor/libxev/src/backend/io_uring.zig
Add ReadBuffer.vectors and WriteBuffer.vectors (iovec / iovec_const with len) and fromSlices constructors; route .vectors to readv/preadv/writev/pwritev or prep_readv/prep_writev; adjust submission/completion and EOF/result handling for vectors.
Windows IOCP backend
vendor/libxev/src/backend/iocp.zig
Add vectors variants and fromSlices; replace single wsa_buffer fields with wsa_buffers: [8]WSABUF; translate .slice/.array/.vectors into WSABUF arrays and pass buffer_count to WSARecv/WSASend variants.
Dynamic API
vendor/libxev/src/dynamic.zig
Add fromSlices helpers for dynamic buffers; make fromBackend explicitly handle .slice and .array and panic for .vectors with "vectors not supported in dynamic API".
Watchers (file, stream, udp)
vendor/libxev/src/watcher/file.zig, vendor/libxev/src/watcher/stream.zig, vendor/libxev/src/watcher/udp.zig
Accept .vectors in read/write/pread/pwrite/send/recv paths; handle empty vectors, compute lengths, advance/split vectors for remainders, and map into backend-specific iov/WSABUF structures.
Completion / Operation structs
vendor/libxev/src/backend/* (multiple)
Update completion/operation fields and result handling to include .vectors cases (EOF, bytes, error) across backends; adjust op fields (e.g., wsa_buffer -> wsa_buffers) where needed.
Build & CI
.github/workflows/test.yml, check.sh
Add CI/test step to run zig build test in vendor/libxev; check.sh now runs xev unit tests by cd'ing into vendor/libxev and invoking zig build test.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor App
  participant Watcher as Watcher
  participant Backend as Backend Router
  participant OS as Kernel / Syscall

  App->>Watcher: submit op(buffer: slice/array/vectors, offset?)
  Watcher->>Watcher: validate/compute length, adjust vectors
  Watcher->>Backend: enqueue op (includes buffer.variant)

  alt POSIX (epoll/kqueue/wasi)
    Backend->>OS: slice/array -> read/write/pread/pwrite/recv/send
    Backend->>OS: vectors -> readv/preadv/writev/pwritev
  else io_uring
    Backend->>OS: slice/array -> prep_read/prep_write
    Backend->>OS: vectors -> prep_readv/prep_writev
  else Windows IOCP
    Backend->>Backend: build WSABUF[n]
    Backend->>OS: WSARecv/WSASend(WSABUF array)
  end

  OS-->>Backend: completion (n / EOF / error)
  Backend-->>Watcher: result
  Watcher-->>App: callback/result
Loading
sequenceDiagram
  autonumber
  actor App
  participant Dyn as Dynamic API
  App->>Dyn: fromBackend(ReadBuffer with .vectors)
  Dyn-->>App: panic "vectors not supported in dynamic API"
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

I bundle bytes in tiny rows,
Two iovecs hop where data goes.
Readv and writev clap their paws,
WSABUF lines up for applause.
CI hums, the rabbit dances, because. 🐇

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, namely adding vectored I/O support via readv/writev to libxev, and avoids unnecessary detail or noise, making it immediately clear to reviewers what the PR implements.
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.

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

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)

1747-1766: Blocker: vectors variant breaks multiple kqueue switches

The new .vectors arms on ReadBuffer/WriteBuffer aren’t reflected in all the switches over these unions. In this file we still have switches that only cover .slice/.array (e.g., the .sendto/.recvfrom cases and the machport kevent builder), so the compiler now issues switch must handle all possibilities errors (see the CI failure). Please add explicit handling for the vectored branch—either by wiring it up (e.g., translate into sendmsg/recvmsg with multiple iovec) or by rejecting it in a defined way—so the backend builds again.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6393de2 and 2cbff64.

📒 Files selected for processing (9)
  • vendor/libxev/src/backend/epoll.zig (6 hunks)
  • vendor/libxev/src/backend/io_uring.zig (9 hunks)
  • vendor/libxev/src/backend/iocp.zig (5 hunks)
  • vendor/libxev/src/backend/kqueue.zig (6 hunks)
  • vendor/libxev/src/backend/wasi_poll.zig (4 hunks)
  • vendor/libxev/src/dynamic.zig (2 hunks)
  • vendor/libxev/src/watcher/file.zig (4 hunks)
  • vendor/libxev/src/watcher/stream.zig (5 hunks)
  • vendor/libxev/src/watcher/udp.zig (6 hunks)
🧰 Additional context used
🪛 GitHub Actions: CI
vendor/libxev/src/backend/kqueue.zig

[error] 1077-1077: Zig compile error: switch must handle all possibilities in v.buffer.


[error] 1179-1179: Zig compile error: switch must handle all possibilities in op.buffer.

Comment thread vendor/libxev/src/backend/iocp.zig Resolved
Comment thread vendor/libxev/src/watcher/stream.zig Resolved
Comment thread vendor/libxev/src/watcher/udp.zig Resolved
Comment thread vendor/libxev/src/watcher/udp.zig Resolved
Repository owner deleted a comment from claude Bot Sep 28, 2025
Repository owner deleted a comment from claude Bot Sep 28, 2025

@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 (2)
vendor/libxev/src/backend/io_uring.zig (1)

1074-1123: Dropping excess slices corrupts vectored I/O

fromSlices silently truncates any slice past vecs.data.len (currently 2), so a call such as ReadBuffer.fromSlices(&.{buf_a, buf_b, buf_c}) will issue the read with only the first two iovecs. The data that was supposed to land in buf_c is simply never mapped into a kernel iovec, so the completer reports success while buf_c stays untouched. The same issue exists for WriteBuffer.fromSlices, which will gather at most two pieces and drop the rest. As soon as a caller hands us more than two chunks we start losing data.

Please either carry the full slice set (e.g. keep a dynamically-sized []posix.iovec or fall back to allocating a temporary contiguous buffer) or at the very least detect slices.len > vecs.data.len and reject the operation. Silently discarding the tail makes vectored I/O fundamentally unsafe.

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

562-632: File vectored I/O needs ReadFileScatter/WriteFileGather

The .vectors branches call ReadFile/WriteFile on only the first WSABUF, with a comment “Windows ReadFile doesn't support vectored I/O”. That’s true, but the platform APIs that do support scatter/gather for files are ReadFileScatter and WriteFileGather, which require page-aligned buffers and lengths that are multiples of the volume sector size. Using ReadFile/WriteFile ignores every buffer beyond index 0, so any caller that passes more than one slice sees silent data loss exactly like the POSIX backends above. Either plumb vectored files through ReadFileScatter/WriteFileGather and validate the alignment constraints, or fail fast when vecs.len > 1 instead of pretending the extra buffers were serviced.(learn.microsoft.com)

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2cbff64 and 3cbe0ed.

📒 Files selected for processing (11)
  • .github/workflows/test.yml (1 hunks)
  • check.sh (1 hunks)
  • vendor/libxev/src/backend/epoll.zig (6 hunks)
  • vendor/libxev/src/backend/io_uring.zig (9 hunks)
  • vendor/libxev/src/backend/iocp.zig (10 hunks)
  • vendor/libxev/src/backend/kqueue.zig (8 hunks)
  • vendor/libxev/src/backend/wasi_poll.zig (8 hunks)
  • vendor/libxev/src/dynamic.zig (4 hunks)
  • vendor/libxev/src/watcher/file.zig (3 hunks)
  • vendor/libxev/src/watcher/stream.zig (5 hunks)
  • vendor/libxev/src/watcher/udp.zig (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • vendor/libxev/src/watcher/udp.zig
  • vendor/libxev/src/backend/wasi_poll.zig
  • vendor/libxev/src/dynamic.zig
🔇 Additional comments (2)
vendor/libxev/src/backend/iocp.zig (1)

1507-1563: Same truncation bug as io_uring

ReadBuffer.fromSlices/WriteBuffer.fromSlices here cap the data at [2]WSABUF and drop anything past vecs.data.len. The Windows backend therefore shares the same data-loss bug the POSIX path has: any vectored operation with more than two segments will quietly ignore the tail. Please fix or reject the call instead of building an incomplete WSABUF array.

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

1750-1806: Same vectored truncation (see io_uring comment)

fromSlices here is identical to the io_uring version: it unconditionally copies at most two entries into the fixed [2]posix.iovec and silently forgets the rest. Any user that relies on scatter/gather with more than two segments hits partial reads/writes. Please adopt the same fix as suggested for io_uring.zig.

Comment on lines +1303 to +1323
/// Contains up to 2 iovecs for efficient syscall usage.
vectors: struct {
data: [2]posix.iovec,
len: usize,
},

/// Create a ReadBuffer from a slice of byte slices, automatically
/// choosing the optimal representation (slice for single buffer,
/// vectors for multiple buffers).
pub fn fromSlices(slices: [][]u8) ReadBuffer {
if (slices.len == 0) return .{ .slice = &.{} };
if (slices.len == 1) return .{ .slice = slices[0] };

// Convert to platform-specific iovec format for vectored I/O
var data: [2]posix.iovec = undefined;
const len = @min(slices.len, 2);
for (slices[0..len], 0..) |slice, i| {
data[i] = .{ .base = slice.ptr, .len = slice.len };
}
return .{ .vectors = .{ .data = data, .len = len } };
}

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

Do not silently drop extra read buffers

@min(slices.len, 2) means any ReadBuffer.fromSlices(&.{ buf0, buf1, buf2, … }) will only keep the first two buffers and silently ignore the rest. On readv/preadv/recv this manifests as missing data with no error, which is a correctness/data-loss bug. We either need to preserve every buffer (e.g. store an arbitrarily sized iovec list or copy into a single slice) or fail fast when the caller supplies more buffers than we can represent so the corruption is detectable. Please rework this so extra buffers are never just dropped.

🤖 Prompt for AI Agents
In vendor/libxev/src/backend/epoll.zig around lines 1303 to 1323 the
ReadBuffer.fromSlices implementation silently drops any buffers beyond the first
two by using @min(slices.len, 2); change this so extra buffers are never
ignored: add a runtime check that if slices.len > 2 the function fails fast
(return an explicit error or propagate an error union) or alternatively
implement full support by allocating and populating a dynamically sized
posix.iovec array (or concatenate into a single contiguous buffer) so all input
slices are preserved; pick one approach and update the function signature/return
path accordingly so callers can detect and handle the too-many-buffers case
instead of losing data.

Comment thread vendor/libxev/src/backend/epoll.zig Resolved
Comment on lines +1041 to +1066
var result = xev.WriteBuffer{ .vectors = .{ .data = undefined, .len = 0 } };
var skip = offset;

for (vecs.data[0..vecs.len]) |vec| {
if (skip >= vec.len) {
skip -= vec.len;
continue;
}

// Copy remaining vectors, adjusting the first one
if (skip > 0) {
result.vectors.data[result.vectors.len] = .{
.base = vec.base + skip,
.len = vec.len - skip,
};
skip = 0;
} else {
result.vectors.data[result.vectors.len] = vec;
}
result.vectors.len += 1;

// Stop if we've filled our result array
if (result.vectors.len >= 2) break;
}
return result;
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Don't silently drop remaining vectors on partial writes

writeBufferRemainder copies at most two slices before breaking, so any partial write against a WriteBuffer.vectors with three or more segments will quietly truncate the tail of the request. That turns every retry into a data-loss bug. Please keep consuming until we've reached the end of the vector list (or assert that the remainder fits in the available capacity) instead of stopping after two entries.

I’d expect something along these lines:

-                    for (vecs.data[0..vecs.len]) |vec| {
+                    for (vecs.data[0..vecs.len]) |vec| {
                         if (skip >= vec.len) {
                             skip -= vec.len;
                             continue;
                         }
 
-                        // Copy remaining vectors, adjusting the first one
-                        if (skip > 0) {
-                            result.vectors.data[result.vectors.len] = .{
-                                .base = vec.base + skip,
-                                .len = vec.len - skip,
-                            };
-                            skip = 0;
-                        } else {
-                            result.vectors.data[result.vectors.len] = vec;
-                        }
-                        result.vectors.len += 1;
-
-                        // Stop if we've filled our result array
-                        if (result.vectors.len >= 2) break;
-                    }
+                        assert(result.vectors.len < result.vectors.data.len);
+
+                        if (skip > 0) {
+                            result.vectors.data[result.vectors.len] = .{
+                                .base = vec.base + skip,
+                                .len = vec.len - skip,
+                            };
+                            skip = 0;
+                        } else {
+                            result.vectors.data[result.vectors.len] = vec;
+                        }
+                        result.vectors.len += 1;
+                    }
+                    assert(skip == 0);
                     return result;
                 },

That way callers either get a complete remainder or a hard failure they can debug, never a silently truncated write.

📝 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
var result = xev.WriteBuffer{ .vectors = .{ .data = undefined, .len = 0 } };
var skip = offset;
for (vecs.data[0..vecs.len]) |vec| {
if (skip >= vec.len) {
skip -= vec.len;
continue;
}
// Copy remaining vectors, adjusting the first one
if (skip > 0) {
result.vectors.data[result.vectors.len] = .{
.base = vec.base + skip,
.len = vec.len - skip,
};
skip = 0;
} else {
result.vectors.data[result.vectors.len] = vec;
}
result.vectors.len += 1;
// Stop if we've filled our result array
if (result.vectors.len >= 2) break;
}
return result;
},
var result = xev.WriteBuffer{ .vectors = .{ .data = undefined, .len = 0 } };
var skip = offset;
for (vecs.data[0..vecs.len]) |vec| {
if (skip >= vec.len) {
skip -= vec.len;
continue;
}
// Ensure we never overflow the result buffer
assert(result.vectors.len < result.vectors.data.len);
if (skip > 0) {
result.vectors.data[result.vectors.len] = .{
.base = vec.base + skip,
.len = vec.len - skip,
};
skip = 0;
} else {
result.vectors.data[result.vectors.len] = vec;
}
result.vectors.len += 1;
}
// We must have consumed the full offset or panic early
assert(skip == 0);
return result;
🤖 Prompt for AI Agents
In vendor/libxev/src/watcher/stream.zig around lines 1041-1066 the loop in
writeBufferRemainder stops after collecting two slices which silently truncates
the remainder when the original WriteBuffer.vectors has three+ segments; either
iterate until you've consumed the entire input vecs (no early break) and append
all remaining slices into result (respecting result.vectors capacity), or
explicitly check/assert that the remainder will fit the result capacity up front
and return a hard failure if it doesn't; ensure you do not silently drop
segments by removing the `if (result.vectors.len >= 2) break;` pattern and
replacing it with proper capacity checks and an explicit error or panic when
capacity would be exceeded.

@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

🧹 Nitpick comments (1)
vendor/libxev/src/watcher/stream.zig (1)

1011-1015: Guard against length accumulator overflow in .vectors

Summing iovec lengths can overflow usize on 32‑bit or extremely large writes. Add a simple bound check.

-                .vectors => |vecs| blk: {
-                    var total: usize = 0;
-                    for (vecs.data[0..vecs.len]) |vec| total += vec.len;
-                    break :blk total;
-                },
+                .vectors => |vecs| blk: {
+                    var total: usize = 0;
+                    for (vecs.data[0..vecs.len]) |vec| {
+                        assert(total <= std.math.maxInt(usize) - vec.len);
+                        total += vec.len;
+                    }
+                    break :blk 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 3cbe0ed and 6bec240.

📒 Files selected for processing (1)
  • vendor/libxev/src/watcher/stream.zig (5 hunks)
🔇 Additional comments (4)
vendor/libxev/src/watcher/stream.zig (4)

535-586: Readable.read: vectors path looks good

Adding .vectors to the inline switch and plumbing through recv/read is correct and consistent with existing variants. No issues spotted.


606-608: kqueue: correct zero-length short‑circuit for .vectors

Skipping threadpool when v.len == 0 for .vectors matches the .slice behavior and avoids unnecessary blocking calls. LGTM.


961-1004: writeInit: vectors support wired correctly

Routing .vectors through write/send and preserving dup/threadpool flag logic is consistent with existing variants. Looks good.


1041-1062: Remainder for .vectors: add capacity and offset assertions to prevent OOB writes

You removed the early “cap at 2” truncation (good), but now we can overflow result.vectors.data if the remainder has more entries than the inline capacity, and we don’t assert offset ≤ total. Add explicit checks so we fail fast rather than corrupting memory.

                 .vectors => |vecs| {
                     var result = xev.WriteBuffer{ .vectors = .{ .data = undefined, .len = 0 } };
                     var skip = offset;
+                    // Ensure the offset is within the total length of all vectors
+                    var total_len: usize = 0;
+                    for (vecs.data[0..vecs.len]) |v| total_len += v.len;
+                    assert(offset <= total_len);

                     for (vecs.data[0..vecs.len]) |vec| {
                         if (skip >= vec.len) {
                             skip -= vec.len;
                             continue;
                         }

+                        // Do not exceed inline capacity of the remainder buffer
+                        assert(result.vectors.len < result.vectors.data.len);
+
                         if (skip > 0) {
                             result.vectors.data[result.vectors.len] = .{
                                 .base = vec.base + skip,
                                 .len = vec.len - skip,
                             };
                             skip = 0;
                         } else {
                             result.vectors.data[result.vectors.len] = vec;
                         }
                         result.vectors.len += 1;
                     }
+                    // We must have consumed the entire offset
+                    assert(skip == 0);
                     return result;
                 },

Optional: fast‑path if (offset == 0) return buf; to avoid copying the vector list on the first retry.

@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

🧹 Nitpick comments (4)
vendor/libxev/src/watcher/udp.zig (4)

111-144: Confirm kqueue recvfrom op handles vectors (or provide fallback).

You now accept .vectors and forward it to .recvfrom. Please verify the kqueue backend maps vectors to recvmsg/readv (or equivalent) rather than only scalar recvfrom, otherwise multi‑iov reads may not work as intended.

Consider documenting that UDPSendto supports vectors via backend translation, or internally switch to recvmsg when .vectors is used.


174-207: Same verification for kqueue send path.

Ensure .sendto in the kqueue backend supports multiple iovecs (e.g., via sendmsg), or add an internal fallback when .vectors is provided.

Add a UDP vectored send test to catch regressions.


289-322: Verify IOCP read path uses multi-WSABUF for vectors.

Forwarding .vectors to .recvfrom is fine if the IOCP layer calls WSARecvFrom with multiple WSABUF. Please confirm this is implemented; otherwise, only the first buffer may be read.


352-385: Verify IOCP write path uses multi-WSABUF for vectors.

Same concern for .sendto on IOCP: ensure WSASendTo (or WSASend) is called with multiple WSABUF.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between de2d744 and 6df26aa.

📒 Files selected for processing (1)
  • vendor/libxev/src/watcher/udp.zig (6 hunks)
🔇 Additional comments (1)
vendor/libxev/src/watcher/udp.zig (1)

630-633: Same iov assignment issue on send path.

Mirror the fix from recv: assign msghdr.iov to the actual iovec pointer, not the address of the holder field.

-                    s.op.send.msghdr.iov = &vecs.data;
+                    // If vectors = { ptr: [*]std.posix.iovec_const, len: usize }
+                    s.op.send.msghdr.iov = @ptrCast(vecs.ptr);
                     s.op.send.msghdr.iovlen = @intCast(vecs.len);
-                    s.op.send.msghdr.iov = &vecs.data;
+                    // If vectors = { data: [*]std.posix.iovec_const, len: usize }
+                    s.op.send.msghdr.iov = vecs.data;
                     s.op.send.msghdr.iovlen = @intCast(vecs.len);

Add std.debug.assert(slices.len <= 2) to all fromSlices functions
across all backend implementations to ensure input slice arrays
contain at most 2 elements, matching the fixed-size arrays used
for vectored I/O operations.
@lalinsky
lalinsky merged commit 311acf6 into main Sep 29, 2025
@lalinsky
lalinsky deleted the feature/libxev-vectored-io branch October 1, 2025 10:47
@coderabbitai coderabbitai Bot mentioned this pull request Oct 2, 2025
lalinsky added a commit that referenced this pull request Jan 6, 2026
lalinsky added a commit that referenced this pull request Jan 6, 2026
* WIP

* Add standalone signal tests to CI

Add test programs for stack overflow and segmentation fault handling,
with a Python test runner that validates crash behavior and diagnostics.
Integrate into CI for native platforms only.

* Make signal tests compatible with Windows

- Fix Unicode encoding issues on Windows (use UTF-8)
- Handle .exe extension for Windows executables
- Accept both Linux and Windows stack overflow messages

* Fix segfault test to actually cause segfault

Use a non-zero invalid address (10) instead of null to bypass Zig's
null pointer safety check. Use volatile to prevent compiler optimization.
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