Skip to content

runtime: steal hints and batched I/O wakes - #633

Merged
lalinsky merged 3 commits into
mainfrom
steal-hints
Aug 1, 2026
Merged

lalinsky merged 3 commits into
mainfrom
steal-hints

Conversation

@lalinsky

@lalinsky lalinsky commented Jul 31, 2026 •

Copy link
Copy Markdown
Owner

Two commits, one story: wakes get smarter about where work is and how much of it there is.

Commit 1: steal hints

armSearcher records the pusher's executor id in the elected searcher's steal_hint just before the wake (exclusive by construction: only the winner of the idle-bit claim writes, and the wake edge publishes the store). stealWork consumes the hint as its scan start and falls back to the usual random circular sweep, so a stale hint degrades to exactly the old behavior. The wake becomes an invitation with directions instead of a blind search warrant: the elected searcher skips the random victim probing, while the work stays in the waker's ring until actually stolen -- the wake-to-pop race still decides whether anything migrates. Hint sources: local announce passes the pusher's id; shed/remote wakes pass none (their work is in the shared overflow queue, checked first anyway); a successful steal propagates by pointing the next searcher at the same victim's remainder.

Commit 2: batched I/O wakes (Go's injectglist, zio-shaped)

Task-wake completions (waitForIo) now set a null callback, which the loop routes into the dispatched queue instead of invoking anything -- a null callback is the per-completion form of do_not_call_callbacks, and nextDispatched() serves both. The executor drains the queue after every poll, signaling each waiter with per-push announces suppressed, then makes one batched wake decision for the whole poll's worth of newly ready tasks: wake log2(ready) sleepers hinted at this executor (each steals half of what remains, so log2 covers the batch). Batches bypass the single-searcher token -- the token throttles speculative announces, and a counted batch is not speculation; Go draws the same line (wakep single-flights, injectglist starts min(batch, idle) threads).

Rationale: early per-completion wakes bought nothing locally -- a task woken mid-poll cannot run until the poll returns anyway, so immediate callbacks only enabled per-completion announce traffic and mid-poll steals, the churny kind. This also removes the last per-completion indirect call.

The subtle requirement (found via a hanging TCP handshake test): an operation that completes inline during loop.add (a socket open) enters the dispatched queue outside any poll, on the very thread about to park. checkLocalWork therefore drains the queue first, making pending wakes visible to every work check including the pre-park one.

Alternatives probed and rejected

  • Raising the searcher token cap: fan workloads ~11% worse (thieves racing CAS on one victim's ring head). Targeting, not more pullers.
  • Mailbox handoff (push-side batch delivery to a claimed sleeper): beat main on fan-in by ~15% but commits migration at push time -- shedding without a trigger -- and needed three new protocol invariants. Kept as a local reference branch.
  • Gating hints on ring depth >= 2: no measurable effect.

Benchmarks (interleaved, rotated order, isolated caches; dev box with +-5% noise -- please rerun on the Xeon box)

  • tcp many (1000 conns): +11% vs main -- the completion-burst shape the batching targets, the strongest result on that benchmark from any of this week's scheduler work.
  • ping_pong 1 pair: -7..10% (reproduced every session; hints).
  • lat / pipe / sleep / spawn / ping_pong 100p: neutral. worker_pool fan wakes are task-to-task (not completions), so the batch path doesn't run there; observed deltas did not reproduce across sessions.
  • Known micro-trade: ops that complete inline during loop.add (socket open) lose the completed-inline fast path and pay one park/unpark round trip; where that class is most frequent (tcp many) the net is still +11%. Recovery exists if ever needed (self-drain after add).

Testing

Native 601/601, epoll 601/601, poll suite, Windows/iocp under Wine 518/518, kqueue cross-compiles, Mutex churn stress clean, all under verbose per-test-timeout runs. Rebased on main (includes #632/#634/#635).

@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 732bd2af-b9f5-4a86-a246-4cfcbbc4035d

📥 Commits

Reviewing files that changed from the base of the PR and between 3497861 and 1d8862a.

📒 Files selected for processing (3)
  • src/common.zig
  • src/ev/loop.zig
  • src/runtime.zig
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/runtime.zig
  • src/ev/loop.zig
  • src/common.zig

📝 Walkthrough

Walkthrough

The runtime batches dispatched-completion wakeups and carries optional victim-executor hints through searcher election. Steal scans consume valid hints and propagate victim IDs. Null-callback I/O completions use nextDispatched(). The changelog documents these behaviors.

Changes

Executor wakeup and completion delivery

Layer / File(s) Summary
Dispatched completion delivery
src/common.zig, src/ev/loop.zig, docs/changelog.md
I/O wait helpers use null callbacks. Standalone completions with null callbacks enter the dispatched queue for nextDispatched() delivery. The changelog records this behavior.
Batched dispatched wakeups
src/runtime.zig
Executors drain dispatched completions after event-loop polls, suppress per-push announcements, and issue one batched wake decision.
Hinted stealing and searcher election
src/runtime.zig, docs/changelog.md
Searcher election publishes optional victim hints before waking executors. Steal scans consume valid hints, and successful steals propagate victim IDs. Remote, load-shed, and overflow paths use no hint.

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

Possibly related PRs

  • lalinsky/zio#555 — Extends related run-queue and work-stealing coordination.
  • lalinsky/zio#562 — Shares the executor wakeup and victim-hint coordination paths.
  • lalinsky/zio#593 — Shares the dispatched-completion and nextDispatched() mechanisms.

Poem

Null callbacks join the queue,
Polls release them in a batch.
Hints guide each stealing search,
Victim IDs point the way.
Wake, dispatch, and steal.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main changes: steal hints and batched I/O wakeups.
Description check ✅ Passed The description directly explains the scheduler, I/O wakeup, benchmark, and testing changes in the pull request.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch steal-hints

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.

armSearcher now records the pusher's executor id in the elected
searcher's steal_hint just before the wake (exclusive by construction:
only the winner of the idle-bit claim writes, and the wake edge
publishes the store), and stealWork consumes the hint as its scan start,
falling back to the usual random circular sweep so a stale hint degrades
to exactly the old behavior. Pushes whose work lands in the shared
overflow queue (shed wakes, remote submissions) pass no hint; a
successful steal propagates by pointing the next searcher at the same
victim's remaining ring.

The wake becomes an invitation with directions rather than a blind
search warrant: the woken executor skips the random victim probing
(average n_exec/2 cross-ring reads), while the work itself stays in the
waker's ring until actually stolen, so the wake-to-pop race still
decides whether anything migrates at all. Work distribution stays
strictly pull-based; push-based placement remains the job of the shed
path, which has a measured trigger.

Alternatives probed and rejected on this codebase (details in
notes/2026-07-31-scheduler-architecture-vision.md): raising the searcher
token cap made fan workloads 11% worse (more thieves racing one ring
head), and delivering ring batches into per-executor mailboxes at push
time beat main on fan-in but is eager migration, i.e. shedding without a
trigger, and needed three new protocol invariants to stay sound.
@lalinsky lalinsky changed the title runtime: point elected stealers at the executor that woke them runtime: steal hints and batched I/O wakes Aug 1, 2026
Task-wake completions (waitForIo) now set a null callback, which the
loop routes into the dispatched queue instead of invoking anything: a
null callback is the per-completion form of do_not_call_callbacks, and
nextDispatched serves both. The executor drains the queue after every
poll, signaling each waiter with per-push announces suppressed, and then
makes one batched wake decision for the whole poll's worth of newly
ready tasks: wake log2(ready) sleepers, hinted at this executor, since
each steals half of what remains. Go's injectglist is the precedent -
batch arrival deserves batch wakeup, bypassing the single-searcher
token, which throttles speculation and a counted batch is not
speculation.

Early per-completion wakes bought nothing locally: a task woken mid-poll
cannot run until the poll returns anyway, so the only thing immediate
callbacks enabled was per-completion announce traffic (mid-poll steals,
the churny kind). This removes the last per-completion indirect call and
up to N-1 announce checks per poll.

The subtle requirement, found via a hang in the TCP handshake test: an
operation that completes inline during loop.add (socket open) enters the
dispatched queue outside any poll, on the very thread about to park. So
checkLocalWork drains the queue first, making pending wakes visible to
every work check, pre-park checks included; the post-poll drain in park
covers the sleeping side.

Benchmarks: tcp many (1000 conns) +11% vs main, +9% vs steal-hints -
the completion-burst shape this targets; lat/pipe/ping-pong/sleep
neutral. worker_pool fan wakes come from running tasks, not completions,
so this path does not affect them.
The batch and hint comments narrated the change instead of the code:
contrasts with behavior that no longer exists, restated mechanisms at
every call site, and justifications that only make sense while reviewing
the diff. Keep the invariants (why a check must sit where it sits) and
the non-obvious geometry (log2 coverage, token bypass), drop the rest.
@lalinsky
lalinsky merged commit 9471726 into main Aug 1, 2026
28 checks passed
@lalinsky
lalinsky deleted the steal-hints branch August 1, 2026 09:52
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