agent-formal-verify 0.4.17 → 0.4.18
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 +18 -0
- package/package.json +1 -1
- package/skills/formal-verify/SKILL.md +3 -3
- package/skills/formal-verify/references/evidence.md +2 -1
- package/skills/formal-verify/references/helpers.md +7 -7
- package/skills/formal-verify/references/setup.md +17 -4
- package/skills/formal-verify/references/tla-brief.md +4 -3
- package/skills/formal-verify/scripts/baseline.py +18 -5
- package/skills/formal-verify/scripts/kani_reader.py +38 -19
- package/skills/formal-verify/scripts/lean_mutations.py +8 -5
- package/skills/formal-verify/scripts/mutate.py +17 -8
- package/skills/formal-verify/scripts/processes.py +1 -1
- package/skills/formal-verify/scripts/tlc.py +165 -65
- package/skills/formal-verify/scripts/tlc_report.py +17 -10
- package/skills/setup/SKILL.md +1 -1
package/CHANGES.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# Changes
|
|
2
2
|
|
|
3
|
+
## 0.4.18 - everystate as an optional TLA+ engine, Kani baselines that read methods and report added functions, and elapsed time for Lean mutants
|
|
4
|
+
|
|
5
|
+
Kani baselines now include helper and method signatures. Changing a generator helper from `fn input() -> u16` to `fn input() -> u8` prints `CHANGED` even when its body stays `{ kani::any() }`. Older records show the added signature on the first comparison.
|
|
6
|
+
|
|
7
|
+
The Kani baseline reads methods in impls with braced const arguments, such as `impl Input<{ WIDTH * 2 }>`. Older records can lack those methods. Review them against the original revision and record the file again.
|
|
8
|
+
|
|
9
|
+
`scripts/baseline.py` now also records the body of each method in an `impl` or trait block in a Kani module that holds a harness, or in a module under one, as the item `body <method>`, written as a harness body is. A method's name puts its block's header between angle brackets, without the whitespace that a reformat can change, such as `proofs::<impl kani::Arbitrary for State>::any`, and a `kani::assume`, `kani::any_where` or `kani::cover!` inside the method is recorded under that name. Before this change, the record did not read such a method, so changing `next: kani::any()` to `next: 0` in the `any` of an `impl kani::Arbitrary for State` beside the template's harnesses printed `UNCHANGED`, and a `kani::assume` inside a method failed the record with `cannot identify a function owner`. A `#[kani::proof]`, `#[kani::stub]`, `#[kani::should_panic]` or `#[kani::unwind]` on a method still fails the record, as does a Kani form in an `impl` or trait block inside a function body. A method outside the modules that hold harnesses is still read only for its assumptions and covers. A record made before this change prints `CHANGED` once, with the line `previous baseline did not record the methods beside its harnesses`, when the file has such a method; check each one against the original revision, then record the file again.
|
|
10
|
+
|
|
11
|
+
`setup.sh tla`, the TLA+ matrix runner and the mutation runner can now check models with the native everystate engine, version 0.4.6 or later, in place of Java TLC. Set `TLC_ENGINE=everystate`, and set `EVERYSTATE` to the binary's path when it is not on `PATH`. The everystate engine needs no JDK and no `tla2tools.jar`, and the helpers never download it. `setup.sh tla` prints an `UNAVAILABLE` line and exits 3 when the binary is missing or older than 0.4.6. The runners run everystate with `-lncheck final`, which checks temporal properties once on the complete state graph, and end the `SUMMARY` line with `(everystate <version>)`. Java TLC is still the default and the reference checker, and the setup skill still prepares only Java TLC. The everystate engine skips some of SANY's semantic checks, and its result differs from TLC's on some models, so check with Java TLC when the result must be authoritative.
|
|
12
|
+
|
|
13
|
+
Each run of the matrix runner, and each mutation run on a TLA+ model, now prints an `ENGINE` line before its first check, such as `ENGINE TLC 2.19 (tla2tools v1.7.4)`, and the HTML report that `TLC_HTML_REPORT` writes names the engine. A `TLC_ENGINE` value other than `tlc` or `everystate`, such as `TLC`, now makes `setup.sh tla` and both runners print `UNAVAILABLE TLC_ENGINE='TLC' is not supported; use 'tlc' or 'everystate'` and exit 3, before the matrix runner checks `TLC_HTML_REPORT` and before any run starts. An unset or empty `TLC_ENGINE` still selects Java TLC. Before this change, the helpers ignored `TLC_ENGINE`.
|
|
14
|
+
|
|
15
|
+
`scripts/baseline.py compare` now prints `CHANGED`, with the line `added body <function>`, when a free function or method that the record does not hold appears in a Kani module that holds a harness, or in a module under one. Such a function can shadow a production function that `use super::*;` brings in, so a harness calls it with no edit to its own body. Before this change, adding `fn claim(_window: u16, _state: State) -> Option<State> { None }` to the template's `mod proofs` made `claim_keeps_invariant` call it, so Kani passed the harness with a bug in the production `claim` and reported its assertion unreachable, while `compare` printed `UNCHANGED`. The body of an added harness is still allowed. 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; check each one against the original revision, then record the file again. Accept a new function only when each recorded body that names it is also listed as added or changed, and revert it when an unchanged recorded body names it. For a file with no added function or method, a record made before this change prints the same status as before.
|
|
16
|
+
|
|
17
|
+
The mutation runner now reports long Lean elaborations on `stderr` as the Lean checker does. After fifteen seconds, and every thirty seconds after that, it writes `[lean] unmutated model: <N>s elapsed` while Lean elaborates the unmutated model and `[lean] mutation <label>: <N>s elapsed` while Lean elaborates a mutant, where `<label>` is the label on the mutation's `mutation` line. The printed results on `stdout` and the exit status do not change. Before this change, the runner reported only the checker's `build`, `audit` and `replay` steps, so a long mutant check printed nothing until it finished.
|
|
18
|
+
|
|
19
|
+
A Kani check, a Lean checker step or a Lean mutant check that starts with `stderr` closed now reaches its verdict and writes no elapsed-time lines. Before this change, Python set `sys.stderr` to `None` in such a process, so the first elapsed-time report stopped the check with an `AttributeError`.
|
|
20
|
+
|
|
3
21
|
## 0.4.17 - one Cargo build directory per Rust mutation run, and elapsed time for long Kani and Lean runs
|
|
4
22
|
|
|
5
23
|
The Rust mutation runner now builds the crate for discovery, for the unmutated checks and for every mutation in one Cargo target directory, so Kani compiles the crate's dependencies once per run rather than once per mutation. Each mutation still checks a fresh copy of the crate. The target directory is in a temporary directory that the runner removes when it ends, including when `SIGTERM`, `SIGINT` or `SIGHUP` stops it. A copy keeps the modification times of the original files, which can be older than the previous mutant's build, so Kani's Cargo now compares file contents to decide what to rebuild. By modification times alone, such a copy would reuse the mutant's build.
|
package/package.json
CHANGED
|
@@ -54,7 +54,7 @@ Then ask the user whether to add an independent review of each model's propertie
|
|
|
54
54
|
Prepare tools after picking targets and before launching agents. The helpers are in this skill's `scripts/` directory. Stay in the target repository and run each helper with `bash` and its absolute path. Pass absolute paths to models and matrices. [Tool setup](references/setup.md) describes the pins, caches and environment settings.
|
|
55
55
|
|
|
56
56
|
- When a target needs Kani, run `bash <skill-dir>/scripts/setup.sh rust`. Before any agent starts, declare `cfg(kani)` in each target crate's `Cargo.toml`, a moved harness's production crate among them, as the Kani template's `[lints.rust]` entry does, or under `[workspace.lints.rust]` when the crate sets `lints.workspace = true`. Without it, rustc warns about every harness module, and a build with `-D warnings` fails.
|
|
57
|
-
- When a target needs TLA+, run `bash <skill-dir>/scripts/setup.sh tla
|
|
57
|
+
- When a target needs TLA+, run `bash <skill-dir>/scripts/setup.sh tla` with the selected engine. Java TLC is the default. For a native run, use `TLC_ENGINE=everystate` and any `EVERYSTATE` binary path from [tool setup](references/setup.md). Reuse the setup settings for baseline checks, mutations and final reruns.
|
|
58
58
|
- When a target needs Lean, every Lean model in the repository shares one Lake project. If the repository has none, copy `lakefile.toml`, `lake-manifest.json` and `lean-toolchain` from `<skill-dir>/examples/lean-template/` to `lean/` in the target repository, once. Then run `bash <skill-dir>/scripts/setup.sh lean <absolute-model-project-path>`.
|
|
59
59
|
|
|
60
60
|
Require a successful exit and a `READY` line from each command. A helper that cannot run prints `UNAVAILABLE` and exits 3. Report it as "not checked" with its remedy. It is neither a pass nor a failure of the model. A check that ran and failed exits 1; usage errors exit 2. The setup helper reuses ready tools and installs a missing Lean pin, so the user does not need to rerun `/agent-formal-verify:setup` when a target or pin changes. Keep the installed skill files read-only and copy templates into the target repository.
|
|
@@ -81,7 +81,7 @@ Spawn one agent per target, in parallel when supported. Use the host runtime's a
|
|
|
81
81
|
|
|
82
82
|
- the target's row from the table, with its source files and line ranges;
|
|
83
83
|
- the model's name, `<Name>`, which for a new Kani harness is the stem of its production file, such as `lib`, and for a Lean target the absolute path of the Lake project, or for Kani the absolute path of the crate;
|
|
84
|
-
- the absolute path of this skill's directory as `<skill-dir>`, and any `JAVA`
|
|
84
|
+
- the absolute path of this skill's directory as `<skill-dir>`, and for TLA+ the selected `TLC_ENGINE` plus any `EVERYSTATE`, `JAVA`, `TLC_JAR` or `TLC_CACHE` settings used during setup;
|
|
85
85
|
- the instruction to read `<skill-dir>/references/tla-brief.md` for a protocol, `<skill-dir>/references/lean-brief.md` for arithmetic, or `<skill-dir>/references/rust-brief.md` for a Rust function, in full and to follow it;
|
|
86
86
|
- for an existing model, its files.
|
|
87
87
|
|
|
@@ -89,7 +89,7 @@ Name the brief file and leave its text out of the prompt. The [TLA+ brief](refer
|
|
|
89
89
|
|
|
90
90
|
An agent writes only its own files, `tla/<Name>.tla`, `.matrix` and `.mutations`, `lean/Model/<Name>.lean`, `.mutations` and `.statements`, or the `#[cfg(kani)]` harness module in the production file that defines its Rust function and the `.mutations` file beside it, so parallel agents share none. Give one agent every Rust target in one production file. An existing Lean project keeps its layout and must pin Lean 4.20.0 or later. A Kani harness that an earlier run wrote in a crate of its own moves into its production file when the Rust brief's "Moving a harness" section allows, so it gets an agent even when it passes; otherwise its agent edits it and its `.mutations` file in place.
|
|
91
91
|
|
|
92
|
-
When the agents have reported, delete each moved harness's old file, and its crate, workspace entry and CI steps once they hold nothing else. Then rerun every check in this thread: the matrix runner on each matrix file, the Lean checker on the whole project without a file name, the Rust checker on each crate, and the mutation runner on each mutations file. Take each verdict from these runs, not from an agent's report. For a moved harness, first run `baseline.py move` as the [helper reference](references/helpers.md) says. Then run `python3 <skill-dir>/scripts/baseline.py compare <record-file>`. It exits 1 and prints CHANGED with the changed parts when a recorded property, fairness condition, matrix line, `.statements` record, Kani harness or helper body, cover or stub changed, a Kani harness was removed, renamed, no longer compiles or had its `cfg` guards changed on a route the record reads,
|
|
92
|
+
When the agents have reported, delete each moved harness's old file, and its crate, workspace entry and CI steps once they hold nothing else. Then rerun every check in this thread: the matrix runner on each matrix file, the Lean checker on the whole project without a file name, the Rust checker on each crate, and the mutation runner on each mutations file. Take each verdict from these runs, not from an agent's report. For a moved harness, first run `baseline.py move` as the [helper reference](references/helpers.md) says. Then run `python3 <skill-dir>/scripts/baseline.py compare <record-file>`. It exits 1 and prints CHANGED with the changed parts when a recorded property, fairness condition, matrix line, `.statements` record, Kani harness or helper body, cover or stub changed, a Kani harness was removed, renamed, no longer compiles or had its `cfg` guards changed on a route the record reads, a Kani assumption was added or changed, or a function or method was added beside a Kani harness. Accept a move only as that reference says. Also read `git diff` for each model that existed before this run, for the changes the record does not cover, such as a theorem newly marked `private`, a new guard in a TLA+ action, or a narrowed input in a Kani helper outside the harness's module. Each such change needs the evidence its row cites, a specification correction accepted below, or for a re-freeze another reason the Lean brief permits. Revert any change without it and give the model back to its agent with the reason. Run the comparison again until it exits 0. Report each file that prints `NOT CHECKED` as not checked against Kani.
|
|
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
|
|
|
@@ -5,6 +5,7 @@ Include the matching meaning from this table where each kind of evidence first a
|
|
|
5
5
|
| Evidence | Meaning to give |
|
|
6
6
|
| --- | --- |
|
|
7
7
|
| TLC passes | TLC tried every ordering of the modelled steps at the listed small sizes and found none that breaks the property. The SUMMARY line's state total is the size of that search, not a count of real runs. |
|
|
8
|
+
| everystate passes | The native `everystate` engine tried every ordering of the modelled steps at the listed small sizes (using `-lncheck final` for liveness) and found none that breaks the property. The runner uses in-memory storage and needs no JVM. Report the engine version. Compare speed only when both engines were timed on the same workload. Use Java TLC for an authoritative TLC/SANY verdict because everystate skips some SANY semantic checks and can produce a different liveness counter-example. |
|
|
8
9
|
| Kani passes | Kani checked every input within the stated bounds and found no violation. Larger inputs are not covered. |
|
|
9
10
|
| Lean passes | Lean proved the property for every input, under the listed assumptions. |
|
|
10
11
|
| Kernel replay passed | Lean's kernel checked every declaration of the built modules a second time, including any that a command added without a check. `unavailable` means the pinned Lean has no `leanchecker`, so this second check did not run. |
|
|
@@ -12,7 +13,7 @@ Include the matching meaning from this table where each kind of evidence first a
|
|
|
12
13
|
| A bounded search passes | Every input up to the stated bound was tried. |
|
|
13
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. |
|
|
14
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. |
|
|
15
|
-
| 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 in a module that holds one, such as an input helper
|
|
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 one 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. |
|
|
16
17
|
| UNAVAILABLE | The tool could not run. This target was not checked; give the printed remedy. |
|
|
17
18
|
| reproduced | A deterministic test or race-detector run fails on the production code. |
|
|
18
19
|
| reachable at shipped settings | The shipped constants and callers permit the counter-example, but no production reproduction has confirmed it yet. |
|
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
Detailed behaviour of the verification scripts under `scripts/`. Run each helper from the target repository using `bash` or `python3` with `<skill-dir>` resolved to the installed `formal-verify` skill directory.
|
|
4
4
|
|
|
5
|
-
- **Setup helper ([`scripts/setup.sh`](../scripts/setup.sh))**: verifies the pinned TLC JAR (`tla`), checks the pinned Kani driver and bundled Rust toolchain (`rust`), and is the only helper that installs a Lean toolchain (`lean`).
|
|
6
|
-
- **Matrix runner ([`scripts/tlc-matrix.sh`](../scripts/tlc-matrix.sh))**: runs TLC with a matrix of constants
|
|
7
|
-
- **Lean checker ([`scripts/lean-check.sh`](../scripts/lean-check.sh))**: builds every `.lean` file in the pinned Lake project and audits every declaration of every built module. It fails on a build error, a `sorry`, a declaration that rests on an axiom beyond `propext`, `Classical.choice` and `Quot.sound`, or a `.lean` file that no Lake library owns. It checks each `<Property>.witness` theorem against its property's hypotheses, and fails on a witness that states something else, as the [Lean brief](lean-brief.md) describes. It then replays every built module, and every project module it imports, through the Lean kernel with the pin's `leanchecker`, which rejects a declaration that a command added without a kernel check. A pin without `leanchecker`, such as Lean 4.20.0, passes with the replay reported as unavailable. While the build, the audit or the replay runs, the checker writes a line such as `[lean] build: 45s elapsed` to `stderr` after fifteen seconds and every thirty seconds after that. Use `--freeze` before the file names to record statement types and definition bodies in each model's `.statements` file before proving it. Freezing permits `sorry` and reports `FROZEN`, not a proof `PASS`. Later checks enforce those records and permit proof changes and added declarations. Given file names after the project, it checks only those files. Copy [`examples/lean-template/Model/BoundedQueue.lean`](../examples/lean-template/Model/BoundedQueue.lean) to start a model.
|
|
5
|
+
- **Setup helper ([`scripts/setup.sh`](../scripts/setup.sh))**: verifies the pinned TLC JAR (`tla`), or `everystate` 0.4.6 or later when `TLC_ENGINE=everystate`, checks the pinned Kani driver and bundled Rust toolchain (`rust`), and is the only helper that installs a Lean toolchain (`lean`).
|
|
6
|
+
- **Matrix runner ([`scripts/tlc-matrix.sh`](../scripts/tlc-matrix.sh))**: runs TLC (or the native `everystate` engine with `-lncheck final` when `TLC_ENGINE=everystate`, requiring no JDK or JAR) with a matrix of constants. It prints an `ENGINE` line naming the checker and version before the first run, then one `PASS` or `FAIL` per run with its state count, then a `SUMMARY` line with the totals (tagged with `(everystate <version>)` when using `everystate`). Stops each run after sixty minutes, or after the limit in `TLC_TIMEOUT` as [setup](setup.md) describes, and forwards periodic elapsed-time and `Progress(...)` updates to `stderr` during long runs. A failing run prints its error trace reduced by [`scripts/tlc_trace.py`](../scripts/tlc_trace.py) to the variables each step changed. Set `TLC_HTML_REPORT=<path>` to also write a self-contained offline HTML report through [`scripts/tlc_report.py`](../scripts/tlc_report.py) with the active engine metadata, the run table, an interactive native SVG state chain, a variable diff panel, and copyable Mermaid `stateDiagram-v2` source for each failing and `reach` witness trace. The runner checks the path after checking the TLA+ engine and before the first run, and a path where it cannot write the report prints an `UNAVAILABLE TLC_HTML_REPORT=...` line with the remedy and exits 3. It replaces the report in one step, and a written report leaves `stdout` and the exit status as they are without one. If the write fails after the runs, the runner prints the same line and exits 1 when a run failed and 3 otherwise. `tlc.py ready` and `mutate.py` ignore the variable. Copy [`examples/tla-template/`](../examples/tla-template/BoundedQueue.tla) to start a spec and its matrix.
|
|
7
|
+
- **Lean checker ([`scripts/lean-check.sh`](../scripts/lean-check.sh))**: builds every `.lean` file in the pinned Lake project and audits every declaration of every built module. It fails on a build error, a `sorry`, a declaration that rests on an axiom beyond `propext`, `Classical.choice` and `Quot.sound`, or a `.lean` file that no Lake library owns. It checks each `<Property>.witness` theorem against its property's hypotheses, and fails on a witness that states something else, as the [Lean brief](lean-brief.md) describes. It then replays every built module, and every project module it imports, through the Lean kernel with the pin's `leanchecker`, which rejects a declaration that a command added without a kernel check. A pin without `leanchecker`, such as Lean 4.20.0, passes with the replay reported as unavailable. While the build, the audit or the replay runs, the checker writes a line such as `[lean] build: 45s elapsed` to `stderr` after fifteen seconds and every thirty seconds after that. The mutation runner writes the same lines while it runs the checker on the unmutated model. It then writes `[lean] unmutated model: <N>s elapsed` while Lean elaborates that model, and a line such as `[lean] mutation no step: 45s elapsed`, which names the mutation, while Lean elaborates each mutant. Use `--freeze` before the file names to record statement types and definition bodies in each model's `.statements` file before proving it. Freezing permits `sorry` and reports `FROZEN`, not a proof `PASS`. Later checks enforce those records and permit proof changes and added declarations. Given file names after the project, it checks only those files. Copy [`examples/lean-template/Model/BoundedQueue.lean`](../examples/lean-template/Model/BoundedQueue.lean) to start a model.
|
|
8
8
|
- **Rust checker ([`scripts/kani-check.sh`](../scripts/kani-check.sh))**: runs the pinned Kani on the crate's proof harnesses. It reports each harness's unwind bound and check count, requires a satisfied cover witness in each passing harness, rejects failed checks, and prints concrete playback tests when available. It stops each harness after five minutes, or after the limit in `KANI_HARNESS_TIMEOUT` as [setup](setup.md) describes, and fails a harness that reaches the limit with a message that names the setting. Each harness check, here or in the mutation runner, can take up to that limit, so run the command in the background or with a command timeout longer than the total. While Kani builds the crate or checks a harness, the checker and the mutation runner write a line such as `[kani] proofs::claim_keeps_invariant: 45s elapsed` to `stderr` after fifteen seconds and every thirty seconds after that. When discovery fails because code Kani compiles uses a feature newer than Kani's bundled toolchain (error E0658), the failure names that toolchain, and the [Rust brief](rust-brief.md) says what to rewrite or report. Copy [`examples/kani-template/`](../examples/kani-template/src/lib.rs) for a bounded-queue example.
|
|
9
|
-
- **Mutation runner ([`scripts/mutate.py`](../scripts/mutate.py))**: takes a model's `<Name>.mutations` file and applies each listed bug to a temporary copy of the model. It prints `DETECTED` or `MISSED` per mutation with what failed, `UNCOVERED` for a TLA+ property or a Kani harness in the adjacent Rust file that no mutation targets or for a public theorem in a Lean model's `.statements` file whose proof no mutation makes fail, and a `SUMMARY` line. Lean names are fully qualified. A Lean `DETECTED` line means the existing proof fails; it does not establish that the statement is false or its hypotheses can hold. A Lean mutation that changes the statement of a theorem, example or `#guard`, such as renaming a definition that the statement names, reaches no verdict, and so does a mutation that edits the text of a theorem whose proof then fails. The runner matches a failing example or `#guard` to one occurrence in the original model, so a failure in an example or `#guard` that the mutation adds, or in one that it cannot match to a single original occurrence, also reaches no verdict. So does a TLA+ mutation whose check reaches the
|
|
9
|
+
- **Mutation runner ([`scripts/mutate.py`](../scripts/mutate.py))**: takes a model's `<Name>.mutations` file and applies each listed bug to a temporary copy of the model. It prints `DETECTED` or `MISSED` per mutation with what failed, `UNCOVERED` for a TLA+ property or a Kani harness in the adjacent Rust file that no mutation targets or for a public theorem in a Lean model's `.statements` file whose proof no mutation makes fail, and a `SUMMARY` line. Lean names are fully qualified. A Lean `DETECTED` line means the existing proof fails; it does not establish that the statement is false or its hypotheses can hold. A Lean mutation that changes the statement of a theorem, example or `#guard`, such as renaming a definition that the statement names, reaches no verdict, and so does a mutation that edits the text of a theorem whose proof then fails. The runner matches a failing example or `#guard` to one occurrence in the original model, so a failure in an example or `#guard` that the mutation adds, or in one that it cannot match to a single original occurrence, also reaches no verdict. So does a TLA+ mutation whose check reaches the `TLC_TIMEOUT` limit, or a Kani mutation whose harness reaches the Rust checker's time limit. TLA+ runs inherit `TLC_ENGINE`, print the `ENGINE` line before checking the unmutated model, and tag `SUMMARY` with `(everystate <version>)` when using `everystate`. A mutation with no verdict stops the run with a `FAIL` line. A Lean model needs its `.statements` file before its mutations run. All three templates include a mutations file.
|
|
10
10
|
- **Sync helper ([`scripts/sync.py`](../scripts/sync.py))**: takes an existing model's files, the source files its header names as `--source` and the functions and shared variables it covers as `--name`, and lists what changed since the model was last synced. [Step 1 of the skill](../SKILL.md#1-pick-the-targets) says what to do with its `SYNC none`, `READ` and `MISSING` lines.
|
|
11
11
|
- Output:
|
|
12
12
|
- `SYNC <commit> <reason>` gives the sync commit: the header's `Source read at` commit when `HEAD`'s history contains it, and otherwise the last commit of the model files that qualifies, with the reason the header's commit was not used. For a model file that is also given as `--source`, such as a production file with its Kani harness, a commit qualifies only when it changed the code of the file's `#[cfg(kani)]` items and none of its other code.
|
|
@@ -24,8 +24,8 @@ Detailed behaviour of the verification scripts under `scripts/`. Run each helper
|
|
|
24
24
|
- 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.
|
|
25
25
|
- Output of `compare <record-file>`, which exits 1 when a recorded file changed. Each indented line under `CHANGED` counts as a change, except the `not checked against Kani at record, ...` line and the lines under it:
|
|
26
26
|
- `UNCHANGED <file>`, `CHANGED <file>` or `NOT CHECKED <file>` for each recorded file, then `SUMMARY <n> unchanged, <m> changed`, which ends with `, <k> not checked` when a file printed `NOT CHECKED`.
|
|
27
|
-
- An indented `removed <item>`, or `changed <item>` with its `old:` and `new:` values. A Kani harness's value is the `cfg` guards that can switch it off, followed by its `kani::should_panic` and `kani::unwind(<n>)` attributes and the `unread(...)` note that "Cannot see" describes. When more than one route that the record reads leads to the file, the value holds each route as its crate root's path relative to the harness file's directory and its guards, such as `routes(lib.rs: unguarded; main.rs: cfg(feature = "slow"))`, so adding, removing or guarding any route, or moving a guard from one route to another, changes the harness. The item `body <function>` holds, for a harness and for each other free function in a module that holds a harness or under one, such as an input helper
|
|
28
|
-
- An indented `added <item>`, which only a new Kani assumption or
|
|
27
|
+
- An indented `removed <item>`, or `changed <item>` with its `old:` and `new:` values. A Kani harness's value is the `cfg` guards that can switch it off, followed by its `kani::should_panic` and `kani::unwind(<n>)` attributes and the `unread(...)` note that "Cannot see" describes. When more than one route that the record reads leads to the file, the value holds each route as its crate root's path relative to the harness file's directory and its guards, such as `routes(lib.rs: unguarded; main.rs: cfg(feature = "slow"))`, so adding, removing or guarding any route, or moving a guard from one route to another, changes the harness. The item `body <function>` holds, for a harness and for each other free function or method in an `impl` or trait block in a module that holds a harness or under one, such as an input helper or the `any` of an `impl kani::Arbitrary`, the normalized body without comments, without each `kani::cover!` call whose condition cannot run code, which is an item of its own, and without whitespace except one space where two tokens would otherwise join, such as `{let(window,state)=inputs();...}`. For a helper, the value includes its declaration so a change to a qualifier such as `async`, a parameter, return type or `where` clause is visible even when the body stays the same. An older record shows the added signature on its first comparison. Check it against the recorded revision before recording again. A method's name puts its block's 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. Re-indenting or rewrapping the body leaves it unchanged, but a trailing comma that a formatter adds or removes changes it. A cover whose condition holds a call, a block, an index, `?`, `return`, `break`, `continue`, `await` or `yield` can return early or change a value before an assertion, so it stays in the body, and adding one changes the body. Accept such a change when the `new:` value differs from the `old:` value only by the added cover and its condition only reads values, then record the file again. A record made before bodies were recorded prints `previous baseline did not record harness bodies` once, one made before the other functions' bodies were recorded prints `previous baseline did not record the functions beside its harnesses` once, and one made before the methods' bodies were recorded prints `previous baseline did not record the methods beside its harnesses` once. For those records, check each harness body against the original revision before recording the file again.
|
|
28
|
+
- An indented `added <item>`, which only a new Kani assumption, stub or `body <function>` prints. A function or method added in a module that holds a harness, or under one, can shadow a function that a glob import such as `use super::*;` brings in, so a harness calls the new function with no edit to its own body. Every such function or method prints `added body <function>`, whatever its name, except a new harness, whose body is allowed with it. A harness added in a module that held none puts that module's functions in the record, so each of them prints `added body <function>` once. A record made before the other functions' or the methods' bodies were recorded also prints `added body <function>` for each body it did not record. Check a function that existed at the original revision against that revision. Accept a new function only when each recorded body that names it is listed as added or changed and its change is accepted, and revert it when an unchanged recorded body names it, since that body now calls the new function in place of the one it checked. Then record the file again. A `kani::any_where` assumption includes the complete call, including explicit type arguments. Older records used one representation for plain assumptions and generator predicates. For those records, check the assumptions and generator types against the original revision before recording the file again.
|
|
29
29
|
- 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.
|
|
30
30
|
- An indented `file is missing`: the recorded file no longer exists.
|
|
31
31
|
- 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.
|
|
@@ -34,7 +34,7 @@ Detailed behaviour of the verification scripts under `scripts/`. Run each helper
|
|
|
34
34
|
- `FAIL baseline: <reason>` exits 1, and a `usage:` line exits 2. `record` fails this way for a file it cannot read, such as a harness file that no route the record reads reaches or a Kani form the record cannot read, where `compare` prints an indented `FAIL` under `CHANGED`. Both fail this way for an unsupported or malformed record file.
|
|
35
35
|
- Cannot see:
|
|
36
36
|
- 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.
|
|
37
|
-
- In Kani, the body of a
|
|
37
|
+
- 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.
|
|
38
38
|
- 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.
|
|
39
39
|
- 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.
|
|
40
40
|
- `baseline.py move <record-file> <old file> <new file>` moves a model's record entry to the file the model moved to, reading the record alone, so a later `compare` checks the new file against what the old one specified, including the harnesses that Kani compiled. For a Kani harness moved into a module of its production file, add `--module <old module> <new module>`, each relative to its file, with `crate` for the file's root, such as `--module crate proofs` for harnesses that sat at the old crate's root, even when the production file is `src/queue.rs`. When the new file already has an entry, the two are merged, and an item in both fails the move. It prints `MOVED <old> -> <new>`. Accept a move when `compare` prints `UNCHANGED`, or `NOT CHECKED` for an entry that `record` could not check against Kani, and `git diff` shows the old file's harness lines in the new module with only their indentation changed, plus the `use crate as <name>;` line and the `#[cfg(kani)] mod proofs` lines around them. When the production file's crate has a route that the record cannot read, `compare` prints a `changed harness` line for each moved harness whose `new:` value only adds an `unread(...)` note to its `old:` value; accept those too, then record the new file again. Any other change, such as an edited assertion, needs the evidence its row cites.
|
|
@@ -20,7 +20,7 @@ The left-behind processes share the process group of the runner that ended. To f
|
|
|
20
20
|
ps -A -o stat,pid,ppid,pgid,command | grep '^T'
|
|
21
21
|
```
|
|
22
22
|
|
|
23
|
-
A left-behind checker has lost its runner, so its parent is process 1 or a service manager such as `systemd --user`, and it runs a command such as TLC's `java`, `cargo-kani`, `cbmc`, `cargo`, `elan`, `lake` or `lean`. A job that you suspended yourself, such as an editor stopped with Ctrl-Z, has your shell as its parent; leave it alone. To list every process in a left-behind checker's group, including those still running, run `ps -A -o stat,pid,ppid,pgid,command` and keep the rows whose group matches the checker's. End each one with `kill -KILL <pid>`, or with `kill -TERM <pid>` followed by `kill -CONT <pid>` to let it clean up first. Do not signal the whole group, which can also hold the shell or job that started the runner.
|
|
23
|
+
A left-behind checker has lost its runner, so its parent is process 1 or a service manager such as `systemd --user`, and it runs a command such as TLC's `java`, `everystate`, `cargo-kani`, `cbmc`, `cargo`, `elan`, `lake` or `lean`. A job that you suspended yourself, such as an editor stopped with Ctrl-Z, has your shell as its parent; leave it alone. To list every process in a left-behind checker's group, including those still running, run `ps -A -o stat,pid,ppid,pgid,command` and keep the rows whose group matches the checker's. End each one with `kill -KILL <pid>`, or with `kill -TERM <pid>` followed by `kill -CONT <pid>` to let it clean up first. Do not signal the whole group, which can also hold the shell or job that started the runner.
|
|
24
24
|
|
|
25
25
|
## TLA+ and TLC
|
|
26
26
|
|
|
@@ -32,12 +32,25 @@ bash <skill-dir>/scripts/tlc-matrix.sh /path/to/models/Name.matrix
|
|
|
32
32
|
python3 <skill-dir>/scripts/mutate.py /path/to/models/Name.mutations
|
|
33
33
|
```
|
|
34
34
|
|
|
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.
|
|
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
|
-
|
|
37
|
+
With Java TLC, the matrix runner requires the JAR and a working Java runtime; with everystate, it needs neither. It checks for Python 3.9 or later before running, so a failing model can always print its reduced trace. It does not download tools. Each run checks the formula its spec names `Spec` and sees only the modules beside that spec. `TLC_WORKERS` sets the worker count for either engine. Set `TLC_HTML_REPORT=<path>` to write a self-contained offline HTML report (matrix summary, interactive SVG state chain, variable diffs, and copyable Mermaid source for failing and `reach` witness traces) via `scripts/tlc_report.py`; the runner checks the target path after the TLA+ engine and before the first run, prints `UNAVAILABLE` and exits 3 when it cannot write there, and writes the report atomically without changing `stdout` or exit status on success (`tlc.py ready` and `mutate.py` ignore `TLC_HTML_REPORT`). Each run stops after sixty minutes by default; set `TLC_TIMEOUT` to change the limit using a whole number from 1 to 4294967295 with an optional unit `s`, `m` or `h`, such as `90s` or `1h`. For any other value, `setup.sh tla`, the matrix runner and the mutation runner print `UNAVAILABLE` and exit 3 without running TLC. A run that reaches the limit fails with a message naming the limit and `TLC_TIMEOUT`, and a mutation run that reaches it reaches no verdict. During long runs, the runner forwards periodic elapsed-time and `Progress(...)` updates from `tlc.log` to `stderr`. With Java TLC, each run gives the JVM its own `java.io.tmpdir` inside the run directory, so TLC runs started at the same time do not delete each other's copy of the standard modules. A `-Djava.io.tmpdir` in `_JAVA_OPTIONS` overrides it, because the JVM reads that variable after the command line; set the temporary directory with `TMPDIR` instead.
|
|
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
|
|
|
41
|
+
### Optional native engine (`everystate`)
|
|
42
|
+
|
|
43
|
+
Java TLC (`TLC_ENGINE=tlc`, the default) remains the reference TLA+ checker. To run matrices and mutations without a JDK or `tla2tools.jar`, set `TLC_ENGINE=everystate` with [everystate](https://github.com/mattzcarey/everystate) 0.4.6 or later (verified through `everystate --version`; never downloaded by the helpers). Set `EVERYSTATE` to the binary path when it is not on PATH. Any other `TLC_ENGINE` value prints `UNAVAILABLE` and exits 3 before checking `TLC_HTML_REPORT` or starting a run.
|
|
44
|
+
|
|
45
|
+
```shell
|
|
46
|
+
# Install through Homebrew, Cargo, npm or the GitHub release archives, then check readiness:
|
|
47
|
+
TLC_ENGINE=everystate bash <skill-dir>/scripts/setup.sh tla
|
|
48
|
+
TLC_ENGINE=everystate bash <skill-dir>/scripts/tlc-matrix.sh /path/to/models/Name.matrix
|
|
49
|
+
TLC_ENGINE=everystate python3 <skill-dir>/scripts/mutate.py /path/to/models/Name.mutations
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The runner invokes `everystate` natively with `-lncheck final` so temporal properties are checked once on the complete state graph, forwards `[everystate]` elapsed-time and `Progress(...)` updates to `stderr`, and tags `SUMMARY` lines and HTML reports with `everystate <version>`. The runner uses everystate’s in-memory storage. The engine skips four SANY-only semantic checks from TLC's test suite; keep Java TLC for models that exceed RAM or when an authoritative TLC/SANY check is required.
|
|
53
|
+
|
|
41
54
|
## Rust and Kani
|
|
42
55
|
|
|
43
56
|
Install Rust and Cargo, then install Kani 0.68.0, the version pinned in [`scripts/kani.py`](../scripts/kani.py):
|
|
@@ -82,7 +95,7 @@ Helpers print `UNAVAILABLE` and exit 3 when a required tool is missing, unusable
|
|
|
82
95
|
|
|
83
96
|
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.
|
|
84
97
|
|
|
85
|
-
Install the chosen runtime and the pinned TLC JAR, 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_JAR` and `
|
|
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.
|
|
86
99
|
|
|
87
100
|
```yaml
|
|
88
101
|
- uses: actions/checkout@<commit>
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# TLA+ modelling brief
|
|
2
2
|
|
|
3
|
-
Follow this brief to model one thread protocol with TLA+ and TLC. Your task gives the source files and line ranges, the threads and shared variables, the model's `<Name>`, the absolute path `<skill-dir>` and
|
|
3
|
+
Follow this brief to model one thread protocol with TLA+ and TLC. Your task gives the source files and line ranges, the threads and shared variables, the model's `<Name>`, the absolute path `<skill-dir>` and the TLA+ engine settings from setup. Read the whole of each source file so the model follows the code.
|
|
4
4
|
|
|
5
5
|
## Files
|
|
6
6
|
|
|
@@ -38,18 +38,19 @@ Write each fact once.
|
|
|
38
38
|
```
|
|
39
39
|
|
|
40
40
|
- Define a guard or expression that two actions or properties share as one operator.
|
|
41
|
+
- Parenthesize `SUBSET`, `UNION` and `DOMAIN` when combined with binary set operators (such as `(UNION S) \cup T`) so the spec parses identically on TLC 1.7.4 and `everystate` (which follows post-2.19 precedence).
|
|
41
42
|
- Keep mutations in the mutations file. The spec has no `Mutation` constant and no branch for a planted bug. When one replacement restores the behaviour before a fix, list it as a mutation instead of adding a constant that switches the fix off.
|
|
42
43
|
|
|
43
44
|
## Check
|
|
44
45
|
|
|
45
|
-
|
|
46
|
+
Run both commands from the target repository with absolute paths. Apply the engine settings from your task to each command.
|
|
46
47
|
|
|
47
48
|
```shell
|
|
48
49
|
bash <skill-dir>/scripts/tlc-matrix.sh <absolute-path>/tla/<Name>.matrix
|
|
49
50
|
python3 <skill-dir>/scripts/mutate.py <absolute-path>/tla/<Name>.mutations
|
|
50
51
|
```
|
|
51
52
|
|
|
52
|
-
The matrix runner prints PASS or FAIL per run and a SUMMARY line. A failing run prints its error trace, reduced to the variables each step changed. When the user requests an HTML report, set `TLC_HTML_REPORT=<absolute-path>.html` (outside the repository unless requested otherwise) when running `tlc-matrix.sh` to write a self-contained offline HTML report with interactive SVG traces, variable diffs, and copyable Mermaid `stateDiagram-v2` source for failing and `reach` witness traces.
|
|
53
|
+
The matrix runner prints PASS or FAIL per run and a SUMMARY line. A failing run prints its error trace, reduced to the variables each step changed. The initial `ENGINE` line identifies the checker in both matrix and mutation output. With everystate the `SUMMARY` line also records `(everystate <version>)`. Set `TLC_ENGINE=tlc` for a follow-up Java TLC run when SANY semantic checks, disk-backed state storage, or an authoritative TLC verdict is required. When the user requests an HTML report, set `TLC_HTML_REPORT=<absolute-path>.html` (outside the repository unless requested otherwise) when running `tlc-matrix.sh` to write a self-contained offline HTML report with engine metadata, interactive SVG traces, variable diffs, and copyable Mermaid `stateDiagram-v2` source for failing and `reach` witness traces.
|
|
53
54
|
|
|
54
55
|
Each reach check prints its own PASS with the shortest witness length in states and transitions, or FAIL when the model never reaches the state. Witness searches use one worker and ignore deadlock so they can finish exploring a stopped model; `reach:` mutations run with `TLC_WORKERS` because confirming `UNREACHED` explores the full state graph without a witness trace. Attach each `reach` check—especially those paired with `detects reach:<Operator>`—to the smallest boundary `run` that exercises the predicate rather than large fault-injection configurations. The SUMMARY counts reach checks separately; its state total covers ordinary runs only. Use `detects reach:<Operator>` for a mutation that removes a required state. Reach checks do not count as properties for mutation coverage.
|
|
55
56
|
|
|
@@ -19,10 +19,14 @@ change, and so is an added item whose kind narrows what is checked.
|
|
|
19
19
|
items, the file and each out-of-line mod declaration that leads to the file from a crate root, through
|
|
20
20
|
#[path], with each route in the file's crates that the record cannot read, such as a mod
|
|
21
21
|
declaration inside a macro, and each kani::assume, kani::any_where, kani::cover! and
|
|
22
|
-
#[kani::stub] with its owning free function, under inline modules
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
22
|
+
#[kani::stub] with its owning free function, under inline modules, or method in an impl or trait block,
|
|
23
|
+
such as proofs::<impl kani::Arbitrary for State>::any. Unsupported owners fail. Added covers and harnesses are allowed.
|
|
24
|
+
Added assumes and stubs are changes. Also the body of each harness and of each other free function or
|
|
25
|
+
method in a module that holds a harness, or under one, without its comments, the kani::cover! calls whose
|
|
26
|
+
conditions cannot run code, and the whitespace that a reformat can change. A helper's record includes
|
|
27
|
+
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. An added
|
|
29
|
+
harness can still have its own body.
|
|
26
30
|
In a Cargo package, also the recorded harnesses that Kani compiles from the file; Kani must give
|
|
27
31
|
each harness it compiles there a module path that a route the record reads gives, and a harness
|
|
28
32
|
that no longer compiles is a change.
|
|
@@ -337,6 +341,7 @@ class KaniKind:
|
|
|
337
341
|
entry = model_entry(self.name, surface)
|
|
338
342
|
entry["generator_types"] = True
|
|
339
343
|
entry["helper_bodies"] = True
|
|
344
|
+
entry["method_bodies"] = True
|
|
340
345
|
notes = [f" route not read: {route.message}" for route in self.reader.unread(path)]
|
|
341
346
|
# A harness that no longer compiles is recorded from its text alone; compare asks Kani again.
|
|
342
347
|
try:
|
|
@@ -352,6 +357,10 @@ class KaniKind:
|
|
|
352
357
|
def changes(self, entry, path):
|
|
353
358
|
surface = kani_surface(path, self.reader)
|
|
354
359
|
lines = differences(entry["surface"], surface, ("assume", "stub"))
|
|
360
|
+
# An added function or method can shadow one that a glob import such as `use super::*;` brings in, so a
|
|
361
|
+
# harness calls it with no edit to a recorded body. An added harness's own body is allowed with it.
|
|
362
|
+
lines += [f" added {name}" for name in surface if name.startswith("body ") and name not in entry["surface"]
|
|
363
|
+
and "harness " + name.removeprefix("body ") not in surface]
|
|
355
364
|
if may_omit_generator_types(entry):
|
|
356
365
|
lines.insert(0, " previous baseline stored assumptions without distinguishing any_where input types; review the original assumptions and record this file again")
|
|
357
366
|
if any(name.startswith("harness ") and "body " + name.removeprefix("harness ") not in entry["surface"] for name in entry["surface"]):
|
|
@@ -359,6 +368,8 @@ class KaniKind:
|
|
|
359
368
|
# A record's keys cannot show whether it read the functions beside its harnesses, so the entry says so.
|
|
360
369
|
if not entry.get("helper_bodies") and any(name.startswith("body ") and "harness " + name.removeprefix("body ") not in surface for name in surface):
|
|
361
370
|
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")
|
|
371
|
+
if not entry.get("method_bodies") and any(name.startswith("body ") and "<" in name for name in surface):
|
|
372
|
+
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")
|
|
362
373
|
unchecked = (" not checked against Kani at record, so compare cannot tell a harness that "
|
|
363
374
|
"stopped compiling from one that never compiled")
|
|
364
375
|
try:
|
|
@@ -380,7 +391,7 @@ class KaniKind:
|
|
|
380
391
|
compiled = entry.get("compiled", [])
|
|
381
392
|
return (isinstance(compiled, list) and all(isinstance(name, str) for name in compiled)
|
|
382
393
|
and isinstance(entry.get("partial", False), bool) and isinstance(entry.get("generator_types", False), bool)
|
|
383
|
-
and isinstance(entry.get("helper_bodies", False), bool))
|
|
394
|
+
and isinstance(entry.get("helper_bodies", False), bool) and isinstance(entry.get("method_bodies", False), bool))
|
|
384
395
|
|
|
385
396
|
def moved(self, entry, module, new, existing):
|
|
386
397
|
surface, compiled = entry["surface"], entry.get("compiled")
|
|
@@ -400,6 +411,8 @@ class KaniKind:
|
|
|
400
411
|
result["generator_types"] = True
|
|
401
412
|
if all(part.get("helper_bodies") for part in (entry, existing) if part is not None):
|
|
402
413
|
result["helper_bodies"] = True
|
|
414
|
+
if all(part.get("method_bodies") for part in (entry, existing) if part is not None):
|
|
415
|
+
result["method_bodies"] = True
|
|
403
416
|
if compiled is not None:
|
|
404
417
|
result["compiled"] = sorted(compiled)
|
|
405
418
|
if partial:
|
|
@@ -16,7 +16,8 @@ import storage
|
|
|
16
16
|
from rust_source import RustSource, after_closing, normalized, rust_masks
|
|
17
17
|
from surface import Surface, collapse
|
|
18
18
|
|
|
19
|
-
|
|
19
|
+
# A method's owner holds spaces, such as `proofs::<impl kani::Arbitrary for State>::any`.
|
|
20
|
+
KANI_KEY = re.compile(r"(harness |body |(?:assume|cover|stub) .* in )(.+?)( #\d+)?", re.DOTALL)
|
|
20
21
|
|
|
21
22
|
|
|
22
23
|
class RustFunction(NamedTuple):
|
|
@@ -25,30 +26,37 @@ class RustFunction(NamedTuple):
|
|
|
25
26
|
keyword: int
|
|
26
27
|
body: int
|
|
27
28
|
end: int
|
|
29
|
+
method: bool = False
|
|
28
30
|
|
|
29
31
|
|
|
30
|
-
RUST_ITEM = re.compile(r"\b(fn|mod)\s+((?:r#)?\w+)\b")
|
|
32
|
+
RUST_ITEM = re.compile(r"\b(fn|mod)\s+((?:r#)?\w+)\b|\b(impl|trait)\b")
|
|
31
33
|
INCLUDE = re.compile(r"\binclude\s*!$")
|
|
32
34
|
|
|
33
35
|
|
|
34
36
|
def rust_functions(mask):
|
|
35
|
-
"""Locate free functions, inline modules, out-of-line
|
|
36
|
-
function bodies; leave macro and
|
|
37
|
+
"""Locate free functions, methods in `impl` and trait blocks outside function bodies, inline modules, out-of-line
|
|
38
|
+
`mod name;` declarations and `include!(...)` items outside function bodies and those blocks; leave macro and
|
|
39
|
+
other item bodies opaque, and return the `impl` and trait blocks apart.
|
|
37
40
|
|
|
38
|
-
A
|
|
41
|
+
A method's name puts its block's header between angle brackets, such as `proofs::<impl kani::Arbitrary for
|
|
42
|
+
State>::any`. A declaration's or an include's body is its `;`.
|
|
39
43
|
"""
|
|
40
|
-
functions, modules, opaque, declarations, includes, counts = [], [], [], [], [], {}
|
|
44
|
+
functions, modules, opaque, declarations, includes, blocks, counts = [], [], [], [], [], [], {}
|
|
41
45
|
|
|
42
46
|
def add_include(boundary, header, stop, in_body):
|
|
43
47
|
if not in_body and (include := INCLUDE.search(header)):
|
|
44
48
|
semicolon = re.compile(r"\s*;").match(mask, stop)
|
|
45
49
|
includes.append(RustFunction("include", boundary, boundary + include.start(), semicolon.end() - 1 if semicolon else stop - 1, stop))
|
|
46
50
|
|
|
47
|
-
def walk(start, end, namespace=(), in_function=False, in_body=False):
|
|
51
|
+
def walk(start, end, namespace=(), in_function=False, in_body=False, in_block=False):
|
|
48
52
|
i, boundary, item = start, start, None
|
|
49
53
|
while i < end:
|
|
50
54
|
if match := RUST_ITEM.match(mask, i):
|
|
51
|
-
item
|
|
55
|
+
# An `impl` after a pending item, such as `fn f() -> impl Trait`, is a type, not a block.
|
|
56
|
+
if match[3] is None:
|
|
57
|
+
item = (match[1], match[2], match.start())
|
|
58
|
+
elif item is None and not in_body:
|
|
59
|
+
item = (match[3], None, match.start())
|
|
52
60
|
i = match.end()
|
|
53
61
|
elif mask[i] in "([":
|
|
54
62
|
stop = after_closing(mask, i)
|
|
@@ -61,14 +69,22 @@ def rust_functions(mask):
|
|
|
61
69
|
stop = after_closing(mask, i)
|
|
62
70
|
header = mask[boundary:i].rstrip()
|
|
63
71
|
macro = header.endswith("!") or bool(re.search(r"\bmacro_rules\s*!\s*\w+\s*$", header))
|
|
64
|
-
if item and
|
|
72
|
+
if item and item[0] in ("impl", "trait"):
|
|
73
|
+
# A braced const argument in the header ends before the next generic argument or closing angle.
|
|
74
|
+
if re.compile(r"\s*[,>]").match(mask, stop):
|
|
75
|
+
i = stop
|
|
76
|
+
continue
|
|
77
|
+
# A block's items are no module's items, so an include! or mod in it is no route.
|
|
78
|
+
blocks.append((i, stop))
|
|
79
|
+
walk(i + 1, stop - 1, (*namespace, f"<{normalized(mask[item[2]:i])}>"), in_body=True, in_block=True)
|
|
80
|
+
elif item and not macro:
|
|
65
81
|
kind, name, keyword = item
|
|
66
82
|
qualified = (*namespace, name)
|
|
67
83
|
if kind == "fn":
|
|
68
84
|
owner = "::".join(qualified)
|
|
69
85
|
counts[owner] = counts.get(owner, 0) + 1
|
|
70
86
|
suffix = f"[{counts[owner]}]" if counts[owner] > 1 else ""
|
|
71
|
-
functions.append(RustFunction(owner + suffix, boundary, keyword, i, stop))
|
|
87
|
+
functions.append(RustFunction(owner + suffix, boundary, keyword, i, stop, method=in_block))
|
|
72
88
|
else:
|
|
73
89
|
modules.append(RustFunction("::".join(qualified), boundary, keyword, i, stop))
|
|
74
90
|
walk(i + 1, stop - 1, qualified, kind == "fn", in_body or kind == "fn")
|
|
@@ -87,7 +103,7 @@ def rust_functions(mask):
|
|
|
87
103
|
i += 1
|
|
88
104
|
|
|
89
105
|
walk(0, len(mask))
|
|
90
|
-
return functions, modules, opaque, declarations, includes
|
|
106
|
+
return functions, modules, opaque, declarations, includes, blocks
|
|
91
107
|
|
|
92
108
|
|
|
93
109
|
KANI_ATTRIBUTE = r"#\s*\[\s*(?:cfg_attr\s*\(\s*kani\s*,\s*)?kani\s*::\s*"
|
|
@@ -231,9 +247,9 @@ HIDDEN_ROUTE = re.compile(r"\bmod\s+(?:\$\w+|(?:r#)?\w+)\s*;|\binclude\s*!\s*[(\
|
|
|
231
247
|
def parse_rust(path):
|
|
232
248
|
source = rust_masks(path.read_text(encoding="utf-8"))
|
|
233
249
|
mask = source.without_comments_or_strings
|
|
234
|
-
functions, modules, opaque, declarations, includes = rust_functions(mask)
|
|
250
|
+
functions, modules, opaque, declarations, includes, blocks = rust_functions(mask)
|
|
235
251
|
hidden = {}
|
|
236
|
-
for start, end in opaque + [(function.body, function.end) for function in functions]:
|
|
252
|
+
for start, end in opaque + blocks + [(function.body, function.end) for function in functions]:
|
|
237
253
|
for match in HIDDEN_ROUTE.finditer(mask, start, end):
|
|
238
254
|
stop = match.end() - 1 if match[0].startswith("mod") else after_closing(mask, match.end() - 1)
|
|
239
255
|
route = rust_masks(source.uncommented[match.start():stop])
|
|
@@ -484,7 +500,7 @@ def kani_surface(path, reader):
|
|
|
484
500
|
text, mask = source.uncommented, source.without_comments_or_strings
|
|
485
501
|
if renaming := RENAMING_IMPORT.search(mask):
|
|
486
502
|
raise ValueError(f"{path}: '{collapse(renaming[0])}' brings a Kani assumption, cover, stub, harness or harness attribute in under another name; write each as kani::<name> so the record can read it")
|
|
487
|
-
functions, modules, opaque, _
|
|
503
|
+
functions, modules, opaque, *_ = rust_functions(mask)
|
|
488
504
|
declared = route_label(path, reader.routes(path))
|
|
489
505
|
unread = unread_label(path, reader.unread(path))
|
|
490
506
|
|
|
@@ -492,9 +508,12 @@ def kani_surface(path, reader):
|
|
|
492
508
|
if not any(start <= position < end for start, end in opaque):
|
|
493
509
|
for function in reversed(functions):
|
|
494
510
|
if function.start <= position < function.end and (position < function.body if attribute else position > function.body):
|
|
511
|
+
# The record reads a harness, its attributes and its stubs only on a free function.
|
|
512
|
+
if attribute and function.method:
|
|
513
|
+
break
|
|
495
514
|
return function
|
|
496
515
|
line = mask.count("\n", 0, position) + 1
|
|
497
|
-
raise ValueError(f"{path}:{line}: cannot identify a function owner; write Kani forms in free functions under inline modules, outside macro definitions and
|
|
516
|
+
raise ValueError(f"{path}:{line}: cannot identify a function owner; write Kani forms in free functions under inline modules or in methods of impl or trait blocks outside function bodies, outside macro definitions, and put Kani attributes on free functions")
|
|
498
517
|
|
|
499
518
|
surface = Surface()
|
|
500
519
|
spans, read, covers = [], [], []
|
|
@@ -519,9 +538,9 @@ def kani_surface(path, reader):
|
|
|
519
538
|
if HARNESS_ATTRIBUTE.fullmatch(item := re.sub(r"\s+", "", mask[start:end])):
|
|
520
539
|
read.append((start, end))
|
|
521
540
|
attributes.setdefault(owner_at(start, attribute=True), []).append(item)
|
|
522
|
-
def body(function):
|
|
541
|
+
def body(function, start):
|
|
523
542
|
# Each cover is an item of its own, so an added cover leaves the body as it was.
|
|
524
|
-
kept
|
|
543
|
+
kept = []
|
|
525
544
|
for begin, end in covers:
|
|
526
545
|
if function.body < begin < function.end:
|
|
527
546
|
kept.append(text[start:begin])
|
|
@@ -538,14 +557,14 @@ def kani_surface(path, reader):
|
|
|
538
557
|
guards = cfg_guards(source, [(0, 0, -1)] + [(item.start, item.keyword, item.body) for item in enclosing])
|
|
539
558
|
value = " ".join(filter(None, (declared, guards, *sorted(attributes.get(harness, ())), unread)))
|
|
540
559
|
spans.append((match.start(), f"harness {harness.name}", value))
|
|
541
|
-
spans.append((harness.body, f"body {harness.name}", body(harness)))
|
|
560
|
+
spans.append((harness.body, f"body {harness.name}", body(harness, harness.body)))
|
|
542
561
|
# A function in a module that holds a harness, or under one, such as an input helper, is part of what it checks.
|
|
543
562
|
scopes = {max((module for module in modules if module.start <= harness.start < module.end), key=lambda module: module.start, default=None)
|
|
544
563
|
for harness in harnesses}
|
|
545
564
|
for function in functions:
|
|
546
565
|
nested = any(other.body < function.start < other.end for other in functions)
|
|
547
566
|
if function not in harnesses and not nested and any(scope is None or scope.start <= function.start < scope.end for scope in scopes):
|
|
548
|
-
spans.append((function.body, f"body {function.name}", body(function)))
|
|
567
|
+
spans.append((function.body, f"body {function.name}", body(function, function.start)))
|
|
549
568
|
for token in KANI_TOKEN.finditer(mask):
|
|
550
569
|
if not any(start <= token.start() < end for start, end in read):
|
|
551
570
|
line = mask.count("\n", 0, token.start()) + 1
|
|
@@ -39,11 +39,14 @@ def _checked_record(model, project):
|
|
|
39
39
|
return record
|
|
40
40
|
|
|
41
41
|
|
|
42
|
-
def _analyze(model, project, toolchain):
|
|
43
|
-
"""Get Lean's declaration identities and error positions, never infer them from source text.
|
|
42
|
+
def _analyze(model, project, toolchain, label):
|
|
43
|
+
"""Get Lean's declaration identities and error positions, never infer them from source text.
|
|
44
|
+
|
|
45
|
+
While Lean runs, report the elapsed time on stderr as '[lean] <label>: <N>s elapsed'.
|
|
46
|
+
"""
|
|
44
47
|
done = processes.run_captured(["elan", "run", toolchain, "lake", "--dir", str(project), "env", "lean", "--run",
|
|
45
48
|
str(HERE / "lean-analysis.lean"), "analyze", str(model)],
|
|
46
|
-
encoding="utf-8", errors="replace")
|
|
49
|
+
label=f"[lean] {label}", encoding="utf-8", errors="replace")
|
|
47
50
|
output = done.stdout + done.stderr
|
|
48
51
|
records = [line.removeprefix("AFV_LEAN ") for line in done.stdout.splitlines() if line.startswith("AFV_LEAN ")]
|
|
49
52
|
if done.returncode != 0 or len(records) != 1:
|
|
@@ -184,12 +187,12 @@ def prepare(model, project):
|
|
|
184
187
|
record = _checked_record(model, project)
|
|
185
188
|
pin = record["toolchain"]
|
|
186
189
|
frozen = {entry["name"] for entry in record["declarations"] if entry["kind"] == "theorem"}
|
|
187
|
-
original = OriginalChecks(model, frozen, _analyze(model, project, pin))
|
|
190
|
+
original = OriginalChecks(model, frozen, _analyze(model, project, pin, "unmutated model"))
|
|
188
191
|
|
|
189
192
|
def check(mutation, work):
|
|
190
193
|
copy = work / model.name
|
|
191
194
|
source = mutation.apply()
|
|
192
195
|
copy.write_text(source, encoding="utf-8")
|
|
193
|
-
return original.broken_checks(mutation, source, copy, _analyze(copy, project, pin))
|
|
196
|
+
return original.broken_checks(mutation, source, copy, _analyze(copy, project, pin, f"mutation {mutation.label}"))
|
|
194
197
|
|
|
195
198
|
return original.targets, check
|
|
@@ -113,6 +113,13 @@ class Result:
|
|
|
113
113
|
covers: frozenset = frozenset()
|
|
114
114
|
|
|
115
115
|
|
|
116
|
+
@dataclass(frozen=True)
|
|
117
|
+
class Prepared:
|
|
118
|
+
targets: set
|
|
119
|
+
check: Callable
|
|
120
|
+
summary_suffix: str = ""
|
|
121
|
+
|
|
122
|
+
|
|
116
123
|
def stop(message, status=1):
|
|
117
124
|
print(f"FAIL {message}")
|
|
118
125
|
sys.exit(status)
|
|
@@ -220,13 +227,14 @@ def tla_runner(spec, mutations, run):
|
|
|
220
227
|
plan.selected(mutation.detects, mutation.only)
|
|
221
228
|
except ValueError as error:
|
|
222
229
|
stop(f"mutation '{mutation.label}': {error}")
|
|
223
|
-
checker = tlc.
|
|
230
|
+
checker = tlc.engine()
|
|
224
231
|
with tempfile.TemporaryDirectory(prefix="formal-tlc-originals-", dir=storage.ensure_temp_root()) as temporary:
|
|
232
|
+
print(f"ENGINE {checker.label}", flush=True)
|
|
225
233
|
try:
|
|
226
234
|
plan.check_originals(checker, [(mutation.detects, mutation.only) for mutation in mutations], Path(temporary))
|
|
227
235
|
except ValueError as error:
|
|
228
236
|
stop(str(error))
|
|
229
|
-
return plan.properties, partial(check_tla, plan, checker)
|
|
237
|
+
return Prepared(plan.properties, partial(check_tla, plan, checker), checker.summary_suffix)
|
|
230
238
|
|
|
231
239
|
|
|
232
240
|
def lean_runner(model, mutations, run):
|
|
@@ -235,7 +243,7 @@ def lean_runner(model, mutations, run):
|
|
|
235
243
|
if project is None:
|
|
236
244
|
stop(f"{model} is in no Lake project")
|
|
237
245
|
targets, broken_checks = lean_mutations.prepare(model, project)
|
|
238
|
-
return targets, partial(check_lean, broken_checks)
|
|
246
|
+
return Prepared(targets, partial(check_lean, broken_checks))
|
|
239
247
|
|
|
240
248
|
|
|
241
249
|
def rust_runner(model, mutations, run):
|
|
@@ -263,7 +271,7 @@ def rust_runner(model, mutations, run):
|
|
|
263
271
|
except kani.CheckError as error:
|
|
264
272
|
stop(str(error))
|
|
265
273
|
targets = {name for name, harness in bounds.items() if harness.source == model} | selected
|
|
266
|
-
return targets, partial(check_rust, model, project, verifier, bounds, sources, work)
|
|
274
|
+
return Prepared(targets, partial(check_rust, model, project, verifier, bounds, sources, work))
|
|
267
275
|
|
|
268
276
|
|
|
269
277
|
# Each runner checks the names the mutations detect and that the unmutated model passes the checks they select,
|
|
@@ -296,26 +304,27 @@ def main():
|
|
|
296
304
|
language, text = LANGUAGES[model.suffix], model.read_text(encoding="utf-8")
|
|
297
305
|
mutations = [make_mutation(label, directives, model, text, language) for label, directives in parse(path)]
|
|
298
306
|
with contextlib.ExitStack() as run:
|
|
299
|
-
|
|
307
|
+
prepared = language.runner(model, mutations, run)
|
|
300
308
|
storage.warn_runtime()
|
|
301
309
|
temp_root = storage.ensure_temp_root()
|
|
302
310
|
|
|
303
311
|
detected, covered = 0, set()
|
|
304
312
|
for mutation in mutations:
|
|
305
313
|
with tempfile.TemporaryDirectory(dir=temp_root) as work:
|
|
306
|
-
result = check(mutation, Path(work))
|
|
314
|
+
result = prepared.check(mutation, Path(work))
|
|
307
315
|
if result.verdict is Verdict.ERROR:
|
|
308
316
|
stop(f"mutation '{mutation.label}' did not reach a verdict:\n{result.detail.strip()}")
|
|
309
317
|
detected += result.verdict is Verdict.DETECTED
|
|
310
318
|
covered |= result.covers
|
|
311
319
|
print(f"{result.verdict.value} {mutation.label}" + (f": {result.detail}" if result.detail else ""), flush=True)
|
|
312
|
-
uncovered = sorted(targets - covered)
|
|
320
|
+
uncovered = sorted(prepared.targets - covered)
|
|
313
321
|
for name in uncovered:
|
|
314
322
|
print(f"UNCOVERED {name}")
|
|
315
323
|
if model.suffix == ".lean":
|
|
316
324
|
print(LEAN_NOTE)
|
|
317
325
|
print(f"SUMMARY {detected} of {len(mutations)} mutations detected"
|
|
318
|
-
+ (f", {len(uncovered)} properties without a mutation" if uncovered else "")
|
|
326
|
+
+ (f", {len(uncovered)} properties without a mutation" if uncovered else "")
|
|
327
|
+
+ prepared.summary_suffix)
|
|
319
328
|
return 0 if detected == len(mutations) and not uncovered else 1
|
|
320
329
|
|
|
321
330
|
|
|
@@ -231,7 +231,7 @@ def guarded(command, body, **kwargs):
|
|
|
231
231
|
|
|
232
232
|
def communicate(process, label=None):
|
|
233
233
|
"""Return process.communicate(); with a label, write '<label>: <N>s elapsed' to stderr while the process runs."""
|
|
234
|
-
if label is None:
|
|
234
|
+
if label is None or sys.stderr is None:
|
|
235
235
|
return process.communicate()
|
|
236
236
|
start = time.monotonic()
|
|
237
237
|
next_report = start + PROGRESS_DELAY
|
|
@@ -17,16 +17,19 @@ Matrix file, one directive per line (# starts a comment):
|
|
|
17
17
|
A malformed directive prints a FAIL line and the runner goes on to the next.
|
|
18
18
|
|
|
19
19
|
Usage: tlc-matrix.sh <matrix-file> [label-substring]
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
20
|
+
TLC_ENGINE=<name> TLA+ engine: tlc (default) or everystate
|
|
21
|
+
TLC_JAR=<path> use this existing tla2tools.jar (tlc engine)
|
|
22
|
+
TLC_CACHE=<dir> where the pinned jar lives (default ~/.cache/tla, tlc engine)
|
|
23
|
+
JAVA=<path> the java binary (default: java on PATH, tlc engine)
|
|
24
|
+
EVERYSTATE=<path> the everystate binary (default: everystate on PATH, everystate engine)
|
|
25
|
+
TLC_WORKERS=<n> worker threads (default auto)
|
|
24
26
|
TLC_TIMEOUT=<lim> per-run time limit, e.g. 90s, 30m, 1h (default 60m)
|
|
25
27
|
TLC_HTML_REPORT=<path> write a self-contained HTML report to this path
|
|
26
28
|
|
|
27
29
|
Usage: tlc.py ready
|
|
28
|
-
Checks
|
|
29
|
-
the temporary directory's free space as
|
|
30
|
+
Checks TLC_ENGINE, TLC_TIMEOUT, and the selected engine (Java and the pinned or supplied JAR for tlc;
|
|
31
|
+
everystate 0.4.6 or later for everystate), then reports the temporary directory's free space as
|
|
32
|
+
storage.py report does. setup.sh tla runs it.
|
|
30
33
|
"""
|
|
31
34
|
from __future__ import annotations
|
|
32
35
|
|
|
@@ -180,7 +183,63 @@ def _read_progress(log_path, offset, partial):
|
|
|
180
183
|
return new_offset, new_partial, latest
|
|
181
184
|
|
|
182
185
|
|
|
183
|
-
|
|
186
|
+
EVERYSTATE_VERSION = re.compile(r"^everystate (\d+)\.(\d+)\.(\d+)$")
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
class _Engine:
|
|
190
|
+
"""Shared timeout, worker, disk-warning and watched-run logic for TLA+ engines."""
|
|
191
|
+
name = "TLC"
|
|
192
|
+
log_tag = "tlc"
|
|
193
|
+
summary_suffix = ""
|
|
194
|
+
label = ""
|
|
195
|
+
ready_line = ""
|
|
196
|
+
|
|
197
|
+
def __init__(self):
|
|
198
|
+
timeout_raw = os.environ.get("TLC_TIMEOUT", "").strip() or DEFAULT_TIMEOUT
|
|
199
|
+
self.limit, self.timeout_seconds = runner.parse_limit("TLC_TIMEOUT", timeout_raw, "run time limit", "sixty minutes")
|
|
200
|
+
self.workers = os.environ.get("TLC_WORKERS") or "auto"
|
|
201
|
+
self._warned_disk = False
|
|
202
|
+
|
|
203
|
+
def _run_watched(self, command, log, progress_label=""):
|
|
204
|
+
if not self._warned_disk:
|
|
205
|
+
self._warned_disk = True
|
|
206
|
+
storage.warn_runtime()
|
|
207
|
+
start = time.monotonic()
|
|
208
|
+
deadline = start + self.timeout_seconds
|
|
209
|
+
|
|
210
|
+
def watch(process):
|
|
211
|
+
"""Wait for the checker, report its progress and stop it at the deadline; return its status and whether it timed out."""
|
|
212
|
+
next_report = start + PROGRESS_DELAY
|
|
213
|
+
offset, partial, latest = 0, "", ""
|
|
214
|
+
while True:
|
|
215
|
+
now = time.monotonic()
|
|
216
|
+
remaining = deadline - now
|
|
217
|
+
if remaining <= 0:
|
|
218
|
+
processes.stop_process(process)
|
|
219
|
+
return process.returncode, True
|
|
220
|
+
if now >= next_report:
|
|
221
|
+
offset, partial, found = _read_progress(log, offset, partial)
|
|
222
|
+
if found:
|
|
223
|
+
latest = found
|
|
224
|
+
elapsed = int(now - start)
|
|
225
|
+
prefix = f"[{self.log_tag}] {progress_label}: " if progress_label else f"[{self.log_tag}] "
|
|
226
|
+
body = f"{elapsed}s elapsed: {latest}" if latest else f"{elapsed}s elapsed"
|
|
227
|
+
sys.stderr.write(f"{prefix}{body}\n")
|
|
228
|
+
sys.stderr.flush()
|
|
229
|
+
next_report = now + PROGRESS_INTERVAL
|
|
230
|
+
wait_for = min(remaining, max(0.05, next_report - time.monotonic()))
|
|
231
|
+
try:
|
|
232
|
+
process.wait(timeout=wait_for)
|
|
233
|
+
return process.returncode, False
|
|
234
|
+
except subprocess.TimeoutExpired:
|
|
235
|
+
continue
|
|
236
|
+
|
|
237
|
+
with log.open("w", encoding="utf-8") as stream:
|
|
238
|
+
returncode, timed_out = processes.guarded(command, watch, stdout=stream, stderr=subprocess.STDOUT)
|
|
239
|
+
return returncode, read_raw(log), timed_out
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
class Tlc(_Engine):
|
|
184
243
|
"""The pinned TLC, checked once. Nothing here downloads it."""
|
|
185
244
|
version = "v1.7.4"
|
|
186
245
|
sha256 = "936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88"
|
|
@@ -192,8 +251,7 @@ class Tlc:
|
|
|
192
251
|
return Path(os.environ.get("TLC_CACHE") or Path.home() / ".cache/tla") / f"tla2tools-{cls.version}.jar"
|
|
193
252
|
|
|
194
253
|
def __init__(self):
|
|
195
|
-
|
|
196
|
-
self.limit, self.timeout_seconds = runner.parse_limit("TLC_TIMEOUT", timeout_raw, "run time limit", "sixty minutes")
|
|
254
|
+
super().__init__()
|
|
197
255
|
self.java = os.environ.get("JAVA") or "java"
|
|
198
256
|
try:
|
|
199
257
|
# The JVM prints in the platform encoding, which need not be UTF-8.
|
|
@@ -217,24 +275,30 @@ class Tlc:
|
|
|
217
275
|
if status and "TLC - provides model checking" not in output:
|
|
218
276
|
raise runner.Unavailable(f"UNAVAILABLE tlc2.TLC cannot run from {self.jar}; save a working JAR from {self.release} "
|
|
219
277
|
f"or set TLC_JAR\n{output.rstrip()}")
|
|
220
|
-
|
|
221
|
-
|
|
278
|
+
# The TLC version in the help banner and the tla2tools release tag use different numbering.
|
|
279
|
+
banner = re.search(r"^\s*(?:TLC - provides model checking[^\n]*? - Version |TLC2 Version )([0-9][\w.+-]*)", output, re.MULTILINE)
|
|
280
|
+
checker = f"TLC {banner[1]}" if banner else "TLC"
|
|
281
|
+
jar_source = "custom JAR" if supplied else f"tla2tools {self.version}"
|
|
282
|
+
if supplied and not banner:
|
|
283
|
+
jar_source += f", version unreported, sha256 {self._jar_digest()}"
|
|
284
|
+
self.label = f"{checker} ({jar_source})"
|
|
285
|
+
self.ready_line = f"READY TLC {self.jar}"
|
|
286
|
+
|
|
287
|
+
def _jar_digest(self):
|
|
288
|
+
try:
|
|
289
|
+
return hashlib.sha256(Path(self.jar).read_bytes()).hexdigest()
|
|
290
|
+
except OSError as error:
|
|
291
|
+
raise runner.Unavailable(f"UNAVAILABLE cannot read {self.jar}; check its permissions") from error
|
|
222
292
|
|
|
223
293
|
def _check_pinned_jar(self):
|
|
224
294
|
if not Path(self.jar).is_file():
|
|
225
295
|
raise runner.Unavailable(f"UNAVAILABLE {self.jar} is missing; save tla2tools.jar from {self.release} there, or set TLC_JAR")
|
|
226
|
-
|
|
227
|
-
got = hashlib.sha256(Path(self.jar).read_bytes()).hexdigest()
|
|
228
|
-
except OSError as error:
|
|
229
|
-
raise runner.Unavailable(f"UNAVAILABLE cannot read {self.jar}; check its permissions") from error
|
|
296
|
+
got = self._jar_digest()
|
|
230
297
|
if got != self.sha256:
|
|
231
298
|
raise runner.Unavailable(f"UNAVAILABLE {self.jar} has sha256 {got}, want {self.sha256}")
|
|
232
299
|
|
|
233
300
|
def run(self, directory, module, config, reach, workers=None, progress_label=""):
|
|
234
301
|
"""Run TLC on module in directory with config; return (exit_status, log, timed_out)."""
|
|
235
|
-
if not self._warned_disk:
|
|
236
|
-
self._warned_disk = True
|
|
237
|
-
storage.warn_runtime()
|
|
238
302
|
log = directory / "tlc.log"
|
|
239
303
|
(directory / "MC.cfg").write_text(config, encoding="utf-8")
|
|
240
304
|
chosen_workers = workers if workers is not None else ("1" if reach else self.workers)
|
|
@@ -244,39 +308,71 @@ class Tlc:
|
|
|
244
308
|
command = [self.java, "-XX:+UseParallelGC", f"-Djava.io.tmpdir={java_tmp}", "-cp", self.jar, "tlc2.TLC", "-workers", chosen_workers,
|
|
245
309
|
*(["-deadlock"] if reach else []), "-cleanup", "-metadir", str(directory / "states"),
|
|
246
310
|
"-config", str(directory / "MC.cfg"), str(directory / f"{module}.tla")]
|
|
247
|
-
|
|
248
|
-
deadline = start + self.timeout_seconds
|
|
311
|
+
return self._run_watched(command, log, progress_label)
|
|
249
312
|
|
|
250
|
-
def watch(process):
|
|
251
|
-
"""Wait for TLC, report its progress and stop it at the deadline; return its status and whether it timed out."""
|
|
252
|
-
next_report = start + PROGRESS_DELAY
|
|
253
|
-
offset, partial, latest = 0, "", ""
|
|
254
|
-
while True:
|
|
255
|
-
now = time.monotonic()
|
|
256
|
-
remaining = deadline - now
|
|
257
|
-
if remaining <= 0:
|
|
258
|
-
processes.stop_process(process)
|
|
259
|
-
return process.returncode, True
|
|
260
|
-
if now >= next_report:
|
|
261
|
-
offset, partial, found = _read_progress(log, offset, partial)
|
|
262
|
-
if found:
|
|
263
|
-
latest = found
|
|
264
|
-
elapsed = int(now - start)
|
|
265
|
-
prefix = f"[tlc] {progress_label}: " if progress_label else "[tlc] "
|
|
266
|
-
body = f"{elapsed}s elapsed: {latest}" if latest else f"{elapsed}s elapsed"
|
|
267
|
-
sys.stderr.write(f"{prefix}{body}\n")
|
|
268
|
-
sys.stderr.flush()
|
|
269
|
-
next_report = now + PROGRESS_INTERVAL
|
|
270
|
-
wait_for = min(remaining, max(0.05, next_report - time.monotonic()))
|
|
271
|
-
try:
|
|
272
|
-
process.wait(timeout=wait_for)
|
|
273
|
-
return process.returncode, False
|
|
274
|
-
except subprocess.TimeoutExpired:
|
|
275
|
-
continue
|
|
276
313
|
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
314
|
+
class Everystate(_Engine):
|
|
315
|
+
"""The native everystate engine, checked once. Nothing here downloads it."""
|
|
316
|
+
name = "everystate"
|
|
317
|
+
log_tag = "everystate"
|
|
318
|
+
min_version = (0, 4, 6)
|
|
319
|
+
min_version_text = "0.4.6"
|
|
320
|
+
release = "https://github.com/mattzcarey/everystate/releases/tag/v0.4.6"
|
|
321
|
+
remedy = (
|
|
322
|
+
f"install everystate {min_version_text} or later from {release} "
|
|
323
|
+
"(or with Homebrew, Cargo or npm) and set EVERYSTATE if it is not on PATH"
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
def __init__(self):
|
|
327
|
+
super().__init__()
|
|
328
|
+
self.binary = os.environ.get("EVERYSTATE", "").strip() or "everystate"
|
|
329
|
+
try:
|
|
330
|
+
probe = processes.run_captured([self.binary, "--version"], errors="replace")
|
|
331
|
+
status, stdout, stderr = probe.returncode, probe.stdout, probe.stderr
|
|
332
|
+
except OSError as error:
|
|
333
|
+
raise runner.Unavailable(f"UNAVAILABLE {self.binary} cannot run: {error}; {self.remedy}") from error
|
|
334
|
+
output = (stdout + stderr).strip()
|
|
335
|
+
if status:
|
|
336
|
+
detail = f"\n{output}" if output else ""
|
|
337
|
+
raise runner.Unavailable(f"UNAVAILABLE {self.binary} --version failed; {self.remedy}{detail}")
|
|
338
|
+
first_line = next((line.strip() for line in stdout.splitlines() if line.strip()), "")
|
|
339
|
+
match = EVERYSTATE_VERSION.fullmatch(first_line)
|
|
340
|
+
if not match:
|
|
341
|
+
detail = f"\n{output}" if output else ""
|
|
342
|
+
raise runner.Unavailable(f"UNAVAILABLE {self.binary} did not report an everystate version; {self.remedy}{detail}")
|
|
343
|
+
parsed = tuple(int(part) for part in match.groups())
|
|
344
|
+
self.version = ".".join(match.groups())
|
|
345
|
+
if parsed < self.min_version:
|
|
346
|
+
raise runner.Unavailable(f"UNAVAILABLE {self.binary} is everystate {self.version}, want {self.min_version_text} or later; {self.remedy}")
|
|
347
|
+
self.resolved_binary = shutil.which(self.binary) or self.binary
|
|
348
|
+
self.label = f"everystate {self.version}"
|
|
349
|
+
self.summary_suffix = f" ({self.label})"
|
|
350
|
+
self.ready_line = f"READY everystate {self.version} {self.resolved_binary}"
|
|
351
|
+
|
|
352
|
+
def run(self, directory, module, config, reach, workers=None, progress_label=""):
|
|
353
|
+
"""Run everystate on module in directory with config; return (exit_status, log, timed_out)."""
|
|
354
|
+
log = directory / "tlc.log"
|
|
355
|
+
(directory / "MC.cfg").write_text(config, encoding="utf-8")
|
|
356
|
+
chosen_workers = workers if workers is not None else ("1" if reach else self.workers)
|
|
357
|
+
# -lncheck final checks temporal properties once on the complete graph instead of at periodic checkpoints.
|
|
358
|
+
command = [
|
|
359
|
+
self.binary, "-workers", chosen_workers,
|
|
360
|
+
*(["-deadlock"] if reach else []),
|
|
361
|
+
"-lncheck", "final",
|
|
362
|
+
"-config", str(directory / "MC.cfg"),
|
|
363
|
+
str(directory / f"{module}.tla"),
|
|
364
|
+
]
|
|
365
|
+
return self._run_watched(command, log, progress_label)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def engine():
|
|
369
|
+
"""Return the selected TLA+ engine from TLC_ENGINE (default: tlc)."""
|
|
370
|
+
raw = os.environ.get("TLC_ENGINE", "").strip()
|
|
371
|
+
if not raw or raw == "tlc":
|
|
372
|
+
return Tlc()
|
|
373
|
+
if raw == "everystate":
|
|
374
|
+
return Everystate()
|
|
375
|
+
raise runner.Unavailable(f"UNAVAILABLE TLC_ENGINE={raw!r} is not supported; use 'tlc' or 'everystate'")
|
|
280
376
|
|
|
281
377
|
|
|
282
378
|
class Outcome(Enum):
|
|
@@ -298,9 +394,9 @@ class Violation:
|
|
|
298
394
|
initial: bool
|
|
299
395
|
|
|
300
396
|
|
|
301
|
-
# TLC
|
|
397
|
+
# TLC 2.19 prints "Temporal properties were violated."; newer TLC names the violated property or properties.
|
|
302
398
|
VIOLATION = re.compile(r"Error: (?:(Invariant|Property|Action property) (.+) is violated(\.| by the initial state:)"
|
|
303
|
-
r"|(Temporal)
|
|
399
|
+
r"|(Temporal) propert(?:ies(?: .+)? were|y .+ was) violated\.)")
|
|
304
400
|
|
|
305
401
|
|
|
306
402
|
def violation(error):
|
|
@@ -506,7 +602,7 @@ def render(result):
|
|
|
506
602
|
Outcome.MISSING: f"FAIL {name} {label}: spec {result.detail} not found",
|
|
507
603
|
Outcome.WITNESS: f"PASS {name} reach {operator} {label}: shortest trace {result.detail}",
|
|
508
604
|
Outcome.UNREACHED: f"FAIL {name} reach {operator} {label}: the model never reaches this state",
|
|
509
|
-
Outcome.INCOMPLETE: f"FAIL {name} reach {operator} {label}: TLC did not complete the reach check",
|
|
605
|
+
Outcome.INCOMPLETE: f"FAIL {name} reach {operator} {label}: {result.detail or 'TLC did not complete the reach check'}",
|
|
510
606
|
Outcome.NO_RUN: f"FAIL {name} reach {operator}: no run matching '{result.detail}'",
|
|
511
607
|
Outcome.MALFORMED: f"FAIL {result.detail}",
|
|
512
608
|
}[result.outcome]
|
|
@@ -543,6 +639,7 @@ def run_task(checker, matrix_dir, task, work, source=None, traces=False):
|
|
|
543
639
|
config = f"CONSTANTS\n{constants}SPECIFICATION Spec\n"
|
|
544
640
|
if not task.check_deadlock:
|
|
545
641
|
config += "CHECK_DEADLOCK FALSE\n"
|
|
642
|
+
engine_name = getattr(checker, "name", "TLC")
|
|
546
643
|
if not operator:
|
|
547
644
|
start = time.monotonic()
|
|
548
645
|
status, log, timed_out = checker.run(
|
|
@@ -551,7 +648,7 @@ def run_task(checker, matrix_dir, task, work, source=None, traces=False):
|
|
|
551
648
|
)
|
|
552
649
|
elapsed = time.monotonic() - start
|
|
553
650
|
shutil.rmtree(directory / "states", ignore_errors=True)
|
|
554
|
-
result = ordinary(name, run, status, log, checker.limit if timed_out else None, traces)
|
|
651
|
+
result = ordinary(name, run, status, log, checker.limit if timed_out else None, traces, engine_name=engine_name)
|
|
555
652
|
return replace(result, constants=run_constants, checks=run_checks, duration_s=elapsed)
|
|
556
653
|
wrapper = f"Reach{uuid.uuid4().hex}"
|
|
557
654
|
invariant = f"{wrapper}Negated"
|
|
@@ -564,18 +661,18 @@ def run_task(checker, matrix_dir, task, work, source=None, traces=False):
|
|
|
564
661
|
reach=True, workers=reach_workers, progress_label=f"{name} reach {operator} {run.label}",
|
|
565
662
|
)
|
|
566
663
|
elapsed = time.monotonic() - start
|
|
567
|
-
result = witness(name, run, operator, invariant, status, log, checker.limit if timed_out else None, traces)
|
|
664
|
+
result = witness(name, run, operator, invariant, status, log, checker.limit if timed_out else None, traces, engine_name=engine_name)
|
|
568
665
|
return replace(result, constants=run_constants, checks=run_checks, duration_s=elapsed)
|
|
569
666
|
finally:
|
|
570
667
|
shutil.rmtree(directory, ignore_errors=True)
|
|
571
668
|
|
|
572
669
|
|
|
573
670
|
|
|
574
|
-
def ordinary(name, run, status, log, timeout_limit=None, traces=False):
|
|
671
|
+
def ordinary(name, run, status, log, timeout_limit=None, traces=False, *, engine_name="TLC"):
|
|
575
672
|
if timeout_limit:
|
|
576
673
|
tail = tuple(line for line in log.split("\n") if line.strip())[-10:]
|
|
577
674
|
return Result(Outcome.FAIL, name, run.label,
|
|
578
|
-
detail=f"
|
|
675
|
+
detail=f"{engine_name} timed out after {timeout_limit}; set TLC_TIMEOUT to change the limit", lines=tail)
|
|
579
676
|
if status == 0 and "No error has been found" in log:
|
|
580
677
|
found = re.findall(r"[0-9,]* distinct states found", log)
|
|
581
678
|
states = found[-1] if found else ""
|
|
@@ -586,11 +683,12 @@ def ordinary(name, run, status, log, timeout_limit=None, traces=False):
|
|
|
586
683
|
violation=violation(first), trace=tlc_trace.parse(re.split(r"\r\n|\r|\n", log)) if traces else None)
|
|
587
684
|
|
|
588
685
|
|
|
589
|
-
def witness(name, run, operator, invariant, status, log, timeout_limit=None, traces=False):
|
|
686
|
+
def witness(name, run, operator, invariant, status, log, timeout_limit=None, traces=False, *, engine_name="TLC"):
|
|
687
|
+
incomplete = f"{engine_name} did not complete the reach check"
|
|
590
688
|
if timeout_limit:
|
|
591
689
|
tail = tuple(line for line in log.split("\n") if line.strip())[-10:]
|
|
592
|
-
return Result(Outcome.INCOMPLETE, name, run.label, operator,
|
|
593
|
-
lines=(f"
|
|
690
|
+
return Result(Outcome.INCOMPLETE, name, run.label, operator, detail=incomplete,
|
|
691
|
+
lines=(f"{engine_name} timed out after {timeout_limit}; set TLC_TIMEOUT to change the limit", *tail))
|
|
594
692
|
lines = log.split("\n")
|
|
595
693
|
length = 0
|
|
596
694
|
if status == 12 and f"Error: Invariant {invariant} is violated by the initial state:" in lines:
|
|
@@ -602,7 +700,8 @@ def witness(name, run, operator, invariant, status, log, timeout_limit=None, tra
|
|
|
602
700
|
trace=tlc_trace.parse(re.split(r"\r\n|\r|\n", log)) if traces else None)
|
|
603
701
|
if status == 0 and "No error has been found" in log:
|
|
604
702
|
return Result(Outcome.UNREACHED, name, run.label, operator)
|
|
605
|
-
return Result(Outcome.INCOMPLETE, name, run.label, operator,
|
|
703
|
+
return Result(Outcome.INCOMPLETE, name, run.label, operator, detail=incomplete,
|
|
704
|
+
lines=tuple(log.removesuffix("\n").split("\n")) if log else ())
|
|
606
705
|
|
|
607
706
|
|
|
608
707
|
class Runner:
|
|
@@ -687,7 +786,7 @@ def validate_report_path(raw: str) -> Path | None:
|
|
|
687
786
|
|
|
688
787
|
def main():
|
|
689
788
|
if sys.argv[1:] == ["ready"]:
|
|
690
|
-
print(
|
|
789
|
+
print(engine().ready_line)
|
|
691
790
|
storage.report()
|
|
692
791
|
return 0
|
|
693
792
|
if not 2 <= len(sys.argv) <= 3:
|
|
@@ -697,10 +796,11 @@ def main():
|
|
|
697
796
|
if not Path(matrix).is_file():
|
|
698
797
|
print(f"FAIL {matrix} does not exist")
|
|
699
798
|
return 1
|
|
700
|
-
|
|
799
|
+
checker = engine()
|
|
701
800
|
report_path = validate_report_path(os.environ.get("TLC_HTML_REPORT", ""))
|
|
702
801
|
with tempfile.TemporaryDirectory(dir=storage.ensure_temp_root()) as work:
|
|
703
|
-
|
|
802
|
+
print(f"ENGINE {checker.label}", flush=True)
|
|
803
|
+
matrix_runner = Runner(checker, Path(matrix).resolve().parent, only, lambda result: print("\n".join(render(result)), flush=True), Path(work),
|
|
704
804
|
keep_results=report_path is not None)
|
|
705
805
|
for task in MatrixPlan(matrix):
|
|
706
806
|
matrix_runner.check(task)
|
|
@@ -711,13 +811,13 @@ def main():
|
|
|
711
811
|
summary = f"SUMMARY {matrix_runner.passed} of {matrix_runner.runs_total} runs passed"
|
|
712
812
|
if matrix_runner.reach_total:
|
|
713
813
|
summary += f", {matrix_runner.reached} of {matrix_runner.reach_total} reach checks passed"
|
|
714
|
-
summary_line = f"{summary}, {matrix_runner.states} distinct states in total"
|
|
814
|
+
summary_line = f"{summary}, {matrix_runner.states} distinct states in total{checker.summary_suffix}"
|
|
715
815
|
print(summary_line)
|
|
716
816
|
if report_path is not None:
|
|
717
817
|
import tlc_report
|
|
718
818
|
|
|
719
819
|
try:
|
|
720
|
-
tlc_report.write_html(report_path, Path(matrix).name, matrix_runner.results, summary_line, only=only)
|
|
820
|
+
tlc_report.write_html(report_path, Path(matrix).name, matrix_runner.results, summary_line, only=only, engine=checker.label)
|
|
721
821
|
except OSError as error:
|
|
722
822
|
# A failed run's status wins over a report that could not be written.
|
|
723
823
|
print(f"UNAVAILABLE TLC_HTML_REPORT={str(report_path)!r} could not be written: {error}; {REPORT_REMEDY}")
|
|
@@ -457,8 +457,8 @@ def _trace_card(idx: int, result: object) -> str:
|
|
|
457
457
|
])
|
|
458
458
|
|
|
459
459
|
|
|
460
|
-
def render_html(matrix_name: str, results: list, summary: str, *, only: str = "", generated_at: str | None = None) -> str:
|
|
461
|
-
"""Render a complete, self-contained HTML5 report for a
|
|
460
|
+
def render_html(matrix_name: str, results: list, summary: str, *, only: str = "", engine: str = "", generated_at: str | None = None) -> str:
|
|
461
|
+
"""Render a complete, self-contained HTML5 report for a TLA+ matrix run."""
|
|
462
462
|
# A file name argument that is not UTF-8 arrives with lone surrogates, which the UTF-8 page cannot hold.
|
|
463
463
|
matrix_name = os.fsencode(matrix_name).decode("utf-8", "replace")
|
|
464
464
|
timestamp = generated_at or time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
|
@@ -466,7 +466,16 @@ def render_html(matrix_name: str, results: list, summary: str, *, only: str = ""
|
|
|
466
466
|
overall = "FAIL" if has_failure else "PASS"
|
|
467
467
|
overall_cls = "badge-fail" if has_failure else "badge-pass"
|
|
468
468
|
total_s = sum(r.duration_s for r in results)
|
|
469
|
-
|
|
469
|
+
engine_title = "everystate" if engine.startswith("everystate") else "TLC"
|
|
470
|
+
meta_items = []
|
|
471
|
+
if engine:
|
|
472
|
+
meta_items.append(f" <span>Engine: <code>{_esc(engine)}</code></span>")
|
|
473
|
+
meta_items.extend([
|
|
474
|
+
f" <span>Total duration: <strong>{total_s:.2f}s</strong></span>",
|
|
475
|
+
f" <span>Generated (UTC): <code>{_esc(timestamp)}</code></span>",
|
|
476
|
+
])
|
|
477
|
+
if only:
|
|
478
|
+
meta_items.append(f" <span>Filter: <code>{_esc(only)}</code></span>")
|
|
470
479
|
rows_html = "\n".join(_table_row(idx, r) for idx, r in enumerate(results))
|
|
471
480
|
trace_cards = [_trace_card(idx, r) for idx, r in enumerate(results) if r.trace is not None and bool(r.trace.steps)]
|
|
472
481
|
traces_html = "\n".join(trace_cards) if trace_cards else '<p class="empty-note">There are no counter-example or witness traces for this run.</p>'
|
|
@@ -476,21 +485,19 @@ def render_html(matrix_name: str, results: list, summary: str, *, only: str = ""
|
|
|
476
485
|
"<head>",
|
|
477
486
|
' <meta charset="utf-8">',
|
|
478
487
|
' <meta name="viewport" content="width=device-width, initial-scale=1">',
|
|
479
|
-
f" <title>
|
|
488
|
+
f" <title>{engine_title} Report — {_esc(matrix_name)}</title>",
|
|
480
489
|
f" <style>{_STYLE}</style>",
|
|
481
490
|
"</head>",
|
|
482
491
|
"<body>",
|
|
483
492
|
' <main class="page">',
|
|
484
493
|
' <section class="card">',
|
|
485
494
|
' <div class="header-top">',
|
|
486
|
-
f" <h1>
|
|
495
|
+
f" <h1>{engine_title} Matrix Report: {_esc(matrix_name)}</h1>",
|
|
487
496
|
f' <span class="badge {overall_cls}">{overall}</span>',
|
|
488
497
|
" </div>",
|
|
489
498
|
f" <p>{_esc(summary)}</p>",
|
|
490
499
|
' <div class="meta">',
|
|
491
|
-
|
|
492
|
-
f" <span>Generated (UTC): <code>{_esc(timestamp)}</code></span>",
|
|
493
|
-
f" {filter_html}",
|
|
500
|
+
*meta_items,
|
|
494
501
|
" </div>",
|
|
495
502
|
" </section>",
|
|
496
503
|
' <section class="card">',
|
|
@@ -509,8 +516,8 @@ def render_html(matrix_name: str, results: list, summary: str, *, only: str = ""
|
|
|
509
516
|
])
|
|
510
517
|
|
|
511
518
|
|
|
512
|
-
def write_html(path: Path, matrix_name: str, results: list, summary: str, *, only: str = "") -> Path:
|
|
519
|
+
def write_html(path: Path, matrix_name: str, results: list, summary: str, *, only: str = "", engine: str = "") -> Path:
|
|
513
520
|
"""Render the HTML report and write it atomically to path."""
|
|
514
521
|
target = Path(path)
|
|
515
|
-
runner.atomic_write(target, render_html(matrix_name, results, summary, only=only))
|
|
522
|
+
runner.atomic_write(target, render_html(matrix_name, results, summary, only=only, engine=engine))
|
|
516
523
|
return target
|
package/skills/setup/SKILL.md
CHANGED
|
@@ -17,7 +17,7 @@ Prepare the complete shared toolset once, independently of any repository. Verif
|
|
|
17
17
|
|
|
18
18
|
```shell
|
|
19
19
|
bash <skill-dir>/scripts/setup.sh rust
|
|
20
|
-
bash <skill-dir>/scripts/setup.sh tla
|
|
20
|
+
TLC_ENGINE=tlc TLC_JAR= bash <skill-dir>/scripts/setup.sh tla
|
|
21
21
|
bash <skill-dir>/scripts/setup.sh lean <skill-dir>/examples/lean-template
|
|
22
22
|
```
|
|
23
23
|
|