Skip to content

state_exec: scheduler core for single-thread use (run queue, timers, waits, caches) - #842

Merged
transfix merged 28 commits into
masterfrom
perf/sched
Oct 28, 2026
Merged

transfix merged 28 commits into
masterfrom
perf/sched

Conversation

@transfix

@transfix transfix commented Oct 27, 2026 •

Copy link
Copy Markdown
Owner

One of three single-thread optimization branches (perf/sched, perf/async, perf/eval) that touch separate code. It was stacked on #834 (the benchmark suite); once #834 is merged, this branch takes a merge of master and targets master, so its diff is its own changes. Merged together, only docs/STATE_EXEC_BENCH.md conflicts, and perf/all (all three merged) passes every state_exec, app, pool, Ariadne and pycvc suite. The numbers below were measured on a fully loaded machine. A quiet-machine A/B of all three and their merge against the a7b966f baseline is running, and its results will be posted here.

Branch perf/sched, on top of #834 (the benchmark suite). This branch speeds up the scheduler core for single-thread use, then fixes the findings from the semantics and performance reviews.

What changed

  • Run queue (detail::process_table). Processes are kept in pid order, with a Fenwick tree for each priority level. A pick is O(log n), with no scan, rebuild or sort. The pick order is the same: round robin in pid order, priority, priority_rr. One deliberate change: under priority, ties always go to the lowest pid. Before, an unstable sort made this true only for up to 32 runnable processes on MSVC and 16 on libstdc++.

  • Timer heap and waiter indexes. Sleepers and timed waits live in a min-heap. Receivers are indexed by channel. Frame waiters and watchers are kept in lists. A wake costs O(woken).

  • Finished processes leave every per-step index but stay readable until reap(). The sync scheduler gains reap(). A process reaped from its own on_complete is erased by a scope guard once its step ends, even if the step throws.

  • has_runnable() reads counters.

  • Sync run() no longer spins. max_steps counts loop iterations, idle ones included. An idle wait is charged to max_steps at 100 ns per iteration, about what a spinning iteration took. It is charged to max_time as run time through the new time_budget::charge_wait. The effect:

    • a run(N) frame pump returns at once, as before;
    • a bounded run to completion with steps to spare (Ariadne init: 10M steps, 5 s) waits for the sleeper, as before;
    • descheduled time is still forgiven.
  • Infinite or huge max_time and sleeps use saturating time arithmetic (detail::time_after).

  • Watches are polled only when the watch root's change count has moved.

  • Settings caches. The async scheduler's per-submit reads and the sync scheduler's inline-call rate are re-read only when something under the tree's state_exec node changes (detail::settings_changes). The async tree rate for calls in flight is cached on the root's change count. set_id() and set_watch_root() invalidate these caches.

  • Clock reads. A step reads the steady clock once. The chain is broken after handlers, finishes, polls, cycle collection, charges, timer wakes and watch-count (dis)connects.

  • Async scheduler step. One drain per step, no lock when the ingress is empty, no coroutine frames, and the in-flight list is walked in place.

  • Charging calls. check_limits uses the step's own clock reading. A drain reads the tree's rate once, before it walks the calls in flight. A changed rate is published at that point. That publication is a tree write whose slots may kill or reap, so no slot runs mid-walk. The walk is in place until a call's own timeout, then goes on over a copy. The limit checks find the charged processes again by pid. Cancelling a process's calls takes them out of the list before it reads the rate, so a kill from a slot of that publication doesn't recurse.

  • wait_for_work() blocks an idle driver until any of:

    • a post or a settled call;
    • a sleeper or timed-wait deadline;
    • a call's registration timeout, counted only while its process still runs. An abandoned future of an ended process doesn't end the wait, and a NaN or infinite timeout never does. The wait lasts until the first clock tick at which the call counts as timed out (async_call::timeout_point());
    • a 1 ms charge beat, while a call runs for a live process with max_time or max_steps.

    Posts notify while holding the ingress lock.

  • Waits (detail::wakeup). No wait returns before its time on the steady clock: after an early OS timer it reads the clock and waits the rest. Only a deadline of the timer heap, a sleeper's or a timed wait's, is precise. On Windows the high-resolution timer is set 0.6 ms early and the wait spins on YieldProcessor for the rest. A thread at normal priority runs at above normal during that time. A thread the host gave any other priority keeps it, and a raised thread goes back to normal only if its priority wasn't changed meanwhile. Other waits burn no CPU.

  • pycvc Exec uses wait_for_work, with a 1 ms beat for frame waiters. While a coroutine is pending, asyncio's 5 ms slice is the wait wherever it blocks: Linux, macOS, and Windows on Python 3.13+. A 5 ms non-spinning beat follows only a slice that returned at once. That happens on Windows before Python 3.13, whose ~15.6 ms clock runs the stop timer at once.

  • New additive APIs: scheduler::run_steps(), async_scheduler::sync_run_steps(), wait_for_work(), time_budget::charge_wait() and async_call::timeout_point(), plus detail::seconds_passed() and detail::first_time_passed() next to detail::time_after(). pycvc Exec and the bench's drive() pump with the first two.

Review findings

All 13 semantics findings are fixed. One needed a decision: run(N) with sleepers uses the step-budget model above. The alternative, returning whenever max_steps bounds the run, would make Ariadne init scripts that sleep fail.

Performance findings fixed: late wakes, per-submit tree reads, the clock read per charged process, get_results per run, the sync inline rate, the docs, and the single-runnable pick.

Accepted as is: +62 B per process (+1.4%). eval.method_send showed no regression (round 2: 96.6 -> 84.1 ms and 91.2 -> 90.5 ms, both within noise).

The post-fix review's findings are fixed, each with a regression test that fails without the fix:

  • sched-1: wait_for_work spun on an ended process's timed-out call, and on NaN timeouts;
  • sched-2: Exec's beat after a waiting asyncio slice;
  • sched-3: rate publication mid-walk, and cancel recursion;
  • sched-4: the priority raise from lowered threads, and the restore clobbering a host's change.

The second-round review is fixed too. timeout_point() now returns exactly the first tick past the timeout. For timeouts of ~1e7 s and up it used to return a later tick, up to a few hundred ns later, which was harmless for the wait. The wait_for_work header and the wait docs now name timed waits as precise and say that ended processes' calls don't end the wait.

A/B against a7b966f

Interleaved rounds on a loaded machine; medians below.

Scenarios Points Geomean wall, cand/base Notes
sched.single.* 34 0.42 arith_loop: sync 307 -> 143 ns/step, async 572 -> 162 ns/step
sched.scaling, bystanders, watch_poll, gc_spike 37 0.075 scaling p=2000 sync: 85254 -> 308 ns/step
limits.* 17 0.40
msg.* 20 0.16
flood.* 43 0.061
async.inflight_tax 16 0.175 c=8, rate=tree: ~20.8 us -> 470-612 ns per step
async.flood.*, async.futures 55 0.72
footprint.idle_process 4 0.015 (wall) heap per process 4384 -> 4446 B
eval.* (code this branch doesn't touch) 66 0.81 load drift

Other points:

  • flood.stream batch_last_over_first: sync 16.6 -> 0.95, async reap=0 15.9 -> 0.97.
  • flood.small_host ns_per_submit with a watch root: 13-15 us -> 3.6-3.7 us.
  • async.flood.noop sync inline n=1000: 108.9 ms -> 9.5 ms.
  • sched.sleepers sync n=300: 1.05 s -> 45 ms.
  • sched.sleepers sync n=1 (20 x 1 ms, pinned): driver CPU/wall 1.0 -> ~0.45, lateness p50 0.35 -> 0.57 ms. On a fully loaded machine an occasional wake is still a few ms late.
  • No point got worse beyond the noise.

Probes on the candidate build:

  • registration timeout under wait_for_work: 0.051 s (base 0.051);
  • max_time kill: 0.101 s;
  • set_id mid-call: 35863 steps (base 19259; previous candidate 255431);
  • run(None, inf): 0.200 s with results;
  • run(20), run(20, 0.3), run(1000): 0.000 s, as on base;
  • Exec idle on a coroutine: 0.02-0.05 s CPU per second.

Tests

  • All state_exec_*_test, ariadne_runtime_test, ariadne_host_test, app_test, async_lane_test and the pycvc pytest files pass on Windows (MSVC 14.44, Release).
  • The Windows CI failure (SchedulerIdleTest.RunSleepsUntilTheEarliestWakeInsteadOfSpinning, wall 0.285) was the test's fault. The first thread_cpu_seconds() in a process calibrates with a Sleep(5), which takes 5-20 ms. The test called it between the sleep and its start time, and ctest's process-per-test exposes that. The test (and AStepBoundedRunWithStepsToSpare...) now times from before the sleeps.
  • New C++ tests cover: idle-wait budgets; inf and huge max_time; infinite sleep; pump vs run-to-completion; run_steps; time_after; charge_wait; 34-way priority ties; a reap from a throwing on_complete; the rate cache across set_id and tree writes; submit settings across tree changes; wait_for_work with a call timeout and a max_time charge; set_id mid-call; a state_list pop_back watch; ended-process and NaN-timeout calls under wait_for_work; rate-publication slots that kill mid-charge or at each publication; the precise wait's priority policy; never-early waits, and sleepers that never wake early, both under the sync run and under an async driver whose waits are cut short; the first tick past a timeout (first_time_passed, timeout_point).
  • New pycvc tests cover wait_for_work with call timeouts and charges, run(None, inf), and Exec's pump with a waiting and a non-waiting asyncio slice.
  • One async-track GIL-accounting pytest failed once under load and then passed 20 of 20 reruns.

Risks

  • Behaviour changes, documented:
    • priority ties go to the lowest pid;
    • a step-bounded run waits for a sleeper only within N x 100 ns;
    • with wait_for_work and no process limits, calls are charged only at drains.
  • Watch and settings caches rely on tree writes firing signals. state_list resets are followed by a size write, so they are seen. A reset(..., false) with no later write, or an operator() creation, is seen at the next write that fires.
  • Thread priority. A precise wait (a sleeper's or a timed wait's deadline) raises a normal-priority thread to above normal on Windows. It raises only from normal, and a change made during the wait stands.
  • types.h/types.cpp are touched (charge_wait, saturating after(), start(now)). That is the eval track's file, so watch for merge conflicts there.
  • Not built on Linux or macOS here.

…s and async calls

A standalone executable (plain main(), `--smoke` CTest entry) with about 80 scenarios. They time
the recursive and the stackless evaluators bare, and the sync and async schedulers under floods of
small, large and mixed programs. They also cover async functions on the background pool, a lane
and inline; compute fan-outs; messaging; native and state-tree calls; per-process footprint;
armed limits; deep-data work; and parsing.

Each record is a JSONL line with:
- wall time, driver-thread and process CPU;
- steps by kind and ns/step;
- latency percentiles;
- peak working set and private bytes;
- allocation counts;
- thread and handle counts, including the app's pooled threads.

The driver pins itself to a performance core, and every scenario checks its programs' results.

tools/bench/state_exec_bench.py runs one process per scenario with repetitions and compares two
runs against their noise. docs/STATE_EXEC_BENCH.md describes every scenario, the metrics, how to get
stable numbers, and the pathologies the first runs exposed:
- scheduler steps that cost O(P log P);
- the background pool's thread per call, kept alive with its result until ~app;
- the step rate re-read from the state tree on every charge;
- busy-spinning sleepers;
- unreaped floods.
…x64)

WPR and VSDiagnostics need elevation, so the bench samples itself. A sampler thread suspends the
driver about every millisecond and unwinds its stack in place with RtlVirtualUnwind into a
preallocated ring, with no allocation, locks or DbgHelp while the driver is suspended. A watchdog
resumes it if a sample holds it over 50 ms. Waits and other system calls are told apart by the
ntdll/win32u stub they sit in.

After the run, DbgHelp, loaded on demand, symbolizes the samples into folded stacks
(speedscope, flamegraph.pl) and top self/inclusive/line tables.

Only the first measured rep is sampled, so the other reps' timings stay clean; records name the
sample files. Elsewhere --sample says it is unsupported and points at perf.
detail::process_table keeps a scheduler's processes by pid (ended ones until
reaped) and the indexes a step needs, so nothing per step scans every process:

- a run queue: the ready and running processes in pid order, one level (or one
  per priority for the priority policies), with order statistics (a Fenwick tree
  over pid-ordered slots), so the k-th runnable process is found in O(log n).
  That keeps the round-robin pick exactly what the sorted scan gave: the
  runnable list in pid order indexed by rr_index. Ended processes leave their
  slot; slots are compacted when the table grows;
- a timer min-heap of wake_time and timed-wait deadlines (stale entries dropped
  when they surface, the heap rebuilt if they pile up), so waking costs
  O(woken);
- the processes waiting for a message by channel, the frame waiters, and the
  processes with state watches;
- counts of sleepers and receivers.

The scheduler changes a process's fields, then calls update() (set_status() for
a status change, which touches nothing between ready and running).

Also here: detail::wakeup, a notify/timed wait that keeps sub-millisecond time
on Windows (a high-resolution waitable timer and an event, since a timed wait on
a condition variable there lasts whole timer ticks), and detail::tree_changes,
a counter of changes under a state tree root (its childChanged and valueChanged
signals) for polling only when something changed. process gains the table's
bookkeeping entry and elapsed_time/time_left/charges_cpu_time/over_time_limit
overloads that take a steady_clock reading the caller already has.
… spinning

The sync scheduler keeps its processes in a process_table:

- select_process() picks from the run queue (no scan, vector or sort per
  step); the pick order is the one the sorted scan gave under every policy
  (priority: the lowest pid of the best priority, which is what the unstable
  sort gave for small runnable sets);
- sleepers and timed waits wake from the timer heap, and only when one is due;
  deliver_to_receivers() takes the channel's waiters from the receiver index;
- has_runnable() is three counters;
- poll_watches() visits only the processes with watches, and only when the
  tree under the watch root changed since the last poll (a slot on the root's
  change signals, connected while there are watches);
- finished processes are out of every per-step structure but stay readable
  (get_result, get_process_info, get_results); reap() (new) erases one;
- execute_process_step() takes the process_ptr from the run queue: no hash
  lookups or shared_ptr copies per step (current_process() refers to the
  table's entry);
- a step reads steady_clock once: inside run() it starts from the reading the
  previous step ended at when nothing but the loop's bookkeeping ran in
  between (a signal or watch handler setup, a finished process's on_complete,
  a cycle collection or a watch poll start a fresh reading), and every time
  budget of the step (time_left, charges_cpu_time, over_time_limit, run's
  budget) uses that reading; the CPU clock is chained the same way;
- run() no longer spins while only sleepers (or timed waits) are left: it
  waits for the earliest deadline, never past its max_time (then returns, as a
  spinning run would once its budget ran out); a wait counts as one of
  max_steps. With only untimed message waiters left, run() returns at once
  when max_steps bounds it (what spinning through the rest would come to),
  else waits out max_time, else waits for stop().
…it_for_work

The async scheduler gets the sync scheduler's process_table changes (run queue,
timers, receiver and frame-waiter indexes, watch polling only on tree changes,
one clock reading a step), and:

- a step drains the ingress once (deliveries, settled calls, charges, due
  timers), not twice, and an empty ingress costs an atomic load, not the
  mutex;
- the evaluator step is called directly (async_stackless_evaluator::step_now):
  it never suspends inside a step, so sync_step()/sync_run() make no coroutine
  frame per step; step() and run() stay coroutines over the same loop;
- wait_for_work(deadline) blocks an idle driver until a post_message(), a
  settled async call, the earliest sleeper or timed-wait deadline, or the
  deadline; posts notify it only while it waits. awaiting_frame_count() tells a
  driver it has frame waiters to wake;
- charge_async_calls() walks the in-flight list in place (a copy only from a
  call's own timeout on, which changes the list), with reused buffers;
- the tree's limits.async_steps_per_cpu_ms is read again only when something
  under the watch root changed since the last read (a slot on the root's change
  signals, connected while calls are in flight or watches exist), so a change
  still applies to the next charge while a quiet tree costs no walk per call;
- wake_awaiting() and the async-call waiter wake take their processes from the
  indexes; reap() erases through the table.
Exec::run's idle loop blocks in async_scheduler::wait_for_work (GIL released)
until a kernel posts or settles, a sleeper or timed wait is due, or the idle
deadline comes, in place of its 1 ms sleep (about 15.6 ms on Windows, a timer
tick). With asyncio coroutines pending or processes parked until the next pump
((await ...)), which this loop itself drives, the wait stays a 1 ms beat; a
50 ms cap is the backstop for work that arrives some other way.

pycvc wraps async_scheduler.wait_for_work(seconds) (GIL released) and
awaiting_frame_count(), and scheduler.reap(pid).
…t_for_work, watches

- process_table against the sorted scan it replaces, under every policy, through
  20000 random inserts, status, priority and wait changes, wakes, channel takes
  and erases, with every index checked after each;
- both schedulers end to end: each step picks the process the sorted scan would
  have, while processes pause, resume, wait for and get messages, change
  priority, end, get killed, forked and reaped between steps;
- timers wake in deadline order and drop stale entries; a timed wait expires;
  ended processes leave the indexes but stay readable;
- the sync run() waits (burning no CPU) while only sleepers are left, returns at
  its max_time while a process sleeps past it, returns at once with a step bound
  when only message waiters are left, lets a timed wait expire; reap();
- wait_for_work returns at once with a ready process, times out idle, wakes on
  a post from another thread and at a sleeper's deadline, and leaves frame
  waiters to the driver;
- state watches fire on a value the host changes between steps (both
  schedulers) and one another thread changes, and not on a write of the same
  value or of another node.
…is over

The step holds a reference to the process's entry in the table, not a copy of
its process_ptr, so reap() of the process stepping now (a host reaping from
on_complete) defers the erase to the end of the step instead of freeing the
process under it. Tested on both schedulers.
eval_deadline_guard and time_budget::start take an optional steady_clock reading
the caller already has (additive overloads; the one-argument guard still reads
nothing when unarmed). Both schedulers arm a step's deadline from the reading
the step started at, so a step with max_time (or max_step_time) reads the
steady clock once at its start (chained from the previous step) and once at its
end, instead of also once more inside the guard.
… the scheduler work fixed

The developer guide says how the run queue picks (the same order as ever),
that the sync run() waits instead of spinning and how it returns, how an idle
host waits for work (async_scheduler::wait_for_work), that finished processes
stay readable until reaped, and when watches and the step rate are read.
STATE_EXEC_BENCH.md notes, under each pathology the scheduler work fixed, what
changed; the bench's own drivers are unchanged so their numbers compare.
The high-resolution waitable timer fires on a ~0.5 ms grid, so a 1 ms sleep
woke ~0.5 ms late (sched.sleepers sync n=1: 20 sleeps of 1 ms finished ~11 ms
late, against ~0.5 ms when run() spun). The timer is now set 0.6 ms early and
the rest is spent yielding while watching the event: the wait ends on time for
at most that much CPU per wait (driver CPU per wall 0.16 against 1.0 spinning).
Also include <iterator> for std::size in the scheduler test.
… change count

- detail::time_after(): t plus seconds, saturating, so an infinite or huge
  max_time, sleep or wait is "never" instead of an overflowed cast that lands
  in the past. time_budget's own deadline arithmetic saturates the same way.
- time_budget::charge_wait(): charge a stretch its owner waited idle as run
  time (steady clock in the first half, CPU time in the second), for a run
  loop that waits where it used to poll.
- wakeup::wait_until(t, precise): only a precise wait (a sleeper's deadline)
  spins through its last ~0.6 ms on Windows, and it now spins with pause
  instructions instead of SwitchToThread, which on a loaded machine could
  give the core away for a whole quantum and wake late. Other waits take the
  high-resolution timer and burn no CPU. Far deadlines are capped per wait
  on the condition-variable path.
- tree_changes::attached(), and watch() reconnects when the node it watched
  went away even if another node has its address.
- detail::settings_changes: a version that moves on any change under the
  tree's state_exec node, for caching settings reads.
- pick_round_robin: a lone runnable process is picked again without the
  Fenwick descent, and the index skips its modulo when in range.
… inline rate

- run() no longer blocks a step-bounded pump: while only sleepers wait, the
  wait is charged to max_steps at 100 ns an idle iteration (about what a
  spinning one took) and to max_time as run time (time_budget::charge_wait).
  A run(N) whose steps would run out before the next deadline returns at
  once, as the spin did; a run with steps to spare (Ariadne init: 10M steps,
  5 s) waits for the sleeper, as the spin did. The wait's end follows the
  time budget, not a wall-clock end, so descheduled time is forgiven as
  before; an infinite max_time no longer overflows.
- run_steps(): run() without building the results map (additive).
- A process reaped from its on_complete is erased by a scope guard, so a
  step that throws afterwards doesn't leave it behind.
- The clock chain breaks after timer wakes and watch-count (dis)connects.
- async_steps_per_cpu_ms() caches the tree's rate on the settings version;
  set_id() and set_watch_root() invalidate it.
- sleep() and timed receives use saturating deadlines.
…ached submit settings

- wait_for_work() also ends at an in-flight call's registration timeout and,
  while a call runs for a process with a step or time limit, at a 1 ms charge
  beat (anchored at the wait's start), so a driver idling on it keeps
  budgets and timeouts current (3.8). Only sleeper deadlines wait precisely.
  wait_for_work(double) saturates (infinity waits for work, not zero).
- set_id() invalidates the cached tree rate; set_parser_defaults(),
  set_data_defaults() and set_watch_root() invalidate the submit cache.
- execute() reads max_alloc_bytes, heap_check_steps, parser.* and data.*
  from the tree only when the settings version moved.
- charge_async_calls passes the step's clock reading to check_limits; a rate
  read that publishes (a tree write whose slots may kill or reap) switches
  to the copying walk, which finds processes again by pid; finish and
  cancel read the rate before touching the call list.
- post_message()/post_async_completion() notify under the ingress lock.
- step_once keeps drain_ingress's error prefix; the reap guard and chain
  breaks match the sync scheduler.
- sync_run_steps(): sync_run() without the results map (additive).
…lices

drive_coros' asyncio slice is the idle wait while a coroutine is pending, as
it was alongside the old 1 ms sleep; the 1 ms beat for frame waiters is a
plain (non-spinning) wait. Slices use sync_run_steps, since the loop reads
its one result with get_result.
…rk and calls, caches

C++: run(nullopt, inf/1e12) with a sleeper; an infinite sleep; run(N) as a
frame pump returns at once while run(10M, 5 s) waits for the sleeper with
little CPU; run_steps against run; time_after saturation; charge_wait;
priority ties among 34 processes go to the lowest pid; a reap from a
throwing on_complete; the rate cache across set_id and tree writes (both
schedulers); submit settings follow the tree across submissions;
wait_for_work wakes for a call's registration timeout and for the charge
that kills a process at max_time; switching set_id mid-call applies to the
next charge (AS-27 style); a watch sees a state_list element popped off.
pycvc: wait_for_work with a call timeout and max_time; run(None, inf).
…ettings caches

Developer guide: no step scans or sorts (per-step cost still grows with cache
misses); priority ties go to the lowest pid; run() charges idle waits to
max_steps and max_time; wait_for_work's call timeouts and charge beat; a
precise wait may spin ~0.6 ms on Windows; watches rely on change signals
(state_list resets are followed by a size write); the settings caches.
EXCEPTIONS 3.8: a driver idling in wait_for_work keeps budgets current.
Bench: the drivers pump with run_steps/sync_run_steps.
On a machine whose cores are all busy (the bench pins its driver to one),
a thread blocked until its sleeper's deadline waited a scheduler quantum
for its core after the timer fired, and woke milliseconds late where the
old spin never gave the core up. A precise wait now raises the thread to
THREAD_PRIORITY_ABOVE_NORMAL (only from below it) for the wait and its
final spin, and restores it after. sched.sleepers sync n=1 (20 x 1 ms,
pinned, loaded machine, 15 reps): lateness p50 median 1.26 -> 0.57 ms,
worst run 86.5 -> 28.0 ms wall (base: 0.35 ms, 20.6 ms).
drive_coros' asyncio slice does not wait: asyncio runs a timer due within
its clock's resolution (~15.6 ms on Windows) at once, so with no wait of its
own the loop spun at a full core while a coroutine slept (probe E2: 0.98 s
CPU over 1 s). The old 1 ms sleep lasted a timer tick; a 5 ms
wait_for_work beat now takes its place (E2: 0.02-0.05 s CPU, base 0.00).
… is read before the walk

wait_for_work() ended at once, again and again, while a call whose process
had already terminated or failed (an abandoned future) was past its
registration timeout and its kernel still ran: next_call_charge added the
timeout before it looked at the process, and the drains pass such calls
over, so nothing ever settled it and an idle driver spun a core until the
kernel ended. It now skips calls of ended or reaped processes for the
timeout as for the charge beat, and takes the timeout point from the new
async_call::timeout_point(), the first time point past_timeout() holds at:
none for a NaN or infinite timeout (time_after(created, NaN) was the call's
creation, so a NaN timeout spun even for a live process).

charge_async_calls read the tree's rate at the first started call that
needed it; a change of the rate is published, a tree write whose slots may
kill or reap, and the walk then went on over a copy from its index, which
the slots may have put past the end of the list (std::length_error), or
skipped the calls that shifted down. The rate is now read, and published,
once before the walk, which is in place until a call's own timeout; the
limit checks find the charged processes again by pid. cancel_async_calls
takes the calls out of the list before it reads the rate, so a kill from a
slot of that publication finds nothing to cancel and doesn't read (and
publish) again at each level, and kill_process leaves a process that such
a slot ended alone.
…rmal thread

A wait that its OS timer ended early returned, when not precise, without
reading the clock again, and the condition-variable wait returned at its
one-hour cap: wait_until() now reads the clock after every wait and waits
the rest, so it never returns false before its time on the steady clock
(its callers already looped; this makes it the wakeup's own contract).

A precise wait raised its thread to above-normal priority from any lower
one, a priority the host lowered on purpose included, and restored the
value it read at entry even if the host changed it meanwhile. It now
raises only a thread at normal priority, and puts it back to normal only
if it is still at above normal.
…t once

The beat added while a coroutine is pending assumed drive_coros' asyncio
slice never waits, which holds only where asyncio's clock is coarse
(Windows before Python 3.13: a stop timer due within its ~15.6 ms
resolution runs at once). Where the clock is fine (Linux, macOS, Windows
on 3.13+) the slice blocks in the selector until its 5 ms stop timer, and
the beat then held asyncio off for another 5 ms, about half the time.
drive_coros now reports whether its slice waited (most of it), and the
pump skips its wait after one that did. Tested both ways with the loop's
clock resolution set: a waiting slice is followed at once, one that
returned at once by a ~5 ms beat, not a spin.
…riorities, sleeper deadlines

RunSleepsUntilTheEarliestWakeInsteadOfSpinning failed on the windows-2022
runner (wall 0.285 s, expected >= 0.29). The sleeper did not wake early:
the test read the CPU clock between b's sleep() and t0, and the first
thread_cpu_seconds() in a process calibrates the clock with a Sleep(5),
5-20 ms at Windows' default timer granularity. ctest runs each test in a
process of its own, so that test paid it there (4 of 5 fresh-process runs
failed here too); AStepBoundedRunWithStepsToSpareWaitsForTheSleeper had
the same flaw. Both now read the CPU clock first and time from before the
sleeps, so the run can't be shorter than the sleep: >= 0.3 s and 0.1 s.

New tests:
- wait_for_work with a call past its timeout whose process ended, and
  with a NaN timeout (failed before: the wait returned at once);
- a rate publication whose slot kills every caller mid-charge (failed
  before: std::length_error), and a slot that kills and changes the rate
  at each publication (failed before: 21 nested publications);
- a precise wait raises a normal thread and restores it, leaves a lowered
  thread alone, and keeps a priority changed during it (the last two
  failed before);
- no wakeup wait returns false before its time, with notifications at
  random moments; no sleeper's second stamp comes sooner than its first
  plus the sleep, under the sync run() and under an async driver whose
  waits a poster thread keeps ending early.
…xec's beat, live rate reads

Developer guide: only the calls of running processes end a wait_for_work
(an abandoned future's doesn't, nor does a NaN or infinite timeout); a
drain reads the tree's rate once, before it walks the calls; a precise
wait raises only a thread at normal priority and keeps a change made
meanwhile; no wait ends before its time on the steady clock; Exec's 5 ms
beat follows only an asyncio slice that returned at once.
EXCEPTIONS 3.8: the same for wait_for_work; the rate is read live, the
tree read again only after something under it changed (not "at every
charge"). Bench: async.inflight_tax rate=tree and the inline path's rate
reads, likewise.
timeout_point() stepped up from time_after's point in doubling steps. For
long timeouts (about 1e7 s and up) the doubles round over several ticks:
the first tick at which past_timeout() holds may be before time_after's
point, where it returned time_after's, or hundreds of ticks after it, where
the doubling step overshot it (1500000000.343 s: the first is +128, it gave
+255). Harmless for wait_for_work, but not the documented "first".

The search moves to detail::first_time_passed (process_table.h), next to
time_after, with past_timeout's test as detail::seconds_passed. It brackets
the first tick from time_after's point in doubling steps, down or up, then
halves the bracket; seconds_passed only goes from false to true as the time
grows. NaN, infinite and out-of-range times still give none, zero and
negative ones the call's creation. A typical timeout costs three
comparisons, against one before.
…tick

FirstTimePassedTest sweeps 12009 times (short, 1e7 and 1e8 grids, random up
to 5e9 s) and checks that the tick before each result fails seconds_passed.
The old step-up search failed 7992 of them. It also checks NaN, infinite,
out-of-range, zero and negative times and the clock's last tick.
ACallsTimeoutPointIsTheFirstTickPastItsTimeout checks a real call's
timeout_point() for 1e7 s and 1500000000.343 s; both failed before.
…ise too

wait_for_work()'s header comment now says that a call's timeout and charges
count only while its process still runs (an abandoned future of an ended
process doesn't end the wait, nor does a NaN or infinite timeout), and that
the wait never ends before a deadline.

Both schedulers ask detail::wakeup for a precise wait for any deadline of
their timer heap: a timed wait's as well as a sleeper's. So those waits also
spin up to ~0.6 ms on Windows and raise a normal-priority thread. The
wakeup comment, the sync idle wait's comment, wait_for_work's comment and
the developer guide's "Waits and the CPU" now say so.
#834, the benchmark suite this branch was stacked on, is squash-merged into master as bc4761b.
The merge base is a7b966f, the #834 commit this branch forked from, so the merge adds exactly
what master has beyond it, and the PR's diff against master is this branch's own changes.
@transfix
transfix changed the base branch from feat/state-exec-bench to master October 27, 2026 23:32
@transfix
transfix marked this pull request as ready for review October 27, 2026 23:32
@transfix
transfix enabled auto-merge (squash) October 27, 2026 23:33
@transfix
transfix merged commit 72e4c60 into master Oct 28, 2026
20 of 24 checks passed
transfix added a commit that referenced this pull request Oct 28, 2026
Brings in #842 (the scheduler track), squash-merged as 72e4c60. The only conflict is
docs/STATE_EXEC_BENCH.md, where both tracks edited the same paragraphs; the resolution keeps both
tracks' edits. It is the one made when the three tracks were merged together and tested
(perf/all), with perf/eval's edits taken out: perf/eval isn't on master yet. Every other file's
change against master is the same as before the merge.
@transfix

Copy link
Copy Markdown
Owner Author

Final A/B results (all three tracks)

This is the A/B the description said would be posted here. It ran on 2026-10-27 against a7b966f, with Release builds of the state_exec benchmark on the same Windows machine as before.

  • Phase 1 ran all 389 scenario points once per build.
  • Phase 2 ran the 181 single-thread points over 3 interleaved rounds, rotating the build order each round.
  • Each ratio below is the geomean wall time, build / a7b966f, where 0.25 means 4x faster.
  • Phase 2 figures are the median of the three rounds' geomeans. The machine was loaded by other builds during part of round 3, and the median absorbs one disturbed round.
scenario family points phase #842 sched #844 eval #843 async all three (master)
flood.* (many processes, small and large work) 43 1 0.07 1.19 0.99 0.06
sched.scaling 10 1 0.05 0.93 0.98 0.05
sched.bystanders 8 1 0.03 0.94 0.97 0.03
sched.watch_poll 16 1 0.11 0.91 0.92 0.09
async.inflight_tax 16 1 0.16 1.02 1.29 0.17
async.pool_batches 2 1 0.54 1.03 0.51 0.20
async.pool_aging 6 2 1.04 0.82 0.30 0.17
footprint.* 6 2 0.07 0.82 1.04 0.05
msg.* 20 2 0.23 0.85 0.96 0.15
sched.single.* 34 2 0.55 0.77 1.09 0.28
limits.* 17 2 0.44 0.88 1.01 0.34
native.* 22 2 0.58 0.89 1.02 0.46
eval.* (evaluator, no scheduler) 66 2 0.85 0.55 0.96 0.49
data.* 10 2 0.98 1.00 1.02 0.95
all points 389 1 0.37 1.01 1.15 0.33
all single-thread points 181 2 0.60 0.72 0.90 0.34

Some absolute times for all three tracks together (phase 1, median wall time):

scenario a7b966f all three
flood.small, sync, 1000 processes 3.20 s 71 ms
flood.stream, async, 500 per batch 6.85 s 55 ms
sched.scaling, async, 2000 processes 3.61 s 14 ms
sched.bystanders, async, 3000 idle bystanders 2.76 s 5.1 ms
footprint.idle_process, async, 3000 2.26 s 24 ms
msg.pingpong, async, 1000 bystanders 2.10 s 32 ms
async.pool_aging, background, k=3000 3.84 s 79 ms
sched.single.fib, async 225 ms 55 ms
eval.fib, recursive 25.8 ms 9.6 ms

The combined build regresses nowhere:

  • No point in the combined build was more than 10% slower than a7b966f in both of phase 2's first two rounds.
  • Phase 1 flagged parse.small at +58%, in one run only. A 5-round recheck of parse.* puts it at -0.9% (and state_exec async: persistent background pool, cheaper async calls, concurrent compute fan-outs #843's build at -11.8%), so the +58% doesn't reproduce.
  • Phase 1's other "worse" points don't reproduce either:
    • data.copy_equal and eval.raise_depth are flat in phase 2.
    • The poll-driver points with 10 tasks flip between runs, including on builds that don't touch the pool.

Notes on single tracks:

transfix added a commit that referenced this pull request Oct 28, 2026
The project version and the cvcpkg recipe family move to 3.7.2. Every recipe is at cvc_revision 1
already, so none restarts.

3.7.2 carries the dynamic plants on the terrain and in a Jolt world, and the four-wheel plant
(#869): --plant dynamic and dynamic4w drive the ground, collide with the
buildings and each other, and book the collisions. It also carries dyn_4w's port-Hamiltonian form
(#850), dyn_bike's wheel-frame front slip (#852), the books goldens for GRL-SNAM's twins (#848,
#849), pycvc's drive telemetry (#857) and keep-alives (#864), the macOS SDK's openssl (#846), and
the state_exec scheduler and evaluator work (#842, #843, #844, #861, #863).
@transfix
transfix deleted the perf/sched branch October 29, 2026 20:54
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