Skip to content

Cancelable blocking syscalls on thread-pool workers (SIGURG) - #514

Merged
lalinsky merged 3 commits into
mainfrom
cancel-blocking
Jul 5, 2026
Merged

lalinsky merged 3 commits into
mainfrom
cancel-blocking

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

What

Adds a signal-based mechanism to interrupt blocking syscalls running on thread-pool workers, so cancelling a task can break it out of a kernel sleep instead of waiting for the syscall to finish on its own. POSIX-only; first real user is randomSecure (getrandom) via blockInPlace.

How it works

src/os/syscall_cancel.zig holds the core:

  • A task-owned Token with a 4-state machine (idle → blocked → blocked_canceling → canceled). The worker binds it (records pthread_self() + a threadlocal) around the task function; a syscall site brackets the call with begin() / checkCancel() / finish().
  • To cancel, another thread flips the token to blocked_canceling and pthread_kill(SIGURG)s the worker. A no-op handler installed without SA_RESTART turns the interruption into EINTR; checkCancel() then reports error.Canceled.
  • Because the token is task-scoped rather than thread-scoped, a stale signal can at worst land on a worker now running a different token, yielding a harmless spurious EINTR that the syscall's retry loop swallows. No wrong cancellation is possible.

Integration

  • ev.Work gains an optional cancel_token; the thread pool enter/exits it around work.func and signals it from cancel().
  • ThreadPool install/uninstalls the process-global SIGURG handler (refcounted) in init/deinit.
  • os.getrandom's Linux loop is now cancelable; random() / setup() absorb the type-only Canceled they can never actually observe.
  • blockInPlace binds a stack token and, on cancel, drives a cooperative resend-with-backoff loop (via timedWait, so the executor thread is never blocked) to cover the lost-signal window between start() and the kernel entering the syscall. randomSecure is cancelable for free.

Why resend

The SIGURG can be lost if delivered in the gap between marking the thread "in a syscall" and the kernel actually entering the interruptible sleep (the no-op handler eats it, then the syscall blocks uninterrupted). There's no way to confirm a single signal landed, so the waiter resends with backoff until the worker acknowledges (token leaves blocked_canceling). In practice one signal suffices; resend is the correctness backstop. Same approach as std.Io.Threaded.

Scope / follow-ups

This PR covers the mechanism and the blockInPlace path only. Deferred to separate PRs:

  • JoinHandle.cancel / Group.cancel resend loops for spawnBlocking tasks (the waiter safely owns the token in both cases; Group needs a small deferred-release restructure).
  • Cancelable ev completions (delegated file ops on kqueue/poll backends), which is the more significant next piece.

Tests

  • syscall_cancel: the token mechanism in isolation (worker blocked in read, canceled via signal).
  • blockInPlace: cancellation interrupts a blocking syscall on the worker: full task-cancel → blockInPlace → worker read → Canceled path.

487/489 unit tests pass; the two failures are the pre-existing file-size .INVAL cases unrelated to this change. zig fmt --check clean.

@coderabbitai

coderabbitai Bot commented Jun 23, 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: fc8d9f14-9238-4187-a0c8-358f52a6e584

📥 Commits

Reviewing files that changed from the base of the PR and between 0bd6ee9 and 7e237df.

📒 Files selected for processing (10)
  • src/common.zig
  • src/dns/posix.zig
  • src/ev/completion.zig
  • src/ev/thread_pool.zig
  • src/os/posix.zig
  • src/os/root.zig
  • src/os/syscall_cancel.zig
  • src/os/windows.zig
  • src/random.zig
  • src/zio.zig
✅ Files skipped from review due to trivial changes (1)
  • src/zio.zig
🚧 Files skipped from review as they are similar to previous changes (8)
  • src/os/root.zig
  • src/random.zig
  • src/ev/completion.zig
  • src/ev/thread_pool.zig
  • src/dns/posix.zig
  • src/os/posix.zig
  • src/common.zig
  • src/os/syscall_cancel.zig

📝 Walkthrough

Walkthrough

Adds cooperative syscall cancellation through a new OS module, wires it into thread-pool work and blockInPlace, and updates Linux getrandom plus startup error handling to use the new cancellation path.

Changes

Cooperative Syscall Cancellation

Layer / File(s) Summary
syscall_cancel module and exports
src/os/syscall_cancel.zig, src/os/root.zig, src/zio.zig
src/os/syscall_cancel.zig defines the token state machine, Syscall wrapper, SIGURG handler lifecycle, and a read-based cancellation test. os/root.zig re-exports the module, and zio.zig adds it to test coverage.
ThreadPool token lifecycle and cancel signaling
src/ev/completion.zig, src/ev/thread_pool.zig
Work gains cancel_token. ThreadPool installs/removes the handler, wraps inline and worker execution with token enter/exit, and signals the token after a successful cancel transition.
blockInPlace cancellation backoff and test
src/common.zig
blockInPlace adds a done flag, binds a syscall_cancel.Token during allow-cancel handling, retries timed waits with repeated signaling, and adds a cancellation test around a blocked read.
DNS lookup cancellation check
src/dns/posix.zig
lookupBlocking imports syscall_cancel and checks for cancellation before calling getaddrinfo.
Linux getrandom cancellation and startup handling
src/os/posix.zig, src/random.zig
Linux getrandom now uses Syscall.begin()/finish() and returns syscall_cancel.Cancelable; random.zig handles EntropyUnavailable explicitly and marks Canceled unreachable in setup.

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

Possibly related PRs

  • lalinsky/zio#311: Both PRs modify src/common.zig’s blockInPlace implementation.
  • lalinsky/zio#512: Both PRs touch the Linux getrandom and entropy-handling path in src/os/posix.zig and src/random.zig.
  • lalinsky/zio#534: Both PRs modify src/ev/thread_pool.zig lifecycle and cancellation behavior.

Poem

A SIGURG tap wakes sleeping syscalls near,
the token tracks when cancel draws too near.
read can stall, but not for long today—
signal, wait, and let the worker yield its way.
Then getrandom learns to pause and cope,
and startup says “entropy” with narrower scope.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: making blocking syscalls on thread-pool workers cancelable with SIGURG.
Description check ✅ Passed The description matches the patch and explains the syscall-cancellation mechanism, integration points, and tests.
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 cancel-blocking

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

🧹 Nitpick comments (2)
src/os/syscall_cancel.zig (1)

278-284: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Make the interrupt test wait for “inside read,” not for time.

The 50ms sleep can pass through the pre-canceled Syscall.begin() path if the worker has not reached read yet, so the test does not always prove that SIGURG interrupted a blocking syscall. Add a small readiness handshake from the worker after Syscall.begin() and just before read.

🤖 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/os/syscall_cancel.zig` around lines 278 - 284, The test uses a fixed 50ms
sleep which does not reliably synchronize with the worker reaching the blocking
read operation, so cancellation may be handled at Syscall.begin() or
checkCancel() instead of during the actual blocking read call. Replace the
time-based synchronization with a readiness handshake: the worker should signal
back to the test after invoking Syscall.begin() but just before calling read,
and the test should wait for this signal instead of sleeping. This ensures the
test consistently proves that SIGURG can interrupt a blocking syscall operation.
src/common.zig (1)

496-500: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Synchronize the test with the worker reaching read.

The 20ms sleep can cancel before the worker is actually blocked, so the test may pass through the pre-canceled token path and not cover the SIGURG interrupt path it names. Have the worker signal readiness after Syscall.begin() and before entering read, then cancel after that signal.

🤖 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/common.zig` around lines 496 - 500, The current implementation uses a
fixed 20ms sleep to synchronize with the worker, which creates a race condition
where the cancel may occur before the worker actually reaches the blocking read
operation, bypassing the SIGURG interrupt path the test intends to cover. Modify
the worker function to signal readiness after calling Syscall.begin() and before
entering the read operation, then update the test to wait for that signal from
the worker before calling handle.cancel() instead of using the fixed sleep
duration.
🤖 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/common.zig`:
- Around line 417-440: The issue is that after the cancellation catch block
handles the wait, the code unconditionally returns ctx.result, but when
ThreadPool.cancel removes a pending work item it can run completionFn without
calling Context.workFn, leaving ctx.result undefined. After the backoff loop
exits (when ctx.done is true), you need to distinguish between two outcomes: if
the work was queued and canceled (where completionFn ran but the actual workFn
never executed), return or record Canceled when the return type supports it;
otherwise if the work completed normally despite the cancel request, call
task.recancel() before returning ctx.result, similar to how waitForIo handles
this scenario. The key is checking whether the work actually executed its workFn
or was dropped from the queue during cancellation.
- Around line 426-437: The timedWait call within the backoff loop is using a
hardcoded count of 1, which is an absolute waiter signal count that causes the
loop to return immediately on subsequent iterations once the count reaches 1,
resulting in busy spinning and signal spam. Instead of using a fixed count
parameter, increment the waiter signal count on each iteration of the while loop
so that each timedWait call waits for the next signal increment rather than
checking against a static absolute count value.

In `@src/os/posix.zig`:
- Around line 335-350: The syscall_cancel.Syscall region started at the
beginning spans the entire while loop, but the loop performs multiple getrandom
syscalls. The cancellation region should wrap each individual syscall and its
result handling, not the entire loop. Move the sc.finish() call to execute
inside the loop after the errno switch statement completes for each getrandom
call, and restructure the code so that try syscall_cancel.Syscall.begin() is
called for each iteration before the getrandom syscall, rather than once before
the loop. This ensures the cancellation token is only active during each
individual kernel call and its result handling, allowing proper cancellation
delivery between chunks.

In `@src/os/syscall_cancel.zig`:
- Around line 205-228: The `installHandler` and `uninstallHandler` functions
have a race condition because while `install_count` is atomic, the access to
`prev_action` and the `posix.sigaction` calls are not protected as one critical
section. Multiple threads can concurrently check the count, manipulate
`prev_action`, and call `sigaction`, causing data corruption or incorrect
handler state. Introduce a process-local mutex (using std.Thread.Mutex or
similar) and wrap the critical sections in both `installHandler` and
`uninstallHandler` so that the entire sequence of checking `install_count`,
reading/writing `prev_action`, and calling `posix.sigaction` executes atomically
without race conditions.

---

Nitpick comments:
In `@src/common.zig`:
- Around line 496-500: The current implementation uses a fixed 20ms sleep to
synchronize with the worker, which creates a race condition where the cancel may
occur before the worker actually reaches the blocking read operation, bypassing
the SIGURG interrupt path the test intends to cover. Modify the worker function
to signal readiness after calling Syscall.begin() and before entering the read
operation, then update the test to wait for that signal from the worker before
calling handle.cancel() instead of using the fixed sleep duration.

In `@src/os/syscall_cancel.zig`:
- Around line 278-284: The test uses a fixed 50ms sleep which does not reliably
synchronize with the worker reaching the blocking read operation, so
cancellation may be handled at Syscall.begin() or checkCancel() instead of
during the actual blocking read call. Replace the time-based synchronization
with a readiness handshake: the worker should signal back to the test after
invoking Syscall.begin() but just before calling read, and the test should wait
for this signal instead of sleeping. This ensures the test consistently proves
that SIGURG can interrupt a blocking syscall operation.
🪄 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: baf342bd-d5a1-41f4-999b-57ce8a087d0a

📥 Commits

Reviewing files that changed from the base of the PR and between 87eb691 and d18a857.

📒 Files selected for processing (8)
  • src/common.zig
  • src/ev/completion.zig
  • src/ev/thread_pool.zig
  • src/os/posix.zig
  • src/os/root.zig
  • src/os/syscall_cancel.zig
  • src/random.zig
  • src/zio.zig

Comment thread src/common.zig Resolved
Comment thread src/common.zig Resolved
Comment thread src/os/posix.zig Resolved
Comment thread src/os/syscall_cancel.zig Resolved

@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/common.zig`:
- Around line 509-511: The readiness wait in the test can block forever if the
worker never reaches ready.store(...), so add a deadline/timeout around the loop
that waits for ready in the cancelation test. Update the waiting logic near the
cancelable-region check in src/common.zig to fail the test with a clear error
when the deadline is exceeded, instead of sleeping indefinitely.
🪄 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: ece38ff9-5832-4530-a4b2-23effc1df39f

📥 Commits

Reviewing files that changed from the base of the PR and between d18a857 and fbc211f.

📒 Files selected for processing (3)
  • src/common.zig
  • src/os/posix.zig
  • src/os/syscall_cancel.zig
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/os/posix.zig
  • src/os/syscall_cancel.zig

Comment thread src/common.zig Resolved
lalinsky and others added 3 commits July 3, 2026 13:24
Add a signal-based mechanism to interrupt blocking syscalls running on
thread-pool workers, so cancelling a task can break it out of a kernel
sleep instead of waiting for the syscall to finish on its own.

src/os/syscall_cancel.zig holds the core (POSIX only):

  - A task-owned Token with a 4-state machine
    (idle -> blocked -> blocked_canceling -> canceled). The worker binds
    it (records pthread_self() + a threadlocal) around the task function;
    a syscall site brackets the call with begin()/checkCancel()/finish().
  - To cancel, another thread flips the token to blocked_canceling and
    pthread_kill(SIGURG)s the worker. A no-op handler installed without
    SA_RESTART turns the syscall's interruption into EINTR; checkCancel
    then reports error.Canceled. Because the token is task-scoped rather
    than thread-scoped, a stale signal can at worst land on a worker now
    running a different token, yielding a harmless spurious EINTR.

Integration:

  - ev.Work gains an optional cancel_token; the thread pool enters/exits
    it around work.func and signals it from cancel().
  - ThreadPool install/uninstalls the process-global SIGURG handler
    (refcounted) in init/deinit.
  - os.getrandom's Linux loop is now cancelable; random()/setup() absorb
    the type-only Canceled they can never actually observe.
  - blockInPlace binds a stack token and, on cancel, drives a cooperative
    resend-with-backoff loop (timedWait, so the executor thread is never
    blocked) to cover the lost-signal window between start() and the
    kernel entering the syscall. randomSecure is cancelable for free.

Tests cover the token mechanism in isolation and the full task-cancel ->
blockInPlace -> worker-read -> Canceled path.
- installHandler/uninstallHandler: replace atomic install_count with a
  mutex guarding the entire count-check + prev_action + sigaction critical
  section, eliminating a race where concurrent install/uninstall could
  corrupt prev_action or double-install the SIGURG handler

- blockInPlace cancel path: remove thread_pool.cancel() so workFn always
  runs and ctx.result is always valid; only signal the token directly
  (token.cancel + token.signal) so queued work gets canceled at the next
  Syscall.begin() call; use an incrementing wait_count in timedWait to
  prevent spinning after the first timer callback increments notify.state

- getrandom (Linux): move Syscall.begin/finish inside the loop so each
  getrandom call has its own cancelable region; INTR now calls sc.finish()
  and lets the next begin() surface a pending cancel, removing the need for
  checkCancel() in this call site

- Tests: replace fixed-duration sleeps with a ready atomic that the worker
  sets after Syscall.begin() but before read(), so the test reliably
  exercises the SIGURG-while-blocked path

Co-authored-by: Lukáš Lalinský <[email protected]>
getaddrinfo cannot be interrupted by a signal (glibc restarts internally),
so it cannot be canceled once running. Add syscall_cancel.checkCanceled(),
a lightweight peek at the worker's bound token, and call it in the posix DNS
lookupBlocking path right before getaddrinfo, so a cancel that arrived while
the work was still queued aborts the lookup instead of running it to
completion.

Also fix a single-threaded build break in Token: the disabled placeholder for
the pthread handle was `void`, but std.atomic.Value is an extern struct that
can only hold a pointer optional (defined null layout). Use *anyopaque so
`?Handle` has a valid layout; the field is never accessed when disabled.
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