Skip to content

Add cross-platform signal handling API - #67

Merged
lalinsky merged 13 commits into
mainfrom
add-signal-handling
Oct 24, 2025
Merged

lalinsky merged 13 commits into
mainfrom
add-signal-handling

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 23, 2025 •

Copy link
Copy Markdown
Owner

Summary

Adds a cross-platform Signal API for handling OS signals (SIGINT, SIGTERM) in async applications, enabling graceful shutdown patterns.

  • Implements zio.Signal with .int (SIGINT/Ctrl+C) and .term (SIGTERM) support
  • Stack-allocated API with lazy initialization on first wait()
  • Full integration with xev event loop on all platforms

Platform Implementations

Linux

  • Uses signalfd() to convert signals into file descriptor events
  • Blocks signal with sigprocmask() to prevent default handler
  • Integrates with xev via standard .read operation

macOS/BSD

  • Adds EVFILT_SIGNAL support to libxev's kqueue backend
  • Implements signal operation type, kevent generation, and completion handling
  • Blocks signal with sigprocmask() in application code

Windows

  • Uses SetConsoleCtrlHandler() to catch console control events
  • Global handler registry with thread-safe event distribution
  • Uses ResetEvent to wake waiting coroutines from system thread

Example Usage

var sig = zio.Signal.init(.int);
defer sig.deinit();

while (true) {
    try sig.wait(rt);
    // Handle Ctrl+C - initiate graceful shutdown
    break;
}

Test Plan

  • All 106 existing unit tests pass
  • Compiles for Linux (tested natively)
  • Compiles for macOS ARM64 and x86_64
  • Compiles for Windows x86_64 (tested via Wine)
  • signal-demo example works on Linux and Windows
  • Graceful shutdown pattern demonstrated in example

Files Changed

  • src/signal.zig - New cross-platform Signal API (321 lines)
  • examples/signal_demo.zig - Graceful shutdown example (65 lines)
  • vendor/libxev/src/backend/kqueue.zig - Added EVFILT_SIGNAL support (35 lines)
  • src/zio.zig - Export Signal and SignalType
  • build.zig - Add signal-demo to examples

Summary by CodeRabbit

  • New Features

    • Added comprehensive cross-platform signal handling enabling graceful shutdown on both POSIX and Windows platforms
    • New example demonstrating signal-driven shutdown patterns
  • Breaking Changes

    • Simplified synchronization API: Notify.signal(), Notify.broadcast(), and ResetEvent.set() no longer require a Runtime parameter

Implements Signal API for graceful shutdown handling across Linux,
macOS/BSD, and Windows platforms.

- Linux: Uses signalfd with xev read operation
- macOS/BSD: Adds EVFILT_SIGNAL support to libxev kqueue backend
- Windows: Uses SetConsoleCtrlHandler with ResetEvent
- Supports SIGINT (.int) and SIGTERM (.term) signal types
- Stack-allocated API with lazy initialization
- Includes signal_demo example demonstrating graceful shutdown
@coderabbitai

coderabbitai Bot commented Oct 23, 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 1 minutes and 17 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 47d075d and 66cc5b3.

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

Walkthrough

This PR adds cross-platform signal handling to the async runtime with Unix and Windows implementations, refactors synchronization primitive APIs by removing Runtime parameters from ResetEvent and Notify, integrates signal operations into the kqueue backend, and relocates I/O completion registration from waitForIo to IoOperation.run. A new signal-demo example demonstrates graceful shutdown via SIGINT.

Changes

Cohort / File(s) Summary
Signal Handling Infrastructure
src/signal.zig, src/zio.zig, examples/signal_demo.zig
New cross-platform signal module with per-platform handler registries (Unix/Windows), SignalKind enum, Signal struct, and integration with async/await runtime. Module re-exported from main library. Demo example showing graceful shutdown via signal handling.
Synchronization Primitive API Changes
src/sync/ResetEvent.zig, src/sync/Notify.zig
Removed Runtime parameter from ResetEvent.set() and Notify.signal()/broadcast() methods, reducing API coupling and updating all call sites accordingly.
Build & Examples
build.zig
Added "signal-demo" example entry to build system.
I/O Operation Registration
src/io/base.zig
Relocated completion registration from waitForIo initialization to IoOperation.run, refactored shield lifecycle to use canceled flag, and adjusted executor fetching per iteration.
Kqueue Backend Signal Support
vendor/libxev/src/backend/kqueue.zig
Extended OperationType enum and Operation union with signal variant, added SignalError type to Result union, and integrated signal kevent construction into event routing.
Benchmark Updates
benchmarks/echo_server.zig
Updated ResetEvent.set() calls to remove Runtime parameter.

Sequence Diagram

sequenceDiagram
    participant Main
    participant Runtime
    participant SignalHandler as Signal Handler Task
    participant ServerTask as Server Task
    participant SignalModule as Signal Module
    participant OSSignal as OS Signal
    
    Main->>SignalModule: Signal.init(SIGINT)
    SignalModule->>SignalModule: Install OS handler (first use)
    SignalModule-->>Main: Signal with event
    
    Main->>Runtime: Create & spawn tasks
    activate Runtime
    
    rect rgb(200, 220, 255)
    Note over ServerTask,SignalHandler: Concurrent Execution
    ServerTask->>Runtime: wait(shutdown_event, rt)
    activate ServerTask
    
    SignalHandler->>Runtime: wait for signal
    activate SignalHandler
    end
    
    OSSignal->>SignalModule: SIGINT received
    SignalModule->>SignalModule: Trigger async event
    SignalModule->>SignalHandler: Wake waiter
    
    SignalHandler->>Main: Set shutdown event
    Main->>SignalModule: event.set()
    SignalModule-->>ServerTask: Wake waiter
    
    deactivate ServerTask
    deactivate SignalHandler
    deactivate Runtime
    
    ServerTask->>Main: Exit loop
    SignalHandler->>Main: Cleanup
    
    Main->>SignalModule: Signal.deinit()
    SignalModule->>SignalModule: Uninstall OS handler (if last)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Multiple areas require careful analysis: new signal module with OS-specific handler registry logic and reference counting; refactored I/O registration with shifted completion lifecycle; kqueue backend extension; API signature changes across synchronization primitives requiring verification of all affected call sites.

Possibly related PRs

Poem

🐰 Signals caught on whispered breeze,
Async tasks now wake with ease,
Runtime shed, the API's lean—
Graceful shutdown, clean and keen!
Kqueue hops where signals play, 💫

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "Add cross-platform signal handling API" directly and accurately reflects the primary objective of this changeset. The main work involves introducing a new Signal API (src/signal.zig) with cross-platform support for Linux, macOS/BSD, and Windows, enabling graceful shutdown patterns in async applications. While the PR includes supporting changes such as refactoring synchronization primitives (removing Runtime parameters from ResetEvent and Notify), updating the build configuration, and extending the libxev backend, these are secondary modifications that facilitate the core feature. The title is concise, specific, and clearly conveys the essential change without unnecessary details or vague language, making it easy for someone reviewing the project history to understand the primary contribution.

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: 4

🧹 Nitpick comments (1)
examples/signal_demo.zig (1)

53-63: Optional: avoid polling with fixed sleep

Consider waiting on a channel/event or select with a timeout rather than loop+sleep to reduce idle wakeups in serverTask.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f2b8ca4 and 090e757.

📒 Files selected for processing (5)
  • build.zig (1 hunks)
  • examples/signal_demo.zig (1 hunks)
  • src/signal.zig (1 hunks)
  • src/zio.zig (1 hunks)
  • vendor/libxev/src/backend/kqueue.zig (8 hunks)
🔇 Additional comments (5)
build.zig (1)

40-41: Example target addition looks good

signal-demo is wired like other examples; no build issues spotted.

src/zio.zig (1)

34-36: Re-exports are correct

Public surface matches the new module; no issues.

vendor/libxev/src/backend/kqueue.zig (1)

828-831: Kqueue signal op wiring looks consistent

Start, kevent construction, result/err typing, and unions align with existing patterns. No correctness issues found.

Also applies to: 1138-1146, 1376-1377, 1492-1499, 1632-1632, 1727-1730, 1750-1751, 1809-1813

src/signal.zig (2)

288-306: ResetEvent.set() is safe to call from console handler with undefined runtime

The verification confirms that set() explicitly discards its runtime parameter via _ = runtime; and does not dereference it. The implementation uses atomic operations for state transitions and wakeups, making it non-blocking and safe for cross-thread calls. Passing an undefined runtime pointer is harmless.


157-158: Review comment is incorrect—runIo uses compile-time generics, not runtime switching

The runIo function at src/io/base.zig:48 uses Zig's @FieldType(xev.Result, op) to extract field types at compile time. This is a generic pattern, not a runtime switch statement. The "signal" op at src/signal.zig:157 is safe: if xev.Result.signal doesn't exist, the code fails to compile (impossible to silently fail at runtime). No manual handling is required.

Likely an incorrect or invalid review comment.

Comment thread src/signal.zig Outdated
Comment on lines +111 to +112
self.fd = try std.posix.signalfd(-1, &mask, std.posix.SOCK.CLOEXEC | std.posix.SOCK.NONBLOCK);
}

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.

🛠️ Refactor suggestion | 🟠 Major

Use SFD_ flags for signalfd, not SOCK_ (clarity and future‑proofing)**

Replace socket flags with the signalfd flags.

Apply this diff:

-        self.fd = try std.posix.signalfd(-1, &mask, std.posix.SOCK.CLOEXEC | std.posix.SOCK.NONBLOCK);
+        const sfd_flags: u32 = std.os.linux.SFD.CLOEXEC | std.os.linux.SFD.NONBLOCK;
+        self.fd = try std.posix.signalfd(-1, &mask, sfd_flags);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
self.fd = try std.posix.signalfd(-1, &mask, std.posix.SOCK.CLOEXEC | std.posix.SOCK.NONBLOCK);
}
const sfd_flags: u32 = std.os.linux.SFD.CLOEXEC | std.os.linux.SFD.NONBLOCK;
self.fd = try std.posix.signalfd(-1, &mask, sfd_flags);
}
🤖 Prompt for AI Agents
In src/signal.zig around lines 111-112, the call to std.posix.signalfd is using
std.posix.SOCK.CLOEXEC and std.posix.SOCK.NONBLOCK; replace those socket flags
with the signalfd-specific flags (e.g. use std.posix.SFD.CLOEXEC |
std.posix.SFD.NONBLOCK) so the correct SFD_* constants are passed to signalfd.

Comment thread src/signal.zig Resolved
Comment thread src/signal.zig Resolved
Comment thread src/signal.zig Resolved
@lalinsky

Copy link
Copy Markdown
Owner Author

@claude we need a global state for unix as well, refcount how many signals we masked, do the masking in init and unmask in deinit, no code yet, just plan it

@claude

claude Bot commented Oct 23, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


Unix Signal Masking Refcount Design Plan

Here's a detailed design for implementing reference-counted signal masking for Unix platforms (Linux and macOS/BSD).


Overview

Currently, both LinuxImpl and KqueueImpl call sigprocmask(SIG.BLOCK, ...) in their initialization but never unmask signals in deinit(). This means:

  1. Signals remain blocked for the lifetime of the process
  2. Multiple Signal instances for the same signal type will redundantly block the same signal
  3. There's no way to restore the original signal mask

The solution is to add a global reference counting registry similar to Windows's GlobalHandlerRegistry, but for tracking signal mask state on Unix platforms.


Proposed Design

1. Global State Structure

Add a new UnixSignalMaskRegistry that lives outside the impl structs:

const UnixSignalMaskRegistry = struct {
    var mutex: std.Thread.Mutex = .{};
    var refcounts: [2]usize = .{0, 0};  // Index 0 = SIGINT, 1 = SIGTERM
    
    fn indexForSignal(signal_type: SignalType) usize {
        return switch (signal_type) {
            .int => 0,
            .term => 1,
        };
    }
};

Rationale:

  • Simple fixed-size array since we only support 2 signal types (.int and .term)
  • Mutex protects concurrent access from multiple coroutines
  • Refcount tracks how many active Signal instances exist for each signal type

2. Init Path Changes

In LinuxImpl.initializeSignal() and KqueueImpl.initializeSignal():

1. Lock UnixSignalMaskRegistry.mutex
2. Get current refcount for this signal_type
3. If refcount == 0:
     - This is the first Signal instance for this signal type
     - Call sigprocmask(SIG.BLOCK, ...) to block the signal
     - Handle errors from sigprocmask (return error if it fails)
4. Increment refcount
5. Unlock mutex
6. Continue with platform-specific initialization (signalfd for Linux, set initialized flag for kqueue)

Key points:

  • Signal masking only happens on the first Signal instance for a given type
  • All subsequent instances just increment the refcount
  • The mutex ensures atomicity of check-and-mask
  • Each impl keeps its own instance-level mutex for lazy initialization, but uses the global mutex for refcounting

3. Deinit Path Changes

In LinuxImpl.deinit() and KqueueImpl.deinit():

1. Lock UnixSignalMaskRegistry.mutex
2. If this instance was initialized (fd != -1 for Linux, initialized == true for kqueue):
     - Decrement refcount for this signal_type
     - If refcount reaches 0:
         - This is the last Signal instance for this signal type
         - Call sigprocmask(SIG.UNBLOCK, ...) to restore default signal handling
         - Log/ignore errors from sigprocmask (we're in cleanup path)
3. Unlock mutex
4. Clean up platform-specific resources (close fd for Linux)

Key points:

  • Signal unmasking only happens when the last Signal instance is destroyed
  • Must track whether this instance was initialized to avoid double-decrements
  • Errors during unmask should be logged but not propagate (cleanup path)
  • Instance cleanup (closing fd, etc.) happens after refcount management

4. Thread Safety Considerations

Two-level locking strategy:

  1. Instance-level mutex (LinuxImpl.mutex, KqueueImpl.mutex):

    • Guards lazy initialization of the instance
    • Prevents races between multiple calls to wait() on the same Signal instance
  2. Global registry mutex (UnixSignalMaskRegistry.mutex):

    • Guards the shared refcount array
    • Ensures atomic check-and-mask / decrement-and-unmask operations
    • Must be held during sigprocmask calls to prevent TOCTOU issues

Lock ordering: Always acquire instance mutex first, then global mutex (if both are needed).


5. Error Handling

During initialization (initializeSignal):

  • If sigprocmask(SIG.BLOCK, ...) fails:
    • Do NOT increment refcount
    • Return error to caller
    • No cleanup needed (refcount wasn't incremented)

During deinitialization (deinit):

  • If sigprocmask(SIG.UNBLOCK, ...) fails:
    • Log the error (process may be in weird state)
    • Continue with cleanup
    • Don't propagate error (deinit should be infallible)

6. Integration Points

For LinuxImpl:

  • Wrap the sigprocmask(SIG.BLOCK, ...) call at line 108 with refcount check
  • Add sigprocmask(SIG.UNBLOCK, ...) in deinit at line 114-122
  • Track initialization state to know whether to decrement refcount

For KqueueImpl:

  • Wrap the sigprocmask(SIG.BLOCK, ...) call at line 175 with refcount check
  • Replace no-op deinit at line 180-182 with refcount decrement + unmask
  • Already has initialized flag for tracking

7. Edge Cases

  1. Multiple Signal instances created concurrently:

    • Global mutex ensures only one thread masks the signal
    • Other threads see refcount > 0 and skip masking
  2. Signal instance created, never used (wait() never called):

    • Lazy initialization means no masking happens
    • deinit() checks initialization state, doesn't decrement refcount
    • No spurious unmask
  3. Process receives signal before any Signal.wait():

    • Signal is not yet blocked, default handler runs (process terminates)
    • This is expected behavior (signal handling starts on first wait)
  4. Race between last deinit() and new init():

    • Global mutex prevents: unmask can't happen while new mask is being set up
    • Refcount transitions: 1 → 0 (unmask) or 0 → 1 (mask), never 1 → 0 → 1 simultaneously

8. Testing Considerations

Unit tests should verify:

  • Single Signal instance: signal is masked during lifetime, unmasked after deinit
  • Multiple Signal instances (same type): signal masked once, unmasked after all deinit
  • Multiple Signal instances (different types): both signals masked independently
  • Lazy initialization: no masking until first wait()

Testing approach:

  • Check /proc/self/status (Linux) or sigprocmask(0, NULL, &oldmask) (macOS) to verify mask state
  • Create test helper that reads current signal mask and validates expected blocked signals

Summary

This design provides:

  • ✅ Correct refcounting to avoid redundant mask/unmask calls
  • ✅ Thread-safe operation across multiple Signal instances
  • ✅ Lazy initialization preserved
  • ✅ Proper cleanup that restores original signal mask
  • ✅ Symmetric with existing Windows GlobalHandlerRegistry pattern
  • ✅ Minimal changes to existing code structure

Implementation effort: ~50-80 lines of new code, ~20 lines of modifications to existing init/deinit paths.


Checklist

  • Read current signal.zig implementation
  • Design global state structure for Unix platforms
  • Plan initialization and reference counting logic
  • Plan masking/unmasking behavior
  • Plan thread safety approach
  • Document complete design

Job Run | Branch: add-signal-handling

@lalinsky

Copy link
Copy Markdown
Owner Author

@claude implement it, don't bother with testing

@claude

claude Bot commented Oct 23, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


Implementing Unix Signal Masking Refcount

Checklist

  • Read current signal.zig implementation
  • Implement UnixSignalMaskRegistry structure
  • Update LinuxImpl initialization with refcounting
  • Update LinuxImpl deinit with refcount decrement and unmask
  • Update KqueueImpl initialization with refcounting
  • Update KqueueImpl deinit with refcount decrement and unmask
  • Format code with ./check.sh
  • Commit and push changes

Summary

Successfully implemented the Unix signal masking refcount design. The implementation adds a global UnixSignalMaskRegistry that:

Key Features:

  • Tracks reference counts for SIGINT and SIGTERM independently
  • Only masks signals when the first Signal instance is created for a given type
  • Only unmasks signals when the last Signal instance is destroyed for a given type
  • Thread-safe with mutex protection for all refcount operations
  • Works on Linux (signalfd), macOS, and BSD platforms (kqueue)

Changes Made:

  • Added UnixSignalMaskRegistry struct with mutex and refcount array (lines 59-117)
  • Modified LinuxImpl.initializeSignal() to use incrementAndMaskIfNeeded() (line 161)
  • Modified LinuxImpl.deinit() to call decrementAndUnmaskIfNeeded() (line 183)
  • Modified KqueueImpl.initializeSignal() to use incrementAndMaskIfNeeded() (line 231)
  • Modified KqueueImpl.deinit() to call decrementAndUnmaskIfNeeded() (lines 236-245)

Test Results: All 106 unit tests pass ✅

The implementation ensures proper cleanup of signal masks and prevents redundant masking operations, matching the design pattern used by Windows's GlobalHandlerRegistry.


Job Run | Branch: add-signal-handling | Commit: aa6b9a3

Implements a global UnixSignalMaskRegistry that tracks how many Signal
instances are active for each signal type (SIGINT/SIGTERM). Signal
masking now only happens when the first instance is created, and
unmasking only happens when the last instance is destroyed.

This ensures that:
- Multiple Signal instances for the same type don't redundantly mask
- The process signal mask is properly restored on cleanup
- No signals remain permanently blocked after deinit

The registry uses a mutex-protected refcount array and integrates with
both LinuxImpl (signalfd) and KqueueImpl (EVFILT_SIGNAL).

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: 2

♻️ Duplicate comments (2)
src/signal.zig (2)

171-171: Use SFD_ flags for signalfd, not SOCK_ flags.**

This was flagged in a previous review. While SOCK.CLOEXEC and SOCK.NONBLOCK may have the same numeric values as the signalfd flags on Linux, using the correct SFD.* constants improves clarity and future-proofs the code.

Apply this diff:

-        self.fd = try std.posix.signalfd(-1, &mask, std.posix.SOCK.CLOEXEC | std.posix.SOCK.NONBLOCK);
+        const sfd_flags: u32 = std.os.linux.SFD.CLOEXEC | std.os.linux.SFD.NONBLOCK;
+        self.fd = try std.posix.signalfd(-1, &mask, sfd_flags);

315-334: Fix stale entry on SetConsoleCtrlHandler failure.

This was flagged in a previous review. The code appends the handler entry (lines 322-326) before attempting to install the console handler (line 329). If SetConsoleCtrlHandler fails, the appended entry remains in the registry, causing a stale registration.

Apply this diff to install the handler first:

+            if (!ctrl_handler_installed) {
+                const result = std.os.windows.kernel32.SetConsoleCtrlHandler(consoleCtrlHandler, 1);
+                if (result == 0) return error.SetConsoleCtrlHandlerFailed;
+                ctrl_handler_installed = true;
+            }
+
             const id = next_id;
             next_id += 1;

             try handlers.append(std.heap.page_allocator, .{
                 .id = id,
                 .signal_type = signal_type,
                 .event = event,
             });

-            if (!ctrl_handler_installed) {
-                const result = std.os.windows.kernel32.SetConsoleCtrlHandler(consoleCtrlHandler, 1);
-                if (result == 0) return error.SetConsoleCtrlHandlerFailed;
-                ctrl_handler_installed = true;
-            }
-
             return id;
🧹 Nitpick comments (2)
src/signal.zig (2)

95-114: Consider handling sigprocmask errors on unmask.

Line 111 ignores errors from std.posix.sigprocmask during unmask. While less critical than the mask operation, a failure here could leave signals blocked permanently.

Since this is called from deinit (which can't return errors), consider logging the failure:

-                    std.posix.sigprocmask(std.posix.SIG.UNBLOCK, &mask, null);
+                    std.posix.sigprocmask(std.posix.SIG.UNBLOCK, &mask, null) catch |err| {
+                        std.log.warn("Failed to unblock signal {}: {}", .{ signum, err });
+                    };

322-322: Consider explicit memory management for handler registry.

Using std.heap.page_allocator for the handlers array means allocations persist for the process lifetime. While handlers are removed on unregister, the underlying array capacity is never freed.

For long-running processes with dynamic Signal creation/destruction, consider adding a deallocation path or using a different allocator strategy. However, given typical usage patterns (a few signals per process), this is likely acceptable.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 090e757 and aa6b9a3.

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

1-13: LGTM!

The imports and SignalType enum provide a clean cross-platform abstraction over OS-specific signal mechanisms.


15-57: LGTM!

The public API is clean and properly delegates to platform-specific implementations. The compile-time error for unsupported platforms ensures early detection of portability issues.


188-246: LGTM!

The kqueue implementation correctly uses the new UnixSignalMaskRegistry for reference-counted signal masking and properly cleans up in deinit. The lazy initialization pattern is thread-safe.


355-359: Verify Windows event-to-signal mapping matches intent.

Line 356 maps both CTRL_C_EVENT and CTRL_BREAK_EVENT to .int. Typically, Ctrl+Break is distinct from Ctrl+C and might warrant separate handling. Similarly, CTRL_LOGOFF_EVENT and CTRL_SHUTDOWN_EVENT (line 357) are mapped to .term along with CTRL_CLOSE_EVENT.

Confirm this mapping aligns with the intended signal semantics for your use case:

  • CTRL_C_EVENT → .int ✓ (standard Ctrl+C)
  • CTRL_BREAK_EVENT → .int ? (Ctrl+Break, traditionally more forceful)
  • CTRL_CLOSE_EVENT → .term ✓ (console window closed)
  • CTRL_LOGOFF_EVENT → .term ? (user logoff)
  • CTRL_SHUTDOWN_EVENT → .term ? (system shutdown)

If Ctrl+Break or logoff/shutdown events should not trigger application shutdown, adjust the mapping.


378-384: Test coverage noted.

The comment correctly identifies that signal handling requires integration testing. The refAllDecls test ensures compilation of all declarations.

As noted in the PR comments, thorough testing is deferred.

Comment thread src/signal.zig Resolved
Comment thread src/signal.zig Resolved
@lalinsky

Copy link
Copy Markdown
Owner Author

@claude investigate macos build failure

@claude

claude Bot commented Oct 23, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


Claude finished @lalinsky's task


macOS Build Failure Investigation & Fix

Summary

Fixed a macOS-specific test failure in net.test.tcpConnectToHost: basic by using pthread_sigmask() instead of sigprocmask() on macOS/BSD platforms.

Root Cause

On macOS and BSD systems, sigprocmask() only affects the calling thread, not the entire process. The failing test uses a multi-threaded runtime (thread_pool = .{ .enabled = true }), and the incorrect use of sigprocmask() was causing signal mask inconsistencies across threads.

According to POSIX documentation:

  • Linux: sigprocmask() affects the entire process
  • macOS/BSD: sigprocmask() only affects the calling thread; pthread_sigmask() should be used in multi-threaded applications

Fix Applied

Modified src/signal.zig in the UnixSignalMaskRegistry:

  1. incrementAndMaskIfNeeded(): Use pthread_sigmask() with error handling on macOS/BSD
  2. decrementAndUnmaskIfNeeded(): Use pthread_sigmask() on macOS/BSD
  3. Linux: Continue using sigprocmask() (correct behavior on Linux)

This ensures thread-safe signal masking behavior on all Unix platforms.

Testing

  • ✅ All 106 tests pass on Linux
  • 🔄 Pushed fix to add-signal-handling branch
  • ⏳ CI will verify the fix on macOS

Changes

  • Committed: b332c84 - Use pthread_sigmask on macOS/BSD for thread-safe signal masking

Job Run | Branch: add-signal-handling | Commit: b332c84

@lalinsky
lalinsky force-pushed the add-signal-handling branch from b332c84 to aa6b9a3 Compare October 23, 2025 09:38
The Runtime parameter was never used by ResetEvent.set() (it was
immediately discarded with `_ = runtime`). Removing it simplifies
the API and fixes the Windows signal handler which was passing an
undefined Runtime pointer to work around this.

This is a breaking API change, but the signal handling feature has
not been released yet.
… Runtime parameters

Changes:
- Remove unused Runtime parameter from Notify.signal() and Notify.broadcast()
- Update Windows signal handler to use Notify instead of ResetEvent

Benefits:
- Notify is stateless and better matches signal handling semantics
- No need to call reset() after each wait()
- Cleaner API - signal() and broadcast() can be called from any thread without Runtime
- Eliminates the undefined Runtime pointer issue in Windows console handler

All tests pass.
The console control handler is now properly uninstalled when the last
Signal instance is destroyed. This prevents a resource leak where the
handler would remain registered even when no Signal instances exist.

When unregister() removes the last handler from the list, it calls
SetConsoleCtrlHandler(consoleCtrlHandler, 0) to uninstall the handler
and sets ctrl_handler_installed = false to track the state.

@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: 1

♻️ Duplicate comments (3)
src/signal.zig (3)

76-93: Handle sigprocmask/sigset errors; don’t ignore failures.

Propagate or log errors from sigemptyset/sigaddset/sigprocmask so masking failures don’t go unnoticed. Same for UNBLOCK in decrement.

Apply one of these, depending on your Zig version:

-                var mask = std.posix.sigemptyset();
-                std.posix.sigaddset(&mask, @intCast(signum));
-                std.posix.sigprocmask(std.posix.SIG.BLOCK, &mask, null);
+                var mask = std.posix.sigemptyset();
+                _ = std.posix.sigaddset(&mask, @intCast(signum)); // check return if your std exposes it
+                try std.posix.sigprocmask(std.posix.SIG.BLOCK, &mask, null);

And similarly for UNBLOCK in decrement.


169-172: Use SFD_ flags with signalfd, not SOCK_ (correctness/clarity).**

Pass SFD_CLOEXEC/SFD_NONBLOCK to signalfd; SOCK_* are socket‑specific and may be rejected on some libcs/kernels.

-        self.fd = try std.posix.signalfd(-1, &mask, std.posix.SOCK.CLOEXEC | std.posix.SOCK.NONBLOCK);
+        const sfd_flags: u32 = std.os.linux.SFD.CLOEXEC | std.os.linux.SFD.NONBLOCK;
+        self.fd = try std.posix.signalfd(-1, &mask, sfd_flags);

312-333: Fix stale entry risk on SetConsoleCtrlHandler failure (install first, then append).

If SetConsoleCtrlHandler fails, the appended handler remains registered in your list. Install first, then append.

-            const id = next_id;
-            next_id += 1;
-
-            try handlers.append(std.heap.page_allocator, .{
-                .id = id,
-                .signal_type = signal_type,
-                .notify = notify,
-            });
-
-            if (!ctrl_handler_installed) {
-                const result = std.os.windows.kernel32.SetConsoleCtrlHandler(consoleCtrlHandler, 1);
-                if (result == 0) return error.SetConsoleCtrlHandlerFailed;
-                ctrl_handler_installed = true;
-            }
-
-            return id;
+            if (!ctrl_handler_installed) {
+                const ok = std.os.windows.kernel32.SetConsoleCtrlHandler(consoleCtrlHandler, 1);
+                if (ok == 0) return error.SetConsoleCtrlHandlerFailed;
+                ctrl_handler_installed = true;
+            }
+
+            const id = next_id;
+            next_id += 1;
+            try handlers.append(std.heap.page_allocator, .{
+                .id = id,
+                .signal_type = signal_type,
+                .notify = notify,
+            });
+            return id;
🧹 Nitpick comments (1)
src/signal.zig (1)

354-371: Reduce work under registry mutex in console handler (optional).

You wake waiters while holding GlobalHandlerRegistry.mutex. Consider copying matching notify pointers to a small stack buffer, unlock, then signal them. Cuts lock hold time and contention. Keep it allocation‑free in the handler.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aa6b9a3 and d1c7edc.

📒 Files selected for processing (7)
  • README.md (0 hunks)
  • benchmarks/echo_server.zig (2 hunks)
  • examples/signal_demo.zig (1 hunks)
  • src/signal.zig (1 hunks)
  • src/sync/Notify.zig (9 hunks)
  • src/sync/ResetEvent.zig (7 hunks)
  • src/zio.zig (1 hunks)
💤 Files with no reviewable changes (1)
  • README.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/signal_demo.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 (7)
src/zio.zig (1)

33-36: Re-exports look good.

Surface matches the new module; no issues.

src/sync/ResetEvent.zig (2)

33-33: Docs/tests updated to new API.

Examples and tests now call event.set(); consistent and correct.

Also applies to: 270-270, 274-274, 299-299, 360-360, 389-389, 419-419


83-92: API change correctly applied; external-thread concern is based on incorrect assumption.

The removal of the Runtime parameter from set() is properly implemented. All call sites (lines 270, 274, 389) correctly invoke set() without arguments. However, the review comment's concern about external-thread safety appears to be based on a misunderstanding: ResetEvent is designed for cooperative synchronization within the zio runtime, as documented at the top of the file. The documentation and examples exclusively show usage with runtime-spawned tasks, not external thread invocation. No changes are needed.

Likely an incorrect or invalid review comment.

benchmarks/echo_server.zig (1)

34-34: Call site updates match ResetEvent API.

No functional change; good.

Also applies to: 139-139

src/sync/Notify.zig (2)

33-33: Examples/tests align with new Notify API.

All updated usages look consistent.

Also applies to: 37-37, 235-235, 257-259, 285-285, 323-326, 387-387, 413-413


76-82: Runtime‑free Notify.signal()/broadcast(): Cross‑thread safety verified as safe.

Verified that WaitQueue uses a mutation spinlock with atomic memory ordering for thread-safe operations. The wake handler (AnyTask.waitNodeWake) calls resumeTask with .maybe_remote mode, which is explicitly designed for cross-executor and cross-thread resumption from system threads. All calls to notify.signal() and notify.broadcast() use the new parameter-free signatures consistently.

src/signal.zig (1)

198-221: No action needed — xev signal op is properly implemented.

The .signal completion operation is fully wired in the kqueue backend. The Operation union includes a signal variant (vendor/libxev/src/backend/kqueue.zig:1727), the handler exists (line 828), and EVFILT_SIGNAL is correctly used via std.c.EVFILT.SIGNAL (line 1140). Your code is using a supported and properly implemented feature.

Comment thread src/signal.zig Resolved
Rewrites signal handling with a unified approach using xev.Async for both Unix
and Windows platforms. Key changes:

- Add Windows support via SetConsoleCtrlHandler
- Implement atomic reference counting for proper OS handler cleanup
- Unix: Track per-signal refcounts, restore previous handlers when count reaches 0
- Windows: Track total handlers, uninstall global console handler when no handlers remain
- Add more Unix signals: HUP, ALRM, CHLD, IO, PIPE, QUIT, USR1, USR2, WINCH
- Rename SignalType to SignalKind for consistency
- Simplify API with platform-specific registry structs
- Fix IO cancellation handling in waitForIo
Add two comprehensive tests for signal handling:
- Basic signal handling: tests signal reception and handler lifecycle
- Multiple handlers: tests that multiple handlers receive the same signal

Tests are skipped on Windows as GenerateConsoleCtrlEvent doesn't support
reliable self-signaling in test environments.
@lalinsky

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Oct 24, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

🧹 Nitpick comments (3)
examples/signal_demo.zig (1)

57-59: Optionally listen for SIGTERM too.

Spawn a second handler for .terminate so both Ctrl+C and SIGTERM trigger shutdown.

-    // Spawn signal handler task
-    var signal_task = try runtime.spawn(signalHandler, .{ &runtime, &shutdown }, .{});
-    defer signal_task.deinit();
+    // Spawn signal handlers (INT and TERM)
+    var sigint_task = try runtime.spawn(signalHandler, .{ &runtime, &shutdown }, .{});
+    defer sigint_task.deinit();
+    var sigterm_task = try runtime.spawn(struct {
+        fn run(rt: *zio.Runtime, sd: *zio.ResetEvent) !void {
+            var sig = try zio.Signal.init(.terminate);
+            defer sig.deinit();
+            try sig.wait(rt);
+            sd.set();
+        }
+    }.run, .{ &runtime, &shutdown }, .{});
+    defer sigterm_task.deinit();
src/signal.zig (2)

238-275: Tests rely on std.posix.raise mapping; update after SignalKind decoupling.

After making SignalKind OS-agnostic, use posixSigNum(.interrupt) in tests.

-            try std.posix.raise(@intFromEnum(SignalKind.interrupt));
+            try std.posix.raise(posixSigNum(.interrupt));

277-320: Broadcast semantics validated by test; document API behavior.

One SIGINT wakes all registered handlers. Consider documenting this explicitly to avoid surprises.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d1c7edc and 4ad207f.

📒 Files selected for processing (4)
  • examples/signal_demo.zig (1 hunks)
  • src/io/base.zig (2 hunks)
  • src/signal.zig (1 hunks)
  • src/zio.zig (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/zio.zig
🔇 Additional comments (2)
src/io/base.zig (2)

62-73: Registering completion in IoOperation.run centralizes lifecycle.

Good consolidation; reduces duplication and mis-registrations.


18-41: All call sites properly register completions before waitForIo.

Verification confirms both waitForIo call sites handle completion registration correctly: src/io/base.zig:72 uses explicit executor.loop.add(), and src/signal.zig:231 registers via self.event.wait() which implicitly adds to the loop (line 209 comment confirms this). The code changes are sound.

Comment thread examples/signal_demo.zig Resolved
Comment thread src/signal.zig Resolved
Comment thread src/signal.zig Resolved
Comment thread src/signal.zig Resolved
Comment thread src/signal.zig Resolved
Comment thread src/signal.zig Resolved
Comment thread src/signal.zig
Comment on lines +148 to +155
fn signalHandlerUnix(signum: c_int) callconv(.c) void {
for (&registry.handlers) |*entry| {
const kind = entry.kind.load(.acquire);
if (kind != NO_SIGNAL and kind == signum) {
entry.event.notify() catch {};
}
}
}

@coderabbitai coderabbitai Bot Oct 24, 2025 •

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.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify async-signal-safety of xev.Async.notify() and notify/deinit race.

Calling notify() from a POSIX signal handler must be async-signal-safe. Also confirm it's safe if uninstall() concurrently deinit’s the same Async.

If not guaranteed, switch to a self-pipe/eventfd or one xev.Async per signal and only write a byte in the handler; do the rest on the loop thread.


🌐 Web query:

Is xev.Async.notify in libxev safe to call from a POSIX signal handler? Does libxev guarantee notify is safe if another thread concurrently calls Async.deinit?

💡 Result:

Short answer: No — you should not assume xev.Async.notify is safe to call from a POSIX signal handler, and libxev does not promise it is safe while another thread concurrently calls Async.deinit.

Why: POSIX signal handlers are only allowed to call async‑signal‑safe functions; anything that may take locks, allocate, call non‑reentrant library code, or perform complex syscall sequences is unsafe inside a handler. libxev is an async/event‑loop library (not a tiny signal‑safe shim) and its public API is implemented in Zig/C on top of normal threading/primitives, so you cannot rely on it being async‑signal‑safe. See POSIX rules for async‑signal‑safe functions. [1]

Practical consequence:

  • Do not call xev.Async.notify directly from a signal handler. Instead use a guaranteed signal‑safe technique (for example write a byte to a pipe/eventfd that the loop polls, or use signalfd/SIGEV_THREAD where appropriate) to notify the event loop.
  • Likewise, do not rely on safety if another thread may call Async.deinit concurrently; deinit likely races with notify if both touch shared state without explicit async‑signal guarantees.

Sources:

  • libxev project (library description / API is an event loop rather than a signal‑safe primitive). [2]
  • POSIX list of async‑signal‑safe functions / guidance on what is allowed in signal handlers. [1]

If you want, I can: (a) inspect the exact libxev Async implementation to point to specific non‑signal‑safe operations, or (b) show a minimal safe pattern (pipe/eventfd or signalfd) to notify a libxev loop from a signal handler.


I'll verify the codebase context to confirm the exact type of entry.event and ensure the fix recommendation is precise.





🏁 Script executed:

#!/bin/bash
# Check signal.zig structure to understand registry, entries, and event type
rg -n -A10 -B5 "registry" src/signal.zig | head -80

Length of output: 1987


🏁 Script executed:

#!/bin/bash
# Look for the registry and handler entry struct definition
rg -n -A15 "struct.*Handler\|const registry\|var registry" src/signal.zig

Length of output: 0


🏁 Script executed:

#!/bin/bash
# Check what xev.Async is and how it's used in the codebase
rg -n "xev\.Async\|@import.*xev" src/signal.zig

Length of output: 0


🏁 Script executed:

#!/bin/bash
# Look for the entry struct definition and event field
rg -n -B5 -A10 "event.*notify\|\.event\s*=" src/signal.zig | head -100

Length of output: 0


🏁 Script executed:

#!/bin/bash
# Check imports and type definitions at the top of signal.zig
head -50 src/signal.zig

Length of output: 1830


🏁 Script executed:

#!/bin/bash
# Search for Async struct definition in the entire codebase to understand it
fd -t f -e zig | xargs rg -l "fn notify" | head -5

Length of output: 68


Signal handler must use async-signal-safe notification mechanism.

Calling xev.Async.notify() from signalHandlerUnix() violates POSIX signal handler requirements—only async-signal-safe functions are allowed. Additionally, if uninstall() concurrently deinits the registry entry, a race condition occurs.

Use a self-pipe/eventfd pattern: write a single byte in the signal handler, and read it on the event loop thread to trigger actual notification.

🤖 Prompt for AI Agents
In src/signal.zig around lines 148-155, the signal handler currently calls
entry.event.notify() from the signal handler which is not async-signal-safe and
races with uninstall(); replace that with a self-pipe/eventfd approach: create a
pipe or eventfd during initialization, set it non-blocking, and in
signalHandlerUnix() only perform a single safe write (one byte or uint64) to the
pipe/eventfd (handling EINTR/EAGAIN) and return; on the event loop thread
monitor the read end (epoll/select/async wait), drain the pipe/eventfd and then
iterate the registry entries on the non-signal thread to check kind with atomics
and call entry.event.notify() there, so notification and any registry deinits
occur only on the safe thread and races are avoided.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@coderabbitai how is xev.Async.notify() not signal-safe?

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.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find the xev.Async implementation in vendor/libxev
fd -t f "async" vendor/libxev

Length of output: 378


🏁 Script executed:

#!/bin/bash
# Search for Async struct and notify method in libxev
rg -n -A20 "pub const Async" vendor/libxev/

Length of output: 7080


🏁 Script executed:

#!/bin/bash
# Look for notify function implementation
rg -n -A30 "fn notify" vendor/libxev/ | head -150

Length of output: 10503


🏁 Script executed:

#!/bin/bash
# Check what backend is used and how notify works
rg -n -B5 -A25 "struct.*Async\|pub fn notify" vendor/libxev/src/backend/

Length of output: 0


@lalinsky I apologize - I was wrong about the Linux implementation. Let me explain what I found:

Looking at the actual xev.Async.notify() implementation in vendor/libxev/src/watcher/async.zig:

On Linux (eventfd backend, lines 202-209):

pub fn notify(self: Self) !void {
    const val = @as([8]u8, @bitCast(@as(u64, 1)));
    _ = posix.write(self.fd, &val) catch |err| switch (err) {
        error.WouldBlock => return,
        else => return err,
    };
}

This is async-signal-safe because:

  • It only calls the write() syscall, which is in the POSIX list of async-signal-safe functions
  • No locks, no allocations, no complex operations
  • Uses a stack-allocated value
  • The fd is already opened

However, on other platforms:

  • Windows (IOCP): Uses self.guard.lock() (line 598), which is NOT async-signal-safe
  • macOS (mach ports): Uses mach_msg(), which is not guaranteed to be async-signal-safe

So for the Linux signal handler in this PR, xev.Async.notify() should be safe. My concern about the race condition with concurrent uninstall()/deinit() still stands though - if one thread is in uninstall() calling entry.event.deinit() while a signal arrives and tries to call entry.event.notify(), that could be problematic.

Would you like me to focus on just the race condition issue, or do you see this differently?

@lalinsky
lalinsky merged commit 54358fd into main Oct 24, 2025
@lalinsky
lalinsky deleted the add-signal-handling branch October 24, 2025 11:11

@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: 4

♻️ Duplicate comments (2)
src/signal.zig (2)

7-25: Make SignalKind OS-agnostic (map to OS numbers at use sites).

Binding enum values to OS constants harms portability and likely caused the macOS build issue mentioned. Prefer a stable enum like { interrupt, terminate } and translate with a helper (e.g., posixSigNum()).

Minimal sketch:

-else => enum(u8) {
-    interrupt = std.posix.SIG.INT,
-    terminate = std.posix.SIG.TERM,
-    ...
-},
+else => enum(u8) { interrupt, terminate },

Then use posixSigNum(kind) where needed.


69-77: Fix publish-before-init race (can call notify on an uninitialized event).

A signal can arrive after you set kind but before event init, leading to notify() on undefined memory. Publish only after the event is initialized using an INSTALLING sentinel.

Apply:

+const INSTALLING = 254;
@@
-        // Now find a slot for this signal handler
+        // Find a slot; publish after event is initialized
         for (&self.handlers) |*entry| {
-            const prev = entry.kind.cmpxchgStrong(NO_SIGNAL, signum, .acq_rel, .monotonic);
+            const prev = entry.kind.cmpxchgStrong(NO_SIGNAL, INSTALLING, .acq_rel, .monotonic);
             if (prev == null) {
                 errdefer entry.kind.store(NO_SIGNAL, .release);
-
-                entry.event = try xev.Async.init();
-
-                return &entry.event;
+                var ev = try xev.Async.init();
+                entry.event = ev;
+                // Publish: ensure event is visible before kind is observable
+                entry.kind.store(signum, .release);
+                return &entry.event;
             }
         }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4ad207f and 47d075d.

📒 Files selected for processing (1)
  • src/signal.zig (1 hunks)
⏰ 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)

Comment thread src/signal.zig
Comment on lines +130 to +137
// Now find a slot for this signal handler
for (&self.handlers) |*entry| {
const prev = entry.kind.cmpxchgStrong(NO_SIGNAL, signum, .acq_rel, .monotonic);
if (prev == null) {
errdefer entry.kind.store(NO_SIGNAL, .release);
entry.event = try xev.Async.init();
return &entry.event;
}

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.

⚠️ Potential issue | 🔴 Critical

Mirror INSTALLING/publish-after-init on Windows path.

Same race exists here; use the INSTALLING sentinel and publish kind after Async.init.

Apply:

-        for (&self.handlers) |*entry| {
-            const prev = entry.kind.cmpxchgStrong(NO_SIGNAL, signum, .acq_rel, .monotonic);
+        for (&self.handlers) |*entry| {
+            const prev = entry.kind.cmpxchgStrong(NO_SIGNAL, INSTALLING, .acq_rel, .monotonic);
             if (prev == null) {
                 errdefer entry.kind.store(NO_SIGNAL, .release);
-                entry.event = try xev.Async.init();
-                return &entry.event;
+                var ev = try xev.Async.init();
+                entry.event = ev;
+                entry.kind.store(signum, .release);
+                return &entry.event;
             }
         }
🤖 Prompt for AI Agents
In src/signal.zig around lines 130 to 137, the current loop can race because it
publishes the signum via cmpxchgStrong(NO_SIGNAL, signum) before Async.init
completes; change to use an INSTALLING sentinel: cmpxchgStrong(NO_SIGNAL,
INSTALLING) to reserve the slot, call Async.init(), and only after successful
init store the real signum (entry.kind.store(signum, .release)); on failure
revert to NO_SIGNAL (entry.kind.store(NO_SIGNAL, .release)) and remove the
errdefer that unconditionally stores NO_SIGNAL before init so the slot stays
reserved while initializing.

Comment thread src/signal.zig
Comment on lines +166 to +173
fn signalHandlerUnix(signum: c_int) callconv(.c) void {
for (&registry.handlers) |*entry| {
const kind = entry.kind.load(.acquire);
if (kind != NO_SIGNAL and kind == signum) {
entry.event.notify() catch {};
}
}
}

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.

⚠️ Potential issue | 🔴 Critical

Type mismatch in comparison (u8 vs c_int) — won’t compile; cast signum.

kind is u8 while signum is c_int. Explicitly cast before comparing.

Apply:

 fn signalHandlerUnix(signum: c_int) callconv(.c) void {
     for (&registry.handlers) |*entry| {
         const kind = entry.kind.load(.acquire);
-        if (kind != NO_SIGNAL and kind == signum) {
+        const sig_u8: u8 = @intCast(signum);
+        if (kind != NO_SIGNAL and kind == sig_u8) {
             entry.event.notify() catch {};
         }
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
fn signalHandlerUnix(signum: c_int) callconv(.c) void {
for (&registry.handlers) |*entry| {
const kind = entry.kind.load(.acquire);
if (kind != NO_SIGNAL and kind == signum) {
entry.event.notify() catch {};
}
}
}
fn signalHandlerUnix(signum: c_int) callconv(.c) void {
for (&registry.handlers) |*entry| {
const kind = entry.kind.load(.acquire);
const sig_u8: u8 = @intCast(signum);
if (kind != NO_SIGNAL and kind == sig_u8) {
entry.event.notify() catch {};
}
}
}
🤖 Prompt for AI Agents
In src/signal.zig around lines 166 to 173, the comparison mixes types (kind is
u8, signum is c_int) causing a compile error; cast signum to u8 before comparing
(or cast once to a local u8 variable) and use that cast in the if condition so
both sides share the same integer type; ensure you handle any potential
out-of-range signum appropriately if needed.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify Async.notify safety in signal context across platforms.

Calling xev.Async.notify() from a Unix signal handler must be async-signal-safe. Linux backends that do a bare write() are fine; macOS/BSD may differ. Also confirm notify vs concurrent deinit is safe.

Run to inspect libxev:


🏁 Script executed:

#!/bin/bash
# Locate Async.notify implementations
rg -nP 'pub\s+const\s+Async\b|fn\s+notify\s*\(' vendor/libxev -C3

# Print platform-specific notify code paths (kqueue/darwin, linux)
rg -nP 'async.*notify|eventfd|pipe|EVFILT_USER|mach' vendor/libxev -C2

Length of output: 48422


Fix macOS async-signal-safety violation in signal handler.

The review concern is valid. Only low-level UNIX APIs (open, write, close) are documented to be async-signal-safe, but the code calls entry.event.notify() from signalHandlerUnix(), which on macOS uses mach_msg() — a Mach subsystem call that is not async-signal-safe.

From the libxev source:

  • Linux (io_uring/epoll): Uses eventfd with write(), which is async-signal-safe ✓
  • macOS (kqueue): Uses Mach ports and mach_msg(), which is not async-signal-safe ✗
  • BSD (kqueue): Comments indicate eventfd support is unimplemented; current code path also unsafe

Additionally, concurrent access patterns need review:

  • Signal handler reads entry.kind and calls notify() without synchronization
  • Main thread may deinit or modify entries during signal delivery
  • No documented guarantee that notify() or .load() operations are safe under concurrent access from signal handlers

Comment thread src/signal.zig
Comment on lines +283 to +286
fn sendSignal(r: *Runtime) !void {
try r.sleep(10);
try std.posix.raise(@intFromEnum(SignalKind.interrupt));
}

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.

⚠️ Potential issue | 🔴 Critical

Cast to c_int in tests for std.posix.raise.

@intFromEnum(SignalKind.interrupt) is u8; raise expects c_int.

Apply:

-            try std.posix.raise(@intFromEnum(SignalKind.interrupt));
+            try std.posix.raise(@as(c_int, @intFromEnum(SignalKind.interrupt)));

Also applies to: 328-331

🤖 Prompt for AI Agents
In src/signal.zig around lines 283-286 and 328-331, the call to std.posix.raise
uses @intFromEnum(SignalKind.interrupt) which yields a u8 while raise expects a
c_int; update both calls to cast the enum value to c_int (e.g., use
@intCast(std.os.c_int, @intFromEnum(SignalKind.interrupt))) so raise receives
the correct C integer type.

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