agent-formal-verify 0.4.10 → 0.4.12
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/README.md +11 -3
- package/package.json +1 -1
- package/skills/formal-verify/SKILL.md +8 -26
- package/skills/formal-verify/references/evidence.md +20 -0
- package/skills/formal-verify/references/helpers.md +10 -0
- package/skills/formal-verify/references/lean-brief.md +1 -1
- package/skills/formal-verify/references/rust-brief.md +37 -5
- package/skills/formal-verify/references/setup.md +2 -0
- package/skills/formal-verify/references/tla-brief.md +1 -1
- package/skills/formal-verify/scripts/baseline.py +79 -18
- package/skills/formal-verify/scripts/kani.py +97 -63
- package/skills/formal-verify/scripts/lean-check.sh +1 -0
- package/skills/formal-verify/scripts/lean-statements.py +4 -0
- package/skills/formal-verify/scripts/mutate.py +60 -38
- package/skills/formal-verify/scripts/tlc.py +3 -0
package/CHANGES.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# Changes
|
|
2
2
|
|
|
3
|
+
## 0.4.12 - Kani harness time limits checked before any harness runs
|
|
4
|
+
|
|
5
|
+
The Rust checker, the mutation runner and `setup.sh rust` now check `KANI_HARNESS_TIMEOUT` before Kani runs. The setting takes a whole number from 1 to 4294967295 with an optional unit `s`, `m` or `h`, as Kani 0.68.0 reads it, and spaces around the value are ignored. For any other value, including `0`, the helpers print `UNAVAILABLE` and check no harness. Before this change, `0` stopped every harness at once, and a value that Kani rejects failed every harness with a message about a missing result file. The limit cannot be turned off, so set a long one, such as `24h`, instead. A harness that reaches the limit fails with a message that names the limit with its unit, such as `90s` for a value of `90`, and the setting that changes it. The setup guide says that each harness check can take up to the limit, so run the Rust checker and the mutation runner in the background or with a command timeout longer than the total.
|
|
6
|
+
|
|
7
|
+
## 0.4.11 - Antigravity install, stricter verdicts and a Kani harness time limit
|
|
8
|
+
|
|
9
|
+
Kani now checks the configured crate and requires a satisfied cover witness for each passing harness. Each Rust mutation starts from a passing harness. Coverage is checked per harness source file, and the checker supports Kani stubs. A missing toolchain version file no longer hides the original compiler error.
|
|
10
|
+
|
|
11
|
+
TLC mutations use the runs that actually enable their named property. Temporal mutations must violate that property to count as detected. TLA+ baselines now follow local module imports. Review and record older matrix baselines again. Lean now fingerprints opaque definition bodies. Review and re-freeze older statements records that contain an opaque definition.
|
|
12
|
+
|
|
13
|
+
The plugin now installs in Antigravity with `agy plugin install`. The `.antigravity-plugin/plugin.json` manifest exposes the `setup` and `formal-verify` skills from `skills/` and adds no hooks or MCP servers. Antigravity loads only the first 24,000 bytes of a skill body, which cut off most of the formal-verify reply instructions. The helper reference and the table of evidence meanings moved from `SKILL.md` to `references/helpers.md` and `references/evidence.md`, which the skill tells the agent to read, and a test keeps each skill body within that limit.
|
|
14
|
+
|
|
15
|
+
When a crate uses a standard library feature that is newer than the toolchain bundled with Kani 0.68.0, Kani discovery fails with E0658. The Rust checker and the mutation runner now add a note to that failure. The note names the bundled toolchain and says to rewrite harness code that uses the feature. When every error is in production code or a dependency, it says to report the target as not checked, because the feature attribute that the compiler suggests would change the production crate. The Rust brief says the same.
|
|
16
|
+
|
|
17
|
+
The Rust checker and the mutation runner now stop each Kani harness after five minutes, through Kani's own harness timeout, which also stops the CBMC solver. Set `KANI_HARNESS_TIMEOUT` to change the limit, for example to `90s` or `20m`. A harness that reaches the limit fails with a message that names the setting, and a mutation that reaches it gets no verdict, so it never counts as detected. Before this change, a harness whose symbolic inputs reached message-formatting error paths or a wide symbolic division could run with no output until something else stopped it.
|
|
18
|
+
|
|
19
|
+
The repository now tells Git to check out text files with LF line endings on every platform. A Windows clone with `core.autocrlf=true` used to get CRLF line endings in the Bash helpers.
|
|
20
|
+
|
|
3
21
|
## 0.4.10 - baselines keep each check's run and each Kani constraint's function
|
|
4
22
|
|
|
5
23
|
The specification baseline now records the checks that apply to each TLA+ run and the inputs selected by each reach check. Moving check lines below a run or changing which run a reach check selects no longer compares unchanged. Kani assumptions, covers and stubs now retain their qualified owning function, and harness names include their modules, so moving a constraint between functions is reported. The Rust reader supports free functions under inline modules and rejects Kani forms in an owner it cannot identify, including macro definitions and implementation or trait bodies. Baseline records use format 2; create a new record after updating rather than reuse a format 1 record.
|
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
<a href="https://github.com/michael-denyer/agent-formal-verify/actions/workflows/ci.yml"><img src="https://github.com/michael-denyer/agent-formal-verify/actions/workflows/ci.yml/badge.svg" alt="CI" width="8.91%"><img src="assets/badge-gap.svg" alt="" width="0.75%"></a><a href="CHANGES.md"><img src="https://img.shields.io/github/package-json/v/michael-denyer/agent-formal-verify?color=0969DA" alt="Version" width="9.5%"><img src="assets/badge-gap.svg" alt="" width="0.75%"></a><a href="LICENSE"><img src="https://img.shields.io/badge/license-GPL--3.0--only-6B7280" alt="License: GPL-3.0-only" width="12.87%"><img src="assets/badge-gap.svg" alt="" width="0.75%"></a><a href="#claude-code"><img src="https://img.shields.io/badge/Claude%20Code-plugin-D97757" alt="Claude Code plugin" width="12.07%"><img src="assets/badge-gap.svg" alt="" width="0.75%"></a><a href="#codex"><img src="https://img.shields.io/badge/Codex-plugin-10A37F" alt="Codex plugin" width="8.71%"><img src="assets/badge-gap.svg" alt="" width="0.75%"></a><a href="#pi"><img src="https://img.shields.io/badge/Pi-package-7C3AED" alt="Pi package" width="7.33%"><img src="assets/badge-gap.svg" alt="" width="0.75%"></a><a href="#opencode"><img src="https://img.shields.io/badge/OpenCode-plugin-211E1E" alt="OpenCode plugin" width="10.89%"><img src="assets/badge-gap.svg" alt="" width="0.75%"></a><a href="https://github.com/tlaplus/tlaplus"><img src="https://img.shields.io/badge/TLA%2B-TLC-2E6DB4" alt="TLA+ and TLC" width="6.93%"><img src="assets/badge-gap.svg" alt="" width="0.75%"></a><a href="https://lean-lang.org"><img src="https://img.shields.io/badge/Lean%204-proofs-0F9D9A" alt="Lean 4" width="9.11%"><img src="assets/badge-gap.svg" alt="" width="0.75%"></a><a href="https://github.com/model-checking/kani"><img src="https://img.shields.io/badge/Kani-Rust-B7410E" alt="Kani" width="6.93%"></a>
|
|
8
8
|
</p>
|
|
9
9
|
|
|
10
|
-
A skill for Claude Code, Codex, Pi and
|
|
10
|
+
A skill for Claude Code, Codex, Pi, OpenCode and Antigravity that implements the targeted formal-verification method [recently promoted by Boris Cherny](https://x.com/bcherny/status/2102543349102338309). The agent models selected parts of your code, checks their properties, maps counter-examples to source lines, and helps reproduce and fix reachable bugs.
|
|
11
11
|
|
|
12
12
|
It uses TLA+ and TLC for thread interleavings, shutdown and resource ownership, and Lean 4 for arithmetic, bounds and sequential state transitions. A protocol that depends on arithmetic can use both. For Rust functions with bounded inputs and loops, Kani checks the production code for overflow, invalid memory access, panics and broken invariants.
|
|
13
13
|
|
|
@@ -51,7 +51,15 @@ opencode plugin add agent-formal-verify
|
|
|
51
51
|
|
|
52
52
|
To install from Git instead, use `opencode plugin add 'git+https://github.com/michael-denyer/agent-formal-verify.git'`.
|
|
53
53
|
|
|
54
|
-
|
|
54
|
+
### Antigravity
|
|
55
|
+
|
|
56
|
+
Clone or check out the repository, then run in your terminal:
|
|
57
|
+
|
|
58
|
+
```shell
|
|
59
|
+
agy plugin install /absolute/path/to/agent-formal-verify
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Run `setup` once to prepare the shared Java, Python, TLC, elan, Lean, Rust and Kani tools. In Claude Code, use `/agent-formal-verify:setup`. In Codex, request the plugin's `setup` skill. In Pi, use `/skill:setup`. In OpenCode or Antigravity, request the `setup` skill. It reuses installed prerequisites and needs no target repository.
|
|
55
63
|
|
|
56
64
|
For local checkouts and skills-only installs, see [shared installation](docs/reference.md#shared-installation).
|
|
57
65
|
|
|
@@ -61,7 +69,7 @@ For local checkouts and skills-only installs, see [shared installation](docs/ref
|
|
|
61
69
|
Use formal-verify to check this queue's shutdown protocol and window arithmetic.
|
|
62
70
|
```
|
|
63
71
|
|
|
64
|
-
In Claude Code, use `/agent-formal-verify:formal-verify`. In Codex, type `$formal-verify` or request the plugin's `formal-verify` skill. In Pi, use `/skill:formal-verify`. In OpenCode, request the `formal-verify` skill.
|
|
72
|
+
In Claude Code, use `/agent-formal-verify:formal-verify`. In Codex, type `$formal-verify` or request the plugin's `formal-verify` skill. In Pi, use `/skill:formal-verify`. In OpenCode or Antigravity, request the `formal-verify` skill.
|
|
65
73
|
|
|
66
74
|
## How it works
|
|
67
75
|
|
package/package.json
CHANGED
|
@@ -66,14 +66,14 @@ Require a successful exit and a `READY` line from each command. A helper that ca
|
|
|
66
66
|
|
|
67
67
|
If a system prerequisite such as Java or elan is missing, use the [setup skill](../setup/SKILL.md) to prepare it within the user's installation constraints and existing authorization. Report any prerequisite that cannot be prepared. If `java` on PATH has no runtime, set `JAVA` to a working JDK's `java` binary for the setup helper and the matrix runner.
|
|
68
68
|
|
|
69
|
-
The helpers:
|
|
69
|
+
Read the [helper reference](references/helpers.md) before you interpret a helper's output. The helpers:
|
|
70
70
|
|
|
71
|
-
- The setup helper, [`scripts/setup.sh`](scripts/setup.sh)
|
|
72
|
-
- The matrix runner, [`scripts/tlc-matrix.sh`](scripts/tlc-matrix.sh)
|
|
73
|
-
- The Lean checker, [`scripts/lean-check.sh`](scripts/lean-check.sh)
|
|
74
|
-
- The Rust checker, [`scripts/kani-check.sh`](scripts/kani-check.sh)
|
|
75
|
-
- The mutation runner, [`scripts/mutate.py`](scripts/mutate.py)
|
|
76
|
-
- The baseline helper, [`scripts/baseline.py`](scripts/baseline.py)
|
|
71
|
+
- The setup helper, [`scripts/setup.sh`](scripts/setup.sh): verifies the pinned TLC JAR (`tla`), checks Kani (`rust`), and installs a missing Lean toolchain (`lean`).
|
|
72
|
+
- The matrix runner, [`scripts/tlc-matrix.sh`](scripts/tlc-matrix.sh) and [`scripts/tlc-trace.py`](scripts/tlc-trace.py): run TLC across a `.matrix` of constants and reduce failing traces. Template: [`examples/tla-template/`](examples/tla-template/BoundedQueue.tla).
|
|
73
|
+
- The Lean checker, [`scripts/lean-check.sh`](scripts/lean-check.sh): builds and audits `.lean` models, checks `<Property>.witness` theorems, replays modules through `leanchecker`, and freezes specifications with `--freeze`. Template: [`examples/lean-template/Model/BoundedQueue.lean`](examples/lean-template/Model/BoundedQueue.lean).
|
|
74
|
+
- The Rust checker, [`scripts/kani-check.sh`](scripts/kani-check.sh): runs the pinned Kani across the crate's proof harnesses and prints concrete playback tests. Template: [`examples/kani-template/`](examples/kani-template/src/lib.rs).
|
|
75
|
+
- The mutation runner, [`scripts/mutate.py`](scripts/mutate.py): tests `<Name>.mutations` against copied models (`DETECTED`, `MISSED`, `UNCOVERED`).
|
|
76
|
+
- The baseline helper, [`scripts/baseline.py`](scripts/baseline.py): snapshots and compares model specifications (`record` and `compare`).
|
|
77
77
|
|
|
78
78
|
Run every existing model's checker and mutations once, before any agent changes a model, and record the results. Then record what the models specify with `python3 <skill-dir>/scripts/baseline.py record <record-file> <model files>`, naming each existing `.matrix`, `.statements` and Kani harness file. Put `<record-file>` in a temporary directory outside the repository, and leave its path out of every brief. For a TLA+ or Lean model a pass shows only that the old description still holds; a Kani harness runs the code as it is now. A model that still describes the code needs no agent. When it passes, refresh its header as step 5 says; when it fails, take the failure through step 4. A Kani compile error means the harness no longer fits the code, so give it to an agent. An UNCOVERED line means the mutations file lacks a bug that the property detects, not that the code fails; give the model to an agent to add one. A check that passes here and fails after the update was passing on a stale description; say so in the reply.
|
|
79
79
|
|
|
@@ -139,25 +139,7 @@ Write the reply, and any pull request or document, for a reader who knows the co
|
|
|
139
139
|
|
|
140
140
|
1. Start with what was found, in the code's terms. For each bug, say what goes wrong for a caller or user, the code events in order with `file:line`, whether the shipped settings can reach it, how to reproduce it, and the fix or proposed fix, with a PR link when one was opened.
|
|
141
141
|
2. Give a table with one row per target: what was checked, as a sentence about the code, and the verdict. Label each counter-example `reproduced`, `reachable at shipped settings`, or `model-only`. State each property as what it guarantees, such as "the bar never shows 100% before the work finishes". Add the model's name for it in backticks only so the reader can find it. For a model from an earlier run, add whether it was unchanged or updated, or is proposed for retirement, with its sync commit and the commits read for it. For each model, say whether its properties were reviewed, how many of the reviewer's mutations were detected and missed, and the reviewer's open questions.
|
|
142
|
-
3.
|
|
143
|
-
|
|
144
|
-
| Evidence | Meaning to give |
|
|
145
|
-
| --- | --- |
|
|
146
|
-
| 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. |
|
|
147
|
-
| Kani passes | Kani checked every input within the stated bounds and found no violation. Larger inputs are not covered. |
|
|
148
|
-
| Lean passes | Lean proved the property for every input, under the listed assumptions. |
|
|
149
|
-
| 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. |
|
|
150
|
-
| Witness checked | A Lean proof shows that some concrete values satisfy all of a property's hypotheses at once, so the property is not true merely because nothing meets its conditions. `absent` and `unavailable` mean this was not checked. |
|
|
151
|
-
| A bounded search passes | Every input up to the stated bound was tried. |
|
|
152
|
-
| 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. |
|
|
153
|
-
| 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. |
|
|
154
|
-
| Specification unchanged | The baseline comparison preserved each recorded run's inputs and checks, reach check's selected inputs, property and fairness definition, statement record, qualified Kani harness name and function-owned assumption, cover and stub. It does not cover a Kani harness's assertions, input construction, surrounding guards or calls to assumption helpers; `git diff` does. |
|
|
155
|
-
| UNAVAILABLE | The tool could not run. This target was not checked; give the printed remedy. |
|
|
156
|
-
| reproduced | A deterministic test or race-detector run fails on the production code. |
|
|
157
|
-
| reachable at shipped settings | The shipped constants and callers permit the counter-example, but no production reproduction has confirmed it yet. |
|
|
158
|
-
| model-only | The counter-example needs a configuration or caller the shipped code does not use. |
|
|
159
|
-
| Counter-example | A step-by-step schedule or an input that breaks the property. |
|
|
160
|
-
|
|
142
|
+
3. Read [evidence meanings](references/evidence.md) and state the matching meaning where each kind of evidence first appears.
|
|
161
143
|
4. Give a term of any tool its meaning beside it: an invariant is always true, a liveness property says something eventually happens, fairness assumes a thread that can run does run, an axiom is taken without proof, and `sorry` marks an unfinished proof.
|
|
162
144
|
5. Say what a pass leaves open: the sizes TLC checked, the code constraints the model omits, each theorem's hypotheses and integer widths, and the properties that could not be expressed.
|
|
163
145
|
6. End with the commands to recheck and their SUMMARY and PASS lines.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Evidence meanings
|
|
2
|
+
|
|
3
|
+
Include the matching meaning from this table where each kind of evidence first appears in a reply, pull request or document:
|
|
4
|
+
|
|
5
|
+
| Evidence | Meaning to give |
|
|
6
|
+
| --- | --- |
|
|
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
|
+
| Kani passes | Kani checked every input within the stated bounds and found no violation. Larger inputs are not covered. |
|
|
9
|
+
| Lean passes | Lean proved the property for every input, under the listed assumptions. |
|
|
10
|
+
| 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. |
|
|
11
|
+
| Witness checked | A Lean proof shows that some concrete values satisfy all of a property's hypotheses at once, so the property is not true merely because nothing meets its conditions. `absent` and `unavailable` mean this was not checked. |
|
|
12
|
+
| A bounded search passes | Every input up to the stated bound was tried. |
|
|
13
|
+
| 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
|
+
| 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, statement record, qualified Kani harness name and function-owned assumption, cover and stub. It does not cover a Kani harness's assertions, input construction, surrounding guards or calls to assumption helpers; `git diff` does. |
|
|
16
|
+
| UNAVAILABLE | The tool could not run. This target was not checked; give the printed remedy. |
|
|
17
|
+
| reproduced | A deterministic test or race-detector run fails on the production code. |
|
|
18
|
+
| reachable at shipped settings | The shipped constants and callers permit the counter-example, but no production reproduction has confirmed it yet. |
|
|
19
|
+
| model-only | The counter-example needs a configuration or caller the shipped code does not use. |
|
|
20
|
+
| Counter-example | A step-by-step schedule or an input that breaks the property. |
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# Helpers
|
|
2
|
+
|
|
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
|
+
|
|
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 and prints one `PASS` or `FAIL` per run with its state count, then a `SUMMARY` line with the totals. A failing run prints its error trace reduced by [`scripts/tlc-trace.py`](../scripts/tlc-trace.py) to the variables each step changed. 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. Use `--freeze` before the file names to record statement types and definition bodies in each model's `.statements` file before proving it. Freezing permits `sorry` and reports `FROZEN`, not a proof `PASS`. Later checks enforce those records and permit proof changes and added declarations. Given file names after the project, it checks only those files. Copy [`examples/lean-template/Model/BoundedQueue.lean`](../examples/lean-template/Model/BoundedQueue.lean) to start a model.
|
|
8
|
+
- **Rust checker ([`scripts/kani-check.sh`](../scripts/kani-check.sh))**: runs the pinned Kani on the crate's proof harnesses. It reports each harness's unwind bound and check count, requires a satisfied cover witness in each passing harness, rejects failed checks, and prints concrete playback tests when available. It stops each harness after five minutes, or after the limit in `KANI_HARNESS_TIMEOUT` as [setup](setup.md) describes, and fails a harness that reaches the limit with a message that names the setting. Each harness check, here or in the mutation runner, can take up to that limit, so run the command in the background or with a command timeout longer than the total. 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. So does a Kani mutation whose harness reaches the Rust checker's time limit. 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
|
+
- **Baseline helper ([`scripts/baseline.py`](../scripts/baseline.py))**: records what each model specifies and later names each part that changed. For TLA+ it records each run's inputs and effective checks, each reach check's selected run and inputs, and the definitions of `Spec`, of the checked and reach operators, and of the operators those reference, including the initial state. It resolves operators through sibling modules named by `EXTENDS`, including transitive imports. When a local `INSTANCE` introduces substitutions or an imported module has indented definitions that the reader cannot resolve, it compares the complete local module texts with comments and formatting removed, so edits to unrelated definitions in those modules also need review. A matrix recorded before import tracking needs review and a fresh record. It shares the matrix runner's execution plan, so a check applies only to the runs after it in its section. It does not follow `Spec` into the actions it names under `[][...]_vars`, `WF_` or `SF_`, because every correction of the transcription changes them. An operator that `Spec` names outside those, such as a fairness definition, is followed into its actions. A column-0 definition whose header it cannot read, such as an infix operator, is recorded whether or not a property references it, with the operators it references. For Lean it records the `.statements` file. For Kani it records each qualified harness name and each `kani::assume`, `kani::any_where`, `kani::cover!` and `#[kani::stub]` with its qualified owning function, including helper functions. The Rust reader supports free functions under inline modules; a Kani form in a macro, implementation or trait body, or another owner it cannot identify, fails the record. A spelling it cannot read, such as an import that renames `kani::assume`, also fails. It does not record a harness's assertions, input construction, surrounding guards or calls to assumption helpers; read `git diff` for those. Create a new record after updating the helper if it reports an unsupported record format.
|
|
@@ -42,7 +42,7 @@ bash <skill-dir>/scripts/lean-check.sh <absolute-project-path> Model/<Name>.lean
|
|
|
42
42
|
python3 <skill-dir>/scripts/mutate.py <absolute-project-path>/Model/<Name>.mutations
|
|
43
43
|
```
|
|
44
44
|
|
|
45
|
-
The checker enforces the `.statements` file beside each checked source. Changing a theorem type, a definition type or body, or deleting a frozen declaration fails with its name. Adding lemmas and definitions and changing proofs is allowed. Re-freeze only after the production code changes, after a production test contradicts the transcription, after reviewing a toolchain bump, or after the main thread accepts a specification correction under step 3 of the skill. Record the evidence, the old and new guarantees, and the reason for re-freezing in the report. Records are specific to the pinned Lean toolchain. Fingerprints use structural expressions, including the module identity of private references. If two private declarations share a name in one model, give them distinct names before freezing. A project-wide check also rejects records whose source files were deleted. Named-file checks remain limited to those files. A model without a record retains the usual proof and axiom checks, so keep the records under version control. Deleting a record removes that protection.
|
|
45
|
+
The checker enforces the `.statements` file beside each checked source. Changing a theorem type, a definition type or body (including an opaque definition), or deleting a frozen declaration fails with its name. Adding lemmas and definitions and changing proofs is allowed. Re-freeze only after the production code changes, after a production test contradicts the transcription, after reviewing a toolchain bump, or after the main thread accepts a specification correction under step 3 of the skill. Older records that lack opaque body hashes also require reviewing those definitions and explicitly re-freezing before they can pass. Record the evidence, the old and new guarantees, and the reason for re-freezing in the report. Records are specific to the pinned Lean toolchain. Fingerprints use structural expressions, including the module identity of private references. If two private declarations share a name in one model, give them distinct names before freezing. A project-wide check also rejects records whose source files were deleted. Named-file checks remain limited to those files. A model without a record retains the usual proof and axiom checks, so keep the records under version control. Deleting a record removes that protection.
|
|
46
46
|
|
|
47
47
|
The file name limits the Lean checker to your model, so another agent's unfinished file does not fail your check.
|
|
48
48
|
|
|
@@ -38,13 +38,25 @@ integer widths, input bounds and each assumption beside the harness. If a callee
|
|
|
38
38
|
needs a stub or a function contract, name that assumption in the header comment.
|
|
39
39
|
Put `#[kani::unwind(N)]` on every harness, above its real loop bounds. The checker
|
|
40
40
|
requires this explicit bound and passes it to Kani. A failed unwinding assertion
|
|
41
|
-
means the bound is too low and fails the check.
|
|
41
|
+
means the bound is too low and fails the check. Discovery and verification both
|
|
42
|
+
enable `-Z stubbing`, so documented `#[kani::stub]` attributes work in either step.
|
|
43
|
+
|
|
44
|
+
Kani stops a harness at `KANI_HARNESS_TIMEOUT`, five minutes by default. Symbolic
|
|
45
|
+
inputs that reach an error constructor that builds a message with `format!`, or
|
|
46
|
+
a wide division by a symbolic divisor, can stop the solver finishing within it. Give
|
|
47
|
+
those parameters concrete values or write one harness per variant, and keep the
|
|
48
|
+
symbolic inputs on the arithmetic the property is about.
|
|
42
49
|
|
|
43
50
|
Add `kani::cover!` witnesses for the boundary or blocking states each property
|
|
44
51
|
depends on, such as a full window or an empty queue. The checker rejects
|
|
45
52
|
unsatisfiable, unreachable and undetermined covers, even when Kani exits
|
|
46
53
|
successfully. Ordinary unreachable assertions are allowed because they describe
|
|
47
|
-
impossible panic branches. Every
|
|
54
|
+
impossible panic branches. Every passing harness must have at least one
|
|
55
|
+
`Satisfied` cover after its assumptions. Successful assertions alone do not
|
|
56
|
+
establish reachability: Kani also labels compiler safety checks as assertions,
|
|
57
|
+
and one before contradictory assumptions can pass while the property is
|
|
58
|
+
unreachable. Existing coverless harnesses must add an explicit boundary
|
|
59
|
+
witness. Every cover must have status `Satisfied`.
|
|
48
60
|
|
|
49
61
|
## Check
|
|
50
62
|
|
|
@@ -62,14 +74,34 @@ bundle's driver directly, without invoking the auto-installing Cargo wrapper.
|
|
|
62
74
|
A registered Cargo installer is not required after setup. Relative `KANI_HOME`
|
|
63
75
|
paths resolve against the caller's directory before any temporary work begins.
|
|
64
76
|
The helper installs no Kani runtime. `UNAVAILABLE` means not checked; follow the
|
|
65
|
-
printed
|
|
77
|
+
printed remedy before making any claim about the code. A compilation
|
|
66
78
|
error, missing harness or incomplete verifier report fails.
|
|
67
79
|
|
|
80
|
+
A discovery failure that names Kani's bundled toolchain means that code Kani
|
|
81
|
+
compiles uses a feature the toolchain lacks. When an error location is in
|
|
82
|
+
harness code, rewrite the harness without that feature. When every location is
|
|
83
|
+
in production code or a dependency, do not add a feature attribute to the
|
|
84
|
+
production crate, and report the target as not checked by Kani. A harness in a
|
|
85
|
+
separate crate that copies the function checks the copy, not the production
|
|
86
|
+
code, so report it as a model and name the copied source and commit.
|
|
87
|
+
|
|
68
88
|
Put `<Name>.mutations` beside the assigned `<Name>.rs`. Use
|
|
69
89
|
`detects <fully-qualified-harness>` for each mutation. The mutation runner uses
|
|
70
90
|
the bundled Cargo to find the crate's workspace and local dependencies, copies
|
|
71
|
-
them to temporary storage with their relative paths intact, and checks the
|
|
72
|
-
|
|
91
|
+
them to temporary storage with their relative paths intact, and checks the
|
|
92
|
+
copied manifest from the original crate directory so Cargo retains configuration
|
|
93
|
+
and relative paths to external files. Each selected harness must first pass on
|
|
94
|
+
the unmutated source; a compiler error or inconclusive check never counts as
|
|
95
|
+
detection. Every harness declared in the adjacent Rust file needs a mutation.
|
|
96
|
+
An explicit property failure or a lost cover witness can detect a mutation;
|
|
97
|
+
missing covers and unreachable assertions alone are inconclusive.
|
|
98
|
+
An explicit `detects` may also name a harness in another file; unrelated
|
|
99
|
+
harnesses in other files do not contribute to this file’s coverage requirement.
|
|
100
|
+
|
|
101
|
+
Direct checks and discovery run from the crate directory so Cargo reads crate
|
|
102
|
+
and ancestor configuration. Discovery uses code generation metadata in an
|
|
103
|
+
isolated target directory and does not write a `kani-list.json` into the source
|
|
104
|
+
tree. Cargo may create or update its normal lockfile.
|
|
73
105
|
|
|
74
106
|
For each fix commit in your row whose fixed code is in the file beside the
|
|
75
107
|
mutations file, add a mutation that restores the code before the fix, with the
|
|
@@ -43,6 +43,8 @@ Kani supports Linux and macOS on x86_64 and aarch64. See the [pinned installatio
|
|
|
43
43
|
|
|
44
44
|
The Rust checker discovers proof harnesses and checks each selected harness separately. It reports the unwind bound and check count, rejects an insufficient bound and any cover condition that was not satisfied, and prints a concrete playback test for a failed assertion when Kani can produce one. Larger inputs and loops remain outside the reported bounds. Crate builds may obtain dependencies declared in Cargo; the template has none.
|
|
45
45
|
|
|
46
|
+
Kani stops each harness after five minutes. Set `KANI_HARNESS_TIMEOUT` to change the limit to a whole number from 1 to 4294967295 with an optional unit `s`, `m` or `h`, such as `90s` or `20m`. A number with no unit counts seconds. The limit cannot be turned off, so set a long one, such as `24h`, instead. For any other value, the Rust checker, the mutation runner and `setup.sh rust` print `UNAVAILABLE` and check no harness. A harness that reaches the limit fails with a message that names the limit and the setting, and a mutation that reaches it gets no verdict. Each harness check can take up to the limit, so run the command in the background or give it a timeout longer than the total.
|
|
47
|
+
|
|
46
48
|
The mutation runner reads `Name.mutations` beside `Name.rs`, uses the bundled Cargo to find the crate's workspace and local dependencies, and copies them to a temporary directory with their relative paths intact. It checks the harness named by `detects` and leaves the source crate unchanged. Each harness must have a mutation that its property detects.
|
|
47
49
|
|
|
48
50
|
## Lean 4
|
|
@@ -53,7 +53,7 @@ The matrix runner prints PASS or FAIL per run and a SUMMARY line. A failing run
|
|
|
53
53
|
|
|
54
54
|
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. Reach searches use one worker and ignore deadlock so they can finish exploring a stopped model. 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
55
|
|
|
56
|
-
Before reporting a pass, list mutations that represent plausible code bugs in the mutations file. Try replacing `while` with `if`, removing a broadcast, replacing FIFO order with stack order, leaving a flag set, or taking an item without removing it. Each mutation names the one property that must fail on it. For each fix commit in your row, add a mutation that restores the behaviour the code had before the fix, with the commit's short hash in its label. The mutation runner applies each to a copy of the spec. Revise a property it reports as UNCOVERED, and the property or the mutation behind each MISSED line.
|
|
56
|
+
Before reporting a pass, list mutations that represent plausible code bugs in the mutations file. Try replacing `while` with `if`, removing a broadcast, replacing FIFO order with stack order, leaving a flag set, or taking an item without removing it. Each mutation names the one property that must fail on it. For each fix commit in your row, add a mutation that restores the behaviour the code had before the fix, with the commit's short hash in its label. The mutation runner applies each to a copy of the spec, using only matrix runs where its named check is in scope. Temporal mutations disable TLC's separate deadlock check so that the temporal property itself must fail; a deadlock alone earns no detection. Revise a property it reports as UNCOVERED, and the property or the mutation behind each MISSED line.
|
|
57
57
|
|
|
58
58
|
## Report
|
|
59
59
|
|
|
@@ -12,7 +12,7 @@ change, and so is an added item whose kind narrows what is checked.
|
|
|
12
12
|
.matrix TLA+. Each run's effective checks and each reach check's selected inputs,
|
|
13
13
|
and the normalized definitions of Spec,
|
|
14
14
|
of each operator a check or reach line names, and of the operators those
|
|
15
|
-
reference
|
|
15
|
+
reference through local EXTENDS. Local INSTANCE substitutions retain their whole module tree.
|
|
16
16
|
.rs Kani. Each qualified harness name, and each kani::assume, kani::any_where,
|
|
17
17
|
kani::cover! and #[kani::stub] with its owning free function, under inline
|
|
18
18
|
modules. Unsupported owners fail. Added covers and harnesses are allowed.
|
|
@@ -127,7 +127,7 @@ def begins_in_column_zero(line):
|
|
|
127
127
|
|
|
128
128
|
def tla_definitions(text):
|
|
129
129
|
found, unreadable, name, lines = {}, set(), None, []
|
|
130
|
-
for line in
|
|
130
|
+
for line in text.split("\n"):
|
|
131
131
|
if begins_in_column_zero(line):
|
|
132
132
|
match = DEFINITION.match(line)
|
|
133
133
|
header = None if match or MODULE_LEVEL.match(line) or "==" not in line else collapse(line.partition("==")[0])
|
|
@@ -145,18 +145,82 @@ def tla_definitions(text):
|
|
|
145
145
|
return found, unreadable
|
|
146
146
|
|
|
147
147
|
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
148
|
+
EXTENDS = re.compile(r"\bEXTENDS\s+(\w+(?:\s*,\s*\w+)*)")
|
|
149
|
+
INSTANCE = re.compile(r"\bINSTANCE\s+(\w+)")
|
|
150
|
+
INDENTED_DEFINITION = re.compile(r"^[ \t]*" + DEFINITION.pattern, re.MULTILINE)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def tla_module_surface(directory, spec, operators):
|
|
154
|
+
"""Resolve operator references in the module that defines them, including sibling imports."""
|
|
155
|
+
root = Path(spec)
|
|
156
|
+
texts, bodies, scopes, exports = {}, {}, {}, {}
|
|
157
|
+
required, visiting = set(), set()
|
|
158
|
+
whole_modules = False
|
|
159
|
+
|
|
160
|
+
def load(path):
|
|
161
|
+
nonlocal whole_modules
|
|
162
|
+
if path in exports:
|
|
163
|
+
return exports[path]
|
|
164
|
+
if path in visiting:
|
|
165
|
+
raise ValueError(f"cyclic TLA+ import at {path}")
|
|
166
|
+
visiting.add(path)
|
|
167
|
+
text = blank_tla_comments(tlc.read_raw(directory / path))
|
|
168
|
+
texts[path] = text
|
|
169
|
+
code = STRING.sub('""', text)
|
|
170
|
+
# Indented or multiline headers cannot always be separated from a local LET definition.
|
|
171
|
+
if path != root and re.search(r"(?m)^(?:[ \t].*)?(?<!=)==(?!=)", code):
|
|
172
|
+
whole_modules = True
|
|
173
|
+
scope = {}
|
|
174
|
+
for group in EXTENDS.findall(code):
|
|
175
|
+
for name in IDENTIFIER.findall(group):
|
|
176
|
+
sibling = path.with_name(f"{name}.tla")
|
|
177
|
+
if (directory / sibling).is_file():
|
|
178
|
+
scope.update(load(sibling))
|
|
179
|
+
for name in INSTANCE.findall(code):
|
|
180
|
+
sibling = path.with_name(f"{name}.tla")
|
|
181
|
+
if (directory / sibling).is_file():
|
|
182
|
+
whole_modules = True
|
|
183
|
+
load(sibling)
|
|
184
|
+
definitions, unreadable = tla_definitions(text)
|
|
185
|
+
for name, body in definitions.items():
|
|
186
|
+
key = (path, name)
|
|
187
|
+
bodies[key] = body
|
|
188
|
+
scope[name] = key
|
|
189
|
+
required.update((path, name) for name in unreadable)
|
|
190
|
+
scopes[path] = scope
|
|
191
|
+
exports[path] = {name: key for name, key in scope.items() if not bodies[key].startswith("LOCAL ")}
|
|
192
|
+
visiting.remove(path)
|
|
193
|
+
return exports[path]
|
|
194
|
+
|
|
195
|
+
load(root)
|
|
196
|
+
surface = {f"imports {spec}": sorted(str(path) for path in texts if path != root)}
|
|
197
|
+
fallback_names = set()
|
|
198
|
+
if whole_modules:
|
|
199
|
+
fallback_names = {match[1] for text in texts.values() for match in INDENTED_DEFINITION.finditer(text)}
|
|
200
|
+
for name in sorted({"Spec", *operators}):
|
|
201
|
+
if name in scopes[root]:
|
|
202
|
+
required.add(scopes[root][name])
|
|
203
|
+
elif name.rpartition("!")[2] not in fallback_names:
|
|
204
|
+
raise ValueError(f"{name} is named in the {spec} section but no definition was found in it or its local imports")
|
|
205
|
+
if whole_modules:
|
|
206
|
+
# Preserve substitutions and dependencies whose operator scope cannot be resolved.
|
|
207
|
+
for path, text in texts.items():
|
|
208
|
+
surface[f"module text {spec} | {path}"] = collapse(text)
|
|
209
|
+
return surface
|
|
210
|
+
|
|
211
|
+
seen = set()
|
|
212
|
+
while required:
|
|
213
|
+
key = required.pop()
|
|
214
|
+
if key in seen:
|
|
153
215
|
continue
|
|
154
|
-
seen.add(
|
|
155
|
-
|
|
156
|
-
|
|
216
|
+
seen.add(key)
|
|
217
|
+
owner, name = key
|
|
218
|
+
surface[f"definition {owner} {name}"] = bodies[key]
|
|
219
|
+
body = STRING.sub('""', bodies[key].partition("==")[2])
|
|
220
|
+
if key == scopes[root]["Spec"]:
|
|
157
221
|
body = SPEC_ACTIONS.sub(" ", body)
|
|
158
|
-
|
|
159
|
-
return
|
|
222
|
+
required.update(scopes[owner][word] for word in IDENTIFIER.findall(body) if word in scopes[owner])
|
|
223
|
+
return surface
|
|
160
224
|
|
|
161
225
|
|
|
162
226
|
def tla_surface(path):
|
|
@@ -188,12 +252,7 @@ def tla_surface(path):
|
|
|
188
252
|
source = path.parent / spec
|
|
189
253
|
if not source.is_file():
|
|
190
254
|
raise ValueError(f"{path}: spec {spec} not found")
|
|
191
|
-
|
|
192
|
-
for name in sorted({"Spec", *operators}):
|
|
193
|
-
if name not in definitions:
|
|
194
|
-
raise ValueError(f"{path}: {name} is named in the {spec} section but {source} does not define it")
|
|
195
|
-
for name in sorted(tla_closure(definitions, {"Spec", *operators, *unreadable})):
|
|
196
|
-
surface[f"definition {spec} {name}"] = definitions[name]
|
|
255
|
+
surface.update(tla_module_surface(path.parent, spec, operators))
|
|
197
256
|
return surface
|
|
198
257
|
|
|
199
258
|
|
|
@@ -420,6 +479,8 @@ def record(record_path, files):
|
|
|
420
479
|
|
|
421
480
|
def differences(kind, old, new):
|
|
422
481
|
lines = []
|
|
482
|
+
if kind == "tla" and not any(name.startswith("imports ") for name in old):
|
|
483
|
+
lines.append(" previous baseline did not track imported modules; review and record this matrix again")
|
|
423
484
|
for name in old:
|
|
424
485
|
if name not in new:
|
|
425
486
|
lines.append(f" removed {name}")
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import argparse
|
|
6
6
|
import json
|
|
7
7
|
import os
|
|
8
|
+
import re
|
|
8
9
|
import subprocess
|
|
9
10
|
import sys
|
|
10
11
|
import tempfile
|
|
@@ -36,6 +37,12 @@ class Verdict(IntEnum):
|
|
|
36
37
|
INCONCLUSIVE = 2
|
|
37
38
|
|
|
38
39
|
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class Harness:
|
|
42
|
+
unwind: int
|
|
43
|
+
source: Path
|
|
44
|
+
|
|
45
|
+
|
|
39
46
|
@dataclass(frozen=True)
|
|
40
47
|
class Outcome:
|
|
41
48
|
verdict: Verdict
|
|
@@ -56,6 +63,14 @@ class Kani:
|
|
|
56
63
|
|
|
57
64
|
def __init__(self):
|
|
58
65
|
home = Path(os.environ.get("KANI_HOME", Path.home() / ".kani")).resolve()
|
|
66
|
+
self.timeout = os.environ.get("KANI_HARNESS_TIMEOUT", "").strip() or "5m"
|
|
67
|
+
limit = re.fullmatch(r"\+?0*([1-9][0-9]{0,9})([smh]?)", self.timeout)
|
|
68
|
+
if not limit or int(limit[1]) >= 2**32:
|
|
69
|
+
raise Unavailable(f"KANI_HARNESS_TIMEOUT={self.timeout!r} is not a harness time limit; set a whole "
|
|
70
|
+
"number from 1 to 4294967295 with an optional unit s, m or h, such as 90s or 20m, "
|
|
71
|
+
"or unset it for five minutes")
|
|
72
|
+
# Kani reads a number with no unit as seconds; name the unit when reporting the limit.
|
|
73
|
+
self.limit = limit[1] + (limit[2] or "s")
|
|
59
74
|
bundle = home / f"kani-{self.version}"
|
|
60
75
|
remedy = (f"run cargo install --locked kani-verifier --version {self.version} "
|
|
61
76
|
"then cargo kani setup")
|
|
@@ -65,6 +80,7 @@ class Kani:
|
|
|
65
80
|
raise Unavailable(f"Kani {self.version} bundle is incomplete; {remedy}")
|
|
66
81
|
if any(home.glob("*.tar.gz")):
|
|
67
82
|
raise Unavailable(f"incomplete Kani setup at {home}; finish cargo kani setup before checking")
|
|
83
|
+
self.bundle = bundle
|
|
68
84
|
self.driver = bundle / "bin/kani-driver"
|
|
69
85
|
self.cargo = bundle / "toolchain/bin/cargo"
|
|
70
86
|
self.env = os.environ | {
|
|
@@ -96,46 +112,49 @@ class Kani:
|
|
|
96
112
|
except OSError as error:
|
|
97
113
|
raise CheckError(f"cannot execute Kani: {error}") from error
|
|
98
114
|
|
|
99
|
-
def
|
|
100
|
-
"""
|
|
115
|
+
def cargo_metadata(self, crate, resolve=False):
|
|
116
|
+
"""Read package declarations; resolve only when finding the full local source graph."""
|
|
117
|
+
try:
|
|
118
|
+
done = subprocess.run(
|
|
119
|
+
[str(self.cargo), "metadata", *([] if resolve else ["--no-deps"]), "--format-version", "1",
|
|
120
|
+
"--manifest-path", str(crate / "Cargo.toml")],
|
|
121
|
+
cwd=crate, env=self.env, capture_output=True, text=True, check=False)
|
|
122
|
+
except OSError as error:
|
|
123
|
+
raise CheckError(f"cannot read Cargo metadata: {error}") from error
|
|
124
|
+
if done.returncode:
|
|
125
|
+
raise CheckError(f"Cargo metadata failed for {crate}:\n{done.stdout}{done.stderr}")
|
|
126
|
+
try:
|
|
127
|
+
report = json.loads(done.stdout)
|
|
128
|
+
if report["version"] != 1:
|
|
129
|
+
raise CheckError("unsupported Cargo metadata version")
|
|
130
|
+
paths = [Path(report["workspace_root"])]
|
|
131
|
+
for package in report["packages"]:
|
|
132
|
+
if package["source"] is None:
|
|
133
|
+
paths.append(Path(package["manifest_path"]).parent)
|
|
134
|
+
paths.extend(Path(dep["path"]) for dep in package["dependencies"] if "path" in dep)
|
|
135
|
+
if not all(path.is_absolute() for path in paths):
|
|
136
|
+
raise CheckError("Cargo metadata returned a relative source path")
|
|
137
|
+
return paths
|
|
138
|
+
except (ValueError, KeyError, TypeError) as error:
|
|
139
|
+
raise CheckError(f"malformed Cargo metadata: {error}") from error
|
|
140
|
+
|
|
141
|
+
def source_roots(self, crate):
|
|
142
|
+
"""Find local workspaces, including transitive and optional path dependencies."""
|
|
101
143
|
pending, visited, roots = {crate}, set(), set()
|
|
102
144
|
while pending:
|
|
103
145
|
directory = pending.pop()
|
|
104
146
|
if directory in visited:
|
|
105
147
|
continue
|
|
106
148
|
visited.add(directory)
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
"--format-version", "1", "--manifest-path", str(directory / "Cargo.toml")],
|
|
111
|
-
cwd=work, env=self.env, capture_output=True, text=True, check=False)
|
|
112
|
-
except OSError as error:
|
|
113
|
-
raise CheckError(f"cannot read Cargo metadata: {error}") from error
|
|
114
|
-
if done.returncode:
|
|
115
|
-
raise CheckError(f"Cargo metadata failed for {directory}:\n{done.stdout}{done.stderr}")
|
|
116
|
-
try:
|
|
117
|
-
report = json.loads(done.stdout)
|
|
118
|
-
if report["version"] != 1:
|
|
119
|
-
raise CheckError("unsupported Cargo metadata version")
|
|
120
|
-
paths = [Path(report["workspace_root"]), directory]
|
|
121
|
-
for package in report["packages"]:
|
|
122
|
-
if package["source"] is not None:
|
|
123
|
-
continue
|
|
124
|
-
paths.append(Path(package["manifest_path"]).parent)
|
|
125
|
-
paths.extend(Path(dependency["path"]) for dependency in package["dependencies"] if "path" in dependency)
|
|
126
|
-
if not all(path.is_absolute() for path in paths):
|
|
127
|
-
raise CheckError("Cargo metadata returned a relative source path")
|
|
128
|
-
roots.add(paths[0].resolve())
|
|
129
|
-
roots.add(directory)
|
|
130
|
-
pending.update(path.resolve() for path in paths[2:])
|
|
131
|
-
except (ValueError, KeyError, TypeError) as error:
|
|
132
|
-
raise CheckError(f"malformed Cargo metadata: {error}") from error
|
|
149
|
+
paths = self.cargo_metadata(directory, resolve=directory == crate)
|
|
150
|
+
roots.update((paths[0].resolve(), directory))
|
|
151
|
+
pending.update(path.resolve() for path in paths[1:])
|
|
133
152
|
return roots
|
|
134
153
|
|
|
135
154
|
|
|
136
|
-
def invoke(crate, work, kani, *arguments):
|
|
155
|
+
def invoke(crate, work, kani, *arguments, cwd=None):
|
|
137
156
|
return kani.run("--manifest-path", str(crate / "Cargo.toml"),
|
|
138
|
-
"--target-dir", str(work / "target"), *arguments, cwd=
|
|
157
|
+
"--target-dir", str(work / "target"), "-Z", "stubbing", *arguments, cwd=cwd or crate)
|
|
139
158
|
|
|
140
159
|
|
|
141
160
|
def read_json(path):
|
|
@@ -146,46 +165,54 @@ def read_json(path):
|
|
|
146
165
|
|
|
147
166
|
|
|
148
167
|
def discover(crate, work, kani):
|
|
149
|
-
"""
|
|
168
|
+
"""Compile current harness metadata without `list`, which writes into the source directory."""
|
|
150
169
|
if not (crate / "Cargo.toml").is_file():
|
|
151
170
|
raise CheckError(f"{crate}/Cargo.toml is missing")
|
|
152
|
-
|
|
171
|
+
workspace = kani.cargo_metadata(crate)[0]
|
|
172
|
+
done = invoke(crate, work, kani, "--only-codegen")
|
|
153
173
|
if done.returncode:
|
|
154
|
-
|
|
174
|
+
output = done.stdout + done.stderr
|
|
175
|
+
if "error[E0658]" in output:
|
|
176
|
+
try:
|
|
177
|
+
toolchain = (kani.bundle / "rust-toolchain-version").read_text(encoding="utf-8").strip()
|
|
178
|
+
except OSError:
|
|
179
|
+
toolchain = "Rust toolchain (version metadata unavailable)"
|
|
180
|
+
output += (f"\nKani {kani.version} compiles with its bundled {toolchain}, which lacks a feature "
|
|
181
|
+
"used at the locations above. Rewrite harness code that uses it. If every location is "
|
|
182
|
+
"in production code or a dependency, report the Kani target as not checked; a feature "
|
|
183
|
+
"attribute would change the production crate.")
|
|
184
|
+
raise CheckError(f"Kani discovery failed:\n{output}")
|
|
185
|
+
harnesses = {}
|
|
155
186
|
try:
|
|
156
|
-
report = read_json(work / "kani-list.json")
|
|
157
|
-
if report.get("kani-version") != kani.version or report.get("file-version") != "0.1":
|
|
158
|
-
raise CheckError("unsupported Kani discovery schema or version")
|
|
159
|
-
groups = report.get("standard-harnesses")
|
|
160
|
-
if not isinstance(groups, dict) or not all(
|
|
161
|
-
isinstance(names, list) and all(isinstance(name, str) and name for name in names)
|
|
162
|
-
for names in groups.values()):
|
|
163
|
-
raise CheckError("malformed Kani harness list")
|
|
164
|
-
names = [name for group in groups.values() for name in group]
|
|
165
|
-
if not names:
|
|
166
|
-
raise CheckError("no proof harnesses found")
|
|
167
|
-
if len(set(names)) != len(names):
|
|
168
|
-
raise CheckError("duplicate harness names; select a single crate")
|
|
169
|
-
bounds = {}
|
|
170
187
|
for metadata in (work / "target").rglob("*.kani-metadata.json"):
|
|
171
|
-
for harness in read_json(metadata)
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
188
|
+
for harness in read_json(metadata)["proof_harnesses"]:
|
|
189
|
+
if harness["attributes"]["kind"] != "Proof":
|
|
190
|
+
continue
|
|
191
|
+
name = harness["pretty_name"]
|
|
192
|
+
bound = harness["attributes"].get("unwind_value")
|
|
193
|
+
source = harness["original_file"]
|
|
194
|
+
if not isinstance(name, str) or not name or not isinstance(source, str) or not source:
|
|
195
|
+
raise CheckError("malformed Kani harness name or source")
|
|
196
|
+
if name in harnesses:
|
|
197
|
+
raise CheckError("duplicate harness names; select a single crate")
|
|
198
|
+
if type(bound) is not int or bound < 1:
|
|
199
|
+
raise CheckError(f"{name} needs #[kani::unwind(N)] with N greater than zero")
|
|
200
|
+
harnesses[name] = Harness(bound, (workspace / source).resolve())
|
|
201
|
+
except (KeyError, TypeError, AttributeError) as error:
|
|
179
202
|
raise CheckError(f"malformed Kani discovery record: {error!r}") from error
|
|
180
|
-
if
|
|
181
|
-
raise CheckError("
|
|
182
|
-
return
|
|
203
|
+
if not harnesses:
|
|
204
|
+
raise CheckError("no proof harnesses found")
|
|
205
|
+
return harnesses
|
|
183
206
|
|
|
184
207
|
|
|
185
208
|
def harness_result(report, kani, name, returncode):
|
|
186
209
|
"""Return the one harness result in report after checking it agrees with itself and the process."""
|
|
187
210
|
if report.get("metadata", {}).get("version") != "1.0" or report["metadata"].get("kani_version") != kani.version:
|
|
188
211
|
raise CheckError("unsupported Kani result schema or version")
|
|
212
|
+
if any(detail.get("harness_id") == name and detail.get("exit_status") == "timeout"
|
|
213
|
+
for detail in report.get("error_details", [])):
|
|
214
|
+
raise CheckError(f"the solver did not finish within the {kani.limit} harness limit; "
|
|
215
|
+
"narrow the harness or set KANI_HARNESS_TIMEOUT to a longer limit")
|
|
189
216
|
verification = report["verification_results"]
|
|
190
217
|
summary, results = verification["summary"], verification["results"]
|
|
191
218
|
if summary["status"] != "completed" or summary["executed"] != 1 or summary["total_harnesses"] != 1:
|
|
@@ -220,15 +247,16 @@ def describe(check):
|
|
|
220
247
|
f"{location['file']}:{location['line']}:{location['column']}")
|
|
221
248
|
|
|
222
249
|
|
|
223
|
-
def verify(crate, work, kani, name, bound):
|
|
250
|
+
def verify(crate, work, kani, name, bound, *, cwd=None):
|
|
224
251
|
"""Check one harness; a report that is malformed or disagrees with the process is inconclusive."""
|
|
225
252
|
result_file = work / "result.json"
|
|
226
253
|
result_file.unlink(missing_ok=True)
|
|
227
254
|
try:
|
|
228
255
|
done = invoke(crate, work, kani, "--harness", name, "--exact", "--unwind", str(bound),
|
|
229
|
-
"-Z", "unstable-options", "--
|
|
256
|
+
"-Z", "unstable-options", "--harness-timeout", kani.timeout,
|
|
257
|
+
"--export-json", str(result_file),
|
|
230
258
|
"-Z", "concrete-playback", "--concrete-playback", "print",
|
|
231
|
-
"--output-format", "regular")
|
|
259
|
+
"--output-format", "regular", cwd=cwd)
|
|
232
260
|
except CheckError as error:
|
|
233
261
|
return Outcome(Verdict.INCONCLUSIVE, 0, [str(error)], "")
|
|
234
262
|
output = done.stdout + done.stderr
|
|
@@ -238,6 +266,12 @@ def verify(crate, work, kani, name, bound):
|
|
|
238
266
|
verdict = max(verdict for _, verdict in verdicts)
|
|
239
267
|
if verdict is Verdict.PASS and result["status"] != "Success":
|
|
240
268
|
raise CheckError("Kani reports a harness failure that no check explains")
|
|
269
|
+
if verdict is Verdict.PASS and not any(
|
|
270
|
+
check["status"] == "Satisfied" and check["category"] == "cover"
|
|
271
|
+
for check, _ in verdicts):
|
|
272
|
+
# Kani labels compiler safety checks as assertions too: an overflow check
|
|
273
|
+
# before contradictory assumptions can succeed while the property is unreachable.
|
|
274
|
+
raise CheckError("no satisfied kani::cover! witness; cover a boundary after the assumptions")
|
|
241
275
|
failures = [describe(check) for check, verdict in verdicts if verdict is not Verdict.PASS]
|
|
242
276
|
except (KeyError, TypeError, AttributeError, CheckError) as error:
|
|
243
277
|
return Outcome(Verdict.INCONCLUSIVE, 0, [f"verification did not complete: {error}"], output)
|
|
@@ -274,10 +308,10 @@ def main():
|
|
|
274
308
|
return 1
|
|
275
309
|
passed = 0
|
|
276
310
|
for name in names:
|
|
277
|
-
outcome = verify(crate, work, kani, name, bounds[name])
|
|
311
|
+
outcome = verify(crate, work, kani, name, bounds[name].unwind)
|
|
278
312
|
ok = outcome.verdict is Verdict.PASS
|
|
279
313
|
passed += ok
|
|
280
|
-
print(f"{'PASS' if ok else 'FAIL'} {name} unwind={bounds[name]} checks={outcome.checks}"
|
|
314
|
+
print(f"{'PASS' if ok else 'FAIL'} {name} unwind={bounds[name].unwind} checks={outcome.checks}"
|
|
281
315
|
+ (": " + "; ".join(outcome.failures) if outcome.failures else ""))
|
|
282
316
|
if not ok:
|
|
283
317
|
print(outcome.output.rstrip())
|
|
@@ -150,6 +150,7 @@ open Lean Elab Command in
|
|
|
150
150
|
| .axiomInfo _ => "axiom"
|
|
151
151
|
let value := match info with
|
|
152
152
|
| .defnInfo v => toJson (reprStr v.value)
|
|
153
|
+
| .opaqueInfo v => toJson (reprStr v.value)
|
|
153
154
|
| _ => Json.null
|
|
154
155
|
let pp ← liftTermElabM <| Meta.ppExpr info.type
|
|
155
156
|
let record := Json.mkObj [
|
|
@@ -114,6 +114,10 @@ def check(toolchain, modules, sources):
|
|
|
114
114
|
raise ValueError(f"{path}: expected module {module}, found {frozen['module']}")
|
|
115
115
|
changed = 0
|
|
116
116
|
for old in frozen["declarations"]:
|
|
117
|
+
if old["kind"] == "opaque" and old["valueHash"] is None:
|
|
118
|
+
print(f"FROZEN {old['name']}: opaque body was not recorded; review the definition and run --freeze")
|
|
119
|
+
failed = True
|
|
120
|
+
continue
|
|
117
121
|
new = records.get(old["name"])
|
|
118
122
|
if new is not None and all(old[key] == new[key] for key in ("kind", "typeHash", "valueHash")):
|
|
119
123
|
continue
|
|
@@ -51,7 +51,7 @@ import subprocess
|
|
|
51
51
|
import sys
|
|
52
52
|
import tempfile
|
|
53
53
|
from collections.abc import Callable
|
|
54
|
-
from dataclasses import dataclass
|
|
54
|
+
from dataclasses import dataclass, replace
|
|
55
55
|
from enum import Enum
|
|
56
56
|
from functools import partial
|
|
57
57
|
from os.path import commonpath
|
|
@@ -148,36 +148,47 @@ def make_mutation(label, directives, model, text, language):
|
|
|
148
148
|
return Mutation(label, detects, only, old, new, text.replace(old, new))
|
|
149
149
|
|
|
150
150
|
|
|
151
|
-
def check_tla(spec, checker,
|
|
152
|
-
"""
|
|
151
|
+
def check_tla(spec, checker, plan, mutation, work):
|
|
152
|
+
"""Narrow the matrix's existing tasks to the named mutation target without changing run scope."""
|
|
153
153
|
for module in spec.parent.glob("*.tla"):
|
|
154
154
|
(work / module.name).write_text(module.read_text(encoding="utf-8"), encoding="utf-8")
|
|
155
155
|
(work / spec.name).write_text(mutation.source, encoding="utf-8")
|
|
156
|
-
|
|
157
|
-
if kind:
|
|
158
|
-
checks = [tlc.Check(f"{kind} {mutation.detects}", kind, (mutation.detects,))]
|
|
159
|
-
else:
|
|
160
|
-
checks = [d for d in section if isinstance(d, tlc.Reach) and f"reach:{d.operator}" == mutation.detects]
|
|
161
|
-
results = []
|
|
156
|
+
covers, results = frozenset({mutation.detects}), []
|
|
162
157
|
runner = tlc.Runner(checker, work, mutation.only, results.append, work)
|
|
163
|
-
for task in
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
if
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
158
|
+
for task in plan:
|
|
159
|
+
if isinstance(task, tlc.Result):
|
|
160
|
+
if f"reach:{task.operator}" == mutation.detects:
|
|
161
|
+
runner.check(task)
|
|
162
|
+
elif task.reach:
|
|
163
|
+
if f"reach:{task.reach.operator}" == mutation.detects:
|
|
164
|
+
runner.check(task)
|
|
165
|
+
else:
|
|
166
|
+
checks = tuple(tlc.Check(f"{check.kind} {mutation.detects}", check.kind, (mutation.detects,))
|
|
167
|
+
for check in task.checks if mutation.detects in check.names)
|
|
168
|
+
if checks:
|
|
169
|
+
runner.check(replace(task, checks=checks,
|
|
170
|
+
check_deadlock=not any(check.kind.startswith("PROPERT") for check in checks)))
|
|
171
|
+
if not results:
|
|
172
|
+
return Result(Verdict.ERROR, f"no run matches '{mutation.only}' for '{mutation.detects}'")
|
|
173
|
+
detected, errors = [], []
|
|
174
|
+
for result in results:
|
|
175
|
+
if result.outcome is tlc.Outcome.UNREACHED:
|
|
176
|
+
detected.append((result, "the model never reaches this state"))
|
|
177
|
+
elif result.outcome is tlc.Outcome.FAIL and (
|
|
178
|
+
result.detail in (f"Error: Invariant {mutation.detects} is violated.",
|
|
179
|
+
f"Error: Invariant {mutation.detects} is violated by the initial state:",
|
|
180
|
+
f"Error: Property {mutation.detects} is violated by the initial state:",
|
|
181
|
+
f"Error: Action property {mutation.detects} is violated.",
|
|
182
|
+
"Error: Temporal properties were violated.")):
|
|
183
|
+
detected.append((result, result.detail.removeprefix("Error: ").rstrip(".")))
|
|
184
|
+
elif result.outcome not in (tlc.Outcome.PASS, tlc.Outcome.WITNESS):
|
|
185
|
+
errors.extend(tlc.render(result))
|
|
186
|
+
if errors:
|
|
187
|
+
return Result(Verdict.ERROR, "\n".join(errors))
|
|
188
|
+
if detected:
|
|
189
|
+
result, error = detected[0]
|
|
190
|
+
return Result(Verdict.DETECTED, f"{mutation.detects} fails in run '{result.label}' ({error})", covers)
|
|
191
|
+
return Result(Verdict.MISSED, covers=covers)
|
|
181
192
|
|
|
182
193
|
|
|
183
194
|
def lean_toolchain(project):
|
|
@@ -270,7 +281,8 @@ def check_rust(model, project, verifier, bounds, sources, mutation, work):
|
|
|
270
281
|
shutil.copytree(source, work / "source" / source.relative_to(anchor), ignore=shutil.ignore_patterns("target", ".git"))
|
|
271
282
|
copy, covers = work / "source" / project.relative_to(anchor), frozenset({mutation.detects})
|
|
272
283
|
(copy / model.relative_to(project)).write_text(mutation.source, encoding="utf-8")
|
|
273
|
-
|
|
284
|
+
# Cargo resolves configuration from cwd, including paths outside the copied packages.
|
|
285
|
+
outcome = kani.verify(copy, work, verifier, mutation.detects, bounds[mutation.detects].unwind, cwd=project)
|
|
274
286
|
if outcome.verdict is kani.Verdict.PASS:
|
|
275
287
|
return Result(Verdict.MISSED, covers=covers)
|
|
276
288
|
if outcome.verdict is kani.Verdict.REFUTED:
|
|
@@ -283,7 +295,7 @@ def project_root(model, *markers):
|
|
|
283
295
|
|
|
284
296
|
|
|
285
297
|
def tla_runner(spec, mutations):
|
|
286
|
-
"""
|
|
298
|
+
"""Preserve the execution plan of every matching spec section, and check TLC once."""
|
|
287
299
|
matrix = spec.with_suffix(".matrix")
|
|
288
300
|
if not matrix.is_file():
|
|
289
301
|
stop(f"{matrix} is missing; mutations use its checks and runs")
|
|
@@ -293,19 +305,21 @@ def tla_runner(spec, mutations):
|
|
|
293
305
|
stop(f"{matrix}: {directive.message}")
|
|
294
306
|
if isinstance(directive, tlc.Spec):
|
|
295
307
|
ours = (matrix.parent / directive.path).resolve() == spec
|
|
308
|
+
if ours:
|
|
309
|
+
section.append(tlc.Spec(spec.name))
|
|
296
310
|
elif ours:
|
|
297
311
|
section.append(directive)
|
|
298
|
-
|
|
312
|
+
targets = {name for d in section if isinstance(d, tlc.Check) for name in d.names}
|
|
299
313
|
reaches = {f"reach:{d.operator}" for d in section if isinstance(d, tlc.Reach)}
|
|
300
314
|
for mutation in mutations:
|
|
301
|
-
if mutation.detects not in
|
|
315
|
+
if mutation.detects not in targets and mutation.detects not in reaches:
|
|
302
316
|
stop(f"mutation '{mutation.label}': detects '{mutation.detects}', which {matrix} does not check")
|
|
303
317
|
try:
|
|
304
318
|
checker = tlc.Tlc()
|
|
305
319
|
except tlc.Unavailable as error:
|
|
306
320
|
print(error)
|
|
307
321
|
sys.exit(3)
|
|
308
|
-
return
|
|
322
|
+
return targets, partial(check_tla, spec, checker, tuple(tlc.execution_plan(section)))
|
|
309
323
|
|
|
310
324
|
|
|
311
325
|
def frozen_theorems(model):
|
|
@@ -349,15 +363,23 @@ def rust_runner(model, mutations):
|
|
|
349
363
|
print(f"UNAVAILABLE {error}")
|
|
350
364
|
sys.exit(3)
|
|
351
365
|
with tempfile.TemporaryDirectory(prefix="formal-kani-discover-") as temporary:
|
|
366
|
+
work = Path(temporary)
|
|
352
367
|
try:
|
|
353
|
-
bounds = kani.discover(project,
|
|
354
|
-
sources = verifier.source_roots(project
|
|
368
|
+
bounds = kani.discover(project, work, verifier)
|
|
369
|
+
sources = verifier.source_roots(project)
|
|
370
|
+
for mutation in mutations:
|
|
371
|
+
if mutation.detects not in bounds:
|
|
372
|
+
stop(f"mutation '{mutation.label}': unknown harness '{mutation.detects}'")
|
|
373
|
+
selected = {mutation.detects for mutation in mutations}
|
|
374
|
+
for name in sorted(selected):
|
|
375
|
+
outcome = kani.verify(project, work, verifier, name, bounds[name].unwind)
|
|
376
|
+
if outcome.verdict is not kani.Verdict.PASS:
|
|
377
|
+
stop(f"unmutated Rust harness '{name}' did not pass: "
|
|
378
|
+
+ "; ".join(outcome.failures) + "\n" + outcome.output)
|
|
355
379
|
except kani.CheckError as error:
|
|
356
380
|
stop(str(error))
|
|
357
|
-
for
|
|
358
|
-
|
|
359
|
-
stop(f"mutation '{mutation.label}': unknown harness '{mutation.detects}'")
|
|
360
|
-
return set(bounds), partial(check_rust, model, project, verifier, bounds, sources)
|
|
381
|
+
targets = {name for name, harness in bounds.items() if harness.source == model} | selected
|
|
382
|
+
return targets, partial(check_rust, model, project, verifier, bounds, sources)
|
|
361
383
|
|
|
362
384
|
|
|
363
385
|
# Each runner checks the names the mutations detect, then returns the names they must cover and a check for one mutation.
|
|
@@ -170,6 +170,7 @@ class Task:
|
|
|
170
170
|
run: Run
|
|
171
171
|
checks: tuple = ()
|
|
172
172
|
reach: Reach | None = None
|
|
173
|
+
check_deadlock: bool = True
|
|
173
174
|
|
|
174
175
|
|
|
175
176
|
def execution_plan(directives):
|
|
@@ -259,6 +260,8 @@ class Runner:
|
|
|
259
260
|
(directory / module.name).write_bytes(module.read_bytes())
|
|
260
261
|
constants = "".join(f" {pair.split('=')[0]} = {pair.split('=', 1)[-1]}\n" for pair in run.constants.split())
|
|
261
262
|
config = f"CONSTANTS\n{constants}SPECIFICATION Spec\n"
|
|
263
|
+
if not task.check_deadlock:
|
|
264
|
+
config += "CHECK_DEADLOCK FALSE\n"
|
|
262
265
|
if not operator:
|
|
263
266
|
status, log = self.tlc.run(directory, name, config + "\n".join(check.line for check in task.checks) + "\n", reach=False)
|
|
264
267
|
self.report(self.ordinary(name, run, status, log, directory / "tlc.log"))
|