agent-formal-verify 0.4.12 → 0.4.14

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 (43) hide show
  1. package/CHANGES.md +150 -0
  2. package/README.md +5 -3
  3. package/package.json +2 -1
  4. package/skills/formal-verify/SKILL.md +17 -19
  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 +33 -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 +3 -3
  16. package/skills/formal-verify/scripts/baseline.py +290 -261
  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/kani_reader.py +592 -0
  20. package/skills/formal-verify/scripts/lean-analysis.lean +387 -0
  21. package/skills/formal-verify/scripts/lean-check.sh +6 -243
  22. package/skills/formal-verify/scripts/lean.py +484 -0
  23. package/skills/formal-verify/scripts/lean_mutations.py +195 -0
  24. package/skills/formal-verify/scripts/lean_records.py +25 -0
  25. package/skills/formal-verify/scripts/mutate.py +81 -195
  26. package/skills/formal-verify/scripts/processes.py +266 -0
  27. package/skills/formal-verify/scripts/python-tools.sh +15 -0
  28. package/skills/formal-verify/scripts/runner.py +56 -0
  29. package/skills/formal-verify/scripts/rust_source.py +74 -0
  30. package/skills/formal-verify/scripts/setup.sh +18 -19
  31. package/skills/formal-verify/scripts/storage.py +207 -0
  32. package/skills/formal-verify/scripts/surface.py +27 -0
  33. package/skills/formal-verify/scripts/sync.py +401 -0
  34. package/skills/formal-verify/scripts/tlc-matrix.sh +3 -1
  35. package/skills/formal-verify/scripts/tlc.py +501 -117
  36. package/skills/formal-verify/scripts/tlc_report.py +516 -0
  37. package/skills/formal-verify/scripts/tlc_trace.py +167 -0
  38. package/skills/setup/SKILL.md +1 -1
  39. package/skills/formal-verify/scripts/lean-mutations.lean +0 -95
  40. package/skills/formal-verify/scripts/lean-statements.py +0 -161
  41. package/skills/formal-verify/scripts/lean-tools.sh +0 -24
  42. package/skills/formal-verify/scripts/tlc-tools.sh +0 -47
  43. package/skills/formal-verify/scripts/tlc-trace.py +0 -64
@@ -5,7 +5,7 @@
5
5
 
6
6
  Prints one PASS or FAIL line per run with its distinct state count, then a
7
7
  SUMMARY line with the totals. A failing run prints TLC's error and its error
8
- trace reduced to the variables each step changed (tlc-trace.py).
8
+ trace reduced to the variables each step changed (tlc_trace.py).
9
9
 
10
10
  Matrix file, one directive per line (# starts a comment):
11
11
  spec <path.tla> the spec for the runs below, relative to the file;
@@ -21,20 +21,42 @@ Usage: tlc-matrix.sh <matrix-file> [label-substring]
21
21
  TLC_CACHE=<dir> where the pinned jar lives (default ~/.cache/tla)
22
22
  JAVA=<path> the java binary (default: java on PATH)
23
23
  TLC_WORKERS=<n> TLC worker threads (default auto)
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
26
+
27
+ Usage: tlc.py ready
28
+ Checks TLC_TIMEOUT, that Java runs, and that the JAR is the pinned release or the one TLC_JAR names, then reports
29
+ the temporary directory's free space as storage.py report does. setup.sh tla runs it.
24
30
  """
25
31
  from __future__ import annotations
26
32
 
33
+ import signal
34
+
35
+ if __name__ == "__main__":
36
+ # Python's SIGINT handler raises KeyboardInterrupt, which prints a traceback when it arrives during the imports.
37
+ # Until runner.run installs its own handlers, the default action ends the process by the signal instead.
38
+ if signal.getsignal(signal.SIGINT) is signal.default_int_handler:
39
+ signal.signal(signal.SIGINT, signal.SIG_DFL)
40
+
41
+ import hashlib
27
42
  import os
28
43
  import re
44
+ import shutil
29
45
  import subprocess
30
46
  import sys
31
47
  import tempfile
48
+ import time
32
49
  import uuid
33
- from dataclasses import dataclass
50
+ from dataclasses import dataclass, replace
34
51
  from enum import Enum
35
52
  from pathlib import Path
36
53
 
37
- HERE = Path(__file__).resolve().parent
54
+ sys.dont_write_bytecode = True
55
+ import processes
56
+ import runner
57
+ import storage
58
+ import tlc_trace
59
+
38
60
  CHECK_KINDS = ("INVARIANT", "INVARIANTS", "PROPERTY", "PROPERTIES")
39
61
  REACH = re.compile(r"([a-zA-Z_][a-zA-Z_0-9]*)\s*\|\s*(.*\S)\s*")
40
62
 
@@ -74,7 +96,7 @@ class Malformed:
74
96
  message: str
75
97
 
76
98
 
77
- def directives(lines):
99
+ def _directives(lines):
78
100
  """Yield each directive of a matrix in file order, with a Malformed in place of a line it rejects."""
79
101
  seen_spec = False
80
102
  for raw in lines:
@@ -107,39 +129,140 @@ def directives(lines):
107
129
  if not bar:
108
130
  yield Malformed(f"run '{rest}' has no | before its constants")
109
131
  elif not seen_spec:
110
- yield Malformed(f"run '{label.removesuffix(' ')}' before any spec line")
132
+ yield Malformed(f"run '{label.rstrip()}' before any spec line")
111
133
  else:
112
- yield Run(label.removesuffix(" "), constants)
134
+ yield Run(label.rstrip(), constants)
113
135
  else:
114
136
  yield Malformed(f"unknown directive: {line}")
115
137
 
116
138
 
117
- class Unavailable(Exception):
118
- pass
139
+ DEFAULT_TIMEOUT = "60m"
140
+ PROGRESS_DELAY = 15.0
141
+ PROGRESS_INTERVAL = 30.0
142
+
143
+
144
+ def _read_progress(log_path, offset, partial):
145
+ """Read newly written complete lines from tlc.log and return (new_offset, new_partial, latest_progress)."""
146
+ latest = ""
147
+ try:
148
+ with log_path.open("r", encoding="utf-8", errors="replace") as stream:
149
+ stream.seek(offset)
150
+ chunk = stream.read()
151
+ new_offset = stream.tell()
152
+ except OSError:
153
+ return offset, partial, ""
154
+ if not chunk:
155
+ return new_offset, partial, ""
156
+ text = partial + chunk
157
+ lines = text.splitlines(keepends=True)
158
+ if lines and not lines[-1].endswith(("\n", "\r")):
159
+ new_partial = lines.pop()
160
+ else:
161
+ new_partial = ""
162
+ for line in lines:
163
+ stripped = line.strip()
164
+ if "Progress(" in stripped:
165
+ latest = stripped
166
+ return new_offset, new_partial, latest
119
167
 
120
168
 
121
169
  class Tlc:
122
- """The pinned TLC, checked once; tlc-tools.sh owns the pin and the readiness checks."""
170
+ """The pinned TLC, checked once. Nothing here downloads it."""
171
+ version = "v1.7.4"
172
+ sha256 = "936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88"
173
+ release = f"https://github.com/tlaplus/tlaplus/releases/tag/{version}"
174
+
175
+ @classmethod
176
+ def cached_jar(cls):
177
+ """Return the path where the pinned JAR must be saved, under TLC_CACHE."""
178
+ return Path(os.environ.get("TLC_CACHE") or Path.home() / ".cache/tla") / f"tla2tools-{cls.version}.jar"
123
179
 
124
180
  def __init__(self):
125
- done = subprocess.run(
126
- ["bash", "-c", 'source "$1/tlc-tools.sh" && require_tlc_runtime && tlc_jar_ready && printf "%s\\n%s\\n" "$JAVA" "$TLC_JAR"',
127
- "bash", str(HERE)], capture_output=True, text=True, check=False)
128
- if done.returncode:
129
- raise Unavailable(done.stdout.rstrip("\n"))
130
- self.java, self.jar = done.stdout.splitlines()[-2:]
181
+ timeout_raw = os.environ.get("TLC_TIMEOUT", "").strip() or DEFAULT_TIMEOUT
182
+ self.limit, self.timeout_seconds = runner.parse_limit("TLC_TIMEOUT", timeout_raw, "run time limit", "sixty minutes")
183
+ self.java = os.environ.get("JAVA") or "java"
184
+ try:
185
+ # The JVM prints in the platform encoding, which need not be UTF-8.
186
+ runtime = processes.run_captured([self.java, "-version"], errors="replace").returncode
187
+ except OSError:
188
+ runtime = 127
189
+ if runtime:
190
+ raise runner.Unavailable(f"UNAVAILABLE {self.java} has no runtime; install a JDK and set JAVA to its java binary")
191
+ # A JAR the user supplies is trusted; the cached one must match the pin.
192
+ supplied = os.environ.get("TLC_JAR")
193
+ self.jar = supplied or str(self.cached_jar())
194
+ if not supplied:
195
+ self._check_pinned_jar()
196
+ elif not Path(supplied).is_file():
197
+ raise runner.Unavailable(f"UNAVAILABLE supplied TLC_JAR {supplied} does not exist")
198
+ try:
199
+ probe = processes.run_captured([self.java, "-cp", self.jar, "tlc2.TLC", "-help"], errors="replace")
200
+ status, output = probe.returncode, probe.stdout + probe.stderr
201
+ except OSError as error:
202
+ status, output = 127, str(error)
203
+ if status and "TLC - provides model checking" not in output:
204
+ raise runner.Unavailable(f"UNAVAILABLE tlc2.TLC cannot run from {self.jar}; save a working JAR from {self.release} "
205
+ f"or set TLC_JAR\n{output.rstrip()}")
131
206
  self.workers = os.environ.get("TLC_WORKERS") or "auto"
132
-
133
- def run(self, directory, module, config, reach):
134
- """Run TLC on module in directory with config; return its exit status and log."""
207
+ self._warned_disk = False
208
+
209
+ def _check_pinned_jar(self):
210
+ if not Path(self.jar).is_file():
211
+ raise runner.Unavailable(f"UNAVAILABLE {self.jar} is missing; save tla2tools.jar from {self.release} there, or set TLC_JAR")
212
+ try:
213
+ got = hashlib.sha256(Path(self.jar).read_bytes()).hexdigest()
214
+ except OSError as error:
215
+ raise runner.Unavailable(f"UNAVAILABLE cannot read {self.jar}; check its permissions") from error
216
+ if got != self.sha256:
217
+ raise runner.Unavailable(f"UNAVAILABLE {self.jar} has sha256 {got}, want {self.sha256}")
218
+
219
+ def run(self, directory, module, config, reach, workers=None, progress_label=""):
220
+ """Run TLC on module in directory with config; return (exit_status, log, timed_out)."""
221
+ if not self._warned_disk:
222
+ self._warned_disk = True
223
+ storage.warn_runtime()
135
224
  log = directory / "tlc.log"
136
225
  (directory / "MC.cfg").write_text(config, encoding="utf-8")
137
- command = [self.java, "-XX:+UseParallelGC", "-cp", self.jar, "tlc2.TLC", "-workers", "1" if reach else self.workers,
226
+ chosen_workers = workers if workers is not None else ("1" if reach else self.workers)
227
+ # TLC unpacks its standard modules into java.io.tmpdir and deletes them on exit, so concurrent runs must not share it.
228
+ java_tmp = directory / "java"
229
+ java_tmp.mkdir(exist_ok=True)
230
+ command = [self.java, "-XX:+UseParallelGC", f"-Djava.io.tmpdir={java_tmp}", "-cp", self.jar, "tlc2.TLC", "-workers", chosen_workers,
138
231
  *(["-deadlock"] if reach else []), "-cleanup", "-metadir", str(directory / "states"),
139
232
  "-config", str(directory / "MC.cfg"), str(directory / f"{module}.tla")]
233
+ start = time.monotonic()
234
+ deadline = start + self.timeout_seconds
235
+
236
+ def watch(process):
237
+ """Wait for TLC, report its progress and stop it at the deadline; return its status and whether it timed out."""
238
+ next_report = start + PROGRESS_DELAY
239
+ offset, partial, latest = 0, "", ""
240
+ while True:
241
+ now = time.monotonic()
242
+ remaining = deadline - now
243
+ if remaining <= 0:
244
+ processes.stop_process(process)
245
+ return process.returncode, True
246
+ if now >= next_report:
247
+ offset, partial, found = _read_progress(log, offset, partial)
248
+ if found:
249
+ latest = found
250
+ elapsed = int(now - start)
251
+ prefix = f"[tlc] {progress_label}: " if progress_label else "[tlc] "
252
+ body = f"{elapsed}s elapsed: {latest}" if latest else f"{elapsed}s elapsed"
253
+ sys.stderr.write(f"{prefix}{body}\n")
254
+ sys.stderr.flush()
255
+ next_report = now + PROGRESS_INTERVAL
256
+ wait_for = min(remaining, max(0.05, next_report - time.monotonic()))
257
+ try:
258
+ process.wait(timeout=wait_for)
259
+ return process.returncode, False
260
+ except subprocess.TimeoutExpired:
261
+ continue
262
+
140
263
  with log.open("w", encoding="utf-8") as stream:
141
- status = subprocess.run(command, stdout=stream, stderr=subprocess.STDOUT, check=False).returncode
142
- return status, read_raw(log)
264
+ returncode, timed_out = processes.guarded(command, watch, stdout=stream, stderr=subprocess.STDOUT)
265
+ return returncode, read_raw(log), timed_out
143
266
 
144
267
 
145
268
  class Outcome(Enum):
@@ -153,15 +276,45 @@ class Outcome(Enum):
153
276
  MALFORMED = "malformed"
154
277
 
155
278
 
279
+ @dataclass(frozen=True)
280
+ class Violation:
281
+ """A property violation as TLC's first error line names it."""
282
+ kind: str
283
+ name: str | None
284
+ initial: bool
285
+
286
+
287
+ # TLC names the property it found violated in one of these lines; a temporal violation names none.
288
+ VIOLATION = re.compile(r"Error: (?:(Invariant|Property|Action property) (.+) is violated(\.| by the initial state:)"
289
+ r"|(Temporal) properties were violated\.)")
290
+
291
+
292
+ def violation(error):
293
+ """Return the violation that TLC's error line reports, or None for any other error."""
294
+ match = VIOLATION.fullmatch(error)
295
+ if not match:
296
+ return None
297
+ return Violation(match[1] or match[4], match[2], match[3] == " by the initial state:")
298
+
299
+
156
300
  @dataclass(frozen=True)
157
301
  class Result:
158
- """One line of the runner's report and the output printed under it."""
302
+ """One line of the runner's report and the output printed under it.
303
+
304
+ detail is the text printed after the label; states and violation hold what callers count and match on.
305
+ """
159
306
  outcome: Outcome
160
307
  name: str = ""
161
308
  label: str = ""
162
309
  operator: str = ""
163
310
  detail: str = ""
164
311
  lines: tuple = ()
312
+ states: int = 0
313
+ violation: Violation | None = None
314
+ constants: str = ""
315
+ checks: tuple[str, ...] = ()
316
+ duration_s: float = 0.0
317
+ trace: tlc_trace.Trace | None = None
165
318
 
166
319
 
167
320
  @dataclass(frozen=True)
@@ -173,32 +326,161 @@ class Task:
173
326
  check_deadlock: bool = True
174
327
 
175
328
 
176
- def execution_plan(directives):
177
- """Snapshot each run's effective checks and resolve each reach to its first matching run."""
178
- spec, checks, reaches, runs = "", [], [], []
179
-
180
- def reach_tasks():
329
+ class _Section:
330
+ """A spec occurrence owns its declared checks and the runs to which each applies."""
331
+
332
+ def __init__(self, spec, directives):
333
+ self.spec = spec
334
+ self.properties = set()
335
+ self.reaches = set()
336
+ self.tasks = []
337
+ checks, reaches, runs = [], [], []
338
+ for directive in directives:
339
+ if isinstance(directive, Check):
340
+ checks.append(directive)
341
+ self.properties.update(directive.names)
342
+ elif isinstance(directive, Reach):
343
+ reaches.append(directive)
344
+ self.reaches.add(f"reach:{directive.operator}")
345
+ elif isinstance(directive, Run):
346
+ runs.append(directive)
347
+ self.tasks.append(Task(spec, directive, tuple(checks)))
348
+ else:
349
+ self.tasks.append(Result(Outcome.MALFORMED, detail=directive.message))
181
350
  for reach in reaches:
182
351
  run = next((run for run in runs if reach.match in run.label), None)
183
352
  if run is None:
184
- yield Result(Outcome.NO_RUN, Path(spec).name.removesuffix(".tla"), operator=reach.operator, detail=reach.match)
353
+ self.tasks.append(Result(Outcome.NO_RUN, Path(spec).name.removesuffix(".tla"), operator=reach.operator, detail=reach.match))
185
354
  else:
186
- yield Task(spec, run, reach=reach)
187
-
188
- for directive in directives:
189
- if isinstance(directive, Spec):
190
- yield from reach_tasks()
191
- spec, checks, reaches, runs = directive.path, [], [], []
192
- elif isinstance(directive, Check):
193
- checks.append(directive)
194
- elif isinstance(directive, Reach):
195
- reaches.append(directive)
196
- elif isinstance(directive, Run):
197
- runs.append(directive)
198
- yield Task(spec, directive, tuple(checks))
199
- else:
200
- yield Result(Outcome.MALFORMED, detail=directive.message)
201
- yield from reach_tasks()
355
+ self.tasks.append(Task(spec, run, reach=reach))
356
+
357
+
358
+ class MatrixPlan:
359
+ """Compile a matrix once for execution, specification recording or mutation selection."""
360
+
361
+ def __init__(self, path):
362
+ self.path = Path(path)
363
+ self._sections = []
364
+ spec, body = None, []
365
+ for directive in _directives(read_raw(self.path).split("\n")):
366
+ if isinstance(directive, Spec):
367
+ self._sections.append(_Section(spec, body))
368
+ spec, body = directive.path, []
369
+ else:
370
+ body.append(directive)
371
+ self._sections.append(_Section(spec, body))
372
+
373
+ def __iter__(self):
374
+ for section in self._sections:
375
+ yield from section.tasks
376
+
377
+ @property
378
+ def specs(self):
379
+ return [section.spec for section in self._sections if section.spec is not None]
380
+
381
+ def checked_tasks(self):
382
+ """A baseline needs every task to be resolved, including every reach."""
383
+ errors = ["; ".join(render(task)) for task in self if isinstance(task, Result)]
384
+ if errors:
385
+ raise ValueError(f"{self.path}: {'; '.join(errors)}")
386
+ if "" in self.specs:
387
+ raise ValueError(f"{self.path}: spec line has no path")
388
+ return iter(self)
389
+
390
+ def mutations_for(self, spec):
391
+ spec = Path(spec).resolve()
392
+ for task in self:
393
+ if isinstance(task, Result) and task.outcome is Outcome.MALFORMED:
394
+ raise ValueError(f"{self.path}: {task.detail}")
395
+ sections = [section for section in self._sections
396
+ if section.spec and (self.path.parent / section.spec).resolve() == spec]
397
+ return MutationPlan(spec, sections)
398
+
399
+
400
+ class MutationPlan:
401
+ """Run a named detector on exactly the tasks selected for a copied spec."""
402
+
403
+ def __init__(self, spec, sections):
404
+ self._spec = spec
405
+ self.properties = {name for section in sections for name in section.properties}
406
+ self.detectors = self.properties | {name for section in sections for name in section.reaches}
407
+ self._tasks = [task for section in sections for task in section.tasks]
408
+
409
+ def _select(self, detector):
410
+ for task in self._tasks:
411
+ if isinstance(task, Result):
412
+ if f"reach:{task.operator}" == detector:
413
+ yield task
414
+ elif task.reach:
415
+ if f"reach:{task.reach.operator}" == detector:
416
+ yield replace(task, spec=self._spec.name)
417
+ else:
418
+ checks = tuple(Check(f"{check.kind} {detector}", check.kind, (detector,))
419
+ for check in task.checks if detector in check.names)
420
+ if checks:
421
+ yield Task(self._spec.name, task.run, checks,
422
+ check_deadlock=not any(check.kind.startswith("PROPERT") for check in checks))
423
+
424
+ def selected(self, detector, only):
425
+ """Return the tasks that check a mutation naming detector and only; raise ValueError when none can."""
426
+ tasks = list(self._select(detector))
427
+ unresolved = [line for task in tasks if isinstance(task, Result) for line in render(task)]
428
+ if unresolved:
429
+ raise ValueError("\n".join(unresolved))
430
+ tasks = [task for task in tasks if only in task.run.label]
431
+ if not tasks:
432
+ raise ValueError(f"no run matches '{only}' for '{detector}'")
433
+ return tasks
434
+
435
+ def check_originals(self, checker, selections, work):
436
+ """Run every task that the (detector, only) selections name on the unmutated spec, each once.
437
+
438
+ Raise ValueError when a task does not pass, and before running any task when a selection has none to run.
439
+ """
440
+ chosen = [(detector, task) for detector, only in selections for task in self.selected(detector, only)]
441
+ passed = set()
442
+ for detector, task in chosen:
443
+ if task in passed:
444
+ continue
445
+ original = run_task(checker, self._spec.parent, task, work)
446
+ if original.outcome not in (Outcome.PASS, Outcome.WITNESS):
447
+ raise ValueError(f"unmutated model did not pass {detector}: " + "\n".join(render(original)))
448
+ passed.add(task)
449
+
450
+ def check(self, checker, detector, only, source, work):
451
+ """Return the first confirmed detection, None for a miss, or raise on inconclusive evidence.
452
+
453
+ The caller has passed the same detector and only to check_originals.
454
+ """
455
+ results = [(run_task(checker, self._spec.parent, task, work, source),
456
+ any(check.kind.startswith("PROPERT") for check in task.checks))
457
+ for task in self.selected(detector, only)]
458
+ detections, errors = [], []
459
+ for result, temporal in results:
460
+ if result.outcome is Outcome.UNREACHED:
461
+ detections.append((result.label, "the model never reaches this state"))
462
+ elif result.outcome is Outcome.FAIL and result.violation and detects(result.violation, detector, temporal):
463
+ detections.append((result.label, result.detail.removeprefix("Error: ").rstrip(".")))
464
+ elif result.outcome not in (Outcome.PASS, Outcome.WITNESS):
465
+ errors.extend(render(result))
466
+ if errors:
467
+ raise ValueError("\n".join(errors))
468
+ if detections:
469
+ label, reason = detections[0]
470
+ return f"{detector} fails in run '{label}' ({reason})"
471
+ return None
472
+
473
+
474
+ def detects(found, detector, temporal):
475
+ """Return whether TLC's violation shows the detector failing, in the forms TLC reports for each kind."""
476
+ if found.kind == "Temporal":
477
+ return True
478
+ if found.kind == "Invariant":
479
+ # TLC checks a property such as []P as the invariant P and names P. The config holds only the detector.
480
+ return found.name == detector or temporal
481
+ if found.kind == "Property":
482
+ return found.name == detector and found.initial
483
+ return found.name == detector and not found.initial
202
484
 
203
485
 
204
486
  def render(result):
@@ -217,24 +499,111 @@ def render(result):
217
499
  return [head, *result.lines]
218
500
 
219
501
 
220
- def reduced_trace(log_path, log):
221
- done = subprocess.run([sys.executable, str(HERE / "tlc-trace.py"), str(log_path)], capture_output=True, text=True, check=False)
222
- sys.stderr.write(done.stderr)
223
- lines = done.stdout.removesuffix("\n").split("\n") if done.stdout else []
224
- if done.returncode:
225
- lines += [line for line in log.split("\n") if line.strip()][-40:]
226
- return lines
502
+ def reduced_trace(log):
503
+ """Return the error trace reduced to what each step changed, or the end of the log when it holds no trace."""
504
+ lines = tlc_trace.reduce(re.split(r"\r\n|\r|\n", log))
505
+ return lines if lines is not None else [line for line in log.split("\n") if line.strip()][-40:]
506
+
507
+
508
+ def run_task(checker, matrix_dir, task, work, source=None, traces=False):
509
+ """Execute a resolved matrix task, optionally replacing its spec in the private run directory.
510
+
511
+ With traces, a FAIL or WITNESS result holds the parsed trace for the HTML report.
512
+ """
513
+ spec, run = task.spec, task.run
514
+ operator = task.reach.operator if task.reach else ""
515
+ name = Path(spec).name.removesuffix(".tla")
516
+ run_constants = run.constants.strip()
517
+ run_checks = tuple(check.line for check in task.checks)
518
+ if not (matrix_dir / spec).is_file():
519
+ return Result(Outcome.MISSING, name, run.label, detail=spec, constants=run_constants, checks=run_checks)
520
+ directory = Path(tempfile.mkdtemp(prefix="run.", dir=work))
521
+ try:
522
+ for module in (matrix_dir / spec).parent.glob("*.tla"):
523
+ dest = directory / module.name
524
+ if source is not None and module.name == Path(spec).name:
525
+ dest.write_text(source, encoding="utf-8")
526
+ else:
527
+ dest.write_bytes(module.read_bytes())
528
+ constants = "".join(f" {pair.split('=')[0]} = {pair.split('=', 1)[-1]}\n" for pair in run.constants.split())
529
+ config = f"CONSTANTS\n{constants}SPECIFICATION Spec\n"
530
+ if not task.check_deadlock:
531
+ config += "CHECK_DEADLOCK FALSE\n"
532
+ if not operator:
533
+ start = time.monotonic()
534
+ status, log, timed_out = checker.run(
535
+ directory, name, config + "\n".join(check.line for check in task.checks) + "\n",
536
+ reach=False, progress_label=f"{name} {run.label}",
537
+ )
538
+ elapsed = time.monotonic() - start
539
+ shutil.rmtree(directory / "states", ignore_errors=True)
540
+ result = ordinary(name, run, status, log, checker.limit if timed_out else None, traces)
541
+ return replace(result, constants=run_constants, checks=run_checks, duration_s=elapsed)
542
+ wrapper = f"Reach{uuid.uuid4().hex}"
543
+ invariant = f"{wrapper}Negated"
544
+ (directory / f"{wrapper}.tla").write_text(f"---- MODULE {wrapper} ----\nEXTENDS {name}\n{invariant} == ~{operator}\n====\n", encoding="utf-8")
545
+ # Exhaustive UNREACHED checks in reach: mutations do not depend on shortest-trace determinism.
546
+ reach_workers = checker.workers if source is not None else "1"
547
+ start = time.monotonic()
548
+ status, log, timed_out = checker.run(
549
+ directory, wrapper, config + f"INVARIANT {invariant}\n",
550
+ reach=True, workers=reach_workers, progress_label=f"{name} reach {operator} {run.label}",
551
+ )
552
+ elapsed = time.monotonic() - start
553
+ result = witness(name, run, operator, invariant, status, log, checker.limit if timed_out else None, traces)
554
+ return replace(result, constants=run_constants, checks=run_checks, duration_s=elapsed)
555
+ finally:
556
+ shutil.rmtree(directory, ignore_errors=True)
557
+
558
+
559
+
560
+ def ordinary(name, run, status, log, timeout_limit=None, traces=False):
561
+ if timeout_limit:
562
+ tail = tuple(line for line in log.split("\n") if line.strip())[-10:]
563
+ return Result(Outcome.FAIL, name, run.label,
564
+ detail=f"TLC timed out after {timeout_limit}; set TLC_TIMEOUT to change the limit", lines=tail)
565
+ if status == 0 and "No error has been found" in log:
566
+ found = re.findall(r"[0-9,]* distinct states found", log)
567
+ states = found[-1] if found else ""
568
+ return Result(Outcome.PASS, name, run.label, detail=states, states=int(states.partition(" ")[0].replace(",", "") or 0))
569
+ errors = [line for line in log.split("\n") if line.startswith("Error:")]
570
+ first = errors[0] if errors else ""
571
+ return Result(Outcome.FAIL, name, run.label, detail=first, lines=(*errors[1:5], *reduced_trace(log)),
572
+ violation=violation(first), trace=tlc_trace.parse(re.split(r"\r\n|\r|\n", log)) if traces else None)
573
+
574
+
575
+ def witness(name, run, operator, invariant, status, log, timeout_limit=None, traces=False):
576
+ if timeout_limit:
577
+ tail = tuple(line for line in log.split("\n") if line.strip())[-10:]
578
+ return Result(Outcome.INCOMPLETE, name, run.label, operator,
579
+ lines=(f"TLC timed out after {timeout_limit}; set TLC_TIMEOUT to change the limit", *tail))
580
+ lines = log.split("\n")
581
+ length = 0
582
+ if status == 12 and f"Error: Invariant {invariant} is violated by the initial state:" in lines:
583
+ length = 1
584
+ elif status == 12 and f"Error: Invariant {invariant} is violated." in lines:
585
+ length = sum(1 for line in lines if re.match(r"State [0-9]+:", line))
586
+ if length:
587
+ return Result(Outcome.WITNESS, name, run.label, operator, f"{length} states ({length - 1} transitions)",
588
+ trace=tlc_trace.parse(re.split(r"\r\n|\r|\n", log)) if traces else None)
589
+ if status == 0 and "No error has been found" in log:
590
+ return Result(Outcome.UNREACHED, name, run.label, operator)
591
+ return Result(Outcome.INCOMPLETE, name, run.label, operator, lines=tuple(log.removesuffix("\n").split("\n")) if log else ())
227
592
 
228
593
 
229
594
  class Runner:
230
- """Runs a matrix's directives in order, as tlc-matrix.sh reads them, and reports each result to emit."""
595
+ """Run the selected tasks and report each result to emit."""
231
596
 
232
- def __init__(self, tlc, matrix_dir, only, emit, work):
597
+ def __init__(self, tlc, matrix_dir, only, emit, work, keep_results=False):
233
598
  self.tlc, self.matrix_dir, self.only, self.emit, self.work = tlc, matrix_dir, only, emit, work
234
599
  self.runs_total = self.passed = self.states = self.reach_total = self.reached = 0
235
600
  self.failed = False
601
+ # Only the HTML report reads the results and their traces.
602
+ self.results = [] if keep_results else None
236
603
 
237
604
  def report(self, result):
605
+ if self.results is not None:
606
+ self.results.append(result)
238
607
  self.failed |= result.outcome not in (Outcome.PASS, Outcome.WITNESS)
239
608
  self.emit(result)
240
609
 
@@ -243,63 +612,70 @@ class Runner:
243
612
  self.reach_total += task.outcome is Outcome.NO_RUN
244
613
  self.report(task)
245
614
  return
246
- spec, run = task.spec, task.run
247
- operator = task.reach.operator if task.reach else ""
248
- if self.only not in run.label:
615
+ if self.only not in task.run.label:
249
616
  return
250
- if operator:
617
+ if task.reach:
251
618
  self.reach_total += 1
252
619
  else:
253
620
  self.runs_total += 1
254
- name = Path(spec).name.removesuffix(".tla")
255
- if not (self.matrix_dir / spec).is_file():
256
- self.report(Result(Outcome.MISSING, name, run.label, detail=spec))
257
- return
258
- directory = Path(tempfile.mkdtemp(prefix="run.", dir=self.work))
259
- for module in (self.matrix_dir / spec).parent.glob("*.tla"):
260
- (directory / module.name).write_bytes(module.read_bytes())
261
- constants = "".join(f" {pair.split('=')[0]} = {pair.split('=', 1)[-1]}\n" for pair in run.constants.split())
262
- config = f"CONSTANTS\n{constants}SPECIFICATION Spec\n"
263
- if not task.check_deadlock:
264
- config += "CHECK_DEADLOCK FALSE\n"
265
- if not operator:
266
- status, log = self.tlc.run(directory, name, config + "\n".join(check.line for check in task.checks) + "\n", reach=False)
267
- self.report(self.ordinary(name, run, status, log, directory / "tlc.log"))
268
- return
269
- wrapper = f"Reach{uuid.uuid4().hex}"
270
- invariant = f"{wrapper}Negated"
271
- (directory / f"{wrapper}.tla").write_text(f"---- MODULE {wrapper} ----\nEXTENDS {name}\n{invariant} == ~{operator}\n====\n", encoding="utf-8")
272
- status, log = self.tlc.run(directory, wrapper, config + f"INVARIANT {invariant}\n", reach=True)
273
- self.report(self.witness(name, run, operator, invariant, status, log))
274
-
275
- def ordinary(self, name, run, status, log, log_path):
276
- if status == 0 and "No error has been found" in log:
277
- found = re.findall(r"[0-9,]* distinct states found", log)
278
- states = found[-1] if found else ""
621
+ result = run_task(self.tlc, self.matrix_dir, task, self.work, traces=self.results is not None)
622
+ if result.outcome is Outcome.PASS:
279
623
  self.passed += 1
280
- count = states.partition(" ")[0].replace(",", "")
281
- self.states += int(count or 0)
282
- return Result(Outcome.PASS, name, run.label, detail=states)
283
- errors = [line for line in log.split("\n") if line.startswith("Error:")]
284
- return Result(Outcome.FAIL, name, run.label, detail=errors[0] if errors else "",
285
- lines=(*errors[1:5], *reduced_trace(log_path, log)))
286
-
287
- def witness(self, name, run, operator, invariant, status, log):
288
- lines = log.split("\n")
289
- length = 0
290
- if status == 12 and f"Error: Invariant {invariant} is violated by the initial state:" in lines:
291
- length = 1
292
- elif status == 12 and f"Error: Invariant {invariant} is violated." in lines:
293
- length = sum(1 for line in lines if re.match(r"State [0-9]+:", line))
294
- if length:
624
+ self.states += result.states
625
+ elif result.outcome is Outcome.WITNESS:
295
626
  self.reached += 1
296
- return Result(Outcome.WITNESS, name, run.label, operator, f"{length} states ({length - 1} transitions)")
297
- if status == 0 and "No error has been found" in log:
298
- return Result(Outcome.UNREACHED, name, run.label, operator)
299
- return Result(Outcome.INCOMPLETE, name, run.label, operator, lines=tuple(log.removesuffix("\n").split("\n")) if log else ())
627
+ self.report(result)
628
+
629
+
630
+ REPORT_REMEDY = "set it to a file in an existing directory that you can write to, or unset it to write no report"
631
+
632
+
633
+ def validate_report_path(raw: str) -> Path | None:
634
+ """Return the TLC_HTML_REPORT path, checked before TLC starts, or None when it is unset.
635
+
636
+ Raise runner.Unavailable naming the setting when the report cannot be written there.
637
+ """
638
+ trimmed = raw.strip()
639
+ if not trimmed:
640
+ return None
641
+
642
+ def unavailable(problem):
643
+ return runner.Unavailable(f"UNAVAILABLE TLC_HTML_REPORT={trimmed!r} {problem}; {REPORT_REMEDY}")
644
+
645
+ seps = tuple(dict.fromkeys(s for s in ("/", os.sep, os.altsep) if s))
646
+ dot_suffixes = tuple(f"{sep}." for sep in seps) + tuple(f"{sep}.." for sep in seps)
647
+ if trimmed in (".", "..") or trimmed.endswith(seps + dot_suffixes):
648
+ raise unavailable("is a directory")
649
+ path = Path(trimmed)
650
+ try:
651
+ is_dir = path.is_dir()
652
+ parent_is_dir = path.parent.is_dir()
653
+ exists = path.exists()
654
+ is_file = path.is_file() if exists else False
655
+ except OSError as error:
656
+ raise unavailable(f"is not accessible: {error}") from error
657
+ if is_dir:
658
+ raise unavailable("is a directory")
659
+ if not parent_is_dir:
660
+ raise unavailable("is not in an existing directory")
661
+ if exists and not is_file:
662
+ raise unavailable("is not a regular file")
663
+ try:
664
+ fd, temp_path = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.")
665
+ except OSError as error:
666
+ raise unavailable(f"is not writable: {error}") from error
667
+ try:
668
+ os.close(fd)
669
+ finally:
670
+ Path(temp_path).unlink(missing_ok=True)
671
+ return path
300
672
 
301
673
 
302
674
  def main():
675
+ if sys.argv[1:] == ["ready"]:
676
+ print(f"READY TLC {Tlc().jar}")
677
+ storage.report()
678
+ return 0
303
679
  if not 2 <= len(sys.argv) <= 3:
304
680
  print("usage: tlc-matrix.sh <matrix-file> [label-substring]")
305
681
  return 2
@@ -307,25 +683,33 @@ def main():
307
683
  if not Path(matrix).is_file():
308
684
  print(f"FAIL {matrix} does not exist")
309
685
  return 1
310
- try:
311
- tlc = Tlc()
312
- except Unavailable as error:
313
- print(error)
314
- return 3
315
- with tempfile.TemporaryDirectory() as work:
316
- runner = Runner(tlc, Path(matrix).resolve().parent, only, lambda result: print("\n".join(render(result)), flush=True), Path(work))
317
- for task in execution_plan(directives(read_raw(matrix).split("\n"))):
318
- runner.check(task)
319
- if runner.runs_total == 0:
686
+ tlc = Tlc()
687
+ report_path = validate_report_path(os.environ.get("TLC_HTML_REPORT", ""))
688
+ with tempfile.TemporaryDirectory(dir=storage.ensure_temp_root()) as work:
689
+ matrix_runner = Runner(tlc, Path(matrix).resolve().parent, only, lambda result: print("\n".join(render(result)), flush=True), Path(work),
690
+ keep_results=report_path is not None)
691
+ for task in MatrixPlan(matrix):
692
+ matrix_runner.check(task)
693
+ if matrix_runner.runs_total == 0:
320
694
  matching = f"matching '{only}' " if only else ""
321
695
  print(f"FAIL no run {matching}in {matrix}")
322
696
  return 1
323
- summary = f"SUMMARY {runner.passed} of {runner.runs_total} runs passed"
324
- if runner.reach_total:
325
- summary += f", {runner.reached} of {runner.reach_total} reach checks passed"
326
- print(f"{summary}, {runner.states} distinct states in total")
327
- return int(runner.failed)
697
+ summary = f"SUMMARY {matrix_runner.passed} of {matrix_runner.runs_total} runs passed"
698
+ if matrix_runner.reach_total:
699
+ summary += f", {matrix_runner.reached} of {matrix_runner.reach_total} reach checks passed"
700
+ summary_line = f"{summary}, {matrix_runner.states} distinct states in total"
701
+ print(summary_line)
702
+ if report_path is not None:
703
+ import tlc_report
704
+
705
+ try:
706
+ tlc_report.write_html(report_path, Path(matrix).name, matrix_runner.results, summary_line, only=only)
707
+ except OSError as error:
708
+ # A failed run's status wins over a report that could not be written.
709
+ print(f"UNAVAILABLE TLC_HTML_REPORT={str(report_path)!r} could not be written: {error}; {REPORT_REMEDY}")
710
+ return 1 if matrix_runner.failed else 3
711
+ return int(matrix_runner.failed)
328
712
 
329
713
 
330
714
  if __name__ == "__main__":
331
- sys.exit(main())
715
+ runner.run(main)