Skip to content

Add multi-threaded runtime support - #56

Merged
lalinsky merged 14 commits into
mainfrom
feature/multi-threaded-runtime
Oct 19, 2025
Merged

lalinsky merged 14 commits into
mainfrom
feature/multi-threaded-runtime

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 18, 2025 •

Copy link
Copy Markdown
Owner

Summary

Implements multi-threaded runtime support for ZIO, enabling parallel execution of coroutines across multiple threads.

Key Features

  • Configurable executor count: num_executors option (null=auto-detect CPU count, 1=default single-threaded)
  • Task pinning: executor_id spawn option to pin tasks to specific executors
  • Round-robin assignment: Tasks distributed across executors by default
  • Cross-executor spawning: Tasks can be spawned on any executor from any thread
  • Graceful shutdown: Main executor coordinates worker shutdown when all tasks complete

Implementation Details

  • Runtime manages multiple Executors via ArrayList
  • Main executor (index 0) runs on calling thread, orchestrates shutdown
  • Worker executors (index 1..N) run on spawned threads
  • Loop initialization separated from struct setup for thread-safety
  • Remote queues handle cross-thread task resumption
  • Global task counter for shutdown coordination

Tests

  • Multi-threaded runtime with auto-detect CPU count
  • Multi-threaded runtime with explicit executor count
  • Executor pinning across multiple executors
  • All existing tests continue to pass

Breaking Changes

None - defaults to single-threaded mode (backward compatible)

Summary by CodeRabbit

  • New Features

    • Multi‑executor runtime: configurable executor count, task pinning or round‑robin, cross‑executor routing and remote wakeups, per‑executor operation, and new errors for invalid executor or runtime shutdown; join handles can report a task's executor.
  • Refactor

    • Stack pool reuse switched from LIFO to FIFO queueing for improved cross‑thread behavior and scalability.
  • Chores

    • Test runner logs test start in verbose mode; added multi‑executor tests.

- Add num_executors option to RuntimeOptions (null=auto-detect, 1=default)
- Change Runtime to manage multiple Executors via ArrayList
- Add executor_id option to SpawnOptions for task pinning
- Implement round-robin task assignment across executors
- Add global_task_count for shutdown coordination
- Split Executor.run() into runMain() and runWorker()
- Main executor (index 0) runs on calling thread, orchestrates shutdown
- Worker executors (index 1..N) run on spawned threads until signaled
- Add cross-executor task spawning support via remote queues
- Fix task loss bug: use pointer instead of copy when spawning
- Add ResetEvent for worker thread startup synchronization
- Separate loop initialization (initLoop/deinitLoop) from struct setup
@coderabbitai

coderabbitai Bot commented Oct 18, 2025 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@lalinsky has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 5 minutes and 13 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 8454f22 and 3671d97.

📒 Files selected for processing (1)
  • README.md (1 hunks)

Walkthrough

Runtime changes shift from a single-executor model to a multi-executor architecture with explicit executor pinning, global task coordination, and shutdown/error variants; stack pool switches from a LIFO free-list to a concurrent FIFO queue; test runner prints test names when verbose. (≈38 words)

Changes

Cohort / File(s) Summary
Core multi-executor runtime
src/runtime.zig
Replaces single Executor with executors: std.ArrayList(Executor) and multi-executor coordination fields (next_executor, global_task_count, accepting_spawns, shutting_down). Adds RuntimeOptions.num_executors, SpawnOptions.executor_id, new ZioError variants (InvalidExecutorId, RuntimeShutdown). Executor gains identity, runtime pointer, thread/loop lifecycle fields and methods (id, runtime_ptr, thread, ready, remote_initialized, shutdown_async, shutdown_completion, initLoop, deinitLoop). Spawn/run APIs updated for executor selection, cross-executor routing, and shutdown behavior; JoinHandle.getExecutorId() added.
Stack pool concurrency
src/stack_pool.zig
Replaces intrusive LIFO free-list with a ConcurrentQueue of FreeListNode (imports lib: utils/concurrent_queue.zig). Bucket methods (acquire, release, cleanupOld, deinit) rewritten for FIFO queue semantics; FreeListNode fields/initialization updated.
Test runner logging
test_runner.zig
Adds a verbose-only debug print that emits Starting: <test_name> when TEST_VERBOSE is true before running each test.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Caller
    participant RT as Runtime
    participant E0 as Executor 0 (main)
    participant Ew as Executor 1..N (workers)

    Caller->>RT: run(num_executors = N)
    RT->>RT: allocate executors, set next_executor & global_task_count
    RT->>Ew: init(id=1..N-1) -> spawn worker threads
    Ew->>Ew: initLoop() -> worker event loop (drain remote queues)
    RT->>E0: init(id=0) on caller thread
    E0->>E0: runMain() (main event loop)

    Note over E0,Ew: Spawn routing
    E0->>E0: spawn(executor_id=0 or round-robin) -> enqueue local ready
    E0->>Ew: spawn(executor_id=remote) -> enqueue remote ready + remote_wakeup
    Ew->>Ew: remote_wakeup -> drain remote queue -> execute task

    Note over RT: Shutdown
    E0->>RT: initiate shutdown (set shutting_down)
    RT->>Ew: signal shutdown, wake workers
    Ew->>RT: deinitLoop() -> completion
    E0->>RT: deinitLoop() -> return to caller
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐇 I hopped through loops and split the run,

Executors many, now the work is spun.
Queues line up where stacks once flew,
Workers wake and tasks hop through.
A rabbit cheers — new threads begun!

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 pull request title "Add multi-threaded runtime support" accurately and specifically captures the primary objective of the changeset, which is transforming the runtime from a single-executor architecture to a multi-executor architecture that enables parallel execution across multiple threads. The title directly reflects the main changes in src/runtime.zig, where the Runtime struct now manages multiple Executors, SpawnOptions gains executor_id support, and RuntimeOptions gains num_executors configuration. The title is concise, clear, and specific enough that a teammate reviewing the PR history would understand the core change without needing additional context.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

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.

- Combine runMain() and runWorker() into single run() method
- Use id == 0 check to determine shutdown behavior
- Workers check shutdown flag before processing (early exit)
- Main executor checks after processing (process remaining tasks first)
- Reduces code duplication while preserving correct shutdown semantics

@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

Caution

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

⚠️ Outside diff range comments (2)
src/runtime.zig (2)

823-884: Data race: Executor.tasks is mutated from multiple threads. Guard or funnel to owner thread.

Executor.spawn mutates self.tasks (ensure capacity, put) on whatever thread calls spawn (caller may be on a different executor or an external thread), while the executor thread removes from the same hashmap during completion and in deinit. std.AutoHashMapUnmanaged is not thread-safe, so this is a race with potential memory corruption.

Two viable fixes (pick one):

  • Owner-thread funnel (preferred): do not touch self.tasks off-thread. Enqueue the task via next_ready_queue_remote and insert into self.tasks on the executor thread when draining that queue or right before first switch to it.

  • Locking: protect all read/write operations on self.tasks with a mutex.

Minimal mutex-based patch:

@@ pub const Executor = struct {
-    tasks: std.AutoHashMapUnmanaged(*AnyTask, void) = .{},
+    tasks: std.AutoHashMapUnmanaged(*AnyTask, void) = .{},
+    tasks_mutex: std.Thread.Mutex = .{},
@@
-        try self.tasks.ensureUnusedCapacity(self.allocator, 1);
+        self.tasks_mutex.lock();
+        defer self.tasks_mutex.unlock();
+        try self.tasks.ensureUnusedCapacity(self.allocator, 1);
@@
-        self.tasks.putAssumeCapacityNoClobber(&task.impl.base, {});
+        self.tasks.putAssumeCapacityNoClobber(&task.impl.base, {});
@@
-                        _ = self.tasks.remove(current_task);
+                        self.tasks_mutex.lock();
+                        _ = self.tasks.remove(current_task);
+                        self.tasks_mutex.unlock();
@@
-                        _ = self.tasks.remove(current_task);
+                        self.tasks_mutex.lock();
+                        _ = self.tasks.remove(current_task);
+                        self.tasks_mutex.unlock();

Also guard deinit iteration with the same mutex.

Also applies to: 1064-1070, 1160-1165


1195-1215: markReady: asserting remote_initialized can trip before loop init.

When mode == .maybe_remote and called from an external thread before the target executor initializes its loop, assert(self.remote_initialized.load(.acquire)); will crash. In spawn() you already handle this by only notifying when initialized.

Mirror the spawn() pattern here:

-                // Remote queue is always initialized in Executor.init()
-                assert(self.remote_initialized.load(.acquire));
-                // Push to remote ready queue (thread-safe)
+                // Push to remote ready queue (thread-safe)
                 self.next_ready_queue_remote.push(&task.awaitable.wait_node);
-                // Notify the target executor's event loop
-                self.remote_wakeup.notify() catch {};
+                // Notify the target executor's event loop if initialized
+                if (self.remote_initialized.load(.acquire)) {
+                    self.remote_wakeup.notify() catch {};
+                }
🧹 Nitpick comments (3)
src/runtime.zig (3)

1567-1583: Avoid O(N) scan; use current_exec.id to pick executor.

You can skip scanning self.executors.items to find the current executor and just use current_exec.id.

-        else if (Runtime.current_executor) |current_exec|
-            // In coroutine context - inherit current executor
-            blk: {
-                // Find index of current executor
-                for (self.executors.items, 0..) |*exec, i| {
-                    if (exec == current_exec) break :blk i;
-                }
-                // Fallback to round-robin if not found (shouldn't happen)
-                break :blk self.next_executor.fetchAdd(1, .monotonic) % self.executors.items.len;
-            } else
+        else if (Runtime.current_executor) |current_exec|
+            current_exec.id
+        else

1229-1245: Tagged pointer safety: assert alignment when stealing low bits.

packTimerUserdata/unpackTimerUserdata rely on low 2 bits being zero. Add a compile‑time assert to prevent accidental use with insufficient alignment.

 inline fn packTimerUserdata(comptime T: type, ptr: *T, generation: u2) ?*anyopaque {
+    comptime {
+        if (@alignOf(T) < 4) @compileError("Timer userdata T must be at least 4-byte aligned");
+    }
     const addr = @intFromPtr(ptr);
     const tagged = addr | @as(usize, generation);
     return @ptrFromInt(tagged);
 }

Also applies to: 1236-1245


1741-1744: Metrics and time only reflect executor 0; consider aggregated helpers.

getMetrics() and now() return data from the main executor. Provide getAggregatedMetrics() and nowApprox() that consider all executors for multi-threaded runs, or clarify in docs if this is intentional and sufficient.

Also applies to: 1756-1758

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2f32e85 and 02634cc.

📒 Files selected for processing (2)
  • src/runtime.zig (18 hunks)
  • test_runner.zig (1 hunks)
🔇 Additional comments (2)
test_runner.zig (1)

130-133: Useful: early test banner under TEST_VERBOSE.

LGTM; this helps when diagnosing hangs without affecting captured logs.

src/runtime.zig (1)

29-33: API shape for multi-executor config looks good.

Executor pinning via SpawnOptions.executor_id and RuntimeOptions.num_executors semantics are clear; invalid IDs are surfaced via error.InvalidExecutorId. No blocking issues here.

Also applies to: 39-44, 56-57

Comment thread src/runtime.zig Resolved
- Add shutdown_async and shutdown_completion to Executor
- Register shutdownCallback that calls loop.stop()
- Main executor notifies all executors' shutdown_async when done
- All executors check loop.stopped() instead of shutdown flag
- Remove shutdown atomic bool (no longer needed)
- Shutdown is now handled uniformly via xev.Async notification

@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

♻️ Duplicate comments (1)
src/runtime.zig (1)

1085-1098: Critical: Shutdown race condition from previous review is still present.

The race condition flagged in the previous review has not been addressed. After the main executor checks global_task_count == 0 (line 1086) but before setting shutdown = true (line 1090), a concurrent Runtime.spawn() can increment the counter and enqueue work. Since Runtime.spawn() (lines 1489-1518) has no shutdown gating, this new task may never execute.

The previous review suggested adding an accepting_spawns atomic flag. Here's a lightweight implementation:

 pub const Runtime = struct {
     executors: std.ArrayList(Executor),
     thread_pool: ?*xev.ThreadPool,
     allocator: Allocator,
     options: RuntimeOptions,
 
     // Multi-executor coordination
     next_executor: std.atomic.Value(usize),
     global_task_count: std.atomic.Value(usize),
     shutdown: std.atomic.Value(bool),
+    accepting_spawns: std.atomic.Value(bool),

In Runtime.init() (after line 1463):

         .next_executor = std.atomic.Value(usize).init(0),
         .global_task_count = std.atomic.Value(usize).init(0),
         .shutdown = std.atomic.Value(bool).init(false),
+        .accepting_spawns = std.atomic.Value(bool).init(false),

In Runtime.spawn() (after line 1489):

     pub fn spawn(self: *Runtime, func: anytype, args: meta.ArgsType(func), options: SpawnOptions) !JoinHandle(meta.ReturnType(func)) {
+        if (!self.accepting_spawns.load(.acquire)) return error.RuntimeShuttingDown;

In Runtime.run() (after line 1548):

         // Reset shutdown flag
         self.shutdown.store(false, .release);
+        self.accepting_spawns.store(true, .release);

In Executor.run() main path (after line 1090):

                 // Signal all workers to shut down
                 self.runtime_ptr.shutdown.store(true, .release);
+                self.runtime_ptr.accepting_spawns.store(false, .release);

Also need to add RuntimeShuttingDown to the error set at line 53.

🧹 Nitpick comments (1)
src/runtime.zig (1)

1118-1133: Suggested improvement: Make remote wakeup more robust.

The assertion at line 1126 assumes remote_initialized is always true when using the remote path. While this is likely safe in practice, it's fragile—if markReady() is called before run() (e.g., via early Future.set()), the assertion could fail.

Consider checking remote_initialized and conditionally notifying, similar to the spawn path (line 871):

             } else {
                 // Different executor (or no current executor) - use remote path
-                // Remote queue is always initialized in Executor.init()
-                assert(self.remote_initialized.load(.acquire));
 
                 // Push to remote ready queue (thread-safe)
                 self.next_ready_queue_remote.push(&task.awaitable.wait_node);
 
                 // Notify the target executor's event loop
-                self.remote_wakeup.notify() catch {};
+                if (self.remote_initialized.load(.acquire)) {
+                    self.remote_wakeup.notify() catch {};
+                }
             }

This makes the code more defensive without changing behavior (the remote queue push still works, and the queue will be drained when run() starts).

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 02634cc and 2d6df6c.

📒 Files selected for processing (1)
  • src/runtime.zig (17 hunks)
🔇 Additional comments (11)
src/runtime.zig (11)

27-57: LGTM: Well-designed multi-executor configuration options.

The new configuration options are clear and well-documented:

  • executor_id enables task pinning with sensible defaults (round-robin or inherit)
  • num_executors provides flexible executor control (auto-detect, single-threaded, or explicit count)
  • Error handling with InvalidExecutorId is appropriate

450-456: LGTM: Stack lifecycle management is correct.

The assertion and comment correctly document that the executor releases the stack when the coroutine becomes dead (lines 1061-1064), so it's null by the time the task is destroyed.


719-752: LGTM: Executor fields properly support multi-threaded coordination.

The new fields are well-designed for multi-executor support:

  • id identifies each executor
  • remote_initialized prevents unsafe wakeup notifications before loop initialization
  • runtime_ptr enables global coordination
  • thread and ready handle worker thread lifecycle

764-805: LGTM: Thread-safe executor lifecycle design.

The separation of init() and initLoop() is correct for thread safety:

  • init() establishes stable memory location
  • initLoop() initializes loop on the thread that will run it (critical for thread-local xev state)
  • remote_initialized flag prevents premature notifications

This design properly handles multi-threaded executor startup.


863-884: LGTM: Cross-executor spawning is correctly implemented.

The local vs. remote path selection is well-designed:

  • Same-executor check uses fast local path
  • Cross-executor uses thread-safe remote queue
  • remote_initialized check prevents notification before loop is ready
  • Global task count tracking is correct

1400-1410: LGTM: Runtime coordination fields are well-designed.

The multi-executor coordination fields are appropriate:

  • ArrayList(Executor) provides flexible executor management
  • next_executor enables round-robin task distribution
  • global_task_count coordinates shutdown across executors
  • shutdown signals workers to terminate

1415-1465: LGTM: Runtime initialization correctly sets up multi-executor layout.

The initialization logic is well-structured:

  • Auto-detection of CPU count when num_executors is null
  • Efficient pre-allocation with initCapacity
  • Proper error handling with errdefer cleanup
  • Each executor is initialized with its unique ID

1489-1518: LGTM: Spawn delegation with proper executor selection.

The executor selection logic is sensible:

  • Explicit executor_id takes precedence
  • Inherits current executor when in coroutine context
  • Falls back to round-robin distribution
  • Bounds checking prevents invalid IDs

Minor note: The current executor lookup (lines 1498-1500) is O(n), but acceptable for typical executor counts. Could be optimized with a reverse index if needed.


1541-1576: LGTM: Multi-threaded runtime orchestration is well-structured.

The run() implementation properly coordinates multi-executor execution:

  • Runtime pointer updates handle potential moves
  • Shutdown flag is reset for reruns
  • Single-threaded fast path avoids overhead
  • Worker threads spawned and synchronized via ready.wait()
  • Main executor runs on calling thread (good for stack usage)
  • Proper cleanup with thread joins

1591-1655: LGTM: Convenience methods properly delegate to thread-local executor.

The runtime convenience methods are well-designed:

  • Use current_executor threadlocal for multi-executor support
  • Gracefully handle calls outside coroutine context
  • sleep() falls back to blocking sleep when appropriate
  • Clean separation between Runtime (orchestrator) and Executor (worker)

1794-1902: LGTM: Comprehensive tests for multi-threaded runtime.

The new tests provide good coverage of multi-executor functionality:

  • Auto-detect CPU count validates dynamic configuration
  • Explicit executor count verifies manual configuration
  • Executor pinning confirms task routing works correctly
  • Multiple concurrent tasks exercise parallel execution

These tests should catch regressions in multi-threaded behavior.

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

1684-1702: Consider aggregate metrics for multi-threaded mode.

getMetrics() currently returns only executor 0's metrics in multi-threaded mode. While documented, users might expect system-wide metrics. Consider adding a method to collect and aggregate metrics from all executors.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2d6df6c and f199897.

📒 Files selected for processing (1)
  • src/runtime.zig (18 hunks)
🔇 Additional comments (17)
src/runtime.zig (17)

29-32: Clear documentation for executor pinning.

The executor_id field is well-documented with clear semantics for both explicit pinning and automatic assignment.


39-43: Good defaults preserving backward compatibility.

The single-threaded default (1) maintains existing behavior while allowing opt-in multi-threading.


131-144: Clean shutdown signaling mechanism.

The shutdown callback correctly stops the event loop and returns .disarm to prevent re-arming.


735-771: Well-structured executor fields for multi-threading.

The new coordination fields are clearly documented, including the distinction between main and worker executors.


779-781: Cleaner runtime accessor.

The inline function provides efficient access to the runtime pointer.


783-796: Proper lifecycle separation for thread-safety.

Setting up the struct with undefined loop/async handles is correct here since initLoop() will initialize them from the thread that runs the executor.


798-832: Thread-safe loop initialization.

The loop is correctly initialized from the thread that will run it, and the remote_initialized flag with .release store ensures proper visibility for cross-thread notifications.


834-838: Clean resource cleanup.

Loop resources are properly cleaned up in the correct order.


1047-1132: Main executor orchestrates coordinated shutdown.

The shutdown logic correctly notifies all executors when the main executor detects that all tasks are complete. The use of global_task_count ensures coordinated termination.


1144-1159: Cross-executor wakeup correctly synchronized.

The assertion on remote_initialized is safe because the main executor waits for all workers to be ready before proceeding (line 1582-1584).


1427-1488: Robust multi-executor initialization.

The initialization correctly handles CPU auto-detection, ArrayList capacity management, and proper error cleanup via errdefer.


1513-1542: Well-designed executor selection logic.

The spawn function correctly handles explicit pinning, context inheritance, and round-robin assignment, with proper bounds checking and defensive runtime pointer updates.


1558-1563: Appropriate worker thread error handling.

Worker threads log errors since they can't propagate them, which is reasonable for background execution.


1565-1597: Clean multi-threaded runtime orchestration.

The thread spawning, synchronization via ready.wait(), and cleanup are all correctly implemented.


1619-1667: Thread-local executor access enables multi-threading.

The convenience methods correctly use Runtime.current_executor to support multiple executors, with appropriate no-op behavior when not in coroutine context.


1815-1923: Comprehensive multi-threading test coverage.

The tests effectively validate auto-detection, explicit executor counts, and task pinning across multiple executors.


468-470: Good defensive assertion on stack cleanup.

The assertion confirms that the executor properly released the stack before the task is destroyed.

Comment thread src/runtime.zig Resolved
Adds getExecutorId() method to JoinHandle which returns the executor ID
for coroutine tasks. This allows users to colocate tasks by passing the
executor ID from one task to SpawnOptions.executor_id when spawning
another task, ensuring they run on the same executor.
Use current_exec.id directly instead of scanning through executors
array to find the current executor's index.
packTimerUserdata and unpackTimerUserdata steal the low 2 bits to store
a generation counter. Add compile-time assertions to ensure T has at
least 4-byte alignment, preventing accidental misuse with types that
have insufficient alignment.
Adds Runtime.shutting_down atomic flag that is set when the runtime
begins shutdown. Both spawn() and spawnBlocking() now check this flag
and return error.RuntimeShutdown if attempting to spawn tasks during
shutdown, preventing tasks from being queued while the runtime is
shutting down.
Extract common task scheduling logic into scheduleTask() helper function
that handles both local and remote queue paths. Both Executor.spawn() and
Executor.markReady() now use this shared implementation, eliminating code
duplication and ensuring consistent behavior.

The helper conditionally notifies the remote executor only if the event
loop has been initialized, allowing spawn() to be called before the
executor thread starts while markReady() is always called from within
the running event loop.
Move the responsibility of setting coro.state to .ready into scheduleTask,
simplifying both call sites (spawn and resumeTask). This makes scheduleTask
a more complete abstraction that fully handles task scheduling including
state management.

scheduleTask now takes *AnyTask instead of *WaitNode, giving it access to
set the coroutine state. The state assignment is idempotent for spawn
(which creates tasks already in .ready state) and necessary for resumeTask
(which transitions from .waiting to .ready).

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

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f199897 and a363217.

📒 Files selected for processing (1)
  • src/runtime.zig (22 hunks)
🔇 Additional comments (24)
src/runtime.zig (24)

29-32: LGTM: Executor pinning option is well-documented.

The executor_id field clearly explains the pinning semantics for task placement.


39-43: LGTM: Backward-compatible multi-threading configuration.

Defaulting to 1 preserves single-threaded behavior while enabling multi-threaded mode via explicit configuration or auto-detection.


56-57: LGTM: Clear error cases for multi-executor coordination.


132-145: LGTM: Shutdown callback correctly stops event loop.


323-328: LGTM: State validation before resuming task.

The assertion ensures we're only resuming tasks in the waiting state, preventing logic errors.


676-688: LGTM: Executor ID query enables task colocation.

Correctly returns null for blocking tasks and futures that don't have an associated executor.


754-790: LGTM: Executor fields support multi-executor coordination.

The added fields enable executor identification, cross-thread synchronization, shutdown coordination, and runtime back-references.


798-800: LGTM: Simplified runtime accessor via direct back-reference.


802-815: LGTM: Deferred loop initialization for thread-safety.

Separating struct initialization from loop initialization ensures the loop is created on the correct thread. The undefined fields are properly initialized in initLoop() before use.


817-851: LGTM: Loop initialization on executor thread with proper cleanup.

The separation ensures thread-local resources are created on the correct thread. The remote_initialized flag prevents races during startup.


853-857: LGTM: Proper cleanup of loop resources.


915-922: Note: Global task counter for shutdown coordination.

The increment at line 922 pairs with the decrement at line 1113 to track active tasks across all executors for shutdown.


1146-1179: LGTM: Cross-executor task routing with startup race prevention.

The remote_initialized check (line 1170) prevents notifying the remote wakeup before it's registered, avoiding a lost wakeup race during executor startup.


1194-1206: LGTM: Compile-time alignment validation for tagged pointer safety.

The comptime checks ensure the timer userdata type is properly aligned for packing the 2-bit generation in the lower bits.


1446-1456: LGTM: Runtime fields for multi-executor coordination.


1461-1510: LGTM: Multi-executor initialization with CPU auto-detection.

Proper error handling with errdefer ensures cleanup if executor initialization fails partway through.


1513-1532: LGTM: Proper cleanup order prevents use-after-free.

Thread pool shutdown before executor cleanup ensures no new work is scheduled during teardown.


1565-1582: Consistent shutdown gating for blocking tasks.

The shutting_down check is consistent with Runtime.spawn(), though it shares the same race window.


1591-1623: LGTM: Multi-executor startup with proper synchronization.

Waiting for workers to become ready (lines 1608-1610) before running the main executor prevents races where cross-executor task spawning might occur before worker loops are initialized.


1625-1636: LGTM: Main task pinned to executor 0 for predictable execution.


1645-1693: LGTM: Threadlocal executor access for multi-executor delegation.


1710-1728: LGTM: Metrics access with documented multi-executor limitations.

The comment at line 1711 appropriately notes that getMetrics() returns only the main executor's metrics in multi-threaded mode. For comprehensive metrics, callers would need per-executor access (potential future enhancement).


1841-1988: LGTM: Comprehensive tests for multi-executor features.

Tests cover auto-detection, explicit configuration, pinning, colocation, and shutdown behavior. The test at line 1951 demonstrates a practical use case for getExecutorId() to colocate related tasks.


2015-2067: Good test coverage for shutdown error handling.

Tests verify that both spawn() and spawnBlocking() return error.RuntimeShutdown when called after shutdown is initiated.

Comment thread src/runtime.zig Resolved
Replace Bucket's manual linked list with ConcurrentQueue for lock-free
thread-safe stack management. FIFO ordering naturally keeps oldest stacks
at the front, simplifying age-based cleanup logic.

Changes:
- Use ConcurrentQueue(FreeListNode) instead of manual head/count tracking
- Update FreeListNode with required prev and in_list fields
- Simplify acquire() to use queue.pop() (gets oldest stack)
- Simplify release() to use queue.push()
- Optimize cleanupOld() leveraging FIFO property - stop at first young stack
- Simplify deinit() to drain queue

The StackPool can now be safely shared across multiple executor threads.

@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 (3)
src/stack_pool.zig (3)

23-26: Drop unused fields from FreeListNode.

prev and in_list appear obsolete with the queue; keeping them bloats header and causes confusion.

 const FreeListNode = struct {
-    next: ?*FreeListNode = null,
-    prev: ?*FreeListNode = null,
-    in_list: bool = false,
+    next: ?*FreeListNode = null,
     returned_at: i64,
@@
         node.* = .{
             .next = null,
-            .prev = null,
-            .in_list = false,
             .returned_at = returned_at,
         };

Also applies to: 33-35


49-58: FIFO reuse may hurt locality; consider a per-executor LIFO fast path.

Switching from LIFO to FIFO can increase page/TLB misses for stacks. If feasible, keep a tiny per-executor LIFO cache (SPSC) and fall back to the global MPMC queue to balance locality and sharing.


65-84: Don’t rely on FIFO age ordering under concurrency; drop the early break and bound the scan.

With concurrent producers, “first young means all following are younger” doesn’t always hold. Early break can strand stale entries and bloat memory. Iterate a bounded window to free eligible old nodes without assuming global order.

 fn cleanupOld(self: *Bucket, size: usize, allocator: Allocator, now: i64, retention_ms: i64, min_warm: usize) void {
-        var kept_count: usize = 0;
-        // Pop from front (oldest first due to FIFO)
-        while (self.queue.pop()) |node| {
-            // Check if stack is too old
-            if (node.returned_at + retention_ms < now and kept_count >= min_warm) {
-                // Too old and we have enough warm stacks - free it
-                allocator.free(node.toStack(size));
-            } else {
-                // Still young or need to keep for min_warm - push back to queue
-                self.queue.push(node);
-                kept_count += 1;
-
-                // Since queue is FIFO, once we find a young stack, all following are younger
-                // So we can stop here
-                break;
-            }
-        }
+        const scan_limit: usize = 4096; // bound per-cleanup work
+        var kept_count: usize = 0;
+        var scanned: usize = 0;
+        while (scanned < scan_limit) {
+            const maybe = self.queue.pop();
+            if (maybe) |node| {
+                scanned += 1;
+                if (node.returned_at + retention_ms < now and kept_count >= min_warm) {
+                    allocator.free(node.toStack(size));
+                } else {
+                    self.queue.push(node);
+                    kept_count += 1;
+                }
+            } else break;
+        }
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a363217 and f4779f5.

📒 Files selected for processing (1)
  • src/stack_pool.zig (4 hunks)
🔇 Additional comments (3)
src/stack_pool.zig (3)

47-47: Queue field initialization LGTM; ensure zero-cost init across buckets.

Using ConcurrentQueue(T).empty looks fine for POD buckets. Just confirm the queue doesn’t require an allocator/capacity init.


8-8: The original review comment is incorrect. The code is memory-safe and well-designed.

The concerns raised don't reflect how ConcurrentQueue actually works:

  • Import path is valid: utils/concurrent_queue.zig correctly imports at src/ level (same as runtime.zig).
  • FreeListNode properly implements the intrusive queue interface with required next, prev, and in_list fields.
  • ConcurrentQueue is intrusive (stores pointers via T.next/T.prev), but guarantees memory safety for immediate free: When pop() completes, it has already removed the node from the linked list (clearing its pointers) while holding the mutation spinlock. After the lock is released, no other thread can access that node through list traversal.
  • The FIFO early-break in cleanupOld() is sound: FIFO guarantees that once the first "young" (recently returned) stack is encountered, all remaining stacks must be younger, so breaking is correct.

The code demonstrates proper concurrent data structure usage with sound reasoning about FIFO ordering and memory reclamation.

Likely an incorrect or invalid review comment.


86-91: Deinit must run after producers quiesce.

During task execution, stacks are released via stack_pool.release() → queue.push() (line 1102 in runtime.zig). Concurrently calling stack_pool.deinit() → queue.pop() creates a data race if tasks still execute. Ensure shutdown guarantees no further stack_pool.release() calls before deinit; optionally assert in debug mode to catch misuse.

Comment thread src/stack_pool.zig Resolved
Replace tasks HashMap with ConcurrentQueue(AnyTask) to enable lock-free
concurrent access from multiple threads. Tasks are pushed directly to the
queue during spawn(), eliminating the need for deferred initialization or
separate async notification mechanisms.

Changes:
- Add intrusive list fields (next/prev/in_list) to AnyTask
- Change Executor.tasks from HashMap to ConcurrentQueue
- Push to tasks queue directly in spawn() - thread-safe
- Allocation errors are immediate, not deferred
- Remove complexity: ~50 lines of deferred spawn infrastructure
- scheduleTask() already handles cross-thread notification via remote_wakeup

This allows spawn() to be called safely from any thread, including external
threads that aren't part of the executor pool.
Prevents race where spawn() could succeed after shutdown initiated by:
- Incrementing global_task_count before checking shutdown flag
- Using errdefer to rollback on error
- Proper memory ordering: .release for increments/decrements, .acquire for reads

This ensures when executor checks task_count == 0, no concurrent spawn()
can be in flight between the check and setting the shutdown flag.

@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 (2)
src/runtime.zig (2)

1717-1733: Metrics methods default to main executor.

getMetrics() and now() use only the main executor (index 0), which is documented but means worker executor metrics aren't visible. Consider returning aggregated metrics across all executors in future iterations if needed.


1846-2072: LGTM: New tests provide good coverage of multi-threaded features.

The tests comprehensively cover auto-detection, explicit executor counts, pinning, colocation, and shutdown error handling. The shutdown tests verify the error paths but don't stress-test the race condition.

Consider adding a stress test that spawns tasks from multiple external threads concurrently to verify the shutdown race fix once it's implemented.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ff9cc6e and a10175d.

📒 Files selected for processing (1)
  • src/runtime.zig (24 hunks)
⏰ 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 (26)
src/runtime.zig (26)

27-33: LGTM: executor_id field enables task pinning.

The new executor_id field in SpawnOptions clearly enables explicit executor pinning with good defaults (inherit or round-robin).


36-43: LGTM: num_executors configuration is well-designed.

The new num_executors field provides flexible configuration with sensible defaults that maintain backward compatibility (single-threaded by default).


53-58: LGTM: New error variants support shutdown gating and validation.

The InvalidExecutorId and RuntimeShutdown errors provide clear failure modes for the new multi-executor spawn logic.


132-145: LGTM: Shutdown callback correctly stops event loop.

The shutdown callback properly triggers loop termination for coordinated multi-executor shutdown.


311-329: LGTM: resumeTask correctly delegates to scheduleTask for cross-executor support.

The state assertion and delegation to scheduleTask with ResumeMode properly support cross-executor task resumption.


340-343: LGTM: Intrusive list fields support ConcurrentQueue-based task tracking.

The intrusive list node fields properly enable the task queue implementation.


478-479: LGTM: Stack release assertion validates executor cleanup.

The assertion that the stack is null during destruction correctly validates that the executor already released the stack during task completion.


681-693: LGTM: getExecutorId enables task colocation.

The new method properly exposes executor assignment for coroutine tasks, enabling colocation patterns.


742-742: LGTM: ConcurrentQueue import supports thread-safe task tracking.

The import is necessary for the thread-safe task queue implementation.


758-796: LGTM: Executor struct changes enable multi-threaded coordination.

The new fields properly support executor identification, thread-safe task management, shutdown coordination, and runtime back-references.


807-820: LGTM: Executor.init correctly defers loop initialization for thread-safety.

Separating struct setup from loop initialization enables safe initialization on the owning thread, which is required for xev's thread-local state.


822-856: LGTM: initLoop properly initializes event loop resources on the owning thread.

The initialization sequence correctly sets up the loop, async handles, and callbacks with proper error handling and memory ordering.


858-862: LGTM: deinitLoop correctly cleans up event loop resources.

The cleanup properly releases async handles and loop in reverse initialization order.


878-925: LGTM: executor.spawn is now thread-safe with ConcurrentQueue.

The switch from HashMap to ConcurrentQueue for task tracking (line 916) resolves the thread-safety concerns raised in past reviews. Concurrent external spawns can now safely target the same executor.


1152-1178: LGTM: scheduleTask correctly handles cross-executor task routing.

The local/remote path selection with initialization checks properly supports cross-executor task resumption.


1193-1195: LGTM: Alignment checks ensure safe timer userdata packing.

The compile-time assertions correctly validate that pointer alignment supports generation tagging in the lower 2 bits.

Also applies to: 1203-1205


1446-1455: Runtime struct properly supports multi-executor coordination.

The ArrayList(Executor) and atomic coordination fields enable multi-threaded runtime operation. Note: The shutdown race issue identified in the Executor.run() review applies to the shutting_down flag usage.


1460-1510: LGTM: Runtime.init correctly initializes multi-executor configuration.

The initialization properly handles auto-detection, executor creation, and coordination state setup with correct error handling.


1512-1531: LGTM: Runtime.deinit correctly cleans up multi-executor resources.

The cleanup sequence properly shuts down the thread pool, deinitializes executors, and frees resources in the correct order.


1534-1568: Runtime.spawn logic is mostly correct, but shutdown race persists.

The executor selection and bounds checking are correct. However, the shutdown gating at lines 1542-1544 is subject to the race condition identified in the Executor.run() review. The fix in that review must be applied in coordination with this spawn logic.

See the critical issue raised in the Executor.run() review (lines 1124-1135) for the shutdown race details and fix.


1571-1574: spawnBlocking shutdown check subject to same race.

The shutdown gating has the same race condition as Runtime.spawn() (though less critical since blocking tasks run on thread pool, not executors). Apply the same fix as described in the Executor.run() review.


1589-1594: LGTM: Worker thread entry point correctly runs executor.

The worker thread function properly executes the executor's event loop with error logging.


1596-1628: LGTM: Runtime.run correctly coordinates multi-threaded executor startup and shutdown.

The initialization, worker thread spawning, ready synchronization, and thread joining properly orchestrate multi-threaded execution.


1630-1641: LGTM: runUntilComplete correctly pins task to main executor.

Explicitly setting executor_id = 0 ensures the task runs on the main executor, which is the correct behavior for this convenience method.


1650-1698: LGTM: Runtime convenience methods correctly delegate to current executor.

The threadlocal current_executor pattern properly supports multi-executor delegation with appropriate guards for non-coroutine contexts.


1702-1707: LGTM: getCurrentTask correctly uses threadlocal current_executor.

The implementation properly supports multi-threaded runtime by using the threadlocal executor reference.

Comment thread src/runtime.zig Resolved
Add separate accepting_spawns flag to prevent race between task count
check and shutdown flag being set. Main executor now:
1. Sets accepting_spawns=false to gate new spawns
2. Re-checks global_task_count for tasks that snuck in
3. Either confirms shutdown or resets accepting_spawns=true

This prevents spawn() from succeeding after we observe count=0 but
before we can set shutdown flag and signal executors.

@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 (2)
src/runtime.zig (2)

1727-1731: Consider: exposing per-executor metrics in multi-threaded mode.

In multi-threaded mode, getMetrics() returns only the main executor's metrics. This hides activity on worker executors, making it difficult to observe:

  • Load distribution across executors
  • Worker executor performance
  • Task spawn/completion rates per executor

For debugging and monitoring multi-executor workloads, users would benefit from accessing individual executor metrics.

Consider returning []const ExecutorMetrics or adding getExecutorMetrics(executor_id: usize) ?ExecutorMetrics:

pub fn getMetrics(self: *Runtime) []const ExecutorMetrics {
    // Return slice of all executor metrics (read-only view)
    const metrics = self.allocator.alloc(ExecutorMetrics, self.executors.items.len) catch unreachable;
    for (self.executors.items, 0..) |*exec, i| {
        metrics[i] = exec.getMetrics();
    }
    return metrics;
}

Or add a simpler per-executor accessor:

pub fn getExecutorMetrics(self: *Runtime, executor_id: usize) ?ExecutorMetrics {
    if (executor_id >= self.executors.items.len) return null;
    return self.executors.items[executor_id].getMetrics();
}

1858-1892: Test coverage: auto-detect executor count is non-deterministic.

The test spawns tasks on an auto-detected number of executors but doesn't verify the actual count beyond >= 1. On single-core systems, this test behaves identically to single-threaded mode.

Consider adding an assertion or skip for meaningful multi-threaded testing:

// Skip test if only 1 executor (single-core system)
if (runtime.executors.items.len < 2) return error.SkipZigTest;

Or test with explicit count to ensure multi-executor logic is actually exercised.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a10175d and 8454f22.

📒 Files selected for processing (1)
  • src/runtime.zig (24 hunks)
⏰ 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 (6)
src/runtime.zig (6)

1124-1145: Shutdown coordination: verify two-phase check prevents all spawn races.

The two-phase shutdown check aims to prevent race conditions:

  1. Check global_task_count == 0 (line 1125)
  2. Set accepting_spawns = false (line 1127)
  3. Re-check global_task_count == 0 (line 1131)
  4. If still 0, initiate shutdown; else revert accepting_spawns = true (line 1143)

However, there's a subtle window between lines 1547-1550 in Runtime.spawn():

Thread A (spawn):          Thread B (main executor):
fetchAdd(1, .release)      
  global_task_count: 0→1   load(.acquire) == 0 ✓     [line 1125]
                           store(false, .release)     [line 1127]
                           load(.acquire) reads 1 ✓   [line 1131]
load(.acquire)             
  reads false ✗            
  returns RuntimeShutdown  [spawns incremented but will be rejected]
fetchSub(1, .release)
  global_task_count: 1→0

If the spawn's fetchAdd happens just after the first check but its accepting_spawns.load reads the stale true value before line 1127's store is visible, the spawn will proceed past the shutdown check but then be rejected at the errdefer, correctly decrementing the count.

Wait—the spawn does fetchAdd before checking accepting_spawns (line 1547 before line 1554). This means:

  • If spawn's fetchAdd happens after the main executor's first check (line 1125), the re-check (line 1131) will see count > 0 and revert to accepting spawns (line 1143). ✓ Correct.
  • If spawn's fetchAdd happens before the main executor's first check, spawn will either succeed (if before shutdown) or fail after the fetchAdd due to accepting_spawns == false, triggering errdefer to decrement. ✓ Correct.

The key insight: optimistic increment before checking the flag ensures the count reflects intent before the gate closes. The two-phase check catches increments that happen between the checks.

This pattern appears sound, but the memory ordering needs verification. Both fetchAdd(.release) and load(.acquire) use acquire/release, which should synchronize correctly. However, I should verify the memory model guarantees here.

Actually, on closer inspection, the synchronization is correct:

  • fetchAdd(1, .release) in spawn ensures the increment is visible to subsequent acquires
  • load(.acquire) in main executor (line 1125, 1131) synchronizes-with prior releases
  • store(false, .release) (line 1127) ensures the flag change is visible to subsequent acquires
  • load(.acquire) in spawn (line 1554) synchronizes-with the store

The two-phase check with optimistic increment is a valid pattern. No issue here.


1155-1188: Confirm: scheduleTask correctly handles task state transitions.

Line 1164 unconditionally sets task.coro.state = .ready, even for tasks that are being scheduled from spawn() (where they're already .ready from line 903 in Executor.spawn()).

For tasks resumed via resumeTask(), the state transition .waiting → .ready is correct (and line 324 asserts .waiting).

For tasks spawned via Executor.spawn(), setting .ready again is harmless (idempotent), but slightly redundant.

Minor concern: The unconditional state assignment could mask bugs where a task in an unexpected state is scheduled (e.g., .dead). The assertion at line 324 catches this for resumeTask(), but direct calls to scheduleTask() from other contexts wouldn't be guarded.

This is not a critical issue in the current code since scheduleTask() is only called from two places:

  1. Executor.spawn() (line 919) — task is .ready from line 903
  2. resumeTask() (line 328) — assertion at line 324 ensures .waiting

Both paths are safe, so this is more of a defensive coding consideration.


1545-1580: Verify: optimistic increment correctly coordinates with shutdown.

The pattern here is:

  1. Optimistically fetchAdd(1, .release) to global_task_count (line 1550)
  2. Check accepting_spawns.load(.acquire) (line 1554)
  3. If shutting down, errdefer decrements via fetchSub(1, .release) (line 1551)

This coordinates with the main executor's two-phase shutdown check (lines 1124-1145):

  • Main checks global_task_count == 0, sets accepting_spawns = false, re-checks count
  • If a spawn's fetchAdd happens between the checks, the re-check will see count > 0 and resume accepting spawns
  • If a spawn's fetchAdd happens after accepting_spawns is set false, the spawn fails and errdefer decrements

The memory ordering is correct:

  • fetchAdd(.release) makes the increment visible to subsequent load(.acquire) in main executor
  • load(.acquire) in spawn synchronizes with store(.release) in main executor
  • Errdefer ensures cleanup on all error paths

This implementation correctly prevents the race condition flagged in past reviews.


1582-1599: Assess: blocking tasks don't increment global_task_count—is this correct?

spawnBlocking() checks accepting_spawns but does not increment global_task_count. This means blocking tasks don't participate in shutdown coordination.

Is this correct? Blocking tasks run on the thread pool, not on executors. They don't prevent executor shutdown. However, if a blocking task completes and tries to wake a coroutine (via markComplete), that wakeup uses resumeTask(..., .maybe_remote) which calls executor.scheduleTask(). If executors have shut down, this could be problematic.

But wait: Shutdown only initiates when global_task_count == 0, meaning all coroutine tasks have completed. Blocking tasks can still be running, but:

  1. If no coroutines remain to wait on blocking tasks, they're "detached" (no JoinHandle held)
  2. If a coroutine is waiting on a blocking task, that coroutine is counted in global_task_count, so shutdown won't initiate

This is correct by design: coroutines that wait on blocking tasks keep the runtime alive. Orphaned blocking tasks don't prevent shutdown.


1608-1640: Verify: worker threads are properly synchronized before main executor runs.

The sequence is:

  1. Spawn worker threads for executors[1..] (line 1621)
  2. Wait for all workers to signal ready (lines 1625-1627)
  3. Run main executor (line 1630)
  4. Join worker threads (lines 1633-1637)

Each worker thread:

  1. Calls executor.run() → initLoop() → ready.set() (lines 1056-1061)
  2. Begins processing tasks

The ready.wait() loop ensures all worker loops are initialized before the main executor starts. This prevents:

  • Main executor notifying workers before their loops are ready
  • Race conditions in remote wakeup

However, there's a subtle issue: After ready.set() (line 1061), the worker immediately starts processing (line 1069 begins the main loop). There's no guarantee that all workers have started their loops before the main executor runs.

But wait—is this a problem? Let's trace what could happen:

  1. Main executor runs and spawns tasks on worker executors
  2. Tasks are enqueued via executor.scheduleTask() → next_ready_queue_remote.push() → remote_wakeup.notify()
  3. If worker loop isn't running yet, remote_wakeup.notify() might be called before the loop starts

Actually, remote_initialized (line 1179) gates the notify() call, and it's set to true in initLoop() (line 855) after the remote_wakeup callback is registered (line 834-840). The ready.set() (line 1061) happens after initLoop(), so by the time ready.wait() returns, remote_initialized == true and the loop is ready to receive notifications.

This is correct: the synchronization ensures workers are ready before main executor can send them tasks.


2032-2056: Test artificially triggers shutdown—verify behavior matches production.

Line 2047 manually sets accepting_spawns = false to simulate shutdown. However, in production, shutdown is triggered by global_task_count == 0 (line 1125), which also sets shutting_down = true (line 1133).

This test verifies spawn gating via accepting_spawns, but doesn't test the full shutdown sequence. The test should either:

  1. Trigger natural shutdown (spawn no tasks, let runtime drain), or
  2. Document that it's testing the gating mechanism in isolation

The current approach is valid but incomplete—it tests one component of the shutdown mechanism.

Consider adding a test that verifies the full shutdown sequence:

test "runtime: natural shutdown when all tasks complete" {
    const testing = std.testing;
    
    var runtime = try Runtime.init(testing.allocator, .{
        .num_executors = 2,
    });
    defer runtime.deinit();
    
    const TestContext = struct {
        fn task(rt: *Runtime) !void {
            try rt.sleep(10);
            // After this completes, global_task_count should reach 0
            // triggering natural shutdown
        }
        
        fn mainTask(rt: *Runtime) !void {
            var handle = try rt.spawn(task, .{rt}, .{});
            defer handle.deinit();
            try handle.join();
            // Runtime should shut down after this
        }
    };
    
    try runtime.runUntilComplete(TestContext.mainTask, .{&runtime}, .{});
    
    // Verify runtime shut down cleanly
    try testing.expect(runtime.shutting_down.load(.acquire));
}

@lalinsky
lalinsky merged commit 992d51d into main Oct 19, 2025
@lalinsky
lalinsky deleted the feature/multi-threaded-runtime branch October 19, 2025 06:32
@coderabbitai coderabbitai Bot mentioned this pull request Nov 12, 2025
2 tasks
lalinsky added a commit that referenced this pull request Nov 30, 2025
0a1b5ee Add custom kernel32 function wrappers (#56)
28c95bf Decouple ThreadPool from Loop using completion callbacks (#55)
e9d7b0a Add net_poll to socket operations in README
f0dcd13 Add NetPoll operation for socket readiness detection (#54)

git-subtree-dir: src/lib/aio
git-subtree-split: 0a1b5ee
lalinsky added a commit that referenced this pull request Nov 30, 2025
0a1b5ee Add custom kernel32 function wrappers (#56)
28c95bf Decouple ThreadPool from Loop using completion callbacks (#55)
e9d7b0a Add net_poll to socket operations in README
f0dcd13 Add NetPoll operation for socket readiness detection (#54)

git-subtree-dir: src/lib/aio
git-subtree-split: 0a1b5ee
lalinsky added a commit that referenced this pull request Jan 6, 2026
Create src/os/windows.zig with custom wrappers for all kernel32 functions
used in the codebase, decoupling from std.os.windows.kernel32. This
prepares the codebase for Zig 0.16 where std.posix will be removed.

Changes:
- Add src/os/windows.zig with wrappers for file, IOCP, thread/APC, and
  error handling functions
- Update src/os/fs.zig to use custom wrappers (w2.*)
- Update src/os/time.zig to use SleepEx wrapper
- Update src/backends/iocp.zig to use custom wrappers (w.*)
- Define PAPCFUNC type directly as it's not in std.os.windows

All tests passing on Windows (55/58, 3 IPv6 tests skipped).
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