Skip to content

Add user-mode futex for std.Io compatibility - #170

Merged
lalinsky merged 4 commits into
mainfrom
user-mode-futex
Dec 28, 2025
Merged

lalinsky merged 4 commits into
mainfrom
user-mode-futex

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Summary

  • Implement user-mode futex for the zio coroutine runtime
  • Replace mutex/condition callbacks in std.Io VTable with futex-based primitives
  • Add recancel() to Awaitable for re-arming cancellation after acknowledgment
  • Fix Group.token to use atomic for Io.Group compatibility
  • Add tests for Io.Event wait/set

Changes

  • src/sync/Futex.zig: New file with wait/timedWait/wake APIs mirroring std.Thread.Futex
  • src/runtime.zig: Add futex_table to Runtime
  • src/stdio.zig: Update VTable to use futex callbacks instead of mutex/condition
  • src/core/awaitable.zig: Add recancel() method
  • src/core/group.zig: Fix token field type for Io.Group compatibility

Test plan

  • All 199 existing tests pass
  • New Io.Event wait/set test
  • New Io.Event set before wait test
  • Stress tested Event tests 20x without failure

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

coderabbitai Bot commented Dec 27, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The 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

Cohort / File(s) Summary
Core async primitives
src/core/awaitable.zig, src/core/group.zig, src/core/task.zig
Added recancel method to Awaitable. Refactored Group to use atomic token, renamed groupWait/groupCancel signatures, updated wait/cancel to load atomic token and assert null after completion. Removed trailing whitespace in task.zig.
Runtime infrastructure
src/runtime.zig, src/zio.zig
Added futex_table: Futex.Table field to Runtime struct with init/deinit lifecycle. Re-exported Futex module.
Synchronization (new)
src/sync/Futex.zig
Introduced full futex implementation with Table struct, wait/timedWait/wake functions supporting cancellation and timeout. Uses per-address wait queues and atomic ptr checks.
I/O system overhaul
src/compat/std/src/Io.zig
Massive refactor: added recancel, swapCancelProtection, checkCancel to VTable. Replaced mutex/condition callbacks with futexWait/futexWaitUncancelable/futexWake. Added CancelProtection enum, redesigned Queue with close/closed state and cancellation-aware put/get returning Cancelable!usize or QueueClosedError. Introduced Event type with atomic state. Reworked Mutex/Condition internals to use atomic state and futex waits.
File operations
src/compat/std/src/Io/Dir.zig, src/compat/std/src/Io/File.zig
Removed error-catch swallow in makeDir call (error propagation). Changed seekBy success-path pattern from discard binding to direct block execution.
Network/DNS
src/compat/std/src/Io/net/HostName.zig, src/compat/std/src/Io/net/test.zig
Changed lookup/connectMany return type to LookupError!void. Removed ConnectManyResult union; now use IpAddress.ConnectError!Stream directly. Removed end variant from LookupResult. Updated test error handling from end-callbacks to explicit error switches with Closed/Canceled branches.
Runtime integration
src/stdio.zig
Replaced Mutex/Condition imports with Futex. Updated VTable entries to futex callbacks and added recancel/swapCancelProtection/checkCancel. Refactored groupWait/groupCancel token handling and removed CompactWaitQueue token parameters. Updated netLookupImpl signature to return LookupError!void; added error handling for queue put calls. Updated test initializers for Condition/Mutex.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • PR #167: Directly modifies the same compat/std Io implementation; this PR extends that backport with futex-based synchronization and cancellation-aware APIs.
  • PR #154: Modifies identical Group APIs, token handling, and groupWait/groupCancel semantics; overlapping structural changes to Group initialization and cancellation flow.
  • PR #144: Implements the original std.Io runtime-backed layer (stdio.zig) that this PR now replaces with futex-based wait/wake and adds cancellation control methods to the VTable.

Poem

Futex threads now dance in harmony,
Cancellation points bloom free,
Queues that close and errors rise,
Atomic tokens synchronize—
No more condition, mutex sleeps,
Just futex tables, promises to keep. 🔄

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change—implementing user-mode futex for std.Io compatibility—which is the core objective reflected throughout the PR summary and code changes.
Description check ✅ Passed The description is directly related to the changeset, outlining the key modifications (futex implementation, VTable updates, atomic token fixes, recancel method) and providing concrete test results.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch user-mode-futex

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

📥 Commits

Reviewing files that changed from the base of the PR and between 55f2e53 and dced856.

📒 Files selected for processing (12)
  • src/compat/std/src/Io.zig
  • src/compat/std/src/Io/Dir.zig
  • src/compat/std/src/Io/File.zig
  • src/compat/std/src/Io/net/HostName.zig
  • src/compat/std/src/Io/net/test.zig
  • src/core/awaitable.zig
  • src/core/group.zig
  • src/core/task.zig
  • src/runtime.zig
  • src/stdio.zig
  • src/sync/Futex.zig
  • src/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 env to get the path to the Zig standard library when needed

Files:

  • src/core/awaitable.zig
  • src/zio.zig
  • src/compat/std/src/Io/net/test.zig
  • src/runtime.zig
  • src/compat/std/src/Io/net/HostName.zig
  • src/compat/std/src/Io/Dir.zig
  • src/stdio.zig
  • src/sync/Futex.zig
  • src/core/group.zig
  • src/compat/std/src/Io.zig
  • src/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.zig
  • src/compat/std/src/Io/net/test.zig
  • src/stdio.zig
  • src/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.zig
  • src/runtime.zig
  • src/stdio.zig
  • src/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.zig
  • src/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.zig
  • src/sync/Futex.zig
  • src/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 makeDir errors 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_errors is a u16, 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 token in std.atomic.Value allows safe concurrent checks of whether the group has spawned tasks. The .acquire ordering on loads pairs correctly with mutation sites.


99-101: Direct .raw access is correct here.

Using token.raw in getTaskList() 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 on token.raw == null after 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 list parameter from groupWait/groupCancel and having them call group.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 from fileSeekBy isn't used. Cleaner this way.

src/runtime.zig (3)

863-864: Global futex table in Runtime.

The futex_table field 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 try before lookup and the switch on error.Closed/error.Canceled in 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 UnknownHostName or NameServerFailure makes 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_wait state 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_wake buffer is fixed at 32 entries, but if max_waiters > 32, only the first 32 will be woken. The caller would need to call wake multiple times to wake more. This is fine for typical use (usually max_waiters is 1 or maxInt), 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:

  1. Basic wait/wake coordination between two tasks
  2. 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 .end variant 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!void to surface lookup failures
  • Always closes resolved before return (even on error)
  • Caller must not close the queue

217-256: connect handles the new queue-based error flow well.

The ip_connect_error tracking (line 230, 245) captures the last connection-level error so that if all addresses fail, you get something meaningful back. The error.Closed branch (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 path
  • lookup_future is explicitly managed with defer 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 errdefer closes the stream if putOne fails - this prevents leaking the connection. The error.Closed => unreachable at 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 Canceled in groupWait is correct since Io.Group.wait returns 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.Timeout to error.Canceled (line 247) aligns with how Io treats timeout expiration as a form of cancellation. The i96 to u64 cast on line 243 is safe in practice since no sane timeout exceeds 584 years, though a @min with maxInt(u64) would make it bulletproof.


252-261: Shield pattern correctly prevents cancellation during uncancelable wait.

The beginShield/endShield wrapping ensures the futex wait cannot be canceled, making the unreachable on 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 the unreachable on error.Closed is 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/contended distinction 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, and checkCancel APIs form a coherent cancellation model. The docstrings explain the intended usage patterns clearly, especially the swapCancelProtection example showing the defer pattern.


1562-1580: close correctly 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: Queue putLocked handles 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) for token and loading with .acquire ordering (lines 1026, 1042) provides the necessary synchronization with concurrent async/concurrent calls. 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) == 4 catch misuse early. The early return in futexWake when max_waiters == 0 is a good optimization.

Comment thread src/compat/std/src/Io.zig Resolved
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