Repository navigation
Add user-mode futex for std.Io compatibility - #170
Conversation
Source: ziglang/zig@c3f2de5 Breaking API changes: - VTable now uses futex primitives (futexWait, futexWaitUncancelable, futexWake) instead of mutex/condition callbacks - Mutex.State changed from enum(usize) to enum(u32) with std.atomic.Value - Condition struct now has state and epoch fields - hostname.lookup now returns error union Requires updating src/stdio.zig to implement new VTable API.
Implement user-mode futex for the zio coroutine runtime, replacing mutex/condition callbacks in std.Io VTable with futex-based primitives. Changes: - Add src/sync/Futex.zig with wait/timedWait/wake APIs - Add futex_table to Runtime for global wait queue management - Update stdio.zig VTable to use futex callbacks - Add recancel() to Awaitable for re-arming cancellation - Fix Group.token to use atomic for Io.Group compatibility - Add tests for Io.Event wait/set
📝 WalkthroughWalkthroughThe PR introduces futex-based synchronization throughout the async runtime, adds explicit cancellation APIs and control points (recancel, swapCancelProtection, checkCancel), redesigns Queue and Event types to be cancellation and closure-aware, refactors Group with atomic token state, and updates DNS/network lookup signatures to propagate errors. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ 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 |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/compat/std/src/Io.zig (1)
1333-1376: Typo in comment at line 1350.Minor nit: "laod" should be "load".
- epoch = cond.epoch.load(.acquire); // `.acquire` to ensure ordered before `state` laod + epoch = cond.epoch.load(.acquire); // `.acquire` to ensure ordered before `state` load
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (12)
src/compat/std/src/Io.zigsrc/compat/std/src/Io/Dir.zigsrc/compat/std/src/Io/File.zigsrc/compat/std/src/Io/net/HostName.zigsrc/compat/std/src/Io/net/test.zigsrc/core/awaitable.zigsrc/core/group.zigsrc/core/task.zigsrc/runtime.zigsrc/stdio.zigsrc/sync/Futex.zigsrc/zio.zig
💤 Files with no reviewable changes (1)
- src/core/task.zig
🧰 Additional context used
📓 Path-based instructions (1)
**/*.zig
📄 CodeRabbit inference engine (CLAUDE.md)
Use
zig envto get the path to the Zig standard library when needed
Files:
src/core/awaitable.zigsrc/zio.zigsrc/compat/std/src/Io/net/test.zigsrc/runtime.zigsrc/compat/std/src/Io/net/HostName.zigsrc/compat/std/src/Io/Dir.zigsrc/stdio.zigsrc/sync/Futex.zigsrc/core/group.zigsrc/compat/std/src/Io.zigsrc/compat/std/src/Io/File.zig
🧠 Learnings (7)
📚 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/core/awaitable.zigsrc/compat/std/src/Io/net/test.zigsrc/stdio.zigsrc/compat/std/src/Io.zig
📚 Learning: 2025-10-15T19:38:44.659Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 47
File: src/sync/Mutex.zig:237-237
Timestamp: 2025-10-15T19:38:44.659Z
Learning: In the `unlock` method of `src/sync/Mutex.zig`, the `runtime` parameter is intentionally retained (marked with `_ = runtime;`) for API consistency and future-proofing, even though it's not currently used in the implementation.
Applied to files:
src/zio.zigsrc/runtime.zigsrc/stdio.zigsrc/sync/Futex.zig
📚 Learning: 2025-10-23T16:17:53.575Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.575Z
Learning: In src/select.zig, the select() function is designed to accept futures either as copyable wrappers (e.g., JoinHandle(T)) by value, or as pointers (e.g., &reset_event) for value-owned types. This is intentional, and users are expected to pass the appropriate form based on the future type.
Applied to files:
src/runtime.zigsrc/compat/std/src/Io.zig
📚 Learning: 2025-10-03T11:09:46.846Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 18
File: src/net.zig:18-25
Timestamp: 2025-10-03T11:09:46.846Z
Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.
Applied to files:
src/runtime.zig
📚 Learning: 2025-10-16T14:33:19.718Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 48
File: src/core/ConcurrentAwaitableList.zig:254-269
Timestamp: 2025-10-16T14:33:19.718Z
Learning: In the zio repository's `src/core/ConcurrentAwaitableList.zig` and `src/core/Awaitable.zig`, the `in_list` field should remain debug-only (conditional compilation with `builtin.mode == .Debug`). Double-removal detection in `ConcurrentAwaitableList.remove()` uses pointer-based checks (comparing `prev`/`next` against `head`/`tail`) rather than relying on a regular `in_list` field.
Applied to files:
src/stdio.zigsrc/sync/Futex.zigsrc/core/group.zig
📚 Learning: 2025-11-30T10:31:31.222Z
Learnt from: CR
Repo: lalinsky/zio PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-30T10:31:31.222Z
Learning: Applies to **/*.zig : Use `zig env` to get the path to the Zig standard library when needed
Applied to files:
src/stdio.zig
📚 Learning: 2025-11-30T10:31:31.222Z
Learnt from: CR
Repo: lalinsky/zio PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-30T10:31:31.222Z
Learning: Applies to build.zig : To test Windows builds on Linux, use `zig build build-tests -Dtarget=x86_64-windows && wine zig-out/bin/test.exe`
Applied to files:
src/stdio.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 (33)
src/compat/std/src/Io/Dir.zig (1)
324-346: Solid error handling fix.The switch from a catch-all swallow to explicit error routing is the right call. Now
makeDirerrors actually propagate instead of getting silently absorbed. The three-way split (PathAlreadyExists→ verify it's a dir,FileNotFound→ walk up the tree, everything else → bail) is clean and handles the edge cases correctly (dangling symlinks, non-directory files at the path).src/core/awaitable.zig (1)
98-119: Solid CAS loop implementation for re-arming cancellation.The pattern mirrors
cancel()and the assert at line 107 provides a clear contract that this should only be called on already-canceled awaitables. The memory ordering is consistent with the rest of the cancellation infrastructure.One edge case to be aware of:
pending_errorsis au16, so theoretically 65535+ recancels would overflow. In practice this is a non-issue since no sane control flow would do that.src/core/group.zig (4)
22-24: Atomic token for thread-safe group state checking.Good change - wrapping
tokeninstd.atomic.Valueallows safe concurrent checks of whether the group has spawned tasks. The.acquireordering on loads pairs correctly with mutation sites.
99-101: Direct .raw access is correct here.Using
token.rawingetTaskList()is the right call - you need the underlying pointer for the ptrCast, and this function is called after the token is known to be non-null (from the caller's perspective).
152-165: Early return optimization and post-condition assertions.The null check on
token.load(.acquire)avoids unnecessary work when no tasks were spawned. The assertions ontoken.raw == nullafter wait/cancel document the invariant that all tasks have completed and been cleaned up.
183-199: Cleaner API - deriving list from group internally.Removing the
listparameter fromgroupWait/groupCanceland having them callgroup.getTaskList()internally reduces the surface area and avoids passing redundant information.src/zio.zig (1)
43-43: Consistent with existing sync primitive exports.The Futex re-export follows the same pattern as other sync primitives. Users can now access it via
@import("zio").Futex.src/compat/std/src/Io/File.zig (1)
422-428: Minor cleanup - removed unused capture.The
|_|discard was unnecessary since the success value fromfileSeekByisn't used. Cleaner this way.src/runtime.zig (3)
863-864: Global futex table in Runtime.The
futex_tablefield provides per-runtime storage for futex wait queues, enabling the user-mode futex implementation to work across executors. Correct placement alongside other runtime-global resources.
876-876: Futex table initialization.Using the runtime's allocator is consistent with how other resources are managed.
930-932: Futex table cleanup in correct order.Cleaning up the futex table after task_pool ensures no tasks are still potentially waiting on futexes when the table is destroyed.
src/compat/std/src/Io/net/test.zig (2)
132-148: Updated to handle new lookup API returning LookupError!void.The
trybeforelookupand the switch onerror.Closed/error.Canceledin the else branch correctly handles the new semantics where:
- Queue closes on completion (Closed = normal termination)
- Cancellation is propagated as an error
163-175: Good handling for offline CI environments.Skipping the test on
UnknownHostNameorNameServerFailuremakes this robust for CI runners without internet. The error propagation for other cases and the Closed/Canceled handling matches the first lookup test.src/sync/Futex.zig (4)
43-55: Clean Table structure for per-runtime futex state.The design is straightforward - mutex protects the map, map keys on address pointers. Using
std.Thread.Mutex(not the coroutine-aware zio Mutex) is correct here since this is infrastructure that the higher-level primitives build on.
71-126: timedWait implementation follows standard futex patterns.Good:
- Fast path at line 73 avoids locking if value already changed
- Double-check under lock at line 92 prevents lost wakeups
.preparing_to_waitstate before queue insertion prevents race with concurrent wake- Timeout handling integrates with the existing Timeout infrastructure
The allocation failure path (lines 98-101) silently returns, which is fine given futex's spurious wakeup contract.
148-175: Wake has a 32-waiter cap per invocation.The
to_wakebuffer is fixed at 32 entries, but ifmax_waiters > 32, only the first 32 will be woken. The caller would need to callwakemultiple times to wake more. This is fine for typical use (usuallymax_waitersis 1 ormaxInt), but worth documenting.The pattern of collecting nodes under lock then waking outside is correct - avoids holding the mutex during potentially expensive task scheduling.
Consider documenting the 32-waiter-per-call limit, or looping internally to handle
max_waiters > 32:🔎 Possible fix to handle large max_waiters
pub fn wake(runtime: *Runtime, ptr: *const u32, max_waiters: u32) void { if (max_waiters == 0) return; const table = &runtime.futex_table; + var remaining = max_waiters; + while (remaining > 0) { // Collect nodes to wake under lock var to_wake: [32]*WaitNode = undefined; var count: u32 = 0; table.mutex.lock(); if (table.map.getPtr(ptr)) |queue| { - while (count < max_waiters and count < 32) { + while (count < remaining and count < 32) { if (queue.pop()) |node| { to_wake[count] = node; count += 1; } else { break; } } // Clean up empty queue entry if (queue.isEmpty()) { _ = table.map.remove(ptr); } } table.mutex.unlock(); + if (count == 0) break; + remaining -= count; + // Wake outside lock to avoid holding lock during resume for (to_wake[0..count]) |node| { node.wake(); } + } }
180-219: Tests cover the basics.The tests verify:
- Basic wait/wake coordination between two tasks
- Spurious wakeup when value already differs
These are good sanity checks. The stress-tested Event tests mentioned in the PR provide additional coverage.
src/compat/std/src/Io/net/HostName.zig (5)
82-85: Simplified LookupResult - end variant removed.Using queue closure (
error.Closed) as the termination signal instead of a dedicated.endvariant is cleaner. The consumer's iteration loop becomes a straightforward while/else pattern.
87-102: lookup now returns errors and documents closure semantics.The updated contract is clear:
- Returns
LookupError!voidto surface lookup failures- Always closes
resolvedbefore return (even on error)- Caller must not close the queue
217-256: connect handles the new queue-based error flow well.The
ip_connect_errortracking (line 230, 245) captures the last connection-level error so that if all addresses fail, you get something meaningful back. Theerror.Closedbranch (lines 249-255) correctly awaits the lookup future to surface any DNS errors before falling back.The cleanup in defer (lines 221-228) properly drains and closes any leftover connections.
265-296: connectMany with deferred close and proper future management.Good structure:
defer results.close(io)at line 272 ensures closure regardless of exit pathlookup_futureis explicitly managed withdefer lookup_future.cancel(io)- The group waits for in-flight connections before returning lookup errors
307-319: enqueueConnectionFallible handles cancellation and prevents connection leaks.Line 314's
errdefercloses the stream ifputOnefails - this prevents leaking the connection. Theerror.Closed => unreachableat line 316 documents the contract that the queue must remain open during this call.src/stdio.zig (5)
189-203: Looks good - group wait/cancel correctly handle void return and swallow Canceled.The pattern of eating
CanceledingroupWaitis correct sinceIo.Group.waitreturns void. The cancellation still propagates to group tasks internally, which is the right behavior.
236-250: Timeout-to-cancellation mapping is a reasonable design choice.The conversion from
error.Timeouttoerror.Canceled(line 247) aligns with howIotreats timeout expiration as a form of cancellation. Thei96tou64cast on line 243 is safe in practice since no sane timeout exceeds 584 years, though a@minwithmaxInt(u64)would make it bulletproof.
252-261: Shield pattern correctly prevents cancellation during uncancelable wait.The
beginShield/endShieldwrapping ensures the futex wait cannot be canceled, making theunreachableon line 259 a valid assertion.
765-809: Queue closure semantics are correct - producer closes, not consumer.The
defer queue.close(io)at line 768 ensures the queue is closed whether lookup succeeds or fails, and theunreachableonerror.Closedis justified since this function is the sole closer. Clean design.
1697-1751: Event tests cover both wait-before-set and set-before-wait scenarios.Good coverage of the two main use cases. The stress testing mentioned in the PR summary (20× runs) gives confidence in the implementation.
src/compat/std/src/Io.zig (6)
1231-1303: Three-state mutex is a classic optimization - looks correct.The
locked_once/contendeddistinction avoids futex wake syscalls when there's no contention. The acquire/release ordering is appropriate for the critical section boundaries.
1048-1101: Cancellation control APIs are well-documented and provide clear semantics.The
recancel,CancelProtection, andcheckCancelAPIs form a coherent cancellation model. The docstrings explain the intended usage patterns clearly, especially theswapCancelProtectionexample showing the defer pattern.
1562-1580:closecorrectly wakes all blocked waiters.Both getters and putters are signaled when the queue is closed, ensuring no threads remain blocked indefinitely. The lock protects the state transition.
1614-1684: QueueputLockedhandles partial transfer on cancellation correctly.The use of
recancel()at line 1673 when some elements were added before cancellation is the right approach - it reports the partial success and re-arms for the next cancellation point. This prevents data loss while maintaining cancellation semantics.
948-1046: Atomic token access for Group is correct.Using
std.atomic.Value(?*anyopaque)fortokenand loading with.acquireordering (lines 1026, 1042) provides the necessary synchronization with concurrentasync/concurrentcalls. The raw access in the assert is safe since it's after the implementation call completes and the function is documented as not threadsafe.
1193-1229: Futex helper functions provide type-safe wrappers.The compile-time assertions on
@sizeOf(T) == 4catch misuse early. The early return infutexWakewhenmax_waiters == 0is a good optimization.
Summary
recancel()to Awaitable for re-arming cancellation after acknowledgmentChanges
src/sync/Futex.zig: New file with wait/timedWait/wake APIs mirroringstd.Thread.Futexsrc/runtime.zig: Add futex_table to Runtimesrc/stdio.zig: Update VTable to use futex callbacks instead of mutex/conditionsrc/core/awaitable.zig: Add recancel() methodsrc/core/group.zig: Fix token field type for Io.Group compatibilityTest plan