Skip to content

state_exec locks L3: one app, several threads - #961

Merged
transfix merged 70 commits into
masterfrom
perf/locks-l3
Nov 3, 2026
Merged

transfix merged 70 commits into
masterfrom
perf/locks-l3

Conversation

@transfix

@transfix transfix commented Nov 1, 2026 •

Copy link
Copy Markdown
Owner

Phase L3 of the state_exec locks plan (docs/STATE_EXEC_LOCKS.md 8.3,
8.4, 8.6, 8.7, 9.1, 9.2): one app, several threads. Every scheduler of an
app can share app::lock_manager(); pycvc's Execs on Python threads,
Ariadne's init lane and the app's exec scheduler are one lock namespace,
and a grant to a waiter on another thread reaches it through that home's
lock port. Nothing changes for a scheduler with no lock home, and a
program that never locks takes the same steps.

  • Shared mode (protocol 2.1, 4.4): every lock_table operation under one
    mutex (M.mu), nothing called out of the table under it; several homes
    per manager, ids never reused, a detached home's entry freed, lending a
    count; lock_attach{cross_thread} and its refusal on a single-mode
    manager (naming state_exec.locks.threading); threads_compiled_in and
    threaded_host_attach() for builds without threads.
  • Ports and posts (protocol 2.3, 4.14, 5.7, 5.9): detail::lock_port
    under its own mutex; deliver posts another home's notes; ~lock_home
    closes the port first, detaches, discards and counts what is left; the
    post counters and the manager mutex's wait count in lock_stats.
  • Schedulers: the wakeup each shares with its home's port; the port
    drained at the top of a sync step and first in the async drain;
    wait_for_work and idle_wait end on a post; last_progress stored after
    each step; set_lock_manager(mgr, lock_attach) keeps the old home when
    the new attach is refused; has_lock_home(), lock_waiting_count() and
    lock_waiting_pids().
  • blocking_sinks (protocol 4.13), from one waiter or from a set of them.
  • Hosts: app::lock_manager() picks single or shared from
    state_exec.locks.threading (auto: shared when threads are compiled in
    and a threaded host announced itself or state_exec.threads > 0);
    Ariadne's init lane locks on the app manager and never waits (LW-9).
  • pycvc: Execs attach to the app's manager; idle_timeout's lock-wait rule
    (a lock wait of any of the Exec's processes counts as pending only
    while a sink on another home made progress within the window, which
    runs from that progress); Exec.lock_query from any thread;
    scheduler.set_lock_manager(app) for a scheduler's first lock home.
  • Robustness: an unwound wait whose ticket another home granted releases
    the grant (protocol 5.4); deliver and drain_port finish their posts
    after a throw; a throwing wait_expired leaves no stale expiry.
  • CVC_EXEC_FUZZ: fuzzed yields at the protocol points, with a seed setter
    for tests.
  • Model check: ports, two-step destruction, late attaches and progress
    cells in the world; 15 configurations of two and three homes against
    the real table, the L1/L2 mutations on two homes and the port race
    (splitpost_mut), random runs over 1-3 homes, l3 traces from the Python
    model.
  • Tests: LocksThreads (LT-2, 3, 3b, 4, 10, LD-6, PI-7, PI-10, LX-5, 7, 10,
    11, and the progress store) and LocksStress; the pycvc cross-thread
    tests (LT-1, 3, 7, 7b, 7c, 8, 8b, 8c, 10, 11, LD-5, PR-8); LockShared,
    LockHomes, LockPort and LockFuzz table cases; the wasm smokes can fail.
    LT-3b stops at 90 s unless CVC_LOCKS_LT03B_RUNS sets its count (at least
    a twentieth of its runs): on macOS each sched_yield in its spins and
    barrier can give up the core for a 10 ms quantum, and its 10^4 runs took
    228-300 s there against 12 s on Linux.
  • CI: the cross-thread cases in the TSan and ASan jobs, each run checked
    for its required cases; locks-deep.yml split into six lanes with the
    two-home model at bounds 4 and 5 and the Linux lock.cross_thread
    record.
  • Bench: locks=shared, lock.uncontended's threading size, and
    lock.cross_thread.
  • Docs: the developer guide's Locks chapter, pycvc's README and parity
    doc, ARIADNE.md, TESTING.md, STATE_EXEC_BENCH.md, the protocol, the
    locks design's status and 11.3, STATE_EXEC_THREADED.md 2.4.
  • Docs, which scheduler runs a program: a developer-guide section that
    tables every host and Ariadne lane (scheduler class, fixed in code;
    policy source; lock home; thread) and when each state_exec.* setting is
    read (once, at build; nothing switches at run time), with ARIADNE.md,
    APP_API.md (exec_scheduler, exec_async_host, lock_manager) and
    CLI_GUIDE.md to match. Corrected: app.h's comment and the roadmaps put
    init: on the app scheduler (it runs on a private sync one), and the
    roadmaps said only async_stackless_evaluator is scheduled; ARIADNE.md's
    frame budget is 30 ms; the bench's rr is a bench-only name.

A/B (bench.md), base master baf8b6d, two windows on 2026-11-01
(07:45-08:07 and 12:44-13:05 local). Neither met the quiet rule: no
build ran and builder #28 was idle, but an editor, other agent sessions
and an unrelated renderer took 0.5-1 core, with bursts to 77% load.

  • steps_total is unchanged in every family, in both windows: this branch
    against master, locks=none against locks=shared, and L2's reruns.
  • Every timing point is over its noise limit (4-209%), so the timing gates
    have no verdict. Geometric means of the ratios, for orientation only:
    locks=shared over locks=none in one binary 1.00 in both windows (p10-p90
    0.95-1.09); this branch over master 0.96 and 1.08. The second window's
    shift is the same in eval.*, which L3 does not touch: its candidate
    rounds ran in the load burst. With no lock home, L3 adds two null checks
    per step.
  • lock.cross_thread, hot key: handoff p50 13-17, 16-21 and 29-35 us at
    t = 2, 4 and 8 in window 1, 10-12, 11-14 and 17-23 us in window 2 (gate
    50 us).
  • lock.cross_thread, disjoint keys, 3 us sections at t = 4: 0.80 and 0.86
    of the unlocked loop (gate 0.9). The manager mutex's counters show why:
    at t = 1 there is no wait (0.92-0.95), and at t = 4 more than a third
    of the locks wait on M.mu, losing 430-580 ns each. Each lock holds it for
    about its whole cost, a few hundred ns, against design 3.3's 30-150 ns
    per operation. 30 us sections stay at 0.94 or better through t = 8.
  • lock.uncontended at threading=shared: 468-1360 ns (gate 120 ns), the same
    as single mode beside it; it waits on L1's per-lock cost (60 ns gate,
    also missed).

Sharding (STATE_EXEC_LOCKS.md 11.3): no verdict, so the manager keeps
its one mutex. A confirmed miss would come from each lock's hold time,
which sharding by subtree would not shorten, so L1's per-lock cost comes
first, then lock.cross_thread is measured again in a quiet window.

locks-deep.yml on this branch (run 41340188915): every lane passes (the
one-home and two/three-home model checks at bounds 3-5, LocksStress).
Its Linux lock.cross_thread record (4-vCPU hosted runner, not gated):
disjoint 3 us sections at 0.91, 0.88 and 0.83 of unlocked at t = 1, 2
and 4; hot-key handoff p50 11.6-11.8 us at t = 4 (design 20 us).

…per-step calls

Phase L3's interface commit (locks plan, overview 5): the declarations
the L3 implementers build against, with the small bodies that make them
usable at once.

- lock_manager.h: lock_attach { cross_thread }, threads_compiled_in
  (false on Emscripten without pthreads), and
  detail::note_threaded_host() / threaded_host_noted().
- lock_table: attach_home takes a lock_attach and refuses a cross-thread
  home on a manager not in shared mode (naming
  state_exec.locks.threading); options::shared; blocking_sinks(pid),
  a stub until L3.3; the closed_outside_mu mutation bit (L3.4); the
  cross_home_note test hook (LT-3b).
- lock_home.h: detail::lock_port (protocol 2.3: post, close, drain and
  pending, under the port's own mutex), the CVC_EXEC_FUZZ points with a
  stub (L3.7), and the home's scheduler-facing calls: port_pending(),
  drain_port(), store_progress(now), port() and blocking_sinks(pid).
  The home makes its port (sharing the scheduler's wakeup, when given)
  and its progress cell and passes both to attach_home; deliver posts
  another home's notes to its port; the destructor closes the port
  first.
- The manager accepts several homes; shared mode still throws until
  L3.1.
- scheduler and async_scheduler: set_lock_manager(mgr, lock_attach = {}).

No behavior changes for a scheduler with one home or none.
Locks plan L3.5, with the wasm smoke row of L3.6 and LW-9's L3 case.

- app::lock_manager() fixes the manager's mode at its first call
  (design 8.3, 14.2 Q4) from state_exec.locks.threading: single or
  shared as it says; auto (the default) is shared when threads are
  compiled in and either state_exec.threads asks for workers (a whole
  number above 0, or auto) or a threaded host announced itself
  (detail::note_threaded_host()), else single. An unknown value is
  logged and auto used, as an unknown state_exec.policy is. The call
  that makes the manager holds interruption off and logs once the
  mutex is released, as exec_scheduler() does.
- exec_scheduler() makes the manager before the scheduler and attaches
  its home with lock_attach{ shared }.
- Ariadne's run_scoped_program attaches the init lane's scheduler to the
  app's manager (same thread). lock_wait_allowed false, which its
  children copy, keeps it from ever waiting for a resident: one attach
  and one detach per init script.
- cvc-cli's schedulers are left alone (L3.5's optional row): they bind
  no intrinsics, so with-lock and lock-query never reach a manager
  there, and an eager home would only add its per-step costs.
- Tests: Locks.LW09_InitLaneNeverWaits (an init script and its child
  against a resident's hold: TimeoutError at once, :else, and no wait
  queued on the manager); AppLockManager.* (the mode choice; the
  threaded-host case runs in a child process, since the flag is
  process-wide); state_exec_wasm_smoke checks auto's choice and the
  attach pycvc's Exec makes, and runs a section with a waiter on the
  app's manager.
…tach rules

Locks plan L3.1 (manager and home half).

- lock_table: every public operation runs under one guard (impl::guard,
  the plan's lock_manager::guard, placed at the table since the homes
  call it directly). In shared mode (options::shared) it holds one
  std::mutex, M.mu, for the whole operation; in single mode it keeps the
  debug owner-thread token. No public operation calls another, and
  nothing is called out of the table under the mutex: notifications are
  returned and delivered after the unlock (protocol 0, 4.14; design
  8.3). detach_home releases the home's port and progress cell after
  the unlock, so nothing is destroyed under M.mu.
  lock_stats::leaked_at_exit is a relaxed atomic, counted outside M.mu.
- lock_manager accepts threading = shared and sets the table's mode from
  it. The cross-thread attach refusal and several homes per manager
  (from the interface commit) are kept and tested.
- lock_home: a debug-only home token, an atomic thread id taken at each
  home action's entry and released at its exit, asserting that no two
  threads run one home's actions at once; the owning thread may re-enter
  (an action delivers, a delivery applies a post that calls the table).
  The members are present in every build, so the layout never depends
  on NDEBUG; release builds compile the checks out.
- Comments in lock_manager.h, lock_table.h and lock_home.h say what L3
  now does.

Tests (state_exec_locks_model_test): LockShared.SharedModeConstructs,
LockShared.CrossThreadAttachNeedsASharedManager (refused on a single
table and manager, naming state_exec.locks.threading; accepted on a
shared one), LockHomes.SeveralHomesAttachAndDetach (three homes on one
manager in each mode, a wake through a port, destruction in any order,
ids never reused), and LockShared.TableDrivenFromSeveralThreads (four
threads on one shared table, contended keys, nested requests that close
cycles, waits resolved by other threads' releases, timeouts; check()
inside every operation, the table empty at the end).
The schedulers' half of L3.2 (locks plan L3.md 1; protocol 2.3, 5.9;
design 8.7). The home half (lock_home, deliver, drain_port, the post
counters) is its own commit under the same title.

- async_scheduler: wakeup_ becomes a shared_ptr, still made at
  construction, and is given to the home wherever it is made
  (set_lock_manager, locks()), so a post to the home's port notifies the
  wakeup wait_for_work blocks on. drain() applies the port's posts first
  when its pending flag is set. wait_for_work() returns true while posts
  are pending, at its first test and at the test after announcing the
  wait; the port notifies unconditionally, so a post is either seen by a
  test or ends the wait. The drain clears the flag: no busy-wait.
- scheduler (sync): idle_ becomes a shared_ptr, made with the home (on
  the scheduler's thread, gap G-25) and shared with its port; a
  replacing home gets the same one, and a scheduler with no home still
  makes it at its first idle wait. step_once() applies the port's posts
  first when pending. idle_wait()'s loop also ends when a post is
  pending and then returns true, so run() steps again and step_once
  drains the port; the early return of a run bounded by max_steps is
  unchanged (design 6.1).
- Every new test is behind home_: a scheduler with no home pays nothing
  new per step.

Tests (SchedulerLockPort): two schedulers on one manager stepped by one
thread, every pairing of the two types: A's release posts a wake to B's
port, and B's next step drains it and runs the waiter to its result. An
async_scheduler in wait_for_work(30 s) and a sync run() beside a 5 s
sleeper both return on another thread's post (a relevel for an unknown
pid, ignored when applied); the run's sleeper is still asleep when it
returns, and the drained port no longer ends a wait.
Locks plan L3.2, the manager and home half (the scheduler half, the
shared wakeup, drain and the waits, is a separate commit under the same
title).

- lock_manager: the three port counters, posts, posts_dropped and
  posts_discarded, are std::atomic<std::uint64_t> members bumped by the
  homes with relaxed adds outside M.mu and read by stats() into
  lock_stats (declared there since L1.2, G-35).
- lock_home::deliver (protocol 4.14): a note for another home's port
  calls lock_test_hooks::cross_home_note when set, then posts; a post
  that lands counts posts, one refused by a closed port counts
  posts_dropped.
- ~lock_home in protocol 5.7's order: close the port, assert it closed
  (debug, outside M.mu), detach_home, deliver its notes, drain and
  discard the port's queue counting each post in posts_discarded, drop
  the port reference, then clear every process's lock fields. Each step
  is guarded, so nothing throws out of the destructor.

Tests (state_exec_locks_model_test): LockPort.PostCloseDrain (FIFO, a
post notifies the shared wakeup, drain clears pending, a post after the
close returns false and appends nothing), LockHomes.
CrossHomeNoteLandsInItsPort (two homes in each mode: a real wake and a
hand-made note land in the other home's port and are counted, a note
for the home itself is applied at once, a note for a destroyed home is
dropped and counted), LockHomes.DestroyedHomeDiscardsItsPosts (posts
left in a destroyed home's port are counted as discarded, its grant
released, its processes' lock fields cleared), and LockHomes.
PostsRacingACloseNeverLand (200 rounds of three poster threads racing a
home's destruction: posts + posts_dropped equal the notes handed over,
every landed post drained or discarded, none after the close).
The schedulers' half of L3.3 (locks plan L3.md 1; design 8.4, 8.8): both
schedulers' execute_process_step store the clock reading each step ends
with in the home's progress cell, right after it is taken (a relaxed
store; no clock read of its own). The early returns (signal and watch
handler setup, a step that fails or is killed inside the evaluator)
take no reading and store nothing; the next step does. A scheduler with
no home stores nothing.

The home half (the cell's attach, lock_table::blocking_sinks) is its own
commit under the same title; the test that reads the cell through
blocking_sinks rides with it.
Locks plan L3.3, the manager half (the schedulers' progress store is a
separate commit under the same title).

- lock_table::blocking_sinks(p), protocol 4.13: under M.mu (shared
  mode), every process reachable from p in the wait-for graph (3.2) with
  no edge out, other than p, each with its home's progress cell loaded
  (relaxed; 0 for a home with none), sorted by lock_pid. Empty when p
  waits for nothing. It reads only the shared cell, never a home object,
  so a caller never reaches another home after the unlock (design 9.2).
  The home's progress cell, store_progress and lock_home::blocking_sinks
  are the interface commit's.

Tests (state_exec_locks_model_test): LockTable.
BlockingSinksFollowTheChain (A waits for B waits for C gives {C}, also
through a waiter edge; a holder and a process with no record give {}),
LockTable.BlockingSinksBothSharedHolders (two S holders of the key give
both), LockTable.BlockingSinksCarryTheirHomesProgress (sinks on other
homes carry their homes' cells, loaded at each call, 0 without a cell;
a sink on the waiter's own home carries its own), and LockHomes.
BlockingSinksReadTheHomesProgressCell (through two homes in each mode:
the holder's home's store_progress is what the waiter's home reads).

Also, in the test file: LockHomes.PostsRacingACloseNeverLand's posters
yield after each post (on a loaded machine three spinning posters
starved the closing thread for seconds), and the L3 section banners are
single 100-column lines.
…ule; Exec.lock_query

Phase L3.6 of the locks plan (docs/STATE_EXEC_LOCKS.md 7.4, 8.4, 9.2).

- pycvc.i: the module's init calls detail::note_threaded_host(), so an
  app's lock manager in auto mode is shared from pycvc's import where the
  build has threads. %feature("kwargs") for Exec::lock_query. Both
  schedulers get set_lock_manager(app): a host scheduler over an app's
  tree on app::lock_manager(), attached as an Exec's home is (LT-7's sync
  scheduler cases need it).
- Exec's constructor attaches its scheduler to app->lock_manager() with
  lock_attach{threads_compiled_in}: cross-thread wherever the build has
  threads (a single-mode manager refuses it, naming
  state_exec.locks.threading), and not on the static Emscripten pycvc,
  whose auto manager is single.
- Exec::run's idle test: whenever the existing test finds work pending,
  the home's last_progress is stored. While our pid waits for a lock,
  blocking_sinks(pid) counts as pending only for a sink on another home
  whose progress lies within idle_timeout; a sink on this home counts
  only through the existing test. A kill at the limit names the key:
  "parked with no pending work (pid N, waiting for lock <key>)".
- Exec.lock_query(prefix=""): lock_manager::query with the Exec's home and
  owner "", from any thread, with the GIL released for the query; never
  waits for run() or the control mutex. Python objects are made after.
- The static pycvc's node smoke runs Exec(app) with a with-lock and
  prints PYCVC_EXEC_OK; link-host.sh's status is the smoke's when NODE is
  set (build-wasm.sh keeps the link non-fatal); the publish workflow runs
  the installed host itself and fails unless it exits 0 with
  PYCVC_VTK_BRIDGE_OK, PYCVC_EXEC_OK and PYCVC_WASM_OK.
- test_l3_exec_needs_a_shared_manager: the refusal on a single manager.
  The test file's CVC_STATE_EXEC_CHECK=1 is now a default, so =0 runs it
  without the manager's checks.
Phase L3.9's pycvc cases (docs/STATE_EXEC_LOCKS.md 13.5, 13.6, 13.7), in
test_pycvc_state_exec_locks.py, at the sizes of the plan
(CVC_LOCKS_SANITIZER=1: the sanitizer jobs' smaller ones):

- LT-1: two Execs on two threads, 10^5 read-modify-write sections each on
  one key: the count exact.
- LT-3: a holder killed while another Exec waits: granted; an Exec
  destroyed with a grant's wake in its port: nothing held after, and the
  manager goes on.
- LT-7: a waiter with idle_timeout 0.5 behind an Exec's 1.5 s await, a
  sync scheduler's run() stepping for 2 s, and a step() every 0.1 s:
  granted on release, never killed.
- LT-8: behind an unpumped Exec: killed at the limit, naming the key;
  behind a pumped one: granted; behind a parked holder while a sibling
  steps: alive while it steps, killed after.
- LT-8b: a holder parked in the waiter's own Exec: killed at the limit.
- LT-10's smoke: 8 Execs on 8 threads over 4 keys: counters exact,
  nothing held or waiting at the end.
- LT-11: another Exec's pids hidden from lock-query and Exec.lock_query,
  its holds counted; a cross-Exec DeadlockError's cycle shows the other
  Exec's pids as nil.
- LD-5: a cycle across two Execs: DeadlockError when the closing request
  blocks; the other side granted.
- PR-8 (L3): lock_query answered from other threads, on an idle Exec and
  while run() is inside a step; a monitor polling it across 10^4 runs
  that terminate, are killed and raise: whole answers, no hang.
Locks plan L3.7 (gap G-27; LT-4 uses it).

- detail::lock_fuzz_point(lock_fuzz_at): with CVC_EXEC_FUZZ=<seed> in
  the environment (read once, as the library loads; decimal or 0x hex,
  any other non-empty value hashed), each thread's PRNG, seeded from the
  seed and a per-thread stream number, runs on, yields, or pauses
  0-50 us by yielding until the time has passed (a sleep would round up
  to the OS tick, up to ~16 ms on Windows). Off, a point is one relaxed
  load.
- detail::set_lock_fuzz_seed(std::uint64_t) overrides the environment
  for the process (0: off), so LT-4 can run many seeds in one process;
  each thread re-seeds at its next point. lock_fuzz_seed() and
  lock_fuzz_hits() read the seed in effect and how many points were
  reached under one.
- The points: in the home, between every table call that returns notes
  and their delivery (deliver_op; an operation with no notes has no
  delivery to race, so the uncontended path pays nothing); inside
  lock_port::post before and after its critical section; in drain_port
  between posts; in ~lock_home between the close and detach_home.

Tests (state_exec_locks_model_test): LockFuzz.OffByDefault (with
CVC_EXEC_FUZZ unset the seed is 0; with the seed 0 a pass through every
point fuzzes none; with a seed it reaches each of them) and LockFuzz.
PostsRacingACloseNeverLandUnderFuzz (L3.2's port race, 100 rounds,
under a seed: every count still holds).
world_opts' locks=shared gives a world's scheduler a shared-mode manager
(or one passed in), attached through set_lock_manager; the async
scheduler's home attaches cross_thread (threads_compiled_in), as pycvc's
Exec does. sched.single.*, flood.small and msg.* accept it, so L3's
paired gate (--size locks=none,shared, then shared,none; compare --pair
locks=none:shared) runs on the hosts' shape. Their step counts are the
same at none and shared.

lock.uncontended's threading key takes single and shared (a shared-mode
manager per world: every operation under its mutex). The CTest gates
run both, so 0 steps and 0 allocations per uncontended lock hold for
shared too.

lock.cross_thread: t async schedulers on t threads (1, 2, 4, 8), each
pumped as Exec::run pumps it, on one shared manager; disjoint keys or
one hot key, sections of 0.3, 3 and 30 us of calibrated CPU work
(xorshift rounds). Each rep runs the loop without with-lock first on
the same schedulers, so extra.ratio_to_nolock comes from one rep. On
the hot key each cross-thread handoff is timed from the holder's last
section form to the waiter's first, the waits found through the
lock_test_hooks cross_home_note hook (extra.handoff_p50_ns). The mutex
wait is read from lock_stats when it has mutex_waits/mutex_wait_ns.

docs/STATE_EXEC_BENCH.md: the new sizes, the scenario and its metrics,
and the phase L3 gates.
Design 9.2: a wait behind a holder whose home has made no progress
within the limit is killed at the limit. run()'s lock-wait rule
refreshed the idle deadline from the time of its check, so a waiter
outlived the sink's last progress by up to twice idle_timeout. Now the
latest in-window progress of a sink on another home moves the deadline
to that progress plus idle_timeout (never earlier than it already is),
and a waiter is killed about idle_timeout after the sink's last
progress; a sink that keeps progressing (LT-7) keeps it alive. The
existing test's refresh (store_progress(now), the deadline from now)
is unchanged.

LT-8's third case checks, one-sided, that the kill comes no earlier
than idle_timeout after A's last step began (the gap printed).
Locks plan L3.4 (LT-5 on two homes; protocol 7): the model check of
state_exec_locks_model_test runs explore.py's configurations of two and
three homes over the real lock table, beside the spec oracle.

- The world gains world.py's ports: a post to another home is an action
  of its own (in 'splitpost' its closed test and its append are two, the
  append one critical section under the port's mutex), a home is
  destroyed in two actions (the port's close, then detach_home), a late
  home attaches by an action, and each process step advances its home's
  progress cell, a logical clock the oracle and the table share.
- blocking_sinks (4.13) is checked at every quiescent state: the
  oracle's against lock_table::blocking_sinks, each sink a process that
  can run, its time its home's cell. Every notification of the table
  must carry its home's port (4.14).
- Configurations: core, wide, handlers, priority, destroy, coalesce,
  attach, noinh, foreign, splitpost, splitpost2, cache, two2, grantseeds
  and three (LocksModel.Homes*, LocksModelStress.Homes* at bound 3).
  Coalescing is set on both sides as explore.py sets it (G-39);
  CVC_LOCKS_MODEL_COALESCE=1 runs the stress cases' +c variants. The
  regular bounds follow the measurement (L1 section 3): Release 3 but
  2 for wide; Debug 3 for attach, splitpost and splitpost2, else 2;
  sanitizers 2. With explore.py's cache each configuration has
  explore.py's state counts at bounds 1-3.
- Mutations on two homes, each reporting its own violation:
  closed_outside_mu (port-race, also by exploring splitpost_mut), and
  the L1 and L2 ones again; coalesce_no_clear explored on coalesce (I8).
  scenarios.py's scenarios run as written on two homes.
- Random runs over one to three homes (RandomHomes).
- export_traces.py writes l3_* traces of two and three homes, with
  blocking_sinks and the progress cells it loaded; PythonTraces replays
  them into the oracle and the table.
What L3.4's port of the model adds: ports, two-step destruction, late attaches, progress cells and blocking_sinks in the world; the configurations of two and three homes, the TwoHomes scenarios and mutations, the random runs over one to three homes; the Python state counts and the l3 traces; the bounds per lane and the measurements they were chosen from.
The manager mutex's wait time, which the bench's lock.cross_thread
records (locks plan L3 section 4).

- lock_stats gains, after posts_discarded, mutex_waits (shared mode:
  operations that found M.mu held) and mutex_wait_ns (the time those
  operations blocked on it).
- The table's shared-mode guard takes M.mu with try_lock first; only
  when that fails does it read steady_clock, lock, and add one wait and
  the blocked nanoseconds to counters kept in the table's impl, guarded
  by the mutex itself. stats() copies them. The uncontended path stays
  one try_lock; single mode counts nothing.

Test (state_exec_locks_model_test): LockShared.MutexWaitsCounted (a
single table and a single manager report 0; two threads on disjoint keys
of one shared table produce mutex_waits > 0 within a bounded loop, no
timing asserted).
Locks plan L3.9 (L3.md section 3), its C++ rows, in
state_exec_locks_test.cpp's LocksThreads suite: several schedulers'
homes on one shared manager, each attached cross_thread, most on a
thread of its own (home_thread runs a home's actions on its thread, in
an order the test fixes). No case asserts wall-clock precision: each
proves a structural fact, and prints its times.

- LT-2: a grant posted from another thread ends an async wait_for_work,
  and a sync run()'s idle_wait beside a 5 s sleeper (still asleep when
  the waiter ends); a sync run(N) too short for the wait, and a
  run(10^7) with only the waiter, return, and the next run applies the
  wake.
- LT-3: a holder killed while another thread pumps its waiter; a
  scheduler destroyed with a wake in its port.
- LT-3b: a post racing its scheduler's destruction on a third thread,
  10^4 runs on each scheduler: posts + posts_dropped equal the
  cross-home notes (lock_test_hooks::cross_home_note), and every post
  that landed was applied or discarded.
- LT-4: CVC_EXEC_FUZZ's seeds (100; 20 unoptimized or under a
  sanitizer; 1000 in LocksStress), 4 homes on 4 threads, stopping
  every 100 operations; the fuzz points were reached.
- LT-10: 8 priority_rr async_schedulers on 8 threads, 10^4 operations
  (2*10^3; 10^5 in LocksStress), and a std::barrier stop every 1000:
  every port drained, every home's check_quiescent(), the manager's
  check(), then on. The programs also check X exclusion themselves.
- LD-6, PI-7, PI-10, LX-5, LX-7, LX-10 and LX-11 on two or three
  homes, and the progress store: a step on the sink's home moves the
  cell blocking_sinks reports, a step on the waiter's does not.

The L1 fixture gains what these need: a manager, an attach, a policy
and a shared tree for checked_world, what its check_all() checks when
its home is one of several (world_checks), the spawn context, and a
hook native. The L1 cases are unchanged.
Locks plan L3.8.

- ci.yml's sanitizer jobs already run state_exec_locks_test, the model
  test and pycvc's lock script whole, at their sanitizer sizes
  (CVC_LOCKS_SANITIZER=1), so LocksThreads and the model's two- and
  three-home configurations at bound 2 run there. Each job now names
  the cases it is there for (the matrix's `required`, which run.sh
  checks against each run's log): LocksThreads in both, LT-3b and LX-7
  under ASan, LocksModel.Homes* and TwoHomes*, and pycvc's cross-thread
  tests (LT-1, LT-3, LT-7, LT-8, LT-10's smoke, LD-5) under TSan. A case
  renamed, skipped or filtered out fails the job rather than leaving it
  green without it. No suppression is added.
- ari-wasm: app.cpp and app.h in its path filter, and its smoke step's
  comment says what the smoke now checks.
- locks-deep.yml: split into lanes, one job each, each under the hosted
  runner's 6 hours with its own timeouts: the one-home model runs as
  before; L3.4's configurations at bound 4; at bound 5 core, destroy,
  handlers and attach, and cache alone; the '+c' variants at bound 3
  with the two-home random runs and state counts; and LocksStress
  (LT-4's 1000 seeds, LT-10's 10^5 operations) with the Linux
  lock.cross_thread record, kept as an artifact and printed beside the
  design's 20 us handoff p50, never gated.
L3.9's LT-4 ran against a local stand-in for the seed setter until L3.7
landed. It now sets CVC_EXEC_FUZZ's seed through
detail::set_lock_fuzz_seed, and checks that each seed's runs reached
the protocol points (detail::lock_fuzz_hits), printing how many.
Locks plan L3.11 (L3.md section 5): the docs of phase L3.

- STATE_EXEC_DEVELOPER_GUIDE.md, Locks: one manager per app (the app's
  exec scheduler, Ariadne's init lane, pycvc's Execs); single and shared
  mode and state_exec.locks.threading (auto's rule, an unknown value
  logged and auto used, state_exec.threads auto, the mode fixed by the
  first lock_manager(), exec_scheduler() or init script); lock_attach
  and the single manager's refusal; several schedulers on threads;
  cross-thread grants (applied at the waiter's next step boundary after
  the post, the waits ending on a post); deadlocks across threads; hot
  keys in one thread.
- pycvc README and PYCVC_STATE_EXEC_PARITY.md: every Exec on the app's
  lock namespace, Exec.lock_query(prefix=""), idle_timeout's lock-wait
  rule and its kill message, scheduler/async_scheduler
  set_lock_manager(app).
- ARIADNE.md: the init lane on the app's manager; it never waits.
- TESTING.md: the lock suites, CVC_STATE_EXEC_CHECK, CVC_EXEC_FUZZ and
  detail::set_lock_fuzz_seed, CVC_LOCKS_SANITIZER,
  CVC_LOCKS_MODEL_BOUND and _COALESCE, the sanitizer jobs' required L3
  cases, and locks-deep.yml's lanes and Linux lock.cross_thread record.
- STATE_EXEC_LOCKS.md: L3's status, and 11.3, the frame for
  lock.cross_thread's numbers and the sharding decision.
- STATE_EXEC_THREADED.md 2.4: the locks track row.
- tools/locks_model/README.md: one paragraph reflowed.
- pycvc-gl-cp312 build-wasm.sh: the link-host failure message names the
  node smoke, which can fail since L3.6.
…first home, the idle rule over every lock wait, a posted grant is pending, threaded_host_attach)
… follow the L3 review fixes

The no-threads smoke now attaches through the same helper pycvc's Exec uses, so a change to that attach is checked on every PR. The docs say what the review fixes changed: set_lock_manager(app) attaches only a scheduler's first lock home; the idle rule counts a lock wait of any of the Exec's processes, and a post in its port is pending work; the kill message's form for a spawned waiter; a refused set_lock_manager keeps the scheduler's home; has_lock_home().
Second-round review fix (L3). pycvc's idle rule calls blocking_sinks once
per lock-waiting process every idle pass; each call searched on its own
and successors() walks key queues, so n waiters cost about n^3 a pass
and n acquisitions of M.mu.

- lock_table::blocking_sinks(std::span<const lock_pid> from): one
  breadth-first search from every source under one M.mu hold, each
  process visited and its successors computed once; every sink reachable
  from a source that is not itself a source, with its home's progress,
  sorted by pid. The single-pid overload is that search from one source.
- lock_home::blocking_sinks(std::span<const int> pids): the same for
  several of the home's pids.

Tests (state_exec_locks_model_test): LockTable.
BlockingSinksFromSeveralWaiters (equal to the union of the single-pid
results less the sources on a chain, two shared holders, a FIFO queue of
300 waiters on one key (the holder alone), sources that wait for each
other, and sources that include a sink) and LockHomes.
BlockingSinksOfSeveralWaitersOfAHome (through a home in each mode, with
the holder's home's progress).
Second-round review nit (L3). Home ids come from a counter since
05df939, and a home_id has 32 bits: at the wrap the next id could equal
a live home's, and the entries' binary search assumes ascending ids. The
counter is now 64 bits, and attach_home refuses with std::logic_error
once every 32-bit id has been handed out, changing nothing.
lock_table::options::first_home (test-only) starts the count elsewhere.

Test (state_exec_locks_model_test): LockTable.HomeIdsNeverWrap (from
2^32 - 2: two homes get the last two ids, the next attach is refused,
also after a detach; the last id locks and releases as any other).
Without the refusal the third attach wraps to id 0.
…l; protocol 5.4 and 5.6 follow the review fixes

The restored no-argument app::lock_manager_locked() logged the mode-choice warning while _execSchedulerMutex was held, but log() is an interruption point and can fire data signals whose slots call back into the app. It now keeps the warning, and the next lock_manager() or exec_scheduler() call logs it after unlocking.

Protocol 5.4: a lock_enter frame unwound with its ticket set may find it granted by another home; the grant is released at once. 5.6: the implementation ends every process that ever reached the manager, a superset of the exact test.
Second-round review nit (L3). 54c0e8d delivered the cancel's notes in
release_frame's defensive path only after the resume and any release, so
an exception from either would have lost the wakes of the waiters the
cancel let in. They go right after the cancel again (an error delivering
them doesn't stop the resume), then the resume, then any release with
its own notes. (A release follows only a cancel that found the ticket
granted, which emits no notes, so in practice only a failing resume
could have lost them.)

Test (state_exec_locks_model_test): LockHomes.
UnwoundWaitDeliversTheCancelsNotesFirst (the cancel lets another home's
waiter in; the cross_home_note hook sees the unwinding ticket still
there, not yet resumed, when that wake goes out; failed before the fix).

Also: LockTable.BlockingSinksFromSeveralWaiters' FIFO case has 100
waiters, not 300; its reference (one single-pid search per waiter) is
cubic and took 1.7 s in Release.
pycvc's idle rule needs the lock-waiting processes on every idle pass,
and list_processes() builds a process_info for every process to find
them. Both schedulers gain, beside has_lock_home():

- lock_waiting_count(): the process table's own count of the processes
  parked on a with-lock request (0: nothing to look for);
- lock_waiting_pids(out): clears `out` and appends their pids in pid
  order. The table counts the waiters but keeps no list of them, so it
  walks the processes, only while the count is not zero, and stops once
  it has found them all.

Test (SchedulerLockPort.ListsItsLockWaiters, both scheduler types): no
waiter and an emptied list before; two waiters behind a holder parked on
a message, listed in pid order; none once both are granted and done.
The model follows protocol 5.4 as the L3 review fix rewrote it (X's
54c0e8d, cd05cc0's text): in the defensive path, a lock_enter frame
unwound with its ticket still set, the cancel's notes are delivered at
the cancel; then the resume, which from L3 may return a grant another
home made meanwhile, and that hold is released as any lock_enter
frame's grant is, and the release's notes delivered.

- world.py and the C++ world: the cancel's notes go out before
  defensive_resume, as before; defensive_resume releases a returned
  grant and delivers the release's notes.
- No configuration reaches the path: a lock_enter frame unwinds only
  from a running process, after its wake was collected. A raise into a
  parked waiter (wraise) is an action for directed checks, never
  enabled, so every state count and trace is unchanged.
- LocksModel.TwoHomesUnwoundWaitGrantedByAnotherHome: p2's ticket
  granted by H0's release, its wake in H1's port, then its frame
  unwound: the hold is released, p3 granted, the late wake ignored.
  TwoHomesMutationUnwoundWaitDropsGrant runs the reading before the
  fix (the grant dropped) and must report I3.
Both schedulers collect a pass's lock expiries in lock_expired_, raw
process pointers that wait_expired clears only when it returns. When
wake_due or wait_expired threw (an allocation, a delivery callback) the
list kept them; the next pass appended to it, and a process reaped in
between was read after it was freed.

The expiry pass (step_once on the sync scheduler, drain on
async_scheduler) now catches, empties the list and rethrows. Before
emptying it, keep_lock_expiries flags the lock waiters the pass had not
yet timed out (lock_expired_pending, the table's own record, which drops
an ended process), so the next wait_expired times them out as the old
list would have, with no raw pointer kept across passes. The normal path
is unchanged.

Test (SchedulerLockPort.AThrowingWaitExpiredKeepsNoStaleExpiry, both
scheduler types): two homes on one manager; B's waiter b1 times out, its
cancel grants a waiter on A, and the lock_test_hooks cross_home_note
hook throws on that note, so B's step throws mid-pass. Kept, b1 is timed
out by the next expiry pass (b2's); killed and reaped first, the next
pass runs over no freed process (the case ASan reports on the old
code), b2 times out, and the tables and the manager check clean.
…never wrap; an unwound wait delivers its cancel's notes first
Skeptic pass over 327c991. run()'s idle rule ran every idle pass
(about every 50 ms): list_processes() (a process_info per process), then
blocking_sinks once per lock-waiting process, each an unbounded search,
so an Exec with n waiters on one key behind another Exec cost about n^3
a pass, with the GIL held and n holds of the shared mutex.

Now the rule is skipped while lock_waiting_count() is 0; otherwise
lock_waiting_pids() fills a vector reused across passes, and one
multi-source blocking_sinks over it (one search, one hold of the
mutex) gives the sinks, read with the same window rule. The kill
message's choice is unchanged (run()'s own lock wait, else another
waiter's), read only when killing.

test_lt07c_many_spawned_waiters: 200 spawned waiters (50 under the
sanitizers) on one key behind another Exec's holder that steps for
2 s: every one granted after the release, the Exec never killed, the
time printed.
The multi-source form pycvc's idle rule now uses: one search from every source under one M.mu hold, reach(S) less S with no edge out.
857da44 kept the lock waiters a throwing expiry pass had not timed out
by flagging them (lock_expired_pending). But wake_due had already spent
their deadlines, and the flagged ones are collected only by a
wait_expired, which runs only when a later pass has a lock expiry of its
own: with no other lock waiter expiring on the scheduler (only a
sleeper's timer following, say), a kept waiter stayed parked until
granted, killed or idle-killed.

keep_lock_expiries(now) now gives each kept waiter a lock_deadline due
at the pass's own time and re-heaps it (process_table::update), so the
next timer pass expires it the normal way, whatever else is due then.
It stays inside the timer branch: nothing new per step. A process ended
meanwhile leaves the heap with its timer.

Allocation failures can still lose an expiry: a bad_alloc in wake_due
between a waiter's deadline reset and its push_back onto the list, or
while keep_lock_expiries re-heaps one (swallowed there, so the pass's
own exception is the one reported). That waiter then waits until a
grant or a kill.

Test: SchedulerLockPort.AThrowingWaitExpiredKeepsNoStaleExpiry gains a
third case, both scheduler types: b1's pass throws with a 0.5 s sleeper
as the only other timer on B; b1 still times out ("timeout") and the
sleeper finishes ("slept"). The b2 and reaped cases are unchanged.
# Conflicts:
#	src/cvc/tests/ariadne_runtime_test.cpp
Two windows on 2026-11-01, neither quiet enough for a timing verdict.
Steps are unchanged everywhere. lock.cross_thread's mutex counters show
the disjoint shortfall at t = 4 comes from each lock's hold time on M.mu
(the per-lock cost), so sharding stays closed until L1's speed and a
quiet rerun.
From locks-deep.yml's stress lane on perf/locks-l3 (run 41340188915):
disjoint 3 us sections at 0.83 of unlocked at t = 4 on a 4-vCPU runner,
hot-key handoff p50 11.6-11.8 us at t = 4 (design: 20 us).
A new developer-guide section tables every host and Ariadne lane: the
scheduler class (fixed in code), its policy source, its lock home and
thread, and when each state_exec.* setting is read (once, at build).
ARIADNE.md says which lane runs on what, and why ari runs round_robin
with a single lock manager. APP_API.md covers exec_scheduler(),
exec_async_host() and lock_manager(); CLI_GUIDE.md says cvc exec runs a
sync round_robin scheduler.

Corrected: app.h's exec_scheduler() comment and the roadmaps put init:
on the app scheduler (it runs on a private sync one); the roadmaps said
only async_stackless_evaluator is scheduled; ARIADNE.md's frame budget
is 30 ms, not 10; the bench's rr is a bench-only name; the lock mode is
also fixed by exec_scheduler(); the threaded design's notes on Exec's
wait and B29 are brought up to date.
package-macos timed out LT-3b at ctest's 300 s on most runs of this
branch: 10^4 runs took 228-300 s in Release there (about 25 ms a run),
against 12 s on Linux and 6 s on Windows. The test's spins, the
dropper's wait and libc++'s std::barrier all call sched_yield, and on
macOS that gives up the core for up to a 10 ms quantum while other
threads are runnable, as they are under ctest's parallel run.

Unless CVC_LOCKS_LT03B_RUNS sets the count, the runs now stop at 90 s,
and the test fails below a twentieth of them. Linux, Windows and the
sanitizer jobs finish their 10^4 well inside the budget.
@transfix
transfix merged commit 3320f18 into master Nov 3, 2026
46 of 49 checks passed
@transfix
transfix deleted the perf/locks-l3 branch November 3, 2026 18:44
transfix added a commit that referenced this pull request Nov 4, 2026
…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.
transfix added a commit that referenced this pull request Nov 7, 2026
…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)
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