"""Run the Prod2U CPLD offline verification matrix with bounded concurrency. Each lane uses an independent work root and receipt. A failed lane does not cancel unrelated lanes. Missing toolchains produce `blocked` or `not_run`, never a fabricated pass. Long tasks use tools/run_visible.py for live heartbeat. Resource classes (light / medium / heavy / exclusive) come from tools/resource_scheduler.py (nproc, MemAvailable, free disk). Formal concurrency is memory-capped. TD is always exclusive (serialized after open-source lanes, with a lock file). Per-lane TEMP/cocotb builds stay under the task work root — never a shared sim_build. """ from __future__ import annotations import argparse import json import os import sys import time import uuid from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime, timezone from pathlib import Path from typing import Any, Callable _repo_root = Path(__file__).resolve().parents[1] if str(_repo_root) not in sys.path: sys.path.insert(0, str(_repo_root)) from tools import prod2u_p4_harness # noqa: E402 from tools.resource_scheduler import ( # noqa: E402 TASK_RESOURCE_CLASS, TD_EXCLUSIVE, allocate_task_dirs, assert_not_shared_sim_build, classify_task, host_resources, lane_isolation_env, plan_concurrency, schedule_waves, ) from tools.run_visible import run_visible # noqa: E402 # Back-compat alias used by receipts / external importers. LANE_RESOURCE_CLASS = TASK_RESOURCE_CLASS DEFAULT_LANES = [ "python", "board_viewer", "icarus", "verilator", "cocotb", "formal", "td", ] def _utc_now() -> str: return datetime.now(timezone.utc).isoformat() def _sha256_file(path: Path) -> str: return prod2u_p4_harness.sha256_file(path) def _write_json(path: Path, payload: dict[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8") def _prefer_oss_cad_on_path() -> None: cache = Path(os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))) / "prod2u" root = Path(os.environ.get("OSS_CAD_SUITE_ROOT", str(cache / "oss-cad-suite" / "latest"))) oss_bin = root / "bin" if not oss_bin.is_dir(): return prefix = str(oss_bin) current = os.environ.get("PATH", "") parts = current.split(os.pathsep) if current else [] if prefix not in parts: os.environ["PATH"] = prefix + (os.pathsep + current if current else "") def _run_visible_cmd( cmd: list[str], *, cwd: Path, log_path: Path, status_path: Path, name: str, timeout_s: float | None, env: dict[str, str] | None = None, ) -> int: # Strip Anlogic libs for non-TD lanes so apt/python stay healthy. clean = os.environ.copy() keep_td = name == "td" if not keep_td: for key in ("LD_LIBRARY_PATH", "LD_PRELOAD", "QT_PLUGIN_PATH"): clean.pop(key, None) if env: clean.update(env) return run_visible( cmd, cwd=cwd, env=clean, log_path=log_path, status_path=status_path, name=name, timeout_s=timeout_s, heartbeat_s=5.0, keep_td_libs=keep_td, ) def _lane_paths( *, lane: str, run_id: str, run_root: Path | None, work_root_prefix: str | None, ) -> dict[str, Path]: if run_root is not None: dirs = allocate_task_dirs(run_root, lane, run_id=run_id, create=True) assert_not_shared_sim_build(dirs["work_root"]) return dirs if not work_root_prefix: raise ValueError("either --run-root or --work-root-prefix is required") work_root = Path(f"{work_root_prefix}-{lane}-{run_id[:8]}") assert_not_shared_sim_build(work_root) work_root.mkdir(parents=True, exist_ok=True) log_dir = work_root return { "run_root": work_root.parent, "task": lane, "build_dir": work_root, "log_dir": log_dir, "work_root": work_root, } def run_python_unit(repo: Path, work_root: Path, run_id: str, *, log_dir: Path | None = None) -> dict[str, Any]: log_root = log_dir or work_root receipt_path = work_root / "python-unit-receipt.json" log_path = log_root / "python-unit.log" status_path = log_root / "python-unit.status.json" work_root.mkdir(parents=True, exist_ok=True) log_root.mkdir(parents=True, exist_ok=True) isolation = lane_isolation_env(work_root, task="python") cmd = [ sys.executable, "-B", "-m", "pytest", "-q", "-p", "no:cacheprovider", f"--basetemp={work_root / 'tmp' / 'pytest'}", "tests/unit", "tests/test_project_structure.py", ] code = _run_visible_cmd( cmd, cwd=repo, log_path=log_path, status_path=status_path, name="python", timeout_s=600, env=isolation, ) status = "pass" if code == 0 else "fail" full_commit = prod2u_p4_harness.current_commit() receipt = { "schema": "prod2u-p4-normal-v3-python-unit-receipt-v1", "status": status, "verification_run_id": run_id, "commit": full_commit, "commit_full": full_commit, "project_config_sha256": _sha256_file(repo / "projects" / "prod2u-door-temp" / "project.json"), "td_source_manifest_sha256": _sha256_file(repo / "src" / "generated" / "td-source-manifest.json"), "command": " ".join(cmd), "tool_version": f"Python {sys.version.split()[0]}", "returncode": code, "log_path": str(log_path), "status_path": str(status_path), "report_path": str(receipt_path), "work_root": str(work_root), "resource_class": classify_task("python"), } _write_json(receipt_path, receipt) return receipt def run_board_viewer(repo: Path, work_root: Path, run_id: str, *, log_dir: Path | None = None) -> dict[str, Any]: log_root = log_dir or work_root receipt_path = work_root / "board-viewer-receipt.json" log_path = log_root / "board-viewer.log" status_path = log_root / "board-viewer.status.json" work_root.mkdir(parents=True, exist_ok=True) log_root.mkdir(parents=True, exist_ok=True) isolation = lane_isolation_env(work_root, task="board_viewer") cmd = [ sys.executable, "-B", "-m", "pytest", "-q", "-p", "no:cacheprovider", f"--basetemp={work_root / 'tmp' / 'pytest'}", "tests/board_viewer", ] code = _run_visible_cmd( cmd, cwd=repo, log_path=log_path, status_path=status_path, name="board_viewer", timeout_s=900, env=isolation, ) receipt = { "schema": "prod2u-board-viewer-receipt-v1", "status": "pass" if code == 0 else "fail", "verification_run_id": run_id, "commit_full": prod2u_p4_harness.current_commit(), "command": " ".join(cmd), "returncode": code, "log_path": str(log_path), "report_path": str(receipt_path), "work_root": str(work_root), "resource_class": classify_task("board_viewer"), } _write_json(receipt_path, receipt) return receipt def _run_harness_lane( repo: Path, work_root: Path, run_id: str, lane: str, subcommand: str, extra_args: list[str] | None = None, *, timeout_s: float = 1800, log_dir: Path | None = None, ) -> dict[str, Any]: log_root = log_dir or work_root receipt_path = work_root / f"{lane}-receipt.json" log_path = log_root / f"{lane}.log" status_path = log_root / f"{lane}.status.json" work_root.mkdir(parents=True, exist_ok=True) log_root.mkdir(parents=True, exist_ok=True) isolation = lane_isolation_env(work_root, task=lane) cmd = [ sys.executable, "-B", "tools/prod2u_p4_harness.py", subcommand, "--run", "--work-root", str(work_root), "--verification-run-id", run_id, "--report-file", str(receipt_path), ] if extra_args: cmd.extend(extra_args) _run_visible_cmd( cmd, cwd=repo, log_path=log_path, status_path=status_path, name=lane, timeout_s=timeout_s, env=isolation, ) try: receipt = json.loads(receipt_path.read_text(encoding="utf-8-sig")) except (OSError, json.JSONDecodeError): receipt = { "schema": f"prod2u-p4-normal-v3-{lane}-receipt-v1", "status": "blocked", "verification_run_id": run_id, "failures": [f"receipt_unreadable:{lane}"], "log_path": str(log_path), } receipt.setdefault("log_path", str(log_path)) receipt.setdefault("report_path", str(receipt_path)) receipt.setdefault("status_path", str(status_path)) receipt.setdefault("work_root", str(work_root)) receipt.setdefault("resource_class", classify_task(lane)) return receipt def run_hdl_lane( repo: Path, work_root: Path, run_id: str, lane: str, *, log_dir: Path | None = None, ) -> dict[str, Any]: return _run_harness_lane( repo, work_root, run_id, lane, "hdl-sim", ["--backend", lane], timeout_s=1200, log_dir=log_dir, ) def run_formal( repo: Path, work_root: Path, run_id: str, *, log_dir: Path | None = None, ) -> dict[str, Any]: # Wall-clock for the whole formal lane. Per-task timeout remains # PROD2U_P4_TIMEOUT_FORMAL_SECONDS (default 600). Low-memory hosts need a # long lane budget because frame_tx BMC depth=96 alone can exceed 15 minutes. raw = os.environ.get("PROD2U_P4_TIMEOUT_FORMAL_LANE_SECONDS", "").strip() try: lane_timeout = float(raw) if raw else 7200.0 except ValueError: lane_timeout = 7200.0 if lane_timeout <= 0: lane_timeout = 7200.0 return _run_harness_lane( repo, work_root, run_id, "formal", "formal", timeout_s=lane_timeout, log_dir=log_dir, ) def run_td( repo: Path, work_root: Path, run_id: str, *, log_dir: Path | None = None, ) -> dict[str, Any]: lock_dir = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "prod2u" lock_dir.mkdir(parents=True, exist_ok=True) lock_path = lock_dir / "td.lock" # Exclusive file lock via O_EXCL marker. try: fd = os.open(str(lock_path), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644) os.write(fd, f"{os.getpid()} {run_id}\n".encode()) os.close(fd) except FileExistsError: return { "schema": "prod2u-p4-normal-v3-td-build-receipt-v2", "status": "blocked", "verification_run_id": run_id, "failures": [f"td_lock_held:{lock_path}"], "report_path": str(work_root / "td-receipt.json"), "work_root": str(work_root), "resource_class": "exclusive", } try: receipt = _run_harness_lane( repo, work_root, run_id, "td", "td-build", timeout_s=3600, log_dir=log_dir, ) receipt["resource_class"] = "exclusive" return receipt finally: try: lock_path.unlink(missing_ok=True) except OSError: pass LANE_RUNNERS: dict[str, Callable[..., dict[str, Any]]] = { "python": run_python_unit, "board_viewer": run_board_viewer, "icarus": run_hdl_lane, "verilator": run_hdl_lane, "cocotb": run_hdl_lane, "formal": run_formal, "td": run_td, } def _overall_status(results: dict[str, dict[str, Any]], selected: list[str]) -> str: if not selected: return "not_run" statuses = {lane: results.get(lane, {}).get("status", "not_run") for lane in selected} if all(s == "pass" for s in statuses.values()): return "pass" if all(s in ("blocked", "not_run") for s in statuses.values()): return "blocked" return "fail" def main() -> int: parser = argparse.ArgumentParser(description="Run the verification matrix") parser.add_argument( "--work-root-prefix", default="", help="Legacy prefix: {prefix}-{lane}-{run_id8} (mutually exclusive with --run-root).", ) parser.add_argument( "--run-root", default="", help="Run root with builds/ and logs/ per task (preferred for packager matrix).", ) parser.add_argument("--verification-run-id", default="") parser.add_argument("--report-file", required=True) parser.add_argument("--lanes", default=",".join(DEFAULT_LANES)) parser.add_argument("--only-lane", help="rerun a single lane") parser.add_argument( "--max-workers", type=int, default=None, help="Cap open-source concurrency (default: host-resource plan).", ) args = parser.parse_args() for key in ("LD_LIBRARY_PATH", "LD_PRELOAD", "QT_PLUGIN_PATH"): os.environ.pop(key, None) _prefer_oss_cad_on_path() repo = _repo_root run_id = (args.verification_run_id or uuid.uuid4().hex).strip().lower() if len(run_id) != 32 or any(c not in "0123456789abcdef" for c in run_id): # Allow non-hex run ids from wrappers by hashing to 32 hex. import hashlib run_id = hashlib.sha256(run_id.encode()).hexdigest()[:32] selected = [args.only_lane] if args.only_lane else [l.strip() for l in args.lanes.split(",") if l.strip()] unknown = [l for l in selected if l not in LANE_RUNNERS] if unknown: print(f"unknown lanes: {unknown}", file=sys.stderr) return 1 run_root = Path(args.run_root).expanduser().resolve() if args.run_root else None work_root_prefix = args.work_root_prefix.strip() or None if run_root is None and work_root_prefix is None: print("error: provide --run-root or --work-root-prefix", file=sys.stderr) return 2 plan = plan_concurrency(selected, max_workers_cap=args.max_workers) print( f"[matrix] resource_plan workers={plan['max_workers']} " f"formal_slots={plan['formal_slots']} td_exclusive={plan['td_exclusive']} " f"nproc={plan['host']['nproc']} mem_available_kb={plan['host']['mem_available_kb']} " f"disk_free_bytes={plan['host'].get('disk_free_bytes')} " f"classes={plan['lane_classes']}", flush=True, ) results: dict[str, dict[str, Any]] = {} lane_dirs: dict[str, dict[str, str]] = {} def _run_lane(lane: str) -> tuple[str, dict[str, Any]]: paths = _lane_paths( lane=lane, run_id=run_id, run_root=run_root, work_root_prefix=work_root_prefix, ) work_root = paths["work_root"] log_dir = paths["log_dir"] lane_dirs[lane] = { "work_root": str(work_root), "build_dir": str(paths["build_dir"]), "log_dir": str(log_dir), } runner = LANE_RUNNERS[lane] print( f"[matrix] starting lane={lane} class={classify_task(lane)} " f"work_root={work_root} log_dir={log_dir}", flush=True, ) if lane in ("icarus", "verilator", "cocotb"): receipt = runner(repo, work_root, run_id, lane, log_dir=log_dir) else: receipt = runner(repo, work_root, run_id, log_dir=log_dir) print(f"[matrix] finished lane={lane} status={receipt.get('status')}", flush=True) return lane, receipt start = time.time() open_lanes = [lane for lane in selected if lane not in TD_EXCLUSIVE] td_lanes = [lane for lane in selected if lane in TD_EXCLUSIVE] for wave in schedule_waves(open_lanes, plan): workers = min(plan["max_workers"], max(1, len(wave))) with ThreadPoolExecutor(max_workers=workers) as pool: futures = [pool.submit(_run_lane, lane) for lane in wave] for fut in as_completed(futures): lane, receipt = fut.result() results[lane] = receipt # TD exclusive: never overlap with OSS lanes or another TD. for lane in td_lanes: lane_name, receipt = _run_lane(lane) results[lane_name] = receipt duration = time.time() - start full_commit = prod2u_p4_harness.current_commit() overall = _overall_status(results, selected) matrix = { "schema": "prod2u-p4-normal-v3-verification-matrix-v2", "generated_at": _utc_now(), "verification_run_id": run_id, "commit": full_commit[:8] if full_commit else None, "commit_full": full_commit, "dirty": None, "project_config_sha256": _sha256_file(repo / "projects" / "prod2u-door-temp" / "project.json"), "td_source_manifest_sha256": _sha256_file(repo / "src" / "generated" / "td-source-manifest.json"), "status": overall, "duration_seconds": round(duration, 3), "lanes": results, "lane_dirs": lane_dirs, "failures": [f"{lane}:{r['status']}" for lane, r in results.items() if r.get("status") != "pass"], "environment": "linux", "td_command": "td2026", "resource_plan": plan, "host_resources": host_resources(), } report_path = Path(args.report_file) report_path.parent.mkdir(parents=True, exist_ok=True) _write_json(report_path, matrix) print(json.dumps({"status": overall, "report": str(report_path)}, indent=2)) return 0 if overall == "pass" else 1 if __name__ == "__main__": sys.exit(main())