Skip to content

state_exec_bench: a benchmark suite for the evaluators, the schedulers and async calls - #834

Merged
transfix merged 4 commits into
masterfrom
feat/state-exec-bench
Oct 27, 2026
Merged

transfix merged 4 commits into
masterfrom
feat/state-exec-bench

Conversation

@transfix

Copy link
Copy Markdown
Owner

A benchmark suite for libcvc's state_exec runtime. It's the measuring stick for the single-thread optimization and the threaded-execution design that come next.

What's in it

  • state_exec_bench (src/cvc/tests/state_exec_bench.cpp): a plain-main() executable with about 80 scenarios.
    • Bare evaluators: the recursive and the stackless evaluator, on the same programs: an arithmetic loop, fib, closures, lists, dicts, strings, exceptions, generators and native calls.
    • The same programs as one process under the sync and the async scheduler.
    • Floods: small, large, mixed and streamed programs, with sweeps over size and process count.
    • Async functions: on the app's background pool, an async_lane and inline, with no-op, sleeping and CPU-bound kernels; futures with await-all; compute-pool fan-outs; pool aging and retention.
    • The rest: messaging, native and state-tree call costs, per-process footprint, the cost of armed limits, deep-data work, parsing, and independent schedulers on several threads.
  • Records: each 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.
  • Measuring and checking: the driver pins itself to a performance core (the box this was written on is a hybrid Core Ultra), and every scenario checks its programs' results.
  • CI: registered as a state_exec_bench_smoke CTest entry. --smoke runs every scenario at tiny sizes and fails only on a wrong result, never on timing.
  • tools/bench/state_exec_bench.py (stdlib only) runs one process per scenario, with repetitions. compare reports the median deltas between two runs against their noise.
  • docs/STATE_EXEC_BENCH.md describes every scenario and metric, how to get stable numbers, and the pathologies below.

What the first runs show

These are single-rep runs at default sizes on Windows (MSVC 14.44 Release); the doc cites file:line for each.

  • Steps cost O(P log P). Neither scheduler has a run queue; every step rebuilds and sorts a vector of all processes. sched.scaling (sync) goes from about 230 ns/step at 1 process to 22 µs at 1,000 and 119 µs at 3,000.
  • The sync scheduler never erases a finished process. The 20th batch of a streamed flood takes 16× the first.
  • Sleepers make the driver spin. The sync scheduler counts sleeping and receiving processes as runnable, so its driver spins at 100% CPU: 1,000 sleepers × 20 × 1 ms take 13 s.
  • In-flight async calls tax every step. With 8 calls in flight, an unrelated step costs about 25 µs, against about 1 µs when the process sets its own rate: each charge re-reads the step rate from the state tree.
  • The background pool starts an OS thread per call and keeps it. The thread and its result live until ~app: about 1 MiB retained per call, and after 3,000 calls each call costs 17× as much as the first ones. A lane stays flat.
  • Past its size, the background pool stalls, then hangs. Queued calls can share a thread key; a worker then interrupts the one holding it and waits up to 5 s. async.flood.noop --size n=100 on 22 threads logged eight such stalls, then hung for good. The doc gives the likely cause; it's a bug to fix next. Default sizes stay under the pool size, and a watchdog turns a hang into a failed record.
  • Concurrent computePool() fan-outs serialize behind one job slot.
  • Independent schedulers on 8 threads run fib about 4.5× faster.

Notes

  • The Linux and macOS code paths (pinning, /proc and mach counters, the operator new count) haven't been compiled before this PR. CI is their first build.
  • --smoke takes about 8 s on an idle machine.

…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.
transfix added a commit that referenced this pull request Oct 27, 2026
The locks fold-in made its references to STATE_EXEC_LOCKS.md and STATE_EXEC_LOCKS_PROTOCOL.md
relative links, while the document still named STATE_EXEC_EXCEPTIONS.md, ARIADNE.md and
STATE_EXEC_DEVELOPER_GUIDE.md as plain code paths. Those ten mentions are now links too, as in
most of docs/ and in the two locks documents, and the lines they lengthened are re-wrapped. The
words are unchanged. STATE_EXEC_BENCH.md stays a plain path: it is not on this branch (#834).
…ug build finishes

The scenario arms max_time = 0.1 s, Ariadne's action default, on a loop that must finish inside
it. Its smoke size, 300 iterations, takes about 150 ms on the async scheduler in a Debug build
(package-linux / libcvc-debug), so the process was killed (time_limit_exceeded) and the smoke
test failed there on every attempt. The smoke run only checks that the scenario works; it now
runs 30 iterations. The measured size (8000) is unchanged.
transfix added a commit that referenced this pull request Oct 27, 2026
…oups first) (#835)

* docs: STATE_EXEC_THREADED.md, a design for running state_exec programs on several threads

Every scheduler steps its processes on one thread today. This designs parallel execution after
weighing five independently written proposals:
- one scheduler on N workers over heap domains;
- one scheduler per thread with handoff;
- BEAM-style SMP;
- share-nothing isolates;
- an incremental groups-first path.
A prior-art survey (BEAM, Go, Tokio, CPython subinterpreters, Racket places, V8 isolates) informs
it, and three judges scored all five against the code.

The decision, unanimous among the judges, is groups first. An execution group is one scheduler
with its own async host, cycle registry and random stream, stepped by one thread at a time. Groups
run in parallel on a shared worker pool, added in stages:
- 0: process-global hazard fixes and a TSan job;
- 1: groups on a fork-join pool;
- 2: a continuous pool with wakeups and a router for messages between groups;
- 3: isolated spawns and moving processes;
- S: slices, a single-thread speed-up;
- 4: several threads inside one group, held in reserve.

The doc lists every blocker (B1-B32) with file:line and the stage that resolves it, the semantics
changes, expected performance with the measured data and new benchmark scenarios, a test list
(including TSan), risks, and questions for review.

The developer guide links to it.

* docs: adopt the groups-first threaded design and record the 9.2 decisions

The user adopted STATE_EXEC_THREADED.md with the proposed answer to each of
its 14 questions. Section 9.2 now records the decisions; Q7, Q10, Q13 and the
width half of Q11 had no proposal and take the plan the document already
follows. The references that called those questions open now state the
answers, the developer guide's link says the design is adopted, and settled
question 4 of STATE_EXEC_EXCEPTIONS.md notes that Stage 2 splits the kernel
pool.

* docs: STATE_EXEC_LOCKS.md, locks on the state tree and process priority changes

The user asked for mutexes in the DSL, to lock sections of the state tree that programs are
working on, and for programs to change process priority. This designs both, on one thread and on
several, as a track beside STATE_EXEC_THREADED.md, and leaves what a later cross-host stage needs.

Four proposals were written and two judges scored them; the named, scoped locks proposal won. Two
adversarial review rounds then showed its protocol was not converging, so its core was simplified:
one lock manager per app under one mutex, requests granted all at once or not at all, tickets that
hold the outcome, exact deadlock detection when a request blocks, and only wake and relevel hints
crossing threads. Four more review rounds settled the text.

The document covers:
- the DSL: with-lock, locks-held, lock-query, set-priority, get-priority, and the atomic
  state-incr, state-cas and state-swap, with LockError, DeadlockError and PermissionError;
- the semantics: ownership, modes and coverage, fairness, timeouts, release on every way a process
  ends or unwinds, fork, spawn and snapshots;
- deadlock detection and priority inheritance through locks, and priority changes with Unix rules;
- the C++ architecture (the manager, a lock home per scheduler, single and shared mode), how locks
  meet execution groups, and migration between hosts as the last phase;
- phases L0-L7, the bench scenarios and gates, a test list, risks and open questions.

The exact protocol is STATE_EXEC_LOCKS_PROTOCOL.md, in the next commit.

* docs: STATE_EXEC_LOCKS_PROTOCOL.md, the exact lock protocol behind STATE_EXEC_LOCKS.md

STATE_EXEC_LOCKS.md section 8.6 names this as its protocol. It specifies, as pseudo-code, the
lock manager's state (one table under one mutex), the per-scheduler homes and their ports, every
manager operation, and every home action from with-lock's entry to a scheduler's destruction.
Section 6 lists invariants I1-I15 with their proofs; lock_manager::check() is to assert the
manager's clauses after every operation in test builds.

Section 7 sets out the model check (LT-5): the configurations, the properties, the mutations that
must be caught, and the design-time Python model that checks this text before any code exists.
That model lands as tools/locks_model/. Section 8 lists what the simplification removed from the
earlier design, and section 9 leaves moving a lock holder between groups (L4) to a later
specification.

* docs: fold locks, priority changes and Stage M into STATE_EXEC_THREADED.md

The locks design (STATE_EXEC_LOCKS.md) extends the threaded design. These edits make the threaded
design agree with it:
- groups: locks have no home group and do not use the router. All lock state lives in the app's
  lock manager under one mutex, and only wake and relevel posts cross groups, through each group's
  lock port, which its teardown closes right after taking the group's token;
- B28 lands whole in the locks track's L1, before Stage 0, and B27's single-scheduler part in its
  L1b, before Stage 1, each with section 5's compatibility scan;
- priority: strict inside a group; Stage 2's ready queue weights a group by its best runnable
  priority; cross-group set-priority goes through post_control under Q5; workers get an OS thread
  class, host-only;
- deterministic mode grants in arrival order and names the requester that closes a cycle as the
  deadlock victim;
- Stage 3 moves lock holders, never waiters, through the lock protocol's move, specified first;
- a new Stage M, scheduled last, moves programs between hosts, needing only Stage 0 and the locks
  track's single-machine phases.

New sections 4.19 (locks and priority across groups), 4.20 (Stage M), 8.11 (LG tests) and 8.12
(MG tests), and additions to the header, 1.1, 1.2, 2.3, 2.4, 4.1-4.6 and 4.10-4.18, sections 5 to 7,
9.1 and 9.2. The references to the two new documents are links. One line of the 4.19 Priority
bullet is re-wrapped to the document's width.

* tools: locks_model, the design-time model of the lock protocol

STATE_EXEC_LOCKS_PROTOCOL.md section 7 checks the protocol with a Python model before any C++
exists, and STATE_EXEC_LOCKS.md 8.1 places it here. This is revision 5b, the one section 7 names:
lockmodel.py implements the manager's operations literally and asserts the manager's invariants
after each; world.py adds the homes, ports and posts as a step relation with the home-side
invariants. scenarios.py runs directed scenarios and checks that every mutation section 7 lists is
caught by the violation it names; explore.py explores a configuration exhaustively to a bound;
explore_scripts.py explores every interleaving of scripted processes with faults; random_runs.py
runs long random worlds. run_long.sh runs all of them at full size (about 2 hours on 22 cores and
15 GB) into results/, which is ignored. The README says how to run each one and what each
configuration covers.

One fix to the scripted runs: the nested mode drew a destroy flag for about 30% of its
combinations but used the default fault kinds, which have no 'destroy', so no nested run ever
destroyed a home (only pairs did). Its destroy combinations now add 'destroy' to their fault
kinds; the generator is drawn in the same order, so every combination is otherwise unchanged. Seven
nested combinations now count 1205 destroys with lock state, where ten counted none before.

The docstrings name STATE_EXEC_LOCKS_PROTOCOL.md rather than the draft's file name.

* docs: STATE_EXEC_THREADED.md, make the locks fold-in agree with the rest

Review of the locks edits found places where the new text and the old disagreed:
- 2.4: the locks track's row now names the blockers it settles (B28 in L1, B27's single-scheduler
  part in L1b), and the lead-in covers the track as well as the branches;
- 4.4: fork-join breaks LPT ties by best_runnable only from Stage 2, which publishes it (4.5);
  the ready queue's mutex is named as such, not as "the lock";
- 4.7 and 4.18 B7: "the built-in class dicts", since their number grows from 13 to 16 with the
  locks track;
- 4.11: cross-group set-priority and cross-group lock grants lose their immediacy too;
- 4.15: a lock holder's eligibility for a move follows the requirement list instead of joining
  it, and the spawn-context and 6.3 Stage 2 lists keep one ending per list;
- 4.19: the app's lock manager runs in shared mode only when several threads use it, single at 0
  threads (4.14);
- 4.20: Stage M's eligibility is a subset of Stage 3's, not the same rules;
- 7: Stage 0's fork entries and risk, and Stage 1's spawn-context entries, say what changes when
  the locks track's L1 or L1b lands first.

* docs: STATE_EXEC_THREADED.md, link every doc on this branch

The locks fold-in made its references to STATE_EXEC_LOCKS.md and STATE_EXEC_LOCKS_PROTOCOL.md
relative links, while the document still named STATE_EXEC_EXCEPTIONS.md, ARIADNE.md and
STATE_EXEC_DEVELOPER_GUIDE.md as plain code paths. Those ten mentions are now links too, as in
most of docs/ and in the two locks documents, and the lines they lengthened are re-wrapped. The
words are unchanged. STATE_EXEC_BENCH.md stays a plain path: it is not on this branch (#834).

* docs: STATE_EXEC_LOCKS*.md, define the shorthands and fix stale references

STATE_EXEC_LOCKS.md:
- Sources defines Bn (td's blockers, td 2.3) beside Qn, since the design cites B17, B21 and others
  bare.
- Sources no longer says the files of unprefixed references are identical on perf/sched: there
  the cited lines of pycvc_exec.cpp, pycvc.i and process.h move by up to four, and Exec::run waits
  for work instead of sleeping.
- 8.7's process.cpp row cited state_exec_scheduler_test.cpp:1369-1438 without the sched: prefix;
  the wake_due tests are on perf/sched only, at sched:state_exec_scheduler_test.cpp:1386-1431.

STATE_EXEC_LOCKS_PROTOCOL.md:
- The intro defines Qn (td's decisions), which the protocol cites as Q5.
- Section 7's port-race mutation is "a reading 2.3 rules out" rather than an earlier reading of a
  draft.
- Section 8's "5.2 compatibility table" named a section of the unpublished round-2 design; it is
  now "their compatibility table".

* docs, tools: keep the model's revision history in tools/locks_model

STATE_EXEC_LOCKS_PROTOCOL.md section 7 ended with the model's revision history (revision 5b
follows this text, revision 5 added this, revision 5b added that), and STATE_EXEC_LOCKS.md's LT-5
named revision 5b. Neither the earlier revisions nor their runs are in the repository, and the
landed model is 5b plus the nested-destroy fix, so section 7 now says which clauses the model
checks, without revision numbers, and points to tools/locks_model/README.md. LT-5 drops the
revision. The README gains a Revisions section with the history section 7 held, and its notes on
the fix become a subsection of it; lockmodel.py's docstring names the README instead of
section 7.

* tools: locks_model run_long.sh, check the interpreter and quote the knobs

run_long.sh took PY from command -v python3 and only checked that it was non-empty. On Windows
that finds the Microsoft Store's stub, which prints "Python was not found" and exits, so the
README's plain "sh run_long.sh" ran nothing, wrote every marker and a SUMMARY.txt without a
result line, and still exited 0. It now runs PY first and requires it to print that it is Python
3.8 or later, trying python3 then python when PY is unset, and stops with a message otherwise. A
relative PY is taken from the caller's directory, before the script changes to its own.

PY and R are user knobs, so every use is quoted: the calls, mkdir, every redirect, the xargs
command (which now takes the configuration as an argument) and the summary call. A path with a
space, such as a Python under "Program Files", no longer splits.

The script's exit status is now the summary's verdict: 0 only when SUMMARY.txt's last line is
"0 unexpected" (read without the CR a Windows Python writes). The header and the README say that a
relative R is resolved against the script's directory, and that PY usually has to be set on
Windows.
@transfix
transfix enabled auto-merge (squash) October 27, 2026 22:12
@transfix
transfix merged commit bc4761b into master Oct 27, 2026
20 of 24 checks passed
transfix added a commit that referenced this pull request Oct 27, 2026
#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 added a commit that referenced this pull request Oct 27, 2026
#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 added a commit that referenced this pull request Oct 27, 2026
#834, the benchmark suite this branch was stacked on, is squash-merged into master as bc4761b.
The merge base is cd9c50e, 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 added a commit that referenced this pull request Oct 27, 2026
The required clang-format (changed lines) check runs only on PRs against master, so it first ran
when this PR was retargeted from #834's branch. Formatting only.
transfix added a commit that referenced this pull request Oct 27, 2026
The required clang-format (changed lines) check runs only on PRs against master, so it first ran
when this PR was retargeted from #834's branch. Formatting only.
transfix added a commit that referenced this pull request Oct 28, 2026
* state_exec_bench: a benchmark suite for the evaluators, the schedulers 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.

* state_exec_bench: an in-process sampling profiler (--sample, Windows 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.

* state_exec: find special forms with a switch, not a chain of string compares

Both evaluators matched a call head against every special form in turn, up to 19
std::string compares for each ordinary call. special_form_of() (special_forms.h, private)
switches on the name's length and a letter or two and confirms the one candidate with a
single compare. The order is unchanged: special forms first, then user macros (the macro
map is no longer hashed when no macro is defined), then bindings. The recursive evaluator
still treats yield and break as ordinary names.

Tests: the classifier against every special form name and its one-letter neighbours, and
the precedence of special forms over macros and bindings in both evaluators.

* state_exec: recycle call scopes per thread, and hash a name once per lookup

environment::extend() made a fresh std::unordered_map for every closure call, let and catch:
on MSVC three allocations (the make_shared block, the map's list sentinel and its bucket
array) before the first binding, and a node per binding. A scope from extend() now has a
deleter that empties it the way its destructor would (the enclosing scope first, then each
binding through ~value_tag, so a release backlog sees the same owners in the same order) and
keeps it, with its bindings' nodes and its control block, for the next extend() and set() on
the same thread. What is kept is bounded (64 scopes, 128 nodes, 64 blocks per thread) and only
scopes whose map is still small; nothing is shared between threads, and a scope dropped after
its thread's pool is gone is freed.

environment::lookup() hashed the name again in every scope of the chain. It now skips empty
scopes, hashes once, and walks the bucket of that hash in each scope. The bucket formula (a
mask for a power-of-two bucket count, else a remainder) is checked against the map's own
bucket() at startup; where it doesn't hold, lookups use find() as before. A standalone MSVC
micro benchmark of a 17-scope chain: 86 -> 73 ns for '+', 99 -> 64 ns for 'fib', 401 -> 55 ns
for a 24-character name.

Tests: a recycled scope comes back empty, unfrozen and linked to its new parent; its bindings
are dropped through the release backlog as a destroyed scope's are; a 200000-deep chain frees;
lookups over 5000-name scopes, empty scopes and shadowing; a scope dropped at thread exit.

* state_exec: reuse frame vectors in the stackless evaluator

Most of a step's allocations were a frame's vectors: a call form copied its arguments into a
fresh vector, its children's values grew another one from empty (two or three allocations for
a two-argument call), and a set or for copied its name into a vector of strings. A popped frame
now gives its emptied vectors back to a small per-thread store, kept by capacity, and a frame
takes one of exactly the capacity it needs (the call's argument count, a begin's form count),
so a frame holds no more than it did and the stack's heap measurement doesn't grow. The parts
of a popped frame are freed in its destructor's order, so dropped owners reach a release
backlog as before. Frames are built in place on the stack instead of moved in from a
temporary, step_init reads the form's arguments in place and copies only what a frame keeps,
and a for over a list copies the list once, not twice.

Allocations per iteration (state_exec_bench, stackless): arith_loop 18 -> 0, closure_calls
24 -> 0, native_calls 17 -> 0, list_build_walk 21 -> 0, fib 16.5 -> 0.19.

Tests: step counts of each kind for fourteen programs (calls, closures, loops, let, try, macros,
classes, generators, sliced deep data), pinned at the values the evaluator took before this
work; a popped frame keeps no value alive.

* state_exec: count an eval step without a locked add

evaluation_stats::increment_step() did a lock-prefixed fetch_add on every step, although only
the thread stepping a state counts its steps. Eval steps now go to a counter of their own,
updated with a relaxed load and store; steps of the other kinds and the steps add_steps()
charges (an async host, possibly from another thread) keep their atomic adds on the shared
counter, and get_step_count() is the sum. Readers on other threads still read atomics, and
every count is what it was.

Test: a thread counting steps while another charges steps and a third reads them gets exact
totals per kind, and a moved or restarted stats object carries or clears them.

* state_exec: build a closure's (begin ...) body once, not on every call

A call of a DSL function whose body has several forms wrapped them in a new (begin ...) list
every time: two allocations and a reference count per form. The stackless evaluator now makes
that list when it makes the closure (lambda, defun, defclass methods) and keeps it in a new
closure::body_expr; a call (and generator, which did the same) uses it while it still matches
the body, form for form, and builds one as before otherwise (a closure made elsewhere, or a
body changed since). The heap walks count it as one of the closure's edges and the cycle
collector clears it with the body; the codec, printing and equality ignore it.

Test: the list is made for a body of several forms only, holds the body's own forms, and a
body changed after the closure was made runs as changed.

* state_exec: look a call's function up once, at its init

A call's init step looked its head up through the scope chain only to check it exists, and
its apply step looked it up again. The init now records the binding it found (a node of a
scope's bindings), the scope, and the sum of the sizes of the scopes from the frame's out to
that one (eval_frame::callee, callee_scope, callee_stamp, not serialized). Apply uses it when
that sum is unchanged and the binding still has the call's head name, and looks the name up
otherwise. Bindings are only added to a live scope, so an unchanged sum means no nearer scope
has gained a binding that could shadow the one found; a binding rebound in place is read
through the node, so the apply step sees the value a lookup would. A restored frame has no
record and looks the name up. environment::find_binding() is lookup() saying where.

Tests: a function rebound in place, shadowed in a nearer scope, or rebound between calls while
a call's arguments run is the one applied; the record of a call's init, and a binding added in
the process scope between init and apply.

* state_exec: clang-format the lines of the last three commits

* state_exec: cheaper steps in the recursive evaluator

- The environment goes down by const reference: eval_internal, eval_form and every special
  form took the shared_ptr by value, two atomic reference count changes per node.
- A form's copy of its arguments and the vector of their values come from vectors the
  evaluator keeps between forms (emptied when the form is done, so they hold no values),
  not fresh allocations. The copy itself stays: a program may change its own code while
  it runs, and a form evaluates the arguments it had.
- The trail guard tells an unwinding exception from a return by a flag set when eval_form
  returns, not two std::uncaught_exceptions() calls per node (a fiber-local read on MSVC).
- A let body runs over the form's own argument copy instead of a second copy.
- evaluate() no longer makes a scope it throws away.

With the scope and dispatch changes before it, the recursive eval.* programs run in about
half the time and allocate nothing per iteration (arith_loop 9 -> 0, fib 12 -> 0.03).

Test: a form's kept vectors hold no values once it is done.

* state_exec: copy a value once when a frame returns it, and a frame's expression once

A frame's value went to the frame below through pop_frame's by-value parameter: copied in,
moved into the parent's results, then destroyed. A symbol's value, an atom, and the value an
if, begin or let passes on are now put straight into the parent's results (an atom's and a
passed-on value moved, not copied), before the frame goes: the value may live in that frame,
or in a scope only that frame holds. The frame's parts are freed as before, in the same
order. push_frame copies the expression and scope straight into the new frame when the stack
has room (they may be in the top frame, which a growing stack moves), instead of copying them
into parameters and moving those in.

* state_exec: read tokens and strings in runs, and make each list at its exact size

- A symbol or number token is found first and copied once, not built a character at a time,
  and strtod is asked only about a token it could read (a sign, then a digit, '.', or the i/n
  of inf and nan): every other token is a symbol, as strtod would have said.
- A string's or bytes literal's plain characters up to the next quote or escape are appended
  as one run, the line and column moved on as advance() would have moved them.
- A list's elements are collected in a vector the parser keeps (or one with room for eight)
  and the list gets a vector of its exact size, instead of growing one an element at a time:
  parse.large 37050 -> 17779 allocations, parse.small 42 -> 34, and a parsed program holds no
  spare capacity.

Tests: tokens read as numbers, booleans, nil or symbols exactly as before (the cases checked
against the previous parser too), line and column after tokens and multi-line strings, string
and bytes runs around escapes, and parsed lists at their exact size.

* state_exec: keep a closure's (begin ...) body as a list pointer

closure::body_expr was a value_t, 72 bytes on MSVC, which footprint.closure showed on every
closure (291 -> 364 heap bytes per closure). It is now the list_ptr itself (16 bytes); the
heap walks count it as a list edge, and the cycle collector resets it.

* state_exec: fewer value copies for set, native results and try entry

- set binds a copy of its value and passes the value itself on, instead of copying it into a
  local, again into the binding and again into the frame below.
- A native call's result is moved straight into the frame below.
- Entering a try moves the body, cleanup and catch clauses into its frame instead of copying
  them out of initializer lists, and takes its vectors from the kept ones.

* state_exec: one allocation per recycled scope, and keep only fresh-sized ones

A scope from environment::extend() and its shared_ptr control block are one
allocation again, as make_shared made them: a scope_block holds the scope and
a slot that the block's allocator hands out for the control block. The block
is kept for reuse, or freed, when the control block is deallocated, which is
after the deleter emptied the scope. Long-lived scopes (a process's) are back
to one allocation each and sit where they did. Before, the separate control
block made the many-process scheduler scenarios 5-18% slower.

A scope is kept only while its map has the bucket count of a new map. On
libstdc++ and libc++ a new map has no buckets allocated, so the bucket count
of a recycled scope, which heap measurement counts, could depend on what the
thread recycled before. Now it never does. On MSVC nothing changes: a new map
has 8 buckets and keeps them up to 8 bindings.

bind_new() takes the node out of the pool before filling it, so a throwing key
copy or insert frees the node and its value, as a failed emplace would.

* state_exec: fix a tail call through a parameter, and check a call's scopes by identity

call_closure() popped the call's frame and then read the closure through
`cls`, a reference into the callee's binding. When the function is a
parameter called in tail position, that binding is in the scope only the
popped frame held, and the scope recycler had just moved the value out of it:
`(defun twice (f x) (f (f x))) (twice inc 5)` crashed. (Before the recycler
this was a latent use after free; `(defun call-it (h) (h)) (call-it (lambda
() 42))` crashed on the old code too.) The call now takes the bound scope and
the body expression before the frame goes. Tests cover a named function and
lambdas passed as parameters on the bare evaluators and both schedulers.

A call's record of the function its init found now marks the scopes the
lookup walked by their count and a stamp: the sum of their sizes (exact: a
scope that gains a binding changes it) and a mix of their addresses, so a
chain a host rewires (environment::outer, writable from pycvc) is looked up
again. The init lookup computes the mark in the same walk, so there is one
walk fewer per call. eval_frame now grows by 16 bytes, not 24 (224 -> 240 on
MSVC x64). environment::find_binding(), added earlier on this branch, is gone.

The last frame's parts are dropped before the state's old result again, as
pop_frame did (with slicing on, release backlog order decides how freeing is
split into data steps). push_frame() copies the expression and scope before it
grows the stack, so an out-of-memory copy leaves the stack as it was.

* state_exec: share a closure's (begin ...) body among the closures one form makes

closure::body_expr was built for every closure with a body of several forms
when the closure was made: a list of n+1 values and its control block per
closure, made even for closures never called, and counted by heap
measurement. 100k two-form closures cost 717 bytes each instead of 418.

Now the closures one lambda form makes share one (begin ...). A small
per-thread table, one slot per form address, holds it weakly. A slot is used
only while what it holds is exactly (begin body...) for the new closure's
body, so a slot whose form was freed and its address reused is harmless. A
closure costs its 16-byte pointer, and making one costs a few pointer
compares, not two allocations.

A generator gets a body list of its own again. (root) in a generator returns
that list, and a generator that appends to it no longer changes the body of a
sibling generator made from the same closure.

* state_exec: keep evaluation_stats::increment_step() safe for any thread

increment_step() is public, and pycvc wraps it (and start()). The evaluators
release the GIL while they run, so a count made from another thread during
stepping could be lost under the load-and-store fast path. increment_step()
is a locked add again. The evaluators count their own eval steps through a
private count_eval_step(), which keeps the load and store: the stepping
thread is the only one that counts while it steps. start() now says not to
reset the counts while another thread steps the state.

* state_exec: keep only short element vectors in the parser

The parser copied every closed list into an exact-size vector and kept the
vector it was collected in. For a large literal list that held about twice
the list's memory while the list closed, and then kept the large vector until
the parser was destroyed. Now a list collected in a vector of more than 64
values takes that vector, as before this branch. Only short vectors are
copied and kept.

* state_exec: state the evaluators' cache bounds in bytes; bench a multi-form closure

The recursive evaluator keeps at most 64 spare argument vectors of up to 8
values (was 16), about 37 KB per evaluator on 64-bit MSVC. The stackless
evaluator's per-thread frame vectors are at most about 41 KB, and the scope
pool (types.cpp) under 35 KB per thread. The comments now say so.

footprint.closure_forms keeps n closures whose body has two forms, the case
the per-closure (begin ...) cost showed up in; footprint.closure has a
one-form body.

* state_exec: put a scope's control block first in its block, with a stateless allocator

The block allocator carried a pointer to its block, which made the control
block 8 bytes larger and the block 136 bytes on MSVC (make_shared's was
104). footprint.environment measured 813 -> 861 bytes per item. Now the
block is a 32-byte slot followed by the scope (120 bytes on MSVC). extend()
names the block for the allocator in a thread-local just before it makes the
shared_ptr, so the deleter and allocator are empty and the control block is
24 bytes (32 with libc++). Deallocation finds the block at the slot's
address.

* state_exec: leave a kept binding node holding nil, not a moved-from value

scope_recycler moved each binding's value out and kept the node for the
next bind_new(). That empties the node only if a moved-from value is
empty. libc++ moves a std::function whose callable fits its small buffer
by copying the callable, so a kept node held a live copy of a native
function: a class constructor's copy kept the class dict alive, with its
methods and the scopes they captured, until the node was reused (in some
other process's step) or the thread exited. The node's value is now
exchanged for nil, so the value still drops through the same local, in
the same order. MSVC and libstdc++ already leave the source empty, so the
new test fails only on libc++.

* state_exec: count another thread's steps apart from the evaluator's own

increment_step(eval) did a locked add on eval_step_count, the counter the
stepping evaluator updates with a plain load and store in
count_eval_step(), so a count made from another thread between that load
and store was lost. increment_step() now adds to step_count, as it did
before this branch, and only the stepping evaluator writes
eval_step_count. get_step_count() and steps(eval) sum both, as before.
New tests race increment_step() against each evaluator stepping a loop.

* state_exec: compare a body's numbers bit for bit before sharing its (begin ...)

same_form() compared doubles with ==, so 0.0 and -0.0 were the same form.
A lambda form made at the address of a freed one, whose body differed
only in the sign of a zero, got the freed form's (begin ...) and
evaluated the other literal: (defmacro k (v) (lambda () nil v))
(set a (k -0.0)) (set b (k 0.0)) (b) returned -0.0. Numbers now compare
by bit pattern (a NaN is the same form as itself). The other atoms
already compare exactly, and lists, dicts and closures by object.

* state_exec: tell a scope made in a dropped scope's block from that scope

A call's record stamped the scopes its lookup walked with their addresses
and sizes. extend() hands out the block the last dropped scope left, so a
host that rewired outer, dropping a scope, and built a replacement with
as many bindings got the same address and the same stamp: the apply step
then used the dropped scope's binding node, kept (holding nil) or freed.

Each environment now has a serial, drawn when it is made, copied or
assigned, and when extend() makes a scope in a kept block. Serials come
from one count, a run of 1024 per thread at a time, so no two scopes
share one until 2^32 have been made. The stamp mixes the serial in with
the address. It is 4 bytes in the padding after `frozen`, so a scope is
no larger (88 bytes on 64-bit MSVC before and after).

* state_exec: assert a scope's reuse only where the scope is kept

ExtendedScopeComesBackEmpty expected the next scope to be the one just
dropped, which had bindings. Only MSVC keeps such a scope (its maps have
8 buckets from the start); libstdc++ and libc++ free it, so the check
held only when the allocator happened to hand the same block back, and
fails under ASan. The test now takes the thread's kept scopes first, so
the pool has room, expects the same address only when the dropped scope
had a new map's bucket count, and otherwise checks what holds
everywhere: the next scope is empty, unfrozen and in the given scope.

* state_exec: say in the bench doc which evaluator pathologies are fixed

The known-pathology bullets for per-form argument copies and string
dispatch (with the step count's atomic increment) and for the
(begin ...) body rebuilt on every call described the old code as
current. Each now says what changed, as the scheduler and async bullets
do, and the closure_body scenario no longer says its body is rebuilt on
every call.

* state_exec: say which step counts are locked adds, and test them across steps

The step-count notes said increment_step() adds to a counter the
evaluators never write. The stackless evaluator writes it too, for its
read and data steps (and the async evaluator for each of its steps).
What keeps another thread's count is that every one of those writes is
a locked add: only count_eval_step() stores plainly, and only to
eval_step_count. increment_step()'s comment and the bench doc now say
so, and name the one step where a count from another thread can still
be lost, as at base: the step that ends a script read in slices moves
the stats into the program's state, and a move copies the counts.

The new test races increment_step() against a stackless evaluator that
reads a script a token per step and walks data two nodes per step. It
fails if those steps count with a plain store.

* style: clang-format 18 on the lines this branch changes

The required clang-format (changed lines) check runs only on PRs against master, so it first ran
when this PR was retargeted from #834's branch. Formatting only.
transfix added a commit that referenced this pull request Oct 28, 2026
…ncurrent compute fan-outs (#843)

* state_exec_bench: a benchmark suite for the evaluators, the schedulers 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.

* state_exec_bench: an in-process sampling profiler (--sample, Windows 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.

* thread_pool: run concurrent fan-outs side by side, wake only enlisted workers

parallel_for held one job slot behind _post_mtx, so a second caller blocked
until the first fan-out drained, and every post notify_all'd the whole pool,
even for a fan-out capped at two participants.

Jobs now go on a FIFO list. A free worker joins the oldest job with room
under its cap and indices left; the caller unlinks its job (no joins after)
before waiting for the workers that did join. A post wakes min(idle,
enlisted) workers. Chunks still run under the poster's fanout_context, one
run_chunks per joined worker, so async_host's per-call charge accounts are
unchanged.

Tests: two capped fan-outs that each wait to see the other running; three
posters sharing six workers, each chunk under its own context, at most the
cap's workers inside a context at once.

* app: persistent background-pool workers; fix the stall and hang past the pool size

The background pool created a boost::thread per task, registered it in
_threads until ~app (so each task's functor and captures, an async call's
result included, lived until then), probed uniqueThreadKey from 0 under a
mutex and rebuilt the thread-key sets over every thread ever started.

The hang: tasks queued while the pool was full all got the same key, so a
worker starting the next one interrupted and timed_joined the thread holding
that key. tryStartWorker unlocked _threadPoolMutex by hand around
threads(key, ...), whose interruption points (its top, hasThread, the
timed_join) then threw thread_interrupted in a worker another worker had
just interrupted. The caller's scoped_lock unlocked the mutex a second time;
on Windows that flips boost::mutex's lock bit back on with no owner, and
every later locker blocks forever. Confirmed with a probe on the old code:
the throw fired in each failing run, followed by "did not stop in 5s"
stalls, stranded tasks (14 of 1000 done after 10 s) or a hard hang.

Now:
- anonymous tasks (wait=false, and the new submitPooled) run on persistent
  workers, started on demand up to the pool size and joined by ~app; no key,
  no _threads entry, destroyed on the worker before they count as done;
- one queue ordered by priority, then submission (FIFO within a priority);
- keyed tasks (wait=true) keep their contract: a thread of their own,
  registered under the key before they run (synchronously when the pool has
  room), the entry kept after they end; a finishing keyed thread starts the
  next queued keyed task itself, so join-then-lookup chains still work;
- the pool mutex is only released by the RAII lock that took it, and workers
  and registrations run with interruption disabled (only tasks are
  interruptible; a stale request is dropped before the next task);
- wait_for_threads() interrupts the running pooled tasks and waits up to 5 s
  for the pool to drain; ~app interrupts running tasks, drops queued ones and
  joins the workers;
- compute_async submits anonymously.

Tests: a 1000-task flood on 4 workers (hung or stranded before), worker
reuse and no thread-map entries, FIFO within a priority, no retention after
a task ends, wait() waits for the pool, and ~app with a full queue returns
promptly and releases the dropped tasks.

* async_host: less per-call work; kernels on the pool's persistent workers

Per call, on the scheduler thread:
- the {"function": name} error-field vectors (call, outcome, begin_external)
  are built only on the way to a throw;
- the reply channel string is made only for a call that parks or returns a
  future (a transparent inline call has neither);
- check_open reads an atomic instead of taking the host lock;
- shared_state::add prunes expired weak_ptrs when the list has doubled since
  the last prune (amortized O(1)) instead of scanning every live call;
- the kernel goes into the executor's task itself (no shared_ptr holder), and
  that task is submitted anonymously with app::submitPooled (no key string,
  no uniqueThreadKey probing, no thread per call) or moved to the lane;
- run_inline no longer reads the step rate up front: cancelled() reads it on
  first need for a step budget, and the final charge reads it as before (so a
  change still applies to the next charge).

run_kernel destroys the kernel on its thread before the host's count goes
down, as the holder did. launch_pool_task submits to the background pool
directly instead of compute_async(1, ...), which also built the compute pool.

Tests: 40 calls on a 2-worker pool all complete on at most 2 threads with no
thread-map entries; a finished call keeps neither its kernel's captures nor
itself (its result) alive; shutdown still cancels the call in flight after
300 finished ones.

* app: don't start a pool worker per task in a burst

A worker started for a queued task takes it and wakes or starts the next
one before it waits, so while one is still starting, a new submission
doesn't start another. A burst of short tasks now starts workers only as
fast as they are needed (async.flood.noop n=10 started 19 threads per
fresh app; the old pool started 10, one per task).

* app: start pool workers outside the pool mutex

Creating a thread can take milliseconds on a loaded machine, and the worker
was created with _threadPoolMutex held, so every submitter (the scheduler
thread among them) and every finishing worker waited behind it: in
async.flood.noop n=10 the completions of a burst arrived together, 1-30 ms
late. tryStartWorker now only asks for a worker; whoever called it creates
the thread once it has let the mutex go (startRequestedWorkers), and a
worker created while ~app stops the pool is joined by its creator.

* async_host: a call leaves the host's cancel list when its kernel ends

The list of calls to cancel at shutdown held a weak_ptr per call until a
batch prune, and a weak_ptr keeps a make_shared object's storage (the whole
async_call) allocated: async.pool_retention where=lane kept ~270 bytes per
call. Each call now records its index in the list, and leaves in O(1) (the
last entry moves into its slot) when its kernel ends, or, for an external
call, when finish() posts its outcome. The batch prune stays for calls that
die without leaving. The shutdown test makes 100 calls first instead of 300
(each costs a pump period).

* docs: the background pool, async host and compute pool pathologies after the fixes

STATE_EXEC_BENCH.md: what changed for the thread-per-call executor, the
stall and hang past the pool size (its cause, now confirmed), the
serialized compute fan-outs and the per-call overhead, with the A/B
numbers; --bg-oversubscribe now only matters for older builds.

* app: a keyed task with room registers before it returns; a burst gets its workers at once

Review fixes for the persistent background pool.

- A keyed startThreadPooled (wait=true) with room in the pool for it and
  for every task already queued now starts on the submitting thread, so
  it is in threads() when startThreadPooled returns even right behind an
  anonymous task still waiting for its worker. Before, it was registered
  only if it was at the head of the queue, and the documented pattern
  `if (hasThread(k)) threads(k)->join();` silently skipped it.
- poolKickLocked() gives every queued task that may start a worker on its
  way: a signalled or starting one, else an idle one to wake, else a new
  one up to the pool size. A burst of N tasks on a fresh app now starts
  min(N, pool size) workers at once instead of one at a time, and a
  signalled worker that has not woken yet is no longer counted as idle.
- Workers wait on a std::condition_variable_any (boost's makes and closes
  a semaphore per wait on Windows) and are signalled after the pool mutex
  is released. Threads are created after it is released too, and with no
  extra lock round trip when nothing was asked for.
- Workers are interrupted only under the pool mutex (wait_for_threads,
  ~app), with a generation count: a worker clears a stale request, under
  the mutex, before it takes its next task, and an interrupt sent after
  the take is that task's. One that reached a worker between taking a
  task and starting it used to be cleared as stale, and ~app then waited
  5 s for a task that never stopped.

Tests: a keyed task behind anonymous ones on a fresh and a warm pool is
registered on return and joined by the hasThread/join pattern; ~app right
after submitting interrupts every task taken (64 delays); a burst of 8
mutually waiting tasks runs at once on a fresh and a warm pool.

* async_host: settle a call before freeing its kernel; build the progress key on first post

- run_kernel decides the timeout, settles and posts the completion when
  the kernel ends, and only then frees the kernel. Freeing its captures (a
  large buffer, a Python callable's last reference under the GIL) had been
  counted against the call's timeout, turning a call that returned in
  time into a TimeoutError. The kernel is still freed on its thread before
  the host's count drops. Test: a kernel that returns at once with a 0.2 s
  timeout and captures taking 0.4 s to free returns its value.
- The "<name>.progress" channel key is built on the first post() (most
  kernels never post), from the process's root path kept on the call.

* docs: wait() is not a barrier; fan-outs share a pool's workers; keyed registration

- THREAD_POOL.md's many-small-tasks example waits on the tasks' own
  completion, and says that app.wait() interrupts running tasks and gives
  up after 5 s.
- THREAD_POOL(_API).md: when a keyed task is registered before
  startThreadPooled returns, and that a burst starts its workers at once.
- Comments that still described one fan-out at a time per compute pool
  (raycaster, VOLREN_API, lod tiles, producer_thread, a volren test) and
  launch_pool_task starting a thread per call (async_lane.h) now describe
  fan-outs running side by side on shared workers and the background
  pool's persistent workers.

* docs: the async-track bench numbers from the final A/B

- The baseline's pool aging is load-dependent (about 3-17x, median 12 at
  k=3000), retention is a few hundred bytes per call after the fix, and
  the baseline's oversubscribe hang is intermittent.
- A burst gets its workers at once; the worker wake's cost after the move
  to std::condition_variable_any.
- Concurrent saturating fan-outs: all of them finish 23-25 % sooner, and a
  single one's stretch at m=4 moves with load.
- Allocation savings quoted from the inline points (-15 to -23 %) and the
  poll1ms background point (-22 %), with a note that spin-driven threaded
  points mostly count idle pump iterations.

* app: a new pool worker takes no task before it is registered

- wait_for_threads() and ~app interrupt the workers in _poolWorkers, but a
  worker started by applyPoolKick could take and start a task before its
  creator had put it there. The interrupt then missed that task: wait()
  waited it out (up to 5 s), and in ~app the creator, seeing the stop,
  joined the worker with no interrupt and no time limit, or ~app gave up
  on the creator and freed the app while the worker still ran.
- A new worker now waits at a gate (PoolWorkerGate, guarded by the pool
  mutex) until its creator has registered it, or has seen the stop; one
  that is not registered ends without taking a task, and its creator
  interrupts it and joins it with a 5 s bound, with interruption disabled.
- A worker clears any interrupt sent before its first task, as it already
  did before each later one.
- Tests, through a protected test seam that holds the creator between the
  worker's start and its registration: wait() interrupts the task such a
  worker took (before: missed, wait() took 4 s), and a stop in that window
  leaves the task unrun and the creator not held up (before: the worker
  ran the task).

* app, async_host: a task the stopped pool drops reports it

- Once ~app has stopped the pool, a task submitted to it, or still in its
  queue, was destroyed without running and without any signal. An async
  call whose kernel was dropped stayed unsettled, its process parked, and
  its host's count of calls in flight never went down, so shutdown()
  waited for good; launch_pool_task never posted its one value, and
  compute_async never called back.
- submitPooled returns false when it drops a task (it returned void), and
  stopThreadPool destroys the queued tasks before it joins the workers.
- async_host: a threaded call's task holds a kernel_task that ends the
  call exactly once: run_kernel when it runs, or, refused (submitPooled
  false, a stopped lane) or destroyed unrun, RuntimeError "<name>: not
  run: ...", its kernel freed and the host's count lowered. The task's
  one capture fits std::function's buffer, so a call still allocates one
  block for it.
- launch_pool_task posts on_error("not run: the app's background pool has
  stopped") for a dropped task.
- compute_async gains an on_error overload that calls exactly one of
  on_done and on_error, also for a throw and a dropped job; the old form
  calls neither for a dropped job and releases both.
- Tests: a call made after the stop and one still queued at it raise
  RuntimeError and leave the host; a pool task dropped either way resumes
  its process with on_error's value; submitPooled reports a late submit
  and frees the task; compute_async's on_error form for a throw, a late
  submit and a queued drop.

* docs: dropped pool tasks report it; a new worker's first task is interruptible

- STATE_EXEC_EXCEPTIONS.md 3.5: async kernels, compute_async and
  launch_pool_task use app::submitPooled (it said startThreadPooled);
  3.6: a kernel its executor never runs ends its call with RuntimeError.
- THREAD_POOL(_API).md: wait() and ~app interrupt a task a worker took a
  moment after it started; a dropped task is destroyed unrun, submitPooled
  returns false after the stop, and what a task captured can report it.

* app, async_host, async_task: a pool task's drop guard is its own callable

- The drop guards (async_host's kernel_task, launch_pool_task's
  pool_task_post, compute_async's compute_job) were shared objects that
  each task captured by shared_ptr. MSVC and libc++ keep that one capture
  in std::function's buffer, but libstdc++ keeps only a trivially
  copyable callable there, so on Linux each threaded async call,
  launch_pool_task and compute_async allocated two blocks (the guard and
  the std::function's copy of the lambda) where they used to allocate one.
- Each guard is now the std::function's target itself, holding its state
  by value, with a flag that a move takes over: one heap block on every
  standard library, and no shared_ptr counts. Destroyed unrun, it ends
  the call, posts on_error's value or calls on_error, as before.
  std::function needs a copy constructor; no executor copies its task,
  and a copy takes the task over as a move does, so one object alone can
  end it.
- async_host::submit no longer settles a refused call itself: the task,
  destroyed unrun inside the lane's submit() or submitPooled(), does. A
  lane refusal still raises "<name>: lane '<lane>' is stopped" (the task
  points at the lane's key in the host); a kernel still queued when the
  pool stops now says "<name>: not run: the app's background pool has
  stopped", as a late submit does (it said "not run: its executor
  stopped").
- Tests: a call to a stopped lane raises RuntimeError naming the lane and
  leaves the host; the queued-drop test checks the whole message.

* docs: a dropped kernel's message names its cause; drop guards hold their state

- STATE_EXEC_EXCEPTIONS.md 3.6 grouped a kernel a stopped lane refuses
  with the pool's dropped kernels under "name: not run: ...". A lane
  refusal raises "name: lane 'lane' is stopped"; the pool's say "name:
  not run: the app's background pool has stopped". A lane runs every
  kernel it accepted before it stopped.
- THREAD_POOL(_API).md: a task reports its drop from its own destructor;
  the in-tree ones hold that state by value, since a shared_ptr capture
  adds a heap block per task under libstdc++.

* app_test: master's compute_async reap tests assert their guarantees on anonymous tasks

#827's four tests pinned the reap mechanism (a wait=false job's
reserved key, its thread-map entry, a later worker reaping it). On
perf/async a wait=false job or compute_async call is an anonymous pool
task with no key and no entry, so each test now checks the same
user-visible guarantee directly:

- ComputeAsyncReapsFinishedWorkerThreads -> ComputeAsyncCallsDoNotGrowTheThreadMap:
  threads() stays at its starting size right after every one of 60
  on_done calls (it allowed 4 stragglers once reaping caught up), and
  once the pool is idle every call's fn/on_done captures are released.
- QueuedComputeAsyncCallsKeepDistinctKeysAndAreReaped ->
  QueuedComputeAsyncCallsEachRunOnceUninterrupted: 100 calls queued
  behind a pool of 2 still each run on_done exactly once, none
  interrupted; threads() does not grow while they queue or after, and
  no finished call holds its captures.
- ReapingLeavesARunningPooledThreadListed ->
  ComputeAsyncChurnLeavesRunningPooledJobsAlone: with 20 compute_async
  calls going through, a long wait=false job is not listed, keeps its
  captures while it runs, is never interrupted and releases them once
  it ends; a long keyed (wait=true) job, the listed kind, keeps its
  entry, stays joinable, reports "Processing: <key>", and keeps its
  entry once it has ended.
- DestroyingAnAppWithComputeAsyncInFlightIsClean: same body, comments
  for the persistent workers, and every job ~app ran or dropped has
  released its captures when ~app returns.

* app: keep #827's overlay fallback, interrupt before joining in ~app, keep interrupts pending

Review of the master merge into perf/async found three behaviours the
merged pool got wrong.

compute_async no longer reported a thread it couldn't start. On master
it threw when creating a job's thread failed, and a threaded tf overlay
task caught that and carried on cooperatively (#827). On perf/async a
failed worker creation was swallowed and the job left queued, so with
no worker running the overlay process parked on a chunk nothing would
run until an unrelated submission started a worker. Now
enqueuePoolTask can hand an anonymous task back when the worker its
call asked for could not be created and the pool has none, running or
starting; compute_async then throws boost::thread_resource_error,
having released fn and on_done (and on_error) uncalled, and nothing is
left queued. With a worker running, the job still just waits for it. A
submitPooled task keeps waiting in the queue (its drop message names a
stopped pool). The overlay_tasks comments say so again, and
_poolWorkerSpawnHook is a test seam that makes worker creation fail.

~app joined the pool's workers before it interrupted the threads in
threads(). A pool task waiting, with no interruption point, on
something a keyed or startThread thread held got no help from it for
the 5 s join and then outlived the app. stopThreadPool() is split into
closeThreadPool() (close, interrupt, drop the queue) and
joinPoolWorkers(); ~app interrupts the first sweep of the thread map
between the two, as master interrupted everything before joining
anything.

Some waits and drops swallowed an interrupt, the pattern #825 removed
from thread_info, thread_feedback and library_lock: wait_for_threads'
joins and pool wait, the destructors of dropped tasks (compute_job's
on_error, pool_task_post's on_error and post, kernel_task's drop), the
pool's destruction of a refused or queued task, the joins in
stopThreadPool and ~app. Each now holds interruption off, so an
interrupt sent to the thread doing it stays pending.

app.h, THREAD_POOL.md and THREAD_POOL_API.md describe all three; the
overlay_tasks.h paragraph is reflowed, and its threaded mode is on the
background pool, not the compute pool.

Tests (app_test): AppPoolSpawnFailure.ComputeAsyncThrowsWhenNoWorkerCanBeStarted,
AppPoolSpawnFailure.ComputeAsyncQueuesTheJobWhenAWorkerIsRunning,
AppPoolTeardown.DestroyingTheAppInterruptsTheThreadMapBeforeJoiningThePool,
AppPoolTeardown.WaitKeepsAnInterruptSentToItsCallerPending,
AppPoolTeardown.DroppingATaskKeepsAnInterruptPendingOnTheDroppingThread;
(tf_overlay_tasks_test) TfOverlayTasksNoThreads.ThreadedTaskCarriesOnCooperativelyWhenNoWorkerCanStart.

* docs: pool comments the merged background pool made stale

- state_exec_bench: --bg-oversubscribe's rationale and skip message
  described tasks sharing a thread key, which no current build does;
  the skip now keeps runs comparable with builds before the
  persistent-worker pool, as docs/STATE_EXEC_BENCH.md says.
- THREAD_POOL_API.md's batch example used a thread_feedback with no app
  (it doesn't compile) and keyed feedback in an anonymous task; it now
  counts finished batches itself.
- tf_binding.h: overlay chunks run on the app's background pool, not
  the compute pool.

* app: ~app sweeps threads() again after joining the pool's workers

5acc14d moved the pool-worker join into sweep 0, after its snapshot of
the thread map, but still broke out of the loop on that snapshot being
empty. A thread a worker registers while ~app joins it (a keyed task the
worker took just before the pool closed, or a thread a pool task starts
once it is interrupted) was then never interrupted or joined, and ran on
into the freed app. Sweep 0 now goes on to the next sweep whenever it
joined workers, even with an empty snapshot.

Test: AppPoolTeardown.AThreadRegisteredWhileTheAppJoinsThePoolIsJoinedToo.

* app: compute_async's hand-back waits for the worker creations under way

compute_async threw only when its own worker creation failed and the
pool's thread count was zero at that moment. Another call's creation
still under way counted as a worker on its way, so when that one failed
too, after the look, the job stayed queued with no worker running or
starting and its caller was never told. A call that made no creation of
its own (a pool of 1, another call's creation already under way) never
looked at all.

The pool now counts the creations under way (_creatingWorkers: claimed by
poolKickLocked, until registered or given up). A call whose task, at its
kick, had no running worker and only creations under way waits (bounded)
for those to succeed or fail, then hands the task back if the pool has no
worker (poolHasNoWorkerLocked). With a worker running, nothing changes and
nothing waits.

Test: AppPoolSpawnFailure.ComputeAsyncThrowsWhenTheWorkerItReliedOnFailsLater
(both cases: a creation of its own that fails first, and none of its own).

* app, async_host, async_task: fail an async call at once when no worker can start

5acc14d brought back master's throw for compute_async only. The other
two background-pool users, the exec async host (state_exec async
functions) and launch_pool_task, still queued their task when no worker
could be started and the pool had none. The calling process stayed
parked, and ~app never returned: it first waits, with no bound, in
async_host::shutdown() for a kernel no worker would run, and only the
later closeThreadPool() would have dropped it.

- app::trySubmitPooled (PoolSubmit is now public): submitPooled, but a
  task no worker can be started for is handed back unrun (no_worker).
  compute_async now goes through it.
- async_host::submit drops a handed-back kernel with RuntimeError
  "<fn>: not run: no background worker could be started", ending the call.
- launch_pool_task posts on_error("not run: no background worker could be
  started") for a handed-back task.
- ~app closes a pool that has no worker (none could be created) before
  the async host's shutdown, so a kernel queued behind keyed threads whose
  end-of-task kick then failed is dropped instead of waited for.

Docs: app.h, async_task.h, THREAD_POOL.md, STATE_EXEC_EXCEPTIONS.md.

Tests (state_exec_async_calls_test):
AsyncCalls.ACallNoWorkerCanBeStartedForRaisesAndLeavesTheHost,
AsyncCalls.APoolTaskNoWorkerCanBeStartedForPostsOnErrorsValue,
AsyncCalls.DestroyingTheAppEndsACallQueuedOnAPoolWithNoWorker.

* app: startThreadPooled(wait=true) throws when its task's thread can't be created

On base, a keyed task whose thread couldn't be created made
startThreadPooled throw boost::thread_resource_error. Since the
persistent-worker pool, startKeyedPoolThread dropped the task silently
and startThreadPooled returned as if the task were registered under its
key, so `if (hasThread(k)) threads(k)->join();` went on at once (or
found the old, already-joined thread) and the caller read results that
were never computed. A keyed task started later from the queue was
dropped without a word as well.

startKeyedPoolThread now reports the failure. enqueuePoolTask throws
boost::thread_resource_error when it is the caller's own keyed task; a
keyed task started for another submission, by a worker, or by the
previous keyed thread's tail is logged as dropped. Keyed-thread creation
goes through the _poolWorkerSpawnHook test seam too.

Docs: app.h (wait=true), THREAD_POOL.md, THREAD_POOL_API.md.

Test: AppPoolSpawnFailure.AKeyedTaskWhoseThreadCantBeCreatedThrowsOrIsLogged.

* app: ~app holds interruption off until its last member is destroyed

5acc14d held interruption off for ~app's body only. An interrupt pending
on the thread destroying the app then outlived the body and was thrown at
the first interruption point in a member destructor (the state tree in
_data joining a handler thread, a user object in the data or in a slot
that joins one), out of a noexcept destructor: std::terminate. Before
that commit, the first interruptible join in the body happened to absorb
it whenever ~app had something to join.

The hold is now a member, _teardownHold (a std::optional of
disable_interruption), declared before every other member so that it is
destroyed after all of them, and engaged first thing in ~app. The
interrupt is still pending for the caller once the app is gone.

Test: AppPoolTeardown.AnInterruptPendingOnTheThreadDestroyingTheAppOutlivesIt.

* docs: closeThreadPool in the pool comments; when wait() throws an interrupt

The split of stopThreadPool into closeThreadPool and joinPoolWorkers left
two comments naming stopThreadPool as where ~app sets _poolStopping and
destroys the queue. THREAD_POOL.md said wait() "isn't interruptible
itself", but an interrupt already pending when it is called is thrown at
its first line (threads() is an interruption point); only one sent once
it has begun stays pending. Say so there and in app.h.

* app_test: bound the creation-reliance test's waits by the clock

Its hooks counted 1 ms sleeps, which take a timer tick (~15 ms) each on
Windows, so its two 300 ms windows took 4.7 s apiece. Wait on a
steady_clock deadline instead: the test now takes about 0.6 s.

* app: log a keyed task's drop before freeing its slot

When a keyed task that waited in the queue couldn't get a thread of its
own as its turn came, startKeyedPoolThread freed its slot (counting it
out of _activeWorkers and signalling an idle pool), ran the pool's kick,
and only then logged the drop. Anyone who saw the pool idle in that gap,
wait() or a poll of the counts, could read the log before the line was
in it: AppPoolSpawnFailure.AKeyedTaskWhoseThreadCantBeCreatedThrowsOrIsLogged
failed about 1 run in 100 on this box (1/100 with the AppPoolSpawnFailure
and AppPoolTeardown filter, 3/60 and 4/40 in earlier runs).

The drop is now logged first, still outside _threadPoolMutex and with
interruption held off, and the slot freed after it, so an idle pool
implies the drop is logged.

The test now also records, from a dataChanged slot on its log key, what
the pool's counts were while log() ran. On the old order they were 0
every time (logged after the slot was freed), so it fails deterministically
instead of 1 run in 100.

Test: AppPoolSpawnFailure.AKeyedTaskWhoseThreadCantBeCreatedThrowsOrIsLogged.

* app, async_host, async_task: drop a trySubmitPooled task left with no worker

ed4d3df made trySubmitPooled hand a task back when the worker creations
it relied on failed, but only for creations under way while it was
submitting. A task can also be queued with no worker running or being
created: keyed tasks, on threads of their own, hold every slot of a pool
that has never started a worker, so the submission asks for no worker.
When the last of them ended, its tail kick asked for one, and if that
creation failed, applyPoolKick's rollback only adjusted the counts. The
task stayed queued with nothing to run it until a later submission or
~app: an async call's process stayed parked, launch_pool_task never
posted, compute_async never called on_done or on_error, and a host bound
to the app that shuts down before ~app (a pycvc Exec's) waited in
shutdown() for its kernel. ~app's early close only covered the app's own
exec host.

Tasks queued through trySubmitPooled are now marked (ThreadPoolTask::
handBack, which fits in the struct's padding). Wherever a failed creation
leaves the pool with no worker, running or being created, and the pool
is not stopping (applyPoolKick's rollback, and a worker that couldn't be
recorded), takeUnstartableLocked takes the marked tasks out of the queue
and dropPoolTasks destroys them unrun once the mutex is released, on the
thread whose creation failed. A trySubmitPooled call still waiting for
the creations its own task relies on is counted in _handBackChecks;
while one is, nothing else drops marked tasks, so it still takes its own
task back and returns no_worker (compute_async throws, as before), and
it drops the rest when it is done. submitPooled tasks stay queued, as
documented.

The drop reason reaches the guards in other translation units
(async_host's kernel_task, async_task's pool_task_post, compute_job)
through app::poolDropReason(), a thread-local that the pool sets with a
scope while it destroys tasks unrun: kPoolNoWorker for these drops,
kPoolStopped for ~app's and for a submission refused once the pool has
stopped (also the answer where no drop is under way, so a guard
destroyed any other way says what it said before). The guards read it in
their destructors before calling out. A field or hook on the task record
would not reach them: the pool holds only a std::function, a callable's
address inside it is not stable across the moves and swaps the queue
does, and a second callable per task would cost an allocation on every
submission. The thread-local costs the normal path nothing; the only
additions there are one bool store per queued task, and a counter
update on the path that already waits for creations.

startKeyedPoolThread's failure handling moved out of its catch block,
since the kick there may now drop tasks whose destructors call out.

Docs: app.h (trySubmitPooled, poolDropReason, compute_async),
async_task.h (launch_pool_task).

Tests: AppPoolSpawnFailure.ComputeAsyncJobsLeftWithNoWorkerAreDroppedAndReported,
AsyncCalls.ACallLeftQueuedOnAPoolWithNoWorkerRaisesAndLeavesTheHost,
AsyncCalls.APoolTaskLeftQueuedOnAPoolWithNoWorkerPostsOnErrorsValue.
AsyncCalls.DestroyingTheAppEndsACallQueuedOnAPoolWithNoWorker asserted
the old state (the kernel still queued after the failed creation); it
now covers ~app's early close with the keyed thread still running when
~app begins, the case that close is still for.

* docs: when a pool submission waits, ~app's shutdown order, no-worker drops

compute_async's doc still said it never blocks the caller, and
launch_pool_task's that it returns immediately, but since f425247 a
trySubmitPooled submission made while the pool has no worker running
yet, only creations under way, waits in poolHasNoWorkerLocked (up to
5 s) for them to succeed or fail; trySubmitPooled's own doc didn't say
so either. That covers compute_async, an async call on the exec
scheduler's thread and launch_pool_task. Say so in app.h, async_task.h,
THREAD_POOL.md and STATE_EXEC_EXCEPTIONS.md 3.6.

THREAD_POOL_API.md's Shutdown item said ~app closes the pool first
"after only the async host". It now says that ~app shuts down its own
exec host first while the pool stays open, and closes the pool before
that instead when the pool has no worker; that it sweeps the thread map
again after joining the pool's workers, even when the first sweep found
it empty; and that ~app holds interruption off until its last member is
destroyed. A new item covers thread creation failures (the hand-back,
its wait, and the later no-worker drop), and the Notes list
trySubmitPooled with PoolSubmit, and poolDropReason.

The no-worker drop of the previous commit is in THREAD_POOL.md and
STATE_EXEC_EXCEPTIONS.md 3.6 as well, and a keyed task's drop being
logged before its slot is freed in THREAD_POOL.md and
THREAD_POOL_API.md.

* app: keep a compute_async job without on_error queued when no worker is left

c81166c dropped every task queued through trySubmitPooled once a failed
worker creation left the pool with no worker running or being created.
compute_async's four-argument form submits through it too, but its job has
no on_error, so the drop called nothing and its caller was never told. The
threaded tf overlay task is such a caller: its chunk's on_done posts the
reply the task's process waits on. When a keyed thread held the only slot
of a pool with no worker and the worker asked for as it ended couldn't be
created, the chunk was dropped and the task waited for good, even after a
later submission started a worker. Before c81166c the chunk stayed queued
and ran then.

trySubmitPooled's body is now submitPooledHandingBack(task, priority,
dropIfNoWorker), and the task flag ThreadPoolTask::handBack is renamed
dropIfNoWorker, since it now says only whether a queued task is dropped,
not whether the call hands it back. compute_async sets it only when
on_error is set. A four-argument job is still handed back, and
compute_async still throws, when no worker can be started for it while it
is submitted; once queued, it waits for a later submission to start a
worker, as a submitPooled task does. The on_error form is unchanged.

Test: AppPoolSpawnFailure.ComputeAsyncJobsLeftWithNoWorkerAreDroppedOrWaitForOne,
which replaces ...AreDroppedAndReported (that test asserted the silent
drop). On the unfixed build it fails: the four-argument job's captures
were released, one task was pending instead of two, and the job never ran
once a worker started.

* tf: carry an overlay task on cooperatively when its chunk is left with no worker

A threaded overlay task launches each chunk with compute_async and parks
on the reply that the chunk's on_done posts. Suppose the pool is left with
no worker after the chunk is queued: a keyed thread held the only slot of
a pool with none, and the worker asked for as it ended couldn't be
created. With the four-argument form the chunk then waits in the queue
until a later submission starts a worker (as before c81166c, and again
since the previous commit), or, under c81166c, it was dropped without a
reply. Either way the task stopped advancing, though overlay_tasks.h says
a task carries on cooperatively when no thread can be started.

launch_chunk now uses compute_async's on_error form. When the pool drops
the chunk with app::kPoolNoWorker, on_error marks the chunk's reply
no_worker and posts #f to it, unless the task has let go of the chunk.
The next (tf-overlay-step) sees the mark and switches the task to
cooperative slices, as it does when compute_async throws. A chunk dropped
as ~app stops the pool, or interrupted, still posts nothing, as the
four-argument form's did.

Test: TfOverlayTasksNoThreads.AThreadedTaskWhoseChunkIsLeftWithNoWorkerCarriesOnCooperatively,
which holds the slot with a keyed task, queues a chunk behind it, fails
the worker creation as the keyed task ends, and waits for the task with
no later submission. It fails both on the build before this series
(wait_overlays timed out: the chunk was dropped without a reply) and with
the previous commit alone (timed out with the chunk still queued); its
rescue then starts a worker so the test ends.

* app: a trySubmitPooled call that starts a queued keyed task decides about its own task

A trySubmitPooled call that finds a keyed task at the head of the queue,
with the slot free, starts that task on the calling thread. That state
arises once the pool drops anonymous tasks queued ahead of keyed ones for
want of a worker (c81166c), or when a worker creation fails after a
queued keyed task's own start failed. If the keyed task's thread then
couldn't be created, nor the worker asked for as it freed its slot, that
failed creation dropped the call's own task inside the call:
_handBackChecks counted only calls relying on creations already under
way, and this one relied on none. compute_async returned as though its
job were queued. The on_error form's on_error ran inside the call instead
of the documented boost::thread_resource_error, and the four-argument
form's job was lost without a word (since the previous commit, it is left
queued instead, still without the throw).

Such a call is now counted in _handBackChecks too while it starts the
keyed task. When a failed creation leaves the pool with no worker while a
check is pending, takeUnstartableLocked sets _poolDropOwed rather than
only returning. Having started the keyed task, the call hands its own
task back if a drop is owed and the pool still has no worker running or
being created; and the last deciding call to finish does the owed drop of
the other dropIfNoWorker tasks (a call relying on creations decides as
before, and does that drop too). A keyed thread that started leaves the
call's task queued behind it, as any task queued behind a keyed thread
holding the slot is. Only a call that starts a keyed task while no worker
is running is counted, so a submission with a worker running takes no
second lock and pays only a branch.

Test: AppPoolSpawnFailure.ComputeAsyncThrowsWhenAQueuedKeyedTaskItStartsLeavesNoWorker
(the reviewer's scenario: a job dropped ahead of two keyed tasks, then
one call in each form, each starting a keyed task whose thread can't be
created). On the unfixed build neither call threw, and the on_error
form's job got "not run: no background worker could be started" inside
its own call.

* app_test: cover the drop a failed creation leaves to a waiting trySubmitPooled call

While a trySubmitPooled call waits on a worker creation that its own task
relies on, a failed creation that leaves the pool with no worker doesn't
drop anything itself: it leaves the drop to that call (_poolDropOwed),
which hands its own task back first. Nothing tested that half. Removing
the call's takeUnstartableLocked left every test passing, though a job
queued earlier then waited for a worker nothing would start.

AppPoolSpawnFailure.AJobLeftWithNoWorkerWhileACallWaitsOnTheCreationIsDroppedByThatCall
queues job A behind a keyed task holding the only slot, holds the creation
asked for as the keyed task ends until call B waits on it
(probe_app::handBackChecks, new), and then fails it. A's on_error gets
"not run: no background worker could be started" on B's thread, B's
compute_async throws, and nothing is left queued. With the call's drop
removed, A is never reported and the test fails; its rescue then starts a
worker so that it ends.

* docs: when and where the pool drops a task left with no worker

The docs for c81166c's no-worker drop said a queued trySubmitPooled task
is dropped when the worker asked for as the LAST keyed thread ends can't
be created, on the thread whose creation failed. The code drops it once
any worker creation fails and leaves the pool with no worker running or
being created, also while other keyed threads still hold their slots.
Waiting for the last of them would leave the task stuck behind a
long-lived keyed thread, the state c81166c set out to end, so the docs
now give the code's rule.

The drop does not always run on the thread whose creation failed. When a
trySubmitPooled call is still deciding about its own task (waiting on
that creation, or, since the commit before last, starting a keyed task
queued ahead of it), the failed creation leaves the drop to that call. It
runs there before the call returns, so another submitter's report of the
drop (an async call's RuntimeError, launch_pool_task's post,
compute_async's on_error) can run inside a compute_async call, an async
call made on the scheduler's thread or launch_pool_task. The docs say so,
and they cover the two changes earlier in this series: compute_async's
form without on_error has its job wait for a worker rather than be
dropped, and a call that starts a queued keyed task hands its own task
back when that leaves the pool with no worker.

Updated: app.h (trySubmitPooled, compute_async's on_error form),
async_task.h (launch_pool_task), THREAD_POOL.md (thread creation
failures), THREAD_POOL_API.md (item 6, trySubmitPooled in Notes),
STATE_EXEC_EXCEPTIONS.md 3.6, the change history in app.cpp, and the
comments in the drop guards (compute_job, pool_task_post, kernel_task)
and in one state_exec_async_calls_test comment.

* app: a deciding pool submission that throws leaves no hand-back check raised

A trySubmitPooled call that decides what becomes of its own task raises _handBackChecks before it
kicks the pool and starts a keyed task, and lowers it only once it has decided. If applyPoolKick or
startKeyedPoolThread threw in between (out of memory making a thread's state), the count stayed
raised, and no failed worker creation would drop a task for want of a worker again for that app.
The call now lowers it on the way out.

Also corrects compute_async's comment, which still said its caller returns immediately: while the
pool has no worker yet, it waits for the worker creations under way, as app.h says.

* style: clang-format 18 on the lines this branch changes

The required clang-format (changed lines) check runs only on PRs against master, so it first ran
when this PR was retargeted from #834's branch. Formatting only.
transfix added a commit that referenced this pull request Oct 28, 2026
The test ran one rt.drain() after setting each tick program and then asserted
the program had finished. A drain pumps the app scheduler for a bounded slice
(0.1 s, its second half on the thread's CPU clock), and a program that needs
more carries on in the next frame's drain, by design. In package-linux's
Debug lanes, which build with coverage instrumentation, the deep-graph program
(a 64-level mix/gain graph, two stream-opens) can need more than one
slice on a loaded runner: "the deep-graph program ran" failed on all 3
attempts in #834's run 40494020761 (job 122154778441) and on 1 attempt in
master 83b6020's debug-grpc job; in the runs checked, only in Debug lanes.

The test now drains until the program has set its key, for 10 s at most, and
prints how many drains that took when it was more than one.
@transfix
transfix deleted the feat/state-exec-bench branch October 29, 2026 20:53
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