Skip to content

ev: don't complete a socket op the owner loop already resolved - #586

Merged
lalinsky merged 1 commit into
mainfrom
fix-sockreg-cancel-race
Jul 17, 2026
Merged

lalinsky merged 1 commit into
mainfrom
fix-sockreg-cancel-race

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

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's
poller 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_loop reassignment caused a use-after-free). So a cancel
runs on one thread while the owner services the op on another. The usual trigger
is an op's own timeout: timedWaitForIo puts the I/O and its timer in a race
group on the submitting loop, and the expiring timer cancels the I/O from there.

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 found cancel_state.completed still clear,
detached nothing, and completed the op a second time.

The comment claiming cancel routes to the owner's thread predates 59d6160,
which deleted the invariant that made it true.

Impact

  • Safe builds: trips assert(!c.has_result) in setError.
  • ReleaseFast: overwrites the natural result, so a read reports error.Timeout
    after the bytes were already consumed off the socket. Silent data loss. The op
    is also dispatched twice with active/inflight double-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 cancel finishes the op only when it did. The shard lock makes that answer
exact rather than conservative: 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, since it is published
after the unlock.) When the cancel loses, cancelLocal's existing epilogue
already hands the dispatch back to the owner, and the callback still fires
exactly once.

This is the same claim-before-commit discipline Channel uses via tryClaim:
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.

@coderabbitai

coderabbitai Bot commented Jul 17, 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
📝 Walkthrough

Walkthrough

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

Changes

Socket cancellation race fix

Layer / File(s) Summary
Detachment ownership contract
src/ev/sockreg.zig
detach now reports whether cancellation removed the completion from the owner’s waiter queue.
Backend cancellation flow
src/ev/backends/epoll.zig, src/ev/backends/kqueue.zig
Socket cancel paths only mark operations canceled when detachment succeeds, preventing result overwrites after the owner wins the race.
Multi-executor regression coverage
src/net.zig, docs/changelog.md
A jittered cross-loop test verifies reads, timeouts, and zero unexpected errors, and the race fix is documented under Unreleased.

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

Possibly related PRs

  • lalinsky/zio#229: Related epoll cancellation handling for stale or overwritten completion state.
  • lalinsky/zio#443: Related kqueue socket cancellation and completion lifecycle handling.
  • lalinsky/zio#526: Related cross-loop socket-cancellation ownership through sockreg.

Poem

Timeout knocks, readiness rings,
Two loops tug on completion strings.
Detach decides who gets the prize,
No double finish, no stale disguise.
Reads and timeouts both survive.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the core fix: avoiding duplicate completion when the owner loop already resolved a socket op.
Description check ✅ Passed The description is directly about the same race, cause, impact, fix, and test added in this 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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-sockreg-cancel-race

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

📥 Commits

Reviewing files that changed from the base of the PR and between e0bdaf5 and 635da0a.

📒 Files selected for processing (5)
  • docs/changelog.md
  • src/ev/backends/epoll.zig
  • src/ev/backends/kqueue.zig
  • src/ev/sockreg.zig
  • src/net.zig

Comment thread src/net.zig Resolved
@lalinsky
lalinsky force-pushed the fix-sockreg-cancel-race branch from ae6f562 to 789113c Compare July 17, 2026 13:00

@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

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between ae6f562 and 789113c.

📒 Files selected for processing (5)
  • docs/changelog.md
  • src/ev/backends/epoll.zig
  • src/ev/backends/kqueue.zig
  • src/ev/sockreg.zig
  • src/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

Comment thread src/ev/sockreg.zig Resolved
@lalinsky
lalinsky force-pushed the fix-sockreg-cancel-race branch from 789113c to 95da406 Compare July 17, 2026 20:18
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.
@lalinsky
lalinsky force-pushed the fix-sockreg-cancel-race branch from 95da406 to 80beda0 Compare July 17, 2026 20:29
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