Skip to content

Ev loop wake refactor - #205

Merged
lalinsky merged 3 commits into
scheduler-changesfrom
ev-loop-wake-refactor
Jan 16, 2026
Merged

lalinsky merged 3 commits into
scheduler-changesfrom
ev-loop-wake-refactor

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

No description provided.

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

coderabbitai Bot commented Jan 16, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

Refactored 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

Cohort / File(s) Summary
Backend wake implementations
src/ev/backends/epoll.zig, src/ev/backends/io_uring.zig, src/ev/backends/iocp.zig, src/ev/backends/kqueue.zig, src/ev/backends/poll.zig
All backends updated: wake() now accepts state: *LoopState parameter. Epoll uses eventfd registration with epoll_ctl. io_uring replaces eventfd with futex-based FUTEX_WAIT/WAKE logic. iocp adds logging. kqueue consolidates UserEventWaker/FdWaker into single waker_ident. Poll splits Waker into waker_read_fd/waker_write_fd with platform-specific setup (socket pair on Windows, pipe on POSIX). All remove public Waker types.
Loop state and wake coordination
src/ev/loop.zig
Migrated wake_requested and wake flags (wake_loop, wake_async) from Loop to LoopState. Updated wake() and wakeAsync() to set flags on state and pass state reference to backend. Removed wakeFromAnywhere.
Test removal
src/ev/tests.zig
Removed "Loop: wakeFromAnywhere - cross-thread" test case.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • PR #170: Implements user-mode Futex and Runtime.futex_table that io_uring backend's new futex-based FUTEX_WAIT/WAKE calls depend on.
  • PR #136: Also modifies backend wake() signatures and LoopState wake mechanism coordination, directly overlapping with state-passing changes here.

Poem

Wakers shed their abstract skin,
Each OS whispers what lies within—
Futex, eventfd, socket pair,
State flows through the loop with care. ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description check ⚠️ Warning No pull request description was provided by the author; the description field is empty. Add a description explaining the motivation, implementation approach, and impact of the wake mechanism refactor.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Ev loop wake refactor' directly matches the changeset, which refactors the event loop's wake mechanism across all backends.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch ev-loop-wake-refactor

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@lalinsky

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jan 16, 2026

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6fded14 and 58e9a9c.

📒 Files selected for processing (7)
  • src/ev/backends/epoll.zig
  • src/ev/backends/io_uring.zig
  • src/ev/backends/iocp.zig
  • src/ev/backends/kqueue.zig
  • src/ev/backends/poll.zig
  • src/ev/loop.zig
  • src/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.zig
  • src/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.zig
  • src/ev/backends/io_uring.zig
  • src/ev/backends/poll.zig
  • src/ev/loop.zig
  • src/ev/backends/kqueue.zig
  • src/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.zig
  • src/ev/backends/io_uring.zig
  • src/ev/backends/poll.zig
  • src/ev/loop.zig
  • src/ev/backends/kqueue.zig
  • src/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 _ = state is 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_requested to LoopState with u32 type enables futex-based waking on io_uring (futex requires 32-bit alignment). The bitmask approach with wake_loop and wake_async flags lets you distinguish wake sources without multiple atomics.


292-302: The coalescing logic is correct.

When fetchOr returns 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 when tick() does swap(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.raw access assumes std.atomic.Value(u32) exposes a .raw field - 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 between Loop.tick()'s swap(0) and io_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_write and eventfd_read functions in src/os/eventfd.zig call std.debug.panic() for any error other than WouldBlock. Since the waker is created with EFD.NONBLOCK, the only error reaching the catch {} is WouldBlock—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.

Comment on lines +186 to 203
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,
};
}

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 | 🟡 Minor

🧩 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 -20

Repository: 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 -20

Repository: 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 -20

Repository: 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.md

Repository: 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.zig

Repository: 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.zig

Repository: lalinsky/zio

Length of output: 1535


🏁 Script executed:

# Check if there's a minimum Zig or system requirement documented
cat README.md | head -100

Repository: 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 -20

Repository: 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.

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