agent-formal-verify 0.4.20 → 0.4.21
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 +20 -0
- package/package.json +1 -1
- package/skills/formal-verify/SKILL.md +1 -1
- package/skills/formal-verify/references/evidence.md +1 -1
- package/skills/formal-verify/references/rust-brief.md +15 -23
- package/skills/formal-verify/references/rust-helpers.md +4 -5
- package/skills/formal-verify/references/setup.md +5 -3
- package/skills/formal-verify/references/tla-brief.md +1 -0
- package/skills/formal-verify/references/tla-helpers.md +3 -1
- package/skills/formal-verify/scripts/baseline.py +37 -13
- package/skills/formal-verify/scripts/kani_reader.py +23 -2
- package/skills/formal-verify/scripts/lean.py +124 -2
- package/skills/formal-verify/scripts/lean_mutations.py +2 -5
- package/skills/formal-verify/scripts/mutate.py +12 -7
- package/skills/formal-verify/scripts/tlc.py +198 -34
- package/skills/formal-verify/scripts/tlc_report.py +2 -2
package/CHANGES.md
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
# Changes
|
|
2
2
|
|
|
3
|
+
## 0.4.21 - TLA+ matrix symmetry and cfg checks, a TLC check in setup, natively built Lean analysis, and Kani baselines that read the items beside a harness
|
|
4
|
+
|
|
5
|
+
The matrix runner and `mutate.py` now reject, before any run, a matrix line that could change the generated cfg beyond itself. That is a name on a `check` line, or a constant's name, that is not a TLA+ identifier or that is a cfg keyword of TLC or everystate, such as `TYPE` or `TYPE_CONSTRAINT`, or a TLA+ reserved word, and a `reach` operator that is not a TLA+ identifier or is a reserved word. It is also a constant's value that holds a comment opener, a string that it does not close, or a cfg keyword outside a string that is not the whole value or a whole set element, such as `{}PROPERTIES`. Each such line prints `FAIL <matrix>:<line>:` with the problem, and both runners exit 2. `baseline.py record` fails on the same lines. Before this change, the check line `check INVARIANTS InWindow PROPERTIES Bogus`, the constant `FailAt={}PROPERTIES(**)Bogus` or a constant named `PROPERTIES(**)Bogus(**)CONSTANT(**)FailAt` added a `PROPERTIES Bogus` statement to the cfg, and a value with an unclosed string made TLC stop with an unexpected exception.
|
|
6
|
+
|
|
7
|
+
`setup.sh tla` with Java TLC now checks a one-state model before it prints `READY`, so where TLC cannot listen on a local port, setup prints the matrix runner's `UNAVAILABLE` line and exits 3. Before this change, setup printed `READY TLC` there, and the agent learned that TLC could not run only after it had written a model. The check adds about 0.6 seconds: setup took 0.76 s at the median of ten runs against 0.17 s before, on an Apple Silicon Mac with JDK 21. With an unusable `TMPDIR`, setup now prints only its `FAIL` line, without a `READY` line before it. Setup with everystate runs no model.
|
|
8
|
+
|
|
9
|
+
A TLA+ matrix section can hold one `symmetry <Operator>` line, which adds `SYMMETRY <Operator>` to the cfg of each run and `reach` check in the section and of the mutation runs taken from it. On the template with three workers, `Perms == Permutations(Workers)` and a section of the invariants and reach checks, the `window=4 items=5 workers=3` run falls from 46,451 to 8,019 distinct states on TLC 1.7.4 and on everystate 0.4.6, and every run, reach witness length and mutation verdict stays the same. TLC can miss a liveness violation under symmetry, so the runner refuses the line in a section that checks a `PROPERTY` or `PROPERTIES`, and in a section with two such lines. It prints a `FAIL` line, runs that section without symmetry and exits 1, and the mutation runner and baseline helper stop on that line. The operator passes the same name check as a `check` name, so `symmetry PROPERTIES` stops the runners with status 2 before any run. The baseline helper records each run's symmetry and the operator's definition, so adding, removing or changing the line prints `CHANGED`. The TLA+ brief says when symmetry is sound: a `CHOOSE` over the set, a value named in the spec or a constant, or an order on the values can make an invariant pass falsely or a reach check report "never reached", and no runner detects that.
|
|
10
|
+
|
|
11
|
+
The Lean checker and the mutation runner now run `scripts/lean-analysis.lean` as a program that the pin's own `lean` and `leanc` build the first time they use the toolchain. The program stays in `~/.cache/agent-formal-verify/lean-analysis`, or in `LEAN_ANALYSIS_CACHE` when that is set, and nothing is written into the skill directory. Before this change, every audit and every mutation ran the file with `lean --run`, which elaborated it and imported Lean for it on each call, and then imported Lean a second time for the model. On the Lean template, with Lean 4.35.0 on an Apple M5 Pro, the median of seven interleaved runs of a `lean-check.sh` call went from 3.2 s to 1.8 s, and of a run of its three mutations from 8.3 s to 3.0 s, below the 2.3 s and 7.3 s measured before the analysis moved into one program. The first call with a toolchain spends about 4 s on the build. The output is unchanged. A toolchain without `leanc`, or a build that fails, runs the file with `lean --run` as before, and a failed build prints why on `stderr`.
|
|
12
|
+
|
|
13
|
+
The Kani baseline now records the rest of each module that holds a harness, without its functions, as `items in <module>`: its `use` declarations, constants, macro definitions and calls, and the headers of its modules and `impl` blocks. A change there prints `CHANGED` with `changed items in <module>`. Before this change, a `use super::fake::claim;`, a `const claim` or a macro that defines `fn claim`, added beside a harness, took the place of the `claim` that `use super::*;` brings in, so the harness checked the stand-in and `compare` printed `UNCHANGED`. A record made before this change holds no such items, so `compare` prints `CHANGED` with a `previous baseline did not record items in <module>` line for each module until the file is recorded again, and `move` keeps no `items in` when it merges such a record with a newer one. A harness moved from a crate of its own with `baseline.py move` now prints one `changed items in proofs` line for the `use crate as <name>;` that the Rust brief adds; the Rust helper reference says to accept it.
|
|
14
|
+
|
|
15
|
+
`references/rust-helpers.md` and `references/rust-brief.md` are shorter. With `references/helpers.md`, a Rust target now reads 28,090 bytes, 1,153 under the 29,243-byte limit that keeps the read in one inline tool result. The three files held 29,236 bytes before this change and the older-record note above, so an addition of more than 7 bytes failed the size test. The notes on older Kani records are now one sentence, since `compare` prints what to review for each such record, and text that repeated another section or described how the helpers work inside is gone. The TLA+ and Lean reads are unchanged.
|
|
16
|
+
|
|
17
|
+
The native build of `scripts/lean-analysis.lean` is now named for the size and modification time of the toolchain's `bin/lean`, of each library in its `lib/lean` and of each `.olean` file under that directory. Before this change it read only `bin/lean`, which on macOS is a 49,968-byte launcher in both Lean 4.35.0 and 4.36.0, while the program links Lean's libraries and reads the `.olean` files. With a path pin whose directory held 4.35.0 and then 4.36.0, and `bin/lean` given its old modification time, the next `lean-check.sh` reused the 4.35.0 program and failed with `failed to read file '…/lib/lean/Init.olean', incompatible header`; it now builds a new program and passes. Reading the files costs each Lean checker and mutation runner process 15 ms with Lean 4.20.0 (1,529 files) and 35 ms with 4.35.0 (2,565 files), at the median of 21 runs, against 0.2 ms before. Each program in the cache is built once more after the upgrade.
|
|
18
|
+
|
|
19
|
+
A matrix constant can again use a cfg keyword as a model value when the keyword is the whole value, a whole set element or inside a string, as in `Mode=INIT`, `Mode={TYPE,VIEW}` or `Mode="INIT"`, and a `reach` operator can again be named like a cfg keyword, as in `reach INIT | label`. The check above had refused them, though TLC 1.7.4 and everystate 0.4.6 read each of the 24 keywords in those places as a model value or string, and the reach check names its operator in a wrapper module rather than in the cfg. A keyword in any other place, such as `FailAt={}CONSTANT`, still stops the runners with status 2; both engines read that one as a second `CONSTANTS` statement and pass the run.
|
|
20
|
+
|
|
21
|
+
The line of a run or `reach` check under a section's `symmetry` line now names the operator, as in `PASS BoundedQueue window=4 items=5 workers=3 8019 distinct states found under symmetry Perms` or `FAIL One reach Full n=4 under symmetry Perms: the model never reaches this state`. So do the run's row and the title of its trace in the `TLC_HTML_REPORT` report, and the mutation runner's `DETECTED` line, as in `Counted fails in run 'three' under symmetry Perms`. A `MISSED` line names each run that passed under symmetry, as in `MISSED <label>: run 'three' passes under symmetry Perms`. Before this change, these lines matched those of a full run, so a reader without the matrix could not tell that 8019 counted one state for each set of states that the symmetry merges, not the 46,451 states of a full run, or that the verdict depended on the model treating the values alike.
|
|
22
|
+
|
|
3
23
|
## 0.4.20 - Protocols between processes routed to TLA+, per-engine helper notes, TLC sandbox reporting, and mutation and Kani baseline fixes
|
|
4
24
|
|
|
5
25
|
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.
|
package/package.json
CHANGED
|
@@ -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 [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.
|
|
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, or another item such as a `use` changed, 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
|
|
|
@@ -13,7 +13,7 @@ Include the matching meaning from this table where each kind of evidence first a
|
|
|
13
13
|
| A bounded search passes | Every input up to the stated bound was tried. |
|
|
14
14
|
| Mutations detected | Deliberate bugs were planted in copies of the model, and the checks caught each one. For Lean, this shows that existing proofs fail, not that the mutated statements are false. |
|
|
15
15
|
| Past fix detected | The checks fail on the behaviour before a recorded bug fix. For Lean, report proof sensitivity separately from whether a checked counterexample establishes that the property rules out that bug. |
|
|
16
|
-
| Specification unchanged | The baseline comparison preserved each recorded run's inputs and checks, reach check's selected inputs, property and fairness definition, action subscript such as `vars`, statement record, qualified Kani harness name with its `should_panic` and `unwind` attributes and the `cfg` attributes that can switch it off on each route the record reads, function-owned assumption, cover and stub, and body of each Kani harness and of each function or method in a module that holds one, such as an input helper or an `impl kani::Arbitrary`, including its assertions, input construction and the conditions around its assertions, apart from comments, layout and covers whose conditions cannot run code. It also found no function or method added in those modules, other than a new harness, since
|
|
16
|
+
| Specification unchanged | The baseline comparison preserved each recorded run's inputs and checks, reach check's selected inputs, property and fairness definition, action subscript such as `vars`, statement record, qualified Kani harness name with its `should_panic` and `unwind` attributes and the `cfg` attributes that can switch it off on each route the record reads, function-owned assumption, cover and stub, and body of each Kani harness and of each function or method in a module that holds one, such as an input helper or an `impl kani::Arbitrary`, including its assertions, input construction and the conditions around its assertions, apart from comments, layout and covers whose conditions cannot run code. It also found no function or method added in those modules, other than a new harness, and no change to their other items, such as a `use`, `const` or macro call, since each can shadow a function that a glob import brings in. It does not cover the body of a function or method outside those modules, apart from its assumptions, covers and stubs, or the `cfg` attributes on a route that its record value lists under `unread(...)`; `git diff` does. |
|
|
17
17
|
| UNAVAILABLE | The tool could not run. This target was not checked; give the printed remedy. |
|
|
18
18
|
| reproduced | A deterministic test or race-detector run fails on the production code. |
|
|
19
19
|
| reachable at shipped settings | The shipped constants and callers permit the counter-example, but no production reproduction has confirmed it yet. |
|
|
@@ -46,9 +46,8 @@ to the code you read.
|
|
|
46
46
|
|
|
47
47
|
## Moving a harness
|
|
48
48
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
the production file that defines the functions it calls:
|
|
49
|
+
Move a harness that an earlier run wrote in a crate of its own into the
|
|
50
|
+
production file that defines the functions it calls:
|
|
52
51
|
|
|
53
52
|
1. Move its helpers and harnesses into the `#[cfg(kani)] mod proofs` at the
|
|
54
53
|
end of the production file, creating the module if the file has none, and
|
|
@@ -86,7 +85,7 @@ Use `kani::any()` for inputs and `kani::assume` for caller constraints. Record
|
|
|
86
85
|
integer widths, input bounds and each assumption beside the harness. If a callee
|
|
87
86
|
needs a stub or a function contract, name that assumption in the header comment.
|
|
88
87
|
Put `#[kani::unwind(N)]` on every harness, above its real loop bounds. The checker
|
|
89
|
-
requires this explicit bound
|
|
88
|
+
requires this explicit bound. A failed unwinding assertion
|
|
90
89
|
means the bound is too low and fails the check. Discovery and verification both
|
|
91
90
|
enable `-Z stubbing`, so documented `#[kani::stub]` attributes work in either step.
|
|
92
91
|
The checker rejects a harness marked `#[kani::should_panic]` when it would verify
|
|
@@ -103,12 +102,11 @@ Add `kani::cover!` witnesses for the boundary or blocking states each property
|
|
|
103
102
|
depends on, such as a full window or an empty queue. The checker rejects
|
|
104
103
|
unsatisfiable, unreachable and undetermined covers, even when Kani exits
|
|
105
104
|
successfully. Ordinary unreachable assertions are allowed because they describe
|
|
106
|
-
impossible panic branches. Every passing harness
|
|
107
|
-
`Satisfied` cover after its assumptions. Successful assertions alone do not
|
|
105
|
+
impossible panic branches. Every passing harness, an existing coverless one
|
|
106
|
+
included, needs a `Satisfied` cover after its assumptions. Successful assertions alone do not
|
|
108
107
|
establish reachability: Kani also labels compiler safety checks as assertions,
|
|
109
108
|
and one before contradictory assumptions can pass while the property is
|
|
110
|
-
unreachable.
|
|
111
|
-
witness. Every cover must have status `Satisfied`.
|
|
109
|
+
unreachable.
|
|
112
110
|
|
|
113
111
|
## Check
|
|
114
112
|
|
|
@@ -121,11 +119,9 @@ python3 <skill-dir>/scripts/mutate.py /absolute/path/to/crate/src/Name.mutations
|
|
|
121
119
|
|
|
122
120
|
Append fully qualified harness names to check only those properties. The helper
|
|
123
121
|
prints one verdict per harness with the unwind bound and number of checks. It
|
|
124
|
-
requires a complete Kani 0.68.0 bundle and Python 3.9 or later. It
|
|
125
|
-
bundle's driver directly,
|
|
126
|
-
A
|
|
127
|
-
paths resolve against the caller's directory before any temporary work begins.
|
|
128
|
-
The helper installs no Kani runtime. `UNAVAILABLE` means not checked; follow the
|
|
122
|
+
requires a complete Kani 0.68.0 bundle and Python 3.9 or later. It runs the
|
|
123
|
+
bundle's driver directly, so it needs no registered Cargo installer and installs
|
|
124
|
+
no Kani runtime. A relative `KANI_HOME` resolves against the caller's directory. `UNAVAILABLE` means not checked; follow the
|
|
129
125
|
printed remedy before making any claim about the code. A compilation
|
|
130
126
|
error, missing harness or incomplete verifier report fails.
|
|
131
127
|
|
|
@@ -137,14 +133,11 @@ production crate, and report the target as not checked by Kani. A harness in a
|
|
|
137
133
|
separate crate that copies the function checks the copy, not the production
|
|
138
134
|
code, so report it as a model and name the copied source and commit.
|
|
139
135
|
|
|
140
|
-
|
|
141
|
-
`mutation <label>` line, one `detects <fully-qualified-harness>` line, `-`
|
|
136
|
+
Write each mutation in `<Name>.mutations` as a `mutation <label>` line, one `detects <fully-qualified-harness>` line, `-`
|
|
142
137
|
lines quoting consecutive lines of `<Name>.rs` that occur once in it, and `+`
|
|
143
|
-
lines replacing them. The mutation runner
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
copied manifest from the original crate directory so Cargo retains configuration
|
|
147
|
-
and relative paths to external files. Each selected harness must first pass on
|
|
138
|
+
lines replacing them. The mutation runner checks a
|
|
139
|
+
temporary copy of the crate's workspace and local dependencies from the original
|
|
140
|
+
crate directory, so Cargo keeps its configuration and relative paths. Each selected harness must first pass on
|
|
148
141
|
the unmutated source; a compiler error or inconclusive check never counts as
|
|
149
142
|
detection. Every harness declared in the adjacent Rust file needs a mutation.
|
|
150
143
|
An explicit property failure or a lost cover witness can detect a mutation;
|
|
@@ -153,9 +146,8 @@ An explicit `detects` may also name a harness in another file; unrelated
|
|
|
153
146
|
harnesses in other files do not contribute to this file’s coverage requirement.
|
|
154
147
|
|
|
155
148
|
Direct checks and discovery run from the crate directory so Cargo reads crate
|
|
156
|
-
and ancestor configuration. Discovery
|
|
157
|
-
|
|
158
|
-
tree. Cargo may create or update its normal lockfile.
|
|
149
|
+
and ancestor configuration. Discovery writes no `kani-list.json` into the
|
|
150
|
+
source tree. Cargo may create or update its normal lockfile.
|
|
159
151
|
|
|
160
152
|
For each fix commit in your row whose fixed code is in the file beside the
|
|
161
153
|
mutations file, add a mutation that restores the code before the fix, with the
|
|
@@ -2,18 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
The Kani behaviour of the helpers. The [helper reference](helpers.md) holds what every engine shares; read it first.
|
|
4
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
|
|
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 code Kani compiles uses a feature newer than Kani's bundled toolchain (error E0658), discovery fails and 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
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
7
|
- In the output of `record`:
|
|
9
8
|
- 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
9
|
- 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.
|
|
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
|
|
10
|
+
- 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();...}`. The item `items in <module>`, `items in crate` at the file's root, holds the rest of such a module the same way, without its functions or its modules' contents, such as `use super::*;`. 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. 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 or a helper's declaration, and one made before harness, function or method bodies, `items in` or `kani::any_where` types were recorded prints a `previous baseline ...` line once. Check what each names against the original revision before recording the file again.
|
|
11
|
+
- 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. An added `use`, `const` or macro call can too, so it changes `items in <module>`. 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 recorded code, check whether the reference resolves to the added proof. Same-named references in other scopes also trigger 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 methods' bodies were recorded, such as those in a module inside a function, prints `added body <function>` for each. Check a function that existed at the original revision against that revision. Accept a new function or item 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.
|
|
13
12
|
- 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
13
|
- 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
14
|
- Cannot see:
|
|
16
15
|
- 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
16
|
- 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
17
|
- 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.
|
|
18
|
+
- `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, but `items in` texts are joined, the new file's first, and dropped when either entry predates them. 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. `compare` prints `changed items in <module>` for that line and, when the production file's crate has a route that the record cannot read, 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.
|
|
@@ -10,7 +10,7 @@ The helpers are in the `scripts/` directory of the installed `formal-verify` ski
|
|
|
10
10
|
|
|
11
11
|
Stay in the target repository and run each helper with `bash` and its absolute path. Pass absolute paths to model projects and matrices. Keep the installed skill files read-only, and create models and build outputs in the target repository. Shared tool caches can serve several repositories; each repository determines its own tool requirements and Lean pins.
|
|
12
12
|
|
|
13
|
-
Every runner writes its temporary state into `TMPDIR` (failing cleanly with `FAIL` if an explicitly set `TMPDIR` cannot be created or written) and removes its working directories between matrix runs and on `SIGINT`, `SIGTERM` or `SIGHUP`. `setup.sh tla`, `setup.sh rust` and `setup.sh lean` stop their readiness check on these signals too, including one sent to the `setup.sh` process alone, and end by the signal. Lean builds write into the model project's `.lake` directory, while `lean-check.sh` places its module lists for the audit and the kernel replay in `TMPDIR
|
|
13
|
+
Every runner writes its temporary state into `TMPDIR` (failing cleanly with `FAIL` if an explicitly set `TMPDIR` cannot be created or written) and removes its working directories between matrix runs and on `SIGINT`, `SIGTERM` or `SIGHUP`. `setup.sh tla`, `setup.sh rust` and `setup.sh lean` stop their readiness check on these signals too, including one sent to the `setup.sh` process alone, and end by the signal. Lean builds write into the model project's `.lake` directory, while `lean-check.sh` places its module lists for the audit and the kernel replay in `TMPDIR`, and the Lean checker and the mutation runner keep their analysis program in the cache that the Lean section below names. `setup.sh` (`tla`, `rust`, `lean`, and `storage`) reports `TEMP_DIR` free space, and `SYSTEM_DISK` free space when the temporary directory is on another device. It warns when the active temporary volume, or the system disk while it holds the temporary directory, has less than `FORMAL_MIN_FREE_GIB` free (default `64` GiB). It also lists larger writable `EXTERNAL_VOLUME` mounts so heavy runs can redirect `TMPDIR` onto an external disk. `bash <skill-dir>/scripts/setup.sh storage` runs this storage check alone. Checkers also warn once on `stderr` before starting when active temporary space drops below `10` GiB (or `FORMAL_MIN_FREE_GIB` when set).
|
|
14
14
|
|
|
15
15
|
To stop a checker, a runner suspends the checker and every process it started, then sends them `SIGTERM` and resumes them, so none can start another process meanwhile. This takes a few `ps` calls, a few tens of milliseconds on an idle machine and longer under load. A runner ended in that time by a signal it does not handle, such as `SIGKILL` or `SIGQUIT`, cannot resume them. The checker and the processes suspended so far then stay suspended until something ends them, and the processes it started that were not yet suspended keep running. `SIGINT`, `SIGTERM` and `SIGHUP` do not cause this, because the runner holds them back until the stop finishes and then ends by the signal.
|
|
16
16
|
|
|
@@ -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. 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.
|
|
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. `setup.sh tla` checks a one-state model with Java TLC, so it prints the same line before any model is written. 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
|
|
|
@@ -85,6 +85,8 @@ python3 <skill-dir>/scripts/mutate.py /path/to/lean-project/Model/Name.mutations
|
|
|
85
85
|
|
|
86
86
|
The setup helper and the Lean checker need Python 3.9 or later as `python3`. The Lean pin lookup and readiness check live in [`scripts/lean.py`](../scripts/lean.py), with the checker's steps. The setup helper runs `lean.py ready`, which checks the version in the project's current `lean-toolchain` and installs it only when it is not ready; it leaves the global default unchanged. `elan run` installs a toolchain that is not installed, even without its install flag, so the Lean checker and the mutation runner first look for the pin in `elan toolchain list` and report a missing toolchain as UNAVAILABLE instead of downloading it. A `lean-toolchain` names a release, such as `leanprover/lean4:v4.35.0`, a toolchain that `elan toolchain link` added, or an absolute path to a toolchain directory. A channel, `stable`, `beta` or `nightly`, or a repository's `lean-toolchain` release name, fails, because elan resolves it to a release online. Lake builds may fetch dependencies declared by the model project. The supplied template has no external Lean packages.
|
|
87
87
|
|
|
88
|
+
The Lean checker and the mutation runner read each model through [`scripts/lean-analysis.lean`](../scripts/lean-analysis.lean). The first time they use a toolchain, they build that file into a program with the toolchain's own `lean` and `leanc`, which takes a few seconds, and keep the program in `~/.cache/agent-formal-verify/lean-analysis`. Set `LEAN_ANALYSIS_CACHE` to choose another directory. There is one program for each toolchain and version of the analysis, each 100 to 180 MB, and building one deletes any that no check has used for seven days. A toolchain directory whose `bin/lean`, libraries in `lib/lean` or `.olean` files change size or modification time gets a new program, so a toolchain rebuilt at the same path does not run a program built against the old Lean. When the toolchain has no `leanc`, or the build fails, they run the file with `lean --run` instead, which gives the same output and takes about one more second per call; a failed build prints why on `stderr`.
|
|
89
|
+
|
|
88
90
|
The Lean checker builds every `.lean` file in the project by its path, so a file that no Lake library owns fails the build instead of going unchecked. It then runs the audit in [`scripts/lean-analysis.lean`](../scripts/lean-analysis.lean) against the modules Lake reports for those files. The checker needs a pin of Lean 4.20.0 or later, the first whose Lake builds a module by its source path, and says so when an older pin fails. The audit lists every declaration that rests on an axiom beyond `propext`, `Classical.choice` and `Quot.sound`, so a model needs no `#print axioms` lines. The audit imports the project's modules together, so each model declares its names in a namespace of its own. A file name after the project limits the build and the audit to that file.
|
|
89
91
|
|
|
90
92
|
The mutation runner reads `Name.mutations` beside `Name.lean`. It elaborates each mutated copy with the project's toolchain and built modules, outside the project, and does not install a toolchain.
|
|
@@ -95,7 +97,7 @@ Helpers print `UNAVAILABLE` and exit 3 when a required tool is missing, unusable
|
|
|
95
97
|
|
|
96
98
|
The helpers live in this plugin, not in the target repository. In CI, check out `michael-denyer/agent-formal-verify` at a pinned commit into a separate directory and run the helpers from its `skills/formal-verify/scripts/`. Update that pin deliberately, as for any other tool. A repository that vendors the scripts instead must keep their GPL-3.0-only license headers.
|
|
97
99
|
|
|
98
|
-
Install the chosen runtime and the pinned TLC JAR (or an `everystate` 0.4.6+ binary when running with `TLC_ENGINE=everystate`), and for Rust the pinned Kani, in the CI environment, run the setup helper, then run the matrix runner, Lean checker, Rust checker or mutation runner as a separate step. Cache elan's toolchain directory if useful, and keep the version pins with the models. Use the same `TLC_ENGINE`, `TLC_JAR`, `JAVA` and `EVERYSTATE` settings in setup and verification.
|
|
100
|
+
Install the chosen runtime and the pinned TLC JAR (or an `everystate` 0.4.6+ binary when running with `TLC_ENGINE=everystate`), and for Rust the pinned Kani, in the CI environment, run the setup helper, then run the matrix runner, Lean checker, Rust checker or mutation runner as a separate step. Cache elan's toolchain directory and the Lean analysis directory if useful, and keep the version pins with the models. Use the same `TLC_ENGINE`, `TLC_JAR`, `JAVA` and `EVERYSTATE` settings in setup and verification.
|
|
99
101
|
|
|
100
102
|
```yaml
|
|
101
103
|
- uses: actions/checkout@<commit>
|
|
@@ -23,6 +23,7 @@ Apply each requirement that fits the protocol, and say in the report which did n
|
|
|
23
23
|
- For a protocol between processes or services, give the network and the processes their failures as separate actions: a lost or repeated message, a crash, and a timeout. Inject loss, duplication and crash at any point, through constants such as `LoseAt`, `DupAt` and `CrashAt` whose matrix values cover every point, as `FailAt` does, and let the caller's timer fire at any point while it waits. Allow any in-flight message to arrive next. Keep one entry per send, using a bounded send ID or a count for each payload, so retries with the same request key and payload can both arrive. To model network duplication, deliver a copy without removing it. A crash keeps the durable state and clears the state in memory; a restart action then runs the recovery code. A timeout changes only the caller's state: the request may already have taken effect, or may still arrive and take effect later. For a lease, let the lease expire while its holder still acts on it, as after a pause, so a stale holder's write can reach storage. Give loss, duplication and crash no fairness. Give weak fairness to each process's steps, to delivery of a message that was not lost, to restart, and to the caller's own timer while it waits. Use at least two clients or workers, two or three retries and one crash.
|
|
24
24
|
- Check small instances and boundary cases. Use slot counts of 1, 2 and the shipped count, item counts of 0, 1, 3 and 5, and one, two and three workers.
|
|
25
25
|
- Name a reachable state predicate for each blocking or boundary behaviour the properties depend on, such as a full window, an empty queue, a parked waiter or an injected failure. Add `reach <Operator> | <label-substring>` to its matrix section. It selects the first run whose label contains the substring. A command-line filter skips the reach check if it excludes that selected run.
|
|
26
|
+
- A set of interchangeable model values, such as workers, clients or replicas, makes TLC explore every permutation of them. To merge those states, add `TLC` to `EXTENDS`, define an operator such as `Perms == Permutations(Workers)`, and add `symmetry Perms` to a matrix section. Use it only when renaming the values changes nothing the model checks: `Init`, every action, invariant and reach predicate, and every run constant treat them alike. A `CHOOSE` over the set, a value named in the spec or in another constant such as `Leader=w1`, or an order on the values breaks that. An invariant can then pass falsely or a reach check report a reachable state as never reached, and no runner detects it. A mutation that treats the values unequally gets no sound verdict under symmetry either. TLC can miss a liveness violation under symmetry, so the runner refuses it in a section that checks a `PROPERTY` or `PROPERTIES`. Check the properties in a second section for the same spec, without the line.
|
|
26
27
|
- Check `TypeOK`, the ownership partition, delivery order, no delivery after end or error, the documented error-ordering guarantee, and no double free or leak at `closed`. For liveness, check that each blocking call returns, `close` terminates from every allowed calling state, and a run without `close` reaches the end. Require weak fairness on thread steps except consumer choices and spurious wakeups. Add strong fairness on a mutex acquisition only when a counter-example shows pure starvation by a spuriously waking peer. Name that assumption in the spec.
|
|
27
28
|
- For a protocol between processes or services, check `TypeOK` and the promise whose break harms a user, stated in one sentence from the code, such as "a card is charged at most once". Add a property from this list only when the code makes that promise to its callers:
|
|
28
29
|
- an effect happens at most once per request key, under repeated requests and retries;
|
|
@@ -2,9 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
The TLA+ behaviour of the helpers. The [helper reference](helpers.md) holds what every engine shares; read it first.
|
|
4
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.
|
|
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. Before it checks the engine, the runner rejects each matrix line that could change the cfg beyond itself: a check name, reach or symmetry operator or constant name that is not a TLA+ identifier or is a TLA+ reserved word; a check name, symmetry operator or constant name that is a cfg keyword; and a constant value that holds a comment opener, a string that it does not close, or a cfg keyword outside a string that is not the whole value or a whole set element. So `Mode=INIT`, `Mode={TYPE,VIEW}`, `Mode="INIT"` and `reach INIT | label` pass, and `FailAt={}PROPERTIES` stops the runner. It prints a `FAIL <matrix>:<line>:` line for each and exits 2, and `mutate.py` does the same. 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
|
+
- **Symmetry**: one `symmetry <Operator>` line in a matrix `spec` section adds `SYMMETRY <Operator>` to the cfg of each run and `reach` check of that section, wherever the line stands in it, and to the mutation runs that [`scripts/mutate.py`](../scripts/mutate.py) takes from the section. Both engines read the line. The line of each run and `reach` check of the section says `under symmetry <Operator>`, after the state count when a run passes and before the colon otherwise, as in `PASS BoundedQueue window=4 items=5 workers=3 8019 distinct states found under symmetry Perms`, where 8019 counts one state for each set of states that the symmetry merges. The run's row in the `TLC_HTML_REPORT` table and the title of its trace add the same words to its label. The mutation runner adds them after the run's name in a `DETECTED` line, and a `MISSED` line names each run that passed under symmetry, as in `MISSED <label>: run 'three' passes under symmetry Perms`. In a section that checks a `PROPERTY` or `PROPERTIES`, or that has two `symmetry` lines, the runner prints a `FAIL` line, runs the section without symmetry and exits 1. The mutation runner and the baseline helper stop on that line before any run. The [TLA+ brief](tla-brief.md) says when symmetry is sound.
|
|
6
7
|
- **Baseline helper ([`scripts/baseline.py`](../scripts/baseline.py))** on a TLA+ model:
|
|
7
8
|
- In the output of `compare`:
|
|
9
|
+
- A `symmetry` line added to a section, removed from it or naming another operator prints `CHANGED`, with an `added symmetry` or `removed symmetry` line for each run and `reach` check. So does an edit to the operator's definition.
|
|
8
10
|
- 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
11
|
- Cannot see:
|
|
10
12
|
- 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.
|
|
@@ -10,8 +10,9 @@ change, and so is an added item whose kind narrows what is checked.
|
|
|
10
10
|
.statements Lean. The toolchain, and each declaration's kind, type hash and value hash.
|
|
11
11
|
Added declarations are allowed.
|
|
12
12
|
.matrix TLA+. Each run's effective checks and each reach check's selected inputs,
|
|
13
|
+
the symmetry of each run and reach check, where an added one is a change,
|
|
13
14
|
and the normalized definitions of Spec,
|
|
14
|
-
of each operator a check or
|
|
15
|
+
of each operator a check, reach or symmetry line names, and of the operators those
|
|
15
16
|
reference through local EXTENDS. Local INSTANCE substitutions retain their whole module tree.
|
|
16
17
|
.rs Kani. Each qualified harness name with its #[kani::should_panic] and
|
|
17
18
|
#[kani::unwind(...)] attributes and the #[cfg(...)] attributes other
|
|
@@ -25,8 +26,10 @@ change, and so is an added item whose kind narrows what is checked.
|
|
|
25
26
|
method in a module that holds a harness, or under one, without its comments, the kani::cover! calls whose
|
|
26
27
|
conditions cannot run code, and the whitespace that a reformat can change. A helper's record includes
|
|
27
28
|
its attributes, qualifiers, parameters, return type and where clause as well as its body. An added
|
|
28
|
-
function or method there is a change, since it can shadow one that a glob import brings in.
|
|
29
|
-
|
|
29
|
+
function or method there is a change, since it can shadow one that a glob import brings in. So is a
|
|
30
|
+
change to the rest of such a module, such as a use, a const or a macro call, recorded without its
|
|
31
|
+
functions or the contents of its modules as items in <module>, or items in crate for the file's root.
|
|
32
|
+
An added harness is also reported if its name occurs in recorded code.
|
|
30
33
|
In a Cargo package, also the recorded harnesses that Kani compiles from the file; Kani must give
|
|
31
34
|
each harness it compiles there a module path that a route the record reads gives, and a harness
|
|
32
35
|
that no longer compiles is a change.
|
|
@@ -265,15 +268,18 @@ def tla_surface(path):
|
|
|
265
268
|
specs.setdefault(spec, set())
|
|
266
269
|
for task in tasks:
|
|
267
270
|
if task.reach:
|
|
268
|
-
surface.add(f"reach {task.spec} {task.reach.operator} | {collapse(task.reach.match)}",
|
|
269
|
-
|
|
271
|
+
item = surface.add(f"reach {task.spec} {task.reach.operator} | {collapse(task.reach.match)}",
|
|
272
|
+
{"run": collapse(task.run.label), "constants": task.run.constants})
|
|
270
273
|
specs[task.spec].add(task.reach.operator)
|
|
271
274
|
else:
|
|
272
|
-
|
|
275
|
+
item = surface.add(f"run {task.spec} {collapse(task.run.label)}", task.run.constants)
|
|
273
276
|
for check in task.checks:
|
|
274
277
|
for name in check.names:
|
|
275
|
-
surface.add(f"check {task.spec} {check.kind} {name} | [{
|
|
278
|
+
surface.add(f"check {task.spec} {check.kind} {name} | [{item}]")
|
|
276
279
|
specs[task.spec].update(check.names)
|
|
280
|
+
if task.symmetry:
|
|
281
|
+
surface.add(f"symmetry {task.spec} {task.symmetry} | [{item}]")
|
|
282
|
+
specs[task.spec].add(task.symmetry)
|
|
277
283
|
for spec, operators in specs.items():
|
|
278
284
|
source = path.parent / spec
|
|
279
285
|
if not source.is_file():
|
|
@@ -315,7 +321,8 @@ class TlaKind:
|
|
|
315
321
|
lines.append(" previous baseline did not track imported modules; review and record this matrix again")
|
|
316
322
|
if "TLA+ layout version" not in old:
|
|
317
323
|
lines.append(" previous baseline did not preserve TLA+ layout; review and record this matrix again")
|
|
318
|
-
|
|
324
|
+
# Symmetry merges states, so an added symmetry line narrows what a run checks.
|
|
325
|
+
return lines + differences(old, new, ("symmetry",)), []
|
|
319
326
|
|
|
320
327
|
def valid(self, entry):
|
|
321
328
|
return True
|
|
@@ -329,6 +336,11 @@ def may_omit_generator_types(entry):
|
|
|
329
336
|
return not entry.get("generator_types") and any(key.startswith("assume ") for key in entry["surface"])
|
|
330
337
|
|
|
331
338
|
|
|
339
|
+
def predates_items(surface):
|
|
340
|
+
# Record gives each harness's module an items in <module>, so only an older record holds a harness without one.
|
|
341
|
+
return any(name.startswith("harness ") for name in surface) and not any(name.startswith("items in ") for name in surface)
|
|
342
|
+
|
|
343
|
+
|
|
332
344
|
def compact_kani_record(surface, current):
|
|
333
345
|
"""Earlier records kept spaces between punctuation even where Rust reads two separate operators."""
|
|
334
346
|
compact = {}
|
|
@@ -349,6 +361,8 @@ def kani_references(surface):
|
|
|
349
361
|
for item, value in surface.items():
|
|
350
362
|
if item.startswith("body "):
|
|
351
363
|
code = re.sub(r"^fn\s+(?:r#)?\w+", "", value)
|
|
364
|
+
elif item.startswith("items in "):
|
|
365
|
+
code = value
|
|
352
366
|
elif item.startswith(("assume ", "stub ", "cover ")):
|
|
353
367
|
code = item.partition(" ")[2].rsplit(" in ", 1)[0]
|
|
354
368
|
else:
|
|
@@ -416,6 +430,9 @@ class KaniKind:
|
|
|
416
430
|
lines.insert(0, " previous baseline did not record the functions beside its harnesses; review each of them against the original revision and record this file again")
|
|
417
431
|
if not entry.get("method_bodies") and any(name.startswith("body ") and "<" in name for name in surface):
|
|
418
432
|
lines.insert(0, " previous baseline did not record the methods beside its harnesses; review each of them against the original revision and record this file again")
|
|
433
|
+
if predates_items(entry["surface"]):
|
|
434
|
+
lines[:0] = [f" previous baseline did not record {name}; review its uses, consts and macro calls against the original revision and record this file again"
|
|
435
|
+
for name in surface if name.startswith("items in ")]
|
|
419
436
|
unchecked = (" not checked against Kani at record, so compare cannot tell a harness that "
|
|
420
437
|
"stopped compiling from one that never compiled")
|
|
421
438
|
try:
|
|
@@ -445,6 +462,9 @@ class KaniKind:
|
|
|
445
462
|
surface = renamed(surface, *module)
|
|
446
463
|
compiled = compiled and list(renamed(dict.fromkeys(compiled), *module))
|
|
447
464
|
surface = joined(surface, new, existing)
|
|
465
|
+
# The other part's items would hide that one part never recorded its own, so the merge keeps none.
|
|
466
|
+
if any(predates_items(part["surface"]) for part in (entry, existing) if part is not None):
|
|
467
|
+
surface = {name: value for name, value in surface.items() if not name.startswith("items in ")}
|
|
448
468
|
partial = compiled is None or entry.get("partial", False)
|
|
449
469
|
if existing is not None:
|
|
450
470
|
# The merged list keeps the harnesses of each entry checked against Kani at record, and is partial when
|
|
@@ -480,12 +500,16 @@ def model_entry(kind, surface):
|
|
|
480
500
|
|
|
481
501
|
|
|
482
502
|
def joined(surface, new, existing):
|
|
483
|
-
"""Add the items that the entry existing records for the file new, which must not repeat an item of surface
|
|
503
|
+
"""Add the items that the entry existing records for the file new, which must not repeat an item of surface, apart
|
|
504
|
+
from the other items of a Kani module, whose different texts are joined with existing's first."""
|
|
484
505
|
if existing is None:
|
|
485
506
|
return surface
|
|
486
|
-
|
|
507
|
+
recorded = existing["surface"]
|
|
508
|
+
shared = surface.keys() & recorded.keys()
|
|
509
|
+
if overlap := {name for name in shared if not name.startswith("items in ")}:
|
|
487
510
|
raise ValueError(f"{new} already records {', '.join(sorted(overlap))}")
|
|
488
|
-
|
|
511
|
+
texts = {name: surface[name] if surface[name] == recorded[name] else normalized(f"{recorded[name]} {surface[name]}") for name in shared}
|
|
512
|
+
return {**recorded, **surface, **texts}
|
|
489
513
|
|
|
490
514
|
|
|
491
515
|
def read_record(path, kinds):
|
|
@@ -546,9 +570,9 @@ def renamed(surface, old_module, new_module):
|
|
|
546
570
|
if (item := KANI_KEY.fullmatch(name)) is None:
|
|
547
571
|
raise ValueError(f"cannot rename the recorded item '{name}', which is not a Kani harness, assume, cover or stub")
|
|
548
572
|
head, owner, duplicate = item.groups()
|
|
549
|
-
parts = owner.split("::")
|
|
573
|
+
parts = [] if owner == "crate" else owner.split("::")
|
|
550
574
|
if parts[:len(old)] == old:
|
|
551
|
-
owner = "::".join(new + parts[len(old):])
|
|
575
|
+
owner = "::".join(new + parts[len(old):]) or "crate"
|
|
552
576
|
result[f"{head}{owner}{duplicate or ''}"] = value
|
|
553
577
|
if len(result) != len(surface):
|
|
554
578
|
raise ValueError(f"renaming {old_module} to {new_module} merges recorded items")
|
|
@@ -16,8 +16,9 @@ import storage
|
|
|
16
16
|
from rust_source import RustSource, after_closing, normalized, rust_masks
|
|
17
17
|
from surface import Surface, collapse
|
|
18
18
|
|
|
19
|
-
# A method's owner holds spaces, such as `proofs::<impl kani::Arbitrary for State>::any`.
|
|
20
|
-
|
|
19
|
+
# A method's owner holds spaces, such as `proofs::<impl kani::Arbitrary for State>::any`. The owner of a module's other
|
|
20
|
+
# items is the module, or `crate` for the file's root.
|
|
21
|
+
KANI_KEY = re.compile(r"(harness |body |items in |(?:assume|cover|stub) .* in )(.+?)( #\d+)?", re.DOTALL)
|
|
21
22
|
|
|
22
23
|
|
|
23
24
|
class RustFunction(NamedTuple):
|
|
@@ -595,6 +596,26 @@ def kani_surface(path, reader):
|
|
|
595
596
|
recorded_end = function.end
|
|
596
597
|
if function not in harnesses:
|
|
597
598
|
spans.append((function.body, f"body {function.name}", body(function, function.start)))
|
|
599
|
+
# Any other item in those modules, such as a `use`, a `const`, a macro call or a module, can shadow a name that a
|
|
600
|
+
# glob import brings in, so each module records its text without its functions and its modules' contents.
|
|
601
|
+
for module in [None, *modules]:
|
|
602
|
+
if module is None:
|
|
603
|
+
if None not in scopes:
|
|
604
|
+
continue
|
|
605
|
+
position, name, start, end = 0, "crate", 0, len(text)
|
|
606
|
+
elif any(scope is None or scope.start <= module.start < scope.end for scope in scopes):
|
|
607
|
+
position, name, start, end = module.body, module.name, module.body + 1, module.end - 1
|
|
608
|
+
else:
|
|
609
|
+
continue
|
|
610
|
+
cuts = [(item.start, item.end) for item in functions] + [(item.body + 1, item.end - 1) for item in modules if item != module]
|
|
611
|
+
kept = []
|
|
612
|
+
# An enclosing span sorts before the spans it holds, which then fall before start.
|
|
613
|
+
for cut, stop in sorted(cuts, key=lambda span: (span[0], -span[1])):
|
|
614
|
+
if start <= cut and stop <= end:
|
|
615
|
+
kept.append(text[start:cut])
|
|
616
|
+
start = stop
|
|
617
|
+
kept.append(text[start:end])
|
|
618
|
+
spans.append((position, f"items in {name}", normalized(" ".join(kept))))
|
|
598
619
|
for token in KANI_TOKEN.finditer(mask):
|
|
599
620
|
if not any(start <= token.start() < end for start, end in read):
|
|
600
621
|
line = mask.count("\n", 0, token.start()) + 1
|
|
@@ -26,6 +26,7 @@ if __name__ == "__main__":
|
|
|
26
26
|
if signal.getsignal(signal.SIGINT) is signal.default_int_handler:
|
|
27
27
|
signal.signal(signal.SIGINT, signal.SIG_DFL)
|
|
28
28
|
|
|
29
|
+
import functools
|
|
29
30
|
import hashlib
|
|
30
31
|
import json
|
|
31
32
|
import os
|
|
@@ -34,6 +35,8 @@ import shutil
|
|
|
34
35
|
import subprocess
|
|
35
36
|
import sys
|
|
36
37
|
import tempfile
|
|
38
|
+
import time
|
|
39
|
+
from contextlib import suppress
|
|
37
40
|
from pathlib import Path
|
|
38
41
|
|
|
39
42
|
sys.dont_write_bytecode = True
|
|
@@ -49,12 +52,26 @@ SORRY = re.compile(r"(warning|error): .*: declaration uses .sorry.")
|
|
|
49
52
|
AUDITED = re.compile(r"AUDITED [0-9]+ declarations")
|
|
50
53
|
BLANK = re.compile(r"[ \t\n\r\f\v]*")
|
|
51
54
|
OLD_LAKE = re.compile(r"error: (unknown command 'query'|invalid script spec)")
|
|
55
|
+
ANALYSIS = HERE / "lean-analysis.lean"
|
|
56
|
+
# The pin's own compiler builds lean-analysis.lean into a program, as Lake builds an executable that supports the
|
|
57
|
+
# interpreter: -rdynamic lets the interpreter find the native code of the modules that the analysis imports.
|
|
58
|
+
NATIVE_BUILD = (
|
|
59
|
+
("{lean}", "--root={work}", "-c", "{work}/LeanAnalysis.c", "{work}/LeanAnalysis.lean"),
|
|
60
|
+
("{leanc}", "-c", "-o", "{work}/LeanAnalysis.o", "{work}/LeanAnalysis.c", "-O3", "-DNDEBUG"),
|
|
61
|
+
("{leanc}", "-o", "{work}/lean-analysis", "{work}/LeanAnalysis.o", "-rdynamic"),
|
|
62
|
+
)
|
|
63
|
+
# A build that no check has used for this long, or a build directory left by a killed build, is deleted.
|
|
64
|
+
STALE_SECONDS = 7 * 24 * 3600
|
|
52
65
|
|
|
53
66
|
|
|
54
67
|
class CheckError(Exception):
|
|
55
68
|
"""The project cannot be checked as given; the message is the FAIL line to print."""
|
|
56
69
|
|
|
57
70
|
|
|
71
|
+
class BuildError(Exception):
|
|
72
|
+
"""The native build of lean-analysis.lean failed; the message says which step and why."""
|
|
73
|
+
|
|
74
|
+
|
|
58
75
|
def lines(text):
|
|
59
76
|
"""Split output into the lines a shell reads, without the empty piece after a final newline."""
|
|
60
77
|
parts = text.split("\n")
|
|
@@ -149,6 +166,111 @@ def step(command, *, merge=True, env=None, label=None):
|
|
|
149
166
|
return 127, "", f"cannot run {command[0]}: {error}\n"
|
|
150
167
|
|
|
151
168
|
|
|
169
|
+
@functools.cache
|
|
170
|
+
def toolchain_prefix(toolchain):
|
|
171
|
+
"""Return the status, output and errors of the pin's lean --print-prefix, which runs once per process."""
|
|
172
|
+
return step(["elan", "run", toolchain, "lean", "--print-prefix"], merge=False)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@functools.cache
|
|
176
|
+
def analysis(toolchain):
|
|
177
|
+
"""Return the command that runs lean-analysis.lean in lake env: its native build, or lean --run.
|
|
178
|
+
|
|
179
|
+
lean --run elaborates the analysis and imports Lean for it on every call, and the analysis then imports Lean
|
|
180
|
+
again for the model. The native build does neither. A pin without lean and leanc in its prefix runs the source,
|
|
181
|
+
and so does a failed build, which says why on stderr.
|
|
182
|
+
"""
|
|
183
|
+
source = ["lean", "--run", str(ANALYSIS)]
|
|
184
|
+
status, prefix, _ = toolchain_prefix(toolchain)
|
|
185
|
+
prefix = Path(prefix.rstrip("\n"))
|
|
186
|
+
tools = {name: prefix / "bin" / name for name in ("lean", "leanc")}
|
|
187
|
+
if status or not prefix.is_absolute() or not all(os.access(tool, os.X_OK) for tool in tools.values()):
|
|
188
|
+
return source
|
|
189
|
+
try:
|
|
190
|
+
return [str(native_analysis(tools))]
|
|
191
|
+
except (BuildError, OSError) as error:
|
|
192
|
+
processes.report_progress(f"[lean] running lean-analysis.lean from source: {error}")
|
|
193
|
+
return source
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def analysis_cache():
|
|
197
|
+
"""Return LEAN_ANALYSIS_CACHE, or the directory for native analysis builds under ~/.cache."""
|
|
198
|
+
configured = os.environ.get("LEAN_ANALYSIS_CACHE")
|
|
199
|
+
if configured:
|
|
200
|
+
return Path(configured).absolute()
|
|
201
|
+
# expanduser returns ~ unchanged when it cannot find the home directory.
|
|
202
|
+
home = os.path.expanduser("~")
|
|
203
|
+
if not os.path.isabs(home):
|
|
204
|
+
raise OSError("set LEAN_ANALYSIS_CACHE or HOME to cache the native analysis build")
|
|
205
|
+
return Path(home, ".cache/agent-formal-verify/lean-analysis")
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def toolchain_files(prefix):
|
|
209
|
+
"""Return the path, size and mtime of the toolchain's lean, of each library in lib/lean and of each .olean in it.
|
|
210
|
+
|
|
211
|
+
The native build links Lean's libraries into the program, and the program reads the toolchain's .olean files. On
|
|
212
|
+
macOS, bin/lean is a launcher that a rebuild of Lean can leave as it was.
|
|
213
|
+
"""
|
|
214
|
+
library = os.path.join(prefix, "lib", "lean")
|
|
215
|
+
files = [os.path.join(prefix, "bin", "lean")]
|
|
216
|
+
# os.walk takes less than half the time of Path.rglob over the 15,282 files in Lean 4.35.0's lib/lean.
|
|
217
|
+
for directory, _, names in os.walk(library):
|
|
218
|
+
files.extend(os.path.join(directory, name) for name in names
|
|
219
|
+
if name.endswith(".olean") or directory == library and name.startswith("lib"))
|
|
220
|
+
return sorted((path, (status := os.stat(path)).st_size, status.st_mtime_ns) for path in files)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def native_analysis(tools):
|
|
224
|
+
"""Return the native build of lean-analysis.lean for the toolchain of these tools, building it on first use.
|
|
225
|
+
|
|
226
|
+
A build is named for the analysis source, the build steps and the toolchain's files, so a toolchain changed or
|
|
227
|
+
rebuilt at the same path gets its own build. Each build directory lands whole by a rename, so parallel checks may
|
|
228
|
+
build at once.
|
|
229
|
+
"""
|
|
230
|
+
text = ANALYSIS.read_bytes()
|
|
231
|
+
identity = repr((NATIVE_BUILD, toolchain_files(tools["lean"].parents[1]))).encode("utf-8")
|
|
232
|
+
cache = analysis_cache()
|
|
233
|
+
build = cache / f"lean-analysis-{hashlib.sha256(identity + text).hexdigest()[:16]}"
|
|
234
|
+
program = build / "lean-analysis"
|
|
235
|
+
if not program.is_file():
|
|
236
|
+
cache.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
237
|
+
work = Path(tempfile.mkdtemp(prefix="lean-analysis-build.", dir=cache))
|
|
238
|
+
try:
|
|
239
|
+
(work / "LeanAnalysis.lean").write_bytes(text)
|
|
240
|
+
names = tools | {"work": work}
|
|
241
|
+
for template in NATIVE_BUILD:
|
|
242
|
+
command = [part.format(**names) for part in template]
|
|
243
|
+
done = processes.run_captured(command, label="[lean] analysis build", encoding="utf-8", errors="replace")
|
|
244
|
+
if done.returncode:
|
|
245
|
+
log = lines(done.stdout + done.stderr)[-20:]
|
|
246
|
+
raise BuildError("\n".join([f"native build step {' '.join(command)} exited {done.returncode}", *log]))
|
|
247
|
+
try:
|
|
248
|
+
os.rename(work, build)
|
|
249
|
+
except OSError:
|
|
250
|
+
# A parallel check renamed its build first.
|
|
251
|
+
if not program.is_file():
|
|
252
|
+
raise
|
|
253
|
+
finally:
|
|
254
|
+
shutil.rmtree(work, ignore_errors=True)
|
|
255
|
+
cutoff = time.time() - STALE_SECONDS
|
|
256
|
+
for entry in cache.glob("lean-analysis-*"):
|
|
257
|
+
with suppress(OSError):
|
|
258
|
+
if entry == build or entry.lstat().st_mtime >= cutoff:
|
|
259
|
+
continue
|
|
260
|
+
if entry.is_dir() and not entry.is_symlink():
|
|
261
|
+
shutil.rmtree(entry)
|
|
262
|
+
else:
|
|
263
|
+
entry.unlink()
|
|
264
|
+
# A directory on a file system mounted noexec holds programs that cannot run.
|
|
265
|
+
if not os.access(program, os.X_OK):
|
|
266
|
+
raise BuildError(f"cannot run {program}; set LEAN_ANALYSIS_CACHE to a directory where programs can run")
|
|
267
|
+
# A build in use is never stale. Its directory carries the mark: on macOS, touching the program itself made its
|
|
268
|
+
# next run about 0.8 s slower.
|
|
269
|
+
with suppress(OSError):
|
|
270
|
+
os.utime(build)
|
|
271
|
+
return program
|
|
272
|
+
|
|
273
|
+
|
|
152
274
|
def project_files(project):
|
|
153
275
|
"""Find model sources and orphan records in the same walk, outside the root Lake build directory."""
|
|
154
276
|
sources, records = set(), []
|
|
@@ -347,7 +469,7 @@ def checked(project, toolchain, files, freeze, out, work):
|
|
|
347
469
|
return 1
|
|
348
470
|
module_list = work / "modules"
|
|
349
471
|
module_list.write_text("".join(name + "\n" for name in modules), encoding="utf-8")
|
|
350
|
-
audit_status, output, _ = step([*lake, "env",
|
|
472
|
+
audit_status, output, _ = step([*lake, "env", *analysis(toolchain),
|
|
351
473
|
"audit", *(["--freeze"] if freeze else []), str(module_list)], label="audit")
|
|
352
474
|
audit = lines(output)
|
|
353
475
|
if not any(AUDITED.fullmatch(line) for line in audit):
|
|
@@ -409,7 +531,7 @@ def checked(project, toolchain, files, freeze, out, work):
|
|
|
409
531
|
# replays every declaration of the built modules through the kernel and rejects it. Use its exact-module
|
|
410
532
|
# replayer rather than its CLI's prefix search, which also finds deleted sources' cached objects. A named
|
|
411
533
|
# module rests on the project modules it imports, so replay those too.
|
|
412
|
-
status, prefix, errors =
|
|
534
|
+
status, prefix, errors = toolchain_prefix(toolchain)
|
|
413
535
|
prefix = prefix.rstrip("\n")
|
|
414
536
|
compiler = os.path.join(prefix, "bin", "lean")
|
|
415
537
|
if status or not os.path.isabs(prefix) or not os.path.isfile(compiler) or not os.access(compiler, os.X_OK):
|
|
@@ -5,15 +5,12 @@ import json
|
|
|
5
5
|
import sys
|
|
6
6
|
from collections import Counter
|
|
7
7
|
from dataclasses import dataclass
|
|
8
|
-
from pathlib import Path
|
|
9
8
|
|
|
10
9
|
sys.dont_write_bytecode = True
|
|
11
10
|
import lean
|
|
12
11
|
import processes
|
|
13
12
|
from lean_records import read_record
|
|
14
13
|
|
|
15
|
-
HERE = Path(__file__).resolve().parent
|
|
16
|
-
|
|
17
14
|
|
|
18
15
|
class AnalysisError(Exception):
|
|
19
16
|
"""The original model, its frozen declarations or the pinned frontend could not be read."""
|
|
@@ -44,8 +41,8 @@ def _analyze(model, project, toolchain, label):
|
|
|
44
41
|
|
|
45
42
|
While Lean runs, report the elapsed time on stderr as '[lean] <label>: <N>s elapsed'.
|
|
46
43
|
"""
|
|
47
|
-
done = processes.run_captured(["elan", "run", toolchain, "lake", "--dir", str(project), "env",
|
|
48
|
-
|
|
44
|
+
done = processes.run_captured(["elan", "run", toolchain, "lake", "--dir", str(project), "env",
|
|
45
|
+
*lean.analysis(toolchain), "analyze", str(model)],
|
|
49
46
|
label=f"[lean] {label}", encoding="utf-8", errors="replace")
|
|
50
47
|
output = done.stdout + done.stderr
|
|
51
48
|
records = [line.removeprefix("AFV_LEAN ") for line in done.stdout.splitlines() if line.startswith("AFV_LEAN ")]
|
|
@@ -14,7 +14,10 @@ per mutation:
|
|
|
14
14
|
targets, or a Lean proof no mutation breaks
|
|
15
15
|
|
|
16
16
|
A TLA+ mutation is checked against the property or reach operator it names,
|
|
17
|
-
using the matrix runs. A
|
|
17
|
+
using the matrix runs. A run under a symmetry line adds "under symmetry
|
|
18
|
+
<Operator>" after the run's name in a DETECTED line, and a MISSED line names
|
|
19
|
+
each such run that passes, as "MISSED <label>: run '<run>' passes under symmetry
|
|
20
|
+
<Operator>". A Lean mutation is elaborated in the project, the mutated
|
|
18
21
|
module alone, and reported with the theorems, lemmas, examples and #guard
|
|
19
22
|
lines that fail. Every public theorem recorded in the model's .statements file
|
|
20
23
|
must have its proof fail on some mutation; a failing #guard does not cover it.
|
|
@@ -45,7 +48,9 @@ prints a FAIL line for each malformed mutation, and names the lines where
|
|
|
45
48
|
- text that occurs more than once starts.
|
|
46
49
|
|
|
47
50
|
Usage: mutate.py <Name.mutations>
|
|
48
|
-
The environment settings of tlc-matrix.sh apply to TLA+ mutations.
|
|
51
|
+
The environment settings of tlc-matrix.sh apply to TLA+ mutations. A matrix
|
|
52
|
+
line that tlc-matrix.sh rejects with status 2 stops this runner with status 2
|
|
53
|
+
before TLC runs.
|
|
49
54
|
"""
|
|
50
55
|
import signal
|
|
51
56
|
|
|
@@ -186,13 +191,10 @@ def make_mutation(label, directives, model, text, language):
|
|
|
186
191
|
|
|
187
192
|
def check_tla(plan, checker, mutation, work):
|
|
188
193
|
try:
|
|
189
|
-
|
|
194
|
+
detected, detail = plan.check(checker, mutation.detects, mutation.only, mutation.apply(), work)
|
|
190
195
|
except ValueError as error:
|
|
191
196
|
return Result(Verdict.ERROR, str(error))
|
|
192
|
-
|
|
193
|
-
if detection is None:
|
|
194
|
-
return Result(Verdict.MISSED, covers=covers)
|
|
195
|
-
return Result(Verdict.DETECTED, detection, covers)
|
|
197
|
+
return Result(Verdict.DETECTED if detected else Verdict.MISSED, detail, frozenset({mutation.detects}))
|
|
196
198
|
|
|
197
199
|
|
|
198
200
|
def check_lean(broken_checks, mutation, work):
|
|
@@ -240,6 +242,9 @@ def tla_runner(spec, mutations, run):
|
|
|
240
242
|
stop(f"{matrix} is missing; mutations use its checks and runs")
|
|
241
243
|
try:
|
|
242
244
|
plan = tlc.MatrixPlan(matrix).mutations_for(spec)
|
|
245
|
+
except tlc.MatrixError as error:
|
|
246
|
+
print("\n".join(f"FAIL {problem}" for problem in error.problems))
|
|
247
|
+
sys.exit(2)
|
|
243
248
|
except ValueError as error:
|
|
244
249
|
stop(str(error))
|
|
245
250
|
for mutation in mutations:
|
|
@@ -5,16 +5,29 @@
|
|
|
5
5
|
|
|
6
6
|
Prints one PASS or FAIL line per run with its distinct state count, then a
|
|
7
7
|
SUMMARY line with the totals. A failing run prints TLC's error and its error
|
|
8
|
-
trace reduced to the variables each step changed (tlc_trace.py).
|
|
8
|
+
trace reduced to the variables each step changed (tlc_trace.py). The line of a
|
|
9
|
+
run or reach check under a symmetry line says "under symmetry <Operator>": after
|
|
10
|
+
the state count when a run passes, and before the colon otherwise.
|
|
9
11
|
|
|
10
12
|
Matrix file, one directive per line (# starts a comment):
|
|
11
13
|
spec <path.tla> the spec for the runs below, relative to the file;
|
|
12
14
|
TLC checks the formula it names Spec
|
|
13
15
|
check <cfg line> an INVARIANTS or PROPERTIES line, kept until the next spec
|
|
14
16
|
reach <Operator> | <label-substring> a witness in the first matching run
|
|
17
|
+
symmetry <Operator> at most one per spec section: adds SYMMETRY <Operator> to the
|
|
18
|
+
cfg of each run and reach check of the section, wherever the
|
|
19
|
+
line stands in it; refused, with no symmetry applied, in a
|
|
20
|
+
section that checks a PROPERTY or PROPERTIES
|
|
15
21
|
run <label> | <Name=Value ...> one TLC run with those CONSTANTS
|
|
16
22
|
|
|
17
23
|
A malformed directive prints a FAIL line and the runner goes on to the next.
|
|
24
|
+
A line that could change the cfg beyond itself stops the runner before any run
|
|
25
|
+
with a FAIL <matrix>:<line>: line for each and status 2: a check name, reach or
|
|
26
|
+
symmetry operator or constant name that is not a TLA+ identifier or is a TLA+
|
|
27
|
+
reserved word; a check name, symmetry operator or constant name that is a cfg
|
|
28
|
+
keyword; and a constant value that holds a comment opener, a string that it does
|
|
29
|
+
not close, or a cfg keyword outside a string that is not the whole value or a
|
|
30
|
+
whole set element.
|
|
18
31
|
|
|
19
32
|
Usage: tlc-matrix.sh <matrix-file> [label-substring]
|
|
20
33
|
TLC_ENGINE=<name> TLA+ engine: tlc (default) or everystate
|
|
@@ -27,9 +40,10 @@ Usage: tlc-matrix.sh <matrix-file> [label-substring]
|
|
|
27
40
|
TLC_HTML_REPORT=<path> write a self-contained HTML report to this path
|
|
28
41
|
|
|
29
42
|
Usage: tlc.py ready
|
|
30
|
-
Checks TLC_ENGINE, TLC_TIMEOUT, and the selected engine (Java and the pinned or supplied JAR for tlc
|
|
31
|
-
|
|
32
|
-
storage.py report does.
|
|
43
|
+
Checks TLC_ENGINE, TLC_TIMEOUT, and the selected engine (Java and the pinned or supplied JAR for tlc,
|
|
44
|
+
then a one-state model that TLC can check only where it may listen on a local port; everystate 0.4.6
|
|
45
|
+
or later for everystate), then reports the temporary directory's free space as storage.py report does.
|
|
46
|
+
setup.sh tla runs it.
|
|
33
47
|
"""
|
|
34
48
|
from __future__ import annotations
|
|
35
49
|
|
|
@@ -61,7 +75,27 @@ import storage
|
|
|
61
75
|
import tlc_trace
|
|
62
76
|
|
|
63
77
|
CHECK_KINDS = ("INVARIANT", "INVARIANTS", "PROPERTY", "PROPERTIES")
|
|
64
|
-
REACH = re.compile(r"([
|
|
78
|
+
REACH = re.compile(r"([^\s|]+)\s*\|\s*(.*\S)\s*")
|
|
79
|
+
# The words that start a cfg statement: TLC's (tla2tools 1.7.4, with ALIAS and POSTCONDITION from later TLC) and everystate's.
|
|
80
|
+
CFG_KEYWORDS = frozenset({
|
|
81
|
+
"ACTION_CONSTRAINT", "ACTION_CONSTRAINTS", "ALIAS", "CHECK_DEADLOCK", "CONSTANT", "CONSTANTS", "CONSTRAINT",
|
|
82
|
+
"CONSTRAINTS", "INIT", "INVARIANT", "INVARIANTS", "NEXT", "POSTCONDITION", "POSTCONDITIONS", "PROPERTIES",
|
|
83
|
+
"PROPERTY", "SPECIFICATION", "SYMMETRY", "TYPE", "TYPE_CONSTRAINT", "VIEW", "_PERIODIC", "_POSSIBLE", "_RL_REWARD",
|
|
84
|
+
})
|
|
85
|
+
# TLA+'s reserved words. IDENTIFIER rejects the prefixes WF_ and SF_.
|
|
86
|
+
RESERVED_WORDS = frozenset({
|
|
87
|
+
"ACTION", "ASSUME", "ASSUMPTION", "AXIOM", "BY", "CASE", "CHOOSE", "CONSTANT", "CONSTANTS", "COROLLARY", "DEF",
|
|
88
|
+
"DEFINE", "DEFS", "DOMAIN", "ELSE", "ENABLED", "EXCEPT", "EXTENDS", "HAVE", "HIDE", "IF", "IN", "INSTANCE", "LAMBDA",
|
|
89
|
+
"LEMMA", "LET", "LOCAL", "MODULE", "NEW", "OBVIOUS", "OMITTED", "ONLY", "OTHER", "PICK", "PROOF", "PROPOSITION",
|
|
90
|
+
"PROVE", "QED", "RECURSIVE", "STATE", "SUBSET", "SUFFICES", "TAKE", "TEMPORAL", "THEN", "THEOREM", "UNCHANGED",
|
|
91
|
+
"UNION", "USE", "VARIABLE", "VARIABLES", "WITH", "WITNESS",
|
|
92
|
+
})
|
|
93
|
+
IDENTIFIER = re.compile(r"(?!WF_|SF_)[A-Za-z0-9_]*[A-Za-z][A-Za-z0-9_]*")
|
|
94
|
+
# A constant's value split as both engines' cfg readers split it here: a closed string, a word, or one other character.
|
|
95
|
+
VALUE_TOKEN = re.compile(r'"(?:[^"\\]|\\.)*"|[A-Za-z0-9_]+|.', re.DOTALL)
|
|
96
|
+
COMMENT_OPENERS = ("(*", "\\*")
|
|
97
|
+
# Text whose every double quote opens a string that a later quote closes, where a backslash escapes the next character.
|
|
98
|
+
CLOSED_STRINGS = re.compile(r'(?:[^"]|"(?:[^"\\]|\\.)*")*')
|
|
65
99
|
|
|
66
100
|
|
|
67
101
|
def read_raw(path):
|
|
@@ -88,6 +122,11 @@ class Reach:
|
|
|
88
122
|
match: str
|
|
89
123
|
|
|
90
124
|
|
|
125
|
+
@dataclass(frozen=True)
|
|
126
|
+
class Symmetry:
|
|
127
|
+
operator: str
|
|
128
|
+
|
|
129
|
+
|
|
91
130
|
@dataclass(frozen=True)
|
|
92
131
|
class Run:
|
|
93
132
|
label: str
|
|
@@ -103,20 +142,83 @@ class Malformed:
|
|
|
103
142
|
message: str
|
|
104
143
|
|
|
105
144
|
|
|
106
|
-
|
|
145
|
+
@dataclass(frozen=True)
|
|
146
|
+
class Rejected:
|
|
147
|
+
"""A matrix line whose name or value could change the cfg beyond itself."""
|
|
148
|
+
line: int
|
|
149
|
+
message: str
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class MatrixError(ValueError):
|
|
153
|
+
"""A matrix holds lines that could change the cfg beyond themselves; each problem names its file and line."""
|
|
154
|
+
|
|
155
|
+
def __init__(self, problems):
|
|
156
|
+
super().__init__("\n".join(problems))
|
|
157
|
+
self.problems = tuple(problems)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def operator_problem(name):
|
|
161
|
+
"""Return why a name cannot name a TLA+ operator, or None."""
|
|
162
|
+
if not IDENTIFIER.fullmatch(name):
|
|
163
|
+
return "is not a TLA+ identifier"
|
|
164
|
+
if name in RESERVED_WORDS:
|
|
165
|
+
return "is a TLA+ reserved word"
|
|
166
|
+
return None
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def name_problem(name):
|
|
170
|
+
"""Return why a name cannot go into a cfg statement, or None for a TLA+ identifier that no engine reads as a keyword."""
|
|
171
|
+
return "is a cfg keyword" if name in CFG_KEYWORDS else operator_problem(name)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def value_problem(value):
|
|
175
|
+
"""Return why a constant's value could end early and start a cfg statement or hide the ones after it, or None.
|
|
176
|
+
|
|
177
|
+
TLC 1.7.4 and everystate 0.4.6 read a closed string as one token, and a cfg keyword that is the whole value or
|
|
178
|
+
a whole set element as a model value, so a keyword counts only in any other place.
|
|
179
|
+
"""
|
|
180
|
+
tokens = ["", *VALUE_TOKEN.findall(value), ""]
|
|
181
|
+
depth = 0
|
|
182
|
+
for before, token, after in zip(tokens, tokens[1:], tokens[2:]):
|
|
183
|
+
depth += (token == "{") - (token == "}")
|
|
184
|
+
whole = before == after == ""
|
|
185
|
+
element = depth > 0 and before in ("{", ",") and after in (",", "}")
|
|
186
|
+
if token in CFG_KEYWORDS and not (whole or element):
|
|
187
|
+
return f"holds the cfg keyword {token} outside a whole value or set element"
|
|
188
|
+
opener = next((opener for opener in COMMENT_OPENERS if opener in value), None)
|
|
189
|
+
if opener:
|
|
190
|
+
return f"holds the comment opener {opener}"
|
|
191
|
+
if not CLOSED_STRINGS.fullmatch(value):
|
|
192
|
+
return "opens a string that it does not close"
|
|
193
|
+
return None
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _binding_problem(label, name, value):
|
|
197
|
+
problem = name_problem(name)
|
|
198
|
+
if problem:
|
|
199
|
+
return f"constant name '{name}' in run '{label}' {problem}"
|
|
200
|
+
problem = value_problem(value)
|
|
201
|
+
if problem:
|
|
202
|
+
return f"constant '{name}={value}' in run '{label}' {problem}"
|
|
203
|
+
return None
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _parse_run(number, label, constants):
|
|
107
207
|
bindings = []
|
|
108
208
|
for token in constants.split():
|
|
109
209
|
name, _, value = token.partition("=")
|
|
110
210
|
if not name or not value:
|
|
111
|
-
|
|
211
|
+
yield Malformed(f"malformed constant {token!r} in run {label!r}: expected Name=Value")
|
|
212
|
+
return
|
|
112
213
|
bindings.append((name, value))
|
|
113
|
-
|
|
214
|
+
problems = [_binding_problem(label, name, value) for name, value in bindings]
|
|
215
|
+
yield from [Rejected(number, problem) for problem in problems if problem] or [Run(label, tuple(bindings))]
|
|
114
216
|
|
|
115
217
|
|
|
116
218
|
def _directives(lines):
|
|
117
|
-
"""Yield each directive of a matrix in file order, with a Malformed in place of a line it rejects."""
|
|
219
|
+
"""Yield each directive of a matrix in file order, with a Malformed or Rejected in place of a line it rejects."""
|
|
118
220
|
seen_spec = False
|
|
119
|
-
for raw in lines:
|
|
221
|
+
for number, raw in enumerate(lines, 1):
|
|
120
222
|
line = raw.split("#", 1)[0]
|
|
121
223
|
if not line.strip():
|
|
122
224
|
continue
|
|
@@ -132,7 +234,9 @@ def _directives(lines):
|
|
|
132
234
|
elif kind not in CHECK_KINDS or not names.strip():
|
|
133
235
|
yield Malformed(f"malformed check '{rest}'")
|
|
134
236
|
else:
|
|
135
|
-
|
|
237
|
+
problems = [(name, name_problem(name)) for name in names.split()]
|
|
238
|
+
yield from ([Rejected(number, f"check name '{name}' {problem}") for name, problem in problems if problem]
|
|
239
|
+
or [Check(rest, kind, tuple(names.split()))])
|
|
136
240
|
elif keyword == "reach":
|
|
137
241
|
match = REACH.fullmatch(rest)
|
|
138
242
|
if not seen_spec:
|
|
@@ -140,7 +244,17 @@ def _directives(lines):
|
|
|
140
244
|
elif not match:
|
|
141
245
|
yield Malformed(f"malformed reach '{rest}': expected reach <Operator> | <label-substring>")
|
|
142
246
|
else:
|
|
143
|
-
|
|
247
|
+
# The reach check names its operator in a wrapper module, not in the cfg.
|
|
248
|
+
problem = operator_problem(match[1])
|
|
249
|
+
yield Rejected(number, f"reach operator '{match[1]}' {problem}") if problem else Reach(match[1], match[2])
|
|
250
|
+
elif keyword == "symmetry":
|
|
251
|
+
if not seen_spec:
|
|
252
|
+
yield Malformed(f"symmetry '{rest}' before any spec line")
|
|
253
|
+
elif not rest:
|
|
254
|
+
yield Malformed("malformed symmetry '': expected symmetry <Operator>")
|
|
255
|
+
else:
|
|
256
|
+
problem = name_problem(rest)
|
|
257
|
+
yield Rejected(number, f"symmetry operator '{rest}' {problem}") if problem else Symmetry(rest)
|
|
144
258
|
elif keyword == "run":
|
|
145
259
|
label, bar, constants = rest.partition("|")
|
|
146
260
|
if not bar:
|
|
@@ -148,7 +262,7 @@ def _directives(lines):
|
|
|
148
262
|
elif not seen_spec:
|
|
149
263
|
yield Malformed(f"run '{label.rstrip()}' before any spec line")
|
|
150
264
|
else:
|
|
151
|
-
yield _parse_run(label.rstrip(), constants)
|
|
265
|
+
yield from _parse_run(number, label.rstrip(), constants)
|
|
152
266
|
else:
|
|
153
267
|
yield Malformed(f"unknown directive: {line}")
|
|
154
268
|
|
|
@@ -200,6 +314,9 @@ class _Engine:
|
|
|
200
314
|
self.workers = os.environ.get("TLC_WORKERS") or "auto"
|
|
201
315
|
self._warned_disk = False
|
|
202
316
|
|
|
317
|
+
def preflight(self):
|
|
318
|
+
"""Check, before setup reports the engine ready, what its version probe cannot show; nothing by default."""
|
|
319
|
+
|
|
203
320
|
def _run_watched(self, command, log, progress_label=""):
|
|
204
321
|
if not self._warned_disk:
|
|
205
322
|
self._warned_disk = True
|
|
@@ -296,6 +413,16 @@ class Tlc(_Engine):
|
|
|
296
413
|
if got != self.sha256:
|
|
297
414
|
raise runner.Unavailable(f"UNAVAILABLE {self.jar} has sha256 {got}, want {self.sha256}")
|
|
298
415
|
|
|
416
|
+
def preflight(self):
|
|
417
|
+
"""Check a one-state model, so that a sandbox that denies TLC its local port stops setup instead of the first model run."""
|
|
418
|
+
with tempfile.TemporaryDirectory(dir=storage.ensure_temp_root()) as work:
|
|
419
|
+
directory = Path(work)
|
|
420
|
+
(directory / "Preflight.tla").write_text("---- MODULE Preflight ----\nVARIABLE x\nInit == x = 0\nNext == UNCHANGED x\n====\n", encoding="utf-8")
|
|
421
|
+
# run raises Unavailable when TLC cannot listen; any other outcome is left for the model runs to report.
|
|
422
|
+
# Setup reports free space after this, so the run's own low-space warning would repeat it.
|
|
423
|
+
self._warned_disk = True
|
|
424
|
+
self.run(directory, "Preflight", "INIT Init\nNEXT Next\n", reach=False, workers="1")
|
|
425
|
+
|
|
299
426
|
def run(self, directory, module, config, reach, workers=None, progress_label=""):
|
|
300
427
|
"""Run TLC on module in directory with config; return (exit_status, log, timed_out)."""
|
|
301
428
|
log = directory / "tlc.log"
|
|
@@ -417,6 +544,7 @@ class Result:
|
|
|
417
544
|
"""One line of the runner's report and the output printed under it.
|
|
418
545
|
|
|
419
546
|
detail is the text printed after the label; states and violation hold what callers count and match on.
|
|
547
|
+
symmetry is the operator of the section's symmetry line that the run used, or "".
|
|
420
548
|
"""
|
|
421
549
|
outcome: Outcome
|
|
422
550
|
name: str = ""
|
|
@@ -430,6 +558,12 @@ class Result:
|
|
|
430
558
|
checks: tuple[str, ...] = ()
|
|
431
559
|
duration_s: float = 0.0
|
|
432
560
|
trace: tlc_trace.Trace | None = None
|
|
561
|
+
symmetry: str = ""
|
|
562
|
+
|
|
563
|
+
@property
|
|
564
|
+
def under_symmetry(self):
|
|
565
|
+
"""Return the words that name the run's symmetry in its lines, or "" for a run without one."""
|
|
566
|
+
return f" under symmetry {self.symmetry}" if self.symmetry else ""
|
|
433
567
|
|
|
434
568
|
|
|
435
569
|
@dataclass(frozen=True)
|
|
@@ -439,6 +573,7 @@ class Task:
|
|
|
439
573
|
checks: tuple = ()
|
|
440
574
|
reach: Reach | None = None
|
|
441
575
|
check_deadlock: bool = True
|
|
576
|
+
symmetry: str = ""
|
|
442
577
|
|
|
443
578
|
|
|
444
579
|
class _Section:
|
|
@@ -449,7 +584,7 @@ class _Section:
|
|
|
449
584
|
self.properties = set()
|
|
450
585
|
self.reaches = set()
|
|
451
586
|
self.tasks = []
|
|
452
|
-
checks, reaches, runs = [], [], []
|
|
587
|
+
checks, reaches, runs, symmetries = [], [], [], []
|
|
453
588
|
for directive in directives:
|
|
454
589
|
if isinstance(directive, Check):
|
|
455
590
|
checks.append(directive)
|
|
@@ -457,6 +592,8 @@ class _Section:
|
|
|
457
592
|
elif isinstance(directive, Reach):
|
|
458
593
|
reaches.append(directive)
|
|
459
594
|
self.reaches.add(f"reach:{directive.operator}")
|
|
595
|
+
elif isinstance(directive, Symmetry):
|
|
596
|
+
symmetries.append(directive.operator)
|
|
460
597
|
elif isinstance(directive, Run):
|
|
461
598
|
runs.append(directive)
|
|
462
599
|
self.tasks.append(Task(spec, directive, tuple(checks)))
|
|
@@ -468,21 +605,38 @@ class _Section:
|
|
|
468
605
|
self.tasks.append(Result(Outcome.NO_RUN, Path(spec).name.removesuffix(".tla"), operator=reach.operator, detail=reach.match))
|
|
469
606
|
else:
|
|
470
607
|
self.tasks.append(Task(spec, run, reach=reach))
|
|
608
|
+
if not symmetries:
|
|
609
|
+
return
|
|
610
|
+
liveness = [check.line for check in checks if check.kind.startswith("PROPERT")]
|
|
611
|
+
if len(symmetries) > 1:
|
|
612
|
+
refusal = f"symmetry lines {', '.join(symmetries)} in one {spec} section, which runs without symmetry; give it one symmetry line"
|
|
613
|
+
elif liveness:
|
|
614
|
+
refusal = (f"symmetry {symmetries[0]} in the {spec} section, which checks {'; '.join(liveness)}: TLC can miss "
|
|
615
|
+
"a liveness violation under symmetry, so the section runs without it; check the properties in a section without symmetry")
|
|
616
|
+
else:
|
|
617
|
+
self.tasks = [replace(task, symmetry=symmetries[0]) if isinstance(task, Task) else task for task in self.tasks]
|
|
618
|
+
return
|
|
619
|
+
self.tasks.insert(0, Result(Outcome.MALFORMED, detail=refusal))
|
|
471
620
|
|
|
472
621
|
|
|
473
622
|
class MatrixPlan:
|
|
474
623
|
"""Compile a matrix once for execution, specification recording or mutation selection."""
|
|
475
624
|
|
|
476
625
|
def __init__(self, path):
|
|
626
|
+
"""Read the matrix at path; raise MatrixError naming each line it rejects, after reading every line."""
|
|
477
627
|
self.path = Path(path)
|
|
478
628
|
self._sections = []
|
|
479
|
-
spec, body = None, []
|
|
629
|
+
spec, body, rejected = None, [], []
|
|
480
630
|
for directive in _directives(read_raw(self.path).split("\n")):
|
|
481
|
-
if isinstance(directive,
|
|
631
|
+
if isinstance(directive, Rejected):
|
|
632
|
+
rejected.append(f"{self.path}:{directive.line}: {directive.message}")
|
|
633
|
+
elif isinstance(directive, Spec):
|
|
482
634
|
self._sections.append(_Section(spec, body))
|
|
483
635
|
spec, body = directive.path, []
|
|
484
636
|
else:
|
|
485
637
|
body.append(directive)
|
|
638
|
+
if rejected:
|
|
639
|
+
raise MatrixError(rejected)
|
|
486
640
|
self._sections.append(_Section(spec, body))
|
|
487
641
|
|
|
488
642
|
def __iter__(self):
|
|
@@ -533,8 +687,8 @@ class MutationPlan:
|
|
|
533
687
|
checks = tuple(Check(f"{check.kind} {detector}", check.kind, (detector,))
|
|
534
688
|
for check in task.checks if detector in check.names)
|
|
535
689
|
if checks:
|
|
536
|
-
yield
|
|
537
|
-
|
|
690
|
+
yield replace(task, spec=self._spec.name, checks=checks,
|
|
691
|
+
check_deadlock=not any(check.kind.startswith("PROPERT") for check in checks))
|
|
538
692
|
|
|
539
693
|
def selected(self, detector, only):
|
|
540
694
|
"""Return the tasks that check a mutation naming detector and only; raise ValueError when none can."""
|
|
@@ -563,8 +717,9 @@ class MutationPlan:
|
|
|
563
717
|
passed.add(task)
|
|
564
718
|
|
|
565
719
|
def check(self, checker, detector, only, source, work):
|
|
566
|
-
"""Return
|
|
720
|
+
"""Return whether a run confirms a detection, with the text for the verdict's line, or raise on inconclusive evidence.
|
|
567
721
|
|
|
722
|
+
A detection names the first run that fails; a miss names each run that passed under symmetry, or nothing.
|
|
568
723
|
The caller has passed the same detector and only to check_originals.
|
|
569
724
|
"""
|
|
570
725
|
results = [(run_task(checker, self._spec.parent, task, work, source),
|
|
@@ -573,17 +728,17 @@ class MutationPlan:
|
|
|
573
728
|
detections, errors = [], []
|
|
574
729
|
for result, temporal in results:
|
|
575
730
|
if result.outcome is Outcome.UNREACHED:
|
|
576
|
-
detections.append((result
|
|
731
|
+
detections.append((result, "the model never reaches this state"))
|
|
577
732
|
elif result.outcome is Outcome.FAIL and result.violation and detects(result.violation, detector, temporal):
|
|
578
|
-
detections.append((result
|
|
733
|
+
detections.append((result, result.detail.removeprefix("Error: ").rstrip(".")))
|
|
579
734
|
elif result.outcome not in (Outcome.PASS, Outcome.WITNESS):
|
|
580
735
|
errors.extend(render(result))
|
|
581
736
|
if errors:
|
|
582
737
|
raise ValueError("\n".join(errors))
|
|
583
738
|
if detections:
|
|
584
|
-
|
|
585
|
-
return f"{detector} fails in run '{label}' ({reason})"
|
|
586
|
-
return
|
|
739
|
+
result, reason = detections[0]
|
|
740
|
+
return True, f"{detector} fails in run '{result.label}'{result.under_symmetry} ({reason})"
|
|
741
|
+
return False, "; ".join(f"run '{result.label}' passes{result.under_symmetry}" for result, _ in results if result.symmetry)
|
|
587
742
|
|
|
588
743
|
|
|
589
744
|
def detects(found, detector, temporal):
|
|
@@ -600,14 +755,14 @@ def detects(found, detector, temporal):
|
|
|
600
755
|
|
|
601
756
|
def render(result):
|
|
602
757
|
"""Return the lines the matrix runner prints for one result."""
|
|
603
|
-
name, label, operator = result.name, result.label, result.operator
|
|
758
|
+
name, label, operator, under = result.name, result.label, result.operator, result.under_symmetry
|
|
604
759
|
head = {
|
|
605
|
-
Outcome.PASS: f"PASS {name} {label} {result.detail}",
|
|
606
|
-
Outcome.FAIL: f"FAIL {name} {label}: {result.detail}",
|
|
760
|
+
Outcome.PASS: f"PASS {name} {label} {result.detail}{under}",
|
|
761
|
+
Outcome.FAIL: f"FAIL {name} {label}{under}: {result.detail}",
|
|
607
762
|
Outcome.MISSING: f"FAIL {name} {label}: spec {result.detail} not found",
|
|
608
|
-
Outcome.WITNESS: f"PASS {name} reach {operator} {label}: shortest trace {result.detail}",
|
|
609
|
-
Outcome.UNREACHED: f"FAIL {name} reach {operator} {label}: the model never reaches this state",
|
|
610
|
-
Outcome.INCOMPLETE: f"FAIL {name} reach {operator} {label}: {result.detail or 'TLC did not complete the reach check'}",
|
|
763
|
+
Outcome.WITNESS: f"PASS {name} reach {operator} {label}{under}: shortest trace {result.detail}",
|
|
764
|
+
Outcome.UNREACHED: f"FAIL {name} reach {operator} {label}{under}: the model never reaches this state",
|
|
765
|
+
Outcome.INCOMPLETE: f"FAIL {name} reach {operator} {label}{under}: {result.detail or 'TLC did not complete the reach check'}",
|
|
611
766
|
Outcome.NO_RUN: f"FAIL {name} reach {operator}: no run matching '{result.detail}'",
|
|
612
767
|
Outcome.MALFORMED: f"FAIL {result.detail}",
|
|
613
768
|
}[result.outcome]
|
|
@@ -642,6 +797,8 @@ def run_task(checker, matrix_dir, task, work, source=None, traces=False):
|
|
|
642
797
|
dest.write_bytes(module.read_bytes())
|
|
643
798
|
constants = "".join(f" {name} = {value}\n" for name, value in run.bindings)
|
|
644
799
|
config = f"CONSTANTS\n{constants}SPECIFICATION Spec\n"
|
|
800
|
+
if task.symmetry:
|
|
801
|
+
config += f"SYMMETRY {task.symmetry}\n"
|
|
645
802
|
if not task.check_deadlock:
|
|
646
803
|
config += "CHECK_DEADLOCK FALSE\n"
|
|
647
804
|
engine_name = getattr(checker, "name", "TLC")
|
|
@@ -654,7 +811,7 @@ def run_task(checker, matrix_dir, task, work, source=None, traces=False):
|
|
|
654
811
|
elapsed = time.monotonic() - start
|
|
655
812
|
shutil.rmtree(directory / "states", ignore_errors=True)
|
|
656
813
|
result = ordinary(name, run, status, log, checker.limit if timed_out else None, traces, engine_name=engine_name)
|
|
657
|
-
return replace(result, constants=run_constants, checks=run_checks, duration_s=elapsed)
|
|
814
|
+
return replace(result, constants=run_constants, checks=run_checks, duration_s=elapsed, symmetry=task.symmetry)
|
|
658
815
|
wrapper = f"Reach{uuid.uuid4().hex}"
|
|
659
816
|
invariant = f"{wrapper}Negated"
|
|
660
817
|
(directory / f"{wrapper}.tla").write_text(f"---- MODULE {wrapper} ----\nEXTENDS {name}\n{invariant} == ~{operator}\n====\n", encoding="utf-8")
|
|
@@ -667,7 +824,7 @@ def run_task(checker, matrix_dir, task, work, source=None, traces=False):
|
|
|
667
824
|
)
|
|
668
825
|
elapsed = time.monotonic() - start
|
|
669
826
|
result = witness(name, run, operator, invariant, status, log, checker.limit if timed_out else None, traces, engine_name=engine_name)
|
|
670
|
-
return replace(result, constants=run_constants, checks=run_checks, duration_s=elapsed)
|
|
827
|
+
return replace(result, constants=run_constants, checks=run_checks, duration_s=elapsed, symmetry=task.symmetry)
|
|
671
828
|
finally:
|
|
672
829
|
shutil.rmtree(directory, ignore_errors=True)
|
|
673
830
|
|
|
@@ -791,7 +948,9 @@ def validate_report_path(raw: str) -> Path | None:
|
|
|
791
948
|
|
|
792
949
|
def main():
|
|
793
950
|
if sys.argv[1:] == ["ready"]:
|
|
794
|
-
|
|
951
|
+
checker = engine()
|
|
952
|
+
checker.preflight()
|
|
953
|
+
print(checker.ready_line)
|
|
795
954
|
storage.report()
|
|
796
955
|
return 0
|
|
797
956
|
if not 2 <= len(sys.argv) <= 3:
|
|
@@ -801,13 +960,18 @@ def main():
|
|
|
801
960
|
if not Path(matrix).is_file():
|
|
802
961
|
print(f"FAIL {matrix} does not exist")
|
|
803
962
|
return 1
|
|
963
|
+
try:
|
|
964
|
+
plan = MatrixPlan(matrix)
|
|
965
|
+
except MatrixError as error:
|
|
966
|
+
print("\n".join(f"FAIL {problem}" for problem in error.problems))
|
|
967
|
+
return 2
|
|
804
968
|
checker = engine()
|
|
805
969
|
report_path = validate_report_path(os.environ.get("TLC_HTML_REPORT", ""))
|
|
806
970
|
with tempfile.TemporaryDirectory(dir=storage.ensure_temp_root()) as work:
|
|
807
971
|
print(f"ENGINE {checker.label}", flush=True)
|
|
808
972
|
matrix_runner = Runner(checker, Path(matrix).resolve().parent, only, lambda result: print("\n".join(render(result)), flush=True), Path(work),
|
|
809
973
|
keep_results=report_path is not None)
|
|
810
|
-
for task in
|
|
974
|
+
for task in plan:
|
|
811
975
|
matrix_runner.check(task)
|
|
812
976
|
if matrix_runner.runs_total == 0:
|
|
813
977
|
matching = f"matching '{only}' " if only else ""
|
|
@@ -361,8 +361,8 @@ def _result_type(result: object) -> str:
|
|
|
361
361
|
|
|
362
362
|
def _result_label(result: object) -> str:
|
|
363
363
|
if result.operator:
|
|
364
|
-
return f"reach {result.operator} {result.label}".strip()
|
|
365
|
-
return result.label or "-"
|
|
364
|
+
return f"reach {result.operator} {result.label}{result.under_symmetry}".strip()
|
|
365
|
+
return f"{result.label}{result.under_symmetry}" or "-"
|
|
366
366
|
|
|
367
367
|
|
|
368
368
|
def _table_row(idx: int, result: object) -> str:
|