Skip to content

Cross thread cancel - #209

Merged
lalinsky merged 9 commits into
mainfrom
cross-thread-cancel
Jan 16, 2026
Merged

lalinsky merged 9 commits into
mainfrom
cross-thread-cancel

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

No description provided.

@coderabbitai

coderabbitai Bot commented Jan 16, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Refactors cancellation: removes the public Cancel type, makes cancellation a loop-level, thread-safe operation via a lock-free cross-thread cancel queue and wake flag, and migrates time-related APIs to Duration/Timestamp across loop, timers, and backends.

Changes

Cohort / File(s) Summary
Backends (submit/cancel changes)
src/ev/backends/...{epoll.zig,io_uring.zig,iocp.zig,kqueue.zig,poll.zig}
Removed .cancel handling from submit paths; cancel now handled exclusively via Loop.cancel/cancel queue. io_uring.poll signature updated to accept Duration; cancel CQEs flow through normal completion handling.
Completion & Cancel State
src/ev/completion.zig
Removed Cancel variant and public Cancel type. Completion now contains loop and a nested cancel struct with next and atomic requested; removed prior canceled/canceled_by fields. Timer/Async fields updated to Duration/Timestamp and to use Completion.loop.
Event Loop Core
src/ev/loop.zig
Added cancel_queue (atomic MPSC), wake_cancel flag, processCancelQueue() and cancelLocal(). cancel() is now thread-safe/idempotent and fire-and-forget; tick processes cancel queue. Timer scheduling now records timer.c.loop; time APIs use Duration/Timestamp.
Public exports
src/ev/root.zig
Removed public Cancel alias/export.
Tests
src/ev/test/cancel.zig
Tests rewritten to remove Cancel object usage and exercise loop.cancel() including cross-thread cancel behavior; assertions updated for new cancel.requested state.
Runtime integration & IO
src/io.zig, src/runtime/autocancel.zig
Removed construction/use of ev.Cancel; replaced with direct executor.loop.cancel(completion). AutoCancel no longer stores loop; derives loop from timer.c.loop.
Task runtime
src/runtime/task.zig
canMigrate() no longer checks cancellation status; migration decision based on pin_count only.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

A Cancel once stood on its own, now folded into the loop,
Cross-thread queues whisper, wake flags give it a nudge.
Durations and timestamps keep the clocks in line,
Fire-and-forget cancels travel fast, no extra type to judge.
Small code rustles — timers, backends, tests — and the loop hums on.

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Description check ❓ Inconclusive No pull request description was provided by the author. Add a description explaining what the PR accomplishes and why these changes were necessary for users to understand the intent.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Cross thread cancel' directly describes the main feature introduced: cross-thread cancellation infrastructure.
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 cross-thread-cancel

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.

@lalinsky
lalinsky changed the base branch from main to timestamp January 16, 2026 20:20
@lalinsky

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jan 16, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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 (3)
src/ev/backends/poll.zig (1)

14-14: Remove unused Cancel import.

The refactor removed the Cancel completion type from the submit function, making this import dead code. A grep search confirms there are no actual references to Cancel in the file beyond the import itself.

src/ev/backends/kqueue.zig (1)

16-16: Remove unused Cancel import.

The Cancel type isn't referenced anywhere in the file (only appears in a doc comment). This import should be deleted.

src/ev/backends/epoll.zig (1)

15-15: Remove unused import on line 15.

The Cancel type is imported but never used. The code only references error.Canceled (the error value), not the Cancel type itself.

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

493-538: Cross-thread cancellation test: minor robustness concern.

The test works, but there's a subtle timing window: between loop1.add(&timer.c) (line 509) and the cancel thread starting, loop1 hasn't called run() yet. The timer's state is .running after add, so the cancel should work.

However, the polling loop at lines 526-532 uses loop.run(.no_wait) which doesn't block - the 1ms sleep between iterations is the actual wait mechanism. This is fine for testing but slightly inefficient.

Consider using loop.run(.once) instead of no_wait + sleep for cleaner blocking:

while (!completed.load(.acquire)) {
    try loop1.run(.once);
    if (wall_timer.read() > 1 * std.time.ns_per_s) {
        return error.TestTimeout;
    }
}

This would make the test faster since .once blocks until an event occurs.

Base automatically changed from timestamp to main January 16, 2026 20:55
@lalinsky

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jan 16, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

1 similar comment
@coderabbitai

coderabbitai Bot commented Jan 16, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

- Add loop field to Completion to track which loop owns it
- Add cancel struct to Completion with next pointer and requested atomic
- Add cancel_queue to Loop for cross-thread cancel requests
- Add wake_cancel bit to LoopState
- Remove redundant loop field from Async (use c.loop instead)
- Remove redundant loop field from AutoCancel (use timer.c.loop instead)
- Set completion.loop in add() and setTimer()

This is Phase 1 of the cross-thread cancellation refactor - adding the
infrastructure without changing the cancellation logic yet.
- Rewrite cancel() to handle same-loop vs cross-loop cases
- Same-loop: call cancelLocal() directly
- Cross-loop: push to target's cancel_queue and wake it
- Add cancelLocal() with the actual cancellation logic
- Add processCancelQueue() to drain cross-thread requests
- Process cancel queue in tick() when wake_cancel flag is set
- Simplify cancelInternal() to use cancelLocal()

Phase 2 of cross-thread cancellation refactor.
Remove the Cancel completion and just call loop.cancel() directly,
then wait for the target operation to complete.

Phase 3 of cross-thread cancellation refactor.
- Remove Cancel completion type (struct with target field)
- Remove .cancel from Op enum
- Remove canceled and canceled_by fields from Completion
- Remove cancelInternal() function
- Remove recursive completion logic from markCompleted()
- Clean up Cancel handling in loop.add()
- Update backends to remove .cancel references and outdated comments
- Update tests to use cancel.requested instead of canceled field
- Remove tests that relied on Cancel completion type

This is a net removal of ~380 lines of code.

Phase 4 of cross-thread cancellation refactor.
Test that verifies cancelling an operation from a different thread/loop
works correctly via the cancel queue mechanism.

Phase 5 of cross-thread cancellation refactor.
- Remove error returns from cancel() - it's now fire-and-forget
- Double cancel is no-op
- Cancel after completion is no-op
- Cancel before submit marks it, fails on add
- Update tests to reflect idempotent behavior
@lalinsky
lalinsky force-pushed the cross-thread-cancel branch from 1de4a9a to ed6f367 Compare January 16, 2026 21:25

@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

Caution

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

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

15-15: Unused import: Cancel type was removed from completion.zig.

The Cancel type no longer exists in the completion module (removed as part of this PR's cancellation refactor). This import will cause a compile error.

🔧 Proposed fix
-const Cancel = `@import`("../completion.zig").Cancel;
🤖 Fix all issues with AI agents
In `@src/ev/backends/epoll.zig`:
- Around line 396-401: The current cancel path calls
removeFromPollQueue(getHandle(target), target) and on catch simply logs and
returns, which can leave the completion stuck; change the catch handler to
either reinsert the completion or mark/complete the waiter with error.Canceled
(use the same completion finalization path used elsewhere) so the waiter is not
left in .running — locate removeFromPollQueue and the cancel caller in
epoll.zig, capture the removal error, and call the completion finalize/complete
routine (or requeue via the same queue insertion helper) before returning
instead of only logging.

Comment thread src/ev/backends/epoll.zig Resolved
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