Skip to content

state_exec: threaded execution Stage 0 (process-global hazards) - #1014

Merged
transfix merged 108 commits into
masterfrom
perf/threaded-s0
Nov 7, 2026
Merged

transfix merged 108 commits into
masterfrom
perf/threaded-s0

Conversation

@transfix

@transfix transfix commented Nov 3, 2026 •

Copy link
Copy Markdown
Owner

Threaded execution, Stage 0 (docs/STATE_EXEC_THREADED.md 7; plan threaded-impl/S0.md in the
workstream): fixes for the process-global hazards a second thread would hit today. No thread is
added. With state_exec.threads unset, behaviour is today's, apart from td 5 items 1-4 and the
decisions S0-Q1..Q6 approved in the plan.

Status: reviews done, S0.13 complete, and the Windows A/B recorded (below). The branch has master
2172222 merged in, so the A/B's base is that commit rather than #961's merge. By bench.md's rule,
step counts are unchanged and no timing point is worse. Every timing gate is INCONCLUSIVE on noise,
as in every earlier window on this box.

What changes

  • S0.0 interfaces:
    • control_cmd kill/pause/resume/signal with done;
    • the 5-argument register_watch_handler;
    • copy_mode and is_builtin_class_dict;
    • the pinned link walks, removeChild, and root_pins/pinned_root();
    • async_call's claim;
    • cvc::pin_vector.
  • S0.1 The 17 built-in exception class dicts are read-only to set-attr, del-attr and
    set_field. Derived classes stay mutable.
  • S0.2 state-data-set stores an isolating copy. It refuses closures, natives, generators,
    futures, lock forms, lock waits and user-class instances at any depth, and leaves the node
    unchanged. Built-in exception instances are stored with their class shared. pycvc relinks them
    the same way. The writer is charged for the copy.
  • S0.3/S0.4 Walks through links are pinned, and so is a chroot (root_pins). Writes and sliced
    jobs hold chain pins. state-delete removes exactly one node, through removeChild, and so do
    pycvc's tree accessors. The subtree cursor drops its levels deepest first.
  • S0.5 Each watch keeps its own root. A chrooted state-watch no longer moves the scheduler's
    watch root, settings or rate. Polling is gated per root, and watch_root() and watch_polls() are
    added.
  • S0.6 The stop flags are atomic.
  • S0.7 post_control kills, pauses, resumes and signals on both schedulers:
    • each command runs a done callback, in FIFO order;
    • a post ends a sync idle wait, and the CLI loop steps for pending controls;
    • a kill whose cancel throws still kills, then rethrows;
    • posts that arrive during destruction are refused in rounds, without recursion.
  • S0.8 The coordinator drives its scheduler through post_control. Its submit, migrate, ingest
    and admin paths are posted, and migrate() returns "requested". A failed migration resumes its
    process. Posted entries do nothing once the coordinator is gone.
  • S0.9 A future is finished once, and every waiter is woken, including when a finish throws.
    A cancelled call settles with ": cancelled: the process that made the call ended" on every
    await path.
  • S0.10 print writes whole lines.
  • S0.11 HZ-8 is covered under pycvc and Ariadne.
  • S0.12 New bench scenarios and points: mt.multi_exec, the chroot sizes, the watch_poll
    points, state-delete's cost and mt.pycvc_threads.
  • S0.13 Stage 0's binaries join the sanitizer jobs, with a required line for each HZ case,
    and mt.multi_exec runs at t=8 under TSan. After a baseline run on the 16 other state_exec
    binaries, they join the sanitizer list too. Its findings are fixed here:
    • evaluation_stats::last_kind raced. It is now a relaxed atomic. Under TSan, the race's
      reports slowed two suites past an hour.
    • Seven suites left cycles uncollected at exit. Each now collects in a gtest environment.
    • deep_data's worker threads collect before they end, since the cycle registry is per thread.
  • S0.14 Updated docs:
    • the developer guide;
    • the exceptions doc;
    • the lifetime and atomicity roadmap;
    • a roadmap item for rebuilding user-class instances by class name.

Found and fixed along the way (pre-existing):

  • pycvc's state_observer used freed memory.
  • The recursive and coroutine evaluators held class methods where the cycle collector could not
    see them (detail::evaluator_method). The coroutine evaluator's inherited finalize now gets its
    arguments, and isinstance works on its instances.
  • The codec's restore did not track captured scopes.
  • master's tests failed to build under GCC 15, which no longer includes <algorithm>
    transitively.

Tests and reviews

  • Tests: HZ-1..HZ-14 were written from the plan by a separate test writer. Each implementer
    added unit tests, and every review fix came with a test that fails without it.
  • Reviews:
    • R0-mid, with two lenses;
    • R0a, for memory and concurrency;
    • R0b, for semantics and compatibility/docs;
    • four skeptic rounds over the review fixes. The fourth was clean.
  • Windows (MSVC Release):
    • At dbba7c4, every suite passed (46 entries): hazards 12, lifetime stress 16, state 181,
      intrinsics 177, exceptions 25, data_steps 54, codec 73, scheduler 193, async 102,
      integration 104, coordinator 74, async_calls 68, locks 215, priority 40, Ariadne runtime 262
      and host 46, the other state_exec suites, 11 pycvc scripts and state_exec_bench_gates.
    • AsyncCalls.AS24_FuturesInFlightAreEachCharged missed its wall-clock bound once under load,
      then passed 20 times out of 20 alone. It is a known timing flake.
  • CI at dbba7c4: 24 of 27 checks pass, including both sanitizer legs with the 16 added
    binaries. The three macOS package jobs are still queued.
    The wasm publish dry run passed on the master merge.

Windows A/B (S0.md section 6)

  • Setup: base master 2172222, candidate dbba7c4, MSVC Release, --pin auto, 5 reps.
  • Window: 2026-11-07, 00:03-00:59 local, made quiet by hand.
  • Runs:
    • run 1 interleaved whole runs (base, candidate, candidate, base);
    • run 2 repeated the 3%-gated families in ABBA order per scenario.
Gate Result
steps_total unchanged (eval, sched.single, flood.small sync, native, data, limits) pass: 187 points identical
sched.single, flood, limits within 3% inconclusive (noise median 31% and 61%); none worse; geomean -8.3% and -6.4%
msg, async unchanged inconclusive; none worse; the 8 points under 3% noise are within 3%; geomean -3.5% and +2.3%
native.state_get/set (chroot=0), state_atomic, msg_send, watch_poll (chroot=0) within 3% inconclusive; none worse; 9 points judged, all within 3%; state ops -2.1% to +2.7% in run 2 (noise median 6.5%)
mt.multi_exec t=8 of_ceiling >= 0.9 medians 1.03 (fib) and 1.04 (exceptions), inconclusive at the 10% noise bound

Recorded:

  • native.state_delete: at nodes=10000, 1420 ms went to 20.7 ms; at nodes=100, the change was
    -43% to -47% (S0.4).
  • chroot=1 against chroot=0 in the candidate, pooled over runs in reversed order:
    • state_get and state_set: -12% to +11% at 7-38% noise, so no clear cost.
    • sched.watch_poll with writes elsewhere: w=1000 went from 420-492 ms to 6.9-7.4 ms, and
      w=100 from 46-64 ms to 6.7-7.3 ms (S0.5's per-root gating).
  • mt.independent (ast=private), programs per second at t = 12, 16 and 20:
    • fib: 708, 785 and 778 (89 at t=1);
    • exceptions: 208, 215 and 215 (37 at t=1).

Follow-ups, not Stage 0's (recorded in the workstream)

  • A process restored mid-loop loses updates to outer variables. decode_frame and
    decode_evaluator_state decode environments with separate readers, so the restored frames do
    not share scopes. This affects migration.
  • Bus addressing in handle_migrate and handle_control.
  • Ariadne's uri_state/stream release order.
  • spawn_child's re-chroot.
  • equal_walk's seen_ is keyed by raw address pairs.
  • election_start_time_ is written and read on different threads.
  • The StateObjectLocking timing flake.
  • pycvc's findDescendantShared(path) and sharedChild(path) leak a pin per call.
  • process_ended throwing after the status is set.
  • kill_owner iterates the process table while kills reap.
  • STATE_API.md does not list the new state APIs.

The declarations threaded execution's Stage 0 shares (docs/STATE_EXEC_THREADED.md 7), with stubs,
so its commits can be written at once:

- control_cmd gains kill, pause, resume and signal, a signal name and an optional done
  callback (called once, on the scheduler's thread, with the direct call's result, or false
  from the destructor); has_pending_control() on both schedulers.
- register_watch_handler gains a 5-argument form with the watch's own root; the 4-argument
  pure virtual stays, and both schedulers implement it as the 5-argument one with a null
  root. watch_handler_entry::root records it.
- make_copy_job(v, copy_mode, who): copy_mode::isolate is state-data-set's refusing copy; the
  defaults keep every caller as it is.
- is_builtin_class_dict(); the built-in classes' comment names all 17.
- state::findThroughLinksShared, childThroughLinksShared and removeChild.
- intrinsics_context::root_pins and pinned_root().
- async_call's closed_ claim.
- state_exec_hazards_test, an empty binary for the HZ cases, discovered by CTest and run by
  the sanitizer jobs.
exec_coordinator's bus-thread paths no longer touch the scheduler on the bus's thread
(docs/STATE_EXEC_THREADED.md B17, 4.12):

- handle_control posts pause, resume, kill, signal and set_priority, fire and forget.
- admin_pause/resume/kill post locally and return true once posted, as admin_set_priority does.
- handle_submit posts a query entry that runs the submission and sends the response; a script
  execute refuses is answered as a rejected submission (an entry must not throw).
- migrate() is asynchronous: the no-scheduler and self checks stay synchronous, then one posted
  entry pauses, serializes, sends and kills, and migrate() returns {true, -1, target, ""},
  "requested". A failure there is counted in migrations_failed. The migrate ingest runs in a
  posted entry too.
- policy_ is read as a snapshot under remote_mu_.
- ps_all, cluster_stats, emit_heartbeat, emit_status_broadcast and the local submit() are
  documented as scheduler-thread calls, not posted.

Posted entries hold a weak_ptr to a token the coordinator owns and resets in its destructor, and
do nothing once it is gone; none captures a bare this.

Tests: the coordinator and migration tests that checked an outcome at once now take a step first;
MigrateNonexistentProcess and MigrateNonexistentProcessFails expect "requested" and read the
failure from the stats. MultiClusterACLTest's CrossNodeAdminKillEnforcedByLeader and
CrossNodePauseResume take a step too. New: SubmitViaMessageThatDoesNotParseIsRejected and
PostedEntriesOutliveTheCoordinator.
The tree's half of td 4.8 (S0.3), for the pinned lookups of S0.4:

- findThroughLinksShared and childThroughLinksShared hold every hop while they walk (a link
  hop's resolveLink() reads the link node's fullName(), which walks the hops above it), and on
  a link hop the resolution's target chain. `pins` gets all of them, from the start's child down
  to the result; without it they are held on the walk's own stack (16 inline). The start is the
  caller's and is not pinned, except as the result of an empty path. The raw findThroughLinks
  and childThroughLinks are their .get().
- findDescendantShared and sharedChild gain a start-pinned form for a caller that already holds
  the start (an intrinsics context's root_pins, a watch's root): it takes the caller's hold as
  `self`, returns it for an empty path, and takes no reference on the start, so a lookup leaves
  the root's count alone. The existing forms are that form with shared_from_this().
- removeChild unlinks one child under the parent's mutex, stamps the parent, then emits
  childChanged once; never `expiring`. The subtree goes with its last pin, on that thread.

A node no shared_ptr owns (a host's own root) is held by a non-owning alias rather than throwing
bad_weak_ptr.
The 17 built-in class dicts are one per OS process and shared by every environment, so a
set-attr on ValueError.__cls_dict__ changed init for every program in the process
(docs/STATE_EXEC_THREADED.md B7, 5 item 1). They are now read-only:

- set-attr and del-attr raise TypeError "set-attr: built-in class is read-only: <Name>" (and
  "del-attr: ..."). set-attr refuses before track_mutated, so a built-in dict never enters a
  cycle registry.
- set_field raises TypeError "built-in class is read-only: <Name>", which covers the built-in
  init applied to a class dict.
- is_builtin_class_dict is a binary search over the 17 sorted addresses; the dicts stay
  separate allocations. Every check sits behind a shape test (2-3 entries, __name__ first)
  that an instance fails on its first key, so creating an exception and set-attr on an
  instance do no search.
- The evaluators' annotate leaves a raised built-in class dict as it is, rather than turn the
  raise into a TypeError. (The coroutine evaluator has no try or raise.)

User classes, including those derived from the built-ins, are unaffected.
make_copy_job's copy_mode::isolate is the copy state-data-set will store
(docs/STATE_EXEC_THREADED.md 4.3, 5 item 2; S0-Q4). At any depth it refuses a closure, a
native function, a generator, a future (an async call's future or its handle), the lock form,
a lock wait's handle, or an instance of a user class, with std::runtime_error
"<who>: cannot store a <kind>", plus " (nested in a list)" or " (nested in a dict)" when the
value is an element. A user class's methods hold the defining program's live environment, so
its instances cannot be isolated; a built-in exception's instance is copied with its class dict
shared, which is safe now that the built-in classes are read-only. Other data_objects are shared
under their read-only contract, as before.

The refusal is thrown from the slice that reaches the value, so a refused copy has no result and
the job's `then` never runs. A dict is checked once, on its first visit, so a shared one still
costs its physical size.

The copy's deadline names its caller (`who`) instead of always state-data-get. Share mode is
otherwise unchanged. The DataJob cases cover each kind at the root, in a list, in a dict and
deep, a refusal in a later slice, what is shared, sharing and cycles, share mode, and the
deadline's label.
print wrote each argument, separator and newline to std::cout separately, so lines printed
from programs on several threads could interleave (docs/STATE_EXEC_THREADED.md 4.11, guarantee
9). It now makes the whole line first, outside any lock (a line with a list or dict in it
finishes in its concat job's `then`, as before), then writes it with its newline in one
std::cout.write under a function-local mutex. The mutex is held for that write only, never
across a data job or DSL code. The text and the charging are unchanged.
td B17, HZ-14 (S0.md section 2, S0.6). Both schedulers' running_ and stop_requested_ become
std::atomic<bool>, asserted lock-free:

- A run clears the stop flag, then publishes itself running with a release store, so a stop()
  made once is_running() (an acquire load) reads true is no longer lost to the run's own reset.
- The loop reads the flag relaxed: no data rides on it. stop() stores it with release.
- Every exit of a run stores running_ false with release, a step's exception included (an
  on_complete that throws used to leave is_running() true for good).
- The sync scheduler makes its idle wakeup at construction, no longer lazily, and stop()
  notifies it, so a stop from another thread ends an idle run() at once. The 10 ms slice stays
  as a fallback. The async run loop never waits, so its stop() notifies nothing.

stop() is no longer async-signal-safe (the notify takes a lock on POSIX), and a stop() with no
run active is still discarded by the next run; both are documented.

Test: SchedulerRunFlags.ARunEndedByAnExceptionIsNoLongerRunning.
The built-in exception classes' cases of docs/STATE_EXEC_THREADED.md 8.1, on all four engines:

- HZ-1: set-attr and del-attr on a built-in class dict, reached by name, through a caught
  exception's __class__ and through __super__, and init called on the class dict, each raise
  TypeError "... built-in class is read-only: <Name>"; a later instance is made as before. From
  C++, set_field on each of the 17 classes throws and leaves the dict as it was. pycvc has the
  same through Exec.run.
- HZ-1c: raising a class dict stays the TypeError it is today, and leaves the dict unchanged.
- HZ-2: a class derived from ValueError keeps its own init and its set-attr and del-attr, and is
  still caught as a ValueError.

The C++ cases put the 17 dicts back after each engine's run, and the pycvc case puts init back,
so a build where they are writable fails only these cases.
The state tree's cases of docs/STATE_EXEC_THREADED.md 8.1:

- HZ-5 (StateTreeIntrinsicsTest): state-delete unlinks its one node. An expired sibling and an
  expired node elsewhere stay until state-sweep-expired, which then removes both; the parent's
  childChanged fires once and expiring never. Chrooted, the same, and state-delete "" leaves the
  chroot unexpired, so a later sweep above it no longer deletes the document.
- HZ-6 (Hazards): three threads, each with its own scheduler on one tree, delete and re-create
  p.x, read its siblings, the parent's children and p.x.y, and write p.x.y. Every read is a value
  or nil and the siblings never change; the sanitizer legs require it clean.
- HZ-6b (Hazards): a state-set-tree sliced a node a step, whose target's ancestor another process
  deletes between two slices, finishes with nothing freed under it.

state_exec_hazards_test gets a world per program (an async_scheduler and an intrinsics context
on the shared tree) and a runner that starts several on threads at once. The threaded case runs
fewer iterations when CVC_LOCKS_SANITIZER is set.
The built-in exception class dicts are read-only since S0.1, so state-data-get's copy shares
them as state-data-set's does: an exception read back from the tree is a built-in instance
again, and storing it a second time is not refused as an object instance (S0-Q4 stores
built-in instances). The refusal says "an object instance". pycvc's async-argument copy names
itself in its deadline message, and builtin_class.h is listed with the library's headers.
…cost

Threaded execution's Stage 0 scenarios (docs/STATE_EXEC_THREADED.md 6.3; its plan's S0.12):

- mt.multi_exec (async, spawns_threads): t threads (1, 2, 4, 8), each pumping a world("async",
  app) of its own with a background-pool host, every world over one app tree (its watch root),
  pumped as pycvc's Exec::run pumps (lock.cross_thread's loop), each running fib 18 or 2000
  caught raises `runs` (5) times. extra.speedup is over one such thread, and extra.of_ceiling over
  mt.independent's ast=private speedup, both measured in the same rep, for Stage 0's gate (at
  least 0.9 at t=8). prog=tree runs Stage 0's code from every thread for the sanitizer jobs
  (HZ-10), recorded and never gated: chrooted state-get, state-set and state-data-set, a
  state-watch, and pause, resume, signal, set_priority, query and kill posted to the next
  thread's scheduler. Smoke: t 1 and 2, one run.
- mt.independent gains t = 12, 16, 20. Its worker is shared with mt.multi_exec's ceiling, and
  each thread collects the reference cycles its runs left before it ends (the collector is per
  thread), so LeakSanitizer sees them freed. A prog other than fib or exceptions is skipped.
- native.state_get and native.state_set gain chroot 0/1 (lock.uncontended's apply_chroot at
  bench.doc); sched.watch_poll gains chroot 0/1 (the watchers in a context of their own,
  chrooted) and writes none/elsewhere (the loop writes under the app root outside the watched
  paths and the chroot), so a watch root of its own can be seen keeping those writes from
  polling. The runner's IMPLICIT_DEFAULTS gain chroot=0 and writes=none, so the base binary's
  points match; extra.of_ceiling is higher-is-better.
- native.state_delete no longer describes an expiry sweep: state-delete unlinks one node.
- native.state_data_set (n): a list stored with state-data-set, extra.data_nodes_per_call
  recording the isolating copy.
- The bench replaces the nothrow operator new and operator delete (plain and sized) next to its
  operator new, all over malloc and free, so it runs under ASan without an alloc-dealloc
  mismatch.
- tools/bench/mt_pycvc_threads.py: mt.pycvc_threads, t Python threads with a pycvc.Exec each,
  writing the bench's JSON records (recorded, not gated).

docs/STATE_EXEC_BENCH.md describes all of it, and test_state_exec_bench.py tests the runner's new
defaults, the chroot pairing, the mt.multi_exec gate and mt_pycvc_threads.py's records.
Threaded execution's Stage 0 (docs/STATE_EXEC_THREADED.md 7, 8.1; its plan's S0.13, first
commit) under TSan and under ASan with UBSan:

- SAN_CXX_TESTS gains Stage 0's own binaries: state_lifetime_stress_test,
  state_exec_intrinsics_test, state_exec_exceptions_test, state_exec_async_calls_test and
  state_exec_data_steps_test (state_exec_hazards_test came with the interfaces).
- SAN_PY_TESTS gains test_pycvc_state.py (state_remove).
- SAN_BENCH, a new list of state_exec_bench runs, one a line, which run.sh runs with --reps 1
  --warmup 0 --timeout 900 and a JSON file in san-logs (the bench takes no --gtest_filter):
  mt.multi_exec at t=8 with one run of each program (HZ-10). The build line builds
  state_exec_bench.
- `required`, in both legs: every HZ case of the plan's section 4 whose test it names, the pycvc
  HZ cases' "ok:" lines, and mt.multi_exec's three points (t=8 prog=fib, exceptions and tree,
  runs=1): a bench run whose points were all skipped exits 0.
- The job comment names Stage 0.
state-data-set's isolating copy (docs/STATE_EXEC_THREADED.md 8.1, 4.3):

- HZ-3: a list changed after it was stored, at the top or nested, no longer changes what
  state-data-get returns: on the intrinsic (StateTreeIntrinsicsTest), in a program at
  data.step_nodes 0 and 1 (Hazards), and through pycvc's Exec.
- HZ-3b (Hazards): storing 1000 elements adds at least 1000 data nodes to the writer, at least 900
  data steps at step_nodes 1 and none at 0, measured against the same program storing nothing; a
  process stepped beside it is charged nothing.
- HZ-4 (StateTreeIntrinsicsTest, and its pycvc twin): a closure, a native function, a generator, a
  future (and its async_call handle), a lock form, a lock wait and a user-class instance are
  refused at the root, in a list and in a dict, with the exact text ("cannot store a closure",
  ..., "cannot store an object instance", " (nested in a list)"/" (nested in a dict)" for the
  container they are in), and the node keeps its value. A data_object and a built-in exception's
  class come back shared, and an exception read back stores again.

Each process the hazards worlds run now gets a scope of its own over the world's environment, so
two programs' top-level variables don't meet.
stop() from another thread (docs/STATE_EXEC_THREADED.md 8.1, 4.12): it ends a run() that is
stepping a busy loop on either scheduler (SchedulerStop, AsyncSchedulerStop on sync_run_steps),
and the sync run() of a lone (sleep 5), which returns within 0.2 s of the stop with the sleeper
still waiting. The process is left as it was and steps on in the next run, and check_tables()
holds; a lost stop would end the run at the process's 60 s max_time instead and fail the case.
pycvc has the same from a second Python thread (stop() is the one raw scheduler call S0-Q5 allows
there). The proof is the TSan leg: the flags are plain bools until S0.6.
A watch's own root (docs/STATE_EXEC_THREADED.md 8.1, 4.8, B13), as a typed suite over both
schedulers (HazardsWatchRoot):

- HZ-7: the host's root says max_depth 3 and a rate of 1000, the document's state_exec subtree 100
  and 0. After the document's chrooted state-watch the host's still apply: an async submission
  deeper than 3 is refused, the rate is 1000 and published under the host's root, the sync
  scheduler's load_settings() publishes nothing under the document, and a write to doc.x fires
  the handler.
- HZ-7b: documents A and B each watch "x"; a write to B.x fires only B's handler, and A.x only A's.
- HZ-7c: an unchrooted state-watch on a scheduler with no watch root still makes it read and
  publish its settings from that root (S0.md section 0, item 20). Per-root gating: writes
  elsewhere in the app tree don't poll a chrooted watch, a write under the chroot does.

The gating half reads a poll counter neither scheduler has yet. It is written against the name
proposed for S0.5, watch_polls() on both schedulers (the polls that got past the gate and read
the watched nodes), found through a requires-expression, so the file builds without it and the
case fails until it exists.
A future finished once, every waiter woken (docs/STATE_EXEC_THREADED.md 8.1, 4.9):

- AsyncCalls.HZ13_AFutureAwaitedTwiceIsChargedOnce, on both schedulers: a future awaited twice
  gives both awaits its one result and is charged one call (a process rate of 0 leaves a call its
  one-step minimum); the same for a failing call, whose error both awaits raise; and for a future
  a fork child awaits beside its parent, both get the value and the child is charged nothing.
- HZ13_AnOutcomeTakenBeforeTheDrainIsNotChargedAgain: an await in a generator's body can't park,
  so it takes the outcome before the scheduler drains the call's completion; the drain charges
  nothing more.
- HZ13_ACancelledCallWakesEveryWaiter: killing the process that made a call wakes a fork child
  awaiting the same future, within 10 s (today it waits for ever).
- AriadneHazards.HZ13_InitLaneAwaitsAnAppHostFuture: an init script on the init lane's private
  scheduler awaits a host async verb's future, whose call belongs to the app's scheduler, twice,
  and gets its value (S0-Q6: no foreign-future check in Stage 0).
The coordinator's control from a bus thread (docs/STATE_EXEC_THREADED.md 8.1, 4.12; S0.md S0.8):
Priority.HZ09_BusThreadControlAppliesBetweenSteps. A pump thread steps the scheduler while a bus
thread sends, in order: pause P, a query, (once Q has stepped 200 more times) a query, resume P, a
query, set P's priority to 7, SIGKILL to Q, kill P, and a last query. The queries see P paused,
then ready, never during a step (current_pid() is -1); P takes no step while paused; at the end P
was killed by the user, Q by SIGKILL, P's priority is 7, and check_tables() holds. On a build
where the bus thread pauses and kills directly, a kill can land inside a step and be lost, and the
tables break; the TSan leg reports the race itself.
print writes whole lines (docs/STATE_EXEC_THREADED.md 8.1, 4.11): Hazards.HZ12_PrintWritesWholeLines.
Eight threads, each with its own scheduler, print 1000 lines each with a 512-character payload,
every other line with a list argument (the concat job's path), half the threads slicing deep data
a node a step. The captured output is exactly 8000 lines, each whole and each thread's in order.
HZ-8 (docs/STATE_EXEC_THREADED.md 8.1, 5 item 5), on the hosts; LocksReview.ForkInAStepReturnsZeroInTheChild
and Locks.LW06_Fork cover the schedulers:

- pycvc test_hz08_fork_in_exec_run: a (fork) in a program Exec.run runs returns the child's pid,
  which run() returns; the child goes on to park on msg-recv, with the running process as its
  parent, and kill_owner("") reaps it (an Exec's processes have no owner).
- AriadneHazards.HZ08_ForkedChildKeepsOwnerAndTeardownReapsIt: an action forks and both park; both
  have the Runtime's owner, read back from snapshots. Tearing the Runtime down kills both
  (kill_owner) and reaps the action's children, so the forked child leaves the table; the action's
  own process stays in it, killed with reason owner_reaped. Whether teardown should reap that one
  too is left to Stage 1's teardown work.

The comments at LW06_Fork and LW10_GeneratorBodies (state_exec_locks_test.cpp) and at
test_lw06_fork_from_exec said a DSL (fork)'s child forks again or is unusable; since L1 (td B28)
its (fork) returns 0 and it goes on, and they now say so.
Two pycvc Execs on one app, run on two Python threads at once (docs/STATE_EXEC_THREADED.md 8.1;
Linux TSan): test_hz11_two_execs_exceptions_and_data. A changes a list, state-data-sets it,
raises and catches ValueError and tries to set-attr ValueError's class, which is refused; B reads
the stored list (always two long) and raises KeyError, caught as an Exception. Each counts its
good rounds (3000, or 300 under CVC_LOCKS_SANITIZER), and both get them all; ValueError's class
has no "x" after. _in_thread is copied from test_pycvc_state_exec_locks.py.
The Stage 0 interface commit stored the workflow with LF endings, so the file read as rewritten against master. It is stored with CRLF again, as on master.
…delete

td 4.8 and 5 item 3 (S0.4): no node a state intrinsic uses can be freed under it by another
thread's delete.

- The context's root_pins hold its root and every ancestor. apply_chroot pins the chroot node
  and the chain down to it once; pinned_root() re-pins, walking parent() once, when root_pins is
  empty or its back() is not `root` (a host that assigns `root` directly). A root no shared_ptr
  owns is held by a non-owning alias, the host keeping it alive. make_spawn_context copies them.
- state-get, state-exists and state-data-get read through findThroughLinksShared with a leaf
  pin; state-children, state-set, state-data-set, state-cas, state-swap and state-incr hold the
  chain below the root to the end of the call. Chain pins sit on one stack per thread, popped
  when the call ends, so a call allocates nothing once the stack has grown.
- A compound state-set's job holds the root chain and walks and writes in its `then`, as it
  wrote there before. state-json holds its node; the state-from-json and state-set-tree jobs
  hold the target's chain, from the tree's root and through a writable link, for their whole
  life, and state-set-tree's frames hold their nodes.
- state-delete normalizes its path (an empty one does nothing: the context's root is never
  deleted, where a chroot used to be left expired), finds the parent physically and calls
  removeChild: one node goes, and other expired nodes stay until a sweep. state-set-tree's
  stale children go the same way, a unit each.
- state-expire*, state-sweep-expired (chain pins: the sweep emits up the chain), msg-send's node
  (held across sendMessage) and the channel lookups use the start-pinned physical walks.
- pycvc's state_set, state_get, state_has, state_comment, state_property(_keys) and
  state_children use the pinned walks, and state_remove uses removeChild.
td B17, 4.5 (S0.md section 2, S0.7). Both schedulers apply the Stage 0 kinds of control_cmd
through the direct calls' host paths, unchecked: kill (reason killed_by_user), pause, resume,
and signal (send_signal; "SIGKILL" kills). set_priority and the four kinds then call `done`, when
set, with what the call returned, on the scheduler's thread; a query has no done.

- Commands are applied one at a time, first in, first out, at the next step boundary. One that
  throws (a kill releases locks and cancels async calls, either of which can publish to the
  tree) gets done(false), and the commands after it go back to the front of the queue before
  the exception propagates; the swapped batch used to be lost. On the async scheduler the same
  holds for the drain's messages and settled calls, which it applies before its commands,
  whatever the order they were posted in (documented).
- Each destructor gives done(false) to the commands never applied.
- Sync scheduler: a post notifies the idle wakeup under control_mutex_; idle_wait's slice loop
  ends on a pending command and returns true; run() applies pending commands before it tests
  has_runnable(), so a resume of the only process, or a kill of the last one, takes effect.
- async_scheduler::has_pending_control() is exact: a flag of its own, set while commands are
  queued, rather than the whole ingress's.
- cvc-cli's serve loop steps when has_runnable() || has_pending_control().
- SchedulerLockPort.APostEndsTheSyncIdleWait posts to the port first and queues its stop after
  the port post returns: a post now ends the idle wait, so the old order let the stop end the
  run before the port post landed.

Tests (state_exec_async_test.cpp): AsyncPostControl and SyncPostControl
.KillPauseResumeSignalFromAnyThread, .AThrowingCommandRequeuesTheRest and
.TheDestructorRefusesWhatWasNeverApplied; AsyncPostControl.HasPendingControlCountsCommandsOnly;
SyncPostControl.APostedControlEndsTheIdleWait.
Two follow-ups in async_host.cpp to E's S0.1 and copy walk:

- The async arguments' copy is labelled "async arguments" (make_copy_job's who), so a deadline
  that cuts it no longer names state-data-get.
- outcome() leaves a built-in class dict alone: a kernel's dsl_exception can hold one itself,
  and set_field now refuses the 17 read-only class dicts (td 5 item 1). Its origin and function
  fields are added only to an instance, so such a call raises the class as it is, as the
  evaluators' raise does, instead of a TypeError from the read-only class.

Test: AsyncCallOutcome.AKernelRaisingABuiltinClassDictRaisesItUnchanged.
td 4.3 and 5 item 2 (S0.2's intrinsic). nil, scalars, strings and symbols are stored as they
are, and bytes as before. Anything else, an empty list or dict and every data_object included,
is copied by make_copy_job(v, copy_mode::isolate, "state-data-set") through run_data_job, and
the node is written once, in `then`, when the whole copy is made: a list changed after it was
stored no longer changes what state-data-get returns, and a refusal in any slice leaves the node
as it was. The top-level callable check goes: the walk refuses closures, natives, generators,
futures, lock forms, lock waits and object instances at any depth, the top included, and shares
an ordinary data_object (a lone one costs only the check of its root). The copy is charged to
the writer as deep-data work, and is never tracked by the writer's cycle registry.
Both sanitizer legs now require a scheduler stopped from another thread and destroyed as its run returns (ASan is what proves it), has_pending_control() while a batch applies, and a cancelled call raising for an await-all.
The docs against perf/threaded-s0 at 5684b4b, after the final reviews'
scheduler, coordinator, pycvc and memory fixes.

- Futures: cancel_async_calls settles each call it claims with the
  cancelled-call RuntimeError, so every await path raises it and the
  kernel's late result is ignored; outcome()'s check is a backstop. A
  finish that throws still wakes its waiters, and so does a completion
  requeue_ingress cannot queue again (td 4.9, td 7).
- has_pending_control() stays true until a taken batch is applied,
  refused or put back; done is moved out before it is called; each
  destructor refuses until nothing is queued; the sync stop() holds the
  wakeup it notifies; cvc serve logs a step that throws and goes on
  (guide "From Another Thread", td 4.12, td 7).
- Migrations: a failed serialize or send resumes the process and counts
  once as failed; migrations_initiated counts sent ones; a source that
  survives its kill is left paused (migrations_kill_failed). The weak
  token's limit stated exactly (guide 9, td 4.12, td 5 "Hosts").
- pycvc: exceptions passed through Python keep the built-in class
  (builtin_class_of_copy, shared with the codec); a dropped
  state_observer is never called; the pinned walks and removeChild are
  not exposed (README, EXCEPTIONS 2.3 and 2.7, td 4.8, LIFETIME 3.4).
- The copy's memo keeps its sources alive (td 4.3).
- Leaf-first release is cvc::pin_vector's, for pinned chains only; a
  single-node hold can outlive an unlinked ancestor (guide, td 4.8,
  LIFETIME 3.4). td 7's file list names pin_vector and the rest.
state_exec_exceptions_test, state_exec_async_calls_test and state_exec_data_steps_test joined the ASan+UBSan leg with Stage 0 and leaked their programs' closure/scope cycles at exit (every report an indirect leak: cycles, no direct leak). Like #877's binaries, each runs collect_cycles() in a global gtest environment's TearDown.
Deleting its assignment (R0a-mem-4) also took assignment from state_json_writer, which holds one, both public on master (the skeptic pass). The assignment now releases the old levels deepest first, then the old start.
The skeptic pass's SK-1 and SK-2, which finish R0a-conc-1 and R0b-sem-1 in cancel_async_calls.
Two things still skipped the wake of another process awaiting a cancelled call (a fork child):
- SK-1: the waiters were woken after the step rate was read to charge the calls. Reading the
  rate may publish it, and a slot on the tree that throws then left the child, and the parent,
  parked for good. The call was claimed and off the list, and nothing finished it again.
- SK-2: the cancel hook ran before the call was settled, so a hook that throws (against its
  contract) skipped both the settle and the wake:
  - a kernel that ignores the cancel then gave the child its late value;
  - started work that never settles once cancelled left the child waiting for good.

Each call is now claimed and settled before its cancel hook runs. That also settles a kernel's
race to settle between the two. A hook's exception is caught and kept. The waiters are woken
before the rate is read, then the calls are charged, and the first hook exception is rethrown
last.

Tests:
- AsyncCalls.AKillWhoseRateReadThrowsStillWakesTheForkChild: await and await-all. The kill
  throws, and the child and the parent both end, the child with the cancel's error.
- AsyncCalls.AThrowingCancelHookSkipsNeitherTheSettleNorTheWake: a kernel that ignores the
  cancel, and started work that never settles. The child gets the cancel's error.
The skeptic pass's SK-3, a pre-existing twin of SK-2 on the timeout path. charge_async_calls_from
settles a timed-out call with TimeoutError, cancels it, then finishes it, which wakes its waiter.
A cancel hook that throws (against its contract) skipped the finish. The call stayed on the list,
settled, and its kernel's late settle was refused, so no completion came either. The process
awaiting it waited until its own time limit. The finish now runs in the catch too, before the
hook's exception propagates.

Test: AsyncCalls.ATimeoutWhoseCancelHookThrowsStillResumesItsProcess. A 50 ms timeout on a kernel
whose cancel hook throws. The process catches the TimeoutError ("timed out"); before, it was
still waiting after 3 s.
…scheduler refuses late posts

The skeptic pass's nits on post_control:
- has_pending_control() is now a count of the commands posted and not yet applied or refused,
  queued or in a batch being applied. A command counts until it is applied or refused, and a
  requeued one goes on counting. The count replaces the flag a batch settled under the lock,
  whose failure path (a lock that throws) left the flag set until the next drain that had
  commands. That contradicted the comment, and the async header's comment was stale. With the
  count there is no such path left.
- Once a destructor has taken the queue, a post is refused at once: its done gets false, it is
  not queued, and post_control returns false. A done that posts again from its own refusal no
  longer keeps the destructor looping: the refusals end with the done's reposts.

Tests:
- {Async,Sync}PostControl.TheDestructorRefusesEveryRepost: a done reposts 1000 times while the
  scheduler is destroyed. All 1000 are refused, none is queued. Before, each repost was queued
  and post_control returned true.
- {Async,Sync}PostControl.HasPendingControlCountsWhatWaits pins the rule:
  - a query sees the command after it waiting;
  - a throwing command last in its batch leaves nothing waiting;
  - one that throws before another leaves that one waiting until the next drain or step.
  These pass with the old flag too. The failure path the count removes can't be made to happen
  in a test.
GCC 15's libstdc++ (ubuntu-latest now ships 15.2) no longer brings <algorithm> in through other headers, so state_compression_registry_test.cpp's std::sort failed to compile on every Linux lane; state_exec_intrinsics_test.cpp's std::find would have been next.
A class the recursive or the coroutine evaluator defines leaked at exit, even after
collect_cycles() (CI's ASan+UBSan leg: state_exec_exceptions_test's classes, from
evaluator::do_defclass). Their methods already went through do_lambda, which tracks the scope a
method captures, so the scope was a candidate. The cycle ran through lambdas the collector cannot
see into, though: each method was a native lambda holding its closure, the default init and
finalize were lambdas holding the superclass's dict, and the coroutine evaluator's constructor was
a lambda holding the class dict. The collector counted those references as outside owners, so the
scope always looked held. Tracking the scope once more where the class is bound, as first
suggested, changes nothing: the new tests fail with it.

Both evaluators now store the natives as named types the collector reads
(closure_natives.h): a method is a detail::evaluator_method, which holds its closure in the open
and applies it on the evaluator that made the class (not an owner); the default init and finalize
are class_inherited_method, as in the stackless evaluator; and the coroutine evaluator's
constructor is the stackless evaluator's class_constructor (the recursive one's already was).
heap.cpp follows an evaluator_method to its closure.

Behaviour: an inherited init or finalize now resolves up the chain as the stackless evaluator's
does, and the coroutine evaluator's inherited finalize passes its arguments on (it passed none).

Tests (heap): a class with methods and a subclass with none, defined and used through each
evaluator, are freed by collect_cycles() once the evaluator and its scope are dropped. Both fail
before this change, and with only the extra tracking.
The codec rebuilds a restored process's closures, a class's methods among them, and the scopes
they capture, but registered none of those scopes with the cycle collector. A defun or a class
bound back into a restored scope was therefore a cycle no collection could free (CI's
ASan+UBSan leg: state_exec_data_steps_test's restored-process test, from async_scheduler::restore
through decode_environment and begin_closure). The reader now tracks the scope each decoded
closure captures, as the evaluators do when they make one. Restored lists and dicts need no
tracking: the writer refuses a value that contains itself, so their cycles all run through a
scope.

Test (heap): a process with a defun and a class instance, snapshotted mid-run on one async
scheduler and finished on another, is freed by collect_cycles() once that scheduler is gone. It
fails before this change.
The regression test 14b296a lacked (the skeptic's R2-3): a cursor that is the last owner of a removed subtree, assigned over, lets a.b.c.d die while a.b.c is alive. It fails with a defaulted assignment.
The skeptic's round 2, R2-1. Since 3ada6e4, cancel_async_calls wakes every waiter of the calls
it cancels before it reads the step rate and before it rethrows a cancel hook's exception, and
that includes the process being killed. When either throws, kill_process aborted before it marked
the process killed. The woken process then ran on with its call cancelled: its await raised "the
process that made the call ended", which it could catch, though it never ended.

A kill always kills (the lead's decision). kill_process now catches what cancel_async_calls
throws, marks the process killed (its locks released, its exit error set, its state released) and
then rethrows, as a kill whose locks' release throws already leaves its process killed. The done
of a posted kill, or of a SIGKILL, whose call threw now hears the truth: true when its process is
killed. Any other command that throws is still refused with done(false). The post_control docs say
so. AsyncPostControl.AThrowingCommandRequeuesTheRest now expects the throwing kill to kill, and its
done to get true.

Test: AsyncCalls.AKillThatThrowsStillKillsItsProcess. A cancel hook that throws, and a slot on
the tree that throws when the kill publishes the rate. Each kill throws, and the process is
killed_by_user with no result, also after half a second of pumping. Before, it ran on and ended
with its catch's value.
…refuse

The skeptic's round 2: R2-2 and the nits on post_control.

- R2-2: since 1640c1f, a post made while the scheduler is being destroyed was refused inside
  post_control, which called the done, which could post again. The refusals nested one level per
  repost, so a done that retries until applied ran out of stack (about 1800 reposts on a 1 MiB
  thread, Release). Now such a post is queued for refusal: it returns false, is never applied,
  and calls no done itself. The destructor refuses it in its next round, so the refusals iterate
  and never nest. A done that posts again every time it is refused still never lets the
  destructor end; that is documented.
- has_pending_control() inside the destructor: the destructor now counts out each command as it
  refuses it. Every path counts a command out once its call is made, before its done runs:
  apply_control tells the batch it has, so a throw after that point is not counted twice.
- The post_control docs say a post to a scheduler being destroyed is undefined, except one made
  from a done the destructor calls.

Tests:
- {Async,Sync}PostControl.TheDestructorRefusesEveryRepost: now 100000 reposts, on a thread of its
  own with the default 1 MiB stack. All are refused, and none is accepted for application.
  Before, the process crashed.
- {Async,Sync}PostControl.TheDestructorCountsOutWhatItRefuses: the first refusal's done sees the
  second command waiting, and the last sees none. Before, both saw true.
@transfix
transfix marked this pull request as ready for review November 6, 2026 20:40
…e) (#1020)

The v3.7.9 tag's publish-pycvc-gl-wasm run failed at the host smoke: right
after PYCVC_VTK_BRIDGE_OK, pycvc_host aborted under node with
"Aborted(undefined)" from ___cxa_throw.

cvc, cvcGL and the SWIG wrappers compile with -fexceptions, but
link-host.sh's emcc line did not pass it. So emscripten linked the host with
exception catching off, and every throw aborted, even one a catch would take.
v3.7.9's smoke added Exec(make_app()) (#961), and on a new app
cvc::state::instance() throws and catches a boost::bad_any_cast. The link
now passes -fexceptions.

Separately, build-wasm.ps1 builds on a Windows host:
- it finds the windows swig bundle's library in bin/Lib;
- it presses past cvcGL's test executables when their links fail, through an
  opt-in -KeepGoing on Invoke-CvcWasmCMakeBuild, as build-wasm.sh does with
  -k 0;
- it checks that _pycvc.a and _pycvc_gl.a were installed.

(cherry picked from commit 7a5d94a)
…izer jobs

S0.13's baseline run put the 16 state_exec binaries no sanitizer had run under ASan+UBSan. All
pass, and eight end with LeakSanitizer reports, every one an indirect leak (cycles, no direct
leak). Seven of them (advanced integration, codec, deep data, evaluator, heap, stackless
evaluator, stdlib) leak their programs' scope and closure cycles, which only the collector frees.
Like Stage 0's own binaries, each now runs collect_cycles() in a global gtest environment's
TearDown. state_exec_types_test's WalksTerminateOnCyclicStructure makes a list that holds itself
outside any collector; the test now breaks that cycle.
One conflict: bindings/pycvc/wasm/link-host.sh, where the branch had only master's #1020 (cherry-picked
for the wasm dry run) and master has #1020 and #1027 since; master's file is taken.
…n baseline found)

S0.13's baseline run put state_exec_evaluator_test and state_exec_stackless_evaluator_test under
TSan for the first time. Their tests that count steps from another thread while an evaluator steps
(EvaluationStatsTest.IncrementStepCountsWhileTheEvaluatorSteps,
StacklessStepCounts.CountedFromAnotherThreadWhileTheEvaluatorSteps) raced on last_kind. The counters
are atomic, but last_kind, written by the evaluator's count_eval_step() and by increment_step() on
the other thread, was a plain field. Under TSan, every step took the race's report path, and both
binaries ran past run.sh's hour (exit 124). It is now a relaxed atomic. That orders nothing, and
its store is a plain store on x86, so the evaluator's hot path is unchanged.
state_exec_deep_data_test runs its programs on boost threads with chosen stack sizes. The cycle
collector's registry is per thread, so the exit collection on the main thread never saw those
threads' cycles, and their ASan recheck leaked as before. Each thread now collects before it ends.
(Nothing collects a thread's registry when the thread exits: a follow-up.)
…d commit)

Stage 0's plan (S0.13) adds, after a baseline run, the state_exec binaries no sanitizer had run:
types, parser, builtins, evaluator, stackless evaluator, codec, unicode, stdlib, heap, grammar,
corpus, PEGTL, gaps, advanced integration, deep data and the micro-benchmarks
(state_exec_bench_test, a no-op without CVC_STATE_EXEC_BENCH=1). state_exec_multiprocess_test calls
fork() and stays out.

The baseline ran them under both legs on a scratch branch. Every test passed. The reports, all
fixed in earlier commits on this branch, with nothing suppressed:
- ASan: eight binaries leaked cycles at exit, and they now collect them.
- TSan: two binaries raced on evaluation_stats::last_kind, now atomic.
Rechecks came back clean: the two TSan binaries, and seven of the ASan ones. deep_data's
thread fix is verified by this commit's own ASan leg. Without the two binaries the race slowed past
the hour, the 16 add about 76 s to the TSan leg and 30 s to the ASan leg.
@transfix
transfix merged commit 2ea9ce9 into master Nov 7, 2026
27 of 28 checks passed
@transfix
transfix deleted the perf/threaded-s0 branch November 7, 2026 07:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant