Repository navigation
Refactor spawnBlockingTask to bypass event loop - #192
Conversation
Submit blocking tasks directly to the thread pool instead of going through the executor's event loop. This fixes a thread-safety issue where spawnBlocking() could be called from any thread but loop.add() was not designed for concurrent calls. The completion callback now runs on the thread pool worker thread and uses thread-safe operations (atomic wait queues, ref counting) to mark tasks complete and wake waiters. Fixes #190
📝 WalkthroughWalkthroughReplaces per-task completion wiring with thread-pool completion callbacks, submits blocking work directly to Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches🧪 Generate unit tests (beta)
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: 2
🤖 Fix all issues with AI agents
In @src/runtime/blocking_task.zig:
- Around line 95-101: The worker function workFunc is unwrapping work.userdata
with work.userdata.? which will trap on mis-initialization; make the invariant
explicit by asserting work.userdata != null at the start of workFunc (or
otherwise handling the null case) before doing the @ptrCast/@alignCast to
AnyBlockingTask, then use the non-null value for the cast and subsequent
task.closure.call; reference the workFunc function and AnyBlockingTask to locate
and update the check so the failure mode is deterministic and clear.
- Around line 121-128: The registerBlockingTask function publishes the awaitable
into shared rt.tasks before incrementing its ref_count, risking a transiently
published object with an incorrect refcount; change the order so you call
task.awaitable.ref_count.incr() before calling rt.tasks.add(&task.awaitable)
(and keep rt.thread_pool.submit(&task.work) after these steps) to ensure the
reference count is incremented prior to making the awaitable visible to other
threads.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/runtime/blocking_task.zig
🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: lalinsky
Repo: lalinsky/zio PR: 18
File: src/net.zig:18-25
Timestamp: 2025-10-03T11:09:46.846Z
Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.
📚 Learning: 2025-10-03T11:09:46.846Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 18
File: src/net.zig:18-25
Timestamp: 2025-10-03T11:09:46.846Z
Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.
Applied to files:
src/runtime/blocking_task.zig
📚 Learning: 2025-11-04T10:29:56.949Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 118
File: src/core/task.zig:33-115
Timestamp: 2025-11-04T10:29:56.949Z
Learning: In zio's task implementation (src/core/task.zig), the Closure struct intentionally caps result_len and context_len at 4096 bytes (using u12 fields) and alignment at 16 bytes (using u4 padding fields). This is a deliberate design decision to avoid bloating task structures. Users needing larger result or context storage should heap-allocate and pass pointers instead. These limits are more generous than std lib's fixed storage (64 bytes for results, 1024 bytes for args).
<!-- [add_learning]
The task storage limits in zio (4 KiB for result/context, 16-byte alignment) are intentional design constraints to prevent task bloat, not correctness issues. The maintainer's position is that larger data should be heap-allocated.
Applied to files:
src/runtime/blocking_task.zig
📚 Learning: 2026-01-10T13:55:00.163Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/runtime/blocking_task.zig:117-146
Timestamp: 2026-01-10T13:55:00.163Z
Learning: In Zig files, do not reference libxev for async I/O. The project uses a custom event loop implementation under src/ev/ and a callback-based async I/O loop similar to libuv/libxev. Reviewers should ensure code relies on the src/ev event loop and that there are no libxev usage patterns; prefer the central event loop in src/ev/ for all asynchronous operations.
Applied to files:
src/runtime/blocking_task.zig
📚 Learning: 2026-01-10T14:08:37.019Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/stdio.zig:117-129
Timestamp: 2026-01-10T14:08:37.019Z
Learning: In Zig files implementing swap-like semantics (e.g., old = swap(new); defer swap(old)), ensure the return value is an opaque restoration token rather than a direct reflection of internal state. Rely on the contract to perform increment/decrement logic internally (e.g., shield_count) and not expose internal state through the token. This makes behavior predictable, supports refactoring, and avoids leaking internal state across calls. Apply this pattern broadly to Zig code that uses a paired-swap or restoration-token mechanism.
Applied to files:
src/runtime/blocking_task.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: test (windows-latest)
🔇 Additional comments (3)
src/runtime/blocking_task.zig (3)
82-84: Good: completion callback is wired before submission, and it doesn’t free the result.
This matches the intended ownership model (wrapper freed by runtime, result owned by caller). Based on learnings, result ownership is caller-side.
132-157: The thread-safety claim is accurate and doesn't need narrowing.registerGroupTasksafely handles the group path from any thread:
- Counter increments use atomic
.acq_reloperationsisClosed()checks are atomicCompactWaitQueue.pushUnless()is thread-safe via atomic head pointer with mutation spinlock and proper memory ordering (.acq_rel)- Flag operations use atomic RMW with
.acq_relsemantics- The non-atomic write to
group_node.groupis effectively synchronized by the happens-before relationship established by the surrounding atomic operationsLikely an incorrect or invalid review comment.
103-119: The callback is thread-safe.markComplete()uses atomic operations with release semantics,onGroupTaskComplete()uses@atomicRmwon the counter and thread-safe queue operations, andreleaseAwaitable()callsWaitQueue.remove()which internally uses atomic mutation locks (acquireMutationLock/releaseMutationLockwith.acquire/.releasesemantics). All three functions handle concurrent access correctly without requiring external synchronization at the call site.
Ensures reference count is correct before task becomes visible to other threads, avoiding race conditions. Co-authored-by: Lukáš Lalinský <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In @src/runtime/blocking_task.zig:
- Around line 82-85: The completion callback for a work item isn’t invoked when
thread_pool.cancel() removes the work from the queue, leaking the ref_count
increment done by registerBlockingTask(); update cancel() so that after it
successfully removes a work item it invokes that item's completion path (call
the stored completion_fn with completion_context or directly call
threadPoolCompletion/releaseAwaitable) exactly once for that work, mirroring the
case where runTasks() pops and runs completion_fn, so waiters get released and
the ref_count is balanced.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/runtime/blocking_task.zigsrc/runtime/task.zig
🧰 Additional context used
🧠 Learnings (6)
📚 Learning: 2025-09-27T04:41:48.632Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 5
File: src/runtime.zig:257-273
Timestamp: 2025-09-27T04:41:48.632Z
Learning: RefCounter.init() starts with an initial count of 1, not 0. When a task is created in spawn(), the initial count represents the runtime's ownership when stored in self.tasks, and an additional incr() is called for the returned Task(T) handle.
Applied to files:
src/runtime/task.zigsrc/runtime/blocking_task.zig
📚 Learning: 2026-01-10T13:55:00.163Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/runtime/blocking_task.zig:117-146
Timestamp: 2026-01-10T13:55:00.163Z
Learning: In Zig files, do not reference libxev for async I/O. The project uses a custom event loop implementation under src/ev/ and a callback-based async I/O loop similar to libuv/libxev. Reviewers should ensure code relies on the src/ev event loop and that there are no libxev usage patterns; prefer the central event loop in src/ev/ for all asynchronous operations.
Applied to files:
src/runtime/task.zigsrc/runtime/blocking_task.zig
📚 Learning: 2026-01-10T14:08:37.019Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/stdio.zig:117-129
Timestamp: 2026-01-10T14:08:37.019Z
Learning: In Zig files implementing swap-like semantics (e.g., old = swap(new); defer swap(old)), ensure the return value is an opaque restoration token rather than a direct reflection of internal state. Rely on the contract to perform increment/decrement logic internally (e.g., shield_count) and not expose internal state through the token. This makes behavior predictable, supports refactoring, and avoids leaking internal state across calls. Apply this pattern broadly to Zig code that uses a paired-swap or restoration-token mechanism.
Applied to files:
src/runtime/task.zigsrc/runtime/blocking_task.zig
📚 Learning: 2025-10-03T11:09:46.846Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 18
File: src/net.zig:18-25
Timestamp: 2025-10-03T11:09:46.846Z
Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.
Applied to files:
src/runtime/blocking_task.zig
📚 Learning: 2025-11-04T10:29:56.949Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 118
File: src/core/task.zig:33-115
Timestamp: 2025-11-04T10:29:56.949Z
Learning: In zio's task implementation (src/core/task.zig), the Closure struct intentionally caps result_len and context_len at 4096 bytes (using u12 fields) and alignment at 16 bytes (using u4 padding fields). This is a deliberate design decision to avoid bloating task structures. Users needing larger result or context storage should heap-allocate and pass pointers instead. These limits are more generous than std lib's fixed storage (64 bytes for results, 1024 bytes for args).
<!-- [add_learning]
The task storage limits in zio (4 KiB for result/context, 16-byte alignment) are intentional design constraints to prevent task bloat, not correctness issues. The maintainer's position is that larger data should be heap-allocated.
Applied to files:
src/runtime/blocking_task.zig
📚 Learning: 2025-10-16T14:33:19.718Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 48
File: src/core/ConcurrentAwaitableList.zig:254-269
Timestamp: 2025-10-16T14:33:19.718Z
Learning: In the zio repository's `src/core/ConcurrentAwaitableList.zig` and `src/core/Awaitable.zig`, the `in_list` field should remain debug-only (conditional compilation with `builtin.mode == .Debug`). Double-removal detection in `ConcurrentAwaitableList.remove()` uses pointer-based checks (comparing `prev`/`next` against `head`/`tail`) rather than relying on a regular `in_list` field.
Applied to files:
src/runtime/blocking_task.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: test (windows-latest)
- GitHub Check: test (macos-latest)
🔇 Additional comments (5)
src/runtime/blocking_task.zig (4)
95-101: workFunc userdata cast looks correct; keep userdata/context consistentCasting
work.userdataback to*AnyBlockingTaskis straightforward and avoids extra indirections. Small footgun to avoid later: make sure any future changes don’t setcompletion_contextto something different thanwork.userdataunless that’s explicitly intended.
121-128: registerBlockingTask ordering is correct; submit cannot failThe ref_count increment before publishing (add to task list) and before submit is the correct race-proof order.
The submit function returns void and cannot fail—queue operations don't return errors, and the only potential failure (thread spawn) is already handled with a catch block inside submit. No error handling or unwinding is needed in registerBlockingTask.
130-157: registerGroupTask handles thread-safety correctly with atomics—no guard neededThe concern holds merit, but the code handles it properly.
registerGroupTaskuses atomic operations with acq_rel ordering: it atomically increments the counter, then sets the group pointer, then pushes to the task list with a sentinel check to prevent races on closed groups. The acq_rel pairing ensures memory visibility across threads. If the push fails (group closed), the counter is atomically rolled back. This is lock-free synchronization, not mutex-based, so it's safe from arbitrary threads by design.Also confirms the codebase is sticking to its local locking patterns (
src/ev/+ thread pool approach) rather than pulling in external event loop assumptions. Solid thread-local design here.
103-119: All three functions are genuinely thread-safe for worker-thread executionmarkComplete() atomically transitions the state with
.releasesemantics and wakes waiters through a concurrent waiting list. onGroupTaskComplete() removes from the group's task list using pointer-based checks (matching the design pattern you're using elsewhere), atomically decrements the group counter with.acq_rel, and signals with Futex. releaseAwaitable() handles the ref count decrement atomically and, when called from a worker thread (done=true), removes from the global task list under the shutdown_mutex if needed—a lock only held briefly during shutdown iteration.The ref counting pattern works: the runtime increments when registering a blocking task, and releaseAwaitable decrements it only after all bookkeeping is done. If markComplete wakes a waiter that immediately drops its handle, the awaitable stays alive because the runtime's ref keeps it around until releaseAwaitable executes. The boolean flag semantics are correct: true from worker threads (removes from global list, wakes main executor), false from executor cleanup paths (group cancellation, where the list is already managed).
This matches the PR goal—no event loop calls from foreign threads, only atomic operations and futex wakeups.
src/runtime/task.zig (1)
414-422: Refcount ordering is sound; balanced against learningsMoving
task.awaitable.ref_count.incr()beforert.tasks.add()is correct and necessary to avoid "published with too-low refcount" races. SinceRefCounter.init()starts at 1 and tasks are stored inrt.tasksat count=2 (one for runtime ownership, one for the handle), the incr must happen before publishing. The removal path correctly callsrt.tasks.remove()followed byawaitable.ref_count.decr(), maintaining the expected 1:1 balance. No leak or ownership drift detected.
Summary
spawnBlocking()could be called from any thread butloop.add()was not designed for concurrent callsFixes #190