Repository navigation
I/O load shedding: rebalance sticky I/O across executors - #581
Conversation
A task woken by an I/O completion always landed on the executor that owns the ring its op completed on, and long-lived connection tasks never leave: the steal window between the wake and the local pop is sub-microsecond, so an idle executor gets searcher-woken tens of thousands of times a second and finds nothing every time. A multi-threaded TCP server ends up doing all its work on one core (with the other executors burning cycles on futile steal attempts). Now a wake that arrives while the executor already has queued work and another executor sits idle goes to the global queue instead of the local ring. One spill rebalances a connection permanently, because its next ops are submitted from wherever it runs. Measured with the new driver-based TCP benchmarks (2 driver cores, 2 server cores, 8 connections, 64KB chunks): server write throughput 3.5 -> 7.8 GB/s (was identical to single-threaded before, now ~2x and ahead of go's 7.4), server read 5.1 -> 7.1 GB/s. Ping-pong, worker pool and echo benchmarks unchanged — the spill only triggers on a non-empty ring, which a latency chain never has.
📝 WalkthroughWalkthroughExecutors atomically track cross-thread I/O load, compute bounded per-tick shedding quotas, and route selected wakes through overflow queues. Spawn notifications refill local rings, while new tasks use deterministic executor selection and completion callbacks can be explicitly deferred. ChangesLoad-aware scheduling
Estimated code review effort: 3 (Moderate) | ~30 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 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.
🧹 Nitpick comments (1)
src/runtime.zig (1)
743-754: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueLift the common searcher arming out of the branches.
The spillover condition safely handles the backlog without risking starvation. Since both paths conclude by calling
armSearcher(), you can drop the early return and use a standardif/elseblock to remove the duplicated call.♻️ Proposed refactor
- if (!self.run_queue.isEmpty() and self.runtime.stealingActive() and self.runtime.idle_mask.load(.monotonic) != 0) { - self.run_queue.overflow.push(&task.awaitable.wait_node); - self.runtime.armSearcher(); - return; - } - - self.run_queue.push(&task.awaitable.wait_node); - self.runtime.armSearcher(); + if (!self.run_queue.isEmpty() and self.runtime.stealingActive() and self.runtime.idle_mask.load(.monotonic) != 0) { + self.run_queue.overflow.push(&task.awaitable.wait_node); + } else { + self.run_queue.push(&task.awaitable.wait_node); + } + self.runtime.armSearcher();🤖 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 743 - 754, Refactor the spillover branch in the task wake/enqueue flow to remove its early return and shared armSearcher() call. Keep the spill condition and overflow push unchanged, use an if/else structure for the spill versus normal enqueue paths, then call self.runtime.armSearcher() once after both branches.
🤖 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.
Nitpick comments:
In `@src/runtime.zig`:
- Around line 743-754: Refactor the spillover branch in the task wake/enqueue
flow to remove its early return and shared armSearcher() call. Keep the spill
condition and overflow push unchanged, use an if/else structure for the spill
versus normal enqueue paths, then call self.runtime.armSearcher() once after
both branches.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: d4e8ae80-8a2e-4b98-80d1-527e8d6d8b94
📒 Files selected for processing (1)
src/runtime.zig
Reverts the spawn-onto-current-executor placement. Initial spread matters more than the saved global-queue push: on epoll and kqueue backends a socket is pinned to the loop that registers it, so the executor a task starts on decides where its I/O lives, permanently. Spawning everything onto the acceptor's executor concentrated whole servers onto one core.
The first version spilled a wake whenever the ring was non-empty and someone was idle — correct on the benchmark, but a wake burst under light load would route everything through the global queue. Now it's an actual load balancer, decentralized: once per tick each executor compares its in-flight I/O count (== tasks parked on its ring) against the runtime average, and if it is above, sheds the excess by routing up to four wakes to the global queue. Less loaded executors pull from it, the shed task's I/O re-homes wherever it runs next, and the metric converges in a few ticks. Work stealing cannot do this job: I/O wakes are always local and the wake-to-pop window is far too small for a thief, which is why a multi-threaded server used to sit on one core no matter how many executors it had. The per-loop inflight counter is now read cross-thread (monotonic atomics; the owner remains the only writer).
When an I/O completion wakes a task onto an empty ring, this executor is inside its run loop and pops the task right after completion processing — no thief can beat that. Announcing it just wakes an idle executor for nothing, and when the thief does win the race it drags the task (and with it the connection's I/O home) to another ring for no benefit; a lone streaming connection lost ~20% of its throughput to that bouncing. Wakes from a running task still announce, since the waker may keep the executor busy for a while. push() now reports whether the ring was empty instead of the caller peeking beforehand. Single-connection streaming on the multi-threaded runtime now matches single-threaded (3.3 GB/s, was 2.7), and 1000-connection echo improves 147k -> 166k msgs/s from the removed wakeup churn alone.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/utils/local_run_queue.zig (1)
297-297: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAssert the
was_emptyreturn value in tests.Since
pushnow returns a boolean indicating whether the queue was empty, it's worth actually testing this behavior in the basic test instead of just discarding it.♻️ Proposed refactor
for (&nodes, 0..) |*n, i| { n.* = .{ .id = i }; - _ = q.push(n); + const was_empty = q.push(n); + try testing.expectEqual(i == 0, was_empty); }🤖 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/utils/local_run_queue.zig` at line 297, Update the basic queue test around q.push(n) to capture and assert the returned was_empty boolean, verifying the expected value for the queue’s initial state instead of discarding it.
🤖 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.
Nitpick comments:
In `@src/utils/local_run_queue.zig`:
- Line 297: Update the basic queue test around q.push(n) to capture and assert
the returned was_empty boolean, verifying the expected value for the queue’s
initial state instead of discarding it.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 96771383-9782-4ec4-8edd-a1a34f9d1a27
📒 Files selected for processing (2)
src/runtime.zigsrc/utils/local_run_queue.zig
🚧 Files skipped from review as they are similar to previous changes (1)
- src/runtime.zig
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/utils/local_run_queue.zig`:
- Around line 251-266: Update OverflowQueue.refillFrom to size its local pointer
buffer to capacity instead of the hardcoded 64 entries, allowing the existing
want calculation to honor max up to the queue capacity and drain the requested
batch in one call.
🪄 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: 34b264ed-5d1f-483d-ab02-c963d189c746
📒 Files selected for processing (3)
src/runtime.zigsrc/task.zigsrc/utils/local_run_queue.zig
🚧 Files skipped from review as they are similar to previous changes (1)
- src/task.zig
| pub fn refillFrom(self: *Self, source: *OverflowQueue(T), max: usize) usize { | ||
| const t = self.ownTail(); | ||
| const h = self.loadHead(); | ||
| const space: usize = capacity - (t -% h); | ||
| var buf: [64]*T = undefined; | ||
| const want = @min(space, @min(max, buf.len)); | ||
| if (want == 0) return; | ||
| const got = self.overflow.popBatch(buf[0..want]); | ||
| if (want == 0) return 0; | ||
| const got = source.popBatch(buf[0..want]); | ||
| var tt = t; | ||
| for (buf[0..got]) |node| { | ||
| self.buffer[tt & mask] = node; | ||
| tt +%= 1; | ||
| } | ||
| if (got > 0) self.storeTail(tt); | ||
| return got; | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Fix the arbitrary batch size limit to honor max.
Notice how buf is hardcoded to 64 pointers? spawnDrainCallback passes capacity (256) as the max argument, but this hardcoded array size forces the queue to only pull 64 tasks at a time. The rest get left in the overflow queue, triggering spawn_async.notify() and forcing an entirely new event loop tick just to pick up the next batch of 64.
You can fix this by just bumping the buffer size to capacity. Since T is a pointer, [capacity]*T is only 2KB. This easily fits on the executor's OS thread stack, avoids wasting event loop ticks, and completes the pull with a single lock acquisition.
🚀 Proposed fix to allocate a capacity-sized buffer
pub fn refillFrom(self: *Self, source: *OverflowQueue(T), max: usize) usize {
const t = self.ownTail();
const h = self.loadHead();
const space: usize = capacity - (t -% h);
- var buf: [64]*T = undefined;
- const want = `@min`(space, `@min`(max, buf.len));
+ var buf: [capacity]*T = undefined;
+ const want = `@min`(space, max);
if (want == 0) return 0;
- const got = source.popBatch(buf[0..want]);
+ const got = source.popBatch(buf[0..want]);
var tt = t;
for (buf[0..got]) |node| {
self.buffer[tt & mask] = node;(Alternatively, if you're feeling exceptionally strict about keeping the stack frame tiny, wrap the existing 64-item popBatch in a while (total_got < limit) loop until you hit max.)
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| pub fn refillFrom(self: *Self, source: *OverflowQueue(T), max: usize) usize { | |
| const t = self.ownTail(); | |
| const h = self.loadHead(); | |
| const space: usize = capacity - (t -% h); | |
| var buf: [64]*T = undefined; | |
| const want = @min(space, @min(max, buf.len)); | |
| if (want == 0) return; | |
| const got = self.overflow.popBatch(buf[0..want]); | |
| if (want == 0) return 0; | |
| const got = source.popBatch(buf[0..want]); | |
| var tt = t; | |
| for (buf[0..got]) |node| { | |
| self.buffer[tt & mask] = node; | |
| tt +%= 1; | |
| } | |
| if (got > 0) self.storeTail(tt); | |
| return got; | |
| } | |
| pub fn refillFrom(self: *Self, source: *OverflowQueue(T), max: usize) usize { | |
| const t = self.ownTail(); | |
| const h = self.loadHead(); | |
| const space: usize = capacity - (t -% h); | |
| var buf: [capacity]*T = undefined; | |
| const want = `@min`(space, max); | |
| if (want == 0) return 0; | |
| const got = source.popBatch(buf[0..want]); | |
| var tt = t; | |
| for (buf[0..got]) |node| { | |
| self.buffer[tt & mask] = node; | |
| tt +%= 1; | |
| } | |
| if (got > 0) self.storeTail(tt); | |
| return got; | |
| } |
🤖 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/utils/local_run_queue.zig` around lines 251 - 266, Update
OverflowQueue.refillFrom to size its local pointer buffer to capacity instead of
the hardcoded 64 entries, allowing the existing want calculation to honor max up
to the queue capacity and drain the requested batch in one call.
|
Reverted the per-executor spawn queue commits (4b482d2, 6a1228b) from this PR — CI still hangs on 2-core runners despite the deferral fixes, and it shouldn't block the load-shedding work. The spawn queue idea and everything learned (callback re-add recursion, defer_callback design, the two stranding bugs) moved to #582; WIP preserved on spawn-queue-wip. |
Found while building the driver-based TCP benchmarks (separate C load generator, driver and server pinned to disjoint cores, so the runtime under test is only ever the server side).
I/O is sticky: a task's ops live on the ring of the executor it runs on — by preference on io_uring, by force on epoll/kqueue. Work stealing cannot rebalance I/O-bound tasks, because their wakes are always local and the wake-to-pop window is sub-microsecond: an idle executor gets searcher-woken tens of thousands of times a second and never catches anything. A multi-threaded TCP server ended up doing all of its work on one core (second executor at 0.0% CPU), byte-for-byte identical to single-threaded on the streaming benchmark.
Go avoids this problem structurally — one shared netpoller means readiness is global and balance is free (at the price of a central funnel, which is why zio beats go on 1000-connection echo). With per-executor rings we need an explicit balancer:
Benchmarks
Driver/server split, i7-6700 (2 driver cores, 2 server cores), 8 connections, 64KB chunks, ReleaseFast:
In-process benchmarks (channel ping-pong, worker pool fan-out/fan-in, spawn) unchanged within noise — non-I/O workloads keep inflight counts below the shedding threshold, so the balancer never engages there.
Follow-up commit: the first wake pushed onto an empty ring from scheduler context no longer arms a searcher — the executor is in its run loop and pops it immediately, so the announcement only caused an idle executor to occasionally win the race and drag the connection to another ring. That fixed single-connection streaming on mt (2.7 -> 3.3 GB/s, now matching st) and, as a bonus, removed enough wakeup churn to lift 1000-connection echo from 147k to 166k msgs/s.