Repository navigation
Cancelable blocking syscalls on thread-pool workers (SIGURG) - #514
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (10)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (8)
📝 WalkthroughWalkthroughAdds cooperative syscall cancellation through a new OS module, wires it into thread-pool work and ChangesCooperative Syscall 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: 4
🧹 Nitpick comments (2)
src/os/syscall_cancel.zig (1)
278-284: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMake 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 reachedreadyet, so the test does not always prove that SIGURG interrupted a blocking syscall. Add a small readiness handshake from the worker afterSyscall.begin()and just beforeread.🤖 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 winSynchronize 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 enteringread, 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
📒 Files selected for processing (8)
src/common.zigsrc/ev/completion.zigsrc/ev/thread_pool.zigsrc/os/posix.zigsrc/os/root.zigsrc/os/syscall_cancel.zigsrc/random.zigsrc/zio.zig
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/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
📒 Files selected for processing (3)
src/common.zigsrc/os/posix.zigsrc/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
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.
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) viablockInPlace.How it works
src/os/syscall_cancel.zigholds the core:Tokenwith a 4-state machine (idle → blocked → blocked_canceling → canceled). The worker binds it (recordspthread_self()+ a threadlocal) around the task function; a syscall site brackets the call withbegin()/checkCancel()/finish().blocked_cancelingandpthread_kill(SIGURG)s the worker. A no-op handler installed withoutSA_RESTARTturns the interruption intoEINTR;checkCancel()then reportserror.Canceled.EINTRthat the syscall's retry loop swallows. No wrong cancellation is possible.Integration
ev.Workgains an optionalcancel_token; the thread poolenter/exits it aroundwork.funcand signals it fromcancel().ThreadPoolinstall/uninstalls the process-globalSIGURGhandler (refcounted) ininit/deinit.os.getrandom's Linux loop is now cancelable;random()/setup()absorb the type-onlyCanceledthey can never actually observe.blockInPlacebinds a stack token and, on cancel, drives a cooperative resend-with-backoff loop (viatimedWait, so the executor thread is never blocked) to cover the lost-signal window betweenstart()and the kernel entering the syscall.randomSecureis cancelable for free.Why resend
The
SIGURGcan 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 leavesblocked_canceling). In practice one signal suffices; resend is the correctness backstop. Same approach asstd.Io.Threaded.Scope / follow-ups
This PR covers the mechanism and the
blockInPlacepath only. Deferred to separate PRs:JoinHandle.cancel/Group.cancelresend loops forspawnBlockingtasks (the waiter safely owns the token in both cases; Group needs a small deferred-release restructure).Tests
syscall_cancel: the token mechanism in isolation (worker blocked inread, canceled via signal).blockInPlace: cancellation interrupts a blocking syscall on the worker: full task-cancel →blockInPlace→ workerread→Canceledpath.487/489 unit tests pass; the two failures are the pre-existing file-size
.INVALcases unrelated to this change.zig fmt --checkclean.