run_6400_td.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. #!/usr/bin/env python3
  2. """Run clean, source-bound TD synthesis, place/route, and bit generation."""
  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 subprocess
  13. import sys
  14. import time
  15. ROOT = Path(__file__).resolve().parents[1]
  16. PROJECT = ROOT / "products/6400-control/project.json"
  17. CLOSURE = ROOT / "products/6400-control/source-closure.json"
  18. TD_PROJECT = "td/prod2u_6400_front_back.prj"
  19. TD_FILES = (
  20. "td/syn/prod2u_6400_front_back.tcl",
  21. "td/phy/prod2u_6400_front_back.tcl",
  22. "td/bitgen/prod2u_6400_front_back.tcl",
  23. )
  24. CONSTRAINT_FILES = (
  25. "constraints/prod2u_6400_front_back.adc",
  26. "constraints/prod2u_6400_front_back.sdc",
  27. )
  28. def sha256(path: Path) -> str:
  29. digest = hashlib.sha256()
  30. with path.open("rb") as stream:
  31. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  32. digest.update(chunk)
  33. return digest.hexdigest()
  34. def git(*args: str) -> str:
  35. return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
  36. def input_manifest() -> dict[str, str]:
  37. closure = json.loads(CLOSURE.read_text(encoding="utf-8"))
  38. paths = [*closure["sources"], *CONSTRAINT_FILES, TD_PROJECT, *TD_FILES, str(PROJECT.relative_to(ROOT)), str(CLOSURE.relative_to(ROOT))]
  39. missing = [item for item in paths if not (ROOT / item).is_file()]
  40. if missing:
  41. raise RuntimeError(f"source closure contains missing inputs: {missing}")
  42. return {item: sha256(ROOT / item) for item in paths}
  43. def run_stage(name: str, command: list[str], cwd: Path, env: dict[str, str]) -> dict[str, object]:
  44. log_path = cwd / f"{name}.log"
  45. started = time.monotonic()
  46. with log_path.open("wb") as log:
  47. completed = subprocess.run(command, cwd=cwd, env=env, stdout=log, stderr=subprocess.STDOUT, check=False)
  48. duration = round(time.monotonic() - started, 3)
  49. return {
  50. "command": command,
  51. "cwd": str(cwd),
  52. "exit_code": completed.returncode,
  53. "duration_seconds": duration,
  54. "log": str(log_path),
  55. "log_sha256": sha256(log_path),
  56. }
  57. def first_int(text: str, patterns: tuple[str, ...]) -> int | None:
  58. for pattern in patterns:
  59. match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE)
  60. if match:
  61. return int(match.group(1))
  62. return None
  63. def first_float(text: str, patterns: tuple[str, ...]) -> float | None:
  64. for pattern in patterns:
  65. match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE)
  66. if match:
  67. return float(match.group(1))
  68. return None
  69. def parse_metrics(run_root: Path) -> dict[str, object]:
  70. area_paths = [
  71. run_root / "phy/prod2u_6400_front_back_phy.area",
  72. run_root / "syn/prod2u_6400_front_back_gate.area",
  73. ]
  74. area = "\n".join(path.read_text(encoding="utf-8", errors="replace") for path in area_paths if path.is_file())
  75. timing_path = run_root / "phy/prod2u_6400_front_back_pr.timing"
  76. timing = timing_path.read_text(encoding="utf-8", errors="replace") if timing_path.is_file() else ""
  77. return {
  78. "total_luts": first_int(area, (r"^#Total_luts\s+(\d+)",)),
  79. "lut": first_int(area, (r"^#lut\s+(\d+)",)),
  80. "registers": first_int(area, (r"^#reg\s+(\d+)",)),
  81. "dsp": first_int(area, (r"^#dsp\s+(\d+)",)),
  82. "bram": first_int(area, (r"^#bram\s+(\d+)",)),
  83. "mslice": first_int(area, (r"^#MSLICE\s+(\d+)", r"MSLICE\s*[:=]\s*(\d+)")),
  84. "lslice": first_int(area, (r"^#LSLICE\s+(\d+)", r"LSLICE\s*[:=]\s*(\d+)")),
  85. "packed_slices": first_int(area, (r"Packed(?:/Total)?\s+Slice\w*\s*[:=]\s*(\d+)",)),
  86. "fmax_mhz": first_float(timing, (r"Fmax[^\n]*?([0-9]+(?:\.[0-9]+)?)\s*MHz", r"([0-9]+(?:\.[0-9]+)?)\s*MHz")),
  87. "setup_slack_ns": first_float(timing, (r"(?:Setup|WNS)[^\n]*?(-?[0-9]+(?:\.[0-9]+)?)\s*ns",)),
  88. "hold_slack_ns": first_float(timing, (r"Hold[^\n]*?(-?[0-9]+(?:\.[0-9]+)?)\s*ns",)),
  89. "area_reports": [str(path) for path in area_paths if path.is_file()],
  90. "timing_report": str(timing_path) if timing_path.is_file() else None,
  91. }
  92. def warning_audit(stage_records: dict[str, dict[str, object]]) -> dict[str, object]:
  93. lines: list[str] = []
  94. blocking: list[str] = []
  95. blocker = re.compile(r"\b(error|fatal|timing violation|unrouted|not routed|setup failed|hold failed)\b", re.IGNORECASE)
  96. noteworthy = re.compile(r"\b(warn(?:ing)?|error|fatal|unconstrained|unassigned|latch|loop)\b", re.IGNORECASE)
  97. for record in stage_records.values():
  98. log = Path(str(record["log"]))
  99. for line in log.read_text(encoding="utf-8", errors="replace").splitlines():
  100. if noteworthy.search(line):
  101. compact = line.strip()
  102. if compact and compact not in lines:
  103. lines.append(compact)
  104. if blocker.search(compact):
  105. blocking.append(compact)
  106. return {
  107. "status": "FAIL" if blocking else "PASS",
  108. "noteworthy_count": len(lines),
  109. "blocking_count": len(blocking),
  110. "blocking": blocking[:100],
  111. "noteworthy": lines[:300],
  112. }
  113. def main(argv: list[str] | None = None) -> int:
  114. parser = argparse.ArgumentParser()
  115. parser.add_argument("--run-root", type=Path)
  116. args = parser.parse_args(argv)
  117. td = shutil.which("td2026")
  118. local_td = ROOT / "tools/td2026"
  119. if td is None and local_td.is_file():
  120. td = str(local_td)
  121. if td is None:
  122. print("TD_MISSING: td2026 is not on PATH", file=sys.stderr)
  123. return 4
  124. dirty_before = git("status", "--porcelain")
  125. if dirty_before:
  126. print("TD_BLOCKED: source worktree must be clean", file=sys.stderr)
  127. print(dirty_before, file=sys.stderr)
  128. return 3
  129. commit = git("rev-parse", "HEAD")
  130. tree = git("rev-parse", "HEAD^{tree}")
  131. stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
  132. run_id = f"6400-td-{stamp}-{commit[:8]}"
  133. run_root = args.run_root or Path(os.environ.get("PROD2U_TD_RUN_ROOT", "/data/prod2u/cpld-runs")) / run_id
  134. for stage in ("syn", "phy", "bitgen"):
  135. (run_root / stage).mkdir(parents=True, exist_ok=False)
  136. inputs = input_manifest()
  137. manifest_bytes = json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode()
  138. version_probe = subprocess.run([td, "-version"], capture_output=True, text=True, check=False)
  139. version_text = (version_probe.stdout + version_probe.stderr).strip()
  140. env = os.environ.copy()
  141. env["PROD2U_SOURCE_ROOT"] = str(ROOT)
  142. env["PATH"] = str(ROOT / "tools") + os.pathsep + env.get("PATH", "")
  143. stages: dict[str, dict[str, object]] = {}
  144. tcl = {
  145. "syn": ROOT / TD_FILES[0],
  146. "phy": ROOT / TD_FILES[1],
  147. "bitgen": ROOT / TD_FILES[2],
  148. }
  149. status = "PASS"
  150. for name in ("syn", "phy", "bitgen"):
  151. stages[name] = run_stage(name, [td, str(tcl[name])], run_root / name, env)
  152. print(f"{name}: exit={stages[name]['exit_code']} duration_s={stages[name]['duration_seconds']}", flush=True)
  153. if stages[name]["exit_code"] != 0:
  154. status = "FAIL"
  155. break
  156. expected = {
  157. "syn": run_root / "syn/prod2u_6400_front_back_gate.db",
  158. "phy": run_root / "phy/prod2u_6400_front_back_pr.db",
  159. "bitgen": run_root / "bitgen/prod2u_6400_front_back.bit",
  160. }
  161. missing = [name for name, path in expected.items() if name in stages and stages[name]["exit_code"] == 0 and not path.is_file()]
  162. if missing:
  163. status = "FAIL"
  164. audit = warning_audit(stages)
  165. if audit["status"] != "PASS":
  166. status = "FAIL"
  167. bitstream = expected["bitgen"]
  168. receipt = {
  169. "schema": "prod2u-6400-td-receipt-v1",
  170. "run_id": run_id,
  171. "status": status,
  172. "generated_at": datetime.now(timezone.utc).isoformat(),
  173. "commit": commit,
  174. "tree": tree,
  175. "branch": git("branch", "--show-current"),
  176. "clean_before": not bool(dirty_before),
  177. "clean_after": not bool(git("status", "--porcelain")),
  178. "project": str(PROJECT.relative_to(ROOT)),
  179. "project_sha256": sha256(PROJECT),
  180. "source_closure": str(CLOSURE.relative_to(ROOT)),
  181. "source_closure_sha256": sha256(CLOSURE),
  182. "source_manifest_sha256": hashlib.sha256(manifest_bytes).hexdigest(),
  183. "inputs": inputs,
  184. "tool": {
  185. "command": "td2026",
  186. "resolved": td,
  187. "version_probe_exit": version_probe.returncode,
  188. "version": version_text,
  189. "container_image_id": os.environ.get("PROD2U_CONTAINER_IMAGE_ID"),
  190. "container_digest": os.environ.get("PROD2U_CONTAINER_DIGEST"),
  191. },
  192. "safety": {"opens_serial": False, "programs_hardware": False, "jtag": False},
  193. "stages": stages,
  194. "missing_outputs": missing,
  195. "warning_audit": audit,
  196. "metrics": parse_metrics(run_root),
  197. "bitstream": str(bitstream) if bitstream.is_file() else None,
  198. "bitstream_sha256": sha256(bitstream) if bitstream.is_file() else None,
  199. }
  200. receipt_path = run_root / "td-receipt.json"
  201. receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  202. print(receipt_path)
  203. if status != "PASS":
  204. for name, record in stages.items():
  205. if record["exit_code"] != 0:
  206. log = Path(str(record["log"]))
  207. print(f"--- {name} log tail ---", file=sys.stderr)
  208. print("\n".join(log.read_text(encoding="utf-8", errors="replace").splitlines()[-120:]), file=sys.stderr)
  209. return 1
  210. print(f"TD_PASS bitstream_sha256={receipt['bitstream_sha256']}")
  211. return 0
  212. if __name__ == "__main__":
  213. raise SystemExit(main())