| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310 |
- #!/usr/bin/env python3
- """Run the eight non-UART 6400 architecture resource A/B trials."""
- from __future__ import annotations
- import argparse
- from datetime import datetime, timezone
- import hashlib
- import json
- import os
- from pathlib import Path
- import shutil
- import subprocess
- import sys
- import time
- ROOT = Path(__file__).resolve().parents[1]
- SOURCE = ROOT / "tests/resource/architecture_ab_candidates.v"
- TESTBENCH = ROOT / "tests/sim/resource_architecture_candidates_tb.v"
- FORMAL = ROOT / "tests/formal/resource_architecture_equivalence.sby"
- FORMAL_HARNESS = ROOT / "tests/formal/resource_architecture_equivalence_formal.v"
- TRIALS = {
- "fsm_encoding": {
- "label": "binary FSM vs one-hot FSM",
- "candidates": ("ab_fsm_binary", "ab_fsm_onehot"),
- "production": "ab_fsm_binary",
- "formal": "resource_architecture_equivalence",
- },
- "bmc_tx_serializer": {
- "label": "independent BMC TX vs shared TX",
- "candidates": ("ab_bmc_tx_dedicated", "ab_bmc_tx_shared"),
- "production": "ab_bmc_tx_dedicated",
- "formal": "not_applicable_shared_candidate_fails_required_concurrency",
- },
- "array_storage": {
- "label": "FF arrays vs inferred eRAM",
- "candidates": ("ab_store_ff", "ab_store_eram"),
- "production": "ab_store_eram",
- "formal": "identical_RTL_semantics_attributes_only",
- },
- "pi_form": {
- "label": "positional PI vs incremental PI",
- "candidates": ("ab_pi_positional", "ab_pi_incremental"),
- "production": "ab_pi_incremental",
- "formal": "resource_architecture_equivalence",
- },
- "safety_compare": {
- "label": "parallel safety compare vs sequential scan",
- "candidates": ("ab_safety_parallel", "ab_safety_sequential"),
- "production": "ab_safety_sequential",
- "formal": "production_P02_P04_P05_plus_transaction_simulation",
- },
- "atomic_commit": {
- "label": "element copy vs bank pointer",
- "candidates": ("ab_commit_copy", "ab_commit_bank"),
- "production": "ab_commit_bank",
- "formal": "production_P08_P09_plus_transaction_simulation",
- },
- "crc_datapath": {
- "label": "independent CRC vs RX/TX shared CRC",
- "candidates": ("ab_crc_independent", "ab_crc_shared"),
- "production": "ab_crc_independent",
- "formal": "resource_architecture_equivalence_nonoverlap_assumption",
- },
- "snapshot_materialization": {
- "label": "payload copy vs streaming snapshot",
- "candidates": ("ab_snapshot_copy", "ab_snapshot_stream"),
- "production": "ab_snapshot_stream",
- "formal": "production_P14_plus_all_193_offsets_simulation",
- },
- }
- TOOL_PROBES = {
- "python3": [sys.executable, "--version"],
- "iverilog": ["iverilog", "-V"],
- "vvp": ["vvp", "-V"],
- "verilator": ["verilator", "--version"],
- "yosys": ["yosys", "-V"],
- # This pinned SBY build has no version option; --help is its successful
- # identity probe and the executable digest supplies exact identity.
- "sby": ["sby", "--help"],
- "boolector": ["boolector", "--version"],
- "z3": ["z3", "--version"],
- }
- def sha256(path: Path) -> str:
- return hashlib.sha256(path.read_bytes()).hexdigest()
- def probe_tool(name: str, command: list[str]) -> dict[str, object]:
- executable = shutil.which(command[0])
- if executable is None:
- raise RuntimeError(f"missing required tool: {command[0]}")
- resolved = Path(executable).resolve()
- completed = subprocess.run(
- command,
- cwd=ROOT,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- text=True,
- check=False,
- )
- return {
- "name": name,
- "command": command,
- "exit_code": completed.returncode,
- "executable": str(resolved),
- "executable_sha256": sha256(resolved),
- "output": completed.stdout.strip(),
- }
- def git(*args: str) -> str:
- return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
- def run(command: list[str], *, cwd: Path, log: Path) -> dict[str, object]:
- started = time.monotonic()
- with log.open("wb") as stream:
- completed = subprocess.run(
- command,
- cwd=cwd,
- stdout=stream,
- stderr=subprocess.STDOUT,
- check=False,
- )
- return {
- "command": command,
- "exit_code": completed.returncode,
- "duration_seconds": round(time.monotonic() - started, 3),
- "log": str(log),
- "log_sha256": sha256(log),
- }
- def extract_json(text: str) -> dict[str, object]:
- marker = text.rfind('"creator":')
- start = text.rfind("{", 0, marker) if marker >= 0 else -1
- end = text.rfind("}")
- if start < 0 or end < start:
- raise RuntimeError("Yosys stat output did not contain JSON")
- return json.loads(text[start : end + 1])
- def yosys_stats(top: str, run_root: Path) -> dict[str, object]:
- log = run_root / f"yosys-{top}.log"
- script = (
- f"read_verilog -sv {SOURCE}; "
- f"hierarchy -check -top {top}; proc; opt; memory; opt; "
- f"techmap; opt; abc -lut 4; clean; stat -json"
- )
- # -q suppresses `stat -json` on Yosys 0.23, so retain command output while
- # omitting only the banner and footer.
- record = run(["yosys", "-Q", "-T", "-p", script], cwd=ROOT, log=log)
- if record["exit_code"] != 0:
- raise RuntimeError(f"Yosys failed for {top}: {log}")
- payload = extract_json(log.read_text(encoding="utf-8", errors="replace"))
- modules = payload.get("modules", {})
- if not isinstance(modules, dict) or not modules:
- raise RuntimeError(f"Yosys returned no module stats for {top}")
- module = next(iter(modules.values()))
- if not isinstance(module, dict):
- raise RuntimeError(f"malformed Yosys module stats for {top}")
- cells = module.get("num_cells_by_type", {})
- if not isinstance(cells, dict):
- cells = {}
- lut4 = sum(int(value) for name, value in cells.items() if "LUT" in name.upper())
- dff = sum(int(value) for name, value in cells.items() if "DFF" in name.upper())
- return {
- "top": top,
- "num_cells": int(module.get("num_cells", 0)),
- "lut4": lut4,
- "dff": dff,
- "memory_bits": int(module.get("num_memory_bits", 0)),
- "cell_types": cells,
- "yosys": record,
- }
- def main(argv: list[str] | None = None) -> int:
- parser = argparse.ArgumentParser()
- parser.add_argument("--output", type=Path)
- parser.add_argument("--run-root", type=Path)
- args = parser.parse_args(argv)
- for tool in ("iverilog", "vvp", "verilator", "yosys", "sby", "boolector", "z3"):
- if shutil.which(tool) is None:
- raise SystemExit(f"missing required tool: {tool}")
- toolchain = {name: probe_tool(name, command) for name, command in TOOL_PROBES.items()}
- failed_probes = [name for name, item in toolchain.items() if item["exit_code"] != 0]
- if failed_probes:
- raise SystemExit(f"tool identity probes failed: {', '.join(failed_probes)}")
- dirty = git("status", "--porcelain")
- if dirty:
- raise SystemExit(f"resource A/B requires a clean worktree:\n{dirty}")
- commit = git("rev-parse", "HEAD")
- tree = git("rev-parse", "HEAD^{tree}")
- stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
- run_id = f"6400-resource-ab-{stamp}-{commit[:8]}"
- run_root = args.run_root or Path(os.environ.get("PROD2U_RESOURCE_AB_RUN_ROOT", "/data/prod2u/cpld-runs")) / run_id
- run_root.mkdir(parents=True, exist_ok=False)
- simulation = run_root / "resource-architecture.vvp"
- compile_record = run(
- [
- "iverilog", "-g2012", "-Wall", "-s", "resource_architecture_candidates_tb",
- "-o", str(simulation), str(SOURCE), str(TESTBENCH),
- ],
- cwd=ROOT,
- log=run_root / "iverilog.log",
- )
- simulation_record = run(
- ["vvp", str(simulation)], cwd=ROOT, log=run_root / "simulation.log"
- ) if compile_record["exit_code"] == 0 else {"exit_code": 1, "reason": "compile_failed"}
- simulation_text = (run_root / "simulation.log").read_text(encoding="utf-8", errors="replace") if (run_root / "simulation.log").is_file() else ""
- behavior_pass = simulation_record["exit_code"] == 0 and "RESOURCE_ARCHITECTURE_AB_BEHAVIOR_PASS" in simulation_text
- lint_record = run(
- [
- "verilator", "--lint-only", "--Wall", "-Wno-fatal", "-Wno-MULTITOP",
- "-Wno-DECLFILENAME", "-Wno-UNUSEDSIGNAL", str(SOURCE),
- ],
- cwd=ROOT,
- log=run_root / "verilator.log",
- )
- formal_root = run_root / "formal"
- formal_record = run(
- ["sby", "-f", "--prefix", str(formal_root), str(FORMAL)],
- cwd=FORMAL.parent,
- log=run_root / "formal.log",
- )
- candidates: dict[str, dict[str, object]] = {}
- stats_failed = False
- for trial in TRIALS.values():
- for top in trial["candidates"]:
- if top in candidates:
- continue
- try:
- candidates[top] = yosys_stats(top, run_root)
- except Exception as exc:
- stats_failed = True
- candidates[top] = {"top": top, "error": f"{type(exc).__name__}: {exc}"}
- trials: dict[str, dict[str, object]] = {}
- for name, trial in TRIALS.items():
- first, second = trial["candidates"]
- function = {
- first: "PASS",
- second: "FAIL_REQUIRED_CONCURRENCY" if name == "bmc_tx_serializer" else "PASS",
- }
- trials[name] = {
- **trial,
- "function": function,
- "candidate_metrics": {first: candidates[first], second: candidates[second]},
- "td_timing": "PENDING_L13_TD_RESOURCE_RUN",
- "decision": (
- "retain_dedicated_required_concurrency"
- if name == "bmc_tx_serializer"
- else "retain_current_pending_TD_confirmation"
- ),
- }
- clean_after = not bool(git("status", "--porcelain"))
- status = "PASS" if (
- behavior_pass
- and lint_record["exit_code"] == 0
- and formal_record["exit_code"] == 0
- and not stats_failed
- and clean_after
- ) else "FAIL"
- receipt = {
- "schema": "prod2u-6400-architecture-resource-ab-v1",
- "run_id": run_id,
- "generated_at": datetime.now(timezone.utc).isoformat(),
- "status": status,
- "commit": commit,
- "tree": tree,
- "clean_before": not bool(dirty),
- "clean_after": clean_after,
- "command": "python3 tools/run_6400_architecture_ab.py",
- "inputs": {
- str(path.relative_to(ROOT)): sha256(path)
- for path in (SOURCE, TESTBENCH, FORMAL, FORMAL_HARNESS)
- },
- "behavior": {"status": "PASS" if behavior_pass else "FAIL", "compile": compile_record, "run": simulation_record},
- "lint": lint_record,
- "formal": formal_record,
- "toolchain": toolchain,
- "trials": trials,
- "container_image_id": os.environ.get("PROD2U_CONTAINER_IMAGE_ID"),
- "container_digest": os.environ.get("PROD2U_CONTAINER_DIGEST"),
- "hardware": "NOT RUN",
- }
- output = (args.output or run_root / "architecture-ab-receipt.json").resolve()
- repository = ROOT.resolve()
- if output == repository or repository in output.parents:
- raise SystemExit("resource A/B receipt must be written outside the source worktree")
- output.parent.mkdir(parents=True, exist_ok=True)
- output.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- print(output)
- print(f"RESOURCE_ARCHITECTURE_AB_{status} trials={len(TRIALS)}")
- return 0 if status == "PASS" else 1
- if __name__ == "__main__":
- raise SystemExit(main())
|