Repository navigation
Simplify blocking task completion and move spawnBlocking to Runtime - #55
Conversation
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).
WalkthroughConsolidates blocking-task handling into Runtime: Executor no longer stores or manages thread-pool or blocking-completion state. Changes
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 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
📒 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?
There was a problem hiding this comment.
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 ifruntime.thread_poolis null. WhileRuntime.spawnBlockingchecks for null before calling this function,BlockingTask.initis public and could be called directly by users. Consider either:
- Adding an explicit null check with a clear error message
- Documenting that
thread_poolmust be initialized- Making
initnon-public if direct usage isn't intendedApply 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
📒 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
markCompletefrom the thread pool callback is thread-safe and eliminates the need for the blocking_completions queue and async wakeup machinery. ThemarkCompletefunction uses proper atomic operations and handles cross-thread wakeups via the.maybe_remotepath inresumeTask.
1391-1403: LGTM! Clean refactoring that moves blocking task ownership to Runtime.The rewritten
spawnBlockingmethod properly:
- Validates thread pool availability with a clear error
- Creates
BlockingTaskdirectly using the runtime's thread pool- Returns a properly initialized
JoinHandleThis 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).
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
Two refactorings to improve the blocking task architecture:
Call markComplete() directly from thread pool callback
Move spawnBlocking from Executor to Runtime level
Both changes simplify the codebase while maintaining full thread safety. All tests pass (98/98).
Summary by CodeRabbit