Skip to content

feat: work stealing - #541

Closed
notxorand wants to merge 18 commits into
lalinsky:mainfrom
notxorand:work_stealing
Closed

notxorand wants to merge 18 commits into
lalinsky:mainfrom
notxorand:work_stealing

Conversation

@notxorand

Copy link
Copy Markdown
Contributor

closes: #460

+ replace individual ready queues with a multi-stack pool per executor
+ introduce work stealing logic to balance task distribution
+ add a centralized global task queue protected by a mutex
+ update scheduler to periodically check for global or stolen tasks
+ add `pop` method to `ConcurrentStack` for atomic item retrieval
@coderabbitai

coderabbitai Bot commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: efd2d0cd-777e-488f-b3ba-577848ff9cfd

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The runtime scheduler now uses per-executor stealable stacks plus a global queue, with atomic readiness tracking and idle-executor wake coordination. ConcurrentStack gains atomic pop support, and the runtime scheduling paths are updated for local, remote, stealing, and wake-up handling.

Changes

Executor scheduling and work-stealing rewrite

Layer / File(s) Summary
ConcurrentStack pop primitive
src/utils/concurrent_stack.zig
Adds atomic pop() that swaps the head and returns the removed node, or null if empty.
Executor and Runtime state fields
src/runtime.zig
Replaces ready_queue/next_ready_queue_remote with queue_pool (stealable stacks), atomic ready_count, pop_cursor/push_cursor; adds Runtime's global_queue, global_queue_mutex, idle_mask, searchers.
Task selection and local scheduling
src/runtime.zig
maybeYield reads ready_count atomically; getNextTask scans/pops the rotating stack pool; scheduleTaskLocal pushes into queue_pool and updates ready_count.
Run loop and stealing
src/runtime.zig
Run loop drains the stack pool, tracks idleness, chooses wait mode from checkAboutForWork, and steals from other executors or the global queue when local work is empty.
Remote dispatch and wakeOne
src/runtime.zig
scheduleTask picks local vs home placement, remote tasks go through the mutex-protected global queue, and wakeOne signals one idle executor.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

  • lalinsky/zio#56: Same file overhaul—queue_pool, idle_mask/searchers, and global_queue/wakeOne changes overlap directly.
  • lalinsky/zio#61: Rewrites the same scheduleTask* and getNextTask paths for local vs remote work selection.
  • lalinsky/zio#296: Also changes executor run/yield flow and getNextTask task selection logic.

Poem

Stacks now multiply, one queue no more,
idle loops go hunting through the floor.
A tiny pop() lifts work in hand,
and wakeups nudge the sleeping band.
Bits, cursors, mutexes—clean and neat,
the scheduler finally moves with its feet.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: adding work stealing for executor load balancing.
Description check ✅ Passed The description is related to the issue by closing #460, even though it adds no detail.
Linked Issues check ✅ Passed The PR implements work stealing so idle executors can pull ready tasks from busy ones, which matches #460.
Out of Scope Changes check ✅ Passed The changes stay focused on scheduler work stealing and the supporting concurrent stack pop helper.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

+ optimize `has_local_work` check by simplifying condition logic
+ use `unreachable` for mutex locking to reflect system constraints
+ update task stealing to re-queue tasks already processed this tick
+ panic on failed remote task scheduling to prevent silent failures

@lalinsky lalinsky left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

This is a critical core part of the library, so be prepared that I'll be hard on the review. :)

Nothing, but a perfect solution, will be accepted.

Comment thread src/utils/concurrent_stack.zig Resolved
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
notxorand added 3 commits July 5, 2026 11:48
+ replace custom mutex with `std.Io.Mutex` for global queue
  synchronization
+ update mutex methods to accept IO instance
+ limit task draining to the current executor's stack
+ adjust global queue check frequency in `getNextTask`
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
notxorand added 5 commits July 6, 2026 13:02
+ simplify global queue locking by removing I/O context dependencies.
+ integrate periodic global queue polling directly into the executor
  task loop.
+ remove error handling from scheduleTaskRemote as the mutex operations
  are now infallible.
@notxorand

Copy link
Copy Markdown
Contributor Author

@lalinsky, I think the mutex might need a way to let us know it didn't succeed. e.g., a situation where we previously locked and we're attempting to lock again. really, the only issue might be logic bugs, but it seems to happen (ran into one today 😅)

+ add `idle_mask` and `searchers` atomic fields to `Runtime` to track
  executor activity.
+ introduce `checkAboutForWork` to encapsulate local, stolen, and global
  task discovery.
+ update worker loop to manage idle bit during blocking I/O calls.
+ implement `wakeOne` to target a single idle executor instead of
  broadcasting wakeups.
@notxorand
notxorand marked this pull request as ready for review July 6, 2026 22:03
@notxorand
notxorand requested a review from lalinsky July 6, 2026 22:03

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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/runtime.zig`:
- Line 512: The global-queue pop path in the runtime still contains a leftover
debug statement, so remove the `std.debug.print` call from the queue-pop logic
in `runtime.zig` to avoid printing on every successful pop. Locate the debug
output inside the code path that performs the global queue pop and delete it,
keeping the rest of the queue handling unchanged.
- Around line 633-647: The task migration option is not affecting dispatch
because Runtime.initStatic still assigns the shared loop_group and
scheduleTask() still always routes tasks through the current/home executor path.
Update Runtime.initStatic, Executor, and scheduleTask to branch on
enable_task_migration so non-migration mode keeps tasks local to one executor
and does not use the shared/global queue, or remove enable_task_migration
entirely if it is always enabled.
- Around line 533-543: The steal path in the queue-pool loop is leaving the
victim executor’s ready_count unchanged after tasks are removed by popAll(), so
adjust the victim’s counter when transferring work in the steal logic around
victim.queue_pool, push_cursor, and ready_count. Update the stealing code to
decrement victim.ready_count by the number of drained tasks before or after
moving them, while still incrementing self.ready_count for the stolen tasks, so
maybeYield() reflects the victim’s actual remaining work.
- Around line 461-473: Reset runtime.searchers on both execution paths in the
worker loop around checkAboutForWork and the idle_mask handling, because
wakeOne() relies on the 0 -> 1 transition and the current early-return path
leaves the token stuck at 1 when work is already available. Update the logic so
the cmpxchgStrong(1, 0, ...) reset happens regardless of whether the branch
takes .no_wait or .once, ensuring future wakeups from global_queue pushes can
arm a sleeper correctly.
- Around line 454-459: The shuffle in `popAll()`/task redistribution inside
`runtime.zig` is incorrectly incrementing `ready_count` for tasks that are only
being moved between `queue_pool` stacks. Remove the `fetchAdd(1)` from the
`while (drained.pop())` loop in the `queue_pool` transfer logic, and keep the
existing count unchanged since these tasks are already accounted for by the
scheduler state used by `maybeYield()`.
- Around line 1048-1061: The wake token in Runtime.wakeOne is left set after
Executor.run() takes the .no_wait path, so later wakeOne calls can no longer
acquire it and wake an idle executor. Move the searchers reset out of the .once
branch in Executor.run() so it is cleared for both .once and .no_wait flows, and
keep the wakeOne logic unchanged except for relying on that token being released
correctly.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 47f52521-ab38-497a-a5eb-261b6b5ef6cf

📥 Commits

Reviewing files that changed from the base of the PR and between d1ef67f and e49750d.

📒 Files selected for processing (2)
  • src/runtime.zig
  • src/utils/concurrent_stack.zig

Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
+ decrement ready_count of victim when stealing tasks
+ remove unnecessary debug print
+ remove redundant ready_count increment in drain loop
@notxorand

notxorand commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor Author

will keep at it in the morning. the failing ci, some seem to be unrelated but others seem to be an issue with using a 64 bit atomic with 32 bit archs? (I'm unsure). how do we deal with failing ci? and tell me what part of this needs improvements

@notxorand notxorand closed this Jul 7, 2026
@notxorand notxorand reopened this Jul 7, 2026
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
+ add atomic global_queue_count to reduce lock contention
+ implement batch popping from the global queue
+ ensure correct ready_count decrements when stealing tasks
+ fix task scheduling priority to prefer local execution over remote
+ simplify queue_pool initialization using @Splat

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

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)

624-628: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Update global_queue_count while holding the queue mutex.

There is a window after push()/unlock() but before fetchAdd() where another popper that already passed the count check can pop this uncounted node and then fetchSub() from zero. Keep the queue mutation and count mutation in the same mutex window.

🐛 Proposed fix
         const wait_node = &task.awaitable.wait_node;
         self.runtime.global_queue_mutex.lock();
         self.runtime.global_queue.push(wait_node);
+        _ = self.runtime.global_queue_count.fetchAdd(1, .acq_rel);
         self.runtime.global_queue_mutex.unlock();
-        _ = self.runtime.global_queue_count.fetchAdd(1, .acq_rel);
         if (self.runtime.options.enable_task_migration) {
             self.runtime.wakeOne();
         }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/runtime.zig` around lines 624 - 628, The `global_queue_count` update in
`runtime.zig` is happening outside the `global_queue_mutex` critical section in
the `wait_node` enqueue path. Move the count increment into the same mutex-held
window as the `global_queue.push(wait_node)` inside the relevant runtime
queueing code so both the queue mutation and count mutation are synchronized
together, using the `global_queue_mutex`, `global_queue`, and
`global_queue_count` symbols to locate the fix.

591-600: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Avoid ConcurrentStack.pop() here. It does swap(null) and then restores chain.next, so a concurrent push() in that gap can be overwritten and dropped. Use a CAS-based pop, or stop calling pop() on this stack until the primitive is fixed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/runtime.zig` around lines 591 - 600, The task selection path in `Runtime`
is using `ConcurrentStack.pop()`, which can lose nodes because it clears the
head before restoring the next pointer. Update this branch to avoid calling
`stack.pop()` from the ready/task loop and instead use a CAS-based pop
implementation, or replace the usage with a safer primitive until
`ConcurrentStack` itself is fixed. Keep the change localized around the
`stack.pop()` / `stack.push(node)` logic in `runtime.zig` so `last_run_tick` and
`ready_count` handling stays unchanged.
♻️ Duplicate comments (2)
src/runtime.zig (2)

470-483: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Release searchers on the .no_wait path too.

This still leaves searchers == 1 when checkAboutForWork() finds work and the executor runs .no_wait, so later wakeOne() calls can stop waking idle executors. Move the reset after the if/else so both paths release the token.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/runtime.zig` around lines 470 - 483, The .no_wait branch in runtime.zig
leaves the searchers token held when checkAboutForWork() finds work, which can
block later wakeOne() calls from waking idle executors. Update the logic around
the self.loop.run(.no_wait) / self.loop.run(.once) paths in runtime main loop so
the searchers reset via cmpxchgStrong(1, 0, .acq_rel, .acquire) happens after
the if/else, ensuring both execution paths release the token consistently.

673-682: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Gate the current-executor fast path by runtime and migration mode.

Line 673 schedules onto whatever executor is current. With enable_task_migration = false, that still migrates tasks; with nested/different runtimes, it can enqueue a task into the wrong runtime. Only use current_exec when it is the home executor, or when it belongs to the same runtime and migration is enabled; otherwise inject into the home executor and wake it.

🐛 Proposed fix
-        if (getCurrentExecutorOrNull()) |current_exec| {
+        if (getCurrentExecutorOrNull()) |current_exec| {
+            if (current_exec == home_exec or
+                (current_exec.runtime == home_exec.runtime and home_exec.runtime.options.enable_task_migration))
+            {
+                current_exec.scheduleTaskLocal(task);
+                return;
+            }
+        }
+
+        if (home_exec.runtime.options.enable_task_migration) {
+            home_exec.scheduleTaskRemote(task);
+        } else {
+            home_exec.scheduleTaskLocal(task);
+            home_exec.loop.wake();
+        }
-            current_exec.scheduleTaskLocal(task);
-            return;
-        }
-
-        if (home_exec.runtime.options.enable_task_migration) {
-            home_exec.scheduleTaskRemote(task);
-        } else {
-            home_exec.scheduleTaskLocal(task);
-        }

Based on learnings, enable_task_migration == false means each executor should behave as an independent event loop.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/runtime.zig` around lines 673 - 682, The fast path in `scheduleTask` /
`getCurrentExecutorOrNull()` is too broad and can route work to the wrong
executor or runtime. Update the current-executor branch so it is only used when
`current_exec` is the home executor, or when it belongs to the same runtime and
`enable_task_migration` is enabled; otherwise fall back to scheduling on
`home_exec` and wake it appropriately. Keep the existing `enable_task_migration`
branch behavior aligned with `home_exec.scheduleTaskRemote` versus
`home_exec.scheduleTaskLocal`.

Source: Learnings

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/runtime.zig`:
- Around line 624-628: The `global_queue_count` update in `runtime.zig` is
happening outside the `global_queue_mutex` critical section in the `wait_node`
enqueue path. Move the count increment into the same mutex-held window as the
`global_queue.push(wait_node)` inside the relevant runtime queueing code so both
the queue mutation and count mutation are synchronized together, using the
`global_queue_mutex`, `global_queue`, and `global_queue_count` symbols to locate
the fix.
- Around line 591-600: The task selection path in `Runtime` is using
`ConcurrentStack.pop()`, which can lose nodes because it clears the head before
restoring the next pointer. Update this branch to avoid calling `stack.pop()`
from the ready/task loop and instead use a CAS-based pop implementation, or
replace the usage with a safer primitive until `ConcurrentStack` itself is
fixed. Keep the change localized around the `stack.pop()` / `stack.push(node)`
logic in `runtime.zig` so `last_run_tick` and `ready_count` handling stays
unchanged.

---

Duplicate comments:
In `@src/runtime.zig`:
- Around line 470-483: The .no_wait branch in runtime.zig leaves the searchers
token held when checkAboutForWork() finds work, which can block later wakeOne()
calls from waking idle executors. Update the logic around the
self.loop.run(.no_wait) / self.loop.run(.once) paths in runtime main loop so the
searchers reset via cmpxchgStrong(1, 0, .acq_rel, .acquire) happens after the
if/else, ensuring both execution paths release the token consistently.
- Around line 673-682: The fast path in `scheduleTask` /
`getCurrentExecutorOrNull()` is too broad and can route work to the wrong
executor or runtime. Update the current-executor branch so it is only used when
`current_exec` is the home executor, or when it belongs to the same runtime and
`enable_task_migration` is enabled; otherwise fall back to scheduling on
`home_exec` and wake it appropriately. Keep the existing `enable_task_migration`
branch behavior aligned with `home_exec.scheduleTaskRemote` versus
`home_exec.scheduleTaskLocal`.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5097e629-64c7-4efd-b166-6689dbafd7bc

📥 Commits

Reviewing files that changed from the base of the PR and between b233c12 and e3129af.

📒 Files selected for processing (1)
  • src/runtime.zig

@lalinsky

lalinsky commented Jul 7, 2026 •

Copy link
Copy Markdown
Owner

I think we will need to change course a little bit. I'm sorry to say this, but I don't have much confidence that you know what you are doing too well here. Like, the last commit, introducing a non-concurrent doubly-linked list and removing the last_tick fairness policy, is very wrong.

Can you please write down the design of what you want to end up with? And then follow that design.

@notxorand
notxorand marked this pull request as draft July 7, 2026 14:44
+ change ready_count load to acquire order for better performance
+ prevent race conditions in idle state entry by double-checking work
+ add assertion in scheduleTaskLocal to verify executor locality
@lalinsky

lalinsky commented Jul 8, 2026

Copy link
Copy Markdown
Owner

I've done a LOT of benchmarking, all possible variants of concurrent linked lists, plus the Go-style ring buffer, and I must say, the ring buffer is by far the cheapest option. It's super close to the current plain-ptr linked list. The atomic linked lists are 1.5-2x slower in a single channel ping-pong benchmark.

This is why I wanted to do it in phases, because it allows us to decide on the queue before reworking the whole scheduler. It's not possible to get relevant numbers if you mix too many changes.

If you want, I can open a PR for the ring buffer that essentially implements phase 1 of my original design. It just replaces the current queues, but doesn't add work stealing yet. And then you can work on the design of the idle/searching executors + work stealing.

@notxorand

Copy link
Copy Markdown
Contributor Author

If you want, I can open a PR for the ring buffer that essentially implements phase 1 of my original design. It just replaces the current queues, but doesn't add work stealing yet. And then you can work on the design of the idle/searching executors + work stealing.

yes, do

@lalinsky

lalinsky commented Jul 9, 2026 •

Copy link
Copy Markdown
Owner

I've merged the queue swap, plus had to fix a nasty bug where LLVM was silently ignoring our register clobbers and the queue swap exposed it.

@notxorand notxorand closed this Jul 9, 2026
@notxorand

Copy link
Copy Markdown
Contributor Author

work stealing requires a new pr and branch or we'll just have to squash the merge

@notxorand notxorand reopened this Jul 9, 2026
@notxorand notxorand closed this Jul 9, 2026
@notxorand
notxorand deleted the work_stealing branch July 9, 2026 17:24
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.

Implement work stealing for load balancing across executors

2 participants