"""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) are derived from host nproc, MemAvailable, and free disk. Formal concurrency is memory-capped. TD is always exclusive (serialized after open-source lanes, with a lock file). """ from __future__ import annotations import argparse import json import os import shutil 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_EXCLUSIVE = frozenset({"td"}) # Approximate resident budgets used only for concurrency planning (not fake %). _CLASS_MEM_KB = { "light": 256 * 1024, "medium": 512 * 1024, "heavy": 1536 * 1024, "exclusive": 2048 * 1024, } LANE_RESOURCE_CLASS: dict[str, str] = { "python": "light", "board_viewer": "light", "icarus": "medium", "cocotb": "medium", "verilator": "heavy", "formal": "heavy", "td": "exclusive", } 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 host_resources() -> dict[str, Any]: nproc = os.cpu_count() or 1 mem_available_kb: int | None = None try: with open("/proc/meminfo", encoding="utf-8") as handle: for line in handle: if line.startswith("MemAvailable:"): mem_available_kb = int(line.split()[1]) break except OSError: mem_available_kb = None try: disk_free_bytes = shutil.disk_usage("/").free except OSError: disk_free_bytes = None return { "nproc": nproc, "mem_available_kb": mem_available_kb, "disk_free_bytes": disk_free_bytes, } def plan_concurrency(selected: list[str], *, max_workers_cap: int | None = None) -> dict[str, Any]: """Derive open-source worker count from host resources and lane classes. - TD (exclusive) never shares the pool; callers run it alone after OSS lanes. - Formal is heavy and memory-capped: at most one formal job when MemAvailable is under ~3.5 GiB, and never more than one formal concurrent with another heavy lane on small hosts. """ host = host_resources() nproc = int(host["nproc"] or 1) mem_kb = host["mem_available_kb"] disk_free = host["disk_free_bytes"] open_lanes = [lane for lane in selected if lane not in TD_EXCLUSIVE] classes = {lane: LANE_RESOURCE_CLASS.get(lane, "medium") for lane in open_lanes} has_formal = "formal" in open_lanes has_heavy = any(classes[lane] == "heavy" for lane in open_lanes) # Disk gate: refuse to oversubscribe if free disk is critically low. disk_ok = disk_free is None or disk_free >= 2 * 1024**3 if mem_kb is None: # Unknown memory: stay conservative. workers = 1 if has_heavy else min(2, nproc) formal_slots = 1 else: # Leave ~512 MiB headroom for the matrix process / OS. usable = max(0, mem_kb - 512 * 1024) if has_formal and mem_kb < 3500 * 1024: formal_slots = 1 # On low-memory hosts, do not overlap formal with another heavy lane. workers = 1 if has_heavy else min(2, nproc) else: formal_slots = 1 # formal is always single-flight within this matrix # Pack light/medium/heavy budgets into usable RAM, capped by nproc. budget_workers = max(1, usable // _CLASS_MEM_KB["medium"]) workers = max(1, min(nproc, budget_workers, 4)) if has_heavy and mem_kb < 2500 * 1024: workers = 1 if not disk_ok: workers = 1 if max_workers_cap is not None: workers = max(1, min(workers, max_workers_cap)) workers = max(1, min(workers, max(1, len(open_lanes)))) return { "host": host, "open_lanes": open_lanes, "lane_classes": classes, "max_workers": workers, "formal_slots": formal_slots if has_formal else 0, "td_exclusive": bool(any(lane in TD_EXCLUSIVE for lane in selected)), "disk_ok": disk_ok, } 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 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), "resource_class": LANE_RESOURCE_CLASS["python"], } _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), "resource_class": LANE_RESOURCE_CLASS["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, ) -> 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)) receipt.setdefault("resource_class", LANE_RESOURCE_CLASS.get(lane, "medium")) 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]: # 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) 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"), "resource_class": "exclusive", } try: receipt = _run_harness_lane( repo, work_root, run_id, "td", "td-build", timeout_s=3600, ) 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 _schedule_open_lanes(open_lanes: list[str], plan: dict[str, Any]) -> list[list[str]]: """Partition open-source lanes into waves respecting memory / formal caps. When formal_slots==1 and memory is tight (max_workers==1 with heavy), run heavy lanes (formal, verilator) sequentially. Otherwise run the pool wave first, then any remaining exclusive-within-OSS serialization is handled by max_workers alone. """ if not open_lanes: return [] workers = int(plan["max_workers"]) mem_kb = (plan.get("host") or {}).get("mem_available_kb") # On low-memory hosts: serialize heavy lanes, allow light/medium to share. if workers <= 1 or (mem_kb is not None and mem_kb < 2500 * 1024): light_medium = [lane for lane in open_lanes if LANE_RESOURCE_CLASS.get(lane) in ("light", "medium")] heavy = [lane for lane in open_lanes if LANE_RESOURCE_CLASS.get(lane) == "heavy"] waves: list[list[str]] = [] if light_medium: waves.append(light_medium) for lane in heavy: waves.append([lane]) return waves or [open_lanes] return [open_lanes] 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=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 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"classes={plan['lane_classes']}", flush=True, ) 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} class={LANE_RESOURCE_CLASS.get(lane)} " f"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() 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_open_lanes(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, "failures": [f"{lane}:{r['status']}" for lane, r in results.items() if r.get("status") != "pass"], "environment": "linux", "td_command": "td2026", "resource_plan": plan, } 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())