agent-formal-verify 0.4.12 → 0.4.13

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.
Files changed (38) hide show
  1. package/CHANGES.md +136 -0
  2. package/README.md +5 -3
  3. package/package.json +2 -1
  4. package/skills/formal-verify/SKILL.md +11 -13
  5. package/skills/formal-verify/examples/kani-template/src/lib.rs +5 -6
  6. package/skills/formal-verify/examples/lean-template/Model/BoundedQueue.statements +10 -45
  7. package/skills/formal-verify/examples/tla-template/BoundedQueue.matrix +16 -13
  8. package/skills/formal-verify/examples/tla-template/BoundedQueue.mutations +92 -14
  9. package/skills/formal-verify/examples/tla-template/BoundedQueue.tla +169 -28
  10. package/skills/formal-verify/references/evidence.md +1 -1
  11. package/skills/formal-verify/references/helpers.md +4 -3
  12. package/skills/formal-verify/references/lean-brief.md +2 -2
  13. package/skills/formal-verify/references/rust-brief.md +58 -6
  14. package/skills/formal-verify/references/setup.md +23 -7
  15. package/skills/formal-verify/references/tla-brief.md +2 -2
  16. package/skills/formal-verify/scripts/baseline.py +564 -66
  17. package/skills/formal-verify/scripts/kani-check.sh +3 -1
  18. package/skills/formal-verify/scripts/kani.py +127 -59
  19. package/skills/formal-verify/scripts/lean-analysis.lean +387 -0
  20. package/skills/formal-verify/scripts/lean-check.sh +6 -243
  21. package/skills/formal-verify/scripts/lean.py +484 -0
  22. package/skills/formal-verify/scripts/lean_mutations.py +195 -0
  23. package/skills/formal-verify/scripts/lean_records.py +25 -0
  24. package/skills/formal-verify/scripts/mutate.py +81 -195
  25. package/skills/formal-verify/scripts/processes.py +266 -0
  26. package/skills/formal-verify/scripts/python-tools.sh +15 -0
  27. package/skills/formal-verify/scripts/runner.py +56 -0
  28. package/skills/formal-verify/scripts/setup.sh +18 -19
  29. package/skills/formal-verify/scripts/storage.py +207 -0
  30. package/skills/formal-verify/scripts/sync.py +401 -0
  31. package/skills/formal-verify/scripts/tlc-matrix.sh +3 -1
  32. package/skills/formal-verify/scripts/tlc.py +423 -116
  33. package/skills/formal-verify/scripts/{tlc-trace.py → tlc_trace.py} +16 -10
  34. package/skills/setup/SKILL.md +1 -1
  35. package/skills/formal-verify/scripts/lean-mutations.lean +0 -95
  36. package/skills/formal-verify/scripts/lean-statements.py +0 -161
  37. package/skills/formal-verify/scripts/lean-tools.sh +0 -24
  38. package/skills/formal-verify/scripts/tlc-tools.sh +0 -47
@@ -13,23 +13,33 @@ change, and so is an added item whose kind narrows what is checked.
13
13
  and the normalized definitions of Spec,
14
14
  of each operator a check or reach line names, and of the operators those
15
15
  reference through local EXTENDS. Local INSTANCE substitutions retain their whole module tree.
16
- .rs Kani. Each qualified harness name, and each kani::assume, kani::any_where,
17
- kani::cover! and #[kani::stub] with its owning free function, under inline
18
- modules. Unsupported owners fail. Added covers and harnesses are allowed.
16
+ .rs Kani. Each qualified harness name with the #[cfg(...)] attributes other
17
+ than cfg(kani), and the #[cfg_attr(..., cfg(...))] ones, on it, its enclosing
18
+ items, the file and each out-of-line mod declaration that leads to the file from a crate root, through
19
+ #[path], and each kani::assume, kani::any_where, kani::cover! and
20
+ #[kani::stub] with its owning free function, under inline modules. Unsupported owners fail. Added covers and harnesses are allowed.
19
21
  Added assumes and stubs are changes.
22
+ In a Cargo package, also the recorded harnesses that Kani compiles from the file; Kani must give
23
+ each harness it compiles there a module path that a route the record reads gives, and a harness
24
+ that no longer compiles is a change.
20
25
 
21
26
  Usage:
22
27
  baseline.py record <record-file> <model-file>... record these files, keep the other entries
23
28
  baseline.py compare <record-file> exit 1 when a recorded file changed
29
+ baseline.py move <record-file> <old> <new> [--module OLD NEW]
30
+ compare old's entry with new from now on
24
31
 
25
32
  Compare prints UNCHANGED or CHANGED per file, indented lines for each item that
26
- changed, and a SUMMARY line. Exit codes: 0 unchanged, 1 changed or a record or
27
- model file that fails to parse, 2 usage error.
33
+ changed, and a SUMMARY line. Move prints MOVED; it reads only the record, never
34
+ the new file, and with --module renames the recorded Kani owners under module
35
+ OLD to sit under NEW. Exit codes: 0 unchanged, 1 changed or a record or model
36
+ file that fails to parse, 2 usage error.
28
37
  """
29
38
  import argparse
39
+ import functools
30
40
  import hashlib
31
- import importlib.util
32
41
  import json
42
+ import os
33
43
  import re
34
44
  import sys
35
45
  import tempfile
@@ -38,9 +48,12 @@ from typing import NamedTuple
38
48
 
39
49
  sys.dont_write_bytecode = True
40
50
 
51
+ import kani
52
+ import runner
53
+ import storage
41
54
  import tlc
55
+ from lean_records import read_record as read_lean_record
42
56
 
43
- HERE = Path(__file__).resolve().parent
44
57
  FORMAT = 2
45
58
  NARROWING = {"lean": (), "tla": (), "kani": ("assume", "stub")}
46
59
  KINDS = {".statements": "lean", ".matrix": "tla", ".rs": "kani"}
@@ -69,10 +82,7 @@ class Surface(dict):
69
82
 
70
83
 
71
84
  def lean_surface(path):
72
- spec = importlib.util.spec_from_file_location("lean_statements", HERE / "lean-statements.py")
73
- module = importlib.util.module_from_spec(spec)
74
- spec.loader.exec_module(module)
75
- record = module.read_record(path)
85
+ record = read_lean_record(path)
76
86
  surface = Surface()
77
87
  surface.add("toolchain", record["toolchain"])
78
88
  for entry in record["declarations"]:
@@ -80,6 +90,12 @@ def lean_surface(path):
80
90
  return surface
81
91
 
82
92
 
93
+ def tla_text(text):
94
+ """Columns can group TLA+ conjunctions and disjunctions across lines."""
95
+ lines = [line.rstrip() for line in text.splitlines() if line.strip()]
96
+ return "\n".join(lines) if len(lines) > 1 else collapse("".join(lines))
97
+
98
+
83
99
  def blank_tla_comments(text):
84
100
  out, i = [], 0
85
101
  while i < len(text):
@@ -90,7 +106,7 @@ def blank_tla_comments(text):
90
106
  out.append(string[0])
91
107
  i = string.end()
92
108
  elif text.startswith("(*", i):
93
- depth = 0
109
+ start, depth = i, 0
94
110
  while i < len(text):
95
111
  if text.startswith("(*", i):
96
112
  depth += 1
@@ -101,9 +117,9 @@ def blank_tla_comments(text):
101
117
  if not depth:
102
118
  break
103
119
  else:
104
- out.append("\n" if text[i] == "\n" else "")
105
120
  i += 1
106
- out.append(" ")
121
+ # A following token keeps its source column, even after a nested comment.
122
+ out.append(re.sub(r"[^\s]", " ", text[start:i]))
107
123
  elif text.startswith("\\*", i):
108
124
  end = text.find("\n", i)
109
125
  i = len(text) if end < 0 else end
@@ -117,14 +133,40 @@ def blank_tla_comments(text):
117
133
  DEFINITION = re.compile(r"(?:LOCAL\s+)?(\w*[A-Za-z]\w*)\s*(?:\((?:[^()]|\([^()]*\))*\)|\[(?:[^\[\]]|\[[^\[\]]*\])*\])?\s*==")
118
134
  MODULE_LEVEL = re.compile(r"-{4,}|={4,}|(?:EXTENDS|VARIABLES?|CONSTANTS?|ASSUME|ASSUMPTION|AXIOM|THEOREM|LEMMA|PROPOSITION|COROLLARY|INSTANCE|RECURSIVE|USE|HIDE)\b")
119
135
  IDENTIFIER = re.compile(r"\w*[A-Za-z]\w*")
120
- SUBSCRIPT = r"_(?:\w+|<<[^>]*>>)"
136
+ SUBSCRIPT = r"_(\w+|<<[^>]*>>)"
121
137
  SPEC_ACTIONS = re.compile(rf"\[\]\[[^\]]*\]{SUBSCRIPT}|[WS]F{SUBSCRIPT}\s*\([^()]*\)")
138
+ # The prefix that joins a subscript, such as vars in WF_vars, [A]_vars or <<A>>_vars, to one token.
139
+ SUBSCRIPT_PREFIX = re.compile(r"\b[WS]F_|\]_|>>_")
122
140
 
123
141
 
124
142
  def begins_in_column_zero(line):
125
143
  return line[:1].strip() != ""
126
144
 
127
145
 
146
+ DEFINITION_TOKENS = re.compile(r"\b(?:LET|IN)\b|(?<!=)==(?!=)")
147
+
148
+
149
+ def has_unplaced_definition(code):
150
+ """Return whether a definition can lie outside the column-0 headers that tla_definitions splits on.
151
+
152
+ An indented `==` inside an open LET defines a LET-local operator. Any other indented `==`, a line
153
+ that starts with `==`, or a column-0 header while a LET is open can define a module operator.
154
+ """
155
+ open_lets = 0
156
+ for line in code.split("\n"):
157
+ indented = not begins_in_column_zero(line)
158
+ if open_lets and not indented and ("==" in line or MODULE_LEVEL.match(line)):
159
+ return True
160
+ for token in DEFINITION_TOKENS.finditer(line):
161
+ if token[0] == "LET":
162
+ open_lets += 1
163
+ elif token[0] == "IN":
164
+ open_lets = max(open_lets - 1, 0)
165
+ elif not open_lets and (indented or token.start() == 0):
166
+ return True
167
+ return False
168
+
169
+
128
170
  def tla_definitions(text):
129
171
  found, unreadable, name, lines = {}, set(), None, []
130
172
  for line in text.split("\n"):
@@ -133,7 +175,7 @@ def tla_definitions(text):
133
175
  header = None if match or MODULE_LEVEL.match(line) or "==" not in line else collapse(line.partition("==")[0])
134
176
  if match or header or MODULE_LEVEL.match(line):
135
177
  if name:
136
- found[name] = collapse(" ".join(lines))
178
+ found[name] = tla_text("\n".join(lines))
137
179
  name, lines = (match[1] if match else header), ([line] if match or header else [])
138
180
  if header:
139
181
  unreadable.add(header)
@@ -141,7 +183,7 @@ def tla_definitions(text):
141
183
  if name:
142
184
  lines.append(line)
143
185
  if name:
144
- found[name] = collapse(" ".join(lines))
186
+ found[name] = tla_text("\n".join(lines))
145
187
  return found, unreadable
146
188
 
147
189
 
@@ -167,8 +209,7 @@ def tla_module_surface(directory, spec, operators):
167
209
  text = blank_tla_comments(tlc.read_raw(directory / path))
168
210
  texts[path] = text
169
211
  code = STRING.sub('""', text)
170
- # Indented or multiline headers cannot always be separated from a local LET definition.
171
- if path != root and re.search(r"(?m)^(?:[ \t].*)?(?<!=)==(?!=)", code):
212
+ if has_unplaced_definition(code):
172
213
  whole_modules = True
173
214
  scope = {}
174
215
  for group in EXTENDS.findall(code):
@@ -188,7 +229,7 @@ def tla_module_surface(directory, spec, operators):
188
229
  scope[name] = key
189
230
  required.update((path, name) for name in unreadable)
190
231
  scopes[path] = scope
191
- exports[path] = {name: key for name, key in scope.items() if not bodies[key].startswith("LOCAL ")}
232
+ exports[path] = {name: key for name, key in scope.items() if not re.match(r"LOCAL\s", bodies[key])}
192
233
  visiting.remove(path)
193
234
  return exports[path]
194
235
 
@@ -205,7 +246,7 @@ def tla_module_surface(directory, spec, operators):
205
246
  if whole_modules:
206
247
  # Preserve substitutions and dependencies whose operator scope cannot be resolved.
207
248
  for path, text in texts.items():
208
- surface[f"module text {spec} | {path}"] = collapse(text)
249
+ surface[f"module text {spec} | {path}"] = tla_text(text)
209
250
  return surface
210
251
 
211
252
  seen = set()
@@ -216,27 +257,28 @@ def tla_module_surface(directory, spec, operators):
216
257
  seen.add(key)
217
258
  owner, name = key
218
259
  surface[f"definition {owner} {name}"] = bodies[key]
219
- body = STRING.sub('""', bodies[key].partition("==")[2])
260
+ header, _, body = bodies[key].partition("==")
261
+ body = STRING.sub('""', body)
220
262
  if key == scopes[root]["Spec"]:
221
- body = SPEC_ACTIONS.sub(" ", body)
263
+ # Keep the subscript, such as vars: it decides which steps may stutter and what fairness requires.
264
+ body = SPEC_ACTIONS.sub(lambda form: f" {form[1] or form[2]} ", body)
265
+ body = SUBSCRIPT_PREFIX.sub(" ", body)
266
+ if "[" in header:
267
+ # A function definition such as F[x \in S] == ... references S in its header.
268
+ body = f"{header} {body}"
222
269
  required.update(scopes[owner][word] for word in IDENTIFIER.findall(body) if word in scopes[owner])
223
270
  return surface
224
271
 
225
272
 
226
273
  def tla_surface(path):
227
274
  surface = Surface()
275
+ surface.add("TLA+ layout version", 1)
228
276
  specs = {}
229
- parsed = list(tlc.directives(tlc.read_raw(path).split("\n")))
230
- tasks = list(tlc.execution_plan(parsed))
231
- errors = ["; ".join(tlc.render(task)) for task in tasks if isinstance(task, tlc.Result)]
232
- if errors:
233
- raise ValueError(f"{path}: {'; '.join(errors)}")
234
- for directive in parsed:
235
- if isinstance(directive, tlc.Spec):
236
- if not directive.path:
237
- raise ValueError(f"{path}: spec line has no path")
238
- surface.add(f"spec {directive.path}")
239
- specs.setdefault(directive.path, set())
277
+ plan = tlc.MatrixPlan(path)
278
+ tasks = plan.checked_tasks()
279
+ for spec in plan.specs:
280
+ surface.add(f"spec {spec}")
281
+ specs.setdefault(spec, set())
240
282
  for task in tasks:
241
283
  if task.reach:
242
284
  surface.add(f"reach {task.spec} {task.reach.operator} | {collapse(task.reach.match)}",
@@ -328,54 +370,72 @@ def after_closing(mask, opener):
328
370
  class RustFunction(NamedTuple):
329
371
  name: str
330
372
  start: int
373
+ keyword: int
331
374
  body: int
332
375
  end: int
333
376
 
334
377
 
335
378
  RUST_ITEM = re.compile(r"\b(fn|mod)\s+((?:r#)?\w+)\b")
379
+ INCLUDE = re.compile(r"\binclude\s*!$")
336
380
 
337
381
 
338
382
  def rust_functions(mask):
339
- """Locate free functions under inline modules; leave macro and other item bodies opaque."""
340
- functions, opaque, counts = [], [], {}
383
+ """Locate free functions, inline modules, out-of-line `mod name;` declarations and `include!(...)` items outside
384
+ function bodies; leave macro and other item bodies opaque.
341
385
 
342
- def walk(start, end, namespace=(), in_function=False):
386
+ A declaration's or an include's body is its `;`.
387
+ """
388
+ functions, modules, opaque, declarations, includes, counts = [], [], [], [], [], {}
389
+
390
+ def add_include(boundary, header, stop, in_body):
391
+ if not in_body and (include := INCLUDE.search(header)):
392
+ semicolon = re.compile(r"\s*;").match(mask, stop)
393
+ includes.append(RustFunction("include", boundary, boundary + include.start(), semicolon.end() - 1 if semicolon else stop - 1, stop))
394
+
395
+ def walk(start, end, namespace=(), in_function=False, in_body=False):
343
396
  i, boundary, item = start, start, None
344
397
  while i < end:
345
398
  if match := RUST_ITEM.match(mask, i):
346
- item = (match[1], match[2])
399
+ item = (match[1], match[2], match.start())
347
400
  i = match.end()
348
401
  elif mask[i] in "([":
349
402
  stop = after_closing(mask, i)
350
- if mask[boundary:i].rstrip().endswith("!"):
403
+ header = mask[boundary:i].rstrip()
404
+ if header.endswith("!"):
351
405
  opaque.append((i, stop))
406
+ add_include(boundary, header, stop, in_body)
352
407
  i = stop
353
408
  elif mask[i] == "{":
354
409
  stop = after_closing(mask, i)
355
410
  header = mask[boundary:i].rstrip()
356
411
  macro = header.endswith("!") or bool(re.search(r"\bmacro_rules\s*!\s*\w+\s*$", header))
357
412
  if item and not macro:
358
- kind, name = item
413
+ kind, name, keyword = item
359
414
  qualified = (*namespace, name)
360
415
  if kind == "fn":
361
416
  owner = "::".join(qualified)
362
417
  counts[owner] = counts.get(owner, 0) + 1
363
418
  suffix = f"[{counts[owner]}]" if counts[owner] > 1 else ""
364
- functions.append(RustFunction(owner + suffix, boundary, i, stop))
365
- walk(i + 1, stop - 1, qualified, kind == "fn")
419
+ functions.append(RustFunction(owner + suffix, boundary, keyword, i, stop))
420
+ else:
421
+ modules.append(RustFunction("::".join(qualified), boundary, keyword, i, stop))
422
+ walk(i + 1, stop - 1, qualified, kind == "fn", in_body or kind == "fn")
366
423
  elif in_function and not macro and not re.search(r"\b(?:impl|trait|struct|enum|union|extern|macro)\b", header):
367
- walk(i + 1, stop - 1, namespace, True)
424
+ walk(i + 1, stop - 1, namespace, True, True)
368
425
  else:
369
426
  opaque.append((i, stop))
427
+ add_include(boundary, header, stop, in_body)
370
428
  i = boundary = stop
371
429
  item = None
372
430
  else:
373
431
  if mask[i] == ";":
432
+ if item and item[0] == "mod" and not in_body:
433
+ declarations.append(RustFunction("::".join((*namespace, item[1])), boundary, item[2], i, i + 1))
374
434
  boundary, item = i + 1, None
375
435
  i += 1
376
436
 
377
437
  walk(0, len(mask))
378
- return functions, opaque
438
+ return functions, modules, opaque, declarations, includes
379
439
 
380
440
 
381
441
  KANI_ATTRIBUTE = r"#\s*\[\s*(?:cfg_attr\s*\(\s*kani\s*,\s*)?kani\s*::\s*"
@@ -387,21 +447,305 @@ MACROS = (
387
447
  )
388
448
  PROOF = re.compile(KANI_ATTRIBUTE + r"proof(?:_for_contract\s*\([^)]*\))?\s*\)?\s*\]")
389
449
  KANI_TOKEN = re.compile(r"\bkani\s*::\s*(?:assume|any_where|cover|stub|proof)\w*\b")
450
+ ATTRIBUTE = re.compile(r"#\s*(!\s*)?\[")
451
+ INNER_ATTRIBUTE = re.compile(r"[\s\ufeff]*#\s*!\s*\[")
390
452
  RENAMING_IMPORT = re.compile(r"\buse\s+[^;]*?(?<![\w:])(?:::\s*)?kani\b[^;]*?(?:\bas\b|\*|\b(?:assume|any_where|cover|stub|proof)\w*\b)|\bextern\s+crate\s+kani\s+as\b")
391
453
 
392
454
 
455
+ def applies_cfg(attribute):
456
+ """Return whether a compact `cfg_attr(predicate, attribute, ...)` applies a cfg or a module path in its own
457
+ attribute list."""
458
+ arguments, depth, start = [], 0, len("cfg_attr(")
459
+ for i in range(start, len(attribute) - 1):
460
+ depth += (attribute[i] in "([{") - (attribute[i] in ")]}")
461
+ if attribute[i] == "," and not depth:
462
+ arguments.append(attribute[start:i])
463
+ start = i + 1
464
+ arguments.append(attribute[start:-1])
465
+ return any(argument.startswith(("cfg(", "path=")) or argument.startswith("cfg_attr(") and applies_cfg(argument) for argument in arguments[1:])
466
+
467
+
468
+ def outer_attributes(source, start, keyword):
469
+ """Yield the contents of each top-level outer attribute between start and keyword; skip inner attributes."""
470
+ mask = source.without_comments_or_strings
471
+ while attribute := ATTRIBUTE.search(mask, start, keyword):
472
+ opener = attribute.end() - 1
473
+ start = after_closing(mask, opener)
474
+ if not attribute[1]:
475
+ yield rust_masks(source.uncommented[opener + 1:start - 1])
476
+
477
+
478
+ def cfg_guards(source, items):
479
+ """Return the cfg attributes other than cfg(kani), and the cfg_attr ones whose attribute list applies a cfg or a
480
+ module path, on each (start, keyword, body) item, between its start and its fn or mod keyword, and at the start
481
+ of its body.
482
+
483
+ A body of -1 stands for the file, which has only inner attributes, and a body at a `;` for an out-of-line `mod`
484
+ declaration, which has none. An attribute nested inside another attribute's tokens is not read.
485
+ """
486
+ text, mask = source.uncommented, source.without_comments_or_strings
487
+ guards = []
488
+
489
+ def read(attribute):
490
+ compact = re.sub(r"\s+", "", attribute.without_comments_or_strings)
491
+ if compact.startswith("cfg(") and compact != "cfg(kani)" or compact.startswith("cfg_attr(") and applies_cfg(compact):
492
+ guards.append(collapse(attribute.uncommented, attribute.literals))
493
+
494
+ for start, keyword, body in items:
495
+ if body >= 0:
496
+ for attribute in outer_attributes(source, start, keyword):
497
+ read(attribute)
498
+ if body >= 0 and mask[body] == ";":
499
+ continue
500
+ inner = body + 1
501
+ while attribute := INNER_ATTRIBUTE.match(mask, inner):
502
+ opener = attribute.end() - 1
503
+ inner = after_closing(mask, opener)
504
+ read(rust_masks(text[opener + 1:inner - 1]))
505
+ return " ".join(guards)
506
+
507
+
508
+ PATH_ATTRIBUTE = re.compile(r"\bpath\s*=\s*")
509
+
510
+
511
+ def module_paths(source, item, file):
512
+ """Return the paths that `#[path = "..."]` sets on a module item, and those that a cfg_attr may set."""
513
+ paths, conditional = [], []
514
+ for attribute in outer_attributes(source, item.start, item.keyword):
515
+ compact = re.sub(r"\s+", "", attribute.without_comments_or_strings)
516
+ if not compact.startswith(("path=", "cfg_attr(")):
517
+ continue
518
+ for setting in PATH_ATTRIBUTE.finditer(attribute.without_comments_or_strings):
519
+ value = string_value(next((attribute.uncommented[begin:end] for begin, end in attribute.literals if begin == setting.end()), ""))
520
+ if value is None:
521
+ line = source.without_comments_or_strings.count("\n", 0, item.start) + 1
522
+ raise ValueError(f"{file}:{line}: cannot read the path in '{collapse(attribute.uncommented, attribute.literals)}'; write it as a string without escapes")
523
+ (paths if compact.startswith("path=") else conditional).append(value)
524
+ return paths, conditional
525
+
526
+
527
+ def string_value(literal):
528
+ """Return the value of a Rust string literal without escapes, or None."""
529
+ plain = re.fullmatch(r'r(#*)"(.*)"\1', literal, re.DOTALL) or re.fullmatch(r'"([^"\\]*)"', literal)
530
+ return plain[plain.lastindex] if plain else None
531
+
532
+
533
+ class RustFile(NamedTuple):
534
+ source: RustSource
535
+ modules: list
536
+ declarations: list
537
+ includes: list
538
+
539
+
540
+ PARSED = {}
541
+
542
+
543
+ def parse_rust(path):
544
+ if path not in PARSED:
545
+ source = rust_masks(path.read_text(encoding="utf-8"))
546
+ _, modules, _, declarations, includes = rust_functions(source.without_comments_or_strings)
547
+ PARSED[path] = RustFile(source, modules, declarations, includes)
548
+ return PARSED[path]
549
+
550
+
551
+ def enclosing_modules(parsed, item):
552
+ return sorted((module for module in parsed.modules if module.start <= item.start < module.end), key=lambda module: module.start)
553
+
554
+
555
+ def module_files(file, owner, parsed, declaration):
556
+ """Yield each file that an out-of-line `mod` declaration in file may load, by rustc's rules, and whether that
557
+ file owns its directory, as a crate root, a mod.rs or a `#[path]` file does."""
558
+ states = [(file.parent, file.parent if owner else file.parent / file.stem)]
559
+ for module in enclosing_modules(parsed, declaration):
560
+ paths, conditional = module_paths(parsed.source, module, file)
561
+ name = module.name.rsplit("::", 1)[-1].removeprefix("r#")
562
+ states = [(child, child) for directory, prefix in states for child in ([] if paths else [prefix / name]) + [directory / path for path in paths + conditional]]
563
+ paths, conditional = module_paths(parsed.source, declaration, file)
564
+ name = declaration.name.rsplit("::", 1)[-1].removeprefix("r#")
565
+ for directory, prefix in states:
566
+ if not paths:
567
+ yield prefix / f"{name}.rs", False
568
+ yield prefix / name / "mod.rs", True
569
+ for path in paths + conditional:
570
+ yield directory / path, True
571
+
572
+
573
+ def crate_roots(path):
574
+ """Return the crate roots whose module trees may hold path, and those of them that Cargo names, or None for a
575
+ file in no crate.
576
+
577
+ They are the lib.rs and main.rs in the nearest directory above path that holds either and, in the Cargo package
578
+ of the nearest directory above path with a Cargo.toml, Cargo's target files and each `.rs` path that Cargo.toml
579
+ names.
580
+ """
581
+ marker = next((folder for folder in path.parents if (folder / "lib.rs").is_file() or (folder / "main.rs").is_file()), None)
582
+ package = next((folder for folder in path.parents if (folder / "Cargo.toml").is_file()), None)
583
+ if marker is None and package is None:
584
+ return None
585
+ markers = [marker / "lib.rs", marker / "main.rs"] if marker else []
586
+ named = []
587
+ if package:
588
+ named += [package / "src/lib.rs", package / "src/main.rs"]
589
+ for folder in ("src/bin", "tests", "examples", "benches"):
590
+ named += sorted((package / folder).glob("*.rs")) + sorted((package / folder).glob("*/main.rs"))
591
+ manifest = (package / "Cargo.toml").read_text(encoding="utf-8")
592
+ named += [package / file for file in re.findall(r"""\bpath\s*=\s*["']([^"']+\.rs)["']""", manifest)]
593
+ return tuple(dict.fromkeys(root.resolve() for root in markers + named if root.is_file())), {root.resolve() for root in named}
594
+
595
+
596
+ CONCAT = re.compile(r"(?:\w+\s*::\s*)*concat\s*!\s*[(\[{]")
597
+ MANIFEST_DIR = re.compile(r'(?:\w+\s*::\s*)*env\s*!\s*[(\[{]\s*"CARGO_MANIFEST_DIR"\s*,?\s*[)\]}]')
598
+
599
+
600
+ def include_path(argument, file, package):
601
+ """Return the file that the argument of an `include!` in file names, or None when the argument is neither a
602
+ string without escapes nor a `concat!` of such strings and `env!("CARGO_MANIFEST_DIR")`, which is package,
603
+ the directory of the Cargo.toml of the crate being compiled.
604
+
605
+ Raises:
606
+ ValueError: The argument uses `env!("CARGO_MANIFEST_DIR")` and package is None.
607
+ """
608
+ argument = argument.strip()
609
+ if (value := string_value(argument)) is not None:
610
+ return file.parent / value
611
+ mask = rust_masks(argument).without_comments_or_strings
612
+ if not (concat := CONCAT.match(mask)) or after_closing(mask, concat.end() - 1) != len(mask):
613
+ return None
614
+ parts, start, depth = [], concat.end(), 0
615
+ for i in range(start, len(mask) - 1):
616
+ depth += (mask[i] in "([{") - (mask[i] in ")]}")
617
+ if mask[i] == "," and not depth:
618
+ parts.append(argument[start:i].strip())
619
+ start = i + 1
620
+ parts.append(argument[start:-1].strip())
621
+ pieces = []
622
+ for part in filter(None, parts):
623
+ if (value := string_value(part)) is not None:
624
+ pieces.append(value)
625
+ elif MANIFEST_DIR.fullmatch(part):
626
+ if package is None:
627
+ raise ValueError('no Cargo.toml above the crate root sets env!("CARGO_MANIFEST_DIR"), so the record cannot tell which file it reads')
628
+ pieces.append(str(package))
629
+ else:
630
+ return None
631
+ return file.parent / "".join(pieces)
632
+
633
+
634
+ TREES = {}
635
+
636
+
637
+ def module_tree(roots):
638
+ """Return the module declarations that lead to each file the crate roots reach, as {file: {(declarer,
639
+ declaration)}}, and the message for each reached file or declaration that could not be read.
640
+
641
+ An `include!("...")` item outside function bodies leads to the file it names, relative to the including file,
642
+ which declares modules as a file that owns its directory does, whatever inline modules hold the include.
643
+ """
644
+ if roots not in TREES:
645
+ edges, broken, seen = {}, [], set()
646
+ work = [(root, True, next((folder for folder in root.parents if (folder / "Cargo.toml").is_file()), None)) for root in roots]
647
+ while work:
648
+ file, owner, package = work.pop()
649
+ if (file, owner, package) in seen:
650
+ continue
651
+ seen.add((file, owner, package))
652
+ try:
653
+ parsed = parse_rust(file)
654
+ except ValueError as error:
655
+ broken.append(f"{file}: {error}")
656
+ continue
657
+ for declaration in parsed.declarations:
658
+ try:
659
+ targets = list(module_files(file, owner, parsed, declaration))
660
+ except ValueError as error:
661
+ broken.append(str(error))
662
+ continue
663
+ for target, owns in targets:
664
+ if target.is_file():
665
+ target = target.resolve()
666
+ edges.setdefault(target, set()).add((file, declaration))
667
+ work.append((target, owns, package))
668
+ for include in parsed.includes:
669
+ invocation = rust_masks(parsed.source.uncommented[include.keyword:include.end])
670
+ line = parsed.source.without_comments_or_strings.count("\n", 0, include.keyword) + 1
671
+ shown = collapse(invocation.uncommented, invocation.literals)
672
+ try:
673
+ target = include_path(invocation.uncommented[invocation.without_comments_or_strings.index("!") + 1:].strip()[1:-1], file, package)
674
+ except ValueError as error:
675
+ broken.append(f"{file}:{line}: cannot read the path in '{shown}': {error}")
676
+ continue
677
+ if target is None:
678
+ broken.append(f"{file}:{line}: cannot read the path in '{shown}'; write it as a string without escapes, or as concat! of such strings and env!(\"CARGO_MANIFEST_DIR\")")
679
+ elif target.is_file():
680
+ target = target.resolve()
681
+ edges.setdefault(target, set()).add((file, include))
682
+ work.append((target, True, package))
683
+ TREES[roots] = edges, broken
684
+ return TREES[roots]
685
+
686
+
687
+ def declaration_guards(path):
688
+ """Return the guards on the out-of-line `mod` declarations that lead to path from its crate roots, outermost
689
+ first, and the module path that each route gives path's items, with "" for a crate root. A crate root is one
690
+ route without guards, since its own crate always compiles it, unless it is a lib.rs or main.rs that Cargo does
691
+ not name and another file declares, which makes it a module. For more than one route, the guards are
692
+ `routes(...)` with each route as its crate root's path relative to path's directory, a colon and its guards,
693
+ or `unguarded` for a route without any, sorted and separated by `; `.
694
+
695
+ It follows each declaration from the crate roots by rustc's rules, including `#[path = "..."]` and each path
696
+ that a cfg_attr may set, and each `include!("...")` item outside function bodies. It does not expand macros, so
697
+ a declaration that a macro holds or builds is not a route it reads; `compiled_problems` checks those against the
698
+ harnesses that Kani compiles. It fails for a file that no route it reads reaches, and names each reached file,
699
+ declaration and `include!` that it could not read.
700
+ """
701
+ if (crates := crate_roots(path)) is None:
702
+ return "", {""}
703
+ roots, named = crates
704
+ edges, broken = module_tree(roots)
705
+ if path in roots and path not in edges:
706
+ return "", {""}
707
+ if path not in edges:
708
+ unread = "".join(f"; {message}" for message in broken)
709
+ raise ValueError(f"{path}: no module declaration that the record can read leads to this file from a crate root; declare it with `mod <name>;` or `#[path = \"...\"]` outside macros and function bodies, in a file that a crate root reaches{unread}")
710
+
711
+ def routes(file, visiting):
712
+ root = file in named or file in roots and all(declarer == file for declarer, _ in edges.get(file, ()))
713
+ found = [(file, "", "")] if root else []
714
+ for declarer, declaration in edges.get(file, ()):
715
+ if declarer in visiting:
716
+ continue
717
+ parsed = parse_rust(declarer)
718
+ enclosing = enclosing_modules(parsed, declaration)
719
+ items = [(0, 0, -1)] + [(module.start, module.keyword, module.body) for module in enclosing] + [(declaration.start, declaration.keyword, declaration.body)]
720
+ guards = cfg_guards(parsed.source, items)
721
+ # An included file's items sit in the modules around the include!; a declared file's in its module.
722
+ local = (enclosing[-1].name if enclosing else "") if declaration in parsed.includes else declaration.name
723
+ found += [(start, " ".join(filter(None, (route, guards))), "::".join(filter(None, (module, local))))
724
+ for start, route, module in routes(declarer, visiting | {declarer})]
725
+ return found
726
+
727
+ traced = routes(path, {path})
728
+ modules = {module for _, _, module in traced}
729
+ found = sorted((os.path.relpath(root, path.parent), guards) for root, guards, _ in traced)
730
+ if len(found) == 1:
731
+ return found[0][1], modules
732
+ labelled = "; ".join(f"{root}: {guards or 'unguarded'}" for root, guards in found)
733
+ return f"routes({labelled})", modules
734
+
735
+
393
736
  def kani_surface(path):
394
737
  source = rust_masks(path.read_text(encoding="utf-8"))
395
738
  text, mask = source.uncommented, source.without_comments_or_strings
396
739
  if renaming := RENAMING_IMPORT.search(mask):
397
740
  raise ValueError(f"{path}: '{collapse(renaming[0])}' brings a Kani assumption, cover, stub or harness attribute in under another name; write each as kani::<name> so the record can read it")
398
- functions, opaque = rust_functions(mask)
741
+ functions, modules, opaque, _, _ = rust_functions(mask)
742
+ declared, _ = declaration_guards(path)
399
743
 
400
744
  def owner_at(position, *, attribute=False):
401
745
  if not any(start <= position < end for start, end in opaque):
402
746
  for function in reversed(functions):
403
747
  if function.start <= position < function.end and (position < function.body if attribute else position > function.body):
404
- return function.name
748
+ return function
405
749
  line = mask.count("\n", 0, position) + 1
406
750
  raise ValueError(f"{path}:{line}: cannot identify a function owner; write Kani forms in free functions under inline modules, outside macro definitions and impl or trait bodies")
407
751
 
@@ -412,20 +756,90 @@ def kani_surface(path):
412
756
  end = after_closing(mask, match.end() - 1)
413
757
  read.append((match.start(), end))
414
758
  argument = rust_masks(text[match.end():end - 1])
415
- owner = owner_at(match.start(), attribute=kind == "stub")
416
- spans.append((match.start(), f"{kind} {collapse(argument.uncommented, argument.literals)} in {owner}"))
759
+ owner = owner_at(match.start(), attribute=kind == "stub").name
760
+ spans.append((match.start(), f"{kind} {collapse(argument.uncommented, argument.literals)} in {owner}", ""))
417
761
  for match in PROOF.finditer(mask):
418
762
  read.append(match.span())
419
- spans.append((match.start(), f"harness {owner_at(match.start(), attribute=True)}"))
763
+ harness = owner_at(match.start(), attribute=True)
764
+ enclosing = sorted((item for item in functions + modules if item.start <= harness.start and harness.end <= item.end), key=lambda item: item.start)
765
+ guards = " ".join(filter(None, (declared, cfg_guards(source, [(0, 0, -1)] + [(item.start, item.keyword, item.body) for item in enclosing]))))
766
+ spans.append((match.start(), f"harness {harness.name}", guards))
420
767
  for token in KANI_TOKEN.finditer(mask):
421
768
  if not any(start <= token.start() < end for start, end in read):
422
769
  line = mask.count("\n", 0, token.start()) + 1
423
770
  raise ValueError(f"{path}:{line}: '{collapse(token[0])}' is in a form the record cannot read; write kani::assume(...), kani::any_where(...), kani::cover!(...), #[kani::stub(...)] or #[kani::proof], alone or under #[cfg_attr(kani, ...)]")
424
- for _, item in sorted(spans):
425
- surface.add(item)
771
+ for _, item, guards in sorted(spans):
772
+ surface.add(item, guards)
426
773
  return surface
427
774
 
428
775
 
776
+ @functools.cache
777
+ def checker():
778
+ return kani.Kani()
779
+
780
+
781
+ @functools.cache
782
+ def compiled_in(package):
783
+ """Return each harness that Kani compiles in the Cargo package at package.
784
+
785
+ Raises:
786
+ ValueError: Kani is not installed, or cannot compile the package.
787
+ """
788
+ try:
789
+ with tempfile.TemporaryDirectory(prefix="baseline-kani-", dir=storage.ensure_temp_root()) as work:
790
+ return tuple(kani.compiled(package, Path(work), checker()))
791
+ except (kani.CheckError, runner.Unavailable) as error:
792
+ raise ValueError(f"cannot ask Kani which harnesses it compiles in {package}: {error}") from error
793
+
794
+
795
+ # A closure or a `const _` block puts an anonymous segment in Kani's name for a harness inside it.
796
+ ANONYMOUS = re.compile(r"\{\w+#\d+\}|_")
797
+
798
+
799
+ def item_path(name):
800
+ return "::".join(part.removeprefix("r#") for part in name.split("::") if not ANONYMOUS.fullmatch(part))
801
+
802
+
803
+ def route_owner(name, modules, owners):
804
+ """Return the owner in owners, keyed by item_path, that Kani's harness name gives under one of modules, or None.
805
+
806
+ The name must start with the module path itself. Anonymous segments are dropped only after it, since no route
807
+ that the record reads runs through a closure or a `const _` block.
808
+ """
809
+ parts = [part.removeprefix("r#") for part in name.split("::")]
810
+ for module in modules:
811
+ prefix = [part.removeprefix("r#") for part in module.split("::")] if module else []
812
+ if parts[:len(prefix)] == prefix and (owner := owners.get(item_path("::".join(parts[len(prefix):])))):
813
+ return owner
814
+ return None
815
+
816
+
817
+ def compiled_problems(path, surface, recorded=None):
818
+ """Return the lines on which the harnesses that Kani compiles from path disagree with surface and recorded, and
819
+ surface's harnesses that it compiles, as `harness <owner>` items, or None for them when no Cargo package holds
820
+ path.
821
+
822
+ Each harness that Kani compiles from path must be one of surface's harnesses under the module path of a route
823
+ that the record reads. A harness in recorded that Kani compiles on no route is a harness that was switched off.
824
+
825
+ Raises:
826
+ ValueError: Kani is not installed, or cannot compile the package.
827
+ """
828
+ package = next((folder for folder in path.parents if (folder / "Cargo.toml").is_file()), None)
829
+ if package is None:
830
+ return [f" not compiled {item}" for item in recorded or ()], None
831
+ names = {harness.name for harness in compiled_in(package) if harness.source == path}
832
+ _, modules = declaration_guards(path)
833
+ owners = {re.sub(r"\[\d+\]$", "", KANI_KEY.fullmatch(item)[2]) for item in surface if item.startswith("harness ")}
834
+ found = {name: route_owner(name, modules, {item_path(owner): owner for owner in owners}) for name in names}
835
+ lines = [f" FAIL Kani compiles {name} from this file, but no route that the record reads gives that name; declare "
836
+ "the module with `mod <name>;` or `#[path = \"...\"]` outside macros and function bodies"
837
+ for name, owner in sorted(found.items()) if owner is None]
838
+ compiled = sorted({f"harness {owner}" for owner in found.values() if owner is not None})
839
+ lines += [f" not compiled {item}" for item in sorted(set(recorded or ()) - set(compiled))]
840
+ return lines, compiled
841
+
842
+
429
843
  SURFACES = {"lean": lean_surface, "tla": tla_surface, "kani": kani_surface}
430
844
 
431
845
 
@@ -441,20 +855,15 @@ def read_record(path):
441
855
  for model, entry in models.items():
442
856
  if not isinstance(entry, dict) or entry.get("kind") not in SURFACES or not isinstance(entry.get("surface"), dict):
443
857
  raise ValueError(f"{path}: malformed entry for {model}")
858
+ compiled = entry.get("compiled", [])
859
+ if not isinstance(compiled, list) or not all(isinstance(name, str) for name in compiled):
860
+ raise ValueError(f"{path}: malformed entry for {model}")
444
861
  return models
445
862
 
446
863
 
447
864
  def write_record(path, models):
448
865
  path.parent.mkdir(parents=True, exist_ok=True)
449
- temporary = None
450
- try:
451
- with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent, delete=False) as stream:
452
- temporary = Path(stream.name)
453
- stream.write(json.dumps({"format": FORMAT, "models": models}, ensure_ascii=False, indent=2, sort_keys=True) + "\n")
454
- temporary.replace(path)
455
- finally:
456
- if temporary is not None:
457
- temporary.unlink(missing_ok=True)
866
+ runner.atomic_write(path, json.dumps({"format": FORMAT, "models": models}, ensure_ascii=False, indent=2, sort_keys=True) + "\n")
458
867
 
459
868
 
460
869
  def record(record_path, files):
@@ -463,24 +872,90 @@ def record(record_path, files):
463
872
  print(f"usage: {file} has no model surface; expected one of {', '.join(KINDS)}")
464
873
  return 2
465
874
  models = read_record(record_path) if record_path.exists() else {}
466
- updates = {}
875
+ updates, notes = {}, {}
467
876
  for file in files:
468
877
  kind = KINDS[file.suffix]
469
878
  surface = SURFACES[kind](file.resolve())
470
- updates[str(file.resolve())] = {"kind": kind, "digest": digest(surface), "surface": surface}
879
+ entry = {"kind": kind, "digest": digest(surface), "surface": surface}
880
+ if kind == "kani":
881
+ # A harness that no longer compiles is recorded from its text alone; compare asks Kani again.
882
+ try:
883
+ problems, names = compiled_problems(file.resolve(), surface)
884
+ except ValueError as error:
885
+ notes[str(file.resolve())] = f" not checked against Kani: {error}"
886
+ else:
887
+ if problems:
888
+ raise ValueError(f"{file.resolve()}: " + "; ".join(problem.strip().removeprefix("FAIL ") for problem in problems))
889
+ if names is not None:
890
+ entry["compiled"] = names
891
+ updates[str(file.resolve())] = entry
471
892
  for model, entry in updates.items():
472
893
  print(f"RECORDED {model} {entry['digest']}")
473
894
  previous = models.get(model, {}).get("digest")
474
895
  if previous and previous != entry["digest"]:
475
896
  print(f" previous {previous}")
897
+ if model in notes:
898
+ print(notes[model])
476
899
  write_record(record_path, {**models, **updates})
477
900
  return 0
478
901
 
479
902
 
903
+ KANI_KEY = re.compile(r"(harness |(?:assume|cover|stub) .* in )(\S+)( #\d+)?", re.DOTALL)
904
+
905
+
906
+ def renamed(surface, old_module, new_module):
907
+ """Rewrite each Kani owner under old_module to sit under new_module, where `crate` is the file's root."""
908
+ old, new = ([] if path == "crate" else path.split("::") for path in (old_module, new_module))
909
+ result = {}
910
+ for name, value in surface.items():
911
+ head, owner, duplicate = KANI_KEY.fullmatch(name).groups()
912
+ parts = owner.split("::")
913
+ if parts[:len(old)] == old:
914
+ owner = "::".join(new + parts[len(old):])
915
+ result[f"{head}{owner}{duplicate or ''}"] = value
916
+ if len(result) != len(surface):
917
+ raise ValueError(f"renaming {old_module} to {new_module} merges recorded items")
918
+ return result
919
+
920
+
921
+ def move(record_path, old_file, new_file, module):
922
+ models = read_record(record_path) if record_path.is_file() else {}
923
+ old, new = str(old_file.resolve()), str(new_file.resolve())
924
+ if old not in models:
925
+ print(f"usage: {old} has no record entry; record it before the move")
926
+ return 2
927
+ kind = models[old]["kind"]
928
+ if KINDS.get(new_file.suffix) != kind:
929
+ print(f"usage: {new} is not a {kind} model file")
930
+ return 2
931
+ if module and kind != "kani":
932
+ print("usage: --module applies only to a Kani harness file")
933
+ return 2
934
+ entry = models.pop(old)
935
+ surface, compiled = entry["surface"], entry.get("compiled")
936
+ if module:
937
+ surface = renamed(surface, *module)
938
+ compiled = compiled and list(renamed(dict.fromkeys(compiled), *module))
939
+ if new in models:
940
+ if overlap := surface.keys() & models[new]["surface"].keys():
941
+ raise ValueError(f"{new} already records {', '.join(sorted(overlap))}")
942
+ surface = {**models[new]["surface"], **surface}
943
+ # The merged entry holds Kani's list only when both entries were checked against Kani at record.
944
+ compiled = [*models[new]["compiled"], *compiled] if "compiled" in models[new] and compiled is not None else None
945
+ models[new] = {"kind": kind, "digest": digest(surface), "surface": surface}
946
+ if compiled is not None:
947
+ models[new]["compiled"] = sorted(compiled)
948
+ write_record(record_path, models)
949
+ print(f"MOVED {old} -> {new}")
950
+ return 0
951
+
952
+
480
953
  def differences(kind, old, new):
481
954
  lines = []
482
955
  if kind == "tla" and not any(name.startswith("imports ") for name in old):
483
956
  lines.append(" previous baseline did not track imported modules; review and record this matrix again")
957
+ if kind == "tla" and "TLA+ layout version" not in old:
958
+ lines.append(" previous baseline did not preserve TLA+ layout; review and record this matrix again")
484
959
  for name in old:
485
960
  if name not in new:
486
961
  lines.append(f" removed {name}")
@@ -501,7 +976,17 @@ def compare(record_path):
501
976
  if not Path(model).is_file():
502
977
  lines = [" file is missing"]
503
978
  else:
504
- lines = differences(entry["kind"], entry["surface"], SURFACES[entry["kind"]](Path(model)))
979
+ surface = SURFACES[entry["kind"]](Path(model))
980
+ lines = differences(entry["kind"], entry["surface"], surface)
981
+ if entry["kind"] == "kani":
982
+ try:
983
+ problems, names = compiled_problems(Path(model), surface, entry.get("compiled"))
984
+ lines += problems
985
+ if names is not None and "compiled" not in entry:
986
+ lines.append(" not checked against Kani at record, so compare cannot see a harness that "
987
+ "stopped compiling on a route that the record does not read")
988
+ except ValueError as error:
989
+ lines.append(f" FAIL {error}")
505
990
  except (OSError, ValueError, KeyError, TypeError) as error:
506
991
  lines = [f" FAIL {error}"]
507
992
  changed += bool(lines)
@@ -519,15 +1004,28 @@ def main():
519
1004
  recording.add_argument("record_file", type=Path)
520
1005
  recording.add_argument("models", nargs="+", type=Path)
521
1006
  commands.add_parser("compare", help="compare every recorded model with its file").add_argument("record_file", type=Path)
1007
+ moving = commands.add_parser("move", help="move a model's recorded entry to the file it moved to")
1008
+ moving.add_argument("record_file", type=Path)
1009
+ moving.add_argument("old_file", type=Path)
1010
+ moving.add_argument("new_file", type=Path)
1011
+ moving.add_argument("--module", nargs=2, metavar=("OLD", "NEW"),
1012
+ help="the Kani harnesses moved from module OLD to NEW; crate names the file's root")
522
1013
  arguments = parser.parse_args()
523
1014
  if arguments.command == "record":
524
1015
  return record(arguments.record_file, arguments.models)
1016
+ if arguments.command == "move":
1017
+ return move(arguments.record_file, arguments.old_file, arguments.new_file, arguments.module)
525
1018
  return compare(arguments.record_file)
526
1019
 
527
1020
 
528
- if __name__ == "__main__":
1021
+ def guarded_main():
529
1022
  try:
530
- sys.exit(main())
1023
+ return main()
531
1024
  except (OSError, ValueError, KeyError, TypeError) as error:
532
1025
  print(f"FAIL baseline: {error}")
533
- sys.exit(1)
1026
+ return 1
1027
+
1028
+
1029
+ if __name__ == "__main__":
1030
+ # The runner turns a stopping signal into an exception, so Kani's work directory is removed before the exit.
1031
+ runner.run(guarded_main)