| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552 |
- #!/usr/bin/env python3
- """Run and bind the active 6400-front-rear Formal target registry."""
- 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 signal
- 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"
- SOLVER_MAP = FORMAL_DIR / "solver-map.yaml"
- ENVIRONMENT_RECEIPT = ROOT / "receipts" / "environment" / "container-image-6400.json"
- PROJECT_CONTRACT = ROOT / "projects" / "prod2u-6400-front-back" / "project.json"
- PROFILE_CONTRACT = ROOT / "products" / "6400-front-rear" / "project.json"
- SOURCE_MANIFEST = ROOT / "products" / "6400-front-rear" / "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 evidence_path(path: Path) -> str:
- resolved = path.resolve()
- try:
- return resolved.relative_to(ROOT.resolve()).as_posix()
- except ValueError:
- return resolved.as_posix()
- def formal_run_base() -> Path:
- configured = os.environ.get("PRODU2_FORMAL_RUN_BASE")
- base = Path(configured) if configured else (
- Path(os.environ.get("XDG_STATE_HOME", "/tmp")) / "prod2u" / "formal-runs"
- )
- resolved = base.expanduser().resolve()
- if resolved == ROOT.resolve() or ROOT.resolve() in resolved.parents:
- raise RuntimeError("formal run base must be outside the Git worktree")
- return resolved
- 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,
- "solver_map": SOLVER_MAP,
- }
- 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": evidence_path(path), "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
- process = subprocess.Popen(
- command,
- cwd=FORMAL_DIR,
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- start_new_session=True,
- )
- try:
- output, _ = process.communicate(timeout=timeout)
- returncode: int | None = process.returncode
- except subprocess.TimeoutExpired as exc:
- timed_out = True
- partial_output = exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "")
- if os.name == "posix":
- try:
- os.killpg(process.pid, signal.SIGTERM)
- except ProcessLookupError:
- pass
- else:
- process.terminate()
- try:
- final_output, _ = process.communicate(timeout=5)
- except subprocess.TimeoutExpired:
- if os.name == "posix":
- try:
- os.killpg(process.pid, signal.SIGKILL)
- except ProcessLookupError:
- pass
- else:
- process.kill()
- final_output, _ = process.communicate()
- # A retry of communicate() returns all captured output, including the
- # bytes reported by TimeoutExpired. Do not prepend partial_output and
- # duplicate the solver log.
- output = final_output if final_output is not None else partial_output
- returncode = process.returncode
- 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"] in {"prove", "bmc"}:
- if not assertions:
- failures.append("compiled_assertions_missing")
- if target["mode"] == "prove" and "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}")
- elif target["mode"] == "cover":
- 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")
- else:
- failures.append(f"unsupported_mode:{target['mode']}")
- 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": evidence_path(workdir),
- "process_log": {
- "path": evidence_path(process_log),
- "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]
- if not ids or any(not isinstance(value, str) or not value for value in ids):
- raise ValueError("formal property IDs must be non-empty strings")
- if len(ids) != len(set(ids)):
- raise ValueError(f"formal property IDs must be unique, 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 formal 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=1)
- parser.add_argument("--timeout-seconds", type=int, default=600)
- args = parser.parse_args(argv)
- if args.jobs != 1:
- parser.error("6400 formal permits exactly one heavy solver task at a time")
- 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 = formal_run_base() / 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", "")
- host_mounted = os.environ.get("PROD2U_FORMAL_HOST_MOUNTED", "") == "1"
- if host_mounted:
- distro = os.environ.get("WSL_DISTRO_NAME", "")
- suite_root = Path(os.environ.get("OSS_CAD_SUITE_ROOT", "")).resolve()
- expected_root = Path("/data/prod2u/oss-cad-suite/latest").resolve()
- if distro != "Debian13" or suite_root != expected_root:
- raise RuntimeError("host-mounted formal requires Debian13 and the pinned OSS CAD Suite path")
- if not (suite_root / "bin" / "sby").is_file():
- raise RuntimeError("host-mounted formal sby executable is missing")
- elif (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": {
- "status": "not_used_host_mounted" if host_mounted else "used",
- "image": None if host_mounted else environment["image"],
- "digest": None if host_mounted else observed_digest,
- "image_id": None if host_mounted else observed_image_id,
- "receipt_sha256": sha256_file(ENVIRONMENT_RECEIPT),
- "sby_commit": environment["sby_commit"],
- },
- "execution_environment": {
- "kind": "host-mounted-toolchain" if host_mounted else "container",
- "identity": (
- "WSL2 Debian13; OSS CAD Suite /data/prod2u/oss-cad-suite/latest"
- if host_mounted else environment["image"]
- ),
- },
- "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": evidence_path(receipt_path),
- "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())
|