Repository navigation
Add cross-platform signal handling API - #67
Conversation
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
|
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 We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (1)
WalkthroughThis 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
Sequence DiagramsequenceDiagram
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)
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
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
examples/signal_demo.zig (1)
53-63: Optional: avoid polling with fixed sleepConsider 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
📒 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 goodsignal-demo is wired like other examples; no build issues spotted.
src/zio.zig (1)
34-36: Re-exports are correctPublic surface matches the new module; no issues.
vendor/libxev/src/backend/kqueue.zig (1)
828-831: Kqueue signal op wiring looks consistentStart, 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 runtimeThe verification confirms that
set()explicitly discards itsruntimeparameter 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 switchingThe
runIofunction atsrc/io/base.zig:48uses 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 atsrc/signal.zig:157is safe: ifxev.Result.signaldoesn'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.
| self.fd = try std.posix.signalfd(-1, &mask, std.posix.SOCK.CLOEXEC | std.posix.SOCK.NONBLOCK); | ||
| } |
There was a problem hiding this comment.
🛠️ 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.
| 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.
|
@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 finished @lalinsky's task —— View job Unix Signal Masking Refcount Design PlanHere's a detailed design for implementing reference-counted signal masking for Unix platforms (Linux and macOS/BSD). OverviewCurrently, both
The solution is to add a global reference counting registry similar to Windows's Proposed Design1. Global State StructureAdd a new 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:
2. Init Path ChangesIn Key points:
3. Deinit Path ChangesIn Key points:
4. Thread Safety ConsiderationsTwo-level locking strategy:
Lock ordering: Always acquire instance mutex first, then global mutex (if both are needed). 5. Error HandlingDuring initialization (
During deinitialization (
6. Integration PointsFor LinuxImpl:
For KqueueImpl:
7. Edge Cases
8. Testing ConsiderationsUnit tests should verify:
Testing approach:
SummaryThis design provides:
Implementation effort: ~50-80 lines of new code, ~20 lines of modifications to existing init/deinit paths. Checklist
|
|
@claude implement it, don't bother with testing |
|
Claude finished @lalinsky's task —— View job Implementing Unix Signal Masking RefcountChecklist
SummarySuccessfully implemented the Unix signal masking refcount design. The implementation adds a global Key Features:
Changes Made:
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 |
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]>
There was a problem hiding this comment.
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.CLOEXECandSOCK.NONBLOCKmay have the same numeric values as the signalfd flags on Linux, using the correctSFD.*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
SetConsoleCtrlHandlerfails, 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.sigprocmaskduring 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_allocatorfor thehandlersarray means allocations persist for the process lifetime. While handlers are removed onunregister, 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
📒 Files selected for processing (1)
src/signal.zig(1 hunks)
🔇 Additional comments (5)
src/signal.zig (5)
1-13: LGTM!The imports and
SignalTypeenum 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
UnixSignalMaskRegistryfor reference-counted signal masking and properly cleans up indeinit. The lazy initialization pattern is thread-safe.
355-359: Verify Windows event-to-signal mapping matches intent.Line 356 maps both
CTRL_C_EVENTandCTRL_BREAK_EVENTto.int. Typically, Ctrl+Break is distinct from Ctrl+C and might warrant separate handling. Similarly,CTRL_LOGOFF_EVENTandCTRL_SHUTDOWN_EVENT(line 357) are mapped to.termalong withCTRL_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
refAllDeclstest ensures compilation of all declarations.As noted in the PR comments, thorough testing is deferred.
|
@claude investigate macos build failure |
|
Claude finished @lalinsky's task —— View job Claude finished @lalinsky's task macOS Build Failure Investigation & FixSummaryFixed a macOS-specific test failure in Root CauseOn macOS and BSD systems, According to POSIX documentation:
Fix AppliedModified
This ensures thread-safe signal masking behavior on all Unix platforms. Testing
Changes
|
b332c84 to
aa6b9a3
Compare
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.
There was a problem hiding this comment.
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
📒 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 invokeset()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
.signalcompletion operation is fully wired in the kqueue backend. The Operation union includes asignalvariant (vendor/libxev/src/backend/kqueue.zig:1727), the handler exists (line 828), and EVFILT_SIGNAL is correctly used viastd.c.EVFILT.SIGNAL(line 1140). Your code is using a supported and properly implemented feature.
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.
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (3)
examples/signal_demo.zig (1)
57-59: Optionally listen for SIGTERM too.Spawn a second handler for
.terminateso 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
SignalKindOS-agnostic, useposixSigNum(.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
📒 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 beforewaitForIo.Verification confirms both
waitForIocall sites handle completion registration correctly:src/io/base.zig:72uses explicitexecutor.loop.add(), andsrc/signal.zig:231registers viaself.event.wait()which implicitly adds to the loop (line 209 comment confirms this). The code changes are sound.
| fn signalHandlerUnix(signum: c_int) callconv(.c) void { | ||
| for (®istry.handlers) |*entry| { | ||
| const kind = entry.kind.load(.acquire); | ||
| if (kind != NO_SIGNAL and kind == signum) { | ||
| entry.event.notify() catch {}; | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
🧩 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 -80Length 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.zigLength 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.zigLength 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 -100Length of output: 0
🏁 Script executed:
#!/bin/bash
# Check imports and type definitions at the top of signal.zig
head -50 src/signal.zigLength 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 -5Length 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.
There was a problem hiding this comment.
@coderabbitai how is xev.Async.notify() not signal-safe?
There was a problem hiding this comment.
🧩 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?
There was a problem hiding this comment.
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
📒 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)
| // 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; | ||
| } |
There was a problem hiding this comment.
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.
| fn signalHandlerUnix(signum: c_int) callconv(.c) void { | ||
| for (®istry.handlers) |*entry| { | ||
| const kind = entry.kind.load(.acquire); | ||
| if (kind != NO_SIGNAL and kind == signum) { | ||
| entry.event.notify() catch {}; | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
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 (®istry.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.
| fn signalHandlerUnix(signum: c_int) callconv(.c) void { | |
| for (®istry.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 (®istry.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.
🧩 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 -C2Length 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
eventfdwithwrite(), 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.kindand callsnotify()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
| fn sendSignal(r: *Runtime) !void { | ||
| try r.sleep(10); | ||
| try std.posix.raise(@intFromEnum(SignalKind.interrupt)); | ||
| } |
There was a problem hiding this comment.
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.
Summary
Adds a cross-platform Signal API for handling OS signals (SIGINT, SIGTERM) in async applications, enabling graceful shutdown patterns.
zio.Signalwith.int(SIGINT/Ctrl+C) and.term(SIGTERM) supportwait()Platform Implementations
Linux
signalfd()to convert signals into file descriptor eventssigprocmask()to prevent default handler.readoperationmacOS/BSD
EVFILT_SIGNALsupport to libxev's kqueue backendsigprocmask()in application codeWindows
SetConsoleCtrlHandler()to catch console control eventsResetEventto wake waiting coroutines from system threadExample Usage
Test Plan
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 SignalTypebuild.zig- Add signal-demo to examplesSummary by CodeRabbit
New Features
Breaking Changes
Notify.signal(),Notify.broadcast(), andResetEvent.set()no longer require a Runtime parameter