run_6400_formal.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. #!/usr/bin/env python3
  2. """Run and bind the complete 6400 P01-P17 formal acceptance suite."""
  3. from __future__ import annotations
  4. import argparse
  5. from concurrent.futures import ThreadPoolExecutor
  6. from datetime import datetime, timezone
  7. import hashlib
  8. import json
  9. import os
  10. from pathlib import Path
  11. import re
  12. import shutil
  13. import subprocess
  14. import sys
  15. import time
  16. from typing import Any, Iterable
  17. ROOT = Path(__file__).resolve().parents[1]
  18. FORMAL_DIR = ROOT / "tests" / "formal"
  19. MANIFEST = FORMAL_DIR / "6400-properties.json"
  20. ENVIRONMENT_RECEIPT = ROOT / "receipts" / "environment" / "container-image.json"
  21. PROJECT_CONTRACT = ROOT / "projects" / "prod2u-6400-front-back" / "project.json"
  22. PROFILE_CONTRACT = ROOT / "products" / "6400-control" / "project.json"
  23. SOURCE_MANIFEST = ROOT / "products" / "6400-control" / "source-closure.json"
  24. DESIGN_LOCK = ROOT / "docs" / "architecture" / "6400-v1-design-lock.md"
  25. RECEIPT_SCHEMA = "prod2u-6400-formal-receipt-v1"
  26. def sha256_file(path: Path) -> str:
  27. digest = hashlib.sha256()
  28. with path.open("rb") as stream:
  29. for block in iter(lambda: stream.read(1024 * 1024), b""):
  30. digest.update(block)
  31. return digest.hexdigest()
  32. def canonical_sha256(value: Any) -> str:
  33. data = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
  34. return hashlib.sha256(data.encode("utf-8")).hexdigest()
  35. def run_text(argv: list[str], *, check: bool = True) -> str:
  36. result = subprocess.run(
  37. argv,
  38. cwd=ROOT,
  39. check=check,
  40. text=True,
  41. stdout=subprocess.PIPE,
  42. stderr=subprocess.STDOUT,
  43. )
  44. return result.stdout.strip()
  45. def repository_state() -> dict[str, Any]:
  46. commit = run_text(["git", "rev-parse", "HEAD"])
  47. branch = run_text(["git", "branch", "--show-current"])
  48. status_lines = [
  49. line for line in run_text(
  50. ["git", "status", "--porcelain=v1", "--untracked-files=all"]
  51. ).splitlines()
  52. if line
  53. ]
  54. return {
  55. "commit": commit,
  56. "branch": branch,
  57. "clean": not status_lines,
  58. "status_lines": status_lines,
  59. }
  60. def contract_binding() -> dict[str, Any]:
  61. paths = {
  62. "project_contract": PROJECT_CONTRACT,
  63. "profile_contract": PROFILE_CONTRACT,
  64. "source_manifest": SOURCE_MANIFEST,
  65. "design_lock": DESIGN_LOCK,
  66. "formal_manifest": MANIFEST,
  67. }
  68. return {
  69. name: {"path": path.relative_to(ROOT).as_posix(), "sha256": sha256_file(path)}
  70. for name, path in paths.items()
  71. }
  72. def source_binding() -> dict[str, Any]:
  73. manifest = json.loads(SOURCE_MANIFEST.read_text(encoding="utf-8"))
  74. entries: list[dict[str, str]] = []
  75. for relative in manifest["sources"]:
  76. path = ROOT / relative
  77. if not path.is_file():
  78. raise FileNotFoundError(f"source closure entry is missing: {relative}")
  79. entries.append({"path": relative, "sha256": sha256_file(path)})
  80. return {
  81. "manifest_sha256": sha256_file(SOURCE_MANIFEST),
  82. "source_count": len(entries),
  83. "sources": entries,
  84. "source_tree_sha256": canonical_sha256(entries),
  85. }
  86. def sby_files(sby_path: Path) -> list[Path]:
  87. files: list[Path] = []
  88. in_files = False
  89. for raw in sby_path.read_text(encoding="utf-8").splitlines():
  90. line = raw.strip()
  91. if line == "[files]":
  92. in_files = True
  93. continue
  94. if in_files and line.startswith("["):
  95. break
  96. if not in_files or not line or line.startswith("#"):
  97. continue
  98. source_token = line.split()[-1]
  99. source = (sby_path.parent / source_token).resolve()
  100. if not source.is_file():
  101. raise FileNotFoundError(f"formal input is missing: {source}")
  102. files.append(source)
  103. return files
  104. def formal_input_binding(targets: Iterable[dict[str, Any]]) -> dict[str, Any]:
  105. values: list[dict[str, Any]] = []
  106. for target in targets:
  107. sby_path = FORMAL_DIR / target["sby"]
  108. files = [
  109. {"path": path.relative_to(ROOT).as_posix(), "sha256": sha256_file(path)}
  110. for path in sby_files(sby_path)
  111. ]
  112. values.append({
  113. "name": target["name"],
  114. "mode": target["mode"],
  115. "depth": target["depth"],
  116. "tasks": target["tasks"],
  117. "sby": {
  118. "path": sby_path.relative_to(ROOT).as_posix(),
  119. "sha256": sha256_file(sby_path),
  120. },
  121. "files": files,
  122. "input_sha256": canonical_sha256({"sby": sha256_file(sby_path), "files": files}),
  123. })
  124. return {"targets": values, "sha256": canonical_sha256(values)}
  125. def executable_evidence(name: str, version_args: list[str], version_override: str = "") -> dict[str, Any]:
  126. executable = shutil.which(name)
  127. failures: list[str] = []
  128. output = ""
  129. if executable is None:
  130. return {
  131. "name": name,
  132. "path": "",
  133. "sha256": "0" * 64,
  134. "version": "",
  135. "status": "fail",
  136. "failures": [f"tool_missing:{name}"],
  137. }
  138. result = subprocess.run(
  139. [executable, *version_args],
  140. cwd=ROOT,
  141. check=False,
  142. text=True,
  143. stdout=subprocess.PIPE,
  144. stderr=subprocess.STDOUT,
  145. )
  146. output = result.stdout.strip()
  147. if result.returncode != 0:
  148. failures.append(f"tool_version_probe_failed:{name}:{result.returncode}")
  149. version = version_override or next((line.strip() for line in output.splitlines() if line.strip()), "")
  150. if not version:
  151. failures.append(f"tool_version_missing:{name}")
  152. return {
  153. "name": name,
  154. "path": executable,
  155. "sha256": sha256_file(Path(executable).resolve()),
  156. "version": version,
  157. "status": "pass" if not failures else "fail",
  158. "failures": failures,
  159. }
  160. def toolchain_evidence(environment: dict[str, Any]) -> dict[str, Any]:
  161. tools = [
  162. executable_evidence("sby", ["-h"], f"git:{environment['sby_commit']}"),
  163. executable_evidence("yosys", ["-V"]),
  164. executable_evidence("boolector", ["--version"]),
  165. executable_evidence("z3", ["--version"]),
  166. ]
  167. failures = [failure for tool in tools for failure in tool["failures"]]
  168. return {"status": "pass" if not failures else "fail", "tools": tools, "failures": failures}
  169. def compiled_property_ids(workdir: Path) -> tuple[list[str], list[str], str, list[str]]:
  170. design_json = workdir / "model" / "design.json"
  171. assertions: set[str] = set()
  172. covers: set[str] = set()
  173. failures: list[str] = []
  174. try:
  175. payload = json.loads(design_json.read_text(encoding="utf-8"))
  176. modules = payload.get("modules", [])
  177. for module in modules if isinstance(modules, list) else []:
  178. module_name = str(module.get("name", ""))
  179. for cell_sort in module.get("cell_sorts", []):
  180. sort_type = str(cell_sort.get("type", ""))
  181. for cell in cell_sort.get("cells", []):
  182. name = str(cell.get("name", ""))
  183. flavor = cell.get("parameters", {}).get("FLAVOR")
  184. if not module_name or not name:
  185. continue
  186. identifier = f"{module_name}.{name}"
  187. if sort_type == "$assert" or flavor == "assert":
  188. assertions.add(identifier)
  189. elif sort_type == "$cover" or flavor == "cover":
  190. covers.add(identifier)
  191. except (OSError, UnicodeError, json.JSONDecodeError, AttributeError, TypeError) as exc:
  192. failures.append(f"compiled_properties_unavailable:{type(exc).__name__}")
  193. design_hash = sha256_file(design_json) if design_json.is_file() else "0" * 64
  194. return sorted(assertions), sorted(covers), design_hash, failures
  195. def cover_hit_ids(workdir: Path) -> list[str]:
  196. pattern = re.compile(r"(?i)reached cover statement\s+(\S+)\s+at\s+\S+:\d+")
  197. hits: set[str] = set()
  198. for path in (workdir / "PASS", workdir / "logfile.txt"):
  199. if not path.is_file():
  200. continue
  201. for value in pattern.findall(path.read_text(encoding="utf-8", errors="replace")):
  202. if value.casefold() != "in":
  203. hits.add(value)
  204. return sorted(hits)
  205. def property_cell_ids(values: Iterable[str]) -> set[str]:
  206. """Normalize JNY module IDs and SBY hierarchical IDs to cell names."""
  207. normalized: set[str] = set()
  208. for value in values:
  209. positions = [value.rfind(marker) for marker in ("$assert$", "$cover$")]
  210. start = max(positions)
  211. normalized.add(value[start:] if start >= 0 else value)
  212. return normalized
  213. def relative_artifacts(workdir: Path, pattern: str) -> list[dict[str, str]]:
  214. return [
  215. {"path": path.relative_to(ROOT).as_posix(), "sha256": sha256_file(path)}
  216. for path in sorted(workdir.rglob(pattern))
  217. if path.is_file()
  218. ]
  219. def run_job(job: dict[str, Any], run_root: Path, timeout: int) -> dict[str, Any]:
  220. target = job["target"]
  221. task = job["task"]
  222. suffix = task if task != "default" else "default"
  223. workdir = run_root / "work" / target["name"] / suffix
  224. workdir.parent.mkdir(parents=True, exist_ok=True)
  225. sby_path = FORMAL_DIR / target["sby"]
  226. command = [shutil.which("sby") or "sby", "-f", "-d", str(workdir), sby_path.name]
  227. if task != "default":
  228. command.append(task)
  229. started = time.monotonic()
  230. timed_out = False
  231. try:
  232. process = subprocess.run(
  233. command,
  234. cwd=FORMAL_DIR,
  235. check=False,
  236. text=True,
  237. stdout=subprocess.PIPE,
  238. stderr=subprocess.STDOUT,
  239. timeout=timeout,
  240. )
  241. returncode: int | None = process.returncode
  242. output = process.stdout
  243. except subprocess.TimeoutExpired as exc:
  244. timed_out = True
  245. returncode = None
  246. output = exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "")
  247. duration = time.monotonic() - started
  248. process_log = workdir.parent / f"{suffix}.process.log"
  249. process_log.write_text(output, encoding="utf-8")
  250. status_file = workdir / "status"
  251. status_raw = status_file.read_text(encoding="utf-8", errors="replace").strip() if status_file.is_file() else ""
  252. status_token = status_raw.split()[0].upper() if status_raw else "MISSING"
  253. logfile = workdir / "logfile.txt"
  254. log_text = logfile.read_text(encoding="utf-8", errors="replace") if logfile.is_file() else ""
  255. assertions, covers, design_hash, failures = compiled_property_ids(workdir)
  256. if timed_out:
  257. failures.append("timeout")
  258. if returncode != 0:
  259. failures.append(f"returncode:{returncode}")
  260. if status_token != "PASS":
  261. failures.append(f"status:{status_token}")
  262. if not (workdir / "PASS").is_file() or (workdir / "FAIL").exists():
  263. failures.append("pass_fail_marker_mismatch")
  264. if "DONE (PASS" not in log_text:
  265. failures.append("sby_done_pass_missing")
  266. if target["mode"] == "prove":
  267. if not assertions:
  268. failures.append("compiled_assertions_missing")
  269. if "successful proof by k-induction" not in log_text:
  270. failures.append("k_induction_evidence_missing")
  271. expected_solver = task
  272. if not re.search(rf"(?im)Solver:\s*{re.escape(expected_solver)}\b", log_text):
  273. failures.append(f"solver_observation_missing:{expected_solver}")
  274. else:
  275. hits = cover_hit_ids(workdir)
  276. if not covers:
  277. failures.append("compiled_covers_missing")
  278. if property_cell_ids(hits) != property_cell_ids(covers):
  279. failures.append(f"cover_hit_set_mismatch:{len(hits)}/{len(covers)}")
  280. if not relative_artifacts(workdir, "*.vcd"):
  281. failures.append("cover_trace_missing")
  282. return {
  283. "name": target["name"],
  284. "task": task,
  285. "mode": target["mode"],
  286. "depth": target["depth"],
  287. "status": "pass" if not failures else "fail",
  288. "returncode": returncode,
  289. "timed_out": timed_out,
  290. "duration_seconds": round(duration, 3),
  291. "command": command,
  292. "workdir": workdir.relative_to(ROOT).as_posix(),
  293. "process_log": {
  294. "path": process_log.relative_to(ROOT).as_posix(),
  295. "sha256": sha256_file(process_log),
  296. },
  297. "sby_log_sha256": sha256_file(logfile) if logfile.is_file() else "0" * 64,
  298. "compiled_design_sha256": design_hash,
  299. "compiled_assertion_count": len(assertions),
  300. "compiled_cover_count": len(covers),
  301. "compiled_assertion_ids": assertions,
  302. "compiled_cover_ids": covers,
  303. "cover_hit_ids": cover_hit_ids(workdir) if target["mode"] == "cover" else [],
  304. "traces": relative_artifacts(workdir, "*.vcd") if target["mode"] == "cover" else [],
  305. "evidence_failures": failures,
  306. }
  307. def validate_manifest(manifest: dict[str, Any]) -> None:
  308. properties = manifest.get("properties", [])
  309. ids = [entry.get("id") for entry in properties]
  310. expected = [f"P{index:02d}" for index in range(1, 18)]
  311. if ids != expected:
  312. raise ValueError(f"formal property IDs must be exactly {expected}, got {ids}")
  313. proof_targets = manifest.get("proof_targets", [])
  314. if not proof_targets:
  315. raise ValueError("proof_targets is empty")
  316. harnesses = {entry["sby"] for entry in proof_targets}
  317. if any(entry.get("harness") not in harnesses for entry in properties):
  318. raise ValueError("a P01-P17 property references a non-proof harness")
  319. for target in [*proof_targets, *manifest.get("cover_targets", [])]:
  320. sby_path = FORMAL_DIR / target["sby"]
  321. if not sby_path.is_file():
  322. raise FileNotFoundError(sby_path)
  323. text = sby_path.read_text(encoding="utf-8")
  324. if not re.search(rf"(?m)^mode\s+{re.escape(target['mode'])}\s*$", text):
  325. raise ValueError(f"mode mismatch in {sby_path.name}")
  326. if not re.search(rf"(?m)^depth\s+{target['depth']}\s*$", text):
  327. raise ValueError(f"depth mismatch in {sby_path.name}")
  328. def main(argv: list[str] | None = None) -> int:
  329. parser = argparse.ArgumentParser()
  330. parser.add_argument("--run-id")
  331. parser.add_argument("--jobs", type=int, default=4)
  332. parser.add_argument("--timeout-seconds", type=int, default=600)
  333. args = parser.parse_args(argv)
  334. timestamp = datetime.now(timezone.utc)
  335. run_id = args.run_id or timestamp.strftime("6400-formal-%Y%m%dT%H%M%SZ")
  336. if not re.fullmatch(r"[A-Za-z0-9._-]+", run_id):
  337. parser.error("run ID may contain only letters, digits, dot, underscore, and hyphen")
  338. run_root = ROOT / "receipts" / "6400-formal" / run_id
  339. if run_root.exists():
  340. parser.error(f"run directory already exists: {run_root}")
  341. run_root.mkdir(parents=True)
  342. manifest = json.loads(MANIFEST.read_text(encoding="utf-8"))
  343. validate_manifest(manifest)
  344. repository = repository_state()
  345. if not repository["clean"]:
  346. raise RuntimeError("formal acceptance requires a clean worktree")
  347. environment = json.loads(ENVIRONMENT_RECEIPT.read_text(encoding="utf-8"))
  348. observed_digest = os.environ.get("PROD2U_CONTAINER_DIGEST", "")
  349. observed_image_id = os.environ.get("PROD2U_CONTAINER_IMAGE_ID", "")
  350. if observed_digest != environment.get("digest") or observed_image_id != environment.get("image_id"):
  351. raise RuntimeError("container identity environment does not match the pinned image receipt")
  352. tools = toolchain_evidence(environment)
  353. if tools["status"] != "pass":
  354. raise RuntimeError(f"formal toolchain evidence failed: {tools['failures']}")
  355. targets = [*manifest["proof_targets"], *manifest["cover_targets"]]
  356. formal_inputs = formal_input_binding(targets)
  357. jobs = [
  358. {"target": target, "task": task}
  359. for target in targets
  360. for task in (target["tasks"] or ["default"])
  361. ]
  362. with ThreadPoolExecutor(max_workers=max(1, min(args.jobs, len(jobs)))) as executor:
  363. results = list(executor.map(lambda job: run_job(job, run_root, args.timeout_seconds), jobs))
  364. result_by_target: dict[str, list[dict[str, Any]]] = {}
  365. for result in results:
  366. result_by_target.setdefault(result["name"], []).append(result)
  367. target_results = [
  368. {
  369. "name": target["name"],
  370. "sby": target["sby"],
  371. "mode": target["mode"],
  372. "depth": target["depth"],
  373. "status": "pass" if all(item["status"] == "pass" for item in result_by_target[target["name"]]) else "fail",
  374. "tasks": result_by_target[target["name"]],
  375. }
  376. for target in targets
  377. ]
  378. target_status = {entry["sby"]: entry["status"] for entry in target_results}
  379. result_status_by_name = {entry["name"]: entry["status"] for entry in target_results}
  380. witness_status = {
  381. property_id: result_status_by_name.get(target["name"], "fail")
  382. for target in manifest["cover_targets"]
  383. for property_id in target.get("witnesses", [])
  384. }
  385. properties = []
  386. for entry in manifest["properties"]:
  387. proof_status = target_status.get(entry["harness"], "fail")
  388. witness = witness_status.get(entry["id"], "not_required")
  389. properties.append({
  390. **entry,
  391. "proof_status": proof_status,
  392. "witness_status": witness,
  393. "status": "pass" if proof_status == "pass" and witness in {"pass", "not_required"} else "fail",
  394. })
  395. passed = all(entry["status"] == "pass" for entry in target_results)
  396. receipt = {
  397. "schema": RECEIPT_SCHEMA,
  398. "status": "pass" if passed else "fail",
  399. "verification_layer": "formal",
  400. "run_id": run_id,
  401. "started_utc": timestamp.isoformat(),
  402. "finished_utc": datetime.now(timezone.utc).isoformat(),
  403. "command": [sys.executable, str(Path(__file__).relative_to(ROOT)), *sys.argv[1:]],
  404. "repository": repository,
  405. "contracts": contract_binding(),
  406. "source_binding": source_binding(),
  407. "formal_inputs": formal_inputs,
  408. "container": {
  409. "image": environment["image"],
  410. "digest": observed_digest,
  411. "image_id": observed_image_id,
  412. "receipt_sha256": sha256_file(ENVIRONMENT_RECEIPT),
  413. "sby_commit": environment["sby_commit"],
  414. },
  415. "toolchain": tools,
  416. "properties": properties,
  417. "targets": target_results,
  418. "applicable_bitstream": False,
  419. "bitstream_sha256": None,
  420. "physical_evidence": {
  421. "hardware": "not_run",
  422. "jtag": "not_run",
  423. "com": "not_run",
  424. "real_bmc": "not_run",
  425. "real_rs232": "not_run",
  426. "real_ttl_uart": "not_run",
  427. "real_thermal_performance": "not_run",
  428. },
  429. "authority_boundary": "Formal proves RTL properties and reachable witnesses only; it is not TD, bitstream, hardware, or thermal evidence.",
  430. }
  431. receipt_path = run_root / "formal-receipt.json"
  432. receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  433. print(json.dumps({
  434. "status": receipt["status"],
  435. "run_id": run_id,
  436. "receipt": receipt_path.relative_to(ROOT).as_posix(),
  437. "receipt_sha256": sha256_file(receipt_path),
  438. "target_count": len(target_results),
  439. "task_count": len(results),
  440. }, indent=2, sort_keys=True))
  441. return 0 if passed else 1
  442. if __name__ == "__main__":
  443. raise SystemExit(main())