Skip to content

Refactor cancellation to use atomic CancelState - #219

Merged
lalinsky merged 2 commits into
mainfrom
atomic-cancel-state
Jan 20, 2026
Merged

lalinsky merged 2 commits into
mainfrom
atomic-cancel-state

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Summary

  • Replace the cancel.requested atomic boolean with a CancelState packed struct
  • Keep state field non-atomic (only loop thread modifies it)
  • Use in_queue flag to coordinate who calls finishCompletion

Design

The new CancelState is an 8-bit packed struct with three flags:

  • requested - cancel was requested
  • in_queue - completion is in cancel queue (queue will call finish)
  • completed - markCompleted ran (result is set)

Key coordination:

  • cancel() sets requested=true and in_queue=true when queuing
  • markCompleted() sets completed=true, only finishes if !in_queue
  • cancelLocal() clears in_queue in defer, finishes if completed was true

This ensures exactly one path calls finishCompletion, preventing the use-after-free race where a completion in the cancel queue could be freed before processing.

Test plan

  • All existing cancel tests pass (38 tests)
  • Full test suite passes (294 tests)

…nting

Replace the previous atomic Status with reference counting approach with
a simpler CancelState packed struct:
- requested: bool - cancel was requested
- in_queue: bool - completion is in cancel queue (queue will call finish)
- completed: bool - markCompleted ran (result is set)

Key design:
- state field remains non-atomic (only loop thread modifies it)
- cancel_state is atomic for cross-thread cancellation coordination
- in_queue flag determines who calls finishCompletion:
  - If in_queue=false when markCompleted runs, markCompleted finishes
  - If in_queue=true, cancelLocal will finish after clearing in_queue
- completed flag prevents cancel from overwriting natural results

The CAS in cancel() and markCompleted() ensures exactly one path
calls finishCompletion, avoiding the use-after-free race where a
completion in the cancel queue could be freed before processing.
@coderabbitai

coderabbitai Bot commented Jan 20, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR replaces the per-Completion cancel struct with an atomic CancelState (requested, in_queue, completed) and an intrusive cancel_next pointer, and updates loop cancellation, completion finalization, tests, and backend poll loops to use the new atomic queue-based cancellation semantics.

Changes

Cohort / File(s) Summary
Completion state
src/ev/completion.zig
Remove old nested cancel struct; add packed CancelState (u8) and cancel_state: std.atomic.Value(CancelState) plus cancel_next: ?*Completion. Update init/reset to store/clear cancel_state and null cancel_next.
Loop cancellation & processing
src/ev/loop.zig
Replace uses of completion.cancel.requested/cancel.next with completion.cancel_state.load(...).[flags] and completion.cancel_next. Rework cancel(), cancelLocal(), processCancelQueue(), markCompleted/finishCompletion paths to honor in_queue/completed flags and cross-loop enqueueing via cancel_next.
Tests
src/ev/test/cancel.zig
Update tests to read cancel_state.load(.acquire).requested (and related flags) instead of the old cancel.requested field; adjust test names/assertions accordingly.
Backends: poll loops
src/ev/backends/epoll.zig, src/ev/backends/kqueue.zig, src/ev/backends/poll.zig
Add guards in per-fd/completion iteration to skip completions that are already finished or dead, preventing redundant processing when cancellations complete concurrently.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Poem

Old per-Completion bits unwind,
Three atomic flags in a byte aligned,
A cancel queue links through the night,
In_queue, requested, completed right—
Cross-thread handoffs hum, precise and kind. ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: replacing an atomic boolean with an atomic CancelState packed struct for cancellation coordination.
Description check ✅ Passed The description clearly relates to the changeset, explaining the new CancelState design, coordination rules, and test coverage.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch atomic-cancel-state

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 and usage tips.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/ev/loop.zig (1)

369-409: cancel() can run cancelLocal off-thread when caller uses the target loop.

The branch uses self == target to decide local vs queued cancel. If a caller on another thread calls target_loop.cancel(...) (which the doc comment allows), this will run cancelLocal and mutate loop-owned structures off-thread (timer heap, async queue, backend cancel) — data race territory. Consider guarding cancelLocal to only run on the loop thread, otherwise enqueue to target.cancel_queue, or tighten/clarify the API contract and assert on misuse.

Skip already-completed completions in poll loops to prevent setting
results twice. This can happen with cancellations where:
- cancel() marks completion as done
- A kernel event arrives before the registration is removed
- poll() tries to process the stale event

The guard was already present in io_uring, now added to kqueue, epoll,
and poll backends for consistency and defensive programming.
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