Repository navigation
Ev loop wake refactor - #205
Conversation
- Remove wakeFromAnywhere (will be re-added differently for signals later) - Inline Waker structs directly into each backend - Remove FdWaker from kqueue (was only for signal-safe wakeups)
- Replace eventfd + POLL_ADD with FUTEX_WAIT on wake_requested atomic - Move wake_requested to LoopState, change from u8 to u32 for futex alignment - Update backend.wake() signature to take *LoopState - wake() does futex_wake syscall directly, no fd overhead
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the 📝 WalkthroughWalkthroughRefactored the waker mechanism across all event loop backends, replacing abstraction-based Waker structs with OS-level mechanisms (eventfd, futex, EVFILT_USER, socket pairs) and centralizing wake state management in LoopState. The wake() method signature was updated throughout to accept a LoopState parameter for state tracking. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches🧪 Generate unit tests (beta)
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 |
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@src/ev/backends/io_uring.zig`:
- Around line 186-203: The prepFutexWait function unconditionally uses the
IORING_OP_FUTEX_WAIT opcode (FUTEX_WAIT) which requires Linux kernel 6.7+, but
there's no documentation or runtime guard; add a clear runtime capability check
and/or documentation: detect kernel/io_uring feature support at startup (e.g.,
during io_uring setup) and error with a helpful message if FUTEX_WAIT is
unavailable, or implement a fallback that uses an alternative futex mechanism
when FUTEX_WAIT is not present; update README to note the minimum kernel
requirement if you choose to require 6.7+. Ensure you reference prepFutexWait,
the FUTEX_WAIT opcode and FUTEX_BITSET_MATCH_ANY when adding the check and the
error message so the failure points are obvious.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
src/ev/backends/epoll.zigsrc/ev/backends/io_uring.zigsrc/ev/backends/iocp.zigsrc/ev/backends/kqueue.zigsrc/ev/backends/poll.zigsrc/ev/loop.zigsrc/ev/tests.zig
💤 Files with no reviewable changes (1)
- src/ev/tests.zig
🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/runtime/blocking_task.zig:117-146
Timestamp: 2026-01-10T13:55:09.718Z
Learning: zio no longer uses libxev. It has its own custom event loop implementation in src/ev/ that provides a callback-based async I/O event loop similar to libuv or libxev.
📚 Learning: 2026-01-07T13:15:48.677Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 179
File: src/os/windows.zig:424-424
Timestamp: 2026-01-07T13:15:48.677Z
Learning: In `src/os/windows.zig`, WSABUF must be re-exported from `std.os.windows.ws2_32.WSABUF` rather than defined locally because it needs to satisfy `std.Io.Reader` compatibility requirements.
Applied to files:
src/ev/backends/iocp.zigsrc/ev/backends/poll.zig
📚 Learning: 2026-01-10T13:55:00.163Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/runtime/blocking_task.zig:117-146
Timestamp: 2026-01-10T13:55:00.163Z
Learning: In Zig files, do not reference libxev for async I/O. The project uses a custom event loop implementation under src/ev/ and a callback-based async I/O loop similar to libuv/libxev. Reviewers should ensure code relies on the src/ev event loop and that there are no libxev usage patterns; prefer the central event loop in src/ev/ for all asynchronous operations.
Applied to files:
src/ev/backends/iocp.zigsrc/ev/backends/io_uring.zigsrc/ev/backends/poll.zigsrc/ev/loop.zigsrc/ev/backends/kqueue.zigsrc/ev/backends/epoll.zig
📚 Learning: 2026-01-10T14:08:37.019Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/stdio.zig:117-129
Timestamp: 2026-01-10T14:08:37.019Z
Learning: In Zig files implementing swap-like semantics (e.g., old = swap(new); defer swap(old)), ensure the return value is an opaque restoration token rather than a direct reflection of internal state. Rely on the contract to perform increment/decrement logic internally (e.g., shield_count) and not expose internal state through the token. This makes behavior predictable, supports refactoring, and avoids leaking internal state across calls. Apply this pattern broadly to Zig code that uses a paired-swap or restoration-token mechanism.
Applied to files:
src/ev/backends/iocp.zigsrc/ev/backends/io_uring.zigsrc/ev/backends/poll.zigsrc/ev/loop.zigsrc/ev/backends/kqueue.zigsrc/ev/backends/epoll.zig
📚 Learning: 2025-10-10T05:59:17.087Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 41
File: src/udp.zig:79-82
Timestamp: 2025-10-10T05:59:17.087Z
Learning: In UDP socket operations (src/udp.zig), error.Canceled from result_data.result represents OS/IO-level cancellation (e.g., io_uring), not user-requested cancellation. User cancellation is handled by waitForXevCompletion() via try. OS-level error.Canceled should be mapped to error.Unexpected as it represents an unexpected system event.
Applied to files:
src/ev/backends/io_uring.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 (19)
src/ev/backends/iocp.zig (1)
320-329: LGTM - Signature update aligns with the unified wake API.The
_ = stateis fine here since IOCP's wake mechanism (QueueUserAPC) doesn't need the LoopState. The added debug logging on success is helpful for tracing wake behavior.src/ev/loop.zig (3)
112-126: Clean centralization of wake state management.Moving
wake_requestedtoLoopStatewithu32type enables futex-based waking on io_uring (futex requires 32-bit alignment). The bitmask approach withwake_loopandwake_asyncflags lets you distinguish wake sources without multiple atomics.
292-302: The coalescing logic is correct.When
fetchOrreturns 0, no wake was pending so we need to signal the backend. When it returns non-zero, a wake is already in flight - the existing pending wake will see all accumulated flags whentick()doesswap(0).
724-730: Wake flag consumption pattern is solid.Swap-before-poll ensures wake signals that arrive during poll setup aren't lost. The zero timeout when flags are set avoids unnecessary blocking. Good stuff.
src/ev/backends/io_uring.zig (3)
160-169: Direct futex wake - no fd overhead.The futex approach eliminates the eventfd and its poll registration. Just atomic store + futex_wake syscall. The
wake_requested.rawaccess assumesstd.atomic.Value(u32)exposes a.rawfield - that's correct for Zig's atomic implementation.
171-184: Rearm/drain cycle is clean.One FUTEX_WAIT in flight at a time. Drain marks for rearm, poll() resubmits before blocking. No race window where wakes are missed.
768-813: Integration handles the race correctly.If
wake()fires betweenLoop.tick()'sswap(0)andio_uring_enter, the FUTEX_WAIT completes immediately (value != expected). No missed wakes.src/ev/backends/kqueue.zig (3)
89-105: Using self pointer as waker_ident is a nice trick.Guaranteed unique, no allocation needed. EVFILT_USER with EV_CLEAR handles the drain automatically - simpler than the previous dual-waker setup.
136-147: Wake implementation is straightforward.NOTE_TRIGGER on EVFILT_USER does the job. Ignoring the return is acceptable - worst case is the loop doesn't wake early, timeout still works.
388-392: Event filtering is correct.EV_CLEAR already handled the drain, so just skip the waker event. Clean.
src/ev/backends/poll.zig (5)
76-90: Platform-specific wake fd setup looks correct.Windows needs sockets for WSAPoll compatibility, POSIX gets pipes. The errdefer cleanup pattern handles partial init failures properly.
120-131: Classic self-pipe wake pattern.Write one byte, read end sees POLLIN. Ignoring errors is correct - EWOULDBLOCK means buffer is full (wake already pending), other errors are non-fatal.
133-144: Drain buffer size is adequate.64 bytes handles typical wake coalescing. If there's more (unlikely - would need 64+ consecutive wakes before drain), next poll iteration catches it. No problem.
106-118: Cleanup is thorough.Linear search for waker fd is fine at shutdown. Close order doesn't matter during teardown.
441-445: Waker detection and drain is correct.Drain on sight, move on. Simple and effective.
src/ev/backends/epoll.zig (4)
82-99: Eventfd setup + epoll registration looks good.
Clean init flow with proper error handling and registration.
110-113: Cleanup of waker fd is correct.
Deregister + close path looks fine.
437-439: Wake fd handling in poll loop is correct.
Drain + continue keeps the loop clean.
121-128: The error handling here is actually correct—unexpected errors already panic.The
eventfd_writeandeventfd_readfunctions insrc/os/eventfd.zigcallstd.debug.panic()for any error other thanWouldBlock. Since the waker is created withEFD.NONBLOCK, the only error reaching thecatch {}isWouldBlock—which correctly means "already signaled" (write) or "no data to read" (drain). Silently ignoring it is intentional.If you want to explicitly document this behavior, you could switch on the error, but there's no hidden failure risk here.
Likely an incorrect or invalid review comment.
✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.
| fn prepFutexWait(sqe: *linux.io_uring_sqe, futex: *const u32, expected: u64) void { | ||
| sqe.* = .{ | ||
| .opcode = .FUTEX_WAIT, | ||
| .flags = 0, | ||
| .ioprio = 0, | ||
| .fd = @bitCast(linux.FUTEX2_FLAGS{ .size = .U32, .private = true }), | ||
| .off = expected, | ||
| .addr = @intFromPtr(futex), | ||
| .len = 0, | ||
| .rw_flags = 0, | ||
| .user_data = 0, | ||
| .buf_index = 0, | ||
| .personality = 0, | ||
| .splice_fd_in = 0, | ||
| .addr3 = FUTEX_BITSET_MATCH_ANY, | ||
| .resv = 0, | ||
| }; | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
IORING_OP_FUTEX_WAIT Linux kernel version when added
💡 Result:
IORING_OP_FUTEX_WAIT was added as part of the io_uring futex patchset merged into mainline for the 6.7 development cycle — the 6.7 release (final) on 7 January 2024. [1][2]
Sources:
- Patchset adding IORING_OP_FUTEX_WAIT (io_uring futex/wake/wait). [1]
- Linux 6.7 release timing (final 6.7 on 7 Jan 2024). [2]
🏁 Script executed:
# Search for any kernel version checks or documentation in the codebase
rg -i "futex|kernel.*version|6\.[0-9]" --type zig src/ev/backends/io_uring.zig | head -20Repository: lalinsky/zio
Length of output: 712
🏁 Script executed:
# Look for version guards or compatibility notes elsewhere in the codebase
find . -type f -name "*.zig" -o -name "*.md" | head -20Repository: lalinsky/zio
Length of output: 487
🏁 Script executed:
# Check if there's any existing version checking or build config
rg -i "target_os|version|6\.7" --type zig | head -20Repository: lalinsky/zio
Length of output: 1655
🏁 Script executed:
# Check documentation files for kernel version or FUTEX mentions
rg -i "kernel|6\.7|futex|version.*requirement" docs/ README.mdRepository: lalinsky/zio
Length of output: 38
🏁 Script executed:
# Check if there are any runtime kernel checks or version probes in the codebase
rg -i "kernel.*version|uname|probe" --type zig src/Repository: lalinsky/zio
Length of output: 138
🏁 Script executed:
# Look at the broader context around io_uring usage and whether version checks exist
head -50 src/ev/backends/io_uring.zigRepository: lalinsky/zio
Length of output: 2660
🏁 Script executed:
# Search for any comments or context around FUTEX_WAIT usage
rg -B5 -A5 "FUTEX_WAIT" --type zig src/ev/backends/io_uring.zigRepository: lalinsky/zio
Length of output: 1535
🏁 Script executed:
# Check if there's a minimum Zig or system requirement documented
cat README.md | head -100Repository: lalinsky/zio
Length of output: 3985
🏁 Script executed:
# Look for any build configuration or feature detection
rg -i "build|feature|detect" --type zig build.zig 2>/dev/null | head -20Repository: lalinsky/zio
Length of output: 333
Document or guard Linux 6.7+ kernel requirement for FUTEX_WAIT.
The code unconditionally uses IORING_OP_FUTEX_WAIT (added in Linux 6.7), but this requirement isn't documented in the README or checked at runtime. Users on older kernels will hit a runtime failure with no clear error message. Either document the minimum kernel version in README, add a runtime check with a helpful error, or implement a fallback for older kernels if broader compatibility is needed.
🤖 Prompt for AI Agents
In `@src/ev/backends/io_uring.zig` around lines 186 - 203, The prepFutexWait
function unconditionally uses the IORING_OP_FUTEX_WAIT opcode (FUTEX_WAIT) which
requires Linux kernel 6.7+, but there's no documentation or runtime guard; add a
clear runtime capability check and/or documentation: detect kernel/io_uring
feature support at startup (e.g., during io_uring setup) and error with a
helpful message if FUTEX_WAIT is unavailable, or implement a fallback that uses
an alternative futex mechanism when FUTEX_WAIT is not present; update README to
note the minimum kernel requirement if you choose to require 6.7+. Ensure you
reference prepFutexWait, the FUTEX_WAIT opcode and FUTEX_BITSET_MATCH_ANY when
adding the check and the error message so the failure points are obvious.
No description provided.