Skip to content

Add mutex protection for timer heap on multi-threaded backends - #194

Merged
lalinsky merged 3 commits into
mainfrom
timer-mutex-protection
Jan 11, 2026
Merged

lalinsky merged 3 commits into
mainfrom
timer-mutex-protection

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Summary

  • Add is_multi_threaded capability to BackendCapabilities (IOCP sets it to true)
  • Add conditional timer_mutex to LoopState with lockTimers()/unlockTimers() helpers
  • Protect timer heap operations in Loop.setTimer, Loop.clearTimer, Loop.checkTimers, Loop.add, and Loop.cancelInternal

This enables safe cross-thread timer cancellation when completions may be delivered on a different loop thread than where the timer was submitted (e.g., grouped IOCP loops).

Zero overhead on single-threaded backends - mutex and lock/unlock calls are compiled out.

@coderabbitai

coderabbitai Bot commented Jan 10, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The PR adds multi-threaded timer support to the event loop by introducing conditional mutex protection around timer state mutations, extending backend capability reporting to declare multi-threaded support, and making completion context optional across timer and linked work operations.

Changes

Cohort / File(s) Summary
Backend capability reporting
src/ev/backends/iocp.zig, src/ev/completion.zig
Adds is_multi_threaded capability field to BackendCapabilities; iocp backend sets it to true, completion.zig provides the struct definition with default false
Timer synchronization & loop refactoring
src/ev/loop.zig
Introduces conditional timer_mutex field on LoopState, adds lockTimers/unlockTimers methods, refactors checkTimers to batch-process fired timers under lock before signaling completions, guards all timer state mutations (setTimer, clearTimer, cancellation) with the mutex, changes completion callback signatures to accept optional context, introduces public LinkedWorkContext struct
Timeout integration
src/runtime/timeout.zig
Adds loop field to Timeout struct, updates set() to store loop reference, updates clear() to retrieve and clear timer via stored loop, clears loop reference in callback after task resumption

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🔒 Mutexes guard the ticking clock,
Threads compete, but now they lock—
Timers batched in safety's fold,
One loop's threads won't leave timers cold. ⏰

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: adding mutex protection for timer heap operations on multi-threaded backends.
Description check ✅ Passed The description clearly relates to the changeset, outlining the is_multi_threaded capability, conditional timer_mutex, protected timer operations, and zero overhead on single-threaded backends.
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 timer-mutex-protection

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.

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

526-541: Potential deadlock when defer_callbacks=false on multi-threaded backends.

checkTimers holds timer_mutex (line 527-528) while calling markCompleted. When defer_callbacks is false (line 139-142), markCompleted invokes the callback immediately.

If the callback tries to set/clear a timer (e.g., rescheduling a periodic timer), it will attempt to acquire timer_mutex again → deadlock on single-threaded mutex.

The default defer_callbacks=true is safe because completions are queued and processed outside the lock. But the combination of is_multi_threaded=true + defer_callbacks=false is problematic.

Options:

  1. Document that defer_callbacks=false is incompatible with multi-threaded backends
  2. Move markCompleted calls outside the lock (collect fired timers, release lock, then mark them)
  3. Use a recursive mutex (not great, but would work)
Option 2: Mark completions outside lock
     fn checkTimers(self: *Loop) TimerCheckResult {
+        var fired_timers: [16]*Timer = undefined;
+        var fired_count: usize = 0;
+
         self.state.lockTimers();
-        defer self.state.unlockTimers();
         self.state.updateNow();
-        var fired = false;
         while (self.state.timers.peek()) |timer| {
             if (timer.deadline_ms > self.state.now_ms) {
-                return .{ .next_timeout_ms = timer.deadline_ms - self.state.now_ms, .fired = fired };
+                break;
             }
             timer.c.setResult(.timer, {});
             self.state.clearTimer(timer);
-            self.state.markCompleted(&timer.c);
-            fired = true;
+            if (fired_count < fired_timers.len) {
+                fired_timers[fired_count] = timer;
+                fired_count += 1;
+            }
         }
-        return .{ .next_timeout_ms = null, .fired = fired };
+        const next_timeout = if (self.state.timers.peek()) |t|
+            t.deadline_ms - self.state.now_ms
+        else
+            null;
+        self.state.unlockTimers();
+
+        for (fired_timers[0..fired_count]) |timer| {
+            self.state.markCompleted(&timer.c);
+        }
+        return .{ .next_timeout_ms = next_timeout, .fired = fired_count > 0 };
     }

Note: This sketch uses a fixed-size array. A more robust solution might use a dynamic list or loop until all fired timers are processed.

🧹 Nitpick comments (1)
src/ev/loop.zig (1)

175-193: Public methods without locking: potential footgun.

LoopState.setTimer and LoopState.clearTimer are pub but require the caller to hold timer_mutex. Direct calls without locking cause data races on multi-threaded backends.

Consider either:

  • Making these non-public (drop pub)
  • Adding a doc comment with the locking contract
  • Renaming to setTimerLocked / clearTimerLocked
Example: document the locking requirement
+    /// Internal: caller must hold timer_mutex on multi-threaded backends.
     pub fn setTimer(self: *LoopState, timer: *Timer) void {
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c4c9a9f and 610c63e.

📒 Files selected for processing (3)
  • src/ev/backends/iocp.zig
  • src/ev/completion.zig
  • src/ev/loop.zig
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2026-01-10T13:55:00.163Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/runtime/blocking_task.zig:117-146
Timestamp: 2026-01-10T13:55:00.163Z
Learning: In Zig files, do not reference libxev for async I/O. The project uses a custom event loop implementation under src/ev/ and a callback-based async I/O loop similar to libuv/libxev. Reviewers should ensure code relies on the src/ev event loop and that there are no libxev usage patterns; prefer the central event loop in src/ev/ for all asynchronous operations.

Applied to files:

  • src/ev/completion.zig
  • src/ev/loop.zig
  • src/ev/backends/iocp.zig
📚 Learning: 2026-01-10T14:08:37.019Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/stdio.zig:117-129
Timestamp: 2026-01-10T14:08:37.019Z
Learning: In Zig files implementing swap-like semantics (e.g., old = swap(new); defer swap(old)), ensure the return value is an opaque restoration token rather than a direct reflection of internal state. Rely on the contract to perform increment/decrement logic internally (e.g., shield_count) and not expose internal state through the token. This makes behavior predictable, supports refactoring, and avoids leaking internal state across calls. Apply this pattern broadly to Zig code that uses a paired-swap or restoration-token mechanism.

Applied to files:

  • src/ev/completion.zig
  • src/ev/loop.zig
  • src/ev/backends/iocp.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: test (windows-latest)
🔇 Additional comments (8)
src/ev/completion.zig (1)

24-26: Clean capability flag addition.

Default false means single-threaded backends compile out the mutex entirely. The doc comment is clear about the contract: when true, timer ops get mutex protection.

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

120-124: Correct: IOCP needs multi-threaded timer protection.

With SharedState allowing multiple loops to share an IOCP handle, completions can indeed land on a different loop's thread. Setting this flag activates the timer mutex.

src/ev/loop.zig (6)

109-110: Neat conditional compilation.

When is_multi_threaded is false, timer_mutex becomes void and the lock/unlock calls become no-ops. Zero runtime cost for single-threaded backends.


163-173: LGTM.

The if (Backend.capabilities.is_multi_threaded) check is comptime, so these are genuinely zero-cost when the capability is false.


282-288: Lock scope is correct.

The lock covers updateNow, delay update, and the heap operation. Clean.


350-358: Lock scope is good here.

Lock is held only for clearTimer, then released before markCompleted. This avoids the callback-under-lock issue present in checkTimers.


439-444: Timer locking in add() is correct.

Matches the pattern used in Loop.setTimer.


291-303: Potential race on active counter between cross-thread and loop-thread modifications.

clearTimer decrements active under timer_mutex, but finishCompletion (line 150) decrements it without any lock. If one thread calls clearTimer while the loop thread is in finishCompletion for any completion, you get concurrent modifications to active.

Also, line 263 reads active without holding a lock, so it could see torn or stale values if another thread is modifying it.

This matters only if cross-thread callers can interfere with loop-thread completion processing. If the design intentionally restricts cross-thread callers to timer operations only, and all other active modifications happen single-threaded on the loop thread, then the actual race window may be acceptable—but it's worth documenting explicitly.

Add is_multi_threaded capability to BackendCapabilities. When true
(currently only IOCP), timer heap operations are protected by a mutex
to allow safe cross-thread timer cancellation when completions may be
delivered on a different loop thread than where the timer was submitted.
When completions may be delivered on a different thread (e.g., IOCP),
Timeout.clear() needs access to the original loop to clear the timer.
Store the loop pointer in set() and use it in clear() instead of
deriving it from the current task.
Process fired timers in batches and call markCompleted outside the
timer_mutex lock. This prevents deadlock when defer_callbacks=false
and a timer callback tries to set/clear another timer.
@lalinsky
lalinsky force-pushed the timer-mutex-protection branch from a9dd438 to 18f82ba Compare January 11, 2026 05:23

@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 (2)
src/ev/loop.zig (2)

552-556: Potential null pointer dereference if ctx is null.

The signature makes ctx optional, but line 553 casts it directly without checking for null. Either add a null check or keep the parameter non-optional if it's never null in practice.

🔒 Proposed fix - add null check
 pub fn loopWorkComplete(ctx: ?*anyopaque, work: *Work) void {
-    const loop: *Loop = @ptrCast(@alignCast(ctx));
+    const loop: *Loop = @ptrCast(@alignCast(ctx.?));
     loop.state.work_completions.push(&work.c);
     loop.wake();
 }

Or if ctx is never null:

-pub fn loopWorkComplete(ctx: ?*anyopaque, work: *Work) void {
+pub fn loopWorkComplete(ctx: *anyopaque, work: *Work) void {
     const loop: *Loop = @ptrCast(@alignCast(ctx));
     loop.state.work_completions.push(&work.c);
     loop.wake();
 }

565-575: Potential null pointer dereference if ctx is null.

Same issue as loopWorkComplete - the optional ctx is dereferenced without a null check on line 566.

🔒 Proposed fix - add null check
 pub fn loopLinkedWorkComplete(ctx: ?*anyopaque, work: *Work) void {
-    const context: *LinkedWorkContext = @ptrCast(@alignCast(ctx));
+    const context: *LinkedWorkContext = @ptrCast(@alignCast(ctx.?));
     // Propagate cancel error from work to linked completion
     if (work.c.err) |err| {
         if (!context.linked.has_result) {
             context.linked.setError(err);
         }
     }
     context.loop.state.work_completions.push(context.linked);
     context.loop.wake();
 }

Or keep non-optional if ctx is never null:

-pub fn loopLinkedWorkComplete(ctx: ?*anyopaque, work: *Work) void {
+pub fn loopLinkedWorkComplete(ctx: *anyopaque, work: *Work) void {
     const context: *LinkedWorkContext = @ptrCast(@alignCast(ctx));
     ...
 }
🧹 Nitpick comments (1)
src/runtime/timeout.zig (1)

27-27: Consider removing unused parameter in future refactor.

The rt parameter is now ignored. While keeping it maintains API compatibility, it's misleading. Document this or plan to deprecate it.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a9dd438 and 18f82ba.

📒 Files selected for processing (4)
  • src/ev/backends/iocp.zig
  • src/ev/completion.zig
  • src/ev/loop.zig
  • src/runtime/timeout.zig
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/ev/completion.zig
  • src/ev/backends/iocp.zig
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2026-01-10T13:55:00.163Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/runtime/blocking_task.zig:117-146
Timestamp: 2026-01-10T13:55:00.163Z
Learning: In Zig files, do not reference libxev for async I/O. The project uses a custom event loop implementation under src/ev/ and a callback-based async I/O loop similar to libuv/libxev. Reviewers should ensure code relies on the src/ev event loop and that there are no libxev usage patterns; prefer the central event loop in src/ev/ for all asynchronous operations.

Applied to files:

  • src/runtime/timeout.zig
  • src/ev/loop.zig
📚 Learning: 2026-01-10T14:08:37.019Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/stdio.zig:117-129
Timestamp: 2026-01-10T14:08:37.019Z
Learning: In Zig files implementing swap-like semantics (e.g., old = swap(new); defer swap(old)), ensure the return value is an opaque restoration token rather than a direct reflection of internal state. Rely on the contract to perform increment/decrement logic internally (e.g., shield_count) and not expose internal state through the token. This makes behavior predictable, supports refactoring, and avoids leaking internal state across calls. Apply this pattern broadly to Zig code that uses a paired-swap or restoration-token mechanism.

Applied to files:

  • src/runtime/timeout.zig
  • src/ev/loop.zig
🔇 Additional comments (12)
src/runtime/timeout.zig (4)

22-22: LGTM - Storing loop reference enables cross-thread timer management.

The loop field allows clear() to work reliably across threads without needing the Runtime parameter, which aligns with the PR's goal of supporting multi-threaded timer operations.


44-44: LGTM - Loop reference stored at the right time.

Storing the loop reference before activating the timer ensures it's available for both clear() and the callback, supporting cross-thread cancellation.


76-78: LGTM - Proper cleanup of loop reference.

Clearing the loop field in the callback prevents dangling references and maintains symmetry with the clear() method.


26-34: The loop pointer is safe—there's no threading issue here.

Timeouts are always stack-allocated and cleaned up via defer clear() before the scope ends. The loop pointer points to an embedded field in the Executor struct, which is persistent for the lifetime of the Runtime. Task migration is explicitly disabled (see the TODO comment in src/runtime/task.zig:212), so timeouts cannot outlive their executor. The current design guarantees the pointer remains valid for the entire timeout lifetime.

Likely an incorrect or invalid review comment.

src/ev/loop.zig (8)

109-110: LGTM - Zero-overhead mutex on single-threaded backends.

The conditional compilation ensures the mutex only exists on multi-threaded backends (like IOCP), keeping single-threaded backends free of any synchronization overhead.


163-173: LGTM - Clean abstraction for conditional locking.

The helpers provide a clean interface and the compiler will optimize away the runtime checks on single-threaded backends.


283-288: LGTM - Proper locking around timer heap mutation.

Using defer ensures the lock is released even if an error occurs. The lock scope is appropriately tight.


291-303: LGTM - clearTimer protected with appropriate locking.

The lock guards the timer heap removal and state updates correctly.


336-343: LGTM - Cancel path correctly locks timer operations.

The lock scope is minimal, protecting only the timer heap modification. Error setting and completion marking happen outside the lock, avoiding unnecessary lock holding.


413-418: LGTM - Timer addition properly synchronized.

The lock protects the timer heap insertion, maintaining consistency with other timer operations.


500-536: LGTM - Batching prevents deadlock while maintaining correctness.

The rework processes expired timers in batches, acquiring the lock only for heap access and releasing it before calling completion callbacks. This prevents the deadlock scenario mentioned in the PR objectives where callbacks might try to set/clear timers.

The batch size of 4 is reasonable - small enough to avoid excessive lock holding, large enough to be efficient. The logic correctly handles all cases:

  • Multiple batches when many timers expire
  • Partial last batch
  • Setting next_timeout_ms when hitting the first non-expired timer

559-562: LGTM - LinkedWorkContext provides clear structure for file op completions.

The struct clearly encapsulates the data needed for linked work completions.

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