agent-formal-verify 0.4.18 → 0.4.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGES.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # Changes
2
2
 
3
+ ## 0.4.19 - Protocols between processes in the TLA+ brief, TLA+ runs with stderr closed, and Kani baseline and mutation fixes
4
+
5
+ Step 1 of the skill now searches for protocols between processes or services, such as retries, timeouts, leases, idempotency keys, queue consumers and webhook handlers, and the TLA+ brief says how to model them: lost and repeated messages and crashes are separate actions that constants inject at any point, a timeout can fire whenever a caller waits, each send remains separately deliverable, including a retry with the same payload, and messages can arrive in any order, a crash keeps only durable state and a restart runs the recovery code, a request can still take effect after its caller times out, and a lease can expire while its holder still acts. The brief says which of these steps get fairness. Such a model checks `TypeOK` and the one promise whose break harms a user, and adds a property from a short list, such as at most one effect per request key or no accepted write with a lower fencing token, only when the code makes that promise. The brief now sizes each step to the atomic unit that the code guarantees, such as a critical section, a compare-and-swap, or a transaction whose isolation or conflict mechanism protects its whole relevant read/decision/write dependency, so row locks or per-key conditions alone do not collapse an unprotected predicate read and later write, and it lists mutations for these protocols.
6
+
7
+ Step 1's search for protocols between processes finds the short terms `ack`, `lease` and `ttl` inside identifiers such as `acquire_lease`, `AckDelivery` and `CACHE_TTL`, which can be the only sign of a protocol in a file, and skips words such as `release`, `packet` and `stack`. The two `rg` commands are in the "Find process protocols" section of `references/helpers.md`.
8
+
9
+ The steps for a failing check, from mapping its trace to the code through reachability, reproduction, the fix and its pull request, moved from step 4 of `SKILL.md` to `references/counter-examples.md`. The skill tells the agent to read that file for each violation, and keeps two of its rules in the body: change code only when the user asked for fixes, and never reword a property to pass. The skill body drops from 23,690 to 21,879 bytes, which leaves room under the 24,000 bytes that Antigravity loads.
10
+
11
+ A TLA+ matrix run, or a mutation run on a TLA+ model, that starts with `stderr` closed now reaches its verdicts, with Java TLC or everystate, and writes no elapsed-time lines. Before this change, Python set `sys.stderr` to `None` in such a process, so the first `[tlc]` or `[everystate]` elapsed-time report stopped the run with an `AttributeError`: a passing matrix run exited 1 and printed nothing after its `ENGINE` line.
12
+
13
+ The baseline now keeps a `kani::cover!` whose condition can run user code, such as a comparison through a user `PartialEq`, a field access that can call `Deref`, or an operator on operands whose types the reader cannot establish. It still omits empty covers, bare boolean values, comparisons of primitive literals and short-circuit combinations of them. A cover such as `kani::cover!(state.next == 3)` is now part of the recorded harness body, so an existing record can report a one-time change for it. Before this change, the baseline discarded such a cover as a simple comparison, so a cover whose comparison made a later assertion pass printed `UNCHANGED`.
14
+
15
+ A Rust mutation run now builds each mutant from its staged copy when the crate or a local dependency has a Cargo build script, including one with a custom name. Each such mutant gets a fresh source and target directory, so its build scripts run against that copy. Other crates still share one target directory across mutants. Before this change, a reused build-script output could point back to the unmutated crate or name a generated file missing from the copy.
16
+
17
+ The baseline now records a helper beside a Kani harness in a module inside a function. Before this change, the reader treated every function nested in another function as covered by its parent, even with no record of the parent, so an edit to such a helper printed `UNCHANGED`.
18
+
19
+ The baseline now names a Kani method by its owner type as written, literal arguments included. Before this change, it blanked the contents of literals in the owner name, so exchanging the implementations for `Input<'a'>` and `Input<'b'>` printed `UNCHANGED`, although the harness then checked other inputs.
20
+
21
+ The baseline now ignores the spacing that rustfmt changes between separate Rust operators, so `let y=&x;` and `let y = &x;` record the same body. It keeps a space that stops two tokens from joining or a comment from opening, and it keeps all punctuation spacing inside macro and attribute inputs, which procedural macros can read. A record from an earlier version compares under the same rules. Before this change, running rustfmt on a harness made the baseline report a changed body.
22
+
23
+
3
24
  ## 0.4.18 - everystate as an optional TLA+ engine, Kani baselines that read methods and report added functions, and elapsed time for Lean mutants
4
25
 
5
26
  Kani baselines now include helper and method signatures. Changing a generator helper from `fn input() -> u16` to `fn input() -> u8` prints `CHANGED` even when its body stays `{ kani::any() }`. Older records show the added signature on the first comparison.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-formal-verify",
3
- "version": "0.4.18",
3
+ "version": "0.4.19",
4
4
  "description": "Model-check protocols with TLA+, prove invariants with Lean 4, and check bounded Rust functions with Kani.",
5
5
  "author": {
6
6
  "name": "Michael Denyer",
@@ -34,7 +34,7 @@ Record the sync commit, the commits read and the answers to two questions in the
34
34
 
35
35
  Then search for new targets in code no model covers, unless the user asked only to recheck the existing models.
36
36
 
37
- Search with `rg` for `pthread_cond`, `pthread_mutex`, `atomic_`, `std::condition_variable`, `sync.Cond`, `chan`, `select`, `asyncio.Condition`, `Semaphore`, `atexit` and `setjmp`. Also search for protocol state names such as `ready`, `stop`, `done`, `finished`, `pending`, `inflight`, `head`, `tail` and `exiting`. Classify each hit:
37
+ Search with `rg` for `pthread_cond`, `pthread_mutex`, `atomic_`, `std::condition_variable`, `sync.Cond`, `chan`, `select`, `asyncio.Condition`, `Semaphore`, `atexit` and `setjmp`. Also search for protocol state names such as `ready`, `stop`, `done`, `finished`, `pending`, `inflight`, `head`, `tail` and `exiting`. For protocols between processes, run the [identifier searches](references/helpers.md#find-process-protocols) for acknowledgements, leases, retries and related operations. Classify each hit:
38
38
 
39
39
  - Model hand-written protocols, including hand-overs, bounded pipelines, queues with ordered output, shutdown, cleanup, retry and lease loops.
40
40
  - Leave data-parallel loops over disjoint indices to ThreadSanitizer or the language's race detector, and say so in the reply.
@@ -45,7 +45,7 @@ For Rust functions, also search for `unsafe`, `as u32`, `as usize`, `checked_`,
45
45
 
46
46
  For each target, list the commits that fixed a bug in its code, from `git log --format='%h %s' -- <source files>`. A fix commit is one whose message, linked issue or added test names a bug in a covered function. A model that passes on the code before a fix would not have caught that bug, so the briefs replay each fix commit in the row as a mutation.
47
47
 
48
- Write a table with one row per target before modelling. A protocol and the arithmetic it depends on are separate targets. For a protocol, record its threads, shared variables, every wait and what wakes it, terminal states such as joined or closed, and resources whose ownership moves. Include slots, buffers, file handles and resources that `close` frees. For a Lean target, record the functions, their integer types and the property. Start with waits that have no escape, resources freed by two paths, and errors raised on a different thread from the one that reports them. Read the whole source file for each target so the model follows the code.
48
+ Write a table with one row per target before modelling. A protocol and the arithmetic it depends on are separate targets. For a protocol, record its threads, shared variables, every wait and what wakes it, terminal states such as joined or closed, and resources whose ownership moves. Between processes, also record the messages, durable state and failure points. Include slots, buffers, file handles and resources that `close` frees. For a Lean target, record the functions, their integer types and the property. Start with waits that have no escape, resources freed by two paths, and errors raised on a different thread from the one that reports them. Read the whole source file for each target so the model follows the code.
49
49
 
50
50
  Then ask the user whether to add an independent review of each model's properties, which costs one more agent per target. Use the host's question tool where it has one, such as `AskUserQuestion` in Claude Code. Do not ask when the request already says whether to review. When the user cannot answer, as in a headless run, skip the review and say in the reply that the properties were not reviewed.
51
51
 
@@ -99,14 +99,7 @@ When the user chose the review, spawn one reviewer per model once these checks p
99
99
 
100
100
  For a closed Lean proof, compare the model's printed differential vectors with the production function in the repository's native test framework. Report the agreement count and integer widths. Claim that the proof describes the code only after this comparison agrees, or state beside the verdict that the vectors were not run.
101
101
 
102
- For each violation, in this order:
103
-
104
- 1. Read the reduced trace that the matrix runner prints under the FAIL line, the inputs that Lean's bounded search prints, or Kani's failed check and playback inputs. Map each step to a code event and source line.
105
- 2. Check reachability against the real constants and callers. If a violation occurs at `Slots=1` while the code ships `Slots=4`, decide whether the trace needs the smaller count or can also occur at the shipped one. Report the first as safe only while the count stays at the shipped value, and the second as a reachable bug. Keep the boundary configuration in the matrix either way.
106
- 3. Reproduce a reachable trace with a deterministic test, a ThreadSanitizer or race-detector run, or a stress loop using the trace's counts. Hooks, a small slot count or barriers can force the interleaving. If no practical reproduction exists, report that limitation and the model configuration that demonstrates the violation. Concrete inputs from Lean or Kani always allow a unit test. If it passes on the production code, correct the model or harness and rerun.
107
- 4. Change code only when the user asked for fixes. Otherwise report the trace, the reproduction and the proposed fix, and stop here. The model then describes the code as written, so its failing check is the record of the bug. Do not reword the property to pass, prove its negation or add runs that expect failure. Mutations for a failing property wait for the fix.
108
- 5. Fix only a violation that shipped settings can reach, and only with a reproduction from step 3 unless none is practical. Report the rest. Apply the smallest fix that prevents the trace, update the model to match, and rerun its matrix, the Lean checker or the Rust checker, then its mutations and any reproducing test. Keep the model and code change together.
109
- 6. When the user asked for commits or pull requests, use one PR per bug. Include the model, its mutations file, the fix and any reproducing test. In the description, name the theorem, `#guard`, TLC property or Kani harness that failed, and say when no test reproduces the bug. Write the rest as the Reply section says.
102
+ For each violation, read the [counter-example steps](references/counter-examples.md) in full and follow them in order: map the trace to the code, check reachability, reproduce, then fix or report. Change code only when the user asked for fixes. Do not reword the property to pass, prove its negation or add runs that expect failure.
110
103
 
111
104
  ## 5. Keep the proof, and record each result once
112
105
 
@@ -0,0 +1,10 @@
1
+ # Counter-examples
2
+
3
+ Take each violation that a check reports through these steps, in this order:
4
+
5
+ 1. Read the reduced trace that the matrix runner prints under the FAIL line, the inputs that Lean's bounded search prints, or Kani's failed check and playback inputs. Map each step to a code event and source line.
6
+ 2. Check reachability against the real constants and callers. If a violation occurs at `Slots=1` while the code ships `Slots=4`, decide whether the trace needs the smaller count or can also occur at the shipped one. Report the first as safe only while the count stays at the shipped value, and the second as a reachable bug. Keep the boundary configuration in the matrix either way.
7
+ 3. Reproduce a reachable trace with a deterministic test, a ThreadSanitizer or race-detector run, or a stress loop using the trace's counts. Hooks, a small slot count or barriers can force the interleaving. If no practical reproduction exists, report that limitation and the model configuration that demonstrates the violation. Concrete inputs from Lean or Kani always allow a unit test. If it passes on the production code, correct the model or harness and rerun.
8
+ 4. Change code only when the user asked for fixes. Otherwise report the trace, the reproduction and the proposed fix, and stop here. The model then describes the code as written, so its failing check is the record of the bug. Do not reword the property to pass, prove its negation or add runs that expect failure. Mutations for a failing property wait for the fix.
9
+ 5. Fix only a violation that shipped settings can reach, and only with a reproduction from item 3 unless none is practical. Report the rest. Apply the smallest fix that prevents the trace, update the model to match, and rerun its matrix, the Lean checker or the Rust checker, then its mutations and any reproducing test. Keep the model and code change together.
10
+ 6. When the user asked for commits or pull requests, use one PR per bug. Include the model, its mutations file, the fix and any reproducing test. In the description, name the theorem, `#guard`, TLC property or Kani harness that failed, and say when no test reproduces the bug. Write the rest as the skill's [Reply section](../SKILL.md#reply) says.
@@ -6,7 +6,7 @@ Detailed behaviour of the verification scripts under `scripts/`. Run each helper
6
6
  - **Matrix runner ([`scripts/tlc-matrix.sh`](../scripts/tlc-matrix.sh))**: runs TLC (or the native `everystate` engine with `-lncheck final` when `TLC_ENGINE=everystate`, requiring no JDK or JAR) with a matrix of constants. It prints an `ENGINE` line naming the checker and version before the first run, then one `PASS` or `FAIL` per run with its state count, then a `SUMMARY` line with the totals (tagged with `(everystate <version>)` when using `everystate`). Stops each run after sixty minutes, or after the limit in `TLC_TIMEOUT` as [setup](setup.md) describes, and forwards periodic elapsed-time and `Progress(...)` updates to `stderr` during long runs. A failing run prints its error trace reduced by [`scripts/tlc_trace.py`](../scripts/tlc_trace.py) to the variables each step changed. Set `TLC_HTML_REPORT=<path>` to also write a self-contained offline HTML report through [`scripts/tlc_report.py`](../scripts/tlc_report.py) with the active engine metadata, the run table, an interactive native SVG state chain, a variable diff panel, and copyable Mermaid `stateDiagram-v2` source for each failing and `reach` witness trace. The runner checks the path after checking the TLA+ engine and before the first run, and a path where it cannot write the report prints an `UNAVAILABLE TLC_HTML_REPORT=...` line with the remedy and exits 3. It replaces the report in one step, and a written report leaves `stdout` and the exit status as they are without one. If the write fails after the runs, the runner prints the same line and exits 1 when a run failed and 3 otherwise. `tlc.py ready` and `mutate.py` ignore the variable. Copy [`examples/tla-template/`](../examples/tla-template/BoundedQueue.tla) to start a spec and its matrix.
7
7
  - **Lean checker ([`scripts/lean-check.sh`](../scripts/lean-check.sh))**: builds every `.lean` file in the pinned Lake project and audits every declaration of every built module. It fails on a build error, a `sorry`, a declaration that rests on an axiom beyond `propext`, `Classical.choice` and `Quot.sound`, or a `.lean` file that no Lake library owns. It checks each `<Property>.witness` theorem against its property's hypotheses, and fails on a witness that states something else, as the [Lean brief](lean-brief.md) describes. It then replays every built module, and every project module it imports, through the Lean kernel with the pin's `leanchecker`, which rejects a declaration that a command added without a kernel check. A pin without `leanchecker`, such as Lean 4.20.0, passes with the replay reported as unavailable. While the build, the audit or the replay runs, the checker writes a line such as `[lean] build: 45s elapsed` to `stderr` after fifteen seconds and every thirty seconds after that. The mutation runner writes the same lines while it runs the checker on the unmutated model. It then writes `[lean] unmutated model: <N>s elapsed` while Lean elaborates that model, and a line such as `[lean] mutation no step: 45s elapsed`, which names the mutation, while Lean elaborates each mutant. Use `--freeze` before the file names to record statement types and definition bodies in each model's `.statements` file before proving it. Freezing permits `sorry` and reports `FROZEN`, not a proof `PASS`. Later checks enforce those records and permit proof changes and added declarations. Given file names after the project, it checks only those files. Copy [`examples/lean-template/Model/BoundedQueue.lean`](../examples/lean-template/Model/BoundedQueue.lean) to start a model.
8
8
  - **Rust checker ([`scripts/kani-check.sh`](../scripts/kani-check.sh))**: runs the pinned Kani on the crate's proof harnesses. It reports each harness's unwind bound and check count, requires a satisfied cover witness in each passing harness, rejects failed checks, and prints concrete playback tests when available. It stops each harness after five minutes, or after the limit in `KANI_HARNESS_TIMEOUT` as [setup](setup.md) describes, and fails a harness that reaches the limit with a message that names the setting. Each harness check, here or in the mutation runner, can take up to that limit, so run the command in the background or with a command timeout longer than the total. While Kani builds the crate or checks a harness, the checker and the mutation runner write a line such as `[kani] proofs::claim_keeps_invariant: 45s elapsed` to `stderr` after fifteen seconds and every thirty seconds after that. When discovery fails because code Kani compiles uses a feature newer than Kani's bundled toolchain (error E0658), the failure names that toolchain, and the [Rust brief](rust-brief.md) says what to rewrite or report. Copy [`examples/kani-template/`](../examples/kani-template/src/lib.rs) for a bounded-queue example.
9
- - **Mutation runner ([`scripts/mutate.py`](../scripts/mutate.py))**: takes a model's `<Name>.mutations` file and applies each listed bug to a temporary copy of the model. It prints `DETECTED` or `MISSED` per mutation with what failed, `UNCOVERED` for a TLA+ property or a Kani harness in the adjacent Rust file that no mutation targets or for a public theorem in a Lean model's `.statements` file whose proof no mutation makes fail, and a `SUMMARY` line. Lean names are fully qualified. A Lean `DETECTED` line means the existing proof fails; it does not establish that the statement is false or its hypotheses can hold. A Lean mutation that changes the statement of a theorem, example or `#guard`, such as renaming a definition that the statement names, reaches no verdict, and so does a mutation that edits the text of a theorem whose proof then fails. The runner matches a failing example or `#guard` to one occurrence in the original model, so a failure in an example or `#guard` that the mutation adds, or in one that it cannot match to a single original occurrence, also reaches no verdict. So does a TLA+ mutation whose check reaches the `TLC_TIMEOUT` limit, or a Kani mutation whose harness reaches the Rust checker's time limit. TLA+ runs inherit `TLC_ENGINE`, print the `ENGINE` line before checking the unmutated model, and tag `SUMMARY` with `(everystate <version>)` when using `everystate`. A mutation with no verdict stops the run with a `FAIL` line. A Lean model needs its `.statements` file before its mutations run. All three templates include a mutations file.
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. Each Rust mutation gets a fresh copy of the source. When the crate or a local dependency has a Cargo build script, each mutation also gets its own target directory so the script runs for that source tree. Otherwise every mutation reuses the same source and target paths to cache dependency builds. It prints `DETECTED` or `MISSED` per mutation with what failed, `UNCOVERED` for a TLA+ property or a Kani harness in the adjacent Rust file that no mutation targets or for a public theorem in a Lean model's `.statements` file whose proof no mutation makes fail, and a `SUMMARY` line. Lean names are fully qualified. A Lean `DETECTED` line means the existing proof fails; it does not establish that the statement is false or its hypotheses can hold. A Lean mutation that changes the statement of a theorem, example or `#guard`, such as renaming a definition that the statement names, reaches no verdict, and so does a mutation that edits the text of a theorem whose proof then fails. The runner matches a failing example or `#guard` to one occurrence in the original model, so a failure in an example or `#guard` that the mutation adds, or in one that it cannot match to a single original occurrence, also reaches no verdict. So does a TLA+ mutation whose check reaches the `TLC_TIMEOUT` limit, or a Kani mutation whose harness reaches the Rust checker's time limit. TLA+ runs inherit `TLC_ENGINE`, print the `ENGINE` line before checking the unmutated model, and tag `SUMMARY` with `(everystate <version>)` when using `everystate`. A mutation with no verdict stops the run with a `FAIL` line. A Lean model needs its `.statements` file before its mutations run. All three templates include a mutations file.
10
10
  - **Sync helper ([`scripts/sync.py`](../scripts/sync.py))**: takes an existing model's files, the source files its header names as `--source` and the functions and shared variables it covers as `--name`, and lists what changed since the model was last synced. [Step 1 of the skill](../SKILL.md#1-pick-the-targets) says what to do with its `SYNC none`, `READ` and `MISSING` lines.
11
11
  - Output:
12
12
  - `SYNC <commit> <reason>` gives the sync commit: the header's `Source read at` commit when `HEAD`'s history contains it, and otherwise the last commit of the model files that qualifies, with the reason the header's commit was not used. For a model file that is also given as `--source`, such as a production file with its Kani harness, a commit qualifies only when it changed the code of the file's `#[cfg(kani)]` items and none of its other code.
@@ -19,12 +19,13 @@ Detailed behaviour of the verification scripts under `scripts/`. Run each helper
19
19
  - Documents, such as `.md`, `.txt` and `.tex` files and `README` or `CHANGELOG` with no extension, TLA+ and Lean model files, and each of the model's files that is not also given as `--source` are not searched, unless a source path has the same extension. They get no `PATH` line, and the `READ` command does not show their changes, such as a changelog entry.
20
20
  - In languages other than Rust, such as C, JavaScript or Python, a mention of a covered name in a comment or a string counts as finding it, so the name gets no `MISSING` line even when only a comment still mentions it.
21
21
  - **Baseline helper ([`scripts/baseline.py`](../scripts/baseline.py))**: records what each model specifies and later names each part that changed. [Steps 2](../SKILL.md#2-prepare-the-tools) and [3](../SKILL.md#3-model-one-target-per-agent) of the skill say when to run `record` and `compare`, list the changes that `compare` reports and say what to do with them.
22
+ - The Kani baseline includes helpers in an inline module declared inside a function when that module holds a harness. A baseline made before support for these modules can lack their helpers. Review those helpers against the original revision and record the file again.
22
23
  - Output of `record <record-file> <model files>`:
23
24
  - `RECORDED <file> <digest>` for each file, with an indented `previous <digest>` line under it when the file's entry had another digest.
24
25
  - An indented `not checked against Kani: <reason>` line: Kani is missing or the harness file's Cargo package does not compile, so the entry holds what the file's text shows alone.
25
26
  - 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
27
  - `UNCHANGED <file>`, `CHANGED <file>` or `NOT CHECKED <file>` for each recorded file, then `SUMMARY <n> unchanged, <m> changed`, which ends with `, <k> not checked` when a file printed `NOT CHECKED`.
27
- - An indented `removed <item>`, or `changed <item>` with its `old:` and `new:` values. A Kani harness's value is the `cfg` guards that can switch it off, followed by its `kani::should_panic` and `kani::unwind(<n>)` attributes and the `unread(...)` note that "Cannot see" describes. When more than one route that the record reads leads to the file, the value holds each route as its crate root's path relative to the harness file's directory and its guards, such as `routes(lib.rs: unguarded; main.rs: cfg(feature = "slow"))`, so adding, removing or guarding any route, or moving a guard from one route to another, changes the harness. The item `body <function>` holds, for a harness and for each other free function or method in an `impl` or trait block in a module that holds a harness or under one, such as an input helper or the `any` of an `impl kani::Arbitrary`, the normalized body without comments, without each `kani::cover!` call whose condition cannot run code, which is an item of its own, and without whitespace except one space where two tokens would otherwise join, such as `{let(window,state)=inputs();...}`. For a helper, the value includes its declaration so a change to a qualifier such as `async`, a parameter, return type or `where` clause is visible even when the body stays the same. An older record shows the added signature on its first comparison. Check it against the recorded revision before recording again. A method's name puts its block's header, without the whitespace that a reformat can change, between angle brackets, such as `proofs::<impl kani::Arbitrary for State>::any`, and its assumptions and covers carry that name. Re-indenting or rewrapping the body leaves it unchanged, but a trailing comma that a formatter adds or removes changes it. A cover whose condition holds a call, a block, an index, `?`, `return`, `break`, `continue`, `await` or `yield` can return early or change a value before an assertion, so it stays in the body, and adding one changes the body. Accept such a change when the `new:` value differs from the `old:` value only by the added cover and its condition only reads values, then record the file again. A record made before bodies were recorded prints `previous baseline did not record harness bodies` once, one made before the other functions' bodies were recorded prints `previous baseline did not record the functions beside its harnesses` once, and one made before the methods' bodies were recorded prints `previous baseline did not record the methods beside its harnesses` once. For those records, check each harness body against the original revision before recording the file again.
28
+ - An indented `removed <item>`, or `changed <item>` with its `old:` and `new:` values. A Kani harness's value is the `cfg` guards that can switch it off, followed by its `kani::should_panic` and `kani::unwind(<n>)` attributes and the `unread(...)` note that "Cannot see" describes. When more than one route that the record reads leads to the file, the value holds each route as its crate root's path relative to the harness file's directory and its guards, such as `routes(lib.rs: unguarded; main.rs: cfg(feature = "slow"))`, so adding, removing or guarding any route, or moving a guard from one route to another, changes the harness. The item `body <function>` holds, for a harness and for each other free function or method in an `impl` or trait block in a module that holds a harness or under one, such as an input helper or the `any` of an `impl kani::Arbitrary`, the normalized body without comments, without each `kani::cover!` call whose condition cannot run code, which is an item of its own, and without whitespace except one space where two tokens would otherwise join, such as `{let(window,state)=inputs();...}`. For a helper, the value includes its declaration so a change to a qualifier such as `async`, a parameter, return type or `where` clause is visible even when the body stays the same. An older record shows the added signature on its first comparison. Check it against the recorded revision before recording again. A method's name preserves literals in its block's header, so `impl Input<'a'>` and `impl Input<'b'>` keep separate records. The name puts the header, without the whitespace that a reformat can change, between angle brackets, such as `proofs::<impl kani::Arbitrary for State>::any`, and its assumptions and covers carry that name. Reformatting `let y=&x;` as `let y = &x;` leaves the body unchanged. A space that separates a compound operator counts, as does spacing between operators inside a macro's input, where the macro can inspect it. A trailing comma that a formatter adds or removes also changes the body. The reader omits an empty cover, a boolean name or literal, a comparison between scalar literals (booleans, numbers, characters or byte characters), and short-circuit combinations of those conditions. It keeps other expressions, including `state.next == 3`, as well as string and byte-string comparisons that can call stubbed library code. Field access can call `Deref` and comparisons can call an implementation of `PartialEq`. Review an added cover with a retained condition for implicit calls and side effects before accepting the change. An older record can report changed bodies once for covers it omitted. Check each reported cover against the original revision before recording the file again. A record made before bodies were recorded prints `previous baseline did not record harness bodies` once, one made before the other functions' bodies were recorded prints `previous baseline did not record the functions beside its harnesses` once, and one made before the methods' bodies were recorded prints `previous baseline did not record the methods beside its harnesses` once. For those records, check each harness body against the original revision before recording the file again.
28
29
  - An indented `added <item>`, which only a new Kani assumption, stub or `body <function>` prints. A function or method added in a module that holds a harness, or under one, can shadow a function that a glob import such as `use super::*;` brings in, so a harness calls the new function with no edit to its own body. Every such function or method prints `added body <function>`, whatever its name, except a new harness, whose body is allowed with it. A harness added in a module that held none puts that module's functions in the record, so each of them prints `added body <function>` once. A record made before the other functions' or the methods' bodies were recorded also prints `added body <function>` for each body it did not record. Check a function that existed at the original revision against that revision. Accept a new function only when each recorded body that names it is listed as added or changed and its change is accepted, and revert it when an unchanged recorded body names it, since that body now calls the new function in place of the one it checked. Then record the file again. A `kani::any_where` assumption includes the complete call, including explicit type arguments. Older records used one representation for plain assumptions and generator predicates. For those records, check the assumptions and generator types against the original revision before recording the file again.
29
30
  - In a TLA+ module where a local `INSTANCE` introduces substitutions, or that has an indented definition outside a `LET` or a column-0 definition inside one, the helper compares the complete text of each local module it loaded, with comments removed, so a change to a definition that no property uses also needs review. So does a column-0 definition whose header the helper cannot read, such as an infix operator, which it records with the operators it references, whether or not a property references it.
30
31
  - An indented `file is missing`: the recorded file no longer exists.
@@ -38,3 +39,14 @@ Detailed behaviour of the verification scripts under `scripts/`. Run each helper
38
39
  - A route that the record cannot read: a `mod` declaration or `include!` inside a macro like `cfg_if!`, including a `mod $name;` that a macro builds, or inside a block such as a function body, a `#[path]` or `include!` whose path it cannot read, or a file on the way that fails to parse. It cannot tell where such a route leads, so `record` prints `route not read: <reason>`, which names the file and, except for a file that fails to parse, the line, for each one in the harness file's crates. It adds each to every harness's value as `unread(<file>: <route>; ...)`, with the file relative to the harness file's directory. Adding or removing such a route prints `CHANGED`. It does not record the route's guards, and Kani's check fails only when the route gives the harness another module path, so a guard changed on it can print no `CHANGED` line; read `git diff` for it. When no route that it reads reaches the file, `record` fails and names each of them.
39
40
  - A Kani harness file outside any Cargo package is read from its text alone, so neither `record` nor `compare` asks Kani which harnesses it compiles.
40
41
  - `baseline.py move <record-file> <old file> <new file>` moves a model's record entry to the file the model moved to, reading the record alone, so a later `compare` checks the new file against what the old one specified, including the harnesses that Kani compiled. For a Kani harness moved into a module of its production file, add `--module <old module> <new module>`, each relative to its file, with `crate` for the file's root, such as `--module crate proofs` for harnesses that sat at the old crate's root, even when the production file is `src/queue.rs`. When the new file already has an entry, the two are merged, and an item in both fails the move. It prints `MOVED <old> -> <new>`. Accept a move when `compare` prints `UNCHANGED`, or `NOT CHECKED` for an entry that `record` could not check against Kani, and `git diff` shows the old file's harness lines in the new module with only their indentation changed, plus the `use crate as <name>;` line and the `#[cfg(kani)] mod proofs` lines around them. When the production file's crate has a route that the record cannot read, `compare` prints a `changed harness` line for each moved harness whose `new:` value only adds an `unread(...)` note to its `old:` value; accept those too, then record the new file again. Any other change, such as an edited assertion, needs the evidence its row cites.
42
+
43
+ ## Find process protocols
44
+
45
+ Run both searches from the repository root. The short terms match identifier components in names such as `acquire_lease`, `AckDelivery` and `CACHE_TTL`. Matching substrings anywhere would also return `release`, `packet` and `stack`.
46
+
47
+ ```sh
48
+ rg -n -e '(^|[^[:alnum:]])(ack|lease|ttl)([^[:lower:]]|$)' \
49
+ -e '(Ack|Lease|Ttl)([^[:lower:]]|$)' \
50
+ -e '(^|[^[:upper:]])(ACK|LEASE|TTL)([^[:lower:]]|$)'
51
+ rg -ni 'acknowledg|retr(y|ies)|time_?out|idempoten|dedup|fencing|for[[:blank:]]+update|compare_?(and_?)?(swap|set|exchange)|web_?hook|consumer'
52
+ ```
@@ -1,6 +1,6 @@
1
1
  # TLA+ modelling brief
2
2
 
3
- Follow this brief to model one thread protocol with TLA+ and TLC. Your task gives the source files and line ranges, the threads and shared variables, the model's `<Name>`, the absolute path `<skill-dir>` and the TLA+ engine settings from setup. Read the whole of each source file so the model follows the code.
3
+ Follow this brief to model one thread or process protocol with TLA+ and TLC. Your task gives the source files and line ranges, the threads and shared variables, the model's `<Name>`, the absolute path `<skill-dir>` and the TLA+ engine settings from setup. Read the whole of each source file so the model follows the code.
4
4
 
5
5
  ## Files
6
6
 
@@ -14,14 +14,23 @@ The row in your task gives the commits since the model was last synced and says
14
14
 
15
15
  Apply each requirement that fits the protocol, and say in the report which did not.
16
16
 
17
- - Use one step per critical section under the mutex and one per unlocked phase, such as build, parse or consume. Add an explicit `lock` variable when multiple lock acquisitions can race.
17
+ - Make each step exactly as large as the atomic unit the code guarantees, such as a critical section under the mutex or one atomic load, store or compare-and-swap. A read followed by a write with no such guarantee is two steps. Use one step per unlocked phase that touches only the thread's own data, such as build, parse or consume. Add an explicit `lock` variable when multiple lock acquisitions can race.
18
+ - Collapse a database transaction's committed effect only when serializable isolation or the actual conflict mechanism protects the whole read/decision/write dependency relevant to the property. Identify which rows, ranges or predicates the locks or conditional writes protect, and why every competing writer must conflict or abort. `SELECT ... FOR UPDATE` alone does not establish this: locking returned rows can leave an empty result or future matching inserts unprotected. A version check or conditional insert can protect one key while leaving a capacity decision over other keys stale. Otherwise, model reads and commit separately. Let a serializable commit fail when the code retries a serialization error, and keep effects outside the database transaction separate.
18
19
  - Use a program counter per thread. Represent a condition-variable wait as a pc value in the wait set. Only a broadcast, signal or spurious wakeup can leave that set. The woken thread must retake the mutex and reread the state before acting. Give spurious wakeups no fairness requirement. In this encoding, a lost wakeup appears as a liveness violation rather than a TLC deadlock. Explain that in the header and check liveness.
19
20
  - Model resource ownership as a variable. Each slot or buffer must be free, in exactly one queue, or held by exactly one thread. Each produced item must be recorded by the consumer, awaiting hand-over, or freed.
20
21
  - When `longjmp`, an exception, a panic or `exit()` can leave a critical section without unlocking, use separate variables for the mutex's actual owner and the lock ownership recorded in the thread's live frames. An unwind can leave these inconsistent and block later acquisitions. Preserve that state so the model can detect the hang. List every allocation and exit call that can run under each lock, including out-of-memory exits.
21
22
  - Let the consumer call `next` any number of times, stop calling, or call `close` from any idle point. Include close before the first call, after the last item and after an error. When the producer has a failure path, let it fail at any item through a constant set `FailAt`.
23
+ - For a protocol between processes or services, give the network and the processes their failures as separate actions: a lost or repeated message, a crash, and a timeout. Inject loss, duplication and crash at any point, through constants such as `LoseAt`, `DupAt` and `CrashAt` whose matrix values cover every point, as `FailAt` does, and let the caller's timer fire at any point while it waits. Allow any in-flight message to arrive next. Keep one entry per send, using a bounded send ID or a count for each payload, so retries with the same request key and payload can both arrive. To model network duplication, deliver a copy without removing it. A crash keeps the durable state and clears the state in memory; a restart action then runs the recovery code. A timeout changes only the caller's state: the request may already have taken effect, or may still arrive and take effect later. For a lease, let the lease expire while its holder still acts on it, as after a pause, so a stale holder's write can reach storage. Give loss, duplication and crash no fairness. Give weak fairness to each process's steps, to delivery of a message that was not lost, to restart, and to the caller's own timer while it waits. Use at least two clients or workers, two or three retries and one crash.
22
24
  - Check small instances and boundary cases. Use slot counts of 1, 2 and the shipped count, item counts of 0, 1, 3 and 5, and one, two and three workers.
23
25
  - Name a reachable state predicate for each blocking or boundary behaviour the properties depend on, such as a full window, an empty queue, a parked waiter or an injected failure. Add `reach <Operator> | <label-substring>` to its matrix section. It selects the first run whose label contains the substring. A command-line filter skips the reach check if it excludes that selected run.
24
26
  - Check `TypeOK`, the ownership partition, delivery order, no delivery after end or error, the documented error-ordering guarantee, and no double free or leak at `closed`. For liveness, check that each blocking call returns, `close` terminates from every allowed calling state, and a run without `close` reaches the end. Require weak fairness on thread steps except consumer choices and spurious wakeups. Add strong fairness on a mutex acquisition only when a counter-example shows pure starvation by a spuriously waking peer. Name that assumption in the spec.
27
+ - For a protocol between processes or services, check `TypeOK` and the promise whose break harms a user, stated in one sentence from the code, such as "a card is charged at most once". Add a property from this list only when the code makes that promise to its callers:
28
+ - an effect happens at most once per request key, under repeated requests and retries;
29
+ - each accepted request is eventually acknowledged or reported as failed, under the fairness above;
30
+ - the lock service grants a lease to at most one process at a time, and storage accepts no write whose fencing token is lower than the highest token it has accepted;
31
+ - no update is lost when two writers read and then write the same record;
32
+ - an acknowledged write survives a crash, when the code itself orders the write to durable storage before the acknowledgement;
33
+ - a retry loop ends, by success or by giving up, including when the server answers every attempt with a permanent error.
25
34
 
26
35
  ## Keep the spec small
27
36
 
@@ -54,7 +63,7 @@ The matrix runner prints PASS or FAIL per run and a SUMMARY line. A failing run
54
63
 
55
64
  Each reach check prints its own PASS with the shortest witness length in states and transitions, or FAIL when the model never reaches the state. Witness searches use one worker and ignore deadlock so they can finish exploring a stopped model; `reach:` mutations run with `TLC_WORKERS` because confirming `UNREACHED` explores the full state graph without a witness trace. Attach each `reach` check—especially those paired with `detects reach:<Operator>`—to the smallest boundary `run` that exercises the predicate rather than large fault-injection configurations. The SUMMARY counts reach checks separately; its state total covers ordinary runs only. Use `detects reach:<Operator>` for a mutation that removes a required state. Reach checks do not count as properties for mutation coverage.
56
65
 
57
- 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. The same detector must pass on the original spec at those settings before a mutant can earn credit. Temporal mutations disable TLC's separate deadlock check so that the temporal property itself must fail; a deadlock alone earns no detection. Revise a property it reports as UNCOVERED, and the property or the mutation behind each MISSED line.
66
+ Before reporting a pass, list mutations that represent plausible code bugs in the mutations file. Try replacing `while` with `if`, removing a broadcast, replacing FIFO order with stack order, leaving a flag set, or taking an item without removing it. For a protocol between processes, also try removing the request-key check, acknowledging before the durable write, retrying a permanent error, splitting a compare-and-swap or transaction the code relies on into a separate read and write, and removing the version or token check from a conditional write. Each mutation names the one property that must fail on it. For each fix commit in your row, add a mutation that restores the behaviour the code had before the fix, with the commit's short hash in its label. The mutation runner applies each to a copy of the spec, using only matrix runs where its named check is in scope. The same detector must pass on the original spec at those settings before a mutant can earn credit. Temporal mutations disable TLC's separate deadlock check so that the temporal property itself must fail; a deadlock alone earns no detection. Revise a property it reports as UNCOVERED, and the property or the mutation behind each MISSED line.
58
67
 
59
68
  ## Report
60
69
 
@@ -65,4 +74,4 @@ Report only after reading the output of both commands. If either exits 3 with `U
65
74
  - each reach predicate, its selected run and witness length;
66
75
  - each FAIL line, with every step of its trace mapped to a code event and `file:line`;
67
76
  - for each counter-example, whether the shipped constants and callers can reach it;
68
- - the real-code constraints the model lacks and the properties it could not express.
77
+ - the real-code constraints the model lacks and the properties it could not express; for a protocol between processes, name the failures it does not inject and what it assumes of clocks, storage durability and database isolation.
@@ -59,6 +59,7 @@ import runner
59
59
  import tlc
60
60
  from kani_reader import KANI_KEY, RouteReader, compiled_problems, kani_surface
61
61
  from lean_records import read_record as read_lean_record
62
+ from rust_source import normalized
62
63
  from surface import STRING, Surface, collapse
63
64
 
64
65
  FORMAT = 2
@@ -328,6 +329,20 @@ def may_omit_generator_types(entry):
328
329
  return not entry.get("generator_types") and any(key.startswith("assume ") for key in entry["surface"])
329
330
 
330
331
 
332
+ def compact_kani_record(surface, current):
333
+ """Earlier records kept spaces between punctuation even where Rust reads two separate operators."""
334
+ compact = {}
335
+ for name, value in surface.items():
336
+ if name not in current and (item := KANI_KEY.fullmatch(name)) and "<" in item[2]:
337
+ name = item[1] + normalized(item[2]) + (item[3] or "")
338
+ if name.startswith("body ") and value != current.get(name):
339
+ value = normalized(value)
340
+ if name in compact:
341
+ raise ValueError(f"operator spacing merges recorded items named {name}; review them and record the file again")
342
+ compact[name] = value
343
+ return compact
344
+
345
+
331
346
  class KaniKind:
332
347
  """Record, compare and move the harnesses, assumptions, covers and stubs of a Kani file, checked against what Kani compiles."""
333
348
 
@@ -356,10 +371,11 @@ class KaniKind:
356
371
 
357
372
  def changes(self, entry, path):
358
373
  surface = kani_surface(path, self.reader)
359
- lines = differences(entry["surface"], surface, ("assume", "stub"))
374
+ recorded_surface = compact_kani_record(entry["surface"], surface)
375
+ lines = differences(recorded_surface, surface, ("assume", "stub"))
360
376
  # An added function or method can shadow one that a glob import such as `use super::*;` brings in, so a
361
377
  # harness calls it with no edit to a recorded body. An added harness's own body is allowed with it.
362
- lines += [f" added {name}" for name in surface if name.startswith("body ") and name not in entry["surface"]
378
+ lines += [f" added {name}" for name in surface if name.startswith("body ") and name not in recorded_surface
363
379
  and "harness " + name.removeprefix("body ") not in surface]
364
380
  if may_omit_generator_types(entry):
365
381
  lines.insert(0, " previous baseline stored assumptions without distinguishing any_where input types; review the original assumptions and record this file again")
@@ -79,6 +79,7 @@ class CargoMetadata:
79
79
  workspace: Path
80
80
  target: Path
81
81
  packages: tuple
82
+ local_build_script: bool
82
83
 
83
84
 
84
85
  def tag_cache(directory):
@@ -90,6 +91,7 @@ def tag_cache(directory):
90
91
  class CrateSources:
91
92
  roots: set
92
93
  outputs: set
94
+ local_build_script: bool = False
93
95
 
94
96
  def stage(self, crate, work):
95
97
  """Copy local packages in their relative layout, omitting Cargo's build directories."""
@@ -171,13 +173,13 @@ class Kani:
171
173
  except OSError as error:
172
174
  raise CheckError(f"cannot execute Kani: {error}") from error
173
175
 
174
- def cargo_metadata(self, crate, resolve=False):
176
+ def cargo_metadata(self, crate, resolve=False, *, cwd=None):
175
177
  """Read package declarations; resolve only when finding the full local source graph."""
176
178
  try:
177
179
  done = processes.run_captured(
178
180
  [str(self.cargo), "metadata", *([] if resolve else ["--no-deps"]), "--format-version", "1",
179
181
  "--manifest-path", str(crate / "Cargo.toml")],
180
- cwd=crate, env=self.env)
182
+ cwd=cwd or crate, env=self.env)
181
183
  except OSError as error:
182
184
  raise CheckError(f"cannot read Cargo metadata: {error}") from error
183
185
  if done.returncode:
@@ -189,13 +191,16 @@ class Kani:
189
191
  workspace = Path(report["workspace_root"])
190
192
  target = Path(report["target_directory"])
191
193
  packages = []
194
+ local_build_script = False
192
195
  for package in report["packages"]:
193
196
  if package["source"] is None:
197
+ if any("custom-build" in item["kind"] for item in package["targets"]):
198
+ local_build_script = True
194
199
  packages.append(Path(package["manifest_path"]).parent)
195
200
  packages.extend(Path(dep["path"]) for dep in package["dependencies"] if "path" in dep)
196
201
  if not all(path.is_absolute() for path in (workspace, target, *packages)):
197
202
  raise CheckError("Cargo metadata returned a relative source path")
198
- return CargoMetadata(workspace, target, tuple(packages))
203
+ return CargoMetadata(workspace, target, tuple(packages), local_build_script)
199
204
  except (ValueError, KeyError, TypeError) as error:
200
205
  raise CheckError(f"malformed Cargo metadata: {error}") from error
201
206
 
@@ -209,6 +214,7 @@ class Kani:
209
214
  continue
210
215
  visited.add(directory)
211
216
  metadata = self.cargo_metadata(directory, resolve=directory == crate)
217
+ sources.local_build_script |= metadata.local_build_script
212
218
  sources.roots.update((metadata.workspace.resolve(), directory))
213
219
  sources.outputs.add(metadata.target.parent.resolve() / metadata.target.name)
214
220
  pending.update(path.resolve() for path in metadata.packages)
@@ -232,15 +238,15 @@ def read_json(path):
232
238
  raise CheckError(f"missing or invalid Kani report {path.name}: {error}") from error
233
239
 
234
240
 
235
- def compiled(crate, work, kani):
241
+ def compiled(crate, work, kani, *, cwd=None):
236
242
  """Return each proof harness that Kani compiles in crate's targets, one per target that compiles it.
237
243
 
238
244
  It compiles harness metadata without `list`, which writes into the source directory.
239
245
  """
240
246
  if not (crate / "Cargo.toml").is_file():
241
247
  raise CheckError(f"{crate}/Cargo.toml is missing")
242
- workspace = kani.cargo_metadata(crate).workspace
243
- done = invoke(crate, work, kani, "--only-codegen", label="discovery")
248
+ workspace = kani.cargo_metadata(crate, cwd=cwd).workspace
249
+ done = invoke(crate, work, kani, "--only-codegen", cwd=cwd, label="discovery")
244
250
  if done.returncode:
245
251
  output = done.stdout + done.stderr
246
252
  if "error[E0658]" in output:
@@ -266,10 +272,10 @@ def compiled(crate, work, kani):
266
272
  return found
267
273
 
268
274
 
269
- def discover(crate, work, kani):
275
+ def discover(crate, work, kani, *, cwd=None):
270
276
  """Return the checker's harnesses in crate by name: each `#[kani::proof]` with its unwind bound and source."""
271
277
  harnesses = {}
272
- for harness in compiled(crate, work, kani):
278
+ for harness in compiled(crate, work, kani, cwd=cwd):
273
279
  if harness.attributes.get("kind") != "Proof":
274
280
  continue
275
281
  bound = harness.attributes.get("unwind_value")
@@ -33,7 +33,7 @@ RUST_ITEM = re.compile(r"\b(fn|mod)\s+((?:r#)?\w+)\b|\b(impl|trait)\b")
33
33
  INCLUDE = re.compile(r"\binclude\s*!$")
34
34
 
35
35
 
36
- def rust_functions(mask):
36
+ def rust_functions(source):
37
37
  """Locate free functions, methods in `impl` and trait blocks outside function bodies, inline modules, out-of-line
38
38
  `mod name;` declarations and `include!(...)` items outside function bodies and those blocks; leave macro and
39
39
  other item bodies opaque, and return the `impl` and trait blocks apart.
@@ -41,6 +41,7 @@ def rust_functions(mask):
41
41
  A method's name puts its block's header between angle brackets, such as `proofs::<impl kani::Arbitrary for
42
42
  State>::any`. A declaration's or an include's body is its `;`.
43
43
  """
44
+ mask = source.without_comments_or_strings
44
45
  functions, modules, opaque, declarations, includes, blocks, counts = [], [], [], [], [], [], {}
45
46
 
46
47
  def add_include(boundary, header, stop, in_body):
@@ -76,7 +77,7 @@ def rust_functions(mask):
76
77
  continue
77
78
  # A block's items are no module's items, so an include! or mod in it is no route.
78
79
  blocks.append((i, stop))
79
- walk(i + 1, stop - 1, (*namespace, f"<{normalized(mask[item[2]:i])}>"), in_body=True, in_block=True)
80
+ walk(i + 1, stop - 1, (*namespace, f"<{normalized(source.uncommented[item[2]:i])}>"), in_body=True, in_block=True)
80
81
  elif item and not macro:
81
82
  kind, name, keyword = item
82
83
  qualified = (*namespace, name)
@@ -118,11 +119,28 @@ HARNESS_ATTRIBUTE = re.compile(r"kani::(?:should_panic(?:\(\)|\[\]|\{\})?|unwind
118
119
  KANI_TOKEN = re.compile(r"\bkani\s*::\s*(?:assume|any_where|cover|stub|proof|should_panic|unwind)\w*\b")
119
120
  ATTRIBUTE = re.compile(r"#\s*(!\s*)?\[")
120
121
  STATEMENT_END = re.compile(r"\s*;")
121
- RUNS_CODE = re.compile(r"[(\[{?]|\b(?:return|break|continue|await|yield)\b")
122
+ # The mask blanks character contents. String comparisons can call stubbed library code.
123
+ SCALAR_LITERAL = r"""(?:true|false|-?[0-9]\w*(?:\.[0-9]\w*)?(?:[eE][+-][0-9_]+)?|b?'\s*')"""
124
+ LITERAL_COMPARISON = re.compile(rf"{SCALAR_LITERAL}\s*(?:==|!=|<=|>=|<|>)\s*{SCALAR_LITERAL}")
125
+ BOOLEAN_NAME = re.compile(r"(?:r#)?[^\W\d]\w*")
122
126
  INNER_ATTRIBUTE = re.compile(r"[\s\ufeff]*#\s*!\s*\[")
123
127
  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")
124
128
 
125
129
 
130
+ def inert_cover(arguments):
131
+ """Only omit conditions that cannot call an overloaded Rust operator or access a field via Deref."""
132
+ condition = arguments.partition(",")[0].strip()
133
+ if not condition:
134
+ return True
135
+ for part in re.split(r"&&|\|\|", condition):
136
+ operand = part.strip()
137
+ if operand in ("return", "break", "continue", "yield"):
138
+ return False
139
+ if not BOOLEAN_NAME.fullmatch(operand) and not LITERAL_COMPARISON.fullmatch(operand):
140
+ return False
141
+ return True
142
+
143
+
126
144
  def applies_cfg(attribute):
127
145
  """Return whether a compact `cfg_attr(predicate, attribute, ...)` applies a cfg or a module path in its own
128
146
  attribute list."""
@@ -247,7 +265,7 @@ HIDDEN_ROUTE = re.compile(r"\bmod\s+(?:\$\w+|(?:r#)?\w+)\s*;|\binclude\s*!\s*[(\
247
265
  def parse_rust(path):
248
266
  source = rust_masks(path.read_text(encoding="utf-8"))
249
267
  mask = source.without_comments_or_strings
250
- functions, modules, opaque, declarations, includes, blocks = rust_functions(mask)
268
+ functions, modules, opaque, declarations, includes, blocks = rust_functions(source)
251
269
  hidden = {}
252
270
  for start, end in opaque + blocks + [(function.body, function.end) for function in functions]:
253
271
  for match in HIDDEN_ROUTE.finditer(mask, start, end):
@@ -500,7 +518,7 @@ def kani_surface(path, reader):
500
518
  text, mask = source.uncommented, source.without_comments_or_strings
501
519
  if renaming := RENAMING_IMPORT.search(mask):
502
520
  raise ValueError(f"{path}: '{collapse(renaming[0])}' brings a Kani assumption, cover, stub, harness or harness attribute in under another name; write each as kani::<name> so the record can read it")
503
- functions, modules, opaque, *_ = rust_functions(mask)
521
+ functions, modules, opaque, *_ = rust_functions(source)
504
522
  declared = route_label(path, reader.routes(path))
505
523
  unread = unread_label(path, reader.unread(path))
506
524
 
@@ -522,7 +540,7 @@ def kani_surface(path, reader):
522
540
  end = after_closing(mask, match.end() - 1)
523
541
  read.append((match.start(), end))
524
542
  # A cover whose condition can run code, such as a call or a `return`, can change what its harness checks.
525
- if kind == "cover" and not RUNS_CODE.search(mask, match.end(), end - 1):
543
+ if kind == "cover" and inert_cover(mask[match.end():end - 1]):
526
544
  covers.append((match.start(), end))
527
545
  # The generator's explicit type arguments constrain its domain alongside its predicate.
528
546
  if kind == "any_where":
@@ -561,10 +579,13 @@ def kani_surface(path, reader):
561
579
  # A function in a module that holds a harness, or under one, such as an input helper, is part of what it checks.
562
580
  scopes = {max((module for module in modules if module.start <= harness.start < module.end), key=lambda module: module.start, default=None)
563
581
  for harness in harnesses}
582
+ recorded_end = 0
564
583
  for function in functions:
565
- nested = any(other.body < function.start < other.end for other in functions)
566
- if function not in harnesses and not nested and any(scope is None or scope.start <= function.start < scope.end for scope in scopes):
567
- spans.append((function.body, f"body {function.name}", body(function, function.start)))
584
+ if function.start >= recorded_end and any(scope is None or scope.start <= function.start < scope.end for scope in scopes):
585
+ # Functions arrive in source order. A recorded outer body already includes its local items.
586
+ recorded_end = function.end
587
+ if function not in harnesses:
588
+ spans.append((function.body, f"body {function.name}", body(function, function.start)))
568
589
  for token in KANI_TOKEN.finditer(mask):
569
590
  if not any(start <= token.start() < end for start, end in read):
570
591
  line = mask.count("\n", 0, token.start()) + 1
@@ -191,10 +191,15 @@ def check_lean(broken_checks, mutation, work):
191
191
  def check_rust(model, project, verifier, bounds, sources, kani_work, mutation, work):
192
192
  """Run Kani on the named harness in a mutated copy of the crate; the mutation covers that harness.
193
193
 
194
- Each mutation stages a fresh copy into work, and Kani builds every copy in kani_work's target directory,
195
- so the dependencies compile once per run.
194
+ A local build script can both save an absolute source path and generate files inside the source tree.
195
+ It must run for each fresh copy. Otherwise preserve the paths of both source and target for Cargo.
196
196
  """
197
- copy = sources.stage(project, work)
197
+ if sources.local_build_script:
198
+ kani_work = work
199
+ else:
200
+ kani.tag_cache(work)
201
+ (kani_work / "source").rename(work / "previous")
202
+ copy = sources.stage(project, kani_work)
198
203
  covers = frozenset({mutation.detects})
199
204
  (copy / model.relative_to(project)).write_text(mutation.apply(), encoding="utf-8")
200
205
  # Cargo resolves configuration from cwd, including paths outside the copied packages.
@@ -253,24 +258,24 @@ def rust_runner(model, mutations, run):
253
258
  stop(f"{model} is in no Rust crate")
254
259
  verifier = kani.Kani()
255
260
  work = Path(run.enter_context(tempfile.TemporaryDirectory(prefix="formal-kani-", dir=storage.ensure_temp_root())))
256
- # A temporary root inside the crate holds this directory while the mutations stage copies of the crate.
257
- kani.tag_cache(work)
258
261
  try:
259
- bounds = kani.discover(project, work, verifier)
260
262
  sources = verifier.crate_sources(project)
263
+ copy = sources.stage(project, work)
264
+ bounds = kani.discover(copy, work, verifier, cwd=project)
261
265
  for mutation in mutations:
262
266
  if mutation.detects not in bounds:
263
267
  stop(f"mutation '{mutation.label}': unknown harness '{mutation.detects}'")
264
268
  selected = {mutation.detects for mutation in mutations}
265
269
  kani.reject_should_panic(bounds, sorted(selected))
266
270
  for name in sorted(selected):
267
- outcome = kani.verify(project, work, verifier, name, bounds[name].unwind)
271
+ outcome = kani.verify(copy, work, verifier, name, bounds[name].unwind, cwd=project)
268
272
  if outcome.verdict is not kani.Verdict.PASS:
269
273
  stop(f"unmutated Rust harness '{name}' did not pass: "
270
274
  + "; ".join(outcome.failures) + "\n" + outcome.output)
271
275
  except kani.CheckError as error:
272
276
  stop(str(error))
273
- targets = {name for name, harness in bounds.items() if harness.source == model} | selected
277
+ staged_model = copy / model.relative_to(project)
278
+ targets = {name for name, harness in bounds.items() if harness.source == staged_model} | selected
274
279
  return Prepared(targets, partial(check_rust, model, project, verifier, bounds, sources, work))
275
280
 
276
281
 
@@ -67,32 +67,43 @@ def rust_masks(source):
67
67
 
68
68
  # A `#` joins a word into a raw identifier or string, such as `r#x`.
69
69
  WORD = re.compile(r"[\w#]")
70
- # A character that can join a neighbour into one token, as `<<`, `&&` and `..=` do.
71
- OPERATOR = frozenset("!%&*+-./:<=>^|")
70
+ # Include comment openers: removing the space in a division followed by a dereference would start a comment.
71
+ COMPOUND = {"==", "!=", "<=", ">=", "&&", "||", "+=", "-=", "*=", "/=", "%=", "^=", "&=", "|=",
72
+ "<<", ">>", "<<=", ">>=", "->", "=>", "::", "..", "...", "..=", "//", "/*"}
73
+ PUNCTUATION = re.compile("|".join(re.escape(op) for op in sorted(COMPOUND, key=len, reverse=True)) + r"|[!%&*+./:<=>^|-]")
74
+ MACRO_GROUP = re.compile(r"(?:\bmacro_rules\s*!\s*\w+\s*|\b\w+\s*!\s*)[({\[]|#\s*!?\s*\[")
72
75
 
73
76
 
74
77
  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
- """
78
+ """Compact Rust source while keeping literals, token boundaries and punctuation spacing inside macro inputs."""
80
79
  lexed = rust_masks(source)
81
80
  text = lexed.uncommented
82
81
  inside = {i for start, end in lexed.literals for i in range(start, end)}
83
82
 
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
83
+ mask = lexed.without_comments_or_strings
84
+ punctuation = {match.end(): match[0] for match in PUNCTUATION.finditer(mask)}
85
+ # A procedural macro sees joint punctuation even when Rust has no compound operator for it.
86
+ macro_spaces = set()
87
+ end = 0
88
+ while match := MACRO_GROUP.search(mask, end):
89
+ end = after_closing(mask, match.end() - 1)
90
+ macro_spaces.update(run.start() for run in re.compile(r"\s+").finditer(mask, match.end(), end))
91
+
92
+ def word(i):
93
+ return i in inside or WORD.match(text, i)
88
94
 
89
95
  def space(run):
90
- if run.start() in inside:
96
+ start, end = run.span()
97
+ if start in inside:
91
98
  return run[0]
92
- if run.start() == 0 or run.end() == len(text):
99
+ if start == 0 or end == len(text):
93
100
  return ""
94
- left = kind(run.start() - 1)
95
- return " " if left and left == kind(run.end()) else ""
101
+ if word(start - 1) and word(end):
102
+ return " "
103
+ left = punctuation.get(start)
104
+ if left and (left + text[end] in COMPOUND or start in macro_spaces and PUNCTUATION.match(mask, end)):
105
+ return " "
106
+ return ""
96
107
 
97
108
  return re.sub(r"\s+", space, text)
98
109
 
@@ -50,6 +50,7 @@ import sys
50
50
  import tempfile
51
51
  import time
52
52
  import uuid
53
+ from contextlib import suppress
53
54
  from dataclasses import dataclass, replace
54
55
  from enum import Enum
55
56
  from pathlib import Path
@@ -224,8 +225,12 @@ class _Engine:
224
225
  elapsed = int(now - start)
225
226
  prefix = f"[{self.log_tag}] {progress_label}: " if progress_label else f"[{self.log_tag}] "
226
227
  body = f"{elapsed}s elapsed: {latest}" if latest else f"{elapsed}s elapsed"
227
- sys.stderr.write(f"{prefix}{body}\n")
228
- sys.stderr.flush()
228
+ # Python sets sys.stderr to None when the process starts with stderr closed.
229
+ # A closed or unwritable stderr must not fail a run whose checker passed.
230
+ if sys.stderr is not None:
231
+ with suppress(OSError):
232
+ sys.stderr.write(f"{prefix}{body}\n")
233
+ sys.stderr.flush()
229
234
  next_report = now + PROGRESS_INTERVAL
230
235
  wait_for = min(remaining, max(0.05, next_report - time.monotonic()))
231
236
  try: