run_verification_matrix.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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.
  5. """
  6. from __future__ import annotations
  7. import argparse
  8. import json
  9. import subprocess
  10. import sys
  11. import time
  12. from concurrent.futures import ThreadPoolExecutor
  13. from datetime import datetime, timezone
  14. from pathlib import Path
  15. from typing import Any
  16. _repo_root = Path(__file__).resolve().parents[1]
  17. if str(_repo_root) not in sys.path:
  18. sys.path.insert(0, str(_repo_root))
  19. from tools import prod2u_p4_harness # noqa: E402
  20. DEFAULT_LANES = ["python", "icarus", "verilator", "cocotb", "formal"]
  21. DEFAULT_MAX_WORKERS = 4
  22. def _utc_now() -> str:
  23. return datetime.now(timezone.utc).isoformat()
  24. def _sha256_file(path: Path) -> str:
  25. return prod2u_p4_harness.sha256_file(path)
  26. def _run(cmd: list[str], cwd: Path, log_path: Path | None = None) -> subprocess.CompletedProcess[str]:
  27. result = subprocess.run(
  28. cmd,
  29. cwd=cwd,
  30. text=True,
  31. capture_output=True,
  32. encoding="utf-8",
  33. errors="replace",
  34. )
  35. if log_path is not None:
  36. log_path.parent.mkdir(parents=True, exist_ok=True)
  37. with log_path.open("w", encoding="utf-8") as f:
  38. f.write(f"command: {' '.join(cmd)}\n")
  39. f.write(f"returncode: {result.returncode}\n")
  40. f.write("--- stdout ---\n")
  41. f.write(result.stdout)
  42. f.write("\n--- stderr ---\n")
  43. f.write(result.stderr)
  44. return result
  45. def _write_json(path: Path, payload: dict[str, Any]) -> None:
  46. path.parent.mkdir(parents=True, exist_ok=True)
  47. path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  48. def run_python_unit(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]:
  49. receipt_path = work_root / "python-unit-receipt.json"
  50. log_path = work_root / "python-unit.log"
  51. work_root.mkdir(parents=True, exist_ok=True)
  52. result = _run(
  53. [
  54. sys.executable,
  55. "-B",
  56. "-m",
  57. "pytest",
  58. "-q",
  59. "-p",
  60. "no:cacheprovider",
  61. "tests/unit",
  62. "tests/test_project_structure.py",
  63. ],
  64. repo,
  65. log_path,
  66. )
  67. status = "pass" if result.returncode == 0 else "fail"
  68. full_commit = prod2u_p4_harness.current_commit()
  69. receipt = {
  70. "schema": "prod2u-p4-normal-v3-python-unit-receipt-v1",
  71. "status": status,
  72. "verification_run_id": run_id,
  73. "commit": full_commit,
  74. "commit_full": full_commit,
  75. "project_config_sha256": _sha256_file(repo / "projects" / "prod2u-door-temp" / "project.json"),
  76. "td_source_manifest_sha256": _sha256_file(repo / "src" / "generated" / "td-source-manifest.json"),
  77. "command": "python -B -m pytest -q -p no:cacheprovider tests/unit tests/test_project_structure.py",
  78. "tool_version": f"Python {sys.version.split()[0]}",
  79. "returncode": result.returncode,
  80. "stdout_tail": result.stdout[-4096:] if result.stdout else "",
  81. "stderr_tail": result.stderr[-4096:] if result.stderr else "",
  82. "log_path": str(log_path),
  83. "report_path": str(receipt_path),
  84. }
  85. _write_json(receipt_path, receipt)
  86. return receipt
  87. def _run_harness_lane(
  88. repo: Path,
  89. work_root: Path,
  90. run_id: str,
  91. lane: str,
  92. subcommand: str,
  93. extra_args: list[str] | None = None,
  94. ) -> dict[str, Any]:
  95. receipt_path = work_root / f"{lane}-receipt.json"
  96. log_path = work_root / f"{lane}.log"
  97. work_root.mkdir(parents=True, exist_ok=True)
  98. cmd = [
  99. sys.executable,
  100. "-B",
  101. "tools/prod2u_p4_harness.py",
  102. subcommand,
  103. "--run",
  104. "--work-root",
  105. str(work_root),
  106. "--verification-run-id",
  107. run_id,
  108. "--report-file",
  109. str(receipt_path),
  110. ]
  111. if extra_args:
  112. cmd.extend(extra_args)
  113. _run(cmd, repo, log_path)
  114. try:
  115. receipt = json.loads(receipt_path.read_text(encoding="utf-8-sig"))
  116. except (OSError, json.JSONDecodeError):
  117. receipt = {
  118. "schema": f"prod2u-p4-normal-v3-{lane}-receipt-v1",
  119. "status": "blocked",
  120. "verification_run_id": run_id,
  121. "failures": [f"receipt_unreadable:{lane}"],
  122. "log_path": str(log_path),
  123. }
  124. receipt.setdefault("log_path", str(log_path))
  125. receipt.setdefault("report_path", str(receipt_path))
  126. return receipt
  127. def run_hdl_lane(repo: Path, work_root: Path, run_id: str, lane: str) -> dict[str, Any]:
  128. return _run_harness_lane(
  129. repo,
  130. work_root,
  131. run_id,
  132. lane,
  133. "hdl-sim",
  134. ["--backend", lane],
  135. )
  136. def run_formal(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]:
  137. return _run_harness_lane(repo, work_root, run_id, "formal", "formal")
  138. LANE_RUNNERS = {
  139. "python": run_python_unit,
  140. "icarus": run_hdl_lane,
  141. "verilator": run_hdl_lane,
  142. "cocotb": run_hdl_lane,
  143. "formal": run_formal,
  144. }
  145. def _overall_status(results: dict[str, dict[str, Any]], selected: list[str]) -> str:
  146. if not selected:
  147. return "not_run"
  148. statuses = {lane: results.get(lane, {}).get("status", "not_run") for lane in selected}
  149. if all(s == "pass" for s in statuses.values()):
  150. return "pass"
  151. if all(s in ("blocked", "not_run") for s in statuses.values()):
  152. return "blocked"
  153. return "fail"
  154. def main() -> int:
  155. parser = argparse.ArgumentParser(description="Run the verification matrix")
  156. parser.add_argument("--work-root-prefix", required=True)
  157. parser.add_argument("--verification-run-id", required=True)
  158. parser.add_argument("--report-file", required=True)
  159. parser.add_argument("--lanes", default=",".join(DEFAULT_LANES))
  160. parser.add_argument("--only-lane", help="rerun a single lane")
  161. parser.add_argument("--max-workers", type=int, default=DEFAULT_MAX_WORKERS)
  162. args = parser.parse_args()
  163. repo = _repo_root
  164. run_id = args.verification_run_id
  165. selected = [args.only_lane] if args.only_lane else [l.strip() for l in args.lanes.split(",") if l.strip()]
  166. unknown = [l for l in selected if l not in LANE_RUNNERS]
  167. if unknown:
  168. print(f"unknown lanes: {unknown}", file=sys.stderr)
  169. return 1
  170. results: dict[str, dict[str, Any]] = {}
  171. def _run_lane(lane: str) -> tuple[str, dict[str, Any]]:
  172. work_root = Path(f"{args.work_root_prefix}-{lane}-{run_id[:8]}")
  173. runner = LANE_RUNNERS[lane]
  174. if lane in ("icarus", "verilator", "cocotb"):
  175. return lane, runner(repo, work_root, run_id, lane)
  176. return lane, runner(repo, work_root, run_id)
  177. start = time.time()
  178. with ThreadPoolExecutor(max_workers=min(args.max_workers, len(selected))) as pool:
  179. for lane, receipt in pool.map(_run_lane, selected):
  180. results[lane] = receipt
  181. duration = time.time() - start
  182. full_commit = prod2u_p4_harness.current_commit()
  183. overall = _overall_status(results, selected)
  184. matrix = {
  185. "schema": "prod2u-p4-normal-v3-verification-matrix-v1",
  186. "generated_at": _utc_now(),
  187. "verification_run_id": run_id,
  188. "commit": full_commit[:8] if full_commit else None,
  189. "commit_full": full_commit,
  190. "project_config_sha256": _sha256_file(repo / "projects" / "prod2u-door-temp" / "project.json"),
  191. "td_source_manifest_sha256": _sha256_file(repo / "src" / "generated" / "td-source-manifest.json"),
  192. "status": overall,
  193. "duration_seconds": round(duration, 3),
  194. "lanes": results,
  195. "failures": [f"{lane}:{r['status']}" for lane, r in results.items() if r.get("status") != "pass"],
  196. }
  197. report_path = Path(args.report_file)
  198. report_path.parent.mkdir(parents=True, exist_ok=True)
  199. _write_json(report_path, matrix)
  200. print(json.dumps({"status": overall, "report": str(report_path)}, indent=2))
  201. return 0 if overall == "pass" else 1
  202. if __name__ == "__main__":
  203. sys.exit(main())