Repository navigation
Add mutex protection for timer heap on multi-threaded backends - #194
Conversation
📝 WalkthroughWalkthroughThe 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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ 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: 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 whendefer_callbacks=falseon multi-threaded backends.
checkTimersholdstimer_mutex(line 527-528) while callingmarkCompleted. Whendefer_callbacksis false (line 139-142),markCompletedinvokes the callback immediately.If the callback tries to set/clear a timer (e.g., rescheduling a periodic timer), it will attempt to acquire
timer_mutexagain → deadlock on single-threaded mutex.The default
defer_callbacks=trueis safe because completions are queued and processed outside the lock. But the combination ofis_multi_threaded=true+defer_callbacks=falseis problematic.Options:
- Document that
defer_callbacks=falseis incompatible with multi-threaded backends- Move
markCompletedcalls outside the lock (collect fired timers, release lock, then mark them)- 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.setTimerandLoopState.clearTimerarepubbut require the caller to holdtimer_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/clearTimerLockedExample: 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
📒 Files selected for processing (3)
src/ev/backends/iocp.zigsrc/ev/completion.zigsrc/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.zigsrc/ev/loop.zigsrc/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.zigsrc/ev/loop.zigsrc/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
falsemeans 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
SharedStateallowing 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_threadedis false,timer_mutexbecomesvoidand 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 beforemarkCompleted. This avoids the callback-under-lock issue present incheckTimers.
439-444: Timer locking in add() is correct.Matches the pattern used in
Loop.setTimer.
291-303: Potential race onactivecounter between cross-thread and loop-thread modifications.
clearTimerdecrementsactiveundertimer_mutex, butfinishCompletion(line 150) decrements it without any lock. If one thread callsclearTimerwhile the loop thread is infinishCompletionfor any completion, you get concurrent modifications toactive.Also, line 263 reads
activewithout 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
activemodifications 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.
a9dd438 to
18f82ba
Compare
There was a problem hiding this comment.
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
ctxoptional, 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 optionalctxis 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
rtparameter 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
📒 Files selected for processing (4)
src/ev/backends/iocp.zigsrc/ev/completion.zigsrc/ev/loop.zigsrc/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.zigsrc/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.zigsrc/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 insrc/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_mswhen 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.
Summary
is_multi_threadedcapability toBackendCapabilities(IOCP sets it totrue)timer_mutextoLoopStatewithlockTimers()/unlockTimers()helpersLoop.setTimer,Loop.clearTimer,Loop.checkTimers,Loop.add, andLoop.cancelInternalThis 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.