Skip to content

Refactor spawnBlockingTask to bypass event loop - #192

Merged
lalinsky merged 2 commits into
mainfrom
refactor-blocking-task-bypass-loop
Jan 10, 2026
Merged

lalinsky merged 2 commits into
mainfrom
refactor-blocking-task-bypass-loop

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Summary

  • Submit blocking tasks directly to the thread pool instead of going through the executor's event loop
  • Fixes thread-safety issue where spawnBlocking() could be called from any thread but loop.add() was not designed for concurrent calls
  • Completion callback now runs on thread pool worker thread using thread-safe operations

Fixes #190

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
@coderabbitai

coderabbitai Bot commented Jan 10, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Replaces per-task completion wiring with thread-pool completion callbacks, submits blocking work directly to Runtime.thread_pool (bypassing the event loop), and adjusts task registration order and reference handling. Also removes the executor parameter from registerBlockingTask.

Changes

Cohort / File(s) Change Summary
Blocking task thread-pool refactor
src/runtime/blocking_task.zig
Replaces per-task completionCallback with a threadPoolCompletion callback and context. Work function derives a typed task pointer from userdata and invokes the task closure. registerBlockingTask signature removed the executor parameter, now increments task refcount, adds to rt.tasks, and submits the work item to rt.thread_pool directly (bypasses event loop). Adjusts awaitable completion, group bookkeeping, and reference release to run via the thread-pool completion context.
Task registration order change
src/runtime/task.zig
registerTask now increments the task's reference count before adding it to the runtime's task list; comment updated to reflect the new operation order.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

Threads once queued through the loop's soft hum,
Now to the pool they leap — no fuss, no drum.
A task gets counted, sent, and then set free,
Callbacks land safe where foreign threads can be.
Small change, clearer lines — let the workers run.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed Title clearly summarizes the main architectural change: bypassing the event loop for blocking task submission to fix thread-safety issues.
Description check ✅ Passed Description directly addresses the changeset—explains the thread-safety problem, the solution (direct thread pool submission), and references the fixed issue.
Linked Issues check ✅ Passed Code changes fully implement issue #190 requirements: bypass event loop, submit directly to thread pool, use thread-safe completion handling, and fix concurrent call safety.
Out of Scope Changes check ✅ Passed All changes are scoped to the blocking task submission path. The reference count ordering adjustment in task.zig aligns with preventing race conditions during task registration.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor-blocking-task-bypass-loop

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

📥 Commits

Reviewing files that changed from the base of the PR and between c4c9a9f and a6dd59f.

📒 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. registerGroupTask safely handles the group path from any thread:

  • Counter increments use atomic .acq_rel operations
  • isClosed() checks are atomic
  • CompactWaitQueue.pushUnless() is thread-safe via atomic head pointer with mutation spinlock and proper memory ordering (.acq_rel)
  • Flag operations use atomic RMW with .acq_rel semantics
  • The non-atomic write to group_node.group is effectively synchronized by the happens-before relationship established by the surrounding atomic operations

Likely an incorrect or invalid review comment.


103-119: The callback is thread-safe. markComplete() uses atomic operations with release semantics, onGroupTaskComplete() uses @atomicRmw on the counter and thread-safe queue operations, and releaseAwaitable() calls WaitQueue.remove() which internally uses atomic mutation locks (acquireMutationLock/releaseMutationLock with .acquire/.release semantics). All three functions handle concurrent access correctly without requiring external synchronization at the call site.

Comment thread src/runtime/blocking_task.zig Resolved
Comment thread src/runtime/blocking_task.zig Resolved
Ensures reference count is correct before task becomes visible to
other threads, avoiding race conditions.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 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

📥 Commits

Reviewing files that changed from the base of the PR and between a6dd59f and 57f520d.

📒 Files selected for processing (2)
  • src/runtime/blocking_task.zig
  • src/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.zig
  • 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/task.zig
  • 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/task.zig
  • src/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 consistent

Casting work.userdata back to *AnyBlockingTask is straightforward and avoids extra indirections. Small footgun to avoid later: make sure any future changes don’t set completion_context to something different than work.userdata unless that’s explicitly intended.


121-128: registerBlockingTask ordering is correct; submit cannot fail

The 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 needed

The concern holds merit, but the code handles it properly. registerGroupTask uses 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 execution

markComplete() atomically transitions the state with .release semantics 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 learnings

Moving task.awaitable.ref_count.incr() before rt.tasks.add() is correct and necessary to avoid "published with too-low refcount" races. Since RefCounter.init() starts at 1 and tasks are stored in rt.tasks at count=2 (one for runtime ownership, one for the handle), the incr must happen before publishing. The removal path correctly calls rt.tasks.remove() followed by awaitable.ref_count.decr(), maintaining the expected 1:1 balance. No leak or ownership drift detected.

Comment thread src/runtime/blocking_task.zig Resolved
Repository owner deleted a comment from claude Bot Jan 10, 2026
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.

Refactor spawnBlockingTask to bypass event loop

1 participant