Skip to content

ev: unify completion lifecycle and cancellation into one atomic state word - #609

Merged
lalinsky merged 7 commits into
mainfrom
completion-loop-cleanup
Jul 24, 2026
Merged

lalinsky merged 7 commits into
mainfrom
completion-loop-cleanup

Conversation

@lalinsky

@lalinsky lalinsky commented Jul 24, 2026 •

Copy link
Copy Markdown
Owner

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 state enum (custody plane), the atomic cancel_state byte (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.state is now one atomic packed struct(u8):

pub const State = packed struct(u8) {
    phase: Phase = .new,            // new, running, completed, dead
    cancel_requested: bool = false, // latched by cancel(); backends poll it
    cancel_inflight: bool = false,  // a cancel pass owns the finish dispatch
    _reserved: u4 = 0,
};

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:

  • addInternal gets 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's submit. Publication of the loop pointer is carried by the new -> running CAS, so the loop_set flag and publishLoop are deleted.
  • cancel() collapses from a pre-read of the loop plus two CAS shapes into one CAS; cancelLocal's defer becomes a single fetchAnd.
  • LoopState.setTimer/clearTimer become pure heap operations (armTimer/disarmTimer); timer lifecycle is handled by Loop.setTimer, Loop.clearTimer, and the cancel pass, which 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.
  • has_result stays a plain custody field on purpose: 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.

The branch also adds a debug-only current_loop threadlocal asserting that add, cancel, and deinit run on the loop's own thread. cancel must be called on the calling thread's loop (that is what routes local vs cross-loop); two internal callers cancelling through completion.loop from arbitrary threads were fixed.

Behavior changes

  • cancel_requested survives into .dead, so completion callbacks can still see it; enterRunning drops it on rearm, so a request aimed at a dead incarnation cannot cancel the next one (previously this hinged on reset() timing).
  • requestCancel is a no-op on any non-running phase. This also covers cancelling a disarmed timer, which previously died on a markCompleted assert 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_stress is 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_loop tier (plain state word, no cancel queue, per-loop accounting when task migration is compiled out and the backend has no shared servicing).

@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

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

Changes

Completion lifecycle and cancellation

Layer / File(s) Summary
Unified completion state
src/ev/completion.zig, src/ev/blocking.zig
Completion phases, cancellation flags, loop ownership, reset behavior, and async notification synchronization now use the unified atomic state.
Loop lifecycle, timers, and cancellation
src/ev/loop.zig
Loop completion transitions, timer arm/disarm operations, cross-loop cancellation, active accounting, and debug thread assertions use the new lifecycle helpers.
Backend submission and completion handling
src/ev/backends/*, src/ev/sockreg.zig
Backends stop assigning running state directly, filter non-running completions, use unified cancellation flags, and separate io_uring submission retries.
Callers and regression coverage
src/autocancel.zig, src/common.zig, src/completion_queue.zig, src/io.zig, src/time.zig, src/ev/test/*, src/ev/tests.zig, docs/changelog.md
Callers use loop accessors and current-loop cancellation; tests use loadState() and cover timer race synchronization and cancellation behavior.

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

Possibly related PRs

  • lalinsky/zio#41: Overlaps the completion and loop cancellation state transitions.
  • lalinsky/zio#209: Shares the cross-loop cancellation queue and cancelLocal() redesign.
  • lalinsky/zio#606: Touches the current-loop cancellation contract and completion queue callers.

Poem

One atomic state now guards the gate,
Timers arm, disarm, and negotiate.
Backends skip phases no longer alive,
Cross-thread cancels safely arrive.
Tests watch each transition glow.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: consolidating completion lifecycle and cancellation into one atomic state word.
Description check ✅ Passed The description is on-topic and matches the PR’s atomic state, threading, and cancellation changes.
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 completion-loop-cleanup

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.

@lalinsky lalinsky changed the title [WIP] Completion state cleanup ev: unify completion lifecycle and cancellation into one atomic state word Jul 24, 2026

@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

🧹 Nitpick comments (2)
src/ev/test/cancel.zig (1)

230-245: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Cover cancellation-flag persistence and re-arming.

This test only checks cancel_requested before 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 value

The &c.state.raw → *u8 reinterpret is a silent trap if State ever 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 State is packed struct(u8), so this is correct. But if someone bumps it to u16 (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

📥 Commits

Reviewing files that changed from the base of the PR and between 760cbef and ba4ace6.

📒 Files selected for processing (21)
  • docs/changelog.md
  • src/autocancel.zig
  • src/common.zig
  • src/completion_queue.zig
  • src/ev/backends/epoll.zig
  • src/ev/backends/io_uring.zig
  • src/ev/backends/iocp.zig
  • src/ev/backends/kqueue.zig
  • src/ev/backends/poll.zig
  • src/ev/blocking.zig
  • src/ev/completion.zig
  • src/ev/loop.zig
  • src/ev/sockreg.zig
  • src/ev/test/cancel.zig
  • src/ev/test/fs.zig
  • src/ev/test/group.zig
  • src/ev/test/thread_pool.zig
  • src/ev/test/timer.zig
  • src/ev/tests.zig
  • src/io.zig
  • src/time.zig

Comment thread src/ev/loop.zig Resolved
@lalinsky
lalinsky marked this pull request as ready for review July 24, 2026 11:14
lalinsky added 7 commits July 24, 2026 21:13
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.
@lalinsky
lalinsky force-pushed the completion-loop-cleanup branch from d79559c to 87d0e7e Compare July 24, 2026 19:13

@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/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

📥 Commits

Reviewing files that changed from the base of the PR and between d79559c and 87d0e7e.

📒 Files selected for processing (21)
  • docs/changelog.md
  • src/autocancel.zig
  • src/common.zig
  • src/completion_queue.zig
  • src/ev/backends/epoll.zig
  • src/ev/backends/io_uring.zig
  • src/ev/backends/iocp.zig
  • src/ev/backends/kqueue.zig
  • src/ev/backends/poll.zig
  • src/ev/blocking.zig
  • src/ev/completion.zig
  • src/ev/loop.zig
  • src/ev/sockreg.zig
  • src/ev/test/cancel.zig
  • src/ev/test/fs.zig
  • src/ev/test/group.zig
  • src/ev/test/thread_pool.zig
  • src/ev/test/timer.zig
  • src/ev/tests.zig
  • src/io.zig
  • src/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

Comment thread src/time.zig
_ = self;
_ = waiter;
const loop = ctx.timer.c.loop orelse return true;
const loop = ctx.timer.c.getLoop() orelse return true;

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.

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

Suggested change
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.

@lalinsky
lalinsky merged commit d4202a0 into main Jul 24, 2026
30 checks passed
@lalinsky
lalinsky deleted the completion-loop-cleanup branch July 24, 2026 20:37
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