agent-formal-verify 0.4.11 → 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.
- package/CHANGES.md +140 -0
- package/README.md +5 -3
- package/package.json +2 -1
- package/skills/formal-verify/SKILL.md +11 -13
- package/skills/formal-verify/examples/kani-template/src/lib.rs +5 -6
- package/skills/formal-verify/examples/lean-template/Model/BoundedQueue.statements +10 -45
- package/skills/formal-verify/examples/tla-template/BoundedQueue.matrix +16 -13
- package/skills/formal-verify/examples/tla-template/BoundedQueue.mutations +92 -14
- package/skills/formal-verify/examples/tla-template/BoundedQueue.tla +169 -28
- package/skills/formal-verify/references/evidence.md +1 -1
- package/skills/formal-verify/references/helpers.md +5 -4
- package/skills/formal-verify/references/lean-brief.md +2 -2
- package/skills/formal-verify/references/rust-brief.md +59 -7
- package/skills/formal-verify/references/setup.md +24 -8
- package/skills/formal-verify/references/tla-brief.md +2 -2
- package/skills/formal-verify/scripts/baseline.py +564 -66
- package/skills/formal-verify/scripts/kani-check.sh +3 -1
- package/skills/formal-verify/scripts/kani.py +130 -54
- package/skills/formal-verify/scripts/lean-analysis.lean +387 -0
- package/skills/formal-verify/scripts/lean-check.sh +6 -243
- package/skills/formal-verify/scripts/lean.py +484 -0
- package/skills/formal-verify/scripts/lean_mutations.py +195 -0
- package/skills/formal-verify/scripts/lean_records.py +25 -0
- package/skills/formal-verify/scripts/mutate.py +81 -195
- package/skills/formal-verify/scripts/processes.py +266 -0
- package/skills/formal-verify/scripts/python-tools.sh +15 -0
- package/skills/formal-verify/scripts/runner.py +56 -0
- package/skills/formal-verify/scripts/setup.sh +18 -19
- package/skills/formal-verify/scripts/storage.py +207 -0
- package/skills/formal-verify/scripts/sync.py +401 -0
- package/skills/formal-verify/scripts/tlc-matrix.sh +3 -1
- package/skills/formal-verify/scripts/tlc.py +423 -116
- package/skills/formal-verify/scripts/{tlc-trace.py → tlc_trace.py} +16 -10
- package/skills/setup/SKILL.md +1 -1
- package/skills/formal-verify/scripts/lean-mutations.lean +0 -95
- package/skills/formal-verify/scripts/lean-statements.py +0 -161
- package/skills/formal-verify/scripts/lean-tools.sh +0 -24
- package/skills/formal-verify/scripts/tlc-tools.sh +0 -47
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# Copyright (c) 2026 Michael Denyer
|
|
3
|
+
# SPDX-License-Identifier: GPL-3.0-only
|
|
4
|
+
"""Build a Lean 4 model with Lake, audit its declarations, check its frozen statements and witnesses, and replay it.
|
|
5
|
+
|
|
6
|
+
Fails when the build fails, a declaration uses sorry or rests on an axiom beyond propext, Classical.choice and
|
|
7
|
+
Quot.sound, no Lake library owns a .lean file in the project, a theorem named <Property>.witness does not state
|
|
8
|
+
that the hypotheses of <Property> hold together, or the pin's leanchecker rejects a built module on kernel replay.
|
|
9
|
+
Otherwise prints the build output, a WITNESS line for each property and PASS. A property without a witness passes,
|
|
10
|
+
and so does a pin that ships no leanchecker; the PASS line counts the first and reports the replay as unavailable
|
|
11
|
+
for the second. Named files limit the check to those sources, so agents that share a project can each check their
|
|
12
|
+
own model; a run without them checks the whole project. Needs a pin of Lean 4.20.0 or later, the first whose Lake
|
|
13
|
+
builds a module by its source path.
|
|
14
|
+
|
|
15
|
+
Usage: lean.py check <lake-project-dir> [--freeze] [<file.lean> ...]
|
|
16
|
+
The Lean checker; lean-check.sh runs it.
|
|
17
|
+
Usage: lean.py ready <lake-project-dir>
|
|
18
|
+
Installs the project's pinned toolchain unless it already runs, then reports it and the temporary directory's free
|
|
19
|
+
space as storage.py report does. setup.sh lean runs it.
|
|
20
|
+
"""
|
|
21
|
+
import signal
|
|
22
|
+
|
|
23
|
+
if __name__ == "__main__":
|
|
24
|
+
# Python's SIGINT handler raises KeyboardInterrupt, which prints a traceback when it arrives during the imports.
|
|
25
|
+
# Until runner.run installs its own handlers, the default action ends the process by the signal instead.
|
|
26
|
+
if signal.getsignal(signal.SIGINT) is signal.default_int_handler:
|
|
27
|
+
signal.signal(signal.SIGINT, signal.SIG_DFL)
|
|
28
|
+
|
|
29
|
+
import hashlib
|
|
30
|
+
import json
|
|
31
|
+
import os
|
|
32
|
+
import re
|
|
33
|
+
import shutil
|
|
34
|
+
import subprocess
|
|
35
|
+
import sys
|
|
36
|
+
import tempfile
|
|
37
|
+
from pathlib import Path
|
|
38
|
+
|
|
39
|
+
sys.dont_write_bytecode = True
|
|
40
|
+
import processes
|
|
41
|
+
import runner
|
|
42
|
+
import storage
|
|
43
|
+
from lean_records import read_record
|
|
44
|
+
|
|
45
|
+
HERE = Path(__file__).parent
|
|
46
|
+
USAGE = "usage: lean-check.sh <lake-project-dir> [--freeze] [<file.lean> ...]"
|
|
47
|
+
# Lean quotes sorry with backticks or straight quotes depending on the version.
|
|
48
|
+
SORRY = re.compile(r"(warning|error): .*: declaration uses .sorry.")
|
|
49
|
+
AUDITED = re.compile(r"AUDITED [0-9]+ declarations")
|
|
50
|
+
BLANK = re.compile(r"[ \t\n\r\f\v]*")
|
|
51
|
+
OLD_LAKE = re.compile(r"error: (unknown command 'query'|invalid script spec)")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class CheckError(Exception):
|
|
55
|
+
"""The project cannot be checked as given; the message is the FAIL line to print."""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def lines(text):
|
|
59
|
+
"""Split output into the lines a shell reads, without the empty piece after a final newline."""
|
|
60
|
+
parts = text.split("\n")
|
|
61
|
+
if parts[-1] == "":
|
|
62
|
+
parts.pop()
|
|
63
|
+
return parts
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def logical_path(path):
|
|
67
|
+
"""Make a path absolute as the shell's cd and pwd do, keeping symbolic links in it."""
|
|
68
|
+
if not os.path.isabs(path):
|
|
69
|
+
cwd = os.environ.get("PWD", "")
|
|
70
|
+
if not os.path.isabs(cwd) or not os.path.isdir(cwd) or not os.path.samefile(cwd, "."):
|
|
71
|
+
cwd = os.getcwd()
|
|
72
|
+
path = os.path.join(cwd, path)
|
|
73
|
+
return os.path.normpath(path)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# Release names that elan resolves to a release online, as a channel or as the release a repository's
|
|
77
|
+
# lean-toolchain file names.
|
|
78
|
+
CHANNELS = {"stable", "beta", "nightly", "lean-toolchain"}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def pin(project):
|
|
82
|
+
"""Return the toolchain pin of the Lake project, or raise when it has none or elan is missing."""
|
|
83
|
+
path = Path(project) / "lean-toolchain"
|
|
84
|
+
if not path.is_file():
|
|
85
|
+
raise CheckError(f"FAIL {project} has no lean-toolchain pin")
|
|
86
|
+
if shutil.which("elan") is None:
|
|
87
|
+
raise runner.Unavailable("UNAVAILABLE elan is not on PATH; install elan from https://github.com/leanprover/elan")
|
|
88
|
+
try:
|
|
89
|
+
toolchain = path.read_text(encoding="utf-8").replace("\r", "").replace("\n", "")
|
|
90
|
+
except (OSError, UnicodeDecodeError) as error:
|
|
91
|
+
raise CheckError(f"FAIL cannot read {path}: {error}") from error
|
|
92
|
+
if toolchain.rpartition(":")[2] in CHANNELS:
|
|
93
|
+
raise CheckError(f"FAIL {path} pins {toolchain}, which elan resolves to a release online; pin a release, "
|
|
94
|
+
"such as leanprover/lean4:v<version>")
|
|
95
|
+
return toolchain
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def installed(toolchain):
|
|
99
|
+
"""Whether elan lists the toolchain, under the name elan gives a pin, so that no elan run downloads it.
|
|
100
|
+
|
|
101
|
+
A pin that is an absolute path names a toolchain directory, which elan runs without installing anything.
|
|
102
|
+
"""
|
|
103
|
+
if os.path.isabs(toolchain):
|
|
104
|
+
return os.path.isdir(toolchain)
|
|
105
|
+
origin, _, channel = toolchain.rpartition(":")
|
|
106
|
+
origin = origin or "leanprover/lean4"
|
|
107
|
+
if channel[:1].isdigit():
|
|
108
|
+
channel = "v" + channel
|
|
109
|
+
if channel.startswith("nightly-") and not origin.endswith("-nightly"):
|
|
110
|
+
origin += "-nightly"
|
|
111
|
+
listed = processes.run_captured(["elan", "toolchain", "list"], encoding="utf-8", errors="replace")
|
|
112
|
+
names = {line.split()[0] for line in listed.stdout.splitlines() if line.strip()}
|
|
113
|
+
return listed.returncode == 0 and bool(names & {toolchain, f"{origin}:{channel}"})
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def pin_ready(toolchain):
|
|
117
|
+
"""Whether the toolchain is installed and runs Lake. elan run installs a missing toolchain, so check first."""
|
|
118
|
+
try:
|
|
119
|
+
return installed(toolchain) and processes.run_captured(["elan", "run", toolchain, "lake", "--version"],
|
|
120
|
+
encoding="utf-8", errors="replace").returncode == 0
|
|
121
|
+
except OSError:
|
|
122
|
+
return False
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def ready_pin(project):
|
|
126
|
+
"""Return the project's pin when its toolchain runs, or raise with the remedy."""
|
|
127
|
+
toolchain = pin(project)
|
|
128
|
+
if not pin_ready(toolchain):
|
|
129
|
+
raise runner.Unavailable(f"UNAVAILABLE {toolchain} is not ready; run bash {HERE}/setup.sh lean {project}")
|
|
130
|
+
return toolchain
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def step(command, *, merge=True, env=None):
|
|
134
|
+
"""Run one build step and return its status as a shell reports it, its stdout and its stderr.
|
|
135
|
+
|
|
136
|
+
With merge, stderr joins stdout in the order the step wrote them, and the returned stderr is empty. Lean and Lake
|
|
137
|
+
write UTF-8 whatever the locale, and the frozen records hash that text, so it is read as UTF-8.
|
|
138
|
+
"""
|
|
139
|
+
def collect(process):
|
|
140
|
+
stdout, stderr = process.communicate()
|
|
141
|
+
status = process.returncode
|
|
142
|
+
return (128 - status if status < 0 else status), stdout, stderr or ""
|
|
143
|
+
try:
|
|
144
|
+
return processes.guarded(command, collect, stdout=subprocess.PIPE,
|
|
145
|
+
stderr=subprocess.STDOUT if merge else subprocess.PIPE, encoding="utf-8",
|
|
146
|
+
errors="replace", env=env)
|
|
147
|
+
except OSError as error:
|
|
148
|
+
return 127, "", f"cannot run {command[0]}: {error}\n"
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def project_sources(project):
|
|
152
|
+
"""Every .lean file in the project outside its .lake directory, except Lake's own lakefile.lean."""
|
|
153
|
+
found = []
|
|
154
|
+
for top, directories, names in os.walk(project):
|
|
155
|
+
found += [os.path.join(top, name) for name in directories + names
|
|
156
|
+
if name.endswith(".lean") and name != "lakefile.lean"]
|
|
157
|
+
if top == project and ".lake" in directories:
|
|
158
|
+
directories.remove(".lake")
|
|
159
|
+
return sorted(found)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def layout(objects, search_path):
|
|
163
|
+
"""Name the module of each queried object and the library roots that own them, from Lake's search path."""
|
|
164
|
+
roots = sorted({Path(entry).resolve() for entry in search_path.split(os.pathsep) if entry},
|
|
165
|
+
key=lambda path: len(path.parts), reverse=True)
|
|
166
|
+
names, owners = [], set()
|
|
167
|
+
for line in objects.splitlines():
|
|
168
|
+
path = Path(line)
|
|
169
|
+
# The object itself may link into an artifact cache. Its location in the library names the module.
|
|
170
|
+
path = path.parent.resolve() / path.name
|
|
171
|
+
owner = next((root for root in roots if root in path.parents), None)
|
|
172
|
+
if owner is None or path.suffix != ".olean":
|
|
173
|
+
raise ValueError(f"cannot identify the module of {line}")
|
|
174
|
+
names.append(".".join(path.relative_to(owner).with_suffix("").parts))
|
|
175
|
+
owners.add(owner)
|
|
176
|
+
return names, sorted(owners)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def fingerprint(expression):
|
|
180
|
+
return hashlib.sha256(expression.encode("utf-8")).hexdigest()
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def declarations(audit):
|
|
184
|
+
"""Group the audit's STATEMENT records by module, with each type and value reduced to a fingerprint."""
|
|
185
|
+
modules = {}
|
|
186
|
+
for line in audit:
|
|
187
|
+
if not line.startswith("STATEMENT "):
|
|
188
|
+
continue
|
|
189
|
+
raw = json.loads(line.removeprefix("STATEMENT "))
|
|
190
|
+
record = {key: raw[key] for key in ("name", "kind", "type")}
|
|
191
|
+
record["type"] = " ".join(record["type"].split())
|
|
192
|
+
record["typeHash"] = fingerprint(raw["typeExpr"])
|
|
193
|
+
record["valueHash"] = None if raw["valueExpr"] is None else fingerprint(raw["valueExpr"])
|
|
194
|
+
modules.setdefault(raw["module"], []).append(record)
|
|
195
|
+
return modules
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def records_by_name(modules, module):
|
|
199
|
+
"""Return the module's audited records by name, refusing two declarations with one name."""
|
|
200
|
+
records = {}
|
|
201
|
+
for record in modules.get(module, []):
|
|
202
|
+
if record["name"] in records:
|
|
203
|
+
raise ValueError(f"ambiguous declaration identity {record['name']} in {module}")
|
|
204
|
+
records[record["name"]] = record
|
|
205
|
+
return records
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def check_orphans(project, out):
|
|
209
|
+
"""Report every record whose source file is gone, outside the .lake directory."""
|
|
210
|
+
failed = False
|
|
211
|
+
for path in sorted(project.rglob("*.statements")):
|
|
212
|
+
if ".lake" in path.relative_to(project).parts or path.with_suffix(".lean").is_file():
|
|
213
|
+
continue
|
|
214
|
+
record = read_record(path)
|
|
215
|
+
out(f"FROZEN {path}: source file is missing")
|
|
216
|
+
for declaration in record["declarations"]:
|
|
217
|
+
out(f"FROZEN {declaration['name']}: statement changed (source deleted)")
|
|
218
|
+
failed = True
|
|
219
|
+
return int(failed)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def freeze_statements(toolchain, modules, sources, out):
|
|
223
|
+
"""Record every source's statements, writing none unless all of them can be recorded."""
|
|
224
|
+
pending = []
|
|
225
|
+
for module, source in sources:
|
|
226
|
+
records = records_by_name(modules, module)
|
|
227
|
+
if not records:
|
|
228
|
+
raise ValueError(f"no declaration records for {source}")
|
|
229
|
+
record = {"format": 1, "toolchain": toolchain, "module": module,
|
|
230
|
+
"declarations": [records[name] for name in sorted(records)]}
|
|
231
|
+
pending.append((source.with_suffix(".statements"), json.dumps(record, ensure_ascii=False, indent=2) + "\n"))
|
|
232
|
+
for path, contents in pending:
|
|
233
|
+
runner.atomic_write(path, contents)
|
|
234
|
+
out(f"FROZEN {path}: statements recorded; proofs not checked")
|
|
235
|
+
return 0
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def check_statements(toolchain, modules, sources, out):
|
|
239
|
+
"""Compare every recorded source's statements with the audit; a source without a record passes."""
|
|
240
|
+
failed = False
|
|
241
|
+
for module, source in sources:
|
|
242
|
+
path = source.with_suffix(".statements")
|
|
243
|
+
if not path.exists():
|
|
244
|
+
continue
|
|
245
|
+
records = records_by_name(modules, module)
|
|
246
|
+
frozen = read_record(path)
|
|
247
|
+
if frozen["toolchain"] != toolchain:
|
|
248
|
+
out(f"FROZEN {path}: toolchain changed from {frozen['toolchain']} to {toolchain}; review and run --freeze")
|
|
249
|
+
failed = True
|
|
250
|
+
continue
|
|
251
|
+
if frozen["module"] != module:
|
|
252
|
+
raise ValueError(f"{path}: expected module {module}, found {frozen['module']}")
|
|
253
|
+
changed = 0
|
|
254
|
+
for old in frozen["declarations"]:
|
|
255
|
+
if old["kind"] == "opaque" and old["valueHash"] is None:
|
|
256
|
+
out(f"FROZEN {old['name']}: opaque body was not recorded; review the definition and run --freeze")
|
|
257
|
+
failed = True
|
|
258
|
+
continue
|
|
259
|
+
new = records.get(old["name"])
|
|
260
|
+
if new is not None and all(old[key] == new[key] for key in ("kind", "typeHash", "valueHash")):
|
|
261
|
+
continue
|
|
262
|
+
changed += 1
|
|
263
|
+
out(f"FROZEN {old['name']}: statement changed")
|
|
264
|
+
out(f" old: {old['type']}")
|
|
265
|
+
out(f" new: {new['type'] if new else '(deleted)'}")
|
|
266
|
+
if new and old["valueHash"] != new["valueHash"]:
|
|
267
|
+
out(" definition value changed")
|
|
268
|
+
if changed == len(frozen["declarations"]):
|
|
269
|
+
out(f"FROZEN {path}: every recorded declaration changed; review the model and toolchain before --freeze")
|
|
270
|
+
failed |= changed > 0
|
|
271
|
+
return int(failed)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def statements(action):
|
|
275
|
+
"""Run a frozen-record step on a line sink and return its status and output; an unreadable record fails the step."""
|
|
276
|
+
output = []
|
|
277
|
+
try:
|
|
278
|
+
status = action(output.append)
|
|
279
|
+
except (OSError, ValueError, KeyError, TypeError) as error:
|
|
280
|
+
output.append(f"FAIL statements: {error}")
|
|
281
|
+
status = 1
|
|
282
|
+
return status, output
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def check(project, files, freeze, out):
|
|
286
|
+
"""Check a Lake project, or only the named sources in it, writing each output line to out; return the exit status."""
|
|
287
|
+
if not (Path(project) / "lakefile.toml").is_file() and not (Path(project) / "lakefile.lean").is_file():
|
|
288
|
+
out(f"FAIL {project} has no lakefile")
|
|
289
|
+
return 1
|
|
290
|
+
project = logical_path(project)
|
|
291
|
+
try:
|
|
292
|
+
toolchain = ready_pin(project)
|
|
293
|
+
except CheckError as error:
|
|
294
|
+
out(str(error))
|
|
295
|
+
return 1
|
|
296
|
+
with tempfile.TemporaryDirectory(prefix="lean-check.", dir=storage.ensure_temp_root()) as temporary:
|
|
297
|
+
storage.warn_runtime()
|
|
298
|
+
return checked(project, toolchain, files, freeze, out, Path(temporary))
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def checked(project, toolchain, files, freeze, out, work):
|
|
302
|
+
"""Build, audit, compare frozen statements, check witnesses and replay, in that order, stopping at the first failure."""
|
|
303
|
+
lake = ["elan", "run", toolchain, "lake", "--dir", project]
|
|
304
|
+
# Lake builds a module named by its source path and rejects a path that no library owns, so naming every
|
|
305
|
+
# source leaves no file unchecked. Its query command prints the .olean of each, which names the modules to
|
|
306
|
+
# audit without picking up a module left in the build directory by a deleted source.
|
|
307
|
+
scope = project
|
|
308
|
+
if files:
|
|
309
|
+
scope = f"{project} ({' '.join(files)} only)"
|
|
310
|
+
sources = [source if source.startswith("/") else f"{project}/{source}" for source in files]
|
|
311
|
+
for source in sources:
|
|
312
|
+
if not os.path.isfile(source):
|
|
313
|
+
out(f"FAIL {source} does not exist")
|
|
314
|
+
return 1
|
|
315
|
+
else:
|
|
316
|
+
if not freeze:
|
|
317
|
+
status, output = statements(lambda sink: check_orphans(Path(project), sink))
|
|
318
|
+
if status:
|
|
319
|
+
out(f"FAIL {scope}: frozen model sources are missing or their records are invalid")
|
|
320
|
+
for line in output:
|
|
321
|
+
out(line)
|
|
322
|
+
return status
|
|
323
|
+
sources = project_sources(project)
|
|
324
|
+
if not sources:
|
|
325
|
+
out(f"FAIL {project} has no .lean file to check")
|
|
326
|
+
return 1
|
|
327
|
+
status, objects, log = step([*lake, "query", *(f"{source}:olean" for source in sources)], merge=False)
|
|
328
|
+
log = lines(log)
|
|
329
|
+
sorries = [line for line in log if SORRY.match(line)]
|
|
330
|
+
|
|
331
|
+
# lean-analysis.lean audit imports those modules and collects the axioms under each of their declarations, so
|
|
332
|
+
# it needs no #print axioms line in the model. It skips the compiler's auxiliary declarations, which older
|
|
333
|
+
# pins store with opaque placeholders that would read as axioms.
|
|
334
|
+
audit_status, audit, modules, libraries = 0, [], [], []
|
|
335
|
+
if status == 0:
|
|
336
|
+
# The module of each source, in source order, for the audit's imports and the frozen records.
|
|
337
|
+
# Lake writes notices to stderr, such as one for a project with both lakefiles, so only stdout is the path.
|
|
338
|
+
found, search_path, errors = step([*lake, "env", "printenv", "LEAN_PATH"], merge=False)
|
|
339
|
+
try:
|
|
340
|
+
if found:
|
|
341
|
+
raise ValueError(f"{search_path}{errors}lake env exit {found}")
|
|
342
|
+
modules, libraries = layout(objects, search_path.rstrip("\n"))
|
|
343
|
+
except (ValueError, OSError) as error:
|
|
344
|
+
out(f"FAIL {scope}: cannot resolve Lake's module layout")
|
|
345
|
+
for line in lines(f"{error}\n"):
|
|
346
|
+
out(line)
|
|
347
|
+
return 1
|
|
348
|
+
module_list = work / "modules"
|
|
349
|
+
module_list.write_text("".join(name + "\n" for name in modules), encoding="utf-8")
|
|
350
|
+
audit_status, output, _ = step([*lake, "env", "lean", "--run", str(HERE / "lean-analysis.lean"),
|
|
351
|
+
"audit", *(["--freeze"] if freeze else []), str(module_list)])
|
|
352
|
+
audit = lines(output)
|
|
353
|
+
if not any(AUDITED.fullmatch(line) for line in audit):
|
|
354
|
+
audit_status = 1
|
|
355
|
+
if "AUDITED 0 declarations" in audit:
|
|
356
|
+
frozen = any(os.path.isfile(source.removesuffix(".lean") + ".statements") for source in sources)
|
|
357
|
+
if freeze or not frozen:
|
|
358
|
+
audit_status = 1
|
|
359
|
+
axioms = [line for line in audit if line.startswith("AXIOMS ")]
|
|
360
|
+
|
|
361
|
+
if status or not freeze and sorries or axioms or audit_status:
|
|
362
|
+
out(f"FAIL {scope}: {len(sorries)} unfinished proofs (sorry), {len(axioms)} declarations on an added axiom, "
|
|
363
|
+
f"lake exit {status}")
|
|
364
|
+
for line in sorries + axioms:
|
|
365
|
+
out(line)
|
|
366
|
+
if status:
|
|
367
|
+
for line in [line for line in log if not BLANK.fullmatch(line)][-40:]:
|
|
368
|
+
out(line)
|
|
369
|
+
if any(line.startswith("error: unknown module source path") for line in log):
|
|
370
|
+
out("no library owns that file; import it from a built module or move it out of the project")
|
|
371
|
+
if any(OLD_LAKE.match(line) for line in log):
|
|
372
|
+
out(f"{toolchain} cannot build a module by its source path; pin Lean 4.20.0 or later")
|
|
373
|
+
if audit_status:
|
|
374
|
+
out("the axiom audit did not run or found no declarations:")
|
|
375
|
+
for line in [line for line in audit if not BLANK.fullmatch(line) and not line.startswith("IMPORTED ")][-40:]:
|
|
376
|
+
out(line)
|
|
377
|
+
if any("environment already contains" in line for line in audit):
|
|
378
|
+
out("two modules declare the same name; put each model in a namespace of its own")
|
|
379
|
+
return 1
|
|
380
|
+
def compare(sink):
|
|
381
|
+
if len(modules) != len(sources):
|
|
382
|
+
raise ValueError("Lake did not return one module per source")
|
|
383
|
+
action = freeze_statements if freeze else check_statements
|
|
384
|
+
return action(toolchain, declarations(audit), zip(modules, map(Path, sources)), sink)
|
|
385
|
+
statement_status, output = statements(compare)
|
|
386
|
+
if statement_status:
|
|
387
|
+
out(f"FAIL {scope}: frozen statements differ or could not be checked")
|
|
388
|
+
for line in output:
|
|
389
|
+
out(line)
|
|
390
|
+
return statement_status
|
|
391
|
+
# #eval output arrives as info blocks that can span lines.
|
|
392
|
+
for line in output + [line for line in log if not BLANK.fullmatch(line)]:
|
|
393
|
+
out(line)
|
|
394
|
+
if freeze:
|
|
395
|
+
return 0
|
|
396
|
+
|
|
397
|
+
def witnesses(kind):
|
|
398
|
+
return sum(line.startswith(f"WITNESS {kind} ") for line in audit)
|
|
399
|
+
failed = witnesses("failed")
|
|
400
|
+
if failed:
|
|
401
|
+
out(f"FAIL {scope}: {failed} witnesses do not state their property's hypotheses")
|
|
402
|
+
for line in audit:
|
|
403
|
+
if line.startswith("WITNESS "):
|
|
404
|
+
out(line)
|
|
405
|
+
if failed:
|
|
406
|
+
return 1
|
|
407
|
+
|
|
408
|
+
# The build trusts a declaration that a command adds to the environment without a kernel check. leanchecker
|
|
409
|
+
# replays every declaration of the built modules through the kernel and rejects it. Use its exact-module
|
|
410
|
+
# replayer rather than its CLI's prefix search, which also finds deleted sources' cached objects. A named
|
|
411
|
+
# module rests on the project modules it imports, so replay those too.
|
|
412
|
+
prefix = processes.guarded(["elan", "run", toolchain, "lean", "--print-prefix"],
|
|
413
|
+
lambda process: process.communicate()[0], stdout=subprocess.PIPE,
|
|
414
|
+
encoding="utf-8", errors="replace")
|
|
415
|
+
prefix = prefix.rstrip("\n")
|
|
416
|
+
replay = "unavailable"
|
|
417
|
+
if os.access(f"{prefix}/bin/leanchecker", os.X_OK):
|
|
418
|
+
imported = [line.removeprefix("IMPORTED ") for line in audit if line.startswith("IMPORTED ")]
|
|
419
|
+
replayed = set(modules) | {module for module in imported
|
|
420
|
+
if any((library / (module.replace(".", "/") + ".olean")).is_file() for library in libraries)}
|
|
421
|
+
replay_list = work / "replay-modules"
|
|
422
|
+
replay_list.write_text("".join(module + "\n" for module in sorted(replayed)), encoding="utf-8")
|
|
423
|
+
replay_status, output, _ = step([*lake, "env", "lean", str(HERE / "lean-replay.lean")],
|
|
424
|
+
env=os.environ | {"AFV_REPLAY_MODULES": str(replay_list)})
|
|
425
|
+
replay = "failed" if replay_status else "passed"
|
|
426
|
+
if replay == "failed":
|
|
427
|
+
out(f"FAIL {scope}: kernel replay rejected a built module")
|
|
428
|
+
for line in lines(output):
|
|
429
|
+
out(line)
|
|
430
|
+
return 1
|
|
431
|
+
out(f"REPLAYED {sum(line.startswith('replaying ') for line in lines(output))} modules through the Lean kernel")
|
|
432
|
+
else:
|
|
433
|
+
out(f"UNAVAILABLE kernel replay: {toolchain} ships no leanchecker")
|
|
434
|
+
declared = "\n".join(line.split(" ")[1] for line in audit if line.startswith("AUDITED "))
|
|
435
|
+
out(f"PASS {scope}: {declared} declarations checked, no unfinished proof (sorry), no added axiom, kernel replay "
|
|
436
|
+
f"{replay}, {witnesses('checked')} witnesses checked, {witnesses('absent')} absent, "
|
|
437
|
+
f"{witnesses('unavailable')} unavailable, {witnesses('no-hypotheses')} properties without hypotheses")
|
|
438
|
+
return 0
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def ready(project):
|
|
442
|
+
"""Install the project's pinned toolchain unless it already runs, then report it and the temporary storage."""
|
|
443
|
+
try:
|
|
444
|
+
toolchain = pin(project)
|
|
445
|
+
except CheckError as error:
|
|
446
|
+
print(error)
|
|
447
|
+
return 1
|
|
448
|
+
if not pin_ready(toolchain):
|
|
449
|
+
status, log, _ = step(["elan", "toolchain", "install", toolchain])
|
|
450
|
+
log = log.rstrip("\n")
|
|
451
|
+
if status:
|
|
452
|
+
raise runner.Unavailable(f"UNAVAILABLE cannot install {toolchain}; run elan toolchain install {toolchain}\n{log}")
|
|
453
|
+
if not pin_ready(toolchain):
|
|
454
|
+
raise runner.Unavailable(f"UNAVAILABLE {toolchain} does not run after installation; "
|
|
455
|
+
f"check elan toolchain list and reinstall it\n{log}")
|
|
456
|
+
if log:
|
|
457
|
+
print(log)
|
|
458
|
+
print(f"READY Lean {toolchain}")
|
|
459
|
+
storage.report()
|
|
460
|
+
return 0
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def main():
|
|
464
|
+
# Lean's output is UTF-8 whatever the locale; pass it through unchanged, as the shell checker did. Each line goes
|
|
465
|
+
# out as it is written, so a killed or piped run keeps what it printed, and a path that the locale could not
|
|
466
|
+
# decode goes out as its original bytes.
|
|
467
|
+
sys.stdout.reconfigure(encoding="utf-8", errors="surrogateescape", line_buffering=True)
|
|
468
|
+
command, *arguments = sys.argv[1:] or [""]
|
|
469
|
+
if command == "ready" and len(arguments) == 1:
|
|
470
|
+
return ready(arguments[0])
|
|
471
|
+
if command != "check" or not arguments:
|
|
472
|
+
print(USAGE)
|
|
473
|
+
return 2
|
|
474
|
+
project, *files = arguments
|
|
475
|
+
freeze = files[:1] == ["--freeze"]
|
|
476
|
+
files = files[freeze:]
|
|
477
|
+
if any(name.startswith("--") for name in files):
|
|
478
|
+
print("usage: --freeze must precede source files")
|
|
479
|
+
return 2
|
|
480
|
+
return check(project, files, freeze, print)
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
if __name__ == "__main__":
|
|
484
|
+
runner.run(main)
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
# Copyright (c) 2026 Michael Denyer
|
|
2
|
+
# SPDX-License-Identifier: GPL-3.0-only
|
|
3
|
+
"""Attribute Lean mutation failures to the original model's frozen theorems and anonymous checks."""
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
from collections import Counter
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
sys.dont_write_bytecode = True
|
|
11
|
+
import lean
|
|
12
|
+
import processes
|
|
13
|
+
from lean_records import read_record
|
|
14
|
+
|
|
15
|
+
HERE = Path(__file__).resolve().parent
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AnalysisError(Exception):
|
|
19
|
+
"""The original model, its frozen declarations or the pinned frontend could not be read."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, diagnostic, status=1):
|
|
22
|
+
super().__init__(diagnostic)
|
|
23
|
+
self.status = status
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _checked_record(model, project):
|
|
27
|
+
"""Check the original once with the same frozen declaration audit as lean-check."""
|
|
28
|
+
path = model.with_suffix(".statements")
|
|
29
|
+
if not path.is_file():
|
|
30
|
+
raise AnalysisError(f"FAIL {path} is missing; freeze the model with lean-check.sh --freeze before checking its mutations")
|
|
31
|
+
try:
|
|
32
|
+
record = read_record(path)
|
|
33
|
+
except (OSError, ValueError, KeyError, TypeError) as error:
|
|
34
|
+
raise AnalysisError(f"FAIL invalid statements record {path}: {error}") from error
|
|
35
|
+
output = []
|
|
36
|
+
status = lean.check(str(project), [str(model)], False, output.append)
|
|
37
|
+
if status:
|
|
38
|
+
raise AnalysisError("\n".join(output).strip(), status)
|
|
39
|
+
return record
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _analyze(model, project, toolchain):
|
|
43
|
+
"""Get Lean's declaration identities and error positions, never infer them from source text."""
|
|
44
|
+
done = processes.run_captured(["elan", "run", toolchain, "lake", "--dir", str(project), "env", "lean", "--run",
|
|
45
|
+
str(HERE / "lean-analysis.lean"), "analyze", str(model)],
|
|
46
|
+
encoding="utf-8", errors="replace")
|
|
47
|
+
output = done.stdout + done.stderr
|
|
48
|
+
records = [line.removeprefix("AFV_LEAN ") for line in done.stdout.splitlines() if line.startswith("AFV_LEAN ")]
|
|
49
|
+
if done.returncode != 0 or len(records) != 1:
|
|
50
|
+
raise AnalysisError(f"FAIL Lean declaration analysis did not complete:\n{output.strip()}")
|
|
51
|
+
try:
|
|
52
|
+
analysis = json.loads(records[0])
|
|
53
|
+
for field in ("declarations", "commands", "errors"):
|
|
54
|
+
if not isinstance(analysis[field], list):
|
|
55
|
+
raise TypeError(f"{field} must be a list")
|
|
56
|
+
except (ValueError, KeyError, TypeError) as error:
|
|
57
|
+
raise AnalysisError(f"FAIL invalid Lean declaration analysis: {error}") from error
|
|
58
|
+
return analysis
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass
|
|
62
|
+
class _Check:
|
|
63
|
+
start: list
|
|
64
|
+
end: list
|
|
65
|
+
label: str
|
|
66
|
+
problem: str
|
|
67
|
+
witness: bool = False
|
|
68
|
+
|
|
69
|
+
def contains(self, position):
|
|
70
|
+
return self.start <= position < self.end
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _command_sites(source, commands, edit_start, edit_end):
|
|
74
|
+
"""Identify anonymous checks by the source that survives the edit on either side."""
|
|
75
|
+
line_starts = [0]
|
|
76
|
+
for line in source.split("\n"):
|
|
77
|
+
line_starts.append(line_starts[-1] + len(line) + 1)
|
|
78
|
+
for cmd in commands:
|
|
79
|
+
if not cmd["property"]:
|
|
80
|
+
continue
|
|
81
|
+
first, last = (line_starts[line - 1] + column for line, column in (cmd["start"], cmd["end"]))
|
|
82
|
+
if last <= edit_start:
|
|
83
|
+
site = ("before", first)
|
|
84
|
+
elif first >= edit_end:
|
|
85
|
+
site = ("after", first - edit_end)
|
|
86
|
+
else:
|
|
87
|
+
# An edit can split a check in two. Either surviving endpoint alone could name the new check.
|
|
88
|
+
site = ("restated", source[first:last])
|
|
89
|
+
yield (cmd["property"], site), cmd, first
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _compare_commands(model, before, mutation, after):
|
|
93
|
+
start = mutation.original.index(mutation.old)
|
|
94
|
+
end = start + len(mutation.new)
|
|
95
|
+
originals = {}
|
|
96
|
+
for site, cmd, _ in _command_sites(mutation.original, before, start, start + len(mutation.old)):
|
|
97
|
+
originals.setdefault(site, []).append(cmd["statement"])
|
|
98
|
+
commands = list(_command_sites(mutation.source, after, start, end))
|
|
99
|
+
counts = Counter(site for site, _, _ in commands)
|
|
100
|
+
line_shift = mutation.old.count("\n") - mutation.new.count("\n")
|
|
101
|
+
edit_line = mutation.original.count("\n", 0, start) + 1
|
|
102
|
+
for site, cmd, offset in commands:
|
|
103
|
+
candidates = originals.get(site, [])
|
|
104
|
+
if len(candidates) != 1 or counts[site] != 1:
|
|
105
|
+
reason = f"cannot match this {cmd['property']} to a single original check"
|
|
106
|
+
elif cmd["statement"] is None or candidates[0] != cmd["statement"]:
|
|
107
|
+
reason = "the mutation changes its statement"
|
|
108
|
+
else:
|
|
109
|
+
reason = ""
|
|
110
|
+
line = cmd["start"][0]
|
|
111
|
+
if start <= offset < end:
|
|
112
|
+
location = f"{edit_line} (mutation replacement)"
|
|
113
|
+
else:
|
|
114
|
+
location = str(line + line_shift if offset >= end else line)
|
|
115
|
+
yield _Check(cmd["start"], cmd["end"], f"{cmd['property']} at {model}:{location}", reason)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _position(source, offset):
|
|
119
|
+
"""Return the [line, column] that Lean reports for a character offset into source."""
|
|
120
|
+
return [source.count("\n", 0, offset) + 1, offset - source.rfind("\n", 0, offset) - 1]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _is_witness(name, theorem_names):
|
|
124
|
+
parent, _, last = name.rpartition(".")
|
|
125
|
+
return last == "witness" and parent in theorem_names
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class OriginalChecks:
|
|
129
|
+
"""Attribute errors using the original source and the two frontend analyses."""
|
|
130
|
+
|
|
131
|
+
def __init__(self, path, frozen, original):
|
|
132
|
+
self._path = path
|
|
133
|
+
if original["errors"]:
|
|
134
|
+
raise AnalysisError(f"FAIL unmutated Lean model does not elaborate: {original['errors'][0]['data']}")
|
|
135
|
+
theorems = [decl for decl in original["declarations"] if decl["theorem"]]
|
|
136
|
+
names = {decl["name"] for decl in theorems}
|
|
137
|
+
self.targets = {"theorem " + decl["name"] for decl in theorems
|
|
138
|
+
if not decl["private"] and decl["name"] in frozen and not _is_witness(decl["name"], names)}
|
|
139
|
+
self._theorems = {(decl["name"], decl["type"]) for decl in theorems}
|
|
140
|
+
self._commands = original["commands"]
|
|
141
|
+
|
|
142
|
+
def _theorem_checks(self, declarations, mutation):
|
|
143
|
+
start = mutation.original.index(mutation.old)
|
|
144
|
+
edit_start = _position(mutation.source, start)
|
|
145
|
+
edit_end = _position(mutation.source, start + len(mutation.new))
|
|
146
|
+
theorems = [decl for decl in declarations if decl["theorem"]]
|
|
147
|
+
names = {decl["name"] for decl in theorems}
|
|
148
|
+
for decl in theorems:
|
|
149
|
+
name = decl["name"]
|
|
150
|
+
if (name, decl["type"]) not in self._theorems:
|
|
151
|
+
problem = "the mutation changes its statement"
|
|
152
|
+
elif decl["start"] <= edit_end and edit_start <= decl["end"]:
|
|
153
|
+
# A broken proof shows the model changed only when the edit lies outside that theorem.
|
|
154
|
+
problem = "the mutation edits this theorem"
|
|
155
|
+
else:
|
|
156
|
+
problem = ""
|
|
157
|
+
yield _Check(decl["start"], decl["end"], "theorem " + name, problem, _is_witness(name, names))
|
|
158
|
+
|
|
159
|
+
def broken_checks(self, mutation, copy, analysis):
|
|
160
|
+
"""Return the original checks that fail, or raise ValueError if any error cannot be attributed."""
|
|
161
|
+
if not analysis["errors"]:
|
|
162
|
+
return []
|
|
163
|
+
theorems = list(self._theorem_checks(analysis["declarations"], mutation))
|
|
164
|
+
commands = list(_compare_commands(self._path, self._commands, mutation, analysis["commands"]))
|
|
165
|
+
failed = []
|
|
166
|
+
for error in analysis["errors"]:
|
|
167
|
+
position = [error["pos"]["line"], error["pos"]["column"]]
|
|
168
|
+
where = f"{error['fileName']}:{position[0]}:{position[1]}: {error['data']}"
|
|
169
|
+
checks = [check for check in theorems if check.contains(position)]
|
|
170
|
+
if not checks:
|
|
171
|
+
checks = [check for check in commands if check.contains(position)]
|
|
172
|
+
for check in checks:
|
|
173
|
+
if check.problem:
|
|
174
|
+
raise ValueError(f"{check.label}: {check.problem}, so this error does not show its proof or check failing\n{where}")
|
|
175
|
+
if error["fileName"] != str(copy) or not checks:
|
|
176
|
+
raise ValueError(where)
|
|
177
|
+
for check in checks:
|
|
178
|
+
if not check.witness and check.label not in failed:
|
|
179
|
+
failed.append(check.label)
|
|
180
|
+
return failed
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def prepare(model, project):
|
|
184
|
+
"""Elaborate the original once and return its coverage targets and a check for each mutant."""
|
|
185
|
+
record = _checked_record(model, project)
|
|
186
|
+
pin = record["toolchain"]
|
|
187
|
+
frozen = {entry["name"] for entry in record["declarations"] if entry["kind"] == "theorem"}
|
|
188
|
+
original = OriginalChecks(model, frozen, _analyze(model, project, pin))
|
|
189
|
+
|
|
190
|
+
def check(mutation, work):
|
|
191
|
+
copy = work / model.name
|
|
192
|
+
copy.write_text(mutation.source, encoding="utf-8")
|
|
193
|
+
return original.broken_checks(mutation, copy, _analyze(copy, project, pin))
|
|
194
|
+
|
|
195
|
+
return original.targets, check
|