Repository navigation
ev: don't complete a socket op the owner loop already resolved - #586
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis change makes socket cancellation race-aware across epoll and kqueue, reports detachment ownership, adds a multi-executor regression test, and documents the fixed double-completion behavior. ChangesSocket cancellation race fix
Estimated code review effort: 4 (Complex) | ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/net.zig`:
- Around line 2686-2687: Update the cross-loop exercise around
runtime_mod.spawn, accept, and handler-spawn failures so each infrastructure
failure increments sh.errors before returning or continuing. Ensure failed nudge
spawns and non-timeout accept or handler-spawn paths are counted consistently,
including the corresponding logic at the additional reported location.
🪄 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: 9c45bec5-6b33-446f-997e-092963833edf
📒 Files selected for processing (5)
docs/changelog.mdsrc/ev/backends/epoll.zigsrc/ev/backends/kqueue.zigsrc/ev/sockreg.zigsrc/net.zig
ae6f562 to
789113c
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/sockreg.zig`:
- Around line 325-331: Update the missing-entry fallback in the detach logic
around shard.map.getPtr and return false instead of true when no registry entry
exists. Preserve the existing waiters(dir).remove(target) result for present
entries so cancellation only claims operations still registered.
🪄 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: 24e623c0-3bb9-4212-88e5-7efad55bd7fa
📒 Files selected for processing (5)
docs/changelog.mdsrc/ev/backends/epoll.zigsrc/ev/backends/kqueue.zigsrc/ev/sockreg.zigsrc/net.zig
🚧 Files skipped from review as they are similar to previous changes (4)
- src/ev/backends/kqueue.zig
- docs/changelog.md
- src/ev/backends/epoll.zig
- src/net.zig
789113c to
95da406
Compare
A socket op parks in the (fd, dir) waiter queue of the loop that owns the fd's poller registration, but since 59d6160 it stays owned by its submitting loop: only the registration moved to the owner, not the completion. So a cancel (e.g. the op's timeout timer firing in its race group, on the submitting loop) can run on one thread while the owner services the op on another. epoll/kqueue cancel discarded detach()'s result and then unconditionally ran setError(error.Canceled) + markCompletedFromBackend. service() sets the result under the shard lock but calls markCompleted only after unlocking, so a cancel landing in that window saw cancel_state.completed still clear, detached nothing, and completed the op a second time. In safe builds that trips assert(!c.has_result) in setError. In ReleaseFast it overwrites the natural result, so a read reports error.Timeout after the bytes were already consumed off the socket, and the op is dispatched twice with active/inflight double-decremented. detach() now reports whether it actually removed the op from the waiter queue, and cancel finishes the op only when it did. The shard lock makes that answer exact: service() removes the waiter under the same lock it sets the result under, so "still queued" and "no result yet" are the same condition. cancel_state.completed cannot serve here because it is published after the unlock. When the cancel loses, cancelLocal's epilogue already hands the dispatch back to the owner, and the callback still fires exactly once. A missing table entry counts as claimed: service() bails out the same way, so nothing else could ever finish the op. The comment claiming cancel routes to the owner's thread predates 59d6160, which removed the completion.loop reassignment that made it true. The regression test pairs a writer sending one byte per jittered tick with a reader whose recv timeout is drawn from the same distribution, so recvs park and their timers expire alongside arriving data; the reader hops executors after every byte so the submitting loop is not the owner. It asserts byte loss rather than a crash, since the release-mode shape of the race is a recv whose result the cancel overwrote after the kernel already consumed the bytes: the reader then runs short and sees EOF early. That holds in any build mode and on any machine, unlike a read count (a reader lagging the writer coalesces bytes into fewer reads). Fails 6/6 with the fix reverted, passes 8/8 with it. Full suite passes on epoll (Debug and ReleaseSafe), io_uring and poll; kqueue and iocp cross-compile for macos/freebsd/netbsd/windows.
95da406 to
80beda0
Compare
On epoll and kqueue, a socket op whose timeout expires at the same moment its
data arrives can be completed twice. Shipped in v0.16.0.
Cause
A socket op parks in the
(fd, dir)waiter queue of the loop that owns the fd'spoller registration, but since 59d6160 it stays owned by its submitting loop:
that commit moved the registration to the owner, not the completion (the earlier
completion.loop = owner_loopreassignment caused a use-after-free). So a cancelruns on one thread while the owner services the op on another. The usual trigger
is an op's own timeout:
timedWaitForIoputs the I/O and its timer in a racegroup on the submitting loop, and the expiring timer cancels the I/O from there.
canceldiscardeddetach()'s result and then unconditionally ransetError(error.Canceled)+markCompletedFromBackend.service()sets theresult under the shard lock but calls
markCompletedonly after unlocking, so acancel landing in that window found
cancel_state.completedstill clear,detached nothing, and completed the op a second time.
The comment claiming
cancelroutes to the owner's thread predates 59d6160,which deleted the invariant that made it true.
Impact
assert(!c.has_result)insetError.ReleaseFast: overwrites the natural result, so a read reportserror.Timeoutafter the bytes were already consumed off the socket. Silent data loss. The op
is also dispatched twice with
active/inflightdouble-decremented.Only affects multi-executor runtimes where a socket is driven from more than one
executor. The existing cross-loop stress test uses 5s timeouts, so it practically
never fires the cancel path, which is why this went unnoticed.
Fix
detach()now reports whether it actually removed the op from the waiter queue,and
cancelfinishes the op only when it did. The shard lock makes that answerexact rather than conservative:
service()removes the waiter under the samelock it sets the result under, so "still queued" and "no result yet" are the same
condition. (
cancel_state.completedcannot serve here, since it is publishedafter the unlock.) When the cancel loses,
cancelLocal's existing epiloguealready hands the dispatch back to the owner, and the callback still fires
exactly once.
This is the same claim-before-commit discipline
Channeluses viatryClaim:the claim has to be atomic with the side effect. The old code performed the claim
and ignored its answer.
Test
The regression test drives short jittered recv timeouts against a matching write
cadence, with the reader bouncing executors every round so the submitter is not
the owner and an expiring timeout collides with a cross-loop readiness edge. It
fails 6/6 without the fix and passes 10/10 with it.
Full suite passes on epoll (Debug and ReleaseSafe) and io_uring. kqueue and iocp
cross-compile for macos/freebsd/netbsd/windows; the kqueue half of the fix is
identical in shape but is not executed by CI on this machine.