Repository navigation
feat: work stealing and improved idling - #562
Conversation
+ introduce `idle_mask` and `searchers` count to track executor state. + refactor executor loop into `parkAndSearch` to handle intelligent parking and task discovery. + add `stealWork` logic to balance load across executors. + add `armSearcher` to efficiently wake idle executors when new work is available.
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe runtime executor loop centralizes work checks, coordinates idle executors with searcher tokens, adds migration stealing, and introduces architecture-dependent executor identifiers. ChangesRuntime scheduling coordination
Estimated code review effort: 4 (Complex) | ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (4 passed)
✨ 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: 1
🧹 Nitpick comments (2)
src/runtime.zig (2)
604-612: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winSnapshot
idle_maskonce instead of locking per victim.This locks/unlocks
idle_mask_mutexon every loop iteration (up to ~63 lock cycles per steal attempt) just to read one bit. Since you unlock immediately, the read is already a point-in-time snapshot — take the whole mask once before the loop and test bits against it. Same staleness characteristics, far less contention on the steal hot path. This also lines up with theidle_mask_mutexTODO on line 945 about moving to an atomic.♻️ Proposed refactor
const executors = self.runtime.executors.items; if (executors.len <= 1) return false; + self.runtime.idle_mask_mutex.lock(); + const idle_snapshot = self.runtime.idle_mask; + self.runtime.idle_mask_mutex.unlock(); + for (0..executors.len) |i| { const victim = executors[(self.id + i) % executors.len]; if (victim == self) continue; const victim_bit = `@as`(u64, 1) << victim.id; - self.runtime.idle_mask_mutex.lock(); - const victim_idle = self.runtime.idle_mask & victim_bit != 0; - self.runtime.idle_mask_mutex.unlock(); - if (victim_idle) continue; + if (idle_snapshot & victim_bit != 0) continue;🤖 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 604 - 612, Snapshot self.runtime.idle_mask once under idle_mask_mutex before the executor-stealing loop, store the value locally, and use it to test each victim_bit inside the loop. Remove the per-victim lock/unlock operations while preserving the existing victim selection and idle checks.
945-946: 📐 Maintainability & Code Quality | 🔵 TrivialTODO on
idle_mask_mutex.The
// TODO: replace with atomic scoped based on architecturenote matches the contention concern raised onstealWork. Want me to open a tracking issue for movingidle_maskto an atomic word so the park/steal/arm paths don't need a mutex?🤖 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 945 - 946, Replace the TODO on idle_mask_mutex with an appropriate tracking issue reference, or remove it if the atomic idle_mask migration is addressed in this change; ensure the issue covers converting idle_mask and the park, steal, and arm paths from mutex protection to architecture-appropriate atomic operations.
🤖 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`:
- Around line 1188-1197: In the idle-mask handling code, remove the unreachable
`previous_mask & bit == 0` conditional and its early return. Since `bit` is
derived from the current `self.idle_mask` while holding `idle_mask_mutex`, clear
the bit and wake `self.executors.items[id].loop` directly; remove the now-unused
`previous_mask` binding.
---
Nitpick comments:
In `@src/runtime.zig`:
- Around line 604-612: Snapshot self.runtime.idle_mask once under
idle_mask_mutex before the executor-stealing loop, store the value locally, and
use it to test each victim_bit inside the loop. Remove the per-victim
lock/unlock operations while preserving the existing victim selection and idle
checks.
- Around line 945-946: Replace the TODO on idle_mask_mutex with an appropriate
tracking issue reference, or remove it if the atomic idle_mask migration is
addressed in this change; ensure the issue covers converting idle_mask and the
park, steal, and arm paths from mutex protection to architecture-appropriate
atomic operations.
🪄 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: 098cd499-2277-4782-9fd9-2e8f087935e0
📒 Files selected for processing (1)
src/runtime.zig
+ replace mutex-protected u64 idle mask with an atomic usize value to reduce synchronization overhead. + update max_executors to be architecture-dependent, supporting 32 or 64 executors based on pointer size.
There was a problem hiding this comment.
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/runtime.zig`:
- Around line 1181-1189: Update armSearcher to retry when fetchAnd on idle_mask
returns a stale bit (previous_mask & bit == 0): re-read idle_mask, select
another set bit, and continue the wakeup loop instead of returning, while
preserving the searcher state transition when no idle executors remain.
🪄 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: ad4b4591-18de-4c7d-a1d5-7489ed0f5196
📒 Files selected for processing (1)
src/runtime.zig
|
@lalinsky what do you think of the sized idle_mask, max_executors and executor id? that or mutex guarding? |
lalinsky
left a comment
There was a problem hiding this comment.
not a full review yet, but the idle_mask sizing is fine this way
+ rename U5U6 to ExecutorId + use maxInt(ExecutorId) + 1 over switch of usize for max_executors
|
there are multiple logical issues in this, but please write the design overview how it's supposed to work, so that I don't overwhelm you with comments. |
|
one partial review, since I was interested in the riscv32 crash, you are reaching out to other executors during Runtime.init, so accessing unitialized executors from the array, stealing needs to be gated to start only after all executors are initialized, and disable it at shutdown. |
|
@lalinsky, I've included a design overview as the pr body info |
|
I'm sorry, but there are many issues, so to save my time, I'll have AI review this first. |
lalinsky
left a comment
There was a problem hiding this comment.
Thanks for the detailed writeup, the idle mask + single searcher token design (Tokio-style) is a reasonable shape, and the description of the token handoff protocol is well thought out. Tests pass here in both -Dtask-migration modes. However, there is one design gap that undermines the feature, and a couple of real protocol bugs. Details are in the inline comments; the big one plus a few things that don't anchor to changed lines are below.
Nothing ever arms a searcher on push, so the steady-state case of #460 is still serial
The description says armSearcher is "called after any push, and after a successful steal". The push half doesn't exist in the code. armSearcher has exactly three call sites, all inside the search/steal machinery itself (parkAndSearch x2, stealWork). scheduleTaskLocal, scheduleTaskRemote, the migrate path in scheduleTask, and the ring-to-overflow spill all schedule work without arming anyone.
Consequence: an idle executor parked in loop.run(.once) is only ever woken to steal by a chain started from another successful steal, and the first steal can only happen when some executor is already awake and out of work. In the motivating scenario, executor A wakes many waiting tasks (they migrate to A's local ring via the migrate path in scheduleTask), while B/C/D are parked with no pending I/O. Nothing wakes them, A's ring fills, spills to the global overflow (which also wakes no one), and everything runs serially until an unrelated wake happens to land. That's exactly the situation #460 describes, so as written this mostly adds "steal before parking", not steady-state rebalancing. scheduleTaskLocal and/or the spill path need to call armSearcher (like Tokio's notify-on-push / Go's wakep).
Other items that don't anchor to changed lines
worker_id_startinthreadsStartis stillu6; should beExecutorId.- The
.newcheck inscheduleTaskwith its "can be removed once we have work stealing (#460)" comment is untouched by a PR that claims to close #460. Given the missing push-side arming, removing it now would actually make things worse, but the PR shouldn't claim to close #460 while leaving it. max_executorssilently drops from 64 to 32 on 32-bit targets. That's fine givenidle_mask: usize, but it's a user-visible change worth noting in the changelog.- None of the added/updated tests exercise the searcher protocol (the only test change is the max-executors rename). I'd like to see a stress test that asserts parked executors actually get woken to steal, e.g. one executor waking a batch of migrated tasks while the others are parked with no pending I/O.
Summary
The token-handoff idea is sound, but: the push-side arming from the description was never implemented (so the feature doesn't fire in the steady state), and two paths violate the handoff invariant, one of which permanently and silently disables wake-ups (see the parkAndSearch recheck comment). I'd ask for: push-side armSearcher, handling the fetchAnd result in the pre-park recheck (and preventing self-targeting in armSearcher), the enable_task_migration runtime guard in stealWork, an atomic executors_stealable, plus a test for the wake path.
+ simplify `parkAndSearch` logic for finding work + introduce randomized work stealing targets to improve balance + optimize `armSearcher` and `executors_stealable` synchronization + update task scheduling to trigger `armSearcher` more reliably
lalinsky
left a comment
There was a problem hiding this comment.
Thanks for the quick turnaround. The new revision resolves most of the previous round properly: push-side arming is in, the token leak on the pre-park recheck is fixed by the restructure (including the self-targeting case), stealWork/armSearcher now honor the runtime enable_task_migration option, executors_stealable is a proper atomic, the double release is gone (exactly one release per token path now), the woken-worker path honors check_ready, the idle bit is cleared on the error path, refill uses the fair slice, the victim scan is randomized, and armSearcher retries candidates. Tests pass here in both -Dtask-migration modes.
However, while verifying the fixes I found a serious runtime misbehavior, and I can reproduce it deterministically on this revision.
Idle wake storm: the final recheck arms a searcher forever
parkAndSearch's final recheck calls checkAboutForWork(true) with check_ready hardcoded to true. A worker executor's main_task.state is initialized .ready and effectively never leaves it (the worker main task is only the scheduler context), so for an idle worker that just drained a failed search, checkAboutForWork(true) returns true via main_ready even when there is zero work in the system. It then arms a searcher, which wakes another idle worker, which runs the same failed search, hits the same phantom-ready final recheck, and arms again. The chain is self-sustaining as long as at least two workers are idle; it only dies when the token happens to land on the parked main executor (whose main task is genuinely .waiting, so its recheck returns false) or when a candidate race empties the scan.
Repro (4 executors, main spawns bursts of trivial tasks with busy gaps, then busy-loops so it never parks): with counters added to armSearcher, every run shows 70k-125k spurious wakes over a ~5s run (~40-50k/s), 100% of them attributed to the final recheck returning true via main_ready on a worker executor (I instrumented the reason: main=125212 ring=0 refill=0 steal=0). That's tens of thousands of wasted wake syscalls, epoll returns, and context switches per second while the pool is idle, sustained indefinitely as long as any scheduling activity keeps re-seeding it. On the previous revision this was mostly masked by the (differently buggy) early-out that never let workers reach the final recheck, though I did catch it storming intermittently there too, likely via the rarer main-task park/wake flip (AnyTask.yield with .park on a main task re-enters run(.until_ready)).
Two things need to change:
- The final recheck must pass
check_ready, nottrue. - More fundamentally, a ready main task should never justify arming a searcher: only this executor can run its own main task, so waking someone else to "search" for it is always a wasted wake (this also applies to the main executor with
check_ready = true). The arm condition on the final recheck should be based only on work someone else could actually take: overflow non-empty or a successful steal that left leftovers behind.
And this is exactly the kind of thing the missing test coverage from the last round would catch: a test that runs a multi-executor runtime, makes it go idle while the main task stays busy, and asserts the process doesn't keep waking workers (e.g. bound a wake counter, or assert on CPU/wake counts) would have failed loudly here. Please add one.
Repro program for reference:
fn trivial() void {}
pub fn main(init: std.process.Init) !void {
var rt = try zio.Runtime.init(init.gpa, .{ .executors = .exact(4) });
defer rt.deinit();
var group: zio.Group = .init;
defer group.cancel();
var x: u64 = 1;
for (0..200) |_| {
for (0..4) |_| try group.spawn(trivial, .{});
for (0..2_000_000) |j| x = x *% 6364136223846793005 +% j;
std.mem.doNotOptimizeAway(x);
}
try group.wait();
// main busy, never parks; workers fully idle -> storm sustains
for (0..2_000_000_000) |j| x = x *% 6364136223846793005 +% j;
std.mem.doNotOptimizeAway(x);
}| // being blocked behind a token we're about to give up anyway. | ||
| _ = self.runtime.searchers.cmpxchgStrong(1, 0, .acq_rel, .monotonic); | ||
| if (self.stealWork()) return; | ||
| if (self.checkAboutForWork(true)) self.runtime.armSearcher(); |
There was a problem hiding this comment.
This is the wake storm described in the review body: check_ready is hardcoded true, and a worker's main_task.state is permanently .ready, so an idle worker that just finished a failed search always "finds work" here and arms another searcher, which wakes another idle worker into the same dead end. Self-sustaining chain, measured at ~40-50k spurious wakes/s with 3 idle workers.
Beyond passing check_ready: main_ready should not be an arm reason at all. Only this executor can run its own main task, so waking a searcher for it is always wasted (that applies to the main executor too). Arm here only for work someone else can take (overflow non-empty / steal leftovers).
| fn parkAndSearch(self: *Executor, check_ready: bool) !void { | ||
| const my_bit = @as(usize, 1) << self.id; | ||
| _ = self.runtime.idle_mask.fetchOr(my_bit, .acq_rel); | ||
| errdefer _ = self.runtime.idle_mask.fetchAnd(~my_bit, .acq_rel); |
There was a problem hiding this comment.
Small residue of the token-leak fix: this errdefer discards the fetchAnd result. If armSearcher claimed our bit just before loop.run failed, the token was handed to us and this path never releases it, so searchers sticks at 1 permanently (same failure mode as the leak fixed in this revision, just confined to the rare loop-error path). The errdefer should release searchers when the previous value shows the bit was already clear.
| std.debug.assert(getCurrentExecutorOrNull() == self); | ||
|
|
||
| self.run_queue.push(&task.awaitable.wait_node); | ||
| self.runtime.armSearcher(); |
There was a problem hiding this comment.
Hot-path concern: this is the yield/wake fast path, and armSearcher's check order makes the fully-busy steady state (searchers == 0, idle_mask == 0) the most expensive case: every local push does a successful CAS 0->1 on searchers, a load of idle_mask, and a CAS back 1->0. That's two RMWs on one globally shared cache line per push, serializing all executors under load. Cheap fix: load idle_mask first and return if it's 0 (a monotonic load of a mostly-read line, true whenever everyone is busy) before ever touching searchers. Tokio does the equivalent (check for idle workers before trying to become the notifier). Has this been benchmarked against main under a busy multi-executor workload?
+ update errdefer logic to correctly clear searcher status during park + pass check_ready argument to checkAboutForWork in post-park steal + set executors_stealable to false earlier in shutdownWorkers + add idle_mask check to armSearcher to prevent redundant wakeups
lalinsky
left a comment
There was a problem hiding this comment.
We slightly regressed in some benchmarks, but that can be addressed later. Functionally this seems good as is.
An executor that drained its run queue used to attempt a steal right away, before its own event loop had any chance to complete the I/O of the tasks that just ran there. Since a completion typically re-readies exactly those tasks, and stealing a task also re-homes its pending I/O, this turned the steady-state drain into speculative migration churn (inspired by how ClickHouse Silk gates stealing on proven idleness). The idle path is now a ladder, one step per empty pass of the run loop: 1. probe: one non-blocking poll, without touching idle_mask, so the common completions-already-arrived case goes straight back to the busy loop; 2. doze: a park capped at 100us with the idle bit published and a local-only work check, so a searcher election still cuts it short; 3. full park: indefinite, with stealWork folded into the pre-park check. Stealing in the indefinite park's pre-check (after the idle bit is published) is load-bearing, not an optimization: the seq_cst pairing with armSearcher only prevents lost wakes if the parker's final check can see a task sitting in the pusher's own ring. Without it, a dropped announce strands a ready task behind a non-yielding task on another executor (caught by the Mutex churn test hanging on epoll). The doze is exempt because its wait cap bounds the missed announce to 100us. The capped park needed a wait bound on the loop API, so the RunMode enum is folded into a single knob: Loop.poll(max_wait) replaces Loop.run(mode), with .zero as the old no_wait, .max as once, and a parameterless Loop.run() covering until_done. Timer deadlines, pending completions and the loop's max_wait option shorten the wait as before; the cap only ever tightens it. Benchmarked against main (interleaved A/B, isolated caches): ping-pong, spawn/sleep, CPU-bound pools, tcp lat/pipe/http and single-threaded all neutral; burst-distribution shapes (worker_pool light fan-in/fan-out, tcp many-connections on io_uring) lose ~5%, which tracks the known single-token searcher serialization (lalinsky#562) rather than the doze length (a 10us doze measures the same).
adds work stealing and advanced idle state handling. closes: #460. earlier attempt: #541
Goal
Idle executors find and run work sitting in other executors' local queues, without losing a task, without a stuck wakeup, and without more than one executor "searching" at a time under normal load.
Structures
idle_mask: atomic usize: bitiset <=> executoriis currently parked with no known work.searchers: atomic u32: 0 or 1. Caps concurrent active searches to one at a time; the thread holding it is responsible for eventually releasing it.Steady state (busy executor, every tick)
checkAboutForWork, cheapest first strategy:stealWork(): scan other executors (skip any with itsidle_maskbit set), tryrun_queue.steal(victim). First success wins.If none of these find anything, the executor goes idle.
Going idle
parkAndSearchidle_maskbit.loop.run(.once).stealWork()-> give up. Every branch that finds nothing forwards, one and only one call releasessearchersback to 0.Waking someone (called after any push, and after a successful steal)
armSearchersearchers0 -> 1. If this fails then someone's already searching, we're done here.idle_mask. If it's empty, no one to wake, release the token immediately.fetchAnd(this clear is the token handoff), check the previous value:wake()that executor's loop.Token handoff: searcher token is never passed by a separate message — it's implied by which thread's clear of a given idle-mask bit "wins." If
armSearcherclears it, that executor inherits the search obligation on wake. If the executor clears its own bit first (step 4 above), no one ever gets to claim it and there was nothing to hand off. This is why every code path that finds a bit already clear must immediately releasesearchers.Two liveness rules
armSearcher()again before returning not to risk any leftover work having no one looking for it until the next unrelated wake.searchersbefore the last check, not after so a concurrent pusher racing that exact moment can arm a fresh search instead of finding the token falsely held by a thread that's about to abandon it anyway.Other Changes
max_executorsand executor ids (ExecutorId) were made architecture scoped to follow u32 on 32-bit arch and u64 on 64-bit arch, with their corresponding bit shifting values (u5 for 32-bit, u6 for 64-bit)