agent-formal-verify 0.4.19 → 0.4.20

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/CHANGES.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changes
2
2
 
3
+ ## 0.4.20 - Protocols between processes routed to TLA+, per-engine helper notes, TLC sandbox reporting, and mutation and Kani baseline fixes
4
+
5
+ The skill now sends protocols between processes, such as message delivery, retries, leases and crash recovery, to TLA+ in any language. Kani stays the choice for a bounded sequential Rust function, and Lean for sequential properties in other languages or proofs for every size. Before this change, the checker table named only thread interleavings, and the skill preferred Kani for any Rust function whose inputs and loops can be bounded.
6
+
7
+ The mutation runner now prints a `FAIL` line for every malformed mutation in the file before it stops, and names the lines where `-` text that occurs more than once starts, as in `its - text occurs 3 times in <model>, want 1 (lines 12, 40, 77)`. Before this change, it stopped at the first malformed mutation, so a file with two stale mutations took two runs, and a repeated `-` text took a search of the model to find.
8
+
9
+ `references/helpers.md` now holds what every engine shares, and the matrix runner, Lean checker and Rust checker, with the TLA+ and Kani parts of the baseline helper, moved to `references/tla-helpers.md`, `references/lean-helpers.md` and `references/rust-helpers.md`. The skill reads the shared file with the part for each target's engine. Each line moved unchanged. A Lean or TLA+ target now reads 9.6 KB or 10.5 KB of helper notes in place of 22.1 KB, and a Rust target 18.3 KB. Before this change, reading the helper reference with a brief in one command overflowed the inline output limit in two of six eval traces, and the agent read only a 2 KB preview.
10
+
11
+ A Java TLC run that cannot listen on a local port, as under a sandbox that denies network binding, now makes the matrix and mutation runners print an `UNAVAILABLE` line and exit 3. The line names two remedies: run where processes may listen on localhost, or set `TLC_ENGINE=everystate`, which opens no port. TLC's fingerprint set is an RMI object, so every run opens a port, even on one machine. Before this change, each run printed `FAIL ... TLC threw an unexpected exception`, which reads as a model failure, and the agent searched the references for a fix that they do not hold.
12
+
13
+ The TLA+, Lean and Rust briefs now give the mutations file's syntax: a `mutation` line, the `detects` line each engine needs, `-` lines that quote consecutive model lines occurring once, and `+` lines that replace them. Before this change, only `mutate.py`'s own header and the review brief gave it. A Lean eval run grepped the helper reference and read `mutate.py`'s source to learn how to replace several lines, and a Kani run wrote a mutation with two `detects` lines.
14
+
15
+ Kani baseline comparison reports `added body <function>` for a new proof harness when previously recorded code uses its name. Check whether the new harness shadows a function that an existing proof calls or takes as a function value.
16
+
17
+ A Kani check, a Lean check or a TLA+ run whose `stderr` reader exits while the check runs, such as `head -n 1`, now exits with its verdict's code. Before this change, the elapsed-time line that could not be written stayed in Python's `stderr` buffer, and the flush at shutdown failed on it again, so a passing check exited 120.
18
+
19
+ The Kani baseline reads a function's body after a braced const argument in its return type or where clause, a braced type macro, or the never return type. Older records can contain a const expression in place of the body or omit the function. Review affected functions against the original revision and record them again.
20
+
3
21
  ## 0.4.19 - Protocols between processes in the TLA+ brief, TLA+ runs with stderr closed, and Kani baseline and mutation fixes
4
22
 
5
23
  Step 1 of the skill now searches for protocols between processes or services, such as retries, timeouts, leases, idempotency keys, queue consumers and webhook handlers, and the TLA+ brief says how to model them: lost and repeated messages and crashes are separate actions that constants inject at any point, a timeout can fire whenever a caller waits, each send remains separately deliverable, including a retry with the same payload, and messages can arrive in any order, a crash keeps only durable state and a restart runs the recovery code, a request can still take effect after its caller times out, and a lease can expire while its holder still acts. The brief says which of these steps get fairness. Such a model checks `TypeOK` and the one promise whose break harms a user, and adds a property from a short list, such as at most one effect per request key or no accepted write with a lower fencing token, only when the code makes that promise. The brief now sizes each step to the atomic unit that the code guarantees, such as a critical section, a compare-and-swap, or a transaction whose isolation or conflict mechanism protects its whole relevant read/decision/write dependency, so row locks or per-key conditions alone do not collapse an unprotected predicate read and later write, and it lists mutations for these protocols.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-formal-verify",
3
- "version": "0.4.19",
3
+ "version": "0.4.20",
4
4
  "description": "Model-check protocols with TLA+, prove invariants with Lean 4, and check bounded Rust functions with Kani.",
5
5
  "author": {
6
6
  "name": "Michael Denyer",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: formal-verify
3
- description: "Model-check thread protocols with TLA+ and TLC, prove sequential invariants with Lean 4, and check bounded Rust functions with Kani. Map counter-examples to source locations, reproductions and fixes, and keep the models in CI. Bring existing models back in line after the code changes. Use for /agent-formal-verify:formal-verify, formal verification, model checking, Lean proofs, Kani, bounded Rust verification, rechecking models after code changes, or concurrency bugs that runtime tests cannot reproduce."
3
+ description: "Model-check thread and interprocess protocols with TLA+ and TLC, prove sequential invariants with Lean 4, and check bounded Rust functions with Kani. Map counter-examples to source locations, reproductions and fixes, and keep the models in CI. Bring existing models back in line after the code changes. Use for /agent-formal-verify:formal-verify, formal verification, model checking, Lean proofs, Kani, bounded Rust verification, rechecking models after code changes, or concurrency bugs that runtime tests cannot reproduce."
4
4
  ---
5
5
 
6
6
  # Formal verify
@@ -11,13 +11,13 @@ Choose tools according to the target:
11
11
 
12
12
  | What can go wrong | Tool | Why |
13
13
  | --- | --- | --- |
14
- | Thread interleavings that lose wakeups, free resources twice, deliver items twice or out of order, block close, or report errors on the wrong thread | TLA+ with TLC | TLC explores the states of a small instance and reports counter-examples |
14
+ | Thread interleavings (wakeups, ownership, delivery, close, error routing) or interprocess message delivery, retries, leases and crash recovery | TLA+ with TLC | TLC explores the states of a small instance and reports counter-examples |
15
15
  | Overflow, out-of-bounds access, panics and broken invariants in a Rust function with bounded loops | Kani | Kani checks the real code for every input within the stated bounds |
16
16
  | Arithmetic or sequential transitions that break bounds, invariants or encoder round trips, or reach states the code assumes impossible | Lean 4 | Evaluate bounded instances, then prove the property for every size |
17
17
 
18
- Prefer Kani when the function is Rust and its inputs and loops can be bounded, because it checks the production function directly. Use Lean when the property must hold for every size or the code is not Rust.
18
+ Use TLA+ for interprocess behavior in any language. Prefer Kani for a bounded sequential Rust function. Use Lean for sequential properties in other languages or proofs for every size.
19
19
 
20
- A thread protocol that depends on arithmetic such as `slot = item mod window` needs both tools. Use TLA+ for the interleavings with the arithmetic as a constant, and Lean for the arithmetic.
20
+ A protocol that depends on arithmetic such as `slot = item mod window` needs both tools. Use TLA+ for the interleavings with the arithmetic as a constant, and Lean for the arithmetic.
21
21
 
22
22
  Use the tool the user names. When the table gives another tool for part of the target, report what the named tool leaves unchecked.
23
23
 
@@ -63,7 +63,7 @@ Each setup command also reports the temporary directory's free space; [tool setu
63
63
 
64
64
  If a system prerequisite such as Java or elan is missing, use the [setup skill](../setup/SKILL.md) to prepare it within the user's installation constraints and existing authorization. Report any prerequisite that cannot be prepared. If `java` on PATH has no runtime, set `JAVA` to a working JDK's `java` binary for the setup helper and the matrix runner.
65
65
 
66
- Read the [helper reference](references/helpers.md) before you interpret a helper's output. It says what each helper checks and prints. The helpers:
66
+ Read the [helper reference](references/helpers.md) and the part for each target's engine, [TLA+](references/tla-helpers.md), [Lean](references/lean-helpers.md) or [Rust](references/rust-helpers.md), before you interpret a helper's output. They say what each helper checks and prints. The helpers:
67
67
 
68
68
  - The setup helper: [`scripts/setup.sh`](scripts/setup.sh)
69
69
  - The matrix runner: [`scripts/tlc-matrix.sh`](scripts/tlc-matrix.sh)
@@ -89,7 +89,7 @@ Name the brief file and leave its text out of the prompt. The [TLA+ brief](refer
89
89
 
90
90
  An agent writes only its own files, `tla/<Name>.tla`, `.matrix` and `.mutations`, `lean/Model/<Name>.lean`, `.mutations` and `.statements`, or the `#[cfg(kani)]` harness module in the production file that defines its Rust function and the `.mutations` file beside it, so parallel agents share none. Give one agent every Rust target in one production file. An existing Lean project keeps its layout and must pin Lean 4.20.0 or later. A Kani harness that an earlier run wrote in a crate of its own moves into its production file when the Rust brief's "Moving a harness" section allows, so it gets an agent even when it passes; otherwise its agent edits it and its `.mutations` file in place.
91
91
 
92
- When the agents have reported, delete each moved harness's old file, and its crate, workspace entry and CI steps once they hold nothing else. Then rerun every check in this thread: the matrix runner on each matrix file, the Lean checker on the whole project without a file name, the Rust checker on each crate, and the mutation runner on each mutations file. Take each verdict from these runs, not from an agent's report. For a moved harness, first run `baseline.py move` as the [helper reference](references/helpers.md) says. Then run `python3 <skill-dir>/scripts/baseline.py compare <record-file>`. It exits 1 and prints CHANGED with the changed parts when a recorded property, fairness condition, matrix line, `.statements` record, Kani harness or helper body, cover or stub changed, a Kani harness was removed, renamed, no longer compiles or had its `cfg` guards changed on a route the record reads, a Kani assumption was added or changed, or a function or method was added beside a Kani harness. Accept a move only as that reference says. Also read `git diff` for each model that existed before this run, for the changes the record does not cover, such as a theorem newly marked `private`, a new guard in a TLA+ action, or a narrowed input in a Kani helper outside the harness's module. Each such change needs the evidence its row cites, a specification correction accepted below, or for a re-freeze another reason the Lean brief permits. Revert any change without it and give the model back to its agent with the reason. Run the comparison again until it exits 0. Report each file that prints `NOT CHECKED` as not checked against Kani.
92
+ When the agents have reported, delete each moved harness's old file, and its crate, workspace entry and CI steps once they hold nothing else. Then rerun every check in this thread: the matrix runner on each matrix file, the Lean checker on the whole project without a file name, the Rust checker on each crate, and the mutation runner on each mutations file. Take each verdict from these runs, not from an agent's report. For a moved harness, first run `baseline.py move` as the [Rust helper reference](references/rust-helpers.md) says. Then run `python3 <skill-dir>/scripts/baseline.py compare <record-file>`. It exits 1 and prints CHANGED with the changed parts when a recorded property, fairness condition, matrix line, `.statements` record, Kani harness or helper body, cover or stub changed, a Kani harness was removed, renamed, no longer compiles or had its `cfg` guards changed on a route the record reads, a Kani assumption was added or changed, or a function or method was added beside a Kani harness. Accept a move only as that reference says. Also read `git diff` for each model that existed before this run, for the changes the record does not cover, such as a theorem newly marked `private`, a new guard in a TLA+ action, or a narrowed input in a Kani helper outside the harness's module. Each such change needs the evidence its row cites, a specification correction accepted below, or for a re-freeze another reason the Lean brief permits. Revert any change without it and give the model back to its agent with the reason. Run the comparison again until it exits 0. Report each file that prints `NOT CHECKED` as not checked against Kani.
93
93
 
94
94
  Accept a specification correction when a reviewer finding, a missed mutation, an UNCOVERED result with source evidence, or a checked witness demonstrates a gap in the old statement. Read the old and proposed guarantees against the callers, record the evidence and decision in the target's row, and permit the corresponding re-freeze even when production code is unchanged. The correction must preserve the intended guarantee or strengthen it over the intended inputs. A broken proof alone does not justify changing a statement. A weaker guarantee or a new assumption excluding shipped inputs needs evidence of an intentional production contract change or the user's explicit agreement. Rerun all checks after the accepted correction and re-freeze. Then run `baseline.py record <record-file>` again on that model's file, and add the previous and new digests it prints to the row.
95
95
 
@@ -2,10 +2,9 @@
2
2
 
3
3
  Detailed behaviour of the verification scripts under `scripts/`. Run each helper from the target repository using `bash` or `python3` with `<skill-dir>` resolved to the installed `formal-verify` skill directory.
4
4
 
5
+ Each engine has a part of its own: [TLA+](tla-helpers.md), [Lean](lean-helpers.md) and [Rust](rust-helpers.md). Read the part for each target's engine with this file.
6
+
5
7
  - **Setup helper ([`scripts/setup.sh`](../scripts/setup.sh))**: verifies the pinned TLC JAR (`tla`), or `everystate` 0.4.6 or later when `TLC_ENGINE=everystate`, checks the pinned Kani driver and bundled Rust toolchain (`rust`), and is the only helper that installs a Lean toolchain (`lean`).
6
- - **Matrix runner ([`scripts/tlc-matrix.sh`](../scripts/tlc-matrix.sh))**: runs TLC (or the native `everystate` engine with `-lncheck final` when `TLC_ENGINE=everystate`, requiring no JDK or JAR) with a matrix of constants. It prints an `ENGINE` line naming the checker and version before the first run, then one `PASS` or `FAIL` per run with its state count, then a `SUMMARY` line with the totals (tagged with `(everystate <version>)` when using `everystate`). Stops each run after sixty minutes, or after the limit in `TLC_TIMEOUT` as [setup](setup.md) describes, and forwards periodic elapsed-time and `Progress(...)` updates to `stderr` during long runs. A failing run prints its error trace reduced by [`scripts/tlc_trace.py`](../scripts/tlc_trace.py) to the variables each step changed. Set `TLC_HTML_REPORT=<path>` to also write a self-contained offline HTML report through [`scripts/tlc_report.py`](../scripts/tlc_report.py) with the active engine metadata, the run table, an interactive native SVG state chain, a variable diff panel, and copyable Mermaid `stateDiagram-v2` source for each failing and `reach` witness trace. The runner checks the path after checking the TLA+ engine and before the first run, and a path where it cannot write the report prints an `UNAVAILABLE TLC_HTML_REPORT=...` line with the remedy and exits 3. It replaces the report in one step, and a written report leaves `stdout` and the exit status as they are without one. If the write fails after the runs, the runner prints the same line and exits 1 when a run failed and 3 otherwise. `tlc.py ready` and `mutate.py` ignore the variable. Copy [`examples/tla-template/`](../examples/tla-template/BoundedQueue.tla) to start a spec and its matrix.
7
- - **Lean checker ([`scripts/lean-check.sh`](../scripts/lean-check.sh))**: builds every `.lean` file in the pinned Lake project and audits every declaration of every built module. It fails on a build error, a `sorry`, a declaration that rests on an axiom beyond `propext`, `Classical.choice` and `Quot.sound`, or a `.lean` file that no Lake library owns. It checks each `<Property>.witness` theorem against its property's hypotheses, and fails on a witness that states something else, as the [Lean brief](lean-brief.md) describes. It then replays every built module, and every project module it imports, through the Lean kernel with the pin's `leanchecker`, which rejects a declaration that a command added without a kernel check. A pin without `leanchecker`, such as Lean 4.20.0, passes with the replay reported as unavailable. While the build, the audit or the replay runs, the checker writes a line such as `[lean] build: 45s elapsed` to `stderr` after fifteen seconds and every thirty seconds after that. The mutation runner writes the same lines while it runs the checker on the unmutated model. It then writes `[lean] unmutated model: <N>s elapsed` while Lean elaborates that model, and a line such as `[lean] mutation no step: 45s elapsed`, which names the mutation, while Lean elaborates each mutant. Use `--freeze` before the file names to record statement types and definition bodies in each model's `.statements` file before proving it. Freezing permits `sorry` and reports `FROZEN`, not a proof `PASS`. Later checks enforce those records and permit proof changes and added declarations. Given file names after the project, it checks only those files. Copy [`examples/lean-template/Model/BoundedQueue.lean`](../examples/lean-template/Model/BoundedQueue.lean) to start a model.
8
- - **Rust checker ([`scripts/kani-check.sh`](../scripts/kani-check.sh))**: runs the pinned Kani on the crate's proof harnesses. It reports each harness's unwind bound and check count, requires a satisfied cover witness in each passing harness, rejects failed checks, and prints concrete playback tests when available. It stops each harness after five minutes, or after the limit in `KANI_HARNESS_TIMEOUT` as [setup](setup.md) describes, and fails a harness that reaches the limit with a message that names the setting. Each harness check, here or in the mutation runner, can take up to that limit, so run the command in the background or with a command timeout longer than the total. While Kani builds the crate or checks a harness, the checker and the mutation runner write a line such as `[kani] proofs::claim_keeps_invariant: 45s elapsed` to `stderr` after fifteen seconds and every thirty seconds after that. When discovery fails because code Kani compiles uses a feature newer than Kani's bundled toolchain (error E0658), the failure names that toolchain, and the [Rust brief](rust-brief.md) says what to rewrite or report. Copy [`examples/kani-template/`](../examples/kani-template/src/lib.rs) for a bounded-queue example.
9
8
  - **Mutation runner ([`scripts/mutate.py`](../scripts/mutate.py))**: takes a model's `<Name>.mutations` file and applies each listed bug to a temporary copy of the model. Each Rust mutation gets a fresh copy of the source. When the crate or a local dependency has a Cargo build script, each mutation also gets its own target directory so the script runs for that source tree. Otherwise every mutation reuses the same source and target paths to cache dependency builds. It prints `DETECTED` or `MISSED` per mutation with what failed, `UNCOVERED` for a TLA+ property or a Kani harness in the adjacent Rust file that no mutation targets or for a public theorem in a Lean model's `.statements` file whose proof no mutation makes fail, and a `SUMMARY` line. Lean names are fully qualified. A Lean `DETECTED` line means the existing proof fails; it does not establish that the statement is false or its hypotheses can hold. A Lean mutation that changes the statement of a theorem, example or `#guard`, such as renaming a definition that the statement names, reaches no verdict, and so does a mutation that edits the text of a theorem whose proof then fails. The runner matches a failing example or `#guard` to one occurrence in the original model, so a failure in an example or `#guard` that the mutation adds, or in one that it cannot match to a single original occurrence, also reaches no verdict. So does a TLA+ mutation whose check reaches the `TLC_TIMEOUT` limit, or a Kani mutation whose harness reaches the Rust checker's time limit. TLA+ runs inherit `TLC_ENGINE`, print the `ENGINE` line before checking the unmutated model, and tag `SUMMARY` with `(everystate <version>)` when using `everystate`. A mutation with no verdict stops the run with a `FAIL` line. A Lean model needs its `.statements` file before its mutations run. All three templates include a mutations file.
10
9
  - **Sync helper ([`scripts/sync.py`](../scripts/sync.py))**: takes an existing model's files, the source files its header names as `--source` and the functions and shared variables it covers as `--name`, and lists what changed since the model was last synced. [Step 1 of the skill](../SKILL.md#1-pick-the-targets) says what to do with its `SYNC none`, `READ` and `MISSING` lines.
11
10
  - Output:
@@ -19,26 +18,14 @@ Detailed behaviour of the verification scripts under `scripts/`. Run each helper
19
18
  - Documents, such as `.md`, `.txt` and `.tex` files and `README` or `CHANGELOG` with no extension, TLA+ and Lean model files, and each of the model's files that is not also given as `--source` are not searched, unless a source path has the same extension. They get no `PATH` line, and the `READ` command does not show their changes, such as a changelog entry.
20
19
  - In languages other than Rust, such as C, JavaScript or Python, a mention of a covered name in a comment or a string counts as finding it, so the name gets no `MISSING` line even when only a comment still mentions it.
21
20
  - **Baseline helper ([`scripts/baseline.py`](../scripts/baseline.py))**: records what each model specifies and later names each part that changed. [Steps 2](../SKILL.md#2-prepare-the-tools) and [3](../SKILL.md#3-model-one-target-per-agent) of the skill say when to run `record` and `compare`, list the changes that `compare` reports and say what to do with them.
22
- - The Kani baseline includes helpers in an inline module declared inside a function when that module holds a harness. A baseline made before support for these modules can lack their helpers. Review those helpers against the original revision and record the file again.
23
21
  - Output of `record <record-file> <model files>`:
24
22
  - `RECORDED <file> <digest>` for each file, with an indented `previous <digest>` line under it when the file's entry had another digest.
25
- - An indented `not checked against Kani: <reason>` line: Kani is missing or the harness file's Cargo package does not compile, so the entry holds what the file's text shows alone.
26
23
  - Output of `compare <record-file>`, which exits 1 when a recorded file changed. Each indented line under `CHANGED` counts as a change, except the `not checked against Kani at record, ...` line and the lines under it:
27
24
  - `UNCHANGED <file>`, `CHANGED <file>` or `NOT CHECKED <file>` for each recorded file, then `SUMMARY <n> unchanged, <m> changed`, which ends with `, <k> not checked` when a file printed `NOT CHECKED`.
28
- - An indented `removed <item>`, or `changed <item>` with its `old:` and `new:` values. A Kani harness's value is the `cfg` guards that can switch it off, followed by its `kani::should_panic` and `kani::unwind(<n>)` attributes and the `unread(...)` note that "Cannot see" describes. When more than one route that the record reads leads to the file, the value holds each route as its crate root's path relative to the harness file's directory and its guards, such as `routes(lib.rs: unguarded; main.rs: cfg(feature = "slow"))`, so adding, removing or guarding any route, or moving a guard from one route to another, changes the harness. The item `body <function>` holds, for a harness and for each other free function or method in an `impl` or trait block in a module that holds a harness or under one, such as an input helper or the `any` of an `impl kani::Arbitrary`, the normalized body without comments, without each `kani::cover!` call whose condition cannot run code, which is an item of its own, and without whitespace except one space where two tokens would otherwise join, such as `{let(window,state)=inputs();...}`. For a helper, the value includes its declaration so a change to a qualifier such as `async`, a parameter, return type or `where` clause is visible even when the body stays the same. An older record shows the added signature on its first comparison. Check it against the recorded revision before recording again. A method's name preserves literals in its block's header, so `impl Input<'a'>` and `impl Input<'b'>` keep separate records. The name puts the header, without the whitespace that a reformat can change, between angle brackets, such as `proofs::<impl kani::Arbitrary for State>::any`, and its assumptions and covers carry that name. Reformatting `let y=&x;` as `let y = &x;` leaves the body unchanged. A space that separates a compound operator counts, as does spacing between operators inside a macro's input, where the macro can inspect it. A trailing comma that a formatter adds or removes also changes the body. The reader omits an empty cover, a boolean name or literal, a comparison between scalar literals (booleans, numbers, characters or byte characters), and short-circuit combinations of those conditions. It keeps other expressions, including `state.next == 3`, as well as string and byte-string comparisons that can call stubbed library code. Field access can call `Deref` and comparisons can call an implementation of `PartialEq`. Review an added cover with a retained condition for implicit calls and side effects before accepting the change. An older record can report changed bodies once for covers it omitted. Check each reported cover against the original revision before recording the file again. A record made before bodies were recorded prints `previous baseline did not record harness bodies` once, one made before the other functions' bodies were recorded prints `previous baseline did not record the functions beside its harnesses` once, and one made before the methods' bodies were recorded prints `previous baseline did not record the methods beside its harnesses` once. For those records, check each harness body against the original revision before recording the file again.
29
- - An indented `added <item>`, which only a new Kani assumption, stub or `body <function>` prints. A function or method added in a module that holds a harness, or under one, can shadow a function that a glob import such as `use super::*;` brings in, so a harness calls the new function with no edit to its own body. Every such function or method prints `added body <function>`, whatever its name, except a new harness, whose body is allowed with it. A harness added in a module that held none puts that module's functions in the record, so each of them prints `added body <function>` once. A record made before the other functions' or the methods' bodies were recorded also prints `added body <function>` for each body it did not record. Check a function that existed at the original revision against that revision. Accept a new function only when each recorded body that names it is listed as added or changed and its change is accepted, and revert it when an unchanged recorded body names it, since that body now calls the new function in place of the one it checked. Then record the file again. A `kani::any_where` assumption includes the complete call, including explicit type arguments. Older records used one representation for plain assumptions and generator predicates. For those records, check the assumptions and generator types against the original revision before recording the file again.
30
- - In a TLA+ module where a local `INSTANCE` introduces substitutions, or that has an indented definition outside a `LET` or a column-0 definition inside one, the helper compares the complete text of each local module it loaded, with comments removed, so a change to a definition that no property uses also needs review. So does a column-0 definition whose header the helper cannot read, such as an infix operator, which it records with the operators it references, whether or not a property references it.
25
+ - An indented `removed <item>`, or `changed <item>` with its `old:` and `new:` values.
31
26
  - An indented `file is missing`: the recorded file no longer exists.
32
- - An indented `not compiled harness <name>`: Kani compiles a stored harness on no route, such as when `Cargo.toml` drops a default feature that a route's `cfg` needs.
33
- - An indented `not checked against Kani at record, ...`: `record` could not check the file against Kani, so `compare` cannot tell a harness that stopped compiling from one that never compiled, such as one behind a feature that is not a default. When Kani runs at `compare`, an indented `not compiled now harness <name>` follows for each recorded harness that Kani does not compile. When Kani could not run at `compare` either, the next line gives the reason. When nothing else changed, the file prints `NOT CHECKED` instead of `CHANGED`. When `move` merges such an entry with one that `record` checked against Kani, the merged entry keeps the checked entry's harnesses, so `compare` still prints `not compiled harness <name>` for them and needs Kani. A `NOT CHECKED` file does not count as a change, so `compare` exits 0 when no file printed `CHANGED`. Report its harnesses as not checked against Kani, and name each harness on a `not compiled now` line under it.
34
27
  - An indented `FAIL <reason>`: the helper could not read the file or ask Kani, which `compare` needs for a harness file that `record` checked against Kani, or Kani compiles a harness from the file under a name that no route the record reads gives. The reason names the problem.
35
28
  - `FAIL baseline: <reason>` exits 1, and a `usage:` line exits 2. `record` fails this way for a file it cannot read, such as a harness file that no route the record reads reaches or a Kani form the record cannot read, where `compare` prints an indented `FAIL` under `CHANGED`. Both fail this way for an unsupported or malformed record file.
36
- - Cannot see:
37
- - In TLA+, the actions that `Spec` names under `[][...]_vars`, `WF_` or `SF_`. It does follow the subscript of those forms and of `<<A>>_vars`, such as `vars`, in every definition it follows, and it follows an operator that `Spec` names outside those forms, such as a fairness definition, into its actions.
38
- - In Kani, the body of a function or method outside the modules that hold harnesses, apart from its assumptions, covers and stubs; read `git diff` for those.
39
- - A route that the record cannot read: a `mod` declaration or `include!` inside a macro like `cfg_if!`, including a `mod $name;` that a macro builds, or inside a block such as a function body, a `#[path]` or `include!` whose path it cannot read, or a file on the way that fails to parse. It cannot tell where such a route leads, so `record` prints `route not read: <reason>`, which names the file and, except for a file that fails to parse, the line, for each one in the harness file's crates. It adds each to every harness's value as `unread(<file>: <route>; ...)`, with the file relative to the harness file's directory. Adding or removing such a route prints `CHANGED`. It does not record the route's guards, and Kani's check fails only when the route gives the harness another module path, so a guard changed on it can print no `CHANGED` line; read `git diff` for it. When no route that it reads reaches the file, `record` fails and names each of them.
40
- - A Kani harness file outside any Cargo package is read from its text alone, so neither `record` nor `compare` asks Kani which harnesses it compiles.
41
- - `baseline.py move <record-file> <old file> <new file>` moves a model's record entry to the file the model moved to, reading the record alone, so a later `compare` checks the new file against what the old one specified, including the harnesses that Kani compiled. For a Kani harness moved into a module of its production file, add `--module <old module> <new module>`, each relative to its file, with `crate` for the file's root, such as `--module crate proofs` for harnesses that sat at the old crate's root, even when the production file is `src/queue.rs`. When the new file already has an entry, the two are merged, and an item in both fails the move. It prints `MOVED <old> -> <new>`. Accept a move when `compare` prints `UNCHANGED`, or `NOT CHECKED` for an entry that `record` could not check against Kani, and `git diff` shows the old file's harness lines in the new module with only their indentation changed, plus the `use crate as <name>;` line and the `#[cfg(kani)] mod proofs` lines around them. When the production file's crate has a route that the record cannot read, `compare` prints a `changed harness` line for each moved harness whose `new:` value only adds an `unread(...)` note to its `old:` value; accept those too, then record the new file again. Any other change, such as an edited assertion, needs the evidence its row cites.
42
29
 
43
30
  ## Find process protocols
44
31
 
@@ -46,7 +46,7 @@ The checker enforces the `.statements` file beside each checked source. Changing
46
46
 
47
47
  The file name limits the Lean checker to your model, so another agent's unfinished file does not fail your check.
48
48
 
49
- List plausible bugs in the mutations file, such as `<` instead of `≤`, a missing `+ 1` or a swapped argument. The mutation runner checks each on a copy of the file and names the theorems and `#guard` lines that fail. Expect both the bounded search's `#guard` and the theorem. It rejects a mutation that stops a definition compiling or changes the statement of a theorem, example or `#guard`, such as renaming a definition that a statement names. Revise the properties behind each MISSED line.
49
+ List plausible bugs in the mutations file, such as `<` instead of `≤`, a missing `+ 1` or a swapped argument. Write each as a `mutation <label>` line, then `-` lines that quote consecutive lines of the model exactly and occur once in it, then `+` lines that replace them. A mutation without `+` lines deletes the quoted text. The mutation runner checks each on a copy of the file and names the theorems and `#guard` lines that fail. Expect both the bounded search's `#guard` and the theorem. It rejects a mutation that stops a definition compiling or changes the statement of a theorem, example or `#guard`, such as renaming a definition that a statement names. Revise the properties behind each MISSED line.
50
50
 
51
51
  The mutation runner checks the original file against its frozen declarations with the Lean checker before running any mutants. It uses Lean's elaborated names and source ranges to report each frozen public theorem whose proof no mutation makes fail. Structure and class projections and instance declarations are not property targets. Names remain fully qualified, including nested namespaces. A failing `#guard` or example does not cover a named theorem. The runner matches a failing guard or example to one original occurrence and compares their elaborated statements. When an edit overlaps a check, preserve the check’s text so the runner can identify a unique occurrence on both sides of the edit. A failure in a new or ambiguous check gives the mutation no verdict. Add a mutation that breaks the proof by changing the model outside the theorem, or propose a specification correction with evidence for the main thread to accept before re-freezing. A helper lemma that shows here should be `private`; a property marked `private` to hide it is a change the main thread reverts. Lean mutations take no `detects` line. For each fix commit in your row, add a mutation that restores the behaviour the code had before the fix, with the commit's short hash in its label.
52
52
 
@@ -0,0 +1,5 @@
1
+ # Lean helpers
2
+
3
+ The Lean behaviour of the helpers. The [helper reference](helpers.md) holds what every engine shares; read it first.
4
+
5
+ - **Lean checker ([`scripts/lean-check.sh`](../scripts/lean-check.sh))**: builds every `.lean` file in the pinned Lake project and audits every declaration of every built module. It fails on a build error, a `sorry`, a declaration that rests on an axiom beyond `propext`, `Classical.choice` and `Quot.sound`, or a `.lean` file that no Lake library owns. It checks each `<Property>.witness` theorem against its property's hypotheses, and fails on a witness that states something else, as the [Lean brief](lean-brief.md) describes. It then replays every built module, and every project module it imports, through the Lean kernel with the pin's `leanchecker`, which rejects a declaration that a command added without a kernel check. A pin without `leanchecker`, such as Lean 4.20.0, passes with the replay reported as unavailable. While the build, the audit or the replay runs, the checker writes a line such as `[lean] build: 45s elapsed` to `stderr` after fifteen seconds and every thirty seconds after that. The mutation runner writes the same lines while it runs the checker on the unmutated model. It then writes `[lean] unmutated model: <N>s elapsed` while Lean elaborates that model, and a line such as `[lean] mutation no step: 45s elapsed`, which names the mutation, while Lean elaborates each mutant. Use `--freeze` before the file names to record statement types and definition bodies in each model's `.statements` file before proving it. Freezing permits `sorry` and reports `FROZEN`, not a proof `PASS`. Later checks enforce those records and permit proof changes and added declarations. Given file names after the project, it checks only those files. Copy [`examples/lean-template/Model/BoundedQueue.lean`](../examples/lean-template/Model/BoundedQueue.lean) to start a model.
@@ -137,8 +137,10 @@ production crate, and report the target as not checked by Kani. A harness in a
137
137
  separate crate that copies the function checks the copy, not the production
138
138
  code, so report it as a model and name the copied source and commit.
139
139
 
140
- Put `<Name>.mutations` beside the production file `<Name>.rs`. Use
141
- `detects <fully-qualified-harness>` for each mutation. The mutation runner uses
140
+ Put `<Name>.mutations` beside the production file `<Name>.rs`. Write each as a
141
+ `mutation <label>` line, one `detects <fully-qualified-harness>` line, `-`
142
+ lines quoting consecutive lines of `<Name>.rs` that occur once in it, and `+`
143
+ lines replacing them. The mutation runner uses
142
144
  the bundled Cargo to find the crate's workspace and local dependencies, copies
143
145
  them to temporary storage with their relative paths intact, and checks the
144
146
  copied manifest from the original crate directory so Cargo retains configuration
@@ -0,0 +1,19 @@
1
+ # Rust helpers
2
+
3
+ The Kani behaviour of the helpers. The [helper reference](helpers.md) holds what every engine shares; read it first.
4
+
5
+ - **Rust checker ([`scripts/kani-check.sh`](../scripts/kani-check.sh))**: runs the pinned Kani on the crate's proof harnesses. It reports each harness's unwind bound and check count, requires a satisfied cover witness in each passing harness, rejects failed checks, and prints concrete playback tests when available. It stops each harness after five minutes, or after the limit in `KANI_HARNESS_TIMEOUT` as [setup](setup.md) describes, and fails a harness that reaches the limit with a message that names the setting. Each harness check, here or in the mutation runner, can take up to that limit, so run the command in the background or with a command timeout longer than the total. While Kani builds the crate or checks a harness, the checker and the mutation runner write a line such as `[kani] proofs::claim_keeps_invariant: 45s elapsed` to `stderr` after fifteen seconds and every thirty seconds after that. When discovery fails because code Kani compiles uses a feature newer than Kani's bundled toolchain (error E0658), the failure names that toolchain, and the [Rust brief](rust-brief.md) says what to rewrite or report. Copy [`examples/kani-template/`](../examples/kani-template/src/lib.rs) for a bounded-queue example.
6
+ - **Baseline helper ([`scripts/baseline.py`](../scripts/baseline.py))** on a Kani harness file:
7
+ - The Kani baseline includes helpers in an inline module declared inside a function when that module holds a harness. A baseline made before support for these modules can lack their helpers. Review those helpers against the original revision and record the file again.
8
+ - In the output of `record`:
9
+ - An indented `not checked against Kani: <reason>` line: Kani is missing or the harness file's Cargo package does not compile, so the entry holds what the file's text shows alone.
10
+ - In the output of `compare`:
11
+ - A Kani harness's value is the `cfg` guards that can switch it off, followed by its `kani::should_panic` and `kani::unwind(<n>)` attributes and the `unread(...)` note that "Cannot see" describes. When more than one route that the record reads leads to the file, the value holds each route as its crate root's path relative to the harness file's directory and its guards, such as `routes(lib.rs: unguarded; main.rs: cfg(feature = "slow"))`, so adding, removing or guarding any route, or moving a guard from one route to another, changes the harness. The item `body <function>` holds, for a harness and for each other free function or method in an `impl` or trait block in a module that holds a harness or under one, such as an input helper or the `any` of an `impl kani::Arbitrary`, the normalized body without comments, without each `kani::cover!` call whose condition cannot run code, which is an item of its own, and without whitespace except one space where two tokens would otherwise join, such as `{let(window,state)=inputs();...}`. For a helper, the value includes its declaration so a change to a qualifier such as `async`, a parameter, return type or `where` clause is visible even when the body stays the same. An older record shows the added signature on its first comparison. Check it against the recorded revision before recording again. A method's name preserves literals in its block's header, so `impl Input<'a'>` and `impl Input<'b'>` keep separate records. The name puts the header, without the whitespace that a reformat can change, between angle brackets, such as `proofs::<impl kani::Arbitrary for State>::any`, and its assumptions and covers carry that name. Reformatting `let y=&x;` as `let y = &x;` leaves the body unchanged. A space that separates a compound operator counts, as does spacing between operators inside a macro's input, where the macro can inspect it. A trailing comma that a formatter adds or removes also changes the body. The reader omits an empty cover, a boolean name or literal, a comparison between scalar literals (booleans, numbers, characters or byte characters), and short-circuit combinations of those conditions. It keeps other expressions, including `state.next == 3`, as well as string and byte-string comparisons that can call stubbed library code. Field access can call `Deref` and comparisons can call an implementation of `PartialEq`. Review an added cover with a retained condition for implicit calls and side effects before accepting the change. An older record can report changed bodies once for covers it omitted. Check each reported cover against the original revision before recording the file again. A record made before bodies were recorded prints `previous baseline did not record harness bodies` once, one made before the other functions' bodies were recorded prints `previous baseline did not record the functions beside its harnesses` once, and one made before the methods' bodies were recorded prints `previous baseline did not record the methods beside its harnesses` once. For those records, check each harness body against the original revision before recording the file again.
12
+ - An indented `added <item>`, which only a new Kani assumption, stub or `body <function>` prints. A function or method added in a module that holds a harness, or under one, can shadow a function that a glob import such as `use super::*;` brings in, so a harness calls the new function with no edit to its own body. Every such function or method prints `added body <function>`, whatever its name, except a new harness whose name never occurs in previously recorded code. A new proof can shadow a function that an older proof calls or passes as a value. When its name occurs in a recorded body, assumption, stub or cover, check whether the reference resolves to the added proof. References with the same name in different scopes can also trigger this check. A harness added in a module that held none puts that module's functions in the record, so each of them prints `added body <function>` once. A record made before the other functions' or the methods' bodies were recorded also prints `added body <function>` for each body it did not record. Check a function that existed at the original revision against that revision. Accept a new function only when each recorded body that names it is listed as added or changed and its change is accepted, and revert it when an unchanged recorded body names it, since that body now calls the new function in place of the one it checked. Then record the file again. A `kani::any_where` assumption includes the complete call, including explicit type arguments. Older records used one representation for plain assumptions and generator predicates. For those records, check the assumptions and generator types against the original revision before recording the file again.
13
+ - An indented `not compiled harness <name>`: Kani compiles a stored harness on no route, such as when `Cargo.toml` drops a default feature that a route's `cfg` needs.
14
+ - An indented `not checked against Kani at record, ...`: `record` could not check the file against Kani, so `compare` cannot tell a harness that stopped compiling from one that never compiled, such as one behind a feature that is not a default. When Kani runs at `compare`, an indented `not compiled now harness <name>` follows for each recorded harness that Kani does not compile. When Kani could not run at `compare` either, the next line gives the reason. When nothing else changed, the file prints `NOT CHECKED` instead of `CHANGED`. When `move` merges such an entry with one that `record` checked against Kani, the merged entry keeps the checked entry's harnesses, so `compare` still prints `not compiled harness <name>` for them and needs Kani. A `NOT CHECKED` file does not count as a change, so `compare` exits 0 when no file printed `CHANGED`. Report its harnesses as not checked against Kani, and name each harness on a `not compiled now` line under it.
15
+ - Cannot see:
16
+ - In Kani, the body of a function or method outside the modules that hold harnesses, apart from its assumptions, covers and stubs; read `git diff` for those.
17
+ - A route that the record cannot read: a `mod` declaration or `include!` inside a macro like `cfg_if!`, including a `mod $name;` that a macro builds, or inside a block such as a function body, a `#[path]` or `include!` whose path it cannot read, or a file on the way that fails to parse. It cannot tell where such a route leads, so `record` prints `route not read: <reason>`, which names the file and, except for a file that fails to parse, the line, for each one in the harness file's crates. It adds each to every harness's value as `unread(<file>: <route>; ...)`, with the file relative to the harness file's directory. Adding or removing such a route prints `CHANGED`. It does not record the route's guards, and Kani's check fails only when the route gives the harness another module path, so a guard changed on it can print no `CHANGED` line; read `git diff` for it. When no route that it reads reaches the file, `record` fails and names each of them.
18
+ - A Kani harness file outside any Cargo package is read from its text alone, so neither `record` nor `compare` asks Kani which harnesses it compiles.
19
+ - `baseline.py move <record-file> <old file> <new file>` moves a model's record entry to the file the model moved to, reading the record alone, so a later `compare` checks the new file against what the old one specified, including the harnesses that Kani compiled. For a Kani harness moved into a module of its production file, add `--module <old module> <new module>`, each relative to its file, with `crate` for the file's root, such as `--module crate proofs` for harnesses that sat at the old crate's root, even when the production file is `src/queue.rs`. When the new file already has an entry, the two are merged, and an item in both fails the move. It prints `MOVED <old> -> <new>`. Accept a move when `compare` prints `UNCHANGED`, or `NOT CHECKED` for an entry that `record` could not check against Kani, and `git diff` shows the old file's harness lines in the new module with only their indentation changed, plus the `use crate as <name>;` line and the `#[cfg(kani)] mod proofs` lines around them. When the production file's crate has a route that the record cannot read, `compare` prints a `changed harness` line for each moved harness whose `new:` value only adds an `unread(...)` note to its `old:` value; accept those too, then record the new file again. Any other change, such as an edited assertion, needs the evidence its row cites.
@@ -34,7 +34,7 @@ python3 <skill-dir>/scripts/mutate.py /path/to/models/Name.mutations
34
34
 
35
35
  The plugin does not download TLC. Save `tla2tools.jar` from the [TLA+ release](https://github.com/tlaplus/tlaplus/releases/tag/v1.7.4) pinned in `scripts/tlc.py` as `~/.cache/tla/tla2tools-v1.7.4.jar`; the setup helper verifies its pinned SHA256 and names that path and release when the file is missing or does not match. Set `TLC_CACHE` to choose another cache directory. Set `TLC_JAR` to use an existing JAR; an explicitly supplied JAR is trusted and must already exist. Matrix and mutation output starts with an `ENGINE` line before any model checks. It gives the version from TLC’s help banner and identifies the pinned release or custom JAR. If a custom build omits its version, the runner records the JAR’s SHA256. The HTML report uses the same label.
36
36
 
37
- With Java TLC, the matrix runner requires the JAR and a working Java runtime; with everystate, it needs neither. It checks for Python 3.9 or later before running, so a failing model can always print its reduced trace. It does not download tools. Each run checks the formula its spec names `Spec` and sees only the modules beside that spec. `TLC_WORKERS` sets the worker count for either engine. Set `TLC_HTML_REPORT=<path>` to write a self-contained offline HTML report (matrix summary, interactive SVG state chain, variable diffs, and copyable Mermaid source for failing and `reach` witness traces) via `scripts/tlc_report.py`; the runner checks the target path after the TLA+ engine and before the first run, prints `UNAVAILABLE` and exits 3 when it cannot write there, and writes the report atomically without changing `stdout` or exit status on success (`tlc.py ready` and `mutate.py` ignore `TLC_HTML_REPORT`). Each run stops after sixty minutes by default; set `TLC_TIMEOUT` to change the limit using a whole number from 1 to 4294967295 with an optional unit `s`, `m` or `h`, such as `90s` or `1h`. For any other value, `setup.sh tla`, the matrix runner and the mutation runner print `UNAVAILABLE` and exit 3 without running TLC. A run that reaches the limit fails with a message naming the limit and `TLC_TIMEOUT`, and a mutation run that reaches it reaches no verdict. During long runs, the runner forwards periodic elapsed-time and `Progress(...)` updates from `tlc.log` to `stderr`. With Java TLC, each run gives the JVM its own `java.io.tmpdir` inside the run directory, so TLC runs started at the same time do not delete each other's copy of the standard modules. A `-Djava.io.tmpdir` in `_JAVA_OPTIONS` overrides it, because the JVM reads that variable after the command line; set the temporary directory with `TMPDIR` instead.
37
+ With Java TLC, the matrix runner requires the JAR and a working Java runtime; with everystate, it needs neither. Java TLC also listens on a local port in every run, even on one machine, so where a sandbox denies that, the matrix and mutation runners print `UNAVAILABLE` and exit 3. There, run the checks with `TLC_ENGINE=everystate`, which opens no port. The matrix runner checks for Python 3.9 or later before running, so a failing model can always print its reduced trace. It does not download tools. Each run checks the formula its spec names `Spec` and sees only the modules beside that spec. `TLC_WORKERS` sets the worker count for either engine. Set `TLC_HTML_REPORT=<path>` to write a self-contained offline HTML report (matrix summary, interactive SVG state chain, variable diffs, and copyable Mermaid source for failing and `reach` witness traces) via `scripts/tlc_report.py`; the runner checks the target path after the TLA+ engine and before the first run, prints `UNAVAILABLE` and exits 3 when it cannot write there, and writes the report atomically without changing `stdout` or exit status on success (`tlc.py ready` and `mutate.py` ignore `TLC_HTML_REPORT`). Each run stops after sixty minutes by default; set `TLC_TIMEOUT` to change the limit using a whole number from 1 to 4294967295 with an optional unit `s`, `m` or `h`, such as `90s` or `1h`. For any other value, `setup.sh tla`, the matrix runner and the mutation runner print `UNAVAILABLE` and exit 3 without running TLC. A run that reaches the limit fails with a message naming the limit and `TLC_TIMEOUT`, and a mutation run that reaches it reaches no verdict. During long runs, the runner forwards periodic elapsed-time and `Progress(...)` updates from `tlc.log` to `stderr`. With Java TLC, each run gives the JVM its own `java.io.tmpdir` inside the run directory, so TLC runs started at the same time do not delete each other's copy of the standard modules. A `-Djava.io.tmpdir` in `_JAVA_OPTIONS` overrides it, because the JVM reads that variable after the command line; set the temporary directory with `TMPDIR` instead.
38
38
 
39
39
  The mutation runner reads `Name.mutations` beside `Name.tla` and `Name.matrix`. For each mutation it copies the spec, replaces the listed text, and runs the matrix runner with the one property the mutation names, so it needs the same tools and settings.
40
40
 
@@ -63,7 +63,7 @@ The matrix runner prints PASS or FAIL per run and a SUMMARY line. A failing run
63
63
 
64
64
  Each reach check prints its own PASS with the shortest witness length in states and transitions, or FAIL when the model never reaches the state. Witness searches use one worker and ignore deadlock so they can finish exploring a stopped model; `reach:` mutations run with `TLC_WORKERS` because confirming `UNREACHED` explores the full state graph without a witness trace. Attach each `reach` check—especially those paired with `detects reach:<Operator>`—to the smallest boundary `run` that exercises the predicate rather than large fault-injection configurations. The SUMMARY counts reach checks separately; its state total covers ordinary runs only. Use `detects reach:<Operator>` for a mutation that removes a required state. Reach checks do not count as properties for mutation coverage.
65
65
 
66
- Before reporting a pass, list mutations that represent plausible code bugs in the mutations file. Try replacing `while` with `if`, removing a broadcast, replacing FIFO order with stack order, leaving a flag set, or taking an item without removing it. For a protocol between processes, also try removing the request-key check, acknowledging before the durable write, retrying a permanent error, splitting a compare-and-swap or transaction the code relies on into a separate read and write, and removing the version or token check from a conditional write. Each mutation names the one property that must fail on it. For each fix commit in your row, add a mutation that restores the behaviour the code had before the fix, with the commit's short hash in its label. The mutation runner applies each to a copy of the spec, using only matrix runs where its named check is in scope. The same detector must pass on the original spec at those settings before a mutant can earn credit. Temporal mutations disable TLC's separate deadlock check so that the temporal property itself must fail; a deadlock alone earns no detection. Revise a property it reports as UNCOVERED, and the property or the mutation behind each MISSED line.
66
+ Before reporting a pass, list mutations that represent plausible code bugs in the mutations file. Try replacing `while` with `if`, removing a broadcast, replacing FIFO order with stack order, leaving a flag set, or taking an item without removing it. For a protocol between processes, also try removing the request-key check, acknowledging before the durable write, retrying a permanent error, splitting a compare-and-swap or transaction the code relies on into a separate read and write, and removing the version or token check from a conditional write. Write each as a `mutation <label>` line and a `detects <Property>` or `detects reach:<Operator>` line that names the one check that must fail on it. An optional `only <label-substring>` line keeps only the matrix runs whose label contains it. Then come `-` lines that quote consecutive lines of the spec exactly and occur once in it, and `+` lines that replace them. A mutation without `+` lines deletes the quoted text. For each fix commit in your row, add a mutation that restores the behaviour the code had before the fix, with the commit's short hash in its label. The mutation runner applies each to a copy of the spec, using only matrix runs where its named check is in scope. The same detector must pass on the original spec at those settings before a mutant can earn credit. Temporal mutations disable TLC's separate deadlock check so that the temporal property itself must fail; a deadlock alone earns no detection. Revise a property it reports as UNCOVERED, and the property or the mutation behind each MISSED line.
67
67
 
68
68
  ## Report
69
69
 
@@ -0,0 +1,10 @@
1
+ # TLA+ helpers
2
+
3
+ The TLA+ behaviour of the helpers. The [helper reference](helpers.md) holds what every engine shares; read it first.
4
+
5
+ - **Matrix runner ([`scripts/tlc-matrix.sh`](../scripts/tlc-matrix.sh))**: runs TLC (or the native `everystate` engine with `-lncheck final` when `TLC_ENGINE=everystate`, requiring no JDK or JAR) with a matrix of constants. It prints an `ENGINE` line naming the checker and version before the first run, then one `PASS` or `FAIL` per run with its state count, then a `SUMMARY` line with the totals (tagged with `(everystate <version>)` when using `everystate`). Stops each run after sixty minutes, or after the limit in `TLC_TIMEOUT` as [setup](setup.md) describes, and forwards periodic elapsed-time and `Progress(...)` updates to `stderr` during long runs. A failing run prints its error trace reduced by [`scripts/tlc_trace.py`](../scripts/tlc_trace.py) to the variables each step changed. Set `TLC_HTML_REPORT=<path>` to also write a self-contained offline HTML report through [`scripts/tlc_report.py`](../scripts/tlc_report.py) with the active engine metadata, the run table, an interactive native SVG state chain, a variable diff panel, and copyable Mermaid `stateDiagram-v2` source for each failing and `reach` witness trace. The runner checks the path after checking the TLA+ engine and before the first run, and a path where it cannot write the report prints an `UNAVAILABLE TLC_HTML_REPORT=...` line with the remedy and exits 3. It replaces the report in one step, and a written report leaves `stdout` and the exit status as they are without one. If the write fails after the runs, the runner prints the same line and exits 1 when a run failed and 3 otherwise. `tlc.py ready` and `mutate.py` ignore the variable. Copy [`examples/tla-template/`](../examples/tla-template/BoundedQueue.tla) to start a spec and its matrix.
6
+ - **Baseline helper ([`scripts/baseline.py`](../scripts/baseline.py))** on a TLA+ model:
7
+ - In the output of `compare`:
8
+ - In a TLA+ module where a local `INSTANCE` introduces substitutions, or that has an indented definition outside a `LET` or a column-0 definition inside one, the helper compares the complete text of each local module it loaded, with comments removed, so a change to a definition that no property uses also needs review. So does a column-0 definition whose header the helper cannot read, such as an infix operator, which it records with the operators it references, whether or not a property references it.
9
+ - Cannot see:
10
+ - In TLA+, the actions that `Spec` names under `[][...]_vars`, `WF_` or `SF_`. It does follow the subscript of those forms and of `<<A>>_vars`, such as `vars`, in every definition it follows, and it follows an operator that `Spec` names outside those forms, such as a fairness definition, into its actions.
@@ -20,13 +20,13 @@ change, and so is an added item whose kind narrows what is checked.
20
20
  #[path], with each route in the file's crates that the record cannot read, such as a mod
21
21
  declaration inside a macro, and each kani::assume, kani::any_where, kani::cover! and
22
22
  #[kani::stub] with its owning free function, under inline modules, or method in an impl or trait block,
23
- such as proofs::<impl kani::Arbitrary for State>::any. Unsupported owners fail. Added covers and harnesses are allowed.
23
+ such as proofs::<impl kani::Arbitrary for State>::any. Unsupported owners fail. Added covers and independent harnesses are allowed.
24
24
  Added assumes and stubs are changes. Also the body of each harness and of each other free function or
25
25
  method in a module that holds a harness, or under one, without its comments, the kani::cover! calls whose
26
26
  conditions cannot run code, and the whitespace that a reformat can change. A helper's record includes
27
27
  its attributes, qualifiers, parameters, return type and where clause as well as its body. An added
28
28
  function or method there is a change, since it can shadow one that a glob import brings in. An added
29
- harness can still have its own body.
29
+ harness is also reported if its name occurs in recorded code.
30
30
  In a Cargo package, also the recorded harnesses that Kani compiles from the file; Kani must give
31
31
  each harness it compiles there a module path that a route the record reads gives, and a harness
32
32
  that no longer compiles is a change.
@@ -59,7 +59,7 @@ import runner
59
59
  import tlc
60
60
  from kani_reader import KANI_KEY, RouteReader, compiled_problems, kani_surface
61
61
  from lean_records import read_record as read_lean_record
62
- from rust_source import normalized
62
+ from rust_source import normalized, rust_masks
63
63
  from surface import STRING, Surface, collapse
64
64
 
65
65
  FORMAT = 2
@@ -343,6 +343,39 @@ def compact_kani_record(surface, current):
343
343
  return compact
344
344
 
345
345
 
346
+ def kani_references(surface):
347
+ """Collect identifiers from recorded code, including Kani forms stored outside a body."""
348
+ names = set()
349
+ for item, value in surface.items():
350
+ if item.startswith("body "):
351
+ code = re.sub(r"^fn\s+(?:r#)?\w+", "", value)
352
+ elif item.startswith(("assume ", "stub ", "cover ")):
353
+ code = item.partition(" ")[2].rsplit(" in ", 1)[0]
354
+ else:
355
+ continue
356
+ names.update(re.findall(r"(?:r#)?([^\W\d]\w*)", rust_masks(code).without_comments_or_strings))
357
+ return names
358
+
359
+
360
+ def added_kani_bodies(old, new):
361
+ """An added harness can shadow a name an older proof calls or takes as a function value."""
362
+ references = None
363
+ for name in new:
364
+ if not name.startswith("body ") or name in old:
365
+ continue
366
+ owner = name.removeprefix("body ")
367
+ harness = "harness " + owner
368
+ if harness in new:
369
+ if harness in old:
370
+ continue
371
+ if references is None:
372
+ references = kani_references(old)
373
+ leaf = re.sub(r"\[\d+\]$", "", owner.rsplit("::", 1)[-1]).removeprefix("r#")
374
+ if leaf not in references:
375
+ continue
376
+ yield f" added {name}"
377
+
378
+
346
379
  class KaniKind:
347
380
  """Record, compare and move the harnesses, assumptions, covers and stubs of a Kani file, checked against what Kani compiles."""
348
381
 
@@ -373,10 +406,7 @@ class KaniKind:
373
406
  surface = kani_surface(path, self.reader)
374
407
  recorded_surface = compact_kani_record(entry["surface"], surface)
375
408
  lines = differences(recorded_surface, surface, ("assume", "stub"))
376
- # An added function or method can shadow one that a glob import such as `use super::*;` brings in, so a
377
- # harness calls it with no edit to a recorded body. An added harness's own body is allowed with it.
378
- lines += [f" added {name}" for name in surface if name.startswith("body ") and name not in recorded_surface
379
- and "harness " + name.removeprefix("body ") not in surface]
409
+ lines.extend(added_kani_bodies(recorded_surface, surface))
380
410
  if may_omit_generator_types(entry):
381
411
  lines.insert(0, " previous baseline stored assumptions without distinguishing any_where input types; review the original assumptions and record this file again")
382
412
  if any(name.startswith("harness ") and "body " + name.removeprefix("harness ") not in entry["surface"] for name in entry["surface"]):
@@ -69,7 +69,16 @@ def rust_functions(source):
69
69
  elif mask[i] == "{":
70
70
  stop = after_closing(mask, i)
71
71
  header = mask[boundary:i].rstrip()
72
- macro = header.endswith("!") or bool(re.search(r"\bmacro_rules\s*!\s*\w+\s*$", header))
72
+ macro = re.search(r"\b(?:\w+\s*!|macro_rules\s*!\s*\w+)$", header)
73
+ if item and item[0] == "fn":
74
+ # A const argument sits between generic delimiters. A braced type macro names its macro before !.
75
+ # Both belong to the signature; the brace after a never return type opens the function body.
76
+ const_argument = header.endswith(("<", ",", "=")) and re.compile(r"\s*[,>]").match(mask, stop)
77
+ if macro or const_argument:
78
+ if macro:
79
+ opaque.append((i, stop))
80
+ i = stop
81
+ continue
73
82
  if item and item[0] in ("impl", "trait"):
74
83
  # A braced const argument in the header ends before the next generic argument or closing angle.
75
84
  if re.compile(r"\s*[,>]").match(mask, stop):
@@ -40,7 +40,9 @@ Mutations file (a line starting with # is a comment):
40
40
 
41
41
  A TLA+ or Rust mutation needs one detects line, and a Lean mutation takes
42
42
  none. The runner reads every mutation and applies it to the model's text
43
- before it runs any tool, so a malformed mutation stops the run first.
43
+ before it runs any tool, so a malformed mutation stops the run first. It
44
+ prints a FAIL line for each malformed mutation, and names the lines where
45
+ - text that occurs more than once starts.
44
46
 
45
47
  Usage: mutate.py <Name.mutations>
46
48
  The environment settings of tlc-matrix.sh apply to TLA+ mutations.
@@ -145,26 +147,41 @@ def parse(path):
145
147
  return mutations
146
148
 
147
149
 
150
+ def occurrences(text, old):
151
+ """Return the start of each occurrence of old in text that does not overlap an earlier one."""
152
+ starts = []
153
+ start = text.find(old) if old else -1
154
+ while start >= 0:
155
+ starts.append(start)
156
+ start = text.find(old, start + len(old))
157
+ return starts
158
+
159
+
148
160
  def make_mutation(label, directives, model, text, language):
149
- """Validate one mutation and locate its edit in the original model."""
161
+ """Validate one mutation and locate its edit in the original model.
162
+
163
+ Raises:
164
+ ValueError: the mutation is malformed, or its - text does not occur exactly once in the model.
165
+ """
150
166
  lines = {keyword: [rest for word, rest in directives if word == keyword] for keyword in DIRECTIVES}
151
167
  for keyword in SINGLE:
152
168
  if len(lines[keyword]) > 1:
153
- stop(f"mutation '{label}' has two {keyword} lines")
169
+ raise ValueError(f"mutation '{label}' has two {keyword} lines")
154
170
  if lines["detects"] and not language.needs_detects:
155
- stop(f"mutation '{label}': {language.name} mutations take no detects line; the runner names the theorems that fail")
171
+ raise ValueError(f"mutation '{label}': {language.name} mutations take no detects line; the runner names the theorems that fail")
156
172
  if language.needs_detects and not lines["detects"]:
157
- stop(f"mutation '{label}' has no detects line")
173
+ raise ValueError(f"mutation '{label}' has no detects line")
158
174
  if lines["only"] and not language.takes_only:
159
- stop(f"mutation '{label}': {language.name} mutations do not support 'only'")
175
+ raise ValueError(f"mutation '{label}': {language.name} mutations do not support 'only'")
160
176
  old = "\n".join(lines["-"])
161
- start = text.find(old) if old else -1
162
- if start < 0 or text.find(old, start + len(old)) >= 0:
163
- count = text.count(old) if old else 0
164
- stop(f"mutation '{label}': its - text occurs {count} times in {model}, want 1")
177
+ starts = occurrences(text, old)
178
+ if len(starts) != 1:
179
+ where = sorted({text.count("\n", 0, start) + 1 for start in starts})
180
+ at = f" (lines {', '.join(map(str, where))})" if len(starts) > 1 else ""
181
+ raise ValueError(f"mutation '{label}': its - text occurs {len(starts)} times in {model}, want 1{at}")
165
182
  detects, only = (lines[keyword][0].strip() if lines[keyword] else "" for keyword in SINGLE)
166
183
  new = "\n".join(lines["+"])
167
- return Mutation(label, detects, only, old, new, text, start)
184
+ return Mutation(label, detects, only, old, new, text, starts[0])
168
185
 
169
186
 
170
187
  def check_tla(plan, checker, mutation, work):
@@ -307,7 +324,16 @@ def main():
307
324
  if model is None:
308
325
  stop(f"no {', '.join(model.name for model in models[:-1])} or {models[-1].name} beside {path}")
309
326
  language, text = LANGUAGES[model.suffix], model.read_text(encoding="utf-8")
310
- mutations = [make_mutation(label, directives, model, text, language) for label, directives in parse(path)]
327
+ mutations, errors = [], []
328
+ for label, directives in parse(path):
329
+ try:
330
+ mutations.append(make_mutation(label, directives, model, text, language))
331
+ except ValueError as error:
332
+ errors.append(error)
333
+ for error in errors:
334
+ print(f"FAIL {error}")
335
+ if errors:
336
+ sys.exit(1)
311
337
  with contextlib.ExitStack() as run:
312
338
  prepared = language.runner(model, mutations, run)
313
339
  storage.warn_runtime()
@@ -229,6 +229,21 @@ def guarded(command, body, **kwargs):
229
229
  raise
230
230
 
231
231
 
232
+ def report_progress(line):
233
+ """Write a progress line if stderr is available, without changing the checker's exit status."""
234
+ stream = sys.stderr
235
+ if stream is None:
236
+ return
237
+ with suppress(OSError, ValueError):
238
+ if stream is sys.__stderr__:
239
+ # Keep progress out of stderr's buffer: a failed flush there retries at shutdown and sets exit status 120.
240
+ stream.flush()
241
+ with open(stream.fileno(), "w", closefd=False, encoding=stream.encoding, errors=stream.errors) as progress:
242
+ progress.write(line + "\n")
243
+ else:
244
+ print(line, file=stream, flush=True)
245
+
246
+
232
247
  def communicate(process, label=None):
233
248
  """Return process.communicate(); with a label, write '<label>: <N>s elapsed' to stderr while the process runs."""
234
249
  if label is None or sys.stderr is None:
@@ -242,10 +257,7 @@ def communicate(process, label=None):
242
257
  except subprocess.TimeoutExpired:
243
258
  now = time.monotonic()
244
259
  if now >= next_report:
245
- # Callers read an OSError as a command that could not start, so a closed stderr must not raise one.
246
- with suppress(OSError):
247
- sys.stderr.write(f"{label}: {int(now - start)}s elapsed\n")
248
- sys.stderr.flush()
260
+ report_progress(f"{label}: {int(now - start)}s elapsed")
249
261
  next_report = now + PROGRESS_INTERVAL
250
262
 
251
263
 
@@ -50,7 +50,6 @@ import sys
50
50
  import tempfile
51
51
  import time
52
52
  import uuid
53
- from contextlib import suppress
54
53
  from dataclasses import dataclass, replace
55
54
  from enum import Enum
56
55
  from pathlib import Path
@@ -225,12 +224,7 @@ class _Engine:
225
224
  elapsed = int(now - start)
226
225
  prefix = f"[{self.log_tag}] {progress_label}: " if progress_label else f"[{self.log_tag}] "
227
226
  body = f"{elapsed}s elapsed: {latest}" if latest else f"{elapsed}s elapsed"
228
- # Python sets sys.stderr to None when the process starts with stderr closed.
229
- # A closed or unwritable stderr must not fail a run whose checker passed.
230
- if sys.stderr is not None:
231
- with suppress(OSError):
232
- sys.stderr.write(f"{prefix}{body}\n")
233
- sys.stderr.flush()
227
+ processes.report_progress(f"{prefix}{body}")
234
228
  next_report = now + PROGRESS_INTERVAL
235
229
  wait_for = min(remaining, max(0.05, next_report - time.monotonic()))
236
230
  try:
@@ -313,7 +307,13 @@ class Tlc(_Engine):
313
307
  command = [self.java, "-XX:+UseParallelGC", f"-Djava.io.tmpdir={java_tmp}", "-cp", self.jar, "tlc2.TLC", "-workers", chosen_workers,
314
308
  *(["-deadlock"] if reach else []), "-cleanup", "-metadir", str(directory / "states"),
315
309
  "-config", str(directory / "MC.cfg"), str(directory / f"{module}.tla")]
316
- return self._run_watched(command, log, progress_label)
310
+ status, output, timed_out = self._run_watched(command, log, progress_label)
311
+ # TLC's fingerprint set is an RMI object, so every run exports it on a local port, even on one machine.
312
+ if "java.rmi.server.ExportException: Listen failed on port" in output:
313
+ raise runner.Unavailable("UNAVAILABLE TLC could not listen on a local port (java.rmi.server.ExportException), which it needs even on one machine; "
314
+ "run the check where processes may listen on localhost, such as outside a sandbox that denies network binding, "
315
+ "or with TLC_ENGINE=everystate, which opens no port")
316
+ return status, output, timed_out
317
317
 
318
318
 
319
319
  class Everystate(_Engine):