run_6400_architecture_td_ab.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. #!/usr/bin/env python3
  2. """Run device-backed TD resource/timing comparisons for 6400 A/B candidates."""
  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 re
  11. import shutil
  12. import signal
  13. import subprocess
  14. import sys
  15. import time
  16. ROOT = Path(__file__).resolve().parents[1]
  17. CANDIDATE_SOURCE = ROOT / "tests/resource/architecture_ab_candidates.v"
  18. PIN_CONSTRAINTS = ROOT / "constraints/prod2u_6400_architecture_ab.adc"
  19. TIMING_CONSTRAINTS = ROOT / "constraints/prod2u_6400_architecture_ab.sdc"
  20. TD_SCRIPT = ROOT / "td/resource/prod2u_6400_architecture_ab.tcl"
  21. TRIALS = {
  22. "fsm_encoding": ("ab_fsm_binary", "ab_fsm_onehot"),
  23. "bmc_tx_serializer": ("ab_bmc_tx_dedicated", "ab_bmc_tx_shared"),
  24. "array_storage": ("ab_store_ff", "ab_store_eram"),
  25. "pi_form": ("ab_pi_positional", "ab_pi_incremental"),
  26. "safety_compare": ("ab_safety_parallel", "ab_safety_sequential"),
  27. "atomic_commit": ("ab_commit_copy", "ab_commit_bank"),
  28. "crc_datapath": ("ab_crc_independent", "ab_crc_shared"),
  29. "snapshot_materialization": ("ab_snapshot_copy", "ab_snapshot_stream"),
  30. }
  31. CANDIDATES = tuple(top for pair in TRIALS.values() for top in pair)
  32. TIMING_MEASURED = "MEASURED_REGISTER_TO_REGISTER_PATH"
  33. TIMING_NOT_APPLICABLE = "NOT_APPLICABLE_NO_REG_TO_REG_PATH"
  34. def sha256(path: Path) -> str:
  35. digest = hashlib.sha256()
  36. with path.open("rb") as stream:
  37. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  38. digest.update(chunk)
  39. return digest.hexdigest()
  40. def git(*args: str) -> str:
  41. return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
  42. def first_int(text: str, patterns: tuple[str, ...]) -> int | None:
  43. for pattern in patterns:
  44. match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE)
  45. if match:
  46. return int(match.group(1))
  47. return None
  48. def first_float(text: str, patterns: tuple[str, ...]) -> float | None:
  49. for pattern in patterns:
  50. match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE)
  51. if match:
  52. return float(match.group(1))
  53. return None
  54. def run_bounded(
  55. command: list[str], *, cwd: Path, env: dict[str, str], log: Path, timeout: int
  56. ) -> dict[str, object]:
  57. started = time.monotonic()
  58. with log.open("wb") as stream:
  59. process = subprocess.Popen(
  60. command,
  61. cwd=cwd,
  62. env=env,
  63. stdout=stream,
  64. stderr=subprocess.STDOUT,
  65. start_new_session=(os.name == "posix"),
  66. )
  67. timed_out = False
  68. try:
  69. return_code = process.wait(timeout=timeout)
  70. except subprocess.TimeoutExpired:
  71. timed_out = True
  72. if os.name == "posix":
  73. try:
  74. os.killpg(process.pid, signal.SIGKILL)
  75. except ProcessLookupError:
  76. pass
  77. else:
  78. process.kill()
  79. return_code = process.wait()
  80. return {
  81. "command": command,
  82. "cwd": str(cwd),
  83. "exit_code": return_code,
  84. "timed_out": timed_out,
  85. "timeout_seconds": timeout,
  86. "duration_seconds": round(time.monotonic() - started, 3),
  87. "log": str(log),
  88. "log_sha256": sha256(log),
  89. }
  90. def parse_candidate(top: str, root: Path) -> dict[str, object]:
  91. area_paths = [root / f"{top}_gate.area", root / f"{top}_pr.area"]
  92. timing_path = root / f"{top}_pr.timing"
  93. log_path = root / "td.log"
  94. area = "\n".join(
  95. path.read_text(encoding="utf-8", errors="replace")
  96. for path in area_paths
  97. if path.is_file()
  98. )
  99. timing = timing_path.read_text(encoding="utf-8", errors="replace") if timing_path.is_file() else ""
  100. log_text = log_path.read_text(encoding="utf-8", errors="replace") if log_path.is_file() else ""
  101. slice_matches = re.findall(r"(\d+)\s+mslices,\s+(\d+)\s+lslices", log_text, re.IGNORECASE)
  102. mslice = int(slice_matches[-1][0]) if slice_matches else None
  103. lslice = int(slice_matches[-1][1]) if slice_matches else None
  104. reported_total_luts = first_int(area, (r"^#Total_luts\s+(\d+)",))
  105. lut = first_int(area, (r"^#lut\s+(\d+)",))
  106. fmax_mhz = first_float(
  107. timing,
  108. (r"Fmax[^\n]*?([0-9]+(?:\.[0-9]+)?)\s*MHz", r"([0-9]+(?:\.[0-9]+)?)\s*MHz"),
  109. )
  110. register_to_register_path = bool(
  111. re.search(r"^From Clock\s*:\s*\S+", timing, re.IGNORECASE | re.MULTILINE)
  112. and re.search(r"^To Clock\s*:\s*\S+", timing, re.IGNORECASE | re.MULTILINE)
  113. )
  114. violation_endpoint_counts = [
  115. int(value)
  116. for value in re.findall(r"(\d+)\s+Viol Endpoints", timing, re.IGNORECASE)
  117. ]
  118. metrics = {
  119. "total_luts": reported_total_luts if reported_total_luts is not None else lut,
  120. "total_luts_source": "#Total_luts" if reported_total_luts is not None else "#lut_fallback",
  121. "lut": lut,
  122. "registers": first_int(area, (r"^#reg\s+(\d+)",)),
  123. "dsp": first_int(area, (r"^#dsp\s+(\d+)",)),
  124. "eram_bram": first_int(area, (r"^#(?:eram|bram)\s+(\d+)",)),
  125. "mslice": mslice,
  126. "lslice": lslice,
  127. "packed_slices": mslice + lslice if mslice is not None and lslice is not None else None,
  128. "packed_slices_derivation": "mslice_plus_lslice",
  129. "fmax_mhz": fmax_mhz,
  130. "timing_applicability": (
  131. TIMING_MEASURED if register_to_register_path else TIMING_NOT_APPLICABLE
  132. ),
  133. "register_to_register_path_present": register_to_register_path,
  134. "violation_endpoint_counts": violation_endpoint_counts,
  135. "all_violation_endpoint_counts_zero": all(
  136. value == 0 for value in violation_endpoint_counts
  137. ),
  138. "setup_slack_ns": first_float(
  139. timing,
  140. (
  141. r"^\s*SWNS\s*:\s*(-?[0-9]+(?:\.[0-9]+)?)\s*ns",
  142. r"(?:Setup|WNS)[^\n]*?(-?[0-9]+(?:\.[0-9]+)?)\s*ns",
  143. ),
  144. ),
  145. "hold_slack_ns": first_float(
  146. timing,
  147. (
  148. r"^\s*HWNS\s*:\s*(-?[0-9]+(?:\.[0-9]+)?)\s*ns",
  149. r"(?:Hold|HWNS)[^\n]*?(-?[0-9]+(?:\.[0-9]+)?)\s*ns",
  150. ),
  151. ),
  152. }
  153. return {
  154. "metrics": metrics,
  155. "area_reports": [
  156. {"path": str(path), "sha256": sha256(path)} for path in area_paths if path.is_file()
  157. ],
  158. "timing_report": (
  159. {"path": str(timing_path), "sha256": sha256(timing_path)}
  160. if timing_path.is_file()
  161. else None
  162. ),
  163. }
  164. def evaluate_timing(metrics: dict[str, object]) -> dict[str, object]:
  165. """Evaluate timing while distinguishing designs with no reg-to-reg path."""
  166. setup_slack = metrics["setup_slack_ns"]
  167. hold_slack = metrics["hold_slack_ns"]
  168. violation_counts = metrics["violation_endpoint_counts"]
  169. common_pass = bool(
  170. setup_slack is not None
  171. and hold_slack is not None
  172. and setup_slack >= 0.0
  173. and hold_slack >= 0.0
  174. and all(value == 0 for value in violation_counts)
  175. )
  176. applicability = metrics["timing_applicability"]
  177. if applicability == TIMING_NOT_APPLICABLE:
  178. passed = common_pass and metrics["fmax_mhz"] is None
  179. return {
  180. "status": "PASS" if passed else "FAIL",
  181. "classification": TIMING_NOT_APPLICABLE,
  182. "fmax_requirement": "NOT_APPLICABLE",
  183. "meets_25mhz": None,
  184. "reason": (
  185. "No register-to-register path; all reported setup/hold slacks and "
  186. "violation counts are non-negative/zero."
  187. if passed
  188. else "No register-to-register path, but timing status is incomplete or failing."
  189. ),
  190. }
  191. fmax_mhz = metrics["fmax_mhz"]
  192. passed = bool(
  193. common_pass
  194. and violation_counts
  195. and fmax_mhz is not None
  196. and fmax_mhz >= 25.0
  197. )
  198. return {
  199. "status": "PASS" if passed else "FAIL",
  200. "classification": TIMING_MEASURED,
  201. "fmax_requirement": "AT_LEAST_25_MHZ",
  202. "meets_25mhz": bool(fmax_mhz is not None and fmax_mhz >= 25.0),
  203. "reason": (
  204. "Register-to-register Fmax and all setup/hold checks pass."
  205. if passed
  206. else "Register-to-register timing is missing, below 25 MHz, or has violations."
  207. ),
  208. }
  209. def warning_audit(log_path: Path) -> dict[str, object]:
  210. lines = log_path.read_text(encoding="utf-8", errors="replace").splitlines()
  211. severity = re.compile(
  212. r"^\s*(?:(?:[A-Z][A-Z0-9_-]*-\d+)\s+)?"
  213. r"(?:CRITICAL-WARNING|WARNING|ERROR|FATAL)\s*:",
  214. re.IGNORECASE,
  215. )
  216. noteworthy = [
  217. line.strip()
  218. for line in lines
  219. if severity.search(line)
  220. or re.search(
  221. r"Bitgen will abort|No ADC ports:|\bunrouted\b|\bviolations?\b",
  222. line,
  223. re.IGNORECASE,
  224. )
  225. ]
  226. allowlisted = [
  227. line
  228. for line in noteworthy
  229. if re.search(r"\bSYN-6021\b|Bitgen will abort|No ADC ports:", line, re.IGNORECASE)
  230. ]
  231. blocking_patterns = (
  232. re.compile(
  233. r"^\s*(?:(?:[A-Z][A-Z0-9_-]*-\d+)\s+)?(?:ERROR|FATAL)\s*:",
  234. re.IGNORECASE,
  235. ),
  236. re.compile(r"^\s*\[(?:ERROR|FATAL)\]", re.IGNORECASE),
  237. re.compile(
  238. r"\b(?:synthesis|placement|place\s*&\s*route|routing|route|fit|bitgen)"
  239. r"\s+(?:failed|failure)\b",
  240. re.IGNORECASE,
  241. ),
  242. re.compile(r"\b(?:setup|hold|timing)\s+(?:check\s+)?(?:failed|failure)\b", re.IGNORECASE),
  243. re.compile(r"(?:\b[1-9]\d*\s+unrouted\b|\bunrouted\s*[:=]\s*[1-9]\d*)", re.IGNORECASE),
  244. )
  245. blocking = [
  246. line
  247. for line in noteworthy
  248. if any(pattern.search(line) for pattern in blocking_patterns)
  249. ]
  250. return {
  251. "status": "FAIL" if blocking else "PASS",
  252. "noteworthy_count": len(noteworthy),
  253. "blocking_count": len(blocking),
  254. "allowlisted_expected_count": len(allowlisted),
  255. "allowlisted_expected": allowlisted[:100],
  256. "noteworthy": noteworthy[:200],
  257. "blocking": blocking[:100],
  258. }
  259. def main(argv: list[str] | None = None) -> int:
  260. parser = argparse.ArgumentParser()
  261. parser.add_argument("--run-root", type=Path)
  262. parser.add_argument("--timeout-seconds", type=int, default=900)
  263. args = parser.parse_args(argv)
  264. td = shutil.which("td2026")
  265. local_td = ROOT / "tools/td2026"
  266. if td is None and local_td.is_file():
  267. td = str(local_td)
  268. if td is None:
  269. print("TD_AB_MISSING: td2026 is not on PATH", file=sys.stderr)
  270. return 4
  271. dirty = git("status", "--porcelain")
  272. if dirty:
  273. print("TD_AB_BLOCKED: source worktree must be clean", file=sys.stderr)
  274. print(dirty, file=sys.stderr)
  275. return 3
  276. if args.timeout_seconds <= 0:
  277. raise SystemExit("--timeout-seconds must be positive")
  278. commit = git("rev-parse", "HEAD")
  279. tree = git("rev-parse", "HEAD^{tree}")
  280. stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
  281. run_id = f"6400-architecture-td-ab-{stamp}-{commit[:8]}"
  282. run_root = args.run_root or Path(
  283. os.environ.get("PROD2U_TD_AB_RUN_ROOT", "/data/prod2u/cpld-runs")
  284. ) / run_id
  285. run_root.mkdir(parents=True, exist_ok=False)
  286. version = subprocess.run([td, "-version"], capture_output=True, text=True, check=False)
  287. version_text = (version.stdout + version.stderr).strip()
  288. resolved_td = Path(td).resolve()
  289. vendor_td = Path(os.environ.get("PRODU2_TD_ROOT", "/data/anlogic/TD_Release_2026.1_SP2_NL")) / "bin/td"
  290. env_base = os.environ.copy()
  291. env_base["PROD2U_SOURCE_ROOT"] = str(ROOT)
  292. candidate_records: dict[str, dict[str, object]] = {}
  293. status = "PASS"
  294. for top in CANDIDATES:
  295. candidate_root = run_root / top
  296. candidate_root.mkdir()
  297. env = env_base.copy()
  298. env["PROD2U_AB_TOP"] = top
  299. run = run_bounded(
  300. [td, str(TD_SCRIPT)],
  301. cwd=candidate_root,
  302. env=env,
  303. log=candidate_root / "td.log",
  304. timeout=args.timeout_seconds,
  305. )
  306. outputs = {
  307. "gate_db": candidate_root / f"{top}_gate.db",
  308. "pr_db": candidate_root / f"{top}_pr.db",
  309. }
  310. missing = [name for name, path in outputs.items() if not path.is_file()]
  311. parsed = parse_candidate(top, candidate_root)
  312. audit = warning_audit(candidate_root / "td.log")
  313. metrics = parsed["metrics"]
  314. required_metrics = (
  315. "total_luts", "lut", "registers", "dsp", "eram_bram", "mslice",
  316. "lslice", "packed_slices", "setup_slack_ns", "hold_slack_ns",
  317. )
  318. missing_metrics = [name for name in required_metrics if metrics[name] is None]
  319. if (
  320. metrics["timing_applicability"] == TIMING_MEASURED
  321. and metrics["fmax_mhz"] is None
  322. ):
  323. missing_metrics.append("fmax_mhz")
  324. timing_evaluation = evaluate_timing(metrics)
  325. timing_pass = timing_evaluation["status"] == "PASS"
  326. candidate_status = "PASS" if (
  327. run["exit_code"] == 0
  328. and not run["timed_out"]
  329. and not missing
  330. and not missing_metrics
  331. and timing_pass
  332. and audit["status"] == "PASS"
  333. ) else "FAIL"
  334. if candidate_status != "PASS":
  335. status = "FAIL"
  336. candidate_records[top] = {
  337. "status": candidate_status,
  338. "run": run,
  339. "missing_outputs": missing,
  340. "missing_metrics": missing_metrics,
  341. "timing_pass_25mhz": timing_pass,
  342. "timing_evaluation": timing_evaluation,
  343. "warning_audit": audit,
  344. "outputs": {
  345. name: {"path": str(path), "sha256": sha256(path)}
  346. for name, path in outputs.items()
  347. if path.is_file()
  348. },
  349. **parsed,
  350. }
  351. print(
  352. f"{top}: {candidate_status} exit={run['exit_code']} "
  353. f"timeout={run['timed_out']} duration_s={run['duration_seconds']}",
  354. flush=True,
  355. )
  356. trial_records = {
  357. name: {
  358. "candidates": pair,
  359. "results": {top: candidate_records[top] for top in pair},
  360. }
  361. for name, pair in TRIALS.items()
  362. }
  363. clean_after = not bool(git("status", "--porcelain"))
  364. if not clean_after:
  365. status = "FAIL"
  366. receipt = {
  367. "schema": "prod2u-6400-architecture-td-ab-v1",
  368. "run_id": run_id,
  369. "generated_at": datetime.now(timezone.utc).isoformat(),
  370. "status": status,
  371. "commit": commit,
  372. "tree": tree,
  373. "branch": git("branch", "--show-current"),
  374. "clean_before": not bool(dirty),
  375. "clean_after": clean_after,
  376. "command": "python3 tools/run_6400_architecture_td_ab.py",
  377. "inputs": {
  378. str(path.relative_to(ROOT)): sha256(path)
  379. for path in (CANDIDATE_SOURCE, PIN_CONSTRAINTS, TIMING_CONSTRAINTS, TD_SCRIPT)
  380. },
  381. "tool": {
  382. "wrapper": str(resolved_td),
  383. "wrapper_sha256": sha256(resolved_td),
  384. "vendor_binary": str(vendor_td),
  385. "vendor_binary_sha256": sha256(vendor_td) if vendor_td.is_file() else None,
  386. "version_probe_exit": version.returncode,
  387. "version": version_text,
  388. "container_image_id": os.environ.get("PROD2U_CONTAINER_IMAGE_ID"),
  389. "container_digest": os.environ.get("PROD2U_CONTAINER_DIGEST"),
  390. },
  391. "trials": trial_records,
  392. "hardware": "NOT RUN",
  393. "jtag": "NOT RUN",
  394. "com": "NOT RUN",
  395. }
  396. receipt_path = run_root / "architecture-td-ab-receipt.json"
  397. receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  398. print(receipt_path)
  399. print(f"RESOURCE_ARCHITECTURE_TD_AB_{status} trials={len(TRIALS)} candidates={len(CANDIDATES)}")
  400. return 0 if status == "PASS" else 1
  401. if __name__ == "__main__":
  402. raise SystemExit(main())