Repository navigation
ev: make clearTimer report whether it stopped the callback - #611
Conversation
A timer that has already fired cannot be disarmed, and clearTimer quietly did nothing in that case. A task woken by the other side of the race (a channel send, an I/O completion, anything that migrates it to another executor) then returned and dropped the frame holding the timer while the loop was still on its way to invoking its callback. clearTimer now returns false there, and its callers park until the callback has run. Waiter.timedWait reports error.Timeout instead of leaving callers to infer the winner by trying to remove themselves from a wait queue. The timeout timer no longer signals; it sets a bit in the waiter's state, so the signal count only ever reflects real wakeups. That bit doubles as the handshake the lost clear parks on, and it fixes the cancel paths of Notify, ResetEvent, Condition and Futex, where the timer's phantom signal could satisfy the wait for an in-flight signal and let the waiter be destroyed while one was still being delivered to it. Completion.disarm becomes tryDisarm: it keeps a latched cancel request and refuses to disarm while a cancel pass owns the completion, which would otherwise let both that pass and the next incarnation dispatch it.
📝 WalkthroughWalkthroughThis change makes timed waits return explicit timeout errors, separates timeout state from wake signals, and coordinates timer cancellation with in-flight callbacks. Synchronization primitives, completion queues, sleep paths, and auto-cancellation now resolve timeout, cancellation, and concurrent wakeup races explicitly. ChangesTimer cancellation and timed-wait races
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.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/common.zig (1)
476-488: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winThe
errdefercan't fire for the assertion its message describes.
errdeferonly covers errors returned at or after its declaration. It's declared on Line 480, after theexpectErroron Line 477 — so a "returned without Timeout" failure never prints the diagnostic. It does still fire for the bound checks on Lines 483/487, which is whereelapsedmatters less.Read the stopwatch inside the handler so it covers the whole block:
💚 Move the diagnostic above the first assertion
var timer = Stopwatch.start(); + errdefer std.debug.print("timedWait(50ms) returned after {d}ms\n", .{timer.read().toMilliseconds()}); + try std.testing.expectError(error.Timeout, waiter.timedWait(1, .fromMilliseconds(50), .no_cancel)); const elapsed = timer.read(); - errdefer std.debug.print("timedWait(50ms) returned after {d}ms\n", .{elapsed.toMilliseconds()}); - // Should return after the timeout expires (allow slight undershoot for timer resolution) try std.testing.expect(elapsed.toMilliseconds() >= 40);🤖 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 476 - 488, Move the errdefer diagnostic in the timedWait test to immediately after starting the Stopwatch and before the waiter.timedWait expectError assertion, so failures from that assertion also report the elapsed duration. Keep the existing elapsed calculation and timeout-bound assertions unchanged.
🧹 Nitpick comments (2)
src/completion_queue.zig (1)
116-162: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winPin the timeout before looping.
CompletionQueue.timedWaitreusestimeouton eachtimedWait()call. For.duration, both the task path and futex path convert it inside the waiter and re-arm the full duration on every wake that produces no poppable completion. Convert once before the loop withdeadline: Timeout = timeout.toDeadline()and pass that totimedWait().🤖 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/completion_queue.zig` around lines 116 - 162, Update CompletionQueue.timedWait to convert the incoming timeout to a single deadline before entering its retry loop, then pass that deadline to self.waiter.timedWait on every iteration. Preserve the existing completion, cancellation, and timeout handling while ensuring wakeups cannot re-arm the full duration.src/autocancel.zig (1)
30-46: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winLost-race path in
clear()isn't directly tested.Traced this through and it's correct — the
firedrelease/acquire pair genuinely covers the UAF risk, and finishCompletion's post-callback touches are all short-circuited away for this non-rearm timer. But right now the only test exercising a lost disarm race is the low-level cross-thread one insrc/ev/test/timer.zig; nothing pins downAutoCancel.clear()itself parking onfiredand correctly unblocking. Given how easy it'd be to regress this (e.g. reordering the store/wake in the callback), a small dedicated test — arm a short timer, raceclear()against the fire on a second thread or viado_not_call_callbacks-style manual dispatch — would pay for itself.🤖 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/autocancel.zig` around lines 30 - 46, Add a focused test for AutoCancel.clear() that forces the timer into the lost-disarm path, then verifies clear() parks until the callback publishes fired and wakes it before returning. Use the existing timer test helpers or a controlled second-thread/manual-dispatch race, and cover the callback store/wake ordering without changing the clear() implementation.
🤖 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.
Outside diff comments:
In `@src/common.zig`:
- Around line 476-488: Move the errdefer diagnostic in the timedWait test to
immediately after starting the Stopwatch and before the waiter.timedWait
expectError assertion, so failures from that assertion also report the elapsed
duration. Keep the existing elapsed calculation and timeout-bound assertions
unchanged.
---
Nitpick comments:
In `@src/autocancel.zig`:
- Around line 30-46: Add a focused test for AutoCancel.clear() that forces the
timer into the lost-disarm path, then verifies clear() parks until the callback
publishes fired and wakes it before returning. Use the existing timer test
helpers or a controlled second-thread/manual-dispatch race, and cover the
callback store/wake ordering without changing the clear() implementation.
In `@src/completion_queue.zig`:
- Around line 116-162: Update CompletionQueue.timedWait to convert the incoming
timeout to a single deadline before entering its retry loop, then pass that
deadline to self.waiter.timedWait on every iteration. Preserve the existing
completion, cancellation, and timeout handling while ensuring wakeups cannot
re-arm the full duration.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 58b43c92-9d7a-40a6-a259-59dea46ba206
📒 Files selected for processing (14)
docs/changelog.mdsrc/autocancel.zigsrc/common.zigsrc/completion_queue.zigsrc/ev/completion.zigsrc/ev/loop.zigsrc/ev/test/timer.zigsrc/io.zigsrc/runtime.zigsrc/sync/Condition.zigsrc/sync/Futex.zigsrc/sync/Notify.zigsrc/sync/ResetEvent.zigsrc/time.zig
A timer that has already fired cannot be disarmed, and
Loop.clearTimerquietly did nothing in that case. A task woken by the other side of the race (a channel send, an I/O completion, anything that migrates it to another executor) then returned and dropped the stack frame holding the timer while the loop was still on its way to invoking its callback.clearTimernow returns whether the timer is the caller's again. False means the callback has run or is still to run, and the caller keeps the timer alive until it has. This is a breaking change for low-levelevusers that callclearTimer.Waiter.timedWaitreportserror.Timeoutinstead of leaving callers to infer the winner by trying to remove themselves from a wait queue. The timeout timer no longer signals; it sets a bit in the waiter's state, so the signal count only ever reflects real wakeups. That bit doubles as the handshake a lost clear parks on.Along the way this fixes the cancel paths of
Notify,ResetEvent,ConditionandFutex: theirwaiter.wait(1, .no_cancel)drain could be satisfied by the timer's phantom signal and let the waiter be destroyed while a real signal was still being delivered to it.CompletionQueue.timedWaitalso stops reportingerror.Timeoutwhen a completion woke it but was gone by the time it looked.Completion.disarmbecomestryDisarm: it keeps a latched cancel request and refuses to disarm while a cancel pass owns the completion, which would otherwise let both that pass and the next incarnation dispatch it.Testing
./check.shpasses (565 tests). AddedclearTimer reports a callback it could not stop, which reproduces the window deterministically viado_not_call_callbacks, and the cross-threadclearTimerstress test now asserts the contract instead of working around it.Not covered by a test: the
cancel_inflightbail inclearTimer. Reaching it needs a cross-loop cancel queued while another thread clears, so it needs two loops on two threads, and no in-tree path both cancels and clears the same timer.