agent-formal-verify 0.4.5 → 0.4.9
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 +44 -0
- package/README.md +1 -1
- package/package.json +1 -1
- package/skills/formal-verify/SKILL.md +24 -7
- package/skills/formal-verify/examples/kani-template/src/lib.rs +6 -0
- package/skills/formal-verify/examples/lean-template/Model/BoundedQueue.lean +22 -7
- package/skills/formal-verify/examples/lean-template/Model/BoundedQueue.mutations +6 -1
- package/skills/formal-verify/examples/lean-template/Model/BoundedQueue.statements +34 -6
- package/skills/formal-verify/examples/lean-template/lean-toolchain +1 -1
- package/skills/formal-verify/references/lean-brief.md +24 -4
- package/skills/formal-verify/references/review-brief.md +45 -0
- package/skills/formal-verify/references/rust-brief.md +14 -6
- package/skills/formal-verify/references/setup.md +1 -1
- package/skills/formal-verify/references/tla-brief.md +3 -2
- package/skills/formal-verify/scripts/baseline.py +413 -0
- package/skills/formal-verify/scripts/kani.py +37 -0
- package/skills/formal-verify/scripts/lean-check.sh +88 -9
- package/skills/formal-verify/scripts/lean-mutations.lean +95 -0
- package/skills/formal-verify/scripts/lean-replay.lean +19 -0
- package/skills/formal-verify/scripts/lean-statements.py +61 -39
- package/skills/formal-verify/scripts/lean-tools.sh +9 -0
- package/skills/formal-verify/scripts/mutate.py +271 -138
- package/skills/formal-verify/scripts/tlc-matrix.sh +4 -167
- package/skills/formal-verify/scripts/tlc.py +310 -0
|
@@ -1,172 +1,9 @@
|
|
|
1
1
|
#!/bin/bash
|
|
2
2
|
# Copyright (c) 2026 Michael Denyer
|
|
3
3
|
# SPDX-License-Identifier: GPL-3.0-only
|
|
4
|
-
# Model-checks TLA+ specs with TLC over a matrix of constants
|
|
5
|
-
#
|
|
6
|
-
# state count, then a SUMMARY line with the totals. A failing run prints TLC's
|
|
7
|
-
# error and its error trace reduced to the variables each step changed
|
|
8
|
-
# (tlc-trace.py).
|
|
9
|
-
#
|
|
10
|
-
# Matrix file, one directive per line (# starts a comment):
|
|
11
|
-
# spec <path.tla> the spec for the runs below, relative to the file;
|
|
12
|
-
# TLC checks the formula it names Spec
|
|
13
|
-
# check <cfg line> an INVARIANTS or PROPERTIES line, kept until the next spec
|
|
14
|
-
# reach <Operator> | <label-substring> a witness in the first matching run
|
|
15
|
-
# run <label> | <Name=Value ...> one TLC run with those CONSTANTS
|
|
16
|
-
#
|
|
4
|
+
# Model-checks TLA+ specs with TLC over a matrix of constants. tlc.py holds the
|
|
5
|
+
# runner and documents the matrix file and its environment settings.
|
|
17
6
|
# Usage: tlc-matrix.sh <matrix-file> [label-substring]
|
|
18
|
-
# TLC_JAR=<path> use this existing tla2tools.jar
|
|
19
|
-
# TLC_CACHE=<dir> where the pinned jar lives (default ~/.cache/tla)
|
|
20
|
-
# JAVA=<path> the java binary (default: java on PATH)
|
|
21
|
-
# TLC_WORKERS=<n> TLC worker threads (default auto)
|
|
22
|
-
set -uo pipefail
|
|
23
|
-
HERE=$(cd "$(dirname "$0")" && pwd)
|
|
24
|
-
# shellcheck source=skills/formal-verify/scripts/tlc-tools.sh
|
|
25
|
-
source "$HERE/tlc-tools.sh"
|
|
26
|
-
TLC_WORKERS=${TLC_WORKERS:-auto}
|
|
27
|
-
|
|
28
7
|
[ "$#" -ge 1 ] && [ "$#" -le 2 ] || { echo "usage: tlc-matrix.sh <matrix-file> [label-substring]"; exit 2; }
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
only=${2:-}
|
|
32
|
-
MATRIX_DIR=$(cd "$(dirname "$matrix")" && pwd)
|
|
33
|
-
|
|
34
|
-
require_tlc_runtime || exit $?
|
|
35
|
-
tlc_jar_ready || exit $?
|
|
36
|
-
|
|
37
|
-
OUT=$(mktemp -d)
|
|
38
|
-
trap 'rm -rf "$OUT"' EXIT
|
|
39
|
-
fail=0
|
|
40
|
-
run=0
|
|
41
|
-
passed=0
|
|
42
|
-
total=0
|
|
43
|
-
spec=""
|
|
44
|
-
checks=""
|
|
45
|
-
reaches=()
|
|
46
|
-
runs=()
|
|
47
|
-
reach_count=0
|
|
48
|
-
reach_passed=0
|
|
49
|
-
|
|
50
|
-
check_run() {
|
|
51
|
-
local label=$1 consts=$2 operator=${3:-} name dir pairs c states wrapper invariant status trace
|
|
52
|
-
local workers=$TLC_WORKERS extra=()
|
|
53
|
-
[ -n "$spec" ] || { echo "FAIL run '$label' before any spec line"; fail=1; return; }
|
|
54
|
-
case $label in *"$only"*) ;; *) return ;; esac
|
|
55
|
-
if [ -n "$operator" ]; then reach_count=$((reach_count + 1)); else run=$((run + 1)); fi
|
|
56
|
-
name=$(basename "$spec" .tla)
|
|
57
|
-
[ -f "$MATRIX_DIR/$spec" ] || { echo "FAIL $name $label: spec $spec not found"; fail=1; return; }
|
|
58
|
-
# A directory per run, so a run sees only the modules beside its own spec.
|
|
59
|
-
dir=$(mktemp -d "$OUT/run.XXXXXX")
|
|
60
|
-
cp "$MATRIX_DIR/$(dirname "$spec")"/*.tla "$dir/"
|
|
61
|
-
wrapper=$name
|
|
62
|
-
if [ -n "$operator" ]; then
|
|
63
|
-
# Neither generated identifier may shadow an imported declaration or module.
|
|
64
|
-
while :; do
|
|
65
|
-
wrapper=Reach$(python3 -c 'import uuid; print(uuid.uuid4().hex)')
|
|
66
|
-
invariant=${wrapper}Negated
|
|
67
|
-
grep -Ewq "$wrapper|$invariant" "$dir/"*.tla || break
|
|
68
|
-
done
|
|
69
|
-
printf '%s\n' "---- MODULE $wrapper ----" "EXTENDS $name" "$invariant == ~$operator" "====" > "$dir/$wrapper.tla"
|
|
70
|
-
workers=1
|
|
71
|
-
extra=(-deadlock)
|
|
72
|
-
fi
|
|
73
|
-
read -ra pairs <<< "$consts"
|
|
74
|
-
{
|
|
75
|
-
echo "CONSTANTS"
|
|
76
|
-
# bash 3.2 treats an empty array as unset under set -u.
|
|
77
|
-
for c in ${pairs[@]+"${pairs[@]}"}; do echo " ${c%%=*} = ${c#*=}"; done
|
|
78
|
-
echo "SPECIFICATION Spec"
|
|
79
|
-
if [ -n "$operator" ]; then echo "INVARIANT $invariant"; else printf '%s\n' "$checks"; fi
|
|
80
|
-
} > "$dir/MC.cfg"
|
|
81
|
-
status=0
|
|
82
|
-
"$JAVA" -XX:+UseParallelGC -cp "$TLC_JAR" tlc2.TLC -workers "$workers" ${extra[@]+"${extra[@]}"} -cleanup -metadir "$dir/states" \
|
|
83
|
-
-config "$dir/MC.cfg" "$dir/$wrapper.tla" > "$dir/tlc.log" 2>&1 || status=$?
|
|
84
|
-
if [ -n "$operator" ]; then
|
|
85
|
-
if [ "$status" -eq 12 ] && grep -Fxq "Error: Invariant $invariant is violated by the initial state:" "$dir/tlc.log"; then
|
|
86
|
-
trace=1
|
|
87
|
-
elif [ "$status" -eq 12 ] && grep -Fxq "Error: Invariant $invariant is violated." "$dir/tlc.log"; then
|
|
88
|
-
trace=$(grep -c '^State [0-9][0-9]*:' "$dir/tlc.log")
|
|
89
|
-
else
|
|
90
|
-
trace=0
|
|
91
|
-
fi
|
|
92
|
-
if [ "$trace" -gt 0 ]; then
|
|
93
|
-
echo "PASS $name reach $operator $label: shortest trace $trace states ($((trace - 1)) transitions)"
|
|
94
|
-
reach_passed=$((reach_passed + 1))
|
|
95
|
-
elif [ "$status" -eq 0 ] && grep -q "No error has been found" "$dir/tlc.log"; then
|
|
96
|
-
echo "FAIL $name reach $operator $label: the model never reaches this state"
|
|
97
|
-
fail=1
|
|
98
|
-
else
|
|
99
|
-
echo "FAIL $name reach $operator $label: TLC did not complete the reach check"
|
|
100
|
-
cat "$dir/tlc.log"
|
|
101
|
-
fail=1
|
|
102
|
-
fi
|
|
103
|
-
elif [ "$status" -eq 0 ] && grep -q "No error has been found" "$dir/tlc.log"; then
|
|
104
|
-
# Progress lines carry interim counts; the last match is the final one.
|
|
105
|
-
states=$(grep -o '[0-9,]* distinct states found' "$dir/tlc.log" | tail -1)
|
|
106
|
-
echo "PASS $name $label $states"
|
|
107
|
-
passed=$((passed + 1))
|
|
108
|
-
states=${states%% *}
|
|
109
|
-
states=${states//,/}
|
|
110
|
-
total=$((total + ${states:-0}))
|
|
111
|
-
else
|
|
112
|
-
echo "FAIL $name $label: $(grep -m1 "^Error:" "$dir/tlc.log")"
|
|
113
|
-
grep "^Error:" "$dir/tlc.log" | sed -n '2,5p'
|
|
114
|
-
python3 "$HERE/tlc-trace.py" "$dir/tlc.log" || grep -v '^[[:space:]]*$' "$dir/tlc.log" | tail -40
|
|
115
|
-
fail=1
|
|
116
|
-
fi
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
check_reaches() {
|
|
120
|
-
local reach entry operator match label found
|
|
121
|
-
for reach in ${reaches[@]+"${reaches[@]}"}; do
|
|
122
|
-
operator=${reach%%|*}; match=${reach#*|}; found=0
|
|
123
|
-
for entry in ${runs[@]+"${runs[@]}"}; do
|
|
124
|
-
label=${entry%%|*}
|
|
125
|
-
case $label in
|
|
126
|
-
*"$match"*) check_run "$label" "${entry#*|}" "$operator"; found=1; break ;;
|
|
127
|
-
esac
|
|
128
|
-
done
|
|
129
|
-
if [ "$found" -eq 0 ]; then
|
|
130
|
-
echo "FAIL $(basename "$spec" .tla) reach $operator: no run matching '$match'"
|
|
131
|
-
reach_count=$((reach_count + 1))
|
|
132
|
-
fail=1
|
|
133
|
-
fi
|
|
134
|
-
done
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
while IFS= read -r line || [ -n "$line" ]; do
|
|
138
|
-
line=${line%%#*}
|
|
139
|
-
[[ $line =~ [^[:space:]] ]] || continue
|
|
140
|
-
read -r kw rest <<< "$line"
|
|
141
|
-
case $kw in
|
|
142
|
-
spec) check_reaches; spec=$rest; checks=""; reaches=(); runs=() ;;
|
|
143
|
-
check)
|
|
144
|
-
[ -n "$spec" ] || { echo "FAIL check '$rest' before any spec line"; fail=1; continue; }
|
|
145
|
-
read -r kind names <<< "$rest"
|
|
146
|
-
case $kind in
|
|
147
|
-
INVARIANT|INVARIANTS|PROPERTY|PROPERTIES)
|
|
148
|
-
[ -n "$names" ] || { echo "FAIL malformed check '$rest'"; fail=1; continue; } ;;
|
|
149
|
-
*) echo "FAIL malformed check '$rest'"; fail=1; continue ;;
|
|
150
|
-
esac
|
|
151
|
-
checks="$checks${checks:+$'\n'}$rest" ;;
|
|
152
|
-
reach)
|
|
153
|
-
[ -n "$spec" ] || { echo "FAIL reach '$rest' before any spec line"; fail=1; continue; }
|
|
154
|
-
if [[ $rest =~ ^([a-zA-Z_][a-zA-Z_0-9]*)[[:space:]]*\|[[:space:]]*(.*[^[:space:]])[[:space:]]*$ ]]; then
|
|
155
|
-
reaches+=("${BASH_REMATCH[1]}|${BASH_REMATCH[2]}")
|
|
156
|
-
else
|
|
157
|
-
echo "FAIL malformed reach '$rest': expected reach <Operator> | <label-substring>"
|
|
158
|
-
fail=1
|
|
159
|
-
fi ;;
|
|
160
|
-
run)
|
|
161
|
-
[[ $rest == *"|"* ]] || { echo "FAIL run '$rest' has no | before its constants"; fail=1; continue; }
|
|
162
|
-
label=${rest%%|*}; label=${label% }; runs+=("$label|${rest#*|}"); check_run "$label" "${rest#*|}" ;;
|
|
163
|
-
*) echo "FAIL unknown directive: $line"; fail=1 ;;
|
|
164
|
-
esac
|
|
165
|
-
done < "$matrix"
|
|
166
|
-
check_reaches
|
|
167
|
-
|
|
168
|
-
[ "$run" -gt 0 ] || { echo "FAIL no run ${only:+matching '$only' }in $matrix"; exit 1; }
|
|
169
|
-
summary="SUMMARY $passed of $run runs passed"
|
|
170
|
-
[ "$reach_count" -eq 0 ] || summary="$summary, $reach_passed of $reach_count reach checks passed"
|
|
171
|
-
echo "$summary, $total distinct states in total"
|
|
172
|
-
exit $fail
|
|
8
|
+
command -v python3 > /dev/null || { echo "UNAVAILABLE python3 is not on PATH; install Python 3"; exit 3; }
|
|
9
|
+
exec python3 "$(dirname "$0")/tlc.py" "$@"
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# Copyright (c) 2026 Michael Denyer
|
|
3
|
+
# SPDX-License-Identifier: GPL-3.0-only
|
|
4
|
+
"""Model-check TLA+ specs with TLC over a matrix of constants read from a matrix file.
|
|
5
|
+
|
|
6
|
+
Prints one PASS or FAIL line per run with its distinct state count, then a
|
|
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).
|
|
9
|
+
|
|
10
|
+
Matrix file, one directive per line (# starts a comment):
|
|
11
|
+
spec <path.tla> the spec for the runs below, relative to the file;
|
|
12
|
+
TLC checks the formula it names Spec
|
|
13
|
+
check <cfg line> an INVARIANTS or PROPERTIES line, kept until the next spec
|
|
14
|
+
reach <Operator> | <label-substring> a witness in the first matching run
|
|
15
|
+
run <label> | <Name=Value ...> one TLC run with those CONSTANTS
|
|
16
|
+
|
|
17
|
+
A malformed directive prints a FAIL line and the runner goes on to the next.
|
|
18
|
+
|
|
19
|
+
Usage: tlc-matrix.sh <matrix-file> [label-substring]
|
|
20
|
+
TLC_JAR=<path> use this existing tla2tools.jar
|
|
21
|
+
TLC_CACHE=<dir> where the pinned jar lives (default ~/.cache/tla)
|
|
22
|
+
JAVA=<path> the java binary (default: java on PATH)
|
|
23
|
+
TLC_WORKERS=<n> TLC worker threads (default auto)
|
|
24
|
+
"""
|
|
25
|
+
import os
|
|
26
|
+
import re
|
|
27
|
+
import subprocess
|
|
28
|
+
import sys
|
|
29
|
+
import tempfile
|
|
30
|
+
import uuid
|
|
31
|
+
from dataclasses import dataclass
|
|
32
|
+
from enum import Enum
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
|
|
35
|
+
HERE = Path(__file__).resolve().parent
|
|
36
|
+
CHECK_KINDS = ("INVARIANT", "INVARIANTS", "PROPERTY", "PROPERTIES")
|
|
37
|
+
REACH = re.compile(r"([a-zA-Z_][a-zA-Z_0-9]*)\s*\|\s*(.*\S)\s*")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def read_raw(path):
|
|
41
|
+
"""Return a file's text as bash reads it: line ends untouched, a byte that is not UTF-8 replaced."""
|
|
42
|
+
with open(path, encoding="utf-8", errors="replace", newline="") as stream:
|
|
43
|
+
return stream.read()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class Spec:
|
|
48
|
+
path: str
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class Check:
|
|
53
|
+
line: str
|
|
54
|
+
kind: str
|
|
55
|
+
names: tuple
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True)
|
|
59
|
+
class Reach:
|
|
60
|
+
operator: str
|
|
61
|
+
match: str
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class Run:
|
|
66
|
+
label: str
|
|
67
|
+
constants: str
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(frozen=True)
|
|
71
|
+
class Malformed:
|
|
72
|
+
message: str
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def directives(lines):
|
|
76
|
+
"""Yield each directive of a matrix in file order, with a Malformed in place of a line it rejects."""
|
|
77
|
+
seen_spec = False
|
|
78
|
+
for raw in lines:
|
|
79
|
+
line = raw.split("#", 1)[0]
|
|
80
|
+
if not line.strip():
|
|
81
|
+
continue
|
|
82
|
+
keyword, rest = (line.split(None, 1) + [""])[:2]
|
|
83
|
+
rest = rest.strip()
|
|
84
|
+
if keyword == "spec":
|
|
85
|
+
seen_spec = bool(rest)
|
|
86
|
+
yield Spec(rest)
|
|
87
|
+
elif keyword == "check":
|
|
88
|
+
kind, names = (rest.split(None, 1) + ["", ""])[:2]
|
|
89
|
+
if not seen_spec:
|
|
90
|
+
yield Malformed(f"check '{rest}' before any spec line")
|
|
91
|
+
elif kind not in CHECK_KINDS or not names.strip():
|
|
92
|
+
yield Malformed(f"malformed check '{rest}'")
|
|
93
|
+
else:
|
|
94
|
+
yield Check(rest, kind, tuple(names.split()))
|
|
95
|
+
elif keyword == "reach":
|
|
96
|
+
match = REACH.fullmatch(rest)
|
|
97
|
+
if not seen_spec:
|
|
98
|
+
yield Malformed(f"reach '{rest}' before any spec line")
|
|
99
|
+
elif not match:
|
|
100
|
+
yield Malformed(f"malformed reach '{rest}': expected reach <Operator> | <label-substring>")
|
|
101
|
+
else:
|
|
102
|
+
yield Reach(match[1], match[2])
|
|
103
|
+
elif keyword == "run":
|
|
104
|
+
label, bar, constants = rest.partition("|")
|
|
105
|
+
if not bar:
|
|
106
|
+
yield Malformed(f"run '{rest}' has no | before its constants")
|
|
107
|
+
elif not seen_spec:
|
|
108
|
+
yield Malformed(f"run '{label.removesuffix(' ')}' before any spec line")
|
|
109
|
+
else:
|
|
110
|
+
yield Run(label.removesuffix(" "), constants)
|
|
111
|
+
else:
|
|
112
|
+
yield Malformed(f"unknown directive: {line}")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class Unavailable(Exception):
|
|
116
|
+
pass
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class Tlc:
|
|
120
|
+
"""The pinned TLC, checked once; tlc-tools.sh owns the pin and the readiness checks."""
|
|
121
|
+
|
|
122
|
+
def __init__(self):
|
|
123
|
+
done = subprocess.run(
|
|
124
|
+
["bash", "-c", 'source "$1/tlc-tools.sh" && require_tlc_runtime && tlc_jar_ready && printf "%s\\n%s\\n" "$JAVA" "$TLC_JAR"',
|
|
125
|
+
"bash", str(HERE)], capture_output=True, text=True, check=False)
|
|
126
|
+
if done.returncode:
|
|
127
|
+
raise Unavailable(done.stdout.rstrip("\n"))
|
|
128
|
+
self.java, self.jar = done.stdout.splitlines()[-2:]
|
|
129
|
+
self.workers = os.environ.get("TLC_WORKERS") or "auto"
|
|
130
|
+
|
|
131
|
+
def run(self, directory, module, config, reach):
|
|
132
|
+
"""Run TLC on module in directory with config; return its exit status and log."""
|
|
133
|
+
log = directory / "tlc.log"
|
|
134
|
+
(directory / "MC.cfg").write_text(config, encoding="utf-8")
|
|
135
|
+
command = [self.java, "-XX:+UseParallelGC", "-cp", self.jar, "tlc2.TLC", "-workers", "1" if reach else self.workers,
|
|
136
|
+
*(["-deadlock"] if reach else []), "-cleanup", "-metadir", str(directory / "states"),
|
|
137
|
+
"-config", str(directory / "MC.cfg"), str(directory / f"{module}.tla")]
|
|
138
|
+
with log.open("w", encoding="utf-8") as stream:
|
|
139
|
+
status = subprocess.run(command, stdout=stream, stderr=subprocess.STDOUT, check=False).returncode
|
|
140
|
+
return status, read_raw(log)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class Outcome(Enum):
|
|
144
|
+
PASS = "pass"
|
|
145
|
+
FAIL = "fail"
|
|
146
|
+
MISSING = "missing"
|
|
147
|
+
WITNESS = "witness"
|
|
148
|
+
UNREACHED = "unreached"
|
|
149
|
+
INCOMPLETE = "incomplete"
|
|
150
|
+
NO_RUN = "no run"
|
|
151
|
+
MALFORMED = "malformed"
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@dataclass(frozen=True)
|
|
155
|
+
class Result:
|
|
156
|
+
"""One line of the runner's report and the output printed under it."""
|
|
157
|
+
outcome: Outcome
|
|
158
|
+
name: str = ""
|
|
159
|
+
label: str = ""
|
|
160
|
+
operator: str = ""
|
|
161
|
+
detail: str = ""
|
|
162
|
+
lines: tuple = ()
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def render(result):
|
|
166
|
+
"""Return the lines the matrix runner prints for one result."""
|
|
167
|
+
name, label, operator = result.name, result.label, result.operator
|
|
168
|
+
head = {
|
|
169
|
+
Outcome.PASS: f"PASS {name} {label} {result.detail}",
|
|
170
|
+
Outcome.FAIL: f"FAIL {name} {label}: {result.detail}",
|
|
171
|
+
Outcome.MISSING: f"FAIL {name} {label}: spec {result.detail} not found",
|
|
172
|
+
Outcome.WITNESS: f"PASS {name} reach {operator} {label}: shortest trace {result.detail}",
|
|
173
|
+
Outcome.UNREACHED: f"FAIL {name} reach {operator} {label}: the model never reaches this state",
|
|
174
|
+
Outcome.INCOMPLETE: f"FAIL {name} reach {operator} {label}: TLC did not complete the reach check",
|
|
175
|
+
Outcome.NO_RUN: f"FAIL {name} reach {operator}: no run matching '{result.detail}'",
|
|
176
|
+
Outcome.MALFORMED: f"FAIL {result.detail}",
|
|
177
|
+
}[result.outcome]
|
|
178
|
+
return [head, *result.lines]
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def reduced_trace(log_path, log):
|
|
182
|
+
done = subprocess.run([sys.executable, str(HERE / "tlc-trace.py"), str(log_path)], capture_output=True, text=True, check=False)
|
|
183
|
+
sys.stderr.write(done.stderr)
|
|
184
|
+
lines = done.stdout.removesuffix("\n").split("\n") if done.stdout else []
|
|
185
|
+
if done.returncode:
|
|
186
|
+
lines += [line for line in log.split("\n") if line.strip()][-40:]
|
|
187
|
+
return lines
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class Runner:
|
|
191
|
+
"""Runs a matrix's directives in order, as tlc-matrix.sh reads them, and reports each result to emit."""
|
|
192
|
+
|
|
193
|
+
def __init__(self, tlc, matrix_dir, only, emit, work):
|
|
194
|
+
self.tlc, self.matrix_dir, self.only, self.emit, self.work = tlc, matrix_dir, only, emit, work
|
|
195
|
+
self.spec, self.checks, self.reaches, self.runs = "", [], [], []
|
|
196
|
+
self.runs_total = self.passed = self.states = self.reach_total = self.reached = 0
|
|
197
|
+
self.failed = False
|
|
198
|
+
|
|
199
|
+
def feed(self, directive):
|
|
200
|
+
if isinstance(directive, Spec):
|
|
201
|
+
self.finish_spec()
|
|
202
|
+
self.spec, self.checks, self.reaches, self.runs = directive.path, [], [], []
|
|
203
|
+
elif isinstance(directive, Check):
|
|
204
|
+
self.checks.append(directive.line)
|
|
205
|
+
elif isinstance(directive, Reach):
|
|
206
|
+
self.reaches.append(directive)
|
|
207
|
+
elif isinstance(directive, Run):
|
|
208
|
+
self.runs.append(directive)
|
|
209
|
+
self.check_run(directive)
|
|
210
|
+
else:
|
|
211
|
+
self.report(Result(Outcome.MALFORMED, detail=directive.message))
|
|
212
|
+
|
|
213
|
+
def finish_spec(self):
|
|
214
|
+
"""Run each reach check of the current spec in the first run whose label contains its substring."""
|
|
215
|
+
for reach in self.reaches:
|
|
216
|
+
run = next((run for run in self.runs if reach.match in run.label), None)
|
|
217
|
+
if run is None:
|
|
218
|
+
self.reach_total += 1
|
|
219
|
+
self.report(Result(Outcome.NO_RUN, Path(self.spec).name.removesuffix(".tla"), operator=reach.operator, detail=reach.match))
|
|
220
|
+
else:
|
|
221
|
+
self.check_run(run, reach.operator)
|
|
222
|
+
|
|
223
|
+
def report(self, result):
|
|
224
|
+
self.failed |= result.outcome not in (Outcome.PASS, Outcome.WITNESS)
|
|
225
|
+
self.emit(result)
|
|
226
|
+
|
|
227
|
+
def check_run(self, run, operator=""):
|
|
228
|
+
if self.only not in run.label:
|
|
229
|
+
return
|
|
230
|
+
if operator:
|
|
231
|
+
self.reach_total += 1
|
|
232
|
+
else:
|
|
233
|
+
self.runs_total += 1
|
|
234
|
+
name = Path(self.spec).name.removesuffix(".tla")
|
|
235
|
+
if not (self.matrix_dir / self.spec).is_file():
|
|
236
|
+
self.report(Result(Outcome.MISSING, name, run.label, detail=self.spec))
|
|
237
|
+
return
|
|
238
|
+
directory = Path(tempfile.mkdtemp(prefix="run.", dir=self.work))
|
|
239
|
+
for module in (self.matrix_dir / self.spec).parent.glob("*.tla"):
|
|
240
|
+
(directory / module.name).write_bytes(module.read_bytes())
|
|
241
|
+
constants = "".join(f" {pair.split('=')[0]} = {pair.split('=', 1)[-1]}\n" for pair in run.constants.split())
|
|
242
|
+
config = f"CONSTANTS\n{constants}SPECIFICATION Spec\n"
|
|
243
|
+
if not operator:
|
|
244
|
+
status, log = self.tlc.run(directory, name, config + "\n".join(self.checks) + "\n", reach=False)
|
|
245
|
+
self.report(self.ordinary(name, run, status, log, directory / "tlc.log"))
|
|
246
|
+
return
|
|
247
|
+
wrapper = f"Reach{uuid.uuid4().hex}"
|
|
248
|
+
invariant = f"{wrapper}Negated"
|
|
249
|
+
(directory / f"{wrapper}.tla").write_text(f"---- MODULE {wrapper} ----\nEXTENDS {name}\n{invariant} == ~{operator}\n====\n", encoding="utf-8")
|
|
250
|
+
status, log = self.tlc.run(directory, wrapper, config + f"INVARIANT {invariant}\n", reach=True)
|
|
251
|
+
self.report(self.witness(name, run, operator, invariant, status, log))
|
|
252
|
+
|
|
253
|
+
def ordinary(self, name, run, status, log, log_path):
|
|
254
|
+
if status == 0 and "No error has been found" in log:
|
|
255
|
+
found = re.findall(r"[0-9,]* distinct states found", log)
|
|
256
|
+
states = found[-1] if found else ""
|
|
257
|
+
self.passed += 1
|
|
258
|
+
count = states.partition(" ")[0].replace(",", "")
|
|
259
|
+
self.states += int(count or 0)
|
|
260
|
+
return Result(Outcome.PASS, name, run.label, detail=states)
|
|
261
|
+
errors = [line for line in log.split("\n") if line.startswith("Error:")]
|
|
262
|
+
return Result(Outcome.FAIL, name, run.label, detail=errors[0] if errors else "",
|
|
263
|
+
lines=(*errors[1:5], *reduced_trace(log_path, log)))
|
|
264
|
+
|
|
265
|
+
def witness(self, name, run, operator, invariant, status, log):
|
|
266
|
+
lines = log.split("\n")
|
|
267
|
+
length = 0
|
|
268
|
+
if status == 12 and f"Error: Invariant {invariant} is violated by the initial state:" in lines:
|
|
269
|
+
length = 1
|
|
270
|
+
elif status == 12 and f"Error: Invariant {invariant} is violated." in lines:
|
|
271
|
+
length = sum(1 for line in lines if re.match(r"State [0-9]+:", line))
|
|
272
|
+
if length:
|
|
273
|
+
self.reached += 1
|
|
274
|
+
return Result(Outcome.WITNESS, name, run.label, operator, f"{length} states ({length - 1} transitions)")
|
|
275
|
+
if status == 0 and "No error has been found" in log:
|
|
276
|
+
return Result(Outcome.UNREACHED, name, run.label, operator)
|
|
277
|
+
return Result(Outcome.INCOMPLETE, name, run.label, operator, lines=tuple(log.removesuffix("\n").split("\n")) if log else ())
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def main():
|
|
281
|
+
if not 2 <= len(sys.argv) <= 3:
|
|
282
|
+
print("usage: tlc-matrix.sh <matrix-file> [label-substring]")
|
|
283
|
+
return 2
|
|
284
|
+
matrix, only = sys.argv[1], sys.argv[2] if len(sys.argv) == 3 else ""
|
|
285
|
+
if not Path(matrix).is_file():
|
|
286
|
+
print(f"FAIL {matrix} does not exist")
|
|
287
|
+
return 1
|
|
288
|
+
try:
|
|
289
|
+
tlc = Tlc()
|
|
290
|
+
except Unavailable as error:
|
|
291
|
+
print(error)
|
|
292
|
+
return 3
|
|
293
|
+
with tempfile.TemporaryDirectory() as work:
|
|
294
|
+
runner = Runner(tlc, Path(matrix).resolve().parent, only, lambda result: print("\n".join(render(result)), flush=True), Path(work))
|
|
295
|
+
for directive in directives(read_raw(matrix).split("\n")):
|
|
296
|
+
runner.feed(directive)
|
|
297
|
+
runner.finish_spec()
|
|
298
|
+
if runner.runs_total == 0:
|
|
299
|
+
matching = f"matching '{only}' " if only else ""
|
|
300
|
+
print(f"FAIL no run {matching}in {matrix}")
|
|
301
|
+
return 1
|
|
302
|
+
summary = f"SUMMARY {runner.passed} of {runner.runs_total} runs passed"
|
|
303
|
+
if runner.reach_total:
|
|
304
|
+
summary += f", {runner.reached} of {runner.reach_total} reach checks passed"
|
|
305
|
+
print(f"{summary}, {runner.states} distinct states in total")
|
|
306
|
+
return int(runner.failed)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
if __name__ == "__main__":
|
|
310
|
+
sys.exit(main())
|