Skip to content

ev: make clearTimer report whether it stopped the callback - #611

Merged
lalinsky merged 1 commit into
mainfrom
timer-clear-contract
Jul 25, 2026
Merged

lalinsky merged 1 commit into
mainfrom
timer-clear-contract

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

A timer that has already fired cannot be disarmed, and Loop.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 stack frame holding the timer while the loop was still on its way to invoking its callback.

clearTimer now 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-level ev users that call clearTimer.

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 a lost clear parks on.

Along the way this fixes the cancel paths of Notify, ResetEvent, Condition and Futex: their waiter.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.timedWait also stops reporting error.Timeout when a completion woke it but was gone by the time it looked.

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.

Testing

./check.sh passes (565 tests). Added clearTimer reports a callback it could not stop, which reproduces the window deterministically via do_not_call_callbacks, and the cross-thread clearTimer stress test now asserts the contract instead of working around it.

Not covered by a test: the cancel_inflight bail in clearTimer. 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.

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.
@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This 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.

Changes

Timer cancellation and timed-wait races

Layer / File(s) Summary
Timer completion ownership
src/ev/completion.zig, src/ev/loop.zig, src/time.zig, src/ev/test/timer.zig
Timer disarming now reports whether cancellation succeeded, preserves completion-pass ownership, and tests both stoppable and already-firing callbacks.
Waiter timeout signaling
src/common.zig
Timed waits use a timeout flag separate from signal counts, return error.Timeout, and mask timeout state when checking wake conditions.
Synchronization and completion consumers
src/sync/*.zig, src/completion_queue.zig
Condition, futex, notify, reset-event, and completion-queue waits distinguish timeout from a concurrently claimed signal or completion.
Cancellation callers and regression coverage
src/autocancel.zig, src/io.zig, src/runtime.zig, docs/changelog.md
Auto-cancel waits for in-flight callbacks, while sleep paths consume timeout as normal completion and propagate cancellation.

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

Possibly related PRs

  • lalinsky/zio#609 — Refactors timer cancellation and completion lifecycle ownership.
  • lalinsky/zio#232 — Refactors waiter-based timed-wait and wakeup behavior.
  • lalinsky/zio#233 — Changes timeout cancellation and callback signaling in src/time.zig.

Poem

Timers race, but flags now know,
Which wake arrived, and which must go.
Callbacks finish, waiters speak,
Sleeps wake whole, not timeout-weak.
Signals claim their rightful place—
No dangling frames in the chase.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: clearTimer now returns whether it stopped the callback.
Description check ✅ Passed The description is on-topic and describes the timer, waiter, and completion behavior changes in the patch.
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 timer-clear-contract

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.

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 win

The errdefer can't fire for the assertion its message describes.

errdefer only covers errors returned at or after its declaration. It's declared on Line 480, after the expectError on 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 where elapsed matters 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 win

Pin the timeout before looping.

CompletionQueue.timedWait reuses timeout on each timedWait() 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 with deadline: Timeout = timeout.toDeadline() and pass that to timedWait().

🤖 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 win

Lost-race path in clear() isn't directly tested.

Traced this through and it's correct — the fired release/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 in src/ev/test/timer.zig; nothing pins down AutoCancel.clear() itself parking on fired and 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, race clear() against the fire on a second thread or via do_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

📥 Commits

Reviewing files that changed from the base of the PR and between d4202a0 and 7e517a6.

📒 Files selected for processing (14)
  • docs/changelog.md
  • src/autocancel.zig
  • src/common.zig
  • src/completion_queue.zig
  • src/ev/completion.zig
  • src/ev/loop.zig
  • src/ev/test/timer.zig
  • src/io.zig
  • src/runtime.zig
  • src/sync/Condition.zig
  • src/sync/Futex.zig
  • src/sync/Notify.zig
  • src/sync/ResetEvent.zig
  • src/time.zig

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