run_verification_matrix.py 18 KB

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