Skip to content

Add Semaphore synchronization primitive - #22

Merged
lalinsky merged 4 commits into
mainfrom
add-semaphore
Oct 5, 2025
Merged

lalinsky merged 4 commits into
mainfrom
add-semaphore

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 4, 2025 •

Copy link
Copy Markdown
Owner

Summary

  • Implements Semaphore in src/sync.zig matching the std.Thread.Semaphore API
  • Provides wait(), timedWait(), and post() methods for coroutine-safe resource counting
  • Exported from zio module

Implementation

  • Built on top of Mutex and Condition primitives
  • Default permits: 0 (customizable via struct initialization)
  • Includes 4 comprehensive tests covering basic operations, timeouts, and multiple permits

Test plan

  • ./check.sh --test-filter "Semaphore" passes
  • All tests pass (basic wait/post, timedWait timeout/success, multiple permits)

Summary by CodeRabbit

  • New Features
    • Added a coroutine-safe counting semaphore (blocking wait, timed wait with timeout, permit release) and exposed it in the public API.
    • Added a runtime timed wait-for-ready operation that waits with a timeout and returns on timeout or readiness.
  • Bug Fixes
    • Improved timed-wait cancellation behavior for condition and reset events to ensure proper cleanup and wake-up flow.
  • Tests
    • Added comprehensive tests for wait/post flows, timeouts, successful timed waits, and multiple-permit scenarios.

Implements a coroutine-safe counting semaphore matching the
std.Thread.Semaphore API. Supports wait(), timedWait(), and post()
operations for coordinating access to limited resources across
coroutines.
@coderabbitai

coderabbitai Bot commented Oct 4, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds a coroutine-safe counting Semaphore (wait, timedWait, post) in src/sync.zig, re-exports it from src/zio.zig, updates Condition.timedWait and ResetEvent.timedWait to cancel timers and wait for cancellation when signaled, adds Runtime.timedWaitForReady(timeout_ns) to wait for readiness with timeout, and includes semaphore tests.

Changes

Cohort / File(s) Summary
Semaphore implementation & tests
src/sync.zig
Adds pub const Semaphore (fields: mutex, cond, permits) with wait(rt), timedWait(rt, timeout_ns) error{Timeout}!void, and post(rt). Adds tests covering basic wait/post, timed-wait timeout, timed-wait success, and multi-permit behavior.
Condition & ResetEvent timedWait cancellation
src/sync.zig
Updates Condition.timedWait and ResetEvent.timedWait to cancel the active timer and wait for cancellation when signaled (non-timeout path), ensuring proper timer cleanup and wake sequencing.
Runtime timed wait for readiness
src/runtime.zig
Adds pub fn timedWaitForReady(self: *Runtime, timeout_ns: u64) error{Timeout}!void which schedules a timer to mark the current coroutine ready on timeout, waits for readiness, cancels the timer if awakened, and waits for cancellation completion.
Public API re-export
src/zio.zig
Re-exports Semaphore via pub const Semaphore = @import("sync.zig").Semaphore; other exports unchanged.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Coroutine
  participant S as Semaphore
  participant M as Mutex
  participant V as Condition
  participant R as Runtime/Timer

  rect rgb(250,250,255)
  Note over C,S: wait(rt)
  C->>S: wait(rt)
  S->>M: lock()
  alt permits == 0
    S->>V: wait(rt) (block)
    V-->>S: awakened (post)
  end
  S->>S: decrement permits
  S->>M: unlock()
  C-->>C: resume
  end

  rect rgb(245,255,245)
  Note over C,S: timedWait(rt, timeout_ns)
  C->>S: timedWait(rt, ns)
  S->>M: lock()
  alt permits == 0
    S->>R: start timer -> on timeout: markReady(current)
    S->>V: timed wait(rt, ns)
    alt timeout
      V-->>R: timeout fires -> coroutine resumed with error.Timeout
      S->>M: unlock()
    else awakened
      V->>R: cancel timer, wait-for-cancel
      S->>S: decrement permits
      S->>M: unlock()
    end
  else permits > 0
    S->>S: decrement permits
    S->>M: unlock()
  end
  end

  rect rgb(255,245,245)
  Note over C,S: post(rt)
  C->>S: post(rt)
  S->>M: lock()
  S->>S: increment permits
  S->>V: signal one waiter
  S->>M: unlock()
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

I count the permits, paw tapping slow,
Timers tidy, wake-ups in a row,
I post, I wait, I time the run,
Locks unzip gently — work done, then fun. 🐇

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 "Add Semaphore synchronization primitive" concisely and accurately summarizes the main change by indicating the addition of a new semaphore synchronization primitive, aligning perfectly with the PR’s contents and providing clear context for reviewers.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch add-semaphore

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.

@lalinsky

lalinsky commented Oct 4, 2025

Copy link
Copy Markdown
Owner Author

@claude for some reason, the code is crashing on macos, see if you can find a possible reason

@claude

claude Bot commented Oct 4, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


macOS Crash Analysis - Found the Issue! ✓

I've identified the root cause of the macOS crash in the Semaphore implementation.

Issue Details

Crash Location: test "Semaphore: timedWait success" - Bus error at address 0x104fe98bc

Stack Trace: The crash occurs in libxev's heap implementation when managing timers:

/Users/runner/work/zio/zio/vendor/libxev/src/heap.zig:111:32: in meld
/Users/runner/work/zio/zio/vendor/libxev/src/heap.zig:152:34: in combine_siblings
/Users/runner/work/zio/zio/vendor/libxev/src/heap.zig:51:38: in deleteMin
/Users/runner/work/zio/zio/vendor/libxev/src/backend/kqueue.zig:382:45: in tick

Root Cause

The problem is in Semaphore.timedWait() at src/sync.zig:1156. The timer and completion are stack-allocated local variables that go out of scope when the coroutine suspends:

pub fn timedWait(self: *Semaphore, rt: *Runtime, timeout_ns: u64) error{Timeout}!void {
    var timeout_timer = std.time.Timer.start() catch unreachable;  // Line 1144
    
    self.mutex.lock(rt);
    defer self.mutex.unlock(rt);
    
    while (self.permits == 0) {
        const elapsed = timeout_timer.read();
        if (elapsed > timeout_ns) {
            return error.Timeout;
        }
        
        const local_timeout_ns = timeout_ns - elapsed;
        try self.cond.timedWait(rt, &self.mutex, local_timeout_ns);  // Line 1156
    }
    // ... rest of code
}

When self.cond.timedWait() is called, it:

  1. Creates a var timer = xev.Timer.init() and var completion: xev.Completion on the stack (lines 87-106 in Condition.timedWait)
  2. Registers these with the event loop via timer.run()
  3. Unlocks the mutex and suspends the coroutine (line 136)
  4. Stack variables become invalid when the coroutine suspends!
  5. The event loop later tries to access the now-invalid timer/completion → bus error

This is a use-after-free bug. The same issue exists in Condition.timedWait() and ResetEvent.timedWait().

Why It's macOS-Specific

The crash is macOS-specific due to:

  • kqueue backend timing: macOS uses kqueue for event handling, which may process timer events at different times than Linux's epoll
  • Memory layout differences: Stack memory might be overwritten/reused differently on macOS, making the corruption more likely to cause a bus error
  • Test timing: The "timedWait success" test has a waiter that successfully acquires a permit (no timeout), meaning the timer callback races with the signal callback

Solution

The timer and completion structs must outlive the coroutine suspension. Options:

  1. Move timer/completion to heap (allocate them)
  2. Store them in the waiting task struct (if there's space)
  3. Redesign to use a different timeout mechanism that doesn't require per-wait timers

The same fix needs to be applied to:

  • Condition.timedWait() (src/sync.zig:87-88)
  • ResetEvent.timedWait() (src/sync.zig:261-262)

Recommendation

I recommend looking at how other sync primitives handle this, or checking if libxev provides a pattern for this. The timer and completion need to be allocated in a way that survives coroutine suspension.

Would you like me to implement a fix for this issue?


Job run • Branch: add-semaphore

@lalinsky

lalinsky commented Oct 4, 2025

Copy link
Copy Markdown
Owner Author

@claude the watcher/completion should survive suspend just fine, the coroutine stack exists for as long as the coroutine is alive. Maybe the problem is that we are not cancelling the timer?

@claude

claude Bot commented Oct 4, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


Analysis Complete - Found the Root Cause ✓

You're absolutely right that coroutine stacks survive suspension. After thorough analysis, here's what's actually happening:

The Root Cause

The bug is in Condition.timedWait(), ResetEvent.timedWait(), and Semaphore.timedWait(). When a coroutine wakes via signal() before the timer expires:

The Problem:

  1. Timer is armed via timer.run() and registered in libxev's event loop
  2. Coroutine suspends at current.waitForReady()
  3. signal() wakes the coroutine (before timer fires)
  4. Function returns successfully - stack frame is unwound
  5. defer timer.deinit() executes - but it's a no-op (does nothing)
  6. Timer remains armed in libxev's kqueue heap, with pointers to completion and timeout_ctx
  7. Those local variables are now out of scope (function returned)
  8. Event loop continues, timer fires → accesses invalid stack memory → bus error

Key Insight

While the coroutine stack survives suspension, the function's local variables (timer, completion, timeout_ctx, timed_out) go out of scope when the function returns. If the timer fires after the function has returned, it accesses freed stack memory.

From timer.zig:24-27:

pub fn deinit(self: *const Self) void {
    // Nothing for now.
    _ = self;
}

The Fix Needed

The timer must be explicitly cancelled when waking via signal (non-timeout path). This requires using timer.cancel(), which is asynchronous and needs:

  • A separate cancellation completion
  • Waiting for cancellation to complete before returning

This would add complexity. Do you have a preferred approach for handling this, or should I look for similar patterns elsewhere in the codebase?


Job run • Branch: add-semaphore

@lalinsky

lalinsky commented Oct 4, 2025

Copy link
Copy Markdown
Owner Author

@claude implement it by cancelling the timer and waiting for the cancellation to complete

@claude

claude Bot commented Oct 4, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


Timer Cancellation Fix Complete ✓

Successfully implemented timer cancellation to fix the macOS crash when timedWait succeeds early via signal.

What Was Fixed

The bug occurred when timedWait() returned successfully (via signal/set) before the timer expired. The timer remained armed in libxev's event loop with pointers to stack-allocated variables (completion, timeout_ctx) that went out of scope when the function returned. When the timer later fired, it accessed invalid memory → bus error on macOS.

Changes Made

Condition.timedWait() (src/sync.zig:146-178)

  • Added explicit timer cancellation on non-timeout path
  • Uses timer.cancel() with separate cancellation completion
  • Waits for cancellation to complete via runtime.loop.run(.no_wait) loop

ResetEvent.timedWait() (src/sync.zig:350-380)

  • Applied same timer cancellation pattern
  • Ensures timer cleanup before returning

Semaphore.timedWait()

  • No changes needed - delegates to Condition.timedWait() which now handles cancellation

Test Results

✅ All Semaphore tests pass (4/4)
✅ Full test suite passes (54/54 tests)

Tasks Completed

  • Read current timedWait implementations in src/sync.zig
  • Check libxev timer API for cancellation methods
  • Implement timer cancellation in Condition.timedWait()
  • Implement timer cancellation in ResetEvent.timedWait()
  • Semaphore.timedWait() uses Condition.timedWait() - no changes needed
  • Test with Semaphore tests
  • Run full test suite
  • Commit and push changes

Job run • Branch: add-semaphore

When timedWait succeeds early (via signal/set), the timer must be
explicitly cancelled to prevent the event loop from accessing freed
stack memory when the timer fires later.

Added timer.cancel() calls with proper cancellation completion handling
in both Condition.timedWait() and ResetEvent.timedWait().

Semaphore.timedWait() is automatically fixed as it delegates to
Condition.timedWait().

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Lukáš Lalinský <[email protected]>

@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/sync.zig (1)

145-179: Consider extracting timer cancellation logic to reduce duplication.

The timer cancellation pattern (lines 146-171) is duplicated in ResetEvent.timedWait (lines 349-375). Consider extracting this into a helper function to improve maintainability.

Additionally, the busy-wait pattern (lines 175-177) using runtime.loop.run(.no_wait) in a tight loop could consume unnecessary CPU cycles. While the wait is expected to be brief, a small sleep or a more event-driven approach might be more efficient.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 551a2a2 and 8bd5c52.

📒 Files selected for processing (1)
  • src/sync.zig (3 hunks)
🔇 Additional comments (3)
src/sync.zig (3)

1193-1205: LGTM: Well-designed wait implementation.

The signal optimization (lines 1202-1204) that wakes the next waiter when permits > 0 after decrement is essential for correctness. Without it, multiple waiters could remain blocked even when permits are available. This matches the behavior of std.Thread.Semaphore and ensures fair resource distribution.


1209-1229: LGTM: Correct timedWait implementation.

The approach of using std.time.Timer to track elapsed time and adjusting the timeout for each cond.timedWait call is sound. While minor timing inaccuracies could theoretically accumulate across multiple wait/wakeup cycles, this is acceptable for typical semaphore use cases and matches the expected behavior.

The immediate error propagation on line 1222 is correct because the condition variable's wait_queue.remove() operation serves as a race resolver between signal() and the timeout callback.


1241-1352: LGTM: Good test coverage for Semaphore.

The four tests effectively cover the key scenarios:

  1. Basic mutual exclusion with multiple waiters (lines 1241-1268)
  2. Timeout behavior when no permits available (lines 1270-1293)
  3. Successful acquisition within timeout window (lines 1295-1325)
  4. Multiple-permit behavior (lines 1327-1352)

This provides solid confidence in the core functionality of the Semaphore implementation.

@lalinsky

lalinsky commented Oct 4, 2025

Copy link
Copy Markdown
Owner Author

@claude you should not call loop, but rather waitForReady

@claude

claude Bot commented Oct 4, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


Timer Cancellation Fix Complete ✓

Successfully replaced the busy-wait loop with proper coroutine suspension using waitForReady().

Changes Made

Condition.timedWait() (src/sync.zig:146-185)

  • Replaced while (!cancel_done) { runtime.loop.run(.no_wait); } busy-wait with waitForReady()
  • Updated cancellation callback to use CancelContext with runtime and coroutine
  • Callback now calls runtime.markReady(coroutine) to wake the suspended coroutine

ResetEvent.timedWait() (src/sync.zig:357-394)

  • Applied same pattern: replaced busy-wait with waitForReady()
  • Uses CancelContext to properly wake the coroutine after cancellation completes

Test Results

✅ All Semaphore tests pass (5/5 tests)

  • Basic wait/post
  • timedWait timeout
  • timedWait success
  • Multiple permits

Tasks Completed

  • Read current implementation in src/sync.zig
  • Replace busy-wait loop in Condition.timedWait() with waitForReady
  • Replace busy-wait loop in ResetEvent.timedWait() with waitForReady
  • Run Semaphore tests to verify fix
  • Commit and push changes

Job run • Branch: add-semaphore

Replace runtime.loop.run(.no_wait) busy-wait with proper coroutine suspension
using waitForReady() in Condition.timedWait() and ResetEvent.timedWait().

Co-authored-by: Lukáš Lalinský <[email protected]>
@lalinsky

lalinsky commented Oct 4, 2025

Copy link
Copy Markdown
Owner Author

@claude consider if it would make sense to add rt.timedWaitForReady(timeout_ns) and if so, what would it look like. Don't change code yet, just analyze and design.

@claude

claude Bot commented Oct 4, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


Analyzing rt.timedWaitForReady() Design

  • Read Runtime implementation to understand waitForReady/markReady
  • Analyze current timer cancellation patterns in sync.zig
  • Design timedWaitForReady API and semantics
  • Identify use cases and potential simplifications
  • Document pros/cons and recommendations

Analysis Complete

Current Pattern

The current waitForReady() / markReady() mechanism:

  • waitForReady() (coroutines.zig:365-368): Sets coroutine state to .waiting and yields
  • markReady() (runtime.zig:683-688): Validates state is .waiting, changes to .ready, and appends to ready queue
  • Simple, synchronous suspension/wake mechanism

Timer Cancellation Pattern (Current Bug Fix)

The recent fixes for timer cancellation in Condition.timedWait() and ResetEvent.timedWait() follow this pattern:

// 1. Start timer and wait
timer.run(&runtime.loop, &completion, timeout_ms, ...);
mutex.unlock(runtime);
current.waitForReady();  // Wait for either timer OR signal
mutex.lock(runtime);

// 2. If timed_out flag set → return error.Timeout
if (timed_out) return error.Timeout;

// 3. If signaled (not timeout) → cancel timer and wait for cancellation
timer.cancel(&runtime.loop, &completion, &cancel_completion, ...);
mutex.unlock(runtime);
current.waitForReady();  // Wait for cancel completion
mutex.lock(runtime);

Key insight: We need two separate waits because:

  1. First wait: race between timer expiration OR external signal
  2. Second wait: wait for timer cancellation to complete (to prevent use-after-free)

Proposed rt.timedWaitForReady(timeout_ns) API

Signature:

pub fn timedWaitForReady(self: *Runtime, timeout_ns: u64) error{Timeout}!void

Semantics:

  • Suspends the current coroutine for up to timeout_ns nanoseconds
  • Returns successfully if markReady() is called before timeout
  • Returns error.Timeout if timeout expires before wake
  • Handles timer lifecycle internally (setup, cancellation, cleanup)

Implementation approach:

pub fn timedWaitForReady(self: *Runtime, timeout_ns: u64) error{Timeout}!void {
    const current = coroutines.getCurrent() orelse unreachable;
    
    var timed_out = false;
    var timer = xev.Timer.init() catch unreachable;
    defer timer.deinit();
    
    const TimedWaitContext = struct {
        runtime: *Runtime,
        coroutine: *coroutines.Coroutine,
        timed_out: *bool,
    };
    
    var ctx = TimedWaitContext{
        .runtime = self,
        .coroutine = current,
        .timed_out = &timed_out,
    };
    
    var completion: xev.Completion = undefined;
    timer.run(&self.loop, &completion, timeout_ns / 1_000_000, TimedWaitContext, &ctx, struct {
        fn callback(c: ?*TimedWaitContext, ...) xev.CallbackAction {
            if (c) |context| {
                context.timed_out.* = true;
                context.runtime.markReady(context.coroutine);
            }
            return .disarm;
        }
    }.callback);
    
    // Wait for either timeout or external markReady
    current.waitForReady();
    
    if (timed_out) {
        return error.Timeout;
    }
    
    // Was awakened by external markReady → cancel timer and wait for cleanup
    var cancel_completion: xev.Completion = undefined;
    timer.cancel(&self.loop, &completion, &cancel_completion, TimedWaitContext, &ctx, struct {
        fn callback(c: ?*TimedWaitContext, ...) xev.CallbackAction {
            if (c) |context| {
                context.runtime.markReady(context.coroutine);
            }
            return .disarm;
        }
    }.callback);
    
    current.waitForReady();  // Wait for cancellation to complete
}

Use Cases

1. Simplified sync primitive implementations:

Current Condition.timedWait() (39 lines with timer logic):

pub fn timedWait(self: *Condition, rt: *Runtime, mutex: *Mutex, timeout_ns: u64) error{Timeout}!void {
    // ... 39 lines of timer setup, context, cancellation ...
}

With timedWaitForReady() (simplified to ~15 lines):

pub fn timedWait(self: *Condition, rt: *Runtime, mutex: *Mutex, timeout_ns: u64) error{Timeout}!void {
    const current = coroutines.getCurrent() orelse unreachable;
    const task = AnyTask.fromCoroutine(current);
    
    self.wait_queue.append(&task.awaitable);
    
    mutex.unlock(rt);
    defer mutex.lock(rt);
    
    rt.timedWaitForReady(timeout_ns) catch |err| {
        // On timeout, try to remove from wait queue
        _ = self.wait_queue.remove(&task.awaitable);
        return err;
    };
}

2. New primitives with timeout support:

  • Makes it trivial to add timed versions of any wait operation
  • Consistent timeout behavior across all primitives

3. Direct user-facing API:

// Users could use it directly for custom timeout logic
const waiter = rt.getWaiter();
// ... setup custom wakeup condition in separate task ...
rt.timedWaitForReady(5_000_000_000) catch {
    // Timeout after 5 seconds
};

Pros

  1. Eliminates code duplication: Timer setup/cancellation pattern repeated in Condition, ResetEvent, Semaphore
  2. Encapsulates complexity: Users don't need to understand timer cancellation mechanics
  3. Prevents bugs: Centralized timer lifecycle management reduces use-after-free risks
  4. Consistent API: All timed operations use same underlying mechanism
  5. Simpler sync primitives: Reduces implementation complexity (39 lines → ~15 lines)
  6. Composable: Can be used as building block for higher-level abstractions

Cons

  1. Limited flexibility: May not suit all use cases where custom timeout behavior is needed
  2. Hidden complexity: The two-wait pattern (timer + cancel) is now implicit
  3. Performance overhead: Always sets up cancellation even if timeout would be sufficient
  4. Lock management: Caller must handle mutex unlock/lock around the call (but this is already required)
  5. Stack space: Adds timer/completion structs to every timed wait call

Alternative Design: Simpler Version Without Auto-Cancellation

If we don't need perfect cleanup in all cases:

pub fn timedWaitForReady(self: *Runtime, timeout_ns: u64) error{Timeout}!void {
    // Same as above but WITHOUT the cancellation logic
    // Simpler but timer may fire after return (acceptable if callback is safe)
}

This would work if the timer callback can safely handle the coroutine being in a different state.

Recommendation

YES, rt.timedWaitForReady(timeout_ns) makes sense and would provide significant value:

  1. Immediate benefit: Simplifies existing Condition.timedWait(), ResetEvent.timedWait(), and future primitives
  2. Reduces bugs: Centralizes tricky timer cancellation logic that caused the macOS crash
  3. Better ergonomics: Easier to add timeout support to new primitives
  4. Natural fit: Pairs well with waitForReady() / markReady() abstraction

Suggested implementation strategy:

  1. Start with the full version (with cancellation) to ensure correctness
  2. Add it to Runtime as a public method
  3. Refactor Condition.timedWait() to use it (proves the concept)
  4. Refactor ResetEvent.timedWait() to use it
  5. Consider if Semaphore.timedWait() can be simplified (it already delegates to Condition)

The main decision point is whether the automatic cancellation cleanup is worth the complexity, or if a simpler version would suffice. Given the recent macOS crash from improper timer cleanup, I'd recommend the full version with cancellation.


Job run • Branch: add-semaphore

@lalinsky

lalinsky commented Oct 4, 2025

Copy link
Copy Markdown
Owner Author

@claude implement it

@claude

claude Bot commented Oct 4, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


Implementation Complete ✓

Successfully implemented Runtime.timedWaitForReady(timeout_ns) as designed.

What Was Implemented

New Runtime Method (src/runtime.zig:704-783)

  • pub fn timedWaitForReady(self: *Runtime, timeout_ns: u64) error{Timeout}!void
  • Suspends current coroutine for up to timeout_ns nanoseconds
  • Returns successfully if markReady() called before timeout
  • Returns error.Timeout if timeout expires first
  • Handles timer lifecycle internally with proper cancellation to prevent use-after-scope bugs

Implementation Details

The method follows the two-wait pattern:

  1. First wait: Race between timer expiration OR external markReady() call
  2. Second wait: If awakened by markReady(), cancel timer and wait for cancellation to complete

This prevents the macOS crash bug where timers would fire after stack frames were unwound.

Design Considerations

Why existing Condition.timedWait() and ResetEvent.timedWait() weren't refactored:

Both methods require custom timeout callbacks that remove waiters from their wait queues (lines 124, 339 in sync.zig). The timeout callback acts as a race resolver between timeout and signal/set. Simply using timedWaitForReady() wouldn't provide this critical wait queue management.

Value of the new API:

  • Provides a clean building block for future sync primitives needing simple timeout behavior
  • Encapsulates complex timer cancellation logic in one place
  • Prevents timer use-after-scope bugs by centralizing lifecycle management
  • Can be used directly for custom timeout scenarios without wait queues

Test Results

✅ All Semaphore tests pass (5/5)
✅ Full test suite passes (54/54 tests)

Changes Committed

  • Added Runtime.timedWaitForReady() with proper timer cancellation
  • All tests passing on Linux
  • Ready for macOS CI validation

Job run • Branch: add-semaphore

Implements a new runtime primitive that suspends the current coroutine
for up to timeout_ns nanoseconds, with proper timer cancellation to
prevent use-after-scope bugs.

This provides a building block for future sync primitives that need
simple timeout behavior without custom wait queue management.

Co-authored-by: Lukáš Lalinský <[email protected]>

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

704-783: Implementation correctly addresses the macOS crash by canceling the timer.

The timer cancellation logic (lines 757-782) prevents the timer callback from accessing the stack-allocated ctx after the function returns, which was causing the reported crash. The dual-path approach (timeout vs. external wake) is sound.

However, consider these improvements:

  1. Timeout precision loss: Line 727 converts nanoseconds to milliseconds with integer division (timeout_ns / 1_000_000). Timeouts less than 1ms will round down to 0. If sub-millisecond precision is needed, this could be problematic.

  2. Missing documentation: Add doc comments explaining the method's purpose, parameters, error conditions, and the guarantee that the timer will be properly canceled regardless of which event fires first.

Example documentation:

/// Waits for the current coroutine to be marked ready by an external event,
/// with a timeout. If the timeout expires before an external markReady call,
/// returns error.Timeout. If awakened by external markReady, cancels the
/// timer and waits for cancellation to complete before returning.
///
/// Must be called from within a coroutine context.
///
/// @param timeout_ns Timeout in nanoseconds (converted to milliseconds, rounded down)
/// @return error.Timeout if the timeout expires, otherwise void on success
pub fn timedWaitForReady(self: *Runtime, timeout_ns: u64) error{Timeout}!void {
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a4c9f87 and 41acd4d.

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

@lalinsky
lalinsky merged commit 00c57bd into main Oct 5, 2025
@lalinsky
lalinsky deleted the add-semaphore branch October 23, 2025 21:01
lalinsky added a commit that referenced this pull request Jan 6, 2026
* Refactor completion error handling to separate errors from payloads

This commit refactors the completion system to store errors separately
from result payloads, improving clarity and type safety.

Key changes:
- Added err and has_result fields to base Completion struct
- Changed operation result fields from Error!Payload to Payload
- Renamed result fields to result_private_do_not_touch to prevent direct access
- Updated setResult/setError to handle cancelation race conditions
- Changed getResult API to take comptime operation type parameter
- Updated all backends (io_uring, epoll, kqueue, poll) to use new pattern
- Updated all tests to use getResult() methods

The new pattern requires calling setResult(.operation_type, value) and
getResult(.operation_type) instead of directly accessing result fields.

* Server test

* Refactor EchoServer and EchoClient to use comptime sockaddr types

Instead of using unions to store different sockaddr types, both
EchoServer and EchoClient now accept the sockaddr type as a comptime
parameter. This eliminates the need for runtime unions and separate
length fields, making the code more type-safe and efficient.

Changes:
- Add sockaddr as comptime type parameter to both functions
- Remove union-based server_addr and connect_addr fields
- Remove server_addr_len and connect_addr_len fields
- Use @sizeof(sockaddr) for address length
- Use std.mem.sliceTo() for null-terminated path slices
- Simplify address initialization with direct field assignment

* Simplify server test by removing redundant state tracking

Remove the tagged union enum in favor of plain unions, since the State
enum already tracks the current state. This eliminates redundancy.

Also simplify bindCallback to update server_addr in place with
getsockname, removing the need for a separate bound_port field and
domain-specific switch logic.

Simplify EchoClient by accepting the full server_addr instead of
conditional port/path parameters, removing all address construction
logic from openCallback.

Changes:
- Remove union(enum) tags, use plain unions
- Remove bound_port field from EchoServer
- Simplify bindCallback to call getsockname once for all socket types
- Change EchoClient.init() to accept full sockaddr
- Remove address construction code from EchoClient.openCallback
- Simplify test to pass server.server_addr directly to client

* Skip Unix socket test on Windows

* Move builtin import to top of file

* Fix macOS compatibility by using time.now() instead of std.os.linux.getpid()

* Handle partial writes in echo server

* Rename server.zig to stream_server.zig and add dgram_server.zig

* Add shutdown after send in stream client

* Refactor net_bind to update address

* Fix common.zig socket API calls for cross-platform compatibility

- Change socket.open() to socket.socket() with correct parameters
- Fix socket.close() which returns void, not error union
- Ensures builds work on FreeBSD, NetBSD, and macOS

* Oops

* Fix echo server to read after send and detect EOF

After echoing data back to the client, the server now returns to the
receiving state instead of immediately closing. This allows it to
properly detect when the client shuts down (EOF), at which point it
closes the connection gracefully.

* Handle partial writes in echo client

Track bytes_sent and re-issue NetSend with the remaining slice until
all data is sent. This prevents calling shutdown(.send) early when a
short write occurs, which would cause the server to only read and echo
back a prefix of the message.

* Let client drain the full echo response

Continue reading and accumulating bytes_received until EOF (0 bytes)
instead of closing after the first NetRecv. This handles cases where
the server's echo response is delivered across multiple completions,
preventing data loss and assertion failures.
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