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