run_verification_matrix.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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. # 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(repo, work_root, run_id, "formal", "formal", timeout_s=lane_timeout)
  322. def run_td(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]:
  323. lock_dir = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "prod2u"
  324. lock_dir.mkdir(parents=True, exist_ok=True)
  325. lock_path = lock_dir / "td.lock"
  326. # Exclusive file lock via O_EXCL marker.
  327. try:
  328. fd = os.open(str(lock_path), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
  329. os.write(fd, f"{os.getpid()} {run_id}\n".encode())
  330. os.close(fd)
  331. except FileExistsError:
  332. return {
  333. "schema": "prod2u-p4-normal-v3-td-build-receipt-v2",
  334. "status": "blocked",
  335. "verification_run_id": run_id,
  336. "failures": [f"td_lock_held:{lock_path}"],
  337. "report_path": str(work_root / "td-receipt.json"),
  338. "resource_class": "exclusive",
  339. }
  340. try:
  341. receipt = _run_harness_lane(
  342. repo,
  343. work_root,
  344. run_id,
  345. "td",
  346. "td-build",
  347. timeout_s=3600,
  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 _schedule_open_lanes(open_lanes: list[str], plan: dict[str, Any]) -> list[list[str]]:
  375. """Partition open-source lanes into waves respecting memory / formal caps.
  376. When formal_slots==1 and memory is tight (max_workers==1 with heavy), run
  377. heavy lanes (formal, verilator) sequentially. Otherwise run the pool wave
  378. first, then any remaining exclusive-within-OSS serialization is handled by
  379. max_workers alone.
  380. """
  381. if not open_lanes:
  382. return []
  383. workers = int(plan["max_workers"])
  384. mem_kb = (plan.get("host") or {}).get("mem_available_kb")
  385. # On low-memory hosts: serialize heavy lanes, allow light/medium to share.
  386. if workers <= 1 or (mem_kb is not None and mem_kb < 2500 * 1024):
  387. light_medium = [lane for lane in open_lanes if LANE_RESOURCE_CLASS.get(lane) in ("light", "medium")]
  388. heavy = [lane for lane in open_lanes if LANE_RESOURCE_CLASS.get(lane) == "heavy"]
  389. waves: list[list[str]] = []
  390. if light_medium:
  391. waves.append(light_medium)
  392. for lane in heavy:
  393. waves.append([lane])
  394. return waves or [open_lanes]
  395. return [open_lanes]
  396. def main() -> int:
  397. parser = argparse.ArgumentParser(description="Run the verification matrix")
  398. parser.add_argument("--work-root-prefix", required=True)
  399. parser.add_argument("--verification-run-id", default="")
  400. parser.add_argument("--report-file", required=True)
  401. parser.add_argument("--lanes", default=",".join(DEFAULT_LANES))
  402. parser.add_argument("--only-lane", help="rerun a single lane")
  403. parser.add_argument(
  404. "--max-workers",
  405. type=int,
  406. default=None,
  407. help="Cap open-source concurrency (default: host-resource plan).",
  408. )
  409. args = parser.parse_args()
  410. for key in ("LD_LIBRARY_PATH", "LD_PRELOAD", "QT_PLUGIN_PATH"):
  411. os.environ.pop(key, None)
  412. _prefer_oss_cad_on_path()
  413. repo = _repo_root
  414. run_id = (args.verification_run_id or uuid.uuid4().hex).strip().lower()
  415. if len(run_id) != 32 or any(c not in "0123456789abcdef" for c in run_id):
  416. # Allow non-hex run ids from wrappers by hashing to 32 hex.
  417. import hashlib
  418. run_id = hashlib.sha256(run_id.encode()).hexdigest()[:32]
  419. selected = [args.only_lane] if args.only_lane else [l.strip() for l in args.lanes.split(",") if l.strip()]
  420. unknown = [l for l in selected if l not in LANE_RUNNERS]
  421. if unknown:
  422. print(f"unknown lanes: {unknown}", file=sys.stderr)
  423. return 1
  424. plan = plan_concurrency(selected, max_workers_cap=args.max_workers)
  425. print(
  426. f"[matrix] resource_plan workers={plan['max_workers']} "
  427. f"formal_slots={plan['formal_slots']} td_exclusive={plan['td_exclusive']} "
  428. f"nproc={plan['host']['nproc']} mem_available_kb={plan['host']['mem_available_kb']} "
  429. f"classes={plan['lane_classes']}",
  430. flush=True,
  431. )
  432. results: dict[str, dict[str, Any]] = {}
  433. def _run_lane(lane: str) -> tuple[str, dict[str, Any]]:
  434. work_root = Path(f"{args.work_root_prefix}-{lane}-{run_id[:8]}")
  435. runner = LANE_RUNNERS[lane]
  436. print(
  437. f"[matrix] starting lane={lane} class={LANE_RESOURCE_CLASS.get(lane)} "
  438. f"work_root={work_root}",
  439. flush=True,
  440. )
  441. if lane in ("icarus", "verilator", "cocotb"):
  442. receipt = runner(repo, work_root, run_id, lane)
  443. else:
  444. receipt = runner(repo, work_root, run_id)
  445. print(f"[matrix] finished lane={lane} status={receipt.get('status')}", flush=True)
  446. return lane, receipt
  447. start = time.time()
  448. open_lanes = [lane for lane in selected if lane not in TD_EXCLUSIVE]
  449. td_lanes = [lane for lane in selected if lane in TD_EXCLUSIVE]
  450. for wave in _schedule_open_lanes(open_lanes, plan):
  451. workers = min(plan["max_workers"], max(1, len(wave)))
  452. with ThreadPoolExecutor(max_workers=workers) as pool:
  453. futures = [pool.submit(_run_lane, lane) for lane in wave]
  454. for fut in as_completed(futures):
  455. lane, receipt = fut.result()
  456. results[lane] = receipt
  457. # TD exclusive: never overlap with OSS lanes or another TD.
  458. for lane in td_lanes:
  459. lane_name, receipt = _run_lane(lane)
  460. results[lane_name] = receipt
  461. duration = time.time() - start
  462. full_commit = prod2u_p4_harness.current_commit()
  463. overall = _overall_status(results, selected)
  464. matrix = {
  465. "schema": "prod2u-p4-normal-v3-verification-matrix-v2",
  466. "generated_at": _utc_now(),
  467. "verification_run_id": run_id,
  468. "commit": full_commit[:8] if full_commit else None,
  469. "commit_full": full_commit,
  470. "dirty": None,
  471. "project_config_sha256": _sha256_file(repo / "projects" / "prod2u-door-temp" / "project.json"),
  472. "td_source_manifest_sha256": _sha256_file(repo / "src" / "generated" / "td-source-manifest.json"),
  473. "status": overall,
  474. "duration_seconds": round(duration, 3),
  475. "lanes": results,
  476. "failures": [f"{lane}:{r['status']}" for lane, r in results.items() if r.get("status") != "pass"],
  477. "environment": "linux",
  478. "td_command": "td2026",
  479. "resource_plan": plan,
  480. }
  481. report_path = Path(args.report_file)
  482. report_path.parent.mkdir(parents=True, exist_ok=True)
  483. _write_json(report_path, matrix)
  484. print(json.dumps({"status": overall, "report": str(report_path)}, indent=2))
  485. return 0 if overall == "pass" else 1
  486. if __name__ == "__main__":
  487. sys.exit(main())