Skip to content

feat: work stealing and improved idling - #562

Merged
lalinsky merged 10 commits into
lalinsky:mainfrom
notxorand:work_stealing
Jul 12, 2026
Merged

lalinsky merged 10 commits into
lalinsky:mainfrom
notxorand:work_stealing

Conversation

@notxorand

@notxorand notxorand commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

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: bit i set <=> executor i is 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:

  1. Main task ready? / local ring non-empty?.
  2. Overflow non-empty? refill a batch into the ring, recheck.
  3. Still nothing? stealWork(): scan other executors (skip any with its idle_mask bit set), try run_queue.steal(victim). First success wins.

If none of these find anything, the executor goes idle.

Going idle

parkAndSearch

  1. Publish intent: set own idle_mask bit.
  2. Recheck: we're trying to make sure nothing lands in-between. If work is found now, clear the bit and return.
  3. Otherwise block in loop.run(.once).
  4. On return, clear own bit and inspect the previous value:
    • Bit was already clear means some other thread cleared it for us before we did which is a wake signal. We inherited search duty: check ready -> refill overflow -> stealWork() -> give up. Every branch that finds nothing forwards, one and only one call releases searchers back to 0.
    • Bit was still set means we cleared it ourselves; we just woke for unrelated I/O, not because anyone was signaling us. No search obligation.

Waking someone (called after any push, and after a successful steal)

armSearcher

  1. CAS searchers 0 -> 1. If this fails then someone's already searching, we're done here.
  2. Read idle_mask. If it's empty, no one to wake, release the token immediately.
  3. Pick the lowest set bit, clear it via fetchAnd (this clear is the token handoff), check the previous value:
    • If the previous bit was already cleared (target was self-cleared concurrently) it means we lost the race, release the token.
    • Otherwise, 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 armSearcher clears 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 release searchers.

Two liveness rules

  • Re-arm on leftover work: any time a search step (refill, steal) finds work but leaves more visible behind it (steal's victim not empty, overflow not drained), we call armSearcher() again before returning not to risk any leftover work having no one looking for it until the next unrelated wake.
  • Release before final recheck: when a search is about to give up entirely, release searchers before 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_executors and 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)

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

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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 executor loop centralizes work checks, coordinates idle executors with searcher tokens, adds migration stealing, and introduces architecture-dependent executor identifiers.

Changes

Runtime scheduling coordination

Layer / File(s) Summary
Idle state and searcher wakeup
src/runtime.zig
Adds architecture-dependent executor ID sizing, shared idle-mask and searcher state, and armSearcher() to wake an eligible idle executor.
Work checking and stealing
src/runtime.zig
checkAboutForWork() refills overflow queues and invokes migration stealing, which skips idle victims and arms search after successful steals.
Run-loop parking and polling
src/runtime.zig
Executor.run() uses centralized work checks and parkAndSearch() for non-blocking polling, blocking, and post-I/O readiness checks.

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

Possibly related PRs

  • lalinsky/zio#555: Changes scheduler stealing and run-queue behavior in the same runtime code.
  • lalinsky/zio#319: Relates to last_run_tick and task migration during stealing.
  • lalinsky/zio#56: Also changes multi-executor coordination and task routing.

Poem

Idle bits blink in the night,
Searchers wake when queues ignite.
Tasks take flight from neighbor lanes,
Polling yields, then work remains.
The runtime parks, then springs upright.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Linked Issues check ❓ Inconclusive The PR adds idle-aware work stealing, but the summary does not confirm removal of the .new migration exclusion from #460. Confirm that new tasks are allowed to migrate once stealing is enabled, or update the change summary to show that path was removed.
✅ Passed checks (4 passed)
Check name Status Explanation
Out of Scope Changes check ✅ Passed The changes stay focused on scheduling, idling, and migration coordination with no clear unrelated edits.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title matches the main change: adding work stealing and better executor idling.
Description check ✅ Passed The description clearly describes the same work-stealing and idle-state changes in the patch.
✨ 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.

@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

🧹 Nitpick comments (2)
src/runtime.zig (2)

604-612: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Snapshot idle_mask once instead of locking per victim.

This locks/unlocks idle_mask_mutex on 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 the idle_mask_mutex TODO 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 | 🔵 Trivial

TODO on idle_mask_mutex.

The // TODO: replace with atomic scoped based on architecture note matches the contention concern raised on stealWork. Want me to open a tracking issue for moving idle_mask to 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

📥 Commits

Reviewing files that changed from the base of the PR and between fda17c9 and 4133439.

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

Comment thread src/runtime.zig Resolved
+ 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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1cc576b and 62c96d5.

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

Comment thread src/runtime.zig Resolved
@notxorand

Copy link
Copy Markdown
Contributor Author

@lalinsky what do you think of the sized idle_mask, max_executors and executor id? that or mutex guarding?

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

not a full review yet, but the idle_mask sizing is fine this way

Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
+ rename U5U6 to ExecutorId
+ use maxInt(ExecutorId) + 1 over switch of usize for max_executors
@lalinsky

lalinsky commented Jul 10, 2026 •

Copy link
Copy Markdown
Owner

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.

@lalinsky

Copy link
Copy Markdown
Owner

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.

@notxorand

Copy link
Copy Markdown
Contributor Author

@lalinsky, I've included a design overview as the pr body info

@lalinsky

lalinsky commented Jul 11, 2026 •

Copy link
Copy Markdown
Owner

I'm sorry, but there are many issues, so to save my time, I'll have AI review this first.

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

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_start in threadsStart is still u6; should be ExecutorId.
  • The .new check in scheduleTask with 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_executors silently drops from 64 to 32 on 32-bit targets. That's fine given idle_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.

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

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:

  1. The final recheck must pass check_ready, not true.
  2. 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);
}

Comment thread src/runtime.zig Outdated
// 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();

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

Comment thread src/runtime.zig Outdated
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);

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.

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.

Comment thread src/runtime.zig
std.debug.assert(getCurrentExecutorOrNull() == self);

self.run_queue.push(&task.awaitable.wait_node);
self.runtime.armSearcher();

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.

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?

Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
+ 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 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.

We slightly regressed in some benchmarks, but that can be addressed later. Functionally this seems good as is.

@lalinsky
lalinsky merged commit bd13f81 into lalinsky:main Jul 12, 2026
27 checks passed
@notxorand
notxorand deleted the work_stealing branch July 13, 2026 13:15
lalinsky added a commit that referenced this pull request Jul 14, 2026
dacheng-gao pushed a commit to dacheng-zig/zio that referenced this pull request Aug 17, 2026
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).
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