run_verification_matrix.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. Resource classes (light / medium / heavy / exclusive) come from
  6. tools/resource_scheduler.py (nproc, MemAvailable, free disk). Formal
  7. concurrency is memory-capped. TD is always exclusive (serialized after
  8. open-source lanes, with a lock file). Per-lane TEMP/cocotb builds stay under
  9. the task work root — never a shared sim_build.
  10. """
  11. from __future__ import annotations
  12. import argparse
  13. import json
  14. import os
  15. import sys
  16. import time
  17. import uuid
  18. from concurrent.futures import ThreadPoolExecutor, as_completed
  19. from datetime import datetime, timezone
  20. from pathlib import Path
  21. from typing import Any, Callable
  22. _repo_root = Path(__file__).resolve().parents[1]
  23. if str(_repo_root) not in sys.path:
  24. sys.path.insert(0, str(_repo_root))
  25. from tools import prod2u_p4_harness # noqa: E402
  26. from tools.resource_scheduler import ( # noqa: E402
  27. TASK_RESOURCE_CLASS,
  28. TD_EXCLUSIVE,
  29. allocate_task_dirs,
  30. assert_not_shared_sim_build,
  31. classify_task,
  32. host_resources,
  33. lane_isolation_env,
  34. plan_concurrency,
  35. schedule_waves,
  36. )
  37. from tools.run_visible import run_visible # noqa: E402
  38. # Back-compat alias used by receipts / external importers.
  39. LANE_RESOURCE_CLASS = TASK_RESOURCE_CLASS
  40. DEFAULT_LANES = [
  41. "python",
  42. "board_viewer",
  43. "icarus",
  44. "verilator",
  45. "cocotb",
  46. "formal",
  47. "td",
  48. ]
  49. def _utc_now() -> str:
  50. return datetime.now(timezone.utc).isoformat()
  51. def _sha256_file(path: Path) -> str:
  52. return prod2u_p4_harness.sha256_file(path)
  53. def _write_json(path: Path, payload: dict[str, Any]) -> None:
  54. path.parent.mkdir(parents=True, exist_ok=True)
  55. path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  56. def _prefer_oss_cad_on_path() -> None:
  57. cache = Path(os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))) / "prod2u"
  58. root = Path(os.environ.get("OSS_CAD_SUITE_ROOT", str(cache / "oss-cad-suite" / "latest")))
  59. oss_bin = root / "bin"
  60. if not oss_bin.is_dir():
  61. return
  62. prefix = str(oss_bin)
  63. current = os.environ.get("PATH", "")
  64. parts = current.split(os.pathsep) if current else []
  65. if prefix not in parts:
  66. os.environ["PATH"] = prefix + (os.pathsep + current if current else "")
  67. def _run_visible_cmd(
  68. cmd: list[str],
  69. *,
  70. cwd: Path,
  71. log_path: Path,
  72. status_path: Path,
  73. name: str,
  74. timeout_s: float | None,
  75. env: dict[str, str] | None = None,
  76. ) -> int:
  77. # Strip Anlogic libs for non-TD lanes so apt/python stay healthy.
  78. clean = os.environ.copy()
  79. keep_td = name == "td"
  80. if not keep_td:
  81. for key in ("LD_LIBRARY_PATH", "LD_PRELOAD", "QT_PLUGIN_PATH"):
  82. clean.pop(key, None)
  83. if env:
  84. clean.update(env)
  85. return run_visible(
  86. cmd,
  87. cwd=cwd,
  88. env=clean,
  89. log_path=log_path,
  90. status_path=status_path,
  91. name=name,
  92. timeout_s=timeout_s,
  93. heartbeat_s=5.0,
  94. keep_td_libs=keep_td,
  95. )
  96. def _lane_paths(
  97. *,
  98. lane: str,
  99. run_id: str,
  100. run_root: Path | None,
  101. work_root_prefix: str | None,
  102. ) -> dict[str, Path]:
  103. if run_root is not None:
  104. dirs = allocate_task_dirs(run_root, lane, run_id=run_id, create=True)
  105. assert_not_shared_sim_build(dirs["work_root"])
  106. return dirs
  107. if not work_root_prefix:
  108. raise ValueError("either --run-root or --work-root-prefix is required")
  109. work_root = Path(f"{work_root_prefix}-{lane}-{run_id[:8]}")
  110. assert_not_shared_sim_build(work_root)
  111. work_root.mkdir(parents=True, exist_ok=True)
  112. log_dir = work_root
  113. return {
  114. "run_root": work_root.parent,
  115. "task": lane,
  116. "build_dir": work_root,
  117. "log_dir": log_dir,
  118. "work_root": work_root,
  119. }
  120. def run_python_unit(repo: Path, work_root: Path, run_id: str, *, log_dir: Path | None = None) -> dict[str, Any]:
  121. log_root = log_dir or work_root
  122. receipt_path = work_root / "python-unit-receipt.json"
  123. log_path = log_root / "python-unit.log"
  124. status_path = log_root / "python-unit.status.json"
  125. work_root.mkdir(parents=True, exist_ok=True)
  126. log_root.mkdir(parents=True, exist_ok=True)
  127. isolation = lane_isolation_env(work_root, task="python")
  128. cmd = [
  129. sys.executable,
  130. "-B",
  131. "-m",
  132. "pytest",
  133. "-q",
  134. "-p",
  135. "no:cacheprovider",
  136. f"--basetemp={work_root / 'tmp' / 'pytest'}",
  137. "tests/unit",
  138. "tests/test_project_structure.py",
  139. ]
  140. code = _run_visible_cmd(
  141. cmd,
  142. cwd=repo,
  143. log_path=log_path,
  144. status_path=status_path,
  145. name="python",
  146. timeout_s=600,
  147. env=isolation,
  148. )
  149. status = "pass" if code == 0 else "fail"
  150. full_commit = prod2u_p4_harness.current_commit()
  151. receipt = {
  152. "schema": "prod2u-p4-normal-v3-python-unit-receipt-v1",
  153. "status": status,
  154. "verification_run_id": run_id,
  155. "commit": full_commit,
  156. "commit_full": full_commit,
  157. "project_config_sha256": _sha256_file(repo / "projects" / "prod2u-door-temp" / "project.json"),
  158. "td_source_manifest_sha256": _sha256_file(repo / "src" / "generated" / "td-source-manifest.json"),
  159. "command": " ".join(cmd),
  160. "tool_version": f"Python {sys.version.split()[0]}",
  161. "returncode": code,
  162. "log_path": str(log_path),
  163. "status_path": str(status_path),
  164. "report_path": str(receipt_path),
  165. "work_root": str(work_root),
  166. "resource_class": classify_task("python"),
  167. }
  168. _write_json(receipt_path, receipt)
  169. return receipt
  170. def run_board_viewer(repo: Path, work_root: Path, run_id: str, *, log_dir: Path | None = None) -> dict[str, Any]:
  171. log_root = log_dir or work_root
  172. receipt_path = work_root / "board-viewer-receipt.json"
  173. log_path = log_root / "board-viewer.log"
  174. status_path = log_root / "board-viewer.status.json"
  175. work_root.mkdir(parents=True, exist_ok=True)
  176. log_root.mkdir(parents=True, exist_ok=True)
  177. isolation = lane_isolation_env(work_root, task="board_viewer")
  178. cmd = [
  179. sys.executable,
  180. "-B",
  181. "-m",
  182. "pytest",
  183. "-q",
  184. "-p",
  185. "no:cacheprovider",
  186. f"--basetemp={work_root / 'tmp' / 'pytest'}",
  187. "tests/board_viewer",
  188. ]
  189. code = _run_visible_cmd(
  190. cmd,
  191. cwd=repo,
  192. log_path=log_path,
  193. status_path=status_path,
  194. name="board_viewer",
  195. timeout_s=900,
  196. env=isolation,
  197. )
  198. receipt = {
  199. "schema": "prod2u-board-viewer-receipt-v1",
  200. "status": "pass" if code == 0 else "fail",
  201. "verification_run_id": run_id,
  202. "commit_full": prod2u_p4_harness.current_commit(),
  203. "command": " ".join(cmd),
  204. "returncode": code,
  205. "log_path": str(log_path),
  206. "report_path": str(receipt_path),
  207. "work_root": str(work_root),
  208. "resource_class": classify_task("board_viewer"),
  209. }
  210. _write_json(receipt_path, receipt)
  211. return receipt
  212. def _run_harness_lane(
  213. repo: Path,
  214. work_root: Path,
  215. run_id: str,
  216. lane: str,
  217. subcommand: str,
  218. extra_args: list[str] | None = None,
  219. *,
  220. timeout_s: float = 1800,
  221. log_dir: Path | None = None,
  222. ) -> dict[str, Any]:
  223. log_root = log_dir or work_root
  224. receipt_path = work_root / f"{lane}-receipt.json"
  225. log_path = log_root / f"{lane}.log"
  226. status_path = log_root / f"{lane}.status.json"
  227. work_root.mkdir(parents=True, exist_ok=True)
  228. log_root.mkdir(parents=True, exist_ok=True)
  229. isolation = lane_isolation_env(work_root, task=lane)
  230. cmd = [
  231. sys.executable,
  232. "-B",
  233. "tools/prod2u_p4_harness.py",
  234. subcommand,
  235. "--run",
  236. "--work-root",
  237. str(work_root),
  238. "--verification-run-id",
  239. run_id,
  240. "--report-file",
  241. str(receipt_path),
  242. ]
  243. if extra_args:
  244. cmd.extend(extra_args)
  245. _run_visible_cmd(
  246. cmd,
  247. cwd=repo,
  248. log_path=log_path,
  249. status_path=status_path,
  250. name=lane,
  251. timeout_s=timeout_s,
  252. env=isolation,
  253. )
  254. try:
  255. receipt = json.loads(receipt_path.read_text(encoding="utf-8-sig"))
  256. except (OSError, json.JSONDecodeError):
  257. receipt = {
  258. "schema": f"prod2u-p4-normal-v3-{lane}-receipt-v1",
  259. "status": "blocked",
  260. "verification_run_id": run_id,
  261. "failures": [f"receipt_unreadable:{lane}"],
  262. "log_path": str(log_path),
  263. }
  264. receipt.setdefault("log_path", str(log_path))
  265. receipt.setdefault("report_path", str(receipt_path))
  266. receipt.setdefault("status_path", str(status_path))
  267. receipt.setdefault("work_root", str(work_root))
  268. receipt.setdefault("resource_class", classify_task(lane))
  269. return receipt
  270. def run_hdl_lane(
  271. repo: Path,
  272. work_root: Path,
  273. run_id: str,
  274. lane: str,
  275. *,
  276. log_dir: Path | None = None,
  277. ) -> dict[str, Any]:
  278. return _run_harness_lane(
  279. repo,
  280. work_root,
  281. run_id,
  282. lane,
  283. "hdl-sim",
  284. ["--backend", lane],
  285. timeout_s=1200,
  286. log_dir=log_dir,
  287. )
  288. def run_formal(
  289. repo: Path,
  290. work_root: Path,
  291. run_id: str,
  292. *,
  293. log_dir: Path | None = None,
  294. ) -> dict[str, Any]:
  295. # Wall-clock for the whole formal lane. Per-task timeout remains
  296. # PROD2U_P4_TIMEOUT_FORMAL_SECONDS (default 600). Low-memory hosts need a
  297. # long lane budget because frame_tx BMC depth=96 alone can exceed 15 minutes.
  298. raw = os.environ.get("PROD2U_P4_TIMEOUT_FORMAL_LANE_SECONDS", "").strip()
  299. try:
  300. lane_timeout = float(raw) if raw else 7200.0
  301. except ValueError:
  302. lane_timeout = 7200.0
  303. if lane_timeout <= 0:
  304. lane_timeout = 7200.0
  305. return _run_harness_lane(
  306. repo,
  307. work_root,
  308. run_id,
  309. "formal",
  310. "formal",
  311. timeout_s=lane_timeout,
  312. log_dir=log_dir,
  313. )
  314. def run_td(
  315. repo: Path,
  316. work_root: Path,
  317. run_id: str,
  318. *,
  319. log_dir: Path | None = None,
  320. ) -> dict[str, Any]:
  321. lock_dir = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "prod2u"
  322. lock_dir.mkdir(parents=True, exist_ok=True)
  323. lock_path = lock_dir / "td.lock"
  324. # Exclusive file lock via O_EXCL marker.
  325. try:
  326. fd = os.open(str(lock_path), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
  327. os.write(fd, f"{os.getpid()} {run_id}\n".encode())
  328. os.close(fd)
  329. except FileExistsError:
  330. return {
  331. "schema": "prod2u-p4-normal-v3-td-build-receipt-v2",
  332. "status": "blocked",
  333. "verification_run_id": run_id,
  334. "failures": [f"td_lock_held:{lock_path}"],
  335. "report_path": str(work_root / "td-receipt.json"),
  336. "work_root": str(work_root),
  337. "resource_class": "exclusive",
  338. }
  339. try:
  340. receipt = _run_harness_lane(
  341. repo,
  342. work_root,
  343. run_id,
  344. "td",
  345. "td-build",
  346. timeout_s=3600,
  347. log_dir=log_dir,
  348. )
  349. receipt["resource_class"] = "exclusive"
  350. return receipt
  351. finally:
  352. try:
  353. lock_path.unlink(missing_ok=True)
  354. except OSError:
  355. pass
  356. LANE_RUNNERS: dict[str, Callable[..., dict[str, Any]]] = {
  357. "python": run_python_unit,
  358. "board_viewer": run_board_viewer,
  359. "icarus": run_hdl_lane,
  360. "verilator": run_hdl_lane,
  361. "cocotb": run_hdl_lane,
  362. "formal": run_formal,
  363. "td": run_td,
  364. }
  365. def _overall_status(results: dict[str, dict[str, Any]], selected: list[str]) -> str:
  366. if not selected:
  367. return "not_run"
  368. statuses = {lane: results.get(lane, {}).get("status", "not_run") for lane in selected}
  369. if all(s == "pass" for s in statuses.values()):
  370. return "pass"
  371. if all(s in ("blocked", "not_run") for s in statuses.values()):
  372. return "blocked"
  373. return "fail"
  374. def main() -> int:
  375. parser = argparse.ArgumentParser(description="Run the verification matrix")
  376. parser.add_argument(
  377. "--work-root-prefix",
  378. default="",
  379. help="Legacy prefix: {prefix}-{lane}-{run_id8} (mutually exclusive with --run-root).",
  380. )
  381. parser.add_argument(
  382. "--run-root",
  383. default="",
  384. help="Run root with builds/ and logs/ per task (preferred for packager matrix).",
  385. )
  386. parser.add_argument("--verification-run-id", default="")
  387. parser.add_argument("--report-file", required=True)
  388. parser.add_argument("--lanes", default=",".join(DEFAULT_LANES))
  389. parser.add_argument("--only-lane", help="rerun a single lane")
  390. parser.add_argument(
  391. "--max-workers",
  392. type=int,
  393. default=None,
  394. help="Cap open-source concurrency (default: host-resource plan).",
  395. )
  396. args = parser.parse_args()
  397. for key in ("LD_LIBRARY_PATH", "LD_PRELOAD", "QT_PLUGIN_PATH"):
  398. os.environ.pop(key, None)
  399. _prefer_oss_cad_on_path()
  400. repo = _repo_root
  401. run_id = (args.verification_run_id or uuid.uuid4().hex).strip().lower()
  402. if len(run_id) != 32 or any(c not in "0123456789abcdef" for c in run_id):
  403. # Allow non-hex run ids from wrappers by hashing to 32 hex.
  404. import hashlib
  405. run_id = hashlib.sha256(run_id.encode()).hexdigest()[:32]
  406. selected = [args.only_lane] if args.only_lane else [l.strip() for l in args.lanes.split(",") if l.strip()]
  407. unknown = [l for l in selected if l not in LANE_RUNNERS]
  408. if unknown:
  409. print(f"unknown lanes: {unknown}", file=sys.stderr)
  410. return 1
  411. run_root = Path(args.run_root).expanduser().resolve() if args.run_root else None
  412. work_root_prefix = args.work_root_prefix.strip() or None
  413. if run_root is None and work_root_prefix is None:
  414. print("error: provide --run-root or --work-root-prefix", file=sys.stderr)
  415. return 2
  416. plan = plan_concurrency(selected, max_workers_cap=args.max_workers)
  417. print(
  418. f"[matrix] resource_plan workers={plan['max_workers']} "
  419. f"formal_slots={plan['formal_slots']} td_exclusive={plan['td_exclusive']} "
  420. f"nproc={plan['host']['nproc']} mem_available_kb={plan['host']['mem_available_kb']} "
  421. f"disk_free_bytes={plan['host'].get('disk_free_bytes')} "
  422. f"classes={plan['lane_classes']}",
  423. flush=True,
  424. )
  425. results: dict[str, dict[str, Any]] = {}
  426. lane_dirs: dict[str, dict[str, str]] = {}
  427. def _run_lane(lane: str) -> tuple[str, dict[str, Any]]:
  428. paths = _lane_paths(
  429. lane=lane,
  430. run_id=run_id,
  431. run_root=run_root,
  432. work_root_prefix=work_root_prefix,
  433. )
  434. work_root = paths["work_root"]
  435. log_dir = paths["log_dir"]
  436. lane_dirs[lane] = {
  437. "work_root": str(work_root),
  438. "build_dir": str(paths["build_dir"]),
  439. "log_dir": str(log_dir),
  440. }
  441. runner = LANE_RUNNERS[lane]
  442. print(
  443. f"[matrix] starting lane={lane} class={classify_task(lane)} "
  444. f"work_root={work_root} log_dir={log_dir}",
  445. flush=True,
  446. )
  447. if lane in ("icarus", "verilator", "cocotb"):
  448. receipt = runner(repo, work_root, run_id, lane, log_dir=log_dir)
  449. else:
  450. receipt = runner(repo, work_root, run_id, log_dir=log_dir)
  451. print(f"[matrix] finished lane={lane} status={receipt.get('status')}", flush=True)
  452. return lane, receipt
  453. start = time.time()
  454. open_lanes = [lane for lane in selected if lane not in TD_EXCLUSIVE]
  455. td_lanes = [lane for lane in selected if lane in TD_EXCLUSIVE]
  456. for wave in schedule_waves(open_lanes, plan):
  457. workers = min(plan["max_workers"], max(1, len(wave)))
  458. with ThreadPoolExecutor(max_workers=workers) as pool:
  459. futures = [pool.submit(_run_lane, lane) for lane in wave]
  460. for fut in as_completed(futures):
  461. lane, receipt = fut.result()
  462. results[lane] = receipt
  463. # TD exclusive: never overlap with OSS lanes or another TD.
  464. for lane in td_lanes:
  465. lane_name, receipt = _run_lane(lane)
  466. results[lane_name] = receipt
  467. duration = time.time() - start
  468. full_commit = prod2u_p4_harness.current_commit()
  469. overall = _overall_status(results, selected)
  470. matrix = {
  471. "schema": "prod2u-p4-normal-v3-verification-matrix-v2",
  472. "generated_at": _utc_now(),
  473. "verification_run_id": run_id,
  474. "commit": full_commit[:8] if full_commit else None,
  475. "commit_full": full_commit,
  476. "dirty": None,
  477. "project_config_sha256": _sha256_file(repo / "projects" / "prod2u-door-temp" / "project.json"),
  478. "td_source_manifest_sha256": _sha256_file(repo / "src" / "generated" / "td-source-manifest.json"),
  479. "status": overall,
  480. "duration_seconds": round(duration, 3),
  481. "lanes": results,
  482. "lane_dirs": lane_dirs,
  483. "failures": [f"{lane}:{r['status']}" for lane, r in results.items() if r.get("status") != "pass"],
  484. "environment": "linux",
  485. "td_command": "td2026",
  486. "resource_plan": plan,
  487. "host_resources": host_resources(),
  488. }
  489. report_path = Path(args.report_file)
  490. report_path.parent.mkdir(parents=True, exist_ok=True)
  491. _write_json(report_path, matrix)
  492. print(json.dumps({"status": overall, "report": str(report_path)}, indent=2))
  493. return 0 if overall == "pass" else 1
  494. if __name__ == "__main__":
  495. sys.exit(main())