"""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. """ 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.run_visible import run_visible # noqa: E402 DEFAULT_LANES = [ "python", "board_viewer", "icarus", "verilator", "cocotb", "formal", "td", ] # TD is exclusive; keep open-source concurrency modest on ~3 GiB hosts. DEFAULT_MAX_WORKERS = 2 TD_EXCLUSIVE = frozenset({"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 _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() if name != "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, ) def run_python_unit(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]: receipt_path = work_root / "python-unit-receipt.json" log_path = work_root / "python-unit.log" status_path = work_root / "python-unit.status.json" work_root.mkdir(parents=True, exist_ok=True) cmd = [ sys.executable, "-B", "-m", "pytest", "-q", "-p", "no:cacheprovider", "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, ) 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), } _write_json(receipt_path, receipt) return receipt def run_board_viewer(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]: receipt_path = work_root / "board-viewer-receipt.json" log_path = work_root / "board-viewer.log" status_path = work_root / "board-viewer.status.json" work_root.mkdir(parents=True, exist_ok=True) cmd = [ sys.executable, "-B", "-m", "pytest", "-q", "-p", "no:cacheprovider", "tests/board_viewer", ] code = _run_visible_cmd( cmd, cwd=repo, log_path=log_path, status_path=status_path, name="board_viewer", timeout_s=900, ) 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), } _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, ) -> dict[str, Any]: receipt_path = work_root / f"{lane}-receipt.json" log_path = work_root / f"{lane}.log" status_path = work_root / f"{lane}.status.json" work_root.mkdir(parents=True, exist_ok=True) 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, ) 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)) return receipt def run_hdl_lane(repo: Path, work_root: Path, run_id: str, lane: str) -> dict[str, Any]: return _run_harness_lane( repo, work_root, run_id, lane, "hdl-sim", ["--backend", lane], timeout_s=1200, ) def run_formal(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]: return _run_harness_lane(repo, work_root, run_id, "formal", "formal", timeout_s=1800) def run_td(repo: Path, work_root: Path, run_id: str) -> 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"), } try: return _run_harness_lane( repo, work_root, run_id, "td", "td-build", timeout_s=3600, ) 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", required=True) 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=DEFAULT_MAX_WORKERS) args = parser.parse_args() 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 results: dict[str, dict[str, Any]] = {} def _run_lane(lane: str) -> tuple[str, dict[str, Any]]: work_root = Path(f"{args.work_root_prefix}-{lane}-{run_id[:8]}") runner = LANE_RUNNERS[lane] print(f"[matrix] starting lane={lane} work_root={work_root}", flush=True) if lane in ("icarus", "verilator", "cocotb"): receipt = runner(repo, work_root, run_id, lane) else: receipt = runner(repo, work_root, run_id) print(f"[matrix] finished lane={lane} status={receipt.get('status')}", flush=True) return lane, receipt start = time.time() # Run TD alone after open-source lanes to avoid license/memory contention. open_lanes = [l for l in selected if l not in TD_EXCLUSIVE] td_lanes = [l for l in selected if l in TD_EXCLUSIVE] with ThreadPoolExecutor(max_workers=min(args.max_workers, max(1, len(open_lanes)))) as pool: futures = [pool.submit(_run_lane, lane) for lane in open_lanes] for fut in as_completed(futures): lane, receipt = fut.result() results[lane] = receipt 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, "failures": [f"{lane}:{r['status']}" for lane, r in results.items() if r.get("status") != "pass"], "environment": "linux", "td_command": "td2026", } 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())