Skip to content

ev/epoll: keep sockets registered via a shared cross-loop registration table - #511

Closed
hyird wants to merge 5 commits into
lalinsky:mainfrom
hyird:epoll-shared-registration
Closed

hyird wants to merge 5 commits into
lalinsky:mainfrom
hyird:epoll-shared-registration

Conversation

@hyird

@hyird hyird commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

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 with epoll_ctl(ADD) and the fd is disarmed again with epoll_ctl(DEL) once it fires. One echo round-trip (recv + send) is two arm/disarm pairs, ~4 epoll_ctl per request — about 55% of kernel time in a strace -f -c. That's why the backend trailed io_uring by 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:

  • migration mid-connection — a fiber does recv on loop A, then migrates and does send on loop B;
  • concurrent full-duplex — a reader task and a writer task on one socket land on different executors, so recv and send are 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_queue entry 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:

  • Optimistic syscall. submit() tries recv/send/accept (and the *from/*msg variants) directly first, like the existing net_connect handler, and only registers on WouldBlock. This also guarantees the socket is drained to EAGAIN before we ever wait — which is what makes edge-triggered safe.
  • Persistent edge-triggered registration. A socket is added once with EPOLLIN|EPOLLOUT|EPOLLET and stays registered for its lifetime (no MOD on read/write switches, no DEL on completion).
  • Shared registration table. New SharedState = 64 mutex-sharded fd -> u64 loop-bitmask maps, with an IOCP-style acquire/release refcount that hands each loop a small loop_bit. ensureRegistered(fd) does the epoll_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.
  • Ephemeral local entries. A loop's poll_queue entry is dropped as soon as its completion list empties, so an idle socket never holds a local entry. Combined with net_close clearing 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_poll probe. net_poll has no I/O to drain, so pure edge-triggered would hang on an already-(and continuously)-writable socket. It does a 0-timeout poll() readiness probe in submit() 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 run net_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) (in net.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.allocator fails it on any leak, which also exercises the shared table's teardown. It passes on both epoll and io_uring.

Existing suite under -Dbackend=epoll: net, Stream, recv, send, accept, connect, cancel, timeout, poll, process, pipe all pass. DNS is 35/37 — the two failures are pre-existing live-DNS assertions and are identical on main.

Benchmark

Closed-loop TCP ping-pong, 64-byte messages, system-default sockets (no TCP_NODELAY), server pinned with taskset so it's the bottleneck, 10s/run, 8-core EPYC 7402. req/s:

Single server thread:

conns epoll before epoll after io_uring
50 93.8k 118.4k 125.7k
200 81.7k 99.9k 102.2k
1000 74.5k 86.0k 88.3k

3 server threads (3 executors):

conns epoll before epoll after io_uring
50 266.5k 374.2k 375.6k
200 276.1k 377.4k 400.3k
1000 263.3k 365.8k 374.7k

strace -f on the single-thread server: epoll_ctl drops 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

  • kqueue has 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.
  • I arm IN|OUT|ET unconditionally, so there's one spurious EPOLLOUT wakeup per socket at registration (negligible).
  • Teardown of the persistent registration happens in net_close; the kernel also drops a closed fd from epoll automatically, the explicit cleanup just keeps the tables tidy for fd reuse.

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

coderabbitai Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c1d4bc65-3a3d-411c-9d74-5400e560aac2

📥 Commits

Reviewing files that changed from the base of the PR and between fb840a8 and 38f89d8.

📒 Files selected for processing (1)
  • src/ev/backends/epoll.zig
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/ev/backends/epoll.zig

📝 Walkthrough

Walkthrough

The epoll backend gains a SharedState struct with a sharded fd→loop-bitmask registry for persistent edge-triggered socket registration across executors. Socket operations attempt syscalls directly and only fall back to epoll on WouldBlock, using persistent registrations that survive across read/write alternation and cross-loop migration. The event loop is refactored to drain socket and non-socket completions through separate paths. A new multi-executor stress test exercises these paths under concurrent migration and fd reuse.

Changes

Persistent edge-triggered epoll socket registration

Layer / File(s) Summary
SharedState: sharded fd registry and backend lifecycle
src/ev/backends/epoll.zig
Adds OS root and NetClose imports. Introduces SharedState with sharded fd→loop-bitmask tables, acquire()/release() lifecycle methods, and shard lookup. Extends Self to acquire shared state during init() and release it in deinit().
Socket registry helpers and poll queue routing split
src/ev/backends/epoll.zig
Adds isSocketOp/dirOf classifiers and implements shared-registry helpers: armRegistration for persistent per-loop registration, parkSocket for enqueuing shared waiters with readiness latches, drainDir for consuming owned directions on epoll events, and unregisterSocket for fd teardown with best-effort kernel DEL and waiter cancellation. Introduces removeOneShotFromPollQueue for non-socket one-shot removal while leaving socket registrations intact.
Optimistic syscall-first submit and deferred completion
src/ev/backends/epoll.zig
Refactors submit() to attempt all socket syscalls immediately; on WouldBlock they enqueue via shared registry. Adds completeDeferred() helper routing net_send* success through the deferred completion queue to avoid resend-loop re-entry. net_poll probes with zero-timeout poll(). net_close calls unregisterSocket before closing. Non-socket file and process ops route through per-loop one-shot path.
Submit and cancel dispatch refactoring
src/ev/backends/epoll.zig
Routes socket operations through optimistic/shared-registry path, non-socket pollables through per-loop one-shot queue, and unreachable backend-completions with compile-time assertions. Refactors cancel() to conditionally remove socket completions from shared waiter queues (under shard lock) when owned by current loop; non-socket removals go through removeOneShotFromPollQueue.
Poll loop refactoring: socket and non-socket event draining
src/ev/backends/epoll.zig
Refactors poll() to drain non-socket one-shot entries from poll_queue with selective removal on completion, then drain socket events by consuming only owned directions from shared waiter queues—ignoring edges without an owned waiter. Updates waitEvents() error handling for INTR and NOSYS. Adjusts handleEpollError early-return logic when no socket error is present.
Completion readiness checking for socket and pipe ops
src/ev/backends/epoll.zig
Updates checkCompletion for net_poll to complete on EPOLLERR/EPOLLHUP or matching requested events, otherwise requeues. Updates pipe_poll completion to check error/hangup or event presence while preserving process_wait pidfd result extraction and close. Updates file write streaming to include explicit EPOLLERR/EPOLLHUP branch.
Multi-executor cross-loop socket stress test
src/net.zig
New test with 3 executors, per-connection echo handlers that force task migration mid-echo, concurrent client writer+reader on same stream with deterministic pattern validation, atomic counters tracking errors/connections/verifications across multiple waves, and asserts zero errors with expected connection and verification totals.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related issues

Possibly related PRs

  • lalinsky/zio#480: Modifies the epoll backend's submit() path to swap active counter increment, which now coexists with this PR's refactored socket submission logic.
  • lalinsky/zio#500: Addresses epoll_pwait2 vs epoll_wait fallback and INTR/NOSYS error handling, directly overlapping with this PR's waitEvents() refactor.

Poem

Once registered, stay put—no kernel thrashing.
Try the syscall first, that's where the work goes.
Block? Park in the shared queue. Close? Deregister first.
Drain socket and non-socket completions on separate tracks.
Full-duplex, cross-loop, fd reuse—no missed edges. 🔌

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title directly describes the main change: persistent socket registration via a shared cross-loop table, which is the core optimization in this PR.
Description check ✅ Passed The description thoroughly covers the problem, design rationale, implementation details, correctness testing, and performance benchmarks—all directly relevant to the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@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

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between b3bc41c and 08553a0.

📒 Files selected for processing (2)
  • src/ev/backends/epoll.zig
  • src/net.zig

Comment thread src/ev/backends/epoll.zig Resolved
Comment thread src/ev/backends/epoll.zig Resolved
Comment thread src/net.zig Resolved
Comment thread src/net.zig Resolved
- 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.
@lalinsky

Copy link
Copy Markdown
Owner

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

Copy link
Copy Markdown
Owner

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:

  • We have a shared poll queue, keyed by (fd, direction), so at most two entries per socket.
  • We register with epoll lazily, on the first recv/send.
  • Handling send/recv:
    • Do the optimistic send/recv on whatever event loop you are on, if it worked, you resume task and don;t even touch the poll queue.
    • If you get WouldBlock, then you look up if the fd/dir is already registered.
      • If yes, you add your completion to the wait queue, and return (park yourself). This needs careful synchronization.
      • If no, you add to the shared poll queue and register with your local epoll.

So this approach is supported:

  • recv previously ran on executor A
  • now it gets migrated to executor B and it runs recv again
  • if recv syscall succeeds, it gets resumed on executor B and continues normally
  • if recv syscall got EAGAIN, you register as waiter, and executor A will resume the task locally when the event fires

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:

  • fast-path touches no lock, needs no migration
  • if we need to poll, it's strictly always faster to just delegate the completion to the loop that already has it registered, because it will arrive sooner, than if we registered is ourselved on the local epoll (less syscalls, lower latency)
  • if we keep the direction as part of the key, we support reader/writer on different threads without any issue
  • lazy registration means the balancing depends on the scheduler, and we are not forcing all sockets to just one epoll

What do you think?

@hyird

hyird commented Jun 23, 2026

Copy link
Copy Markdown
Contributor Author

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 (fd, direction) and registering once is cleaner, and reader/writer on different threads falls out for free. I'll rework the PR to it.

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 —

  • A completes it directly (cross-loop), which means active/inflight accounting has to be shared across the group, like the IOCP backend's counters; or
  • A just wakes B and B finishes it locally (per-loop accounting, one extra hop).

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

@lalinsky

Copy link
Copy Markdown
Owner

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 multi_threaded in capabilities, which just changes some internal accounting, everything else is already thread-safe.

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

hyird commented Jun 24, 2026

Copy link
Copy Markdown
Contributor Author

Pushed the rework: shared (fd, direction) poll queue, lazy single registration, and cross-loop completion via the multi_threaded path. The owning loop drains and completes waiters that were submitted on other loops, exactly like IOCP, and epoll is now multi_threaded in capabilities.

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-(fd, dir) readiness latch: the owner latches an edge that found no waiter, so the next op to park re-checks the syscall instead of waiting.

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.

@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

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between c947199 and fb840a8.

📒 Files selected for processing (1)
  • src/ev/backends/epoll.zig

Comment thread src/ev/backends/epoll.zig Resolved
Comment thread src/ev/backends/epoll.zig Resolved
…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.
@hyird

hyird commented Jun 24, 2026

Copy link
Copy Markdown
Contributor Author

Addressed both review comments in 38f89d8:

  • Close orphaning parked ops (critical): unregisterSocket now drains waiters_in/waiters_out and completes each with error.Canceled (deferred, off the close's submit stack) before dropping the entry, so a close racing a pending op on another loop no longer hangs the fiber or unbalances the accounting. The normal close path (no parked waiters) is unchanged.
  • parkSocket inline error completions (minor): the registry-OOM and epoll_ctl-failure paths now go through completeDeferred like the success path, so a net_send reaching them from the NetSendFile fallback can't complete inline and re-enter.

Full suite still 482/484 (the 2 are the pre-existing live-DNS tests), cross-loop stress green.

Comment thread src/ev/backends/epoll.zig
Comment on lines +431 to +466
// 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;
}

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

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

lalinsky added a commit that referenced this pull request Jun 26, 2026
… 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.
lalinsky added a commit that referenced this pull request Jun 26, 2026
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.
lalinsky added a commit that referenced this pull request Jun 26, 2026
… 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.
lalinsky added a commit that referenced this pull request Jun 26, 2026
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.
lalinsky added a commit that referenced this pull request Jun 26, 2026
… 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.
lalinsky added a commit that referenced this pull request Jun 26, 2026
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.
lalinsky added a commit that referenced this pull request Jun 26, 2026
… 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.
lalinsky added a commit that referenced this pull request Jun 26, 2026


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

Copy link
Copy Markdown
Owner

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-(fd, direction) registration shared across both epoll and kqueue. Closing this in favor of that PR, but your branch is merged into #526's history (with authorship preserved + a Co-authored-by trailer), so the contribution is credited when #526 lands.

Really appreciate the work and the review iterations here.

@lalinsky lalinsky closed this Jun 26, 2026
lalinsky added a commit that referenced this pull request Jun 26, 2026
ev: single-owner cross-loop socket registration (epoll + kqueue) — alternative to #511
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.

epoll backend: ~4 epoll_ctl per request (arm/disarm) caps throughput ~25-35% below io_uring

2 participants