Skip to content

First phase of work-stealing, replace run queue with one that can be stolen from across threads - #555

Merged
lalinsky merged 4 commits into
mainfrom
ws-phase1
Jul 9, 2026
Merged

lalinsky merged 4 commits into
mainfrom
ws-phase1

Conversation

@lalinsky

@lalinsky lalinsky commented Jul 8, 2026

Copy link
Copy Markdown
Owner

I've tried to benchmark my original design and a few other variations, they pretty much all added 30-40% to the current ping-pong benchmark. All variants are still faster than Go at that benchmark, but I was wondering if we can do better. Out of curiosity, I've tried the Go-style ring buffer and it benchmark almost identically to my previous non-atomic queue, despite being stealable. So that's the clear winner, we will use that and deal with the slight complexity of having a fixed ring buffer and needing to overflow elsewhere.

I've designed it in a way so that task migration on/off still works, the only difference if we use local or global overflow. With the local overflow, we get the same behavior as before. With the global overflow, we get passive load balancing already, even without work stealing.

The next phases:

  • Track idle executors and when pushing to either queue, wake one idle executor. This needs to be done very carefully, perhaps even with a mutex around the operations in the first version, to get the functionality right first. I'd personally do this first, before actual stealing, and just use this approach to wake up one idle executor when pushing to the global queue.

  • Full work stealing, which means we wake idle executor even when pushing to the local queue, and when it wakes up and has no work to do, it will steal.

  • Then we do a pass of fairness optimizations.

See also #460 and #541

@coderabbitai

coderabbitai Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

An error occurred during the review process. Please try again later.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ws-phase1

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.

@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

🤖 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/utils/local_run_queue.zig`:
- Around line 40-67: The `count` updates in `push`, `pushSlice`, and `popBatch`
are happening outside the `mutex` critical section, which lets the atomic state
drift from the actual queue contents. Move the `fetchAdd`/`fetchSub` operations
inside the same locked region as `queue.push`/`queue.pop` in `LocalRunQueue` so
`count` always stays in lockstep with the queue. Keep the existing behavior and
method structure (`push`, `pushSlice`, `popBatch`) unchanged aside from updating
the ordering around the lock.
🪄 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: 1a1b65ab-97ba-4fd8-9dd0-a175c43cc5b9

📥 Commits

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

📒 Files selected for processing (3)
  • src/runtime.zig
  • src/utils/local_run_queue.zig
  • src/utils/queue.zig
💤 Files with no reviewable changes (1)
  • src/utils/queue.zig

Comment thread src/utils/local_run_queue.zig Resolved
lalinsky added 4 commits July 9, 2026 11:31
Replace the per-executor FIFO ready_queue + remote ConcurrentStack with the
work-stealing layout from issue #460, phase 1 (structure only, no stealing):

- LocalRunQueue: N lock-free stacks + drain cursor. One stack drained at a
  time; new local work pushed round-robin across the others. Owner-only push
  and single-element pop (the unsafe-without-a-lock pop lives here, marked for
  the phase-2 mutation-lock upgrade, so ConcurrentStack stays a clean primitive).
- Two overflow targets, chosen by enable_task_migration:
    * on  -> runtime global queue (SimpleQueue + mutex + atomic len), drained
             by all executors -> load balancing.
    * off -> per-executor overflow ConcurrentStack, drained only by its owner
             -> tasks stay on their home executor (no migration).
- getNextTask pops one task from the drain stack; last_run_tick backstop kept;
  cursor rotates only when the drain stack empties, with the I/O poll between.
- Single-pusher invariant asserted on local push; 256-task overflow spill.

Known gap (to address later): LIFO within a stack weakens maybeYield fairness
vs the old FIFO (a yielded task LIFO-jumps ahead of queued tasks; once
ready_count drops under the threshold maybeYield disengages). One test covers
this and currently fails.
Swap the per-executor run queue (an unbounded intrusive FIFO linked list) for a
fixed 256-slot ring buffer (LocalRunQueue), modeled on Go's runq and Tokio's
local queue: the owner pushes to the tail and pops from the head via CAS, spills
half the ring to an OverflowQueue when full, and exposes steal() to take half
from a victim's head.

The ring is a deliberate choice over a stealable linked list. It is marginally
more expensive than the current non-atomic, owner-only queue -- its head CAS
costs a few ns per pop over plain pointer ops -- but that queue cannot be stolen
from. Among steal-safe structures the ring is the cheapest evaluated by a wide
margin: intrusive steal-safe pop protocols (swap-to-null + store, load + CAS, a
fetchOr tagged-pointer mutation lock) were all substantially slower on the
atomics, whereas the ring's push is a single store and pop a single CAS over
contiguous memory.

The overflow queue is the shared global queue when task migration is on or a
per-executor queue when off, chosen once via a pointer at init so the hot path
never branches on the flag. The last_run_tick I/O-poll guard is reimplemented as
a peek (popIf). steal() is implemented and tested but not yet called by the
scheduler (phase 2).

Delete the unused, superseded WorkStealingQueue (src/utils/queue.zig).
push/pushSlice bumped count after unlock, so a concurrent drainer could
pop a queued-but-not-yet-counted node and fetchSub below zero, wrapping
the usize; len()/isEmpty() then report garbage until the pending
fetchAdd lands (transient busy-poll in the run loop's has_work check).
Only reachable with migration on, where multiple executors drain the
shared global queue concurrently with producers.

Move all count updates inside the critical section, making the
invariant exact: count equals the queue length whenever the lock is
free, and lock-free readers can see a stale value but never an
underflowed one.
The ring's head/tail atomics exist solely to let a phase-2 thief race the
owner on another executor's queue. Task migration (and thus stealing) is
already a comptime decision via zio_options.task_migration; when it is off
every ring is single-owner — cross-thread wakes go to the mutex-guarded
overflow queue, never the ring — so the atomics are pure overhead.

Parameterize LocalRunQueue with a comptime 'stealable' bool, sourced from
zio_options.task_migration. The cursors are now plain u32 fields; cursor
accessors apply atomic-builtin ordering only in the stealable build and
collapse to plain loads/stores otherwise. steal() is a @CompileError on a
non-stealable queue, so wiring it up by mistake fails to compile rather
than silently touching a ring with no synchronization.

Both configs tested: default (migration on) and -Dtask-migration=false
pass (aside from the two pre-existing fs .INVAL failures); the latter also
covers the non-atomic path and the migration-disabled runtime overflow.
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