Repository navigation
state_exec locks L1: with-lock on one scheduler (in progress) - #862
Merged
Merged
Conversation
… the locks deep workflow The state_exec lock work (docs/STATE_EXEC_LOCKS.md) adds code that runs on several threads, and no CI lane ran a race detector or an address checker. This lands them before any lock code, so that the races and leaks already in the tree get a baseline first. - ci.yml `sanitizers` (tsan, asan-ubsan): gcc's -fsanitize=thread, or -fsanitize=address,undefined, over libcvc itself (the cvcpkg deps stay uninstrumented), RelWithDebInfo, building only the targets it runs. It runs the existing suites that use threads (state_exec_scheduler, _async, _integration and _coordinator tests, ariadne_runtime_test, thread_pool_test, async_lane_test) and pycvc's exec scripts, with the sanitizer runtime preloaded into the interpreter. Suppressions go in .github/sanitizers/, each with a comment naming what it hides. Each lock phase appends its suites. - ci.yml's pull_request filter takes perf/** as well, so the lock phases' stacked drafts get the full set of jobs. - locks-deep.yml (daily, and by hand on a branch): a Release Linux build of the lock test targets, running their deep sizes. A dispatchable workflow must be on the default branch, so it lands first; on a ref without the lock tests it stops after the checkout.
…s, gate, and policy/locks sweep keys The state_exec lock phases decide their gates with the bench, and the design's gates need things compare could not do: two points of one run against each other, absolute bounds, a noise rule that refuses to judge a disturbed run, and a rule under which a drop in steps_total fails. tools/bench/state_exec_bench.py: - key_of leaves out a param at its implicit default (policy=rr, locks=none), so records from binaries without those keys still match. - compare --pair KEY=A:B compares the base's points at A with the candidate's at B, matched without KEY (both may be one run). - compare --max-noise P: a point noisier than P% is INCONCLUSIVE (exit 2, "repeat in a quieter window", never a pass). - compare --fail-on-change: any change beyond the noise fails, in either direction, for steps_total. - gate RUN --scenario --metric (--max|--min) [--stat] [--where] [--max-noise]: absolute bounds on one run. state_exec_bench: sched.single.*, flood.small and msg.* take two sweep keys, policy (rr, priority, priority_rr) and locks (none; the lock phases add private and shared, and a build without them skips such a point). A default run measures the same points as before, plus the two params at their defaults. tools/bench/test_state_exec_bench.py tests the rules on synthetic records; CTest runs it as state_exec_bench_tool_test when a working Python 3 is found.
Atomic single-node updates for the DSL's state-cas, state-swap and state-incr (docs/STATE_EXEC_LOCKS.md 4.4). Each compares, or computes, and assigns under one hold of the written node's mutex, then fires valueChanged and the parent's child signal with no lock held, only when the value changed. They write the node a read through a transparent link sees: a writable transparent link writes its target, as value(v) does. Unlike value(v), a transparent link that is not writable, or cannot be resolved, throws read_only_error rather than taking the write on the link node, so a compare and its write are always on the same node (gap G-7). Three non-virtual members and one private helper, so state.h stays source- and layout-compatible. pycvc wraps compareAndSetValue and exchangeValue; updateValue takes a std::function and is %ignore'd.
…-incr detail::read_number_text reads a token as the DSL does: the whole token as an int64, else as a double (strtod, for a token that may be one). The parser's parse_number_or_symbol now calls it, unchanged in behaviour, and state-incr will read a node's text with it, so both agree on what a number is (gap G-9).
The atomic natives of docs/STATE_EXEC_LOCKS.md 4.4, each one native call over cvc::state's atomic members: - (state-cas path expected new): #t when the value equalled `expected` and is now `new`. A nil expected matches an absent or "" node; an absent node is made only then. - (state-swap path new): the value it replaced, nil when absent or "". - (state-incr path [delta]): the new number. The node's text is read as a DSL number (detail::read_number_text); an absent or "" node is 0; anything else is a ValueError and the node is left as it was. int + int stays an int (an overflow is an ArithmeticError, gap G-11); otherwise the sum is a float, stored in its shortest round-trip form. Each resolves its path under the chroot and through a transparent link as state-get reads it; nil is "", a list or dict is a TypeError. A change fires watches and valueChanged once; an equal write fires nothing. Floats are written with std::to_chars where the library has it, else by detail::format_number_shortest_fallback, which writes to_chars's exact text (shortest round-trip digits, fixed or scientific, the exact digits of a whole number in fixed form). It is built everywhere, and a test checks it against to_chars byte for byte (gap G-10). Tests: state_exec_locks_test (new; the Atomics suite AT-1..AT-13 on both schedulers, AT-6's two-thread updateValue, the formatter against to_chars on a table and 20000 values; the locks_world fixture the lock phases reuse), and test_pycvc_state_exec_locks.py. Both join C0's sanitizer jobs.
state-incr and state-cas timed against state-set by the native.* method, on a node 1 or 4 levels down that starts at 0 and must end at n: op=set is (state-set P (+ i 1)), op=incr (state-incr P), op=cas (state-cas P i (+ i 1)), which succeeds and writes every time (gap G-8). Its gate, a paired one: incr and cas each at most 1.1x set in extra.ns_per_call (docs/STATE_EXEC_BENCH.md).
The developer guide's DSL state section gains state-incr, state-cas and state-swap: paths and links, absent nodes, nil, number text, signals, and which tool to use when. Ariadne's reactive lane does not bind them (they write). STATE_EXEC_LOCKS.md's status: L0 built.
…nager's interface Phase L1's interface commit (docs/STATE_EXEC_LOCKS.md, locks plan L1.1 and I1). - Three built-in exception classes: LockError (a RuntimeError), DeadlockError (a LockError) and PermissionError (an Exception), with BuiltinClasses.LockClasses and their rows in STATE_EXEC_EXCEPTIONS.md 2.3. - lock_manager.h (public): lock_mode, lock_threading, lock_info, lock_waiter_info, lock_query_result (gap G-13), lock_stats in full (gap G-35), and lock_manager, a pimpl over the table. Shared mode throws until phase L3; CVC_STATE_EXEC_CHECK=1 forces self-checks on (gap G-4). - detail/lock_table.h: the protocol's operations (sections 4.4-4.15), one member each; the request, key-cache and notification types; the trie node's layout; lock_violation; the test-only mutation bits the model check needs; the test hooks, reached through exported functions (gap G-4); and the canonical dump's format, which the real table and the model test's spec oracle both write. The table's operations are stubs that throw until L1.2.
The process carries the lock home's private state (protocol 2.2): `locks` (null until the process first locks), `lock_waiting`, `lock_deadline`, `inherited_priority` (written only by a relevel, phase L2), `lock_expired_pending`, and `effective_priority()`. The process table counts lock waiters (the sync scheduler's has_runnable will read it) and keeps a lock wait's deadline as a timer. wake_due hands an expired lock wait to the lock home instead of readying it: appended to the caller's vector, or, with none, flagged and counted for take_lock_expired, so a flagged waiter is collected by the next wait_expired (design 8.7). The spent deadline leaves the heap for good. The run-queue level goes through level_key(), which phase L2 switches to the effective priority. check() covers the new counts and flags. Tests: ProcessTableTest.LockDeadlineIsClearedAndNotRepushed, LockExpiryWithoutVectorIsFlaggedAndCounted, TakeLockExpiredCollectsFlagged, WakeDueCountsUnchangedWithoutLockWaiters, CheckSeesLockWaiters.
The home actions of protocol section 5 (docs/STATE_EXEC_LOCKS_PROTOCOL.md), in detail/lock_home.h and lock_home.cpp, and the hooks both schedulers give them. No DSL reaches a home yet (with-lock is bound in the next commit), so every existing path is unchanged: process::locks stays null and every hook tests it first. lock_home: - the mirror (mhold, process_locks) and the private state of protocol 2.2; - try_enter: the handler rule, the upgrade refusal and covered requests on the mirror, then the fast path, with the mirror's slot reserved before the grant; - wait, collect and apply_wake (the outcome kept in the lock_enter frame); - release_frame with its defensive withdraw, process_ended, wait_expired (adopting a grant that beat the timeout), set_base, deliver; - the key cache (design 8.4): a fixed array of entries indexed by (scope, key as written), CLOCK eviction that never takes the request's own entries, each entry one key-cache reference of the home, the reference taken by the request's own table call; - check_quiescent: the home-side clauses of I2, I3, I4, I6 and I8's base clause; the destructor detaches and clears every process's lock fields. Schedulers: set_lock_manager, locks() (a private manager on first use), check_tables(), a destructor that drops the home first; the end hooks in terminate/kill/fail_process before on_complete; lock expiries collected inside the existing timer branch (a program with no timer pays nothing); the sync scheduler's has_runnable counts lock waiters; fork refuses a holder and copies owner (td B28); restore clears every lock field; set_priority keeps the manager's base (I8). scheduler_base gains locks() and check_tables() as non-pure virtuals. eval_phase gains lock_enter and lock_body (pycvc's enum and the codec's names with it), with stub steps until the next commit; evaluator_state gains in_generator. lock_table declares the read-only views the home's checks use; their bodies come with the table (L1.2).
Implements detail::lock_table, the manager of docs/STATE_EXEC_LOCKS_PROTOCOL.md sections 2-4 and 6, one member function per protocol operation, observationally identical to tools/locks_model/lockmodel.py's Manager: same results, the same notifications in the same order, the same state. The structures are those of protocol 2.4. A path trie holds one node per key with a hold, a queued ticket, an abandoned flag or a key-cache reference, and every proper prefix of such a key; each node keeps the holds and queued tickets on its key and the subtree counts sub[m] and subw. Conflicting holds and waiters are found by the root-to-key walk and a descent guided by those counts, never by a scan of every hold or ticket. The queue is an intrusive list in seq order. Records, holds and tickets come from slot pools found through open-addressing indexes, and a record goes back to its pool as soon as its process has no hold and no ticket, so an uncontended try_acquire and release on cached nodes allocates nothing once the pools have grown. The owner is copied only when a record is made. Trie nodes that may have emptied are freed when the operation ends, so a region being re-examined stays valid. re_examine collects the queued tickets that overlap the region through the trie, tests them in seq order and posts a wake for each grant, and does nothing when no queued ticket overlaps. block detects deadlock exactly by reachability from its blockers, and its cycle is the depth-first path the protocol specifies, with each edge's key captured as an absolute string and a pid shown only for a process of the requester's home and owner. query, the key-cache references, detach_home, the counters of lock_stats and the canonical dump are all here. Phase L1 has no inheritance: relevel_all is the protocol's "lending false before and after" case, and attach_home refuses a priority home while inheritance is on. Before L3 a manager accepts one home. With options::self_check on, check() runs after every operation and asserts the manager's clauses of section 6 from their definitions, recomputing every trie count; each grant asserts I1, I5 and I15, and each grant test compares the trie's enumeration with the definition. Debug builds assert the single-mode owner-thread token on every call. The test mutations change the behaviour exactly as the model's do, and plant_divergence leaves the first grant a release makes out of the grants count. lock_table also gains read views of a record, a ticket, a hold and a home's key-cache references, for lock_home's quiescent check. The LockTable suite drives the table directly on one home: the manager-level shapes of LK-3, LK-4, LK-8, LK-19 to LK-22, LK-25 to LK-28, LK-32, LD-1 to LD-4, LD-7, LD-9 and LD-10, emptiness after every end and after a detach, key-cache references, query, abandoned-flag conservation, the canonical dump of known states, the counters, and every mutation.
Locks plan L1.6-L1.11 (docs/STATE_EXEC_LOCKS.md 4.1, 5, 8.5; protocol 5).
- lock_intrinsics.cpp binds with-lock (a lock_ops object: the context it was
registered with), locks-held, lock-query and %lock-wait, and resolves keys
as written: segments trimmed, empties dropped, '' or '#' a ValueError, a
leading '/' app-global where a '/' channel is allowed (else PermissionError,
gap G-15), anything else under the chroot. register_intrinsics calls it.
intrinsics_context gains lock_default_timeout and lock_wait_allowed.
- The stackless evaluator recognizes the form by its binding (a user's
defun, macro or set of the name wins). Options are read first, so a bad one
is a ValueError before the manager sees anything (I13). KEY and :timeout are
inline when literals or symbols. The frame's layout is made before the
grant, :as scope and value included, and the grant only fills them in; the
fast path costs the steps of (begin ...). Busy: :if-available runs :else
holding nothing; a :timeout of 0 or a context that forbids waits raises
TimeoutError; otherwise the frame waits in lock_enter on a %lock-wait child,
applied through the frame's own lock form with the lock-enter token armed.
Every unwinder (unwind_exception, unwind_jump, fail_step) releases a lock
frame before it pops it, so the order with finally is LIFO. A generator's
state refuses (LockError "generator"); a step outside a process refuses
("no process").
- A restored waiter's wait is applied again through the lock form below it,
re-resolved from with-lock in its environment (gap G-41); none there is a
LockError "restore" (gap G-44).
- The codec: the lock_ops binding is skipped like a native and rebound by
rebind_natives; a lock_ops value has no payload and decodes as nil; a lock
wait's handle is written as nil (gap G-1); the lock phases have names; a
holder's snapshot is refused, naming its keys (gap G-16); a parked waiter's
TIMEOUT is written as what is left of it.
- restore refuses a stack holding a lock (LW-12).
- The recursive evaluators refuse with-lock (TypeError "with-lock needs a
scheduler").
- (fork) forks the running process (td B28) and refuses inside with-lock.
- process_info gains locks_held and waiting_on ("lock /key", "msg c",
"sleep", "frame"); inspect shows them, a lock key relative to the caller
(gap G-17); pycvc's process_info has both.
- builtin_generator marks its state in_generator.
- app::lock_manager(): the app's with-lock table, made on first use (single mode in phase L1); exec_scheduler() attaches its home to it when it builds the scheduler (design 8.4). - Ariadne: the init lane never waits for a lock (a busy request is as :timeout 0), and an action's with-lock with no :timeout gives up after ariadne.exec.lock_timeout seconds (default 1.0; design 14.2 Q1).
# Conflicts: # inc/cvc/state/state_exec/detail/lock_table.h # src/cvc/state/state_exec/lock_manager.cpp
A first pass over the lock form: a section's value and locks-held, a waiter parked and granted on release (inspect's waiting_on), a deadlock raised in the request that closes the cycle, a timeout (never early), :if-available and :timeout 0, the option errors, a covered nested request, the upgrade refusal, and :as. The locks_world fixture gains step_until, and run() waits for its own process only.
…ntext fields A with-lock binding registered from Python is a lock_ops copy that keeps the intrinsics context and its Python owner alive (LK-23); it stays a lock_ops object, so the evaluator and a restored wait still find it (gap G-41). intrinsics_context exposes lock_wait_allowed and lock_default_timeout (a float or None).
…model suite in the sanitizer jobs state_exec_wasm_smoke (CVC_BUILD_STATE_EXEC_WASM_SMOKE, off by default) is a plain main() that runs a section, a holder and a waiter granted on release, and an empty lock-query on both schedulers, and prints STATE_EXEC_WASM_OK. ci.yml's ari-wasm job, which builds without pthreads, builds and runs it under node and fails unless it exits 0 with the marker; its path filter now includes the state directories, so a lock-only PR still runs the job (locks plan L1.12, R-7). state_exec_locks_model_test joins the sanitizer jobs.
The developer guide gains a section on with-lock (the form and its options, keys and chroots, waiting and where waits are refused, release, abandoned, deadlocks, the reads, fork and snapshots, the hosts), a note that with-lock is a soft form, and DSL (fork). STATE_EXEC_EXCEPTIONS.md: a kill releases locks without unwinding; holders can't be snapshotted, waiters requeue. STATE_EXEC_GRAMMAR.md: with-lock needs no grammar. ARIADNE.md: the reactive lane has no with-lock, actions' lock timeout, the init lane never waits, actions' fork. The protocol's and the design's status lines, B28 landed, and pycvc's lock context fields.
The model check of locks plan L1.3, test LT-5, written from docs/STATE_EXEC_LOCKS_PROTOCOL.md and tools/locks_model/ rather than from the table's code. state_exec_locks_model_test.cpp ports lockmodel.py's Manager as a spec oracle, world.py as a world of homes, processes, frames, key caches and posts, and explore.py as a 0-1 BFS explorer over fingerprints of the world's state. Every manager operation runs on the oracle and on the real detail::lock_table, driven as a lock home drives it (cached nodes, references taken on a miss, evictions); the results, the notification lists and the two canonical dumps must agree before both check()s and the world's home-side and transition invariants run. States over the real table are rebuilt by replaying their paths. On the oracle alone and with the Python model's FIFO cache, the explorer reproduces explore.py's counts of states and transitions for l1, for l1 with signals and foreign calls, and for the two-home core configuration; the default cache pins a request's own entries as the implementation does. Suite LocksModel has the bounded exploration, random runs, the scenarios of scenarios.py that L1 can run (LX-10 and LX-11 on two homes), the eight L1 mutations, each reporting exactly its violation, the replay of the Python model's traces, and a divergence planted in the table that the lockstep must catch. Suite LocksModelStress has the deep sizes. tools/locks_model/export_traces.py writes those traces, committed under src/cvc/tests/data/locks_model_traces/, and the model's README describes the C++ check, its sizes and the measurements behind them.
… the grant
LX-8 (Locks.LX08_ErrorsBeforeAndAfterTheGrant) injects an error into the step that
grants a with-lock at once, through lock_test_hooks::after_grant. The hook ran inside
lock_home::try_enter, right after the grant joined the mirror and before the frame
became lock_body with its hold id. fail_step then popped a frame that was still in its
init (or key-evaluating lock_enter) phase, so release_lock_frame found nothing to give
back: the hold outlived the failed step, the program went on holding the lock after
catching the error, and only the process's end released it (counted as leaked at exit).
The hook now runs in stackless_evaluator::lock_acquire once the frame records the grant,
the point the plan's risk note names ("the frame becomes lock_body with its hold id
before the body frame is pushed"), so the failed step's unwind releases it. The call in
collect (a grant after a wait) is unchanged.
locks=private gives a world's scheduler a single-mode lock manager of its own through set_lock_manager, attached before anything runs. The sched.single.*, flood.small and msg.* sweeps accept it now and still skip shared, which is phase L3's. Group M adds the lock scenarios of docs/STATE_EXEC_LOCKS.md 11.2, every world with its own manager: lock.uncontended (the native.* method against begin, with steps and allocations per lock from runs of n and 2n sections), lock.handoff, lock.rw, lock.many_keys, lock.bystanders, lock.timeout and lock.deadlock. Each checks its programs' results. docs/STATE_EXEC_BENCH.md describes each scenario, its extras and its gate. On this branch an uncontended with-lock adds no step but allocates once per lock form: the lock frame's results vector is never reserved (lock_body_begins), so allocs_per_lock is 1 for a one-form body and 2 for a nested section. The doc lists it among the known pathologies.
A cmake -P script runs lock.uncontended at n=2000 and sched.single.*, then the runner's gate: 0 steps and 0 allocations per lock on the form=single points, and steps_total pinned for sched.single.arith_loop (1080020 at n=40000) and sched.single.tail_rec (25020, 250020 and 2500020 at n=1000, 10000 and 100000), the same on both schedulers. It is registered where the runner's tool test is (a working Python 3), and only for Release and RelWithDebInfo, since MSVC's Debug STL allocates. The allocation gate fails on this branch until the lock frame reserves its results vector: 1 allocation per lock at every form=single point.
lock_body_begins never made room in frame.results, so the body's first hand_up grew the vector: every uncontended with-lock allocated once (twice when nested), which state_exec_bench_gates' zero-allocation gate caught. It now takes a recycled vector sized for the body, as begin does, and the gate passes at every depth, mode, chroot and owner on both schedulers.
…ngs as tests state_exec_scheduler_test, suite SchedulerLocks: the sync scheduler's has_runnable() counts lock waiters (async_scheduler's does not, as for message waiters); a bounded run left with only a lock waiter and no timer returns at once (design 6.1); run() waits for a sleeping holder's timer and the release grants the waiter; a run waits for a lock deadline and times the wait out. state_exec_locks_test: the review findings the lead is fixing on perf/locks-l1, each confirmed failing for its reason and skipped as known until that fix is merged: LK11b (a key-cache hit skips check_global: a cached /jobs is granted under a policy that doesn't declare it), LK14c (:timeout's symbol is read before a KEY call runs: NameError), LW07c (a restored lock frame whose lock form decoded as nil, mid-KEY or with a failed outcome, is dereferenced: an access violation), LW07d (a restored wait queues where the restoring context forbids lock waits).
…utlives its forks Since L1, (fork) forks the running process (td B28). Two bugs came with it. - The child copied the parent's stack in the middle of the fork call, so its first step called fork again: a runaway chain of forks. The child's copy of that call is now finished with 0, as hand_up finishes a call. - The child's frames still ran in the parent's scopes, so a set in either landed in both: (set c (fork)) left 0 in the parent's c. detail::fork_scopes copies every scope the child's frames run in, up to the global scope, and points the frames at the copies; the builtins above stay shared. Under Ariadne, an action's forked child shares the action's intrinsics context, which the drain freed as soon as the action ended (review R1c). intrinsics_context gains on_child, called with each forked child's pid. Ariadne records an action's children and keeps its context until they end too, reaping them then.
- A lock frame decoded from a snapshot reads its lock form from the restoring environment wherever the frame acts, not only on the wait path. Before, a frame restored while KEY or :timeout was being evaluated, or with a failed outcome, dereferenced a null lock_ops. With no with-lock there, it is LockError "restore" (G-44). - A restored wait follows the restoring context's rules: where no wait is allowed, or no time is left, the request is tried once and refused, as a first request is (protocol 5.1). - :timeout's symbol is looked up only once a call KEY has its value (left to right). - A '/' key found in the key cache is still checked against the requesting context's channel policy: the cache is keyed by chroot and text, not by policy (G-15). - A miss never evicts a cache entry that names one of its own keys' nodes through another spelling. Under self_check the table now reports such a drop as a 4.15 violation. The LocksReview suite covers each, and (fork) in a step.
std::stable_sort on libstdc++ takes a temporary buffer even for one element, so every uncontended with-lock allocated once on Linux and macOS (state_exec_bench_gates' zero-allocation gate failed there, while MSVC's insertion sort for short ranges hid it on Windows). A request has a few keys: an insertion sort, which is stable and allocates nothing, up to 16, and std::stable_sort above.
LK-18's programs drew a fresh random path for every key. Over a long run the paths used once filled the default key cache (1024 entries) and, with the abandoned flags left on them, grew the trie, so the manager's check() after every step slowed the run as it went: LocksStress at 10^5 operations had not finished one case after 40 minutes. The paths now come from a pool drawn once from the same 3-ary tree, 20 of each depth 1-8: requests meet at every depth, the default cache holds the whole pool and the cache of 4 evicts on most requests. Each LocksStress case now takes 2-5 minutes in Release. The summary line also prints the trie's size.
L1's test suites: Locks (LK, LX, LW, LD on both schedulers, on the checked driver), LocksStress, LockHome, LockCodec, the Ariadne and coordinator cases, SchedulerLocks and pycvc's. With the review fixes on this branch, the four known-bug skips go, as does the Ariadne fork skip. LW07c no longer expects a restored msg-recv to park again: a restored process doesn't re-arm one, so the copy may go straight on to its KEY. pycvc.i gains %naturalvar for process_info::waiting_on, so Python reads it as a string.
GCC refuses a `= {}` default argument whose type is a class nested in
the class being defined, when that nested class has default member
initializers: it isn't complete yet there. MSVC accepts it, so
state_exec_locks_test built on Windows and failed every Linux and macOS
lane. The struct is now checked_submit_options, before checked_world,
which names it submit_options as before. Also clang-format on one
changed line of ariadne_runtime_test.cpp.
…looks ASan's leak check failed state_exec_locks_test on 189 indirect leaks: default environments held by a closure bound in the scope it captured, a cycle only collect_cycles() frees. The tests step the schedulers by hand, so nothing ever collected. A gtest global environment now runs collect_cycles() at the end, when every world is gone, so the leak check sees only real leaks.
…e fits CI - home_world::request() built its KEY value as a local, and build_request keeps views into it, so try_enter read freed memory. TSan reported it, and on macOS and Linux it turned LockHome.EvictionAndRefs's keys into garbage. MSVC's stack happened to keep the bytes. The values now live as long as the world. - LK-18 checks every invariant after every step. A CI runner manages about 25 operations a second on the default cache, so 10,000 didn't fit its 240 s. The regular Release size is 3,000; LocksStress keeps the deep sizes.
# Conflicts: # src/cvc/tests/state_exec_locks_test.cpp
The before-terminate hook passed a temporary value_t to build_request, whose request views the key's text; ASan caught the read after the temporary died (LX06). Also move LK-18's sizing comment above the sanitizer branch, which clang-format otherwise indents as part of it.
…ug at 500 run.sh ran each sanitizer binary whole, so the TSan job ran LocksStress's four 10^5-operation cases (about 23 minutes each under TSan) and hit run_one's hour (#862: exit 124, no report). It now passes -*Stress*, as ci.yml's STRESS_REGEX keeps those suites off the PR lanes; locks-deep.yml runs them. Its LocksStress filter named LocksStress.*, which matches none of the parameterized Schedulers/LocksStress.* tests: fixed. LK-18's regular size in a Debug build was 2000 operations, 150-240 s on CI runners against ctest's 300 s, and over it on a loaded one (#862's package-linux debug-grpc). Release does 3000 in 5-13 s; Debug is 25-50 times slower, so it now runs 500.
… for idle wait_pool_idle read getActiveThreadCount() and then getPendingThreadCount(), each under its own lock. A worker could take the last queued task between the two reads, so the pool looked idle while that task ran: AppPoolKeyed.AKeyedTaskWithRoomIsRegisteredOnReturnBehindAnonymousTasks saw 7 of 8 warm-up tasks done (#868's ubuntu Debug run). A task leaves the queue and counts as running under one lock and stops counting after its body, so reading the queue first can't miss one.
transfix
marked this pull request as ready for review
October 30, 2026 03:45
transfix
added a commit
that referenced
this pull request
Oct 30, 2026
transfix
added a commit
that referenced
this pull request
Oct 30, 2026
* ci: TSan and ASan+UBSan jobs over the threaded state_exec suites, and the locks deep workflow
The state_exec lock work (docs/STATE_EXEC_LOCKS.md) adds code that runs on
several threads, and no CI lane ran a race detector or an address checker. This
lands them before any lock code, so that the races and leaks already in the
tree get a baseline first.
- ci.yml `sanitizers` (tsan, asan-ubsan): gcc's -fsanitize=thread, or
-fsanitize=address,undefined, over libcvc itself (the cvcpkg deps stay
uninstrumented), RelWithDebInfo, building only the targets it runs. It runs
the existing suites that use threads (state_exec_scheduler, _async,
_integration and _coordinator tests, ariadne_runtime_test, thread_pool_test,
async_lane_test) and pycvc's exec scripts, with the sanitizer runtime
preloaded into the interpreter. Suppressions go in .github/sanitizers/, each
with a comment naming what it hides. Each lock phase appends its suites.
- ci.yml's pull_request filter takes perf/** as well, so the lock phases'
stacked drafts get the full set of jobs.
- locks-deep.yml (daily, and by hand on a branch): a Release Linux build of the
lock test targets, running their deep sizes. A dispatchable workflow must be
on the default branch, so it lands first; on a ref without the lock tests it
stops after the checkout.
* bench: compare --pair, implicit default params, noise and change rules, gate, and policy/locks sweep keys
The state_exec lock phases decide their gates with the bench, and the design's
gates need things compare could not do: two points of one run against each
other, absolute bounds, a noise rule that refuses to judge a disturbed run,
and a rule under which a drop in steps_total fails.
tools/bench/state_exec_bench.py:
- key_of leaves out a param at its implicit default (policy=rr, locks=none),
so records from binaries without those keys still match.
- compare --pair KEY=A:B compares the base's points at A with the
candidate's at B, matched without KEY (both may be one run).
- compare --max-noise P: a point noisier than P% is INCONCLUSIVE (exit 2,
"repeat in a quieter window", never a pass).
- compare --fail-on-change: any change beyond the noise fails, in either
direction, for steps_total.
- gate RUN --scenario --metric (--max|--min) [--stat] [--where] [--max-noise]:
absolute bounds on one run.
state_exec_bench: sched.single.*, flood.small and msg.* take two sweep keys,
policy (rr, priority, priority_rr) and locks (none; the lock phases add
private and shared, and a build without them skips such a point). A default
run measures the same points as before, plus the two params at their
defaults.
tools/bench/test_state_exec_bench.py tests the rules on synthetic records;
CTest runs it as state_exec_bench_tool_test when a working Python 3 is found.
* state: compareAndSetValue, exchangeValue and updateValue on cvc::state
Atomic single-node updates for the DSL's state-cas, state-swap and
state-incr (docs/STATE_EXEC_LOCKS.md 4.4). Each compares, or computes, and
assigns under one hold of the written node's mutex, then fires valueChanged
and the parent's child signal with no lock held, only when the value changed.
They write the node a read through a transparent link sees: a writable
transparent link writes its target, as value(v) does. Unlike value(v), a
transparent link that is not writable, or cannot be resolved, throws
read_only_error rather than taking the write on the link node, so a compare
and its write are always on the same node (gap G-7).
Three non-virtual members and one private helper, so state.h stays source-
and layout-compatible. pycvc wraps compareAndSetValue and exchangeValue;
updateValue takes a std::function and is %ignore'd.
* state_exec: one reader of number text, shared by the parser and state-incr
detail::read_number_text reads a token as the DSL does: the whole token as an
int64, else as a double (strtod, for a token that may be one). The parser's
parse_number_or_symbol now calls it, unchanged in behaviour, and state-incr
will read a node's text with it, so both agree on what a number is (gap G-9).
* state_exec: state-incr, state-cas and state-swap
The atomic natives of docs/STATE_EXEC_LOCKS.md 4.4, each one native call
over cvc::state's atomic members:
- (state-cas path expected new): #t when the value equalled `expected` and
is now `new`. A nil expected matches an absent or "" node; an absent node
is made only then.
- (state-swap path new): the value it replaced, nil when absent or "".
- (state-incr path [delta]): the new number. The node's text is read as a
DSL number (detail::read_number_text); an absent or "" node is 0; anything
else is a ValueError and the node is left as it was. int + int stays an int
(an overflow is an ArithmeticError, gap G-11); otherwise the sum is a float,
stored in its shortest round-trip form.
Each resolves its path under the chroot and through a transparent link as
state-get reads it; nil is "", a list or dict is a TypeError. A change fires
watches and valueChanged once; an equal write fires nothing.
Floats are written with std::to_chars where the library has it, else by
detail::format_number_shortest_fallback, which writes to_chars's exact text
(shortest round-trip digits, fixed or scientific, the exact digits of a whole
number in fixed form). It is built everywhere, and a test checks it against
to_chars byte for byte (gap G-10).
Tests: state_exec_locks_test (new; the Atomics suite AT-1..AT-13 on both
schedulers, AT-6's two-thread updateValue, the formatter against to_chars on
a table and 20000 values; the locks_world fixture the lock phases reuse),
and test_pycvc_state_exec_locks.py. Both join C0's sanitizer jobs.
* bench: native.state_atomic
state-incr and state-cas timed against state-set by the native.* method, on a
node 1 or 4 levels down that starts at 0 and must end at n: op=set is
(state-set P (+ i 1)), op=incr (state-incr P), op=cas (state-cas P i (+ i 1)),
which succeeds and writes every time (gap G-8). Its gate, a paired one: incr
and cas each at most 1.1x set in extra.ns_per_call (docs/STATE_EXEC_BENCH.md).
* docs: the atomic natives
The developer guide's DSL state section gains state-incr, state-cas and
state-swap: paths and links, absent nodes, nil, number text, signals, and
which tool to use when. Ariadne's reactive lane does not bind them (they
write). STATE_EXEC_LOCKS.md's status: L0 built.
* state_exec: LockError, DeadlockError and PermissionError; the lock manager's interface
Phase L1's interface commit (docs/STATE_EXEC_LOCKS.md, locks plan L1.1 and
I1).
- Three built-in exception classes: LockError (a RuntimeError),
DeadlockError (a LockError) and PermissionError (an Exception), with
BuiltinClasses.LockClasses and their rows in STATE_EXEC_EXCEPTIONS.md 2.3.
- lock_manager.h (public): lock_mode, lock_threading, lock_info,
lock_waiter_info, lock_query_result (gap G-13), lock_stats in full (gap
G-35), and lock_manager, a pimpl over the table. Shared mode throws until
phase L3; CVC_STATE_EXEC_CHECK=1 forces self-checks on (gap G-4).
- detail/lock_table.h: the protocol's operations (sections 4.4-4.15), one
member each; the request, key-cache and notification types; the trie node's
layout; lock_violation; the test-only mutation bits the model check needs;
the test hooks, reached through exported functions (gap G-4); and the
canonical dump's format, which the real table and the model test's spec
oracle both write.
The table's operations are stubs that throw until L1.2.
* state_exec: lock fields on process and the process table
The process carries the lock home's private state (protocol 2.2): `locks`
(null until the process first locks), `lock_waiting`, `lock_deadline`,
`inherited_priority` (written only by a relevel, phase L2),
`lock_expired_pending`, and `effective_priority()`.
The process table counts lock waiters (the sync scheduler's has_runnable will
read it) and keeps a lock wait's deadline as a timer. wake_due hands an
expired lock wait to the lock home instead of readying it: appended to the
caller's vector, or, with none, flagged and counted for take_lock_expired, so
a flagged waiter is collected by the next wait_expired (design 8.7). The
spent deadline leaves the heap for good. The run-queue level goes through
level_key(), which phase L2 switches to the effective priority. check()
covers the new counts and flags.
Tests: ProcessTableTest.LockDeadlineIsClearedAndNotRepushed,
LockExpiryWithoutVectorIsFlaggedAndCounted, TakeLockExpiredCollectsFlagged,
WakeDueCountsUnchangedWithoutLockWaiters, CheckSeesLockWaiters.
* state_exec: lock_home, and the schedulers' lock hooks
The home actions of protocol section 5 (docs/STATE_EXEC_LOCKS_PROTOCOL.md), in
detail/lock_home.h and lock_home.cpp, and the hooks both schedulers give them.
No DSL reaches a home yet (with-lock is bound in the next commit), so every
existing path is unchanged: process::locks stays null and every hook tests it
first.
lock_home:
- the mirror (mhold, process_locks) and the private state of protocol 2.2;
- try_enter: the handler rule, the upgrade refusal and covered requests on the
mirror, then the fast path, with the mirror's slot reserved before the grant;
- wait, collect and apply_wake (the outcome kept in the lock_enter frame);
- release_frame with its defensive withdraw, process_ended, wait_expired
(adopting a grant that beat the timeout), set_base, deliver;
- the key cache (design 8.4): a fixed array of entries indexed by (scope, key
as written), CLOCK eviction that never takes the request's own entries, each
entry one key-cache reference of the home, the reference taken by the
request's own table call;
- check_quiescent: the home-side clauses of I2, I3, I4, I6 and I8's base
clause; the destructor detaches and clears every process's lock fields.
Schedulers: set_lock_manager, locks() (a private manager on first use),
check_tables(), a destructor that drops the home first; the end hooks in
terminate/kill/fail_process before on_complete; lock expiries collected inside
the existing timer branch (a program with no timer pays nothing); the sync
scheduler's has_runnable counts lock waiters; fork refuses a holder and copies
owner (td B28); restore clears every lock field; set_priority keeps the
manager's base (I8). scheduler_base gains locks() and check_tables() as
non-pure virtuals. eval_phase gains lock_enter and lock_body (pycvc's enum and
the codec's names with it), with stub steps until the next commit;
evaluator_state gains in_generator.
lock_table declares the read-only views the home's checks use; their bodies
come with the table (L1.2).
* state_exec: the lock manager (single mode, one home)
Implements detail::lock_table, the manager of docs/STATE_EXEC_LOCKS_PROTOCOL.md sections 2-4
and 6, one member function per protocol operation, observationally identical to
tools/locks_model/lockmodel.py's Manager: same results, the same notifications in the same
order, the same state.
The structures are those of protocol 2.4. A path trie holds one node per key with a hold, a
queued ticket, an abandoned flag or a key-cache reference, and every proper prefix of such a
key; each node keeps the holds and queued tickets on its key and the subtree counts sub[m] and
subw. Conflicting holds and waiters are found by the root-to-key walk and a descent guided by
those counts, never by a scan of every hold or ticket. The queue is an intrusive list in seq
order. Records, holds and tickets come from slot pools found through open-addressing indexes,
and a record goes back to its pool as soon as its process has no hold and no ticket, so an
uncontended try_acquire and release on cached nodes allocates nothing once the pools have
grown. The owner is copied only when a record is made. Trie nodes that may have emptied are
freed when the operation ends, so a region being re-examined stays valid.
re_examine collects the queued tickets that overlap the region through the trie, tests them in
seq order and posts a wake for each grant, and does nothing when no queued ticket overlaps.
block detects deadlock exactly by reachability from its blockers, and its cycle is the
depth-first path the protocol specifies, with each edge's key captured as an absolute string
and a pid shown only for a process of the requester's home and owner. query, the key-cache
references, detach_home, the counters of lock_stats and the canonical dump are all here.
Phase L1 has no inheritance: relevel_all is the protocol's "lending false before and after"
case, and attach_home refuses a priority home while inheritance is on. Before L3 a manager
accepts one home.
With options::self_check on, check() runs after every operation and asserts the manager's
clauses of section 6 from their definitions, recomputing every trie count; each grant asserts
I1, I5 and I15, and each grant test compares the trie's enumeration with the definition. Debug
builds assert the single-mode owner-thread token on every call. The test mutations change the
behaviour exactly as the model's do, and plant_divergence leaves the first grant a release
makes out of the grants count.
lock_table also gains read views of a record, a ticket, a hold and a home's key-cache
references, for lock_home's quiescent check.
The LockTable suite drives the table directly on one home: the manager-level shapes of LK-3,
LK-4, LK-8, LK-19 to LK-22, LK-25 to LK-28, LK-32, LD-1 to LD-4, LD-7, LD-9 and LD-10, emptiness
after every end and after a detach, key-cache references, query, abandoned-flag conservation,
the canonical dump of known states, the counters, and every mutation.
* state_exec: with-lock, its waits, its frames and their snapshots
Locks plan L1.6-L1.11 (docs/STATE_EXEC_LOCKS.md 4.1, 5, 8.5; protocol 5).
- lock_intrinsics.cpp binds with-lock (a lock_ops object: the context it was
registered with), locks-held, lock-query and %lock-wait, and resolves keys
as written: segments trimmed, empties dropped, '' or '#' a ValueError, a
leading '/' app-global where a '/' channel is allowed (else PermissionError,
gap G-15), anything else under the chroot. register_intrinsics calls it.
intrinsics_context gains lock_default_timeout and lock_wait_allowed.
- The stackless evaluator recognizes the form by its binding (a user's
defun, macro or set of the name wins). Options are read first, so a bad one
is a ValueError before the manager sees anything (I13). KEY and :timeout are
inline when literals or symbols. The frame's layout is made before the
grant, :as scope and value included, and the grant only fills them in; the
fast path costs the steps of (begin ...). Busy: :if-available runs :else
holding nothing; a :timeout of 0 or a context that forbids waits raises
TimeoutError; otherwise the frame waits in lock_enter on a %lock-wait child,
applied through the frame's own lock form with the lock-enter token armed.
Every unwinder (unwind_exception, unwind_jump, fail_step) releases a lock
frame before it pops it, so the order with finally is LIFO. A generator's
state refuses (LockError "generator"); a step outside a process refuses
("no process").
- A restored waiter's wait is applied again through the lock form below it,
re-resolved from with-lock in its environment (gap G-41); none there is a
LockError "restore" (gap G-44).
- The codec: the lock_ops binding is skipped like a native and rebound by
rebind_natives; a lock_ops value has no payload and decodes as nil; a lock
wait's handle is written as nil (gap G-1); the lock phases have names; a
holder's snapshot is refused, naming its keys (gap G-16); a parked waiter's
TIMEOUT is written as what is left of it.
- restore refuses a stack holding a lock (LW-12).
- The recursive evaluators refuse with-lock (TypeError "with-lock needs a
scheduler").
- (fork) forks the running process (td B28) and refuses inside with-lock.
- process_info gains locks_held and waiting_on ("lock /key", "msg c",
"sleep", "frame"); inspect shows them, a lock key relative to the caller
(gap G-17); pycvc's process_info has both.
- builtin_generator marks its state in_generator.
* hosts: the app's lock manager, and Ariadne's lock timeouts
- app::lock_manager(): the app's with-lock table, made on first use (single
mode in phase L1); exec_scheduler() attaches its home to it when it builds
the scheduler (design 8.4).
- Ariadne: the init lane never waits for a lock (a busy request is as
:timeout 0), and an action's with-lock with no :timeout gives up after
ariadne.exec.lock_timeout seconds (default 1.0; design 14.2 Q1).
* tests: with-lock end to end on both schedulers (LocksSmoke)
A first pass over the lock form: a section's value and locks-held, a waiter
parked and granted on release (inspect's waiting_on), a deadlock raised in the
request that closes the cycle, a timeout (never early), :if-available and
:timeout 0, the option errors, a covered nested request, the upgrade refusal,
and :as. The locks_world fixture gains step_until, and run() waits for its own
process only.
* pycvc: register_intrinsics keeps the lock form's context; the lock context fields
A with-lock binding registered from Python is a lock_ops copy that keeps the
intrinsics context and its Python owner alive (LK-23); it stays a lock_ops
object, so the evaluator and a restored wait still find it (gap G-41).
intrinsics_context exposes lock_wait_allowed and lock_default_timeout (a
float or None).
* tests: clang-format state_exec_locks_test.cpp
* ci: state_exec_wasm_smoke, with-lock without threads under node; the model suite in the sanitizer jobs
state_exec_wasm_smoke (CVC_BUILD_STATE_EXEC_WASM_SMOKE, off by default) is a
plain main() that runs a section, a holder and a waiter granted on release,
and an empty lock-query on both schedulers, and prints STATE_EXEC_WASM_OK.
ci.yml's ari-wasm job, which builds without pthreads, builds and runs it
under node and fails unless it exits 0 with the marker; its path filter now
includes the state directories, so a lock-only PR still runs the job (locks
plan L1.12, R-7). state_exec_locks_model_test joins the sanitizer jobs.
* docs: locks on one scheduler
The developer guide gains a section on with-lock (the form and its options,
keys and chroots, waiting and where waits are refused, release, abandoned,
deadlocks, the reads, fork and snapshots, the hosts), a note that with-lock is
a soft form, and DSL (fork). STATE_EXEC_EXCEPTIONS.md: a kill releases locks
without unwinding; holders can't be snapshotted, waiters requeue.
STATE_EXEC_GRAMMAR.md: with-lock needs no grammar. ARIADNE.md: the reactive
lane has no with-lock, actions' lock timeout, the init lane never waits,
actions' fork. The protocol's and the design's status lines, B28 landed, and
pycvc's lock context fields.
* state_exec: interface for locks L1b and L2 (I-L1b/L2)
Declarations and stubs that L1b (spawn contexts) and L2 (priorities)
build on, per the locks plan's joint interface commit:
- execute_options: keep_alive, priority_floor, parent_pid; process
keeps them (execute() copies the floor, its explicit flag, the
parent and keep_alive).
- process_info effective_priority and priority_floor;
scheduler_stats priority_clamped.
- priority_info, priority_change, control_cmd, policy_from_state, and
the scheduler_base priority virtuals with default bodies; both
schedulers override them with stubs (get_priority and
set_priority_floor are real) and declare post_control (a stub).
- intrinsics.h: spawn_setup, intrinsics_context::spawn_context, and
make_spawn_context (a stub returning no callback).
- detail/priority.h: declarations only.
No behaviour changes: every existing suite passes.
* state_exec: the locks model check on one home (LT-5)
The model check of locks plan L1.3, test LT-5, written from
docs/STATE_EXEC_LOCKS_PROTOCOL.md and tools/locks_model/ rather than from
the table's code. state_exec_locks_model_test.cpp ports lockmodel.py's
Manager as a spec oracle, world.py as a world of homes, processes, frames,
key caches and posts, and explore.py as a 0-1 BFS explorer over
fingerprints of the world's state. Every manager operation runs on the
oracle and on the real detail::lock_table, driven as a lock home drives it
(cached nodes, references taken on a miss, evictions); the results, the
notification lists and the two canonical dumps must agree before both
check()s and the world's home-side and transition invariants run. States
over the real table are rebuilt by replaying their paths.
On the oracle alone and with the Python model's FIFO cache, the explorer
reproduces explore.py's counts of states and transitions for l1, for l1
with signals and foreign calls, and for the two-home core configuration;
the default cache pins a request's own entries as the implementation does.
Suite LocksModel has the bounded exploration, random runs, the scenarios
of scenarios.py that L1 can run (LX-10 and LX-11 on two homes), the eight
L1 mutations, each reporting exactly its violation, the replay of the
Python model's traces, and a divergence planted in the table that the
lockstep must catch. Suite LocksModelStress has the deep sizes.
tools/locks_model/export_traces.py writes those traces, committed under
src/cvc/tests/data/locks_model_traces/, and the model's README describes
the C++ check, its sizes and the measurements behind them.
* state_exec: spawn_context, make_spawn_context, and a context its process keeps alive
L1b.1 of the locks plan (td 4.15). spawn now gives the child its
parent's owner, always, so a host's kill_owner reaps it with its
parent. When the host installed a spawn_context, the child also gets
the environment and context that callback makes. The context rides in
execute_options::keep_alive and lives as long as the child's process
object. Without a callback the child keeps the bare builtins, as
before.
make_spawn_context is the ready-made callback for hosts that call
plain register_intrinsics. Each child gets a context copying the
parent's scheduler, root and chroot, tracker, identity, channel policy,
document, lock fields and the callback itself, so grandchildren get
one too. It also gets environment::extend(base) with the intrinsics
registered, then the host's after_register bindings.
SpawnContext tests cover the bare env, the chroot and channel key,
the owner (kill_owner), the context's lifetime (reap), grandchildren,
the copied fields and after_register.
* pycvc: an Exec's natives scope, and spawned children that see it
L1b.3 of the locks plan (td 4.15). An Exec now keeps its builtins,
intrinsics and registered functions in a natives scope, and runs
programs in environment::extend(natives). Top-level definitions still
persist across run(). Its context's spawn_context gives a spawned child
extend(natives) too, so the child calls the Exec's registered
functions; before, it got the bare builtins. The Exec's own context
serves the child: on one scheduler the intrinsics act for the running
process.
test_is02_spawned_child_calls_registered_function covers IS-2.
* state_exec: LK-24, spawned children lock under the parent's chroot
A parent chrooted at doc, whose context installs make_spawn_context,
spawns 8 children. Each runs 1000 sections of state-incr and a
read-modify-write that sleeps inside with-lock "q". On both schedulers
doc.q.n and doc.q.m come to exactly 8000, nothing lands under the
root's q, and the manager counts the waits (7999 here).
* state_exec: the after_grant test hook fires once the lock frame holds the grant
LX-8 (Locks.LX08_ErrorsBeforeAndAfterTheGrant) injects an error into the step that
grants a with-lock at once, through lock_test_hooks::after_grant. The hook ran inside
lock_home::try_enter, right after the grant joined the mirror and before the frame
became lock_body with its hold id. fail_step then popped a frame that was still in its
init (or key-evaluating lock_enter) phase, so release_lock_frame found nothing to give
back: the hold outlived the failed step, the program went on holding the lock after
catching the error, and only the process's end released it (counted as leaked at exit).
The hook now runs in stackless_evaluator::lock_acquire once the frame records the grant,
the point the plan's risk note names ("the frame becomes lock_body with its hold id
before the body frame is pushed"), so the failed step's unwind releases it. The call in
collect (a grant after a wait) is unchanged.
* docs: the spawn context on one scheduler
What a spawned child sees with and without a host's spawn context, and
make_spawn_context for C++ hosts (developer guide); B27's
single-scheduler part landed (threaded design); L1b built (locks
status).
* ariadne: spawned children of init scripts, actions and residents run with the document's context
L1b.2 of the locks plan (td 4.15). A child that an action or a resident
spawns now runs in a context of its own, built like theirs by the new
make_action_context: the app scheduler, the parent's chroot, the
document's channel policy and resource scope, the intrinsics, the
host's action intrinsic providers and has?, and the parent's lock
default and lock_wait_allowed. So an action's child gives up on a busy
lock after ariadne.exec.lock_timeout. The child's process keeps that
context alive, and the child keeps the document's owner, so ~Impl's
kill_owner reaps it with the document. Every ActionContext owner
(live_actions_, the resident slots) now holds a shared_ptr.
The init lane installs make_spawn_context with the providers and has?
as its after_register bindings. Its children copy lock_wait_allowed
false and the 0 default, so they never wait for a lock on the host
thread either.
New tests: SpawnContext.IS01_ActionChildMessagesAndWrites,
Locks.LK31_ActionChildTimesOutOnResidentsLock and
Locks.LW09_InitChildNeverWaits. ARIADNE.md describes spawned children,
and the off-allowlist paragraph moves back to the read lane, where it
belongs.
* bench: lock.* scenarios, and locks=private
locks=private gives a world's scheduler a single-mode lock manager of its
own through set_lock_manager, attached before anything runs. The
sched.single.*, flood.small and msg.* sweeps accept it now and still skip
shared, which is phase L3's.
Group M adds the lock scenarios of docs/STATE_EXEC_LOCKS.md 11.2, every
world with its own manager: lock.uncontended (the native.* method against
begin, with steps and allocations per lock from runs of n and 2n
sections), lock.handoff, lock.rw, lock.many_keys, lock.bystanders,
lock.timeout and lock.deadlock. Each checks its programs' results.
docs/STATE_EXEC_BENCH.md describes each scenario, its extras and its gate.
On this branch an uncontended with-lock adds no step but allocates once
per lock form: the lock frame's results vector is never reserved
(lock_body_begins), so allocs_per_lock is 1 for a one-form body and 2 for
a nested section. The doc lists it among the known pathologies.
* bench: state_exec_bench_gates, the deterministic lock gates in CTest
A cmake -P script runs lock.uncontended at n=2000 and sched.single.*,
then the runner's gate: 0 steps and 0 allocations per lock on the
form=single points, and steps_total pinned for sched.single.arith_loop
(1080020 at n=40000) and sched.single.tail_rec (25020, 250020 and 2500020
at n=1000, 10000 and 100000), the same on both schedulers. It is
registered where the runner's tool test is (a working Python 3), and only
for Release and RelWithDebInfo, since MSVC's Debug STL allocates.
The allocation gate fails on this branch until the lock frame reserves
its results vector: 1 allocation per lock at every form=single point.
* ariadne: reap spawned children once they finish
A spawned child's process keeps its context alive, and under Ariadne
that context is a whole action context: an environment with every
intrinsic registered. Ariadne reaped finished actions but never their
children, so an action that spawns on every click grew memory for the
life of the app.
spawn_setup gains an optional spawned(pid) callback that spawn calls
once the child is submitted. Ariadne records its children's pids
there. Its drain sweep reaps the finished ones, warning once for a
killed or failed one as it does for actions, and its teardown erases
them after kill_owner, since their contexts point into the Runtime.
SpawnContext.FinishedChildIsReaped covers the sweep; IS-1 now checks
that the teardown erases the parked child.
* state_exec: the lock body reserves its results, as begin does
lock_body_begins never made room in frame.results, so the body's
first hand_up grew the vector: every uncontended with-lock allocated
once (twice when nested), which state_exec_bench_gates' zero-allocation
gate caught. It now takes a recycled vector sized for the body, as
begin does, and the gate passes at every depth, mode, chroot and owner
on both schedulers.
* tests: with-lock on one scheduler: the Locks, LocksStress and LockHome suites
The L1 cases of docs/STATE_EXEC_LOCKS.md 13.2-13.5 on both schedulers, on a checked driver
that steps one process step at a time and after each step runs the manager's check(), the
home's check_quiescent() and the process table's check(), with CVC_STATE_EXEC_CHECK=1 set
before the first manager so every manager operation checks itself too.
- Locks (sync and async): LK-1..LK-34 (the L1 ones, LK-23's C++ twin included), LX-1..LX-11
(each run with the process queued and granted but not resumed), LW-1..LW-12 (the C++
ones; LW-11 is a plain test), LD-1..LD-4, LD-7, LD-9, LD-10. The test hooks go through
detail::set_lock_test_hooks only and are reset by every test that sets them.
- LocksStress: LK-18 at 10^5 operations, with the default key cache and with a cache of 4.
The regular LK-18 takes CVC_LOCKS_RANDOM_OPS, else 10^4 (Release), 2*10^3 (Debug) or
10^3 (CVC_LOCKS_SANITIZER).
- LockHome: a real lock_home over a fake lock_sched_ops that owns a process table, with
processes and frames built by hand: pinning, eviction and references, the stale wake,
the adopted grant, try_enter's mirror steps, the defensive withdraw, the destructor, and
wait_expired collecting a flagged waiter.
A DSL (fork) of a running process makes a child that forks again at its first step (its
copied stack still applies the call) and shares the parent's scopes; LW06 checks the child
before it steps, and LW10 forks from the host between steps.
* tests: lock frames in snapshots (LockCodec)
The codec's lock rules (locks plan L1.6, L1.7, L1.10): the lock phases round-trip; a lock_ops
value is written as a marker with no payload and decodes as nil, so a snapshot of a process
with the intrinsics carries no context, and its restore uses the restoring context's lock
form (its chroot names the key); a holder's snapshot is refused naming its keys, with nothing
written; rebind_natives binds the lock form where with-lock is unbound, nil or a stale lock
form, and keeps a program's own; a parked waiter's wait handle is written as nil in both
places, and the restored copy queues afresh beside the original; a waiter's TIMEOUT is
written as what is left of it, nil staying nil.
* tests: with-lock under Ariadne and through the coordinator's migrate
ariadne_runtime_test, suite Locks: LK-34 (a document's section on docs.A.x, then an
unchrooted program's X on docs waits for it and excludes the document's next section until
it releases), LW-1's reactive lane (with-lock is a NameError there), LW-6's action fork inside
with-lock (refused; the fork outside it is skipped as known: a DSL (fork) child applies (fork)
again at its first step), and LW-9's L1 part (an action waits for a resident's lock and is
granted on release; with ariadne.exec.lock_timeout's default the outcome is TimeoutError, no
earlier than 1 s).
state_exec_coordinator_test: LW-8, migrate kills the source, which releases its X section;
the next X grant on the key reports it abandoned, once.
Both files set CVC_STATE_EXEC_CHECK=1 before the first lock manager, so every manager
operation checks itself (gap G-38).
* bench: lock.handoff workers=spawn
L1b.4 of the locks plan. lock.handoff gains a workers key: host (the
bench submits the p workers, as before) or spawn. With spawn, the
world's context installs make_spawn_context over the world's
environment, and one host-submitted parent spawns the workers, each
with a context of its own. A first run on this loaded machine shows
handoff rates within noise of workers=host, and fairness_spread at
most 1 on both schedulers.
* tests: with-lock from pycvc
test_pycvc_state_exec_locks.py: with-lock through pycvc.Exec; LK-23 (the with-lock binding
keeps a dropped context alive); LW-6 (fork refused inside with-lock; outside, from a context
whose pid is pycvc's placeholder 0, the running process forks and the child keeps the owner,
checked and reaped by kill_owner before it steps, since a DSL fork's child applies the call
again); LW-11 (the recursive evaluator raises TypeError and never writes x); L1.12's lock
frame phases (a parked waiter decodes with lock_enter below await_call, every phase an
eval_phase; restored, it queues afresh and is granted once the holder is killed); and
process_info.waiting_on, which reads as an opaque SWIG pointer today (pycvc.i declares no
%naturalvar for it): that case says so and skips. The file sets CVC_STATE_EXEC_CHECK=1
before the first manager.
* tests: lock waiters in the schedulers' run loops; the L1 review findings as tests
state_exec_scheduler_test, suite SchedulerLocks: the sync scheduler's has_runnable() counts
lock waiters (async_scheduler's does not, as for message waiters); a bounded run left with
only a lock waiter and no timer returns at once (design 6.1); run() waits for a sleeping
holder's timer and the release grants the waiter; a run waits for a lock deadline and times
the wait out.
state_exec_locks_test: the review findings the lead is fixing on perf/locks-l1, each
confirmed failing for its reason and skipped as known until that fix is merged:
LK11b (a key-cache hit skips check_global: a cached /jobs is granted under a policy that
doesn't declare it), LK14c (:timeout's symbol is read before a KEY call runs: NameError),
LW07c (a restored lock frame whose lock form decoded as nil, mid-KEY or with a failed
outcome, is dereferenced: an access violation), LW07d (a restored wait queues where the
restoring context forbids lock waits).
* state_exec: (fork) in a step forks cleanly, and an action's context outlives its forks
Since L1, (fork) forks the running process (td B28). Two bugs came
with it.
- The child copied the parent's stack in the middle of the fork call,
so its first step called fork again: a runaway chain of forks. The
child's copy of that call is now finished with 0, as hand_up finishes
a call.
- The child's frames still ran in the parent's scopes, so a set in
either landed in both: (set c (fork)) left 0 in the parent's c.
detail::fork_scopes copies every scope the child's frames run in, up
to the global scope, and points the frames at the copies; the
builtins above stay shared.
Under Ariadne, an action's forked child shares the action's intrinsics
context, which the drain freed as soon as the action ended (review
R1c). intrinsics_context gains on_child, called with each forked
child's pid. Ariadne records an action's children and keeps its
context until they end too, reaping them then.
* state_exec: fixes from the L1 reviews
- A lock frame decoded from a snapshot reads its lock form from the
restoring environment wherever the frame acts, not only on the wait
path. Before, a frame restored while KEY or :timeout was being
evaluated, or with a failed outcome, dereferenced a null lock_ops.
With no with-lock there, it is LockError "restore" (G-44).
- A restored wait follows the restoring context's rules: where no wait
is allowed, or no time is left, the request is tried once and
refused, as a first request is (protocol 5.1).
- :timeout's symbol is looked up only once a call KEY has its value
(left to right).
- A '/' key found in the key cache is still checked against the
requesting context's channel policy: the cache is keyed by chroot
and text, not by policy (G-15).
- A miss never evicts a cache entry that names one of its own keys'
nodes through another spelling. Under self_check the table now
reports such a drop as a 4.15 violation.
The LocksReview suite covers each, and (fork) in a step.
* style: clang-format L1's changed lines
* state_exec: canonicalize sorts a request's keys without allocating
std::stable_sort on libstdc++ takes a temporary buffer even for one
element, so every uncontended with-lock allocated once on Linux and
macOS (state_exec_bench_gates' zero-allocation gate failed there,
while MSVC's insertion sort for short ranges hid it on Windows). A
request has a few keys: an insertion sort, which is stable and
allocates nothing, up to 16, and std::stable_sort above.
* tests: rejoin state_exec_locks_test.cpp after the L1 merge
The merge resolution left the LK-24 test unclosed before L1's
LocksReview suite. The file is L1's version with L1b's LocksSpawn
suite appended, as both sides meant.
* tests: LK-18 draws its paths from a pool
LK-18's programs drew a fresh random path for every key. Over a long run the paths used once
filled the default key cache (1024 entries) and, with the abandoned flags left on them, grew
the trie, so the manager's check() after every step slowed the run as it went: LocksStress at
10^5 operations had not finished one case after 40 minutes. The paths now come from a pool
drawn once from the same 3-ary tree, 20 of each depth 1-8: requests meet at every depth, the
default cache holds the whole pool and the cache of 4 evicts on most requests. Each LocksStress
case now takes 2-5 minutes in Release. The summary line also prints the trie's size.
* tests: checked_world's submit options at namespace scope, for GCC
GCC refuses a `= {}` default argument whose type is a class nested in
the class being defined, when that nested class has default member
initializers: it isn't complete yet there. MSVC accepts it, so
state_exec_locks_test built on Windows and failed every Linux and macOS
lane. The struct is now checked_submit_options, before checked_world,
which names it submit_options as before. Also clang-format on one
changed line of ariadne_runtime_test.cpp.
* style: clang-format L1b's changed lines
* ci: run against master
* tests: the locks test collects reference cycles before LeakSanitizer looks
ASan's leak check failed state_exec_locks_test on 189 indirect leaks:
default environments held by a closure bound in the scope it captured,
a cycle only collect_cycles() frees. The tests step the schedulers by
hand, so nothing ever collected. A gtest global environment now runs
collect_cycles() at the end, when every world is gone, so the leak
check sees only real leaks.
* tests: LockHome's requests keep their keys alive; LK-18's regular size fits CI
- home_world::request() built its KEY value as a local, and
build_request keeps views into it, so try_enter read freed memory.
TSan reported it, and on macOS and Linux it turned
LockHome.EvictionAndRefs's keys into garbage. MSVC's stack happened
to keep the bytes. The values now live as long as the world.
- LK-18 checks every invariant after every step. A CI runner manages
about 25 operations a second on the default cache, so 10,000 didn't
fit its 240 s. The regular Release size is 3,000; LocksStress keeps
the deep sizes.
* Keep the leak hook's lock key alive past its request
The before-terminate hook passed a temporary value_t to build_request, whose
request views the key's text; ASan caught the read after the temporary died
(LX06). Also move LK-18's sizing comment above the sanitizer branch, which
clang-format otherwise indents as part of it.
* locks CI: keep the stress suites out of the sanitizer runs; LK-18 Debug at 500
run.sh ran each sanitizer binary whole, so the TSan job ran LocksStress's
four 10^5-operation cases (about 23 minutes each under TSan) and hit
run_one's hour (#862: exit 124, no report). It now passes -*Stress*, as
ci.yml's STRESS_REGEX keeps those suites off the PR lanes; locks-deep.yml
runs them. Its LocksStress filter named LocksStress.*, which matches none
of the parameterized Schedulers/LocksStress.* tests: fixed.
LK-18's regular size in a Debug build was 2000 operations, 150-240 s on CI
runners against ctest's 300 s, and over it on a loaded one (#862's
package-linux debug-grpc). Release does 3000 in 5-13 s; Debug is 25-50
times slower, so it now runs 500.
* app_test: read the pool's queue before its running count when waiting for idle
wait_pool_idle read getActiveThreadCount() and then getPendingThreadCount(),
each under its own lock. A worker could take the last queued task between
the two reads, so the pool looked idle while that task ran:
AppPoolKeyed.AKeyedTaskWithRoomIsRegisteredOnReturnBehindAnonymousTasks saw 7
of 8 warm-up tasks done (#868's ubuntu Debug run). A task leaves the queue and
counts as running under one lock and stops counting after its body, so reading
the queue first can't miss one.
* LK-18: size by the optimizer, not NDEBUG (the mesher defines NDEBUG in Debug builds)
transfix
added a commit
that referenced
this pull request
Nov 16, 2026
…ated gate) (#1175) Fixes the two with-lock bench findings open since L1 (#862), with no protocol change. Plan and measurements: state-exec-perf/locks-impl/L1-speed.md in the workstreams tracker. Deadlock search: block() ran protocol 4.6's reachability as a depth-first search from every target, recomputing successors as it went, which is O(p^2) per re-queue with p waiters on one key. Every edge into the requester P comes from a queued ticket that conflicts with a hold of P (3.2), so a P with no hold skips the search, and otherwise the search is confined to the processes with a path back to P, which finds the same cycle. Protocol 4.6 gains an implementation note; LD-11 is new. lock.handoff at p = 64: 92-93 us -> 12-14 us per handoff; steps per handoff unchanged (37.0). Uncontended lock: lock_home memoizes scope_id and fronts the key cache with a 16-slot memo; lock_table drops the seed copy while nothing lends, builds request text only for the self-check, and looks up the record once per try_acquire; the evaluator's fast path derives the lock_ops once. Probe medians against master: table 180 -> 154 ns single, 232 -> 204 ns shared; home path 297 -> 249 ns single. 0 steps and 0 allocations per lock. Gate restated (owner's decision, 2026-11-12): at most 450 ns over begin single and 550 ns shared (sync, flat key, Release, quiet window), from 60/120. 0 steps and 0 allocations stay the hard gates. Design 11.1-11.3 and STATE_EXEC_BENCH.md follow. The timing A/Bs (lock.uncontended, lock.cross_thread, the locks=none families) wait for a quiet window.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This is phase L1 of the state_exec locks plan:
with-lockon one scheduler (docs/STATE_EXEC_LOCKS.mdsections 4.1-4.3, 5 and 8; the protocol isdocs/STATE_EXEC_LOCKS_PROTOCOL.md). It stacks on #860 (L0). It is a draft and still in progress; it is up now so Linux, macOS and wasm CI can check the code early.In so far
The interface (
lock_manager.h,detail/lock_table.h) and the classesLockError,DeadlockErrorandPermissionError.The manager's table (protocol 2-4 and 6, single mode, one home):
check()of the manager's invariants, the test-only mutations, and the canonical dump.It matched the Python model (
tools/locks_model/lockmodel.py) on about 560,000 random operations. It also has 42 directedLockTablecases.Process and process-table fields: lock waiters are counted, and a lock deadline is a timer, collected within the existing timer branch.
The lock home and the scheduler hooks (protocol 5):
check_quiescent();set_lock_manager,locks()(a private manager on first use), and the end hooks.The lock form in the stackless evaluator:
(begin ...);:if-available,:timeout,:as;%lock-waitchild applied through the form's ownlock_ops;finally;locks-held,lock-query, and key resolution (chroots, and/keys under the channel policy).Snapshots:
nil, with its remaining timeout;restorerefuses a stack that holds a lock.Smaller changes:
with-lock;(fork)forks the running process, and refuses insidewith-lock;inspectshowslocks_heldandwaiting_on.Hosts:
app::lock_manager(), withexec_scheduler()attaching to it;ariadne.exec.lock_timeout(1 s);The model check (LT-5):
state_exec_locks_model_testruns a port of the Python model's Manager as a spec oracle in lockstep with the real table. It compares results, notifications, canonical dumps and bothcheck()s after every operation. It explores thel1configurations breadth-first and matchesexplore.py's state counts exactly (l1bound 3: 26,834 states with the model's FIFO cache). It also runs random runs, directed scenarios, and 20 traces exported from the Python model (tools/locks_model/export_traces.py). Each of the eight mutations reports its own violation. 74 tests; the deep bounds are inLocksModelStress.Tests:
Locks: LK-1 to LK-33, LX-1 to LX-11 (queued and granted variants), LW and LD, on both schedulers. They run on a checked driver: one step at a time, every invariant checked after each step.LocksStress,LockHome,LockCodec,SchedulerLocks, the Ariadne and coordinator cases, and pycvc's.LocksReview: one test per review finding.LocksSmoke.Bench (group M):
lock.uncontended,lock.handoff,lock.rw,lock.many_keys,lock.bystanders,lock.timeout,lock.deadlockon both schedulers, andlocks=private. The new CTeststate_exec_bench_gatespins the deterministic gates: an uncontendedwith-lockadds 0 steps and 0 allocations over(begin ...)at every depth, mode, chroot and owner, andsched.single.*step totals are pinned. The allocation gate found that the lock body never reserved its results vector (one allocation per lock), which is fixed.Docs (developer guide's Locks section, exceptions, grammar, Ariadne, pycvc), and the
state_exec_wasm_smokestep in the wasm job.Found by the reviews and CI, and fixed:
(fork)inside a step copied the unfinished call, so each child forked again without end. The children also shared their parent's scopes.lock_wait_allowed.:timeoutwas read before KEY./key found in the key cache skipped its PermissionError check.after_granttest hook fired before the frame held the grant.std::stable_sorttakes a buffer even for one key.Run locally (Windows, MSVC, Release): every
state_exec_*suite,state_test,ariadne_runtime_test,app_test,state_exec_bench --smokeand the pycvc state/exec scripts pass. Existing results are unchanged.Still to come in this PR: