#!/usr/bin/env python3 """Run and bind the complete 6400 P01-P17 formal acceptance suite.""" from __future__ import annotations import argparse from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timezone import hashlib import json import os from pathlib import Path import re import shutil import subprocess import sys import time from typing import Any, Iterable ROOT = Path(__file__).resolve().parents[1] FORMAL_DIR = ROOT / "tests" / "formal" MANIFEST = FORMAL_DIR / "6400-properties.json" ENVIRONMENT_RECEIPT = ROOT / "receipts" / "environment" / "container-image.json" PROJECT_CONTRACT = ROOT / "projects" / "prod2u-6400-front-back" / "project.json" PROFILE_CONTRACT = ROOT / "products" / "6400-control" / "project.json" SOURCE_MANIFEST = ROOT / "products" / "6400-control" / "source-closure.json" DESIGN_LOCK = ROOT / "docs" / "architecture" / "6400-v1-design-lock.md" RECEIPT_SCHEMA = "prod2u-6400-formal-receipt-v1" def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: for block in iter(lambda: stream.read(1024 * 1024), b""): digest.update(block) return digest.hexdigest() def canonical_sha256(value: Any) -> str: data = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False) return hashlib.sha256(data.encode("utf-8")).hexdigest() def run_text(argv: list[str], *, check: bool = True) -> str: result = subprocess.run( argv, cwd=ROOT, check=check, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) return result.stdout.strip() def repository_state() -> dict[str, Any]: commit = run_text(["git", "rev-parse", "HEAD"]) branch = run_text(["git", "branch", "--show-current"]) status_lines = [ line for line in run_text( ["git", "status", "--porcelain=v1", "--untracked-files=all"] ).splitlines() if line ] return { "commit": commit, "branch": branch, "clean": not status_lines, "status_lines": status_lines, } def contract_binding() -> dict[str, Any]: paths = { "project_contract": PROJECT_CONTRACT, "profile_contract": PROFILE_CONTRACT, "source_manifest": SOURCE_MANIFEST, "design_lock": DESIGN_LOCK, "formal_manifest": MANIFEST, } return { name: {"path": path.relative_to(ROOT).as_posix(), "sha256": sha256_file(path)} for name, path in paths.items() } def source_binding() -> dict[str, Any]: manifest = json.loads(SOURCE_MANIFEST.read_text(encoding="utf-8")) entries: list[dict[str, str]] = [] for relative in manifest["sources"]: path = ROOT / relative if not path.is_file(): raise FileNotFoundError(f"source closure entry is missing: {relative}") entries.append({"path": relative, "sha256": sha256_file(path)}) return { "manifest_sha256": sha256_file(SOURCE_MANIFEST), "source_count": len(entries), "sources": entries, "source_tree_sha256": canonical_sha256(entries), } def sby_files(sby_path: Path) -> list[Path]: files: list[Path] = [] in_files = False for raw in sby_path.read_text(encoding="utf-8").splitlines(): line = raw.strip() if line == "[files]": in_files = True continue if in_files and line.startswith("["): break if not in_files or not line or line.startswith("#"): continue source_token = line.split()[-1] source = (sby_path.parent / source_token).resolve() if not source.is_file(): raise FileNotFoundError(f"formal input is missing: {source}") files.append(source) return files def formal_input_binding(targets: Iterable[dict[str, Any]]) -> dict[str, Any]: values: list[dict[str, Any]] = [] for target in targets: sby_path = FORMAL_DIR / target["sby"] files = [ {"path": path.relative_to(ROOT).as_posix(), "sha256": sha256_file(path)} for path in sby_files(sby_path) ] values.append({ "name": target["name"], "mode": target["mode"], "depth": target["depth"], "tasks": target["tasks"], "sby": { "path": sby_path.relative_to(ROOT).as_posix(), "sha256": sha256_file(sby_path), }, "files": files, "input_sha256": canonical_sha256({"sby": sha256_file(sby_path), "files": files}), }) return {"targets": values, "sha256": canonical_sha256(values)} def executable_evidence(name: str, version_args: list[str], version_override: str = "") -> dict[str, Any]: executable = shutil.which(name) failures: list[str] = [] output = "" if executable is None: return { "name": name, "path": "", "sha256": "0" * 64, "version": "", "status": "fail", "failures": [f"tool_missing:{name}"], } result = subprocess.run( [executable, *version_args], cwd=ROOT, check=False, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) output = result.stdout.strip() if result.returncode != 0: failures.append(f"tool_version_probe_failed:{name}:{result.returncode}") version = version_override or next((line.strip() for line in output.splitlines() if line.strip()), "") if not version: failures.append(f"tool_version_missing:{name}") return { "name": name, "path": executable, "sha256": sha256_file(Path(executable).resolve()), "version": version, "status": "pass" if not failures else "fail", "failures": failures, } def toolchain_evidence(environment: dict[str, Any]) -> dict[str, Any]: tools = [ executable_evidence("sby", ["-h"], f"git:{environment['sby_commit']}"), executable_evidence("yosys", ["-V"]), executable_evidence("boolector", ["--version"]), executable_evidence("z3", ["--version"]), ] failures = [failure for tool in tools for failure in tool["failures"]] return {"status": "pass" if not failures else "fail", "tools": tools, "failures": failures} def compiled_property_ids(workdir: Path) -> tuple[list[str], list[str], str, list[str]]: design_json = workdir / "model" / "design.json" assertions: set[str] = set() covers: set[str] = set() failures: list[str] = [] try: payload = json.loads(design_json.read_text(encoding="utf-8")) modules = payload.get("modules", []) for module in modules if isinstance(modules, list) else []: module_name = str(module.get("name", "")) for cell_sort in module.get("cell_sorts", []): sort_type = str(cell_sort.get("type", "")) for cell in cell_sort.get("cells", []): name = str(cell.get("name", "")) flavor = cell.get("parameters", {}).get("FLAVOR") if not module_name or not name: continue identifier = f"{module_name}.{name}" if sort_type == "$assert" or flavor == "assert": assertions.add(identifier) elif sort_type == "$cover" or flavor == "cover": covers.add(identifier) except (OSError, UnicodeError, json.JSONDecodeError, AttributeError, TypeError) as exc: failures.append(f"compiled_properties_unavailable:{type(exc).__name__}") design_hash = sha256_file(design_json) if design_json.is_file() else "0" * 64 return sorted(assertions), sorted(covers), design_hash, failures def cover_hit_ids(workdir: Path) -> list[str]: pattern = re.compile(r"(?i)reached cover statement\s+(\S+)\s+at\s+\S+:\d+") hits: set[str] = set() for path in (workdir / "PASS", workdir / "logfile.txt"): if not path.is_file(): continue for value in pattern.findall(path.read_text(encoding="utf-8", errors="replace")): if value.casefold() != "in": hits.add(value) return sorted(hits) def property_cell_ids(values: Iterable[str]) -> set[str]: """Normalize JNY module IDs and SBY hierarchical IDs to cell names.""" normalized: set[str] = set() for value in values: positions = [value.rfind(marker) for marker in ("$assert$", "$cover$")] start = max(positions) normalized.add(value[start:] if start >= 0 else value) return normalized def relative_artifacts(workdir: Path, pattern: str) -> list[dict[str, str]]: return [ {"path": path.relative_to(ROOT).as_posix(), "sha256": sha256_file(path)} for path in sorted(workdir.rglob(pattern)) if path.is_file() ] def run_job(job: dict[str, Any], run_root: Path, timeout: int) -> dict[str, Any]: target = job["target"] task = job["task"] suffix = task if task != "default" else "default" workdir = run_root / "work" / target["name"] / suffix workdir.parent.mkdir(parents=True, exist_ok=True) sby_path = FORMAL_DIR / target["sby"] command = [shutil.which("sby") or "sby", "-f", "-d", str(workdir), sby_path.name] if task != "default": command.append(task) started = time.monotonic() timed_out = False try: process = subprocess.run( command, cwd=FORMAL_DIR, check=False, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout, ) returncode: int | None = process.returncode output = process.stdout except subprocess.TimeoutExpired as exc: timed_out = True returncode = None output = exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "") duration = time.monotonic() - started process_log = workdir.parent / f"{suffix}.process.log" process_log.write_text(output, encoding="utf-8") status_file = workdir / "status" status_raw = status_file.read_text(encoding="utf-8", errors="replace").strip() if status_file.is_file() else "" status_token = status_raw.split()[0].upper() if status_raw else "MISSING" logfile = workdir / "logfile.txt" log_text = logfile.read_text(encoding="utf-8", errors="replace") if logfile.is_file() else "" assertions, covers, design_hash, failures = compiled_property_ids(workdir) if timed_out: failures.append("timeout") if returncode != 0: failures.append(f"returncode:{returncode}") if status_token != "PASS": failures.append(f"status:{status_token}") if not (workdir / "PASS").is_file() or (workdir / "FAIL").exists(): failures.append("pass_fail_marker_mismatch") if "DONE (PASS" not in log_text: failures.append("sby_done_pass_missing") if target["mode"] == "prove": if not assertions: failures.append("compiled_assertions_missing") if "successful proof by k-induction" not in log_text: failures.append("k_induction_evidence_missing") expected_solver = task if not re.search(rf"(?im)Solver:\s*{re.escape(expected_solver)}\b", log_text): failures.append(f"solver_observation_missing:{expected_solver}") else: hits = cover_hit_ids(workdir) if not covers: failures.append("compiled_covers_missing") if property_cell_ids(hits) != property_cell_ids(covers): failures.append(f"cover_hit_set_mismatch:{len(hits)}/{len(covers)}") if not relative_artifacts(workdir, "*.vcd"): failures.append("cover_trace_missing") return { "name": target["name"], "task": task, "mode": target["mode"], "depth": target["depth"], "status": "pass" if not failures else "fail", "returncode": returncode, "timed_out": timed_out, "duration_seconds": round(duration, 3), "command": command, "workdir": workdir.relative_to(ROOT).as_posix(), "process_log": { "path": process_log.relative_to(ROOT).as_posix(), "sha256": sha256_file(process_log), }, "sby_log_sha256": sha256_file(logfile) if logfile.is_file() else "0" * 64, "compiled_design_sha256": design_hash, "compiled_assertion_count": len(assertions), "compiled_cover_count": len(covers), "compiled_assertion_ids": assertions, "compiled_cover_ids": covers, "cover_hit_ids": cover_hit_ids(workdir) if target["mode"] == "cover" else [], "traces": relative_artifacts(workdir, "*.vcd") if target["mode"] == "cover" else [], "evidence_failures": failures, } def validate_manifest(manifest: dict[str, Any]) -> None: properties = manifest.get("properties", []) ids = [entry.get("id") for entry in properties] expected = [f"P{index:02d}" for index in range(1, 18)] if ids != expected: raise ValueError(f"formal property IDs must be exactly {expected}, got {ids}") proof_targets = manifest.get("proof_targets", []) if not proof_targets: raise ValueError("proof_targets is empty") harnesses = {entry["sby"] for entry in proof_targets} if any(entry.get("harness") not in harnesses for entry in properties): raise ValueError("a P01-P17 property references a non-proof harness") for target in [*proof_targets, *manifest.get("cover_targets", [])]: sby_path = FORMAL_DIR / target["sby"] if not sby_path.is_file(): raise FileNotFoundError(sby_path) text = sby_path.read_text(encoding="utf-8") if not re.search(rf"(?m)^mode\s+{re.escape(target['mode'])}\s*$", text): raise ValueError(f"mode mismatch in {sby_path.name}") if not re.search(rf"(?m)^depth\s+{target['depth']}\s*$", text): raise ValueError(f"depth mismatch in {sby_path.name}") def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser() parser.add_argument("--run-id") parser.add_argument("--jobs", type=int, default=4) parser.add_argument("--timeout-seconds", type=int, default=600) args = parser.parse_args(argv) timestamp = datetime.now(timezone.utc) run_id = args.run_id or timestamp.strftime("6400-formal-%Y%m%dT%H%M%SZ") if not re.fullmatch(r"[A-Za-z0-9._-]+", run_id): parser.error("run ID may contain only letters, digits, dot, underscore, and hyphen") run_root = ROOT / "receipts" / "6400-formal" / run_id if run_root.exists(): parser.error(f"run directory already exists: {run_root}") run_root.mkdir(parents=True) manifest = json.loads(MANIFEST.read_text(encoding="utf-8")) validate_manifest(manifest) repository = repository_state() if not repository["clean"]: raise RuntimeError("formal acceptance requires a clean worktree") environment = json.loads(ENVIRONMENT_RECEIPT.read_text(encoding="utf-8")) observed_digest = os.environ.get("PROD2U_CONTAINER_DIGEST", "") observed_image_id = os.environ.get("PROD2U_CONTAINER_IMAGE_ID", "") if observed_digest != environment.get("digest") or observed_image_id != environment.get("image_id"): raise RuntimeError("container identity environment does not match the pinned image receipt") tools = toolchain_evidence(environment) if tools["status"] != "pass": raise RuntimeError(f"formal toolchain evidence failed: {tools['failures']}") targets = [*manifest["proof_targets"], *manifest["cover_targets"]] formal_inputs = formal_input_binding(targets) jobs = [ {"target": target, "task": task} for target in targets for task in (target["tasks"] or ["default"]) ] with ThreadPoolExecutor(max_workers=max(1, min(args.jobs, len(jobs)))) as executor: results = list(executor.map(lambda job: run_job(job, run_root, args.timeout_seconds), jobs)) result_by_target: dict[str, list[dict[str, Any]]] = {} for result in results: result_by_target.setdefault(result["name"], []).append(result) target_results = [ { "name": target["name"], "sby": target["sby"], "mode": target["mode"], "depth": target["depth"], "status": "pass" if all(item["status"] == "pass" for item in result_by_target[target["name"]]) else "fail", "tasks": result_by_target[target["name"]], } for target in targets ] target_status = {entry["sby"]: entry["status"] for entry in target_results} result_status_by_name = {entry["name"]: entry["status"] for entry in target_results} witness_status = { property_id: result_status_by_name.get(target["name"], "fail") for target in manifest["cover_targets"] for property_id in target.get("witnesses", []) } properties = [] for entry in manifest["properties"]: proof_status = target_status.get(entry["harness"], "fail") witness = witness_status.get(entry["id"], "not_required") properties.append({ **entry, "proof_status": proof_status, "witness_status": witness, "status": "pass" if proof_status == "pass" and witness in {"pass", "not_required"} else "fail", }) passed = all(entry["status"] == "pass" for entry in target_results) receipt = { "schema": RECEIPT_SCHEMA, "status": "pass" if passed else "fail", "verification_layer": "formal", "run_id": run_id, "started_utc": timestamp.isoformat(), "finished_utc": datetime.now(timezone.utc).isoformat(), "command": [sys.executable, str(Path(__file__).relative_to(ROOT)), *sys.argv[1:]], "repository": repository, "contracts": contract_binding(), "source_binding": source_binding(), "formal_inputs": formal_inputs, "container": { "image": environment["image"], "digest": observed_digest, "image_id": observed_image_id, "receipt_sha256": sha256_file(ENVIRONMENT_RECEIPT), "sby_commit": environment["sby_commit"], }, "toolchain": tools, "properties": properties, "targets": target_results, "applicable_bitstream": False, "bitstream_sha256": None, "physical_evidence": { "hardware": "not_run", "jtag": "not_run", "com": "not_run", "real_bmc": "not_run", "real_rs232": "not_run", "real_ttl_uart": "not_run", "real_thermal_performance": "not_run", }, "authority_boundary": "Formal proves RTL properties and reachable witnesses only; it is not TD, bitstream, hardware, or thermal evidence.", } receipt_path = run_root / "formal-receipt.json" receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8") print(json.dumps({ "status": receipt["status"], "run_id": run_id, "receipt": receipt_path.relative_to(ROOT).as_posix(), "receipt_sha256": sha256_file(receipt_path), "target_count": len(target_results), "task_count": len(results), }, indent=2, sort_keys=True)) return 0 if passed else 1 if __name__ == "__main__": raise SystemExit(main())