run_verification_matrix.py 18 KB

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