Skip to content

Add blocking I/O support for socket and pipe operations - #308

Merged
lalinsky merged 10 commits into
mainfrom
blocking-socket-ops
Feb 9, 2026
Merged

lalinsky merged 10 commits into
mainfrom
blocking-socket-ops

Conversation

@lalinsky

@lalinsky lalinsky commented Feb 9, 2026

Copy link
Copy Markdown
Owner

Summary

Extends blocking mode to support socket and pipe I/O operations, enabling ZIO to work in synchronous contexts without an event loop.

Changes

  • Add blocking support for pipe read/write operations
  • Add blocking support for all socket operations (open, bind, listen, connect, accept, recv, send, etc.)
  • Implement platform-specific strategies:
    • Windows: Direct blocking I/O (no polling needed)
    • POSIX: Poll-then-I/O loop to handle multi-thread race conditions
  • Add pollForReady() helper for waiting on fd readiness
  • Add comprehensive smoke test for blocking socket operations

Implementation Details

On POSIX systems, uses a poll+I/O retry loop to handle races where multiple threads access the same fd:

  • If poll indicates readiness but I/O returns EWOULDBLOCK (another thread consumed data), retry
  • This ensures thread-safe operation without explicit locking

On Windows, blocking I/O works correctly without polling, so operations are direct system calls.

Closes #288

@coderabbitai

coderabbitai Bot commented Feb 9, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds blocking support for pipes and sockets in non-async contexts by implementing per-operation Net* handlers, POSIX poll-based readiness loops, and Windows-specific blocking paths; includes a new blocking socket smoke test.

Changes

Cohort / File(s) Summary
Core blocking logic
src/ev/blocking.zig
Added per-operation handlers for network ops (NetOpen, NetBind, NetListen, NetConnect, NetAccept, NetRecv, NetSend, NetRecvFrom, NetSendTo, NetRecvMsg, NetSendMsg, NetShutdown, NetClose) and pipe read/write; introduced pollForReady and POSIX poll-based retry loops; added Windows-specific blocking paths and WouldBlock retry logic.
Tests — blocking sockets
src/ev/test/blocking_sockets.zig
New test exercising blocking socket server/client behavior using executeBlocking wrappers, thread coordination, send/recv validation, and cleanup.
Test registry
src/ev/tests.zig
Imported the new test/blocking_sockets.zig into the test suite.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

Pipes and sockets once would cry,
Now handlers catch the WouldBlock sigh.
Polls wait on POSIX, Windows stands still,
Threads send and receive on tested will.
Code sleeps sound; the I/O wakes with skill.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: adding blocking I/O support for socket and pipe operations, which is the core focus of the PR.
Description check ✅ Passed The description is directly related to the changeset, covering socket/pipe blocking support, platform-specific strategies, and test additions with clear implementation details.
Linked Issues check ✅ Passed The PR implements blocking socket operations as required by issue #288, covering the full socket API surface and pipe operations with appropriate platform handling.
Out of Scope Changes check ✅ Passed All changes align with the scope of adding blocking socket and pipe I/O support; no unrelated modifications detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch blocking-socket-ops

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

❤️ Share

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

lalinsky and others added 9 commits February 9, 2026 10:39
Implements support for socket read/write operations in blocking mode
(when no async runtime is available).

Implementation follows the same approach as blocking pipe operations:
- POSIX: Polls for readiness (POLLIN/POLLOUT) with infinite timeout,
  then performs the I/O operation using recv/send/recvfrom/sendto/recvmsg/sendmsg
- Windows: Directly performs I/O which blocks automatically

This enables socket I/O without requiring the async runtime, while
safely handling non-blocking sockets by polling first.

Operations implemented:
- recv/send for stream sockets
- recvfrom/sendto for datagram sockets
- recvmsg/sendmsg for advanced message operations
- close and shutdown for connection management

Co-authored-by: Lukáš Lalinský <[email protected]>
These operations are naturally blocking (just call net.socket() and
net.bind()) so they fit perfectly into the blocking execution model.

Co-authored-by: Lukáš Lalinský <[email protected]>
Refactors blocking.zig by extracting the repeated poll-then-operate pattern
into a single pollForReady() helper function. This eliminates ~60 lines of
duplicated code across pipe and socket handlers.

All 355 unit tests pass successfully.

Co-authored-by: Lukáš Lalinský <[email protected]>
The Windows check needs to be at call sites, not inside pollForReady,
because the function body references net.pollfd which doesn't compile
on Windows.

Co-authored-by: Lukáš Lalinský <[email protected]>
…eout support

All socket recv/send operations now use polling on both POSIX and Windows:
- pollForReady now works on all platforms (uses WSAPoll on Windows)
- handleNetRecv, handleNetRecvFrom, handleNetRecvMsg poll before receiving
- handleNetSend, handleNetSendTo, handleNetSendMsg poll before sending

This change enables future timeout support by allowing poll timeout parameter
to be configurable instead of using infinite timeout (-1).

Co-authored-by: Lukáš Lalinský <[email protected]>
Implements blocking execution for socket connection operations:
- listen: Direct synchronous call (no polling needed)
- connect: Poll for write readiness + SO_ERROR checking
- accept: Poll for incoming connections

Follows the same pattern as existing recv/send operations.
All 355 unit tests pass.

Co-authored-by: Lukáš Lalinský <[email protected]>
Tests listen, accept, connect, send, and recv using two threads
(server and client) with ResetEvent synchronization.
On Windows, blocking sockets and pipes naturally block, so polling
is unnecessary overhead. This commit removes polling on Windows for
all blocking I/O operations (recv, send, accept, read, write, etc).

On POSIX, adds retry loop to handle the race condition where multiple
threads access the same file descriptor. The poll+I/O pattern has a
TOCTOU race: if thread A polls (ready) but thread B completes the I/O
first, thread A gets WouldBlock. The retry loop handles this correctly.

All functions now follow a consistent pattern: handle Windows first
(simple blocking I/O), then POSIX (poll+I/O retry loop).
@lalinsky
lalinsky force-pushed the blocking-socket-ops branch from 1bfdafa to 837ce29 Compare February 9, 2026 09:39

@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

🤖 Fix all issues with AI agents
In `@src/ev/test/blocking_sockets.zig`:
- Around line 148-154: The server can block forever on accept if the client
fails; to fix, join the client_thread before server_thread, then check
state.client_err and if non-null signal the server to stop waiting (e.g., close
the listening socket from the main thread or set a recv timeout on the listener
socket using SO_RCVTIMEO) so server_thread.accept() unblocks; adjust the
shutdown logic around server_thread, client_thread, state.client_err, and the
listener socket to ensure the test fails fast instead of hanging.
🧹 Nitpick comments (2)
src/ev/blocking.zig (2)

361-425: unreachable after net.recvmsg/net.sendmsg success on Windows is fragile.

If net.recvmsg/net.sendmsg currently always panic or error on Windows, the unreachable on lines 371 and 404 works today. But if someone later adds Windows support for these calls (e.g., via WSARecvMsg), this becomes undefined behavior in release builds with no compile-time safety net.

Consider replacing the Windows branch with a @compileError if Windows is truly never expected to support these, or handle the success case normally:

Option A: compile-time guard
 fn handleNetRecvMsg(c: *Completion) void {
     const data = c.cast(NetRecvMsg);
 
-    // Windows: not supported (recvmsg is POSIX-only, will panic in net.recvmsg)
-    if (builtin.os.tag == .windows) {
-        _ = net.recvmsg(data.handle, data.data.iovecs, data.flags, data.addr, data.addr_len, data.control) catch |err| {
-            c.setError(err);
-            return;
-        };
-        unreachable;
-    }
+    if (builtin.os.tag == .windows) {
+        `@compileError`("recvmsg is not supported on Windows");
+    }
Option B: handle success defensively
-    if (builtin.os.tag == .windows) {
-        _ = net.recvmsg(data.handle, data.data.iovecs, data.flags, data.addr, data.addr_len, data.control) catch |err| {
-            c.setError(err);
-            return;
-        };
-        unreachable;
-    }
+    if (builtin.os.tag == .windows) {
+        if (net.recvmsg(data.handle, data.data.iovecs, data.flags, data.addr, data.addr_len, data.control)) |result| {
+            c.setResult(.net_recvmsg, result);
+        } else |err| {
+            c.setError(err);
+        }
+        return;
+    }

Same applies to handleNetSendMsg.


225-291: Nine copies of the poll-then-retry loop.

The POSIX poll+retry pattern (poll → syscall → retry on WouldBlock) is duplicated across handlePipeRead, handlePipeWrite, handleNetRecv, handleNetSend, handleNetRecvFrom, handleNetSendTo, handleNetRecvMsg, handleNetSendMsg, and handleNetAccept. Each differs only in poll direction, syscall call, result tag, and argument set.

A comptime helper could collapse these — something like:

fn blockingPollLoop(
    comptime tag: Completion.Op,
    fd: net.fd_t,
    poll_events: i16,
    doOp: anytype, // fn returning error union
) void { ... }

Not urgent — the current code is clear and each function is self-contained. But if you add more operations later, the boilerplate will keep growing.

Comment on lines +148 to +154
// Wait for both threads to complete
server_thread.join();
client_thread.join();

// Check for errors
try std.testing.expectEqual(null, state.server_err);
try std.testing.expectEqual(null, state.client_err);

@coderabbitai coderabbitai Bot Feb 9, 2026 •

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 | 🟡 Minor

If the client dies before connecting, the server blocks on accept forever — test hangs.

If client socket open or connect fails, the server thread is stuck in the blocking accept call with no timeout, and server_thread.join() on line 149 will never return. Unlikely on localhost, but if it ever happens in CI, you'll get a hung test with no useful error output.

One option: join client first, then if client_err is set, you know the server might be stuck. Or set a socket timeout on the server's listening socket. Not a must-fix for a smoke test, just something to keep in mind.

🤖 Prompt for AI Agents
In `@src/ev/test/blocking_sockets.zig` around lines 148 - 154, The server can
block forever on accept if the client fails; to fix, join the client_thread
before server_thread, then check state.client_err and if non-null signal the
server to stop waiting (e.g., close the listening socket from the main thread or
set a recv timeout on the listener socket using SO_RCVTIMEO) so
server_thread.accept() unblocks; adjust the shutdown logic around server_thread,
client_thread, state.client_err, and the listener socket to ensure the test
fails fast instead of hanging.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

this is reasonable for the test, it would get very complex to handle it properly

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.

@lalinsky, fair enough — for a smoke test on localhost the odds are low enough that the extra complexity isn't worth it. If you ever see a hang in CI, you'll know where to look.

@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

🤖 Fix all issues with AI agents
In `@src/ev/blocking.zig`:
- Around line 362-392: The Windows branch in handleNetRecvMsg (and likewise in
handleNetSendMsg) calls net.recvmsg/net.sendmsg then hits unreachable, which is
unsafe if those functions later gain non-panicking implementations; replace that
pattern with a clear compile-time or explicit runtime failure: use a comptime
guard (comptime if (builtin.os.tag == .windows) `@compileError`("recvmsg/sendmsg
not supported on Windows")) to fail builds on Windows, or if you must allow
runtime builds, replace the call+unreachable with an immediate `@panic`("recvmsg
not supported on Windows") (and do the analogous change in handleNetSendMsg) so
there is no path that falls through to unreachable.
🧹 Nitpick comments (1)
src/ev/blocking.zig (1)

140-206: Every poll+retry handler is copy-pasted with minor parameter differences.

handlePipeRead, handlePipeWrite, handleNetRecv, handleNetSend, handleNetRecvFrom, handleNetSendTo, handleNetRecvMsg, handleNetSendMsg — eight functions, same skeleton: Windows direct call, POSIX while(true) { pollForReady; try op; WouldBlock → continue; else → error }.

It works, it's readable, but when you need to change the retry logic (e.g., add a timeout, add logging, handle EINTR), you'll be touching eight places. Something like a generic blockingPollLoop(fd, poll_events, doOp) helper taking a function pointer or inline callback would cut the surface area down. Not urgent, but worth a TODO.

Also applies to: 226-291

Comment thread src/ev/blocking.zig
Comment on lines +362 to +392
fn handleNetRecvMsg(c: *Completion) void {
const data = c.cast(NetRecvMsg);

// Windows: not supported (recvmsg is POSIX-only, will panic in net.recvmsg)
if (builtin.os.tag == .windows) {
_ = net.recvmsg(data.handle, data.data.iovecs, data.flags, data.addr, data.addr_len, data.control) catch |err| {
c.setError(err);
return;
};
unreachable;
}

// POSIX: poll+recvmsg loop to handle race if multiple threads access same socket
while (true) {
pollForReady(data.handle, net.POLL.IN) catch |err| {
c.setError(err);
return;
};

if (net.recvmsg(data.handle, data.data.iovecs, data.flags, data.addr, data.addr_len, data.control)) |result| {
c.setResult(.net_recvmsg, result);
return;
} else |err| switch (err) {
error.WouldBlock => continue, // Another thread consumed data, retry
else => {
c.setError(err);
return;
},
}
}
}

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

unreachable after a potentially-succeeding call on Windows is risky.

If net.recvmsg / net.sendmsg ever stops panicking on Windows (e.g., someone adds a WSA-based implementation), the success path silently falls through to unreachable, which is undefined behavior in ReleaseFast/ReleaseSmall. A compile-time guard is safer:

Proposed fix
 // Windows: not supported (recvmsg is POSIX-only, will panic in net.recvmsg)
 if (builtin.os.tag == .windows) {
-    _ = net.recvmsg(data.handle, data.data.iovecs, data.flags, data.addr, data.addr_len, data.control) catch |err| {
-        c.setError(err);
-        return;
-    };
-    unreachable;
+    `@compileError`("recvmsg is not supported on Windows");
 }

Same for handleNetSendMsg.

If for some reason you need the Windows branch to compile but fail at runtime, at minimum use @panic("recvmsg not supported on Windows") instead of relying on the downstream panic + unreachable combo.

Also applies to: 394-425

🤖 Prompt for AI Agents
In `@src/ev/blocking.zig` around lines 362 - 392, The Windows branch in
handleNetRecvMsg (and likewise in handleNetSendMsg) calls
net.recvmsg/net.sendmsg then hits unreachable, which is unsafe if those
functions later gain non-panicking implementations; replace that pattern with a
clear compile-time or explicit runtime failure: use a comptime guard (comptime
if (builtin.os.tag == .windows) `@compileError`("recvmsg/sendmsg not supported on
Windows")) to fail builds on Windows, or if you must allow runtime builds,
replace the call+unreachable with an immediate `@panic`("recvmsg not supported on
Windows") (and do the analogous change in handleNetSendMsg) so there is no path
that falls through to unreachable.

Windows doesn't have native recvmsg/sendmsg support. This implements
emulation in the net layer that falls back to recvfrom/recv and
sendto/send when control messages (ancillary data) are not used.

Control messages are POSIX-specific and return OperationNotSupported
on Windows when requested.

This removes the unreachable statements from blocking handlers and
enables full socket operation support in blocking mode on Windows.
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.

Implement blocking socket ops

1 participant