run_verification_matrix.py 18 KB

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