Repository navigation
Expand file tree
/
Copy pathrelease_check.py
More file actions
467 lines (416 loc) · 17.5 KB
/
Copy pathrelease_check.py
File metadata and controls
467 lines (416 loc) · 17.5 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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
"""Run the canonical ActiveBlockference gate, one arm at a time.
The release gate is one entry point with separately runnable arms so a
contributor can run the arm they need without paying for the whole gate. Every
arm is the exact command CI runs; CI invokes these arms instead of keeping a
second copy of any command.
Arms:
* ``lint`` -- Ruff over the package, tests, ``GRTs``, and scripts.
* ``types`` -- mypy over the package at the ``requires-python`` floor.
* ``test`` -- fast pytest selection (``-m "not slow"``), no coverage floor.
* ``test-full`` -- the whole suite with the 90% coverage floor.
* ``docs`` -- Markdown links/anchors and the generated gate metrics.
* ``manuscript`` -- variables freshness, source validation, build, and drift.
* ``gnn`` -- the shared ``gnn.importers`` pin check, specification drift, and
pinned-parser conformance.
* ``smoke`` -- pipeline, validation, and standalone ``run`` JSON smoke checks.
* ``package`` -- wheel build and clean virtualenv import.
* ``render`` -- render the manuscript to PDF (needs Pandoc and XeLaTeX).
* ``fast`` -- ``lint``, ``types``, ``test``, ``docs``.
* ``all`` -- every release arm (``test`` and ``render`` are excluded).
``fast`` is the default; ``all`` is the release gate. Refresh the measured
numbers with ``--arm all --arm test --arm render --timings /tmp/gate-after.json``
and then ``uv run python scripts/gate_metrics.py --record-timings /tmp/gate-after.json``.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import platform
import re
import subprocess
import sys
import tempfile
import time
from pathlib import Path
from blockference.gnn_runtime import resolve_gnn_runtime
if __package__:
from scripts.build_manuscript import RENDER_TARGETS
else:
from build_manuscript import RENDER_TARGETS
ROOT = Path(__file__).resolve().parents[1]
SCHEMA = "activeblockference-gate/v1"
ARM_ORDER = (
"lint",
"types",
"test",
"test-full",
"docs",
"manuscript",
"gnn",
"smoke",
"package",
"render",
)
FAST_ARMS = ("lint", "types", "test", "docs")
RELEASE_ARMS = ("lint", "types", "test-full", "docs", "manuscript", "gnn", "smoke", "package")
ALIASES = {"fast": FAST_ARMS, "all": RELEASE_ARMS}
ARM_HELP = {
"fast": "lint, types, fast tests, docs (default)",
"all": "every release arm",
"lint": "Ruff over blockference, tests, GRTs, scripts",
"types": "mypy over blockference",
"test": 'fast pytest selection (-m "not slow")',
"test-full": "full pytest suite with the 90% coverage floor",
"docs": "Markdown links/anchors and generated gate metrics",
"manuscript": "manuscript variables, validation, build, and drift check",
"gnn": "GNN pin/pointer check, specification drift, and pinned-parser conformance",
"smoke": "pipeline, validation, and run JSON smoke checks",
"package": "wheel build and clean virtualenv import",
"render": "manuscript PDF render (Pandoc + XeLaTeX)",
}
def _run(
command: list[str], *, cwd: Path = ROOT, capture: bool = False
) -> subprocess.CompletedProcess[str]:
"""Run one gate command without re-synchronizing the prepared locked environment."""
print("$", " ".join(command), flush=True)
try:
return subprocess.run(
command,
cwd=cwd,
check=True,
text=True,
capture_output=capture,
env={**os.environ, "PYTHONUNBUFFERED": "1", "UV_NO_SYNC": "1"},
stdin=subprocess.DEVNULL,
)
except subprocess.CalledProcessError as exc:
if capture:
if exc.stdout:
print(exc.stdout, end="", flush=True)
if exc.stderr:
print(exc.stderr, end="", file=sys.stderr, flush=True)
raise
def _changed_paths() -> set[str]:
"""Return changed tracked paths, excluding host-toolchain figure artefacts.
``docs/manuscript/figures/*.svg`` and ``*.png`` are regenerated by
``scripts/build_manuscript.py`` and both are written by the host toolchain:
matplotlib changes glyph identifiers, text layout, coordinate formatting,
and rasterizer output between releases, and the lock resolves different
matplotlib versions for different Python versions. Their bytes therefore
legitimately differ between the maintainer host and a runner. The committed
figures keep structural checks (``build_manuscript.py --check``) and every
other generated artefact stays byte-compared here.
"""
result = subprocess.run(
["git", "diff", "--name-only"], cwd=ROOT, check=True, text=True,
capture_output=True, stdin=subprocess.DEVNULL,
)
return {
line
for line in result.stdout.splitlines()
if line
and not (line.startswith("docs/manuscript/figures/") and line.endswith((".svg", ".png")))
}
def _assert_json(command: list[str]) -> None:
"""Run one command whose last output line must be a passing JSON verdict."""
result = _run(command, capture=True)
lines = [line for line in result.stdout.splitlines() if line.strip()]
if not lines:
raise ValueError(f"command emitted no JSON: {' '.join(command)}")
try:
payload = json.loads(lines[-1])
except json.JSONDecodeError as exc:
raise ValueError(f"command did not end in JSON: {lines[-1]!r}") from exc
if not isinstance(payload, dict) or payload.get("ok") is not True:
raise ValueError(f"command returned a non-passing JSON verdict: {payload!r}")
def _plan(
arm: str, *, workdir: Path, gnn_runtime: str | None
) -> list[list[str]] | None:
"""Return the commands for one arm, or ``None`` for a Python-driven arm."""
if arm == "lint":
return [["uv", "run", "ruff", "check", "blockference", "tests", "GRTs", "scripts"]]
if arm == "types":
return [["uv", "run", "mypy", "blockference"]]
if arm == "test":
return [["uv", "run", "pytest", "-m", "not slow"]]
if arm == "test-full":
return [
[
"uv",
"run",
"pytest",
"--cov=blockference",
"--cov-report=term",
"--cov-report=xml",
"--cov-fail-under=90",
]
]
if arm == "docs":
return [
["uv", "run", "python", "scripts/check_docs_links.py"],
["uv", "run", "python", "scripts/gate_metrics.py", "--check"],
]
if arm == "manuscript":
return [
[
"uv", "run", "python", "scripts/manuscript_variables.py", "--check",
*(["--gnn-runtime", gnn_runtime] if gnn_runtime else []),
],
["uv", "run", "python", "scripts/validate_manuscript.py"],
["uv", "run", "python", "scripts/build_manuscript.py"],
["uv", "run", "python", "scripts/build_manuscript.py", "--check"],
]
if arm == "gnn":
commands = [["uv", "run", "python", "scripts/export_gnn_spec.py", "--check"]]
# The validator owns both the deep parser verdict and the producer's
# syntax/pointer check. Each runs in its own fully qualified external
# lifetime; no direct ``-m gnn.importers`` path bypasses admission.
validator = [
"uv", "run", "python", "scripts/validate_gnn_spec.py", "--verify-tag-remote", "--json",
]
if gnn_runtime:
validator[-2:-2] = ["--gnn-runtime", gnn_runtime]
commands.append(validator)
return commands
if arm == "smoke":
output_root = workdir / "output"
return [
[
"uv",
"run",
"blockference",
"pipeline",
"--config",
"configs/smoke.yml",
"--output-root",
str(output_root),
"--run-name",
"gate_smoke",
],
["uv", "run", "blockference", "validation", "--run-dir", str(output_root / "gate_smoke")],
[
"uv",
"run",
"blockference",
"run",
"--config",
"configs/smoke.yml",
"--output",
str(workdir / "run.csv"),
],
]
if arm == "render":
return [["uv", "run", "python", "scripts/build_manuscript.py", "--render", "pdf"]]
if arm == "package":
return None
raise ValueError(f"unknown arm {arm}")
def _package_smoke() -> list[list[str]]:
"""Build a wheel and import it from a clean temporary virtualenv."""
commands: list[list[str]] = []
with tempfile.TemporaryDirectory(prefix="activeblockference-package-") as directory:
wheel_dir = Path(directory) / "dist"
commands.append(["uv", "build", "--wheel", "--out-dir", str(wheel_dir)])
_run(commands[-1])
wheels = [
path for path in wheel_dir.glob("*.whl") if path.is_file() and not path.is_symlink()
]
if len(wheels) != 1:
raise ValueError(f"uv build must produce exactly one fresh wheel; found {len(wheels)}")
constraints = Path(directory) / "constraints.txt"
commands.append(
[
"uv", "export", "--locked", "--no-dev", "--no-emit-project", "--no-hashes",
"--output-file", str(constraints),
]
)
_run(commands[-1], capture=True)
venv = Path(directory) / "venv"
commands.append(["uv", "venv", "--python", sys.executable, str(venv)])
_run(commands[-1])
python = venv / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
commands.append(
[
"uv", "pip", "install", "--python", str(python),
"--constraint", str(constraints), str(wheels[0]),
]
)
_run(commands[-1])
commands.append(
[
str(python),
"-I",
"-c",
"from blockference import GridWorld; "
"assert GridWorld(2, {'agent': (0, 0)}).current_state == {'agent': (0, 0)}",
]
)
_run(commands[-1], cwd=Path(directory))
return commands
def _last_number(pattern: str, text: str) -> int | None:
"""Return the last integer matched by ``pattern`` in ``text``."""
matches = re.findall(pattern, text)
return int(matches[-1]) if matches else None
def _coverage_percent() -> float | None:
"""Return the line coverage recorded by the last ``test-full`` run."""
path = ROOT / "coverage.xml"
if not path.is_file():
return None
match = re.search(r'line-rate="([0-9.]+)"', path.read_text(encoding="utf-8"))
return round(float(match.group(1)) * 100, 2) if match else None
def _selected(arms: list[str]) -> list[str]:
"""Expand aliases and return the selected arms in the canonical order."""
expanded: set[str] = set()
for arm in arms or ["fast"]:
expanded.update(ALIASES.get(arm, (arm,)))
unknown = sorted(expanded - set(ARM_ORDER))
if unknown:
raise ValueError("unknown arm(s): " + ", ".join(unknown))
return [arm for arm in ARM_ORDER if arm in expanded]
def _render_artifact() -> dict[str, object]:
"""Identify the PDF bytes produced by the successful render command."""
pdf = RENDER_TARGETS["pdf"]
with pdf.open("rb") as handle:
digest = hashlib.file_digest(handle, "sha256").hexdigest()
commit = subprocess.run(
["git", "rev-parse", "HEAD"], cwd=ROOT, check=True, text=True,
capture_output=True, stdin=subprocess.DEVNULL,
).stdout.strip()
return {
"path": pdf.relative_to(ROOT).as_posix(),
"bytes": pdf.stat().st_size,
"sha256": digest,
"source_commit": commit,
}
def _write_receipt(path: Path, receipt: dict[str, object]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
def main(argv: list[str] | None = None) -> int:
"""Execute the requested gate arms and optionally record their runtimes."""
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"--arm",
action="append",
choices=[*ALIASES, *ARM_ORDER],
help="arm to run; repeatable (default: fast)",
)
parser.add_argument("--list", action="store_true", help="list arms and their commands")
parser.add_argument("--timings", type=Path, help="write a JSON runtime receipt")
parser.add_argument("--json", action="store_true", help="print a JSON summary")
parser.add_argument(
"--gnn-runtime",
help="interpreter with the pinned GNN distribution (default: $GNN_RUNTIME_PYTHON, "
"else the GNN checkout's own .venv under $GNN_ROOT)",
)
args = parser.parse_args(argv)
selected = _selected(args.arm or [])
runtime_error = None
try:
gnn_runtime = resolve_gnn_runtime(args.gnn_runtime, required=False)
except (OSError, ValueError) as exc:
gnn_runtime, runtime_error = None, str(exc)
if args.list:
for arm in (*ALIASES, *ARM_ORDER):
print(f"{arm:10s} {ARM_HELP[arm]}")
if arm in ALIASES:
continue
plan = _plan(
arm,
workdir=Path("<temporary>"),
gnn_runtime=gnn_runtime,
)
for command in plan or [["(python-driven arm)"]]:
print(" $", " ".join(command))
return 0
receipt: dict[str, object] = {
"schema": SCHEMA,
"generated": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"host": platform.platform(),
"python": platform.python_version(),
}
arms_receipt: dict[str, object] = {}
tests: dict[str, object] = {}
failed = False
with tempfile.TemporaryDirectory(prefix="activeblockference-gate-") as directory:
workdir = Path(directory)
for arm in selected:
print(f"\n== {arm}: {ARM_HELP[arm]}", flush=True)
started = time.perf_counter()
commands: list[list[str]] = []
try:
if arm in {"gnn", "manuscript"} and (runtime_error or gnn_runtime is None):
raise ValueError(
"gnn validation not run: " + (
runtime_error or "select --gnn-runtime/GNN_RUNTIME_PYTHON or GNN_ROOT"
)
)
if arm == "package":
commands = _package_smoke()
else:
commands = (
_plan(
arm,
workdir=workdir,
gnn_runtime=gnn_runtime,
)
or []
)
before = _changed_paths() if arm == "manuscript" else None
for command in commands:
if arm == "smoke":
_assert_json(command)
elif arm in {"test", "test-full"}:
result = _run(command, capture=True)
print(result.stdout, flush=True)
if result.stderr:
print(result.stderr, file=sys.stderr, flush=True)
tests["passed"] = _last_number(r"(\d+) passed", result.stdout)
tests["skipped"] = _last_number(r"(\d+) skipped", result.stdout) or 0
else:
_run(command)
if before is not None:
new_changes = sorted(_changed_paths() - before)
if new_changes:
raise RuntimeError(
"generated files drifted during the manuscript arm: "
+ ", ".join(new_changes)
)
if arm == "test-full":
tests["coverage_percent"] = _coverage_percent()
artifact = _render_artifact() if arm == "render" else None
except (subprocess.CalledProcessError, FileNotFoundError, RuntimeError, ValueError) as exc:
failed = True
arms_receipt[arm] = {
"seconds": round(time.perf_counter() - started, 2),
"status": "failed",
"error": str(exc),
"commands": [" ".join(command) for command in commands],
}
print(f"{arm} failed: {exc}", file=sys.stderr, flush=True)
break
elapsed = time.perf_counter() - started
arms_receipt[arm] = {
"seconds": round(elapsed, 2),
"status": "passed",
"commands": [" ".join(command) for command in commands],
}
if artifact is not None:
arms_receipt[arm]["artifact"] = artifact
print(f"{arm} passed in {elapsed:.2f}s", flush=True)
receipt["arms"] = arms_receipt
if tests:
receipt["tests"] = tests
if args.timings:
_write_receipt(args.timings, receipt)
if args.json:
print(json.dumps({"ok": not failed, "arms": arms_receipt}, sort_keys=True))
if failed:
print("release gate failed", file=sys.stderr)
return 1
print("fast gate passed" if selected == list(FAST_ARMS) else "release gate passed", flush=True)
return 0
if __name__ == "__main__":
raise SystemExit(main())