Repository navigation
Conversation
…n table The epoll backend armed and disarmed interest for every operation (~4 epoll_ctl per echo round-trip), trailing io_uring by 25-35%. Keep each socket registered edge-triggered for its lifetime and track, in a table shared across the loops in a group, which loops have a given fd registered, so the same fd can be driven from several loops (fiber migration, cross-loop full-duplex) without leaving stale per-loop state behind. - optimistic recv/send/accept, register only on WouldBlock (drains to EAGAIN before waiting, which is what makes edge-triggered safe) - persistent EPOLLIN|EPOLLOUT|EPOLLET registration, added once per (loop, fd) - sharded fd -> loop-bitmask SharedState with acquire/release refcount - ephemeral local poll_queue entries, so a closed/reused fd number is never mistaken for registered; net_close clears the shared entry - net_poll does a 0-timeout poll() probe (it has no I/O to drain, so pure edge-triggered would hang on an already-ready socket) - scoped to sockets; pidfd/pipe/streaming stay on the one-shot level-triggered path (they are closed outside net_close) Adds a multi-executor cross-loop stress test (full-duplex across loops + migration mid-connection + fd reuse, byte-verified) that passes on epoll and io_uring. Closes #510. See #262.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThe epoll backend gains a ChangesPersistent edge-triggered epoll socket registration
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/ev/backends/epoll.zig`:
- Around line 67-78: In the RegShard struct and the SharedState struct, replace
the mutex field initialization from `os.Mutex = .{}` to `os.Mutex = .init()` for
both occurrences. The RegShard struct has a mutex field that currently uses
`.{}` for initialization, and the SharedState struct also has a mutex field with
the same pattern. Change both to use `.init()` to match the initialization
pattern used throughout the rest of the codebase and ensure proper
platform-specific setup is performed.
- Around line 80-95: The acquire method in SharedState increments next_loop_id
unconditionally, causing the id to keep climbing even when loops are released,
eventually exceeding the 64-id limit. Instead of only resetting next_loop_id
when refcount reaches zero, track released loop ids in a free list (e.g., a bit
set or queue) within SharedState, and modify acquire to reuse ids from this free
list before incrementing next_loop_id. When a loop is released (in the
corresponding release method), add its id back to the free list rather than just
decrementing refcount. This way, ids are recycled per-loop, keeping the budget
under control even as executors churn while others remain alive.
In `@src/net.zig`:
- Around line 2339-2341: Add a finite per-operation timeout to the blocking I/O
operations in the stress test to prevent indefinite blocking if a lost wakeup
occurs. Define a timeout constant (e.g., a reasonable duration in milliseconds)
and apply it to all blocking I/O operations that read or write with the socket
handle (sh), allowing the existing sh.errors counter to properly catch and count
error.Timeout errors. Apply this timeout addition consistently across all the
mentioned locations in the stress test where blocking operations occur.
- Around line 2479-2496: The cleanup order in this test is unsafe: the `defer
server_group.wait()` at line 2480 will execute before the `sh.done.store(true,
.release)` at line 2496 if any intermediate `try` statement fails, causing the
acceptor thread to hang in its loop indefinitely. Move the `sh.done.store(true,
.release)` signal into a defer block placed immediately after the `server_group`
initialization so it executes during cleanup before the `server_group.wait()`
defer, ensuring the acceptor can exit its loop cleanly even if an error occurs
during the client spawning or waiting operations.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 93803d1c-3314-4222-ac69-d53477eedb08
📒 Files selected for processing (2)
src/ev/backends/epoll.zigsrc/net.zig
- recycle loop ids via a free-list bitmask so a group that churns loops never climbs past the 64-id cap. Previously the id counter only reset when the group fully drained, so under ReleaseFast it could truncate to u6 and alias a live loop's registration bit. - init the shared-state mutexes with .init() to match the rest of the tree (and the platform-specific setup some Mutex variants do). - bound the cross-loop stress test's socket I/O with a finite timeout, so a lost wakeup surfaces as a counted error.Timeout / failed assertion instead of a hung test process. - signal the test's acceptor to stop before draining it, so an early return from any intermediate `try` can't leave it looping.
|
@hyird looks good conceptually, I'll need a bit more time to review, but can you take a look at the failing test? it seems that operations are marked as completed without setting the result in some cases |
…uble-finish The generic NetSendFile fallback (loop.zig) re-submits a NetSend from inside its own send callback, expecting the child to complete asynchronously like every other backend's net ops. The optimistic send added in this branch completed inline when send() succeeded immediately, re-entering netSendFileAdvance and finishing the transfer twice -> panic in setResult (assert !has_result). It only showed up in the full suite under epoll (the sendFile tests), where a real socket send completes synchronously; single-filter runs missed it. Park such completions on the loop's deferred completion queue (work_completions, drained from processCompletions) instead of running their callback inline, so submit never re-enters the submitter. The syscall still happens eagerly; only the notification waits for the next processCompletions. Batching completions there also slightly improves throughput (epoll now ties io_uring on this box). Fixes the epoll-backend CI failures on this PR.
|
Ok, I missed one key part, you are registering the poll on whetever epoll the recv/send lands on, with task migration, single fd could potentially be registered on ALL event loops. I'm not sure if that's good. My original idea was this:
So this approach is supported:
I think this is strictly better, because you are not registering the fd on all event loops, just the key ones. We already use task migration by default, so recv being delivered on executor A when it started on executor B is not an issue. Actually, when the user disabled task migration, we should probably not even use the shared loop group, so this solution would also work with that case and fds would only ever be register locally. Now, I'm not sure whether to accept your version, or push for this approach, but I think it is better. Key points:
What do you think? |
|
Agreed, your approach is better. Registering on whichever loop the op lands on means a migrating fd ends up in every epoll — wasteful, and it causes spurious wakeups on loops that no longer handle the socket. Keying the shared queue by One thing I'd like to pin down before building it: when the fd is registered on loop A but the parked completion came from loop B, how should it finish —
I'm leaning toward the first, since that's the "A resumes the task locally when the event fires" path you described — but it means epoll opts into the shared-counter path. And as you said, I'll skip the shared loop group entirely when task migration is disabled, so single-threaded stays fully local with no cross-loop machinery at all. Does that match what you had in mind? (Aside: the failing test is fixed on the current branch — the optimistic send was completing inline and re-entering the NetSendFile fallback, finishing the transfer twice; I deferred that completion, CI is green now. That code changes in the rework anyway.) |
|
Correct, when the event is delivered on A, we handle it on A, even though the request came from B. That is very similar to the IOCP path, indeed. Everything should already be able to handle it, but it's worth double-checking it. The epoll backend should be then declared as |
Rework the socket path to the design discussed on the PR. Instead of registering a migrating fd in every loop's epoll, key a shared poll queue by (fd, direction) and register it lazily in exactly one loop's epoll: - the optimistic recv/send stays on whatever loop the op lands on (lock-free fast path); on WouldBlock the op parks as a waiter on the (fd, dir) entry, registering locally only if nobody owns it yet; - when the owning loop's epoll fires it drains the waiters and completes them, including ones submitted on other loops - the same cross-loop completion the IOCP backend already does, so epoll is now declared multi_threaded (the active/inflight accounting moves to the shared group atomics; everything else was already thread-safe). A per-(fd, dir) readiness latch closes the wakeup race where data arrives between an op's optimistic syscall returning EAGAIN and it enqueuing as a waiter: the owner latches an edge that found no waiter, so the next op to park re-checks the syscall instead of waiting for an edge edge-triggered epoll won't repeat. Trade-off vs registering locally: each blocking op takes a sharded mutex on the shared queue, and the multi_threaded counters are shared atomics even single-threaded. In exchange a migrating fd is registered on at most one loop per direction, reader and writer can sit on different loops, and the completion is delivered by the loop that already polls the fd (fewer syscalls, lower latency) rather than re-registered. Full suite passes (same 482/484 as main; the 2 are pre-existing live-DNS), including the multi-executor cross-loop stress test.
|
Pushed the rework: shared One thing worth flagging from double-checking it: there's a wakeup race between an op's optimistic syscall returning EAGAIN and it parking as a waiter. If data arrives in that window and the owner's edge fires before the waiter is enqueued, edge-triggered epoll won't repeat the edge. I close it with a per- Full suite is green (same 482/484 as main, the 2 are the pre-existing live-DNS tests), including the multi-executor cross-loop stress test (full-duplex reader/writer on different executors + migration + fd reuse, byte-verified). Heads up on the cost: every blocking op now takes the sharded queue lock, and the shared counters are atomic even single-threaded, so on a non-migrating echo benchmark this is a few percent behind the previous "register locally" version (still within ~5-10% of io_uring single-thread; multi-thread is on par). The win is on the migration / cross-loop side, which that benchmark doesn't exercise. |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/ev/backends/epoll.zig`:
- Around line 397-422: The inline error completion paths in parkSocket for the
getOrPut OOM failure and armRegistration failure both call
state.markCompletedFromBackend(c) directly, which re-enters the send callback
when parkSocket is invoked from submit's error.WouldBlock arm. Instead of
calling state.markCompletedFromBackend(c) directly in both error catch blocks
(the one after getOrPut and the one after armRegistration), route these
completions through the completeDeferred function just like the success path
does, so that the completion is deferred and avoids the re-entrance issue that
completeDeferred was designed to prevent.
- Around line 531-544: The unregisterSocket function is removing the socket
registration from the map before pending operations (stored in reg.waiters_in
and reg.waiters_out) have been completed or cancelled, causing cross-loop
operations to become orphaned. Before removing the entry with fetchRemove,
iterate through and complete or cancel all pending operations in the waiters_in
and waiters_out queues of the FdReg entry, ensuring each parked operation is
properly marked as done before the entry is removed from the registry. This
prevents operations from becoming orphaned when the socket is closed while
operations are still pending on other loops.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 0d65b790-7611-486e-b9ae-fd825a7341e9
📒 Files selected for processing (1)
src/ev/backends/epoll.zig
…rror paths - unregisterSocket now completes any operations still parked on the fd when it is closed (a close racing a pending op on another loop) with error.Canceled, instead of dropping them along with the registry entry. Such orphaned completions would otherwise hang the fiber and leave the group's active / inflight accounting unbalanced. - parkSocket's two inline error completions (registry OOM, epoll_ctl failure) now defer like the success path, so a net_send that reaches them from the NetSendFile fallback can't complete inline and re-enter the send callback.
|
Addressed both review comments in 38f89d8:
Full suite still 482/484 (the 2 are the pre-existing live-DNS tests), cross-loop stress green. |
| // Already registered (possibly by another loop). If an edge fired since the | ||
| // last drain with nobody waiting, the readiness was latched: re-check the | ||
| // syscall now rather than park for an edge edge-triggered epoll won't repeat. | ||
| // net_connect always takes the fresh-ADD path above in practice, so its | ||
| // re-check (which can't distinguish success from failure without the real | ||
| // event) is skipped here. | ||
| const ready = readyPtr(reg, dir); | ||
| if (ready.* and c.op != .net_connect) { | ||
| ready.* = false; | ||
| shard.mutex.unlock(); | ||
| var ev = std.os.linux.epoll_event{ | ||
| .data = .{ .fd = fd }, | ||
| .events = switch (dir) { | ||
| .in => std.os.linux.EPOLL.IN, | ||
| .out => std.os.linux.EPOLL.OUT, | ||
| }, | ||
| }; | ||
| switch (checkCompletion(c, &ev)) { | ||
| .completed => self.completeDeferred(state, c), | ||
| .requeue => { | ||
| // Latch was stale: park for the next real edge. | ||
| c.prev = null; | ||
| c.next = null; | ||
| shard.mutex.lock(); | ||
| if (shard.map.getPtr(fd)) |r| { | ||
| waitersPtr(r, dir).push(c); | ||
| shard.mutex.unlock(); | ||
| } else { | ||
| shard.mutex.unlock(); | ||
| c.setError(error.Canceled); | ||
| self.completeDeferred(state, c); | ||
| } | ||
| }, | ||
| } | ||
| return; | ||
| } |
There was a problem hiding this comment.
Lost wakeup in parkSocket's latch-recheck → requeue path
The recheck path consumes ready, drops the shard lock to run the syscall, and on EAGAIN re-parks as a waiter without re-reading ready under the re-acquired lock. During that unlocked syscall window the owner loop's drainDir can latch ready = true for data that just arrived — and because the registration is edge-triggered, that already-buffered data produces no further edge, so the re-parked completion sleeps until the next arrival.
Interleaving (P parking on loop B, A = owner of (fd, in)):
1. P: ready == true -> clear ready; unlock
2. P: recv() -> EAGAIN (socket momentarily empty)
3. A: data arrives, epoll edge fires
4. A: drainDir: no waiter queued yet (P not re-enqueued),
!drained_any -> ready = true
5. P: re-lock; push P as waiter; unlock // never re-checks ready
-> P parked, ready == true, data buffered, no future edge -> hang
The precondition (a stale latch) is reachable on its own: a latched ready consumed by an optimistic submit() syscall never clears the flag, so the next op finds ready == true and enters the recheck path. With a per-op timeout this surfaces as a spurious error.Timeout; an untimed op hangs. The tell is the asymmetry — drainDir's own requeue clears ready under the lock (epoll.zig:515), but this branch doesn't even read it.
Root cause: the syscall must run outside the lock, so the recheck path drops and re-acquires — and the decision to park is torn across that gap. The invariant that needs restoring is the enqueue must be guarded by a ready == false observed in the same critical section.
Fix — make the recheck a loop; only re-run the syscall when ready is set, so the common ready == false park costs no extra syscall:
var ev = std.os.linux.epoll_event{
.data = .{ .fd = fd },
.events = switch (dir) {
.in => std.os.linux.EPOLL.IN,
.out => std.os.linux.EPOLL.OUT,
},
};
while (true) {
shard.mutex.lock();
const r = shard.map.getPtr(fd) orelse { // closed underneath us
shard.mutex.unlock();
c.setError(error.Canceled);
self.completeDeferred(state, c);
return;
};
// net_connect can't distinguish success/failure without the real event,
// so it never rechecks — it just parks (matches the current carve-out).
if (c.op == .net_connect or !readyPtr(r, dir).*) {
waitersPtr(r, dir).push(c); // ready false -> park, no syscall
shard.mutex.unlock();
return;
}
readyPtr(r, dir).* = false;
shard.mutex.unlock();
c.prev = null;
c.next = null;
switch (checkCompletion(c, &ev)) {
.completed => {
self.completeDeferred(state, c);
return;
},
.requeue => {}, // re-loop: re-test ready under the lock
}
}Now the enqueue can no longer slip past a concurrently-set latch — after every recheck syscall we re-take the lock and re-test ready before being allowed to park. Caveats: re-fetch reg/ready/waiters after each re-lock (a concurrent getOrPut on another fd can rehash the shard map). Termination is bounded — a recheck only repeats if ready was re-latched, i.e. a real edge fired, which the syscall then consumes.
The first-registration path (owner becomes self) doesn't need this: a fresh EPOLLET ADD reports current readiness as an edge, and ready can't be set while owner is null.
(Note: this is narrow — it needs cross-loop ownership and a specific interleaving, so the stress test stayed green across many runs. But it's a genuine lost wakeup, not just a wasted syscall.)
… loop The single-owner registration converged on #511's design, but I had the owner loop take ownership of the *completion* (reassign completion.loop, migrate per-loop accounting). That breaks the "completion.loop is set once and read lock-free" invariant the cancel path relies on: a cross-loop cancel (e.g. a timeout timer firing on the submitting loop) races the reassignment, leaving a completion linked in one loop's cancel_queue while it is completed and its stack frame freed via another loop -> use-after- free. It surfaced as a NetBSD-debug segfault in the cross-loop stress test (fault address == the op's 50ms accept timeout, a freed timer read as a pointer); macOS/FreeBSD/NetBSD-release missed the timing window. Fix: the owner loop owns only the *poller registration*, not the completion. A socket op stays owned by its submitting loop (its loop field, timeout timer and cancel routing unchanged); the owner services it in place when its edge fires and completes it cross-thread through the already-synchronized completion machinery (atomic cancel_state, spinlock WaitQueue, shard-locked waiter queue). Because an op can now be finished by either loop (the owner on a readiness edge, or the submitter on cancel), the active/inflight counters must be group-shared - so epoll and kqueue declare is_multi_threaded (the IOCP accounting path) and carry the shared atomics in SharedState. Drops the bespoke cross_loop_socket_reg capability, the per-loop atomic accounting migration, the completion.loop reassignment, and the cancel-queue forward fallback. The enable_task_migration=false local-group bypass is removed for now (it needs a different gate under is_multi_threaded) and left as a follow-up. epoll 506/506; io_uring 504/506 (2 pre-existing ftruncate env failures); iocp/kqueue compile+link for windows/macos/freebsd/netbsd.
Deferring every optimistic socket completion was over-cautious. Only sends need deferral (the NetSendFile fallback re-submits a NetSend from inside its own send callback, so completing inline there double-finishes the transfer). Reads/accepts cannot re-enter submit, so deferring their optimistic success just delays the consumer's resume past the poll boundary - which desynchronizes the producer/consumer in a ping-pong and forces an extra recv (EAGAIN) + epoll_wait per round trip. Completing reads/accepts inline drops the single-loop TCP ping-pong from 7 to 5 syscalls/round-trip (matching io_uring's submit/complete batching in count) and lifts throughput ~20% (60k -> 72k req/s, 1 executor, 64-byte messages), on par with io_uring and PR #511. epoll 506/506.
… loop The single-owner registration converged on #511's design, but I had the owner loop take ownership of the *completion* (reassign completion.loop, migrate per-loop accounting). That breaks the "completion.loop is set once and read lock-free" invariant the cancel path relies on: a cross-loop cancel (e.g. a timeout timer firing on the submitting loop) races the reassignment, leaving a completion linked in one loop's cancel_queue while it is completed and its stack frame freed via another loop -> use-after- free. It surfaced as a NetBSD-debug segfault in the cross-loop stress test (fault address == the op's 50ms accept timeout, a freed timer read as a pointer); macOS/FreeBSD/NetBSD-release missed the timing window. Fix: the owner loop owns only the *poller registration*, not the completion. A socket op stays owned by its submitting loop (its loop field, timeout timer and cancel routing unchanged); the owner services it in place when its edge fires and completes it cross-thread through the already-synchronized completion machinery (atomic cancel_state, spinlock WaitQueue, shard-locked waiter queue). Because an op can now be finished by either loop (the owner on a readiness edge, or the submitter on cancel), the active/inflight counters must be group-shared - so epoll and kqueue declare is_multi_threaded (the IOCP accounting path) and carry the shared atomics in SharedState. Drops the bespoke cross_loop_socket_reg capability, the per-loop atomic accounting migration, the completion.loop reassignment, and the cancel-queue forward fallback. The enable_task_migration=false local-group bypass is removed for now (it needs a different gate under is_multi_threaded) and left as a follow-up. epoll 506/506; io_uring 504/506 (2 pre-existing ftruncate env failures); iocp/kqueue compile+link for windows/macos/freebsd/netbsd.
Deferring every optimistic socket completion was over-cautious. Only sends need deferral (the NetSendFile fallback re-submits a NetSend from inside its own send callback, so completing inline there double-finishes the transfer). Reads/accepts cannot re-enter submit, so deferring their optimistic success just delays the consumer's resume past the poll boundary - which desynchronizes the producer/consumer in a ping-pong and forces an extra recv (EAGAIN) + epoll_wait per round trip. Completing reads/accepts inline drops the single-loop TCP ping-pong from 7 to 5 syscalls/round-trip (matching io_uring's submit/complete batching in count) and lifts throughput ~20% (60k -> 72k req/s, 1 executor, 64-byte messages), on par with io_uring and PR #511. epoll 506/506.
… loop The single-owner registration converged on #511's design, but I had the owner loop take ownership of the *completion* (reassign completion.loop, migrate per-loop accounting). That breaks the "completion.loop is set once and read lock-free" invariant the cancel path relies on: a cross-loop cancel (e.g. a timeout timer firing on the submitting loop) races the reassignment, leaving a completion linked in one loop's cancel_queue while it is completed and its stack frame freed via another loop -> use-after- free. It surfaced as a NetBSD-debug segfault in the cross-loop stress test (fault address == the op's 50ms accept timeout, a freed timer read as a pointer); macOS/FreeBSD/NetBSD-release missed the timing window. Fix: the owner loop owns only the *poller registration*, not the completion. A socket op stays owned by its submitting loop (its loop field, timeout timer and cancel routing unchanged); the owner services it in place when its edge fires and completes it cross-thread through the already-synchronized completion machinery (atomic cancel_state, spinlock WaitQueue, shard-locked waiter queue). Because an op can now be finished by either loop (the owner on a readiness edge, or the submitter on cancel), the active/inflight counters must be group-shared - so epoll and kqueue declare is_multi_threaded (the IOCP accounting path) and carry the shared atomics in SharedState. Drops the bespoke cross_loop_socket_reg capability, the per-loop atomic accounting migration, the completion.loop reassignment, and the cancel-queue forward fallback. The enable_task_migration=false local-group bypass is removed for now (it needs a different gate under is_multi_threaded) and left as a follow-up. epoll 506/506; io_uring 504/506 (2 pre-existing ftruncate env failures); iocp/kqueue compile+link for windows/macos/freebsd/netbsd.
Deferring every optimistic socket completion was over-cautious. Only sends need deferral (the NetSendFile fallback re-submits a NetSend from inside its own send callback, so completing inline there double-finishes the transfer). Reads/accepts cannot re-enter submit, so deferring their optimistic success just delays the consumer's resume past the poll boundary - which desynchronizes the producer/consumer in a ping-pong and forces an extra recv (EAGAIN) + epoll_wait per round trip. Completing reads/accepts inline drops the single-loop TCP ping-pong from 7 to 5 syscalls/round-trip (matching io_uring's submit/complete batching in count) and lifts throughput ~20% (60k -> 72k req/s, 1 executor, 64-byte messages), on par with io_uring and PR #511. epoll 506/506.
… loop The single-owner registration converged on #511's design, but I had the owner loop take ownership of the *completion* (reassign completion.loop, migrate per-loop accounting). That breaks the "completion.loop is set once and read lock-free" invariant the cancel path relies on: a cross-loop cancel (e.g. a timeout timer firing on the submitting loop) races the reassignment, leaving a completion linked in one loop's cancel_queue while it is completed and its stack frame freed via another loop -> use-after- free. It surfaced as a NetBSD-debug segfault in the cross-loop stress test (fault address == the op's 50ms accept timeout, a freed timer read as a pointer); macOS/FreeBSD/NetBSD-release missed the timing window. Fix: the owner loop owns only the *poller registration*, not the completion. A socket op stays owned by its submitting loop (its loop field, timeout timer and cancel routing unchanged); the owner services it in place when its edge fires and completes it cross-thread through the already-synchronized completion machinery (atomic cancel_state, spinlock WaitQueue, shard-locked waiter queue). Because an op can now be finished by either loop (the owner on a readiness edge, or the submitter on cancel), the active/inflight counters must be group-shared - so epoll and kqueue declare is_multi_threaded (the IOCP accounting path) and carry the shared atomics in SharedState. Drops the bespoke cross_loop_socket_reg capability, the per-loop atomic accounting migration, the completion.loop reassignment, and the cancel-queue forward fallback. The enable_task_migration=false local-group bypass is removed for now (it needs a different gate under is_multi_threaded) and left as a follow-up. epoll 506/506; io_uring 504/506 (2 pre-existing ftruncate env failures); iocp/kqueue compile+link for windows/macos/freebsd/netbsd.
This adopts the cross-loop socket registration approach from @hyird's #511 (ev/epoll: shared cross-loop registration table) into this branch's history so the contribution is credited and preserved. The working tree is taken entirely from this branch (-s ours): #526 reworks the same idea into a single-owner per-(fd,dir) design shared across epoll and kqueue, so none of the #511 file changes are carried forward — only its history. Co-authored-by: hyird <[email protected]>
|
Thanks a lot for this, @hyird — your shared cross-loop registration approach is what drove the design here. I've taken it forward in #526, which reworks the same idea into a single-owner per- Really appreciate the work and the review iterations here. |
ev: single-owner cross-loop socket registration (epoll + kqueue) — alternative to #511
Closes #510. Implements the idea in #262 (keep the fd in epoll), extended to be correct across event loops.
Problem
The epoll backend is a one-shot, level-triggered reactor:
submit()arms interest withepoll_ctl(ADD)and the fd is disarmed again withepoll_ctl(DEL)once it fires. One echo round-trip (recv + send) is two arm/disarm pairs, ~4epoll_ctlper request — about 55% of kernel time in astrace -f -c. That's why the backend trailedio_uringby 25-35% on a plain TCP echo benchmark.Why "just keep the fd registered" isn't enough by itself
@lalinsky already pointed this out on #510: keeping the fd registered is only correct for a single event loop. zio runs one loop per executor and migrates fibers between them, so the same socket fd can be driven from different loops over its life:
recvon loop A, then migrates and doessendon loop B;recvandsendare in flight on different loops at once.A naive per-loop "register once and never DEL" gets this wrong: when the fd is closed on one loop it leaves a stale
poll_queueentry on the other loop, and when that fd number is reused there the backend thinks it's still registered, skips the ADD, and the new socket never gets events — a hang.Design
Interest is per-loop (each loop has its own epoll fd), so the loops in a group share a small table that records, per fd, which loops currently have it registered. The hot path stays off any per-op syscall, and there's no stale state to leave behind:
submit()triesrecv/send/accept(and the*from/*msgvariants) directly first, like the existingnet_connecthandler, and only registers onWouldBlock. This also guarantees the socket is drained toEAGAINbefore we ever wait — which is what makes edge-triggered safe.EPOLLIN|EPOLLOUT|EPOLLETand stays registered for its lifetime (noMODon read/write switches, noDELon completion).SharedState= 64 mutex-shardedfd -> u64 loop-bitmaskmaps, with an IOCP-styleacquire/releaserefcount that hands each loop a smallloop_bit.ensureRegistered(fd)does theepoll_ctl(ADD)at most once per(loop, fd), gated by the shared mask, so the same fd can be registered on two loops at once (cross-loop full-duplex) and each is tracked independently.poll_queueentry is dropped as soon as its completion list empties, so an idle socket never holds a local entry. Combined withnet_closeclearing the whole shared entry, this means a closed/reused fd number can never be mistaken for "already registered" — there's no stale state to reconcile across loops.net_pollprobe.net_pollhas no I/O to drain, so pure edge-triggered would hang on an already-(and continuously)-writable socket. It does a 0-timeoutpoll()readiness probe insubmit()first and only waits on an edge when not ready.The change is scoped to real sockets (the
net_*ops). Other pollable fds —pidfd(process_wait), pipes, streaming files — are closed through paths that don't runnet_close, so they stay on the original one-shot level-triggered path and never enter the shared table.Correctness
New in-tree test
multi-executor: cross-loop socket stress (full-duplex + migration + fd reuse)(innet.zig): a 3-executor runtime drives many short connections in waves, each with its reader and writer as separate tasks (so recv/send for one fd run on different loops), and each echo handler spawns+joins a tiny task every round to force migration. Bytes are verified end-to-end;std.testing.allocatorfails it on any leak, which also exercises the shared table's teardown. It passes on bothepollandio_uring.Existing suite under
-Dbackend=epoll:net,Stream,recv,send,accept,connect,cancel,timeout,poll,process,pipeall pass. DNS is 35/37 — the two failures are pre-existing live-DNS assertions and are identical onmain.Benchmark
Closed-loop TCP ping-pong, 64-byte messages, system-default sockets (no
TCP_NODELAY), server pinned withtasksetso it's the bottleneck, 10s/run, 8-core EPYC 7402. req/s:Single server thread:
3 server threads (3 executors):
strace -fon the single-thread server:epoll_ctldrops from ~4.0/req to ~0.0004/req (52 ADDs total over 131k requests — one per socket, zero DEL/MOD). The per-op work on the wait path is now a sharded-map lookup instead of a syscall; the 3-executor numbers confirm it doesn't hurt multi-core scaling (epoll stays within a few percent of io_uring, essentially tied at 50 conns).Notes
kqueuehas the same per-op churn and the same single-loop limitation; this PR doesn't touch it, but the same shared-table approach applies and I'm happy to follow up.IN|OUT|ETunconditionally, so there's one spuriousEPOLLOUTwakeup per socket at registration (negligible).net_close; the kernel also drops a closed fd from epoll automatically, the explicit cleanup just keeps the tables tidy for fd reuse.