Skip to content

runtime: scheduler event counters and a metrics monitor thread - #636

Merged
lalinsky merged 6 commits into
mainfrom
scheduler-metrics
Aug 1, 2026
Merged

lalinsky merged 6 commits into
mainfrom
scheduler-metrics

Conversation

@lalinsky

@lalinsky lalinsky commented Aug 1, 2026

Copy link
Copy Markdown
Owner

Per-executor counters for the scheduler events every tuning discussion has needed numbers for, plus an optional monitor thread that logs them periodically.

Counters

Runtime.schedulerMetrics() returns a summed snapshot of ten per-executor counters: parks split by doze/full, searcher elections, steal attempts/hits and how often the hint's victim paid off, dispatched wake batches and their sizes, batched wake claims, and load-shed wakes. Writes are plain increments by the owning thread, so the snapshot is approximate while executors run and exact once quiesced.

Counters sit only on cold scheduler paths (a park entry, a steal scan, a drain pass), never on the per-push hot path, so they are compiled in by default; -Dscheduler_metrics=false strips them to nothing (the option name is a valid Zig identifier, matching the zio_options field; the older hyphenated options will be renamed separately). Ping-pong measures identically with counters on.

Monitor thread

The metrics_log_interval runtime option starts a thread that logs the counters' per-interval deltas at that cadence:

info(zio): scheduler: parks doze=182 full=41 elections=37 steals=29/44 hint_hits=25 drains=210 woken=1843 batch_claims=61 sheds=0

A dedicated thread rather than an executor timer, so it keeps reporting even when every executor is wedged or asleep, which is when the numbers matter most. Stopped and joined first thing in deinit (it reads executor state); the sleep is a futex timed wait on the stop word, so shutdown never waits out an interval. Warns and stays off if the counters are compiled out.

Testing

Full suite with metrics on (both new tests included: counter assertions through an ev.Async wait that provably crosses the dispatched queue, and a monitor lifecycle test at 5ms cadence), 601/601 with -Dscheduler_metrics=false, epoll suite, Windows cross-compile.

First intended use: watching steal/drain rates on the tcp pipe workload to chase the ~4% lat/pipe question from #633.

Per-executor counters for the events every tuning discussion this month
has needed numbers for: parks split by doze/full, searcher elections,
steal attempts/hits and how often the hint's victim paid off, dispatched
wake batches and their sizes, batched wake claims, and load-shed wakes.
Summed across executors by Runtime.schedulerMetrics(); the counters are
written without atomics by their owning threads, so the snapshot is
approximate while executors run and exact once quiesced.

Counters sit only on cold scheduler paths (a park, a steal scan, a drain
pass), never on the per-push hot path, so they are compiled in by
default; -Dscheduler-metrics=false strips them to nothing.
The metrics_log_interval runtime option starts a thread that logs the
scheduler counters' per-interval deltas at that cadence. A dedicated
thread rather than an executor timer, so it keeps reporting even when
every executor is wedged or asleep, which is exactly when the numbers
matter most. Stopped and joined first thing in deinit, since it reads
executor state; a futex wait bounds each sleep so shutdown never waits
out an interval. Warns and stays off when the counters are compiled
out.
Build option names should be valid Zig identifiers, matching the
zio_options field they populate.
@coderabbitai

coderabbitai Bot commented Aug 1, 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: 27280c40-5204-4444-9094-d1d831cd3699

📥 Commits

Reviewing files that changed from the base of the PR and between 7c07e39 and f644cd7.

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

📝 Walkthrough

Walkthrough

The runtime adds configurable scheduler counters, exposes aggregated metrics, and optionally logs interval deltas through a monitor thread. A build option controls compilation. Runtime options control monitoring. Tests cover collection and monitor lifecycle.

Changes

Scheduler metrics

Layer / File(s) Summary
Metrics configuration and data contract
build.zig, src/runtime.zig, docs/changelog.md
Adds the scheduler_metrics build option, metrics_log_interval, the SchedulerMetrics type, executor counters, conditional updates, and documentation.
Scheduler event instrumentation
src/runtime.zig
Counts parking, elections, steals, load shedding, drains, and batched wake results.
Aggregation and monitor lifecycle
src/runtime.zig, src/os/root.zig
Adds Runtime.schedulerMetrics(), monitor startup and shutdown, and the public Futex re-export.
Metrics and monitor tests
src/runtime.zig
Tests counter collection, monitor startup, periodic operation, and teardown.

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

Possibly related PRs

  • lalinsky/zio#581: Both changes instrument executor scheduling paths, including wake, steal, and load-shedding behavior.

Poem

Counters mark each park and steal,
Wake batches leave their measured trail.
A monitor logs each interval,
Then stops before resources sail.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main changes: scheduler event counters and an optional metrics monitor thread.
Description check ✅ Passed The description directly explains the scheduler counters, monitor thread, configuration, shutdown behavior, and tests.
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 scheduler-metrics

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

🤖 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 `@docs/changelog.md`:
- Around line 7-14: Align the changelog’s “-Dscheduler_metrics=false strips
them” statement with the implementation: update the scheduler metrics
compile-time gating so disabled builds remove SchedulerMetrics storage and
aggregation, or revise the changelog to describe the behavior accurately. Focus
on the SchedulerMetrics definitions and Runtime.schedulerMetrics aggregation
path.

In `@src/runtime.zig`:
- Around line 345-346: Update the public comment describing the scheduler event
counters build option in runtime.zig to use the registered name
scheduler_metrics instead of scheduler-metrics. Keep the surrounding
documentation unchanged.
- Around line 1470-1475: Update the metrics monitor setup around
runMetricsMonitor to handle metrics_enabled and builtin.single_threaded
separately: retain the compiled-out warning only when metrics are disabled, and
log that the monitor thread is unavailable for single-threaded builds when
metrics are enabled. Update the runtime-option documentation for
metrics_log_interval to document this single-threaded constraint.
- Around line 449-450: Update Executor.metrics in src/runtime.zig to use
per-field atomic counters when scheduler metrics are enabled, while selecting
zero/void storage when -Dscheduler_metrics=false so the feature compiles out as
documented. Update all metric increments, Runtime.schedulerMetrics(), and
monitor reads to use the conditional storage consistently. In docs/changelog.md
lines 7-14, document the scheduler metric storage and compile-out behavior
change.
🪄 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: 0b665e37-bac3-4c92-b1d9-7e8c97e9ffab

📥 Commits

Reviewing files that changed from the base of the PR and between 9471726 and bfd3349.

📒 Files selected for processing (4)
  • build.zig
  • docs/changelog.md
  • src/os/root.zig
  • src/runtime.zig

Comment thread docs/changelog.md Resolved
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
Comment thread src/runtime.zig Resolved
With scheduler_metrics=false the per-executor counter struct is now
zero-bit and the aggregation loop compiles away, matching the
changelog's strip claim. The metrics_enabled doc comment names the
registered option (scheduler_metrics, not scheduler-metrics), and a
single-threaded build with metrics_log_interval set now warns that the
monitor thread is unavailable rather than claiming the counters are
compiled out.

Reported by review on #636.
Targets whose os.Futex is void (the else fallback) get a warning
instead of a compile error in runMetricsMonitor. NetBSD leaves that
set once #640 lands; anything genuinely futex-less stays buildable.

Reported by the NetBSD build failure on #636.
lalinsky added a commit that referenced this pull request Aug 1, 2026
NetBSD was the one supported POSIX target whose Futex resolved to void:
FreeBSD, OpenBSD, DragonFly and Darwin all have implementations, and
anything built on os.Futex (the metrics monitor in #636 being the first)
failed to compile there.

NetBSD >= 9 provides a Linux-compatible futex through the __futex
syscall (FUTEX_WAIT with a relative timeout, FUTEX_WAKE,
FUTEX_PRIVATE_FLAG). libc ships no ___futex stub, so the call goes
through the generic syscall(2) entry point with SYS___futex (166),
which the libc symbol list does provide.

Also adds a timedWait test (expiry and already-changed-value paths) so
CI exercises the syscall on every futex platform, not just the wake
path the existing test covers.
@lalinsky
lalinsky merged commit d466270 into main Aug 1, 2026
26 of 28 checks passed
@lalinsky
lalinsky deleted the scheduler-metrics branch August 1, 2026 17:30
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