agent-formal-verify 0.4.13 → 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.
- package/CHANGES.md +14 -0
- package/package.json +1 -1
- package/skills/formal-verify/SKILL.md +10 -10
- package/skills/formal-verify/references/evidence.md +1 -1
- package/skills/formal-verify/references/helpers.md +32 -3
- package/skills/formal-verify/references/setup.md +1 -1
- package/skills/formal-verify/references/tla-brief.md +1 -1
- package/skills/formal-verify/scripts/baseline.py +157 -626
- package/skills/formal-verify/scripts/kani_reader.py +592 -0
- package/skills/formal-verify/scripts/rust_source.py +74 -0
- package/skills/formal-verify/scripts/surface.py +27 -0
- package/skills/formal-verify/scripts/sync.py +5 -5
- package/skills/formal-verify/scripts/tlc.py +90 -13
- package/skills/formal-verify/scripts/tlc_report.py +516 -0
- package/skills/formal-verify/scripts/tlc_trace.py +97 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Copyright (c) 2026 Michael Denyer
|
|
2
|
+
# SPDX-License-Identifier: GPL-3.0-only
|
|
3
|
+
"""Hold a model's surface, the mapping from item name to canonical value, and collapse whitespace outside strings."""
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
STRING = re.compile(r'"(?:\\.|[^"\\])*"', re.DOTALL)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def collapse(text, literals=None):
|
|
10
|
+
if literals is None:
|
|
11
|
+
literals = (match.span() for match in STRING.finditer(text))
|
|
12
|
+
parts, end = [], 0
|
|
13
|
+
for start, stop in literals:
|
|
14
|
+
parts.extend((re.sub(r"\s+", " ", text[end:start]), text[start:stop]))
|
|
15
|
+
end = stop
|
|
16
|
+
parts.append(re.sub(r"\s+", " ", text[end:]))
|
|
17
|
+
return "".join(parts).strip()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Surface(dict):
|
|
21
|
+
def add(self, name, value=""):
|
|
22
|
+
candidate, count = name, 1
|
|
23
|
+
while candidate in self:
|
|
24
|
+
count += 1
|
|
25
|
+
candidate = f"{name} #{count}"
|
|
26
|
+
self[candidate] = value
|
|
27
|
+
return candidate
|
|
@@ -46,7 +46,7 @@ import sys
|
|
|
46
46
|
from pathlib import Path
|
|
47
47
|
|
|
48
48
|
sys.dont_write_bytecode = True
|
|
49
|
-
import
|
|
49
|
+
import rust_source
|
|
50
50
|
|
|
51
51
|
HEADER = re.compile(r"Source read at ([0-9a-fA-F]{7,40})\b")
|
|
52
52
|
# Documents and model files mention covered names but cannot define them, unless a source has the same extension.
|
|
@@ -71,7 +71,7 @@ FALLBACK_COMMITS = 100
|
|
|
71
71
|
def rust_code(path):
|
|
72
72
|
"""Return a Rust file's text with its comments and strings blanked, or None when it cannot be read."""
|
|
73
73
|
try:
|
|
74
|
-
return
|
|
74
|
+
return rust_source.rust_masks(path.read_text(encoding="utf-8", errors="replace")).without_comments_or_strings
|
|
75
75
|
except OSError:
|
|
76
76
|
return None
|
|
77
77
|
|
|
@@ -107,15 +107,15 @@ def git(root, *arguments, check=True):
|
|
|
107
107
|
@functools.cache
|
|
108
108
|
def split_harness(text):
|
|
109
109
|
"""Return the code of the #[cfg(kani)] items in Rust text and the code outside them, without comments or blank lines."""
|
|
110
|
-
source =
|
|
110
|
+
source = rust_source.rust_masks(text)
|
|
111
111
|
mask, spans = source.without_comments_or_strings, []
|
|
112
112
|
for found in KANI_CFG.finditer(mask):
|
|
113
113
|
if spans and found.start() < spans[-1][1]:
|
|
114
114
|
continue
|
|
115
115
|
at = found.end()
|
|
116
116
|
while at < len(mask) and mask[at] not in "{;":
|
|
117
|
-
at =
|
|
118
|
-
end =
|
|
117
|
+
at = rust_source.after_closing(mask, at) if mask[at] in "([" else at + 1
|
|
118
|
+
end = rust_source.after_closing(mask, at) if at < len(mask) and mask[at] == "{" else at + 1
|
|
119
119
|
spans.append((found.start(), end))
|
|
120
120
|
starts = [0] + [end for _, end in spans]
|
|
121
121
|
ends = [start for start, _ in spans] + [len(mask)]
|
|
@@ -22,6 +22,7 @@ Usage: tlc-matrix.sh <matrix-file> [label-substring]
|
|
|
22
22
|
JAVA=<path> the java binary (default: java on PATH)
|
|
23
23
|
TLC_WORKERS=<n> TLC worker threads (default auto)
|
|
24
24
|
TLC_TIMEOUT=<lim> per-run time limit, e.g. 90s, 30m, 1h (default 60m)
|
|
25
|
+
TLC_HTML_REPORT=<path> write a self-contained HTML report to this path
|
|
25
26
|
|
|
26
27
|
Usage: tlc.py ready
|
|
27
28
|
Checks TLC_TIMEOUT, that Java runs, and that the JAR is the pinned release or the one TLC_JAR names, then reports
|
|
@@ -310,6 +311,10 @@ class Result:
|
|
|
310
311
|
lines: tuple = ()
|
|
311
312
|
states: int = 0
|
|
312
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
|
|
313
318
|
|
|
314
319
|
|
|
315
320
|
@dataclass(frozen=True)
|
|
@@ -500,13 +505,18 @@ def reduced_trace(log):
|
|
|
500
505
|
return lines if lines is not None else [line for line in log.split("\n") if line.strip()][-40:]
|
|
501
506
|
|
|
502
507
|
|
|
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.
|
|
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
|
+
"""
|
|
505
513
|
spec, run = task.spec, task.run
|
|
506
514
|
operator = task.reach.operator if task.reach else ""
|
|
507
515
|
name = Path(spec).name.removesuffix(".tla")
|
|
516
|
+
run_constants = run.constants.strip()
|
|
517
|
+
run_checks = tuple(check.line for check in task.checks)
|
|
508
518
|
if not (matrix_dir / spec).is_file():
|
|
509
|
-
return Result(Outcome.MISSING, name, run.label, detail=spec)
|
|
519
|
+
return Result(Outcome.MISSING, name, run.label, detail=spec, constants=run_constants, checks=run_checks)
|
|
510
520
|
directory = Path(tempfile.mkdtemp(prefix="run.", dir=work))
|
|
511
521
|
try:
|
|
512
522
|
for module in (matrix_dir / spec).parent.glob("*.tla"):
|
|
@@ -520,28 +530,34 @@ def run_task(checker, matrix_dir, task, work, source=None):
|
|
|
520
530
|
if not task.check_deadlock:
|
|
521
531
|
config += "CHECK_DEADLOCK FALSE\n"
|
|
522
532
|
if not operator:
|
|
533
|
+
start = time.monotonic()
|
|
523
534
|
status, log, timed_out = checker.run(
|
|
524
535
|
directory, name, config + "\n".join(check.line for check in task.checks) + "\n",
|
|
525
536
|
reach=False, progress_label=f"{name} {run.label}",
|
|
526
537
|
)
|
|
538
|
+
elapsed = time.monotonic() - start
|
|
527
539
|
shutil.rmtree(directory / "states", ignore_errors=True)
|
|
528
|
-
|
|
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)
|
|
529
542
|
wrapper = f"Reach{uuid.uuid4().hex}"
|
|
530
543
|
invariant = f"{wrapper}Negated"
|
|
531
544
|
(directory / f"{wrapper}.tla").write_text(f"---- MODULE {wrapper} ----\nEXTENDS {name}\n{invariant} == ~{operator}\n====\n", encoding="utf-8")
|
|
532
545
|
# Exhaustive UNREACHED checks in reach: mutations do not depend on shortest-trace determinism.
|
|
533
546
|
reach_workers = checker.workers if source is not None else "1"
|
|
547
|
+
start = time.monotonic()
|
|
534
548
|
status, log, timed_out = checker.run(
|
|
535
549
|
directory, wrapper, config + f"INVARIANT {invariant}\n",
|
|
536
550
|
reach=True, workers=reach_workers, progress_label=f"{name} reach {operator} {run.label}",
|
|
537
551
|
)
|
|
538
|
-
|
|
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)
|
|
539
555
|
finally:
|
|
540
556
|
shutil.rmtree(directory, ignore_errors=True)
|
|
541
557
|
|
|
542
558
|
|
|
543
559
|
|
|
544
|
-
def ordinary(name, run, status, log, timeout_limit=None):
|
|
560
|
+
def ordinary(name, run, status, log, timeout_limit=None, traces=False):
|
|
545
561
|
if timeout_limit:
|
|
546
562
|
tail = tuple(line for line in log.split("\n") if line.strip())[-10:]
|
|
547
563
|
return Result(Outcome.FAIL, name, run.label,
|
|
@@ -553,10 +569,10 @@ def ordinary(name, run, status, log, timeout_limit=None):
|
|
|
553
569
|
errors = [line for line in log.split("\n") if line.startswith("Error:")]
|
|
554
570
|
first = errors[0] if errors else ""
|
|
555
571
|
return Result(Outcome.FAIL, name, run.label, detail=first, lines=(*errors[1:5], *reduced_trace(log)),
|
|
556
|
-
violation=violation(first))
|
|
572
|
+
violation=violation(first), trace=tlc_trace.parse(re.split(r"\r\n|\r|\n", log)) if traces else None)
|
|
557
573
|
|
|
558
574
|
|
|
559
|
-
def witness(name, run, operator, invariant, status, log, timeout_limit=None):
|
|
575
|
+
def witness(name, run, operator, invariant, status, log, timeout_limit=None, traces=False):
|
|
560
576
|
if timeout_limit:
|
|
561
577
|
tail = tuple(line for line in log.split("\n") if line.strip())[-10:]
|
|
562
578
|
return Result(Outcome.INCOMPLETE, name, run.label, operator,
|
|
@@ -568,7 +584,8 @@ def witness(name, run, operator, invariant, status, log, timeout_limit=None):
|
|
|
568
584
|
elif status == 12 and f"Error: Invariant {invariant} is violated." in lines:
|
|
569
585
|
length = sum(1 for line in lines if re.match(r"State [0-9]+:", line))
|
|
570
586
|
if length:
|
|
571
|
-
return Result(Outcome.WITNESS, name, run.label, operator, f"{length} states ({length - 1} transitions)"
|
|
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)
|
|
572
589
|
if status == 0 and "No error has been found" in log:
|
|
573
590
|
return Result(Outcome.UNREACHED, name, run.label, operator)
|
|
574
591
|
return Result(Outcome.INCOMPLETE, name, run.label, operator, lines=tuple(log.removesuffix("\n").split("\n")) if log else ())
|
|
@@ -577,12 +594,16 @@ def witness(name, run, operator, invariant, status, log, timeout_limit=None):
|
|
|
577
594
|
class Runner:
|
|
578
595
|
"""Run the selected tasks and report each result to emit."""
|
|
579
596
|
|
|
580
|
-
def __init__(self, tlc, matrix_dir, only, emit, work):
|
|
597
|
+
def __init__(self, tlc, matrix_dir, only, emit, work, keep_results=False):
|
|
581
598
|
self.tlc, self.matrix_dir, self.only, self.emit, self.work = tlc, matrix_dir, only, emit, work
|
|
582
599
|
self.runs_total = self.passed = self.states = self.reach_total = self.reached = 0
|
|
583
600
|
self.failed = False
|
|
601
|
+
# Only the HTML report reads the results and their traces.
|
|
602
|
+
self.results = [] if keep_results else None
|
|
584
603
|
|
|
585
604
|
def report(self, result):
|
|
605
|
+
if self.results is not None:
|
|
606
|
+
self.results.append(result)
|
|
586
607
|
self.failed |= result.outcome not in (Outcome.PASS, Outcome.WITNESS)
|
|
587
608
|
self.emit(result)
|
|
588
609
|
|
|
@@ -597,7 +618,7 @@ class Runner:
|
|
|
597
618
|
self.reach_total += 1
|
|
598
619
|
else:
|
|
599
620
|
self.runs_total += 1
|
|
600
|
-
result = run_task(self.tlc, self.matrix_dir, task, self.work)
|
|
621
|
+
result = run_task(self.tlc, self.matrix_dir, task, self.work, traces=self.results is not None)
|
|
601
622
|
if result.outcome is Outcome.PASS:
|
|
602
623
|
self.passed += 1
|
|
603
624
|
self.states += result.states
|
|
@@ -606,6 +627,50 @@ class Runner:
|
|
|
606
627
|
self.report(result)
|
|
607
628
|
|
|
608
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
|
|
672
|
+
|
|
673
|
+
|
|
609
674
|
def main():
|
|
610
675
|
if sys.argv[1:] == ["ready"]:
|
|
611
676
|
print(f"READY TLC {Tlc().jar}")
|
|
@@ -619,8 +684,10 @@ def main():
|
|
|
619
684
|
print(f"FAIL {matrix} does not exist")
|
|
620
685
|
return 1
|
|
621
686
|
tlc = Tlc()
|
|
687
|
+
report_path = validate_report_path(os.environ.get("TLC_HTML_REPORT", ""))
|
|
622
688
|
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)
|
|
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)
|
|
624
691
|
for task in MatrixPlan(matrix):
|
|
625
692
|
matrix_runner.check(task)
|
|
626
693
|
if matrix_runner.runs_total == 0:
|
|
@@ -630,7 +697,17 @@ def main():
|
|
|
630
697
|
summary = f"SUMMARY {matrix_runner.passed} of {matrix_runner.runs_total} runs passed"
|
|
631
698
|
if matrix_runner.reach_total:
|
|
632
699
|
summary += f", {matrix_runner.reached} of {matrix_runner.reach_total} reach checks passed"
|
|
633
|
-
|
|
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
|
|
634
711
|
return int(matrix_runner.failed)
|
|
635
712
|
|
|
636
713
|
|