Repository navigation
Expand file tree
/
Copy pathverify.py
More file actions
311 lines (282 loc) · 10.2 KB
/
Copy pathverify.py
File metadata and controls
311 lines (282 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
"""Run the project verification gate on a prepared local or hosted runner."""
import argparse
import glob
import json
import os
import shlex
import shutil
import stat
import subprocess
import sys
from datetime import UTC, datetime
from hashlib import file_digest, sha256
from pathlib import Path
from tempfile import mkdtemp
from xml.etree import ElementTree
from pydantic import JsonValue, TypeAdapter
from scripts.check_receipt import Receipt
from src.synthesis.software import load_software
from src.synthesis.source_lineage import ROOT, source_hashes
COVERAGE_FLOOR = 90
class _Arguments(argparse.Namespace):
mode: str = ""
pytest_temp: Path | None = None
def _project_paths(group: str) -> list[str]:
paths = TypeAdapter(dict[str, list[str]]).validate_json(
(ROOT / "config/verification_paths.json").read_bytes()
)[group]
result: list[str] = []
for path in paths:
matches = sorted(glob.glob(path, root_dir=ROOT))
if not matches:
raise ValueError(f"Verification path has no matches: {path}")
result.extend(matches)
return result
def _stage(
name: str, command: list[str], env: dict[str, str], logs: Path | None
) -> None:
print(f"Running {name}", flush=True)
if logs is None:
_ = subprocess.run(
command, cwd=ROOT, env=env, stdin=subprocess.DEVNULL, check=True
)
else:
log = logs / f"{name}.txt"
with log.open("xb") as stream:
result = subprocess.run(
command,
cwd=ROOT,
env=env,
stdin=subprocess.DEVNULL,
stdout=stream,
stderr=subprocess.STDOUT,
check=False,
)
if result.returncode:
raise RuntimeError(f"{name} exited {result.returncode}; see {log}")
print(f"Passed {name}", flush=True)
def _quality(
env: dict[str, str], logs: Path | None, *, types: bool
) -> tuple[list[str], str]:
expected_uv = next(
tool.version for tool in load_software().tools if tool.name == "uv"
)
uv = shutil.which("uv", path=env.get("PATH"))
if uv is None:
raise RuntimeError(f"Install the pinned uv {expected_uv} and place it on PATH")
version = subprocess.run(
[uv, "--version"],
cwd=ROOT,
env=env,
stdin=subprocess.DEVNULL,
capture_output=True,
text=True,
check=True,
timeout=30,
).stdout.strip()
if version.split()[:2] != ["uv", expected_uv]:
raise RuntimeError(f"Expected uv {expected_uv}; observed {version}")
print(version, flush=True)
style = _project_paths("style")
steps = [
(
"lock",
[
uv,
"lock",
"--check",
"--offline",
"--no-build",
"--no-python-downloads",
"--python",
sys.executable,
],
),
("lint", [sys.executable, "-m", "ruff", "check", *style]),
("format", [sys.executable, "-m", "ruff", "format", "--check", *style]),
]
if types:
steps.append(
(
"types",
[
sys.executable,
"-m",
"basedpyright",
"--baselinemode=lock",
"--pythonpath",
sys.executable,
*_project_paths("types"),
],
)
)
for name, command in steps:
_stage(name, command, env, logs)
return [name for name, _ in steps], version
def _worktree_hash(paths: set[str]) -> str:
entries: list[tuple[str, str, str]] = []
for name in sorted(paths):
path = ROOT / name
try:
mode = path.lstat().st_mode
except FileNotFoundError:
entries.append((name, "missing", ""))
continue
if stat.S_ISLNK(mode):
entries.append((name, "symlink", os.readlink(path)))
elif stat.S_ISREG(mode):
entries.append(
(name, "executable" if mode & 0o111 else "file", _digest(path))
)
else:
raise ValueError(f"Unsupported worktree entry: {name}")
return _json_digest(entries)
def _json_digest(value: object) -> str:
return sha256(
json.dumps(value, sort_keys=True, separators=(",", ":")).encode()
).hexdigest()
def _checkout() -> dict[str, str | bool]:
def git(*args: str) -> bytes:
return subprocess.run(
["git", "--no-optional-locks", *args],
cwd=ROOT,
stdin=subprocess.DEVNULL,
capture_output=True,
check=True,
timeout=30,
).stdout
head, tree = git("rev-parse", "HEAD", "HEAD^{tree}").decode("ascii").splitlines()
paths = git("ls-files", "-z", "--cached", "--others", "--exclude-standard")
return {
"head": head,
"head_tree": tree,
"dirty": bool(git("status", "--porcelain", "--untracked-files=all")),
"worktree_sha256": _worktree_hash(
{os.fsdecode(path) for path in paths.split(b"\0") if path}
),
}
def _fresh_output(env: dict[str, str]) -> Path:
value = env.get("FEP_OUTPUT_DIR")
if not value:
raise ValueError("Set FEP_OUTPUT_DIR to a new retained release directory")
requested = Path(value)
output = requested.resolve()
if requested.is_symlink() or (
output.is_relative_to(ROOT) and not output.is_relative_to(ROOT / "output")
):
raise ValueError(
"Release output must be outside the source tree or under output/"
)
output.mkdir(parents=True, exist_ok=False)
return output
def _digest(path: Path) -> str:
with path.open("rb") as stream:
return file_digest(stream, "sha256").hexdigest()
def _release(env: dict[str, str]) -> None:
checkout, sources = _checkout(), dict(source_hashes())
output = _fresh_output(env)
logs = output / "verification"
logs.mkdir()
env["FEP_OUTPUT_DIR"] = str(output)
stages, uv_version = _quality(env, logs, types=True)
# Reproduction runs the full suite, native studies, Lean, renderer and both checkers.
_stage("reproduction", [sys.executable, "-m", "scripts.reproduce"], env, logs)
if _checkout() != checkout or dict(source_hashes()) != sources:
raise RuntimeError("Checkout or scientific sources changed during verification")
reproduction = Receipt.model_validate_json((output / "receipt.json").read_bytes())
if not reproduction.success or reproduction.local_sources != sources:
raise RuntimeError("Reproduction receipt does not bind the verified sources")
artifacts = {
name: _digest(output / name)
for name in ("receipt.json", "manuscript.pdf", "tests.xml", "coverage.json")
}
for name in ("manuscript.pdf", "tests.xml", "coverage.json"):
if reproduction.outputs[name] != artifacts[name]:
raise RuntimeError(f"Release artifact changed after reproduction: {name}")
suites = list(ElementTree.parse(output / "tests.xml").iter("testsuite"))
total = sum(int(suite.get("tests", "0")) for suite in suites)
coverage_report = TypeAdapter(dict[str, JsonValue]).validate_json(
(output / "coverage.json").read_bytes()
)
totals = coverage_report["totals"]
if not isinstance(totals, dict):
raise TypeError("Expected a coverage totals object")
coverage = totals["percent_covered"]
if (
total == 0
or any(
int(suite.get(key, "0"))
for suite in suites
for key in ("failures", "errors", "skipped")
)
or not isinstance(coverage, (int, float))
or not COVERAGE_FLOOR <= coverage <= 100
):
raise RuntimeError(
"Release requires a complete passing test suite and sufficient coverage"
)
record = {
"schema_version": 1,
"success": True,
"checkout": checkout,
"source_sha256": _json_digest(sources),
"stages": [*stages, "reproduction"],
"uv_version": uv_version,
"tests": total,
"coverage_percent": coverage,
"artifacts": artifacts,
"logs": {
str(log.relative_to(output)): _digest(log)
for log in sorted(logs.glob("*.txt"))
},
"completed_at": datetime.now(UTC).isoformat(),
}
pending = output / ".release-gate.pending"
with pending.open("x", encoding="utf-8") as stream:
json.dump(record, stream, indent=2, allow_nan=False)
_ = stream.write("\n")
receipt = output / "release-gate.json"
_ = pending.rename(receipt)
print(f"Release gate: {receipt}")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
_ = parser.add_argument("mode", choices=("numerical", "release"))
_ = parser.add_argument(
"--pytest-temp", type=Path, help="New directory for pytest scratch"
)
options = parser.parse_args(namespace=_Arguments())
env = os.environ.copy()
# A user-wide pytest filter must not narrow the release suite.
_ = env.pop("PYTEST_ADDOPTS", None)
_ = env.pop("PYTEST_PLUGINS", None)
if options.pytest_temp is not None:
scratch = options.pytest_temp
scratch.mkdir(exist_ok=False)
env["PYTEST_ADDOPTS"] = shlex.join(
["--basetemp", str(scratch.resolve() / "pytest")]
)
if options.mode == "release":
_release(env)
else:
selected = (ROOT / ".python-version").read_text().strip().split(".")[:2]
_ = _quality(env, None, types=tuple(map(int, selected)) == sys.version_info[:2])
if "COVERAGE_FILE" not in env:
directory = ROOT / "output"
directory.mkdir(exist_ok=True)
coverage_root = Path(mkdtemp(prefix="numerical-", dir=directory))
env["COVERAGE_FILE"] = str(coverage_root / ".coverage")
_stage(
"tests",
[
sys.executable,
"-m",
"pytest",
"tests/",
"--cov=src",
f"--cov-fail-under={COVERAGE_FLOOR}",
],
env,
None,
)
if __name__ == "__main__":
main()