agent-formal-verify 0.4.18 → 0.4.20

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,44 @@
1
1
  # Changes
2
2
 
3
+ ## 0.4.20 - Protocols between processes routed to TLA+, per-engine helper notes, TLC sandbox reporting, and mutation and Kani baseline fixes
4
+
5
+ The skill now sends protocols between processes, such as message delivery, retries, leases and crash recovery, to TLA+ in any language. Kani stays the choice for a bounded sequential Rust function, and Lean for sequential properties in other languages or proofs for every size. Before this change, the checker table named only thread interleavings, and the skill preferred Kani for any Rust function whose inputs and loops can be bounded.
6
+
7
+ The mutation runner now prints a `FAIL` line for every malformed mutation in the file before it stops, and names the lines where `-` text that occurs more than once starts, as in `its - text occurs 3 times in <model>, want 1 (lines 12, 40, 77)`. Before this change, it stopped at the first malformed mutation, so a file with two stale mutations took two runs, and a repeated `-` text took a search of the model to find.
8
+
9
+ `references/helpers.md` now holds what every engine shares, and the matrix runner, Lean checker and Rust checker, with the TLA+ and Kani parts of the baseline helper, moved to `references/tla-helpers.md`, `references/lean-helpers.md` and `references/rust-helpers.md`. The skill reads the shared file with the part for each target's engine. Each line moved unchanged. A Lean or TLA+ target now reads 9.6 KB or 10.5 KB of helper notes in place of 22.1 KB, and a Rust target 18.3 KB. Before this change, reading the helper reference with a brief in one command overflowed the inline output limit in two of six eval traces, and the agent read only a 2 KB preview.
10
+
11
+ A Java TLC run that cannot listen on a local port, as under a sandbox that denies network binding, now makes the matrix and mutation runners print an `UNAVAILABLE` line and exit 3. The line names two remedies: run where processes may listen on localhost, or set `TLC_ENGINE=everystate`, which opens no port. TLC's fingerprint set is an RMI object, so every run opens a port, even on one machine. Before this change, each run printed `FAIL ... TLC threw an unexpected exception`, which reads as a model failure, and the agent searched the references for a fix that they do not hold.
12
+
13
+ The TLA+, Lean and Rust briefs now give the mutations file's syntax: a `mutation` line, the `detects` line each engine needs, `-` lines that quote consecutive model lines occurring once, and `+` lines that replace them. Before this change, only `mutate.py`'s own header and the review brief gave it. A Lean eval run grepped the helper reference and read `mutate.py`'s source to learn how to replace several lines, and a Kani run wrote a mutation with two `detects` lines.
14
+
15
+ Kani baseline comparison reports `added body <function>` for a new proof harness when previously recorded code uses its name. Check whether the new harness shadows a function that an existing proof calls or takes as a function value.
16
+
17
+ A Kani check, a Lean check or a TLA+ run whose `stderr` reader exits while the check runs, such as `head -n 1`, now exits with its verdict's code. Before this change, the elapsed-time line that could not be written stayed in Python's `stderr` buffer, and the flush at shutdown failed on it again, so a passing check exited 120.
18
+
19
+ The Kani baseline reads a function's body after a braced const argument in its return type or where clause, a braced type macro, or the never return type. Older records can contain a const expression in place of the body or omit the function. Review affected functions against the original revision and record them again.
20
+
21
+ ## 0.4.19 - Protocols between processes in the TLA+ brief, TLA+ runs with stderr closed, and Kani baseline and mutation fixes
22
+
23
+ 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.
24
+
25
+ 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`.
26
+
27
+ 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.
28
+
29
+ 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.
30
+
31
+ 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`.
32
+
33
+ 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.
34
+
35
+ 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`.
36
+
37
+ 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.
38
+
39
+ 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.
40
+
41
+
3
42
  ## 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
43
 
5
44
  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.20",
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",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: formal-verify
3
- description: "Model-check thread protocols with TLA+ and TLC, prove sequential invariants with Lean 4, and check bounded Rust functions with Kani. Map counter-examples to source locations, reproductions and fixes, and keep the models in CI. Bring existing models back in line after the code changes. Use for /agent-formal-verify:formal-verify, formal verification, model checking, Lean proofs, Kani, bounded Rust verification, rechecking models after code changes, or concurrency bugs that runtime tests cannot reproduce."
3
+ description: "Model-check thread and interprocess protocols with TLA+ and TLC, prove sequential invariants with Lean 4, and check bounded Rust functions with Kani. Map counter-examples to source locations, reproductions and fixes, and keep the models in CI. Bring existing models back in line after the code changes. Use for /agent-formal-verify:formal-verify, formal verification, model checking, Lean proofs, Kani, bounded Rust verification, rechecking models after code changes, or concurrency bugs that runtime tests cannot reproduce."
4
4
  ---
5
5
 
6
6
  # Formal verify
@@ -11,13 +11,13 @@ Choose tools according to the target:
11
11
 
12
12
  | What can go wrong | Tool | Why |
13
13
  | --- | --- | --- |
14
- | Thread interleavings that lose wakeups, free resources twice, deliver items twice or out of order, block close, or report errors on the wrong thread | TLA+ with TLC | TLC explores the states of a small instance and reports counter-examples |
14
+ | Thread interleavings (wakeups, ownership, delivery, close, error routing) or interprocess message delivery, retries, leases and crash recovery | TLA+ with TLC | TLC explores the states of a small instance and reports counter-examples |
15
15
  | Overflow, out-of-bounds access, panics and broken invariants in a Rust function with bounded loops | Kani | Kani checks the real code for every input within the stated bounds |
16
16
  | Arithmetic or sequential transitions that break bounds, invariants or encoder round trips, or reach states the code assumes impossible | Lean 4 | Evaluate bounded instances, then prove the property for every size |
17
17
 
18
- Prefer Kani when the function is Rust and its inputs and loops can be bounded, because it checks the production function directly. Use Lean when the property must hold for every size or the code is not Rust.
18
+ Use TLA+ for interprocess behavior in any language. Prefer Kani for a bounded sequential Rust function. Use Lean for sequential properties in other languages or proofs for every size.
19
19
 
20
- A thread protocol that depends on arithmetic such as `slot = item mod window` needs both tools. Use TLA+ for the interleavings with the arithmetic as a constant, and Lean for the arithmetic.
20
+ A protocol that depends on arithmetic such as `slot = item mod window` needs both tools. Use TLA+ for the interleavings with the arithmetic as a constant, and Lean for the arithmetic.
21
21
 
22
22
  Use the tool the user names. When the table gives another tool for part of the target, report what the named tool leaves unchecked.
23
23
 
@@ -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
 
@@ -63,7 +63,7 @@ Each setup command also reports the temporary directory's free space; [tool setu
63
63
 
64
64
  If a system prerequisite such as Java or elan is missing, use the [setup skill](../setup/SKILL.md) to prepare it within the user's installation constraints and existing authorization. Report any prerequisite that cannot be prepared. If `java` on PATH has no runtime, set `JAVA` to a working JDK's `java` binary for the setup helper and the matrix runner.
65
65
 
66
- Read the [helper reference](references/helpers.md) before you interpret a helper's output. It says what each helper checks and prints. The helpers:
66
+ Read the [helper reference](references/helpers.md) and the part for each target's engine, [TLA+](references/tla-helpers.md), [Lean](references/lean-helpers.md) or [Rust](references/rust-helpers.md), before you interpret a helper's output. They say what each helper checks and prints. The helpers:
67
67
 
68
68
  - The setup helper: [`scripts/setup.sh`](scripts/setup.sh)
69
69
  - The matrix runner: [`scripts/tlc-matrix.sh`](scripts/tlc-matrix.sh)
@@ -89,7 +89,7 @@ Name the brief file and leave its text out of the prompt. The [TLA+ brief](refer
89
89
 
90
90
  An agent writes only its own files, `tla/<Name>.tla`, `.matrix` and `.mutations`, `lean/Model/<Name>.lean`, `.mutations` and `.statements`, or the `#[cfg(kani)]` harness module in the production file that defines its Rust function and the `.mutations` file beside it, so parallel agents share none. Give one agent every Rust target in one production file. An existing Lean project keeps its layout and must pin Lean 4.20.0 or later. A Kani harness that an earlier run wrote in a crate of its own moves into its production file when the Rust brief's "Moving a harness" section allows, so it gets an agent even when it passes; otherwise its agent edits it and its `.mutations` file in place.
91
91
 
92
- When the agents have reported, delete each moved harness's old file, and its crate, workspace entry and CI steps once they hold nothing else. Then rerun every check in this thread: the matrix runner on each matrix file, the Lean checker on the whole project without a file name, the Rust checker on each crate, and the mutation runner on each mutations file. Take each verdict from these runs, not from an agent's report. For a moved harness, first run `baseline.py move` as the [helper reference](references/helpers.md) says. Then run `python3 <skill-dir>/scripts/baseline.py compare <record-file>`. It exits 1 and prints CHANGED with the changed parts when a recorded property, fairness condition, matrix line, `.statements` record, Kani harness or helper body, cover or stub changed, a Kani harness was removed, renamed, no longer compiles or had its `cfg` guards changed on a route the record reads, a Kani assumption was added or changed, or a function or method was added beside a Kani harness. Accept a move only as that reference says. Also read `git diff` for each model that existed before this run, for the changes the record does not cover, such as a theorem newly marked `private`, a new guard in a TLA+ action, or a narrowed input in a Kani helper outside the harness's module. Each such change needs the evidence its row cites, a specification correction accepted below, or for a re-freeze another reason the Lean brief permits. Revert any change without it and give the model back to its agent with the reason. Run the comparison again until it exits 0. Report each file that prints `NOT CHECKED` as not checked against Kani.
92
+ When the agents have reported, delete each moved harness's old file, and its crate, workspace entry and CI steps once they hold nothing else. Then rerun every check in this thread: the matrix runner on each matrix file, the Lean checker on the whole project without a file name, the Rust checker on each crate, and the mutation runner on each mutations file. Take each verdict from these runs, not from an agent's report. For a moved harness, first run `baseline.py move` as the [Rust helper reference](references/rust-helpers.md) says. Then run `python3 <skill-dir>/scripts/baseline.py compare <record-file>`. It exits 1 and prints CHANGED with the changed parts when a recorded property, fairness condition, matrix line, `.statements` record, Kani harness or helper body, cover or stub changed, a Kani harness was removed, renamed, no longer compiles or had its `cfg` guards changed on a route the record reads, a Kani assumption was added or changed, or a function or method was added beside a Kani harness. Accept a move only as that reference says. Also read `git diff` for each model that existed before this run, for the changes the record does not cover, such as a theorem newly marked `private`, a new guard in a TLA+ action, or a narrowed input in a Kani helper outside the harness's module. Each such change needs the evidence its row cites, a specification correction accepted below, or for a re-freeze another reason the Lean brief permits. Revert any change without it and give the model back to its agent with the reason. Run the comparison again until it exits 0. Report each file that prints `NOT CHECKED` as not checked against Kani.
93
93
 
94
94
  Accept a specification correction when a reviewer finding, a missed mutation, an UNCOVERED result with source evidence, or a checked witness demonstrates a gap in the old statement. Read the old and proposed guarantees against the callers, record the evidence and decision in the target's row, and permit the corresponding re-freeze even when production code is unchanged. The correction must preserve the intended guarantee or strengthen it over the intended inputs. A broken proof alone does not justify changing a statement. A weaker guarantee or a new assumption excluding shipped inputs needs evidence of an intentional production contract change or the user's explicit agreement. Rerun all checks after the accepted correction and re-freeze. Then run `baseline.py record <record-file>` again on that model's file, and add the previous and new digests it prints to the row.
95
95
 
@@ -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.
@@ -2,11 +2,10 @@
2
2
 
3
3
  Detailed behaviour of the verification scripts under `scripts/`. Run each helper from the target repository using `bash` or `python3` with `<skill-dir>` resolved to the installed `formal-verify` skill directory.
4
4
 
5
+ Each engine has a part of its own: [TLA+](tla-helpers.md), [Lean](lean-helpers.md) and [Rust](rust-helpers.md). Read the part for each target's engine with this file.
6
+
5
7
  - **Setup helper ([`scripts/setup.sh`](../scripts/setup.sh))**: verifies the pinned TLC JAR (`tla`), or `everystate` 0.4.6 or later when `TLC_ENGINE=everystate`, checks the pinned Kani driver and bundled Rust toolchain (`rust`), and is the only helper that installs a Lean toolchain (`lean`).
6
- - **Matrix runner ([`scripts/tlc-matrix.sh`](../scripts/tlc-matrix.sh))**: runs TLC (or the native `everystate` engine with `-lncheck final` when `TLC_ENGINE=everystate`, requiring no JDK or JAR) with a matrix of constants. It prints an `ENGINE` line naming the checker and version before the first run, then one `PASS` or `FAIL` per run with its state count, then a `SUMMARY` line with the totals (tagged with `(everystate <version>)` when using `everystate`). Stops each run after sixty minutes, or after the limit in `TLC_TIMEOUT` as [setup](setup.md) describes, and forwards periodic elapsed-time and `Progress(...)` updates to `stderr` during long runs. A failing run prints its error trace reduced by [`scripts/tlc_trace.py`](../scripts/tlc_trace.py) to the variables each step changed. Set `TLC_HTML_REPORT=<path>` to also write a self-contained offline HTML report through [`scripts/tlc_report.py`](../scripts/tlc_report.py) with the active engine metadata, the run table, an interactive native SVG state chain, a variable diff panel, and copyable Mermaid `stateDiagram-v2` source for each failing and `reach` witness trace. The runner checks the path after checking the TLA+ engine and before the first run, and a path where it cannot write the report prints an `UNAVAILABLE TLC_HTML_REPORT=...` line with the remedy and exits 3. It replaces the report in one step, and a written report leaves `stdout` and the exit status as they are without one. If the write fails after the runs, the runner prints the same line and exits 1 when a run failed and 3 otherwise. `tlc.py ready` and `mutate.py` ignore the variable. Copy [`examples/tla-template/`](../examples/tla-template/BoundedQueue.tla) to start a spec and its matrix.
7
- - **Lean checker ([`scripts/lean-check.sh`](../scripts/lean-check.sh))**: builds every `.lean` file in the pinned Lake project and audits every declaration of every built module. It fails on a build error, a `sorry`, a declaration that rests on an axiom beyond `propext`, `Classical.choice` and `Quot.sound`, or a `.lean` file that no Lake library owns. It checks each `<Property>.witness` theorem against its property's hypotheses, and fails on a witness that states something else, as the [Lean brief](lean-brief.md) describes. It then replays every built module, and every project module it imports, through the Lean kernel with the pin's `leanchecker`, which rejects a declaration that a command added without a kernel check. A pin without `leanchecker`, such as Lean 4.20.0, passes with the replay reported as unavailable. While the build, the audit or the replay runs, the checker writes a line such as `[lean] build: 45s elapsed` to `stderr` after fifteen seconds and every thirty seconds after that. The mutation runner writes the same lines while it runs the checker on the unmutated model. It then writes `[lean] unmutated model: <N>s elapsed` while Lean elaborates that model, and a line such as `[lean] mutation no step: 45s elapsed`, which names the mutation, while Lean elaborates each mutant. Use `--freeze` before the file names to record statement types and definition bodies in each model's `.statements` file before proving it. Freezing permits `sorry` and reports `FROZEN`, not a proof `PASS`. Later checks enforce those records and permit proof changes and added declarations. Given file names after the project, it checks only those files. Copy [`examples/lean-template/Model/BoundedQueue.lean`](../examples/lean-template/Model/BoundedQueue.lean) to start a model.
8
- - **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.
8
+ - **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
9
  - **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
10
  - Output:
12
11
  - `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.
@@ -21,20 +20,20 @@ Detailed behaviour of the verification scripts under `scripts/`. Run each helper
21
20
  - **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
21
  - Output of `record <record-file> <model files>`:
23
22
  - `RECORDED <file> <digest>` for each file, with an indented `previous <digest>` line under it when the file's entry had another digest.
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
23
  - 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
24
  - `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 `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
- - 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.
25
+ - An indented `removed <item>`, or `changed <item>` with its `old:` and `new:` values.
30
26
  - An indented `file is missing`: the recorded file no longer exists.
31
- - An indented `not compiled harness <name>`: Kani compiles a stored harness on no route, such as when `Cargo.toml` drops a default feature that a route's `cfg` needs.
32
- - An indented `not checked against Kani at record, ...`: `record` could not check the file against Kani, so `compare` cannot tell a harness that stopped compiling from one that never compiled, such as one behind a feature that is not a default. When Kani runs at `compare`, an indented `not compiled now harness <name>` follows for each recorded harness that Kani does not compile. When Kani could not run at `compare` either, the next line gives the reason. When nothing else changed, the file prints `NOT CHECKED` instead of `CHANGED`. When `move` merges such an entry with one that `record` checked against Kani, the merged entry keeps the checked entry's harnesses, so `compare` still prints `not compiled harness <name>` for them and needs Kani. A `NOT CHECKED` file does not count as a change, so `compare` exits 0 when no file printed `CHANGED`. Report its harnesses as not checked against Kani, and name each harness on a `not compiled now` line under it.
33
27
  - An indented `FAIL <reason>`: the helper could not read the file or ask Kani, which `compare` needs for a harness file that `record` checked against Kani, or Kani compiles a harness from the file under a name that no route the record reads gives. The reason names the problem.
34
28
  - `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
- - Cannot see:
36
- - In TLA+, the actions that `Spec` names under `[][...]_vars`, `WF_` or `SF_`. It does follow the subscript of those forms and of `<<A>>_vars`, such as `vars`, in every definition it follows, and it follows an operator that `Spec` names outside those forms, such as a fairness definition, into its actions.
37
- - In Kani, the body of a function or method outside the modules that hold harnesses, apart from its assumptions, covers and stubs; read `git diff` for those.
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
- - 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
- - `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.
29
+
30
+ ## Find process protocols
31
+
32
+ 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`.
33
+
34
+ ```sh
35
+ rg -n -e '(^|[^[:alnum:]])(ack|lease|ttl)([^[:lower:]]|$)' \
36
+ -e '(Ack|Lease|Ttl)([^[:lower:]]|$)' \
37
+ -e '(^|[^[:upper:]])(ACK|LEASE|TTL)([^[:lower:]]|$)'
38
+ rg -ni 'acknowledg|retr(y|ies)|time_?out|idempoten|dedup|fencing|for[[:blank:]]+update|compare_?(and_?)?(swap|set|exchange)|web_?hook|consumer'
39
+ ```
@@ -46,7 +46,7 @@ The checker enforces the `.statements` file beside each checked source. Changing
46
46
 
47
47
  The file name limits the Lean checker to your model, so another agent's unfinished file does not fail your check.
48
48
 
49
- List plausible bugs in the mutations file, such as `<` instead of `≤`, a missing `+ 1` or a swapped argument. The mutation runner checks each on a copy of the file and names the theorems and `#guard` lines that fail. Expect both the bounded search's `#guard` and the theorem. It rejects a mutation that stops a definition compiling or changes the statement of a theorem, example or `#guard`, such as renaming a definition that a statement names. Revise the properties behind each MISSED line.
49
+ List plausible bugs in the mutations file, such as `<` instead of `≤`, a missing `+ 1` or a swapped argument. Write each as a `mutation <label>` line, then `-` lines that quote consecutive lines of the model exactly and occur once in it, then `+` lines that replace them. A mutation without `+` lines deletes the quoted text. The mutation runner checks each on a copy of the file and names the theorems and `#guard` lines that fail. Expect both the bounded search's `#guard` and the theorem. It rejects a mutation that stops a definition compiling or changes the statement of a theorem, example or `#guard`, such as renaming a definition that a statement names. Revise the properties behind each MISSED line.
50
50
 
51
51
  The mutation runner checks the original file against its frozen declarations with the Lean checker before running any mutants. It uses Lean's elaborated names and source ranges to report each frozen public theorem whose proof no mutation makes fail. Structure and class projections and instance declarations are not property targets. Names remain fully qualified, including nested namespaces. A failing `#guard` or example does not cover a named theorem. The runner matches a failing guard or example to one original occurrence and compares their elaborated statements. When an edit overlaps a check, preserve the check’s text so the runner can identify a unique occurrence on both sides of the edit. A failure in a new or ambiguous check gives the mutation no verdict. Add a mutation that breaks the proof by changing the model outside the theorem, or propose a specification correction with evidence for the main thread to accept before re-freezing. A helper lemma that shows here should be `private`; a property marked `private` to hide it is a change the main thread reverts. Lean mutations take no `detects` line. 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.
52
52
 
@@ -0,0 +1,5 @@
1
+ # Lean helpers
2
+
3
+ The Lean behaviour of the helpers. The [helper reference](helpers.md) holds what every engine shares; read it first.
4
+
5
+ - **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.
@@ -137,8 +137,10 @@ production crate, and report the target as not checked by Kani. A harness in a
137
137
  separate crate that copies the function checks the copy, not the production
138
138
  code, so report it as a model and name the copied source and commit.
139
139
 
140
- Put `<Name>.mutations` beside the production file `<Name>.rs`. Use
141
- `detects <fully-qualified-harness>` for each mutation. The mutation runner uses
140
+ Put `<Name>.mutations` beside the production file `<Name>.rs`. Write each as a
141
+ `mutation <label>` line, one `detects <fully-qualified-harness>` line, `-`
142
+ lines quoting consecutive lines of `<Name>.rs` that occur once in it, and `+`
143
+ lines replacing them. The mutation runner uses
142
144
  the bundled Cargo to find the crate's workspace and local dependencies, copies
143
145
  them to temporary storage with their relative paths intact, and checks the
144
146
  copied manifest from the original crate directory so Cargo retains configuration
@@ -0,0 +1,19 @@
1
+ # Rust helpers
2
+
3
+ The Kani behaviour of the helpers. The [helper reference](helpers.md) holds what every engine shares; read it first.
4
+
5
+ - **Rust checker ([`scripts/kani-check.sh`](../scripts/kani-check.sh))**: runs the pinned Kani on the crate's proof harnesses. It reports each harness's unwind bound and check count, requires a satisfied cover witness in each passing harness, rejects failed checks, and prints concrete playback tests when available. It stops each harness after five minutes, or after the limit in `KANI_HARNESS_TIMEOUT` as [setup](setup.md) describes, and fails a harness that reaches the limit with a message that names the setting. Each harness check, here or in the mutation runner, can take up to that limit, so run the command in the background or with a command timeout longer than the total. While Kani builds the crate or checks a harness, the checker and the mutation runner write a line such as `[kani] proofs::claim_keeps_invariant: 45s elapsed` to `stderr` after fifteen seconds and every thirty seconds after that. When 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.
6
+ - **Baseline helper ([`scripts/baseline.py`](../scripts/baseline.py))** on a Kani harness file:
7
+ - The Kani baseline includes helpers in an inline module declared inside a function when that module holds a harness. A baseline made before support for these modules can lack their helpers. Review those helpers against the original revision and record the file again.
8
+ - In the output of `record`:
9
+ - An indented `not checked against Kani: <reason>` line: Kani is missing or the harness file's Cargo package does not compile, so the entry holds what the file's text shows alone.
10
+ - In the output of `compare`:
11
+ - A Kani harness's value is the `cfg` guards that can switch it off, followed by its `kani::should_panic` and `kani::unwind(<n>)` attributes and the `unread(...)` note that "Cannot see" describes. When more than one route that the record reads leads to the file, the value holds each route as its crate root's path relative to the harness file's directory and its guards, such as `routes(lib.rs: unguarded; main.rs: cfg(feature = "slow"))`, so adding, removing or guarding any route, or moving a guard from one route to another, changes the harness. The item `body <function>` holds, for a harness and for each other free function or method in an `impl` or trait block in a module that holds a harness or under one, such as an input helper or the `any` of an `impl kani::Arbitrary`, the normalized body without comments, without each `kani::cover!` call whose condition cannot run code, which is an item of its own, and without whitespace except one space where two tokens would otherwise join, such as `{let(window,state)=inputs();...}`. For a helper, the value includes its declaration so a change to a qualifier such as `async`, a parameter, return type or `where` clause is visible even when the body stays the same. 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.
12
+ - An indented `added <item>`, which only a new Kani assumption, stub or `body <function>` prints. A function or method added in a module that holds a harness, or under one, can shadow a function that a glob import such as `use super::*;` brings in, so a harness calls the new function with no edit to its own body. Every such function or method prints `added body <function>`, whatever its name, except a new harness whose name never occurs in previously recorded code. A new proof can shadow a function that an older proof calls or passes as a value. When its name occurs in a recorded body, assumption, stub or cover, check whether the reference resolves to the added proof. References with the same name in different scopes can also trigger this check. 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.
13
+ - An indented `not compiled harness <name>`: Kani compiles a stored harness on no route, such as when `Cargo.toml` drops a default feature that a route's `cfg` needs.
14
+ - An indented `not checked against Kani at record, ...`: `record` could not check the file against Kani, so `compare` cannot tell a harness that stopped compiling from one that never compiled, such as one behind a feature that is not a default. When Kani runs at `compare`, an indented `not compiled now harness <name>` follows for each recorded harness that Kani does not compile. When Kani could not run at `compare` either, the next line gives the reason. When nothing else changed, the file prints `NOT CHECKED` instead of `CHANGED`. When `move` merges such an entry with one that `record` checked against Kani, the merged entry keeps the checked entry's harnesses, so `compare` still prints `not compiled harness <name>` for them and needs Kani. A `NOT CHECKED` file does not count as a change, so `compare` exits 0 when no file printed `CHANGED`. Report its harnesses as not checked against Kani, and name each harness on a `not compiled now` line under it.
15
+ - Cannot see:
16
+ - In Kani, the body of a function or method outside the modules that hold harnesses, apart from its assumptions, covers and stubs; read `git diff` for those.
17
+ - A route that the record cannot read: a `mod` declaration or `include!` inside a macro like `cfg_if!`, including a `mod $name;` that a macro builds, or inside a block such as a function body, a `#[path]` or `include!` whose path it cannot read, or a file on the way that fails to parse. It cannot tell where such a route leads, so `record` prints `route not read: <reason>`, which names the file and, except for a file that fails to parse, the line, for each one in the harness file's crates. It adds each to every harness's value as `unread(<file>: <route>; ...)`, with the file relative to the harness file's directory. Adding or removing such a route prints `CHANGED`. It does not record the route's guards, and Kani's check fails only when the route gives the harness another module path, so a guard changed on it can print no `CHANGED` line; read `git diff` for it. When no route that it reads reaches the file, `record` fails and names each of them.
18
+ - A Kani harness file outside any Cargo package is read from its text alone, so neither `record` nor `compare` asks Kani which harnesses it compiles.
19
+ - `baseline.py move <record-file> <old file> <new file>` moves a model's record entry to the file the model moved to, reading the record alone, so a later `compare` checks the new file against what the old one specified, including the harnesses that Kani compiled. For a Kani harness moved into a module of its production file, add `--module <old module> <new module>`, each relative to its file, with `crate` for the file's root, such as `--module crate proofs` for harnesses that sat at the old crate's root, even when the production file is `src/queue.rs`. When the new file already has an entry, the two are merged, and an item in both fails the move. It prints `MOVED <old> -> <new>`. Accept a move when `compare` prints `UNCHANGED`, or `NOT CHECKED` for an entry that `record` could not check against Kani, and `git diff` shows the old file's harness lines in the new module with only their indentation changed, plus the `use crate as <name>;` line and the `#[cfg(kani)] mod proofs` lines around them. 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.
@@ -34,7 +34,7 @@ python3 <skill-dir>/scripts/mutate.py /path/to/models/Name.mutations
34
34
 
35
35
  The plugin does not download TLC. Save `tla2tools.jar` from the [TLA+ release](https://github.com/tlaplus/tlaplus/releases/tag/v1.7.4) pinned in `scripts/tlc.py` as `~/.cache/tla/tla2tools-v1.7.4.jar`; the setup helper verifies its pinned SHA256 and names that path and release when the file is missing or does not match. Set `TLC_CACHE` to choose another cache directory. Set `TLC_JAR` to use an existing JAR; an explicitly supplied JAR is trusted and must already exist. Matrix and mutation output starts with an `ENGINE` line before any model checks. It gives the version from TLC’s help banner and identifies the pinned release or custom JAR. If a custom build omits its version, the runner records the JAR’s SHA256. The HTML report uses the same label.
36
36
 
37
- With Java TLC, the matrix runner requires the JAR and a working Java runtime; with everystate, it needs neither. It checks for Python 3.9 or later before running, so a failing model can always print its reduced trace. It does not download tools. Each run checks the formula its spec names `Spec` and sees only the modules beside that spec. `TLC_WORKERS` sets the worker count for either engine. Set `TLC_HTML_REPORT=<path>` to write a self-contained offline HTML report (matrix summary, interactive SVG state chain, variable diffs, and copyable Mermaid source for failing and `reach` witness traces) via `scripts/tlc_report.py`; the runner checks the target path after the TLA+ engine and before the first run, prints `UNAVAILABLE` and exits 3 when it cannot write there, and writes the report atomically without changing `stdout` or exit status on success (`tlc.py ready` and `mutate.py` ignore `TLC_HTML_REPORT`). Each run stops after sixty minutes by default; set `TLC_TIMEOUT` to change the limit using a whole number from 1 to 4294967295 with an optional unit `s`, `m` or `h`, such as `90s` or `1h`. For any other value, `setup.sh tla`, the matrix runner and the mutation runner print `UNAVAILABLE` and exit 3 without running TLC. A run that reaches the limit fails with a message naming the limit and `TLC_TIMEOUT`, and a mutation run that reaches it reaches no verdict. During long runs, the runner forwards periodic elapsed-time and `Progress(...)` updates from `tlc.log` to `stderr`. With Java TLC, each run gives the JVM its own `java.io.tmpdir` inside the run directory, so TLC runs started at the same time do not delete each other's copy of the standard modules. A `-Djava.io.tmpdir` in `_JAVA_OPTIONS` overrides it, because the JVM reads that variable after the command line; set the temporary directory with `TMPDIR` instead.
37
+ With Java TLC, the matrix runner requires the JAR and a working Java runtime; with everystate, it needs neither. Java TLC also listens on a local port in every run, even on one machine, so where a sandbox denies that, the matrix and mutation runners print `UNAVAILABLE` and exit 3. There, run the checks with `TLC_ENGINE=everystate`, which opens no port. The matrix runner checks for Python 3.9 or later before running, so a failing model can always print its reduced trace. It does not download tools. Each run checks the formula its spec names `Spec` and sees only the modules beside that spec. `TLC_WORKERS` sets the worker count for either engine. Set `TLC_HTML_REPORT=<path>` to write a self-contained offline HTML report (matrix summary, interactive SVG state chain, variable diffs, and copyable Mermaid source for failing and `reach` witness traces) via `scripts/tlc_report.py`; the runner checks the target path after the TLA+ engine and before the first run, prints `UNAVAILABLE` and exits 3 when it cannot write there, and writes the report atomically without changing `stdout` or exit status on success (`tlc.py ready` and `mutate.py` ignore `TLC_HTML_REPORT`). Each run stops after sixty minutes by default; set `TLC_TIMEOUT` to change the limit using a whole number from 1 to 4294967295 with an optional unit `s`, `m` or `h`, such as `90s` or `1h`. For any other value, `setup.sh tla`, the matrix runner and the mutation runner print `UNAVAILABLE` and exit 3 without running TLC. A run that reaches the limit fails with a message naming the limit and `TLC_TIMEOUT`, and a mutation run that reaches it reaches no verdict. During long runs, the runner forwards periodic elapsed-time and `Progress(...)` updates from `tlc.log` to `stderr`. With Java TLC, each run gives the JVM its own `java.io.tmpdir` inside the run directory, so TLC runs started at the same time do not delete each other's copy of the standard modules. A `-Djava.io.tmpdir` in `_JAVA_OPTIONS` overrides it, because the JVM reads that variable after the command line; set the temporary directory with `TMPDIR` instead.
38
38
 
39
39
  The mutation runner reads `Name.mutations` beside `Name.tla` and `Name.matrix`. For each mutation it copies the spec, replaces the listed text, and runs the matrix runner with the one property the mutation names, so it needs the same tools and settings.
40
40
 
@@ -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. Write each as a `mutation <label>` line and a `detects <Property>` or `detects reach:<Operator>` line that names the one check that must fail on it. An optional `only <label-substring>` line keeps only the matrix runs whose label contains it. Then come `-` lines that quote consecutive lines of the spec exactly and occur once in it, and `+` lines that replace them. A mutation without `+` lines deletes the quoted text. 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.
@@ -0,0 +1,10 @@
1
+ # TLA+ helpers
2
+
3
+ The TLA+ behaviour of the helpers. The [helper reference](helpers.md) holds what every engine shares; read it first.
4
+
5
+ - **Matrix runner ([`scripts/tlc-matrix.sh`](../scripts/tlc-matrix.sh))**: runs TLC (or the native `everystate` engine with `-lncheck final` when `TLC_ENGINE=everystate`, requiring no JDK or JAR) with a matrix of constants. It prints an `ENGINE` line naming the checker and version before the first run, then one `PASS` or `FAIL` per run with its state count, then a `SUMMARY` line with the totals (tagged with `(everystate <version>)` when using `everystate`). Stops each run after sixty minutes, or after the limit in `TLC_TIMEOUT` as [setup](setup.md) describes, and forwards periodic elapsed-time and `Progress(...)` updates to `stderr` during long runs. A failing run prints its error trace reduced by [`scripts/tlc_trace.py`](../scripts/tlc_trace.py) to the variables each step changed. Set `TLC_HTML_REPORT=<path>` to also write a self-contained offline HTML report through [`scripts/tlc_report.py`](../scripts/tlc_report.py) with the active engine metadata, the run table, an interactive native SVG state chain, a variable diff panel, and copyable Mermaid `stateDiagram-v2` source for each failing and `reach` witness trace. The runner checks the path after checking the TLA+ engine and before the first run, and a path where it cannot write the report prints an `UNAVAILABLE TLC_HTML_REPORT=...` line with the remedy and exits 3. It replaces the report in one step, and a written report leaves `stdout` and the exit status as they are without one. If the write fails after the runs, the runner prints the same line and exits 1 when a run failed and 3 otherwise. `tlc.py ready` and `mutate.py` ignore the variable. Copy [`examples/tla-template/`](../examples/tla-template/BoundedQueue.tla) to start a spec and its matrix.
6
+ - **Baseline helper ([`scripts/baseline.py`](../scripts/baseline.py))** on a TLA+ model:
7
+ - In the output of `compare`:
8
+ - In a TLA+ module where a local `INSTANCE` introduces substitutions, or that has an indented definition outside a `LET` or a column-0 definition inside one, the helper compares the complete text of each local module it loaded, with comments removed, so a change to a definition that no property uses also needs review. So does a column-0 definition whose header the helper cannot read, such as an infix operator, which it records with the operators it references, whether or not a property references it.
9
+ - Cannot see:
10
+ - 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.
@@ -20,13 +20,13 @@ 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, or method in an impl or trait block,
23
- such as proofs::<impl kani::Arbitrary for State>::any. Unsupported owners fail. Added covers and harnesses are allowed.
23
+ such as proofs::<impl kani::Arbitrary for State>::any. Unsupported owners fail. Added covers and independent harnesses are allowed.
24
24
  Added assumes and stubs are changes. Also the body of each harness and of each other free function or
25
25
  method in a module that holds a harness, or under one, without its comments, the kani::cover! calls whose
26
26
  conditions cannot run code, and the whitespace that a reformat can change. A helper's record includes
27
27
  its attributes, qualifiers, parameters, return type and where clause as well as its body. An added
28
28
  function or method there is a change, since it can shadow one that a glob import brings in. An added
29
- harness can still have its own body.
29
+ harness is also reported if its name occurs in recorded code.
30
30
  In a Cargo package, also the recorded harnesses that Kani compiles from the file; Kani must give
31
31
  each harness it compiles there a module path that a route the record reads gives, and a harness
32
32
  that no longer compiles is a change.
@@ -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, rust_masks
62
63
  from surface import STRING, Surface, collapse
63
64
 
64
65
  FORMAT = 2
@@ -328,6 +329,53 @@ 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
+
346
+ def kani_references(surface):
347
+ """Collect identifiers from recorded code, including Kani forms stored outside a body."""
348
+ names = set()
349
+ for item, value in surface.items():
350
+ if item.startswith("body "):
351
+ code = re.sub(r"^fn\s+(?:r#)?\w+", "", value)
352
+ elif item.startswith(("assume ", "stub ", "cover ")):
353
+ code = item.partition(" ")[2].rsplit(" in ", 1)[0]
354
+ else:
355
+ continue
356
+ names.update(re.findall(r"(?:r#)?([^\W\d]\w*)", rust_masks(code).without_comments_or_strings))
357
+ return names
358
+
359
+
360
+ def added_kani_bodies(old, new):
361
+ """An added harness can shadow a name an older proof calls or takes as a function value."""
362
+ references = None
363
+ for name in new:
364
+ if not name.startswith("body ") or name in old:
365
+ continue
366
+ owner = name.removeprefix("body ")
367
+ harness = "harness " + owner
368
+ if harness in new:
369
+ if harness in old:
370
+ continue
371
+ if references is None:
372
+ references = kani_references(old)
373
+ leaf = re.sub(r"\[\d+\]$", "", owner.rsplit("::", 1)[-1]).removeprefix("r#")
374
+ if leaf not in references:
375
+ continue
376
+ yield f" added {name}"
377
+
378
+
331
379
  class KaniKind:
332
380
  """Record, compare and move the harnesses, assumptions, covers and stubs of a Kani file, checked against what Kani compiles."""
333
381
 
@@ -356,11 +404,9 @@ class KaniKind:
356
404
 
357
405
  def changes(self, entry, path):
358
406
  surface = kani_surface(path, self.reader)
359
- lines = differences(entry["surface"], surface, ("assume", "stub"))
360
- # An added function or method can shadow one that a glob import such as `use super::*;` brings in, so a
361
- # harness calls it with no edit to a recorded body. An added harness's own body is allowed with it.
362
- lines += [f" added {name}" for name in surface if name.startswith("body ") and name not in entry["surface"]
363
- and "harness " + name.removeprefix("body ") not in surface]
407
+ recorded_surface = compact_kani_record(entry["surface"], surface)
408
+ lines = differences(recorded_surface, surface, ("assume", "stub"))
409
+ lines.extend(added_kani_bodies(recorded_surface, surface))
364
410
  if may_omit_generator_types(entry):
365
411
  lines.insert(0, " previous baseline stored assumptions without distinguishing any_where input types; review the original assumptions and record this file again")
366
412
  if any(name.startswith("harness ") and "body " + name.removeprefix("harness ") not in entry["surface"] for name in entry["surface"]):
@@ -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):
@@ -68,7 +69,16 @@ def rust_functions(mask):
68
69
  elif mask[i] == "{":
69
70
  stop = after_closing(mask, i)
70
71
  header = mask[boundary:i].rstrip()
71
- macro = header.endswith("!") or bool(re.search(r"\bmacro_rules\s*!\s*\w+\s*$", header))
72
+ macro = re.search(r"\b(?:\w+\s*!|macro_rules\s*!\s*\w+)$", header)
73
+ if item and item[0] == "fn":
74
+ # A const argument sits between generic delimiters. A braced type macro names its macro before !.
75
+ # Both belong to the signature; the brace after a never return type opens the function body.
76
+ const_argument = header.endswith(("<", ",", "=")) and re.compile(r"\s*[,>]").match(mask, stop)
77
+ if macro or const_argument:
78
+ if macro:
79
+ opaque.append((i, stop))
80
+ i = stop
81
+ continue
72
82
  if item and item[0] in ("impl", "trait"):
73
83
  # A braced const argument in the header ends before the next generic argument or closing angle.
74
84
  if re.compile(r"\s*[,>]").match(mask, stop):
@@ -76,7 +86,7 @@ def rust_functions(mask):
76
86
  continue
77
87
  # A block's items are no module's items, so an include! or mod in it is no route.
78
88
  blocks.append((i, stop))
79
- walk(i + 1, stop - 1, (*namespace, f"<{normalized(mask[item[2]:i])}>"), in_body=True, in_block=True)
89
+ walk(i + 1, stop - 1, (*namespace, f"<{normalized(source.uncommented[item[2]:i])}>"), in_body=True, in_block=True)
80
90
  elif item and not macro:
81
91
  kind, name, keyword = item
82
92
  qualified = (*namespace, name)
@@ -118,11 +128,28 @@ HARNESS_ATTRIBUTE = re.compile(r"kani::(?:should_panic(?:\(\)|\[\]|\{\})?|unwind
118
128
  KANI_TOKEN = re.compile(r"\bkani\s*::\s*(?:assume|any_where|cover|stub|proof|should_panic|unwind)\w*\b")
119
129
  ATTRIBUTE = re.compile(r"#\s*(!\s*)?\[")
120
130
  STATEMENT_END = re.compile(r"\s*;")
121
- RUNS_CODE = re.compile(r"[(\[{?]|\b(?:return|break|continue|await|yield)\b")
131
+ # The mask blanks character contents. String comparisons can call stubbed library code.
132
+ SCALAR_LITERAL = r"""(?:true|false|-?[0-9]\w*(?:\.[0-9]\w*)?(?:[eE][+-][0-9_]+)?|b?'\s*')"""
133
+ LITERAL_COMPARISON = re.compile(rf"{SCALAR_LITERAL}\s*(?:==|!=|<=|>=|<|>)\s*{SCALAR_LITERAL}")
134
+ BOOLEAN_NAME = re.compile(r"(?:r#)?[^\W\d]\w*")
122
135
  INNER_ATTRIBUTE = re.compile(r"[\s\ufeff]*#\s*!\s*\[")
123
136
  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
137
 
125
138
 
139
+ def inert_cover(arguments):
140
+ """Only omit conditions that cannot call an overloaded Rust operator or access a field via Deref."""
141
+ condition = arguments.partition(",")[0].strip()
142
+ if not condition:
143
+ return True
144
+ for part in re.split(r"&&|\|\|", condition):
145
+ operand = part.strip()
146
+ if operand in ("return", "break", "continue", "yield"):
147
+ return False
148
+ if not BOOLEAN_NAME.fullmatch(operand) and not LITERAL_COMPARISON.fullmatch(operand):
149
+ return False
150
+ return True
151
+
152
+
126
153
  def applies_cfg(attribute):
127
154
  """Return whether a compact `cfg_attr(predicate, attribute, ...)` applies a cfg or a module path in its own
128
155
  attribute list."""
@@ -247,7 +274,7 @@ HIDDEN_ROUTE = re.compile(r"\bmod\s+(?:\$\w+|(?:r#)?\w+)\s*;|\binclude\s*!\s*[(\
247
274
  def parse_rust(path):
248
275
  source = rust_masks(path.read_text(encoding="utf-8"))
249
276
  mask = source.without_comments_or_strings
250
- functions, modules, opaque, declarations, includes, blocks = rust_functions(mask)
277
+ functions, modules, opaque, declarations, includes, blocks = rust_functions(source)
251
278
  hidden = {}
252
279
  for start, end in opaque + blocks + [(function.body, function.end) for function in functions]:
253
280
  for match in HIDDEN_ROUTE.finditer(mask, start, end):
@@ -500,7 +527,7 @@ def kani_surface(path, reader):
500
527
  text, mask = source.uncommented, source.without_comments_or_strings
501
528
  if renaming := RENAMING_IMPORT.search(mask):
502
529
  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)
530
+ functions, modules, opaque, *_ = rust_functions(source)
504
531
  declared = route_label(path, reader.routes(path))
505
532
  unread = unread_label(path, reader.unread(path))
506
533
 
@@ -522,7 +549,7 @@ def kani_surface(path, reader):
522
549
  end = after_closing(mask, match.end() - 1)
523
550
  read.append((match.start(), end))
524
551
  # 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):
552
+ if kind == "cover" and inert_cover(mask[match.end():end - 1]):
526
553
  covers.append((match.start(), end))
527
554
  # The generator's explicit type arguments constrain its domain alongside its predicate.
528
555
  if kind == "any_where":
@@ -561,10 +588,13 @@ def kani_surface(path, reader):
561
588
  # A function in a module that holds a harness, or under one, such as an input helper, is part of what it checks.
562
589
  scopes = {max((module for module in modules if module.start <= harness.start < module.end), key=lambda module: module.start, default=None)
563
590
  for harness in harnesses}
591
+ recorded_end = 0
564
592
  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)))
593
+ if function.start >= recorded_end and any(scope is None or scope.start <= function.start < scope.end for scope in scopes):
594
+ # Functions arrive in source order. A recorded outer body already includes its local items.
595
+ recorded_end = function.end
596
+ if function not in harnesses:
597
+ spans.append((function.body, f"body {function.name}", body(function, function.start)))
568
598
  for token in KANI_TOKEN.finditer(mask):
569
599
  if not any(start <= token.start() < end for start, end in read):
570
600
  line = mask.count("\n", 0, token.start()) + 1
@@ -40,7 +40,9 @@ Mutations file (a line starting with # is a comment):
40
40
 
41
41
  A TLA+ or Rust mutation needs one detects line, and a Lean mutation takes
42
42
  none. The runner reads every mutation and applies it to the model's text
43
- before it runs any tool, so a malformed mutation stops the run first.
43
+ before it runs any tool, so a malformed mutation stops the run first. It
44
+ prints a FAIL line for each malformed mutation, and names the lines where
45
+ - text that occurs more than once starts.
44
46
 
45
47
  Usage: mutate.py <Name.mutations>
46
48
  The environment settings of tlc-matrix.sh apply to TLA+ mutations.
@@ -145,26 +147,41 @@ def parse(path):
145
147
  return mutations
146
148
 
147
149
 
150
+ def occurrences(text, old):
151
+ """Return the start of each occurrence of old in text that does not overlap an earlier one."""
152
+ starts = []
153
+ start = text.find(old) if old else -1
154
+ while start >= 0:
155
+ starts.append(start)
156
+ start = text.find(old, start + len(old))
157
+ return starts
158
+
159
+
148
160
  def make_mutation(label, directives, model, text, language):
149
- """Validate one mutation and locate its edit in the original model."""
161
+ """Validate one mutation and locate its edit in the original model.
162
+
163
+ Raises:
164
+ ValueError: the mutation is malformed, or its - text does not occur exactly once in the model.
165
+ """
150
166
  lines = {keyword: [rest for word, rest in directives if word == keyword] for keyword in DIRECTIVES}
151
167
  for keyword in SINGLE:
152
168
  if len(lines[keyword]) > 1:
153
- stop(f"mutation '{label}' has two {keyword} lines")
169
+ raise ValueError(f"mutation '{label}' has two {keyword} lines")
154
170
  if lines["detects"] and not language.needs_detects:
155
- stop(f"mutation '{label}': {language.name} mutations take no detects line; the runner names the theorems that fail")
171
+ raise ValueError(f"mutation '{label}': {language.name} mutations take no detects line; the runner names the theorems that fail")
156
172
  if language.needs_detects and not lines["detects"]:
157
- stop(f"mutation '{label}' has no detects line")
173
+ raise ValueError(f"mutation '{label}' has no detects line")
158
174
  if lines["only"] and not language.takes_only:
159
- stop(f"mutation '{label}': {language.name} mutations do not support 'only'")
175
+ raise ValueError(f"mutation '{label}': {language.name} mutations do not support 'only'")
160
176
  old = "\n".join(lines["-"])
161
- start = text.find(old) if old else -1
162
- if start < 0 or text.find(old, start + len(old)) >= 0:
163
- count = text.count(old) if old else 0
164
- stop(f"mutation '{label}': its - text occurs {count} times in {model}, want 1")
177
+ starts = occurrences(text, old)
178
+ if len(starts) != 1:
179
+ where = sorted({text.count("\n", 0, start) + 1 for start in starts})
180
+ at = f" (lines {', '.join(map(str, where))})" if len(starts) > 1 else ""
181
+ raise ValueError(f"mutation '{label}': its - text occurs {len(starts)} times in {model}, want 1{at}")
165
182
  detects, only = (lines[keyword][0].strip() if lines[keyword] else "" for keyword in SINGLE)
166
183
  new = "\n".join(lines["+"])
167
- return Mutation(label, detects, only, old, new, text, start)
184
+ return Mutation(label, detects, only, old, new, text, starts[0])
168
185
 
169
186
 
170
187
  def check_tla(plan, checker, mutation, work):
@@ -191,10 +208,15 @@ def check_lean(broken_checks, mutation, work):
191
208
  def check_rust(model, project, verifier, bounds, sources, kani_work, mutation, work):
192
209
  """Run Kani on the named harness in a mutated copy of the crate; the mutation covers that harness.
193
210
 
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.
211
+ A local build script can both save an absolute source path and generate files inside the source tree.
212
+ It must run for each fresh copy. Otherwise preserve the paths of both source and target for Cargo.
196
213
  """
197
- copy = sources.stage(project, work)
214
+ if sources.local_build_script:
215
+ kani_work = work
216
+ else:
217
+ kani.tag_cache(work)
218
+ (kani_work / "source").rename(work / "previous")
219
+ copy = sources.stage(project, kani_work)
198
220
  covers = frozenset({mutation.detects})
199
221
  (copy / model.relative_to(project)).write_text(mutation.apply(), encoding="utf-8")
200
222
  # Cargo resolves configuration from cwd, including paths outside the copied packages.
@@ -253,24 +275,24 @@ def rust_runner(model, mutations, run):
253
275
  stop(f"{model} is in no Rust crate")
254
276
  verifier = kani.Kani()
255
277
  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
278
  try:
259
- bounds = kani.discover(project, work, verifier)
260
279
  sources = verifier.crate_sources(project)
280
+ copy = sources.stage(project, work)
281
+ bounds = kani.discover(copy, work, verifier, cwd=project)
261
282
  for mutation in mutations:
262
283
  if mutation.detects not in bounds:
263
284
  stop(f"mutation '{mutation.label}': unknown harness '{mutation.detects}'")
264
285
  selected = {mutation.detects for mutation in mutations}
265
286
  kani.reject_should_panic(bounds, sorted(selected))
266
287
  for name in sorted(selected):
267
- outcome = kani.verify(project, work, verifier, name, bounds[name].unwind)
288
+ outcome = kani.verify(copy, work, verifier, name, bounds[name].unwind, cwd=project)
268
289
  if outcome.verdict is not kani.Verdict.PASS:
269
290
  stop(f"unmutated Rust harness '{name}' did not pass: "
270
291
  + "; ".join(outcome.failures) + "\n" + outcome.output)
271
292
  except kani.CheckError as error:
272
293
  stop(str(error))
273
- targets = {name for name, harness in bounds.items() if harness.source == model} | selected
294
+ staged_model = copy / model.relative_to(project)
295
+ targets = {name for name, harness in bounds.items() if harness.source == staged_model} | selected
274
296
  return Prepared(targets, partial(check_rust, model, project, verifier, bounds, sources, work))
275
297
 
276
298
 
@@ -302,7 +324,16 @@ def main():
302
324
  if model is None:
303
325
  stop(f"no {', '.join(model.name for model in models[:-1])} or {models[-1].name} beside {path}")
304
326
  language, text = LANGUAGES[model.suffix], model.read_text(encoding="utf-8")
305
- mutations = [make_mutation(label, directives, model, text, language) for label, directives in parse(path)]
327
+ mutations, errors = [], []
328
+ for label, directives in parse(path):
329
+ try:
330
+ mutations.append(make_mutation(label, directives, model, text, language))
331
+ except ValueError as error:
332
+ errors.append(error)
333
+ for error in errors:
334
+ print(f"FAIL {error}")
335
+ if errors:
336
+ sys.exit(1)
306
337
  with contextlib.ExitStack() as run:
307
338
  prepared = language.runner(model, mutations, run)
308
339
  storage.warn_runtime()
@@ -229,6 +229,21 @@ def guarded(command, body, **kwargs):
229
229
  raise
230
230
 
231
231
 
232
+ def report_progress(line):
233
+ """Write a progress line if stderr is available, without changing the checker's exit status."""
234
+ stream = sys.stderr
235
+ if stream is None:
236
+ return
237
+ with suppress(OSError, ValueError):
238
+ if stream is sys.__stderr__:
239
+ # Keep progress out of stderr's buffer: a failed flush there retries at shutdown and sets exit status 120.
240
+ stream.flush()
241
+ with open(stream.fileno(), "w", closefd=False, encoding=stream.encoding, errors=stream.errors) as progress:
242
+ progress.write(line + "\n")
243
+ else:
244
+ print(line, file=stream, flush=True)
245
+
246
+
232
247
  def communicate(process, label=None):
233
248
  """Return process.communicate(); with a label, write '<label>: <N>s elapsed' to stderr while the process runs."""
234
249
  if label is None or sys.stderr is None:
@@ -242,10 +257,7 @@ def communicate(process, label=None):
242
257
  except subprocess.TimeoutExpired:
243
258
  now = time.monotonic()
244
259
  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()
260
+ report_progress(f"{label}: {int(now - start)}s elapsed")
249
261
  next_report = now + PROGRESS_INTERVAL
250
262
 
251
263
 
@@ -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
 
@@ -224,8 +224,7 @@ class _Engine:
224
224
  elapsed = int(now - start)
225
225
  prefix = f"[{self.log_tag}] {progress_label}: " if progress_label else f"[{self.log_tag}] "
226
226
  body = f"{elapsed}s elapsed: {latest}" if latest else f"{elapsed}s elapsed"
227
- sys.stderr.write(f"{prefix}{body}\n")
228
- sys.stderr.flush()
227
+ processes.report_progress(f"{prefix}{body}")
229
228
  next_report = now + PROGRESS_INTERVAL
230
229
  wait_for = min(remaining, max(0.05, next_report - time.monotonic()))
231
230
  try:
@@ -308,7 +307,13 @@ class Tlc(_Engine):
308
307
  command = [self.java, "-XX:+UseParallelGC", f"-Djava.io.tmpdir={java_tmp}", "-cp", self.jar, "tlc2.TLC", "-workers", chosen_workers,
309
308
  *(["-deadlock"] if reach else []), "-cleanup", "-metadir", str(directory / "states"),
310
309
  "-config", str(directory / "MC.cfg"), str(directory / f"{module}.tla")]
311
- return self._run_watched(command, log, progress_label)
310
+ status, output, timed_out = self._run_watched(command, log, progress_label)
311
+ # TLC's fingerprint set is an RMI object, so every run exports it on a local port, even on one machine.
312
+ if "java.rmi.server.ExportException: Listen failed on port" in output:
313
+ raise runner.Unavailable("UNAVAILABLE TLC could not listen on a local port (java.rmi.server.ExportException), which it needs even on one machine; "
314
+ "run the check where processes may listen on localhost, such as outside a sandbox that denies network binding, "
315
+ "or with TLC_ENGINE=everystate, which opens no port")
316
+ return status, output, timed_out
312
317
 
313
318
 
314
319
  class Everystate(_Engine):