agent-formal-verify 0.4.16 → 0.4.18

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.
@@ -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")
@@ -39,11 +39,14 @@ def _checked_record(model, project):
39
39
  return record
40
40
 
41
41
 
42
- def _analyze(model, project, toolchain):
43
- """Get Lean's declaration identities and error positions, never infer them from source text."""
42
+ def _analyze(model, project, toolchain, label):
43
+ """Get Lean's declaration identities and error positions, never infer them from source text.
44
+
45
+ While Lean runs, report the elapsed time on stderr as '[lean] <label>: <N>s elapsed'.
46
+ """
44
47
  done = processes.run_captured(["elan", "run", toolchain, "lake", "--dir", str(project), "env", "lean", "--run",
45
48
  str(HERE / "lean-analysis.lean"), "analyze", str(model)],
46
- encoding="utf-8", errors="replace")
49
+ label=f"[lean] {label}", encoding="utf-8", errors="replace")
47
50
  output = done.stdout + done.stderr
48
51
  records = [line.removeprefix("AFV_LEAN ") for line in done.stdout.splitlines() if line.startswith("AFV_LEAN ")]
49
52
  if done.returncode != 0 or len(records) != 1:
@@ -184,12 +187,12 @@ def prepare(model, project):
184
187
  record = _checked_record(model, project)
185
188
  pin = record["toolchain"]
186
189
  frozen = {entry["name"] for entry in record["declarations"] if entry["kind"] == "theorem"}
187
- original = OriginalChecks(model, frozen, _analyze(model, project, pin))
190
+ original = OriginalChecks(model, frozen, _analyze(model, project, pin, "unmutated model"))
188
191
 
189
192
  def check(mutation, work):
190
193
  copy = work / model.name
191
194
  source = mutation.apply()
192
195
  copy.write_text(source, encoding="utf-8")
193
- return original.broken_checks(mutation, source, copy, _analyze(copy, project, pin))
196
+ return original.broken_checks(mutation, source, copy, _analyze(copy, project, pin, f"mutation {mutation.label}"))
194
197
 
195
198
  return original.targets, check
@@ -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
@@ -112,6 +113,13 @@ class Result:
112
113
  covers: frozenset = frozenset()
113
114
 
114
115
 
116
+ @dataclass(frozen=True)
117
+ class Prepared:
118
+ targets: set
119
+ check: Callable
120
+ summary_suffix: str = ""
121
+
122
+
115
123
  def stop(message, status=1):
116
124
  print(f"FAIL {message}")
117
125
  sys.exit(status)
@@ -180,13 +188,17 @@ def check_lean(broken_checks, mutation, work):
180
188
  return Result(Verdict.DETECTED, "proof/check fails: " + "; ".join(failures), frozenset(failures))
181
189
 
182
190
 
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."""
191
+ def check_rust(model, project, verifier, bounds, sources, kani_work, mutation, work):
192
+ """Run Kani on the named harness in a mutated copy of the crate; the mutation covers that harness.
193
+
194
+ Each mutation stages a fresh copy into work, and Kani builds every copy in kani_work's target directory,
195
+ so the dependencies compile once per run.
196
+ """
185
197
  copy = sources.stage(project, work)
186
198
  covers = frozenset({mutation.detects})
187
199
  (copy / model.relative_to(project)).write_text(mutation.apply(), encoding="utf-8")
188
200
  # 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)
201
+ outcome = kani.verify(copy, kani_work, verifier, mutation.detects, bounds[mutation.detects].unwind, cwd=project)
190
202
  if outcome.verdict is kani.Verdict.PASS:
191
203
  return Result(Verdict.MISSED, covers=covers)
192
204
  if outcome.verdict is kani.Verdict.REFUTED:
@@ -198,7 +210,7 @@ def project_root(model, *markers):
198
210
  return next((parent for parent in model.parents if any((parent / marker).is_file() for marker in markers)), None)
199
211
 
200
212
 
201
- def tla_runner(spec, mutations):
213
+ def tla_runner(spec, mutations, run):
202
214
  """Preserve the execution plan of every matching spec section, check TLC once, and pass the unmutated
203
215
  spec on every run the mutations select."""
204
216
  matrix = spec.with_suffix(".matrix")
@@ -215,52 +227,56 @@ def tla_runner(spec, mutations):
215
227
  plan.selected(mutation.detects, mutation.only)
216
228
  except ValueError as error:
217
229
  stop(f"mutation '{mutation.label}': {error}")
218
- checker = tlc.Tlc()
230
+ checker = tlc.engine()
219
231
  with tempfile.TemporaryDirectory(prefix="formal-tlc-originals-", dir=storage.ensure_temp_root()) as temporary:
232
+ print(f"ENGINE {checker.label}", flush=True)
220
233
  try:
221
234
  plan.check_originals(checker, [(mutation.detects, mutation.only) for mutation in mutations], Path(temporary))
222
235
  except ValueError as error:
223
236
  stop(str(error))
224
- return plan.properties, partial(check_tla, plan, checker)
237
+ return Prepared(plan.properties, partial(check_tla, plan, checker), checker.summary_suffix)
225
238
 
226
239
 
227
- def lean_runner(model, mutations):
240
+ def lean_runner(model, mutations, run):
228
241
  """Target the frozen theorems that Lean finds public in the source, including their namespaces."""
229
242
  project = project_root(model, "lakefile.toml", "lakefile.lean")
230
243
  if project is None:
231
244
  stop(f"{model} is in no Lake project")
232
245
  targets, broken_checks = lean_mutations.prepare(model, project)
233
- return targets, partial(check_lean, broken_checks)
246
+ return Prepared(targets, partial(check_lean, broken_checks))
234
247
 
235
248
 
236
- def rust_runner(model, mutations):
249
+ def rust_runner(model, mutations, run):
250
+ """Discover the harnesses and check the unmutated crate in a Kani work directory that the mutations reuse."""
237
251
  project = project_root(model, "Cargo.toml")
238
252
  if project is None:
239
253
  stop(f"{model} is in no Rust crate")
240
254
  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))
255
+ 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
+ try:
259
+ bounds = kani.discover(project, work, verifier)
260
+ sources = verifier.crate_sources(project)
261
+ for mutation in mutations:
262
+ if mutation.detects not in bounds:
263
+ stop(f"mutation '{mutation.label}': unknown harness '{mutation.detects}'")
264
+ selected = {mutation.detects for mutation in mutations}
265
+ kani.reject_should_panic(bounds, sorted(selected))
266
+ for name in sorted(selected):
267
+ outcome = kani.verify(project, work, verifier, name, bounds[name].unwind)
268
+ if outcome.verdict is not kani.Verdict.PASS:
269
+ stop(f"unmutated Rust harness '{name}' did not pass: "
270
+ + "; ".join(outcome.failures) + "\n" + outcome.output)
271
+ except kani.CheckError as error:
272
+ stop(str(error))
258
273
  targets = {name for name, harness in bounds.items() if harness.source == model} | selected
259
- return targets, partial(check_rust, model, project, verifier, bounds, sources)
274
+ return Prepared(targets, partial(check_rust, model, project, verifier, bounds, sources, work))
260
275
 
261
276
 
262
277
  # Each runner checks the names the mutations detect and that the unmutated model passes the checks they select,
263
278
  # then returns the names they must cover and a check for one mutation.
279
+ # A runner can enter a temporary directory into run, an ExitStack that closes after the last mutation.
264
280
  # A TLA+ or Rust mutation covers the name it detects; a Lean mutation covers the theorems that fail on it.
265
281
  LANGUAGES = {
266
282
  ".tla": Language("TLA+", needs_detects=True, takes_only=True, runner=tla_runner),
@@ -287,26 +303,28 @@ def main():
287
303
  stop(f"no {', '.join(model.name for model in models[:-1])} or {models[-1].name} beside {path}")
288
304
  language, text = LANGUAGES[model.suffix], model.read_text(encoding="utf-8")
289
305
  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)
303
- uncovered = sorted(targets - covered)
306
+ with contextlib.ExitStack() as run:
307
+ prepared = language.runner(model, mutations, run)
308
+ storage.warn_runtime()
309
+ temp_root = storage.ensure_temp_root()
310
+
311
+ detected, covered = 0, set()
312
+ for mutation in mutations:
313
+ with tempfile.TemporaryDirectory(dir=temp_root) as work:
314
+ result = prepared.check(mutation, Path(work))
315
+ if result.verdict is Verdict.ERROR:
316
+ stop(f"mutation '{mutation.label}' did not reach a verdict:\n{result.detail.strip()}")
317
+ detected += result.verdict is Verdict.DETECTED
318
+ covered |= result.covers
319
+ print(f"{result.verdict.value} {mutation.label}" + (f": {result.detail}" if result.detail else ""), flush=True)
320
+ uncovered = sorted(prepared.targets - covered)
304
321
  for name in uncovered:
305
322
  print(f"UNCOVERED {name}")
306
323
  if model.suffix == ".lean":
307
324
  print(LEAN_NOTE)
308
325
  print(f"SUMMARY {detected} of {len(mutations)} mutations detected"
309
- + (f", {len(uncovered)} properties without a mutation" if uncovered else ""))
326
+ + (f", {len(uncovered)} properties without a mutation" if uncovered else "")
327
+ + prepared.summary_suffix)
310
328
  return 0 if detected == len(mutations) and not uncovered else 1
311
329
 
312
330
 
@@ -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 or sys.stderr 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