run_verification_matrix.py 18 KB

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