run_verification_matrix.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. """Run the Prod2U CPLD offline verification matrix with bounded concurrency.
  2. Each lane uses an independent work root and receipt. A failed lane does not
  3. cancel unrelated lanes. Missing toolchains produce `blocked` or `not_run`, never
  4. a fabricated pass. Long tasks use tools/run_visible.py for live heartbeat.
  5. """
  6. from __future__ import annotations
  7. import argparse
  8. import json
  9. import os
  10. import sys
  11. import time
  12. import uuid
  13. from concurrent.futures import ThreadPoolExecutor, as_completed
  14. from datetime import datetime, timezone
  15. from pathlib import Path
  16. from typing import Any, Callable
  17. _repo_root = Path(__file__).resolve().parents[1]
  18. if str(_repo_root) not in sys.path:
  19. sys.path.insert(0, str(_repo_root))
  20. from tools import prod2u_p4_harness # noqa: E402
  21. from tools.run_visible import run_visible # noqa: E402
  22. DEFAULT_LANES = [
  23. "python",
  24. "board_viewer",
  25. "icarus",
  26. "verilator",
  27. "cocotb",
  28. "formal",
  29. "td",
  30. ]
  31. # TD is exclusive; keep open-source concurrency modest on ~3 GiB hosts.
  32. DEFAULT_MAX_WORKERS = 2
  33. TD_EXCLUSIVE = frozenset({"td"})
  34. def _utc_now() -> str:
  35. return datetime.now(timezone.utc).isoformat()
  36. def _sha256_file(path: Path) -> str:
  37. return prod2u_p4_harness.sha256_file(path)
  38. def _write_json(path: Path, payload: dict[str, Any]) -> None:
  39. path.parent.mkdir(parents=True, exist_ok=True)
  40. path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  41. def _run_visible_cmd(
  42. cmd: list[str],
  43. *,
  44. cwd: Path,
  45. log_path: Path,
  46. status_path: Path,
  47. name: str,
  48. timeout_s: float | None,
  49. env: dict[str, str] | None = None,
  50. ) -> int:
  51. # Strip Anlogic libs for non-TD lanes so apt/python stay healthy.
  52. clean = os.environ.copy()
  53. if name != "td":
  54. for key in ("LD_LIBRARY_PATH", "LD_PRELOAD", "QT_PLUGIN_PATH"):
  55. clean.pop(key, None)
  56. if env:
  57. clean.update(env)
  58. return run_visible(
  59. cmd,
  60. cwd=cwd,
  61. env=clean,
  62. log_path=log_path,
  63. status_path=status_path,
  64. name=name,
  65. timeout_s=timeout_s,
  66. )
  67. def run_python_unit(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]:
  68. receipt_path = work_root / "python-unit-receipt.json"
  69. log_path = work_root / "python-unit.log"
  70. status_path = work_root / "python-unit.status.json"
  71. work_root.mkdir(parents=True, exist_ok=True)
  72. cmd = [
  73. sys.executable,
  74. "-B",
  75. "-m",
  76. "pytest",
  77. "-q",
  78. "-p",
  79. "no:cacheprovider",
  80. "tests/unit",
  81. "tests/test_project_structure.py",
  82. ]
  83. code = _run_visible_cmd(
  84. cmd,
  85. cwd=repo,
  86. log_path=log_path,
  87. status_path=status_path,
  88. name="python",
  89. timeout_s=600,
  90. )
  91. status = "pass" if code == 0 else "fail"
  92. full_commit = prod2u_p4_harness.current_commit()
  93. receipt = {
  94. "schema": "prod2u-p4-normal-v3-python-unit-receipt-v1",
  95. "status": status,
  96. "verification_run_id": run_id,
  97. "commit": full_commit,
  98. "commit_full": full_commit,
  99. "project_config_sha256": _sha256_file(repo / "projects" / "prod2u-door-temp" / "project.json"),
  100. "td_source_manifest_sha256": _sha256_file(repo / "src" / "generated" / "td-source-manifest.json"),
  101. "command": " ".join(cmd),
  102. "tool_version": f"Python {sys.version.split()[0]}",
  103. "returncode": code,
  104. "log_path": str(log_path),
  105. "status_path": str(status_path),
  106. "report_path": str(receipt_path),
  107. }
  108. _write_json(receipt_path, receipt)
  109. return receipt
  110. def run_board_viewer(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]:
  111. receipt_path = work_root / "board-viewer-receipt.json"
  112. log_path = work_root / "board-viewer.log"
  113. status_path = work_root / "board-viewer.status.json"
  114. work_root.mkdir(parents=True, exist_ok=True)
  115. cmd = [
  116. sys.executable,
  117. "-B",
  118. "-m",
  119. "pytest",
  120. "-q",
  121. "-p",
  122. "no:cacheprovider",
  123. "tests/board_viewer",
  124. ]
  125. code = _run_visible_cmd(
  126. cmd,
  127. cwd=repo,
  128. log_path=log_path,
  129. status_path=status_path,
  130. name="board_viewer",
  131. timeout_s=900,
  132. )
  133. receipt = {
  134. "schema": "prod2u-board-viewer-receipt-v1",
  135. "status": "pass" if code == 0 else "fail",
  136. "verification_run_id": run_id,
  137. "commit_full": prod2u_p4_harness.current_commit(),
  138. "command": " ".join(cmd),
  139. "returncode": code,
  140. "log_path": str(log_path),
  141. "report_path": str(receipt_path),
  142. }
  143. _write_json(receipt_path, receipt)
  144. return receipt
  145. def _run_harness_lane(
  146. repo: Path,
  147. work_root: Path,
  148. run_id: str,
  149. lane: str,
  150. subcommand: str,
  151. extra_args: list[str] | None = None,
  152. *,
  153. timeout_s: float = 1800,
  154. ) -> dict[str, Any]:
  155. receipt_path = work_root / f"{lane}-receipt.json"
  156. log_path = work_root / f"{lane}.log"
  157. status_path = work_root / f"{lane}.status.json"
  158. work_root.mkdir(parents=True, exist_ok=True)
  159. cmd = [
  160. sys.executable,
  161. "-B",
  162. "tools/prod2u_p4_harness.py",
  163. subcommand,
  164. "--run",
  165. "--work-root",
  166. str(work_root),
  167. "--verification-run-id",
  168. run_id,
  169. "--report-file",
  170. str(receipt_path),
  171. ]
  172. if extra_args:
  173. cmd.extend(extra_args)
  174. _run_visible_cmd(
  175. cmd,
  176. cwd=repo,
  177. log_path=log_path,
  178. status_path=status_path,
  179. name=lane,
  180. timeout_s=timeout_s,
  181. )
  182. try:
  183. receipt = json.loads(receipt_path.read_text(encoding="utf-8-sig"))
  184. except (OSError, json.JSONDecodeError):
  185. receipt = {
  186. "schema": f"prod2u-p4-normal-v3-{lane}-receipt-v1",
  187. "status": "blocked",
  188. "verification_run_id": run_id,
  189. "failures": [f"receipt_unreadable:{lane}"],
  190. "log_path": str(log_path),
  191. }
  192. receipt.setdefault("log_path", str(log_path))
  193. receipt.setdefault("report_path", str(receipt_path))
  194. receipt.setdefault("status_path", str(status_path))
  195. return receipt
  196. def run_hdl_lane(repo: Path, work_root: Path, run_id: str, lane: str) -> dict[str, Any]:
  197. return _run_harness_lane(
  198. repo,
  199. work_root,
  200. run_id,
  201. lane,
  202. "hdl-sim",
  203. ["--backend", lane],
  204. timeout_s=1200,
  205. )
  206. def run_formal(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]:
  207. return _run_harness_lane(repo, work_root, run_id, "formal", "formal", timeout_s=1800)
  208. def run_td(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]:
  209. lock_dir = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "prod2u"
  210. lock_dir.mkdir(parents=True, exist_ok=True)
  211. lock_path = lock_dir / "td.lock"
  212. # Exclusive file lock via O_EXCL marker.
  213. try:
  214. fd = os.open(str(lock_path), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
  215. os.write(fd, f"{os.getpid()} {run_id}\n".encode())
  216. os.close(fd)
  217. except FileExistsError:
  218. return {
  219. "schema": "prod2u-p4-normal-v3-td-build-receipt-v2",
  220. "status": "blocked",
  221. "verification_run_id": run_id,
  222. "failures": [f"td_lock_held:{lock_path}"],
  223. "report_path": str(work_root / "td-receipt.json"),
  224. }
  225. try:
  226. return _run_harness_lane(
  227. repo,
  228. work_root,
  229. run_id,
  230. "td",
  231. "td-build",
  232. timeout_s=3600,
  233. )
  234. finally:
  235. try:
  236. lock_path.unlink(missing_ok=True)
  237. except OSError:
  238. pass
  239. LANE_RUNNERS: dict[str, Callable[..., dict[str, Any]]] = {
  240. "python": run_python_unit,
  241. "board_viewer": run_board_viewer,
  242. "icarus": run_hdl_lane,
  243. "verilator": run_hdl_lane,
  244. "cocotb": run_hdl_lane,
  245. "formal": run_formal,
  246. "td": run_td,
  247. }
  248. def _overall_status(results: dict[str, dict[str, Any]], selected: list[str]) -> str:
  249. if not selected:
  250. return "not_run"
  251. statuses = {lane: results.get(lane, {}).get("status", "not_run") for lane in selected}
  252. if all(s == "pass" for s in statuses.values()):
  253. return "pass"
  254. if all(s in ("blocked", "not_run") for s in statuses.values()):
  255. return "blocked"
  256. return "fail"
  257. def main() -> int:
  258. parser = argparse.ArgumentParser(description="Run the verification matrix")
  259. parser.add_argument("--work-root-prefix", required=True)
  260. parser.add_argument("--verification-run-id", default="")
  261. parser.add_argument("--report-file", required=True)
  262. parser.add_argument("--lanes", default=",".join(DEFAULT_LANES))
  263. parser.add_argument("--only-lane", help="rerun a single lane")
  264. parser.add_argument("--max-workers", type=int, default=DEFAULT_MAX_WORKERS)
  265. args = parser.parse_args()
  266. repo = _repo_root
  267. run_id = (args.verification_run_id or uuid.uuid4().hex).strip().lower()
  268. if len(run_id) != 32 or any(c not in "0123456789abcdef" for c in run_id):
  269. # Allow non-hex run ids from wrappers by hashing to 32 hex.
  270. import hashlib
  271. run_id = hashlib.sha256(run_id.encode()).hexdigest()[:32]
  272. selected = [args.only_lane] if args.only_lane else [l.strip() for l in args.lanes.split(",") if l.strip()]
  273. unknown = [l for l in selected if l not in LANE_RUNNERS]
  274. if unknown:
  275. print(f"unknown lanes: {unknown}", file=sys.stderr)
  276. return 1
  277. results: dict[str, dict[str, Any]] = {}
  278. def _run_lane(lane: str) -> tuple[str, dict[str, Any]]:
  279. work_root = Path(f"{args.work_root_prefix}-{lane}-{run_id[:8]}")
  280. runner = LANE_RUNNERS[lane]
  281. print(f"[matrix] starting lane={lane} work_root={work_root}", flush=True)
  282. if lane in ("icarus", "verilator", "cocotb"):
  283. receipt = runner(repo, work_root, run_id, lane)
  284. else:
  285. receipt = runner(repo, work_root, run_id)
  286. print(f"[matrix] finished lane={lane} status={receipt.get('status')}", flush=True)
  287. return lane, receipt
  288. start = time.time()
  289. # Run TD alone after open-source lanes to avoid license/memory contention.
  290. open_lanes = [l for l in selected if l not in TD_EXCLUSIVE]
  291. td_lanes = [l for l in selected if l in TD_EXCLUSIVE]
  292. with ThreadPoolExecutor(max_workers=min(args.max_workers, max(1, len(open_lanes)))) as pool:
  293. futures = [pool.submit(_run_lane, lane) for lane in open_lanes]
  294. for fut in as_completed(futures):
  295. lane, receipt = fut.result()
  296. results[lane] = receipt
  297. for lane in td_lanes:
  298. lane_name, receipt = _run_lane(lane)
  299. results[lane_name] = receipt
  300. duration = time.time() - start
  301. full_commit = prod2u_p4_harness.current_commit()
  302. overall = _overall_status(results, selected)
  303. matrix = {
  304. "schema": "prod2u-p4-normal-v3-verification-matrix-v2",
  305. "generated_at": _utc_now(),
  306. "verification_run_id": run_id,
  307. "commit": full_commit[:8] if full_commit else None,
  308. "commit_full": full_commit,
  309. "dirty": None,
  310. "project_config_sha256": _sha256_file(repo / "projects" / "prod2u-door-temp" / "project.json"),
  311. "td_source_manifest_sha256": _sha256_file(repo / "src" / "generated" / "td-source-manifest.json"),
  312. "status": overall,
  313. "duration_seconds": round(duration, 3),
  314. "lanes": results,
  315. "failures": [f"{lane}:{r['status']}" for lane, r in results.items() if r.get("status") != "pass"],
  316. "environment": "linux",
  317. "td_command": "td2026",
  318. }
  319. report_path = Path(args.report_file)
  320. report_path.parent.mkdir(parents=True, exist_ok=True)
  321. _write_json(report_path, matrix)
  322. print(json.dumps({"status": overall, "report": str(report_path)}, indent=2))
  323. return 0 if overall == "pass" else 1
  324. if __name__ == "__main__":
  325. sys.exit(main())