#!/usr/bin/env python3 """Run L11 deterministic randomized soak and emit a source-bound receipt.""" from __future__ import annotations from datetime import datetime, timezone import hashlib import json import os from pathlib import Path import subprocess import tempfile import time import xml.etree.ElementTree as ET try: from cocotb_tools.runner import get_runner except ModuleNotFoundError: from cocotb.runner import get_runner ROOT = Path(__file__).resolve().parents[1] TEST_DIR = ROOT / "tests/cocotb" CLOSURE = ROOT / "products/6400-control/source-closure.json" WRAPPER = TEST_DIR / "prod2u_6400_v1_cocotb_top.v" def sha256(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest() def git(*args: str) -> str: return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip() def main() -> int: dirty = git("status", "--porcelain") if dirty: raise SystemExit(f"soak requires a clean source worktree:\n{dirty}") commit = git("rev-parse", "HEAD") tree = git("rev-parse", "HEAD^{tree}") closure = json.loads(CLOSURE.read_text(encoding="utf-8")) sources = [ROOT / item for item in closure["sources"] if item.endswith(".v")] input_paths = [CLOSURE, WRAPPER, TEST_DIR / "thermal_6400_uart.py", TEST_DIR / "test_6400_v1_soak.py", *sources] inputs = {str(path.relative_to(ROOT)): sha256(path) for path in input_paths} source_hash = hashlib.sha256(json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode()).hexdigest() stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") run_id = f"6400-soak-{stamp}-{commit[:8]}" run_root = Path(os.environ.get("PROD2U_SOAK_RUN_ROOT", "/data/prod2u/cpld-runs")) / run_id run_root.mkdir(parents=True, exist_ok=False) result_json = run_root / "soak-result.json" results_xml = run_root / "results.xml" seed = int(os.environ.get("PROD2U_SOAK_SEED", "1677779166")) iterations = int(os.environ.get("PROD2U_SOAK_ITERATIONS", "96")) runner = get_runner("icarus") started = time.monotonic() status = "FAIL" failure = None try: runner.build( sources=[*sources, WRAPPER], hdl_toplevel="prod2u_6400_v1_cocotb_top", build_dir=run_root / "build", build_args=["-g2012", "-I", str(ROOT)], parameters={"ENABLE_STIMULUS": 1, "BMC_INITIAL_EPOCH": 0xFFFA}, always=True, ) result_path = Path(runner.test( hdl_toplevel="prod2u_6400_v1_cocotb_top", test_module="test_6400_v1_soak", test_dir=TEST_DIR, build_dir=run_root / "build", results_xml=str(results_xml), extra_env={ "PROD2U_SOAK_RESULT": str(result_json), "PROD2U_SOAK_SEED": str(seed), "PROD2U_SOAK_ITERATIONS": str(iterations), "PYTHONPATH": str(TEST_DIR), }, )) xml = ET.parse(result_path).getroot() cases = xml.findall(".//testcase") failures = xml.findall(".//failure") + xml.findall(".//error") skipped = xml.findall(".//skipped") if len(cases) != 1 or failures or skipped or not result_json.is_file(): raise RuntimeError(f"incomplete soak cases={len(cases)} failures={len(failures)} skipped={len(skipped)}") status = "PASS" except Exception as exc: # receipt must survive a failed test failure = f"{type(exc).__name__}: {exc}" duration = round(time.monotonic() - started, 3) payload = json.loads(result_json.read_text(encoding="utf-8")) if result_json.is_file() else None receipt = { "schema": "prod2u-6400-soak-receipt-v1", "run_id": run_id, "status": status, "generated_at": datetime.now(timezone.utc).isoformat(), "commit": commit, "tree": tree, "clean": not bool(dirty), "command": "python3 tools/run_6400_soak.py", "seed": seed, "iterations": iterations, "duration_seconds": duration, "source_manifest_sha256": source_hash, "inputs": inputs, "container_image_id": os.environ.get("PROD2U_CONTAINER_IMAGE_ID"), "container_digest": os.environ.get("PROD2U_CONTAINER_DIGEST"), "result": payload, "results_xml": str(results_xml) if results_xml.is_file() else None, "results_xml_sha256": sha256(results_xml) if results_xml.is_file() else None, "failure": failure, "hardware": "NOT RUN", } receipt_path = run_root / "soak-receipt.json" receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8") print(receipt_path) if status == "PASS": print(f"L11_SOAK_PASS iterations={iterations} seed={seed} duration_s={duration}") return 0 print(f"L11_SOAK_FAIL {failure}") return 1 if __name__ == "__main__": raise SystemExit(main())