Skip to content

docs: a design for running state_exec programs on several threads (groups first) - #835

Merged
transfix merged 11 commits into
masterfrom
docs/state-exec-threaded
Oct 27, 2026
Merged

transfix merged 11 commits into
masterfrom
docs/state-exec-threaded

Conversation

@transfix

@transfix transfix commented Oct 27, 2026 •

Copy link
Copy Markdown
Owner

A design for running state_exec programs on several threads (docs/STATE_EXEC_THREADED.md, linked from the developer guide), and a design for locks on the state tree and process priority changes that extends it (docs/STATE_EXEC_LOCKS.md, with the exact protocol in docs/STATE_EXEC_LOCKS_PROTOCOL.md and a model checker for that protocol in tools/locks_model/). Both are design only; nothing is built yet.

The groups-first design is adopted, and the answers to its section 9.2 questions are recorded there. It stays a draft while the locks design's open questions (its section 14.2) are reviewed.

Locks and priority

The DSL gets advisory, scoped locks on sections of the state tree:

  • (with-lock KEY [:shared|:exclusive] [:timeout s] [:if-available [:else v]] [:as sym] body...), where a key is a tree path (relative to the caller's chroot, / for app-global) or a list of paths;
  • locks-held and lock-query;
  • the atomics state-incr, state-cas and state-swap, so the common read-modify-write needs no lock;
  • set-priority and get-priority, with Unix rules and priority inheritance through locks;
  • OS thread priority for the hosts' workers, as a host-only knob;
  • new classes LockError, DeadlockError and PermissionError.

A lock is released on every way a process ends. Plain state-get/state-set never consult locks, so existing programs keep their behaviour and step counts.

How it was decided. Four proposals (named scoped locks, a lease manager, hierarchical tree locks, optimistic/STM) were scored by two judges; named scoped locks won. Two adversarial review rounds then found the chosen protocol was not converging (55 and 45 confirmed findings), so its core was simplified:

  • all-or-nothing requests;
  • one manager with one mutex (none on one thread);
  • holds on a path trie;
  • one FIFO with a pairwise conversion rule;
  • tickets that own the outcome;
  • exact deadlock detection when a process blocks;
  • inheritance over the same wait-for graph.

The protocol spec states it as pseudo-code with invariants I1-I15 and their proofs. tools/locks_model/ implements it literally in Python and checks it by bounded exhaustive exploration, scripted interleavings, random runs and 13 seeded mutations, each of which it catches. Four more review rounds against the code and the model followed.

Phases.

Phase Content
L0 the atomic natives
L1 locks on one scheduler
L1b the spawn context, so spawned children lock against their parent's chroot
L2 priority
L3 one app on several threads

L1-L3 with L1b are the "hardened on one machine, single or multiple threads" milestone and are planned for implementation next, on top of perf/sched, perf/eval and perf/async. Three phases are documented only:

  • L4: groups, with the threaded stages;
  • L7: migration between hosts, which comes last;
  • L5 and L6: guarded subtrees and semaphores, on request.

STATE_EXEC_THREADED.md is updated to match: the locks track brings blocker B28 forward into L1 and part of B27 into L1b, and it adds the priority and Stage M (migration) sections.

How it was decided

Five proposals were written independently:

  • A: one scheduler on N workers over heap domains;
  • B: one scheduler per thread with handoff;
  • C: BEAM-style SMP with per-process heaps;
  • D: share-nothing isolates;
  • E: an incremental, groups-first path.

A prior-art survey (BEAM, Go, Tokio, CPython subinterpreters, Racket places, V8 isolates, Guile fibers) informed them. Three judges, weighting correctness, delivered performance and cost/risk respectively, scored all five against the current code (summed totals out of 150):

Proposal Total
E, groups first 119
D, isolates 107
B, per-thread schedulers 100
A, one scheduler over heap domains 95
C, BEAM-style 83

The design

An execution group is one scheduler with its own async host, cycle registry and random stream, stepped by one thread at a time. Groups run in parallel on a shared worker pool. This sidesteps the hardest blockers (the scheduler-wide current process, unsynchronized scheduler maps, in-place cross-process writes, the thread-local cycle collector), because no group is ever touched by two threads. The measured ceiling for this shape is mt.independent in #834: 4.45× at 8 threads. The correctness oracle is simple: every group's results must match its solo single-thread run.

Stage What it adds Effort
0 Process-global hazard fixes (exception class dicts, isolating copies, state-tree pinning, atomic stop and control queues) and a TSan CI job. Two pycvc Execs on two Python threads already race today; this fixes it. 1.5–2 weeks
1 Groups on a fork-join pool; spawned children that can message; Ariadne pumping once per frame; isolated Ariadne documents and pycvc.ExecPool 3–4 weeks
2 A continuous pool with wakeups; a router for messages between groups; cross-group control 3–4 weeks
3 spawn-isolated for DSL programs; moving processes; opt-in Ariadne parallel actions 3–5 weeks
S Slices: a single-thread speed-up, independent of the pool 1–2 weeks
4 Several threads inside one group, only if benchmarks show a need in reserve

The doc also covers:

  • every blocker (B1–B32) with file:line and the stage that resolves it;
  • the semantics changes, always-on or opt-in;
  • expected performance per workload, with 11 new benchmark scenarios;
  • a test list (hazards, groups, pool, messaging, isolation, hosts, TSan/ASan, stress, determinism, slices);
  • risks;
  • prior art.

It builds on the single-thread optimization branches in progress (perf/sched, perf/async, perf/eval).

Questions for review (section 9.2)

  1. Confirm groups first, with option A kept as Stage 4.
  2. Freeze the built-in exception classes, or give each group its own copies?
  3. Values crossing groups: refuse nested callables, or copy closures with their environments?
  4. What a spawned child inherits, and whether plain spawn is ever placed on another group automatically.
  5. Cross-group kill/ps from programs: same owner only, never, or all groups?
  6. The router: where channels are homed, and whether a group may receive on a channel homed elsewhere.
  7. Ariadne:
    • Does any host run several Runtimes in one process?
    • Which providers and subscribers must stay on the host thread?
  8. Defaults:
    • state_exec.threads: 0 or auto?
    • Workers on P-cores only, or all cores?
  9. Split async kernels into CPU and blocking pools? That reverses a settled question in STATE_EXEC_EXCEPTIONS.md.
  10. Default slice length: 1 or 256?
  11. Widen pids to 64 bits now?
  12. ExecPool: reuse pooled Execs, or a fresh environment per program?
  13. Move exec_coordinator's local path to async groups?
  14. Setting and API names.

…s on several threads

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

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

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

The developer guide links to it.
…ions

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

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

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

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

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

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

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

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

New sections 4.19 (locks and priority across groups), 4.20 (Stage M), 8.11 (LG tests) and 8.12
(MG tests), and additions to the header, 1.1, 1.2, 2.3, 2.4, 4.1-4.6 and 4.10-4.18, sections 5 to 7,
9.1 and 9.2. The references to the two new documents are links. One line of the 4.19 Priority
bullet is re-wrapped to the document's width.
STATE_EXEC_LOCKS_PROTOCOL.md section 7 checks the protocol with a Python model before any C++
exists, and STATE_EXEC_LOCKS.md 8.1 places it here. This is revision 5b, the one section 7 names:
lockmodel.py implements the manager's operations literally and asserts the manager's invariants
after each; world.py adds the homes, ports and posts as a step relation with the home-side
invariants. scenarios.py runs directed scenarios and checks that every mutation section 7 lists is
caught by the violation it names; explore.py explores a configuration exhaustively to a bound;
explore_scripts.py explores every interleaving of scripted processes with faults; random_runs.py
runs long random worlds. run_long.sh runs all of them at full size (about 2 hours on 22 cores and
15 GB) into results/, which is ignored. The README says how to run each one and what each
configuration covers.

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

The docstrings name STATE_EXEC_LOCKS_PROTOCOL.md rather than the draft's file name.
Review of the locks edits found places where the new text and the old disagreed:
- 2.4: the locks track's row now names the blockers it settles (B28 in L1, B27's single-scheduler
  part in L1b), and the lead-in covers the track as well as the branches;
- 4.4: fork-join breaks LPT ties by best_runnable only from Stage 2, which publishes it (4.5);
  the ready queue's mutex is named as such, not as "the lock";
- 4.7 and 4.18 B7: "the built-in class dicts", since their number grows from 13 to 16 with the
  locks track;
- 4.11: cross-group set-priority and cross-group lock grants lose their immediacy too;
- 4.15: a lock holder's eligibility for a move follows the requirement list instead of joining
  it, and the spawn-context and 6.3 Stage 2 lists keep one ending per list;
- 4.19: the app's lock manager runs in shared mode only when several threads use it, single at 0
  threads (4.14);
- 4.20: Stage M's eligibility is a subset of Stage 3's, not the same rules;
- 7: Stage 0's fork entries and risk, and Stage 1's spawn-context entries, say what changes when
  the locks track's L1 or L1b lands first.
The locks fold-in made its references to STATE_EXEC_LOCKS.md and STATE_EXEC_LOCKS_PROTOCOL.md
relative links, while the document still named STATE_EXEC_EXCEPTIONS.md, ARIADNE.md and
STATE_EXEC_DEVELOPER_GUIDE.md as plain code paths. Those ten mentions are now links too, as in
most of docs/ and in the two locks documents, and the lines they lengthened are re-wrapped. The
words are unchanged. STATE_EXEC_BENCH.md stays a plain path: it is not on this branch (#834).
…ences

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

STATE_EXEC_LOCKS_PROTOCOL.md:
- The intro defines Qn (td's decisions), which the protocol cites as Q5.
- Section 7's port-race mutation is "a reading 2.3 rules out" rather than an earlier reading of a
  draft.
- Section 8's "5.2 compatibility table" named a section of the unpublished round-2 design; it is
  now "their compatibility table".
STATE_EXEC_LOCKS_PROTOCOL.md section 7 ended with the model's revision history (revision 5b
follows this text, revision 5 added this, revision 5b added that), and STATE_EXEC_LOCKS.md's LT-5
named revision 5b. Neither the earlier revisions nor their runs are in the repository, and the
landed model is 5b plus the nested-destroy fix, so section 7 now says which clauses the model
checks, without revision numbers, and points to tools/locks_model/README.md. LT-5 drops the
revision. The README gains a Revisions section with the history section 7 held, and its notes on
the fix become a subsection of it; lockmodel.py's docstring names the README instead of
section 7.
…nobs

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

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

The script's exit status is now the summary's verdict: 0 only when SUMMARY.txt's last line is
"0 unexpected" (read without the CR a Windows Python writes). The header and the README say that a
relative R is resolved against the script's directory, and that PY usually has to be set on
Windows.
@transfix
transfix marked this pull request as ready for review October 27, 2026 22:12
@transfix
transfix merged commit c1f104c into master Oct 27, 2026
25 checks passed
@transfix
transfix deleted the docs/state-exec-threaded branch October 29, 2026 20:51
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