Skip to content

ev: single-owner cross-loop socket registration (epoll + kqueue) — alternative to #511 - #526

Merged
lalinsky merged 20 commits into
mainfrom
socket-single-owner-reg
Jun 26, 2026
Merged

lalinsky merged 20 commits into
mainfrom
socket-single-owner-reg

Conversation

@lalinsky

@lalinsky lalinsky commented Jun 26, 2026 •

Copy link
Copy Markdown
Owner

Draft — alternative to #511. Same single-owner (fd, direction) model @lalinsky described in #511, implemented for both epoll and kqueue behind a shared backend-agnostic layer, plus a couple of extras. Opening it so the two approaches can be compared side by side; #511 is a perfectly good solution and most of this converged on the same design.

Closes #510 (alternatively to #511).

Design

A socket fd is monitored in exactly one loop's poller per direction — the loop that first parks on that (fd, dir). Ops submitted from other loops (task migration / cross-loop full-duplex) are handed to that owner; the owner services and completes them. So a fd is registered on at most two pollers (one per direction), never fanned out across every executor.

  • submit() tries the syscall optimistically and only parks on WouldBlock (draining to EAGAIN, which is what makes the persistent edge-triggered registration safe).
  • New src/ev/sockreg.zig: backend-agnostic sharded fd → Entry table (per-direction owner / readiness latch / waiter queue) plus the generic park / service / submit / cancel control flow. Each backend supplies four small hooks (registerSocket, unregisterCleanup, probeEvent, checkCompletion); epoll and kqueue share one implementation.
  • A per-(fd, dir) readiness latch closes the "edge fires between an op's optimistic EAGAIN and it parking" race.

How this differs from #511

Both converged on the same registration model. The meaningful differences:

#511 this PR
Cross-loop accounting is_multi_threaded = true (reuse IOCP shared counters) new cross_loop_socket_reg capability: per-loop atomic counters, accounting migrated to the owner at park
Completion ownership stays on the submitting loop, completed cross-thread (IOCP-style) completion.loop reassigned to the owner; cancel routes there (with a cancel-queue forward for the reassign race)
Backends epoll epoll + kqueue (shared sockreg.zig)
enable_task_migration=false always shared bypasses the shared group entirely (per-loop local registration, no cross-loop machinery)
latch re-check race (#511 review) inline recheck in parkSocket avoided structurally — the syscall lives in the caller's retry loop, so park re-reads the latch under the lock in the same critical section as the enqueue

Honest note: #511's is_multi_threaded accounting is simpler and is the direction @lalinsky suggested; this PR's per-loop-atomic-migration keeps per-loop done()/active semantics at the cost of more machinery. Either is fine.

Perf

TCP ping-pong + bulk stream (examples/tcp_pingpong_bench.zig, added here; stream mode included), 64-byte messages, ReleaseFast.

Ping-pong, 1 executor, 1 connection (best of 5):

req/s
epoll before 33k
this PR 74k
io_uring 72k

4 executors, count=2000/conn: within noise of #511 everywhere; ~1.8–2.0× over before, ~75–90% of io_uring (io_uring leads multi-exec because client+server share cores in this harness).

One perf detail worth carrying over regardless of which PR lands: completing optimistic reads inline while deferring sends is ~20% on single-loop ping-pong (deferring the read desyncs the producer/consumer and adds an epoll_wait+EAGAIN per round trip).

Known limitation

The deferred-send path does ~1 epoll_wait per chunk, which caps a single bulk stream on one executor (fairness-vs-batching). Bounded to low concurrency; concurrent servers and ping-pong are unaffected. Tracked separately in #525 with options.

Status / testing

  • epoll: full suite 506/506, including a new multi-executor cross-loop stress test (full-duplex + migration + fd reuse, byte-verified) and a migration-disabled variant. io_uring unaffected (capability is comptime-gated; the 2 failures on -Dbackend=io_uring are pre-existing ftruncate env tests on main).
  • kqueue: compiles + links for aarch64-macos / x86_64-macos / x86_64-freebsd, but not yet executed on real hardware — relying on CI for that (please watch the kqueue job).

hyird added 5 commits June 23, 2026 15:16
…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.
- 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.
…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.
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.
…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.
@coderabbitai

coderabbitai Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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: fb40ffa9-604f-4ef9-8f35-ba64baf83f3b

📥 Commits

Reviewing files that changed from the base of the PR and between a82d40a and fcd7476.

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

📝 Walkthrough

Walkthrough

Adds a shared socket registration layer, wires epoll and kqueue through it, adds deferred backend completion handling, and adds a TCP ping-pong benchmark plus a multi-executor full-duplex stress test.

Changes

Cross-loop socket registration and TCP validation

Layer / File(s) Summary
Socket table and helpers
src/ev/sockreg.zig
Defines the shared fd/direction entry state, sharded table, and socket-op mapping helpers used by the registry flow.
Parking and completion flow
src/ev/sockreg.zig, src/ev/loop.zig
Implements parking, readiness servicing, detach/unregister, submit helpers, and deferred backend completion for send-family operations.
epoll shared state and hooks
src/ev/backends/epoll.zig
Adds multi-threaded shared state, tagged epoll event data, sock_table acquire/release, and the exported socket-registration hooks.
epoll socket request flow
src/ev/backends/epoll.zig
Routes epoll close, connect, recv/send/accept/poll, cancel, and error handling through sockreg and tagged event dispatch.
kqueue shared state and hooks
src/ev/backends/kqueue.zig
Adds multi-threaded shared state, socket event tagging, sock_table acquire/release, and the exported socket-registration hooks.
kqueue socket request flow
src/ev/backends/kqueue.zig
Routes kqueue close, connect, recv/send/accept/poll, cancel, and tagged socket events through sockreg.
TCP ping-pong benchmark
build.zig, examples/tcp_pingpong_bench.zig
Adds the example to the build and implements the CLI-driven pingpong/stream TCP benchmark server and clients.
Multi-executor stress test
src/net.zig
Adds the full-duplex multi-executor TCP test with task migration disabled, deterministic payload checks, and atomic result counters.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

  • lalinsky/zio#480: Shares the epoll/kqueue backend area and the shared active/inflight_io accounting added alongside the socket-registration plumbing.
  • lalinsky/zio#504: Touches the same build.zig example wiring used here to add tcp-pingpong-bench.

Poem

A socket woke, then took a bow,
Epoll and kqueue learned the how.
Ping-pong tapped a steady beat,
Stream mode marched on repeat.
The stress test nodded: all good now.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR adds kqueue support, benchmarks, and extra stress tests that are not required by #510. If #510 is the only target, split the kqueue, benchmark, and stress-test work into separate PRs or add linked issues for them.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: single-owner socket registration for epoll and kqueue.
Description check ✅ Passed The description is directly related to the socket registration change and its epoll/kqueue design.
Linked Issues check ✅ Passed The epoll changes meet #510: persistent edge-triggered registration, optimistic syscalls, and net_close cleanup are all present.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch socket-single-owner-reg

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

🤖 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 `@examples/tcp_pingpong_bench.zig`:
- Around line 134-139: The argument parsing in the tcp ping-pong benchmark
should reject invalid count and mode values instead of silently defaulting or
allowing zero. In the CLI setup where cfg.count, cfg.msg, cfg.executors,
cfg.conns, and cfg.mode are parsed, validate that count is greater than zero and
that mode is exactly one of the supported values rather than mapping any unknown
string to .pingpong. Make the parsing fail fast with an error for invalid
inputs, and ensure the round-trip latency path that uses cfg.count cannot reach
a divide-by-zero case.

In `@src/ev/backends/epoll.zig`:
- Line 514: The optimistic connect path in epoll handling is incorrectly
treating the pre-park probe as a successful connection because
`sockreg.submitConnect` relies on `checkCompletion` and `probeEvent` has no
readiness bits. Update the `net_connect` flow to either perform the actual
nonblocking `connect()` before attempting completion or ensure `checkCompletion`
can distinguish `probeEvent` from real epoll readiness so it does not report
success prematurely. Make the same fix consistently in the shared connect
handling path used by `submitConnect` and the corresponding connect-related
logic.

In `@src/ev/backends/kqueue.zig`:
- Around line 413-418: The kqueue cleanup path is only clearing the socket table
and never queues EV_DELETE for pending registrations, so stale EV_ADD changes
can survive in change_buffer and be applied to a reused fd. Update
unregisterCleanup in kqueue.zig, and the related net_close cleanup path, to
enqueue delete changes for both filters before the original fd is closed so the
existing registration is removed from kqueue rather than only from sockreg. Keep
the fix anchored around unregisterCleanup, sockreg.unregister, and net_close so
the deletion happens while the fd is still valid.

In `@src/ev/loop.zig`:
- Around line 344-368: `markCompletedDeferredFromBackend` is pushing into the
non-atomic `completions` queue from a potentially non-owner thread, which can
race with `processCompletions`. Update this path in `LoopState` so synchronous
backend completions only touch `completions` when running on the loop owner
thread; otherwise hand off through `work_completions` or add an owner-thread
assertion/guard around the `submit` callers in `sockreg` to preserve the queue’s
single-threaded invariant.

In `@src/ev/sockreg.zig`:
- Around line 321-326: The unregister path is dropping the entire socket entry,
which can orphan parked completions in read_waiters and write_waiters. Update
unregister() to drain and complete/cancel any queued waiters before removing the
fd from the shard map, using the existing sock_table/shard flow and
unregisterCleanup() as the relevant entry points. If pending close is not
allowed, add an assert that both waiter queues are empty before
shard.map.remove() so active/inflight accounting still unwinds correctly.
- Around line 279-298: The readiness latch in the waiter-drain path is being
cleared even when the queue only contained stale `.completed`/`.dead` waiters,
so the edge can be lost for edge-triggered pollers. Update the logic around
`had_waiters`, the `while` loop over `entry.waiters(dir)`, and the
`entry.readyPtr(dir).*` assignment so only live waiters count as having consumed
the edge. Make the latch stay set when no active waiter actually handled the
event, and only clear it after a real completion/requeue path has drained the
edge.
- Around line 301-303: The completion handling in the `service()` path is
completing parked sends inline, but `net_send*` completions must be deferred the
same way `submitIo` already does because the send callback can re-submit from
`NetSendFile`. Update the `to_finish.pop()` loop in `sockreg.zig` so
`state.markCompletedFromBackend` skips the same `net_send*` branch used in
`submitIo`, deferring those send completions instead of completing them
immediately.

In `@src/net.zig`:
- Around line 2613-2618: The full-duplex test under the migration-disabled path
is asserting a behavior that conflicts with the runtime contract in
src/runtime.zig. Update the test around the full-duplex case to make the
invariant explicit: either assert that the socket fd remains on a single
executor/loop when enable_task_migration is false, or add instrumentation in the
reader/writer setup to verify and enforce the claimed placement. Use the
existing test name and the migration-disabled bypass logic in src/net.zig to
locate the affected assertions and rewrite them so the test validates the actual
contract instead of passing on a false premise.

In `@src/runtime.zig`:
- Around line 340-353: The loop initialization in runtime.zig is incorrectly
bypassing the shared loop_group whenever task migration is disabled, which
breaks split reader/writer ownership and lets per-loop sock_table instances arm
the same fd independently. In the init path around use_internal_group and
self.loop.init, remove the !self.runtime.options.enable_task_migration condition
so any backend with cross_loop_socket_reg always uses the shared
runtime.loop_group; keep null only for backends that do not coordinate
cross-loop socket registration. If split reader/writer behavior is not
supported, add a clear runtime assertion or documented constraint instead of
switching to internal groups.
🪄 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: 1e9431c4-82fa-4648-b989-5e622ee90236

📥 Commits

Reviewing files that changed from the base of the PR and between f5308c5 and 35d99d1.

📒 Files selected for processing (9)
  • build.zig
  • examples/tcp_pingpong_bench.zig
  • src/ev/backends/epoll.zig
  • src/ev/backends/kqueue.zig
  • src/ev/completion.zig
  • src/ev/loop.zig
  • src/ev/sockreg.zig
  • src/net.zig
  • src/runtime.zig

Comment thread examples/tcp_pingpong_bench.zig Resolved
Comment thread src/ev/backends/epoll.zig Resolved
Comment thread src/ev/backends/kqueue.zig Resolved
Comment thread src/ev/loop.zig Resolved
Comment thread src/ev/sockreg.zig Resolved
Comment thread src/ev/sockreg.zig Resolved
Comment thread src/ev/sockreg.zig Resolved
Comment thread src/net.zig Resolved
Comment thread src/runtime.zig Resolved
lalinsky added 9 commits June 26, 2026 22:11
Replace the per-operation epoll_ctl(ADD/DEL) churn for sockets with a
persistent edge-triggered, single-owner registration model that stays
correct under task migration without registering a fd on every loop.

A socket fd is monitored in exactly one loop's epoll per direction - the
loop that first parks on that (fd, dir). Operations submitted from other
loops are handed to the owner at submit time (the completion and its
accounting are migrated to it), so a fd is registered on at most two
epolls (one per direction) regardless of how a fiber migrates.

- New src/ev/sockreg.zig: backend-agnostic sharded fd -> Entry table,
  per-direction owner / readiness latch / waiter queue. Keyed by fd so
  any loop can drop the whole entry on close.
- submit() tries the syscall optimistically and only parks on WouldBlock
  (draining to EAGAIN, which is what makes edge-triggered safe). The
  readiness latch + retry closes the park-after-edge race without a
  syscall recheck.
- Optimistic completions inside submit() are deferred to avoid re-entering
  the submit/add path of drivers like NetSendFile.
- Accounting (active/inflight) is atomic under the new
  cross_loop_socket_reg capability and migrates to the owner loop.
- Completion.loop may be reassigned once at submit; a cancel that raced
  the reassignment is forwarded to the current owner's cancel queue.

New test net.zig "multi-executor: cross-loop socket stress" exercises
full-duplex on one fd across loops, migration mid-connection, and fd
reuse across waves, with byte-level verification and leak checking.

epoll: 505/505. io_uring unaffected (capability is comptime-gated).
Apply the same single-owner model to kqueue, reusing the shared
sockreg.Table from the epoll change. kqueue maps onto it more directly
than epoll: EVFILT_READ / EVFILT_WRITE are natively the (fd, direction)
key, so there is no per-direction mask juggling - each direction is its
own kevent.

- Sockets register EV_ADD | EV_CLEAR (edge-triggered, persistent) on the
  owner loop's kqueue via the per-loop change buffer, tagged with a
  sock_marker udata so poll() routes their events to the shared table
  instead of the one-shot poll_queue (pipes/streaming files share the
  READ/WRITE filters but use udata == 0).
- submit() tries the syscall optimistically and parks on WouldBlock;
  net_poll probes via poll(2); connect tries connect() first.
- parkSocket migrates a completion (and its accounting) to the owning
  loop and wakes it so a pending registration is applied promptly.
- serviceSocket drains a (fd, dir)'s waiters; cancel/close route through
  the shared table; optimistic completions are deferred.

Compile-checked for aarch64-macos, x86_64-macos, x86_64-freebsd (the
shared cross-loop machinery and stress test live in the epoll commit).
epoll still 505/505.
The shared loop group only exists to coordinate cross-loop socket
registration when fibers migrate between executors. With
enable_task_migration = false a socket fd is only ever driven by one
loop, so each executor's loop can use its own (internal) group and
register fds purely locally - no shared table lookups, no cross-loop
accounting.

Gated to the cross_loop_socket_reg backends (epoll/kqueue): multi-threaded
backends (IOCP) keep the shared group unconditionally, since their
completion port and counters live there.

Adds net.zig "multi-executor: full-duplex with task migration disabled":
reader and writer for one fd still land on different executors (each
owning its own direction in its own per-loop table), verifying the
bypass path handles concurrent full-duplex.

epoll 506/506; iocp/kqueue cross-compile clean.
The park / service / submit / cancel / unregister control flow was nearly
identical in both backends - only the poller syscalls differed. Move the
shared logic into sockreg.zig as generic helpers over `self: anytype`
(the backend) and `state: anytype` (its LoopState):

  park, service, detach, unregister, submitIo, submitConnect, submitPoll
  + isSocketOp / dirForOp / netHandle

Each backend now supplies four small hooks instead of duplicating the
logic:

  - registerSocket(fd, dir, other_owned_here) bool  - arm this loop's poller
  - unregisterCleanup(fd)                           - drop this loop's entry
  - probeEvent(fd, dir) Event                        - no-error optimistic event
  - checkCompletion(c, event) (already existed)

epoll keeps its combined IN|OUT mask handling (ADD vs MOD) inside
registerSocket; kqueue ignores other_owned_here since READ/WRITE are
separate filters. Net -140 lines, one implementation to reason about.

epoll 506/506; kqueue cross-compiles for aarch64-macos / x86_64-macos /
x86_64-freebsd.
A loopback TCP ping-pong (client + server tasks) that round-trips a
fixed-size message N times on a runtime with a configurable number of
executors (default 1 - the single-loop micro-benchmark that isolates
per-op event-loop overhead). Prints round-trips/sec and per-round-trip
latency. Args: [count] [msg_bytes] [executors].
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.
A 'stream' mode (5th arg) where each client bulk-sends count*msg bytes
one-directionally to a draining server, measuring GiB/s. Complements the
ping-pong (request/response) mode and exercises the send-heavy / deferred
-send path that ping-pong doesn't.
… 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.
The u64 atomics in epoll/kqueue SharedState fail to compile on 32-bit
targets (arm/riscv32/thumb): @atomicLoad/@atomicrmw reject 64-bit ints
there. Use usize to match the per-loop LoopState counters - u32 on 32-bit
(native atomic), u64 on 64-bit.
@lalinsky
lalinsky force-pushed the socket-single-owner-reg branch from 0fa740c to 7e77603 Compare June 26, 2026 20:11
lalinsky added 3 commits June 26, 2026 22:22
service() cleared the per-direction readiness latch whenever the waiter
queue was non-empty, but it counted completed/dead waiters (which it skips
without consuming the edge). A queue holding only stale waiters would clear
the latch though no live waiter handled the event, so on edge-triggered
pollers the next parker could sleep forever on an edge that already passed.
Only count live, serviced waiters toward consuming the edge.

Addresses a review finding on #526.
submitIo already finishes net_send* via the deferred queue because the
NetSendFile fallback re-submits a NetSend from inside its own send callback;
finishing inline would re-enter submit. A send parked and later completed
from service() takes the same callback path, but was finished inline. Route
serviced net_send* through markCompletedDeferredFromBackend to match.

Addresses a review finding on #526.
count == 0 reached the round-trip latency calc and divided by zero, and an
unknown mode string silently became .pingpong. Fail fast with BadCount/BadMode
instead.

Addresses a review finding on #526.
lalinsky added a commit that referenced this pull request Jun 26, 2026
unregisterCleanup was a no-op, relying on the kernel to remove a closed fd's
knotes. That holds for changes already applied, but a socket EV_ADD still
buffered in change_buffer is flushed after the fd is closed; if the fd number
is reused before the next poll, the stale registration arms the wrong socket
on this loop and routes its readiness through sockreg.service incorrectly.
Scrub any pending change_buffer entries for the fd instead. (Enqueuing an
EV_DELETE was rejected: a buffered delete flushes post-close and could hit a
reused fd, reintroducing the hazard.)

Addresses a review finding on #526.
lalinsky added a commit that referenced this pull request Jun 26, 2026
unregister() removes the fd entry (and its read/write waiter queues) without
finishing any still-parked completions, which would orphan them and leak their
active/inflight accounting. The contract is that callers cancel or await
outstanding socket ops before closing the fd; assert it in safe builds so a
violation surfaces loudly instead of leaking silently.

Addresses a review finding on #526.
@lalinsky
lalinsky marked this pull request as ready for review June 26, 2026 20:27

@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

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

2602-2610: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

clients group has no cleanup safety net on the spawn error path.

Every other group in this file pairs var group: Group = .init; with defer group.cancel(); before try group.wait(); (see lines 2160-2166, and the server_group right above this). This clients group skips it. If try clients.spawn(...) fails partway through a wave, the test returns with the error while already-spawned client tasks are still live and holding a pointer to clients, which then unwinds out of scope — those tasks finish later (during runtime.deinit) against a dead Group. That's a use-after-free, not just a leak.

Spawn failure is rare, but the fix is one line and matches the rest of the file.

Proposed fix
     for (0..H.waves) |_| {
         var clients: Group = .init;
+        defer clients.cancel();
         for (0..H.per_wave) |_| {
             try clients.spawn(H.client, .{ port, id, &sh });
             id += 1;
         }
         try clients.wait();
     }

Same gap exists in the migration-disabled test at lines 2763-2769 — add defer clients.cancel(); after var clients: Group = .init; there too.

🤖 Prompt for 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.

In `@src/net.zig` around lines 2602 - 2610, The clients Group setup in the wave
loop is missing the same cleanup guard used elsewhere in this file. Add defer
clients.cancel() immediately after var clients: Group = .init; in both the main
client-spawn loop and the migration-disabled test, so any partial failure in
clients.spawn cannot leave live tasks holding a dangling reference before
clients.wait() runs.
🤖 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/kqueue.zig`:
- Around line 429-440: `unregisterCleanup` is removing every buffered change
that matches the fd ident, which can also erase non-socket events such as wall
timers on Darwin when the fd is 0 or 1. Update the cleanup logic in
`Self.unregisterCleanup` so it only removes pending socket READ/WRITE changes
for the given `NetHandle`, and leaves timer-related or other non-socket entries
untouched; use the existing `change_buffer` entries’ filter/type fields to
distinguish them while preserving the current ordered removal behavior.

---

Nitpick comments:
In `@src/net.zig`:
- Around line 2602-2610: The clients Group setup in the wave loop is missing the
same cleanup guard used elsewhere in this file. Add defer clients.cancel()
immediately after var clients: Group = .init; in both the main client-spawn loop
and the migration-disabled test, so any partial failure in clients.spawn cannot
leave live tasks holding a dangling reference before clients.wait() runs.
🪄 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: a8a50492-8704-41a7-a2df-bc8378514830

📥 Commits

Reviewing files that changed from the base of the PR and between 35d99d1 and a82d40a.

📒 Files selected for processing (7)
  • build.zig
  • examples/tcp_pingpong_bench.zig
  • src/ev/backends/epoll.zig
  • src/ev/backends/kqueue.zig
  • src/ev/loop.zig
  • src/ev/sockreg.zig
  • src/net.zig
🚧 Files skipped from review as they are similar to previous changes (3)
  • build.zig
  • examples/tcp_pingpong_bench.zig
  • src/ev/sockreg.zig

Comment thread src/ev/backends/kqueue.zig Resolved
unregisterCleanup was a no-op, relying on the kernel to remove a closed fd's
knotes. That holds for changes already applied, but a socket EV_ADD still
buffered in change_buffer is flushed after the fd is closed; if the fd number
is reused before the next poll, the stale registration arms the wrong socket
on this loop and routes its readiness through sockreg.service incorrectly.
Scrub the fd's pending sockreg changes from change_buffer instead.

Match only entries tagged with sock_marker, not every change sharing the ident:
on Darwin the wall timers use idents 0/1 and the waker is EVFILT_USER, so an
ident-only match could drop a pending timer arm. (Enqueuing an EV_DELETE was
rejected: a buffered delete flushes post-close and could hit a reused fd,
reintroducing the hazard.)

Addresses review findings on #526.
unregister() removes the fd entry (and its read/write waiter queues) without
finishing any still-parked completions, which would orphan them and leak their
active/inflight accounting. The contract is that callers cancel or await
outstanding socket ops before closing the fd; assert it in safe builds so a
violation surfaces loudly instead of leaking silently.

Addresses a review finding on #526.
@lalinsky
lalinsky force-pushed the socket-single-owner-reg branch from a82d40a to fcd7476 Compare June 26, 2026 20:44


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