Skip to content

Extract awaitable structures and improve concurrent primitives - #48

Merged
lalinsky merged 8 commits into
mainfrom
refactor/rename-extract-awaitable-structures
Oct 16, 2025
Merged

lalinsky merged 8 commits into
mainfrom
refactor/rename-extract-awaitable-structures

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 16, 2025 •

Copy link
Copy Markdown
Owner

Summary

Refactors runtime internals by extracting awaitable data structures into separate, well-documented modules and improving concurrent task management primitives.

Changes

New Core Data Structures (src/core/):

  • Awaitable.zig - Base type for all awaitable objects (tasks, futures, etc.) with reference counting and cancellation support
  • AwaitableList.zig - Non-concurrent doubly-linked list with O(1) operations
  • ConcurrentAwaitableList.zig - Thread-safe FIFO list using tagged pointers with mutation spinlock
    • Supports two sentinel states for encoding additional information (e.g., locked/unlocked)
    • O(1) concurrent push/pop/remove operations
  • ConcurrentAwaitableStack.zig - Lock-free stack for cross-thread communication
  • SimpleAwaitableStack.zig - Single-threaded LIFO stack

Runtime Improvements (runtime.zig):

  • New centralized resumeTask() function with compile-time optimized resume modes (.local vs .remote)
  • Cross-thread task resumption support via remote ready queues
  • Fixed race conditions in concurrent list management
  • Made in_list field debug-only to reduce memory overhead

Other Changes:

  • Updated file I/O callbacks to use new resumeTask() API
  • Added comprehensive tests for double-removal scenarios and concurrent operations

Benefits

  • Better separation of concerns with modular data structures
  • Improved documentation for concurrent primitives
  • More efficient cross-thread task communication
  • Reduced memory overhead in release builds

Summary by CodeRabbit

  • New Features

    • Added support for cross-thread task resumption with improved concurrency handling.
  • Refactor

    • Optimized task scheduling and wakeup mechanisms for enhanced performance.
    • Improved internal concurrent data structures for better thread safety.

- Rename AwaitableList to SimpleAwaitableList for clarity
- Rename AwaitableStack to ConcurrentAwaitableStack for consistency
- Extract SimpleAwaitableStack to src/core/SimpleAwaitableStack.zig
- Extract ConcurrentAwaitableStack to src/core/ConcurrentAwaitableStack.zig
- Update all references throughout the codebase

Naming convention now consistently distinguishes thread-safe (Concurrent*)
from non-thread-safe (Simple*) data structures.
Extracted Awaitable.markComplete() into a standalone markComplete() function
and added a new polymorphic resumeTask() helper to simplify task resumption.

The resumeTask() function accepts *Awaitable, *AnyTask, or *Coroutine,
providing a unified interface for marking coroutines as ready throughout
the codebase.

Replaced all calls to Executor.fromCoroutine().markReady() with the new
resumeTask() helper across sync primitives (Mutex, Condition, ResetEvent)
and I/O modules (TCP, UDP, File), significantly reducing code duplication
and improving readability.
- Add thread-local current_executor tracking in Runtime
- Add remote ready queue (next_ready_queue_remote) for cross-thread tasks
- Add xev.Async infrastructure for cross-thread notifications
- Modify markReady() to detect executor thread and route appropriately:
  - Same thread: fast path to local ready_queue
  - Different thread: push to remote queue and notify via async
- Initialize remote infrastructure in run() to allow proper error handling
- Clean up remote async in deinit()

This enables tasks to be safely resumed from different executor threads
using lock-free data structures and async notifications, with zero
overhead for the common same-thread case.
Add ResumeMode enum to control cross-thread checking in task resumption:
- `.local`: Skips executor check (IO callbacks always on same thread)
- `.maybe_remote`: Checks executor, uses remote queue if different

IO callbacks (tcp, udp, file, timers) use `.local` for fast path.
Sync primitives (Mutex, Condition, ResetEvent) use `.maybe_remote`
since waiters can belong to different executors.

This eliminates unnecessary thread-local checks in the hot path for
all IO operations.
@coderabbitai

coderabbitai Bot commented Oct 16, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Renames AwaitableList→SimpleAwaitableList, adds Simple/Concurrent awaitable stacks, makes ConcurrentAwaitableList mutation methods accept nullable executor, introduces Awaitable/AwaitableKind and cross-thread resume primitives (resumeTask, ResumeMode), and replaces executor-based markReady calls with resumeTask across runtime, I/O, and sync primitives.

Changes

Cohort / File(s) Change Summary
Awaitable core
src/core/Awaitable.zig
New public Awaitable struct and AwaitableKind enum; adds atomic state, cancellation flag, waiting_list, ref_count, destroy function pointer, and requestCancellation() API; alignment check enforced.
List rename
src/core/AwaitableList.zig
Type renamed AwaitableList → SimpleAwaitableList; public APIs (push, pop, concatByMoving, remove) updated to *SimpleAwaitableList; remove now returns bool with explicit membership validation; tests added/updated.
Concurrent list (nullable executor)
src/core/ConcurrentAwaitableList.zig
Mutation methods accept executor: ?*Executor (acquireMutationLock, push, pop, remove, popOrTransition); null-executor path spins without yielding; debug assertions adjusted; double-remove test added.
New concurrent stack
src/core/ConcurrentAwaitableStack.zig
Added lock-free intrusive stack with atomic head; public push(self:*ConcurrentAwaitableStack, item:*Awaitable) and popAll(self:*ConcurrentAwaitableStack) SimpleAwaitableStack.
New single-thread stack
src/core/SimpleAwaitableStack.zig
Added SimpleAwaitableStack (singly-linked LIFO) with push, pop, and prependByMoving; retains debug in_list handling.
Runtime / scheduling
src/runtime.zig
Introduced ResumeMode enum and resumeTask helper; added waitForComplete/timedWaitForComplete/markComplete; updated markReady signature to accept ResumeMode; added thread-local current_executor, remote-ready ConcurrentAwaitableStack queues and remote wake/completion plumbing; re-exports for list/stack types.
I/O completion callbacks
src/file.zig, src/tcp.zig, src/udp.zig
Replaced Executor.fromCoroutine(...).markReady(...) with resumeTask(..., .local) in completion callbacks; added resumeTask imports; semantics otherwise unchanged.
Sync primitives
src/sync/Condition.zig, src/sync/Mutex.zig, src/sync/ResetEvent.zig
Replaced executor-based markReady flows with resumeTask(awaitable, .maybe_remote); added resumeTask imports; removed unused wake helpers.

Sequence Diagram(s)

sequenceDiagram
    participant IO as I/O callback
    participant Runtime as Runtime
    participant Exec as Executor
    participant LocalQ as LocalReadyQueue
    participant RemoteStack as RemoteReadyStack

    IO->>Runtime: resumeTask(coro, .local)
    note right of Runtime #E8F3FF: resumeTask evaluates ResumeMode
    alt mode == local
        Runtime->>LocalQ: enqueue coro (local ready)
    else mode == maybe_remote
        Runtime->>Exec: check current_executor
        alt same executor
            Exec->>LocalQ: enqueue coro locally
        else different executor
            Exec->>RemoteStack: push coro (ConcurrentAwaitableStack)
            Exec->>Exec: signal remote_wakeup (xev)
        end
    end
    LocalQ->>Runtime: scheduler dequeues ready coro
    Runtime->>coro: resume coroutine
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰
I hopped through queues both simple and grand,
I renamed a list and taught stacks to stand.
resumeTask drums — local or across the sea,
Coroutines spring back like springy glee.
The rabbit grins — concurrency, tuned and free.

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly summarizes the primary refactoring of extracting awaitable structures into separate modules and the enhancements made to concurrent primitives, matching the overall PR objectives without unnecessary detail or noise. It is concise, specific, and directly reflects the core changes in this pull request.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/rename-extract-awaitable-structures

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.

This change makes the executor parameter optional (?*Executor) in
ConcurrentAwaitableList operations, allowing it to work in contexts
where no executor is available, such as thread pool callbacks.

When executor is null, the code spins without yielding during lock
acquisition, which is appropriate for thread pool contexts where
cooperative yielding isn't available or needed.

All call sites in runtime.zig have been updated to correctly pass
the executor parameter. This maintains full compatibility with existing
coroutine-based code while enabling new use cases in thread pool
contexts.
@lalinsky
lalinsky force-pushed the refactor/rename-extract-awaitable-structures branch from eb8d685 to 469be79 Compare October 16, 2025 12:57

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/core/ConcurrentAwaitableList.zig (2)

284-291: Race: tail is cleared after releasing the mutation lock when removing the last node

In the head-removal branch for the final element, head.store(.sentinel0, .release) clears the mutation bit before self.tail = null. Another thread can acquire the lock and push before tail is reset, leaving tail null or stale and corrupting the queue.

Swap the operations to update tail before clearing the lock (match pop()).

Apply this diff:

-            // Was only waiter - transition to sentinel0
-            // (implicitly releases mutation lock since sentinel0 = 0b00 has no mutation bit)
-            // .release: publishes tail update and queue empty state
-            self.head.store(@intFromEnum(State.sentinel0), .release);
-            self.tail = null;
+            // Was only waiter - transition to sentinel0
+            // Update tail first, then clear the mutation bit via store(.release)
+            self.tail = null;
+            // .release: publishes tail update and queue empty state
+            self.head.store(@intFromEnum(State.sentinel0), .release);

253-268: Over-strict debug assert in remove() breaks valid races (timeouts/select cleanup)

std.debug.assert(awaitable.in_list); can legitimately fail when remove is called speculatively (e.g., timeout callback, double-check fast path, select cleanup). The function is documented to return false if not found.

Remove the assert; keep the existing membership test to return false safely.

Apply this diff:

-    if (builtin.mode == .Debug) {
-        std.debug.assert(awaitable.in_list);
-    }
+    // Debug note: awaitable may already be removed by a concurrent action (timeout/complete)
+    // Do not assert; rely on membership checks below to return false safely.
src/core/AwaitableList.zig (1)

65-95: remove() can corrupt the list if the item is not in this list; add membership checks and relax debug assert

Currently:

  • Asserts in_list (too strict) and clears it before confirming membership.
  • Unconditionally rewires pointers, which corrupts the list if awaitable is not on self.

Fix:

  • Early-return false if not a member.
  • Only clear in_list when actually removing.

Apply this diff:

 pub fn remove(self: *SimpleAwaitableList, awaitable: *Awaitable) bool {
   // Handle empty list
   if (self.head == null) return false;

-  if (builtin.mode == .Debug) {
-      std.debug.assert(awaitable.in_list);
-      awaitable.in_list = false;
-  }
+  // Validate membership (minimal check: if no prev, must be head)
+  if (awaitable.prev == null and self.head != awaitable) return false;
+  // Optional symmetric check: if no next, must be tail
+  if (awaitable.next == null and self.tail != awaitable) return false;
+  if (builtin.mode == .Debug) {
+      if (!awaitable.in_list) return false;
+      awaitable.in_list = false;
+  }

   // Update prev node's next pointer (or head if removing first node)
   if (awaitable.prev) |prev_node| {
       prev_node.next = awaitable.next;
   } else {
       // No prev means this is the head
       self.head = awaitable.next;
   }

   // Update next node's prev pointer (or tail if removing last node)
   if (awaitable.next) |next_node| {
       next_node.prev = awaitable.prev;
   } else {
       // No next means this is the tail
       self.tail = awaitable.prev;
   }

   // Clear pointers
   awaitable.next = null;
   awaitable.prev = null;

   return true;
 }
🧹 Nitpick comments (4)
src/core/ConcurrentAwaitableStack.zig (1)

15-31: Tighten atomic memory orders in push for perf

Current ordering is correct but stronger than needed. You can relax without affecting correctness:

  • Use .monotonic (relaxed) for the speculative head load.
  • Use .monotonic for the CAS failure order.

Apply:

-        const current_head = self.head.load(.acquire);
+        const current_head = self.head.load(.monotonic);
...
-        if (self.head.cmpxchgWeak(
+        if (self.head.cmpxchgWeak(
             current_head,
             item,
             .release,
-            .acquire,
+            .monotonic,
         ) == null) {
src/core/AwaitableList.zig (1)

50-56: Minor: redundant null-check after early return

After if (other.head == null) return;, if (other.head) |other_head| is redundant.

Apply this diff:

-    if (self.tail) |tail| {
-        tail.next = other.head;
-        if (other.head) |other_head| {
-            other_head.prev = tail;
-        }
+    if (self.tail) |tail| {
+        tail.next = other.head;
+        const other_head = other.head.?;
+        other_head.prev = tail;
src/core/SimpleAwaitableStack.zig (1)

32-47: Optional: add popAll() to mirror ConcurrentAwaitableStack ergonomics

Runtime uses popAll() on the concurrent stack. Adding a similar helper here can simplify drains/moves between local queues.

Proposed addition:

pub fn popAll(self: *SimpleAwaitableStack) SimpleAwaitableStack {
    const out = SimpleAwaitableStack{ .head = self.head };
    self.head = null;
    return out;
}
src/runtime.zig (1)

1098-1129: markReady remote path is correct; assert ensures initialization

Uses TLS to detect same executor; remote path pushes to lock-free stack and notifies. Consider guarding assert with a recoverable path (e.g., lazily initialize) if cross-thread resume can occur before run(), but current model disallows that, so this is acceptable.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 88115f1 and 469be79.

📒 Files selected for processing (12)
  • src/core/Awaitable.zig (1 hunks)
  • src/core/AwaitableList.zig (4 hunks)
  • src/core/ConcurrentAwaitableList.zig (6 hunks)
  • src/core/ConcurrentAwaitableStack.zig (1 hunks)
  • src/core/SimpleAwaitableStack.zig (1 hunks)
  • src/file.zig (8 hunks)
  • src/runtime.zig (15 hunks)
  • src/sync/Condition.zig (3 hunks)
  • src/sync/Mutex.zig (2 hunks)
  • src/sync/ResetEvent.zig (2 hunks)
  • src/tcp.zig (8 hunks)
  • src/udp.zig (4 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-15T19:38:44.642Z
Learnt from: lalinsky
PR: lalinsky/zio#47
File: src/sync/Mutex.zig:237-237
Timestamp: 2025-10-15T19:38:44.642Z
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/sync/Mutex.zig
🔇 Additional comments (20)
src/sync/ResetEvent.zig (1)

51-51: Resume via resumeTask(.maybe_remote) is appropriate

The switch simplifies wakeups and safely handles potential cross-thread resumptions. Looks good.

Also applies to: 89-90

src/sync/Condition.zig (1)

55-55: Signal/broadcast now use resumeTask(.maybe_remote) — LGTM

Direct resumption removes executor plumbing and preserves cross-thread safety.

Also applies to: 189-191, 212-214

src/sync/Mutex.zig (1)

29-29: Unlock: resumeTask(.maybe_remote) is the right choice

The new wake path is correct and consistent with the queue semantics.

Also applies to: 124-126

src/tcp.zig (1)

8-9: Shift to resumeTask(.local) in xev callbacks — consistent and correct

Using .local in these callbacks matches loop-thread execution and removes executor.markReady boilerplate.

Please confirm all xev callbacks in this module always run on the same executor thread. If any can run off-thread, switch those sites to .maybe_remote.

Also applies to: 85-86, 137-139, 197-198, 307-308, 360-361, 405-406, 448-449

src/udp.zig (1)

5-6: UDP callbacks: resumeTask(.local) — LGTM

Matches the TCP pattern and should be correct on the loop thread.

Please verify xev UDP callbacks are always invoked on the executor’s loop thread; use .maybe_remote if any callback can be off-thread.

Also applies to: 61-62, 117-118, 169-170

src/file.zig (1)

8-9: File I/O callbacks: resumeTask(.local) — solid cleanup

Uniform switch away from executor.markReady improves clarity; .local is correct for loop-thread callbacks.

Also applies to: 59-60, 111-112, 187-188, 235-236, 298-299, 345-346, 383-384

src/core/ConcurrentAwaitableStack.zig (1)

33-38: popAll semantics — LGTM

Atomic swap with .acq_rel correctly drains and synchronizes with producers; returning a SimpleAwaitableStack is clean.

src/core/ConcurrentAwaitableList.zig (2)

120-151: Executor-aware spin yielding looks good

Conditional yielding during lock contention avoids TDZ and preserves non-yielding behavior when executor is null. Memory orderings (.acquire/.release) are appropriate for the lock handoff.


307-338: popOrTransition logic is correct and retry-safe

Transitions use acq_rel on success and acquire on failure; retry on self-removal races is sound. No changes requested.

src/core/SimpleAwaitableStack.zig (1)

13-30: LGTM: push/pop correctness

Push/pop maintain in_list in Debug and clear next on pop. Matches single-threaded LIFO semantics.

src/core/Awaitable.zig (1)

18-48: Awaitable base type looks solid

  • Alignment check for tagged pointers is correct.
  • Atomics and cancellation flag with release/acquire semantics are appropriate.
  • Embedded ConcurrentAwaitableList default-initialized for per-object waiters.
src/runtime.zig (9)

55-69: Switching to resumeTask(.local) in I/O callback is appropriate

Ensures local fast-path without cross-thread checks.


104-124: Remote ready draining logic is correct

Drains concurrent remote stack into local next_ready_queue and rearms. Matches run() initialization.


156-203: waitForComplete: robust coroutine/thread paths with double-check and cleanup

  • Double-checked state prevents lost wakeups.
  • Cancellation path removes from wait list.
  • Futex path uses release/acquire pairing.

205-268: timedWaitForComplete: correct timeout/remove integration

Timeout callback removes from wait list and yields with proper error propagation; thread path uses Futex.timedWait.


270-301: markComplete: correct ordering and cross-executor resumption

  • Sets state with .release before waking.
  • Drains waiters and uses resumeTask(.maybe_remote).
  • Wakes futex waiters after coroutine wakeups.

310-332: resumeTask and ResumeMode: clean API

Type-agnostic resume with executor-local/remote paths; straightforward and safe.


695-706: Re-exporting core types through runtime is fine

Imports of Simple/Concurrent stacks/lists centralize public API.


1027-1034: TLS current_executor and remote init in run()

TLS setup and ensureRemoteInitialized() before loop are necessary for cross-thread resumption. Good.


1519-1547: select() waiter enqueue/dequeue updated correctly

Pushes with executor, defers safe removal for non-ready waiters; aligns with markComplete’s select_waiter handling.

@lalinsky

Copy link
Copy Markdown
Owner Author

@claude address the race identified by coderabbit

And also fix remove(), we will probably need to make the in_list a regular field, not debug only tool

@claude

claude Bot commented Oct 16, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


Race condition fixes completed

Tasks

  • Read affected files to understand current implementation
  • Fix race condition in ConcurrentAwaitableList (tail clearing order)
  • Remove over-strict assert in ConcurrentAwaitableList.remove()
  • Fix SimpleAwaitableList.remove() with proper membership checks
  • Make in_list a regular field (not debug-only)
  • Run tests to verify fixes
  • Commit and push changes

Summary

I've addressed all the race conditions identified by CodeRabbit and fixed the remove() method as requested:

1. Fixed race condition in ConcurrentAwaitableList.remove() (lines 284-291)

  • Swapped the order of operations when removing the last node
  • Now updates tail = null before releasing the mutation lock
  • Prevents another thread from acquiring the lock and pushing before tail is reset

2. Removed over-strict assert in ConcurrentAwaitableList.remove()

  • Replaced std.debug.assert(awaitable.in_list) with a check that returns false
  • This handles legitimate races during timeout callbacks, double-check fast paths, and select cleanup
  • The function is documented to return false if not found, so this is the correct behavior

3. Fixed SimpleAwaitableList.remove() with proper membership checks

  • Added early return if !awaitable.in_list
  • Added validation: if no prev, must be head; if no next, must be tail
  • Only clears in_list when actually removing from the list
  • Prevents list corruption when removing items not actually in the list

4. Made in_list a regular field (not debug-only)

  • Changed from if (builtin.mode == .Debug) bool else void to just bool
  • Removed all if (builtin.mode == .Debug) guards around in_list usage
  • Updated all files: Awaitable.zig, AwaitableList.zig, ConcurrentAwaitableList.zig, SimpleAwaitableStack.zig, ResetEvent.zig
  • This enables reliable membership checks in all builds, not just debug builds

All tests pass successfully (90/90).


Job Run | Branch

- Fix race in ConcurrentAwaitableList.remove() where tail was cleared
  after releasing mutation lock when removing the last node
- Remove over-strict debug assert in ConcurrentAwaitableList.remove()
  that broke valid timeout/cancellation cleanup races
- Add proper membership checks in SimpleAwaitableList.remove() to
  prevent list corruption when removing items not in the list
- Make in_list a regular field instead of debug-only to enable
  reliable membership checks in all builds

Co-authored-by: Lukáš Lalinský <[email protected]>

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

🧹 Nitpick comments (1)
src/core/ConcurrentAwaitableList.zig (1)

248-262: Consider simplifying the redundant checks or document the intent.

There are two separate checks for whether the awaitable is in the list:

  1. Lines 248-253: Pointer-based check (awaitable.prev == null and head != awaitable)
  2. Lines 255-259: Flag-based check (!awaitable.in_list)

The first check serves as an optimization or safety net, but now that in_list is the authoritative source of truth, this could lead to subtle inconsistencies if the flag and pointers ever disagree (e.g., due to a bug elsewhere).

Recommendation: Either document why both checks are necessary, or simplify by checking in_list first and optionally adding pointer checks as assertions for internal consistency.

Example refactor:

-    // Check if we're actually in the list (using prev/next pointers)
-    // If prev is null and we're not head, we're not in the list
-    if (awaitable.prev == null and head != awaitable) {
-        self.releaseMutationLock();
-        return false; // Not in list
-    }
-
     // Check if not in list (may have been removed by concurrent action)
     if (!awaitable.in_list) {
         self.releaseMutationLock();
         return false;
     }
+
+    // Sanity check: if in_list is true, pointers should be consistent
+    std.debug.assert(awaitable.prev != null or head == awaitable);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 469be79 and f0be536.

📒 Files selected for processing (5)
  • src/core/Awaitable.zig (1 hunks)
  • src/core/AwaitableList.zig (4 hunks)
  • src/core/ConcurrentAwaitableList.zig (9 hunks)
  • src/core/SimpleAwaitableStack.zig (1 hunks)
  • src/sync/ResetEvent.zig (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/core/SimpleAwaitableStack.zig
  • src/core/Awaitable.zig
  • src/sync/ResetEvent.zig
🔇 Additional comments (10)
src/core/AwaitableList.zig (4)

9-9: LGTM: Clear type rename.

The rename from AwaitableList to SimpleAwaitableList effectively distinguishes this non-concurrent implementation from concurrent variants introduced elsewhere in the PR.


14-27: LGTM: Defensive double-insertion check.

Making in_list a regular field (rather than debug-only) and unconditionally asserting !awaitable.in_list provides runtime detection of double-insertion bugs, even in release builds. This aligns with the PR objective to make in_list a regular field.


29-41: LGTM: Proper cleanup on removal.

The function correctly clears in_list and resets linkage pointers, ensuring the awaitable is fully detached from the list.


61-97: LGTM: Addresses double-removal concern.

The in_list check (line 66) prevents double-removal, and the membership validations (lines 69, 71) catch scenarios where an awaitable at the head or tail position doesn't belong to this list. This addresses the race/correctness concerns mentioned in the PR comments.

Note: The membership checks are best-effort—they won't detect an awaitable in the middle of a different list. For a non-concurrent data structure, this is reasonable. If stronger guarantees are needed, you could traverse the list to confirm membership, though this would change the operation from O(1) to O(n).

src/core/ConcurrentAwaitableList.zig (6)

127-151: LGTM! Conditional yielding based on executor presence.

The addition of the optional executor parameter and conditional yielding (lines 145-147) allows for a no-yield spin path when called from contexts where yielding is not appropriate (e.g., thread pool callbacks). The implementation correctly defaults to spinning with spinLoopHint() when no executor is provided.


168-193: LGTM! in_list is now tracked unconditionally.

The in_list field is properly set to true when pushing (lines 170-171) and asserted to be false beforehand (line 170). This aligns with the PR objective to make in_list a regular field instead of debug-only.


197-211: LGTM! in_list properly maintained in pop.

The field is correctly asserted (line 210) and cleared (line 211) during removal.


255-262: LGTM! This addresses the race condition.

The check at lines 255-259 correctly handles the case where the awaitable was removed by another operation (e.g., cancellation) after we started waiting for the mutation lock but before we acquired it. This prevents double-removal and aligns with the PR objective to address the race condition identified by CodeRabbit.


309-334: LGTM! Consistent API change.

The executor parameter is properly threaded through to the pop call at line 328.


336-391: Consider adding test coverage for null-executor path.

All tests pass a non-null &runtime.executor. The new null-executor behavior (spinning without yielding) is not exercised in tests. While this might be acceptable if null-executor is only used in specific runtime contexts, adding a test case would improve confidence in the no-yield code path.

Example test addition:

test "ConcurrentAwaitableList with null executor" {
    const testing = std.testing;
    
    var list = ConcurrentAwaitableList.init();
    var awaitable align(8) = Awaitable{
        .kind = .task,
        .destroy_fn = struct {
            fn dummy(_: *Runtime, _: *Awaitable) void {}
        }.dummy,
    };
    
    // Test push/pop without executor (should not yield)
    list.push(null, &awaitable);
    const popped = list.pop(null);
    try testing.expectEqual(&awaitable, popped);
}

- Change in_list from regular field to debug-only field that only
  exists when builtin.mode == .Debug
- Use structural invariants for membership checks: items not in a
  list have both prev and next set to null after removal
- Add missing next/tail membership check to ConcurrentAwaitableList.remove()
  (was only checking prev/head)
- Remove in_list early-return checks from remove() functions - structural
  checks are sufficient and work in all build modes
- Add comprehensive double-remove tests for both SimpleAwaitableList
  and ConcurrentAwaitableList to verify structural checks work correctly

The structural checks provide reliable membership detection:
- If prev == null, item must be head (or not in list)
- If next == null, item must be tail (or not in list)
- If both are null, item is definitely not in list

This makes in_list purely a debug-time validation aid rather than
a runtime requirement, reducing struct size in release builds.
@lalinsky lalinsky changed the title Refactor/rename extract awaitable structures Extract awaitable structures and improve concurrent primitives Oct 16, 2025

@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

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f0be536 and e42ad17.

📒 Files selected for processing (5)
  • src/core/Awaitable.zig (1 hunks)
  • src/core/AwaitableList.zig (5 hunks)
  • src/core/ConcurrentAwaitableList.zig (10 hunks)
  • src/core/SimpleAwaitableStack.zig (1 hunks)
  • src/sync/ResetEvent.zig (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/sync/ResetEvent.zig
  • src/core/SimpleAwaitableStack.zig
🔇 Additional comments (8)
src/core/Awaitable.zig (2)

37-41: LGTM: Alignment enforcement for tagged pointers.

The compile-time alignment check is essential for the tagged pointer operations used by ConcurrentAwaitableList. The check ensures the lower 2 bits are available for state/lock encoding.


45-47: LGTM: Cancellation signaling.

The cancellation mechanism using atomic store with release ordering is correct. The .release ordering ensures the cancellation flag becomes visible to any thread that subsequently loads it.

src/core/AwaitableList.zig (3)

9-9: LGTM: Rename to SimpleAwaitableList.

The rename clarifies that this is a non-concurrent list implementation, distinguishing it from ConcurrentAwaitableList.


65-100: Verify remove() membership validation is sufficient.

The membership validation logic (lines 69-72) checks pointer consistency, but with in_list currently being debug-only (see comment on Awaitable.zig:26), release builds have no definitive membership tracking. Once in_list becomes a regular field, consider adding an explicit check:

if (builtin.mode == .Debug or true) {  // Will become: if (true) after in_list is regular
    if (!awaitable.in_list) return false;
}

This provides an early exit before acquiring locks or traversing pointers.

The current pointer-based validation is correct but could race without the in_list flag in release builds. The fix for Awaitable.zig:26 will address this.


102-157: LGTM: Comprehensive double-remove test coverage.

The test validates:

  • Middle element double-remove (lines 137-140)
  • Head element double-remove (lines 143-146)
  • Tail element double-remove (lines 149-152)
  • Final empty state verification (lines 155-156)

This provides strong coverage for the idempotent remove behavior.

src/core/ConcurrentAwaitableList.zig (3)

127-151: LGTM: Optional executor with conditional yielding.

The pattern of accepting ?*Executor and conditionally yielding (lines 145-147) is well-designed. This allows:

  • Thread pool callbacks to spin without yielding (pass null)
  • Coroutine contexts to yield cooperatively (pass executor)

The memory ordering with .acquire on fetchOr (line 134) correctly synchronizes with the previous lock release.


241-306: Verify remove() membership validation consistency.

The membership validation (lines 254-262) mirrors the logic in SimpleAwaitableList.remove() (lines 69-72), which is good for consistency. However, similar to the non-concurrent version, once in_list becomes a regular field (per the fix in Awaitable.zig:26), consider adding an early exit:

// After acquiring mutation lock, before pointer traversal
if (!awaitable.in_list) {
    self.releaseMutationLock();
    return false;
}

This reduces contention by releasing the lock faster for non-members.

The tail update ordering comment (lines 286-287) correctly identifies that tail must be updated before releasing the mutation lock via store(.release), ensuring proper visibility.

The current implementation is correct, but the suggested optimization becomes possible once in_list is a regular field.


398-451: LGTM: Thorough double-remove test coverage.

The test comprehensively validates idempotent remove behavior across all positions (middle, head, tail) and verifies the final sentinel state. This provides strong confidence in the concurrent remove implementation.

Comment thread src/core/Awaitable.zig Resolved

@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/core/ConcurrentAwaitableList.zig (1)

400-453: Good single-threaded coverage, but consider adding concurrent test.

The test correctly validates idempotent removal behavior for head, middle, and tail positions. However, since this is a concurrent data structure and the double-removal protection is meant to prevent races, consider adding a concurrent test where multiple threads attempt to remove the same awaitable simultaneously.

Example concurrent test skeleton:

test "ConcurrentAwaitableList concurrent double remove" {
    const testing = std.testing;
    var runtime = try Runtime.init(testing.allocator, .{});
    defer runtime.deinit();
    
    var list = ConcurrentAwaitableList.init();
    var awaitable = align(8) Awaitable{ .kind = .task, .destroy_fn = ... };
    
    list.push(&runtime.executor, &awaitable);
    
    // Spawn multiple threads trying to remove the same awaitable
    // Only one should succeed, others should return false
    var threads: [4]std.Thread = undefined;
    var results = [_]std.atomic.Value(bool){...};
    
    for (&threads, 0..) |*thread, i| {
        thread.* = try std.Thread.spawn(.{}, struct {
            fn remove_worker(l: *ConcurrentAwaitableList, a: *Awaitable, result: *std.atomic.Value(bool)) void {
                result.store(l.remove(null, a), .seq_cst);
            }
        }.remove_worker, .{&list, &awaitable, &results[i]});
    }
    
    for (&threads) |*thread| thread.join();
    
    // Verify exactly one thread succeeded
    var success_count: usize = 0;
    for (results) |r| if (r.load(.seq_cst)) success_count += 1;
    try testing.expectEqual(@as(usize, 1), success_count);
}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e42ad17 and 69bca8f.

📒 Files selected for processing (1)
  • src/core/ConcurrentAwaitableList.zig (10 hunks)
🔇 Additional comments (4)
src/core/ConcurrentAwaitableList.zig (4)

127-153: LGTM: Nullable executor pattern correctly implemented.

The conditional yielding logic properly handles both thread pool contexts (null executor) and runtime contexts (non-null executor). When the executor is null, the code appropriately falls back to std.Thread.yield().


170-170: Consistent nullable executor propagation.

The signature changes properly thread the nullable executor through the call chain to acquireMutationLock(). The pattern is applied consistently across push, pop, and popOrTransition.

Also applies to: 201-201, 316-316


287-293: Correct ordering for tail update before lock release.

The explicit comment and implementation correctly update tail = null before the head.store() which implicitly releases the mutation lock. The .release memory order ensures the tail update is visible to future lock acquirers.


129-129: Nullable executor usage is consistent. All waiting_list calls pass a non-null executor; no null arguments were found.

Comment thread src/core/ConcurrentAwaitableList.zig Resolved
lalinsky added a commit that referenced this pull request Jan 6, 2026
* Add IOCP backend skeleton with SharedState refcounting

Implements bare-bones IOCP backend for Windows with thread-safe
SharedState that allows multiple loops to share a single IOCP handle.

- Add iocp backend to BackendType enum
- Set iocp as default backend for Windows
- Implement SharedState with mutex and refcounting
- Implement init/deinit with acquire/release semantics
- Implement poll() using GetQueuedCompletionStatusEx
- Stub wake/submit/cancel with panic for now

The IOCP handle is created on first loop init and destroyed when
the last loop is deinitialized, enabling one loop per thread pattern.

* Add extension function loading with per-family caching

Implements lazy loading of Winsock extension functions (AcceptEx,
ConnectEx) with thread-safe caching per address family.

- Add ExtensionFunctions struct with AcceptEx/ConnectEx pointers
- Add extension_cache (HashMap<family, ExtensionFunctions>)
- Implement getExtensions() for lazy loading with caching
- Load functions via WSAIoctl(SIO_GET_EXTENSION_FUNCTION_POINTER)
- Cache key is address family (u16) since functions are STREAM-only
- Thread-safe access via SharedState mutex

* Implement IOCP backend basic network operations

- Add Completion.internal field with backend-specific CompletionData
- Implement net_open: create socket and associate with IOCP handle
- Implement net_connect: use ConnectEx with pre-binding requirement
- Implement net_accept: use AcceptEx with address buffer
- Implement poll() completion processing using @fieldParentPtr
- Add NetAcceptData for accept-specific address buffer storage

All completions now have OVERLAPPED in Completion.internal, with
net_accept getting additional buffer space in its per-operation internal
field. Processing uses @fieldParentPtr to navigate from OVERLAPPED back
to the Completion struct.

* Implement wake() for IOCP using QueueUserAPC with alertable waits

Each Backend stores a duplicated thread handle obtained during init().
wake() uses QueueUserAPC to queue an APC to the target thread, which
interrupts GetQueuedCompletionStatusEx when called with fAlertable=TRUE.

When poll() receives WAIT_IO_COMPLETION, it calls processAsyncHandles()
to process any pending async notifications.

This allows waking a specific loop thread despite sharing the IOCP handle
across multiple loops, solving the fundamental issue that you cannot wake
a specific waiter with PostQueuedCompletionStatus.

* Progres

* Add null pointer check for IOCP completion entries

Handle cases where lpOverlapped is NULL in IOCP completion entries,
which can occur when the IOCP port is closed or in certain error
conditions.

* Fix IOCP completion handling for immediate operations

According to Windows documentation, when WSARecv/WSASend/WSARecvFrom/
WSASendTo succeed immediately (return 0) or return WSA_IO_PENDING, the
completion is STILL posted to the IOCP port. Previously we were
completing operations twice when they succeeded immediately.

Now we only complete immediately on real errors (not WSA_IO_PENDING),
and let all successful operations complete via IOCP.

Note: Tests still fail on wine due to wine bugs in IOCP implementation,
but the logic is correct for real Windows.

* Implement cancel() for IOCP backend using CancelIoEx

Use Windows CancelIoEx API to cancel running async I/O operations.
When an operation is canceled, Windows posts a completion to the IOCP
port with ERROR_OPERATION_ABORTED status, which we handle in
processCompletion().

Supports cancellation of:
- Network operations (connect, accept, recv, send, recvfrom, sendto)
- File operations (read, write, sync)

Synchronous operations (open, close, etc.) complete immediately and
don't need cancellation support.

* Fix AcceptEx and ConnectEx immediate completion handling

Both AcceptEx and ConnectEx post completions to IOCP even when they
succeed immediately (return TRUE). Previously we were completing these
operations twice - once synchronously and once via IOCP, which caused
crashes.

Now we only complete immediately on real errors (not WSA_IO_PENDING),
and let all successful operations complete via IOCP.

Note: Tests still crash on wine with segfault at address 0x1. This
appears to be a wine-specific issue that needs to be debugged on real
Windows.

* Fix IOCP backend issues and enable proper error handling

Fixed three critical bugs in the IOCP backend:

1. **Dangling pointer in getExtensions()**: Changed to return ExtensionFunctions
   by value instead of pointer to avoid HashMap invalidation issues

2. **Improper error mapping**: Use net.errnoToConnectError/AcceptError/RecvError/SendError
   instead of error.Unexpected, which properly maps WSA_OPERATION_ABORTED to
   error.Canceled for cancelled operations

3. **Duplicate IOCP association**: Removed redundant CreateIoCompletionPort call
   for accepted sockets (already associated in submitAccept)

All tests now pass on Wine (52/54, 2 skipped Unix-specific tests).

* Fix vectored UDP

* Use proper error mapping functions in IOCP submit handlers

Replace error.Unexpected with proper error mapping functions (errnoToAcceptError, errnoToRecvError, errnoToSendError, errnoToConnectError) in submit handlers when operations fail immediately.

* Populate peer address in AcceptEx completion

Call GetAcceptExSockaddrs to parse AcceptEx's address buffer and copy
the remote address to caller-provided buffers, handling truncation
when the user buffer is smaller than the actual address.

* Implement recv/send flags mapping for IOCP backend

Add support for MSG_PEEK and MSG_WAITALL flags in WSARecv/WSARecvFrom.
MSG_NOSIGNAL from SendFlags is ignored on Windows (no signals).

Uses windows.ws2_32.MSG.PEEK and MSG.WAITALL from std library.

* Add BackendCapabilities for granular file operation support

Replace supports_file_ops boolean with BackendCapabilities struct that
allows backends to selectively support individual file operations.

- io_uring: all file ops supported
- poll/epoll/kqueue: no file ops supported (use thread pool)
- iocp: only file_read and file_write supported (async via OVERLAPPED)

This allows IOCP to use async ReadFile/WriteFile while delegating
synchronous operations (open/close/sync/rename/delete) to thread pool.

* Implement async file I/O for IOCP backend

Add support for async file read/write operations on Windows using IOCP:

- Add postProcessFileHandle() hook to associate file handles with IOCP
  after they're opened/created in the thread pool
- Implement submitFileRead/submitFileWrite using ReadFile/WriteFile APIs
- Add completion handlers for file_read and file_write operations
- Add nonblocking flag to FileOpenFlags/FileCreateFlags that defaults
  to true when backend supports async file I/O, ensuring files are
  opened with FILE_FLAG_OVERLAPPED on Windows
- Add capability checks in submitFileOpToThreadPool for all file
  operations to ensure they're only routed there when unsupported

* Cleaner file IO integration

* Test IOCP

* Fix IOCP setsockopt error handling for socket context updates

Check return value of setsockopt calls for SO_UPDATE_CONNECT_CONTEXT
and SO_UPDATE_ACCEPT_CONTEXT. On failure, close the socket handle and
return the appropriate error using errnoToConnectError/errnoToAcceptError.

* Remove files

* Simplify

* Fixes

* Fix
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