agent-formal-verify 0.4.19 → 0.4.21

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.
@@ -10,8 +10,9 @@ change, and so is an added item whose kind narrows what is checked.
10
10
  .statements Lean. The toolchain, and each declaration's kind, type hash and value hash.
11
11
  Added declarations are allowed.
12
12
  .matrix TLA+. Each run's effective checks and each reach check's selected inputs,
13
+ the symmetry of each run and reach check, where an added one is a change,
13
14
  and the normalized definitions of Spec,
14
- of each operator a check or reach line names, and of the operators those
15
+ of each operator a check, reach or symmetry line names, and of the operators those
15
16
  reference through local EXTENDS. Local INSTANCE substitutions retain their whole module tree.
16
17
  .rs Kani. Each qualified harness name with its #[kani::should_panic] and
17
18
  #[kani::unwind(...)] attributes and the #[cfg(...)] attributes other
@@ -20,13 +21,15 @@ change, and so is an added item whose kind narrows what is checked.
20
21
  #[path], with each route in the file's crates that the record cannot read, such as a mod
21
22
  declaration inside a macro, and each kani::assume, kani::any_where, kani::cover! and
22
23
  #[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.
24
+ such as proofs::<impl kani::Arbitrary for State>::any. Unsupported owners fail. Added covers and independent harnesses are allowed.
24
25
  Added assumes and stubs are changes. Also the body of each harness and of each other free function or
25
26
  method in a module that holds a harness, or under one, without its comments, the kani::cover! calls whose
26
27
  conditions cannot run code, and the whitespace that a reformat can change. A helper's record includes
27
28
  its attributes, qualifiers, parameters, return type and where clause as well as its body. An added
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
+ function or method there is a change, since it can shadow one that a glob import brings in. So is a
30
+ change to the rest of such a module, such as a use, a const or a macro call, recorded without its
31
+ functions or the contents of its modules as items in <module>, or items in crate for the file's root.
32
+ An added harness is also reported if its name occurs in recorded code.
30
33
  In a Cargo package, also the recorded harnesses that Kani compiles from the file; Kani must give
31
34
  each harness it compiles there a module path that a route the record reads gives, and a harness
32
35
  that no longer compiles is a change.
@@ -59,7 +62,7 @@ import runner
59
62
  import tlc
60
63
  from kani_reader import KANI_KEY, RouteReader, compiled_problems, kani_surface
61
64
  from lean_records import read_record as read_lean_record
62
- from rust_source import normalized
65
+ from rust_source import normalized, rust_masks
63
66
  from surface import STRING, Surface, collapse
64
67
 
65
68
  FORMAT = 2
@@ -265,15 +268,18 @@ def tla_surface(path):
265
268
  specs.setdefault(spec, set())
266
269
  for task in tasks:
267
270
  if task.reach:
268
- surface.add(f"reach {task.spec} {task.reach.operator} | {collapse(task.reach.match)}",
269
- {"run": collapse(task.run.label), "constants": task.run.constants})
271
+ item = surface.add(f"reach {task.spec} {task.reach.operator} | {collapse(task.reach.match)}",
272
+ {"run": collapse(task.run.label), "constants": task.run.constants})
270
273
  specs[task.spec].add(task.reach.operator)
271
274
  else:
272
- run = surface.add(f"run {task.spec} {collapse(task.run.label)}", task.run.constants)
275
+ item = surface.add(f"run {task.spec} {collapse(task.run.label)}", task.run.constants)
273
276
  for check in task.checks:
274
277
  for name in check.names:
275
- surface.add(f"check {task.spec} {check.kind} {name} | [{run}]")
278
+ surface.add(f"check {task.spec} {check.kind} {name} | [{item}]")
276
279
  specs[task.spec].update(check.names)
280
+ if task.symmetry:
281
+ surface.add(f"symmetry {task.spec} {task.symmetry} | [{item}]")
282
+ specs[task.spec].add(task.symmetry)
277
283
  for spec, operators in specs.items():
278
284
  source = path.parent / spec
279
285
  if not source.is_file():
@@ -315,7 +321,8 @@ class TlaKind:
315
321
  lines.append(" previous baseline did not track imported modules; review and record this matrix again")
316
322
  if "TLA+ layout version" not in old:
317
323
  lines.append(" previous baseline did not preserve TLA+ layout; review and record this matrix again")
318
- return lines + differences(old, new, ()), []
324
+ # Symmetry merges states, so an added symmetry line narrows what a run checks.
325
+ return lines + differences(old, new, ("symmetry",)), []
319
326
 
320
327
  def valid(self, entry):
321
328
  return True
@@ -329,6 +336,11 @@ def may_omit_generator_types(entry):
329
336
  return not entry.get("generator_types") and any(key.startswith("assume ") for key in entry["surface"])
330
337
 
331
338
 
339
+ def predates_items(surface):
340
+ # Record gives each harness's module an items in <module>, so only an older record holds a harness without one.
341
+ return any(name.startswith("harness ") for name in surface) and not any(name.startswith("items in ") for name in surface)
342
+
343
+
332
344
  def compact_kani_record(surface, current):
333
345
  """Earlier records kept spaces between punctuation even where Rust reads two separate operators."""
334
346
  compact = {}
@@ -343,6 +355,41 @@ def compact_kani_record(surface, current):
343
355
  return compact
344
356
 
345
357
 
358
+ def kani_references(surface):
359
+ """Collect identifiers from recorded code, including Kani forms stored outside a body."""
360
+ names = set()
361
+ for item, value in surface.items():
362
+ if item.startswith("body "):
363
+ code = re.sub(r"^fn\s+(?:r#)?\w+", "", value)
364
+ elif item.startswith("items in "):
365
+ code = value
366
+ elif item.startswith(("assume ", "stub ", "cover ")):
367
+ code = item.partition(" ")[2].rsplit(" in ", 1)[0]
368
+ else:
369
+ continue
370
+ names.update(re.findall(r"(?:r#)?([^\W\d]\w*)", rust_masks(code).without_comments_or_strings))
371
+ return names
372
+
373
+
374
+ def added_kani_bodies(old, new):
375
+ """An added harness can shadow a name an older proof calls or takes as a function value."""
376
+ references = None
377
+ for name in new:
378
+ if not name.startswith("body ") or name in old:
379
+ continue
380
+ owner = name.removeprefix("body ")
381
+ harness = "harness " + owner
382
+ if harness in new:
383
+ if harness in old:
384
+ continue
385
+ if references is None:
386
+ references = kani_references(old)
387
+ leaf = re.sub(r"\[\d+\]$", "", owner.rsplit("::", 1)[-1]).removeprefix("r#")
388
+ if leaf not in references:
389
+ continue
390
+ yield f" added {name}"
391
+
392
+
346
393
  class KaniKind:
347
394
  """Record, compare and move the harnesses, assumptions, covers and stubs of a Kani file, checked against what Kani compiles."""
348
395
 
@@ -373,10 +420,7 @@ class KaniKind:
373
420
  surface = kani_surface(path, self.reader)
374
421
  recorded_surface = compact_kani_record(entry["surface"], surface)
375
422
  lines = differences(recorded_surface, surface, ("assume", "stub"))
376
- # An added function or method can shadow one that a glob import such as `use super::*;` brings in, so a
377
- # harness calls it with no edit to a recorded body. An added harness's own body is allowed with it.
378
- lines += [f" added {name}" for name in surface if name.startswith("body ") and name not in recorded_surface
379
- and "harness " + name.removeprefix("body ") not in surface]
423
+ lines.extend(added_kani_bodies(recorded_surface, surface))
380
424
  if may_omit_generator_types(entry):
381
425
  lines.insert(0, " previous baseline stored assumptions without distinguishing any_where input types; review the original assumptions and record this file again")
382
426
  if any(name.startswith("harness ") and "body " + name.removeprefix("harness ") not in entry["surface"] for name in entry["surface"]):
@@ -386,6 +430,9 @@ class KaniKind:
386
430
  lines.insert(0, " previous baseline did not record the functions beside its harnesses; review each of them against the original revision and record this file again")
387
431
  if not entry.get("method_bodies") and any(name.startswith("body ") and "<" in name for name in surface):
388
432
  lines.insert(0, " previous baseline did not record the methods beside its harnesses; review each of them against the original revision and record this file again")
433
+ if predates_items(entry["surface"]):
434
+ lines[:0] = [f" previous baseline did not record {name}; review its uses, consts and macro calls against the original revision and record this file again"
435
+ for name in surface if name.startswith("items in ")]
389
436
  unchecked = (" not checked against Kani at record, so compare cannot tell a harness that "
390
437
  "stopped compiling from one that never compiled")
391
438
  try:
@@ -415,6 +462,9 @@ class KaniKind:
415
462
  surface = renamed(surface, *module)
416
463
  compiled = compiled and list(renamed(dict.fromkeys(compiled), *module))
417
464
  surface = joined(surface, new, existing)
465
+ # The other part's items would hide that one part never recorded its own, so the merge keeps none.
466
+ if any(predates_items(part["surface"]) for part in (entry, existing) if part is not None):
467
+ surface = {name: value for name, value in surface.items() if not name.startswith("items in ")}
418
468
  partial = compiled is None or entry.get("partial", False)
419
469
  if existing is not None:
420
470
  # The merged list keeps the harnesses of each entry checked against Kani at record, and is partial when
@@ -450,12 +500,16 @@ def model_entry(kind, surface):
450
500
 
451
501
 
452
502
  def joined(surface, new, existing):
453
- """Add the items that the entry existing records for the file new, which must not repeat an item of surface."""
503
+ """Add the items that the entry existing records for the file new, which must not repeat an item of surface, apart
504
+ from the other items of a Kani module, whose different texts are joined with existing's first."""
454
505
  if existing is None:
455
506
  return surface
456
- if overlap := surface.keys() & existing["surface"].keys():
507
+ recorded = existing["surface"]
508
+ shared = surface.keys() & recorded.keys()
509
+ if overlap := {name for name in shared if not name.startswith("items in ")}:
457
510
  raise ValueError(f"{new} already records {', '.join(sorted(overlap))}")
458
- return {**existing["surface"], **surface}
511
+ texts = {name: surface[name] if surface[name] == recorded[name] else normalized(f"{recorded[name]} {surface[name]}") for name in shared}
512
+ return {**recorded, **surface, **texts}
459
513
 
460
514
 
461
515
  def read_record(path, kinds):
@@ -516,9 +570,9 @@ def renamed(surface, old_module, new_module):
516
570
  if (item := KANI_KEY.fullmatch(name)) is None:
517
571
  raise ValueError(f"cannot rename the recorded item '{name}', which is not a Kani harness, assume, cover or stub")
518
572
  head, owner, duplicate = item.groups()
519
- parts = owner.split("::")
573
+ parts = [] if owner == "crate" else owner.split("::")
520
574
  if parts[:len(old)] == old:
521
- owner = "::".join(new + parts[len(old):])
575
+ owner = "::".join(new + parts[len(old):]) or "crate"
522
576
  result[f"{head}{owner}{duplicate or ''}"] = value
523
577
  if len(result) != len(surface):
524
578
  raise ValueError(f"renaming {old_module} to {new_module} merges recorded items")
@@ -16,8 +16,9 @@ import storage
16
16
  from rust_source import RustSource, after_closing, normalized, rust_masks
17
17
  from surface import Surface, collapse
18
18
 
19
- # A method's owner holds spaces, such as `proofs::<impl kani::Arbitrary for State>::any`.
20
- KANI_KEY = re.compile(r"(harness |body |(?:assume|cover|stub) .* in )(.+?)( #\d+)?", re.DOTALL)
19
+ # A method's owner holds spaces, such as `proofs::<impl kani::Arbitrary for State>::any`. The owner of a module's other
20
+ # items is the module, or `crate` for the file's root.
21
+ KANI_KEY = re.compile(r"(harness |body |items in |(?:assume|cover|stub) .* in )(.+?)( #\d+)?", re.DOTALL)
21
22
 
22
23
 
23
24
  class RustFunction(NamedTuple):
@@ -69,7 +70,16 @@ def rust_functions(source):
69
70
  elif mask[i] == "{":
70
71
  stop = after_closing(mask, i)
71
72
  header = mask[boundary:i].rstrip()
72
- macro = header.endswith("!") or bool(re.search(r"\bmacro_rules\s*!\s*\w+\s*$", header))
73
+ macro = re.search(r"\b(?:\w+\s*!|macro_rules\s*!\s*\w+)$", header)
74
+ if item and item[0] == "fn":
75
+ # A const argument sits between generic delimiters. A braced type macro names its macro before !.
76
+ # Both belong to the signature; the brace after a never return type opens the function body.
77
+ const_argument = header.endswith(("<", ",", "=")) and re.compile(r"\s*[,>]").match(mask, stop)
78
+ if macro or const_argument:
79
+ if macro:
80
+ opaque.append((i, stop))
81
+ i = stop
82
+ continue
73
83
  if item and item[0] in ("impl", "trait"):
74
84
  # A braced const argument in the header ends before the next generic argument or closing angle.
75
85
  if re.compile(r"\s*[,>]").match(mask, stop):
@@ -586,6 +596,26 @@ def kani_surface(path, reader):
586
596
  recorded_end = function.end
587
597
  if function not in harnesses:
588
598
  spans.append((function.body, f"body {function.name}", body(function, function.start)))
599
+ # Any other item in those modules, such as a `use`, a `const`, a macro call or a module, can shadow a name that a
600
+ # glob import brings in, so each module records its text without its functions and its modules' contents.
601
+ for module in [None, *modules]:
602
+ if module is None:
603
+ if None not in scopes:
604
+ continue
605
+ position, name, start, end = 0, "crate", 0, len(text)
606
+ elif any(scope is None or scope.start <= module.start < scope.end for scope in scopes):
607
+ position, name, start, end = module.body, module.name, module.body + 1, module.end - 1
608
+ else:
609
+ continue
610
+ cuts = [(item.start, item.end) for item in functions] + [(item.body + 1, item.end - 1) for item in modules if item != module]
611
+ kept = []
612
+ # An enclosing span sorts before the spans it holds, which then fall before start.
613
+ for cut, stop in sorted(cuts, key=lambda span: (span[0], -span[1])):
614
+ if start <= cut and stop <= end:
615
+ kept.append(text[start:cut])
616
+ start = stop
617
+ kept.append(text[start:end])
618
+ spans.append((position, f"items in {name}", normalized(" ".join(kept))))
589
619
  for token in KANI_TOKEN.finditer(mask):
590
620
  if not any(start <= token.start() < end for start, end in read):
591
621
  line = mask.count("\n", 0, token.start()) + 1
@@ -26,6 +26,7 @@ if __name__ == "__main__":
26
26
  if signal.getsignal(signal.SIGINT) is signal.default_int_handler:
27
27
  signal.signal(signal.SIGINT, signal.SIG_DFL)
28
28
 
29
+ import functools
29
30
  import hashlib
30
31
  import json
31
32
  import os
@@ -34,6 +35,8 @@ import shutil
34
35
  import subprocess
35
36
  import sys
36
37
  import tempfile
38
+ import time
39
+ from contextlib import suppress
37
40
  from pathlib import Path
38
41
 
39
42
  sys.dont_write_bytecode = True
@@ -49,12 +52,26 @@ SORRY = re.compile(r"(warning|error): .*: declaration uses .sorry.")
49
52
  AUDITED = re.compile(r"AUDITED [0-9]+ declarations")
50
53
  BLANK = re.compile(r"[ \t\n\r\f\v]*")
51
54
  OLD_LAKE = re.compile(r"error: (unknown command 'query'|invalid script spec)")
55
+ ANALYSIS = HERE / "lean-analysis.lean"
56
+ # The pin's own compiler builds lean-analysis.lean into a program, as Lake builds an executable that supports the
57
+ # interpreter: -rdynamic lets the interpreter find the native code of the modules that the analysis imports.
58
+ NATIVE_BUILD = (
59
+ ("{lean}", "--root={work}", "-c", "{work}/LeanAnalysis.c", "{work}/LeanAnalysis.lean"),
60
+ ("{leanc}", "-c", "-o", "{work}/LeanAnalysis.o", "{work}/LeanAnalysis.c", "-O3", "-DNDEBUG"),
61
+ ("{leanc}", "-o", "{work}/lean-analysis", "{work}/LeanAnalysis.o", "-rdynamic"),
62
+ )
63
+ # A build that no check has used for this long, or a build directory left by a killed build, is deleted.
64
+ STALE_SECONDS = 7 * 24 * 3600
52
65
 
53
66
 
54
67
  class CheckError(Exception):
55
68
  """The project cannot be checked as given; the message is the FAIL line to print."""
56
69
 
57
70
 
71
+ class BuildError(Exception):
72
+ """The native build of lean-analysis.lean failed; the message says which step and why."""
73
+
74
+
58
75
  def lines(text):
59
76
  """Split output into the lines a shell reads, without the empty piece after a final newline."""
60
77
  parts = text.split("\n")
@@ -149,6 +166,111 @@ def step(command, *, merge=True, env=None, label=None):
149
166
  return 127, "", f"cannot run {command[0]}: {error}\n"
150
167
 
151
168
 
169
+ @functools.cache
170
+ def toolchain_prefix(toolchain):
171
+ """Return the status, output and errors of the pin's lean --print-prefix, which runs once per process."""
172
+ return step(["elan", "run", toolchain, "lean", "--print-prefix"], merge=False)
173
+
174
+
175
+ @functools.cache
176
+ def analysis(toolchain):
177
+ """Return the command that runs lean-analysis.lean in lake env: its native build, or lean --run.
178
+
179
+ lean --run elaborates the analysis and imports Lean for it on every call, and the analysis then imports Lean
180
+ again for the model. The native build does neither. A pin without lean and leanc in its prefix runs the source,
181
+ and so does a failed build, which says why on stderr.
182
+ """
183
+ source = ["lean", "--run", str(ANALYSIS)]
184
+ status, prefix, _ = toolchain_prefix(toolchain)
185
+ prefix = Path(prefix.rstrip("\n"))
186
+ tools = {name: prefix / "bin" / name for name in ("lean", "leanc")}
187
+ if status or not prefix.is_absolute() or not all(os.access(tool, os.X_OK) for tool in tools.values()):
188
+ return source
189
+ try:
190
+ return [str(native_analysis(tools))]
191
+ except (BuildError, OSError) as error:
192
+ processes.report_progress(f"[lean] running lean-analysis.lean from source: {error}")
193
+ return source
194
+
195
+
196
+ def analysis_cache():
197
+ """Return LEAN_ANALYSIS_CACHE, or the directory for native analysis builds under ~/.cache."""
198
+ configured = os.environ.get("LEAN_ANALYSIS_CACHE")
199
+ if configured:
200
+ return Path(configured).absolute()
201
+ # expanduser returns ~ unchanged when it cannot find the home directory.
202
+ home = os.path.expanduser("~")
203
+ if not os.path.isabs(home):
204
+ raise OSError("set LEAN_ANALYSIS_CACHE or HOME to cache the native analysis build")
205
+ return Path(home, ".cache/agent-formal-verify/lean-analysis")
206
+
207
+
208
+ def toolchain_files(prefix):
209
+ """Return the path, size and mtime of the toolchain's lean, of each library in lib/lean and of each .olean in it.
210
+
211
+ The native build links Lean's libraries into the program, and the program reads the toolchain's .olean files. On
212
+ macOS, bin/lean is a launcher that a rebuild of Lean can leave as it was.
213
+ """
214
+ library = os.path.join(prefix, "lib", "lean")
215
+ files = [os.path.join(prefix, "bin", "lean")]
216
+ # os.walk takes less than half the time of Path.rglob over the 15,282 files in Lean 4.35.0's lib/lean.
217
+ for directory, _, names in os.walk(library):
218
+ files.extend(os.path.join(directory, name) for name in names
219
+ if name.endswith(".olean") or directory == library and name.startswith("lib"))
220
+ return sorted((path, (status := os.stat(path)).st_size, status.st_mtime_ns) for path in files)
221
+
222
+
223
+ def native_analysis(tools):
224
+ """Return the native build of lean-analysis.lean for the toolchain of these tools, building it on first use.
225
+
226
+ A build is named for the analysis source, the build steps and the toolchain's files, so a toolchain changed or
227
+ rebuilt at the same path gets its own build. Each build directory lands whole by a rename, so parallel checks may
228
+ build at once.
229
+ """
230
+ text = ANALYSIS.read_bytes()
231
+ identity = repr((NATIVE_BUILD, toolchain_files(tools["lean"].parents[1]))).encode("utf-8")
232
+ cache = analysis_cache()
233
+ build = cache / f"lean-analysis-{hashlib.sha256(identity + text).hexdigest()[:16]}"
234
+ program = build / "lean-analysis"
235
+ if not program.is_file():
236
+ cache.mkdir(mode=0o700, parents=True, exist_ok=True)
237
+ work = Path(tempfile.mkdtemp(prefix="lean-analysis-build.", dir=cache))
238
+ try:
239
+ (work / "LeanAnalysis.lean").write_bytes(text)
240
+ names = tools | {"work": work}
241
+ for template in NATIVE_BUILD:
242
+ command = [part.format(**names) for part in template]
243
+ done = processes.run_captured(command, label="[lean] analysis build", encoding="utf-8", errors="replace")
244
+ if done.returncode:
245
+ log = lines(done.stdout + done.stderr)[-20:]
246
+ raise BuildError("\n".join([f"native build step {' '.join(command)} exited {done.returncode}", *log]))
247
+ try:
248
+ os.rename(work, build)
249
+ except OSError:
250
+ # A parallel check renamed its build first.
251
+ if not program.is_file():
252
+ raise
253
+ finally:
254
+ shutil.rmtree(work, ignore_errors=True)
255
+ cutoff = time.time() - STALE_SECONDS
256
+ for entry in cache.glob("lean-analysis-*"):
257
+ with suppress(OSError):
258
+ if entry == build or entry.lstat().st_mtime >= cutoff:
259
+ continue
260
+ if entry.is_dir() and not entry.is_symlink():
261
+ shutil.rmtree(entry)
262
+ else:
263
+ entry.unlink()
264
+ # A directory on a file system mounted noexec holds programs that cannot run.
265
+ if not os.access(program, os.X_OK):
266
+ raise BuildError(f"cannot run {program}; set LEAN_ANALYSIS_CACHE to a directory where programs can run")
267
+ # A build in use is never stale. Its directory carries the mark: on macOS, touching the program itself made its
268
+ # next run about 0.8 s slower.
269
+ with suppress(OSError):
270
+ os.utime(build)
271
+ return program
272
+
273
+
152
274
  def project_files(project):
153
275
  """Find model sources and orphan records in the same walk, outside the root Lake build directory."""
154
276
  sources, records = set(), []
@@ -347,7 +469,7 @@ def checked(project, toolchain, files, freeze, out, work):
347
469
  return 1
348
470
  module_list = work / "modules"
349
471
  module_list.write_text("".join(name + "\n" for name in modules), encoding="utf-8")
350
- audit_status, output, _ = step([*lake, "env", "lean", "--run", str(HERE / "lean-analysis.lean"),
472
+ audit_status, output, _ = step([*lake, "env", *analysis(toolchain),
351
473
  "audit", *(["--freeze"] if freeze else []), str(module_list)], label="audit")
352
474
  audit = lines(output)
353
475
  if not any(AUDITED.fullmatch(line) for line in audit):
@@ -409,7 +531,7 @@ def checked(project, toolchain, files, freeze, out, work):
409
531
  # replays every declaration of the built modules through the kernel and rejects it. Use its exact-module
410
532
  # replayer rather than its CLI's prefix search, which also finds deleted sources' cached objects. A named
411
533
  # module rests on the project modules it imports, so replay those too.
412
- status, prefix, errors = step(["elan", "run", toolchain, "lean", "--print-prefix"], merge=False)
534
+ status, prefix, errors = toolchain_prefix(toolchain)
413
535
  prefix = prefix.rstrip("\n")
414
536
  compiler = os.path.join(prefix, "bin", "lean")
415
537
  if status or not os.path.isabs(prefix) or not os.path.isfile(compiler) or not os.access(compiler, os.X_OK):
@@ -5,15 +5,12 @@ import json
5
5
  import sys
6
6
  from collections import Counter
7
7
  from dataclasses import dataclass
8
- from pathlib import Path
9
8
 
10
9
  sys.dont_write_bytecode = True
11
10
  import lean
12
11
  import processes
13
12
  from lean_records import read_record
14
13
 
15
- HERE = Path(__file__).resolve().parent
16
-
17
14
 
18
15
  class AnalysisError(Exception):
19
16
  """The original model, its frozen declarations or the pinned frontend could not be read."""
@@ -44,8 +41,8 @@ def _analyze(model, project, toolchain, label):
44
41
 
45
42
  While Lean runs, report the elapsed time on stderr as '[lean] <label>: <N>s elapsed'.
46
43
  """
47
- done = processes.run_captured(["elan", "run", toolchain, "lake", "--dir", str(project), "env", "lean", "--run",
48
- str(HERE / "lean-analysis.lean"), "analyze", str(model)],
44
+ done = processes.run_captured(["elan", "run", toolchain, "lake", "--dir", str(project), "env",
45
+ *lean.analysis(toolchain), "analyze", str(model)],
49
46
  label=f"[lean] {label}", encoding="utf-8", errors="replace")
50
47
  output = done.stdout + done.stderr
51
48
  records = [line.removeprefix("AFV_LEAN ") for line in done.stdout.splitlines() if line.startswith("AFV_LEAN ")]
@@ -14,7 +14,10 @@ per mutation:
14
14
  targets, or a Lean proof no mutation breaks
15
15
 
16
16
  A TLA+ mutation is checked against the property or reach operator it names,
17
- using the matrix runs. A Lean mutation is elaborated in the project, the mutated
17
+ using the matrix runs. A run under a symmetry line adds "under symmetry
18
+ <Operator>" after the run's name in a DETECTED line, and a MISSED line names
19
+ each such run that passes, as "MISSED <label>: run '<run>' passes under symmetry
20
+ <Operator>". A Lean mutation is elaborated in the project, the mutated
18
21
  module alone, and reported with the theorems, lemmas, examples and #guard
19
22
  lines that fail. Every public theorem recorded in the model's .statements file
20
23
  must have its proof fail on some mutation; a failing #guard does not cover it.
@@ -40,10 +43,14 @@ Mutations file (a line starting with # is a comment):
40
43
 
41
44
  A TLA+ or Rust mutation needs one detects line, and a Lean mutation takes
42
45
  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.
46
+ before it runs any tool, so a malformed mutation stops the run first. It
47
+ prints a FAIL line for each malformed mutation, and names the lines where
48
+ - text that occurs more than once starts.
44
49
 
45
50
  Usage: mutate.py <Name.mutations>
46
- The environment settings of tlc-matrix.sh apply to TLA+ mutations.
51
+ The environment settings of tlc-matrix.sh apply to TLA+ mutations. A matrix
52
+ line that tlc-matrix.sh rejects with status 2 stops this runner with status 2
53
+ before TLC runs.
47
54
  """
48
55
  import signal
49
56
 
@@ -145,37 +152,49 @@ def parse(path):
145
152
  return mutations
146
153
 
147
154
 
155
+ def occurrences(text, old):
156
+ """Return the start of each occurrence of old in text that does not overlap an earlier one."""
157
+ starts = []
158
+ start = text.find(old) if old else -1
159
+ while start >= 0:
160
+ starts.append(start)
161
+ start = text.find(old, start + len(old))
162
+ return starts
163
+
164
+
148
165
  def make_mutation(label, directives, model, text, language):
149
- """Validate one mutation and locate its edit in the original model."""
166
+ """Validate one mutation and locate its edit in the original model.
167
+
168
+ Raises:
169
+ ValueError: the mutation is malformed, or its - text does not occur exactly once in the model.
170
+ """
150
171
  lines = {keyword: [rest for word, rest in directives if word == keyword] for keyword in DIRECTIVES}
151
172
  for keyword in SINGLE:
152
173
  if len(lines[keyword]) > 1:
153
- stop(f"mutation '{label}' has two {keyword} lines")
174
+ raise ValueError(f"mutation '{label}' has two {keyword} lines")
154
175
  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")
176
+ raise ValueError(f"mutation '{label}': {language.name} mutations take no detects line; the runner names the theorems that fail")
156
177
  if language.needs_detects and not lines["detects"]:
157
- stop(f"mutation '{label}' has no detects line")
178
+ raise ValueError(f"mutation '{label}' has no detects line")
158
179
  if lines["only"] and not language.takes_only:
159
- stop(f"mutation '{label}': {language.name} mutations do not support 'only'")
180
+ raise ValueError(f"mutation '{label}': {language.name} mutations do not support 'only'")
160
181
  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")
182
+ starts = occurrences(text, old)
183
+ if len(starts) != 1:
184
+ where = sorted({text.count("\n", 0, start) + 1 for start in starts})
185
+ at = f" (lines {', '.join(map(str, where))})" if len(starts) > 1 else ""
186
+ raise ValueError(f"mutation '{label}': its - text occurs {len(starts)} times in {model}, want 1{at}")
165
187
  detects, only = (lines[keyword][0].strip() if lines[keyword] else "" for keyword in SINGLE)
166
188
  new = "\n".join(lines["+"])
167
- return Mutation(label, detects, only, old, new, text, start)
189
+ return Mutation(label, detects, only, old, new, text, starts[0])
168
190
 
169
191
 
170
192
  def check_tla(plan, checker, mutation, work):
171
193
  try:
172
- detection = plan.check(checker, mutation.detects, mutation.only, mutation.apply(), work)
194
+ detected, detail = plan.check(checker, mutation.detects, mutation.only, mutation.apply(), work)
173
195
  except ValueError as error:
174
196
  return Result(Verdict.ERROR, str(error))
175
- covers = frozenset({mutation.detects})
176
- if detection is None:
177
- return Result(Verdict.MISSED, covers=covers)
178
- return Result(Verdict.DETECTED, detection, covers)
197
+ return Result(Verdict.DETECTED if detected else Verdict.MISSED, detail, frozenset({mutation.detects}))
179
198
 
180
199
 
181
200
  def check_lean(broken_checks, mutation, work):
@@ -223,6 +242,9 @@ def tla_runner(spec, mutations, run):
223
242
  stop(f"{matrix} is missing; mutations use its checks and runs")
224
243
  try:
225
244
  plan = tlc.MatrixPlan(matrix).mutations_for(spec)
245
+ except tlc.MatrixError as error:
246
+ print("\n".join(f"FAIL {problem}" for problem in error.problems))
247
+ sys.exit(2)
226
248
  except ValueError as error:
227
249
  stop(str(error))
228
250
  for mutation in mutations:
@@ -307,7 +329,16 @@ def main():
307
329
  if model is None:
308
330
  stop(f"no {', '.join(model.name for model in models[:-1])} or {models[-1].name} beside {path}")
309
331
  language, text = LANGUAGES[model.suffix], model.read_text(encoding="utf-8")
310
- mutations = [make_mutation(label, directives, model, text, language) for label, directives in parse(path)]
332
+ mutations, errors = [], []
333
+ for label, directives in parse(path):
334
+ try:
335
+ mutations.append(make_mutation(label, directives, model, text, language))
336
+ except ValueError as error:
337
+ errors.append(error)
338
+ for error in errors:
339
+ print(f"FAIL {error}")
340
+ if errors:
341
+ sys.exit(1)
311
342
  with contextlib.ExitStack() as run:
312
343
  prepared = language.runner(model, mutations, run)
313
344
  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