agent-formal-verify 0.4.16 → 0.4.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGES.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changes
2
2
 
3
+ ## 0.4.17 - one Cargo build directory per Rust mutation run, and elapsed time for long Kani and Lean runs
4
+
5
+ The Rust mutation runner now builds the crate for discovery, for the unmutated checks and for every mutation in one Cargo target directory, so Kani compiles the crate's dependencies once per run rather than once per mutation. Each mutation still checks a fresh copy of the crate. The target directory is in a temporary directory that the runner removes when it ends, including when `SIGTERM`, `SIGINT` or `SIGHUP` stops it. A copy keeps the modification times of the original files, which can be older than the previous mutant's build, so Kani's Cargo now compares file contents to decide what to rebuild. By modification times alone, such a copy would reuse the mutant's build.
6
+
7
+ The Rust checker, the mutation runner's Kani checks and the Lean checker now report long runs on `stderr` as the TLA+ matrix runner does. After fifteen seconds, and every thirty seconds after that, they write `[kani] discovery: <N>s elapsed` while Kani builds the crate and `[kani] <harness>: <N>s elapsed` while Kani checks a harness. The Lean checker writes `[lean] build: <N>s elapsed`, and the same for `audit` and `replay`. The printed results on `stdout` and the exit status do not change. Before this change, a cold Kani build or a long Lake build printed nothing until it finished.
8
+
3
9
  ## 0.4.16 - Kani harness and helper bodies in the baseline
4
10
 
5
11
  `scripts/baseline.py` now also records the body of each free function other than a harness in a Kani module that holds a harness, or in a module under one, as the item `body <function>`, written as a harness body is. The template's `inputs()` in `mod proofs` is such a function, so changing its `let window: u16 = kani::any();` to `let window: u16 = 1;`, or weakening a predicate that a `kani::assume` in a harness calls, prints `CHANGED`. Before this change, the record read such a function only for its assumptions, covers and stubs, so both printed `UNCHANGED`. A production function outside those modules, such as the template's `claim`, is not recorded, so a production fix still prints `UNCHANGED`. A harness at the root of a file puts every free function in the file in the record. The record still reads a method in an `impl` or trait block, such as an `impl kani::Arbitrary`, and a function outside the modules that hold harnesses, only for their assumptions, covers and stubs. A record made before this change prints `CHANGED` once, with the line `previous baseline did not record the functions beside its harnesses`, when the file has such a function; check each one against the original revision, then record the file again.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-formal-verify",
3
- "version": "0.4.16",
3
+ "version": "0.4.17",
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",
@@ -4,8 +4,8 @@ Detailed behaviour of the verification scripts under `scripts/`. Run each helper
4
4
 
5
5
  - **Setup helper ([`scripts/setup.sh`](../scripts/setup.sh))**: verifies the pinned TLC JAR (`tla`), checks the pinned Kani driver and bundled Rust toolchain (`rust`), and is the only helper that installs a Lean toolchain (`lean`).
6
6
  - **Matrix runner ([`scripts/tlc-matrix.sh`](../scripts/tlc-matrix.sh))**: runs TLC with a matrix of constants and prints one `PASS` or `FAIL` per run with its state count, then a `SUMMARY` line with the totals. Stops each run after sixty minutes, or after the limit in `TLC_TIMEOUT` as [setup](setup.md) describes, and forwards periodic elapsed-time and `Progress(...)` updates to `stderr` during long runs. A failing run prints its error trace reduced by [`scripts/tlc_trace.py`](../scripts/tlc_trace.py) to the variables each step changed. Set `TLC_HTML_REPORT=<path>` to also write a self-contained offline HTML report through [`scripts/tlc_report.py`](../scripts/tlc_report.py) with the run table, an interactive native SVG state chain, a variable diff panel, and copyable Mermaid `stateDiagram-v2` source for each failing and `reach` witness trace. The runner checks the path after Java and TLC and before the first run, and a path where it cannot write the report prints an `UNAVAILABLE TLC_HTML_REPORT=...` line with the remedy and exits 3. It replaces the report in one step, and a written report leaves `stdout` and the exit status as they are without one. If the write fails after the runs, the runner prints the same line and exits 1 when a run failed and 3 otherwise. `tlc.py ready` and `mutate.py` ignore the variable. Copy [`examples/tla-template/`](../examples/tla-template/BoundedQueue.tla) to start a spec and its matrix.
7
- - **Lean checker ([`scripts/lean-check.sh`](../scripts/lean-check.sh))**: builds every `.lean` file in the pinned Lake project and audits every declaration of every built module. It fails on a build error, a `sorry`, a declaration that rests on an axiom beyond `propext`, `Classical.choice` and `Quot.sound`, or a `.lean` file that no Lake library owns. It checks each `<Property>.witness` theorem against its property's hypotheses, and fails on a witness that states something else, as the [Lean brief](lean-brief.md) describes. It then replays every built module, and every project module it imports, through the Lean kernel with the pin's `leanchecker`, which rejects a declaration that a command added without a kernel check. A pin without `leanchecker`, such as Lean 4.20.0, passes with the replay reported as unavailable. Use `--freeze` before the file names to record statement types and definition bodies in each model's `.statements` file before proving it. Freezing permits `sorry` and reports `FROZEN`, not a proof `PASS`. Later checks enforce those records and permit proof changes and added declarations. Given file names after the project, it checks only those files. Copy [`examples/lean-template/Model/BoundedQueue.lean`](../examples/lean-template/Model/BoundedQueue.lean) to start a model.
8
- - **Rust checker ([`scripts/kani-check.sh`](../scripts/kani-check.sh))**: runs the pinned Kani on the crate's proof harnesses. It reports each harness's unwind bound and check count, requires a satisfied cover witness in each passing harness, rejects failed checks, and prints concrete playback tests when available. It stops each harness after five minutes, or after the limit in `KANI_HARNESS_TIMEOUT` as [setup](setup.md) describes, and fails a harness that reaches the limit with a message that names the setting. Each harness check, here or in the mutation runner, can take up to that limit, so run the command in the background or with a command timeout longer than the total. When discovery fails because code Kani compiles uses a feature newer than Kani's bundled toolchain (error E0658), the failure names that toolchain, and the [Rust brief](rust-brief.md) says what to rewrite or report. Copy [`examples/kani-template/`](../examples/kani-template/src/lib.rs) for a bounded-queue example.
7
+ - **Lean checker ([`scripts/lean-check.sh`](../scripts/lean-check.sh))**: builds every `.lean` file in the pinned Lake project and audits every declaration of every built module. It fails on a build error, a `sorry`, a declaration that rests on an axiom beyond `propext`, `Classical.choice` and `Quot.sound`, or a `.lean` file that no Lake library owns. It checks each `<Property>.witness` theorem against its property's hypotheses, and fails on a witness that states something else, as the [Lean brief](lean-brief.md) describes. It then replays every built module, and every project module it imports, through the Lean kernel with the pin's `leanchecker`, which rejects a declaration that a command added without a kernel check. A pin without `leanchecker`, such as Lean 4.20.0, passes with the replay reported as unavailable. While the build, the audit or the replay runs, the checker writes a line such as `[lean] build: 45s elapsed` to `stderr` after fifteen seconds and every thirty seconds after that. Use `--freeze` before the file names to record statement types and definition bodies in each model's `.statements` file before proving it. Freezing permits `sorry` and reports `FROZEN`, not a proof `PASS`. Later checks enforce those records and permit proof changes and added declarations. Given file names after the project, it checks only those files. Copy [`examples/lean-template/Model/BoundedQueue.lean`](../examples/lean-template/Model/BoundedQueue.lean) to start a model.
8
+ - **Rust checker ([`scripts/kani-check.sh`](../scripts/kani-check.sh))**: runs the pinned Kani on the crate's proof harnesses. It reports each harness's unwind bound and check count, requires a satisfied cover witness in each passing harness, rejects failed checks, and prints concrete playback tests when available. It stops each harness after five minutes, or after the limit in `KANI_HARNESS_TIMEOUT` as [setup](setup.md) describes, and fails a harness that reaches the limit with a message that names the setting. Each harness check, here or in the mutation runner, can take up to that limit, so run the command in the background or with a command timeout longer than the total. While Kani builds the crate or checks a harness, the checker and the mutation runner write a line such as `[kani] proofs::claim_keeps_invariant: 45s elapsed` to `stderr` after fifteen seconds and every thirty seconds after that. When discovery fails because code Kani compiles uses a feature newer than Kani's bundled toolchain (error E0658), the failure names that toolchain, and the [Rust brief](rust-brief.md) says what to rewrite or report. Copy [`examples/kani-template/`](../examples/kani-template/src/lib.rs) for a bounded-queue example.
9
9
  - **Mutation runner ([`scripts/mutate.py`](../scripts/mutate.py))**: takes a model's `<Name>.mutations` file and applies each listed bug to a temporary copy of the model. It prints `DETECTED` or `MISSED` per mutation with what failed, `UNCOVERED` for a TLA+ property or a Kani harness in the adjacent Rust file that no mutation targets or for a public theorem in a Lean model's `.statements` file whose proof no mutation makes fail, and a `SUMMARY` line. Lean names are fully qualified. A Lean `DETECTED` line means the existing proof fails; it does not establish that the statement is false or its hypotheses can hold. A Lean mutation that changes the statement of a theorem, example or `#guard`, such as renaming a definition that the statement names, reaches no verdict, and so does a mutation that edits the text of a theorem whose proof then fails. The runner matches a failing example or `#guard` to one occurrence in the original model, so a failure in an example or `#guard` that the mutation adds, or in one that it cannot match to a single original occurrence, also reaches no verdict. So does a TLA+ mutation whose check reaches the TLC time limit, or a Kani mutation whose harness reaches the Rust checker's time limit. A mutation with no verdict stops the run with a `FAIL` line. A Lean model needs its `.statements` file before its mutations run. All three templates include a mutations file.
10
10
  - **Sync helper ([`scripts/sync.py`](../scripts/sync.py))**: takes an existing model's files, the source files its header names as `--source` and the functions and shared variables it covers as `--name`, and lists what changed since the model was last synced. [Step 1 of the skill](../SKILL.md#1-pick-the-targets) says what to do with its `SYNC none`, `READ` and `MISSING` lines.
11
11
  - Output:
@@ -81,6 +81,11 @@ class CargoMetadata:
81
81
  packages: tuple
82
82
 
83
83
 
84
+ def tag_cache(directory):
85
+ """Mark directory with a CACHEDIR.TAG, as Cargo marks its build directories, so staged crate copies omit it."""
86
+ (directory / "CACHEDIR.TAG").write_text("Signature: 8a477f597d28d172789f06886806bc55\n", encoding="ascii")
87
+
88
+
84
89
  @dataclass
85
90
  class CrateSources:
86
91
  roots: set
@@ -91,7 +96,7 @@ class CrateSources:
91
96
  anchor = Path(os.path.commonpath(self.roots))
92
97
  work = work.resolve()
93
98
  # Other mutations can stage into the same workspace-local temporary root.
94
- (work / "CACHEDIR.TAG").write_text("Signature: 8a477f597d28d172789f06886806bc55\n", encoding="ascii")
99
+ tag_cache(work)
95
100
  destination = work / "source"
96
101
 
97
102
  def ignore(directory, names):
@@ -138,6 +143,9 @@ class Kani:
138
143
  "RUSTUP_TOOLCHAIN": str((bundle / "toolchain").resolve()),
139
144
  "PATH": search_path(os.environ.get("PATH"), bundle / "bin", bundle / "pyroot/bin", bundle / "toolchain/bin"),
140
145
  "PYTHONPATH": search_path(os.environ.get("PYTHONPATH"), bundle / "pyroot"),
146
+ # The mutation runner builds crate copies in one target directory. A copy keeps the original's
147
+ # modification times, older than the previous mutant's build, so Cargo must compare contents instead.
148
+ "CARGO_UNSTABLE_CHECKSUM_FRESHNESS": "true",
141
149
  }
142
150
  # A parent cargo (cargo run, cargo test, a build script) exports its rustup toolchain's
143
151
  # lib directory here; the bundled compiler must load only the bundled toolchain.
@@ -153,11 +161,13 @@ class Kani:
153
161
  if done.returncode or not done.stdout.startswith(f"Kani Rust Verifier {self.version} (cargo plugin)\n"):
154
162
  raise runner.Unavailable(f"UNAVAILABLE Kani {self.version} is required; {remedy}")
155
163
 
156
- def run(self, *arguments, cwd=None, tmpdir=None):
164
+ def run(self, *arguments, cwd=None, tmpdir=None, label=None):
165
+ """Run the driver; with a label, report the elapsed time on stderr as '[kani] <label>: <N>s elapsed'."""
157
166
  env = self.env if tmpdir is None else self.env | {"TMPDIR": str(tmpdir)}
158
167
  try:
159
168
  # The driver selects Cargo mode from argv[0]; the Cargo wrapper can auto-install.
160
- return processes.run_captured(["cargo-kani", *arguments], executable=str(self.driver), env=env, cwd=cwd)
169
+ return processes.run_captured(["cargo-kani", *arguments], executable=str(self.driver), env=env, cwd=cwd,
170
+ label=f"[kani] {label}" if label else None)
161
171
  except OSError as error:
162
172
  raise CheckError(f"cannot execute Kani: {error}") from error
163
173
 
@@ -205,13 +215,14 @@ class Kani:
205
215
  return sources
206
216
 
207
217
 
208
- def invoke(crate, work, kani, *arguments, cwd=None):
218
+ def invoke(crate, work, kani, *arguments, cwd=None, label=None):
209
219
  # Kani's tools, such as goto-cc, write their own temporary files to TMPDIR. Keep those in the
210
220
  # work directory, which the runner removes even when it stops a tool partway.
211
221
  tmpdir = work / "tmp"
212
222
  tmpdir.mkdir(parents=True, exist_ok=True)
213
223
  return kani.run("--manifest-path", str(crate / "Cargo.toml"),
214
- "--target-dir", str(work / "target"), "-Z", "stubbing", *arguments, cwd=cwd or crate, tmpdir=tmpdir)
224
+ "--target-dir", str(work / "target"), "-Z", "stubbing", *arguments, cwd=cwd or crate, tmpdir=tmpdir,
225
+ label=label)
215
226
 
216
227
 
217
228
  def read_json(path):
@@ -229,7 +240,7 @@ def compiled(crate, work, kani):
229
240
  if not (crate / "Cargo.toml").is_file():
230
241
  raise CheckError(f"{crate}/Cargo.toml is missing")
231
242
  workspace = kani.cargo_metadata(crate).workspace
232
- done = invoke(crate, work, kani, "--only-codegen")
243
+ done = invoke(crate, work, kani, "--only-codegen", label="discovery")
233
244
  if done.returncode:
234
245
  output = done.stdout + done.stderr
235
246
  if "error[E0658]" in output:
@@ -332,7 +343,7 @@ def verify(crate, work, kani, name, bound, *, cwd=None):
332
343
  "-Z", "unstable-options", "--harness-timeout", kani.timeout,
333
344
  "--export-json", str(result_file),
334
345
  "-Z", "concrete-playback", "--concrete-playback", "print",
335
- "--output-format", "regular", cwd=cwd)
346
+ "--output-format", "regular", cwd=cwd, label=name)
336
347
  except CheckError as error:
337
348
  return Outcome(Verdict.INCONCLUSIVE, 0, [str(error)], "")
338
349
  output = done.stdout + done.stderr
@@ -130,14 +130,15 @@ def ready_pin(project):
130
130
  return toolchain
131
131
 
132
132
 
133
- def step(command, *, merge=True, env=None):
133
+ def step(command, *, merge=True, env=None, label=None):
134
134
  """Run one build step and return its status as a shell reports it, its stdout and its stderr.
135
135
 
136
136
  With merge, stderr joins stdout in the order the step wrote them, and the returned stderr is empty. Lean and Lake
137
- write UTF-8 whatever the locale, and the frozen records hash that text, so it is read as UTF-8.
137
+ write UTF-8 whatever the locale, and the frozen records hash that text, so it is read as UTF-8. With a label, the
138
+ step reports its elapsed time on stderr as '[lean] <label>: <N>s elapsed'.
138
139
  """
139
140
  def collect(process):
140
- stdout, stderr = process.communicate()
141
+ stdout, stderr = processes.communicate(process, f"[lean] {label}" if label else None)
141
142
  status = process.returncode
142
143
  return (128 - status if status < 0 else status), stdout, stderr or ""
143
144
  try:
@@ -323,7 +324,7 @@ def checked(project, toolchain, files, freeze, out, work):
323
324
  if not sources:
324
325
  out(f"FAIL {project} has no .lean file to check")
325
326
  return 1
326
- status, objects, log = step([*lake, "query", *(f"{source}:olean" for source in sources)], merge=False)
327
+ status, objects, log = step([*lake, "query", *(f"{source}:olean" for source in sources)], merge=False, label="build")
327
328
  log = lines(log)
328
329
  sorries = [line for line in log if SORRY.match(line)]
329
330
 
@@ -347,7 +348,7 @@ def checked(project, toolchain, files, freeze, out, work):
347
348
  module_list = work / "modules"
348
349
  module_list.write_text("".join(name + "\n" for name in modules), encoding="utf-8")
349
350
  audit_status, output, _ = step([*lake, "env", "lean", "--run", str(HERE / "lean-analysis.lean"),
350
- "audit", *(["--freeze"] if freeze else []), str(module_list)])
351
+ "audit", *(["--freeze"] if freeze else []), str(module_list)], label="audit")
351
352
  audit = lines(output)
352
353
  if not any(AUDITED.fullmatch(line) for line in audit):
353
354
  audit_status = 1
@@ -425,7 +426,7 @@ def checked(project, toolchain, files, freeze, out, work):
425
426
  replay_list = work / "replay-modules"
426
427
  replay_list.write_text("".join(module + "\n" for module in sorted(replayed)), encoding="utf-8")
427
428
  replay_status, output, _ = step([*lake, "env", "lean", str(HERE / "lean-replay.lean")],
428
- env=os.environ | {"AFV_REPLAY_MODULES": str(replay_list)})
429
+ env=os.environ | {"AFV_REPLAY_MODULES": str(replay_list)}, label="replay")
429
430
  replay = "failed" if replay_status else "passed"
430
431
  if replay == "failed":
431
432
  out(f"FAIL {scope}: kernel replay rejected a built module")
@@ -53,6 +53,7 @@ if __name__ == "__main__":
53
53
  if signal.getsignal(signal.SIGINT) is signal.default_int_handler:
54
54
  signal.signal(signal.SIGINT, signal.SIG_DFL)
55
55
 
56
+ import contextlib
56
57
  import sys
57
58
  import tempfile
58
59
  from collections.abc import Callable
@@ -180,13 +181,17 @@ def check_lean(broken_checks, mutation, work):
180
181
  return Result(Verdict.DETECTED, "proof/check fails: " + "; ".join(failures), frozenset(failures))
181
182
 
182
183
 
183
- def check_rust(model, project, verifier, bounds, sources, mutation, work):
184
- """Run Kani on the named harness in a mutated copy of the crate; the mutation covers that harness."""
184
+ def check_rust(model, project, verifier, bounds, sources, kani_work, mutation, work):
185
+ """Run Kani on the named harness in a mutated copy of the crate; the mutation covers that harness.
186
+
187
+ Each mutation stages a fresh copy into work, and Kani builds every copy in kani_work's target directory,
188
+ so the dependencies compile once per run.
189
+ """
185
190
  copy = sources.stage(project, work)
186
191
  covers = frozenset({mutation.detects})
187
192
  (copy / model.relative_to(project)).write_text(mutation.apply(), encoding="utf-8")
188
193
  # Cargo resolves configuration from cwd, including paths outside the copied packages.
189
- outcome = kani.verify(copy, work, verifier, mutation.detects, bounds[mutation.detects].unwind, cwd=project)
194
+ outcome = kani.verify(copy, kani_work, verifier, mutation.detects, bounds[mutation.detects].unwind, cwd=project)
190
195
  if outcome.verdict is kani.Verdict.PASS:
191
196
  return Result(Verdict.MISSED, covers=covers)
192
197
  if outcome.verdict is kani.Verdict.REFUTED:
@@ -198,7 +203,7 @@ def project_root(model, *markers):
198
203
  return next((parent for parent in model.parents if any((parent / marker).is_file() for marker in markers)), None)
199
204
 
200
205
 
201
- def tla_runner(spec, mutations):
206
+ def tla_runner(spec, mutations, run):
202
207
  """Preserve the execution plan of every matching spec section, check TLC once, and pass the unmutated
203
208
  spec on every run the mutations select."""
204
209
  matrix = spec.with_suffix(".matrix")
@@ -224,7 +229,7 @@ def tla_runner(spec, mutations):
224
229
  return plan.properties, partial(check_tla, plan, checker)
225
230
 
226
231
 
227
- def lean_runner(model, mutations):
232
+ def lean_runner(model, mutations, run):
228
233
  """Target the frozen theorems that Lean finds public in the source, including their namespaces."""
229
234
  project = project_root(model, "lakefile.toml", "lakefile.lean")
230
235
  if project is None:
@@ -233,34 +238,37 @@ def lean_runner(model, mutations):
233
238
  return targets, partial(check_lean, broken_checks)
234
239
 
235
240
 
236
- def rust_runner(model, mutations):
241
+ def rust_runner(model, mutations, run):
242
+ """Discover the harnesses and check the unmutated crate in a Kani work directory that the mutations reuse."""
237
243
  project = project_root(model, "Cargo.toml")
238
244
  if project is None:
239
245
  stop(f"{model} is in no Rust crate")
240
246
  verifier = kani.Kani()
241
- with tempfile.TemporaryDirectory(prefix="formal-kani-discover-", dir=storage.ensure_temp_root()) as temporary:
242
- work = Path(temporary)
243
- try:
244
- bounds = kani.discover(project, work, verifier)
245
- sources = verifier.crate_sources(project)
246
- for mutation in mutations:
247
- if mutation.detects not in bounds:
248
- stop(f"mutation '{mutation.label}': unknown harness '{mutation.detects}'")
249
- selected = {mutation.detects for mutation in mutations}
250
- kani.reject_should_panic(bounds, sorted(selected))
251
- for name in sorted(selected):
252
- outcome = kani.verify(project, work, verifier, name, bounds[name].unwind)
253
- if outcome.verdict is not kani.Verdict.PASS:
254
- stop(f"unmutated Rust harness '{name}' did not pass: "
255
- + "; ".join(outcome.failures) + "\n" + outcome.output)
256
- except kani.CheckError as error:
257
- stop(str(error))
247
+ work = Path(run.enter_context(tempfile.TemporaryDirectory(prefix="formal-kani-", dir=storage.ensure_temp_root())))
248
+ # A temporary root inside the crate holds this directory while the mutations stage copies of the crate.
249
+ kani.tag_cache(work)
250
+ try:
251
+ bounds = kani.discover(project, work, verifier)
252
+ sources = verifier.crate_sources(project)
253
+ for mutation in mutations:
254
+ if mutation.detects not in bounds:
255
+ stop(f"mutation '{mutation.label}': unknown harness '{mutation.detects}'")
256
+ selected = {mutation.detects for mutation in mutations}
257
+ kani.reject_should_panic(bounds, sorted(selected))
258
+ for name in sorted(selected):
259
+ outcome = kani.verify(project, work, verifier, name, bounds[name].unwind)
260
+ if outcome.verdict is not kani.Verdict.PASS:
261
+ stop(f"unmutated Rust harness '{name}' did not pass: "
262
+ + "; ".join(outcome.failures) + "\n" + outcome.output)
263
+ except kani.CheckError as error:
264
+ stop(str(error))
258
265
  targets = {name for name, harness in bounds.items() if harness.source == model} | selected
259
- return targets, partial(check_rust, model, project, verifier, bounds, sources)
266
+ return targets, partial(check_rust, model, project, verifier, bounds, sources, work)
260
267
 
261
268
 
262
269
  # Each runner checks the names the mutations detect and that the unmutated model passes the checks they select,
263
270
  # then returns the names they must cover and a check for one mutation.
271
+ # A runner can enter a temporary directory into run, an ExitStack that closes after the last mutation.
264
272
  # A TLA+ or Rust mutation covers the name it detects; a Lean mutation covers the theorems that fail on it.
265
273
  LANGUAGES = {
266
274
  ".tla": Language("TLA+", needs_detects=True, takes_only=True, runner=tla_runner),
@@ -287,19 +295,20 @@ def main():
287
295
  stop(f"no {', '.join(model.name for model in models[:-1])} or {models[-1].name} beside {path}")
288
296
  language, text = LANGUAGES[model.suffix], model.read_text(encoding="utf-8")
289
297
  mutations = [make_mutation(label, directives, model, text, language) for label, directives in parse(path)]
290
- targets, check = language.runner(model, mutations)
291
- storage.warn_runtime()
292
- temp_root = storage.ensure_temp_root()
293
-
294
- detected, covered = 0, set()
295
- for mutation in mutations:
296
- with tempfile.TemporaryDirectory(dir=temp_root) as work:
297
- result = check(mutation, Path(work))
298
- if result.verdict is Verdict.ERROR:
299
- stop(f"mutation '{mutation.label}' did not reach a verdict:\n{result.detail.strip()}")
300
- detected += result.verdict is Verdict.DETECTED
301
- covered |= result.covers
302
- print(f"{result.verdict.value} {mutation.label}" + (f": {result.detail}" if result.detail else ""), flush=True)
298
+ with contextlib.ExitStack() as run:
299
+ targets, check = language.runner(model, mutations, run)
300
+ storage.warn_runtime()
301
+ temp_root = storage.ensure_temp_root()
302
+
303
+ detected, covered = 0, set()
304
+ for mutation in mutations:
305
+ with tempfile.TemporaryDirectory(dir=temp_root) as work:
306
+ result = check(mutation, Path(work))
307
+ if result.verdict is Verdict.ERROR:
308
+ stop(f"mutation '{mutation.label}' did not reach a verdict:\n{result.detail.strip()}")
309
+ detected += result.verdict is Verdict.DETECTED
310
+ covered |= result.covers
311
+ print(f"{result.verdict.value} {mutation.label}" + (f": {result.detail}" if result.detail else ""), flush=True)
303
312
  uncovered = sorted(targets - covered)
304
313
  for name in uncovered:
305
314
  print(f"UNCOVERED {name}")
@@ -23,6 +23,9 @@ PS_TIMEOUT = 5
23
23
  MAX_LISTINGS = 50
24
24
  # The termination signals that signal_cleanup converts and that a stop holds back until it finishes.
25
25
  HANDLED = (signal.SIGINT, signal.SIGTERM, *((signal.SIGHUP,) if hasattr(signal, "SIGHUP") else ()))
26
+ # A labelled command reports its elapsed time on stderr after this many seconds, then at this interval, as TLC runs do.
27
+ PROGRESS_DELAY = 15.0
28
+ PROGRESS_INTERVAL = 30.0
26
29
 
27
30
 
28
31
  class SignalTerminated(BaseException):
@@ -226,10 +229,33 @@ def guarded(command, body, **kwargs):
226
229
  raise
227
230
 
228
231
 
229
- def run_captured(command, **kwargs):
230
- """Run a command in the caller's process group and terminate it cleanly on interruption."""
232
+ def communicate(process, label=None):
233
+ """Return process.communicate(); with a label, write '<label>: <N>s elapsed' to stderr while the process runs."""
234
+ if label is None:
235
+ return process.communicate()
236
+ start = time.monotonic()
237
+ next_report = start + PROGRESS_DELAY
238
+ while True:
239
+ try:
240
+ # A timed-out communicate keeps what it has read, so the next call loses no output.
241
+ return process.communicate(timeout=max(0.05, next_report - time.monotonic()))
242
+ except subprocess.TimeoutExpired:
243
+ now = time.monotonic()
244
+ if now >= next_report:
245
+ # Callers read an OSError as a command that could not start, so a closed stderr must not raise one.
246
+ with suppress(OSError):
247
+ sys.stderr.write(f"{label}: {int(now - start)}s elapsed\n")
248
+ sys.stderr.flush()
249
+ next_report = now + PROGRESS_INTERVAL
250
+
251
+
252
+ def run_captured(command, *, label=None, **kwargs):
253
+ """Run a command in the caller's process group and terminate it cleanly on interruption.
254
+
255
+ With a label, report the elapsed time on stderr while the command runs, as communicate does.
256
+ """
231
257
  def collect(process):
232
- stdout, stderr = process.communicate()
258
+ stdout, stderr = communicate(process, label)
233
259
  return subprocess.CompletedProcess(command, process.returncode, stdout, stderr)
234
260
  return guarded(command, collect, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, **kwargs)
235
261