everystate 0.1.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +121 -86
  2. package/bin/everystate.mjs +35 -0
  3. package/native/darwin-arm64/everystate +0 -0
  4. package/native/darwin-x64/everystate +0 -0
  5. package/native/linux-arm64/everystate +0 -0
  6. package/native/linux-x64/everystate +0 -0
  7. package/native/win32-x64/everystate.exe +0 -0
  8. package/package.json +29 -24
  9. package/skills/formal-verification/SKILL.md +115 -0
  10. package/skills/formal-verification/example/Charge.cfg +7 -0
  11. package/skills/formal-verification/example/Charge.tla +61 -0
  12. package/skills/formal-verification/example/ChargeBroken.cfg +7 -0
  13. package/wasm/cli.mjs +26 -0
  14. package/wasm/everystate.d.ts +33 -0
  15. package/wasm/everystate.mjs +112 -0
  16. package/wasm/everystate.wasm +0 -0
  17. package/CONFORMANCE.md +0 -64
  18. package/dist/bundled.d.ts +0 -1
  19. package/dist/bundled.js +0 -2
  20. package/dist/cfg.d.ts +0 -24
  21. package/dist/cfg.js +0 -252
  22. package/dist/checker.d.ts +0 -96
  23. package/dist/checker.js +0 -520
  24. package/dist/cli.d.ts +0 -2
  25. package/dist/cli.js +0 -4
  26. package/dist/community.d.ts +0 -17
  27. package/dist/community.js +0 -1381
  28. package/dist/entry.d.ts +0 -2
  29. package/dist/entry.js +0 -39
  30. package/dist/eval.d.ts +0 -119
  31. package/dist/eval.js +0 -1533
  32. package/dist/index.d.ts +0 -33
  33. package/dist/index.js +0 -24
  34. package/dist/java.d.ts +0 -2
  35. package/dist/java.js +0 -6
  36. package/dist/lexer.d.ts +0 -17
  37. package/dist/lexer.js +0 -255
  38. package/dist/liveness.d.ts +0 -80
  39. package/dist/liveness.js +0 -855
  40. package/dist/main.d.ts +0 -40
  41. package/dist/main.js +0 -494
  42. package/dist/model.d.ts +0 -56
  43. package/dist/model.js +0 -582
  44. package/dist/modules.d.ts +0 -91
  45. package/dist/modules.js +0 -649
  46. package/dist/node-host.d.ts +0 -2
  47. package/dist/node-host.js +0 -25
  48. package/dist/parser.d.ts +0 -30
  49. package/dist/parser.js +0 -1114
  50. package/dist/pprint.d.ts +0 -7
  51. package/dist/pprint.js +0 -647
  52. package/dist/stdlib.d.ts +0 -14
  53. package/dist/stdlib.js +0 -588
  54. package/dist/values.d.ts +0 -150
  55. package/dist/values.js +0 -822
package/README.md CHANGED
@@ -1,125 +1,160 @@
1
1
  # everystate
2
2
 
3
- A TLA+ model checker written in pure TypeScript. No Java, no native code, no runtime dependencies.
3
+ A TLA+ model checker with no Java dependency, written in Rust. It reads ordinary `.tla` specs and
4
+ TLC `.cfg` files, checks every reachable state, and reports results in TLC's format.
4
5
 
5
- It reads ordinary TLA+ modules and TLC configuration files, explores the state space the way TLC
6
- does, and prints results in TLC's format, so tools written against TLC keep working.
6
+ - Safety and liveness checking, fairness, symmetry, `VIEW`, `ALIAS`.
7
+ - TLC-compatible text output, exit codes, `-tool` framing and `-dump`.
8
+ - The standard and community modules are built in.
9
+ - One native binary, or WebAssembly for Node, Bun and workers.
10
+
11
+ ## Install
7
12
 
8
13
  ```sh
9
- npx everystate Spec.tla # uses Spec.cfg next to the spec
10
- npx everystate -config MC.cfg -deadlock Spec.tla
14
+ npm install -g everystate # prebuilt binary for Linux, macOS and Windows
15
+ cargo install everystate # or build from source
16
+ ```
17
+
18
+ ## Example
19
+
20
+ `examples/Counter.tla`:
21
+
22
+ ```tla
23
+ ---- MODULE Counter ----
24
+ EXTENDS Naturals
25
+ VARIABLE n
26
+
27
+ Init == n = 0
28
+ Next == n < 5 /\ n' = n + 1
29
+ Spec == Init /\ [][Next]_n
30
+
31
+ TypeOK == n \in 0..5
32
+ NeverFour == n /= 4
33
+ ====
11
34
  ```
12
35
 
36
+ `examples/Counter.cfg`:
37
+
13
38
  ```
14
- Error: Invariant NotSolved is violated.
39
+ SPECIFICATION Spec
40
+ INVARIANT TypeOK
41
+ INVARIANT NeverFour
42
+ CHECK_DEADLOCK FALSE
43
+ ```
44
+
45
+ ```sh
46
+ everystate examples/Counter.tla
47
+ ```
48
+
49
+ ```
50
+ Error: Invariant NeverFour is violated.
15
51
  Error: The behavior up to this point is:
16
52
  State 1: <Initial predicate>
17
- /\ big = 0
18
- /\ small = 0
53
+ n = 0
19
54
 
20
- State 2: <FillBig line 16, col 12 to line 16, col 37 of module DieHard>
21
- /\ big = 5
22
- /\ small = 0
55
+ State 2: <Next line 6, col 9 to line 6, col 27 of module Counter>
56
+ n = 1
23
57
  ...
24
- 73 states generated, 14 distinct states found, 1 states left on queue.
58
+ State 5: <Next line 6, col 9 to line 6, col 27 of module Counter>
59
+ n = 4
60
+
61
+ 5 states generated, 5 distinct states found, 0 states left on queue.
25
62
  ```
26
63
 
27
- Runs on Node 20+ and Bun. It uses only `node:fs`, `node:path`, `node:worker_threads` and
28
- `node:child_process` in its CLI host; the checker itself (`import { check } from 'everystate'`) needs
29
- no host APIs at all and runs anywhere JavaScript does.
30
-
31
- ## What it does
32
-
33
- - **Language**: the full TLA+ expression language as TLC supports it — modules, `EXTENDS`,
34
- `INSTANCE ... WITH` (named, parameterised, `LOCAL`, inside `LET`), recursive operators and
35
- functions, higher-order operators, `LAMBDA`, `CASE`, `CHOOSE`, `EXCEPT`, junction lists, action
36
- operators (`'`, `UNCHANGED`, `ENABLED`, `[A]_v`, `<<A>>_v`, `\cdot`), temporal operators, proofs
37
- (parsed and ignored).
38
- - **Checking**: invariants, deadlock, state and action constraints, `[][A]_v` action properties,
39
- refinement (`PROPERTY OtherSpec`), and liveness under weak and strong fairness
40
- (`[]<>`, `<>[]`, `~>`, `WF_`, `SF_`) with lasso counterexamples.
41
- - **Configuration**: `SPECIFICATION`, `INIT`/`NEXT`, `CONSTANT(S)` (values, model values, `<-`
42
- substitution), `INVARIANT(S)`, `PROPERTY/PROPERTIES`, `CONSTRAINT(S)`, `ACTION_CONSTRAINT(S)`,
43
- `SYMMETRY`, `VIEW`, `CHECK_DEADLOCK`.
44
- - **Standard modules**, implemented natively: `Naturals`, `Integers`, `Reals` (integers only),
45
- `Sequences`, `FiniteSets`, `Bags`, `TLC`, `TLCExt`, `Randomization`.
46
- - **Community modules**, bundled: `FiniteSetsExt`, `SequencesExt`, `Functions`, `Folds`, `Graphs`,
47
- `UndirectedGraphs`, `Relation`, `BagsExt`, `Bitwise`, `Combinatorics`, `Json`, `CSV`, `IOUtils`,
48
- `VectorClocks`, `DyadicRationals`, `Statistics`, and the TLAPS library modules (`TLAPS`,
49
- `FiniteSetTheorems`, `NaturalsInduction`, ...) so that specs with proofs load.
50
- - **Output**: TLC's messages, `-tool` framing, exit codes, trace format with action names and
51
- source locations, 80-column value wrapping, and `-dump dot,actionlabels`.
52
-
53
- ## Using it where a tool expects Java + TLC
54
-
55
- `everystate-java` accepts the command line of `java -cp tla2tools.jar tlc2.TLC ...` (and of
56
- `tla2sany.xml.XMLExporter`). Point a TLC-driving script at it instead of a JVM:
64
+ Exit status is 12, as with TLC.
65
+
66
+ ### For scripts and agents
57
67
 
58
68
  ```sh
59
- JAVA="$(npm root)/everystate/dist/java.js" TLA2TOOLS=unused some-tool-that-runs-tlc Spec.tla
69
+ everystate -json examples/Counter.tla
70
+ ```
71
+
72
+ ```json
73
+ {"status":"invariant","name":"NeverFour","generated":5,"distinct":5,"queue":0,"depth":5,
74
+ "trace":[{"action":null,"state":{"n":"0"}},{"action":"Next","state":{"n":"1"}}, ...]}
60
75
  ```
61
76
 
62
- The pstack `statechart` skill script runs unmodified this way.
77
+ ### From JavaScript (WebAssembly)
63
78
 
64
- ## API
79
+ The npm package also exports the engine compiled to WebAssembly:
65
80
 
66
81
  ```ts
67
- import { check, fmt } from 'everystate';
82
+ import { check } from 'everystate';
68
83
 
69
- const { result, model } = check({
70
- root: 'Spec',
71
- modules: { Spec: tlaSource }, // plus any modules it imports that are not bundled
72
- config: 'SPECIFICATION Spec\nINVARIANT TypeOK',
84
+ const { result } = check({
85
+ root: 'Counter',
86
+ modules: { Counter: tlaSource },
87
+ config: 'SPECIFICATION Spec\nINVARIANT NeverFour\nCHECK_DEADLOCK FALSE',
73
88
  });
74
- result.status; // 'ok' | 'invariant' | 'deadlock' | 'liveness' | 'action-property' | ...
75
- result.distinct; // distinct states found
76
- result.trace; // counterexample: [{ state, action }]
89
+ result.status; // 'invariant'
90
+ result.name; // 'NeverFour'
77
91
  ```
78
92
 
79
- ## How it is verified
93
+ `checkAsync` runs the same check in a worker with a large stack, for deeply recursive specs.
94
+ The WebAssembly build is about 2x slower than native and cannot use the file-based community
95
+ operators.
80
96
 
81
- Real TLC is the specification. Three suites compare against it:
97
+ ### In place of Java TLC
82
98
 
83
- | Suite | What is compared | Command |
84
- |---|---|---|
85
- | [tlaplus/Examples](https://github.com/tlaplus/Examples) manifest | result kind and exact generated / distinct state counts recorded upstream | `npm run conformance:examples -- /path/to/Examples` |
86
- | TLC's own `test-model` directory | outcome, state counts and trace length against a live run of `tla2tools.jar` | `npm run conformance:tlc -- /path/to/test-model` |
87
- | pstack `statechart` corpus | byte-identical charts and reports produced by the real script with everystate standing in for Java | `npm run conformance:statechart -- /path/to/statechart/scripts` |
99
+ `everystate java ...` (or `everystate-java ...` from npm) accepts the `java -cp tla2tools.jar tlc2.TLC ...` command line, so tools that
100
+ shell out to TLC can point at it instead of a JVM. The pstack `statechart` script runs unmodified
101
+ this way.
88
102
 
89
- `npm test` runs the self-contained tests (no Java needed): the checker API, the value
90
- pretty-printer against 337 outputs recorded from the Java implementation, and the community-module
91
- operators against fixtures validated with real TLC.
103
+ ## Agent skill
92
104
 
93
- Current results are in [CONFORMANCE.md](CONFORMANCE.md).
105
+ [`skills/formal-verification`](skills/formal-verification/SKILL.md) teaches a coding agent to
106
+ model-check a design with everystate: choose the promise, model the steps, run the check, see it
107
+ fail, report the counterexample in the code's words. It comes with a worked example
108
+ (`example/Charge.tla`). Copy the folder into your agent's skills directory, for example
109
+ `.claude/skills/`.
94
110
 
95
- ## Not supported (yet)
111
+ ## Options
96
112
 
97
- - Simulation / generation mode (`-simulate`, `-generate`), depth-first iterative deepening.
98
- - Multiple workers, disk-backed state queues and fingerprint sets, checkpointing: everything is in
99
- memory, so the practical limit is a few million distinct states.
100
- - The PlusCal translator (specs that already contain their translation work).
101
- - Trace-explorer spec generation, the debugger, coverage statistics, Java module overrides.
102
- - TLAPS proofs are parsed and skipped, not checked.
113
+ ```
114
+ everystate [options] SPEC[.tla]
115
+ -config FILE configuration file (default: SPEC.cfg)
116
+ -deadlock do not check for deadlock
117
+ -json one JSON result object
118
+ -tool TLC's machine-readable message framing
119
+ -dump dot,actionlabels FILE write the state graph
120
+ ```
103
121
 
104
- ## Rust port
122
+ Exit status: 0 success, 10 assumption, 11 deadlock, 12 safety, 13 liveness, 150 parse error,
123
+ 151 config error.
105
124
 
106
- `rust/` holds `verify-rs`, a Rust port of the safety checker (no liveness, `-tool` or `-dump`),
107
- built to compare speed. It is about 2x faster than this TypeScript engine on Node and roughly level
108
- with single-worker Java TLC; see `rust/BENCHMARK.md`. The TypeScript engine is the complete one.
125
+ ## How it is checked
109
126
 
110
- ## Layout
127
+ Real TLC is the reference (details in [CONFORMANCE.md](CONFORMANCE.md)):
111
128
 
129
+ - [tlaplus/Examples](https://github.com/tlaplus/Examples), models up to 5 s: 122 of 122 match on
130
+ result and exact state counts.
131
+ - TLC's own `test-model` suite, run side by side with `tla2tools.jar`: 384 of 414 match.
132
+ - pstack `statechart` corpus: 33 of 33 outputs byte-identical.
133
+
134
+ Faster than single-worker Java TLC on all 12 benchmark models (1.1x to 4.6x, thin on three of
135
+ them), with near-instant start-up: [BENCHMARK.md](BENCHMARK.md).
136
+
137
+ ## Not supported
138
+
139
+ Simulation mode, multiple workers, disk-backed state storage (everything is in memory, so a few
140
+ million distinct states is the practical limit), the PlusCal translator (already-translated specs
141
+ work), Java module overrides, labels and subexpression selectors, and TLAPS proof checking (proofs
142
+ are parsed and skipped).
143
+
144
+ ## Development
145
+
146
+ ```sh
147
+ npm run build # native binary and wasm/everystate.wasm
148
+ npm test # WASM API, pretty-printer and community-module tests
112
149
  ```
113
- src/lexer.ts, parser.ts TLA+ front end
114
- src/modules.ts module loading, name resolution, expression levels
115
- src/values.ts values and TLC's ordering
116
- src/eval.ts evaluator and next-state enumeration
117
- src/stdlib.ts, community.ts native standard and community module operators
118
- src/model.ts, cfg.ts configuration -> checkable model
119
- src/checker.ts, liveness.ts breadth-first search, liveness (tableau + SCC)
120
- src/main.ts CLI, TLC-compatible output, java shim
121
- ```
150
+
151
+ Releases use [changesets](.changeset/README.md): add one with `npx changeset` in your pull request,
152
+ then merge the "Version Packages" pull request that appears. That bumps `package.json` and
153
+ `Cargo.toml`, and `.github/workflows/release.yml` builds the binaries and publishes to npm and
154
+ crates.io (trusted publishing, no tokens).
155
+
156
+ An earlier pure-TypeScript engine is in the git history at commit `e8c67ce` (npm `everystate@0.1.0`).
122
157
 
123
158
  ## License
124
159
 
125
- MIT. Bundled TLA+ library modules keep their own (MIT / BSD) licenses.
160
+ MIT
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+ // Launcher: runs the prebuilt native binary for this platform (shipped in ../native/<platform>-<arch>/),
3
+ // or falls back to the WebAssembly build, which only prints a JSON result.
4
+ import { spawnSync } from 'node:child_process';
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+
8
+ const exe = process.platform === 'win32' ? 'everystate.exe' : 'everystate';
9
+
10
+ function nativeBinary() {
11
+ if (process.env.EVERYSTATE_BINARY) return process.env.EVERYSTATE_BINARY;
12
+ const file = path.join(import.meta.dirname, '..', 'native', `${process.platform}-${process.arch}`, exe);
13
+ if (!fs.existsSync(file)) return null;
14
+ try { fs.accessSync(file, fs.constants.X_OK); } catch { try { fs.chmodSync(file, 0o755); } catch {} }
15
+ return file;
16
+ }
17
+
18
+ // `everystate-java ...` is `everystate java ...`: the stand-in for `java -cp tla2tools.jar tlc2.TLC`.
19
+ const asJava = path.basename(process.argv[1] ?? '').startsWith('everystate-java');
20
+ const args = asJava ? ['java', ...process.argv.slice(2)] : process.argv.slice(2);
21
+
22
+ const bin = nativeBinary();
23
+ if (bin) {
24
+ const r = spawnSync(bin, args, { stdio: 'inherit' });
25
+ if (r.error) { console.error(`everystate: cannot run ${bin}: ${r.error.message}`); process.exit(1); }
26
+ if (r.signal) process.kill(process.pid, r.signal);
27
+ process.exit(r.status ?? 1);
28
+ } else if (asJava) {
29
+ console.error(`everystate: no prebuilt binary for ${process.platform}-${process.arch}; the Java stand-in needs one (cargo install everystate).`);
30
+ process.exit(1);
31
+ } else {
32
+ console.error(`everystate: no prebuilt binary for ${process.platform}-${process.arch}; using the WebAssembly build (JSON output only).`);
33
+ process.argv = [process.argv[0], process.argv[1], ...args];
34
+ await import('../wasm/cli.mjs');
35
+ }
Binary file
Binary file
Binary file
Binary file
Binary file
package/package.json CHANGED
@@ -1,53 +1,58 @@
1
1
  {
2
2
  "name": "everystate",
3
- "version": "0.1.0",
4
- "description": "A TLA+ model checker (TLC-compatible) written in pure TypeScript. No Java.",
3
+ "version": "0.3.1",
4
+ "description": "A TLA+ model checker with no Java dependency (TLC-compatible). Prebuilt native binaries, with a WebAssembly build for use from JavaScript.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
- "bin": {
8
- "everystate": "dist/cli.js",
9
- "everystate-java": "dist/java.js"
10
- },
11
- "main": "dist/index.js",
12
- "types": "dist/index.d.ts",
7
+ "main": "wasm/everystate.mjs",
8
+ "types": "wasm/everystate.d.ts",
13
9
  "exports": {
14
10
  ".": {
15
- "types": "./dist/index.d.ts",
16
- "default": "./dist/index.js"
11
+ "types": "./wasm/everystate.d.ts",
12
+ "default": "./wasm/everystate.mjs"
17
13
  }
18
14
  },
15
+ "bin": {
16
+ "everystate": "bin/everystate.mjs",
17
+ "everystate-java": "bin/everystate.mjs"
18
+ },
19
19
  "files": [
20
- "dist",
20
+ "bin/everystate.mjs",
21
+ "native",
22
+ "wasm/everystate.mjs",
23
+ "wasm/everystate.d.ts",
24
+ "wasm/everystate.wasm",
25
+ "wasm/cli.mjs",
26
+ "skills",
21
27
  "README.md",
22
- "CONFORMANCE.md",
23
28
  "LICENSE"
24
29
  ],
25
- "engines": {
26
- "node": ">=20"
27
- },
28
30
  "scripts": {
29
- "build": "tsc -p .",
30
- "bundle": "node scripts/bundle.mjs",
31
- "test": "node --experimental-strip-types --no-warnings --test test/*.test.ts",
31
+ "build": "cargo build --release && sh wasm/build.sh",
32
+ "test": "node --experimental-strip-types --no-warnings --test test/*.test.ts && node test/community.mjs",
32
33
  "conformance:examples": "node scripts/conformance.mjs",
33
34
  "conformance:tlc": "node scripts/diff-tlc.mjs",
34
35
  "conformance:statechart": "node scripts/statechart-corpus.mjs",
35
- "prepublishOnly": "npm run build"
36
+ "bench": "node scripts/bench.mjs",
37
+ "changeset": "changeset",
38
+ "version": "changeset version && node scripts/sync-version.mjs"
36
39
  },
37
- "devDependencies": {
38
- "typescript": "^5.8.0",
39
- "@types/node": "^22.0.0"
40
+ "engines": {
41
+ "node": ">=20"
40
42
  },
41
43
  "keywords": [
42
- "tla+",
44
+ "tla",
43
45
  "tlaplus",
44
46
  "tlc",
45
47
  "model-checker",
46
48
  "formal-verification",
47
- "formal-methods"
49
+ "wasm"
48
50
  ],
49
51
  "repository": {
50
52
  "type": "git",
51
53
  "url": "git+https://github.com/mattzcarey/everystate.git"
54
+ },
55
+ "devDependencies": {
56
+ "@changesets/cli": "^3.0.3"
52
57
  }
53
58
  }
@@ -0,0 +1,115 @@
1
+ ---
2
+ name: formal-verification
3
+ description: "Model-check a design with TLA+ and everystate (no Java needed): write a small model of the code, check every reachable state, and report any counterexample in the code's own words. Use for races, retries, timeouts, locks, leases, queues, state machines, distributed protocols, or when asked to \"model-check this\", \"prove this invariant\", or \"can these steps happen in a bad order?\"."
4
+ ---
5
+
6
+ # Formal verification with everystate
7
+
8
+ A test checks the cases someone thought to write. A model checker checks every order of steps in a
9
+ small model of the design. Use it when the question is "can these events happen in an order that
10
+ breaks a promise?" and the answer depends on interleavings that tests rarely reach.
11
+
12
+ It verifies the model, not the code. It does not answer "is this function correct for every input";
13
+ use property-based tests or a verifier that runs on the code for that.
14
+
15
+ ## The tool
16
+
17
+ `everystate` is a TLA+ model checker with TLC's command line, output and exit codes, as one binary.
18
+
19
+ ```sh
20
+ npx everystate Spec.tla # reads Spec.cfg next to it
21
+ npx everystate -config Other.cfg Spec.tla # another configuration of the same spec
22
+ npx everystate -json Spec.tla # one JSON object on the last line of stdout
23
+ ```
24
+
25
+ | Exit | Meaning |
26
+ |---|---|
27
+ | 0 | every reachable state checked, nothing found |
28
+ | 10 | an `ASSUME` is false |
29
+ | 11 | deadlock: a state with no next step |
30
+ | 12 | an invariant is violated |
31
+ | 13 | a liveness property is violated |
32
+ | 150 / 151 | the spec / the `.cfg` does not parse |
33
+
34
+ The JSON object has `status` (`ok`, `invariant`, `liveness`, `deadlock`, ...), the state counts, and
35
+ on a failure `name` and `trace`: the shortest list of `{action, state}` steps that reaches it.
36
+
37
+ Not supported: simulation mode, multiple workers, the PlusCal translator (write TLA+ directly, or
38
+ translate with the TLA+ tools first), TLAPS proofs. A model must be finite and small enough to
39
+ enumerate; a few million states is fine.
40
+
41
+ ## How to do it
42
+
43
+ 1. **Pick the promise.** One sentence the code is supposed to keep, where a break harms users: "a
44
+ card is charged at most once", "two workers never hold the same lease". Read the code first and
45
+ take the promise from it; ask the user only what you cannot see.
46
+ 2. **Model the steps, not the code.** One variable per piece of state that matters, one action per
47
+ step that can interleave with others. What the model treats as one step must be one indivisible
48
+ step in the code: a read followed by a write is two actions unless a lock or transaction makes
49
+ it one. Include the failures: lost messages, timeouts, crashes, retries. Use the code's names,
50
+ and put a comment on each action saying which function it stands for.
51
+ 3. **Bound it.** Constants in the `.cfg` keep the model finite (2 or 3 workers, 3 retries). Most
52
+ design bugs show up at these sizes.
53
+ 4. **State the properties.** A type invariant first, since it catches modelling mistakes. Then the
54
+ promise as an `INVARIANT` ("never bad") or a `PROPERTY` ("eventually good", which needs fairness
55
+ in `Spec`).
56
+ 5. **Run it and read the result.** On a violation, retell the trace as a short story in the code's
57
+ words. Then decide: is this a real bug, or did the model allow a step the code cannot take?
58
+ Check against the code before changing either.
59
+ 6. **See it fail.** A check that has never failed proves nothing. Break the model the way the code
60
+ could be broken (remove the guard, reorder two steps) and confirm the checker reports it. Keep
61
+ that as a second `.cfg` or note the mutation you tried.
62
+ 7. **Report honestly.** Say what was checked, at which bounds, under which assumptions, and what
63
+ the model leaves out. A pass covers the model at those bounds, not the whole system.
64
+
65
+ Do not weaken a property or the model to get a pass, and do not change product code unless asked:
66
+ a counterexample on the current code is a finding to report.
67
+
68
+ ## Worked example
69
+
70
+ [`example/Charge.tla`](example/Charge.tla) models a client that retries a card charge when the
71
+ reply is lost. The promise is `ChargedAtMostOnce`. The constant `Idempotent` says whether the
72
+ server remembers the request key.
73
+
74
+ ```sh
75
+ cd example
76
+ npx everystate Charge.tla # Idempotent = TRUE: exit 0, 29 distinct states
77
+ npx everystate -config ChargeBroken.cfg Charge.tla # Idempotent = FALSE: exit 12
78
+ ```
79
+
80
+ The broken configuration fails with this trace, which reads: the client sends, times out and sends
81
+ again; the server handles both requests and charges twice.
82
+
83
+ ```
84
+ Error: Invariant ChargedAtMostOnce is violated.
85
+ State 1: <Initial predicate> charges = 0, sent = 0
86
+ State 2: <Send ...> sent = 1, inFlight = 1
87
+ State 3: <Send ...> sent = 2, inFlight = 2
88
+ State 4: <Handle ...> charges = 1
89
+ State 5: <Handle ...> charges = 2
90
+ ```
91
+
92
+ (Shortened: the real output prints every variable in every state.)
93
+
94
+ The same spec checks `EventuallyConfirmed`, a liveness property: under weak fairness on sending,
95
+ handling and receiving, the client always learns the charge went through.
96
+
97
+ ## A `.cfg` in brief
98
+
99
+ ```
100
+ SPECIFICATION Spec \* or INIT Init and NEXT Next
101
+ CONSTANTS
102
+ MaxSends = 3
103
+ Workers = {w1, w2} \* model values
104
+ INVARIANTS TypeOK ChargedAtMostOnce
105
+ PROPERTY EventuallyConfirmed
106
+ CHECK_DEADLOCK FALSE \* when stopping is a legitimate end
107
+ SYMMETRY Perms \* Perms == Permutations(Workers); safety only
108
+ ```
109
+
110
+ ## Leaving it for the next change
111
+
112
+ If the check should outlive this task, commit the spec and `.cfg` next to the code and record with
113
+ them: the one command that runs it, which files and functions each action stands for, the bounds,
114
+ and the commit at which the model was last confirmed against the code. Whoever changes that code
115
+ next can then rerun the check, and can see when the model needs another look.
@@ -0,0 +1,7 @@
1
+ SPECIFICATION Spec
2
+ CONSTANTS
3
+ Idempotent = TRUE
4
+ MaxSends = 3
5
+ INVARIANTS TypeOK ChargedAtMostOnce
6
+ PROPERTY EventuallyConfirmed
7
+ CHECK_DEADLOCK FALSE
@@ -0,0 +1,61 @@
1
+ ---- MODULE Charge ----
2
+ \* A client charges a card through a server and retries when the reply is lost.
3
+ \* Promise: the card is charged at most once, and the client eventually learns the charge went through.
4
+ EXTENDS Naturals
5
+
6
+ CONSTANTS
7
+ Idempotent, \* TRUE: the server remembers the request key and does not charge again
8
+ MaxSends \* bound on how many times the client sends the request
9
+
10
+ VARIABLES
11
+ sent, \* how many times the client has sent the request
12
+ inFlight, \* requests on the wire, not yet handled by the server
13
+ charges, \* how many times the card was charged
14
+ seen, \* the server has recorded the request key
15
+ replies, \* replies on the wire, not yet read by the client
16
+ confirmed \* the client knows the charge went through
17
+
18
+ vars == <<sent, inFlight, charges, seen, replies, confirmed>>
19
+
20
+ Init ==
21
+ /\ sent = 0 /\ inFlight = 0 /\ charges = 0
22
+ /\ seen = FALSE /\ replies = 0 /\ confirmed = FALSE
23
+
24
+ \* The client sends the request: the first time, or again after a timeout.
25
+ Send ==
26
+ /\ ~confirmed /\ sent < MaxSends
27
+ /\ sent' = sent + 1 /\ inFlight' = inFlight + 1
28
+ /\ UNCHANGED <<charges, seen, replies, confirmed>>
29
+
30
+ \* The server handles one request and replies.
31
+ Handle ==
32
+ /\ inFlight > 0
33
+ /\ inFlight' = inFlight - 1
34
+ /\ charges' = IF Idempotent /\ seen THEN charges ELSE charges + 1
35
+ /\ seen' = TRUE
36
+ /\ replies' = replies + 1
37
+ /\ UNCHANGED <<sent, confirmed>>
38
+
39
+ \* The network loses a reply. It never loses the last one the client can still get.
40
+ LoseReply ==
41
+ /\ replies > 0 /\ (sent < MaxSends \/ inFlight + replies > 1)
42
+ /\ replies' = replies - 1
43
+ /\ UNCHANGED <<sent, inFlight, charges, seen, confirmed>>
44
+
45
+ \* The client reads a reply.
46
+ Receive ==
47
+ /\ replies > 0
48
+ /\ replies' = replies - 1 /\ confirmed' = TRUE
49
+ /\ UNCHANGED <<sent, inFlight, charges, seen>>
50
+
51
+ Next == Send \/ Handle \/ LoseReply \/ Receive
52
+
53
+ Spec == Init /\ [][Next]_vars /\ WF_vars(Send) /\ WF_vars(Handle) /\ WF_vars(Receive)
54
+
55
+ TypeOK ==
56
+ /\ sent \in 0..MaxSends /\ inFlight \in 0..MaxSends /\ replies \in 0..MaxSends
57
+ /\ charges \in 0..MaxSends /\ seen \in BOOLEAN /\ confirmed \in BOOLEAN
58
+
59
+ ChargedAtMostOnce == charges <= 1
60
+ EventuallyConfirmed == <>confirmed
61
+ ====
@@ -0,0 +1,7 @@
1
+ SPECIFICATION Spec
2
+ CONSTANTS
3
+ Idempotent = FALSE
4
+ MaxSends = 3
5
+ INVARIANTS TypeOK ChargedAtMostOnce
6
+ PROPERTY EventuallyConfirmed
7
+ CHECK_DEADLOCK FALSE
package/wasm/cli.mjs ADDED
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ // Minimal command line for the WebAssembly build (used by bench.mjs): reads the spec, the modules next
3
+ // to it and the config from disk, runs check() and prints one JSON line like `everystate -json`.
4
+ // usage: node wasm/cli.mjs [-config FILE] [-deadlock] SPEC.tla
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { check } from './everystate.mjs';
8
+ const argv = process.argv.slice(2);
9
+ let config = null, deadlock = true, spec = null;
10
+ for (let i = 0; i < argv.length; i++) {
11
+ if (argv[i] === '-config') config = argv[++i];
12
+ else if (argv[i] === '-deadlock') deadlock = false;
13
+ else if (!argv[i].startsWith('-')) spec = argv[i];
14
+ }
15
+ if (!spec) { console.error('usage: node wasm/cli.mjs [-config FILE] [-deadlock] SPEC.tla'); process.exit(1); }
16
+ const dir = path.dirname(path.resolve(spec)), root = path.basename(spec, '.tla');
17
+ const modules = {};
18
+ for (const f of fs.readdirSync(dir)) if (f.endsWith('.tla')) modules[f.slice(0, -4)] = fs.readFileSync(path.join(dir, f), 'utf8');
19
+ const cfg = fs.readFileSync(config ?? path.join(dir, root + '.cfg'), 'utf8');
20
+ try {
21
+ const { result } = check({ root, modules, config: cfg, deadlock, print: l => console.log(l) });
22
+ console.log(JSON.stringify({ status: result.status, name: result.name, message: result.message, generated: result.generated, distinct: result.distinct, queue: result.queue, depth: result.depth }));
23
+ } catch (e) {
24
+ console.log(JSON.stringify({ status: 'setup-error', message: e.message }));
25
+ process.exit(150);
26
+ }
@@ -0,0 +1,33 @@
1
+ export interface CheckInput {
2
+ /** Name of the root module. */
3
+ root: string;
4
+ /** Module sources by module name (the root and any modules it EXTENDS/INSTANCEs that are not bundled). */
5
+ modules: Record<string, string>;
6
+ /** Contents of the TLC configuration (.cfg) file. */
7
+ config: string;
8
+ /** Check for deadlock (default: true unless the config says CHECK_DEADLOCK FALSE). */
9
+ deadlock?: boolean;
10
+ /** Receives output of Print/PrintT. */
11
+ print?: (line: string) => void;
12
+ }
13
+ export interface TraceStep { action: { name: string } | null; state: string[] }
14
+ export interface CheckResult {
15
+ status: 'ok' | 'invariant' | 'invariant-init' | 'deadlock' | 'action-property' | 'implied-init' | 'liveness' | 'error' | 'assumption' | 'incomplete' | 'init-error';
16
+ name?: string;
17
+ message?: string;
18
+ code?: number;
19
+ generated: number;
20
+ distinct: number;
21
+ queue: number;
22
+ depth: number;
23
+ /** liveness: index (0-based) of the state the lasso returns to; -1 = stuttering */
24
+ loopTo?: number;
25
+ loopAction?: { name: string } | null;
26
+ trace?: TraceStep[];
27
+ }
28
+ export class TlaError extends Error { kind: string }
29
+ export function init(source?: WebAssembly.Module | BufferSource | Response | Promise<Response>): Promise<WebAssembly.Module>;
30
+ export function check(input: CheckInput): { result: CheckResult; model: { vars: { name: string }[] } };
31
+ export function fmt(value: unknown): string;
32
+ /** Under Node: runs `check` in a worker thread with a `stackSizeMb` call stack (default 256). */
33
+ export function checkAsync(input: CheckInput, options?: { stackSizeMb?: number }): Promise<{ result: CheckResult; model: { vars: { name: string }[] } }>;