Repository navigation
Conversation
…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.
Contributor
📝 WalkthroughWalkthroughThe 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. ChangesCross-loop completion accounting
Estimated code review effort: 4 (Complex) | ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Second step of the Linux backend work, following #602. Two commits, no custody movement:
completion.loop,activeaccounting, 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 consultscompletion.loop, but when the receiver IS the target it runscancelLocaldirectly, touching the target's single-threaded state. Two call sites drifted from that contract in 9e3ce1a (self.getLoop().cancel(c)becamecompletion.loop.?.cancel(c)), making receiver == target true by construction from any thread; a task that migrated executors between submitting and canceling would runcancelLocalagainst its old loop from the wrong thread.getCurrentExecutor().loop.cancel(c)(matching their submit sides, and no longer skipping the not-yet-added case).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.parkcounts a socket waiter on the (fd, dir) owner, under the shard lock;service/detachdrop it on removal. An op submitted on loop A but parked on owner B is B's to produce: A'shasInflight()stays false and A skips polling for it - which is the point of the change. A'sactivestill holds A'suntil_doneopen.decrInflighthook becomes a no-op for these two backends (they don't mirror submit/complete); io_uring/poll/iocp keep mirror counting unchanged.loop.ziguntouched 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
Blocking sockets: basic smoke test, a pre-existing load-sensitive Wine flake (error.WouldBlockfrom 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.Commit 3: deregister closing sockets from the owner's epoll
Review of the owner pointer surfaced a real bug:
sockreg.unregisterCTL_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.unregistercaptures the (fd, dir) owners under the shard lock and CTL_DELs on each owner's epoll while the fd is still open (epoll_ctlis thread-safe cross-thread).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)./proc/self/fdinfothat 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.