everystate 0.3.0 → 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,91 @@ 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.
178
+
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).
98
200
 
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.
201
+ ## Agent skill
202
+
203
+ [`skills/formal-verification`](skills/formal-verification/SKILL.md) teaches a coding agent to
204
+ model-check a design with everystate: choose the promise, model the steps, run the check, see it
205
+ fail, report the counterexample in the code's words. It comes with a worked example
206
+ (`example/Charge.tla`). Copy the folder into your agent's skills directory, for example
207
+ `.claude/skills/`.
102
208
 
103
209
  ## Options
104
210
 
@@ -114,13 +220,18 @@ everystate [options] SPEC[.tla]
114
220
  Exit status: 0 success, 10 assumption, 11 deadlock, 12 safety, 13 liveness, 150 parse error,
115
221
  151 config error.
116
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
+
117
228
  ## How it is checked
118
229
 
119
230
  Real TLC is the reference (details in [CONFORMANCE.md](CONFORMANCE.md)):
120
231
 
121
232
  - [tlaplus/Examples](https://github.com/tlaplus/Examples), models up to 5 s: 122 of 122 match on
122
233
  result and exact state counts.
123
- - 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.
124
235
  - pstack `statechart` corpus: 33 of 33 outputs byte-identical.
125
236
 
126
237
  Faster than single-worker Java TLC on all 12 benchmark models (1.1x to 4.6x, thin on three of
@@ -128,9 +239,8 @@ them), with near-instant start-up: [BENCHMARK.md](BENCHMARK.md).
128
239
 
129
240
  ## Not supported
130
241
 
131
- Simulation mode, multiple workers, disk-backed state storage (everything is in memory, so a few
132
- million distinct states is the practical limit), the PlusCal translator (already-translated specs
133
- 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
134
244
  are parsed and skipped).
135
245
 
136
246
  ## Development
@@ -140,8 +250,10 @@ npm run build # native binary and wasm/everystate.wasm
140
250
  npm test # WASM API, pretty-printer and community-module tests
141
251
  ```
142
252
 
143
- Releases: bump the version in `package.json` and `Cargo.toml` and push to `main`;
144
- `.github/workflows/release.yml` builds the binaries and publishes to npm (trusted publishing, no token).
253
+ Releases use [changesets](.changeset/README.md): add one with `npx changeset` in your pull request,
254
+ then merge the "Version Packages" pull request that appears. That bumps `package.json` and
255
+ `Cargo.toml`, and `.github/workflows/release.yml` builds the binaries and publishes to npm and
256
+ crates.io (trusted publishing, no tokens).
145
257
 
146
258
  An earlier pure-TypeScript engine is in the git history at commit `e8c67ce` (npm `everystate@0.1.0`).
147
259
 
@@ -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.0",
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",
@@ -23,16 +22,20 @@
23
22
  "wasm/everystate.d.ts",
24
23
  "wasm/everystate.wasm",
25
24
  "wasm/cli.mjs",
25
+ "skills",
26
26
  "README.md",
27
27
  "LICENSE"
28
28
  ],
29
29
  "scripts": {
30
30
  "build": "cargo build --release && sh wasm/build.sh",
31
- "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",
32
32
  "conformance:examples": "node scripts/conformance.mjs",
33
33
  "conformance:tlc": "node scripts/diff-tlc.mjs",
34
34
  "conformance:statechart": "node scripts/statechart-corpus.mjs",
35
- "bench": "node scripts/bench.mjs"
35
+ "conformance:pcal": "node scripts/pcal-corpus.mjs",
36
+ "bench": "node scripts/bench.mjs",
37
+ "changeset": "changeset",
38
+ "version": "changeset version && node scripts/sync-version.mjs"
36
39
  },
37
40
  "engines": {
38
41
  "node": ">=20"
@@ -48,5 +51,8 @@
48
51
  "repository": {
49
52
  "type": "git",
50
53
  "url": "git+https://github.com/mattzcarey/everystate.git"
54
+ },
55
+ "devDependencies": {
56
+ "@changesets/cli": "^3.0.3"
51
57
  }
52
58
  }
@@ -0,0 +1,240 @@
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. 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).
16
+
17
+ ## The tool
18
+
19
+ `everystate` is a TLA+ model checker with TLC's command line, output and exit codes, as one binary.
20
+
21
+ ```sh
22
+ npx everystate Spec.tla # reads Spec.cfg next to it
23
+ npx everystate -config Other.cfg Spec.tla # another configuration of the same spec
24
+ npx everystate -json Spec.tla # one JSON object on the last line of stdout
25
+ ```
26
+
27
+ | Exit | Meaning |
28
+ |---|---|
29
+ | 0 | every reachable state checked, nothing found |
30
+ | 10 | an `ASSUME` is false |
31
+ | 11 | deadlock: a state with no next step |
32
+ | 12 | an invariant is violated |
33
+ | 13 | a liveness property is violated |
34
+ | 150 / 151 | the spec / the `.cfg` does not parse |
35
+
36
+ The JSON object has `status` (`ok`, `invariant`, `liveness`, `deadlock`, ...), the state counts, and
37
+ on a failure `name` and `trace`: the shortest list of `{action, state}` steps that reaches it.
38
+
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.
45
+
46
+ ## How to do it
47
+
48
+ 1. **Pick the promise.** One sentence the code is supposed to keep, where a break harms users: "a
49
+ card is charged at most once", "two workers never hold the same lease". Read the code first and
50
+ take the promise from it; ask the user only what you cannot see.
51
+ 2. **Model the steps, not the code.** One variable per piece of state that matters, one action per
52
+ step that can interleave with others. What the model treats as one step must be one indivisible
53
+ step in the code: a read followed by a write is two actions unless a lock or transaction makes
54
+ it one. Include the failures: lost messages, timeouts, crashes, retries. Use the code's names,
55
+ and put a comment on each action saying which function it stands for.
56
+ 3. **Bound it.** Constants in the `.cfg` keep the model finite (2 or 3 workers, 3 retries). Most
57
+ design bugs show up at these sizes.
58
+ 4. **State the properties.** A type invariant first, since it catches modelling mistakes. Then the
59
+ promise as an `INVARIANT` ("never bad") or a `PROPERTY` ("eventually good", which needs fairness
60
+ in `Spec`).
61
+ 5. **Run it and read the result.** On a violation, retell the trace as a short story in the code's
62
+ words. Then decide: is this a real bug, or did the model allow a step the code cannot take?
63
+ Check against the code before changing either.
64
+ 6. **See it fail.** A check that has never failed proves nothing. Break the model the way the code
65
+ could be broken (remove the guard, reorder two steps) and confirm the checker reports it. Keep
66
+ that as a second `.cfg` or note the mutation you tried.
67
+ 7. **Report honestly.** Say what was checked, at which bounds, under which assumptions, and what
68
+ the model leaves out. A pass covers the model at those bounds, not the whole system.
69
+
70
+ Do not weaken a property or the model to get a pass, and do not change product code unless asked:
71
+ a counterexample on the current code is a finding to report.
72
+
73
+ ## Worked example
74
+
75
+ [`example/Charge.tla`](example/Charge.tla) models a client that retries a card charge when the
76
+ reply is lost. The promise is `ChargedAtMostOnce`. The constant `Idempotent` says whether the
77
+ server remembers the request key.
78
+
79
+ ```sh
80
+ cd example
81
+ npx everystate Charge.tla # Idempotent = TRUE: exit 0, 29 distinct states
82
+ npx everystate -config ChargeBroken.cfg Charge.tla # Idempotent = FALSE: exit 12
83
+ ```
84
+
85
+ The broken configuration fails with this trace, which reads: the client sends, times out and sends
86
+ again; the server handles both requests and charges twice.
87
+
88
+ ```
89
+ Error: Invariant ChargedAtMostOnce is violated.
90
+ State 1: <Initial predicate> charges = 0, sent = 0
91
+ State 2: <Send ...> sent = 1, inFlight = 1
92
+ State 3: <Send ...> sent = 2, inFlight = 2
93
+ State 4: <Handle ...> charges = 1
94
+ State 5: <Handle ...> charges = 2
95
+ ```
96
+
97
+ (Shortened: the real output prints every variable in every state.)
98
+
99
+ The same spec checks `EventuallyConfirmed`, a liveness property: under weak fairness on sending,
100
+ handling and receiving, the client always learns the charge went through.
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
+
222
+ ## A `.cfg` in brief
223
+
224
+ ```
225
+ SPECIFICATION Spec \* or INIT Init and NEXT Next
226
+ CONSTANTS
227
+ MaxSends = 3
228
+ Workers = {w1, w2} \* model values
229
+ INVARIANTS TypeOK ChargedAtMostOnce
230
+ PROPERTY EventuallyConfirmed
231
+ CHECK_DEADLOCK FALSE \* when stopping is a legitimate end
232
+ SYMMETRY Perms \* Perms == Permutations(Workers); safety only
233
+ ```
234
+
235
+ ## Leaving it for the next change
236
+
237
+ If the check should outlive this task, commit the spec and `.cfg` next to the code and record with
238
+ them: the one command that runs it, which files and functions each action stands for, the bounds,
239
+ and the commit at which the model was last confirmed against the code. Whoever changes that code
240
+ 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
@@ -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