Repository navigation
ev: unify completion lifecycle and cancellation into one atomic state word - #609
Conversation
📝 WalkthroughWalkthroughThe event system consolidates completion lifecycle and cancellation data into one atomic state, updates loop timer and cancellation handling, adapts all event backends, and changes callers and tests to use the new state accessors. ChangesCompletion lifecycle and cancellation
Estimated code review effort: 4 (Complex) | ~60 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
🧹 Nitpick comments (2)
src/ev/test/cancel.zig (1)
230-245: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winCover cancellation-flag persistence and re-arming.
This test only checks
cancel_requestedbefore the run and during the callback. Add assertions after completion that the flag remains set in.dead, then exercise the supported re-arm path and verify the flag is cleared.🤖 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/ev/test/cancel.zig` around lines 230 - 245, Extend the test “cancel: cancel_requested flag is set on completion” after loop.run(.until_done) to assert cancel_requested remains set when the timer is .dead. Then use the timer’s supported re-arm operation and assert the flag is cleared, covering both persistence after completion and successful re-arming.src/ev/completion.zig (1)
427-430: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThe
&c.state.raw→*u8reinterpret is a silent trap ifStateever outgrows a byte.const mask: u8 = `@bitCast`(State{ .cancel_inflight = true }); return `@bitCast`(`@atomicRmw`(u8, `@as`(*u8, `@ptrCast`(&c.state.raw)), .And, ~mask, .acq_rel));Right now
Stateispacked struct(u8), so this is correct. But if someone bumps it tou16(e.g. more flags), this RMW would quietly touch only the low byte and the@bitCast(u8)mask would lose the top bits — no compile error, just a subtle cancel-dispatch bug. A one-line comptime guard makes it fail loud instead:🛡️ Optional guard
pub fn finishCancelPass(c: *Completion) State { + comptime std.debug.assert(`@bitSizeOf`(State) == 8); const mask: u8 = `@bitCast`(State{ .cancel_inflight = true }); return `@bitCast`(`@atomicRmw`(u8, `@as`(*u8, `@ptrCast`(&c.state.raw)), .And, ~mask, .acq_rel)); }🤖 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/ev/completion.zig` around lines 427 - 430, Add a comptime size assertion near finishCancelPass to require that State remains exactly one byte, while preserving the existing u8 atomic RMW and mask logic. Anchor the guard to State and ensure any future widening fails compilation rather than silently truncating state updates.
🤖 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/loop.zig`:
- Around line 661-666: Update the doc comment for Loop.cancel to remove the
claim that it is thread-safe or callable from any thread. Document that cancel
must be called on the current thread’s own loop, while the targeted Completion
may belong to another loop and is routed appropriately.
---
Nitpick comments:
In `@src/ev/completion.zig`:
- Around line 427-430: Add a comptime size assertion near finishCancelPass to
require that State remains exactly one byte, while preserving the existing u8
atomic RMW and mask logic. Anchor the guard to State and ensure any future
widening fails compilation rather than silently truncating state updates.
In `@src/ev/test/cancel.zig`:
- Around line 230-245: Extend the test “cancel: cancel_requested flag is set on
completion” after loop.run(.until_done) to assert cancel_requested remains set
when the timer is .dead. Then use the timer’s supported re-arm operation and
assert the flag is cleared, covering both persistence after completion and
successful re-arming.
🪄 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 Plus
Run ID: 0f576a0d-868f-4b02-8e04-fdcdb697c394
📒 Files selected for processing (21)
docs/changelog.mdsrc/autocancel.zigsrc/common.zigsrc/completion_queue.zigsrc/ev/backends/epoll.zigsrc/ev/backends/io_uring.zigsrc/ev/backends/iocp.zigsrc/ev/backends/kqueue.zigsrc/ev/backends/poll.zigsrc/ev/blocking.zigsrc/ev/completion.zigsrc/ev/loop.zigsrc/ev/sockreg.zigsrc/ev/test/cancel.zigsrc/ev/test/fs.zigsrc/ev/test/group.zigsrc/ev/test/thread_pool.zigsrc/ev/test/timer.zigsrc/ev/tests.zigsrc/io.zigsrc/time.zig
Add a debug-only current_loop threadlocal, set by Loop.init and cleared by Loop.deinit, and assert self == current_loop in add, cancel and deinit. cancel in particular relies on being called on the calling thread's loop to route between local and cross-thread cancellation. Fix the call sites that violated the contract: - CompletionQueue.cancelAll and batchCancelPending canceled via c.loop.?.cancel(c), which takes the local fast path from the wrong thread when the completion lives on another executor's loop; route through the current executor's loop instead - the cross-thread clearTimer test deinited the loop from the main thread; deinit on the runner thread, with a handshake so deinit cannot race the final wake()
All access to Completion.loop now goes through atomic setLoop/getLoop helpers instead of a mix of atomic and plain loads/stores. reset() clears the loop pointer again, reverting the stale-pointer workaround from f6983a3. The lost wake that commit fixed was a store-buffering race: notify() could read a null loop while the re-add read pending as unset, leaving an armed handle with pending set and no wake. Instead of relying on a stale pointer causing a spurious wake, both pending swaps are now acq_rel RMWs on the same variable, so they order against each other: if the re-add's swap comes first, notify sees the new loop and wakes it; if notify's swap comes first, add() sees pending and completes the handle itself. Reading a null loop in notify() therefore proves add() will deliver the notification. Unlike the stale-pointer scheme, this stays correct even if a handle is re-armed on a different loop. The race is only reproducible on weakly ordered hardware (originally caught by async_stress on aarch64 CI).
Add a loop_set flag to CancelState, set by a single acq_rel fetchOr (publishLoop) in add() right after the loop pointer is stored. The RMW returns the previous flags, so it replaces the separate requested check and closes the remaining cancel-before-add race: it orders against the cancel CAS on the same byte, so whichever lands second sees the other's flag. Previously add() checked cancel_state with a plain acquire load, which allowed a store-buffering outcome where a cancel racing the submission was stranded until the op completed naturally. With ordering carried by the RMW handshakes (cancel_state for cancel, pending for async notify), setLoop/getLoop drop from release/acquire to monotonic, plain machine loads/stores on all architectures. cancel() simplifies from pre-reading the loop and two CAS shapes into a single CAS that sets in_queue only when loop_set was already observed, and dereferences the loop only after that observation guarantees its visibility. Loop.setTimer also publishes, so directly-armed timers still support loop.cancel(). executeBlocking clears cancel_state so a completion reused from a previous submitted life cannot leave a stale loop_set routing a cancel to a dead loop.
A running timer sits in its owning loop's heap. Re-arming it through a different loop's setTimer would remove it from that loop's heap under the wrong mutex (corrupting the owner's heap) and reroute the active count decrement, leaking the owner's count. No current caller does this, but both setTimer and AutoCancel.set are public re-arming APIs and task migration makes the cross-loop case reachable.
… word Completion.state becomes a single atomic packed byte holding the lifecycle phase (new/running/completed/dead) plus the cancel_requested and cancel_inflight flags, replacing the separate plain state enum and the atomic cancel_state byte. All transitions are named single-RMW methods (enterRunning, enterCompleted, enterDead, disarm, requestCancel, finishCancelPass), so every cross-thread race on a completion resolves through the modification order of one word. The store-buffering analysis needed for the old two-variable handshakes (loop_set vs cancel, and the original lost-wake bug fixed in f6983a3) disappears structurally. addInternal gains a single prologue (setLoop, enterRunning, incrActive) replacing the per-branch running-transitions and active counting that were spread across its branches, submitFileOpToThreadPool and every backend submit. LoopState.setTimer/clearTimer become pure heap ops (armTimer/disarmTimer) with timer lifecycle handled by Loop.setTimer, Loop.clearTimer and the cancel pass, which now re-checks under the timer lock instead of relying on state sniffing. io_uring's is_new state check becomes an explicit submit/resubmit split. cancel_requested now survives into dead (callbacks can read it) and is dropped by enterRunning on rearm, so a request aimed at a previous incarnation cannot cancel the next one. requestCancel is a no-op on any non-running phase, which also covers canceling a disarmed timer, a path that previously died on an assert in markCompleted. The hot path drops from ~5 ordered atomic ops per completion to two CASes plus the active counter. Measured on x86-64 (ReleaseFast, io_uring): the timer add/fire/finish cycle runs ~3% faster despite executing +0.8% more instructions per callgrind (CAS loops branch more, but cost less), HTTP throughput via wrk is unchanged. The acquire/release fence savings on weakly ordered architectures are untested on real hardware. has_result stays a plain custody-plane field: making it a state bit would add an RMW to every setResult, and its only cross-thread use (the timer mid-fire limbo) is already protected by the timer mutex.
d79559c to
87d0e7e
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/time.zig`:
- Line 579: Update the early-return path in the timer logic around
ctx.timer.c.getLoop() so ctx.waiter is cleared before returning when getLoop()
yields null. Preserve the existing return value and normal loop path, ensuring
no stale waiter remains in WaitContext.
🪄 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 Plus
Run ID: 193c3ec2-15af-45c2-897e-56b9391d6520
📒 Files selected for processing (21)
docs/changelog.mdsrc/autocancel.zigsrc/common.zigsrc/completion_queue.zigsrc/ev/backends/epoll.zigsrc/ev/backends/io_uring.zigsrc/ev/backends/iocp.zigsrc/ev/backends/kqueue.zigsrc/ev/backends/poll.zigsrc/ev/blocking.zigsrc/ev/completion.zigsrc/ev/loop.zigsrc/ev/sockreg.zigsrc/ev/test/cancel.zigsrc/ev/test/fs.zigsrc/ev/test/group.zigsrc/ev/test/thread_pool.zigsrc/ev/test/timer.zigsrc/ev/tests.zigsrc/io.zigsrc/time.zig
🚧 Files skipped from review as they are similar to previous changes (19)
- src/ev/test/thread_pool.zig
- src/autocancel.zig
- src/ev/blocking.zig
- src/ev/test/group.zig
- src/common.zig
- src/ev/tests.zig
- src/completion_queue.zig
- src/ev/backends/poll.zig
- src/ev/sockreg.zig
- src/ev/backends/kqueue.zig
- docs/changelog.md
- src/ev/backends/epoll.zig
- src/ev/test/cancel.zig
- src/io.zig
- src/ev/backends/io_uring.zig
- src/ev/backends/iocp.zig
- src/ev/completion.zig
- src/ev/test/timer.zig
- src/ev/loop.zig
| _ = self; | ||
| _ = waiter; | ||
| const loop = ctx.timer.c.loop orelse return true; | ||
| const loop = ctx.timer.c.getLoop() orelse return true; |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Clear ctx.waiter before the early return.
When getLoop() returns null, this returns before line 580 clears the waiter. That leaves a stale pointer in WaitContext and can let a queued or reused timer callback signal the wrong waiter.
Proposed fix
+ ctx.waiter = null; // Prevent callback from waking a stale/reused waiter
const loop = ctx.timer.c.getLoop() orelse return true;
- ctx.waiter = null; // Prevent callback from waking a stale/reused waiter
loop.clearTimer(&ctx.timer);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const loop = ctx.timer.c.getLoop() orelse return true; | |
| ctx.waiter = null; // Prevent callback from waking a stale/reused waiter | |
| const loop = ctx.timer.c.getLoop() orelse return true; | |
| loop.clearTimer(&ctx.timer); |
🤖 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/time.zig` at line 579, Update the early-return path in the timer logic
around ctx.timer.c.getLoop() so ctx.waiter is cleared before returning when
getLoop() yields null. Preserve the existing return value and normal loop path,
ensuring no stale waiter remains in WaitContext.
Unifies the completion lifecycle and cancellation coordination into a single atomic state word, and tightens the threading contract around the loop's entry points.
Motivation
A completion's state was smeared across four variables: the plain
stateenum (custody plane), the atomiccancel_statebyte (requested/in_queue/completed/loop_set),has_result, and the implicit "loop pointer is published" fact. Every cross-thread interaction needed a two-variable handshake, and each handshake required store-buffering analysis to prove no outcome where both sides read stale values. One such outcome was a real bug caught on aarch64 CI (f6983a3, the lost async wake); the cancel-before-add path had the same theoretical hole.Design
Completion.stateis now one atomicpacked struct(u8):All transitions are named single-RMW methods on
Completion(enterRunning,enterCompleted,enterDead,disarm,requestCancel,finishCancelPass), each returning the previous state so the caller sees the full picture atomically. Every cross-thread race on a completion now resolves through the modification order of this one word; the store-buffering class of bugs is gone structurally, not carefully handled.Consequences that fall out:
addInternalgets a single prologue (setLoop,enterRunning,incrActive) replacing the per-branch running-transitions and active counting previously spread across its op branches,submitFileOpToThreadPool, and every backend'ssubmit. Publication of the loop pointer is carried by thenew -> runningCAS, so theloop_setflag andpublishLoopare deleted.cancel()collapses from a pre-read of the loop plus two CAS shapes into one CAS;cancelLocal's defer becomes a singlefetchAnd.LoopState.setTimer/clearTimerbecome pure heap operations (armTimer/disarmTimer); timer lifecycle is handled byLoop.setTimer,Loop.clearTimer, and the cancel pass, which re-checks under the timer lock instead of relying on state sniffing.is_newstate check becomes an explicitsubmit/resubmitsplit.has_resultstays a plain custody field on purpose: a state bit would add an RMW to everysetResult, and its only cross-thread use (the timer mid-fire limbo) is already protected by the timer mutex.The branch also adds a debug-only
current_loopthreadlocal asserting thatadd,cancel, anddeinitrun on the loop's own thread.cancelmust be called on the calling thread's loop (that is what routes local vs cross-loop); two internal callers cancelling throughcompletion.loopfrom arbitrary threads were fixed.Behavior changes
cancel_requestedsurvives into.dead, so completion callbacks can still see it;enterRunningdrops it on rearm, so a request aimed at a dead incarnation cannot cancel the next one (previously this hinged onreset()timing).requestCancelis a no-op on any non-running phase. This also covers cancelling a disarmed timer, which previously died on amarkCompletedassert when the queued cancel arrived.Performance
The hot path drops from ~5 ordered atomic ops per completion to two CASes plus the active counter pair. Measured on x86-64 (ReleaseFast, io_uring): the timer add/fire/finish cycle runs ~3% faster while executing +0.8% more instructions per callgrind (CAS loops branch more but cost less), HTTP throughput via wrk is unchanged. The acquire/release fence savings on weakly ordered architectures are the larger expected win and remain unmeasured on real hardware; the aarch64 CI run of
async_stressis the regression gate for the ordering itself.Testing
564/564 on io_uring (Debug and ReleaseSafe), epoll, poll (563), Windows/iocp under Wine, aarch64-epoll under QEMU, kqueue compile via aarch64-macos, plus the full examples build.
Follow-up enabled
The transition methods are now the single switch point for a comptime
cross_looptier (plain state word, no cancel queue, per-loop accounting when task migration is compiled out and the backend has no shared servicing).