run_6400_architecture_ab.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. #!/usr/bin/env python3
  2. """Run the eight non-UART 6400 architecture resource A/B trials."""
  3. from __future__ import annotations
  4. import argparse
  5. from datetime import datetime, timezone
  6. import hashlib
  7. import json
  8. import os
  9. from pathlib import Path
  10. import shutil
  11. import subprocess
  12. import sys
  13. import time
  14. ROOT = Path(__file__).resolve().parents[1]
  15. SOURCE = ROOT / "tests/resource/architecture_ab_candidates.v"
  16. TESTBENCH = ROOT / "tests/sim/resource_architecture_candidates_tb.v"
  17. FORMAL = ROOT / "tests/formal/resource_architecture_equivalence.sby"
  18. FORMAL_HARNESS = ROOT / "tests/formal/resource_architecture_equivalence_formal.v"
  19. TRIALS = {
  20. "fsm_encoding": {
  21. "label": "binary FSM vs one-hot FSM",
  22. "candidates": ("ab_fsm_binary", "ab_fsm_onehot"),
  23. "production": "ab_fsm_binary",
  24. "formal": "resource_architecture_equivalence",
  25. },
  26. "bmc_tx_serializer": {
  27. "label": "independent BMC TX vs shared TX",
  28. "candidates": ("ab_bmc_tx_dedicated", "ab_bmc_tx_shared"),
  29. "production": "ab_bmc_tx_dedicated",
  30. "formal": "not_applicable_shared_candidate_fails_required_concurrency",
  31. },
  32. "array_storage": {
  33. "label": "FF arrays vs inferred eRAM",
  34. "candidates": ("ab_store_ff", "ab_store_eram"),
  35. "production": "ab_store_eram",
  36. "formal": "identical_RTL_semantics_attributes_only",
  37. },
  38. "pi_form": {
  39. "label": "positional PI vs incremental PI",
  40. "candidates": ("ab_pi_positional", "ab_pi_incremental"),
  41. "production": "ab_pi_incremental",
  42. "formal": "resource_architecture_equivalence",
  43. },
  44. "safety_compare": {
  45. "label": "parallel safety compare vs sequential scan",
  46. "candidates": ("ab_safety_parallel", "ab_safety_sequential"),
  47. "production": "ab_safety_sequential",
  48. "formal": "production_P02_P04_P05_plus_transaction_simulation",
  49. },
  50. "atomic_commit": {
  51. "label": "element copy vs bank pointer",
  52. "candidates": ("ab_commit_copy", "ab_commit_bank"),
  53. "production": "ab_commit_bank",
  54. "formal": "production_P08_P09_plus_transaction_simulation",
  55. },
  56. "crc_datapath": {
  57. "label": "independent CRC vs RX/TX shared CRC",
  58. "candidates": ("ab_crc_independent", "ab_crc_shared"),
  59. "production": "ab_crc_independent",
  60. "formal": "resource_architecture_equivalence_nonoverlap_assumption",
  61. },
  62. "snapshot_materialization": {
  63. "label": "payload copy vs streaming snapshot",
  64. "candidates": ("ab_snapshot_copy", "ab_snapshot_stream"),
  65. "production": "ab_snapshot_stream",
  66. "formal": "production_P14_plus_all_193_offsets_simulation",
  67. },
  68. }
  69. TOOL_PROBES = {
  70. "python3": [sys.executable, "--version"],
  71. "iverilog": ["iverilog", "-V"],
  72. "vvp": ["vvp", "-V"],
  73. "verilator": ["verilator", "--version"],
  74. "yosys": ["yosys", "-V"],
  75. # This pinned SBY build has no version option; --help is its successful
  76. # identity probe and the executable digest supplies exact identity.
  77. "sby": ["sby", "--help"],
  78. "boolector": ["boolector", "--version"],
  79. "z3": ["z3", "--version"],
  80. }
  81. def sha256(path: Path) -> str:
  82. return hashlib.sha256(path.read_bytes()).hexdigest()
  83. def probe_tool(name: str, command: list[str]) -> dict[str, object]:
  84. executable = shutil.which(command[0])
  85. if executable is None:
  86. raise RuntimeError(f"missing required tool: {command[0]}")
  87. resolved = Path(executable).resolve()
  88. completed = subprocess.run(
  89. command,
  90. cwd=ROOT,
  91. stdout=subprocess.PIPE,
  92. stderr=subprocess.STDOUT,
  93. text=True,
  94. check=False,
  95. )
  96. return {
  97. "name": name,
  98. "command": command,
  99. "exit_code": completed.returncode,
  100. "executable": str(resolved),
  101. "executable_sha256": sha256(resolved),
  102. "output": completed.stdout.strip(),
  103. }
  104. def git(*args: str) -> str:
  105. return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
  106. def run(command: list[str], *, cwd: Path, log: Path) -> dict[str, object]:
  107. started = time.monotonic()
  108. with log.open("wb") as stream:
  109. completed = subprocess.run(
  110. command,
  111. cwd=cwd,
  112. stdout=stream,
  113. stderr=subprocess.STDOUT,
  114. check=False,
  115. )
  116. return {
  117. "command": command,
  118. "exit_code": completed.returncode,
  119. "duration_seconds": round(time.monotonic() - started, 3),
  120. "log": str(log),
  121. "log_sha256": sha256(log),
  122. }
  123. def extract_json(text: str) -> dict[str, object]:
  124. marker = text.rfind('"creator":')
  125. start = text.rfind("{", 0, marker) if marker >= 0 else -1
  126. end = text.rfind("}")
  127. if start < 0 or end < start:
  128. raise RuntimeError("Yosys stat output did not contain JSON")
  129. return json.loads(text[start : end + 1])
  130. def yosys_stats(top: str, run_root: Path) -> dict[str, object]:
  131. log = run_root / f"yosys-{top}.log"
  132. script = (
  133. f"read_verilog -sv {SOURCE}; "
  134. f"hierarchy -check -top {top}; proc; opt; memory; opt; "
  135. f"techmap; opt; abc -lut 4; clean; stat -json"
  136. )
  137. # -q suppresses `stat -json` on Yosys 0.23, so retain command output while
  138. # omitting only the banner and footer.
  139. record = run(["yosys", "-Q", "-T", "-p", script], cwd=ROOT, log=log)
  140. if record["exit_code"] != 0:
  141. raise RuntimeError(f"Yosys failed for {top}: {log}")
  142. payload = extract_json(log.read_text(encoding="utf-8", errors="replace"))
  143. modules = payload.get("modules", {})
  144. if not isinstance(modules, dict) or not modules:
  145. raise RuntimeError(f"Yosys returned no module stats for {top}")
  146. module = next(iter(modules.values()))
  147. if not isinstance(module, dict):
  148. raise RuntimeError(f"malformed Yosys module stats for {top}")
  149. cells = module.get("num_cells_by_type", {})
  150. if not isinstance(cells, dict):
  151. cells = {}
  152. lut4 = sum(int(value) for name, value in cells.items() if "LUT" in name.upper())
  153. dff = sum(int(value) for name, value in cells.items() if "DFF" in name.upper())
  154. return {
  155. "top": top,
  156. "num_cells": int(module.get("num_cells", 0)),
  157. "lut4": lut4,
  158. "dff": dff,
  159. "memory_bits": int(module.get("num_memory_bits", 0)),
  160. "cell_types": cells,
  161. "yosys": record,
  162. }
  163. def main(argv: list[str] | None = None) -> int:
  164. parser = argparse.ArgumentParser()
  165. parser.add_argument("--output", type=Path)
  166. parser.add_argument("--run-root", type=Path)
  167. args = parser.parse_args(argv)
  168. for tool in ("iverilog", "vvp", "verilator", "yosys", "sby", "boolector", "z3"):
  169. if shutil.which(tool) is None:
  170. raise SystemExit(f"missing required tool: {tool}")
  171. toolchain = {name: probe_tool(name, command) for name, command in TOOL_PROBES.items()}
  172. failed_probes = [name for name, item in toolchain.items() if item["exit_code"] != 0]
  173. if failed_probes:
  174. raise SystemExit(f"tool identity probes failed: {', '.join(failed_probes)}")
  175. dirty = git("status", "--porcelain")
  176. if dirty:
  177. raise SystemExit(f"resource A/B requires a clean worktree:\n{dirty}")
  178. commit = git("rev-parse", "HEAD")
  179. tree = git("rev-parse", "HEAD^{tree}")
  180. stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
  181. run_id = f"6400-resource-ab-{stamp}-{commit[:8]}"
  182. run_root = args.run_root or Path(os.environ.get("PROD2U_RESOURCE_AB_RUN_ROOT", "/data/prod2u/cpld-runs")) / run_id
  183. run_root.mkdir(parents=True, exist_ok=False)
  184. simulation = run_root / "resource-architecture.vvp"
  185. compile_record = run(
  186. [
  187. "iverilog", "-g2012", "-Wall", "-s", "resource_architecture_candidates_tb",
  188. "-o", str(simulation), str(SOURCE), str(TESTBENCH),
  189. ],
  190. cwd=ROOT,
  191. log=run_root / "iverilog.log",
  192. )
  193. simulation_record = run(
  194. ["vvp", str(simulation)], cwd=ROOT, log=run_root / "simulation.log"
  195. ) if compile_record["exit_code"] == 0 else {"exit_code": 1, "reason": "compile_failed"}
  196. simulation_text = (run_root / "simulation.log").read_text(encoding="utf-8", errors="replace") if (run_root / "simulation.log").is_file() else ""
  197. behavior_pass = simulation_record["exit_code"] == 0 and "RESOURCE_ARCHITECTURE_AB_BEHAVIOR_PASS" in simulation_text
  198. lint_record = run(
  199. [
  200. "verilator", "--lint-only", "--Wall", "-Wno-fatal", "-Wno-MULTITOP",
  201. "-Wno-DECLFILENAME", "-Wno-UNUSEDSIGNAL", str(SOURCE),
  202. ],
  203. cwd=ROOT,
  204. log=run_root / "verilator.log",
  205. )
  206. formal_root = run_root / "formal"
  207. formal_record = run(
  208. ["sby", "-f", "--prefix", str(formal_root), str(FORMAL)],
  209. cwd=FORMAL.parent,
  210. log=run_root / "formal.log",
  211. )
  212. candidates: dict[str, dict[str, object]] = {}
  213. stats_failed = False
  214. for trial in TRIALS.values():
  215. for top in trial["candidates"]:
  216. if top in candidates:
  217. continue
  218. try:
  219. candidates[top] = yosys_stats(top, run_root)
  220. except Exception as exc:
  221. stats_failed = True
  222. candidates[top] = {"top": top, "error": f"{type(exc).__name__}: {exc}"}
  223. trials: dict[str, dict[str, object]] = {}
  224. for name, trial in TRIALS.items():
  225. first, second = trial["candidates"]
  226. function = {
  227. first: "PASS",
  228. second: "FAIL_REQUIRED_CONCURRENCY" if name == "bmc_tx_serializer" else "PASS",
  229. }
  230. trials[name] = {
  231. **trial,
  232. "function": function,
  233. "candidate_metrics": {first: candidates[first], second: candidates[second]},
  234. "td_timing": "PENDING_L13_TD_RESOURCE_RUN",
  235. "decision": (
  236. "retain_dedicated_required_concurrency"
  237. if name == "bmc_tx_serializer"
  238. else "retain_current_pending_TD_confirmation"
  239. ),
  240. }
  241. clean_after = not bool(git("status", "--porcelain"))
  242. status = "PASS" if (
  243. behavior_pass
  244. and lint_record["exit_code"] == 0
  245. and formal_record["exit_code"] == 0
  246. and not stats_failed
  247. and clean_after
  248. ) else "FAIL"
  249. receipt = {
  250. "schema": "prod2u-6400-architecture-resource-ab-v1",
  251. "run_id": run_id,
  252. "generated_at": datetime.now(timezone.utc).isoformat(),
  253. "status": status,
  254. "commit": commit,
  255. "tree": tree,
  256. "clean_before": not bool(dirty),
  257. "clean_after": clean_after,
  258. "command": "python3 tools/run_6400_architecture_ab.py",
  259. "inputs": {
  260. str(path.relative_to(ROOT)): sha256(path)
  261. for path in (SOURCE, TESTBENCH, FORMAL, FORMAL_HARNESS)
  262. },
  263. "behavior": {"status": "PASS" if behavior_pass else "FAIL", "compile": compile_record, "run": simulation_record},
  264. "lint": lint_record,
  265. "formal": formal_record,
  266. "toolchain": toolchain,
  267. "trials": trials,
  268. "container_image_id": os.environ.get("PROD2U_CONTAINER_IMAGE_ID"),
  269. "container_digest": os.environ.get("PROD2U_CONTAINER_DIGEST"),
  270. "hardware": "NOT RUN",
  271. }
  272. output = (args.output or run_root / "architecture-ab-receipt.json").resolve()
  273. repository = ROOT.resolve()
  274. if output == repository or repository in output.parents:
  275. raise SystemExit("resource A/B receipt must be written outside the source worktree")
  276. output.parent.mkdir(parents=True, exist_ok=True)
  277. output.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  278. print(output)
  279. print(f"RESOURCE_ARCHITECTURE_AB_{status} trials={len(TRIALS)}")
  280. return 0 if status == "PASS" else 1
  281. if __name__ == "__main__":
  282. raise SystemExit(main())