agent-formal-verify 0.4.19 → 0.4.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGES.md +38 -0
- package/package.json +1 -1
- package/skills/formal-verify/SKILL.md +6 -6
- package/skills/formal-verify/references/evidence.md +1 -1
- package/skills/formal-verify/references/helpers.md +3 -16
- package/skills/formal-verify/references/lean-brief.md +1 -1
- package/skills/formal-verify/references/lean-helpers.md +5 -0
- package/skills/formal-verify/references/rust-brief.md +16 -22
- package/skills/formal-verify/references/rust-helpers.md +18 -0
- package/skills/formal-verify/references/setup.md +5 -3
- package/skills/formal-verify/references/tla-brief.md +2 -1
- package/skills/formal-verify/references/tla-helpers.md +12 -0
- package/skills/formal-verify/scripts/baseline.py +73 -19
- package/skills/formal-verify/scripts/kani_reader.py +33 -3
- package/skills/formal-verify/scripts/lean.py +124 -2
- package/skills/formal-verify/scripts/lean_mutations.py +2 -5
- package/skills/formal-verify/scripts/mutate.py +50 -19
- package/skills/formal-verify/scripts/processes.py +16 -4
- package/skills/formal-verify/scripts/tlc.py +206 -42
- package/skills/formal-verify/scripts/tlc_report.py +2 -2
|
@@ -5,16 +5,29 @@
|
|
|
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). The line of a
|
|
9
|
+
run or reach check under a symmetry line says "under symmetry <Operator>": after
|
|
10
|
+
the state count when a run passes, and before the colon otherwise.
|
|
9
11
|
|
|
10
12
|
Matrix file, one directive per line (# starts a comment):
|
|
11
13
|
spec <path.tla> the spec for the runs below, relative to the file;
|
|
12
14
|
TLC checks the formula it names Spec
|
|
13
15
|
check <cfg line> an INVARIANTS or PROPERTIES line, kept until the next spec
|
|
14
16
|
reach <Operator> | <label-substring> a witness in the first matching run
|
|
17
|
+
symmetry <Operator> at most one per spec section: adds SYMMETRY <Operator> to the
|
|
18
|
+
cfg of each run and reach check of the section, wherever the
|
|
19
|
+
line stands in it; refused, with no symmetry applied, in a
|
|
20
|
+
section that checks a PROPERTY or PROPERTIES
|
|
15
21
|
run <label> | <Name=Value ...> one TLC run with those CONSTANTS
|
|
16
22
|
|
|
17
23
|
A malformed directive prints a FAIL line and the runner goes on to the next.
|
|
24
|
+
A line that could change the cfg beyond itself stops the runner before any run
|
|
25
|
+
with a FAIL <matrix>:<line>: line for each and status 2: a check name, reach or
|
|
26
|
+
symmetry operator or constant name that is not a TLA+ identifier or is a TLA+
|
|
27
|
+
reserved word; a check name, symmetry operator or constant name that is a cfg
|
|
28
|
+
keyword; and a constant value that holds a comment opener, a string that it does
|
|
29
|
+
not close, or a cfg keyword outside a string that is not the whole value or a
|
|
30
|
+
whole set element.
|
|
18
31
|
|
|
19
32
|
Usage: tlc-matrix.sh <matrix-file> [label-substring]
|
|
20
33
|
TLC_ENGINE=<name> TLA+ engine: tlc (default) or everystate
|
|
@@ -27,9 +40,10 @@ Usage: tlc-matrix.sh <matrix-file> [label-substring]
|
|
|
27
40
|
TLC_HTML_REPORT=<path> write a self-contained HTML report to this path
|
|
28
41
|
|
|
29
42
|
Usage: tlc.py ready
|
|
30
|
-
Checks TLC_ENGINE, TLC_TIMEOUT, and the selected engine (Java and the pinned or supplied JAR for tlc
|
|
31
|
-
|
|
32
|
-
storage.py report does.
|
|
43
|
+
Checks TLC_ENGINE, TLC_TIMEOUT, and the selected engine (Java and the pinned or supplied JAR for tlc,
|
|
44
|
+
then a one-state model that TLC can check only where it may listen on a local port; everystate 0.4.6
|
|
45
|
+
or later for everystate), then reports the temporary directory's free space as storage.py report does.
|
|
46
|
+
setup.sh tla runs it.
|
|
33
47
|
"""
|
|
34
48
|
from __future__ import annotations
|
|
35
49
|
|
|
@@ -50,7 +64,6 @@ import sys
|
|
|
50
64
|
import tempfile
|
|
51
65
|
import time
|
|
52
66
|
import uuid
|
|
53
|
-
from contextlib import suppress
|
|
54
67
|
from dataclasses import dataclass, replace
|
|
55
68
|
from enum import Enum
|
|
56
69
|
from pathlib import Path
|
|
@@ -62,7 +75,27 @@ import storage
|
|
|
62
75
|
import tlc_trace
|
|
63
76
|
|
|
64
77
|
CHECK_KINDS = ("INVARIANT", "INVARIANTS", "PROPERTY", "PROPERTIES")
|
|
65
|
-
REACH = re.compile(r"([
|
|
78
|
+
REACH = re.compile(r"([^\s|]+)\s*\|\s*(.*\S)\s*")
|
|
79
|
+
# The words that start a cfg statement: TLC's (tla2tools 1.7.4, with ALIAS and POSTCONDITION from later TLC) and everystate's.
|
|
80
|
+
CFG_KEYWORDS = frozenset({
|
|
81
|
+
"ACTION_CONSTRAINT", "ACTION_CONSTRAINTS", "ALIAS", "CHECK_DEADLOCK", "CONSTANT", "CONSTANTS", "CONSTRAINT",
|
|
82
|
+
"CONSTRAINTS", "INIT", "INVARIANT", "INVARIANTS", "NEXT", "POSTCONDITION", "POSTCONDITIONS", "PROPERTIES",
|
|
83
|
+
"PROPERTY", "SPECIFICATION", "SYMMETRY", "TYPE", "TYPE_CONSTRAINT", "VIEW", "_PERIODIC", "_POSSIBLE", "_RL_REWARD",
|
|
84
|
+
})
|
|
85
|
+
# TLA+'s reserved words. IDENTIFIER rejects the prefixes WF_ and SF_.
|
|
86
|
+
RESERVED_WORDS = frozenset({
|
|
87
|
+
"ACTION", "ASSUME", "ASSUMPTION", "AXIOM", "BY", "CASE", "CHOOSE", "CONSTANT", "CONSTANTS", "COROLLARY", "DEF",
|
|
88
|
+
"DEFINE", "DEFS", "DOMAIN", "ELSE", "ENABLED", "EXCEPT", "EXTENDS", "HAVE", "HIDE", "IF", "IN", "INSTANCE", "LAMBDA",
|
|
89
|
+
"LEMMA", "LET", "LOCAL", "MODULE", "NEW", "OBVIOUS", "OMITTED", "ONLY", "OTHER", "PICK", "PROOF", "PROPOSITION",
|
|
90
|
+
"PROVE", "QED", "RECURSIVE", "STATE", "SUBSET", "SUFFICES", "TAKE", "TEMPORAL", "THEN", "THEOREM", "UNCHANGED",
|
|
91
|
+
"UNION", "USE", "VARIABLE", "VARIABLES", "WITH", "WITNESS",
|
|
92
|
+
})
|
|
93
|
+
IDENTIFIER = re.compile(r"(?!WF_|SF_)[A-Za-z0-9_]*[A-Za-z][A-Za-z0-9_]*")
|
|
94
|
+
# A constant's value split as both engines' cfg readers split it here: a closed string, a word, or one other character.
|
|
95
|
+
VALUE_TOKEN = re.compile(r'"(?:[^"\\]|\\.)*"|[A-Za-z0-9_]+|.', re.DOTALL)
|
|
96
|
+
COMMENT_OPENERS = ("(*", "\\*")
|
|
97
|
+
# Text whose every double quote opens a string that a later quote closes, where a backslash escapes the next character.
|
|
98
|
+
CLOSED_STRINGS = re.compile(r'(?:[^"]|"(?:[^"\\]|\\.)*")*')
|
|
66
99
|
|
|
67
100
|
|
|
68
101
|
def read_raw(path):
|
|
@@ -89,6 +122,11 @@ class Reach:
|
|
|
89
122
|
match: str
|
|
90
123
|
|
|
91
124
|
|
|
125
|
+
@dataclass(frozen=True)
|
|
126
|
+
class Symmetry:
|
|
127
|
+
operator: str
|
|
128
|
+
|
|
129
|
+
|
|
92
130
|
@dataclass(frozen=True)
|
|
93
131
|
class Run:
|
|
94
132
|
label: str
|
|
@@ -104,20 +142,83 @@ class Malformed:
|
|
|
104
142
|
message: str
|
|
105
143
|
|
|
106
144
|
|
|
107
|
-
|
|
145
|
+
@dataclass(frozen=True)
|
|
146
|
+
class Rejected:
|
|
147
|
+
"""A matrix line whose name or value could change the cfg beyond itself."""
|
|
148
|
+
line: int
|
|
149
|
+
message: str
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class MatrixError(ValueError):
|
|
153
|
+
"""A matrix holds lines that could change the cfg beyond themselves; each problem names its file and line."""
|
|
154
|
+
|
|
155
|
+
def __init__(self, problems):
|
|
156
|
+
super().__init__("\n".join(problems))
|
|
157
|
+
self.problems = tuple(problems)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def operator_problem(name):
|
|
161
|
+
"""Return why a name cannot name a TLA+ operator, or None."""
|
|
162
|
+
if not IDENTIFIER.fullmatch(name):
|
|
163
|
+
return "is not a TLA+ identifier"
|
|
164
|
+
if name in RESERVED_WORDS:
|
|
165
|
+
return "is a TLA+ reserved word"
|
|
166
|
+
return None
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def name_problem(name):
|
|
170
|
+
"""Return why a name cannot go into a cfg statement, or None for a TLA+ identifier that no engine reads as a keyword."""
|
|
171
|
+
return "is a cfg keyword" if name in CFG_KEYWORDS else operator_problem(name)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def value_problem(value):
|
|
175
|
+
"""Return why a constant's value could end early and start a cfg statement or hide the ones after it, or None.
|
|
176
|
+
|
|
177
|
+
TLC 1.7.4 and everystate 0.4.6 read a closed string as one token, and a cfg keyword that is the whole value or
|
|
178
|
+
a whole set element as a model value, so a keyword counts only in any other place.
|
|
179
|
+
"""
|
|
180
|
+
tokens = ["", *VALUE_TOKEN.findall(value), ""]
|
|
181
|
+
depth = 0
|
|
182
|
+
for before, token, after in zip(tokens, tokens[1:], tokens[2:]):
|
|
183
|
+
depth += (token == "{") - (token == "}")
|
|
184
|
+
whole = before == after == ""
|
|
185
|
+
element = depth > 0 and before in ("{", ",") and after in (",", "}")
|
|
186
|
+
if token in CFG_KEYWORDS and not (whole or element):
|
|
187
|
+
return f"holds the cfg keyword {token} outside a whole value or set element"
|
|
188
|
+
opener = next((opener for opener in COMMENT_OPENERS if opener in value), None)
|
|
189
|
+
if opener:
|
|
190
|
+
return f"holds the comment opener {opener}"
|
|
191
|
+
if not CLOSED_STRINGS.fullmatch(value):
|
|
192
|
+
return "opens a string that it does not close"
|
|
193
|
+
return None
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _binding_problem(label, name, value):
|
|
197
|
+
problem = name_problem(name)
|
|
198
|
+
if problem:
|
|
199
|
+
return f"constant name '{name}' in run '{label}' {problem}"
|
|
200
|
+
problem = value_problem(value)
|
|
201
|
+
if problem:
|
|
202
|
+
return f"constant '{name}={value}' in run '{label}' {problem}"
|
|
203
|
+
return None
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _parse_run(number, label, constants):
|
|
108
207
|
bindings = []
|
|
109
208
|
for token in constants.split():
|
|
110
209
|
name, _, value = token.partition("=")
|
|
111
210
|
if not name or not value:
|
|
112
|
-
|
|
211
|
+
yield Malformed(f"malformed constant {token!r} in run {label!r}: expected Name=Value")
|
|
212
|
+
return
|
|
113
213
|
bindings.append((name, value))
|
|
114
|
-
|
|
214
|
+
problems = [_binding_problem(label, name, value) for name, value in bindings]
|
|
215
|
+
yield from [Rejected(number, problem) for problem in problems if problem] or [Run(label, tuple(bindings))]
|
|
115
216
|
|
|
116
217
|
|
|
117
218
|
def _directives(lines):
|
|
118
|
-
"""Yield each directive of a matrix in file order, with a Malformed in place of a line it rejects."""
|
|
219
|
+
"""Yield each directive of a matrix in file order, with a Malformed or Rejected in place of a line it rejects."""
|
|
119
220
|
seen_spec = False
|
|
120
|
-
for raw in lines:
|
|
221
|
+
for number, raw in enumerate(lines, 1):
|
|
121
222
|
line = raw.split("#", 1)[0]
|
|
122
223
|
if not line.strip():
|
|
123
224
|
continue
|
|
@@ -133,7 +234,9 @@ def _directives(lines):
|
|
|
133
234
|
elif kind not in CHECK_KINDS or not names.strip():
|
|
134
235
|
yield Malformed(f"malformed check '{rest}'")
|
|
135
236
|
else:
|
|
136
|
-
|
|
237
|
+
problems = [(name, name_problem(name)) for name in names.split()]
|
|
238
|
+
yield from ([Rejected(number, f"check name '{name}' {problem}") for name, problem in problems if problem]
|
|
239
|
+
or [Check(rest, kind, tuple(names.split()))])
|
|
137
240
|
elif keyword == "reach":
|
|
138
241
|
match = REACH.fullmatch(rest)
|
|
139
242
|
if not seen_spec:
|
|
@@ -141,7 +244,17 @@ def _directives(lines):
|
|
|
141
244
|
elif not match:
|
|
142
245
|
yield Malformed(f"malformed reach '{rest}': expected reach <Operator> | <label-substring>")
|
|
143
246
|
else:
|
|
144
|
-
|
|
247
|
+
# The reach check names its operator in a wrapper module, not in the cfg.
|
|
248
|
+
problem = operator_problem(match[1])
|
|
249
|
+
yield Rejected(number, f"reach operator '{match[1]}' {problem}") if problem else Reach(match[1], match[2])
|
|
250
|
+
elif keyword == "symmetry":
|
|
251
|
+
if not seen_spec:
|
|
252
|
+
yield Malformed(f"symmetry '{rest}' before any spec line")
|
|
253
|
+
elif not rest:
|
|
254
|
+
yield Malformed("malformed symmetry '': expected symmetry <Operator>")
|
|
255
|
+
else:
|
|
256
|
+
problem = name_problem(rest)
|
|
257
|
+
yield Rejected(number, f"symmetry operator '{rest}' {problem}") if problem else Symmetry(rest)
|
|
145
258
|
elif keyword == "run":
|
|
146
259
|
label, bar, constants = rest.partition("|")
|
|
147
260
|
if not bar:
|
|
@@ -149,7 +262,7 @@ def _directives(lines):
|
|
|
149
262
|
elif not seen_spec:
|
|
150
263
|
yield Malformed(f"run '{label.rstrip()}' before any spec line")
|
|
151
264
|
else:
|
|
152
|
-
yield _parse_run(label.rstrip(), constants)
|
|
265
|
+
yield from _parse_run(number, label.rstrip(), constants)
|
|
153
266
|
else:
|
|
154
267
|
yield Malformed(f"unknown directive: {line}")
|
|
155
268
|
|
|
@@ -201,6 +314,9 @@ class _Engine:
|
|
|
201
314
|
self.workers = os.environ.get("TLC_WORKERS") or "auto"
|
|
202
315
|
self._warned_disk = False
|
|
203
316
|
|
|
317
|
+
def preflight(self):
|
|
318
|
+
"""Check, before setup reports the engine ready, what its version probe cannot show; nothing by default."""
|
|
319
|
+
|
|
204
320
|
def _run_watched(self, command, log, progress_label=""):
|
|
205
321
|
if not self._warned_disk:
|
|
206
322
|
self._warned_disk = True
|
|
@@ -225,12 +341,7 @@ class _Engine:
|
|
|
225
341
|
elapsed = int(now - start)
|
|
226
342
|
prefix = f"[{self.log_tag}] {progress_label}: " if progress_label else f"[{self.log_tag}] "
|
|
227
343
|
body = f"{elapsed}s elapsed: {latest}" if latest else f"{elapsed}s elapsed"
|
|
228
|
-
|
|
229
|
-
# A closed or unwritable stderr must not fail a run whose checker passed.
|
|
230
|
-
if sys.stderr is not None:
|
|
231
|
-
with suppress(OSError):
|
|
232
|
-
sys.stderr.write(f"{prefix}{body}\n")
|
|
233
|
-
sys.stderr.flush()
|
|
344
|
+
processes.report_progress(f"{prefix}{body}")
|
|
234
345
|
next_report = now + PROGRESS_INTERVAL
|
|
235
346
|
wait_for = min(remaining, max(0.05, next_report - time.monotonic()))
|
|
236
347
|
try:
|
|
@@ -302,6 +413,16 @@ class Tlc(_Engine):
|
|
|
302
413
|
if got != self.sha256:
|
|
303
414
|
raise runner.Unavailable(f"UNAVAILABLE {self.jar} has sha256 {got}, want {self.sha256}")
|
|
304
415
|
|
|
416
|
+
def preflight(self):
|
|
417
|
+
"""Check a one-state model, so that a sandbox that denies TLC its local port stops setup instead of the first model run."""
|
|
418
|
+
with tempfile.TemporaryDirectory(dir=storage.ensure_temp_root()) as work:
|
|
419
|
+
directory = Path(work)
|
|
420
|
+
(directory / "Preflight.tla").write_text("---- MODULE Preflight ----\nVARIABLE x\nInit == x = 0\nNext == UNCHANGED x\n====\n", encoding="utf-8")
|
|
421
|
+
# run raises Unavailable when TLC cannot listen; any other outcome is left for the model runs to report.
|
|
422
|
+
# Setup reports free space after this, so the run's own low-space warning would repeat it.
|
|
423
|
+
self._warned_disk = True
|
|
424
|
+
self.run(directory, "Preflight", "INIT Init\nNEXT Next\n", reach=False, workers="1")
|
|
425
|
+
|
|
305
426
|
def run(self, directory, module, config, reach, workers=None, progress_label=""):
|
|
306
427
|
"""Run TLC on module in directory with config; return (exit_status, log, timed_out)."""
|
|
307
428
|
log = directory / "tlc.log"
|
|
@@ -313,7 +434,13 @@ class Tlc(_Engine):
|
|
|
313
434
|
command = [self.java, "-XX:+UseParallelGC", f"-Djava.io.tmpdir={java_tmp}", "-cp", self.jar, "tlc2.TLC", "-workers", chosen_workers,
|
|
314
435
|
*(["-deadlock"] if reach else []), "-cleanup", "-metadir", str(directory / "states"),
|
|
315
436
|
"-config", str(directory / "MC.cfg"), str(directory / f"{module}.tla")]
|
|
316
|
-
|
|
437
|
+
status, output, timed_out = self._run_watched(command, log, progress_label)
|
|
438
|
+
# TLC's fingerprint set is an RMI object, so every run exports it on a local port, even on one machine.
|
|
439
|
+
if "java.rmi.server.ExportException: Listen failed on port" in output:
|
|
440
|
+
raise runner.Unavailable("UNAVAILABLE TLC could not listen on a local port (java.rmi.server.ExportException), which it needs even on one machine; "
|
|
441
|
+
"run the check where processes may listen on localhost, such as outside a sandbox that denies network binding, "
|
|
442
|
+
"or with TLC_ENGINE=everystate, which opens no port")
|
|
443
|
+
return status, output, timed_out
|
|
317
444
|
|
|
318
445
|
|
|
319
446
|
class Everystate(_Engine):
|
|
@@ -417,6 +544,7 @@ class Result:
|
|
|
417
544
|
"""One line of the runner's report and the output printed under it.
|
|
418
545
|
|
|
419
546
|
detail is the text printed after the label; states and violation hold what callers count and match on.
|
|
547
|
+
symmetry is the operator of the section's symmetry line that the run used, or "".
|
|
420
548
|
"""
|
|
421
549
|
outcome: Outcome
|
|
422
550
|
name: str = ""
|
|
@@ -430,6 +558,12 @@ class Result:
|
|
|
430
558
|
checks: tuple[str, ...] = ()
|
|
431
559
|
duration_s: float = 0.0
|
|
432
560
|
trace: tlc_trace.Trace | None = None
|
|
561
|
+
symmetry: str = ""
|
|
562
|
+
|
|
563
|
+
@property
|
|
564
|
+
def under_symmetry(self):
|
|
565
|
+
"""Return the words that name the run's symmetry in its lines, or "" for a run without one."""
|
|
566
|
+
return f" under symmetry {self.symmetry}" if self.symmetry else ""
|
|
433
567
|
|
|
434
568
|
|
|
435
569
|
@dataclass(frozen=True)
|
|
@@ -439,6 +573,7 @@ class Task:
|
|
|
439
573
|
checks: tuple = ()
|
|
440
574
|
reach: Reach | None = None
|
|
441
575
|
check_deadlock: bool = True
|
|
576
|
+
symmetry: str = ""
|
|
442
577
|
|
|
443
578
|
|
|
444
579
|
class _Section:
|
|
@@ -449,7 +584,7 @@ class _Section:
|
|
|
449
584
|
self.properties = set()
|
|
450
585
|
self.reaches = set()
|
|
451
586
|
self.tasks = []
|
|
452
|
-
checks, reaches, runs = [], [], []
|
|
587
|
+
checks, reaches, runs, symmetries = [], [], [], []
|
|
453
588
|
for directive in directives:
|
|
454
589
|
if isinstance(directive, Check):
|
|
455
590
|
checks.append(directive)
|
|
@@ -457,6 +592,8 @@ class _Section:
|
|
|
457
592
|
elif isinstance(directive, Reach):
|
|
458
593
|
reaches.append(directive)
|
|
459
594
|
self.reaches.add(f"reach:{directive.operator}")
|
|
595
|
+
elif isinstance(directive, Symmetry):
|
|
596
|
+
symmetries.append(directive.operator)
|
|
460
597
|
elif isinstance(directive, Run):
|
|
461
598
|
runs.append(directive)
|
|
462
599
|
self.tasks.append(Task(spec, directive, tuple(checks)))
|
|
@@ -468,21 +605,38 @@ class _Section:
|
|
|
468
605
|
self.tasks.append(Result(Outcome.NO_RUN, Path(spec).name.removesuffix(".tla"), operator=reach.operator, detail=reach.match))
|
|
469
606
|
else:
|
|
470
607
|
self.tasks.append(Task(spec, run, reach=reach))
|
|
608
|
+
if not symmetries:
|
|
609
|
+
return
|
|
610
|
+
liveness = [check.line for check in checks if check.kind.startswith("PROPERT")]
|
|
611
|
+
if len(symmetries) > 1:
|
|
612
|
+
refusal = f"symmetry lines {', '.join(symmetries)} in one {spec} section, which runs without symmetry; give it one symmetry line"
|
|
613
|
+
elif liveness:
|
|
614
|
+
refusal = (f"symmetry {symmetries[0]} in the {spec} section, which checks {'; '.join(liveness)}: TLC can miss "
|
|
615
|
+
"a liveness violation under symmetry, so the section runs without it; check the properties in a section without symmetry")
|
|
616
|
+
else:
|
|
617
|
+
self.tasks = [replace(task, symmetry=symmetries[0]) if isinstance(task, Task) else task for task in self.tasks]
|
|
618
|
+
return
|
|
619
|
+
self.tasks.insert(0, Result(Outcome.MALFORMED, detail=refusal))
|
|
471
620
|
|
|
472
621
|
|
|
473
622
|
class MatrixPlan:
|
|
474
623
|
"""Compile a matrix once for execution, specification recording or mutation selection."""
|
|
475
624
|
|
|
476
625
|
def __init__(self, path):
|
|
626
|
+
"""Read the matrix at path; raise MatrixError naming each line it rejects, after reading every line."""
|
|
477
627
|
self.path = Path(path)
|
|
478
628
|
self._sections = []
|
|
479
|
-
spec, body = None, []
|
|
629
|
+
spec, body, rejected = None, [], []
|
|
480
630
|
for directive in _directives(read_raw(self.path).split("\n")):
|
|
481
|
-
if isinstance(directive,
|
|
631
|
+
if isinstance(directive, Rejected):
|
|
632
|
+
rejected.append(f"{self.path}:{directive.line}: {directive.message}")
|
|
633
|
+
elif isinstance(directive, Spec):
|
|
482
634
|
self._sections.append(_Section(spec, body))
|
|
483
635
|
spec, body = directive.path, []
|
|
484
636
|
else:
|
|
485
637
|
body.append(directive)
|
|
638
|
+
if rejected:
|
|
639
|
+
raise MatrixError(rejected)
|
|
486
640
|
self._sections.append(_Section(spec, body))
|
|
487
641
|
|
|
488
642
|
def __iter__(self):
|
|
@@ -533,8 +687,8 @@ class MutationPlan:
|
|
|
533
687
|
checks = tuple(Check(f"{check.kind} {detector}", check.kind, (detector,))
|
|
534
688
|
for check in task.checks if detector in check.names)
|
|
535
689
|
if checks:
|
|
536
|
-
yield
|
|
537
|
-
|
|
690
|
+
yield replace(task, spec=self._spec.name, checks=checks,
|
|
691
|
+
check_deadlock=not any(check.kind.startswith("PROPERT") for check in checks))
|
|
538
692
|
|
|
539
693
|
def selected(self, detector, only):
|
|
540
694
|
"""Return the tasks that check a mutation naming detector and only; raise ValueError when none can."""
|
|
@@ -563,8 +717,9 @@ class MutationPlan:
|
|
|
563
717
|
passed.add(task)
|
|
564
718
|
|
|
565
719
|
def check(self, checker, detector, only, source, work):
|
|
566
|
-
"""Return
|
|
720
|
+
"""Return whether a run confirms a detection, with the text for the verdict's line, or raise on inconclusive evidence.
|
|
567
721
|
|
|
722
|
+
A detection names the first run that fails; a miss names each run that passed under symmetry, or nothing.
|
|
568
723
|
The caller has passed the same detector and only to check_originals.
|
|
569
724
|
"""
|
|
570
725
|
results = [(run_task(checker, self._spec.parent, task, work, source),
|
|
@@ -573,17 +728,17 @@ class MutationPlan:
|
|
|
573
728
|
detections, errors = [], []
|
|
574
729
|
for result, temporal in results:
|
|
575
730
|
if result.outcome is Outcome.UNREACHED:
|
|
576
|
-
detections.append((result
|
|
731
|
+
detections.append((result, "the model never reaches this state"))
|
|
577
732
|
elif result.outcome is Outcome.FAIL and result.violation and detects(result.violation, detector, temporal):
|
|
578
|
-
detections.append((result
|
|
733
|
+
detections.append((result, result.detail.removeprefix("Error: ").rstrip(".")))
|
|
579
734
|
elif result.outcome not in (Outcome.PASS, Outcome.WITNESS):
|
|
580
735
|
errors.extend(render(result))
|
|
581
736
|
if errors:
|
|
582
737
|
raise ValueError("\n".join(errors))
|
|
583
738
|
if detections:
|
|
584
|
-
|
|
585
|
-
return f"{detector} fails in run '{label}' ({reason})"
|
|
586
|
-
return
|
|
739
|
+
result, reason = detections[0]
|
|
740
|
+
return True, f"{detector} fails in run '{result.label}'{result.under_symmetry} ({reason})"
|
|
741
|
+
return False, "; ".join(f"run '{result.label}' passes{result.under_symmetry}" for result, _ in results if result.symmetry)
|
|
587
742
|
|
|
588
743
|
|
|
589
744
|
def detects(found, detector, temporal):
|
|
@@ -600,14 +755,14 @@ def detects(found, detector, temporal):
|
|
|
600
755
|
|
|
601
756
|
def render(result):
|
|
602
757
|
"""Return the lines the matrix runner prints for one result."""
|
|
603
|
-
name, label, operator = result.name, result.label, result.operator
|
|
758
|
+
name, label, operator, under = result.name, result.label, result.operator, result.under_symmetry
|
|
604
759
|
head = {
|
|
605
|
-
Outcome.PASS: f"PASS {name} {label} {result.detail}",
|
|
606
|
-
Outcome.FAIL: f"FAIL {name} {label}: {result.detail}",
|
|
760
|
+
Outcome.PASS: f"PASS {name} {label} {result.detail}{under}",
|
|
761
|
+
Outcome.FAIL: f"FAIL {name} {label}{under}: {result.detail}",
|
|
607
762
|
Outcome.MISSING: f"FAIL {name} {label}: spec {result.detail} not found",
|
|
608
|
-
Outcome.WITNESS: f"PASS {name} reach {operator} {label}: shortest trace {result.detail}",
|
|
609
|
-
Outcome.UNREACHED: f"FAIL {name} reach {operator} {label}: the model never reaches this state",
|
|
610
|
-
Outcome.INCOMPLETE: f"FAIL {name} reach {operator} {label}: {result.detail or 'TLC did not complete the reach check'}",
|
|
763
|
+
Outcome.WITNESS: f"PASS {name} reach {operator} {label}{under}: shortest trace {result.detail}",
|
|
764
|
+
Outcome.UNREACHED: f"FAIL {name} reach {operator} {label}{under}: the model never reaches this state",
|
|
765
|
+
Outcome.INCOMPLETE: f"FAIL {name} reach {operator} {label}{under}: {result.detail or 'TLC did not complete the reach check'}",
|
|
611
766
|
Outcome.NO_RUN: f"FAIL {name} reach {operator}: no run matching '{result.detail}'",
|
|
612
767
|
Outcome.MALFORMED: f"FAIL {result.detail}",
|
|
613
768
|
}[result.outcome]
|
|
@@ -642,6 +797,8 @@ def run_task(checker, matrix_dir, task, work, source=None, traces=False):
|
|
|
642
797
|
dest.write_bytes(module.read_bytes())
|
|
643
798
|
constants = "".join(f" {name} = {value}\n" for name, value in run.bindings)
|
|
644
799
|
config = f"CONSTANTS\n{constants}SPECIFICATION Spec\n"
|
|
800
|
+
if task.symmetry:
|
|
801
|
+
config += f"SYMMETRY {task.symmetry}\n"
|
|
645
802
|
if not task.check_deadlock:
|
|
646
803
|
config += "CHECK_DEADLOCK FALSE\n"
|
|
647
804
|
engine_name = getattr(checker, "name", "TLC")
|
|
@@ -654,7 +811,7 @@ def run_task(checker, matrix_dir, task, work, source=None, traces=False):
|
|
|
654
811
|
elapsed = time.monotonic() - start
|
|
655
812
|
shutil.rmtree(directory / "states", ignore_errors=True)
|
|
656
813
|
result = ordinary(name, run, status, log, checker.limit if timed_out else None, traces, engine_name=engine_name)
|
|
657
|
-
return replace(result, constants=run_constants, checks=run_checks, duration_s=elapsed)
|
|
814
|
+
return replace(result, constants=run_constants, checks=run_checks, duration_s=elapsed, symmetry=task.symmetry)
|
|
658
815
|
wrapper = f"Reach{uuid.uuid4().hex}"
|
|
659
816
|
invariant = f"{wrapper}Negated"
|
|
660
817
|
(directory / f"{wrapper}.tla").write_text(f"---- MODULE {wrapper} ----\nEXTENDS {name}\n{invariant} == ~{operator}\n====\n", encoding="utf-8")
|
|
@@ -667,7 +824,7 @@ def run_task(checker, matrix_dir, task, work, source=None, traces=False):
|
|
|
667
824
|
)
|
|
668
825
|
elapsed = time.monotonic() - start
|
|
669
826
|
result = witness(name, run, operator, invariant, status, log, checker.limit if timed_out else None, traces, engine_name=engine_name)
|
|
670
|
-
return replace(result, constants=run_constants, checks=run_checks, duration_s=elapsed)
|
|
827
|
+
return replace(result, constants=run_constants, checks=run_checks, duration_s=elapsed, symmetry=task.symmetry)
|
|
671
828
|
finally:
|
|
672
829
|
shutil.rmtree(directory, ignore_errors=True)
|
|
673
830
|
|
|
@@ -791,7 +948,9 @@ def validate_report_path(raw: str) -> Path | None:
|
|
|
791
948
|
|
|
792
949
|
def main():
|
|
793
950
|
if sys.argv[1:] == ["ready"]:
|
|
794
|
-
|
|
951
|
+
checker = engine()
|
|
952
|
+
checker.preflight()
|
|
953
|
+
print(checker.ready_line)
|
|
795
954
|
storage.report()
|
|
796
955
|
return 0
|
|
797
956
|
if not 2 <= len(sys.argv) <= 3:
|
|
@@ -801,13 +960,18 @@ def main():
|
|
|
801
960
|
if not Path(matrix).is_file():
|
|
802
961
|
print(f"FAIL {matrix} does not exist")
|
|
803
962
|
return 1
|
|
963
|
+
try:
|
|
964
|
+
plan = MatrixPlan(matrix)
|
|
965
|
+
except MatrixError as error:
|
|
966
|
+
print("\n".join(f"FAIL {problem}" for problem in error.problems))
|
|
967
|
+
return 2
|
|
804
968
|
checker = engine()
|
|
805
969
|
report_path = validate_report_path(os.environ.get("TLC_HTML_REPORT", ""))
|
|
806
970
|
with tempfile.TemporaryDirectory(dir=storage.ensure_temp_root()) as work:
|
|
807
971
|
print(f"ENGINE {checker.label}", flush=True)
|
|
808
972
|
matrix_runner = Runner(checker, Path(matrix).resolve().parent, only, lambda result: print("\n".join(render(result)), flush=True), Path(work),
|
|
809
973
|
keep_results=report_path is not None)
|
|
810
|
-
for task in
|
|
974
|
+
for task in plan:
|
|
811
975
|
matrix_runner.check(task)
|
|
812
976
|
if matrix_runner.runs_total == 0:
|
|
813
977
|
matching = f"matching '{only}' " if only else ""
|
|
@@ -361,8 +361,8 @@ def _result_type(result: object) -> str:
|
|
|
361
361
|
|
|
362
362
|
def _result_label(result: object) -> str:
|
|
363
363
|
if result.operator:
|
|
364
|
-
return f"reach {result.operator} {result.label}".strip()
|
|
365
|
-
return result.label or "-"
|
|
364
|
+
return f"reach {result.operator} {result.label}{result.under_symmetry}".strip()
|
|
365
|
+
return f"{result.label}{result.under_symmetry}" or "-"
|
|
366
366
|
|
|
367
367
|
|
|
368
368
|
def _table_row(idx: int, result: object) -> str:
|