agent-formal-verify 0.4.15 → 0.4.17
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 +14 -0
- package/package.json +1 -1
- package/skills/formal-verify/SKILL.md +1 -1
- package/skills/formal-verify/references/evidence.md +1 -1
- package/skills/formal-verify/references/helpers.md +4 -4
- package/skills/formal-verify/scripts/baseline.py +13 -2
- package/skills/formal-verify/scripts/kani.py +18 -7
- package/skills/formal-verify/scripts/kani_reader.py +28 -3
- package/skills/formal-verify/scripts/lean.py +7 -6
- package/skills/formal-verify/scripts/mutate.py +46 -37
- package/skills/formal-verify/scripts/processes.py +29 -3
- package/skills/formal-verify/scripts/rust_source.py +34 -1
package/CHANGES.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# Changes
|
|
2
2
|
|
|
3
|
+
## 0.4.17 - one Cargo build directory per Rust mutation run, and elapsed time for long Kani and Lean runs
|
|
4
|
+
|
|
5
|
+
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.
|
|
6
|
+
|
|
7
|
+
The Rust checker, the mutation runner's Kani checks and the Lean checker now report long runs on `stderr` as the TLA+ matrix runner does. After fifteen seconds, and every thirty seconds after that, they write `[kani] discovery: <N>s elapsed` while Kani builds the crate and `[kani] <harness>: <N>s elapsed` while Kani checks a harness. The Lean checker writes `[lean] build: <N>s elapsed`, and the same for `audit` and `replay`. The printed results on `stdout` and the exit status do not change. Before this change, a cold Kani build or a long Lake build printed nothing until it finished.
|
|
8
|
+
|
|
9
|
+
## 0.4.16 - Kani harness and helper bodies in the baseline
|
|
10
|
+
|
|
11
|
+
`scripts/baseline.py` now also records the body of each free function other than a harness in a Kani module that holds a harness, or in a module under one, as the item `body <function>`, written as a harness body is. The template's `inputs()` in `mod proofs` is such a function, so changing its `let window: u16 = kani::any();` to `let window: u16 = 1;`, or weakening a predicate that a `kani::assume` in a harness calls, prints `CHANGED`. Before this change, the record read such a function only for its assumptions, covers and stubs, so both printed `UNCHANGED`. A production function outside those modules, such as the template's `claim`, is not recorded, so a production fix still prints `UNCHANGED`. A harness at the root of a file puts every free function in the file in the record. The record still reads a method in an `impl` or trait block, such as an `impl kani::Arbitrary`, and a function outside the modules that hold harnesses, only for their assumptions, covers and stubs. A record made before this change prints `CHANGED` once, with the line `previous baseline did not record the functions beside its harnesses`, when the file has such a function; check each one against the original revision, then record the file again.
|
|
12
|
+
|
|
13
|
+
`scripts/baseline.py` now keeps a `kani::cover!` call in the recorded body of its harness when the cover's condition can run code: when it holds a call, a block, an index, `?`, `return`, `break`, `continue`, `await` or `yield`. Adding such a cover prints `CHANGED`, with the cover under `new:`. Before this change, the record left every cover out of the body, so adding `kani::cover!(if window > 1 { return } else { true });` before the template's assertion skipped that assertion for every window of 2 while `compare` printed `UNCHANGED`. A cover whose condition only reads and compares values, such as `kani::cover!(state.next == 3, "three")`, is still left out, so adding one is still allowed. A record that holds a harness with a cover that can run code prints `CHANGED` once, with the cover under `new:`; record the file again.
|
|
14
|
+
|
|
15
|
+
`scripts/baseline.py` now records the body of each Kani harness as the item `body <harness>`, without comments, without its `kani::cover!` calls and without whitespace except where two tokens would otherwise join, so weakening an assertion, changing how the harness builds its inputs with `kani::any()`, `kani::any_where` or `kani::assume`, or changing the conditions around an assertion prints `CHANGED`. Re-indenting or rewrapping the body, or editing its comments, leaves it unchanged, and adding a `kani::cover!` whose condition cannot run code is still allowed. A trailing comma that a formatter adds or removes prints `CHANGED`. Before this change, the record held a harness's name, attributes and guards but not its body, so weakening `assert!(invariant(window, after))` to `assert!(invariant(window, after) || window > 1)` printed `UNCHANGED`, while the same weakening of a TLA+ property printed `CHANGED`. Every record that holds a Kani harness prints `CHANGED` once, with the line `previous baseline did not record harness bodies`; check each harness body against the original revision, then record the file again.
|
|
16
|
+
|
|
3
17
|
## 0.4.15 - Kani generator types in the baseline, locked baseline updates and a checked Lean replay
|
|
4
18
|
|
|
5
19
|
`scripts/baseline.py` now records the whole `kani::any_where` call in a harness, with its explicit type arguments and its predicate, so changing `kani::any_where::<u16, _>(...)` to `kani::any_where::<u8, _>(...)` prints `CHANGED`. Before this change, the record held the predicate alone, so narrowing a generator's type printed `UNCHANGED`. A record made with 0.4.14 that holds an `any_where` predicate prints `CHANGED` once. Older records used one form for a plain assumption and a generator's predicate, so check the harness's assumptions and generator types against the revision the record was made from before you record the file again.
|
package/package.json
CHANGED
|
@@ -89,7 +89,7 @@ Name the brief file and leave its text out of the prompt. The [TLA+ brief](refer
|
|
|
89
89
|
|
|
90
90
|
An agent writes only its own files, `tla/<Name>.tla`, `.matrix` and `.mutations`, `lean/Model/<Name>.lean`, `.mutations` and `.statements`, or the `#[cfg(kani)]` harness module in the production file that defines its Rust function and the `.mutations` file beside it, so parallel agents share none. Give one agent every Rust target in one production file. An existing Lean project keeps its layout and must pin Lean 4.20.0 or later. A Kani harness that an earlier run wrote in a crate of its own moves into its production file when the Rust brief's "Moving a harness" section allows, so it gets an agent even when it passes; otherwise its agent edits it and its `.mutations` file in place.
|
|
91
91
|
|
|
92
|
-
When the agents have reported, delete each moved harness's old file, and its crate, workspace entry and CI steps once they hold nothing else. Then rerun every check in this thread: the matrix runner on each matrix file, the Lean checker on the whole project without a file name, the Rust checker on each crate, and the mutation runner on each mutations file. Take each verdict from these runs, not from an agent's report. For a moved harness, first run `baseline.py move` as the [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 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, or a Kani assumption was added or changed. 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
|
|
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, or a Kani assumption was added or changed. 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
|
|
|
@@ -12,7 +12,7 @@ Include the matching meaning from this table where each kind of evidence first a
|
|
|
12
12
|
| A bounded search passes | Every input up to the stated bound was tried. |
|
|
13
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
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, 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,
|
|
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, including its assertions, input construction and the conditions around its assertions, apart from comments, layout and covers whose conditions cannot run code. It does not cover the body of a method in an `impl` or trait block or of a function 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
16
|
| UNAVAILABLE | The tool could not run. This target was not checked; give the printed remedy. |
|
|
17
17
|
| reproduced | A deterministic test or race-detector run fails on the production code. |
|
|
18
18
|
| reachable at shipped settings | The shipped constants and callers permit the counter-example, but no production reproduction has confirmed it yet. |
|
|
@@ -4,8 +4,8 @@ Detailed behaviour of the verification scripts under `scripts/`. Run each helper
|
|
|
4
4
|
|
|
5
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
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. 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 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 Java and TLC 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. 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.
|
|
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.
|
|
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
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 time limit, or 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
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:
|
|
@@ -24,7 +24,7 @@ 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.
|
|
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, the text between the function's braces 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();...}`. 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, and one made before the other functions' bodies were recorded prints `previous baseline did not record the functions beside its harnesses` once. For those records, check each harness body against the original revision before recording the file again.
|
|
28
28
|
- An indented `added <item>`, which only a new Kani assumption or stub prints. 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.
|
|
@@ -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, a
|
|
37
|
+
- In Kani, the body of a method in an `impl` or trait block, such as an `impl kani::Arbitrary`, and of a function outside the modules that hold harnesses, apart from their 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,9 @@ change, and so is an added item whose kind narrows what is checked.
|
|
|
20
20
|
#[path], with each route in the file's crates that the record cannot read, such as a mod
|
|
21
21
|
declaration inside a macro, and each kani::assume, kani::any_where, kani::cover! and
|
|
22
22
|
#[kani::stub] with its owning free function, under inline modules. Unsupported owners fail. Added covers and harnesses are allowed.
|
|
23
|
-
Added assumes and stubs are changes.
|
|
23
|
+
Added assumes and stubs are changes. Also the body of each harness and of each other free function in
|
|
24
|
+
a module that holds a harness, or under one, without its comments, the kani::cover! calls whose
|
|
25
|
+
conditions cannot run code, and the whitespace that a reformat can change.
|
|
24
26
|
In a Cargo package, also the recorded harnesses that Kani compiles from the file; Kani must give
|
|
25
27
|
each harness it compiles there a module path that a route the record reads gives, and a harness
|
|
26
28
|
that no longer compiles is a change.
|
|
@@ -334,6 +336,7 @@ class KaniKind:
|
|
|
334
336
|
surface = kani_surface(path, self.reader)
|
|
335
337
|
entry = model_entry(self.name, surface)
|
|
336
338
|
entry["generator_types"] = True
|
|
339
|
+
entry["helper_bodies"] = True
|
|
337
340
|
notes = [f" route not read: {route.message}" for route in self.reader.unread(path)]
|
|
338
341
|
# A harness that no longer compiles is recorded from its text alone; compare asks Kani again.
|
|
339
342
|
try:
|
|
@@ -351,6 +354,11 @@ class KaniKind:
|
|
|
351
354
|
lines = differences(entry["surface"], surface, ("assume", "stub"))
|
|
352
355
|
if may_omit_generator_types(entry):
|
|
353
356
|
lines.insert(0, " previous baseline stored assumptions without distinguishing any_where input types; review the original assumptions and record this file again")
|
|
357
|
+
if any(name.startswith("harness ") and "body " + name.removeprefix("harness ") not in entry["surface"] for name in entry["surface"]):
|
|
358
|
+
lines.insert(0, " previous baseline did not record harness bodies; review each harness body against the original revision and record this file again")
|
|
359
|
+
# A record's keys cannot show whether it read the functions beside its harnesses, so the entry says so.
|
|
360
|
+
if not entry.get("helper_bodies") and any(name.startswith("body ") and "harness " + name.removeprefix("body ") not in surface for name in surface):
|
|
361
|
+
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")
|
|
354
362
|
unchecked = (" not checked against Kani at record, so compare cannot tell a harness that "
|
|
355
363
|
"stopped compiling from one that never compiled")
|
|
356
364
|
try:
|
|
@@ -371,7 +379,8 @@ class KaniKind:
|
|
|
371
379
|
def valid(self, entry):
|
|
372
380
|
compiled = entry.get("compiled", [])
|
|
373
381
|
return (isinstance(compiled, list) and all(isinstance(name, str) for name in compiled)
|
|
374
|
-
and isinstance(entry.get("partial", False), bool) and isinstance(entry.get("generator_types", False), bool)
|
|
382
|
+
and isinstance(entry.get("partial", False), bool) and isinstance(entry.get("generator_types", False), bool)
|
|
383
|
+
and isinstance(entry.get("helper_bodies", False), bool))
|
|
375
384
|
|
|
376
385
|
def moved(self, entry, module, new, existing):
|
|
377
386
|
surface, compiled = entry["surface"], entry.get("compiled")
|
|
@@ -389,6 +398,8 @@ class KaniKind:
|
|
|
389
398
|
result = model_entry(self.name, surface)
|
|
390
399
|
if not any(may_omit_generator_types(part) for part in (entry, existing) if part is not None):
|
|
391
400
|
result["generator_types"] = True
|
|
401
|
+
if all(part.get("helper_bodies") for part in (entry, existing) if part is not None):
|
|
402
|
+
result["helper_bodies"] = True
|
|
392
403
|
if compiled is not None:
|
|
393
404
|
result["compiled"] = sorted(compiled)
|
|
394
405
|
if partial:
|
|
@@ -81,6 +81,11 @@ class CargoMetadata:
|
|
|
81
81
|
packages: tuple
|
|
82
82
|
|
|
83
83
|
|
|
84
|
+
def tag_cache(directory):
|
|
85
|
+
"""Mark directory with a CACHEDIR.TAG, as Cargo marks its build directories, so staged crate copies omit it."""
|
|
86
|
+
(directory / "CACHEDIR.TAG").write_text("Signature: 8a477f597d28d172789f06886806bc55\n", encoding="ascii")
|
|
87
|
+
|
|
88
|
+
|
|
84
89
|
@dataclass
|
|
85
90
|
class CrateSources:
|
|
86
91
|
roots: set
|
|
@@ -91,7 +96,7 @@ class CrateSources:
|
|
|
91
96
|
anchor = Path(os.path.commonpath(self.roots))
|
|
92
97
|
work = work.resolve()
|
|
93
98
|
# Other mutations can stage into the same workspace-local temporary root.
|
|
94
|
-
(work
|
|
99
|
+
tag_cache(work)
|
|
95
100
|
destination = work / "source"
|
|
96
101
|
|
|
97
102
|
def ignore(directory, names):
|
|
@@ -138,6 +143,9 @@ class Kani:
|
|
|
138
143
|
"RUSTUP_TOOLCHAIN": str((bundle / "toolchain").resolve()),
|
|
139
144
|
"PATH": search_path(os.environ.get("PATH"), bundle / "bin", bundle / "pyroot/bin", bundle / "toolchain/bin"),
|
|
140
145
|
"PYTHONPATH": search_path(os.environ.get("PYTHONPATH"), bundle / "pyroot"),
|
|
146
|
+
# The mutation runner builds crate copies in one target directory. A copy keeps the original's
|
|
147
|
+
# modification times, older than the previous mutant's build, so Cargo must compare contents instead.
|
|
148
|
+
"CARGO_UNSTABLE_CHECKSUM_FRESHNESS": "true",
|
|
141
149
|
}
|
|
142
150
|
# A parent cargo (cargo run, cargo test, a build script) exports its rustup toolchain's
|
|
143
151
|
# lib directory here; the bundled compiler must load only the bundled toolchain.
|
|
@@ -153,11 +161,13 @@ class Kani:
|
|
|
153
161
|
if done.returncode or not done.stdout.startswith(f"Kani Rust Verifier {self.version} (cargo plugin)\n"):
|
|
154
162
|
raise runner.Unavailable(f"UNAVAILABLE Kani {self.version} is required; {remedy}")
|
|
155
163
|
|
|
156
|
-
def run(self, *arguments, cwd=None, tmpdir=None):
|
|
164
|
+
def run(self, *arguments, cwd=None, tmpdir=None, label=None):
|
|
165
|
+
"""Run the driver; with a label, report the elapsed time on stderr as '[kani] <label>: <N>s elapsed'."""
|
|
157
166
|
env = self.env if tmpdir is None else self.env | {"TMPDIR": str(tmpdir)}
|
|
158
167
|
try:
|
|
159
168
|
# The driver selects Cargo mode from argv[0]; the Cargo wrapper can auto-install.
|
|
160
|
-
return processes.run_captured(["cargo-kani", *arguments], executable=str(self.driver), env=env, cwd=cwd
|
|
169
|
+
return processes.run_captured(["cargo-kani", *arguments], executable=str(self.driver), env=env, cwd=cwd,
|
|
170
|
+
label=f"[kani] {label}" if label else None)
|
|
161
171
|
except OSError as error:
|
|
162
172
|
raise CheckError(f"cannot execute Kani: {error}") from error
|
|
163
173
|
|
|
@@ -205,13 +215,14 @@ class Kani:
|
|
|
205
215
|
return sources
|
|
206
216
|
|
|
207
217
|
|
|
208
|
-
def invoke(crate, work, kani, *arguments, cwd=None):
|
|
218
|
+
def invoke(crate, work, kani, *arguments, cwd=None, label=None):
|
|
209
219
|
# Kani's tools, such as goto-cc, write their own temporary files to TMPDIR. Keep those in the
|
|
210
220
|
# work directory, which the runner removes even when it stops a tool partway.
|
|
211
221
|
tmpdir = work / "tmp"
|
|
212
222
|
tmpdir.mkdir(parents=True, exist_ok=True)
|
|
213
223
|
return kani.run("--manifest-path", str(crate / "Cargo.toml"),
|
|
214
|
-
"--target-dir", str(work / "target"), "-Z", "stubbing", *arguments, cwd=cwd or crate, tmpdir=tmpdir
|
|
224
|
+
"--target-dir", str(work / "target"), "-Z", "stubbing", *arguments, cwd=cwd or crate, tmpdir=tmpdir,
|
|
225
|
+
label=label)
|
|
215
226
|
|
|
216
227
|
|
|
217
228
|
def read_json(path):
|
|
@@ -229,7 +240,7 @@ def compiled(crate, work, kani):
|
|
|
229
240
|
if not (crate / "Cargo.toml").is_file():
|
|
230
241
|
raise CheckError(f"{crate}/Cargo.toml is missing")
|
|
231
242
|
workspace = kani.cargo_metadata(crate).workspace
|
|
232
|
-
done = invoke(crate, work, kani, "--only-codegen")
|
|
243
|
+
done = invoke(crate, work, kani, "--only-codegen", label="discovery")
|
|
233
244
|
if done.returncode:
|
|
234
245
|
output = done.stdout + done.stderr
|
|
235
246
|
if "error[E0658]" in output:
|
|
@@ -332,7 +343,7 @@ def verify(crate, work, kani, name, bound, *, cwd=None):
|
|
|
332
343
|
"-Z", "unstable-options", "--harness-timeout", kani.timeout,
|
|
333
344
|
"--export-json", str(result_file),
|
|
334
345
|
"-Z", "concrete-playback", "--concrete-playback", "print",
|
|
335
|
-
"--output-format", "regular", cwd=cwd)
|
|
346
|
+
"--output-format", "regular", cwd=cwd, label=name)
|
|
336
347
|
except CheckError as error:
|
|
337
348
|
return Outcome(Verdict.INCONCLUSIVE, 0, [str(error)], "")
|
|
338
349
|
output = done.stdout + done.stderr
|
|
@@ -13,10 +13,10 @@ sys.dont_write_bytecode = True
|
|
|
13
13
|
import kani
|
|
14
14
|
import runner
|
|
15
15
|
import storage
|
|
16
|
-
from rust_source import RustSource, after_closing, rust_masks
|
|
16
|
+
from rust_source import RustSource, after_closing, normalized, rust_masks
|
|
17
17
|
from surface import Surface, collapse
|
|
18
18
|
|
|
19
|
-
KANI_KEY = re.compile(r"(harness |(?:assume|cover|stub) .* in )(\S+)( #\d+)?", re.DOTALL)
|
|
19
|
+
KANI_KEY = re.compile(r"(harness |body |(?:assume|cover|stub) .* in )(\S+)( #\d+)?", re.DOTALL)
|
|
20
20
|
|
|
21
21
|
|
|
22
22
|
class RustFunction(NamedTuple):
|
|
@@ -101,6 +101,8 @@ PROOF = re.compile(KANI_ATTRIBUTE + r"proof(?:_for_contract\s*\([^)]*\))?\s*\)?\
|
|
|
101
101
|
HARNESS_ATTRIBUTE = re.compile(r"kani::(?:should_panic(?:\(\)|\[\]|\{\})?|unwind(?:\([^()]*\)|\[[^\[\]]*\]|\{[^{}]*\}))")
|
|
102
102
|
KANI_TOKEN = re.compile(r"\bkani\s*::\s*(?:assume|any_where|cover|stub|proof|should_panic|unwind)\w*\b")
|
|
103
103
|
ATTRIBUTE = re.compile(r"#\s*(!\s*)?\[")
|
|
104
|
+
STATEMENT_END = re.compile(r"\s*;")
|
|
105
|
+
RUNS_CODE = re.compile(r"[(\[{?]|\b(?:return|break|continue|await|yield)\b")
|
|
104
106
|
INNER_ATTRIBUTE = re.compile(r"[\s\ufeff]*#\s*!\s*\[")
|
|
105
107
|
RENAMING_IMPORT = re.compile(r"\buse\s+[^;]*?(?<![\w:])(?:::\s*)?kani\b[^;]*?(?:\bas\b|\*|\b(?:assume|any_where|cover|stub|proof|should_panic|unwind)\w*\b)|\bextern\s+crate\s+kani\s+as\b")
|
|
106
108
|
|
|
@@ -495,11 +497,14 @@ def kani_surface(path, reader):
|
|
|
495
497
|
raise ValueError(f"{path}:{line}: cannot identify a function owner; write Kani forms in free functions under inline modules, outside macro definitions and impl or trait bodies")
|
|
496
498
|
|
|
497
499
|
surface = Surface()
|
|
498
|
-
spans, read = [], []
|
|
500
|
+
spans, read, covers = [], [], []
|
|
499
501
|
for kind, pattern in MACROS:
|
|
500
502
|
for match in pattern.finditer(mask):
|
|
501
503
|
end = after_closing(mask, match.end() - 1)
|
|
502
504
|
read.append((match.start(), end))
|
|
505
|
+
# A cover whose condition can run code, such as a call or a `return`, can change what its harness checks.
|
|
506
|
+
if kind == "cover" and not RUNS_CODE.search(mask, match.end(), end - 1):
|
|
507
|
+
covers.append((match.start(), end))
|
|
503
508
|
# The generator's explicit type arguments constrain its domain alongside its predicate.
|
|
504
509
|
if kind == "any_where":
|
|
505
510
|
item_kind, expression = "assume", text[match.start():end]
|
|
@@ -514,13 +519,33 @@ def kani_surface(path, reader):
|
|
|
514
519
|
if HARNESS_ATTRIBUTE.fullmatch(item := re.sub(r"\s+", "", mask[start:end])):
|
|
515
520
|
read.append((start, end))
|
|
516
521
|
attributes.setdefault(owner_at(start, attribute=True), []).append(item)
|
|
522
|
+
def body(function):
|
|
523
|
+
# Each cover is an item of its own, so an added cover leaves the body as it was.
|
|
524
|
+
kept, start = [], function.body
|
|
525
|
+
for begin, end in covers:
|
|
526
|
+
if function.body < begin < function.end:
|
|
527
|
+
kept.append(text[start:begin])
|
|
528
|
+
start = semicolon.end() if (semicolon := STATEMENT_END.match(mask, end)) else end
|
|
529
|
+
kept.append(text[start:function.end])
|
|
530
|
+
return normalized(" ".join(kept))
|
|
531
|
+
|
|
532
|
+
harnesses = []
|
|
517
533
|
for match in PROOF.finditer(mask):
|
|
518
534
|
read.append(match.span())
|
|
519
535
|
harness = owner_at(match.start(), attribute=True)
|
|
536
|
+
harnesses.append(harness)
|
|
520
537
|
enclosing = sorted((item for item in functions + modules if item.start <= harness.start and harness.end <= item.end), key=lambda item: item.start)
|
|
521
538
|
guards = cfg_guards(source, [(0, 0, -1)] + [(item.start, item.keyword, item.body) for item in enclosing])
|
|
522
539
|
value = " ".join(filter(None, (declared, guards, *sorted(attributes.get(harness, ())), unread)))
|
|
523
540
|
spans.append((match.start(), f"harness {harness.name}", value))
|
|
541
|
+
spans.append((harness.body, f"body {harness.name}", body(harness)))
|
|
542
|
+
# A function in a module that holds a harness, or under one, such as an input helper, is part of what it checks.
|
|
543
|
+
scopes = {max((module for module in modules if module.start <= harness.start < module.end), key=lambda module: module.start, default=None)
|
|
544
|
+
for harness in harnesses}
|
|
545
|
+
for function in functions:
|
|
546
|
+
nested = any(other.body < function.start < other.end for other in functions)
|
|
547
|
+
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)))
|
|
524
549
|
for token in KANI_TOKEN.finditer(mask):
|
|
525
550
|
if not any(start <= token.start() < end for start, end in read):
|
|
526
551
|
line = mask.count("\n", 0, token.start()) + 1
|
|
@@ -130,14 +130,15 @@ def ready_pin(project):
|
|
|
130
130
|
return toolchain
|
|
131
131
|
|
|
132
132
|
|
|
133
|
-
def step(command, *, merge=True, env=None):
|
|
133
|
+
def step(command, *, merge=True, env=None, label=None):
|
|
134
134
|
"""Run one build step and return its status as a shell reports it, its stdout and its stderr.
|
|
135
135
|
|
|
136
136
|
With merge, stderr joins stdout in the order the step wrote them, and the returned stderr is empty. Lean and Lake
|
|
137
|
-
write UTF-8 whatever the locale, and the frozen records hash that text, so it is read as UTF-8.
|
|
137
|
+
write UTF-8 whatever the locale, and the frozen records hash that text, so it is read as UTF-8. With a label, the
|
|
138
|
+
step reports its elapsed time on stderr as '[lean] <label>: <N>s elapsed'.
|
|
138
139
|
"""
|
|
139
140
|
def collect(process):
|
|
140
|
-
stdout, stderr =
|
|
141
|
+
stdout, stderr = processes.communicate(process, f"[lean] {label}" if label else None)
|
|
141
142
|
status = process.returncode
|
|
142
143
|
return (128 - status if status < 0 else status), stdout, stderr or ""
|
|
143
144
|
try:
|
|
@@ -323,7 +324,7 @@ def checked(project, toolchain, files, freeze, out, work):
|
|
|
323
324
|
if not sources:
|
|
324
325
|
out(f"FAIL {project} has no .lean file to check")
|
|
325
326
|
return 1
|
|
326
|
-
status, objects, log = step([*lake, "query", *(f"{source}:olean" for source in sources)], merge=False)
|
|
327
|
+
status, objects, log = step([*lake, "query", *(f"{source}:olean" for source in sources)], merge=False, label="build")
|
|
327
328
|
log = lines(log)
|
|
328
329
|
sorries = [line for line in log if SORRY.match(line)]
|
|
329
330
|
|
|
@@ -347,7 +348,7 @@ def checked(project, toolchain, files, freeze, out, work):
|
|
|
347
348
|
module_list = work / "modules"
|
|
348
349
|
module_list.write_text("".join(name + "\n" for name in modules), encoding="utf-8")
|
|
349
350
|
audit_status, output, _ = step([*lake, "env", "lean", "--run", str(HERE / "lean-analysis.lean"),
|
|
350
|
-
"audit", *(["--freeze"] if freeze else []), str(module_list)])
|
|
351
|
+
"audit", *(["--freeze"] if freeze else []), str(module_list)], label="audit")
|
|
351
352
|
audit = lines(output)
|
|
352
353
|
if not any(AUDITED.fullmatch(line) for line in audit):
|
|
353
354
|
audit_status = 1
|
|
@@ -425,7 +426,7 @@ def checked(project, toolchain, files, freeze, out, work):
|
|
|
425
426
|
replay_list = work / "replay-modules"
|
|
426
427
|
replay_list.write_text("".join(module + "\n" for module in sorted(replayed)), encoding="utf-8")
|
|
427
428
|
replay_status, output, _ = step([*lake, "env", "lean", str(HERE / "lean-replay.lean")],
|
|
428
|
-
env=os.environ | {"AFV_REPLAY_MODULES": str(replay_list)})
|
|
429
|
+
env=os.environ | {"AFV_REPLAY_MODULES": str(replay_list)}, label="replay")
|
|
429
430
|
replay = "failed" if replay_status else "passed"
|
|
430
431
|
if replay == "failed":
|
|
431
432
|
out(f"FAIL {scope}: kernel replay rejected a built module")
|
|
@@ -53,6 +53,7 @@ if __name__ == "__main__":
|
|
|
53
53
|
if signal.getsignal(signal.SIGINT) is signal.default_int_handler:
|
|
54
54
|
signal.signal(signal.SIGINT, signal.SIG_DFL)
|
|
55
55
|
|
|
56
|
+
import contextlib
|
|
56
57
|
import sys
|
|
57
58
|
import tempfile
|
|
58
59
|
from collections.abc import Callable
|
|
@@ -180,13 +181,17 @@ def check_lean(broken_checks, mutation, work):
|
|
|
180
181
|
return Result(Verdict.DETECTED, "proof/check fails: " + "; ".join(failures), frozenset(failures))
|
|
181
182
|
|
|
182
183
|
|
|
183
|
-
def check_rust(model, project, verifier, bounds, sources, mutation, work):
|
|
184
|
-
"""Run Kani on the named harness in a mutated copy of the crate; the mutation covers that harness.
|
|
184
|
+
def check_rust(model, project, verifier, bounds, sources, kani_work, mutation, work):
|
|
185
|
+
"""Run Kani on the named harness in a mutated copy of the crate; the mutation covers that harness.
|
|
186
|
+
|
|
187
|
+
Each mutation stages a fresh copy into work, and Kani builds every copy in kani_work's target directory,
|
|
188
|
+
so the dependencies compile once per run.
|
|
189
|
+
"""
|
|
185
190
|
copy = sources.stage(project, work)
|
|
186
191
|
covers = frozenset({mutation.detects})
|
|
187
192
|
(copy / model.relative_to(project)).write_text(mutation.apply(), encoding="utf-8")
|
|
188
193
|
# Cargo resolves configuration from cwd, including paths outside the copied packages.
|
|
189
|
-
outcome = kani.verify(copy,
|
|
194
|
+
outcome = kani.verify(copy, kani_work, verifier, mutation.detects, bounds[mutation.detects].unwind, cwd=project)
|
|
190
195
|
if outcome.verdict is kani.Verdict.PASS:
|
|
191
196
|
return Result(Verdict.MISSED, covers=covers)
|
|
192
197
|
if outcome.verdict is kani.Verdict.REFUTED:
|
|
@@ -198,7 +203,7 @@ def project_root(model, *markers):
|
|
|
198
203
|
return next((parent for parent in model.parents if any((parent / marker).is_file() for marker in markers)), None)
|
|
199
204
|
|
|
200
205
|
|
|
201
|
-
def tla_runner(spec, mutations):
|
|
206
|
+
def tla_runner(spec, mutations, run):
|
|
202
207
|
"""Preserve the execution plan of every matching spec section, check TLC once, and pass the unmutated
|
|
203
208
|
spec on every run the mutations select."""
|
|
204
209
|
matrix = spec.with_suffix(".matrix")
|
|
@@ -224,7 +229,7 @@ def tla_runner(spec, mutations):
|
|
|
224
229
|
return plan.properties, partial(check_tla, plan, checker)
|
|
225
230
|
|
|
226
231
|
|
|
227
|
-
def lean_runner(model, mutations):
|
|
232
|
+
def lean_runner(model, mutations, run):
|
|
228
233
|
"""Target the frozen theorems that Lean finds public in the source, including their namespaces."""
|
|
229
234
|
project = project_root(model, "lakefile.toml", "lakefile.lean")
|
|
230
235
|
if project is None:
|
|
@@ -233,34 +238,37 @@ def lean_runner(model, mutations):
|
|
|
233
238
|
return targets, partial(check_lean, broken_checks)
|
|
234
239
|
|
|
235
240
|
|
|
236
|
-
def rust_runner(model, mutations):
|
|
241
|
+
def rust_runner(model, mutations, run):
|
|
242
|
+
"""Discover the harnesses and check the unmutated crate in a Kani work directory that the mutations reuse."""
|
|
237
243
|
project = project_root(model, "Cargo.toml")
|
|
238
244
|
if project is None:
|
|
239
245
|
stop(f"{model} is in no Rust crate")
|
|
240
246
|
verifier = kani.Kani()
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
247
|
+
work = Path(run.enter_context(tempfile.TemporaryDirectory(prefix="formal-kani-", dir=storage.ensure_temp_root())))
|
|
248
|
+
# A temporary root inside the crate holds this directory while the mutations stage copies of the crate.
|
|
249
|
+
kani.tag_cache(work)
|
|
250
|
+
try:
|
|
251
|
+
bounds = kani.discover(project, work, verifier)
|
|
252
|
+
sources = verifier.crate_sources(project)
|
|
253
|
+
for mutation in mutations:
|
|
254
|
+
if mutation.detects not in bounds:
|
|
255
|
+
stop(f"mutation '{mutation.label}': unknown harness '{mutation.detects}'")
|
|
256
|
+
selected = {mutation.detects for mutation in mutations}
|
|
257
|
+
kani.reject_should_panic(bounds, sorted(selected))
|
|
258
|
+
for name in sorted(selected):
|
|
259
|
+
outcome = kani.verify(project, work, verifier, name, bounds[name].unwind)
|
|
260
|
+
if outcome.verdict is not kani.Verdict.PASS:
|
|
261
|
+
stop(f"unmutated Rust harness '{name}' did not pass: "
|
|
262
|
+
+ "; ".join(outcome.failures) + "\n" + outcome.output)
|
|
263
|
+
except kani.CheckError as error:
|
|
264
|
+
stop(str(error))
|
|
258
265
|
targets = {name for name, harness in bounds.items() if harness.source == model} | selected
|
|
259
|
-
return targets, partial(check_rust, model, project, verifier, bounds, sources)
|
|
266
|
+
return targets, partial(check_rust, model, project, verifier, bounds, sources, work)
|
|
260
267
|
|
|
261
268
|
|
|
262
269
|
# Each runner checks the names the mutations detect and that the unmutated model passes the checks they select,
|
|
263
270
|
# then returns the names they must cover and a check for one mutation.
|
|
271
|
+
# A runner can enter a temporary directory into run, an ExitStack that closes after the last mutation.
|
|
264
272
|
# A TLA+ or Rust mutation covers the name it detects; a Lean mutation covers the theorems that fail on it.
|
|
265
273
|
LANGUAGES = {
|
|
266
274
|
".tla": Language("TLA+", needs_detects=True, takes_only=True, runner=tla_runner),
|
|
@@ -287,19 +295,20 @@ def main():
|
|
|
287
295
|
stop(f"no {', '.join(model.name for model in models[:-1])} or {models[-1].name} beside {path}")
|
|
288
296
|
language, text = LANGUAGES[model.suffix], model.read_text(encoding="utf-8")
|
|
289
297
|
mutations = [make_mutation(label, directives, model, text, language) for label, directives in parse(path)]
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
298
|
+
with contextlib.ExitStack() as run:
|
|
299
|
+
targets, check = language.runner(model, mutations, run)
|
|
300
|
+
storage.warn_runtime()
|
|
301
|
+
temp_root = storage.ensure_temp_root()
|
|
302
|
+
|
|
303
|
+
detected, covered = 0, set()
|
|
304
|
+
for mutation in mutations:
|
|
305
|
+
with tempfile.TemporaryDirectory(dir=temp_root) as work:
|
|
306
|
+
result = check(mutation, Path(work))
|
|
307
|
+
if result.verdict is Verdict.ERROR:
|
|
308
|
+
stop(f"mutation '{mutation.label}' did not reach a verdict:\n{result.detail.strip()}")
|
|
309
|
+
detected += result.verdict is Verdict.DETECTED
|
|
310
|
+
covered |= result.covers
|
|
311
|
+
print(f"{result.verdict.value} {mutation.label}" + (f": {result.detail}" if result.detail else ""), flush=True)
|
|
303
312
|
uncovered = sorted(targets - covered)
|
|
304
313
|
for name in uncovered:
|
|
305
314
|
print(f"UNCOVERED {name}")
|
|
@@ -23,6 +23,9 @@ PS_TIMEOUT = 5
|
|
|
23
23
|
MAX_LISTINGS = 50
|
|
24
24
|
# The termination signals that signal_cleanup converts and that a stop holds back until it finishes.
|
|
25
25
|
HANDLED = (signal.SIGINT, signal.SIGTERM, *((signal.SIGHUP,) if hasattr(signal, "SIGHUP") else ()))
|
|
26
|
+
# A labelled command reports its elapsed time on stderr after this many seconds, then at this interval, as TLC runs do.
|
|
27
|
+
PROGRESS_DELAY = 15.0
|
|
28
|
+
PROGRESS_INTERVAL = 30.0
|
|
26
29
|
|
|
27
30
|
|
|
28
31
|
class SignalTerminated(BaseException):
|
|
@@ -226,10 +229,33 @@ def guarded(command, body, **kwargs):
|
|
|
226
229
|
raise
|
|
227
230
|
|
|
228
231
|
|
|
229
|
-
def
|
|
230
|
-
"""
|
|
232
|
+
def communicate(process, label=None):
|
|
233
|
+
"""Return process.communicate(); with a label, write '<label>: <N>s elapsed' to stderr while the process runs."""
|
|
234
|
+
if label is None:
|
|
235
|
+
return process.communicate()
|
|
236
|
+
start = time.monotonic()
|
|
237
|
+
next_report = start + PROGRESS_DELAY
|
|
238
|
+
while True:
|
|
239
|
+
try:
|
|
240
|
+
# A timed-out communicate keeps what it has read, so the next call loses no output.
|
|
241
|
+
return process.communicate(timeout=max(0.05, next_report - time.monotonic()))
|
|
242
|
+
except subprocess.TimeoutExpired:
|
|
243
|
+
now = time.monotonic()
|
|
244
|
+
if now >= next_report:
|
|
245
|
+
# Callers read an OSError as a command that could not start, so a closed stderr must not raise one.
|
|
246
|
+
with suppress(OSError):
|
|
247
|
+
sys.stderr.write(f"{label}: {int(now - start)}s elapsed\n")
|
|
248
|
+
sys.stderr.flush()
|
|
249
|
+
next_report = now + PROGRESS_INTERVAL
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def run_captured(command, *, label=None, **kwargs):
|
|
253
|
+
"""Run a command in the caller's process group and terminate it cleanly on interruption.
|
|
254
|
+
|
|
255
|
+
With a label, report the elapsed time on stderr while the command runs, as communicate does.
|
|
256
|
+
"""
|
|
231
257
|
def collect(process):
|
|
232
|
-
stdout, stderr =
|
|
258
|
+
stdout, stderr = communicate(process, label)
|
|
233
259
|
return subprocess.CompletedProcess(command, process.returncode, stdout, stderr)
|
|
234
260
|
return guarded(command, collect, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, **kwargs)
|
|
235
261
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# Copyright (c) 2026 Michael Denyer
|
|
2
2
|
# SPDX-License-Identifier: GPL-3.0-only
|
|
3
|
-
"""Read Rust source text: blank its comments and string contents, and find where a bracketed span
|
|
3
|
+
"""Read Rust source text: blank its comments and string contents, compact its whitespace, and find where a bracketed span
|
|
4
|
+
ends."""
|
|
4
5
|
import re
|
|
5
6
|
from typing import NamedTuple
|
|
6
7
|
|
|
@@ -64,6 +65,38 @@ def rust_masks(source):
|
|
|
64
65
|
return RustSource("".join(text), "".join(mask), literals)
|
|
65
66
|
|
|
66
67
|
|
|
68
|
+
# A `#` joins a word into a raw identifier or string, such as `r#x`.
|
|
69
|
+
WORD = re.compile(r"[\w#]")
|
|
70
|
+
# A character that can join a neighbour into one token, as `<<`, `&&` and `..=` do.
|
|
71
|
+
OPERATOR = frozenset("!%&*+-./:<=>^|")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def normalized(source):
|
|
75
|
+
"""Return Rust source without comments and without the whitespace outside literals that a reformat can change.
|
|
76
|
+
|
|
77
|
+
One space stays between two word characters, literals or `#`, so `r #x` stays apart from `r#x`, and between two
|
|
78
|
+
operator characters, so `& &x` stays apart from `&&x`.
|
|
79
|
+
"""
|
|
80
|
+
lexed = rust_masks(source)
|
|
81
|
+
text = lexed.uncommented
|
|
82
|
+
inside = {i for start, end in lexed.literals for i in range(start, end)}
|
|
83
|
+
|
|
84
|
+
def kind(i):
|
|
85
|
+
if i in inside or WORD.match(text, i):
|
|
86
|
+
return "word"
|
|
87
|
+
return "operator" if text[i] in OPERATOR else None
|
|
88
|
+
|
|
89
|
+
def space(run):
|
|
90
|
+
if run.start() in inside:
|
|
91
|
+
return run[0]
|
|
92
|
+
if run.start() == 0 or run.end() == len(text):
|
|
93
|
+
return ""
|
|
94
|
+
left = kind(run.start() - 1)
|
|
95
|
+
return " " if left and left == kind(run.end()) else ""
|
|
96
|
+
|
|
97
|
+
return re.sub(r"\s+", space, text)
|
|
98
|
+
|
|
99
|
+
|
|
67
100
|
def after_closing(mask, opener):
|
|
68
101
|
closer = {"(": ")", "[": "]", "{": "}"}[mask[opener]]
|
|
69
102
|
depth = 0
|