Skip to content

Simplify blocking task completion and move spawnBlocking to Runtime - #55

Merged
lalinsky merged 3 commits into
mainfrom
refactor/move-spawn-blocking-to-runtime
Oct 18, 2025
Merged

lalinsky merged 3 commits into
mainfrom
refactor/move-spawn-blocking-to-runtime

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 18, 2025 •

Copy link
Copy Markdown
Owner

Two refactorings to improve the blocking task architecture:

  1. Call markComplete() directly from thread pool callback

    • Remove async wakeup machinery (drainBlockingCompletions callback)
    • markComplete() is already thread-safe and handles cross-thread wakeup
    • Eliminates blocking_completions queue and associated infrastructure
    • ~50 lines of code removed
  2. Move spawnBlocking from Executor to Runtime level

    • Thread pool is owned by Runtime, not Executor
    • Remove Executor.thread_pool field (was just a reference)
    • Executor.init() receives thread_pool parameter for xev.Loop.init()
    • BlockingTask.init() now uses runtime.thread_pool directly
    • More logical API: blocking tasks at Runtime level where thread pool lives

Both changes simplify the codebase while maintaining full thread safety. All tests pass (98/98).

Summary by CodeRabbit

  • Refactor
    • Simplified executor/runtime internals and centralized thread-pool usage for scheduling blocking work.
    • Blocking-task spawning path simplified and direct completion handling added, reducing main-loop wakeups.
    • Reduced internal surface area and task plumbing, yielding lower latency for blocking tasks and improved overall performance.

Two refactorings to improve the blocking task architecture:

1. Call markComplete() directly from thread pool callback
   - Remove async wakeup machinery (drainBlockingCompletions callback)
   - markComplete() is already thread-safe and handles cross-thread wakeup
   - Eliminates blocking_completions queue and associated infrastructure
   - ~50 lines of code removed

2. Move spawnBlocking from Executor to Runtime level
   - Thread pool is owned by Runtime, not Executor
   - Remove Executor.thread_pool field (was just a reference)
   - Executor.init() receives thread_pool parameter for xev.Loop.init()
   - BlockingTask.init() now uses runtime.thread_pool directly
   - More logical API: blocking tasks at Runtime level where thread pool lives

Both changes simplify the codebase while maintaining full thread safety.
All tests pass (98/98).
@coderabbitai

coderabbitai Bot commented Oct 18, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Consolidates blocking-task handling into Runtime: Executor no longer stores or manages thread-pool or blocking-completion state. spawnBlocking now constructs and schedules BlockingTask via runtime.thread_pool; threadPoolCallback marks awaitables complete and releases them directly through Runtime.

Changes

Cohort / File(s) Summary
Runtime / Executor (single-file refactor)
src/runtime.zig
Removed Executor fields: thread_pool, blocking_completions, async_wakeup, async_completion, blocking_initialized; removed Executor blocking plumbing and related init/deinit logic.
Blocking scheduling & API
src/runtime.zig
Runtime.spawnBlocking now constructs BlockingTask via BlockingTask.init using runtime.thread_pool and allocator; returns JoinHandle tied to blocking awaitable; removed Executor-based spawnBlocking path.
Thread-pool callback & completion handling
src/runtime.zig
threadPoolCallback now marks awaitable complete and releases it directly via Runtime instead of pushing to blocking_completions and signalling Executor; removed drainBlockingCompletions.
References updated
src/runtime.zig
Replaced remaining executor.thread_pool usages with runtime.thread_pool; removed routing of blocking work through Executor.

Sequence Diagram(s)

sequenceDiagram
    participant App as Application
    participant RT as Runtime
    participant TP as ThreadPool
    participant CB as threadPoolCallback
    participant A as Awaitable

    App->>RT: spawnBlocking(func, args)
    RT->>RT: BlockingTask.init(..., runtime.thread_pool)
    RT->>TP: schedule blocking task
    TP->>CB: run blocking callback
    CB->>A: markComplete()
    CB->>RT: release awaitable
    RT->>App: awaiter resumes
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 I hopped from Executor to Runtime's shore,
Thread-pool in paw, I needed no more,
Awaitables marked with a soft little tap,
No queues to drain, no waking clap,
A cleaner hop — now back to my nap 🥕

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 "Simplify blocking task completion and move spawnBlocking to Runtime" directly and comprehensively summarizes both main changes in this changeset: the simplification of blocking task completion (removing async wakeup machinery and the drainBlockingCompletions queue) and the relocation of spawnBlocking from Executor to Runtime level. The title uses specific, meaningful terminology related to the primary refactoring objectives rather than vague generic terms, and a teammate scanning the git history would immediately understand the core purpose of these changes.
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/move-spawn-blocking-to-runtime

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dde6e94 and 85168ca.

📒 Files selected for processing (1)
  • src/runtime.zig (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/runtime.zig

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

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)

163-178: Thread join on canceled BlockingTask can crash (no result set) — handle cancellation in thread path.

If a BlockingTask is canceled before it starts, execute_fn is skipped and future_result is never set. In the thread path of waitForComplete(), we’ll return successfully (no error) and later unwrap a nonexistent result (.? crash). Fix by detecting cancellation and returning error.Canceled from the thread path.

Apply this diff:

         // Thread path: use ThreadWaiter for futex-based parking
         var thread_waiter = ThreadWaiter.init();
         awaitable.waiting_list.push(&thread_waiter.wait_node);

         // Double-check before parking (avoid lost wakeup)
         if (awaitable.done.load(.acquire)) {
             _ = awaitable.waiting_list.remove(&thread_waiter.wait_node);
             return;
         }
+        // Respect cancellation for thread waiters too
+        if (awaitable.canceled.load(.acquire)) {
+            _ = awaitable.waiting_list.remove(&thread_waiter.wait_node);
+            return error.Canceled;
+        }

         // Wait loop - check done flag and park on thread_waiter futex
         while (true) {
             if (awaitable.done.load(.acquire)) break;
+            if (awaitable.canceled.load(.acquire)) {
+                _ = awaitable.waiting_list.remove(&thread_waiter.wait_node);
+                return error.Canceled;
+            }
             std.Thread.Futex.wait(&thread_waiter.futex_state, 0);
         }

232-247: Timeout path leaves thread waiter enqueued → potential UAF when task completes later.

In timedWaitForComplete()’s thread path, on error.Timeout you return without removing thread_waiter from the awaitable’s waiting_list. If the task completes later, markComplete() will wake a stale node, causing UAF. Ensure removal on all exit paths and also return error.Canceled if canceled.

Apply this diff:

     // Thread path: use ThreadWaiter with futex timedWait
     var thread_waiter = ThreadWaiter.init();
-    awaitable.waiting_list.push(&thread_waiter.wait_node);
+    awaitable.waiting_list.push(&thread_waiter.wait_node);
+    // Always attempt to unlink on exit; safe if already popped
+    defer {
+        _ = awaitable.waiting_list.remove(&thread_waiter.wait_node);
+    }

     // Double-check before parking (avoid lost wakeup)
     if (awaitable.done.load(.acquire)) {
-        _ = awaitable.waiting_list.remove(&thread_waiter.wait_node);
         return;
     }
+    if (awaitable.canceled.load(.acquire)) {
+        return error.Canceled;
+    }

     // Wait loop with timeout - check done flag and park on thread_waiter futex
     while (true) {
         if (awaitable.done.load(.acquire)) break;
+        if (awaitable.canceled.load(.acquire)) return error.Canceled;
         try std.Thread.Futex.timedWait(&thread_waiter.futex_state, 0, timeout_ns);
     }
🧹 Nitpick comments (2)
src/runtime.zig (2)

579-581: Scheduling via Runtime.thread_pool is correct; consider graceful behavior on shutdown.

The switch to runtime-owned ThreadPool and direct schedule() looks right. If xev.ThreadPool.schedule() can fail or ignore work after shutdown, guard against scheduling during Runtime.deinit by returning error.Shutdown or similar from spawnBlocking/init paths once shutdown begins.


1518-1585: select() may pick a canceled BlockingTask that has no result and then .? unwrap — prefer skipping canceled handles or surface error.

Because threadPoolCallback skips execute on cancellation and we don’t set a result, awaitable.done=true but future_result is unset. select() uses hasResult() (done flag) and then getResult() (unwrap), which will fail. Options:

  • Skip canceled handles when choosing the winner; if all done are canceled, return error.Canceled.
  • Or add a lightweight “is_set” check in FutureResult to let select() distinguish “done with value” vs “done due to cancel.”

I can sketch a small guard here once you confirm preferred semantics.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fc13490 and 5e8e559.

📒 Files selected for processing (1)
  • src/runtime.zig (3 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 (macos-latest)
🔇 Additional comments (2)
src/runtime.zig (2)

95-101: Pool-thread completion path looks good; verify remote wake pre-init is guaranteed.

Directly calling markComplete() from the pool thread and then releasing the awaitable is correct and removes the extra plumbing. One caveat: resumeTask(.maybe_remote) asserts remote_initialized in Executor.markReady for cross-thread wake. Please confirm run() has called ensureRemoteInitialized() before any coroutine can wait on a BlockingTask that may complete on the pool thread. If not guaranteed, we need a fallback (e.g., initializing remote wake lazily when first resuming remotely).


1397-1407: Moving spawnBlocking to Runtime simplifies the API — LGTM.

Clear error on missing pool and direct construction via BlockingTask.init(), returning a JoinHandle. Nice cleanup.

Minor: Do you want error.ThreadPoolRequired added to a public error set (e.g., ZioError) for consistency?

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

579-579: Consider adding a null check or documentation.

The unwrap operator .? will panic if runtime.thread_pool is null. While Runtime.spawnBlocking checks for null before calling this function, BlockingTask.init is public and could be called directly by users. Consider either:

  1. Adding an explicit null check with a clear error message
  2. Documenting that thread_pool must be initialized
  3. Making init non-public if direct usage isn't intended

Apply this diff to add defensive error handling:

-            runtime.thread_pool.?.schedule(
+            const thread_pool = runtime.thread_pool orelse return error.ThreadPoolRequired;
+            thread_pool.schedule(
                 xev.ThreadPool.Batch.from(&task_data.blocking_task.impl.base.thread_pool_task),
             );
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5e8e559 and dde6e94.

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

95-101: LGTM! Excellent simplification of blocking task completion.

The direct call to markComplete from the thread pool callback is thread-safe and eliminates the need for the blocking_completions queue and async wakeup machinery. The markComplete function uses proper atomic operations and handles cross-thread wakeups via the .maybe_remote path in resumeTask.


1391-1403: LGTM! Clean refactoring that moves blocking task ownership to Runtime.

The rewritten spawnBlocking method properly:

  • Validates thread pool availability with a clear error
  • Creates BlockingTask directly using the runtime's thread pool
  • Returns a properly initialized JoinHandle

This provides a more logical API where blocking task functionality resides at the Runtime level alongside thread pool ownership.


1039-1039: LGTM!

The conditional loop run logic correctly blocks when idle (.once) and polls when work is ready (.no_wait).

@lalinsky
lalinsky merged commit be78f1f into main Oct 18, 2025
@lalinsky
lalinsky deleted the refactor/move-spawn-blocking-to-runtime branch October 18, 2025 20:24
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
Replace Work's loop and linked fields with completion_fn and
completion_context callback pattern. This removes all coupling
between ThreadPool and Loop, making ThreadPool a generic work
executor usable with any event system.

Changes:
- Work struct now has completion_fn/completion_context instead of loop/linked
- Work.init() API unchanged - callbacks set by Loop.add()
- ThreadPool calls completion callback after work execution
- Added loopWorkComplete() and loopLinkedWorkComplete() helpers
- File operation internal structs store LinkedWorkContext inline
- No heap allocations needed for completion routing
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