| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237 |
- """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.
- """
- from __future__ import annotations
- import argparse
- import json
- import subprocess
- import sys
- import time
- from concurrent.futures import ThreadPoolExecutor
- from datetime import datetime, timezone
- from pathlib import Path
- from typing import Any
- _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
- DEFAULT_LANES = ["python", "icarus", "verilator", "cocotb", "formal"]
- DEFAULT_MAX_WORKERS = 4
- def _utc_now() -> str:
- return datetime.now(timezone.utc).isoformat()
- def _sha256_file(path: Path) -> str:
- return prod2u_p4_harness.sha256_file(path)
- def _run(cmd: list[str], cwd: Path, log_path: Path | None = None) -> subprocess.CompletedProcess[str]:
- result = subprocess.run(
- cmd,
- cwd=cwd,
- text=True,
- capture_output=True,
- encoding="utf-8",
- errors="replace",
- )
- if log_path is not None:
- log_path.parent.mkdir(parents=True, exist_ok=True)
- with log_path.open("w", encoding="utf-8") as f:
- f.write(f"command: {' '.join(cmd)}\n")
- f.write(f"returncode: {result.returncode}\n")
- f.write("--- stdout ---\n")
- f.write(result.stdout)
- f.write("\n--- stderr ---\n")
- f.write(result.stderr)
- return result
- 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_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"
- work_root.mkdir(parents=True, exist_ok=True)
- result = _run(
- [
- sys.executable,
- "-B",
- "-m",
- "pytest",
- "-q",
- "-p",
- "no:cacheprovider",
- "tests/unit",
- "tests/test_project_structure.py",
- ],
- repo,
- log_path,
- )
- status = "pass" if result.returncode == 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": "python -B -m pytest -q -p no:cacheprovider tests/unit tests/test_project_structure.py",
- "tool_version": f"Python {sys.version.split()[0]}",
- "returncode": result.returncode,
- "stdout_tail": result.stdout[-4096:] if result.stdout else "",
- "stderr_tail": result.stderr[-4096:] if result.stderr else "",
- "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,
- ) -> dict[str, Any]:
- receipt_path = work_root / f"{lane}-receipt.json"
- log_path = work_root / f"{lane}.log"
- 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(cmd, repo, log_path)
- 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))
- 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],
- )
- 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")
- LANE_RUNNERS = {
- "python": run_python_unit,
- "icarus": run_hdl_lane,
- "verilator": run_hdl_lane,
- "cocotb": run_hdl_lane,
- "formal": run_formal,
- }
- 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", required=True)
- 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
- 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]
- if lane in ("icarus", "verilator", "cocotb"):
- return lane, runner(repo, work_root, run_id, lane)
- return lane, runner(repo, work_root, run_id)
- start = time.time()
- with ThreadPoolExecutor(max_workers=min(args.max_workers, len(selected))) as pool:
- for lane, receipt in pool.map(_run_lane, selected):
- results[lane] = 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-v1",
- "generated_at": _utc_now(),
- "verification_run_id": run_id,
- "commit": full_commit[:8] if full_commit else None,
- "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"),
- "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"],
- }
- 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())
|