Skip to content

Refactor timedWait to use callback-based timeout handling - #23

Merged
lalinsky merged 8 commits into
mainfrom
refactor-timed-wait-with-callback
Oct 5, 2025
Merged

lalinsky merged 8 commits into
mainfrom
refactor-timed-wait-with-callback

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 5, 2025 •

Copy link
Copy Markdown
Owner

Summary

This PR refactors timer management in synchronization primitives to use a centralized callback-based approach, eliminating code duplication and preventing race conditions.

Changes

  • Add Runtime.timedWaitForReadyWithCallback(): New generic function that accepts a custom timeout handler callback
  • Refactor Runtime.timedWaitForReady(): Now uses the 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)
  • Total code reduction: ~200 lines removed

Key Improvements

Callback-based timeout discrimination

The new approach uses a callback pattern where the timeout handler decides whether to wake the coroutine:

  • Returns true if successfully removed from wait queue → real timeout, wake with error.Timeout
  • Returns false if already removed by signal → ignore timeout, don't wake

This prevents race conditions where both signal() and the timer could call markReady() on the same coroutine.

Smart timer cancellation

Checks completion.flags.state == .dead to avoid canceling already-completed timers, preventing unnecessary timer cancel operations and additional waitForReady cycles.

Testing

All 54 tests pass including:

  • Condition timedWait timeout
  • Semaphore: timedWait timeout/success
  • ResetEvent timedWait timeout
  • Full test suite via ./check.sh

Summary by CodeRabbit

  • New Features

    • Added a flexible timed-wait API that accepts a user callback for timeout decisions, plus a simpler wrapper for standard timed waits.
    • Exposes per-task timer state to support the new API.
  • Refactor

    • Unified timeout handling across mutex/condition/reset-event waits with a callback-based flow.
    • Simplified sleep and waiting logic to delegate to the new timed-wait mechanism.
  • Bug Fixes

    • Generation-based invalidation to prevent late timer wakeups.
    • Reduces unnecessary timer cancellation; ensures atomic release/reacquire around waits.

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

coderabbitai Bot commented Oct 5, 2025 •

Copy link
Copy Markdown
Contributor

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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.

📥 Commits

Reviewing files that changed from the base of the PR and between 89ab5e2 and 291680a.

📒 Files selected for processing (1)
  • src/runtime.zig (8 hunks)

Walkthrough

Introduces 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

Cohort / File(s) Summary
Runtime timed-wait API & per-task timers
src/runtime.zig
Adds timedWaitForReadyWithCallback (comptime TimeoutContext + onTimeout) and wrapper timedWaitForReady; introduces CallbackContext; adds per-task fields timer_c, timer_cancel_c, timer_generation; replaces TimedWaitContext; implements timer.reset with a generation-tagged userdata and callback that validates generation, invokes onTimeout, and makes coroutine ready; uses timer.cancel with noopTimerCancelCallback; updates Task/AnyTask wiring and sleep to use timed wait.
Sync primitives timed-wait refactor
src/sync.zig
Replaces per-call timer init/cancel and TimedWaitContext usage in Condition.timedWait, ResetEvent.timedWait, and Mutex wait paths with timedWaitForReadyWithCallback; introduces a TimeoutContext holding the wait_queue and awaitable and an onTimeout that attempts to remove the awaitable to determine timeout; adjusts lock/unlock sequencing and removes explicit cancel callbacks/completions.

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
Loading
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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

I am a rabbit, tail a ticking spot,
I plant a generation, guard the spot.
If time outsprings I softly shout,
If wake arrives — I scroll it out.
Hop, callback, cancel — all in one plot. 🐇⏳

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title accurately and concisely describes the main change of the pull request, which is refactoring the timedWait function to use a callback-based approach for timeout handling, matching the core intent of the changeset.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

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.

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.

@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

🧹 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 onTimeout callback.
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f29be46 and 7f4a597.

📒 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, and timer_generation fields 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 treats error.Timeout as 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 timedWaitForReadyWithCallback with a dummy context and an onTimeout that always returns true, 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.

@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/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 onTimeout callback contract should be documented more explicitly. Specifically, clarify that:

  • The callback should return true if it successfully removed the coroutine from a wait queue (real timeout → wake with error.Timeout)
  • The callback should return false if the coroutine was already removed by another source (ignore timeout)

This contract is critical for correct timeout discrimination in primitives like Condition.timedWait and 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7f4a597 and 89ab5e2.

📒 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 .disarm as 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: u2 wraps every 4 calls. While this should be sufficient (cancelled timers complete quickly), consider u8 if 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.runtime is 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 timedWaitForReady with proper ms→ns conversion, and the unreachable is 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 onTimeout that always returns true, appropriate for cases like sleep() where timeouts are unconditional.

@lalinsky
lalinsky merged commit 2bc1458 into main Oct 5, 2025
@lalinsky
lalinsky deleted the refactor-timed-wait-with-callback branch October 5, 2025 16:04
lalinsky added a commit that referenced this pull request Jan 6, 2026
* 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
@coderabbitai coderabbitai Bot mentioned this pull request Jan 14, 2026
2 tasks done
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