Skip to content

ev: per-instance inflight on epoll/kqueue, Loop.cancel receiver contract - #606

Closed
lalinsky wants to merge 3 commits into
mainfrom
ev-owner-inflight
Closed

lalinsky wants to merge 3 commits into
mainfrom
ev-owner-inflight

Conversation

@lalinsky

@lalinsky lalinsky commented Jul 23, 2026 •

Copy link
Copy Markdown
Owner

Second step of the Linux backend work, following #602. Two commits, no custody movement: completion.loop, active accounting, and cancel routing all stay with the submitting loop (the home loop). Relocating fd ownership to follow tasks is a planned follow-up.

Commit 1: enforce Loop.cancel's receiver contract

Loop.cancel's receiver is meant to be the loop the calling thread drives: routing consults completion.loop, but when the receiver IS the target it runs cancelLocal directly, touching the target's single-threaded state. Two call sites drifted from that contract in 9e3ce1a (self.getLoop().cancel(c) became completion.loop.?.cancel(c)), making receiver == target true by construction from any thread; a task that migrated executors between submitting and canceling would run cancelLocal against its old loop from the wrong thread.

  • Both sites restored to getCurrentExecutor().loop.cancel(c) (matching their submit sides, and no longer skipping the not-yet-added case).
  • The contract is now explicit: a threadlocal tracks the loop each thread drives (claimed at init, refreshed each tick, released at deinit) and cancel asserts it in safe builds.

Commit 2: per-instance inflight on epoll/kqueue

hasInflight() was backed by group-shared storage, answering "does anyone in the group have work" - so a loop with nothing of its own registered still paid the wait syscall whenever any other loop had pending ops.

Now each poller instance counts exactly its queue membership: ops it will produce completions for, from queue entry to queue exit.

  • sockreg.park counts a socket waiter on the (fd, dir) owner, under the shard lock; service/detach drop it on removal. An op submitted on loop A but parked on owner B is B's to produce: A's hasInflight() stays false and A skips polling for it - which is the point of the change. A's active still holds A's until_done open.
  • poll_queue entries (pipes, pidfd, streaming, mach ports) count on their own loop at add/remove.
  • Sync-completing ops are no longer transiently counted.
  • The decrInflight hook becomes a no-op for these two backends (they don't mirror submit/complete); io_uring/poll/iocp keep mirror counting unchanged. loop.zig untouched by this commit.

New ev-level test (epoll/kqueue): two loops in a group; B owns the fd, A submits a recv that parks on B - asserts the counts land on B and not A, that one readiness edge on B services both loops' waiters, and that a cancel detached from A's thread drops B's count.

Testing

  • io_uring 564/564 (new test skipped), epoll 565/565, poll 563/563
  • Wine (iocp): 499/500 - the failure is Blocking sockets: basic smoke test, a pre-existing load-sensitive Wine flake (error.WouldBlock from a blocking socket); A/B verified: 8 Wine runs with commit 1 fail 5, 8 runs without it fail 3 - flaky in both configurations, unrelated to this branch. Worth a separate issue.
  • x86_64-macos (kqueue) compiles.

Commit 3: deregister closing sockets from the owner's epoll

Review of the owner pointer surfaced a real bug: sockreg.unregister CTL_DELed on the closing loop's epoll, but the registration lives in the owner's epoll. That worked only by refcount luck (close-time eviction); with the description kept alive by another reference (dup/fork/SCM_RIGHTS), the owner is left with a permanently unremovable registration - epoll subscriptions are keyed to the file description and the closed fd was the only handle to remove them - firing events forever at whatever socket reuses the fd number.

  • unregister captures the (fd, dir) owners under the shard lock and CTL_DELs on each owner's epoll while the fd is still open (epoll_ctl is thread-safe cross-thread).
  • Direction ownership is structural now: optional Owned { owner: *Loop, waiters } per direction - a waiter cannot exist without an owner, and the owner is non-optional where used. Readiness latches stay outside (ERR/HUP can latch a direction nobody owns yet).
  • kqueue is immune to the description footgun (knotes are fd-keyed, dropped at close regardless of refs) and keeps its local change-buffer scrub; its own cross-loop gap (un-flushed EV_ADD in the owner's buffer) is documented, to be removed by registering sockets eagerly in a follow-up.
  • Regression test: dup the fd so eviction can't help, close via a non-owner loop, assert via /proc/self/fdinfo that the owner's epoll no longer lists it. Verified to fail with the old closer-side DEL.

Full matrix re-run: io_uring 564/564, epoll 566/566, poll 563/563, macOS compile OK.

lalinsky added 2 commits July 23, 2026 14:08
…g it

Loop.cancel's receiver is meant to be the loop the calling thread
drives: the routing consults completion.loop and queues the request
cross-thread, but when the receiver IS the target it runs cancelLocal
directly, touching the target's single-threaded state. That contract was
implicit, and two call sites drifted away from it in 9e3ce1a
("simplify current task/executor tracking"), which rewrote
self.getLoop().cancel(c) into completion.loop.?.cancel(c) - making
receiver == target true by construction, from whatever thread the
caller happens to be on. A task that migrated executors between
submitting and canceling would then run cancelLocal against its old
loop from the wrong thread.

Restore both sites to the current executor's loop (matching their
submit sides, and no longer skipping the not-yet-added case), and make
the contract explicit: track the loop each thread drives in a
threadlocal (claimed at init, refreshed at every tick, released at
deinit) and assert it in cancel in safe builds.
The epoll/kqueue inflight count was group-shared: hasInflight() answered
"does any loop in the group have pending ops", so a loop with nothing of
its own registered still paid the wait syscall whenever any other loop
had work.

Count queue membership per poller instance instead: an op is counted on
the instance whose poller will produce its completion, from the moment
it enters a serviced queue until it leaves. sockreg.park counts a socket
waiter on the (fd, dir) owner - the point of the change: an op submitted
on loop A but parked on owner B is B's to produce, so A's hasInflight()
stays false and A skips polling for it - and service/detach drop it on
removal, all under the shard lock that already guards the queues.
poll_queue entries (pipes, pidfd, streaming, mach ports) count on their
own loop at add/remove. Sync-completing ops never enter a queue and are
no longer transiently counted.

The decrInflight hook invoked via markCompletedFromBackend becomes a
no-op for these two backends: they do not mirror submit/complete, since
an op they accept may be parked on (and dropped by) another instance's
poller. io_uring/poll/iocp keep their mirror counting unchanged; the
loop is untouched. Completion custody does not move: completion.loop,
active accounting, and cancel routing stay with the submitting loop.
@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change tracks parked completions per event backend, records the loop driving each thread, routes pending cancellation through the current executor, updates socket-registration ownership bookkeeping, and adds cross-loop socket tests.

Changes

Cross-loop completion accounting

Layer / File(s) Summary
Loop ownership and cancellation routing
src/ev/loop.zig, src/completion_queue.zig, src/io.zig
Tracks the current driving loop, validates Loop.cancel receivers, and routes pending cancellation through the current executor loop.
Per-backend parked counters and cleanup
src/ev/backends/epoll.zig, src/ev/backends/kqueue.zig
Replaces shared inflight accounting with per-backend counters and updates cleanup APIs to receive owning loops.
Socket owner queue bookkeeping
src/ev/sockreg.zig
Stores concrete per-direction owners and waiter queues, updating parked accounting during parking, completion, detachment, and unregister cleanup.
Cross-loop regression tests
src/ev/test/sockreg.zig, src/ev/tests.zig
Adds socketpair coverage for cross-loop completion, cancellation, counter cleanup, and owner-loop epoll deregistration.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

  • lalinsky/zio#219: Changes completion cancellation coordination inside Loop.cancel.
  • lalinsky/zio#526: Refactors the sockreg ownership and backend cleanup paths used here.
  • lalinsky/zio#586: Addresses related socket cancellation and detach coordination.

Poem

Parked waits line up in queues,
Each loop counts the work it owns.
Cancellations find their driver,
Socket waiters shed their stones.
Epoll and kqueue keep time—
Tests verify each count in rhyme.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title matches the main changes: per-instance inflight accounting and Loop.cancel receiver enforcement.
Description check ✅ Passed The description accurately covers the cancel contract, per-instance inflight accounting, and socket deregistration changes.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ev-owner-inflight

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.

An epoll subscription is keyed to the file description, and the fd is
the only handle for removing it. sockreg.unregister issued its CTL_DEL
on the closing loop's epoll, but the registration lives in the owner
loop's epoll, which need not be the same one. That worked by refcount
luck: closing the last reference to the description evicts it from every
epoll at the kernel level. When another reference keeps the description
alive (dup, fork, SCM_RIGHTS), the owner is left with a permanently
unremovable registration - the fd is closed, so no epoll_ctl can ever
name it again - firing events forever, tagged with an fd number that the
shard table resolves to whatever socket occupies it next.

unregister now captures the (fd, dir) owners under the shard lock and
CTL_DELs on each owner's epoll while the fd is still open (epoll_ctl is
thread-safe from any thread). kqueue is unaffected by the description
footgun (knotes are fd-keyed; close removes them regardless of other
references) and keeps its local change-buffer scrub; its remaining
cross-loop gap (an un-flushed EV_ADD in the owner's buffer) is noted and
will be fixed by registering sockets eagerly instead of buffering.

Direction ownership also becomes structural: the per-direction owner and
waiter queue merge into an optional Owned record with a non-optional
*Loop owner, so a waiter cannot exist without an owner and the owner is
never a nullable pointer where it is used. Readiness latches stay
outside the record: an edge can be latched for a direction nobody owns
yet (ERR/HUP is serviced for both directions regardless of
registration).

The regression test dups the fd so close-time eviction cannot clean up,
closes through a non-owner loop, and asserts via /proc fdinfo that the
owner's epoll no longer lists the fd.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant