agent-formal-verify 0.4.13 → 0.4.15

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.
@@ -148,15 +148,18 @@ def step(command, *, merge=True, env=None):
148
148
  return 127, "", f"cannot run {command[0]}: {error}\n"
149
149
 
150
150
 
151
- def project_sources(project):
152
- """Every .lean file in the project outside its .lake directory, except Lake's own lakefile.lean."""
153
- found = []
151
+ def project_files(project):
152
+ """Find model sources and orphan records in the same walk, outside the root Lake build directory."""
153
+ sources, records = set(), []
154
154
  for top, directories, names in os.walk(project):
155
- found += [os.path.join(top, name) for name in directories + names
156
- if name.endswith(".lean") and name != "lakefile.lean"]
157
155
  if top == project and ".lake" in directories:
158
156
  directories.remove(".lake")
159
- return sorted(found)
157
+ for name in directories + names:
158
+ if name.endswith(".lean") and (top != project or name != "lakefile.lean"):
159
+ sources.add(os.path.join(top, name))
160
+ elif name.endswith(".statements"):
161
+ records.append(Path(top, name))
162
+ return sorted(sources), sorted(path for path in records if str(path.with_suffix(".lean")) not in sources)
160
163
 
161
164
 
162
165
  def layout(objects, search_path):
@@ -205,18 +208,14 @@ def records_by_name(modules, module):
205
208
  return records
206
209
 
207
210
 
208
- def check_orphans(project, out):
209
- """Report every record whose source file is gone, outside the .lake directory."""
210
- failed = False
211
- for path in sorted(project.rglob("*.statements")):
212
- if ".lake" in path.relative_to(project).parts or path.with_suffix(".lean").is_file():
213
- continue
211
+ def check_orphans(orphans, out):
212
+ """Report every record without a model source in the project."""
213
+ for path in orphans:
214
214
  record = read_record(path)
215
215
  out(f"FROZEN {path}: source file is missing")
216
216
  for declaration in record["declarations"]:
217
217
  out(f"FROZEN {declaration['name']}: statement changed (source deleted)")
218
- failed = True
219
- return int(failed)
218
+ return int(bool(orphans))
220
219
 
221
220
 
222
221
  def freeze_statements(toolchain, modules, sources, out):
@@ -313,14 +312,14 @@ def checked(project, toolchain, files, freeze, out, work):
313
312
  out(f"FAIL {source} does not exist")
314
313
  return 1
315
314
  else:
315
+ sources, orphans = project_files(project)
316
316
  if not freeze:
317
- status, output = statements(lambda sink: check_orphans(Path(project), sink))
317
+ status, output = statements(lambda sink: check_orphans(orphans, sink))
318
318
  if status:
319
319
  out(f"FAIL {scope}: frozen model sources are missing or their records are invalid")
320
320
  for line in output:
321
321
  out(line)
322
322
  return status
323
- sources = project_sources(project)
324
323
  if not sources:
325
324
  out(f"FAIL {project} has no .lean file to check")
326
325
  return 1
@@ -409,12 +408,17 @@ def checked(project, toolchain, files, freeze, out, work):
409
408
  # replays every declaration of the built modules through the kernel and rejects it. Use its exact-module
410
409
  # replayer rather than its CLI's prefix search, which also finds deleted sources' cached objects. A named
411
410
  # module rests on the project modules it imports, so replay those too.
412
- prefix = processes.guarded(["elan", "run", toolchain, "lean", "--print-prefix"],
413
- lambda process: process.communicate()[0], stdout=subprocess.PIPE,
414
- encoding="utf-8", errors="replace")
411
+ status, prefix, errors = step(["elan", "run", toolchain, "lean", "--print-prefix"], merge=False)
415
412
  prefix = prefix.rstrip("\n")
413
+ compiler = os.path.join(prefix, "bin", "lean")
414
+ if status or not os.path.isabs(prefix) or not os.path.isfile(compiler) or not os.access(compiler, os.X_OK):
415
+ out(f"FAIL {scope}: cannot locate {toolchain} for kernel replay (lean --print-prefix exit {status})")
416
+ for line in lines(errors) + lines(prefix):
417
+ out(line)
418
+ return 1
416
419
  replay = "unavailable"
417
- if os.access(f"{prefix}/bin/leanchecker", os.X_OK):
420
+ # The replayer imports LeanChecker. The installed CLI marks support even if its execute bit was lost.
421
+ if os.path.lexists(f"{prefix}/bin/leanchecker"):
418
422
  imported = [line.removeprefix("IMPORTED ") for line in audit if line.startswith("IMPORTED ")]
419
423
  replayed = set(modules) | {module for module in imported
420
424
  if any((library / (module.replace(".", "/") + ".olean")).is_file() for library in libraries)}
@@ -89,13 +89,13 @@ def _command_sites(source, commands, edit_start, edit_end):
89
89
  yield (cmd["property"], site), cmd, first
90
90
 
91
91
 
92
- def _compare_commands(model, before, mutation, after):
93
- start = mutation.original.index(mutation.old)
92
+ def _compare_commands(model, before, mutation, source, after):
93
+ start = mutation.start
94
94
  end = start + len(mutation.new)
95
95
  originals = {}
96
96
  for site, cmd, _ in _command_sites(mutation.original, before, start, start + len(mutation.old)):
97
97
  originals.setdefault(site, []).append(cmd["statement"])
98
- commands = list(_command_sites(mutation.source, after, start, end))
98
+ commands = list(_command_sites(source, after, start, end))
99
99
  counts = Counter(site for site, _, _ in commands)
100
100
  line_shift = mutation.old.count("\n") - mutation.new.count("\n")
101
101
  edit_line = mutation.original.count("\n", 0, start) + 1
@@ -139,10 +139,9 @@ class OriginalChecks:
139
139
  self._theorems = {(decl["name"], decl["type"]) for decl in theorems}
140
140
  self._commands = original["commands"]
141
141
 
142
- def _theorem_checks(self, declarations, mutation):
143
- start = mutation.original.index(mutation.old)
144
- edit_start = _position(mutation.source, start)
145
- edit_end = _position(mutation.source, start + len(mutation.new))
142
+ def _theorem_checks(self, declarations, mutation, source):
143
+ edit_start = _position(source, mutation.start)
144
+ edit_end = _position(source, mutation.start + len(mutation.new))
146
145
  theorems = [decl for decl in declarations if decl["theorem"]]
147
146
  names = {decl["name"] for decl in theorems}
148
147
  for decl in theorems:
@@ -156,12 +155,12 @@ class OriginalChecks:
156
155
  problem = ""
157
156
  yield _Check(decl["start"], decl["end"], "theorem " + name, problem, _is_witness(name, names))
158
157
 
159
- def broken_checks(self, mutation, copy, analysis):
158
+ def broken_checks(self, mutation, source, copy, analysis):
160
159
  """Return the original checks that fail, or raise ValueError if any error cannot be attributed."""
161
160
  if not analysis["errors"]:
162
161
  return []
163
- theorems = list(self._theorem_checks(analysis["declarations"], mutation))
164
- commands = list(_compare_commands(self._path, self._commands, mutation, analysis["commands"]))
162
+ theorems = list(self._theorem_checks(analysis["declarations"], mutation, source))
163
+ commands = list(_compare_commands(self._path, self._commands, mutation, source, analysis["commands"]))
165
164
  failed = []
166
165
  for error in analysis["errors"]:
167
166
  position = [error["pos"]["line"], error["pos"]["column"]]
@@ -189,7 +188,8 @@ def prepare(model, project):
189
188
 
190
189
  def check(mutation, work):
191
190
  copy = work / model.name
192
- copy.write_text(mutation.source, encoding="utf-8")
193
- return original.broken_checks(mutation, copy, _analyze(copy, project, pin))
191
+ source = mutation.apply()
192
+ copy.write_text(source, encoding="utf-8")
193
+ return original.broken_checks(mutation, source, copy, _analyze(copy, project, pin))
194
194
 
195
195
  return original.targets, check
@@ -93,7 +93,10 @@ class Mutation:
93
93
  old: str
94
94
  new: str
95
95
  original: str
96
- source: str
96
+ start: int
97
+
98
+ def apply(self):
99
+ return "".join((self.original[:self.start], self.new, self.original[self.start + len(self.old):]))
97
100
 
98
101
 
99
102
  class Verdict(Enum):
@@ -135,7 +138,7 @@ def parse(path):
135
138
 
136
139
 
137
140
  def make_mutation(label, directives, model, text, language):
138
- """Check one mutation's directives against its language and apply it to the model's text."""
141
+ """Validate one mutation and locate its edit in the original model."""
139
142
  lines = {keyword: [rest for word, rest in directives if word == keyword] for keyword in DIRECTIVES}
140
143
  for keyword in SINGLE:
141
144
  if len(lines[keyword]) > 1:
@@ -147,17 +150,18 @@ def make_mutation(label, directives, model, text, language):
147
150
  if lines["only"] and not language.takes_only:
148
151
  stop(f"mutation '{label}': {language.name} mutations do not support 'only'")
149
152
  old = "\n".join(lines["-"])
150
- count = text.count(old) if old else 0
151
- if count != 1:
153
+ start = text.find(old) if old else -1
154
+ if start < 0 or text.find(old, start + len(old)) >= 0:
155
+ count = text.count(old) if old else 0
152
156
  stop(f"mutation '{label}': its - text occurs {count} times in {model}, want 1")
153
157
  detects, only = (lines[keyword][0].strip() if lines[keyword] else "" for keyword in SINGLE)
154
158
  new = "\n".join(lines["+"])
155
- return Mutation(label, detects, only, old, new, text, text.replace(old, new))
159
+ return Mutation(label, detects, only, old, new, text, start)
156
160
 
157
161
 
158
162
  def check_tla(plan, checker, mutation, work):
159
163
  try:
160
- detection = plan.check(checker, mutation.detects, mutation.only, mutation.source, work)
164
+ detection = plan.check(checker, mutation.detects, mutation.only, mutation.apply(), work)
161
165
  except ValueError as error:
162
166
  return Result(Verdict.ERROR, str(error))
163
167
  covers = frozenset({mutation.detects})
@@ -178,9 +182,9 @@ def check_lean(broken_checks, mutation, work):
178
182
 
179
183
  def check_rust(model, project, verifier, bounds, sources, mutation, work):
180
184
  """Run Kani on the named harness in a mutated copy of the crate; the mutation covers that harness."""
181
- copy = sources.stage(project, work / "source")
185
+ copy = sources.stage(project, work)
182
186
  covers = frozenset({mutation.detects})
183
- (copy / model.relative_to(project)).write_text(mutation.source, encoding="utf-8")
187
+ (copy / model.relative_to(project)).write_text(mutation.apply(), encoding="utf-8")
184
188
  # Cargo resolves configuration from cwd, including paths outside the copied packages.
185
189
  outcome = kani.verify(copy, work, verifier, mutation.detects, bounds[mutation.detects].unwind, cwd=project)
186
190
  if outcome.verdict is kani.Verdict.PASS:
@@ -0,0 +1,74 @@
1
+ # Copyright (c) 2026 Michael Denyer
2
+ # SPDX-License-Identifier: GPL-3.0-only
3
+ """Read Rust source text: blank its comments and string contents, and find where a bracketed span ends."""
4
+ import re
5
+ from typing import NamedTuple
6
+
7
+
8
+ class RustSource(NamedTuple):
9
+ uncommented: str
10
+ without_comments_or_strings: str
11
+ literals: list
12
+
13
+
14
+ def rust_masks(source):
15
+ text, mask = list(source), list(source)
16
+ literals = []
17
+
18
+ def blank(start, end, *, both):
19
+ for i in range(start, end):
20
+ if source[i] != "\n":
21
+ mask[i] = " "
22
+ if both:
23
+ text[i] = " "
24
+
25
+ i = 0
26
+ while i < len(source):
27
+ if source.startswith("//", i):
28
+ end = source.find("\n", i)
29
+ end = len(source) if end < 0 else end
30
+ blank(i, end, both=True)
31
+ i = end
32
+ elif source.startswith("/*", i):
33
+ depth, start = 0, i
34
+ while i < len(source):
35
+ if source.startswith("/*", i):
36
+ depth, i = depth + 1, i + 2
37
+ elif source.startswith("*/", i):
38
+ depth, i = depth - 1, i + 2
39
+ if not depth:
40
+ break
41
+ else:
42
+ i += 1
43
+ blank(start, i, both=True)
44
+ elif raw := re.compile(r'(?<!\w)[bc]?r(#*)"').match(source, i):
45
+ close = source.find('"' + raw[1], raw.end())
46
+ content_end = len(source) if close < 0 else close
47
+ blank(raw.end(), content_end, both=False)
48
+ i = content_end + 1 + len(raw[1])
49
+ literals.append((raw.start(), min(i, len(source))))
50
+ elif source[i] == '"':
51
+ opening = i
52
+ start = i = i + 1
53
+ while i < len(source) and source[i] != '"':
54
+ i += 2 if source[i] == "\\" else 1
55
+ blank(start, min(i, len(source)), both=False)
56
+ i += 1
57
+ literals.append((opening, min(i, len(source))))
58
+ elif char := re.compile(r"'(?:\\.[^']*|[^'\\])'").match(source, i):
59
+ blank(char.start() + 1, char.end() - 1, both=False)
60
+ i = char.end()
61
+ literals.append(char.span())
62
+ else:
63
+ i += 1
64
+ return RustSource("".join(text), "".join(mask), literals)
65
+
66
+
67
+ def after_closing(mask, opener):
68
+ closer = {"(": ")", "[": "]", "{": "}"}[mask[opener]]
69
+ depth = 0
70
+ for i in range(opener, len(mask)):
71
+ depth += (mask[i] == mask[opener]) - (mask[i] == closer)
72
+ if not depth:
73
+ return i + 1
74
+ raise ValueError(f"unbalanced {mask[opener]} at offset {opener}")
@@ -0,0 +1,27 @@
1
+ # Copyright (c) 2026 Michael Denyer
2
+ # SPDX-License-Identifier: GPL-3.0-only
3
+ """Hold a model's surface, the mapping from item name to canonical value, and collapse whitespace outside strings."""
4
+ import re
5
+
6
+ STRING = re.compile(r'"(?:\\.|[^"\\])*"', re.DOTALL)
7
+
8
+
9
+ def collapse(text, literals=None):
10
+ if literals is None:
11
+ literals = (match.span() for match in STRING.finditer(text))
12
+ parts, end = [], 0
13
+ for start, stop in literals:
14
+ parts.extend((re.sub(r"\s+", " ", text[end:start]), text[start:stop]))
15
+ end = stop
16
+ parts.append(re.sub(r"\s+", " ", text[end:]))
17
+ return "".join(parts).strip()
18
+
19
+
20
+ class Surface(dict):
21
+ def add(self, name, value=""):
22
+ candidate, count = name, 1
23
+ while candidate in self:
24
+ count += 1
25
+ candidate = f"{name} #{count}"
26
+ self[candidate] = value
27
+ return candidate
@@ -46,7 +46,7 @@ import sys
46
46
  from pathlib import Path
47
47
 
48
48
  sys.dont_write_bytecode = True
49
- import baseline
49
+ import rust_source
50
50
 
51
51
  HEADER = re.compile(r"Source read at ([0-9a-fA-F]{7,40})\b")
52
52
  # Documents and model files mention covered names but cannot define them, unless a source has the same extension.
@@ -71,7 +71,7 @@ FALLBACK_COMMITS = 100
71
71
  def rust_code(path):
72
72
  """Return a Rust file's text with its comments and strings blanked, or None when it cannot be read."""
73
73
  try:
74
- return baseline.rust_masks(path.read_text(encoding="utf-8", errors="replace")).without_comments_or_strings
74
+ return rust_source.rust_masks(path.read_text(encoding="utf-8", errors="replace")).without_comments_or_strings
75
75
  except OSError:
76
76
  return None
77
77
 
@@ -107,15 +107,15 @@ def git(root, *arguments, check=True):
107
107
  @functools.cache
108
108
  def split_harness(text):
109
109
  """Return the code of the #[cfg(kani)] items in Rust text and the code outside them, without comments or blank lines."""
110
- source = baseline.rust_masks(text)
110
+ source = rust_source.rust_masks(text)
111
111
  mask, spans = source.without_comments_or_strings, []
112
112
  for found in KANI_CFG.finditer(mask):
113
113
  if spans and found.start() < spans[-1][1]:
114
114
  continue
115
115
  at = found.end()
116
116
  while at < len(mask) and mask[at] not in "{;":
117
- at = baseline.after_closing(mask, at) if mask[at] in "([" else at + 1
118
- end = baseline.after_closing(mask, at) if at < len(mask) and mask[at] == "{" else at + 1
117
+ at = rust_source.after_closing(mask, at) if mask[at] in "([" else at + 1
118
+ end = rust_source.after_closing(mask, at) if at < len(mask) and mask[at] == "{" else at + 1
119
119
  spans.append((found.start(), end))
120
120
  starts = [0] + [end for _, end in spans]
121
121
  ends = [start for start, _ in spans] + [len(mask)]
@@ -370,19 +370,20 @@ def main():
370
370
  print(f"FAIL --source {source} is {path}, which no commit in {root} has")
371
371
  return 1
372
372
  sources.append(str(path.relative_to(root)))
373
- paths = renamed(root, sync, sources)
373
+ source_paths = renamed(root, sync, sources)
374
+ paths = set(source_paths)
374
375
  excluded = [f":(exclude){path}" for path in relative if path not in sources]
375
- suffixes = {Path(path).suffix.lower() for path in paths}
376
+ suffixes = {Path(path).suffix.lower() for path in source_paths}
376
377
  missing = []
377
378
  for name in arguments.name:
378
379
  found = git(root, "grep", "-l", "-z", "-w", "-F", "-e", name, "--", ".", *excluded, check=False)
379
380
  if found.returncode > 1:
380
381
  raise RuntimeError(f"git grep for {name} failed: {found.stderr.strip()}")
381
- roles = {file: role(file, paths, suffixes) for file in found.stdout.split("\0") if file}
382
+ roles = {file: role(file, source_paths, suffixes) for file in found.stdout.split("\0") if file}
382
383
  if not any(kind == "defines" and in_code(root, file, name) for file, kind in roles.items()):
383
384
  missing.append(name)
384
385
  files = [*roles, *held(root, sync, name, [".", *excluded])]
385
- paths.update(file for file in files if role(file, paths, suffixes))
386
+ paths.update(file for file in files if role(file, source_paths, suffixes))
386
387
  for path in sorted(paths):
387
388
  print(f"PATH {path}")
388
389
  for name in missing:
@@ -22,6 +22,7 @@ Usage: tlc-matrix.sh <matrix-file> [label-substring]
22
22
  JAVA=<path> the java binary (default: java on PATH)
23
23
  TLC_WORKERS=<n> TLC worker threads (default auto)
24
24
  TLC_TIMEOUT=<lim> per-run time limit, e.g. 90s, 30m, 1h (default 60m)
25
+ TLC_HTML_REPORT=<path> write a self-contained HTML report to this path
25
26
 
26
27
  Usage: tlc.py ready
27
28
  Checks TLC_TIMEOUT, that Java runs, and that the JAR is the pinned release or the one TLC_JAR names, then reports
@@ -87,7 +88,11 @@ class Reach:
87
88
  @dataclass(frozen=True)
88
89
  class Run:
89
90
  label: str
90
- constants: str
91
+ bindings: tuple[tuple[str, str], ...]
92
+
93
+ @property
94
+ def constants(self):
95
+ return " ".join(f"{name}={value}" for name, value in self.bindings)
91
96
 
92
97
 
93
98
  @dataclass(frozen=True)
@@ -95,6 +100,16 @@ class Malformed:
95
100
  message: str
96
101
 
97
102
 
103
+ def _parse_run(label, constants):
104
+ bindings = []
105
+ for token in constants.split():
106
+ name, _, value = token.partition("=")
107
+ if not name or not value:
108
+ return Malformed(f"malformed constant {token!r} in run {label!r}: expected Name=Value")
109
+ bindings.append((name, value))
110
+ return Run(label, tuple(bindings))
111
+
112
+
98
113
  def _directives(lines):
99
114
  """Yield each directive of a matrix in file order, with a Malformed in place of a line it rejects."""
100
115
  seen_spec = False
@@ -130,7 +145,7 @@ def _directives(lines):
130
145
  elif not seen_spec:
131
146
  yield Malformed(f"run '{label.rstrip()}' before any spec line")
132
147
  else:
133
- yield Run(label.rstrip(), constants)
148
+ yield _parse_run(label.rstrip(), constants)
134
149
  else:
135
150
  yield Malformed(f"unknown directive: {line}")
136
151
 
@@ -310,6 +325,10 @@ class Result:
310
325
  lines: tuple = ()
311
326
  states: int = 0
312
327
  violation: Violation | None = None
328
+ constants: str = ""
329
+ checks: tuple[str, ...] = ()
330
+ duration_s: float = 0.0
331
+ trace: tlc_trace.Trace | None = None
313
332
 
314
333
 
315
334
  @dataclass(frozen=True)
@@ -500,13 +519,18 @@ def reduced_trace(log):
500
519
  return lines if lines is not None else [line for line in log.split("\n") if line.strip()][-40:]
501
520
 
502
521
 
503
- def run_task(checker, matrix_dir, task, work, source=None):
504
- """Execute a resolved matrix task, optionally replacing its spec in the private run directory."""
522
+ def run_task(checker, matrix_dir, task, work, source=None, traces=False):
523
+ """Execute a resolved matrix task, optionally replacing its spec in the private run directory.
524
+
525
+ With traces, a FAIL or WITNESS result holds the parsed trace for the HTML report.
526
+ """
505
527
  spec, run = task.spec, task.run
506
528
  operator = task.reach.operator if task.reach else ""
507
529
  name = Path(spec).name.removesuffix(".tla")
530
+ run_constants = run.constants
531
+ run_checks = tuple(check.line for check in task.checks)
508
532
  if not (matrix_dir / spec).is_file():
509
- return Result(Outcome.MISSING, name, run.label, detail=spec)
533
+ return Result(Outcome.MISSING, name, run.label, detail=spec, constants=run_constants, checks=run_checks)
510
534
  directory = Path(tempfile.mkdtemp(prefix="run.", dir=work))
511
535
  try:
512
536
  for module in (matrix_dir / spec).parent.glob("*.tla"):
@@ -515,33 +539,39 @@ def run_task(checker, matrix_dir, task, work, source=None):
515
539
  dest.write_text(source, encoding="utf-8")
516
540
  else:
517
541
  dest.write_bytes(module.read_bytes())
518
- constants = "".join(f" {pair.split('=')[0]} = {pair.split('=', 1)[-1]}\n" for pair in run.constants.split())
542
+ constants = "".join(f" {name} = {value}\n" for name, value in run.bindings)
519
543
  config = f"CONSTANTS\n{constants}SPECIFICATION Spec\n"
520
544
  if not task.check_deadlock:
521
545
  config += "CHECK_DEADLOCK FALSE\n"
522
546
  if not operator:
547
+ start = time.monotonic()
523
548
  status, log, timed_out = checker.run(
524
549
  directory, name, config + "\n".join(check.line for check in task.checks) + "\n",
525
550
  reach=False, progress_label=f"{name} {run.label}",
526
551
  )
552
+ elapsed = time.monotonic() - start
527
553
  shutil.rmtree(directory / "states", ignore_errors=True)
528
- return ordinary(name, run, status, log, checker.limit if timed_out else None)
554
+ result = ordinary(name, run, status, log, checker.limit if timed_out else None, traces)
555
+ return replace(result, constants=run_constants, checks=run_checks, duration_s=elapsed)
529
556
  wrapper = f"Reach{uuid.uuid4().hex}"
530
557
  invariant = f"{wrapper}Negated"
531
558
  (directory / f"{wrapper}.tla").write_text(f"---- MODULE {wrapper} ----\nEXTENDS {name}\n{invariant} == ~{operator}\n====\n", encoding="utf-8")
532
559
  # Exhaustive UNREACHED checks in reach: mutations do not depend on shortest-trace determinism.
533
560
  reach_workers = checker.workers if source is not None else "1"
561
+ start = time.monotonic()
534
562
  status, log, timed_out = checker.run(
535
563
  directory, wrapper, config + f"INVARIANT {invariant}\n",
536
564
  reach=True, workers=reach_workers, progress_label=f"{name} reach {operator} {run.label}",
537
565
  )
538
- return witness(name, run, operator, invariant, status, log, checker.limit if timed_out else None)
566
+ elapsed = time.monotonic() - start
567
+ result = witness(name, run, operator, invariant, status, log, checker.limit if timed_out else None, traces)
568
+ return replace(result, constants=run_constants, checks=run_checks, duration_s=elapsed)
539
569
  finally:
540
570
  shutil.rmtree(directory, ignore_errors=True)
541
571
 
542
572
 
543
573
 
544
- def ordinary(name, run, status, log, timeout_limit=None):
574
+ def ordinary(name, run, status, log, timeout_limit=None, traces=False):
545
575
  if timeout_limit:
546
576
  tail = tuple(line for line in log.split("\n") if line.strip())[-10:]
547
577
  return Result(Outcome.FAIL, name, run.label,
@@ -553,10 +583,10 @@ def ordinary(name, run, status, log, timeout_limit=None):
553
583
  errors = [line for line in log.split("\n") if line.startswith("Error:")]
554
584
  first = errors[0] if errors else ""
555
585
  return Result(Outcome.FAIL, name, run.label, detail=first, lines=(*errors[1:5], *reduced_trace(log)),
556
- violation=violation(first))
586
+ violation=violation(first), trace=tlc_trace.parse(re.split(r"\r\n|\r|\n", log)) if traces else None)
557
587
 
558
588
 
559
- def witness(name, run, operator, invariant, status, log, timeout_limit=None):
589
+ def witness(name, run, operator, invariant, status, log, timeout_limit=None, traces=False):
560
590
  if timeout_limit:
561
591
  tail = tuple(line for line in log.split("\n") if line.strip())[-10:]
562
592
  return Result(Outcome.INCOMPLETE, name, run.label, operator,
@@ -568,7 +598,8 @@ def witness(name, run, operator, invariant, status, log, timeout_limit=None):
568
598
  elif status == 12 and f"Error: Invariant {invariant} is violated." in lines:
569
599
  length = sum(1 for line in lines if re.match(r"State [0-9]+:", line))
570
600
  if length:
571
- return Result(Outcome.WITNESS, name, run.label, operator, f"{length} states ({length - 1} transitions)")
601
+ return Result(Outcome.WITNESS, name, run.label, operator, f"{length} states ({length - 1} transitions)",
602
+ trace=tlc_trace.parse(re.split(r"\r\n|\r|\n", log)) if traces else None)
572
603
  if status == 0 and "No error has been found" in log:
573
604
  return Result(Outcome.UNREACHED, name, run.label, operator)
574
605
  return Result(Outcome.INCOMPLETE, name, run.label, operator, lines=tuple(log.removesuffix("\n").split("\n")) if log else ())
@@ -577,12 +608,16 @@ def witness(name, run, operator, invariant, status, log, timeout_limit=None):
577
608
  class Runner:
578
609
  """Run the selected tasks and report each result to emit."""
579
610
 
580
- def __init__(self, tlc, matrix_dir, only, emit, work):
611
+ def __init__(self, tlc, matrix_dir, only, emit, work, keep_results=False):
581
612
  self.tlc, self.matrix_dir, self.only, self.emit, self.work = tlc, matrix_dir, only, emit, work
582
613
  self.runs_total = self.passed = self.states = self.reach_total = self.reached = 0
583
614
  self.failed = False
615
+ # Only the HTML report reads the results and their traces.
616
+ self.results = [] if keep_results else None
584
617
 
585
618
  def report(self, result):
619
+ if self.results is not None:
620
+ self.results.append(result)
586
621
  self.failed |= result.outcome not in (Outcome.PASS, Outcome.WITNESS)
587
622
  self.emit(result)
588
623
 
@@ -597,7 +632,7 @@ class Runner:
597
632
  self.reach_total += 1
598
633
  else:
599
634
  self.runs_total += 1
600
- result = run_task(self.tlc, self.matrix_dir, task, self.work)
635
+ result = run_task(self.tlc, self.matrix_dir, task, self.work, traces=self.results is not None)
601
636
  if result.outcome is Outcome.PASS:
602
637
  self.passed += 1
603
638
  self.states += result.states
@@ -606,6 +641,50 @@ class Runner:
606
641
  self.report(result)
607
642
 
608
643
 
644
+ REPORT_REMEDY = "set it to a file in an existing directory that you can write to, or unset it to write no report"
645
+
646
+
647
+ def validate_report_path(raw: str) -> Path | None:
648
+ """Return the TLC_HTML_REPORT path, checked before TLC starts, or None when it is unset.
649
+
650
+ Raise runner.Unavailable naming the setting when the report cannot be written there.
651
+ """
652
+ trimmed = raw.strip()
653
+ if not trimmed:
654
+ return None
655
+
656
+ def unavailable(problem):
657
+ return runner.Unavailable(f"UNAVAILABLE TLC_HTML_REPORT={trimmed!r} {problem}; {REPORT_REMEDY}")
658
+
659
+ seps = tuple(dict.fromkeys(s for s in ("/", os.sep, os.altsep) if s))
660
+ dot_suffixes = tuple(f"{sep}." for sep in seps) + tuple(f"{sep}.." for sep in seps)
661
+ if trimmed in (".", "..") or trimmed.endswith(seps + dot_suffixes):
662
+ raise unavailable("is a directory")
663
+ path = Path(trimmed)
664
+ try:
665
+ is_dir = path.is_dir()
666
+ parent_is_dir = path.parent.is_dir()
667
+ exists = path.exists()
668
+ is_file = path.is_file() if exists else False
669
+ except OSError as error:
670
+ raise unavailable(f"is not accessible: {error}") from error
671
+ if is_dir:
672
+ raise unavailable("is a directory")
673
+ if not parent_is_dir:
674
+ raise unavailable("is not in an existing directory")
675
+ if exists and not is_file:
676
+ raise unavailable("is not a regular file")
677
+ try:
678
+ fd, temp_path = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.")
679
+ except OSError as error:
680
+ raise unavailable(f"is not writable: {error}") from error
681
+ try:
682
+ os.close(fd)
683
+ finally:
684
+ Path(temp_path).unlink(missing_ok=True)
685
+ return path
686
+
687
+
609
688
  def main():
610
689
  if sys.argv[1:] == ["ready"]:
611
690
  print(f"READY TLC {Tlc().jar}")
@@ -619,8 +698,10 @@ def main():
619
698
  print(f"FAIL {matrix} does not exist")
620
699
  return 1
621
700
  tlc = Tlc()
701
+ report_path = validate_report_path(os.environ.get("TLC_HTML_REPORT", ""))
622
702
  with tempfile.TemporaryDirectory(dir=storage.ensure_temp_root()) as work:
623
- matrix_runner = Runner(tlc, Path(matrix).resolve().parent, only, lambda result: print("\n".join(render(result)), flush=True), Path(work))
703
+ matrix_runner = Runner(tlc, Path(matrix).resolve().parent, only, lambda result: print("\n".join(render(result)), flush=True), Path(work),
704
+ keep_results=report_path is not None)
624
705
  for task in MatrixPlan(matrix):
625
706
  matrix_runner.check(task)
626
707
  if matrix_runner.runs_total == 0:
@@ -630,7 +711,17 @@ def main():
630
711
  summary = f"SUMMARY {matrix_runner.passed} of {matrix_runner.runs_total} runs passed"
631
712
  if matrix_runner.reach_total:
632
713
  summary += f", {matrix_runner.reached} of {matrix_runner.reach_total} reach checks passed"
633
- print(f"{summary}, {matrix_runner.states} distinct states in total")
714
+ summary_line = f"{summary}, {matrix_runner.states} distinct states in total"
715
+ print(summary_line)
716
+ if report_path is not None:
717
+ import tlc_report
718
+
719
+ try:
720
+ tlc_report.write_html(report_path, Path(matrix).name, matrix_runner.results, summary_line, only=only)
721
+ except OSError as error:
722
+ # A failed run's status wins over a report that could not be written.
723
+ print(f"UNAVAILABLE TLC_HTML_REPORT={str(report_path)!r} could not be written: {error}; {REPORT_REMEDY}")
724
+ return 1 if matrix_runner.failed else 3
634
725
  return int(matrix_runner.failed)
635
726
 
636
727