Skip to content

Latest commit

 

History

History
607 lines (518 loc) · 47.2 KB

ARCHITECTURE.md

File metadata and controls

607 lines (518 loc) · 47.2 KB

Architecture

everystate is a model checker for TLA+ that behaves like TLC: the same command line, the same output, the same state counts. This document is for someone who has to change it. It says what each part does, which parts must agree with each other, and which rules are easy to break. Everything here describes the code as it is; when you change the code, change this file in the same commit.

The reference for behaviour is Java TLC. docs/TLC_NOTES.md records what TLC does, read from its source, with file and line; the source comments cite it as "TLC_NOTES".

The pipeline

Spec.tla, Spec.cfg
   │  lexer.rs            characters -> tokens
   │  parser.rs           tokens -> ast.rs trees (leaked: every node is &'static)
   │  modules.rs          EXTENDS / INSTANCE, symbol tables, name resolution, levels
   │  cfg.rs              the .cfg file
   ▼  model.rs            root module + configuration -> Model
Model: variables, initial predicates, actions (Next split up), invariants, constraints,
       properties, symmetry, view, alias
   │
   ├─ checker.rs          exhaustive breadth-first search (one thread)
   │    └ par.rs          the same search on several threads (-workers N)
   ├─ liveness.rs         temporal properties, on the state graph the search recorded
   ├─ simulate.rs         -simulate: random behaviours
   └─ conform.rs          `everystate conform`: is a recorded trace a behaviour of the spec?

eval.rs (tree-walker), compile.rs (compiled plans), stepcache.rs: how successors and predicates are computed
value.rs, intern.rs: values and strings          stdlib.rs, community.rs: operators implemented in Rust
hashcons.rs: one node and a small id per distinct value, which the step cache and the search work on
codec.rs: states as bytes          store.rs: the state store (states in SQLite instead of memory)
pcal/: the PlusCal translator (independent of all of the above)
cli.rs, main.rs: the command; wasm.rs, wasm/: the WebAssembly build; bin/everystate.mjs: the npm launcher

liveness::model_check is the entry point for a normal run: it builds a Checker, normalises the temporal formulas first (so errors in them are reported before the search), runs the search, checks liveness on the recorded graph if there are temporal properties (during the search too, see "Liveness checking"), then the POSTCONDITIONs.

The core never touches files, the clock or processes directly. It asks a Host (host.rs), so the same code runs natively (NativeHost) and as WebAssembly.

Almost everything is single-threaded by construction: values are Rc, the syntax tree carries Cell and RefCell caches, and there is one Evaluator per thread (eval::ev(), a leaked thread-local). The main thread runs the checker on a 1 GB stack (main.rs) because deeply recursive TLA+ definitions recurse in the evaluator; eval::check_stack turns exhaustion into TLC's stack overflow message.

Source files

file owns
src/main.rs The binary: picks the Java stand-in when called as everystate java ..., starts the big-stack thread, installs mimalloc.
src/lib.rs Module list. par is native only, wasm is wasm32 only.
src/cli.rs TLC's command line and output: flags, banner, progress, traces, -tool framing, -dump, -json, the java ... tlc2.TLC / tla2sany.xml.XMLExporter / pcal.trans stand-ins. Dispatches the conform and pcal subcommands.
src/host.rs The Host trait (files, environment, processes, printing, clock), NullHost and NativeHost.
src/lexer.rs Tokens for one source file.
src/parser.rs Recursive descent with precedence climbing and column-sensitive junction lists. Reports SANY's precedence conflicts. Proofs are parsed and dropped. A label is not a node: it is recorded on the node it labels (Node::wraps).
src/ast.rs Node / E: the expression tree. Nodes carry caches filled later (resolution, level, interned string id).
src/modules.rs Loader: loads modules (files, bundled modules, built-in modules), builds symbol tables, resolves every name to a Decl or Def, computes levels (level_of: 0 constant, 1 state, 2 action, 3 temporal). Subexpression selectors are resolved here (sub_def).
src/bundled.rs Generated by scripts/export-lib.mjs: the TLA+ sources of lib/*.tla (CommunityModules, TLAPS) compiled into the binary.
src/cfg.rs Parser for TLC configuration files.
src/model.rs build_model: applies the configuration to the root module (constants, overrides, SPECIFICATION / INIT / NEXT, properties), splits Next into actions as TLC does, orders the variables as TLC does.
src/value.rs Value, sets (explicit and symbolic), comparison, equality, hashing (value_word, Hasher), TLC's print format.
src/hashcons.rs Hash-consing: one node per distinct value in a per-thread table, and a dense id for it (Booleans and small integers are immediate ids); the word and shape of a value by id. See "Value ids".
src/intern.rs Interned names and strings (see "String order"), the error types (Fail, R<T>), the worker-thread "impure" flag.
src/eval.rs The tree-walking evaluator and enumerator: eval, enumerate, ENABLED, lazy values. The reference semantics.
src/compile.rs Actions and invariants compiled to closures; the step cache's recording and its on/off policy.
src/stepcache.rs The step cache: its set-associative table of templates and leaves keyed on value ids, the entry format (successors as ids, or as changes with their words), and the memos of changes applied (Applied, Words, Located).
src/stdlib.rs The standard modules (Naturals, Sequences, FiniteSets, Bags, TLC, TLCExt, ...) and the hot community operators, in Rust.
src/community.rs The remaining CommunityModules operators (Json, CSV, IOUtils, graphs, ...), in Rust. Host access goes through ev.host.
src/checker.rs Checker: fingerprint set, initial states, the sequential search loop (on rows of ids in the flat case: IdStore, successors_ids), invariants, constraints, symmetry, traces.
src/codec.rs States and values as bytes (ser_var, ser_state, De): how states cross threads and how the state store keeps them.
src/store.rs The state store: the provider interface (StateStore), the search's side of it (Stored: records, chunks), and the SQL providers (sql: the schema, the statements, the SQLite file of -store sqlite:FILE). See "The state store".
src/par.rs -workers N: value numbers (Dict), worker threads, the level-by-level merge, and in the flat case the claim of new states by segment of the fingerprint set (level_ids).
src/liveness.rs Temporal formula normalisation, tableau, strongly connected components over state graph x tableau; model_check; periodic checks on the partial graph (-lncheck).
src/simulate.rs -simulate: random behaviours with a seeded generator.
src/conform.rs Trace conformance, with its own JSON reader.
src/pprint.rs Port of TLC's value pretty-printer (line breaking at 80 columns).
src/tshash.rs The node identifiers of -dump dot, kept bit-identical to the earlier TypeScript engine.
src/pcal/ Port of the Java PlusCal translator, class by class (tokenize, parse, symtab, explode, gen, trans); output is byte-identical, including layout and checksums.
src/wasm.rs The exported WebAssembly functions (es_check, es_check_stored, es_simulate, es_conform, es_pcal), and the state store's SQL run by JavaScript (JsSql).
wasm/everystate.mjs, .d.ts The JavaScript API over the module; every call runs in a fresh instance. wasm/cli.mjs is the command built on it (JSON output only). wasm/everystate.wasm is a tracked build output of wasm/build.sh.
bin/everystate.mjs What npm installs as everystate: runs native/<platform>-<arch>/everystate (put there by the release workflow), or EVERYSTATE_BINARY, or falls back to wasm/cli.mjs.

Labels and subexpression selectors

Op(a)!lab(x)!2 names a part of the definition of Op (TLA+ version 2; the rules are those of SANY's Generator.selectorToNode, summarised in TLC_NOTES section 12). None of it reaches the evaluators:

  • The parser keeps the parts of a name with ! in E::App::sel and all their arguments, in order, in args. A label, and the bullet of a junction list with one item, are entries of Node::wraps on the expression they stand in front of, so the tree is the same with or without them.
  • Name resolution (modules.rs, the E::App case of resolve) takes the shortest prefix A!B that is a symbol as the operator. If parts remain, sub_def walks the definition's body and makes a new Def: its parameters are the operator's, then the identifiers bound on the way (label parameters, !(args), !@), then those of a LET definition named last; its body is the selected node, wrapped in the LETs it was inside so that their definitions are in scope. For an instantiated operator the selection is made in the original definition and wrapped in the same substitution. The reference then is an ordinary application of that Def.
  • After resolution sel is never read again. Do not test it in an evaluator: every reference through an instance (I!Op) has one.

Values

Value (value.rs) is an enum: Bool, Int (i64; arithmetic checks TLC's 32-bit range), Str and Model (an interned id), Tuple, Record, Fcn, Set, plus four things that are not TLA+ values but occur during evaluation: Closure and DefRef (operators passed as arguments), LazyFcn (a function constructor not yet enumerated) and Thunk (a delayed argument, eval::Lazy).

  • Functions are kept in one canonical form: domain 1..n is a Tuple, a non-empty domain of strings is a Record (field names sorted by string id), anything else is an Fcn with a sorted domain. Equality can therefore compare like with like. Use make_fcn, make_fcn_from_pairs, make_record; do not build the variants by hand unless the form is known.
  • A set (SetV) is either SetK::Enum (a sorted, duplicate-free vector) or symbolic: an interval, SUBSET S, [S -> T], a record set, a product, Seq(S), Nat / Int / STRING, and TLC's lazy union, intersection, difference and filter. elems() enumerates a symbolic set once and caches the result; contains() answers membership without enumerating where it can.
  • Composite values cache their hash (h, 0 = not computed). Values are immutable once built, and states share unchanged values with their parents (Rc), so most of a state is never hashed twice.
  • Comparison (compare) follows TLC's rules, including its errors for incomparable values.

A state (eval::StateData) is a vector of values, one per variable, with a process-unique id (a Cell: the search on ids refills one buffer for state after state, with a new id each time, refill). Undef marks a variable not assigned yet.

Value ids

hashcons.rs interns every distinct value that a state or a step-cache entry keeps, in a table per thread, and gives it an Id (a u32). A value has one canonical form (functions by their domain, sets sorted and duplicate-free) and the table one node per form, so two interned values of one table are equal exactly when their ids are; that is what the step cache compares. Interning a value whose parts are interned costs one hash of their words (the fingerprint's, computed once) and one probe.

  • Booleans and integers within +-2^28 are immediate ids: the value is in the id, with no entry.
  • Not interned: operators, lazy functions, every set that is not an explicit sorted vector (intervals, symbolic and lazy sets), and any value that contains one. Code on ids keeps such a value beside the ids (NOT_INTERNED + i, IdStore::opaque) and takes the value path for it. An interval is not interned although it is a plain value: 1..3 and {1, 2, 3} are equal but print differently.
  • The table is emptied, with a new epoch, at the start of each check (hashcons::reset), and only grows during one: a run that would intern more than 2^30 distinct values in one thread stops with that message. States are interned only while some unit uses the step cache.
  • Ids are per thread. Workers have their own tables; states cross threads as one number per variable (par::Dict, see "Parallel search").

String order

TLC orders strings and model values by the order in which its JVM first interned them, not alphabetically, and that order is visible: it decides the order of set elements, hence CHOOSE, the order in which successors are generated, and what is printed. intern.rs reproduces it: StrId is the position in first-seen order, the configuration is read before the modules, and each module's string tokens are interned when it is loaded (modules.rs, ast.strings).

Consequences:

  • Never intern a string speculatively or in a different order than the tree-walker would. Commit 3cf6732 fixed the compiled evaluator doing exactly that for string arguments.
  • A string first created during the search (ToString, concatenation) gets its id at that moment, so its place in the order depends on the order of exploration. The parallel workers must not decide it: the string table is process-wide, a worker that meets a new string uses a private id and hands the state back to the sequential search (worker_impure). The compiler does not compile an action that can create a string.
  • Fingerprints must not depend on ids: strings are hashed by content (str_hash).

Fingerprints

Defined in checker.rs ("state fingerprints") and value.rs (value_word):

word(v)   = a tagged scalar (integer, boolean, content hash of a string or model value), or, cached in a
            composite value, a sum mod 2^64 of one term per part:
              a function (tuple, record or function)  fn_tag(n)  + sum over k in DOMAIN f of entry_term(word(k), word(f[k]))
              an explicit set                          set_tag(n) + sum over e in S of elem_term(word(e))
term(i,v) = mix64(word(v) xor (i+1) * 0x9E3779B97F4A7C15)          i = index of the variable
fp(state) = mix64((sum over variables of term(i, value_i), mod 2^64) xor 0x243F6A8885A308D3)

mix64 is the splitmix64 finaliser; entry_term and elem_term are one 128-bit multiplication each, folded (value.rs, mum). Because the fingerprint is a sum, a successor's fingerprint is its parent's with the terms of the changed variables replaced (row_fingerprint); an unchanged variable costs one comparison. Because a composite's word is a sum too, the word of a value changed in a few places is the old word with those terms replaced: a step-cache hit computes a successor's fingerprint from its parent's and the stored changes before the successor is built (delta_fingerprint, delta_word), and EVERYSTATE_VERIFY_DELTAS=1 checks every such fingerprint against the one of the built successor. With SYMMETRY or VIEW the input is the canonical state or the view's value (fingerprint_input) and the incremental forms are not used.

The fingerprint is 64 bits and states are identified by it alone (FpSet), as in TLC; the collision estimate printed at the end is TLC's formula. It depends only on the content of the state, so it is the same in every worker thread.

How successors are computed

There is one definition of the semantics and several faster ways to get the same answer.

1. The tree-walker (eval.rs). Evaluator::enumerate(e, ctx, k) walks an action and calls k once for every way of satisfying it, with the primed variables assigned in the next-state buffer (ev.nxt); in init mode it assigns unprimed variables in ev.cur. eval computes values. Operator arguments and LET definitions are delayed (Lazy, Bind::LetLazy) and evaluated on first use, as in TLC. This path is the reference: it words every error, and everything else falls back to it.

2. Compiled plans (compile.rs, the default). Before the search compile turns each action and each invariant into a tree of closures over a frame of slots: names are resolved to a variable index, a slot or a constant; definitions with value parameters are inlined; which conjunct assigns which variable is decided once. Three rules keep it equal to the tree-walker:

  • What the compiler does not handle becomes a fallback: that expression is evaluated by the tree-walker in a context rebuilt from the frame (fb, fb_act). Coverage affects speed only.
  • Compiled code only has to be right when it succeeds. If it fails in any way, Checker::successors_with discards what the action produced and runs the tree-walker on the action from the start, so errors and their wording are the tree-walker's.
  • For that to be sound, an action that may reach an operator with an effect (printing, TLCSet, random choice, I/O, a new string) is not compiled at all (impure). Only the modules listed in pure_module are taken as free of effects.

A plan that falls back more than four times per evaluation over its first 512 evaluations is switched off (Usage). EVERYSTATE_EVAL=tree turns compilation off.

3. The step cache (stepcache.rs, recorded and consulted in compile.rs; on by default, native only). A unit is what is left of a compiled action below its top-level disjunctions, existential quantifiers and inlined definitions. While a unit runs, the compiled code records what it reads of the current state (a whole variable, one element f[k], or whether a value is in a set or bag variable) and what it produces, as changes to the parent's values. An entry is (unit, bound values, reads with their values, successors). In a later state where every read has the same value, the successors are produced by applying the changes. Nothing is stored for an evaluation that failed, used a fallback, made a change the entry format cannot express, or involves a value that cannot be interned.

Everything an entry holds is a value id: a template per (unit, bound ids) lists the locations its evaluations read and has a version, and a leaf per (template version, ids found at those locations) holds the successors, each as the ids of the variables it changes or as changes to the parent's value with their words precomputed (Put::Delta, IdOp). A hit compares ids. Applying a change to a parent's value is remembered per (parent id, list of changes) (Applied), as are the word of the result (Words) and what a location holds in a value (Located). B (+) C with C a bag of at most 64 copies is recorded as one change per copy, so the bag variable is not read whole.

The table is 4-way set-associative (64-byte buckets with the hashes inline; a full bucket gives up its oldest leaf, never a template, whose leaves depend on it) with a fixed budget (EVERYSTATE_STEP_CACHE_MB, default 32, per worker). Each entry is charged what it holds; one over 4 KB or over the budget is not stored, nor is an evaluation that read a value of more than 512 bytes (vsize: such a key rarely recurs). The memos are arrays of cells from zeroed memory, so pages no state touches cost nothing.

Policy (unit_run, UnitStat, Meas in compile.rs): whether the cache pays is measured per unit, on the whole time per expanded state. A unit warms up for 256 evaluations (dropped if nothing could be stored in the first 32 or fewer than half were hits), then goes on trial: each expanded state is taken with or without the cache by a hash of its number, and the time to the next expansion is added to one of two means. The unit keeps the cache when the mean with it is lower by 2.5 standard errors, or by one after 4096 states per side; otherwise it runs without for a while and is tried again later. No clock is read while no unit is on trial. Which units have the cache can therefore differ between runs; the results cannot, because a hit yields exactly what the evaluation would. EVERYSTATE_STEP_CACHE=off turns the cache off, =always gives it to every unit regardless of the measurement (for testing). The WebAssembly build has no clock, so the cache is off there.

4. The flat path (checker.rs, flat). How the search loop consumes successors. When nothing but the fingerprint set looks at a generated state (no CONSTRAINT, ACTION_CONSTRAINT, VIEW, SYMMETRY, action property, recorded graph), successors_flat writes the variables of all successors of a state into one reusable buffer, the loop computes each fingerprint incrementally from the parent's, probes the set, and allocates a state only if it is new. Otherwise successors allocates a state per successor first, because the constraints, the view or the graph need it. Both go through successors_with, which is the single place that chooses between compiled plan and tree-walker.

With one worker the flat case runs on ids (idmode): states are rows of ids (IdStore) and successors rows of ids (successors_ids, stepcache::Rows). The top of an action (disjunctions, \E x \in S, inlined definitions) runs on ids when it can (compile.rs, Skel, Plans::run_skel): S is taken from ids (DOMAIN f from the id of f, a constant set once), the units are looked up with the bound ids, and the state's values are built only when a unit misses or does not use the cache. A successor from a hit is fingerprinted from its changes and probed in the set first; only a new state, about one in seven on the actor-style models, has its row built (Recipe, Plans::build_recipe). A state is rebuilt as values only to be expanded on values or to have its invariants checked.

5. Parallel search (par.rs). Each worker thread builds its own model and evaluator. A level of the search is cut into chunks; workers expand states exactly as the sequential loop does (expand mirrors the loop body of Checker::search, flat and not; expand_ids the search on ids), against a fingerprint set they only read, and report candidates. Anything that is not the plain path (a violation, an error, a deadlock, an operator whose effect depends on exploration order) is not handled by workers: the state is handed back and the sequential loop re-expands it. Workers start when the search does, load the specification while the first levels run on one thread, and take the main thread's measurements of which units pay (Plans::verdicts, adopt). A level goes to them when it has at least 512 states, or 64 (EVERYSTATE_PAR_MIN) once the search has run for 50 ms.

Which candidates are new states is decided as a one-worker run decides it, so ids, counts, depth and traces are the same with any number of workers. There are two ways:

  • In general (Par::level), candidates come as bytes and the main thread merges them in state order, each chunk as soon as it and every chunk before it are whole, while the workers still run (the set has one writer and many readers), the rest at the end of the level.
  • In the flat case with the step cache on (Par::level_ids), states cross threads as one number per variable (Dict: a value gets a number the first time a thread sends it, and each worker keeps ids by number, Nums), and workers expand on ids. Firsts, a table of the level's new fingerprints with the earliest position each was found at, lets a worker drop most occurrences that are not the first. At the end of the level the set grows to room for every candidate (by segment, in parallel: Grow), then each worker inserts the candidates of its groups of segments, chosen by the fingerprint's top bits, in level order (Claim): the first to insert a fingerprint is the state the one-worker search finds first. The main thread then only numbers the new states and appends their parents.

Simulation and conformance use Checker::successors or Evaluator::enumerate directly.

Which states are kept

A safety check reads a state it has already expanded for one thing only: to print a counterexample. So unless something else will read the states, the search does not keep them (Checker::lean):

  • What is released. The values of a state once it is expanded (states[i] becomes the placeholder), its row of ids (IdStore::release), and in the parallel search the bytes or numbers of a level once every state of it is expanded (Par::release). What stays per state is its fingerprint in the set, the fingerprint again by state id (fp_of), its parent and its action. The fingerprint set then stores no ids (set_id gives 0, which FpSet does not write, so the pages of its id array are never touched).
  • The counterexample. trace_to gives the placeholder for a released state, and Checker::run puts the states back at the end (rebuild_trace): the first initial state with the first state's fingerprint, then at each step the first successor by the step's action, inside the model, with the next state's fingerprint. That is the state the search stored, because it stored the first state it met with that fingerprint; a state is told apart from another with the same VIEW or under SYMMETRY by coming first, and from one outside a CONSTRAINT by being inside it.
  • When states are kept instead. With the recorded graph (temporal properties, -dump), with a state store, and when the initial predicate, an action, a constraint or the VIEW may have an effect (compile::may_have_effect: Print, TLCSet, a file, a random choice), since taking a step again would repeat it.
  • What must agree. Every place that numbers a new state calls note_state with the fingerprint the set was given, and rebuild_trace applies the tests the search applies before it stores a state (constraints, action constraints, then the fingerprint). test/cli.test.ts compares rebuilt traces with those of a search that keeps every state.

The state store

By default every state the search finds stays in memory until the run ends. With a state store (-store sqlite:FILE, or store in the JavaScript API) the states are kept in a SQLite database instead, and the result is the same: verdict, counts, depth, counterexample.

  • Providers. The search talks to store::StateStore (put_chunk, get_chunk), which knows nothing of states. store::sql::SqlStore implements it with one table and three statements (store::sql), restricted to what a Durable Object's SQLite storage accepts, over anything that runs a statement (Sql): rusqlite on a file (sql::File, cargo feature sqlite), or the exec of an object handed in from JavaScript (wasm.rs, JsSql). Memory is not a provider: with CheckOptions::store None nothing in store.rs is called.
  • Chunks. Stored encodes each new state (codec.rs, the encoding the parallel search uses) as a record with its parent and action, and hands the provider a chunk once its records hold 64 kB. A chunk ends with the offsets of its records and a checksum, so a provider that returns other bytes is an error, not a wrong result. The states not yet in a full chunk are in memory.
  • Reads. The queue reads chunks in order (Stored::next). Traces, temporal properties and -dump read states in any order through Checker::state_at (Stored::get, which keeps the last 64 chunks). With a store Checker.states holds a placeholder for every state, as in id mode: every read of a state must go through state_at.
  • What it costs. Nothing may keep every state alive, so with a store the search runs on one worker, on values, without interning them and without the step cache (whose keys are ids of interned values). Where the id search is what makes a model fast, a store is several times slower.
  • What stays in memory. The fingerprint set, parent, act and a placeholder per state (40 to 65 bytes per state); the recorded graph, with temporal properties or -dump; a state with a value that has no encoding (an operator, a lazy function, a set defined by a predicate), which is kept as it is.
  • Failures. The provider's first failure ends the search with "The state store failed: ..." and no trace, and nothing more is asked of it. A failure while a trace or a temporal property reads a state ends the process (store::fatal).
  • Scope. The database is the working storage of one run: records hold ids of this process's string table, and a check empties the table when it starts. Continuing a run from its database and a fingerprint set outside memory are not implemented.

Liveness checking

With temporal properties the search records the state graph (Checker::succ, succ_act; with VIEW or SYMMETRY also the real successor states). liveness.rs turns the negation of "fairness implies the properties" into a disjunction of branches, each a tableau formula plus possible-error models of []<> and <>[] conditions, as TLC does. A check (check_group) builds the product of the state graph and the tableau, finds its strongly connected components (edges that break a <>[] condition are left out) and looks for one that fulfils every promise and every []<> condition; the counterexample is a shortest path into the component and a cycle through the witnesses. Predicates, actions and ENABLED are evaluated on the states themselves and remembered per state and per edge.

When the check runs is TLC's -lncheck (CheckOptions::lncheck):

  • final: once, on the complete graph.
  • default: also during the search, on the graph of the states expanded so far (liveness::periodic). A state that is not expanded yet is not a node, as in TLC, so the partial graph is a subgraph of the complete one and a lasso found in it is a counterexample. The run stops there with exit status 13.
  • off: never (TLC reports success).

One kind of violation does not wait for any of these checks, in TLC and here (Onfly, liveness::expanded): when the specification puts no []<> or <>[] condition on a counterexample (no fairness) and the property is safety-shaped, as [](P => []Q) is, a counterexample is a finite behaviour followed by stuttering. The branch's tableau then has the empty particle, and the graph of (state, particle) pairs is followed during the search, as far as the expanded states go; when a state has just been expanded and a pair at it has the empty particle as a tableau successor, the path to that pair is reported: no stuttering line, exit status 12, and after a deadlock at the same state if there is one. The predicates of such a branch are therefore evaluated once more than in the checks of the graph; other models pay one test per expanded state. Checker::search and the merge of Par::level call it at the same point, after the successors of the state are recorded (in parallel, in Par::merge_checked, below).

TLC decides by the clock when a periodic check happens: 3 s after the search starts, then once a minute, if the graph grew by more than 10 % and liveness checking has taken under 20 % of the run time (ModelChecker.doPeriodicWork, LiveCheck.doLiveCheck). So with the default TLC's output, its counterexample and, when it stops early, its state counts differ from run to run. everystate counts states instead: the first check runs when LNCHECK_FIRST = 65536 states have been expanded (TLC has between 700 and 320,000 after its 3 s, depending on the model), the following ones at every growth by LNCHECK_GROWTH = 4. The check runs between two expansions, at exactly that count, so the result is the same on every machine and with any number of workers, and a model with fewer than 65536 states behaves as with -lncheck final. The factor bounds the cost: a check keeps the graph arrays and every evaluated predicate for the next one (Kept), so what is repeated is the product graph and the component search, and the periodic checks together walk at most a third of what the final check walks, or four thirds when the search ends right after one. On test/liveness/LnShallow with 2,000,000 states and a property that holds this is 0.9 s of a 10 s run.

Checker::search asks sid == live_next before it expands state sid; Par::level asks the same in the merge (merge_checked), after bringing the checker to the state the one-thread search has at that point (head, depth, the states below sid rebuilt from their serialised form). The two must stay in step. While temporal properties are checked during the search (Checker::checks_during_search), a level is merged at its end only, one state at a time, and never by level_ids (which records no graph). EVERYSTATE_LNCHECK_FIRST moves the first check, which is how the tests exercise it on small models.

What must change together

  • Semantics of an expression or an action (eval.rs): check whether compile.rs compiles that construct itself. If it does, change both, or make the compiler fall back for it. The list of what falls back is the set of fb(...) / fb_act(...) call sites.
  • What an action reads or how it assigns in compiled code: the step cache's recording (Rec, Loc, DOp in compile.rs and stepcache.rs) must describe it, or the unit must mark the evaluation as not storable (rec.bad).
  • A new operator with an effect or an order-dependent result: it must call worker_impure (and return impure_err on a worker), and its module must stay out of pure_module in compile.rs.
  • The loop body of Checker::search (constraints, fingerprint, invariants, action properties, the order of TLCGet("level") updates) and par::expand / par::expand_init: they are two copies of the same steps and must stay in step.
  • Where a periodic liveness check may run: Checker::search and Par::merge_checked test sid == live_next at the same point, before state sid is expanded; both call liveness::expanded after state sid is expanded when onfly is set.
  • The search on ids and the search on values: successors_ids must give the successors, in the order, that successors_flat gives; par::expand_ids mirrors the id loop of Checker::search.
  • The fingerprint (value_word, Hasher, var_term, fp_finish): fingerprint, row_fingerprint and parent_terms must agree; par.rs uses the same functions. The words of composite values (fn_tag, set_tag, entry_term, elem_term) and what the step cache derives from them (IdOp, key_shift, stepcache::delta_word, compile::delta_fingerprint) must give the same word as the value computed whole; EVERYSTATE_VERIFY_DELTAS=1 checks it during a run.
  • The value representation: codec.rs serialises every variant (T_* tags); stepcache::vsize sizes them; checker::permute maps model values through them.
  • Where a new state is kept: compute_init and the loop of Checker::search push it as a row of ids (idmode), to the state store (ext) or to states; state_at reads all three (and the parallel search's bytes), and gives the placeholder for a state that was released ("Which states are kept").
  • The statements of the state store (store::sql) are listed in test/store.test.ts, which fails on any other statement.

Soundness rules that are easy to break

Where a rule was learned from a bug, the bug is named.

  1. A lazy filtered set must count its state reads when it is made, and be enumerated when it is assigned to a variable. {x \in S : P(x)} over a base that is not explicit (S a product, a function set, SUBSET, ...) is kept as SetK::Filter with the context and the states it was made in; P is evaluated later. Two bugs came from that (issues #3, #10, #15, #18; fixed in 0.4.2, commit 93212bf; cases in test/regress/cases.mjs). First, making the set did not count as reading the state, so a definition or LET cell holding it was cached as a constant and reused in later states: missed and false invariant violations, wrong counts. Now eval.rs (E::SetFilter) bumps st_touch / pr_touch by the level of the predicate at creation, and that level includes what the local names in the predicate stand for when that is delayed (an operator argument, a LET definition, the substitution of an instance: delayed_level; issue #45, where such a name read the state and the set was still taken for a constant). A zero-argument definition is also cached only when its level is constant, as TLC does. Second, assigned to a variable, the set kept a reference to the next-state buffer, which is blank again by the time the state is fingerprinted. Now every assignment to a variable goes through Evaluator::settle, which enumerates such sets; the compiled assignment paths call it too. If you add a way to assign a variable, call settle.

  2. A cached value is valid for one state, identified by state id. Thunks and LET cells (force_cell) record, with the value, whether computing it read the state (st_touch, pr_touch counters compared before and after): no read means constant (ANY), otherwise the value is tied to cur.id and is not reused in init mode or under a prime. Anything that reads the state without going through the variable lookup must bump the counter (rule 1 is the case that was missed; TLCGet, Trace and CounterExample do it in stdlib.rs). LazyFcn memoises recursive functions under the same test. State buffers are reused during enumeration, so never key a cache on a buffer's address.

  3. String order is TLC's interning order (see "String order"). Breaking it does not crash; it changes which element CHOOSE picks and the order of successors, so traces and sometimes counts differ from TLC.

  4. A cache compares full keys; a hash only finds the entry. A step-cache hit compares the unit, the bound ids, the template version and the id found at every location; ids of one table are equal exactly when the values are (see "Value ids"). The symmetry memo (permute_memo) confirms with val_eq. The exception is the fingerprint set itself, which is 64-bit hashes only, as in TLC, with the collision probability printed. TLC's own Unicode*Fingerprint tests show what a weak hash does there: TLC fingerprints strings by their low bytes and drops reachable states; everystate deliberately does not copy that (CONFORMANCE.md).

  5. Compiled code must not have effects before it is known to succeed, because a failed attempt is redone by the tree-walker (see "Compiled plans"). The same holds for worker threads, whose work may be thrown away and redone sequentially.

  6. Operator parameters are evaluated lazily and only where used, as in TLC: Op(f, 1) == f[1] applied to a function constructor computes one point (test/regress/port/LazyParam.tla divides by zero otherwise). The compiler binds parameters by name for the same reason.

Environment variables

Read by the binary:

variable effect
EVERYSTATE_EVAL=tree Tree-walker only: no compiled plans, no step cache.
EVERYSTATE_STEP_CACHE off: no step cache. always: every unit uses it whether or not it pays (testing). on: as the default, and also with EVERYSTATE_EVAL=tree (which then still compiles).
EVERYSTATE_STEP_CACHE_MB Budget of the step cache per worker in MB (default 32).
EVERYSTATE_EVAL_STATS Print on standard error, at the end, how many evaluations were compiled, redone or fell back, and the step cache's counters.
EVERYSTATE_EVAL_DEBUG Print why an action is not compiled, each fallback site the first time it runs, and with EVERYSTATE_EVAL_STATS the verdict per unit.
EVERYSTATE_PAR_MIN Smallest level searched in parallel (default 64); setting it also starts the workers at once. Test hook.
EVERYSTATE_PAR_CHUNK States per unit of work handed to a worker (default: chosen per level). Test hook.
EVERYSTATE_PAR_DEBUG Print what the workers did, on standard error (every line starts with par).
EVERYSTATE_VERIFY_DELTAS Check every fingerprint the step cache computes from changes against the one of the successor built (testing; slow).
EVERYSTATE_LNCHECK_FIRST Number of expanded states at the first periodic liveness check (default 65536). Test hook.
EVERYSTATE_STORE_CHUNK Bytes per chunk of -store sqlite:FILE (default 65536). Test hook: with small chunks a small model reads its states back from the database.
EVERYSTATE_SIM_REPLAY=1 Simulation replays every trace it reports against the exhaustive successor function (self-check used by scripts/gates/simulate-check.mjs).
EVERYSTATE_DEBUG_ASSUMES Report every failing ASSUME instead of stopping at the first; =2 also lists each one checked.

Read by the launcher and the scripts:

variable effect
EVERYSTATE_BINARY bin/everystate.mjs: the native binary to run instead of native/<platform>-<arch>/.
EVERYSTATE_REFS Where the reference material is (default refs/); see scripts/refs.mjs, scripts/fetch-refs.sh.
EVERYSTATE_CMD The binary the gate scripts test (default target/release/everystate).
EVERYSTATE_JAVA_CMD statechart-corpus.mjs: the command that stands in for java (default <binary> java).
EVERYSTATE_TLA2TOOLS_URL fetch-refs.sh: an address to download the pinned tla2tools.jar from; accepted only with the pinned SHA-256.

Tests and gates

npm test needs only the built binary and wasm/everystate.wasm: unit tests of the CLI, pretty-printer, PlusCal translator, simulation, conformance, liveness (liveness.test.ts, lncheck.test.ts) and the WebAssembly API (test/*.test.ts), the regression suite (test/regress.test.ts), the community-module fixtures (test/community.mjs) and the worker tests (test/workers.mjs). test/store.test.ts compares the state store with memory; its native half runs only when the binary was built with --features sqlite (CI builds that after the default build and runs the file again), its WebAssembly half needs node:sqlite (Node 22.13 or later).

npm run gates (scripts/gates.mjs) runs that and the conformance gates against reference material fetched by scripts/fetch-refs.sh: the tlaplus/Examples manifests, the statechart corpus, workers against one worker, the PlusCal corpus, and TLC's own test models (--skip tlc leaves the last one out). All of it takes about twelve minutes on four cores. CONFORMANCE.md says what each compares. .github/workflows/gates.yml runs the gates except tlc on every pull request.

The regression suite runs every case under five settings (default, tree-walker, no step cache, step cache forced, two workers) and requires the exit status and state counts that Java TLC gave (test/regress/expected.json). To add a case, add it to test/regress/cases.mjs (inline, or as files under test/regress/), run TLC on it (scripts/tlc.sh), and record TLC's exit status and counts in expected.json. If everystate disagrees with TLC, the case does not go in until it agrees.

Debugging a wrong state count or verdict

The paths above must agree, so the first question is which of them is wrong.

  1. Run the model with EVERYSTATE_EVAL=tree, with EVERYSTATE_STEP_CACHE=off, with EVERYSTATE_STEP_CACHE=always, and with -workers 2. If the tree-walker agrees with TLC and another setting does not, the bug is in that layer (compiler, step cache, parallel merge) and the tree-walker is your oracle. If the tree-walker disagrees with TLC, the bug is in eval.rs, value.rs, model.rs or the standard modules.
  2. Compare with TLC: scripts/tlc.sh /abs/path/Spec.tla Spec.cfg runs the reference jar. -dump dot file.dot on both sides gives the two state graphs. Shrink the spec until the difference is one state.
  3. EVERYSTATE_EVAL_DEBUG=1 EVERYSTATE_EVAL_STATS=1 shows what was compiled, what fell back and what the step cache did.
  4. Across a corpus: node scripts/gates/engine-diff.mjs --a SIDE --b SIDE --corpus examples,bench,tlc runs two builds or two settings on every model and requires identical output (JSON result with the full trace, and the text). A side is a binary path, env:EVERYSTATE_EVAL=tree or flags:-workers 4; for the state store, --b "flags:-store sqlite:/tmp/diff.db" --jobs 1 --env EVERYSTATE_STORE_CHUNK=2000 against the same binary.
  5. node scripts/gates/fuzz-specs.mjs --a SIDE --b SIDE --n 2000 does the same on random small specifications; --keep DIR keeps them. scripts/gates/pcal-fuzz.mjs fuzzes the PlusCal translator.
  6. When it is fixed, add the shrunken spec to the regression suite with TLC's numbers.

A wrong count with a right verdict is most often rule 1 or 2 above (a value cached across states), or string order (rule 3) when the difference is in a trace or a CHOOSE.

Adding an operator or a module

A module TLC implements in Java (or that should be fast) is implemented in Rust:

  • A standard module is built in stdlib::build_stdlib with the MB builder: m.op(name, arity, |ev, args| ...), op_ops when some arguments are operators (bit mask), op_lazy when the operator must receive unevaluated thunks, val for a constant. Arguments arrive evaluated unless lazy.
  • An operator of a bundled TLA+ module (CommunityModules) keeps its TLA+ definition in lib/*.tla and gets a native override: add a tuple (module, operator, operator-argument mask, lazy, function) to overrides() in stdlib.rs (hot operators) or community.rs. apply_overrides replaces the definition when the module is loaded. Without an override the TLA+ definition is evaluated.
  • A new bundled module: put Name.tla in lib/ and run node scripts/export-lib.mjs (no argument) to regenerate src/bundled.rs.

Rules for the implementation: report errors with TLC's wording (the tests compare text); reach files, environment and processes only through ev.host; if the operator has an effect or its result depends on the order of exploration, start with if worker_impure("...") { return impure_err(); } and bump ev.st_touch if its result may differ between states (see rule 2); do not add its module to pure_module. Then add a fixture under test/community/ or a case to the regression suite, with TLC's result.

Releases

  1. A pull request that changes what users get adds a changeset: npx changeset, pick patch / minor / major, one line for the changelog (.changeset/README.md).
  2. On every push to main, .github/workflows/version.yml opens or updates the "Version Packages" pull request. It runs npm run version: changeset version bumps package.json and CHANGELOG.md, and scripts/release/sync-version.mjs copies the version to Cargo.toml and Cargo.lock.
  3. Merging that pull request changes package.json on main, which starts .github/workflows/release.yml. It builds the native binary for five targets, rebuilds the WebAssembly module, runs npm test, and publishes to npm only if that version is not there yet (trusted publishing, no stored token). Then it attaches the binaries to a GitHub release vX.Y.Z, updates the Homebrew formula in mattzcarey/homebrew-tap (scripts/release/brew-formula.mjs; needs the secret HOMEBREW_TAP_TOKEN, skipped without it) and publishes the crate to crates.io (trusted publishing).
  4. Before merging the Version pull request, run npm run gates locally including tlc; CI does not run that gate.

Every GitHub Action in every workflow is pinned to a full commit SHA with the version in a comment. A tag or branch can be moved by whoever controls the action, and the publish jobs can mint the tokens npm and crates.io trust. Update a pin by hand, after reading what changed, and resolve the tag to its commit yourself (git ls-remote --tags https://github.com/<owner>/<action>).

If you change Rust code that the WebAssembly build includes, rebuild wasm/everystate.wasm (sh wasm/build.sh) and commit it, so that npm test and a git install use the current code. The published package always contains a freshly built module.