everystate 0.3.1 → 0.4.0

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.
package/README.md CHANGED
@@ -3,8 +3,33 @@
3
3
  A TLA+ model checker with no Java dependency, written in Rust. It reads ordinary `.tla` specs and
4
4
  TLC `.cfg` files, checks every reachable state, and reports results in TLC's format.
5
5
 
6
+ ```text
7
+ > use everystate's formal verification skill to find race conditions in my amazing software
8
+
9
+ ⏺ Write(Store.tla)
10
+ // ... models load() and save() from store.ts
11
+
12
+ ⏺ Bash(npx everystate Store.tla)
13
+
14
+ Error: Invariant NoLostUpdates is violated.
15
+ State 2: <Load("a")> a read 0
16
+ State 3: <Load("b")> b read 0
17
+ State 4: <Save("a")> memory = 1
18
+ State 5: <Save("b")> memory = 1
19
+
20
+ ⏺ Found a race. Two overlapping requests both load before either saves,
21
+ so one update is lost. Fix: make load-and-save atomic.
22
+ ```
23
+
24
+ (Condensed. The spec is [`examples/Store.tla`](examples/Store.tla); the skill is
25
+ [`skills/formal-verification`](skills/formal-verification/SKILL.md).)
26
+
6
27
  - Safety and liveness checking, fairness, symmetry, `VIEW`, `ALIAS`.
7
28
  - TLC-compatible text output, exit codes, `-tool` framing and `-dump`.
29
+ - Random simulation (`-simulate`) for models too large to enumerate, with seeded, reproducible runs.
30
+ - Trace conformance (`everystate conform`): check a log of the real system against the spec.
31
+ - Parallel search (`-workers N`) with results identical to one worker.
32
+ - A PlusCal translator (`everystate pcal`) with the Java translator's output, byte for byte.
8
33
  - The standard and community modules are built in.
9
34
  - One native binary, or WebAssembly for Node, Bun and workers.
10
35
 
@@ -12,6 +37,7 @@ TLC `.cfg` files, checks every reachable state, and reports results in TLC's for
12
37
 
13
38
  ```sh
14
39
  npm install -g everystate # prebuilt binary for Linux, macOS and Windows
40
+ brew install mattzcarey/tap/everystate
15
41
  cargo install everystate # or build from source
16
42
  ```
17
43
 
@@ -94,11 +120,83 @@ result.name; // 'NeverFour'
94
120
  The WebAssembly build is about 2x slower than native and cannot use the file-based community
95
121
  operators.
96
122
 
97
- ### In place of Java TLC
123
+ ## Multiple workers
124
+
125
+ `-workers N` (or `-workers auto`, one per core) searches on N threads in the native binary. State
126
+ counts, depth, verdict and the counterexample are the same as with one worker. Operators whose
127
+ effect depends on exploration order (`Print`, `TLCSet`/`TLCGet` registers, `RandomElement`,
128
+ IOUtils, ...) are evaluated by the sequential search; if they occur repeatedly the run continues
129
+ with one worker and says so. Liveness checking, simulation and `conform` run on one thread, and
130
+ the WebAssembly build is single-threaded.
131
+
132
+ ## Simulation
133
+
134
+ When a model is too large to enumerate, `everystate -simulate num=10000 Spec.tla` generates random
135
+ behaviours of up to `-depth` steps (default 100) and checks invariants, action properties, deadlock
136
+ and temporal properties on each, printing TLC's simulation output. A pass means only that no
137
+ generated behaviour violates a property. Without `num=` it runs until it finds an error, as TLC
138
+ does; with `-json` it stops after 1000 behaviours. Every run prints its seed; pass it back with
139
+ `-seed` to repeat the run exactly. From JavaScript:
140
+ `check({ root, modules, config, simulate: { traces: 10000, seed: 1 } })`.
141
+
142
+ Two differences from TLC: a deadlock is reported only for a state with no successor (TLC's
143
+ simulator also reports one when a `CONSTRAINT` excludes every successor), and a state predicate
144
+ given as `PROPERTY` is checked on the initial states (TLC's simulator skips it). Random choices
145
+ differ from Java TLC's, so the same seed gives a different run there.
146
+
147
+ ## PlusCal
148
+
149
+ `everystate pcal` translates the PlusCal algorithm in a module with the output of the Java
150
+ translator (`pcal.trans` 1.12): the same TLA+, layout and checksums, the same `.old` backup and
151
+ `.cfg` handling, the same options (`-wf`, `-sf`, `-wfNext`, `-nof`, `-termination`, `-label`,
152
+ `-labelRoot`, `-lineWidth`, ... and the `PlusCal options (...)` line), in p-syntax and c-syntax.
153
+
154
+ ```tla
155
+ ---- MODULE Transfer ----
156
+ EXTENDS Naturals, TLC
157
+
158
+ (* --algorithm transfer
159
+ variables alice = 10, bob = 10, money \in 1..20;
160
+ begin
161
+ Withdraw: alice := alice - money;
162
+ Deposit: bob := bob + money;
163
+ Check: assert alice >= 0;
164
+ end algorithm *)
165
+ ====
166
+ ```
167
+
168
+ ```sh
169
+ everystate pcal Transfer.tla # writes the translation into Transfer.tla, and Transfer.cfg
170
+ everystate Transfer.tla # "Failure of assertion at line 9, column 13."
171
+ ```
172
+
173
+ When a module is model-checked and its algorithm or translation no longer matches the checksums
174
+ in the `\* BEGIN TRANSLATION` line, everystate prints TLC's warning; `everystate pcal --check
175
+ File.tla` reports the same without checking a model. From JavaScript,
176
+ `translatePlusCal(source, options)` translates the text of a module. `-spec` and `-myspec` are not
177
+ supported. `npm run conformance:pcal` compares the translator with the Java one.
98
178
 
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.
179
+ ## Check the code against the model
180
+
181
+ A pass verifies the model. To check that the running code behaves like it, log what the code does
182
+ and ask whether that run is a behaviour of the spec:
183
+
184
+ ```sh
185
+ everystate conform -trace run.jsonl Charge.tla
186
+ ```
187
+
188
+ ```
189
+ {"state": {"sent": 0, "charges": 0}}
190
+ {"action": "Send", "state": {"sent": 1}}
191
+ {"action": "Handle", "state": {"charges": 2}}
192
+ ```
193
+
194
+ Each line is a step: optionally the action, and whichever variables the code knows. The report
195
+ names the first line the spec does not allow, what it expected, and which steps were possible
196
+ there. Exit status 0 conforms, 20 does not (21 bad trace, 22 limit reached). `-hidden N` allows
197
+ unlogged steps, `-stutter` snapshots, `-behavior` prints a full matching behaviour, `-json`
198
+ structured output. From JavaScript: `conform({ root, modules, config, trace })`. Details are in
199
+ the [skill](skills/formal-verification/SKILL.md).
102
200
 
103
201
  ## Agent skill
104
202
 
@@ -122,13 +220,18 @@ everystate [options] SPEC[.tla]
122
220
  Exit status: 0 success, 10 assumption, 11 deadlock, 12 safety, 13 liveness, 150 parse error,
123
221
  151 config error.
124
222
 
223
+ Environment: `EVERYSTATE_EVAL=tree` evaluates with the tree-walking interpreter alone (the default
224
+ compiles actions and invariants first and gives the same results). `EVERYSTATE_STEP_CACHE=on` turns
225
+ on an experimental cache of local steps, a fixed-size table of `EVERYSTATE_STEP_CACHE_MB` megabytes
226
+ per worker (default 32): faster on models made of many small independent steps, slower on some others.
227
+
125
228
  ## How it is checked
126
229
 
127
230
  Real TLC is the reference (details in [CONFORMANCE.md](CONFORMANCE.md)):
128
231
 
129
232
  - [tlaplus/Examples](https://github.com/tlaplus/Examples), models up to 5 s: 122 of 122 match on
130
233
  result and exact state counts.
131
- - TLC's own `test-model` suite, run side by side with `tla2tools.jar`: 384 of 414 match.
234
+ - TLC's own `test-model` suite, run side by side with `tla2tools.jar`: 383 of 414 match.
132
235
  - pstack `statechart` corpus: 33 of 33 outputs byte-identical.
133
236
 
134
237
  Faster than single-worker Java TLC on all 12 benchmark models (1.1x to 4.6x, thin on three of
@@ -136,9 +239,8 @@ them), with near-instant start-up: [BENCHMARK.md](BENCHMARK.md).
136
239
 
137
240
  ## Not supported
138
241
 
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
242
+ Disk-backed state storage (everything is in memory, so a few
243
+ million distinct states is the practical limit), Java module overrides, labels and subexpression selectors, and TLAPS proof checking (proofs
142
244
  are parsed and skipped).
143
245
 
144
246
  ## Development
@@ -15,9 +15,7 @@ function nativeBinary() {
15
15
  return file;
16
16
  }
17
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);
18
+ const args = process.argv.slice(2);
21
19
 
22
20
  const bin = nativeBinary();
23
21
  if (bin) {
@@ -25,9 +23,6 @@ if (bin) {
25
23
  if (r.error) { console.error(`everystate: cannot run ${bin}: ${r.error.message}`); process.exit(1); }
26
24
  if (r.signal) process.kill(process.pid, r.signal);
27
25
  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
26
  } else {
32
27
  console.error(`everystate: no prebuilt binary for ${process.platform}-${process.arch}; using the WebAssembly build (JSON output only).`);
33
28
  process.argv = [process.argv[0], process.argv[1], ...args];
Binary file
Binary file
Binary file
Binary file
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "everystate",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
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",
@@ -13,8 +13,7 @@
13
13
  }
14
14
  },
15
15
  "bin": {
16
- "everystate": "bin/everystate.mjs",
17
- "everystate-java": "bin/everystate.mjs"
16
+ "everystate": "bin/everystate.mjs"
18
17
  },
19
18
  "files": [
20
19
  "bin/everystate.mjs",
@@ -29,10 +28,11 @@
29
28
  ],
30
29
  "scripts": {
31
30
  "build": "cargo build --release && sh wasm/build.sh",
32
- "test": "node --experimental-strip-types --no-warnings --test test/*.test.ts && node test/community.mjs",
31
+ "test": "node --experimental-strip-types --no-warnings --test test/*.test.ts && node test/community.mjs && node test/workers.mjs",
33
32
  "conformance:examples": "node scripts/conformance.mjs",
34
33
  "conformance:tlc": "node scripts/diff-tlc.mjs",
35
34
  "conformance:statechart": "node scripts/statechart-corpus.mjs",
35
+ "conformance:pcal": "node scripts/pcal-corpus.mjs",
36
36
  "bench": "node scripts/bench.mjs",
37
37
  "changeset": "changeset",
38
38
  "version": "changeset version && node scripts/sync-version.mjs"
@@ -10,7 +10,9 @@ small model of the design. Use it when the question is "can these events happen
10
10
  breaks a promise?" and the answer depends on interleavings that tests rarely reach.
11
11
 
12
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.
13
+ use property-based tests or a verifier that runs on the code for that. To check that the running
14
+ code behaves like the model, record a run and use `everystate conform` (see "Check the real code
15
+ against the model" below).
14
16
 
15
17
  ## The tool
16
18
 
@@ -34,9 +36,12 @@ npx everystate -json Spec.tla # one JSON object on the last line
34
36
  The JSON object has `status` (`ok`, `invariant`, `liveness`, `deadlock`, ...), the state counts, and
35
37
  on a failure `name` and `trace`: the shortest list of `{action, state}` steps that reaches it.
36
38
 
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.
39
+ Also available: `everystate pcal Spec.tla` translates a PlusCal algorithm in the module (same output
40
+ as the Java translator), and `everystate -simulate num=10000 Spec.tla` checks random behaviours
41
+ when a model is too large to enumerate (a pass then covers only the behaviours generated).
42
+
43
+ Add `-workers auto` to search on every core (same results). Not supported: TLAPS proofs. Exhaustive checking needs a model that is finite and
44
+ small enough to enumerate; a few million states is fine.
40
45
 
41
46
  ## How to do it
42
47
 
@@ -94,6 +99,126 @@ State 5: <Handle ...> charges = 2
94
99
  The same spec checks `EventuallyConfirmed`, a liveness property: under weak fairness on sending,
95
100
  handling and receiving, the client always learns the charge went through.
96
101
 
102
+ ## Check the real code against the model
103
+
104
+ A pass says the model keeps the promise. It does not say the code behaves like the model. Trace
105
+ conformance closes part of that gap: record what the running code did, then check that the
106
+ recording is a behaviour the spec allows. If it is not, the code took a step the model forbids:
107
+ a bug in the code, or a model that does not describe it.
108
+
109
+ ```sh
110
+ npx everystate conform -trace run.jsonl Spec.tla # reads Spec.cfg, as for model checking
111
+ ```
112
+
113
+ **Record.** Log one JSON line per step of the model, at the place in the code where the step takes
114
+ effect, using the model's action and variable names. [`example/observe.ts`](example/observe.ts) is
115
+ all it takes:
116
+
117
+ ```ts
118
+ export function observe(action: string | null, state: Record<string, unknown>) {
119
+ if (TRACE) appendFileSync(TRACE, JSON.stringify({ ts: Date.now(), action, state }) + '\n');
120
+ }
121
+ // In the server: observe('Handle', { charges: await countCharges(key) });
122
+ ```
123
+
124
+ **The trace** is JSON Lines (or one JSON array of the same objects). Each observation may have:
125
+
126
+ | Key | Meaning |
127
+ |---|---|
128
+ | `action` | name of the spec action that happened. Left out: any action. |
129
+ | `params` | the action's arguments, `["w1"]` in order or `{"w": "w1"}` by name, for an action `Lease(w)` under `\E w \in Workers`. |
130
+ | `state` | values of some or all variables *after* the step. Variables left out are unconstrained: log what the code knows. |
131
+
132
+ Other keys (`ts`, `msg`) are ignored, and so are entries with neither `action` nor `state`, so
133
+ observations can sit in an ordinary structured log. The first observation is the initial state; if
134
+ it names an action, the initial state is taken as unlogged.
135
+
136
+ **Values** are read according to the type the spec's value has, not guessed from the JSON:
137
+
138
+ | JSON | matches the TLA+ value |
139
+ |---|---|
140
+ | `true`, `3`, `"abc"` | the boolean, the integer, the string |
141
+ | `"w1"` | also the model value `w1` |
142
+ | `[1, 2]` | the sequence `<<1, 2>>` (in order), or the set `{1, 2}` (any order, no duplicates) |
143
+ | `{"a": 1}` | the record `[a |-> 1]`, or a function such as `[w \in Workers |-> ...]` with string, model-value or integer keys (`{"1": "x"}`; a sequence is such a function) |
144
+ | `{"a": 1, "...": 0}` | a record or function with at least `a |-> 1`: one process logging its own entry |
145
+ | `null`, `1.5` | nothing |
146
+
147
+ Ambiguous on purpose: `[]` matches `<<>>` and `{}`; `{}` matches the empty function, which is
148
+ `<<>>`; a string matches a string and a model value of the same name.
149
+
150
+ | Option | |
151
+ |---|---|
152
+ | `-hidden N` | up to N steps the log does not show may happen before each observation (default 0: every step is logged) |
153
+ | `-stutter` | an observation without `action` may be a snapshot of an unchanged state. Off by default: every line is a step, so a duplicated event is reported instead of absorbed. Use it for logs that sample state. |
154
+ | `-behavior` | also print one full behaviour of the spec that matches, with the unlogged variables filled in |
155
+ | `-json` | the result as one JSON object: `status`, `failed`, `lastMatched`, `nearest`, `enabled`, `hints` |
156
+ | `-limit N`, `-noconstraints` | cap on the spec states tracked at once (default 100000); ignore `CONSTRAINT` bounds |
157
+
158
+ | Exit | Meaning |
159
+ |---|---|
160
+ | 0 | the trace is a behaviour of the spec |
161
+ | 20 | it is not: the report names the first line that cannot be matched |
162
+ | 12 | the spec allows the run, but the run violates an `INVARIANT` of the `.cfg`: the model is wrong |
163
+ | 21 / 22 | the trace is malformed / too many candidate states, no verdict |
164
+ | 150 / 151 | the spec / the `.cfg` does not parse |
165
+
166
+ **Worked example.** `example/charge-ok.jsonl` is a run of the charge client and server with one
167
+ retry; `example/charge-double.jsonl` is a run where the server charged again on the retry.
168
+
169
+ ```sh
170
+ cd example
171
+ npx everystate conform -trace charge-ok.jsonl Charge.tla # exit 0
172
+ npx everystate conform -trace charge-double.jsonl Charge.tla # exit 20
173
+ ```
174
+
175
+ ```
176
+ Trace conforms: 6 observations matched; the recorded run is a behaviour of Charge.
177
+ ```
178
+
179
+ ```
180
+ Error: Trace does not conform to Charge: line 5 (observation 5 of 6) cannot be matched.
181
+
182
+ line 5: {"action":"Handle","state":{"charges":2}}
183
+ last matched: line 4 (1 spec state consistent with the trace up to there)
184
+ before this step: charges = 1
185
+
186
+ Handle can happen here, but it does not produce the observed values.
187
+ Closest step the spec allows:
188
+ Handle: charges is 1 in the spec, 2 in the trace
189
+ Steps the spec allows here, and the observed variables after each:
190
+ Send charges = 1
191
+ Handle charges = 1
192
+ LoseReply charges = 1
193
+ Receive charges = 1
194
+ ```
195
+
196
+ Read it as: the model says the second `Handle` leaves `charges` at 1 (the server has seen the key),
197
+ the code made it 2. Here the code is wrong. Against the model of a server that forgets the key, the
198
+ same run is allowed and breaks the promise instead:
199
+
200
+ ```sh
201
+ npx everystate conform -trace charge-double.jsonl -config ChargeBroken.cfg Charge.tla # exit 12
202
+ ```
203
+
204
+ ```
205
+ Error: Invariant ChargedAtMostOnce is violated by the recorded behaviour at line 5.
206
+ ```
207
+
208
+ (Shortened: the full output prints the behaviour up to that line.)
209
+
210
+ **Using it well.**
211
+
212
+ - On a mismatch, decide against the code which side is wrong, as with a counterexample. If the
213
+ report hints that `-hidden` or `-stutter` would match, the log is missing steps or repeats them:
214
+ fix the logging in preference to loosening the check.
215
+ - Observations must be in the order the steps happened. With several processes, write through one
216
+ ordered log, or log per process and check each process's actions separately with `-hidden`.
217
+ - The fewer variables logged, the more runs conform. Log the variables the promise is about, and
218
+ name the action.
219
+ - A pass covers the runs recorded, on the variables logged. It is a test, not a proof: keep it in
220
+ CI next to the model check, fed by an integration test that exercises retries and failures.
221
+
97
222
  ## A `.cfg` in brief
98
223
 
99
224
  ```
@@ -0,0 +1,6 @@
1
+ {"state": {"sent": 0, "charges": 0, "confirmed": false}}
2
+ {"ts": "12:00:00.010", "action": "Send", "state": {"sent": 1}}
3
+ {"ts": "12:00:02.010", "action": "Send", "state": {"sent": 2}}
4
+ {"ts": "12:00:02.150", "action": "Handle", "state": {"charges": 1}}
5
+ {"ts": "12:00:02.320", "action": "Handle", "state": {"charges": 2}}
6
+ {"ts": "12:00:02.400", "action": "Receive", "state": {"confirmed": true}}
@@ -0,0 +1,6 @@
1
+ {"state": {"sent": 0, "charges": 0, "confirmed": false}}
2
+ {"ts": "12:00:00.010", "action": "Send", "state": {"sent": 1}}
3
+ {"ts": "12:00:02.010", "action": "Send", "state": {"sent": 2}}
4
+ {"ts": "12:00:02.150", "action": "Handle", "state": {"charges": 1}}
5
+ {"ts": "12:00:02.320", "action": "Handle", "state": {"charges": 1}}
6
+ {"ts": "12:00:02.400", "action": "Receive", "state": {"confirmed": true}}
@@ -0,0 +1,14 @@
1
+ // How an application records observations for `everystate conform`: one JSON line per step of the
2
+ // model, written where the step happens, with the model's names and only the values this code knows.
3
+ import { appendFileSync } from 'node:fs';
4
+
5
+ const TRACE = process.env.CONFORM_TRACE; // unset in production: nothing is written
6
+
7
+ export function observe(action: string | null, state: Record<string, unknown>) {
8
+ if (TRACE) appendFileSync(TRACE, JSON.stringify({ ts: Date.now(), action, state }) + '\n');
9
+ }
10
+
11
+ // At start-up: observe(null, { sent: 0, charges: 0, confirmed: false });
12
+ // In the client's send: observe('Send', { sent: attempts });
13
+ // In the server: observe('Handle', { charges: await countCharges(key) });
14
+ // On the reply: observe('Receive', { confirmed: true });
package/wasm/cli.mjs CHANGED
@@ -2,24 +2,57 @@
2
2
  // Minimal command line for the WebAssembly build (used by bench.mjs): reads the spec, the modules next
3
3
  // to it and the config from disk, runs check() and prints one JSON line like `everystate -json`.
4
4
  // usage: node wasm/cli.mjs [-config FILE] [-deadlock] SPEC.tla
5
+ // node wasm/cli.mjs conform [-config FILE] [-hidden N] [-stutter] [-behavior] [-limit N] [-noconstraints] -trace TRACE SPEC.tla
5
6
  import fs from 'node:fs';
6
7
  import path from 'node:path';
7
- import { check } from './everystate.mjs';
8
+ import { check, conform } from './everystate.mjs';
8
9
  const argv = process.argv.slice(2);
10
+ if (argv[0] === 'pcal') {
11
+ console.error('everystate: the pcal command needs the native binary; from JavaScript, translatePlusCal() of this package translates the text of a module.');
12
+ process.exit(1);
13
+ }
14
+ const conformMode = argv[0] === 'conform' && argv.length > 1;
15
+ if (conformMode) argv.shift();
16
+ const opts = {};
17
+ let trace = null;
9
18
  let config = null, deadlock = true, spec = null;
10
19
  for (let i = 0; i < argv.length; i++) {
11
20
  if (argv[i] === '-config') config = argv[++i];
12
21
  else if (argv[i] === '-deadlock') deadlock = false;
13
- else if (!argv[i].startsWith('-')) spec = argv[i];
22
+ else if (conformMode && argv[i] === '-trace') trace = argv[++i];
23
+ else if (conformMode && (argv[i] === '-hidden' || argv[i] === '-limit')) opts[argv[i].slice(1)] = Number(argv[++i]);
24
+ else if (conformMode && argv[i] === '-stutter') opts.stutter = true;
25
+ else if (conformMode && (argv[i] === '-behavior' || argv[i] === '-behaviour')) opts.behavior = true;
26
+ else if (conformMode && argv[i] === '-noconstraints') opts.constraints = false;
27
+ else if (!argv[i].startsWith('-')) { if (spec && conformMode) trace ??= argv[i]; else spec = argv[i]; }
14
28
  }
15
29
  if (!spec) { console.error('usage: node wasm/cli.mjs [-config FILE] [-deadlock] SPEC.tla'); process.exit(1); }
16
30
  const dir = path.dirname(path.resolve(spec)), root = path.basename(spec, '.tla');
17
31
  const modules = {};
18
32
  for (const f of fs.readdirSync(dir)) if (f.endsWith('.tla')) modules[f.slice(0, -4)] = fs.readFileSync(path.join(dir, f), 'utf8');
19
33
  const cfg = fs.readFileSync(config ?? path.join(dir, root + '.cfg'), 'utf8');
34
+ if (conformMode) {
35
+ if (!trace) { console.error('usage: node wasm/cli.mjs conform [-config FILE] -trace TRACE SPEC.tla'); process.exit(1); }
36
+ const codes = { conforms: 0, mismatch: 20, 'trace-error': 21, limit: 22, invariant: 12, assumption: 10 };
37
+ let result, code;
38
+ try {
39
+ result = fs.existsSync(trace)
40
+ ? conform({ root, modules, config: cfg, trace: fs.readFileSync(trace, 'utf8'), ...opts, print: l => console.log(l) })
41
+ : { status: 'trace-error', message: `cannot read the trace file ${trace}` };
42
+ code = codes[result.status] ?? 255;
43
+ } catch (e) {
44
+ result = { status: 'setup-error', kind: e.kind, message: e.message };
45
+ code = e.kind === 'config' ? 151 : 150;
46
+ }
47
+ console.log(JSON.stringify(result));
48
+ process.exit(code);
49
+ }
20
50
  try {
21
51
  const { result } = check({ root, modules, config: cfg, deadlock, print: l => console.log(l) });
22
52
  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 }));
53
+ // the native binary's exit status
54
+ const codes = { ok: 0, assumption: 10, deadlock: 11, invariant: 12, 'invariant-init': 12, 'action-property': 13, 'implied-init': 13, liveness: 13, incomplete: 75 };
55
+ process.exitCode = codes[result.status] ?? 255;
23
56
  } catch (e) {
24
57
  console.log(JSON.stringify({ status: 'setup-error', message: e.message }));
25
58
  process.exit(150);
@@ -7,19 +7,46 @@ export interface CheckInput {
7
7
  config: string;
8
8
  /** Check for deadlock (default: true unless the config says CHECK_DEADLOCK FALSE). */
9
9
  deadlock?: boolean;
10
+ /**
11
+ * Random simulation (TLC's `-simulate`) instead of exhaustive checking: generate random behaviours
12
+ * and check each of them. For models too large to enumerate; `status: 'ok'` then only means that no
13
+ * generated behaviour violates a property. `true` uses the defaults.
14
+ */
15
+ simulate?: boolean | SimulateOptions;
10
16
  /** Receives output of Print/PrintT. */
11
17
  print?: (line: string) => void;
12
18
  }
19
+ export interface SimulateOptions {
20
+ /** Number of behaviours to generate (default 1000; a run is always bounded). */
21
+ traces?: number;
22
+ /** Maximal number of steps of a behaviour (default 100, as TLC's `-depth`). */
23
+ depth?: number;
24
+ /** Seed of the random choices; the same seed repeats the run. Default: taken from the clock. */
25
+ seed?: number;
26
+ /** A second number mixed into the seed (TLC's `-aril`, default 0). */
27
+ aril?: number;
28
+ }
13
29
  export interface TraceStep { action: { name: string } | null; state: string[] }
14
30
  export interface CheckResult {
15
31
  status: 'ok' | 'invariant' | 'invariant-init' | 'deadlock' | 'action-property' | 'implied-init' | 'liveness' | 'error' | 'assumption' | 'incomplete' | 'init-error';
16
32
  name?: string;
17
33
  message?: string;
18
34
  code?: number;
35
+ /** States generated. In a simulation: the initial states plus every successor computed. */
19
36
  generated: number;
37
+ /** Distinct states found (-1 in a simulation, which does not count them). */
20
38
  distinct: number;
39
+ /** States left unexplored (-1 in a simulation). */
21
40
  queue: number;
41
+ /** Depth of the search. In a simulation: the number of states of the longest behaviour. */
22
42
  depth: number;
43
+ /** Present, with the three fields below, when the result comes from a simulation. */
44
+ mode?: 'simulate';
45
+ /** Simulation: behaviours generated (including the one that ended in an error). */
46
+ traces?: number;
47
+ /** Simulation: the seed used; pass it as `simulate.seed` to repeat the run. */
48
+ seed?: number;
49
+ aril?: number;
23
50
  /** liveness: index (0-based) of the state the lasso returns to; -1 = stuttering */
24
51
  loopTo?: number;
25
52
  loopAction?: { name: string } | null;
@@ -31,3 +58,98 @@ export function check(input: CheckInput): { result: CheckResult; model: { vars:
31
58
  export function fmt(value: unknown): string;
32
59
  /** Under Node: runs `check` in a worker thread with a `stackSizeMb` call stack (default 256). */
33
60
  export function checkAsync(input: CheckInput, options?: { stackSizeMb?: number }): Promise<{ result: CheckResult; model: { vars: { name: string }[] } }>;
61
+
62
+ /** One recorded step of the real system. Other keys (timestamps, messages) are ignored. */
63
+ export interface Observation {
64
+ /** Name of the spec action that happened. Omit it to allow any action. */
65
+ action?: string | null;
66
+ /** The action's arguments: in order, or by parameter name. */
67
+ params?: unknown[] | Record<string, unknown>;
68
+ /** Values of some or all spec variables after the step. Variables left out are unconstrained. */
69
+ state?: Record<string, unknown>;
70
+ [key: string]: unknown;
71
+ }
72
+ export interface ConformInput {
73
+ root: string;
74
+ modules: Record<string, string>;
75
+ config: string;
76
+ /** JSON Lines text, the text of a JSON array, or the observations themselves. */
77
+ trace: string | Observation[];
78
+ /** Up to this many unlogged steps may happen before each observation (default 0). */
79
+ hidden?: number;
80
+ /** An observation without an action may also be a snapshot of an unchanged state (default false). */
81
+ stutter?: boolean;
82
+ /** Include one full-state behaviour of the spec that matches the trace. */
83
+ behavior?: boolean;
84
+ /** Apply the CONSTRAINT bounds of the configuration (default true). */
85
+ constraints?: boolean;
86
+ /** Stop when more than this many spec states are consistent with the trace (default 100000). */
87
+ limit?: number;
88
+ print?: (line: string) => void;
89
+ }
90
+ export interface ConformResult {
91
+ /** `conforms`; `mismatch`: an observation the spec does not allow; `invariant`: the recorded behaviour
92
+ * is allowed by the spec but violates an invariant of the configuration; `limit`: no verdict;
93
+ * `trace-error`: the trace is malformed. */
94
+ status: 'conforms' | 'mismatch' | 'invariant' | 'limit' | 'trace-error' | 'assumption' | 'error';
95
+ message?: string;
96
+ /** invariant: its name */
97
+ name?: string;
98
+ /** Trace line (for an array of objects: 1-based element position) of the failing observation. */
99
+ line?: number;
100
+ observations: number;
101
+ /** Trace entries without `action` and `state`. */
102
+ ignored: number;
103
+ matched: number;
104
+ /** Number of spec states consistent with the matched observations. */
105
+ candidates: number;
106
+ /** `index` is the 1-based position among the observations. */
107
+ failed?: { index: number; line: number; observation: Observation };
108
+ lastMatched?: { index: number; line: number; candidates: number } | null;
109
+ /** mismatch: the observed variables before the failing step (JSON form of the spec's values). */
110
+ before?: Record<string, unknown>[];
111
+ /** mismatch: the closest steps the spec allows, and how they differ from the observation. */
112
+ nearest?: { action: string | null; differs: { var: string; observed: unknown; expected: unknown }[] }[];
113
+ /** mismatch: the steps the spec allows at that point, with the observed variables after each. */
114
+ enabled?: { action: string; produces: Record<string, unknown>; matchesState: boolean }[];
115
+ enabledMore?: number;
116
+ hints?: string[];
117
+ notes?: string[];
118
+ vars?: string[];
119
+ /** One behaviour of the spec that matches the trace; values are TLA+ text. */
120
+ behavior?: { line: number | null; action: string | null; state: Record<string, string> }[];
121
+ }
122
+ /** Checks that a recorded run is a behaviour of the specification. Throws `TlaError` if the spec or config does not parse. */
123
+ export function conform(input: ConformInput): ConformResult;
124
+
125
+ export interface PlusCalOptions {
126
+ /** Fairness of the generated Spec: `wf`/`sf` (of each process), `wfNext` (of Next) or `nof` (none). */
127
+ fairness?: 'wf' | 'sf' | 'wfNext' | 'nof';
128
+ /** Add missing labels (required when the algorithm has some labels but not all it needs). */
129
+ label?: boolean;
130
+ /** Prefix of added labels (default `Lbl_`). */
131
+ labelRoot?: string;
132
+ /** Translate for checking termination: the default fairness becomes `wf`. */
133
+ termination?: boolean;
134
+ /** Do not add the disjunct that allows stuttering after termination. */
135
+ noDoneDisjunct?: boolean;
136
+ /** Preferred width of the generated lines (default 78, at least 60). */
137
+ lineWidth?: number;
138
+ /** Translate as an earlier PlusCal version did (e.g. `'1.4'`). */
139
+ version?: string;
140
+ }
141
+ export interface PlusCalTranslation {
142
+ /** The text of the module with the new translation (lines end with "\n"), or null if the translation failed. */
143
+ output: string | null;
144
+ /** Why the translation failed (the translator's error messages, with line and column). */
145
+ errors: string[];
146
+ /** Everything the translator printed. */
147
+ messages: string[];
148
+ }
149
+ /**
150
+ * Translates the PlusCal algorithm in the text of a module to TLA+ between its BEGIN TRANSLATION and
151
+ * END TRANSLATION lines (added after the algorithm if missing), with the output of `java pcal.trans`.
152
+ * `options` are the translator's command-line options (`['-wf', '-termination']`) or their object form.
153
+ * Pure: no file is read or written (so no .cfg and no .old file).
154
+ */
155
+ export function translatePlusCal(source: string, options?: string[] | PlusCalOptions): PlusCalTranslation;
@@ -1,4 +1,5 @@
1
- // everystate as WebAssembly: the same `check({ root, modules, config, deadlock?, print? })` API as the
1
+ // everystate as WebAssembly: `conform(...)` for trace conformance, and the same
2
+ // `check({ root, modules, config, deadlock?, simulate?, print? })` API as the
2
3
  // TypeScript package's index.ts, backed by the Rust engine. Works in Node and Bun out of the box (the
3
4
  // .wasm file next to this module is read synchronously); in a browser or worker call `init()` first
4
5
  // with the compiled module, its bytes, or a fetch() Response.
@@ -40,11 +41,8 @@ export class TlaError extends Error {
40
41
  /** Formats a value of a trace state (they are already strings in TLC syntax). */
41
42
  export const fmt = v => String(v);
42
43
 
43
- /**
44
- * Model-check a specification held in memory.
45
- * @param {{root: string, modules: Record<string,string>, config: string, deadlock?: boolean, print?: (line: string) => void}} input
46
- */
47
- export function check(input) {
44
+ /** A fresh instance with the module sources loaded; `put` copies a string into its memory. */
45
+ function instantiate(input) {
48
46
  const module = load();
49
47
  let memory;
50
48
  const print = input.print ?? (() => {});
@@ -63,15 +61,34 @@ export function check(input) {
63
61
  return [p, b.length];
64
62
  };
65
63
  for (const [name, src] of Object.entries(input.modules)) ex.es_add_module(...put(name), ...put(src));
64
+ const result = p => JSON.parse(dec.decode(new Uint8Array(memory.buffer, p, ex.es_result_len())));
65
+ return { ex, put, result };
66
+ }
67
+
68
+ // The engine's call stack (RangeError) or the 64 MiB linear-memory stack (RuntimeError) ran out.
69
+ const isStackOverflow = e => e instanceof RangeError || (typeof WebAssembly !== 'undefined' && e instanceof WebAssembly.RuntimeError);
70
+ const STACK_MESSAGE = 'Stack overflow while evaluating the specification (recursion too deep). Re-run with a larger stack.';
71
+
72
+ /**
73
+ * Model-check a specification held in memory. With `simulate` (true, or `{ traces?, depth?, seed?, aril? }`)
74
+ * random behaviours are generated and checked instead of the whole state space, as TLC's -simulate does:
75
+ * by default 1000 behaviours of at most 100 steps; `result.seed` repeats the run.
76
+ * @param {{root: string, modules: Record<string,string>, config: string, deadlock?: boolean, simulate?: boolean | {traces?: number, depth?: number, seed?: number, aril?: number}, print?: (line: string) => void}} input
77
+ */
78
+ export function check(input) {
79
+ const { ex, put, result: read } = instantiate(input);
66
80
  let json;
67
81
  try {
68
- const p = ex.es_check(...put(input.root), ...put(input.config), (input.deadlock ?? true) ? 1 : 0);
69
- json = JSON.parse(dec.decode(new Uint8Array(memory.buffer, p, ex.es_result_len())));
82
+ const deadlock = (input.deadlock ?? true) ? 1 : 0;
83
+ const sim = input.simulate === true ? {} : input.simulate;
84
+ const num = v => (typeof v === 'number' ? Math.trunc(v) : NaN);
85
+ json = read(sim
86
+ ? ex.es_simulate(...put(input.root), ...put(input.config), deadlock, num(sim.traces) || 0, Number.isNaN(num(sim.depth)) ? -1 : Math.max(0, Math.min(num(sim.depth), 2 ** 31 - 1)), num(sim.seed), num(sim.aril))
87
+ : ex.es_check(...put(input.root), ...put(input.config), deadlock));
70
88
  } catch (e) {
71
- // The engine's call stack (RangeError) or the 64 MiB linear-memory stack (RuntimeError) ran out.
72
- if (e instanceof RangeError || (typeof WebAssembly !== 'undefined' && e instanceof WebAssembly.RuntimeError)) {
89
+ if (isStackOverflow(e)) {
73
90
  return {
74
- result: { status: 'error', message: 'Stack overflow while evaluating the specification (recursion too deep). Re-run with a larger stack.', generated: 0, distinct: 0, queue: 0, depth: 0 },
91
+ result: { status: 'error', message: STACK_MESSAGE, generated: 0, distinct: 0, queue: 0, depth: 0 },
75
92
  model: { vars: [] },
76
93
  };
77
94
  }
@@ -84,11 +101,75 @@ export function check(input) {
84
101
  status: json.status, name: json.name, message: json.message, code: json.code,
85
102
  generated: json.generated, distinct: json.distinct, queue: json.queue, depth: json.depth,
86
103
  loopTo: json.loopTo, loopAction: json.status === 'liveness' ? act(json.loopAction) : undefined,
104
+ ...(json.mode === 'simulate' ? { mode: json.mode, traces: json.traces, seed: json.seed, aril: json.aril } : {}),
87
105
  trace: json.trace?.map(t => ({ action: act(t.action), state: vars.map(v => t.state[v]) })),
88
106
  };
89
107
  return { result, model: { vars: vars.map(name => ({ name })) } };
90
108
  }
91
109
 
110
+ const PCAL_FLAGS = ['label', 'termination', 'noDoneDisjunct', 'reportLabels'];
111
+
112
+ /**
113
+ * Translate the PlusCal algorithm in the text of a module to TLA+, as `java pcal.trans` does (same
114
+ * output, including the checksums in the BEGIN TRANSLATION line). Pure: nothing is read or written.
115
+ * @param {string} source the text of the module
116
+ * @param {string[] | {fairness?: 'wf'|'sf'|'wfNext'|'nof', label?: boolean, labelRoot?: string, termination?: boolean, noDoneDisjunct?: boolean, lineWidth?: number, version?: string}} [options]
117
+ * the translator's command-line options (e.g. `['-wf', '-termination']`) or their object form
118
+ * @returns {{output: string | null, errors: string[], messages: string[]}} the new text of the module
119
+ * (lines end with "\n"), or `null` with the reasons in `errors`
120
+ */
121
+ export function translatePlusCal(source, options = []) {
122
+ let opts = options;
123
+ if (!Array.isArray(options)) {
124
+ opts = [];
125
+ if (options.fairness) opts.push(`-${options.fairness}`);
126
+ for (const f of PCAL_FLAGS) if (options[f]) opts.push(`-${f}`);
127
+ if (options.labelRoot !== undefined) opts.push('-labelRoot', String(options.labelRoot));
128
+ if (options.lineWidth !== undefined) opts.push('-lineWidth', String(options.lineWidth));
129
+ if (options.version !== undefined) opts.push('-version', String(options.version));
130
+ }
131
+ let memory;
132
+ const instance = new WebAssembly.Instance(load(), { env: { es_print: () => {}, es_now: () => Date.now() } });
133
+ const ex = instance.exports;
134
+ memory = ex.memory;
135
+ const put = s => {
136
+ const b = enc.encode(s);
137
+ const p = ex.es_alloc(b.length);
138
+ new Uint8Array(memory.buffer, p, b.length).set(b);
139
+ return [p, b.length];
140
+ };
141
+ const p = ex.es_pcal(...put(String(source)), ...put(opts.join('\n')));
142
+ const json = JSON.parse(dec.decode(new Uint8Array(memory.buffer, p, ex.es_result_len())));
143
+ const errors = [];
144
+ for (const m of json.messages) {
145
+ const e = /^\nUnrecoverable error:\n -- ([^]*)\.\n$/.exec(m);
146
+ if (e) errors.push(e[1]);
147
+ }
148
+ if (json.output === null && errors.length === 0) errors.push(json.messages.join('\n') || 'The translation failed.');
149
+ return { output: json.output, errors, messages: json.messages };
150
+ }
151
+
152
+ /**
153
+ * Trace conformance: is a recorded run of the real system a behaviour of the specification?
154
+ * `trace` is JSON Lines text, the text of a JSON array, or an array of observation objects
155
+ * `{ action?, params?, state? }`. Returns the same object as `everystate conform -json`.
156
+ * @param {{root: string, modules: Record<string,string>, config: string, trace: string | object[], hidden?: number, stutter?: boolean, behavior?: boolean, constraints?: boolean, limit?: number, print?: (line: string) => void}} input
157
+ */
158
+ export function conform(input) {
159
+ const { ex, put, result: read } = instantiate(input);
160
+ const trace = typeof input.trace === 'string' ? input.trace : input.trace.map(o => JSON.stringify(o)).join('\n');
161
+ const flags = (input.stutter ? 1 : 0) | (input.behavior ? 2 : 0) | (input.constraints === false ? 4 : 0);
162
+ let json;
163
+ try {
164
+ json = read(ex.es_conform(...put(input.root), ...put(input.config), ...put(trace), input.hidden ?? 0, input.limit ?? 0, flags));
165
+ } catch (e) {
166
+ if (isStackOverflow(e)) return { status: 'error', message: STACK_MESSAGE, observations: 0, ignored: 0, matched: 0, candidates: 0 };
167
+ throw e;
168
+ }
169
+ if (json.status === 'setup-error') throw new TlaError(json.message, json.kind);
170
+ return json;
171
+ }
172
+
92
173
  /**
93
174
  * Like `check`, but (under Node) runs in a worker thread with a large call stack, because WebAssembly
94
175
  * recursion uses the JavaScript engine's stack: the default ~1 MB allows roughly 500-1000 nested TLA+
Binary file