Skip to content

runtime: doze before stealing (give the idle executor's own loop a grace window) - #632

Merged
lalinsky merged 3 commits into
mainfrom
idle-doze-ladder
Jul 31, 2026
Merged

lalinsky merged 3 commits into
mainfrom
idle-doze-ladder

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

What

An executor that drains its run queue no longer attempts a steal immediately. 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 case (completions already arrived) goes straight back to the busy loop with no idle-machinery traffic;
  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, re-stealing on every wake that finds nothing local.

Rationale: an I/O completion typically re-readies exactly the tasks that just ran on this executor, and stealing a task also re-homes its pending I/O, so stealing before the loop had a chance to answer is speculative migration churn. Same gating idea as ClickHouse Silk's idle-budgeted steal loop, adapted to the existing searcher/idle-mask protocol. Stealing stays exceptional; the searcher wake path (a pusher with excess work electing a parked executor) is unchanged and still immediate.

Protocol note (the subtle bit)

Stealing inside the indefinite park's pre-check, after the idle bit is published, is load-bearing: 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. An earlier draft checked only local queues and reliably hung the Mutex churn test on epoll: a dropped announce stranded a ready task behind a non-yielding task on another executor, with no rescue on any later timeout wake. The doze is exempt from this requirement because its wait cap bounds a missed announce to 100us. This is documented in park().

Loop API change (breaking, low-level)

The capped park needed a wait bound, so Loop.run(RunMode) and RunMode are folded into one knob:

  • loop.poll(max_wait): one pass; .zero = old .no_wait (still skips the syscall when nothing is in flight), .max = old .once, anything in between caps the wait. Timer deadlines, pending completions and the loop's max_wait option shorten the wait as before; the cap only tightens.
  • loop.run() (parameterless) = old .until_done.

Testing

  • Full suite on io_uring, epoll, poll; Windows/iocp under Wine; kqueue cross-compiles; examples build.
  • Mutex cancellation-churn test 10x on epoll (the test that caught the protocol bug).

Benchmarks (zio-benchmarks, interleaved A/B vs main, isolated caches)

Neutral (within the +-5% box noise): ping-pong (1/100 pairs, st+mt), spawn/sleep 10k tasks, worker_pool CPU-bound, tcp lat/pipe, http c128, and all single-threaded cases. Regressions, consistent across reruns: worker_pool light fan-in/fan-out (~4-8%) and tcp many (1000 conns x 100 x 64B) on io_uring-mt (~5-6%), i.e. burst-distribution shapes with no or cold I/O. A 10us doze measures the same, so the cost is the single-token searcher serialization (already known from #562), not the doze length; the planned searching/parking rewrite is the fix for that axis.

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 (#562) rather than the doze length
(a 10us doze measures the same).
@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: 251db13a-e8e4-4d5e-aa52-e2e6b4efed8d

📥 Commits

Reviewing files that changed from the base of the PR and between 13d7a7a and 1bbbda0.

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

📝 Walkthrough

Walkthrough

Changes

Event loop and executor scheduling

Layer / File(s) Summary
Polling API replacement
src/ev/loop.zig, src/ev/root.zig, docs/changelog.md
Removes RunMode and tick, adds Loop.poll(wait_cap), and keeps parameterless Loop.run() for completion-driven execution.
Executor idle and stealing flow
src/runtime.zig, docs/changelog.md
Adds a 100-microsecond doze phase, local-work checks, capped parking, and delayed work stealing.
API call-site migration
examples/ev_demo.zig, src/ev/README.md, src/ev/test/*, src/ev/tests.zig
Migrates examples and tests from mode-based calls to run(), poll(.zero), and poll(.max).

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

Possibly related PRs

Poem

Polls replace the modes of old,
Executors wait before they roam.
A hundred microseconds pass,
Then idle workers search the task.
Tests now run with simpler calls.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main scheduler change: delaying work stealing to give an idle executor a grace window.
Description check ✅ Passed The description directly explains the scheduler changes, loop API changes, synchronization rationale, testing, and benchmark results.
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 idle-doze-ladder

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: 2

🤖 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/ev/tests.zig`:
- Around line 40-56: Rename the three empty-loop tests in src/ev/tests.zig
(lines 40-56) to use poll(.zero), poll(.max), and run() instead of stale
run-mode names. Also update the nearby comment in src/ev/test/timer.zig (line
246) from run(.once) to poll(.max).

In `@src/runtime.zig`:
- Around line 621-624: Reset the executor’s dozed state whenever getNextTask()
returns a task, not only at run() startup, so productive work in the long-lived
loop enables the next idle pass to use the local-only park. Preserve the
existing dozed behavior for iterations where no task is returned.
🪄 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 Plus

Run ID: 9ebfec8e-7e2c-4e00-91e2-c414115a2335

📥 Commits

Reviewing files that changed from the base of the PR and between e595461 and 13d7a7a.

📒 Files selected for processing (18)
  • docs/changelog.md
  • examples/ev_demo.zig
  • src/ev/README.md
  • src/ev/loop.zig
  • src/ev/root.zig
  • src/ev/test/async_stress.zig
  • src/ev/test/cancel.zig
  • src/ev/test/dgram_server.zig
  • src/ev/test/dgram_server_msg.zig
  • src/ev/test/fs.zig
  • src/ev/test/group.zig
  • src/ev/test/poll_server.zig
  • src/ev/test/process_wait.zig
  • src/ev/test/stream_server.zig
  • src/ev/test/thread_pool.zig
  • src/ev/test/timer.zig
  • src/ev/tests.zig
  • src/runtime.zig
💤 Files with no reviewable changes (1)
  • src/ev/root.zig

Comment thread src/ev/tests.zig Resolved
Comment thread src/runtime.zig Resolved
lalinsky added 2 commits July 31, 2026 15:46
The dozed flag was only cleared at run() entry and on the has_work path,
so the common cycle of a doze waking, its completions being drained, and
the ring emptying again never reset it: the next empty pass skipped the
grace window and stole immediately. Derive the reset from this cycle's
quantum count instead, right after the drain: tick_task_count > 0 at that
point means tasks ran here since the last retune zeroed it. It has to be
consulted before the park decision, not folded into the retune at the
bottom of the loop, or the reset lands one iteration after the park it
was supposed to influence.

Reported by review on #632.
The empty-loop test names and one comment still referred to the removed
run(.no_wait)/(.once)/(.until_done) API.
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