Repository navigation
Refactor timedWait to use callback-based timeout handling - #23
Conversation
Replace custom timer management in Condition.timedWait() and ResetEvent.timedWait() with new Runtime.timedWaitForReadyWithCallback(). The callback pattern allows timeout handlers to decide whether to wake the coroutine by attempting to remove from the wait queue. This prevents race conditions where both signal() and timeout could call markReady(). Changes: - Add Runtime.timedWaitForReadyWithCallback() with custom timeout handler - Refactor Runtime.timedWaitForReady() to use callback version internally - Simplify Condition.timedWait(): 107 lines → 33 lines (~70% reduction) - Simplify ResetEvent.timedWait(): 114 lines → 42 lines (~63% reduction) - Simplify Runtime.sleep(): 19 lines → 4 lines (~80% reduction) - Check completion.flags.state to avoid canceling completed timers Total: ~200 lines of code removed
|
Warning Rate limit exceeded@lalinsky has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 6 minutes and 22 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (1)
WalkthroughIntroduces a callback-based timed-wait API with per-task timer state and generation-based invalidation: adds timedWaitForReadyWithCallback and CallbackContext, moves per-call timer logic into per-task timers with generation checks, refactors sleep to use timed wait, and updates Condition/ResetEvent/Mutex timed waits to use onTimeout semantics. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Caller
participant Sync as Condition/ResetEvent
participant RT as Runtime
participant Timer
participant CB as onTimeout(ctx)
participant Co as Coroutine
Caller->>Sync: timedWait(..., timeout_ns)
Sync->>RT: timedWaitForReadyWithCallback(timeout_ns, TimeoutContext, onTimeout)
RT->>Timer: timer.reset(CallbackContext + generation)
Note over Timer,RT: Timer runs asynchronously with generation tag
alt signaled before timeout
Sync->>Co: dequeue & signal
RT->>Timer: timer.cancel(noopTimerCancelCallback) [guard if dead]
RT-->>Sync: return success
else timeout fires (matching generation)
Timer-->>RT: invoke callback(CallbackContext)
RT->>CB: onTimeout(TimeoutContext)
alt onTimeout returns true (removed -> timed out)
RT->>Co: wake with Timeout
RT-->>Sync: return Timeout
else onTimeout returns false (already signaled)
RT-->>Sync: return success
end
else timeout fires (stale generation)
RT-->>Timer: ignore (generation mismatch)
end
sequenceDiagram
autonumber
participant Sync as Condition.timedWait
participant MQ as WaitQueue
participant RT as Runtime
participant CB as onTimeout(ctx)
Sync->>MQ: enqueue(awaitable)
Sync->>RT: timedWaitForReadyWithCallback(...)
CB->>MQ: tryRemove(awaitable)
alt removed
CB-->>RT: true (timeout -> wake)
else not present
CB-->>RT: false (already signaled)
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
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 |
Store timer completions on AnyTask and use loop.timer_reset() to avoid blocking on timer cancellation. This eliminates an extra suspend/resume cycle when a coroutine is woken by external markReady() before the timer fires. Changes: - Add timer_c and timer_cancel_c fields to AnyTask for reusable completions - Add noopTimerCancelCallback for async cancellation without blocking - Use loop.timer_reset() instead of creating new Timer objects - Cancel timers asynchronously without waiting for completion This builds on the callback-based timeout discrimination to further reduce timer management overhead.
Check if timer has already completed (state == .dead) before attempting to cancel it. This avoids unnecessary cancellation when the timer fires at the same time as external wakeup.
Replace direct loop.timer_reset() and loop.cancel() calls with xev.Timer methods for cross-platform compatibility. The loop.cancel() method only exists on io_uring backend, causing compilation failures on macOS/kqueue. The xev.Timer wrapper provides reset() and cancel() methods that work across all backends by abstracting the platform-specific cancellation mechanisms.
Add timer_generation field to AnyTask to prevent stale timer callbacks from accessing deallocated stack memory. When a timer is cancelled asynchronously, the callback may still fire on kqueue before cancellation completes. Without generation tracking, consecutive timedWait calls could have the old callback access freed stack variables. The generation counter increments on each timedWait call and is checked in the timer callback. Mismatched generations indicate a stale callback that should be ignored, preventing segfaults from use-after-free. This fixes crashes in Semaphore and other sync primitives on macOS/kqueue.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/runtime.zig (1)
705-799: Timer deinit is safe; document onTimeout semantics
xev.Timer.deinit()is a no-op for the static API (TimerLoop), so deferring deinit after an async cancel has no impact on underlying resources.- Add a note in the API docs spelling out the required invariants and expected behavior of the
onTimeoutcallback.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/runtime.zig(5 hunks)
🔇 Additional comments (4)
src/runtime.zig (4)
69-81: LGTM: Clean noop callback implementation.The noop callback correctly ignores all parameters and returns
.disarm, which is appropriate for asynchronous timer cancellation where no further action is needed.
144-146: LGTM: Per-task timer state enables race-free timeout handling.The addition of
timer_c,timer_cancel_c, andtimer_generationfields provides the foundation for generation-based callback invalidation, preventing stale timers from waking the wrong coroutine after a task is reused.
569-572: LGTM: Elegant simplification with correct timeout semantics.The refactored
sleep()correctly treatserror.Timeoutas the expected code path (catching and returning normally), while marking non-timeout wakeups as unreachable since external signals should never wake a sleeping coroutine. This 80% code reduction maintains correct behavior.
801-814: LGTM: Clean wrapper maintaining backward compatibility.The wrapper correctly delegates to
timedWaitForReadyWithCallbackwith a dummy context and anonTimeoutthat always returnstrue, preserving the original simple timeout semantics while enabling the more powerful callback-based API for internal use.
Replace simple generation counter with tagged pointer approach that stores the 2-bit generation in the lower bits of the userdata pointer itself. The previous fix incremented a generation counter but still dereferenced the userdata pointer (pointing to freed stack memory) before checking the generation. This could crash before the check. New approach: - Pack context pointer + 2-bit generation into userdata using lower bits - In callback: get AnyTask from completion without dereferencing userdata - Extract generation from tag bits (no pointer deref!) - Only dereference context pointer if generation matches This ensures we never touch freed stack memory when a stale timer callback fires after async cancellation completes on kqueue/macOS. Changes: - Add runtime pointer to AnyTask for access in timer callbacks - Remove redundant runtime field from Task struct - Add packTimerUserdata/unpackTimerUserdata helpers for tagged pointers - Change timer_generation from u64 to u2 (only need 0-3) - Pass anyopaque with tagged pointer instead of typed context - Get task via @fieldParentPtr instead of from context - Reduce CallbackContext from 4 fields to 2 (removed runtime, coroutine)
Store timed_out directly as bool in CallbackContext instead of as a pointer to a separate local variable. After waitForReady() returns, check ctx.timed_out directly. This eliminates one level of indirection with no functional change.
Move generation increment from timer start to timer cancellation. This ensures stale callbacks from cancelled timers see a generation mismatch and don't access freed stack memory. Flow: - Start timer with current generation X in tagged userdata - If timeout fires: generation matches (X == X), callback runs normally - If signaled early: increment generation to X+1, cancel timer - If stale callback fires: generation mismatch (X != X+1), ignored safely This fixes the remaining use-after-free crashes on macOS/kqueue where async timer cancellation allowed callbacks to fire after the function returned and stack was freed.
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/runtime.zig (1)
724-819: LGTM: Well-designed callback-based timeout handling with generation invalidation.The implementation correctly:
- Uses generation-based invalidation to prevent stale timer callbacks
- Checks timer state before cancellation to optimize cancel operations
- Employs single-threaded event loop semantics to ensure memory safety of stack-allocated context
Documentation needed: The
onTimeoutcallback contract should be documented more explicitly. Specifically, clarify that:
- The callback should return
trueif it successfully removed the coroutine from a wait queue (real timeout → wake witherror.Timeout)- The callback should return
falseif the coroutine was already removed by another source (ignore timeout)This contract is critical for correct timeout discrimination in primitives like
Condition.timedWaitand is mentioned in the PR description but not in code comments.Consider adding a doc comment:
+ /// Wait for the current coroutine to be marked ready, with a timeout and custom timeout handler. + /// + /// The onTimeout callback is invoked when the timer expires. It should: + /// - Return true if the coroutine was successfully removed from a wait queue (timeout applies) + /// - Return false if the coroutine was already signaled by another source (ignore timeout) + /// + /// This pattern prevents both the timeout and signal from waking the same coroutine. pub fn timedWaitForReadyWithCallback(
🧹 Nitpick comments (1)
src/runtime.zig (1)
705-722: LGTM: Clever pointer tagging for generation validation.The pack/unpack functions correctly use lower 2 bits for generation, relying on pointer alignment (≥4 bytes). This is guaranteed by Zig's allocator but worth documenting.
Optional improvement: Add a comment noting the alignment assumption:
/// Pack a pointer and 2-bit generation into a tagged pointer for userdata. /// Assumes pointer alignment >= 4 bytes (lower 2 bits available). inline fn packTimerUserdata(...) { ... }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/runtime.zig(8 hunks)
🔇 Additional comments (5)
src/runtime.zig (5)
69-81: LGTM: Clean noop callback for async timer cancellation.The implementation correctly ignores all parameters and errors, returning
.disarmas expected for one-shot timer cancellation.
144-147: LGTM: Per-task timer state enables efficient timer reuse.The addition of per-task timer fields (
timer_c,timer_cancel_c,timer_generation) is a good design choice that eliminates per-call allocations.Note on generation size:
timer_generation: u2wraps every 4 calls. While this should be sufficient (cancelled timers complete quickly), consideru8if you observe edge cases where late-firing timers coincide with generation wraparound.
188-188: LGTM: Consistent routing through any_task.runtime.The refactoring to access runtime via
self.any_task.runtimeis consistent and enables timer callbacks to reach runtime through the task pointer.Also applies to: 198-198, 530-530
569-571: LGTM: Elegant simplification of sleep() using timed wait.The refactoring correctly delegates to
timedWaitForReadywith proper ms→ns conversion, and theunreachableis correct since sleep should always complete via timeout (any other wake path would be a bug).
821-834: LGTM: Clean wrapper for unconditional timeout semantics.The wrapper correctly uses a dummy context with an
onTimeoutthat always returnstrue, appropriate for cases likesleep()where timeouts are unconditional.
* Add basic file operations * Add proper private internal fields to recv/send completion types Instead of storing msghdr data in a shared Completion.internal field, each recv/send completion type now has its own backend-specific internal field following the same pattern as FileOpen. Changes: - Add internal field to NetRecv, NetSend, NetRecvFrom, NetSendTo - Create NetRecvData, NetSendData, NetRecvFromData, NetSendToData in io_uring backend - Remove shared CompletionData from Completion struct - Update io_uring to use per-completion internal fields for msghdr storage * Missing files * Implement generic file operations support via thread pool Add capability-based routing for file operations on backends without native support (epoll, kqueue, poll). When Backend.supports_file_ops is false, file operations are routed to a thread pool using internal Work completions. Key changes: - Add Work.linked field to connect internal Work to parent file operation - Thread pool pushes linked completion directly to completion queue - Add POSIX implementations in file_ops.zig and os/fs.zig - Handle file operation cancellations by canceling internal Work - Assert user Work completions never have linked field set * Fix FreeBSD compilation errors - Use fs.mode_t in FileOpen.init() parameter instead of u32 - Cast buffers.len to c_uint in preadv/pwritev for FreeBSD * Implement Windows file operations Add Windows implementations for file operations using Win32 API: - CreateFileW for opening files with allocator-based UTF-16 conversion - CloseHandle for closing files - ReadFile/WriteFile with OVERLAPPED for positional I/O All file operation tests now run and pass on Windows. * Remove duplicate platform-specific branches in file_ops Since fs.zig now handles platform differences internally, we don't need separate Windows and POSIX branches in file_ops.zig work functions * Move file operation handlers to backends/common.zig Consolidate file operation work functions with network handlers: - Add handleFileOpen, handleFileClose, handleFileRead, handleFileWrite - Work functions (fileOpenWork, etc.) now call these handlers - Remove src/file_ops.zig as functionality is now in common.zig - Consistent structure with network operation handlers * Clean up file errors * Fixes
Summary
This PR refactors timer management in synchronization primitives to use a centralized callback-based approach, eliminating code duplication and preventing race conditions.
Changes
Runtime.timedWaitForReadyWithCallback(): New generic function that accepts a custom timeout handler callbackRuntime.timedWaitForReady(): Now uses the callback version internallyCondition.timedWait(): 107 lines → 33 lines (~70% reduction)ResetEvent.timedWait(): 114 lines → 42 lines (~63% reduction)Runtime.sleep(): 19 lines → 4 lines (~80% reduction)Key Improvements
Callback-based timeout discrimination
The new approach uses a callback pattern where the timeout handler decides whether to wake the coroutine:
trueif successfully removed from wait queue → real timeout, wake witherror.Timeoutfalseif already removed by signal → ignore timeout, don't wakeThis prevents race conditions where both
signal()and the timer could callmarkReady()on the same coroutine.Smart timer cancellation
Checks
completion.flags.state == .deadto avoid canceling already-completed timers, preventing unnecessary timer cancel operations and additional waitForReady cycles.Testing
All 54 tests pass including:
Condition timedWait timeoutSemaphore: timedWait timeout/successResetEvent timedWait timeout./check.shSummary by CodeRabbit
New Features
Refactor
Bug Fixes