#!/usr/bin/env python3 """Offline verification and TD build harness for Prod2U Profile 4 Normal v3.""" from __future__ import annotations import argparse import hashlib import json import os import re import shutil import subprocess import sys import uuid from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timezone from pathlib import Path from typing import Any, Mapping, Sequence sys.dont_write_bytecode = True ROOT = Path(__file__).resolve().parents[1] TOOLS = ROOT / "tools" if str(TOOLS) not in sys.path: sys.path.insert(0, str(TOOLS)) from prod2u_p4_normal_v3_build import ( # noqa: E402 FULL_COMMIT_RE, PRODUCTION_RTL_SOURCES, PROJECT_CONFIG_PATH as PROJECT_CONFIG_RELATIVE_PATH, SHORT_COMMIT_RE, TD_SOURCE_MANIFEST_PATH as TD_SOURCE_MANIFEST_RELATIVE_PATH, build_synthesis_input_manifest, ) from generate_project import load_project, render_adc # noqa: E402 from tool_env import ensure_safe_sys_executable, safe_python # noqa: E402 # Linux-first: resolve TD from PATH / env. Windows absolute path kept only as last-resort legacy hint. _TD_HOME = Path(os.environ.get("ANLOGIC_TD_HOME", "/data/anlogic/TD_Release_2026.1_SP2_NL")) _TD_FROM_PATH = shutil.which("td2026") or shutil.which("td") TD_EXE = Path( os.environ.get("TD_BIN") or (_TD_FROM_PATH if _TD_FROM_PATH else "") or (_TD_HOME / "bin" / "td") ) def _default_prod2u_toolchain_base() -> Path: override = ( os.environ.get("PRODU2_TOOLCHAIN_BASE", "").strip() or os.environ.get("PROD2U_P4_TOOLCHAIN_ROOT", "").strip() ) if override: return Path(override) persistent = Path("/data/prod2u") if persistent.is_dir() or os.access("/data", os.W_OK): return persistent return Path.home() / ".cache" / "prod2u" DEFAULT_TOOLCHAIN_ROOT = Path( os.environ.get( "OSS_CAD_SUITE_ROOT", str(_default_prod2u_toolchain_base() / "oss-cad-suite" / "latest"), ) ) def _default_verify_venv_root() -> Path: override = os.environ.get("PRODU2_VERIFY_VENV_ROOT", "").strip() if override: return Path(override) verify_venv = os.environ.get("PRODU2_VERIFY_VENV", "").strip() if verify_venv: return Path(verify_venv).expanduser().resolve().parent persistent = Path("/data/prod2u/venvs") if persistent.is_dir(): return persistent return Path.home() / ".cache" / "prod2u" / "venvs" DEFAULT_VENV_ROOT = _default_verify_venv_root() PROFILE = "prod2u_p4_normal_v3" RUNTIME_PROFILE = "prod2u-door-temp-115200-v1" TOP_MODULE = "prod2u_p4_normal_v3_top" PIN_PROFILE = "prod2u-p4-normal-v3" TARGET_DEVICE = "EF2L45BG256B" DEFAULT_TIMEOUT_SECONDS = { "icarus_compile": 120.0, "icarus_run": 180.0, "verilator": 300.0, "cocotb": 600.0, "formal": 600.0, "td": 1800.0, } # Serial formal tasks: hosts often have ~2 CPU / ~1.6–2 GiB available. FORMAL_MAX_WORKERS = 1 HDL_RECEIPT_SCHEMA = "prod2u-p4-normal-v3-hdl-sim-receipt-v1" FORMAL_RECEIPT_SCHEMA = "prod2u-p4-normal-v3-formal-receipt-v1" TD_RECEIPT_SCHEMA = "prod2u-p4-normal-v3-td-build-receipt-v2" TD_BUILD_MODE_PRODUCTION = "production" RESOURCE_VARIANT_PRODUCTION = "minimal_production" OFFLINE_RECEIPT_SCHEMA = "prod2u-p4-normal-v3-strict-offline-gate-v1" PACKAGE_RECEIPT_SCHEMA = "prod2u-p4-normal-v3-package-selftest-v1" CDC_REPORT_SCHEMA = "prod2u-p4-normal-v3-cdc-v2" FSM_REPORT_SCHEMA = "prod2u-p4-normal-v3-fsm-encoding-v2" TARGET_MANIFEST_SCHEMA = "prod2u-simple-verification-target-manifest-v1" TARGET_MANIFEST_PROFILE = "prod2u-door-temp" TARGET_MANIFEST_PATH = ROOT / "config" / "prod2u_p4_verification_targets_v1.json" PROJECT_CONFIG_PATH = ROOT / PROJECT_CONFIG_RELATIVE_PATH TD_SOURCE_MANIFEST_PATH = ROOT / TD_SOURCE_MANIFEST_RELATIVE_PATH TARGET_MANIFEST_LAYERS = ("unit", "icarus", "verilator", "cocotb", "formal") TARGET_MANIFEST_OPTIONAL_LAYERS = ("formal_blocked",) EXPECTED_CDC_SYNC_REGISTERS = frozenset( { "u_uart_rx/rx_sync_pipe[0]", "u_uart_rx/rx_sync_pipe[1]", "u_temperature_i2c/scl_sync[0]", "u_temperature_i2c/scl_sync[1]", "u_temperature_i2c/sda_sync[0]", "u_temperature_i2c/sda_sync[1]", "x_limit_ls_sync0", "x_limit_ls_sync1", "x_limit_hs_sync0", "x_limit_hs_sync1", "y_limit_ls_sync0", "y_limit_ls_sync1", "y_limit_hs_sync0", "y_limit_hs_sync1", "z_limit_ls_sync0", "z_limit_ls_sync1", "z_limit_hs_sync0", "z_limit_hs_sync1", } ) EXPECTED_CDC_FALSE_PATH_ENDPOINTS = frozenset( { "u_uart_rx/rx_sync_pipe[0]", "u_temperature_i2c/scl_sync[0]", "u_temperature_i2c/sda_sync[0]", "x_limit_ls_sync0", "x_limit_hs_sync0", "y_limit_ls_sync0", "y_limit_hs_sync0", "z_limit_ls_sync0", "z_limit_hs_sync0", } ) EXPECTED_CDC_INPUT_REGISTERS = 9 # uart_rx + scl + sda + 6 limit first-stage syncs EXPECTED_FSM_AXES = {"x": 2, "y": 2, "z": 2} BUILD_ROOT_RELATIVE = Path("td") / PROFILE TD_SCRIPTS = { "syn": ROOT / "td" / "syn" / f"{PROFILE}.tcl", "phy": ROOT / "td" / "phy" / f"{PROFILE}.tcl", "bitgen": ROOT / "td" / "bitgen" / f"{PROFILE}.tcl", } SAFETY_BOUNDARY = { "opens_serial": False, "programs_hardware": False, "installs_drivers": False, } FORBIDDEN_TD_COMMANDS = { "connect_cable", "download", "erase_flash", "open_cable", "program", "program_flash", "program_sram", "program_spibin", } def utc_now() -> str: return datetime.now(timezone.utc).isoformat() def new_td_run_id() -> str: return uuid.uuid4().hex def normalize_verification_run_id(value: str | None) -> str: if value is None or not str(value).strip(): raise ValueError("verification_run_id is required") normalized = str(value).strip().lower() if not re.fullmatch(r"[0-9a-f]{32}", normalized): raise ValueError("verification_run_id must be 32 lowercase hex digits") return normalized def valid_td_run_id(value: object) -> bool: return isinstance(value, str) and re.fullmatch(r"[0-9a-f]{32}", value) is not None def active_pin_contract() -> dict[str, dict[str, str]]: """Derive the active 24-ball contract from project.json, not pad folklore.""" project = load_project(PROJECT_CONFIG_PATH) input_signals = {"sys_clk", "host_uart_rx", "x_limit_ls", "x_limit_hs", "y_limit_ls", "y_limit_hs", "z_limit_ls", "z_limit_hs"} inout_signals = {"temp_scl", "temp_sda"} return { signal: { "location": ball, "direction": ( "INOUT" if signal in inout_signals else "INPUT" if signal in input_signals else "OUTPUT" ), "pull_type": "NONE", } for signal, ball in render_adc(project) } def normalized_td_work_root(value: object) -> str | None: if not isinstance(value, str) or not value.strip(): return None candidate = Path(value) if not candidate.is_absolute(): return None return os.path.normcase(os.path.normpath(str(candidate.resolve(strict=False)))) def td_receipts_are_independent( primary: Mapping[str, Any], confirmation: Mapping[str, Any], ) -> bool: primary_run_id = primary.get("run_id") confirmation_run_id = confirmation.get("run_id") primary_work_root = normalized_td_work_root(primary.get("work_root")) confirmation_work_root = normalized_td_work_root(confirmation.get("work_root")) return bool( valid_td_run_id(primary_run_id) and valid_td_run_id(confirmation_run_id) and primary_run_id != confirmation_run_id and primary_work_root is not None and confirmation_work_root is not None and primary_work_root != confirmation_work_root ) def sha256_file(path: Path) -> str: digest = hashlib.sha256() with Path(path).open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def source_identity() -> dict[str, Any]: files = { "project_config_path": PROJECT_CONFIG_PATH, "td_source_manifest_path": TD_SOURCE_MANIFEST_PATH, } result: dict[str, Any] = { "project_config_path": PROJECT_CONFIG_RELATIVE_PATH, "project_config_sha256": None, "td_source_manifest_path": TD_SOURCE_MANIFEST_RELATIVE_PATH, "td_source_manifest_sha256": None, } failures: list[str] = [] for field, path in files.items(): digest_field = field.replace("_path", "_sha256") if not path.is_file(): failures.append(f"source_identity_missing:{field}") continue try: result[digest_field] = sha256_file(path) except OSError as exc: failures.append(f"source_identity_unreadable:{field}:{type(exc).__name__}") result["failures"] = failures return result def source_binding_fields( state: Mapping[str, Any], *, verification_run_id: str | None = None, ) -> dict[str, Any]: bindings: dict[str, Any] = { "commit": state.get("commit"), "commit_full": state.get("commit_full"), "commit_short": state.get("commit_short"), "project_config_sha256": state.get("project_config_sha256"), "td_source_manifest_sha256": state.get("td_source_manifest_sha256"), } if verification_run_id is not None: bindings["verification_run_id"] = verification_run_id return bindings def receipt_commit_full(receipt: Mapping[str, Any]) -> str | None: for field in ("commit_full", "commit"): value = receipt.get(field) if isinstance(value, str) and FULL_COMMIT_RE.fullmatch(value): return value return None def receipt_commit_matches(receipt: Mapping[str, Any], expected_commit: str) -> bool: full = receipt_commit_full(receipt) if full is not None: return full == expected_commit short = receipt.get("commit") return ( isinstance(short, str) and SHORT_COMMIT_RE.fullmatch(short) is not None and short == expected_commit[:8] ) def td_receipt_bitstream_binding_status(receipt: Mapping[str, Any]) -> str: if receipt.get("status") in {"not_run", "blocked", "running"}: return "not_run" digest = receipt.get("bitstream_sha256") if digest is None or digest == "": return "not_run" if not re.fullmatch(r"[0-9a-f]{64}", str(digest)): return "fail" candidates: list[Mapping[str, Any]] = [] direct = receipt.get("bitstream") if isinstance(direct, Mapping): candidates.append(direct) measurements = receipt.get("measurement_artifacts") measured = measurements.get("bitstream") if isinstance(measurements, Mapping) else None if isinstance(measured, Mapping): candidates.append(measured) for candidate in candidates: if candidate.get("sha256") != digest: continue path = Path(str(candidate.get("path", ""))) if path.is_file() and sha256_file(path) == digest: return "pass" return "fail" def canonical_sha256(value: object) -> str: encoded = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("ascii") return hashlib.sha256(encoded).hexdigest() def validation_layer_summary(layers: object) -> str: if not isinstance(layers, Mapping): return "fail" statuses = { layer.get("status") if isinstance(layer, Mapping) else None for layer in layers.values() } for status in ("fail", "running", "not_run"): if status in statuses: return status return "pass" if statuses and statuses == {"pass"} else "fail" def load_receipt(path: Path) -> dict[str, Any]: payload = json.loads(Path(path).read_text(encoding="utf-8-sig")) if not isinstance(payload, dict): raise ValueError(f"receipt root must be an object: {path}") return payload def load_target_manifest() -> dict[str, Any]: payload = json.loads(TARGET_MANIFEST_PATH.read_text(encoding="utf-8")) if not isinstance(payload, dict): raise ValueError("target manifest root must be an object") if payload.get("schema") != TARGET_MANIFEST_SCHEMA: raise ValueError("target manifest schema mismatch") if payload.get("version") != 1: raise ValueError("target manifest version mismatch") if payload.get("profile") != TARGET_MANIFEST_PROFILE: raise ValueError("target manifest profile mismatch") layers = payload.get("layers") allowed_layers = set(TARGET_MANIFEST_LAYERS) | set(TARGET_MANIFEST_OPTIONAL_LAYERS) if not isinstance(layers, dict) or set(layers) - allowed_layers or set(TARGET_MANIFEST_LAYERS) - set(layers): raise ValueError("target manifest layers mismatch") for layer in TARGET_MANIFEST_LAYERS: values = layers.get(layer) if not isinstance(values, list) or not values: raise ValueError(f"target manifest layer must be a non-empty list: {layer}") for layer in ("unit", "icarus", "verilator", "cocotb"): values = layers[layer] if any(not isinstance(value, str) or not value for value in values): raise ValueError(f"target manifest contains invalid name: {layer}") if len(values) != len(set(values)): raise ValueError(f"target manifest contains duplicate names: {layer}") formal_names: list[str] = [] for entry in layers["formal"]: if not isinstance(entry, dict) or set(entry) != {"name", "tasks"}: raise ValueError("target manifest formal entry invalid") name = entry.get("name") tasks = entry.get("tasks") if not isinstance(name, str) or not name or not isinstance(tasks, list): raise ValueError("target manifest formal entry invalid") if any(not isinstance(task, str) or not task for task in tasks): raise ValueError(f"target manifest formal task invalid: {name}") if len(tasks) != len(set(tasks)): raise ValueError(f"target manifest formal task duplicate: {name}") formal_names.append(name) if len(formal_names) != len(set(formal_names)): raise ValueError("target manifest contains duplicate formal names") blocked = layers.get("formal_blocked", []) if blocked: if not isinstance(blocked, list): raise ValueError("target manifest formal_blocked must be a list") blocked_names: list[str] = [] for entry in blocked: if not isinstance(entry, dict): raise ValueError("target manifest formal_blocked entry invalid") allowed_keys = {"name", "tasks", "blocked_reason"} if set(entry) - allowed_keys or "name" not in entry or "tasks" not in entry: raise ValueError("target manifest formal_blocked entry invalid") name = entry.get("name") tasks = entry.get("tasks") if not isinstance(name, str) or not name or not isinstance(tasks, list): raise ValueError("target manifest formal_blocked entry invalid") if name in formal_names: raise ValueError(f"target manifest formal_blocked overlaps active formal: {name}") blocked_names.append(name) if len(blocked_names) != len(set(blocked_names)): raise ValueError("target manifest contains duplicate formal_blocked names") return payload def _normalized_target_layer(layer: str, value: object) -> object: if layer == "formal": if isinstance(value, Mapping): items = value.items() elif isinstance(value, Sequence) and not isinstance(value, (str, bytes)): items = ( (entry.get("name"), entry.get("tasks")) for entry in value if isinstance(entry, Mapping) ) else: return {} normalized: dict[str, list[str]] = {} for name, tasks in items: if isinstance(name, str) and isinstance(tasks, Sequence) and not isinstance(tasks, (str, bytes)): normalized[name] = [str(task) for task in tasks] return dict(sorted(normalized.items())) if not isinstance(value, Sequence) or isinstance(value, (str, bytes)): return [] return sorted(str(item) for item in value) def target_manifest_evidence(layer: str, observed: object) -> dict[str, Any]: failures: list[str] = [] try: manifest = load_target_manifest() except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as exc: return { "schema": TARGET_MANIFEST_SCHEMA, "version": 1, "sha256": "0" * 64, "layer": layer, "status": "fail", "expected": {}, "observed": observed, "failures": [f"target_manifest_unavailable:{type(exc).__name__}:{exc}"], } layers = manifest["layers"] manifest_sha256 = canonical_sha256(manifest) if layer == "all": expected_all = { name: _normalized_target_layer(name, layers[name]) for name in TARGET_MANIFEST_LAYERS } observed_mapping = observed if isinstance(observed, Mapping) else {} observed_all = { name: _normalized_target_layer(name, observed_mapping.get(name)) for name in TARGET_MANIFEST_LAYERS } for name in TARGET_MANIFEST_LAYERS: child = target_manifest_evidence(name, observed_all[name]) failures.extend(child["failures"]) return { "schema": TARGET_MANIFEST_SCHEMA, "version": manifest["version"], "sha256": manifest_sha256, "layer": layer, "status": "pass" if not failures else "fail", "expected": expected_all, "observed": observed_all, "failures": sorted(set(failures)), } if layer not in TARGET_MANIFEST_LAYERS: failures.append(f"target_manifest_layer_unknown:{layer}") expected = [] normalized_observed = _normalized_target_layer(layer, observed) else: expected = _normalized_target_layer(layer, layers[layer]) normalized_observed = _normalized_target_layer(layer, observed) if not normalized_observed: failures.append(f"target_manifest_empty_observed:{layer}") if layer == "formal": expected_names = set(expected) observed_names = set(normalized_observed) for name in sorted(expected_names - observed_names): failures.append(f"target_manifest_missing:{layer}:{name}") for name in sorted(observed_names - expected_names): failures.append(f"target_manifest_extra:{layer}:{name}") for name in sorted(expected_names & observed_names): if normalized_observed[name] != expected[name]: failures.append(f"target_manifest_task_drift:{name}") else: expected_names = set(expected) observed_names = set(normalized_observed) if len(normalized_observed) != len(observed_names): failures.append(f"target_manifest_duplicate:{layer}") for name in sorted(expected_names - observed_names): failures.append(f"target_manifest_missing:{layer}:{name}") for name in sorted(observed_names - expected_names): failures.append(f"target_manifest_extra:{layer}:{name}") return { "schema": TARGET_MANIFEST_SCHEMA, "version": manifest["version"], "sha256": manifest_sha256, "layer": layer, "status": "pass" if not failures else "fail", "expected": expected, "observed": normalized_observed, "failures": sorted(set(failures)), } def _tail(value: str, limit: int = 4000) -> str: return value[-limit:] def configured_timeout(name: str) -> float: default = DEFAULT_TIMEOUT_SECONDS[name] raw = os.environ.get(f"PROD2U_P4_TIMEOUT_{name.upper()}_SECONDS", "").strip() if not raw: return default try: value = float(raw) except ValueError: return default return value if value > 0 else default def _timeout_text(value: str | bytes | None) -> str: if isinstance(value, bytes): return value.decode(errors="replace") return value or "" def _timed_out_result(command: Sequence[str], exc: subprocess.TimeoutExpired) -> subprocess.CompletedProcess[str]: completed = subprocess.CompletedProcess( list(command), None, _timeout_text(exc.stdout or exc.output), _timeout_text(exc.stderr), ) completed.timed_out = True # type: ignore[attr-defined] return completed def _run_bounded(command: Sequence[str], *, timeout_name: str, **kwargs: Any) -> subprocess.CompletedProcess[str]: try: return subprocess.run(list(command), timeout=configured_timeout(timeout_name), **kwargs) except subprocess.TimeoutExpired as exc: return _timed_out_result(command, exc) def _was_timed_out(completed: subprocess.CompletedProcess[str] | None) -> bool: return bool(completed is not None and getattr(completed, "timed_out", False)) def write_json_report(payload: Mapping[str, Any], path: Path) -> None: target = Path(path) target.parent.mkdir(parents=True, exist_ok=True) target.write_text(json.dumps(dict(payload), indent=2) + "\n", encoding="utf-8", newline="\n") def _git(*args: str) -> subprocess.CompletedProcess[str]: return subprocess.run( ["git", *args], cwd=ROOT, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False, ) def source_state() -> dict[str, Any]: commit_result = _git("rev-parse", "HEAD") status_result = _git("status", "--porcelain", "--untracked-files=all") full_commit = commit_result.stdout.strip().lower() commit = full_commit changes = [] for line in status_result.stdout.splitlines(): if not line.strip(): continue relative = line[3:].replace("\\", "/") if len(line) >= 4 else line.strip() if relative == ".planning" or relative.startswith(".planning/"): continue changes.append(line) failures: list[str] = [] if commit_result.returncode != 0 or not re.fullmatch( r"[0-9a-f]{40}", full_commit ): failures.append("git_commit_unavailable") if status_result.returncode != 0: failures.append("git_status_unavailable") identity = source_identity() failures.extend(identity["failures"]) return { "status": "pass" if not failures else "fail", "commit": commit, "commit_full": full_commit if FULL_COMMIT_RE.fullmatch(full_commit) else None, "commit_short": full_commit[:8] if FULL_COMMIT_RE.fullmatch(full_commit) else None, "project_config_path": identity["project_config_path"], "project_config_sha256": identity["project_config_sha256"], "td_source_manifest_path": identity["td_source_manifest_path"], "td_source_manifest_sha256": identity["td_source_manifest_sha256"], "clean": status_result.returncode == 0 and not changes, "tracked_changes": changes, "failures": failures, } def current_commit() -> str: state = source_state() if state["status"] != "pass": raise RuntimeError("unable to bind verification evidence to the current Git commit") return str(state["commit"]) def resolve_work_root(work_root: Path | None, *, run: bool) -> Path | None: if work_root is None: if run: raise ValueError("--work-root is required when tools are executed") return None resolved = Path(work_root).expanduser().resolve() repository = ROOT.resolve() if resolved == repository or repository in resolved.parents: raise ValueError("work root must be outside the repository") if resolved.exists() and not resolved.is_dir(): raise ValueError("work root must be a directory") if run: resolved.mkdir(parents=True, exist_ok=True) return resolved def resolve_report_file(report_file: Path) -> Path: resolved = Path(report_file).expanduser().resolve() repository = ROOT.resolve() if resolved == repository or repository in resolved.parents: raise ValueError("report file must be outside the repository") return resolved def resolve_input_receipt(receipt_file: Path) -> Path: resolved = Path(receipt_file).expanduser().resolve() repository = ROOT.resolve() if resolved == repository or repository in resolved.parents: raise ValueError("input receipt must be outside the repository") if not resolved.is_file(): raise ValueError(f"input receipt is missing: {resolved}") return resolved def _tool_candidates(name: str) -> list[Path]: if name == "verilator": executable_names = ["verilator_bin.exe", "verilator.exe"] else: executable_names = [name, f"{name}.exe"] roots: list[Path] = [] configured = os.environ.get("OSS_CAD_SUITE_ROOT", "").strip() if configured: roots.append(Path(configured)) roots.append(DEFAULT_TOOLCHAIN_ROOT) candidates: list[Path] = [] for root in roots: for directory in (root / "bin", root): candidates.extend(directory / executable for executable in executable_names) return candidates def _native_verilator_binary(path: str | Path) -> str | None: candidate = Path(path).expanduser().resolve() if candidate.name.lower() not in {"verilator_bin.exe", "verilator.exe"}: return None return str(candidate) if candidate.is_file() else None def toolchain_roots() -> list[Path]: roots: list[Path] = [] configured = os.environ.get("OSS_CAD_SUITE_ROOT", "").strip() if configured: roots.append(Path(configured)) roots.append(DEFAULT_TOOLCHAIN_ROOT) return list(dict.fromkeys(path.expanduser().resolve() for path in roots)) def resolve_tool(name: str) -> str | None: if name == "verilator": for candidate in _tool_candidates(name): resolved = _native_verilator_binary(candidate) if resolved: return resolved for executable in ("verilator", "verilator_bin", "verilator_bin.exe", "verilator.exe"): located = shutil.which(executable) if located: # Linux/OSS CAD: plain `verilator` is enough; Windows names still accepted. if Path(located).name.lower() in {"verilator_bin.exe", "verilator.exe"}: resolved = _native_verilator_binary(located) if resolved: return resolved else: return located return None # Prefer OSS CAD / configured toolchain over ambient PATH. Host stubs such as # /usr/local/bin/sby without sby_cmdline on PYTHONPATH otherwise win shutil.which. for candidate in _tool_candidates(name): if candidate.is_file() and os.access(candidate, os.X_OK): return str(candidate.resolve()) located = shutil.which(name) if located: return located return None def tool_env(extra: Mapping[str, str] | None = None) -> dict[str, str]: env = os.environ.copy() # Keep TD libs out of OSS/Python/cocotb/Verilator subprocesses. for poison in ( "LD_LIBRARY_PATH", "LD_PRELOAD", "QT_PLUGIN_PATH", "PYTHONHOME", "PYTHONPATH", "PYTHONEXECUTABLE", "PERL5LIB", "PERL_LOCAL_LIB_ROOT", "PERL_MB_OPT", "PERL_MM_OPT", ): env.pop(poison, None) path_parts: list[str] = [] for root in toolchain_roots(): bin_dir = root / "bin" lib_dir = root / "lib" verilator_root = root / "share" / "verilator" smtbmc = bin_dir / "yosys-smtbmc.exe.exe" if bin_dir.is_dir(): path_parts.append(str(bin_dir)) if lib_dir.is_dir(): path_parts.append(str(lib_dir)) if verilator_root.is_dir(): env.setdefault("VERILATOR_ROOT", str(verilator_root)) if smtbmc.is_file(): env.setdefault("SMTBMC", str(smtbmc)) for name in ("iverilog", "sby", "yosys"): resolved = resolve_tool(name) if resolved: path_parts.append(str(Path(resolved).parent)) if path_parts: env["PATH"] = os.pathsep.join(dict.fromkeys([*path_parts, env.get("PATH", "")])) env["PYTHONDONTWRITEBYTECODE"] = "1" if extra: env.update({str(key): str(value) for key, value in extra.items()}) return env def formal_tool_env(work_root: Path) -> dict[str, str]: resolved = resolve_work_root(work_root, run=True) assert resolved is not None env = tool_env() wrapper_dir = resolved / "formal-tool-wrappers" wrappers: list[Path] = [] for command in ("yosys-smtbmc", "yosys-witness"): executable = next( ( root / "bin" / f"{command}.exe.exe" for root in toolchain_roots() if (root / "bin" / f"{command}.exe.exe").is_file() ), None, ) if executable is None: continue wrapper_dir.mkdir(parents=True, exist_ok=True) wrapper = wrapper_dir / f"{command}.cmd" wrapper.write_text( f'@echo off\r\n"{executable}" %*\r\n', encoding="ascii", newline="", ) wrappers.append(wrapper) if wrappers: env["PATH"] = os.pathsep.join([str(wrapper_dir), env.get("PATH", "")]) return env def active_rtl_sources() -> list[str]: missing = [relative for relative in PRODUCTION_RTL_SOURCES if not (ROOT / relative).is_file()] if missing: raise FileNotFoundError(f"active source closure is incomplete: {missing}") return list(PRODUCTION_RTL_SOURCES) def hdl_testbenches() -> list[dict[str, Any]]: rtl = active_rtl_sources() targets: list[dict[str, Any]] = [] for name in sorted(load_target_manifest()["layers"]["icarus"]): path = ROOT / "tests" / "sim" / f"{name}.v" if not path.is_file(): raise FileNotFoundError(f"manifest Icarus target is missing: {path}") sources = [*rtl, path.relative_to(ROOT).as_posix()] targets.append( { "name": name, "testbench": path.relative_to(ROOT).as_posix(), "sources": sources, } ) return targets def cocotb_tests() -> list[dict[str, str]]: targets: list[dict[str, str]] = [] for name in load_target_manifest()["layers"]["cocotb"]: runner = ROOT / "tests" / "cocotb" / f"run_{name}.py" if not runner.is_file(): raise FileNotFoundError(f"manifest cocotb target is missing: {runner}") targets.append( {"name": name, "runner": runner.relative_to(ROOT).as_posix()} ) return targets def formal_targets() -> list[dict[str, Any]]: targets: list[dict[str, Any]] = [] for entry in load_target_manifest()["layers"]["formal"]: name = entry["name"] path = ROOT / "tests" / "formal" / f"{name}.sby" if not path.is_file(): raise FileNotFoundError(f"manifest formal target is missing: {path}") targets.append( { "name": name, "sby": path.relative_to(ROOT).as_posix(), "tasks": list(entry["tasks"]), } ) return targets def formal_source_files(sby_file: Path) -> list[Path]: sources: list[Path] = [] in_files = False for raw_line in sby_file.read_text(encoding="utf-8", errors="replace").splitlines(): line = raw_line.strip() if line == "[files]": in_files = True continue if in_files and line.startswith("["): break if not in_files or not line or line.startswith("#"): continue candidate = (sby_file.parent / line.split()[0]).resolve() if candidate.suffix.casefold() in {".v", ".sv"} and candidate.is_file(): sources.append(candidate) return sources def _evidence_path(path: Path) -> str: resolved = Path(path).resolve() try: return resolved.relative_to(ROOT.resolve()).as_posix() except ValueError: return str(resolved) def formal_task_engines(sby_file: Path, tasks: Sequence[str]) -> dict[str, list[str]]: task_engines: dict[str, list[str]] = {} global_engines: list[str] = [] engines_section: str | None = None for raw_line in sby_file.read_text(encoding="utf-8", errors="replace").splitlines(): line = raw_line.strip() section_match = re.fullmatch(r"\[engines(?:\s+([^\]]+))?\]", line) if section_match is not None: engines_section = (section_match.group(1) or "").strip() continue if line.startswith("["): engines_section = None continue if engines_section is None or not line or line.startswith("#"): continue match = re.fullmatch(r"(?:(\S+)\s*:\s*)?(.+)", line) if match is None: continue task_name, engine = match.groups() normalized = engine.strip() if engines_section: task_engines.setdefault(engines_section, []).append(normalized) elif task_name is None: global_engines.append(normalized) else: task_engines.setdefault(task_name, []).append(normalized) names = list(tasks) or ["default"] return { name: list(task_engines.get(name, global_engines)) for name in names } def formal_input_evidence(sby_file: Path, tasks: Sequence[str]) -> dict[str, Any]: sources = formal_source_files(sby_file) payload: dict[str, Any] = { "sby": { "path": _evidence_path(sby_file), "sha256": sha256_file(sby_file), }, "sources": [ {"path": _evidence_path(source), "sha256": sha256_file(source)} for source in sources ], "task_engines": formal_task_engines(sby_file, tasks), } payload["sha256"] = canonical_sha256(payload) return payload def formal_runtime_evidence( workdir: Path, configured_engines: Sequence[str], ) -> dict[str, Any]: texts: list[str] = [] logfile = workdir / "logfile.txt" main_log = "" if logfile.is_file(): main_log = logfile.read_text(encoding="utf-8", errors="replace") texts.append(main_log) if workdir.is_dir(): for engine_log in sorted(workdir.glob("engine_*/logfile.txt")): texts.append(engine_log.read_text(encoding="utf-8", errors="replace")) combined = "\n".join(texts) observed_by_index: dict[int, str] = {} for match in re.finditer(r"(?im)^.*\]\s+engine_(\d+):\s+([^\r\n]+)$", main_log): index = int(match.group(1)) candidate = match.group(2).strip() if candidate and index not in observed_by_index: observed_by_index[index] = candidate solvers = sorted(set(re.findall(r"(?im)\bSolver:\s*([A-Za-z0-9_.+-]+)", combined))) configured = [str(engine).strip() for engine in configured_engines if str(engine).strip()] observed = [observed_by_index[index] for index in sorted(observed_by_index)] failures: list[str] = [] if not configured: failures.append("formal_engine_config_missing") if not observed: failures.append("formal_engine_observation_missing") elif set(observed) != set(configured): failures.append("formal_engine_observation_mismatch") if any(engine.split()[0].casefold() == "smtbmc" for engine in configured) and not solvers: failures.append("formal_solver_observation_missing") explicit_solvers = sorted( { parts[1].casefold() for engine in configured if len(parts := engine.split()) > 1 and parts[0].casefold() == "smtbmc" } ) if explicit_solvers and set(solver.casefold() for solver in solvers) != set(explicit_solvers): failures.append("formal_solver_observation_mismatch") return { "configured_engines": configured, "observed_engines": observed, "solvers": solvers, "failures": failures, } def formal_compiled_property_counts(workdir: Path) -> dict[str, Any]: design_json = workdir / "model" / "design.json" failures: list[str] = [] assertion_ids: set[str] = set() cover_ids: set[str] = set() design_sha256 = "0" * 64 try: payload = json.loads(design_json.read_text(encoding="utf-8")) except (OSError, UnicodeError, json.JSONDecodeError) as exc: payload = None failures.append(f"formal_compiled_properties_unavailable:{type(exc).__name__}") if isinstance(payload, Mapping): design_sha256 = sha256_file(design_json) modules = payload.get("modules") if isinstance(modules, Sequence) and not isinstance(modules, (str, bytes)): for module in modules: if not isinstance(module, Mapping): continue module_name = str(module.get("name", "")).strip() cell_sorts = module.get("cell_sorts") if not module_name or not isinstance(cell_sorts, Sequence) or isinstance(cell_sorts, (str, bytes)): continue for cell_sort in cell_sorts: cells = cell_sort.get("cells") if isinstance(cell_sort, Mapping) else None if not isinstance(cells, Sequence) or isinstance(cells, (str, bytes)): continue for cell in cells: if not isinstance(cell, Mapping): continue parameters = cell.get("parameters") flavor = parameters.get("FLAVOR") if isinstance(parameters, Mapping) else None cell_name = str(cell.get("name", "")).strip() if not cell_name: continue property_id = f"{module_name}.{cell_name}" if flavor == "assert": assertion_ids.add(property_id) elif flavor == "cover": cover_ids.add(property_id) return { "design_json": str(design_json), "design_sha256": design_sha256, "assertion_count": len(assertion_ids), "assertion_ids": sorted(assertion_ids), "cover_count": len(cover_ids), "cover_ids": sorted(cover_ids), "failures": failures, } def formal_tool_version_evidence( name: str, executable: str, version_args: Sequence[str], env: Mapping[str, str], work_root: Path, ) -> dict[str, Any]: resolved_work_root = resolve_work_root(work_root, run=True) assert resolved_work_root is not None path = Path(executable).resolve() failures: list[str] = [] digest = "0" * 64 if path.is_file(): digest = sha256_file(path) else: failures.append(f"formal_tool_path_invalid:{name}") try: completed = subprocess.run( [str(path), *version_args], cwd=resolved_work_root, env=dict(env), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30, check=False, ) except (OSError, subprocess.TimeoutExpired) as exc: completed = None failures.append(f"formal_tool_version_probe_failed:{name}:{type(exc).__name__}") output = "" if completed is None else "\n".join((completed.stdout, completed.stderr)).strip() version = next((line.strip() for line in output.splitlines() if line.strip()), "") if completed is not None and completed.returncode != 0: failures.append(f"formal_tool_version_probe_returncode:{name}:{completed.returncode}") if not version: failures.append(f"formal_tool_version_missing:{name}") return { "name": name, "path": str(path), "sha256": digest, "version": version, "status": "pass" if not failures else "fail", "failures": failures, } def formal_toolchain_evidence( sby: str, yosys: str, solvers: Sequence[str], work_root: Path, ) -> dict[str, Any]: env = formal_tool_env(work_root) sby_evidence = formal_tool_version_evidence("sby", sby, ["--version"], env, work_root) yosys_evidence = formal_tool_version_evidence("yosys", yosys, ["-V"], env, work_root) solver_args = { "yices": ("yices-smt2", ["--version"]), "boolector": ("boolector", ["--version"]), "z3": ("z3", ["-version"]), } solver_evidence: list[dict[str, Any]] = [] failures = [*sby_evidence["failures"], *yosys_evidence["failures"]] for solver in sorted(set(str(value).casefold() for value in solvers if str(value).strip())): command, args = solver_args.get(solver, (solver, ["--version"])) executable = resolve_tool(command) if executable is None: evidence = { "name": solver, "path": "", "sha256": "0" * 64, "version": "", "status": "fail", "failures": [f"formal_solver_tool_missing:{solver}"], } else: evidence = formal_tool_version_evidence(solver, executable, args, env, work_root) solver_evidence.append(evidence) failures.extend(evidence["failures"]) return { "status": "pass" if not failures else "fail", "sby": sby_evidence, "yosys": yosys_evidence, "solvers": solver_evidence, "failures": failures, } def formal_property_counts(sby_file: Path) -> dict[str, int | bool]: text = "\n".join( re.sub(r"//.*$", "", source.read_text(encoding="utf-8", errors="replace"), flags=re.MULTILINE) for source in formal_source_files(sby_file) ) sby_text = sby_file.read_text(encoding="utf-8", errors="replace") mode_cover = bool(re.search(r"(?mi)^\s*mode\s+cover\s*$", sby_text)) return { "assertion_count": len(re.findall(r"\bassert\s*\(", text)), "cover_count": len(re.findall(r"\bcover\s*\(", text)), "mode_cover": mode_cover, } def formal_cover_hit_count(stdout: str, stderr: str) -> int: return len(formal_cover_hit_ids(stdout, stderr)) def formal_cover_hit_ids(*texts: str) -> list[str]: """Collect cover statement IDs from SBY / yosys-smtbmc logs. SBY summary lines carry the full compiled cover id but are prefixed with ``SBY ... summary:``; do not require start-of-line. Legacy bare ``Reached cover statement at file:line`` still matches. Engine lines that say ``in step N`` do not match this pattern (they use a different shape and a short parenthetical id). """ hits: set[str] = set() pattern = re.compile( r"(?i)reached cover statement\s+(\S+)\s+at\s+\S+:\d+", ) for text in texts: for hit in pattern.findall(text): # Engine prose ("... statement in step N at ...") must not count. if hit.casefold() == "in": continue hits.add(hit) return sorted(hits) def formal_status_token(status_raw: str) -> str: token = status_raw.strip().split()[0] if status_raw.strip() else "" return token.upper() if token else "MISSING" def formal_workdir_log_texts(workdir: Path) -> list[str]: texts: list[str] = [] logfile = workdir / "logfile.txt" if logfile.is_file(): texts.append(logfile.read_text(encoding="utf-8", errors="replace")) # SBY truncates cover hits in logfile.txt ("and N further traces"); # the PASS marker holds the complete cover-statement summary. pass_marker = workdir / "PASS" if pass_marker.is_file(): texts.append(pass_marker.read_text(encoding="utf-8", errors="replace")) if workdir.is_dir(): for engine_log in sorted(workdir.glob("engine_*/logfile.txt")): texts.append(engine_log.read_text(encoding="utf-8", errors="replace")) return texts def formal_workdir_marker_failures(workdir: Path, status_token: str) -> list[str]: failures: list[str] = [] if not workdir.is_dir(): return failures has_fail = (workdir / "FAIL").is_file() has_pass = (workdir / "PASS").is_file() if has_fail and has_pass: failures.append("formal_workdir_marker_conflict:fail_and_pass") if has_fail and status_token == "PASS": failures.append("formal_workdir_marker_conflict:fail_marker_with_pass_status") if status_token == "PASS" and not has_pass: failures.append("formal_workdir_marker_missing:pass_status_without_pass_marker") if status_token.startswith("FAIL") and not has_fail: failures.append("formal_workdir_marker_missing:fail_status_without_fail_marker") return failures def formal_task_modes(sby_file: Path, tasks: Sequence[str]) -> dict[str, str]: task_modes: dict[str, str] = {} global_mode = "" in_options = False for raw_line in sby_file.read_text(encoding="utf-8", errors="replace").splitlines(): line = raw_line.strip() if line == "[options]": in_options = True continue if in_options and line.startswith("["): break if not in_options or not line or line.startswith("#"): continue match = re.fullmatch(r"(?:(\S+)\s*:\s*)?mode\s+(\S+)", line, flags=re.IGNORECASE) if match is None: continue task_name, mode = match.groups() if task_name is None: global_mode = mode.casefold() else: task_modes[task_name] = mode.casefold() names = list(tasks) or ["default"] return { name: task_modes.get(name, global_mode or ("cover" if name == "cover" else "")) for name in names } def formal_task_evidence( *, name: str, mode: str, workdir: Path, configured_engines: Sequence[str], returncode: int | None = None, timed_out: bool = False, ) -> dict[str, Any]: status_path = workdir / "status" status_raw = "" if status_path.is_file(): status_raw = status_path.read_text(encoding="utf-8", errors="replace").strip() status = formal_status_token(status_raw) trace_files = sorted(str(path) for path in workdir.rglob("*.vcd")) if workdir.is_dir() else [] cover_hit_ids = formal_cover_hit_ids(*formal_workdir_log_texts(workdir)) runtime_evidence = formal_runtime_evidence(workdir, configured_engines) compiled_properties = formal_compiled_property_counts(workdir) evidence_failures: list[str] = [ *runtime_evidence["failures"], *compiled_properties["failures"], *formal_workdir_marker_failures(workdir, status), ] if timed_out: evidence_failures.append(f"formal_task_timeout:{name}") if returncode not in (None, 0): evidence_failures.append(f"formal_task_returncode_nonzero:{name}:{returncode}") if status == "MISSING": evidence_failures.append(f"formal_task_status_missing:{name}") elif status != "PASS": evidence_failures.append(f"formal_task_status_not_pass:{name}:{status}") if mode in {"prove", "bmc"} and compiled_properties["assertion_count"] <= 0: evidence_failures.append(f"formal_compiled_assertions_missing:{name}") if mode == "cover" and compiled_properties["cover_count"] <= 0: evidence_failures.append(f"formal_compiled_covers_missing:{name}") if mode == "cover": if not trace_files: evidence_failures.append(f"formal_cover_trace_missing:{name}") compiled_cover_count = int(compiled_properties["cover_count"]) if len(cover_hit_ids) < compiled_cover_count: evidence_failures.append( f"formal_cover_hits_incomplete:{name}:{len(cover_hit_ids)}/{compiled_cover_count}" ) if set(cover_hit_ids) != set(compiled_properties["cover_ids"]): evidence_failures.append(f"formal_cover_hit_set_mismatch:{name}") return { "name": name, "mode": mode, "status": status, "status_raw": status_raw, "status_file": str(status_path), "workdir": str(workdir), "trace_files": trace_files, "cover_hit_ids": cover_hit_ids, "returncode": returncode, "timed_out": timed_out, "configured_engines": runtime_evidence["configured_engines"], "observed_engines": runtime_evidence["observed_engines"], "solvers": runtime_evidence["solvers"], "compiled_design_json": compiled_properties["design_json"], "compiled_design_sha256": compiled_properties["design_sha256"], "compiled_assertion_count": compiled_properties["assertion_count"], "compiled_assertion_ids": compiled_properties["assertion_ids"], "compiled_cover_count": compiled_properties["cover_count"], "compiled_cover_ids": compiled_properties["cover_ids"], "evidence_failures": evidence_failures, } def formal_target_status_from_tasks( *, task_process_results: Sequence[Mapping[str, Any]], task_results: Sequence[Mapping[str, Any]], ) -> tuple[str, int | None]: if any(item.get("status") == "fail_timeout" for item in task_process_results): return "fail_timeout", None if any(item.get("status") != "pass" for item in task_process_results): result_status = "fail" else: result_status = "pass" evidence_failures = [ failure for task_result in task_results for failure in task_result.get("evidence_failures", []) ] if result_status != "fail_timeout" and evidence_failures: result_status = "fail_evidence" nonzero_returncodes = [ item["returncode"] for item in task_process_results if item.get("returncode") not in (None, 0) ] returncode: int | None = ( int(nonzero_returncodes[0]) if nonzero_returncodes else (None if result_status == "fail_timeout" else 0) ) return result_status, returncode def formal_top_status_from_targets(targets: Sequence[Mapping[str, Any]]) -> bool: return bool(targets) and all(item.get("status") == "pass" for item in targets) def _missing_tools(schema: str, layer: str, missing: Sequence[str], **extra: Any) -> dict[str, Any]: return { "schema": schema, "status": "blocked_missing_tool", "verification_layer": layer, "profile": PROFILE, "missing_tools": sorted(set(missing)), "safety": dict(SAFETY_BOUNDARY), **extra, } def _run_icarus( work_root: Path, *, verification_run_id: str | None = None, ) -> dict[str, Any]: iverilog = resolve_tool("iverilog") vvp = resolve_tool("vvp") missing = [name for name, value in (("iverilog", iverilog), ("vvp", vvp)) if not value] targets = hdl_testbenches() target_manifest = target_manifest_evidence("icarus", [target["name"] for target in targets]) if missing: return _missing_tools( HDL_RECEIPT_SCHEMA, "hdl_sim", missing, backend="icarus", tests=targets, target_manifest=target_manifest, ) run_dir = work_root / "hdl" / "icarus" run_dir.mkdir(parents=True, exist_ok=True) results: list[dict[str, Any]] = [] for target in targets: output = run_dir / f"{target['name']}.vvp" compile_command = [ str(iverilog), "-g2005-sv", "-I", str(ROOT), "-s", str(target["name"]), "-o", str(output), *[str(ROOT / source) for source in target["sources"]], ] compile_result = _run_bounded( compile_command, timeout_name="icarus_compile", cwd=run_dir, env=tool_env(), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False, ) run_result: subprocess.CompletedProcess[str] | None = None if compile_result.returncode == 0 and not _was_timed_out(compile_result): run_result = _run_bounded( [str(vvp), str(output)], timeout_name="icarus_run", cwd=run_dir, env=tool_env(), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False, ) timed_out = _was_timed_out(compile_result) or _was_timed_out(run_result) passed = not timed_out and compile_result.returncode == 0 and run_result is not None and run_result.returncode == 0 results.append( { "name": target["name"], "status": "pass" if passed else ("fail_timeout" if timed_out else "fail"), "timed_out": timed_out, "compile_returncode": compile_result.returncode, "run_returncode": None if run_result is None else run_result.returncode, "compile_stdout_tail": _tail(compile_result.stdout, 2000), "compile_stderr_tail": _tail(compile_result.stderr, 2000), "run_stdout_tail": "" if run_result is None else _tail(run_result.stdout, 2000), "run_stderr_tail": "" if run_result is None else _tail(run_result.stderr, 2000), } ) passed = ( bool(results) and all(item["status"] == "pass" for item in results) and target_manifest["status"] == "pass" ) result = { "schema": HDL_RECEIPT_SCHEMA, "status": "pass" if passed else "fail", "verification_layer": "hdl_sim", "profile": PROFILE, "backend": "icarus", "work_root": str(work_root), "tests": results, "target_manifest": target_manifest, "safety": dict(SAFETY_BOUNDARY), } result["command"] = " ".join(str(c) for c in compile_command) if run_result is not None: result["command"] += f"; {' '.join(str(c) for c in [str(vvp), str(output)])}" result["tool_version"] = f"iverilog={iverilog}; vvp={vvp}" result.update(source_binding_fields(source_state(), verification_run_id=verification_run_id)) return result def _write_verilator_stubs(work_root: Path) -> Path: path = work_root / "hdl" / "verilator" / "prod2u_p4_guard_stubs.v" path.parent.mkdir(parents=True, exist_ok=True) path.write_text( "/* verilator lint_off DECLFILENAME */\n" "module prod2u_p4_solenoid_polarity_must_be_confirmed(); endmodule\n" "/* verilator lint_on DECLFILENAME */\n", encoding="ascii", newline="\n", ) return path def verilator_warning_lines(stdout: str, stderr: str) -> list[str]: return [ line.strip() for line in f"{stdout}\n{stderr}".splitlines() if re.match(r"^\s*%Warning(?:-[A-Z0-9_]+)?:", line) ] def _run_verilator( work_root: Path, *, verification_run_id: str | None = None, ) -> dict[str, Any]: from verilator_perl_preflight import run_verilator_perl_preflight preflight = run_verilator_perl_preflight(env=tool_env()) verilator = resolve_tool("verilator") target_names = list(load_target_manifest()["layers"]["verilator"]) target_name = target_names[0] target_manifest = target_manifest_evidence("verilator", target_names) if preflight["status"] != "pass": return { "schema": HDL_RECEIPT_SCHEMA, "status": "fail", "verification_layer": "hdl_sim", "profile": PROFILE, "backend": "verilator", "work_root": str(work_root), "tests": [ { "name": target_name, "status": "fail", "timed_out": False, "returncode": 2, "unwaived_warning_count": 0, "unwaived_warnings": [], "waiver_file": str(ROOT / "tests" / "verilator_waivers.vlt"), "stdout_tail": "", "stderr_tail": ";".join(preflight.get("failures") or []), } ], "command": "perl -MFindBin -MEncode -e 1; verilator --version", "tool_version": preflight.get("verilator_version") or "verilator=missing", "target_manifest": target_manifest, "perl_preflight": preflight, "failures": list(preflight.get("failures") or []), } if not verilator: return _missing_tools( HDL_RECEIPT_SCHEMA, "hdl_sim", ["verilator"], backend="verilator", tests=[{"name": target_name}], target_manifest=target_manifest, ) run_dir = work_root / "hdl" / "verilator" run_dir.mkdir(parents=True, exist_ok=True) stubs = _write_verilator_stubs(work_root) command = [ verilator, "--lint-only", "--timing", "-Wall", "-Wno-WIDTHTRUNC", "-Wno-WIDTHEXPAND", "-Wno-UNUSEDSIGNAL", f"-I{ROOT}", "--top-module", TOP_MODULE, str(ROOT / "tests" / "verilator_waivers.vlt"), *[str(ROOT / source) for source in active_rtl_sources()], str(stubs), ] completed = _run_bounded( command, timeout_name="verilator", cwd=run_dir, env=tool_env(), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False, ) timed_out = _was_timed_out(completed) warning_lines = verilator_warning_lines(completed.stdout, completed.stderr) if timed_out: result_status = "fail_timeout" elif warning_lines: result_status = "fail_warning" else: result_status = "pass" if completed.returncode == 0 else "fail" result = { "name": target_name, "status": result_status, "timed_out": timed_out, "returncode": completed.returncode, "unwaived_warning_count": len(warning_lines), "unwaived_warnings": warning_lines, "waiver_file": str(ROOT / "tests" / "verilator_waivers.vlt"), "stdout_tail": _tail(completed.stdout), "stderr_tail": _tail(completed.stderr), } receipt = { "schema": HDL_RECEIPT_SCHEMA, "status": "pass" if result["status"] == "pass" and target_manifest["status"] == "pass" else "fail", "verification_layer": "hdl_sim", "profile": PROFILE, "backend": "verilator", "work_root": str(work_root), "tests": [result], "perl_preflight": preflight, "target_manifest": target_manifest, "safety": dict(SAFETY_BOUNDARY), } receipt["command"] = " ".join(str(c) for c in command) receipt["tool_version"] = f"verilator={verilator}" receipt.update(source_binding_fields(source_state(), verification_run_id=verification_run_id)) return receipt def _run_cocotb( work_root: Path, *, verification_run_id: str | None = None, ) -> dict[str, Any]: python_exe = cocotb_python(work_root) probe_ok = python_has_cocotb(python_exe, work_root) missing: list[str] = [] if not probe_ok: missing.append("python_module:cocotb") for name in ("iverilog", "vvp"): if not resolve_tool(name): missing.append(name) targets = cocotb_tests() target_manifest = target_manifest_evidence("cocotb", [target["name"] for target in targets]) if missing: return _missing_tools( HDL_RECEIPT_SCHEMA, "hdl_sim", missing, backend="cocotb", tests=targets, target_manifest=target_manifest, ) results: list[dict[str, Any]] = [] for target in targets: target_root = work_root / "hdl" / "cocotb" / target["name"] target_root.mkdir(parents=True, exist_ok=True) cocotb_env = tool_env( { "TEMP": str(target_root), "TMP": str(target_root), "TMPDIR": str(target_root), "PYTHONPYCACHEPREFIX": str(target_root / "pycache"), } ) # OSS CAD tabbypy3 exports PYTHONEXECUTABLE/PYTHONHOME; those poison # sys.executable inside the VPI-embedded interpreter and break GPI. # Keeping oss-cad-suite/bin on PATH also makes embedded sys.executable # resolve to tabbypy3 even when PYTHONEXECUTABLE is unset — drop it. for poison in ("PYTHONEXECUTABLE", "PYTHONHOME", "PYTHONNOUSERSITE"): cocotb_env.pop(poison, None) # Prefer the selected venv, then a shim that hides OSS CAD python # shims (tabbypy3) while still exposing system iverilog/vvp. python_bin = str(Path(python_exe).expanduser().parent) shim_dir = target_root / "path-shim" shim_dir.mkdir(parents=True, exist_ok=True) for shim_name in ("python", "python3", "python3.13", "tabbypy3", "tabby"): shim_path = shim_dir / shim_name if shim_path.exists() or shim_path.is_symlink(): shim_path.unlink() shim_path.symlink_to(Path(python_exe).expanduser()) # Expose iverilog/vvp via private shims — never put oss-cad-suite/bin on PATH # (that resurrects tabbypy3 as the VPI sys.executable). for name in ("iverilog", "vvp"): resolved = resolve_tool(name) if not resolved: for fallback in ( Path("/usr/local/bin") / name, Path("/usr/bin") / name, Path("/data/prod2u/oss-cad-suite/latest/bin") / name, ): if fallback.is_file() and os.access(fallback, os.X_OK): resolved = str(fallback) break if resolved: wrapper = shim_dir / name if wrapper.exists() or wrapper.is_symlink(): wrapper.unlink() wrapper.write_text( "#!/bin/sh\n" f'exec "{resolved}" "$@"\n', encoding="ascii", ) wrapper.chmod(0o755) path_parts: list[str] = [python_bin, str(shim_dir)] for name in ("iverilog", "vvp"): for fallback in (Path("/usr/local/bin") / name, Path("/usr/bin") / name): if fallback.is_file() and os.access(fallback, os.X_OK): parent = str(fallback.parent) if parent not in path_parts: path_parts.append(parent) break for part in cocotb_env.get("PATH", "").split(os.pathsep): if not part or part in path_parts: continue if "oss-cad-suite" in part and part.rstrip("/").endswith("/bin"): continue path_parts.append(part) cocotb_env["PATH"] = os.pathsep.join(path_parts) cocotb_env["VIRTUAL_ENV"] = str(Path(python_bin).parent) cocotb_env["PYGPI_PYTHON_BIN"] = str(Path(python_exe).expanduser()) cocotb_env["PROD2U_P4_COCOTB_PYTHON"] = str(Path(python_exe).expanduser()) if "PROD2U_COCOTB_BUILD_DIR" not in cocotb_env: cocotb_env["PROD2U_COCOTB_BUILD_DIR"] = str(target_root / "cocotb" / target["name"]) completed = _run_bounded( [python_exe, "-B", str(ROOT / target["runner"])], timeout_name="cocotb", cwd=target_root, env=cocotb_env, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False, ) timed_out = _was_timed_out(completed) results.append( { "name": target["name"], "status": "pass" if completed.returncode == 0 else ("fail_timeout" if timed_out else "fail"), "timed_out": timed_out, "returncode": completed.returncode, "stdout_tail": _tail(completed.stdout), "stderr_tail": _tail(completed.stderr), } ) passed = ( bool(results) and all(item["status"] == "pass" for item in results) and target_manifest["status"] == "pass" ) result = { "schema": HDL_RECEIPT_SCHEMA, "status": "pass" if passed else "fail", "verification_layer": "hdl_sim", "profile": PROFILE, "backend": "cocotb", "work_root": str(work_root), "tests": results, "target_manifest": target_manifest, "safety": dict(SAFETY_BOUNDARY), } result["command"] = "; ".join( " ".join(str(c) for c in [str(python_exe), "-B", str(ROOT / t["runner"])]) for t in targets ) result["tool_version"] = f"cocotb (Python {python_exe})" result.update(source_binding_fields(source_state(), verification_run_id=verification_run_id)) return result def python_has_cocotb(python_exe: str | Path, work_root: Path) -> bool: resolved_work_root = resolve_work_root(work_root, run=True) assert resolved_work_root is not None completed = subprocess.run( [str(python_exe), "-B", "-c", "import cocotb"], cwd=resolved_work_root, env=tool_env(), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=20, check=False, ) return completed.returncode == 0 def cocotb_python(work_root: Path) -> str: candidates: list[Path] = [] for key in ("PROD2U_P4_COCOTB_PYTHON", "PRODU2_VERIFY_PYTHON"): configured = os.environ.get(key, "").strip() if configured: candidates.append(Path(configured)) # Prefer LD-safe wrapper over bare libexec sys.executable (see tools/tool_env.py). candidates.append(Path(safe_python())) verify_venv = os.environ.get("PRODU2_VERIFY_VENV", "").strip() if verify_venv: for name in ("python", "python3"): candidates.append(Path(verify_venv).expanduser() / "bin" / name) candidates.append(Path("/data/prod2u/venvs/verify/bin/python")) candidates.append(Path(sys.executable)) if DEFAULT_VENV_ROOT.is_dir(): candidates.extend(sorted(DEFAULT_VENV_ROOT.glob("*/Scripts/python.exe"))) candidates.extend(sorted(DEFAULT_VENV_ROOT.glob("*/bin/python"))) candidates.extend(sorted(DEFAULT_VENV_ROOT.glob("*/bin/python3"))) # Do not Path.resolve() before invoke: venv python is often a symlink to the # system interpreter, and resolving it drops the venv site-packages. seen: set[str] = set() for candidate in candidates: expanded = candidate.expanduser() key = str(expanded) if key in seen: continue seen.add(key) if expanded.is_file() and python_has_cocotb(expanded, work_root): return str(expanded) return safe_python() def hdl_target_manifest_evidence(backend: str) -> dict[str, Any]: inventory = target_inventory() if backend == "all": return target_manifest_evidence("all", inventory) observed = inventory.get(backend, []) return target_manifest_evidence(backend, observed) def _aggregate_hdl_sim_payload( children: Mapping[str, Mapping[str, Any]], *, work_root: Path, verification_run_id: str | None = None, ) -> dict[str, Any]: aggregate_manifest = hdl_target_manifest_evidence("all") passed = ( all(child.get("status") == "pass" for child in children.values()) and aggregate_manifest["status"] == "pass" ) result = { "schema": HDL_RECEIPT_SCHEMA, "status": "pass" if passed else "fail", "verification_layer": "hdl_sim", "profile": PROFILE, "backend": "all", "work_root": str(work_root), "backend_results": dict(children), "tests": [ item for child in children.values() for item in child.get("tests", []) ], "target_manifest": aggregate_manifest, "safety": dict(SAFETY_BOUNDARY), } result.update(source_binding_fields(source_state(), verification_run_id=verification_run_id)) return result def hdl_sim_payload( run: bool, backend: str = "icarus", *, work_root: Path | None = None, verification_run_id: str | None = None, ) -> dict[str, Any]: try: resolved = resolve_work_root(work_root, run=run) except ValueError as exc: result = { "schema": HDL_RECEIPT_SCHEMA, "status": "blocked_invalid_work_root", "verification_layer": "hdl_sim", "profile": PROFILE, "backend": backend, "reason": str(exc), "tests": hdl_testbenches(), "target_manifest": hdl_target_manifest_evidence(backend), "safety": dict(SAFETY_BOUNDARY), } result.update(source_binding_fields(source_state(), verification_run_id=verification_run_id)) return result if not run: if backend == "icarus": tests: list[dict[str, Any]] = hdl_testbenches() elif backend == "verilator": tests = [{"name": "prod2u_p4_normal_v3_top_lint"}] elif backend == "cocotb": tests = list(cocotb_tests()) else: inventory = target_inventory() tests = [ {"name": name} for layer in ("icarus", "verilator", "cocotb") for name in inventory[layer] ] result = { "schema": HDL_RECEIPT_SCHEMA, "status": "skipped", "verification_layer": "hdl_sim", "profile": PROFILE, "backend": backend, "work_root": None if resolved is None else str(resolved), "tests": tests, "target_manifest": hdl_target_manifest_evidence(backend), "safety": dict(SAFETY_BOUNDARY), } result.update(source_binding_fields(source_state(), verification_run_id=verification_run_id)) return result assert resolved is not None if backend == "icarus": return _run_icarus(resolved, verification_run_id=verification_run_id) if backend == "verilator": return _run_verilator(resolved, verification_run_id=verification_run_id) if backend == "cocotb": return _run_cocotb(resolved, verification_run_id=verification_run_id) if backend != "all": result = { "schema": HDL_RECEIPT_SCHEMA, "status": "fail", "verification_layer": "hdl_sim", "profile": PROFILE, "backend": backend, "reason": f"unsupported HDL backend: {backend}", "tests": [], "target_manifest": hdl_target_manifest_evidence(backend), "safety": dict(SAFETY_BOUNDARY), } result.update(source_binding_fields(source_state(), verification_run_id=verification_run_id)) return result children = { name: hdl_sim_payload(run=True, backend=name, work_root=resolved, verification_run_id=verification_run_id) for name in ("icarus", "verilator", "cocotb") } return _aggregate_hdl_sim_payload(children, work_root=resolved, verification_run_id=verification_run_id) def formal_payload( run: bool, *, work_root: Path | None = None, verification_run_id: str | None = None, ) -> dict[str, Any]: targets = formal_targets() target_manifest = target_manifest_evidence( "formal", {target["name"]: list(target.get("tasks", [])) for target in targets}, ) try: resolved = resolve_work_root(work_root, run=run) except ValueError as exc: result = { "schema": FORMAL_RECEIPT_SCHEMA, "status": "blocked_invalid_work_root", "verification_layer": "formal", "profile": PROFILE, "reason": str(exc), "targets": targets, "target_manifest": target_manifest, "safety": dict(SAFETY_BOUNDARY), } result.update(source_binding_fields(source_state(), verification_run_id=verification_run_id)) return result if not run: result = { "schema": FORMAL_RECEIPT_SCHEMA, "status": "skipped", "verification_layer": "formal", "profile": PROFILE, "work_root": None if resolved is None else str(resolved), "targets": targets, "target_manifest": target_manifest, "safety": dict(SAFETY_BOUNDARY), } result.update(source_binding_fields(source_state(), verification_run_id=verification_run_id)) return result sby = resolve_tool("sby") yosys = resolve_tool("yosys") missing = [name for name, value in (("sby", sby), ("yosys", yosys)) if not value] if missing: return _missing_tools( FORMAL_RECEIPT_SCHEMA, "formal", missing, targets=targets, target_manifest=target_manifest, ) assert resolved is not None results: list[dict[str, Any]] = [] formal_commands: list[str] = [] for target in targets: sby_file = ROOT / target["sby"] property_counts = formal_property_counts(sby_file) input_evidence = formal_input_evidence(sby_file, target.get("tasks", [])) workdir = resolved / "formal" / target["name"] tasks = list(target.get("tasks", [])) task_names = tasks or ["default"] task_workdirs = [workdir / task_name for task_name in task_names] task_modes = formal_task_modes(sby_file, tasks) task_timeout = configured_timeout("formal") task_env = formal_tool_env(resolved) def run_task(task_name: str, task_workdir: Path) -> dict[str, Any]: nonlocal formal_commands if task_workdir.exists(): shutil.rmtree(task_workdir) command = [str(sby), "-f", "-d", str(task_workdir), str(sby_file)] if tasks: command.append(task_name) formal_commands.append(" ".join(command)) try: completed = subprocess.run( command, cwd=sby_file.parent, env=task_env, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=task_timeout, check=False, ) return { "status": "pass" if completed.returncode == 0 else "fail", "returncode": completed.returncode, "timed_out": False, "stdout": completed.stdout, "stderr": completed.stderr, } except subprocess.TimeoutExpired as exc: return { "status": "fail_timeout", "returncode": None, "timed_out": True, "stdout": ( exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "") ), "stderr": ( exc.stderr.decode(errors="replace") if isinstance(exc.stderr, bytes) else (exc.stderr or "") ), } with ThreadPoolExecutor( max_workers=min(FORMAL_MAX_WORKERS, len(task_names)) ) as executor: task_futures = [ executor.submit(run_task, task_name, task_workdir) for task_name, task_workdir in zip( task_names, task_workdirs, strict=True ) ] task_process_results = [future.result() for future in task_futures] task_results = [ formal_task_evidence( name=task_name, mode=task_modes[task_name], workdir=task_workdir, configured_engines=input_evidence["task_engines"].get(task_name, []), returncode=process_result["returncode"], timed_out=bool(process_result.get("timed_out")), ) for (task_name, task_workdir), process_result in zip( zip(task_names, task_workdirs, strict=True), task_process_results, strict=True, ) ] result_status, returncode = formal_target_status_from_tasks( task_process_results=task_process_results, task_results=task_results, ) stdout = "\n".join( f"[{task_name}]\n{item['stdout']}".rstrip() for task_name, item in zip(task_names, task_process_results, strict=True) if item["stdout"] ) stderr = "\n".join( f"[{task_name}]\n{item['stderr']}".rstrip() for task_name, item in zip(task_names, task_process_results, strict=True) if item["stderr"] ) trace_files = sorted( { trace_file for task_result in task_results for trace_file in task_result["trace_files"] } ) cover_tasks = [result for result in task_results if result["mode"] == "cover"] cover_required = bool(cover_tasks) cover_hit_ids = sorted( { hit_id for task_result in cover_tasks for hit_id in task_result["cover_hit_ids"] } ) cover_hit_count = len(cover_hit_ids) evidence_failures: list[str] = [] for task_result in task_results: evidence_failures.extend(task_result["evidence_failures"]) if int(property_counts["assertion_count"]) <= 0: evidence_failures.append("formal_assertions_missing") if cover_required and int(property_counts["cover_count"]) <= 0: evidence_failures.append("formal_cover_properties_missing") if result_status == "pass" and evidence_failures: result_status = "fail_evidence" results.append( { "name": target["name"], "status": result_status, "returncode": returncode, "tasks": tasks, "workdirs": [str(path) for path in task_workdirs], "trace_files": trace_files, "counterexamples": [] if result_status == "pass" else trace_files, "assertion_count": property_counts["assertion_count"], "cover_count": property_counts["cover_count"], "cover_required": cover_required, "cover_hit_count": cover_hit_count, "cover_hit_ids": cover_hit_ids, "input_evidence": input_evidence, "task_results": task_results, "evidence_failures": evidence_failures, "stdout_tail": _tail(stdout), "stderr_tail": _tail(stderr), } ) observed_solvers = sorted( { solver for result in results for task_result in result.get("task_results", []) for solver in task_result.get("solvers", []) } ) toolchain = formal_toolchain_evidence(sby, yosys, observed_solvers, resolved) passed = ( formal_top_status_from_targets(results) and target_manifest["status"] == "pass" and toolchain["status"] == "pass" ) harness_path = Path(__file__) result = { "schema": FORMAL_RECEIPT_SCHEMA, "status": "pass" if passed else "fail", "verification_layer": "formal", "profile": PROFILE, "work_root": str(resolved), "runner_source_sha256": sha256_file(harness_path), "formal_manifest_sha256": sha256_file(TARGET_MANIFEST_PATH), "targets": results, "toolchain": toolchain, "target_manifest": target_manifest, "safety": dict(SAFETY_BOUNDARY), } result["command"] = "; ".join(formal_commands) result["tool_version"] = f"sby={toolchain['sby']['version']}; yosys={toolchain['yosys']['version']}" result.update(source_binding_fields(source_state(), verification_run_id=verification_run_id)) return result def unit_test_modules() -> list[str]: return list(load_target_manifest()["layers"]["unit"]) def target_inventory() -> dict[str, Any]: return { "unit": list(unit_test_modules()), "icarus": [target["name"] for target in hdl_testbenches()], "verilator": list(load_target_manifest()["layers"]["verilator"]), "cocotb": [target["name"] for target in cocotb_tests()], "formal": { target["name"]: list(target.get("tasks", [])) for target in formal_targets() }, } def unit_payload( work_root: Path, *, verification_run_id: str | None = None, ) -> dict[str, Any]: modules = unit_test_modules() target_manifest = target_manifest_evidence("unit", modules) command = [ sys.executable, "-B", "-m", "pytest", "-q", "-p", "no:cacheprovider", "tests/unit", "tests/test_project_structure.py", ] completed = subprocess.run( command, cwd=ROOT, env=tool_env({"PYTHONPYCACHEPREFIX": str(work_root / "python-cache")}), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=1800, check=False, ) passed = completed.returncode == 0 and target_manifest["status"] == "pass" result = { "status": "pass" if passed else "fail", "returncode": completed.returncode, "modules": modules, "target_manifest": target_manifest, "stdout_tail": _tail(completed.stdout, 12000), "stderr_tail": _tail(completed.stderr, 12000), } result["command"] = " ".join(str(c) for c in command) result["tool_version"] = f"Python {sys.version.split()[0]}" result.update(source_binding_fields(source_state(), verification_run_id=verification_run_id)) return result def source_integrity_payload() -> dict[str, Any]: completed = _git("diff", "--check", "HEAD") state = source_state() passed = ( completed.returncode == 0 and state["status"] == "pass" and state.get("clean") is True ) return { "status": "pass" if passed else "fail", "returncode": completed.returncode, "stdout_tail": _tail(completed.stdout), "stderr_tail": _tail(completed.stderr), "source_state": state, "command": "git diff --check HEAD", "tool_version": "git", } def _offline_runner_exception_payload( name: str, *, work_root: Path, exception: Exception, ) -> dict[str, Any]: reason = f"{type(exception).__name__}: {exception}" if name in {"icarus", "verilator", "cocotb"}: return { "schema": HDL_RECEIPT_SCHEMA, "status": "fail", "verification_layer": "hdl_sim", "profile": PROFILE, "backend": name, "work_root": str(work_root), "reason": reason, "tests": [], "target_manifest": hdl_target_manifest_evidence(name), "safety": dict(SAFETY_BOUNDARY), } if name == "formal": return { "schema": FORMAL_RECEIPT_SCHEMA, "status": "fail", "verification_layer": "formal", "profile": PROFILE, "work_root": str(work_root), "reason": reason, "targets": [], "target_manifest": target_manifest_evidence( "formal", { target["name"]: list(target.get("tasks", [])) for target in formal_targets() }, ), "safety": dict(SAFETY_BOUNDARY), } return { "status": "fail", "work_root": str(work_root), "reason": reason, } def strict_offline_gate_payload( *, work_root: Path, verification_run_id: str | None = None, ) -> dict[str, Any]: state = source_state() run_id = normalize_verification_run_id(verification_run_id) try: resolved = resolve_work_root(work_root, run=True) except ValueError as exc: return { "schema": OFFLINE_RECEIPT_SCHEMA, "status": "fail", "verification_run_id": run_id, **source_binding_fields(state), "source_state": state, "required_layers": ["source_integrity", "unit", "hdl_sim", "formal"], "layers": {}, "failures": [f"work_root_invalid:{exc}"], "safety": dict(SAFETY_BOUNDARY), } assert resolved is not None source_integrity = source_integrity_payload() runner_roots = { name: resolved / name for name in ("unit", "icarus", "verilator", "cocotb", "formal") } runners = { "unit": lambda: unit_payload( runner_roots["unit"], verification_run_id=verification_run_id, ), "icarus": lambda: hdl_sim_payload( run=True, backend="icarus", work_root=runner_roots["icarus"], verification_run_id=verification_run_id, ), "verilator": lambda: hdl_sim_payload( run=True, backend="verilator", work_root=runner_roots["verilator"], verification_run_id=verification_run_id, ), "cocotb": lambda: hdl_sim_payload( run=True, backend="cocotb", work_root=runner_roots["cocotb"], verification_run_id=verification_run_id, ), "formal": lambda: formal_payload( run=True, work_root=runner_roots["formal"], verification_run_id=verification_run_id, ), } runner_results: dict[str, dict[str, Any]] = {} with ThreadPoolExecutor(max_workers=5) as executor: futures = { name: executor.submit(runner) for name, runner in runners.items() } for name, future in futures.items(): try: runner_results[name] = future.result() except Exception as exc: runner_results[name] = _offline_runner_exception_payload( name, work_root=runner_roots[name], exception=exc, ) hdl_children = { name: runner_results[name] for name in ("icarus", "verilator", "cocotb") } layers = { "source_integrity": source_integrity, "unit": runner_results["unit"], "hdl_sim": _aggregate_hdl_sim_payload( hdl_children, work_root=resolved, verification_run_id=verification_run_id, ), "formal": runner_results["formal"], } required = list(layers) failures = [ f"required_layer_not_pass:{name}:{layers[name].get('status', 'missing')}" for name in required if layers[name].get("status") != "pass" ] receipt_dir = resolved / "receipts" receipt_dir.mkdir(parents=True, exist_ok=True) for name, layer in layers.items(): write_json_report(layer, receipt_dir / f"{name}.json") return { "schema": OFFLINE_RECEIPT_SCHEMA, "generated_at": utc_now(), "status": "pass" if not failures else "fail", "verification_run_id": run_id, **source_binding_fields(state), "source_state": state, "profile": PROFILE, "runtime_profile": RUNTIME_PROFILE, "required_layers": required, "layers": layers, "failures": failures, "work_root": str(resolved), "child_receipt_dir": str(receipt_dir), "safety": dict(SAFETY_BOUNDARY), "authority_boundary": "This receipt covers offline source, software, HDL and formal checks only. It does not access serial, JTAG, or a board.", } class StagedBuild: def __init__( self, root: Path, syn: Path, phy: Path, bitgen: Path, clean: Mapping[str, Any], source_state: Mapping[str, Any], source_manifest: Mapping[str, Any], synthesis_input_manifest: Mapping[str, Any], ) -> None: self.root = root self.syn = syn self.phy = phy self.bitgen = bitgen self.clean = clean self.source_state = source_state self.source_manifest = source_manifest self.synthesis_input_manifest = synthesis_input_manifest def _safe_build_root(work_root: Path) -> Path: resolved = resolve_work_root(work_root, run=True) assert resolved is not None target = (resolved / BUILD_ROOT_RELATIVE).resolve() if resolved != target and resolved not in target.parents: raise ValueError("TD build root escaped the external work root") return target def clean_td_outputs(work_root: Path) -> dict[str, Any]: target = _safe_build_root(work_root) deleted: list[str] = [] if target.exists(): deleted.append(str(target)) shutil.rmtree(target) return {"status": "pass", "deleted": deleted, "target": str(target)} def _copy_active_sources(target: Path) -> None: for relative in active_rtl_sources(): source = ROOT / relative destination = target / relative destination.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(source, destination) for relative in ( "constraints/prod2u_p4_normal_v3.adc", "constraints/prod2u_p4_normal_v3.sdc", "td/prod2u_p4_normal_v3.prj", PROJECT_CONFIG_RELATIVE_PATH, TD_SOURCE_MANIFEST_RELATIVE_PATH, ): source = ROOT / relative destination = target / relative destination.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(source, destination) def prepare_td_build_dirs(*, work_root: Path) -> StagedBuild: build_root = _safe_build_root(work_root) clean = clean_td_outputs(work_root) state = source_state() if state.get("status") != "pass" or state.get("clean") is not True: raise RuntimeError("TD build requires a clean committed source state") synthesis_input_manifest = build_synthesis_input_manifest(ROOT) syn = build_root / "syn" phy = build_root / "phy" bitgen = build_root / "bitgen" for directory in (syn, phy, bitgen): directory.mkdir(parents=True, exist_ok=True) _copy_active_sources(directory) for directory in (syn, phy, bitgen): write_json_report(state, directory / "source-state.json") staged_dirs = {"syn": syn, "phy": phy, "bitgen": bitgen} for phase, source in TD_SCRIPTS.items(): shutil.copy2(source, staged_dirs[phase] / source.name) phases: dict[str, Any] = {} for phase, directory in staged_dirs.items(): files = { path.relative_to(directory).as_posix(): sha256_file(path) for path in sorted(directory.rglob("*")) if path.is_file() } phases[phase] = {"files": files, "manifest_sha256": canonical_sha256(files)} source_manifest = { "schema": "prod2u-p4-normal-v3-staged-source-manifest-v1", "status": "pass", "commit": state["commit"], "commit_full": state["commit_full"], "commit_short": state["commit_short"], "project_config_sha256": state["project_config_sha256"], "td_source_manifest_sha256": state["td_source_manifest_sha256"], "source_state_clean": state["clean"], "phases": phases, "failures": [], } return StagedBuild( build_root, syn, phy, bitgen, clean, state, source_manifest, synthesis_input_manifest, ) def _staged_synthesis_input_manifest(staged: StagedBuild) -> dict[str, Any]: expected_inputs = staged.synthesis_input_manifest.get("inputs") if not isinstance(expected_inputs, Mapping) or not expected_inputs: raise ValueError("expected synthesis input manifest is missing") observed: dict[str, str | None] = {} for relative in expected_inputs: relative_text = str(relative) if relative_text.startswith("td/syn/"): path = staged.syn / Path(relative_text).name elif relative_text.startswith("td/phy/"): path = staged.phy / Path(relative_text).name elif relative_text.startswith("td/bitgen/"): path = staged.bitgen / Path(relative_text).name else: path = staged.syn / relative_text observed[relative_text] = sha256_file(path) if path.is_file() else None manifest_binding = { "inputs": observed, "project_config_path": staged.synthesis_input_manifest.get("project_config_path"), "project_config_sha256": observed.get(PROJECT_CONFIG_RELATIVE_PATH), "td_source_manifest_path": staged.synthesis_input_manifest.get("td_source_manifest_path"), "td_source_manifest_sha256": observed.get(TD_SOURCE_MANIFEST_RELATIVE_PATH), } return { "schema": staged.synthesis_input_manifest.get("schema"), "inputs": observed, "project_config_path": manifest_binding["project_config_path"], "project_config_sha256": manifest_binding["project_config_sha256"], "td_source_manifest_path": manifest_binding["td_source_manifest_path"], "td_source_manifest_sha256": manifest_binding["td_source_manifest_sha256"], "sha256": canonical_sha256(manifest_binding), } def verify_staged_source_manifest(staged: StagedBuild) -> dict[str, Any]: failures: list[str] = [] verified_phases: dict[str, Any] = {} for phase in ("syn", "phy", "bitgen"): directory = getattr(staged, phase) expected_phase = staged.source_manifest.get("phases", {}).get(phase, {}) expected_files = expected_phase.get("files") if isinstance(expected_phase, Mapping) else None if not isinstance(expected_files, Mapping) or not expected_files: failures.append(f"manifest_missing:{phase}") continue observed: dict[str, str | None] = {} for relative, expected_digest in expected_files.items(): path = directory / str(relative) digest = sha256_file(path) if path.is_file() else None observed[str(relative)] = digest if digest != expected_digest: failures.append(f"staged_input_mismatch:{phase}:{relative}") observed_digest = canonical_sha256(observed) expected_digest = expected_phase.get("manifest_sha256") if observed_digest != expected_digest: failures.append(f"phase_manifest_mismatch:{phase}") verified_phases[phase] = { "files": dict(expected_files), "manifest_sha256": expected_digest, "observed_manifest_sha256": observed_digest, } expected_synthesis_inputs = staged.synthesis_input_manifest.get("inputs") synthesis_phase_bindings: dict[str, dict[str, str | None]] = {} if not isinstance(expected_synthesis_inputs, Mapping): failures.append("expected_synthesis_inputs_missing") else: for relative, expected_digest in expected_synthesis_inputs.items(): relative_text = str(relative) if relative_text.startswith("td/syn/"): phase_paths = {"syn": staged.syn / Path(relative_text).name} elif relative_text.startswith("td/phy/"): phase_paths = {"phy": staged.phy / Path(relative_text).name} elif relative_text.startswith("td/bitgen/"): phase_paths = {"bitgen": staged.bitgen / Path(relative_text).name} else: phase_paths = { phase: getattr(staged, phase) / relative_text for phase in ("syn", "phy", "bitgen") } observed_by_phase = { phase: sha256_file(path) if path.is_file() else None for phase, path in phase_paths.items() } synthesis_phase_bindings[relative_text] = observed_by_phase for phase, observed_digest in observed_by_phase.items(): if observed_digest != expected_digest: failures.append(f"staged_synthesis_input_mismatch:{phase}:{relative_text}") observed_synthesis = _staged_synthesis_input_manifest(staged) expected_synthesis = staged.synthesis_input_manifest if observed_synthesis.get("inputs") != expected_synthesis.get("inputs"): failures.append("staged_synthesis_inputs_mismatch") if observed_synthesis.get("sha256") != expected_synthesis.get("sha256"): failures.append("staged_synthesis_hash_mismatch") return { "schema": "prod2u-p4-normal-v3-staged-source-manifest-v1", "status": "pass" if not failures else "fail", "commit": staged.source_manifest.get("commit"), "commit_full": staged.source_manifest.get("commit_full"), "commit_short": staged.source_manifest.get("commit_short"), "project_config_sha256": staged.source_manifest.get("project_config_sha256"), "td_source_manifest_sha256": staged.source_manifest.get("td_source_manifest_sha256"), "source_state_clean": staged.source_manifest.get("source_state_clean"), "phases": verified_phases, "synthesis_input_manifest": observed_synthesis, "synthesis_phase_bindings": synthesis_phase_bindings, "expected_synthesis_input_hash": expected_synthesis.get("sha256"), "observed_synthesis_input_hash": observed_synthesis.get("sha256"), "failures": sorted(set(failures)), } def td_process_env( run_dir: Path, extra: Mapping[str, str] | None = None, ) -> dict[str, str]: """Environment for TD subprocess only (do not export into the Agent shell).""" temp_dir = run_dir / "td-user" / "temp" temp_dir.mkdir(parents=True, exist_ok=True) env = tool_env() # Prefer Linux TMPDIR; keep TEMP/TMP for legacy Windows TD scripts. env["TMPDIR"] = str(temp_dir) env["TEMP"] = str(temp_dir) env["TMP"] = str(temp_dir) td_home = Path(os.environ.get("ANLOGIC_TD_HOME", "/data/anlogic/TD_Release_2026.1_SP2_NL")) lib_candidates = [ td_home / "lib", td_home / "lib" / "Qt" / "lib", td_home / "bin", Path("/data/anlogic/BW_Release_2026.1_SP2/lib"), Path("/data/anlogic/BW_Release_2026.1_SP2/lib/Qt/lib"), ] ld_parts = [str(p) for p in lib_candidates if p.is_dir()] existing_ld = env.get("LD_LIBRARY_PATH", "") if existing_ld: ld_parts.append(existing_ld) if ld_parts: env["LD_LIBRARY_PATH"] = os.pathsep.join(dict.fromkeys(ld_parts)) # Confine Qt plugin discovery to the TD tree (matches /usr/local/bin/td2026). qt_plugins = td_home / "lib" / "Qt" / "plugins" if qt_plugins.is_dir(): env["QT_PLUGIN_PATH"] = str(qt_plugins) env.setdefault("QT_QPA_PLATFORM", "offscreen") env["ANLOGIC_TD_HOME"] = str(td_home) env["ANLOGIC_TD2026_HOME"] = str(td_home) if extra: env.update({str(key): str(value) for key, value in extra.items()}) return env def probe_td_tool() -> dict[str, Any]: """Probe TD wrapper + real binary path/hash/version for receipts.""" wrapper = TD_EXE.resolve() td_home = Path(os.environ.get("ANLOGIC_TD_HOME", "/data/anlogic/TD_Release_2026.1_SP2_NL")) real_bin = (td_home / "bin" / "td").resolve() version_text = "" version = "unknown" try: completed = subprocess.run( [str(TD_EXE), "-version"], timeout=30, text=True, encoding="utf-8", errors="replace", stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False, env=td_process_env(Path(os.environ.get("TMPDIR", "/tmp"))), ) version_text = ((completed.stdout or "") + "\n" + (completed.stderr or "")).strip() match = re.search(r"Build:\s*([0-9.]+)", version_text) if match: version = match.group(1) elif "Release_" in version_text: version = version_text.splitlines()[0].strip() except (OSError, subprocess.SubprocessError) as exc: version_text = f"probe_failed:{type(exc).__name__}" return { "path": str(wrapper), "executable": wrapper.name, "version": version, "sha256": sha256_file(wrapper) if wrapper.is_file() else None, "real_binary_path": str(real_bin) if real_bin.is_file() else None, "real_binary_sha256": sha256_file(real_bin) if real_bin.is_file() else None, "version_text": version_text, "release": "Release_2026.1_SP2", } def run_td_script( run_dir: Path, script_name: str, *, extra_env: Mapping[str, str] | None = None, ) -> subprocess.CompletedProcess[str]: return _run_bounded( [str(TD_EXE), script_name], timeout_name="td", cwd=run_dir, env=td_process_env(run_dir, extra_env), text=True, encoding="utf-8", errors="replace", stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False, ) def td_forbidden_script_markers(script_text: str) -> list[str]: markers: set[str] = set() for raw_line in script_text.splitlines(): line = raw_line.strip().casefold() if not line or line.startswith("#"): continue command = re.split(r"\s+", line, maxsplit=1)[0] if command == "source": markers.add("source") for forbidden in FORBIDDEN_TD_COMMANDS: if re.search(rf"(? bool: text = "\n".join(chunks) return bool( re.search( r"(?i)(?:\bPROD2U_P4_NORMAL_V3_CDC_GATE_FAIL\b|\bCDC_GATE_(?:FAIL|FAILED)\b|\bCDC_GATE_STATUS\s*=\s*(?:FAIL|FAILED)\b)", text, ) ) def td_log_has_error(*chunks: str) -> bool: text = "\n".join(chunks) return bool( td_log_has_cdc_gate_failure(*chunks) or re.search( r"(^|\n)\s*(?:[A-Z]+-\d+\s+)?(?:error|fatal)\s*[:|]", text, re.IGNORECASE, ) ) def td_critical_warning_count(*chunks: str) -> int: return len(re.findall(r"critical[-\s]+warning", "\n".join(chunks), re.IGNORECASE)) def parse_qor_attribute_count(path: Path, attribute: str) -> int | None: if not re.fullmatch(r"[a-z][a-z0-9_]*", attribute): return None candidates = [path] if path.is_file() else [] if path.name.endswith("_gate.qor"): candidates.append(path.with_name("gate.qor")) for candidate in candidates: if not candidate.is_file(): continue text = candidate.read_text(encoding="utf-8", errors="replace") match = re.search( rf"^\|\s*#{re.escape(attribute)}\s*\|\s*(\d+)\s*\|\s*$", text, re.MULTILINE, ) if match: return int(match.group(1)) return None def parse_td_cdc_report(path: Path) -> dict[str, Any] | None: if not path.is_file(): return None rows: dict[str, list[str]] = { "schema": [], "retained_sync_register": [], "false_path_endpoint": [], "false_path_source": [], "structural_failure": [], } for raw_line in path.read_text(encoding="utf-8", errors="replace").splitlines(): line = raw_line.strip() if not line: continue if "=" not in line: return None key, value = line.split("=", 1) if key not in rows or not value: return None rows[key].append(value) if rows["schema"] != [CDC_REPORT_SCHEMA]: return None registers = rows["retained_sync_register"] endpoints = rows["false_path_endpoint"] sources = rows["false_path_source"] failures = rows["structural_failure"] if ( len(registers) != len(set(registers)) or len(endpoints) != len(set(endpoints)) or len(sources) != len(set(sources)) ): return None return { "schema": CDC_REPORT_SCHEMA, "retained_sync_registers": registers, "false_path_endpoints": endpoints, "source_only_false_paths": sources, "structural_failures": failures, } def parse_td_fsm_report(path: Path) -> dict[str, Any] | None: if not path.is_file(): return None schema: str | None = None axes: dict[str, int] = {} encodings: dict[str, str] = {} failures: list[str] = [] for raw_line in path.read_text(encoding="utf-8", errors="replace").splitlines(): line = raw_line.strip() if not line or "=" not in line: return None key, value = line.split("=", 1) if key == "schema": if schema is not None or value != FSM_REPORT_SCHEMA: return None schema = value continue if key == "structural_failure": failures.append(value) continue if key != "motion_phase": return None match = re.fullmatch(r"([xy]):(\d+):([a-z][a-z0-9_]*)", value) if match is None or match.group(1) in axes: return None axis = match.group(1) axes[axis] = int(match.group(2)) encodings[axis] = match.group(3) if schema != FSM_REPORT_SCHEMA: return None return { "schema": schema, "axes": axes, "encodings": encodings, "structural_failures": failures, } def structural_cdc_gate( report: Mapping[str, Any] | None, *, async_reg_count: int | None, input_register_count: int | None, ) -> dict[str, Any]: failures: list[str] = [] registers = report.get("retained_sync_registers") if isinstance(report, Mapping) else None endpoints = report.get("false_path_endpoints") if isinstance(report, Mapping) else None source_only = report.get("source_only_false_paths") if isinstance(report, Mapping) else None reported = report.get("structural_failures") if isinstance(report, Mapping) else None register_set = set(registers) if isinstance(registers, list) and all(isinstance(item, str) for item in registers) else set() endpoint_set = set(endpoints) if isinstance(endpoints, list) and all(isinstance(item, str) for item in endpoints) else set() source_set = set(source_only) if isinstance(source_only, list) and all(isinstance(item, str) for item in source_only) else set() reported_failures = list(reported) if isinstance(reported, list) and all(isinstance(item, str) for item in reported) else [] if async_reg_count != len(EXPECTED_CDC_SYNC_REGISTERS): failures.append(f"async_reg_used:{async_reg_count}") if input_register_count != EXPECTED_CDC_INPUT_REGISTERS: failures.append(f"input_registers_used:{input_register_count}") if register_set != EXPECTED_CDC_SYNC_REGISTERS: failures.append("retained_sync_registers_mismatch") if endpoint_set != EXPECTED_CDC_FALSE_PATH_ENDPOINTS: failures.append("false_path_endpoints_mismatch") if source_set: failures.append(f"source_only_false_paths_used:{','.join(sorted(source_set))}") failures.extend(f"td_report:{failure}" for failure in reported_failures) return { "status": "pass" if not failures else "fail", "async_reg": { "status": "pass" if async_reg_count == len(EXPECTED_CDC_SYNC_REGISTERS) else "fail", "used": async_reg_count, }, "input_registers": { "status": "pass" if input_register_count == EXPECTED_CDC_INPUT_REGISTERS else "fail", "used": input_register_count, }, "retained_sync_registers": { "status": "pass" if register_set == EXPECTED_CDC_SYNC_REGISTERS else "fail", "used": len(register_set), }, "first_stage_endpoints": { "status": "pass" if endpoint_set == EXPECTED_CDC_FALSE_PATH_ENDPOINTS else "fail", "used": len(endpoint_set), }, "source_only_false_paths": sorted(source_set), "reported_failures": reported_failures, "failures": failures, } def structural_fsm_gate( report: Mapping[str, Any] | None, *, syn_log: str, ) -> dict[str, Any]: failures: list[str] = [] axes = report.get("axes") if isinstance(report, Mapping) else None encodings = report.get("encodings") if isinstance(report, Mapping) else None reported = report.get("structural_failures") if isinstance(report, Mapping) else None normalized_axes = dict(axes) if isinstance(axes, Mapping) else {} normalized_encodings = dict(encodings) if isinstance(encodings, Mapping) else {} reported_failures = list(reported) if isinstance(reported, list) and all(isinstance(item, str) for item in reported) else [] if normalized_axes != EXPECTED_FSM_AXES: failures.append("motion_phase_width_or_axis_mismatch") if normalized_encodings != {axis: "sequential" for axis in EXPECTED_FSM_AXES}: failures.append("motion_phase_encoding_mismatch") marker_seen = "FSM_ENCODING_GATE_PASS=sequential" in syn_log if not marker_seen: failures.append("fsm_td_log_marker_missing") reencoded = re.findall( r"SYN-1067\s*:.*?state register '[^']*motion_phase(?:_reg)?[^']*'" r".*?encoding '([^']+)'", syn_log, re.IGNORECASE, ) for encoding in reencoded: failures.append(f"motion_phase_reencoded:{encoding.casefold()}") failures.extend(f"td_report:{failure}" for failure in reported_failures) return { "status": "pass" if not failures else "fail", "encoding": "sequential" if not failures else None, "axes": normalized_axes, "td_log_marker": marker_seen, "reencoded_motion_phase_count": len(reencoded), "reported_failures": reported_failures, "failures": failures, } def parse_area_report(path: Path) -> dict[str, Any] | None: if not path.is_file(): return None text = path.read_text(encoding="utf-8", errors="replace") result: dict[str, Any] = {"path": str(path), "utilization": {}, "hierarchy": []} columns: list[str] = [] for line in text.splitlines(): match = re.match( r"#(lut|reg|dsp|bram|bram32k|bram128k|bram256k|pad|pll)\s+" r"(\d+)\s+out of\s+(\d+)\s+([0-9.]+)%", line.strip(), ) if match: result["utilization"][match.group(1)] = { "used": int(match.group(2)), "total": int(match.group(3)), "percent": float(match.group(4)), } continue detail = re.match(r"#(ireg|oreg|treg)\s+(\d+)\s*$", line.strip()) if detail: result["utilization"][detail.group(1)] = {"used": int(detail.group(2))} continue if line.startswith("|") and "Instance" in line and "Module" in line: columns = [part.strip().lower() for part in line.strip("|").split("|")] continue if line.startswith("|") and columns: values = [part.strip() for part in line.strip("|").split("|")] if len(values) != len(columns): continue row = dict(zip(columns, values)) if not row.get("instance") or row.get("instance") == "Instance": continue parsed: dict[str, Any] = {"instance": row["instance"], "module": row["module"]} try: for key, value in row.items(): if key not in {"instance", "module"}: parsed[key] = int(value) except ValueError: continue result["hierarchy"].append(parsed) if "pad" in result["utilization"]: for name in ("ireg", "oreg", "treg"): result["utilization"].setdefault(name, {"used": 0}) return result def parse_td_io_report(path: Path) -> list[dict[str, str]] | None: target = Path(path) if not target.is_file(): return None lines = target.read_text(encoding="utf-8", errors="replace").splitlines() try: start = next(index for index, line in enumerate(lines) if line.strip() == "Detailed IO Report") header = next( index for index in range(start + 1, len(lines)) if lines[index].split()[:4] == ["Name", "Direction", "Location", "IOStandard"] ) except StopIteration: return None rows: list[dict[str, str]] = [] for line in lines[header + 1 :]: fields = line.split() if not fields: if rows: break continue if len(fields) != 9: if rows: break continue rows.append( dict( zip( ( "name", "direction", "location", "io_standard", "io_type", "drive_strength", "pull_type", "pack_reg", "diff_resistor", ), fields, strict=True, ) ) ) return rows or None def post_route_pin_gate(rows: Sequence[Mapping[str, str]] | None) -> dict[str, Any]: failures: list[str] = [] expected_pins = active_pin_contract() normalized = [dict(row) for row in rows or []] by_name = {row.get("name"): row for row in normalized if row.get("name")} locations = [str(row.get("location", "")) for row in normalized] if len(normalized) != len(expected_pins): failures.append(f"io_row_count:{len(normalized)}") if len(by_name) != len(normalized): failures.append("io_name_not_unique") if len(set(locations)) != len(locations): failures.append("io_location_not_unique") required = { name: {**expected, "io_standard": "LVCMOS33"} for name, expected in expected_pins.items() } for name, expected in required.items(): observed = by_name.get(name) if observed is None: failures.append(f"io_signal_missing:{name}") continue for field, value in expected.items(): if observed.get(field) != value: failures.append(f"io_binding_mismatch:{name}:{field}") return { "status": "pass" if not failures else "fail", "row_count": len(normalized), "required": required, "observed": {name: by_name.get(name) for name in required}, "failures": failures, } def parse_packing_summary(*texts: str) -> dict[str, int] | None: matches = [ (int(match.group(1)), int(match.group(2))) for text in texts for match in re.finditer(r"\b(\d+)\s+mslices,\s+(\d+)\s+lslices\b", text, re.IGNORECASE) ] if not matches: return None mslice, lslice = matches[-1] return {"mslice": mslice, "lslice": lslice, "total_slices": mslice + lslice} def parse_timing_report(path: Path) -> dict[str, Any] | None: if not path.is_file(): return None text = path.read_text(encoding="utf-8", errors="replace") result: dict[str, Any] = {"path": str(path)} row = re.search( r"^\s*clk\d+\s+\S+\s+[0-9.]+\s+[0-9.]+\s+" r"([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s+" r"([0-9.+-]+)\s+([0-9.+-]+)\s+([0-9.+-]+)\s+([0-9.+-]+)", text, re.MULTILINE, ) if row: result.update( { "period_ns": float(row.group(1)), "clock_frequency_mhz": float(row.group(2)), "minimum_period_ns": float(row.group(3)), "fmax_mhz": float(row.group(4)), "worst_setup_slack_ns": float(row.group(5)), "setup_total_negative_slack_ns": float(row.group(6)), "worst_hold_slack_ns": float(row.group(7)), "hold_total_negative_slack_ns": float(row.group(8)), } ) errors = re.search(r"(\d+) errors detected : (\d+) setup errors .*?, (\d+) hold errors", text) if errors: result["error_count"] = int(errors.group(1)) result["setup_error_count"] = int(errors.group(2)) result["hold_error_count"] = int(errors.group(3)) else: setup_violations = re.search( r"^\s*Max\s*:.*?\b(\d+)\s+Viol Endpoints\b", text, re.MULTILINE, ) hold_violations = re.search( r"^\s*Min\s*:.*?\b(\d+)\s+Viol Endpoints\b", text, re.MULTILINE, ) if setup_violations and hold_violations: setup_count = int(setup_violations.group(1)) hold_count = int(hold_violations.group(1)) result["error_count"] = setup_count + hold_count result["setup_error_count"] = setup_count result["hold_error_count"] = hold_count return result def pin_binding_gate() -> dict[str, Any]: path = ROOT / "constraints" / "prod2u_p4_normal_v3.adc" text = path.read_text(encoding="utf-8", errors="replace") assignments = re.findall( r"set_pin_assignment\s+\{\s*([^}]+?)\s*\}\s+\{\s*LOCATION\s*=\s*([^;\s]+);\s*" r"IOSTANDARD\s*=\s*([^;\s]+);\s*PULLTYPE\s*=\s*([^;\s]+);", text, ) by_signal = {signal.strip(): (ball.strip(), standard.strip(), pull.strip()) for signal, ball, standard, pull in assignments} failures: list[str] = [] expected_pins = active_pin_contract() if len(assignments) != len(expected_pins): failures.append(f"pad_count:{len(assignments)}") if len(by_signal) != len(assignments): failures.append("duplicate_signal") if len({item[0] for item in by_signal.values()}) != len(assignments): failures.append("duplicate_ball") required = { signal: (expected["location"], expected["pull_type"]) for signal, expected in expected_pins.items() } for signal, (ball, pull) in required.items(): observed = by_signal.get(signal) if observed is None: failures.append(f"missing_signal:{signal}") elif observed[0] != ball or observed[2] != pull: failures.append(f"binding_mismatch:{signal}") return { "status": "pass" if not failures else "fail", "path": str(path), "pad_count": len(assignments), "failures": failures, } def timing_gate(timing: Mapping[str, Any] | None) -> dict[str, Any]: failures: list[str] = [] if not isinstance(timing, Mapping): failures.append("timing_report_missing") else: for name in ("fmax_mhz", "worst_setup_slack_ns", "worst_hold_slack_ns"): value = timing.get(name) if not isinstance(value, (int, float)) or value <= 0: failures.append(f"nonpositive_or_missing:{name}") error_count = timing.get("error_count") if not isinstance(error_count, int) or isinstance(error_count, bool): failures.append("timing_error_count_missing") elif error_count != 0: failures.append("timing_errors_present") return {"status": "pass" if not failures else "fail", "failures": failures} def td_bitgen_eligible( *, route_artifact_usable: bool, timing_status: str, structural_status: str, ) -> bool: """Permit bit generation after a usable routed database exists. Timing and structural results remain recorded in the receipt, but the temporary-image policy does not let those validation failures suppress a bitstream that TD can still generate. """ del timing_status, structural_status return bool(route_artifact_usable) def td_stage_artifact_usable( completed: subprocess.CompletedProcess[str] | None, artifact: Path, ) -> bool: return bool( completed is not None and completed.returncode == 0 and not td_log_has_error(completed.stdout, completed.stderr) and not td_log_has_cdc_gate_failure(completed.stdout, completed.stderr) and artifact.is_file() and artifact.stat().st_size > 0 ) def structural_resource_gate( resources: Mapping[str, Any] | None, ) -> dict[str, Any]: failures: list[str] = [] utilization = resources.get("utilization") if isinstance(resources, Mapping) else None reported_resources = ("bram", "bram32k", "bram128k", "bram256k", "dsp") exact_resources = {"pad": len(active_pin_contract()), "ireg": EXPECTED_CDC_INPUT_REGISTERS} if not isinstance(utilization, Mapping): failures.append("resource_report_missing") else: for name in reported_resources: observed = utilization.get(name) used = observed.get("used") if isinstance(observed, Mapping) else None if not isinstance(used, int) or isinstance(used, bool) or used < 0: failures.append(f"{name}_used:{used}") for name, value in exact_resources.items(): observed = utilization.get(name) used = observed.get("used") if isinstance(observed, Mapping) else None if used != value or isinstance(used, bool): failures.append(f"{name}_used:{used}") return { "status": "pass" if not failures else "fail", "required": { "bram": "reported_nonnegative_integer", "bram32k": "reported_nonnegative_integer", "bram128k": "reported_nonnegative_integer", "bram256k": "reported_nonnegative_integer", "dsp": "reported_nonnegative_integer", "pad": exact_resources["pad"], "ireg": EXPECTED_CDC_INPUT_REGISTERS, }, "failures": failures, } def _stage_result(completed: subprocess.CompletedProcess[str] | None) -> dict[str, Any] | None: if completed is None: return None timed_out = _was_timed_out(completed) command = ( [str(value) for value in completed.args] if isinstance(completed.args, Sequence) and not isinstance(completed.args, (str, bytes)) else [str(completed.args)] ) cdc_gate_failure = td_log_has_cdc_gate_failure(completed.stdout, completed.stderr) return { "status": ( "fail_timeout" if timed_out else ("fail" if completed.returncode != 0 or cdc_gate_failure else "pass") ), "timed_out": timed_out, "returncode": completed.returncode, "log_has_error": td_log_has_error(completed.stdout, completed.stderr), "cdc_gate_failure": cdc_gate_failure, "critical_warning_count": td_critical_warning_count(completed.stdout, completed.stderr), "command": command, "stdout_tail": _tail(completed.stdout), "stderr_tail": _tail(completed.stderr), } def _td_artifact(path: Path) -> dict[str, Any]: target = Path(path).resolve() return { "path": str(target), "size": target.stat().st_size, "sha256": sha256_file(target), } def _write_td_console_log( path: Path, completed: subprocess.CompletedProcess[str], ) -> Path: target = Path(path).resolve() target.parent.mkdir(parents=True, exist_ok=True) target.write_text( "=== STDOUT ===\n" + str(completed.stdout or "") + "\n=== STDERR ===\n" + str(completed.stderr or "") + "\n", encoding="utf-8", newline="\n", ) return target def td_measurement_artifacts( *, syn_dir: Path, phy_dir: Path, bitgen_dir: Path, bitstream: Path, syn: subprocess.CompletedProcess[str] | None, phy: subprocess.CompletedProcess[str] | None, bitgen: subprocess.CompletedProcess[str] | None, ) -> tuple[dict[str, dict[str, Any]], list[str]]: directories = { "syn": Path(syn_dir).resolve(), "phy": Path(phy_dir).resolve(), "bitgen": Path(bitgen_dir).resolve(), } stage_results = {"syn": syn, "phy": phy, "bitgen": bitgen} paths = { "bitstream": Path(bitstream).resolve(), "syn_area": directories["syn"] / f"{PROFILE}_gate.area", "phy_area": directories["phy"] / f"{PROFILE}_phy.area", "timing": directories["phy"] / f"{PROFILE}_pr.timing", "syn_qor": directories["syn"] / "gate.qor", "syn_cdc": directories["syn"] / f"{PROFILE}_cdc.rpt", "phy_cdc": directories["phy"] / f"{PROFILE}_cdc.rpt", } failures: list[str] = [] for phase, completed in stage_results.items(): if completed is None: failures.append(f"measurement_stage_missing:{phase}") continue try: paths[f"{phase}_log"] = _write_td_console_log( directories[phase] / f"{PROFILE}_{phase}.console.log", completed, ) except OSError as exc: failures.append(f"measurement_stage_log_failed:{phase}:{type(exc).__name__}") artifacts: dict[str, dict[str, Any]] = {} for name, path in paths.items(): if not path.is_file() or path.stat().st_size <= 0: failures.append(f"measurement_artifact_missing:{name}") continue try: artifacts[name] = _td_artifact(path) except OSError as exc: failures.append(f"measurement_artifact_unreadable:{name}:{type(exc).__name__}") return artifacts, sorted(set(failures)) def _resource_delta_unavailable(reason: str) -> dict[str, Any]: return { "schema": "prod2u-p4-normal-v3-resource-delta-v1", "advisory_only": True, "affects_build_status": False, "available": False, "reason": reason, } def td_source_states_clean( source_before: Mapping[str, Any], source_after: Mapping[str, Any], staged_manifest: Mapping[str, Any], ) -> bool: return ( source_before.get("clean") is True and source_after.get("clean") is True and staged_manifest.get("source_state_clean") is True and source_before.get("project_config_sha256") == source_after.get("project_config_sha256") == staged_manifest.get("project_config_sha256") and source_before.get("td_source_manifest_sha256") == source_after.get("td_source_manifest_sha256") == staged_manifest.get("td_source_manifest_sha256") ) def td_build_payload( run: bool, top: str = PROFILE, *, work_root: Path | None = None, verification_run_id: str | None = None, ) -> dict[str, Any]: shared_run_id = normalize_verification_run_id(verification_run_id) metadata = { "schema": TD_RECEIPT_SCHEMA, "build_mode": TD_BUILD_MODE_PRODUCTION, "resource_variant": RESOURCE_VARIANT_PRODUCTION, "top": top, "top_module": TOP_MODULE, "pin_profile": PIN_PROFILE, "profile": PROFILE, "runtime_profile": RUNTIME_PROFILE, "verification_run_id": shared_run_id, "safety": dict(SAFETY_BOUNDARY), } if top != PROFILE: return {**metadata, "status": "fail", "reason": f"unsupported TD top: {top}"} try: resolved = resolve_work_root(work_root, run=run) except ValueError as exc: return {**metadata, "status": "blocked_invalid_work_root", "reason": str(exc)} if not run: return { **metadata, "status": "skipped", "reason": "TD build not requested; pass --run to execute it.", "work_root": None if resolved is None else str(resolved), } assert resolved is not None generated_at = utc_now() run_id = new_td_run_id() if not TD_EXE.is_file(): return {**metadata, "status": "blocked", "reason": f"missing TD executable: {TD_EXE}"} script_failures: list[str] = [] for phase, script in TD_SCRIPTS.items(): if not script.is_file(): script_failures.append(f"missing_script:{phase}") continue for marker in td_forbidden_script_markers( script.read_text(encoding="utf-8", errors="replace") ): script_failures.append(f"forbidden_script_command:{phase}:{marker}") pins = pin_binding_gate() if script_failures or pins["status"] != "pass": return { **metadata, "status": "blocked_pin_binding_invalid" if pins["status"] != "pass" else "fail", "script_failures": script_failures, "pin_binding_gate": pins, } try: staged = prepare_td_build_dirs(work_root=resolved) except (OSError, RuntimeError, ValueError) as exc: return {**metadata, "status": "fail_build_preparation", "reason": str(exc)} syn = run_td_script(staged.syn, TD_SCRIPTS["syn"].name) syn_resources = parse_area_report(staged.syn / f"{PROFILE}_gate.area") syn_utilization = syn_resources.get("utilization") if isinstance(syn_resources, Mapping) else None syn_ireg = syn_utilization.get("ireg") if isinstance(syn_utilization, Mapping) else None syn_cdc = structural_cdc_gate( parse_td_cdc_report(staged.syn / f"{PROFILE}_cdc.rpt"), async_reg_count=parse_qor_attribute_count( staged.syn / f"{PROFILE}_gate.qor", "async_reg", ), input_register_count=syn_ireg.get("used") if isinstance(syn_ireg, Mapping) else None, ) syn_ok = ( syn.returncode == 0 and not td_log_has_error(syn.stdout, syn.stderr) and not td_log_has_cdc_gate_failure(syn.stdout, syn.stderr) and td_critical_warning_count(syn.stdout, syn.stderr) == 0 and syn_cdc["status"] == "pass" and "CDC_GATE_PASS=1" in syn.stdout ) syn_artifact_usable = td_stage_artifact_usable( syn, staged.syn / f"{PROFILE}_gate.db", ) phy: subprocess.CompletedProcess[str] | None = None if syn_artifact_usable: phy = run_td_script(staged.phy, TD_SCRIPTS["phy"].name) phy_ok = bool( phy and phy.returncode == 0 and not td_log_has_error(phy.stdout, phy.stderr) and not td_log_has_cdc_gate_failure(phy.stdout, phy.stderr) and td_critical_warning_count(phy.stdout, phy.stderr) == 0 ) route_artifact_usable = td_stage_artifact_usable( phy, staged.phy / f"{PROFILE}_pr.db", ) resources = parse_area_report(staged.phy / f"{PROFILE}_phy.area") if resources is not None and phy is not None: resources["packing"] = parse_packing_summary(phy.stdout, phy.stderr) timing = parse_timing_report(staged.phy / f"{PROFILE}_pr.timing") timing_result = timing_gate(timing) resource_structural = structural_resource_gate(resources) routed_pins = post_route_pin_gate( parse_td_io_report(staged.phy / f"{PROFILE}_phy.area") ) utilization = resources.get("utilization") if isinstance(resources, Mapping) else None ireg = utilization.get("ireg") if isinstance(utilization, Mapping) else None cdc_structural = structural_cdc_gate( parse_td_cdc_report(staged.phy / f"{PROFILE}_cdc.rpt"), async_reg_count=parse_qor_attribute_count( staged.syn / f"{PROFILE}_gate.qor", "async_reg", ), input_register_count=ireg.get("used") if isinstance(ireg, Mapping) else None, ) structural = { "status": ( "pass" if resource_structural["status"] == "pass" and routed_pins["status"] == "pass" and cdc_structural["status"] == "pass" else "fail" ), "resources": resource_structural, "pins": routed_pins, "cdc": cdc_structural, "failures": [ *resource_structural["failures"], *(f"pins:{failure}" for failure in routed_pins["failures"]), *(f"cdc:{failure}" for failure in cdc_structural["failures"]), ], } bitgen: subprocess.CompletedProcess[str] | None = None if td_bitgen_eligible( route_artifact_usable=route_artifact_usable, timing_status=str(timing_result["status"]), structural_status=str(structural["status"]), ): bitgen = run_td_script(staged.bitgen, TD_SCRIPTS["bitgen"].name) bitgen_ok = bool( bitgen and bitgen.returncode == 0 and not td_log_has_error(bitgen.stdout, bitgen.stderr) and not td_log_has_cdc_gate_failure(bitgen.stdout, bitgen.stderr) and td_critical_warning_count(bitgen.stdout, bitgen.stderr) == 0 ) bitstream = staged.bitgen / f"{PROFILE}.bit" bitstream_sha256 = ( sha256_file(bitstream) if bitstream.is_file() and bitstream.stat().st_size > 0 else None ) measurement_artifacts, measurement_failures = td_measurement_artifacts( syn_dir=staged.syn, phy_dir=staged.phy, bitgen_dir=staged.bitgen, bitstream=bitstream, syn=syn, phy=phy, bitgen=bitgen, ) state_after = source_state() staged_source_manifest = verify_staged_source_manifest(staged) source_state_stable = state_after == staged.source_state source_binding_gate = { "status": ( "pass" if staged_source_manifest["status"] == "pass" and source_state_stable and td_source_states_clean(staged.source_state, state_after, staged_source_manifest) else "fail" ), "source_state_stable": source_state_stable, "failures": [ *staged_source_manifest["failures"], *([] if source_state_stable else ["repository_source_state_changed_during_build"]), *([] if staged.source_state.get("clean") is True else ["repository_source_state_dirty_at_start"]), *([] if state_after.get("clean") is True else ["repository_source_state_dirty_after_build"]), ], } passed = ( syn_ok and phy_ok and timing_result["status"] == "pass" and structural["status"] == "pass" and bitgen_ok and bitstream_sha256 is not None and source_binding_gate["status"] == "pass" and not measurement_failures ) td_tool = probe_td_tool() payload = { **metadata, "status": "pass" if passed else "fail", "generated_at": generated_at, "run_id": run_id, "command": " ".join([str(TD_EXE)] + [str(script) for script in TD_SCRIPTS.values()]), "tool_version": str(td_tool.get("version") or "unknown"), **source_binding_fields(staged.source_state), "source_state": dict(staged.source_state), "repository_state_after": state_after, "bitstream_sha256": bitstream_sha256, "synthesis_input_manifest": dict(staged.synthesis_input_manifest), "synthesis_input_hash": staged.synthesis_input_manifest["sha256"], "clean": dict(staged.clean), "staged_source_manifest": staged_source_manifest, "source_binding_gate": source_binding_gate, "work_root": str(resolved), "build_dirs": { "syn": str(staged.syn), "phy": str(staged.phy), "bitgen": str(staged.bitgen), }, "td_tool": td_tool, "pin_binding_gate": pins, "post_route_pin_gate": routed_pins, "binding_gate": {"status": "pass", "target_device": TARGET_DEVICE}, "syn": _stage_result(syn), "phy": _stage_result(phy), "bitgen": _stage_result(bitgen), "bitstream": ( None if bitstream_sha256 is None else {"path": str(bitstream), "size": bitstream.stat().st_size} ), "resources": resources, "resource_gate": { "status": "pass" if resources is not None else "fail", "advisory_only": True, "affects_build_status": False, }, "resource_delta": _resource_delta_unavailable("new_minimal_baseline_pending"), "structural_gate": structural, "timing": timing, "timing_gate": timing_result, "no_programming_safety_declaration": ( "No JTAG, cable, download, flash, SRAM, or board programming was performed. " "Forbidden TD commands were absent from syn/phy/bitgen scripts. " "Hardware validation remains not_run." ), "error_summary": { "error_count": sum( int(bool(item and item.get("log_has_error"))) for item in (_stage_result(syn), _stage_result(phy), _stage_result(bitgen)) ), "critical_warning_count": sum( int(item.get("critical_warning_count", 0)) for item in (_stage_result(syn), _stage_result(phy), _stage_result(bitgen)) if item ), }, "authority_boundary": ( "This TD receipt covers synthesis, placement, routing, bit generation, timing, " "resources, and source binding only. It performs no cable or board action." ), } if measurement_failures: payload["measurement_artifact_failures"] = measurement_failures else: payload["measurement_artifacts"] = measurement_artifacts return payload def _emit(payload: Mapping[str, Any], args: argparse.Namespace, label: str) -> int: emitted = dict(payload) run_id = getattr(args, "verification_run_id", None) for field, value in source_binding_fields(source_state(), verification_run_id=run_id).items(): if field not in emitted or emitted[field] is None: emitted[field] = value if getattr(args, "report_file", None): try: report_file = resolve_report_file(args.report_file) except ValueError as exc: print(json.dumps({"status": "fail", "reason": str(exc)}, indent=2) if getattr(args, "json", False) else f"{label}: fail") return 1 write_json_report(emitted, report_file) print(json.dumps(emitted, indent=2) if getattr(args, "json", False) else f"{label}: {emitted.get('status', 'unknown')}") return 0 if emitted.get("status") == "pass" else 1 def package_required_files(*, confirmation_td_present: bool = True) -> tuple[str, ...]: del confirmation_td_present return ( "fw.bit", "project.json", "package_manifest.json", "package-info.json", "project_config_sha256.txt", "bitstream_sha256.txt", "protocol.md", "requirements.zh-CN.md", "source_manifest.json", "verification_targets.json", "verification_summary.json", "evidence/td-primary-receipt.json", "evidence/td-confirmation-receipt.json", "evidence/python-unit-receipt.json", "evidence/icarus-receipt.json", "evidence/verilator-receipt.json", "evidence/cocotb-receipt.json", "evidence/formal-receipt.json", "evidence/formal-trace-manifest.json", "evidence/validation-summary.json", "evidence/package-selftest-result.json", ) def package_selftest_payload( package_dir: Path, *, verification_run_id: str | None = None, ) -> dict[str, Any]: package = Path(package_dir).expanduser().resolve() run_id = normalize_verification_run_id(verification_run_id) info_path = package / "package-info.json" manifest_path = package / "package_manifest.json" primary_td_path = package / "evidence" / "td-primary-receipt.json" confirmation_td_path = package / "evidence" / "td-confirmation-receipt.json" validation_path = package / "evidence" / "validation-summary.json" packaged_selftest_path = package / "evidence" / "package-selftest-result.json" bitstream = package / "fw.bit" failures: list[str] = [] current_state = source_state() expected_commit = receipt_commit_full(current_state) or "" expected_project_config_sha256 = current_state.get("project_config_sha256") expected_td_source_manifest_sha256 = current_state.get("td_source_manifest_sha256") info: Mapping[str, Any] = {} package_manifest: Mapping[str, Any] = {} primary_td: Mapping[str, Any] = {} confirmation_td: Mapping[str, Any] = {} validation: Mapping[str, Any] = {} packaged_selftest: Mapping[str, Any] = {} inputs = ( (info_path, "package_info"), (primary_td_path, "primary_td"), (validation_path, "validation"), (packaged_selftest_path, "packaged_selftest"), ) loaded_inputs: dict[str, Mapping[str, Any]] = {} for path, label in inputs: try: loaded = json.loads(path.read_text(encoding="utf-8-sig")) except (OSError, UnicodeError, json.JSONDecodeError) as exc: failures.append(f"{label}_unreadable:{exc}") continue if not isinstance(loaded, Mapping): failures.append(f"{label}_not_object") else: loaded_inputs[label] = loaded info = loaded_inputs.get("package_info", {}) try: loaded_manifest = json.loads(manifest_path.read_text(encoding="utf-8-sig")) except (OSError, UnicodeError, json.JSONDecodeError) as exc: failures.append(f"package_manifest_unreadable:{exc}") else: if not isinstance(loaded_manifest, Mapping): failures.append("package_manifest_not_object") else: package_manifest = loaded_manifest delivery_mode = info.get("delivery_mode") if info else None if delivery_mode not in {"normal_dual_td", "urgent_single_td"}: failures.append("package_delivery_mode_invalid") confirmation_expected = confirmation_td_path.exists() or info.get("verification_complete") is True if confirmation_expected or confirmation_td_path.exists(): try: loaded = json.loads(confirmation_td_path.read_text(encoding="utf-8-sig")) except (OSError, UnicodeError, json.JSONDecodeError) as exc: failures.append(f"confirmation_td_unreadable:{exc}") else: if not isinstance(loaded, Mapping): failures.append("confirmation_td_not_object") else: loaded_inputs["confirmation_td"] = loaded primary_td = loaded_inputs.get("primary_td", {}) confirmation_td = loaded_inputs.get("confirmation_td", {}) validation = loaded_inputs.get("validation", {}) packaged_selftest = loaded_inputs.get("packaged_selftest", {}) for label, receipt in ( ("package_info", info), ("primary_td", primary_td), ("confirmation_td", confirmation_td), ("validation", validation), ): if receipt and receipt.get("verification_run_id") != run_id: failures.append(f"verification_run_id_mismatch:{label}") digest = None if not bitstream.is_file() or bitstream.stat().st_size <= 0: failures.append("bitstream_missing") else: digest = sha256_file(bitstream) if info: if info.get("schema") != "prod2u-p4-normal-v3-folder-package-info-v3": failures.append("package_info_schema_mismatch") if info.get("profile") != RUNTIME_PROFILE: failures.append("package_profile_mismatch") verification_complete = info.get("verification_complete") confirmation_td_present = info.get("confirmation_td_present") if not isinstance(verification_complete, bool): failures.append("package_verification_complete_invalid") if not isinstance(confirmation_td_present, bool): failures.append("package_confirmation_td_present_invalid") elif confirmation_td_present != confirmation_td_path.is_file(): failures.append("package_confirmation_td_presence_mismatch") if delivery_mode == "urgent_single_td": if verification_complete is not False: failures.append("urgent_verification_complete_must_be_false") commit = str(info.get("commit", "")) if not FULL_COMMIT_RE.fullmatch(commit): failures.append("package_commit_invalid") info_commit_full = str(info.get("commit_full", "")) if info_commit_full and not FULL_COMMIT_RE.fullmatch(info_commit_full): failures.append("package_commit_full_invalid") if info_commit_full and expected_commit and info_commit_full != expected_commit: failures.append("package_commit_full_mismatch") if info.get("project_config_sha256") != expected_project_config_sha256: failures.append("package_project_config_sha256_mismatch") if info.get("td_source_manifest_sha256") != expected_td_source_manifest_sha256: failures.append("package_td_source_manifest_sha256_mismatch") if info.get("bitstream_sha256") != digest: failures.append("package_bitstream_sha256_mismatch") expected_name = ( f"{commit}-{digest[:16]}" if digest is not None and (FULL_COMMIT_RE.fullmatch(commit) or SHORT_COMMIT_RE.fullmatch(commit)) else None ) if expected_name is not None and package.name != expected_name: failures.append("package_folder_name_mismatch") if (FULL_COMMIT_RE.fullmatch(commit) or SHORT_COMMIT_RE.fullmatch(commit)) and package.parent.name != "prod2u-door-temp": failures.append("package_project_parent_mismatch") if info.get("td_receipt_sha256") != ( sha256_file(primary_td_path) if primary_td_path.is_file() else None ): failures.append("package_td_receipt_sha256_mismatch") if info.get("confirmation_td_receipt_sha256") != ( sha256_file(confirmation_td_path) if confirmation_td_path.is_file() else None ): failures.append("package_confirmation_td_receipt_sha256_mismatch") if info.get("validation_summary_sha256") != ( sha256_file(validation_path) if validation_path.is_file() else None ): failures.append("package_validation_summary_sha256_mismatch") if info.get("package_selftest_result_sha256") != ( sha256_file(packaged_selftest_path) if packaged_selftest_path.is_file() else None ): failures.append("package_selftest_result_sha256_mismatch") package_class = info.get("package_class", "UNVERIFIED") if package_class not in { "UNVERIFIED", "UNVERIFIED_EARLY_BUILD", "UNVERIFIED_FINAL_CANDIDATE", "VERIFIED_OFFLINE", }: failures.append("package_class_invalid") if package_class == "UNVERIFIED_EARLY_BUILD": production_commit = str(info.get("production_integration_commit", "")) if not re.fullmatch(r"[0-9a-f]{40}", production_commit): failures.append("early_production_integration_commit_invalid") source_manifest_path = package / "source_manifest.json" source_manifest_digest = ( sha256_file(source_manifest_path) if source_manifest_path.is_file() else None ) if info.get("source_manifest_sha256") != source_manifest_digest: failures.append("early_source_manifest_binding_mismatch") source_td_digest = primary_td.get("source_receipt_sha256") if info.get("td_source_receipt_sha256") != source_td_digest: failures.append("early_td_source_receipt_binding_mismatch") if package_manifest.get("status") != "UNVERIFIED": failures.append("early_package_status_mismatch") if package_manifest.get("package_class") != package_class: failures.append("early_package_class_mismatch") if package_manifest.get("production_integration_commit") != production_commit: failures.append("early_manifest_commit_mismatch") if package_manifest.get("source_manifest_sha256") != source_manifest_digest: failures.append("early_manifest_source_hash_mismatch") actual_files = { path.relative_to(package).as_posix(): sha256_file(path) for path in sorted(package.rglob("*")) if path.is_file() and path not in {info_path, package / "package_manifest.json", packaged_selftest_path} } expected_files = info.get("file_sha256") if isinstance(info, Mapping) else None if not isinstance(expected_files, Mapping) or dict(expected_files) != actual_files: failures.append("package_file_hash_map_mismatch") required_files = package_required_files(confirmation_td_present=confirmation_expected) checked_files = [ relative for relative in required_files if (package / relative).is_file() ] for relative in required_files: if not (package / relative).is_file(): failures.append(f"package_file_missing:{relative}") commit = info.get("commit") if info else None package_expected_commit = ( receipt_commit_full(info) if info else None ) or str(commit or "") if primary_td: if not receipt_commit_matches(primary_td, package_expected_commit): failures.append("primary_td_commit_mismatch") if primary_td.get("project_config_sha256") != expected_project_config_sha256: failures.append("primary_td_project_config_sha256_mismatch") if primary_td.get("td_source_manifest_sha256") != expected_td_source_manifest_sha256: failures.append("primary_td_td_source_manifest_sha256_mismatch") if primary_td.get("bitstream_sha256") != digest: failures.append("primary_td_bitstream_sha256_mismatch") if info.get("synthesis_input_hash") != primary_td.get("synthesis_input_hash"): failures.append("primary_td_synthesis_input_hash_mismatch") if confirmation_td and confirmation_td.get("status") == "pass": if not receipt_commit_matches(confirmation_td, package_expected_commit): failures.append("confirmation_td_commit_mismatch") if confirmation_td.get("project_config_sha256") != expected_project_config_sha256: failures.append("confirmation_td_project_config_sha256_mismatch") if confirmation_td.get("td_source_manifest_sha256") != expected_td_source_manifest_sha256: failures.append("confirmation_td_td_source_manifest_sha256_mismatch") if info.get("confirmation_bitstream_sha256") != confirmation_td.get( "bitstream_sha256" ): failures.append("confirmation_td_bitstream_sha256_binding_mismatch") if info.get("confirmation_synthesis_input_hash") != confirmation_td.get( "synthesis_input_hash" ): failures.append("confirmation_td_synthesis_input_hash_mismatch") primary_run_id = primary_td.get("run_id") confirmation_run_id = confirmation_td.get("run_id") if ( not valid_td_run_id(primary_run_id) or not valid_td_run_id(confirmation_run_id) or primary_run_id == confirmation_run_id ): failures.append("td_run_id_not_independent") primary_work_root = normalized_td_work_root(primary_td.get("work_root")) confirmation_work_root = normalized_td_work_root( confirmation_td.get("work_root") ) if ( primary_work_root is None or confirmation_work_root is None or primary_work_root == confirmation_work_root ): failures.append("td_work_root_not_independent") if validation: if validation.get("schema") != "prod2u-p4-normal-v3-validation-summary-v1": failures.append("validation_summary_schema_mismatch") if validation.get("commit") != commit or validation.get("bitstream_sha256") != digest: failures.append("validation_summary_binding_mismatch") for name in ("delivery_mode", "verification_complete", "confirmation_td_present"): if validation.get(name) != info.get(name): failures.append(f"validation_summary_{name}_mismatch") layers = validation.get("layers") if not isinstance(layers, Mapping): failures.append("validation_layers_missing") else: for name, layer in layers.items(): status = layer.get("status") if isinstance(layer, Mapping) else None if status not in {"pass", "fail", "running", "blocked", "not_run"}: failures.append(f"validation_layer_status_invalid:{name}") comparisons = { "td_confirmation_synthesis": ( confirmation_td.get("synthesis_input_hash"), primary_td.get("synthesis_input_hash"), ), "td_confirmation_manifest": ( ( confirmation_td.get("synthesis_input_manifest", {}).get("sha256") if isinstance(confirmation_td.get("synthesis_input_manifest"), Mapping) else None ), ( primary_td.get("synthesis_input_manifest", {}).get("sha256") if isinstance(primary_td.get("synthesis_input_manifest"), Mapping) else None ), ), } bitstream_layer = layers.get("td_confirmation_bitstream") expected_bitstream_status = td_receipt_bitstream_binding_status( confirmation_td ) if ( not isinstance(bitstream_layer, Mapping) or bitstream_layer.get("status") != expected_bitstream_status ): failures.append( "validation_layer_semantic_mismatch:td_confirmation_bitstream" ) for name, (observed, expected) in comparisons.items(): expected_status = ( "not_run" if observed in {None, ""} else "pass" if observed == expected else "fail" ) layer = layers.get(name) if not isinstance(layer, Mapping) or layer.get("status") != expected_status: failures.append(f"validation_layer_semantic_mismatch:{name}") if delivery_mode == "urgent_single_td": confirmation_layer = layers.get("td_confirmation") confirmation_status = ( confirmation_layer.get("status") if isinstance(confirmation_layer, Mapping) else None ) if confirmation_status not in {"pass", "not_run", "running"}: failures.append( "urgent_confirmation_layer_invalid:td_confirmation" ) expected_confirmation_status = "pass" if confirmation_status == "pass" else "not_run" for name in ( "td_confirmation_artifacts", "td_confirmation_bitstream", "td_confirmation_synthesis", "td_confirmation_manifest", "resource_confirmation", ): layer = layers.get(name) if not isinstance(layer, Mapping) or layer.get("status") != expected_confirmation_status: failures.append(f"urgent_confirmation_layer_not_not_run:{name}") script_result: dict[str, Any] = {"status": "not_run", "returncode": None} selftest = package / "selftest.ps1" if not selftest.is_file(): failures.append("package_selftest_script_missing") elif not failures: completed = subprocess.run( [ "powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(selftest), ], cwd=package, env=tool_env(), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60, check=False, ) script_result = { "status": "pass" if completed.returncode == 0 else "fail", "returncode": completed.returncode, "stdout_tail": _tail(completed.stdout), "stderr_tail": _tail(completed.stderr), } if completed.returncode != 0: failures.append("package_selftest_script_failed") result = { "schema": PACKAGE_RECEIPT_SCHEMA, "status": "pass" if not failures else "fail", "generated_at": utc_now(), "verification_run_id": run_id, "commit": info.get("commit") if info else None, "commit_full": ( receipt_commit_full(info) if info else None ), "commit_short": ( (receipt_commit_full(info)[:8] if receipt_commit_full(info) else info.get("commit")) if info else None ), "bitstream_sha256": digest, "package_dir": str(package), "delivery_mode": info.get("delivery_mode") if info else None, "verification_complete": info.get("verification_complete") if info else None, "confirmation_td_present": info.get("confirmation_td_present") if info else None, "td_receipt_sha256": sha256_file(primary_td_path) if primary_td_path.is_file() else None, "confirmation_td_receipt_sha256": ( sha256_file(confirmation_td_path) if confirmation_td_path.is_file() else None ), "validation_summary_sha256": sha256_file(validation_path) if validation_path.is_file() else None, "returncode": script_result.get("returncode"), "formal_trace_manifest_sha256": ( sha256_file(package / "evidence" / "formal-trace-manifest.json") if (package / "evidence" / "formal-trace-manifest.json").is_file() else None ), "td_run_id": primary_td.get("run_id") if primary_td else None, "confirmation_td_run_id": confirmation_td.get("run_id") if confirmation_td else None, "synthesis_input_hash": primary_td.get("synthesis_input_hash") if primary_td else None, "confirmation_synthesis_input_hash": ( confirmation_td.get("synthesis_input_hash") if confirmation_td else None ), "project_config_sha256": info.get("project_config_sha256") if info else None, "td_source_manifest_sha256": ( info.get("td_source_manifest_sha256") if info else None ) or (primary_td.get("td_source_manifest_sha256") if primary_td else None), "confirmation_bitstream_sha256": ( confirmation_td.get("bitstream_sha256") if confirmation_td else None ), "hash_exclusions": info.get("hash_exclusions") if info else None, "validation_status": validation_layer_summary(validation.get("layers")), "packaged_selftest_status": script_result.get("status"), "package_file_sha256": actual_files, "package_file_manifest_sha256": canonical_sha256(actual_files) if actual_files else None, "bound_files": checked_files, "failures": sorted(set(failures)), "selftest": script_result, "safety": dict(SAFETY_BOUNDARY), } packaged_selftest_path.write_text( json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n", ) try: package_info = json.loads(info_path.read_text(encoding="utf-8-sig")) if isinstance(package_info, dict): package_info["package_selftest_result_sha256"] = sha256_file(packaged_selftest_path) info_path.write_text( json.dumps(package_info, indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n", ) if manifest_path.is_file(): package_manifest = json.loads(manifest_path.read_text(encoding="utf-8-sig")) if isinstance(package_manifest, dict) and info_path.is_file(): package_manifest["package_info_sha256"] = sha256_file(info_path) manifest_path.write_text( json.dumps(package_manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n", ) except (OSError, UnicodeError, json.JSONDecodeError): result["failures"] = sorted(set(result["failures"] + ["package_selftest_persistence_failed"])) result["status"] = "fail" return result def cmd_strict_offline(args: argparse.Namespace) -> int: return _emit( strict_offline_gate_payload( work_root=args.work_root, verification_run_id=args.verification_run_id, ), args, "p4-normal-v3-strict-offline-gate", ) def cmd_hdl_sim(args: argparse.Namespace) -> int: return _emit( hdl_sim_payload( run=args.run, backend=args.backend, work_root=args.work_root, verification_run_id=args.verification_run_id, ), args, "hdl-sim", ) def cmd_formal(args: argparse.Namespace) -> int: return _emit( formal_payload( run=args.run, work_root=args.work_root, verification_run_id=args.verification_run_id, ), args, "formal", ) def cmd_td_build(args: argparse.Namespace) -> int: return _emit( td_build_payload( run=args.run, top=args.top, work_root=args.work_root, verification_run_id=args.verification_run_id, ), args, "td-build", ) def cmd_package_selftest(args: argparse.Namespace) -> int: return _emit( package_selftest_payload( args.package_dir, verification_run_id=args.verification_run_id, ), args, "package-selftest", ) def _gate_is_pass(receipt: Mapping[str, Any], name: str) -> bool: value = receipt.get(name) return isinstance(value, Mapping) and value.get("status") == "pass" def _td_final_failures( receipt: Mapping[str, Any], *, label: str, expected_commit: str, expected_project_config_sha256: str, expected_td_source_manifest_sha256: str, ) -> list[str]: failures: list[str] = [] prefix = f"{label}:" if receipt.get("schema") != TD_RECEIPT_SCHEMA: failures.append(prefix + "schema") if receipt.get("status") != "pass": failures.append(prefix + "status") if receipt_commit_full(receipt) != expected_commit: failures.append(prefix + "commit") if receipt.get("project_config_sha256") != expected_project_config_sha256: failures.append(prefix + "project_config_sha256") if receipt.get("td_source_manifest_sha256") != expected_td_source_manifest_sha256: failures.append(prefix + "td_source_manifest_sha256") if not re.fullmatch( r"[0-9a-f]{32}", str(receipt.get("verification_run_id", "")) ): failures.append(prefix + "verification_run_id") if not valid_td_run_id(receipt.get("run_id")): failures.append(prefix + "run_id") if normalized_td_work_root(receipt.get("work_root")) is None: failures.append(prefix + "work_root") if not re.fullmatch(r"[0-9a-f]{64}", str(receipt.get("bitstream_sha256", ""))): failures.append(prefix + "bitstream_sha256") if not re.fullmatch(r"[0-9a-f]{64}", str(receipt.get("synthesis_input_hash", ""))): failures.append(prefix + "synthesis_input_hash") source = receipt.get("source_state") if ( not isinstance(source, Mapping) or source.get("clean") is not True or not receipt_commit_matches(source, expected_commit) or source.get("project_config_sha256") != expected_project_config_sha256 or source.get("td_source_manifest_sha256") != expected_td_source_manifest_sha256 ): failures.append(prefix + "source_state") for gate_name in ( "source_binding_gate", "pin_binding_gate", "post_route_pin_gate", "binding_gate", "timing_gate", "structural_gate", ): if not _gate_is_pass(receipt, gate_name): failures.append(prefix + gate_name) structural = receipt.get("structural_gate") cdc = structural.get("cdc") if isinstance(structural, Mapping) else None expected_cdc = { "async_reg": len(EXPECTED_CDC_SYNC_REGISTERS), "input_registers": EXPECTED_CDC_INPUT_REGISTERS, "retained_sync_registers": len(EXPECTED_CDC_SYNC_REGISTERS), "first_stage_endpoints": len(EXPECTED_CDC_FALSE_PATH_ENDPOINTS), } cdc_ok = isinstance(cdc, Mapping) and cdc.get("status") == "pass" for name, expected in expected_cdc.items(): item = cdc.get(name) if isinstance(cdc, Mapping) else None cdc_ok = cdc_ok and isinstance(item, Mapping) and item.get("used") == expected if not cdc_ok: failures.append(prefix + "structural_gate:cdc") resources = receipt.get("resources") utilization = resources.get("utilization") if isinstance(resources, Mapping) else None for name in ("bram", "bram32k", "bram128k", "bram256k", "dsp"): item = utilization.get(name) if isinstance(utilization, Mapping) else None used = item.get("used") if isinstance(item, Mapping) else None if not isinstance(used, int) or isinstance(used, bool) or used < 0: failures.append(prefix + f"resource:{name}:{used}") for name, expected in { "pad": len(active_pin_contract()), "ireg": EXPECTED_CDC_INPUT_REGISTERS, }.items(): item = utilization.get(name) if isinstance(utilization, Mapping) else None used = item.get("used") if isinstance(item, Mapping) else None if used != expected or isinstance(used, bool): failures.append(prefix + f"resource:{name}:{used}") timing = receipt.get("timing") if not isinstance(timing, Mapping): failures.append(prefix + "timing") else: for name in ("fmax_mhz", "worst_setup_slack_ns", "worst_hold_slack_ns"): value = timing.get(name) if not isinstance(value, (int, float)) or isinstance(value, bool) or value <= 0: failures.append(prefix + f"timing:{name}") if timing.get("error_count") != 0: failures.append(prefix + "timing:error_count") routed_pins = receipt.get("post_route_pin_gate") if isinstance(routed_pins, Mapping): if routed_pins.get("row_count") != len(active_pin_contract()): failures.append(prefix + "post_route_pin_count") observed = routed_pins.get("observed") expected_pins = { signal: ( expected["location"], expected["direction"], "LVCMOS33", expected["pull_type"], ) for signal, expected in active_pin_contract().items() } for signal, expected in expected_pins.items(): row = observed.get(signal) if isinstance(observed, Mapping) else None values = ( row.get("location"), row.get("direction"), row.get("io_standard"), row.get("pull_type"), ) if isinstance(row, Mapping) else None if values != expected: failures.append(prefix + f"post_route_pin:{signal}") for phase_name in ("syn", "phy", "bitgen"): phase = receipt.get(phase_name) if ( not isinstance(phase, Mapping) or phase.get("status") != "pass" or phase.get("returncode") != 0 or phase.get("log_has_error") is not False or phase.get("critical_warning_count") != 0 ): failures.append(prefix + f"phase:{phase_name}") bitstream = receipt.get("bitstream") if not isinstance(bitstream, Mapping) or not isinstance(bitstream.get("size"), int) or bitstream.get("size") <= 0: failures.append(prefix + "bitstream_artifact") else: path = Path(str(bitstream.get("path", ""))) if not path.is_file() or path.stat().st_size != bitstream.get("size"): failures.append(prefix + "bitstream_path") elif sha256_file(path) != receipt.get("bitstream_sha256"): failures.append(prefix + "bitstream_file_hash") return failures def _offline_final_failures( receipt: Mapping[str, Any], *, expected_commit: str, expected_project_config_sha256: str, expected_td_source_manifest_sha256: str, ) -> list[str]: failures: list[str] = [] if receipt.get("schema") != OFFLINE_RECEIPT_SCHEMA: failures.append("offline:schema") if receipt.get("status") != "pass" or receipt_commit_full(receipt) != expected_commit: failures.append("offline:status_or_commit") if receipt.get("project_config_sha256") != expected_project_config_sha256: failures.append("offline:project_config_sha256") if receipt.get("td_source_manifest_sha256") != expected_td_source_manifest_sha256: failures.append("offline:td_source_manifest_sha256") source = receipt.get("source_state") if ( not isinstance(source, Mapping) or source.get("clean") is not True or not receipt_commit_matches(source, expected_commit) or source.get("project_config_sha256") != expected_project_config_sha256 or source.get("td_source_manifest_sha256") != expected_td_source_manifest_sha256 ): failures.append("offline:source_state") layers = receipt.get("layers") required = receipt.get("required_layers") if required != ["source_integrity", "unit", "hdl_sim", "formal"]: failures.append("offline:required_layers") for name in required if isinstance(required, list) else []: layer = layers.get(name) if isinstance(layers, Mapping) else None if not isinstance(layer, Mapping) or layer.get("status") != "pass": failures.append(f"offline:layer:{name}") if receipt.get("failures") != []: failures.append("offline:failures") return failures def _package_final_failures( receipt: Mapping[str, Any], *, expected_commit: str, expected_project_config_sha256: str, expected_td_source_manifest_sha256: str, expected_bitstream_sha256: str, expected_primary_td_receipt_sha256: str, expected_confirmation_td_receipt_sha256: str, ) -> list[str]: failures: list[str] = [] expected_verification_run_id = receipt.get("verification_run_id") if receipt.get("schema") != PACKAGE_RECEIPT_SCHEMA: failures.append("package:schema") if receipt.get("status") != "pass" or receipt_commit_full(receipt) != expected_commit: failures.append("package:status_or_commit") if receipt.get("project_config_sha256") != expected_project_config_sha256: failures.append("package:project_config_sha256") if receipt.get("td_source_manifest_sha256") != expected_td_source_manifest_sha256: failures.append("package:td_source_manifest_sha256") if receipt.get("bitstream_sha256") != expected_bitstream_sha256: failures.append("package:bitstream_sha256") if not re.fullmatch( r"[0-9a-f]{32}", str(expected_verification_run_id or "") ): failures.append("package:verification_run_id") if receipt.get("delivery_mode") != "normal_dual_td": failures.append("package:delivery_mode") if receipt.get("failures") != []: failures.append("package:failures") if receipt.get("verification_complete") is not True: failures.append("package:verification_incomplete") if receipt.get("confirmation_td_present") is not True: failures.append("package:confirmation_td_missing") if receipt.get("validation_status") != "pass": failures.append("package:validation_incomplete") if receipt.get("packaged_selftest_status") != "pass": failures.append("package:packaged_selftest") selftest = receipt.get("selftest") if not isinstance(selftest, Mapping) or selftest.get("status") != "pass" or selftest.get("returncode") != 0: failures.append("package:selftest") package_dir = Path(str(receipt.get("package_dir", ""))) info_path = package_dir / "package-info.json" bitstream = package_dir / "fw.bit" primary_path = package_dir / "evidence" / "td-primary-receipt.json" confirmation_path = package_dir / "evidence" / "td-confirmation-receipt.json" validation_path = package_dir / "evidence" / "validation-summary.json" packaged_selftest_path = package_dir / "evidence" / "package-selftest-result.json" for relative in package_required_files(confirmation_td_present=True): if not (package_dir / relative).is_file(): failures.append(f"package:required_file:{relative}") loaded: dict[str, Mapping[str, Any]] = {} for label, path in ( ("info", info_path), ("primary_td", primary_path), ("confirmation_td", confirmation_path), ("validation", validation_path), ("packaged_selftest", packaged_selftest_path), ): if not path.is_file(): continue try: loaded[label] = load_receipt(path) except (OSError, UnicodeError, json.JSONDecodeError, ValueError): failures.append(f"package:{label}_unreadable") info = loaded.get("info", {}) primary_td = loaded.get("primary_td", {}) confirmation_td = loaded.get("confirmation_td", {}) validation = loaded.get("validation", {}) packaged_selftest = loaded.get("packaged_selftest", {}) if info: if ( info.get("schema") != "prod2u-p4-normal-v3-folder-package-info-v3" or info.get("profile") != RUNTIME_PROFILE or info.get("verification_run_id") != expected_verification_run_id or info.get("bitstream_sha256") != expected_bitstream_sha256 ): failures.append("package:info_binding") if not receipt_commit_matches(info, expected_commit): failures.append("package:info_commit_binding") if info.get("project_config_sha256") != expected_project_config_sha256: failures.append("package:info_project_config_sha256") if info.get("td_source_manifest_sha256") != expected_td_source_manifest_sha256: failures.append("package:info_td_source_manifest_sha256") if info.get("delivery_mode") != "normal_dual_td": failures.append("package:info_delivery_mode") if info.get("verification_complete") is not True: failures.append("package:info_verification_incomplete") if info.get("confirmation_td_present") is not True: failures.append("package:info_confirmation_td_missing") if bitstream.is_file(): if sha256_file(bitstream) != expected_bitstream_sha256: failures.append("package:file_hash") actual_hashes = { "package_info_sha256": sha256_file(info_path) if info_path.is_file() else None, "td_receipt_sha256": sha256_file(primary_path) if primary_path.is_file() else None, "confirmation_td_receipt_sha256": ( sha256_file(confirmation_path) if confirmation_path.is_file() else None ), "validation_summary_sha256": ( sha256_file(validation_path) if validation_path.is_file() else None ), "package_selftest_result_sha256": ( sha256_file(packaged_selftest_path) if packaged_selftest_path.is_file() else None ), } for field, actual in actual_hashes.items(): if field in receipt and receipt.get(field) != actual: failures.append(f"package:receipt_hash:{field}") for field in ( "td_receipt_sha256", "confirmation_td_receipt_sha256", "validation_summary_sha256", "package_selftest_result_sha256", ): if info and info.get(field) != actual_hashes[field]: failures.append(f"package:info_hash:{field}") if actual_hashes["td_receipt_sha256"] != expected_primary_td_receipt_sha256: failures.append("package:primary_td_external_binding") if ( actual_hashes["confirmation_td_receipt_sha256"] != expected_confirmation_td_receipt_sha256 ): failures.append("package:confirmation_td_external_binding") actual_files = { path.relative_to(package_dir).as_posix(): sha256_file(path) for path in sorted(package_dir.rglob("*")) if path.is_file() and path not in { info_path, package_dir / "package_manifest.json", packaged_selftest_path, } } if not info or info.get("file_sha256") != actual_files: failures.append("package:file_manifest:info") if receipt.get("package_file_sha256") != actual_files: failures.append("package:file_manifest:receipt") if receipt.get("package_file_manifest_sha256") != canonical_sha256(actual_files): failures.append("package:file_manifest:digest") if primary_td: if ( not receipt_commit_matches(primary_td, expected_commit) or primary_td.get("verification_run_id") != expected_verification_run_id or primary_td.get("bitstream_sha256") != expected_bitstream_sha256 or primary_td.get("project_config_sha256") != expected_project_config_sha256 or primary_td.get("td_source_manifest_sha256") != expected_td_source_manifest_sha256 or info.get("synthesis_input_hash") != primary_td.get("synthesis_input_hash") ): failures.append("package:primary_td_binding") if confirmation_td: if ( not receipt_commit_matches(confirmation_td, expected_commit) or confirmation_td.get("verification_run_id") != expected_verification_run_id or not re.fullmatch(r"[0-9a-f]{64}", str(confirmation_td.get("bitstream_sha256", ""))) or confirmation_td.get("project_config_sha256") != expected_project_config_sha256 or confirmation_td.get("td_source_manifest_sha256") != expected_td_source_manifest_sha256 or info.get("confirmation_bitstream_sha256") != confirmation_td.get("bitstream_sha256") or info.get("confirmation_synthesis_input_hash") != confirmation_td.get("synthesis_input_hash") ): failures.append("package:confirmation_td_binding") if validation: if ( validation.get("schema") != "prod2u-p4-normal-v3-validation-summary-v1" or validation.get("verification_run_id") != expected_verification_run_id or not receipt_commit_matches(validation, expected_commit) or validation.get("bitstream_sha256") != expected_bitstream_sha256 or validation.get("delivery_mode") != "normal_dual_td" or validation.get("verification_complete") is not True or validation.get("confirmation_td_present") is not True ): failures.append("package:validation_binding") if validation_layer_summary(validation.get("layers")) != "pass": failures.append("package:validation_layers") if ( not packaged_selftest or packaged_selftest.get("status") != "pass" or packaged_selftest.get("returncode") != 0 ): failures.append("package:packaged_selftest_content") return failures def cmd_final_gate(args: argparse.Namespace) -> int: try: verification_run_id = normalize_verification_run_id( args.verification_run_id ) except ValueError as exc: return _emit( {"status": "fail", "reason": str(exc)}, args, "p4-normal-v3-final-gate", ) try: paths = { "offline": resolve_input_receipt(args.offline_receipt), "td": resolve_input_receipt(args.td_receipt), "td_confirmation": resolve_input_receipt(args.confirmation_td_receipt), "package": resolve_input_receipt(args.package_receipt), } except ValueError as exc: return _emit({"status": "fail", "reason": str(exc)}, args, "p4-normal-v3-final-gate") try: child_receipts = {name: load_receipt(path) for name, path in paths.items()} except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as exc: return _emit( {"status": "fail", "reason": f"input_receipt_unreadable:{exc}"}, args, "p4-normal-v3-final-gate", ) state = source_state() expected_commit = state.get("commit") if ( state.get("status") != "pass" or state.get("clean") is not True or not FULL_COMMIT_RE.fullmatch(str(expected_commit)) or not re.fullmatch(r"[0-9a-f]{64}", str(state.get("project_config_sha256"))) or not re.fullmatch(r"[0-9a-f]{64}", str(state.get("td_source_manifest_sha256"))) ): failures = ["final_source_state_not_clean"] else: failures = [] failures.extend( _offline_final_failures( child_receipts["offline"], expected_commit=str(expected_commit), expected_project_config_sha256=str(state.get("project_config_sha256")), expected_td_source_manifest_sha256=str(state.get("td_source_manifest_sha256")), ) ) failures.extend( _td_final_failures( child_receipts["td"], label="td", expected_commit=str(expected_commit), expected_project_config_sha256=str(state.get("project_config_sha256")), expected_td_source_manifest_sha256=str(state.get("td_source_manifest_sha256")), ) ) failures.extend( _td_final_failures( child_receipts["td_confirmation"], label="td_confirmation", expected_commit=str(expected_commit), expected_project_config_sha256=str(state.get("project_config_sha256")), expected_td_source_manifest_sha256=str(state.get("td_source_manifest_sha256")), ) ) for name, receipt in child_receipts.items(): if receipt.get("verification_run_id") != verification_run_id: failures.append(f"verification_run_id_mismatch:{name}") primary = child_receipts["td"] confirmation = child_receipts["td_confirmation"] package = child_receipts["package"] failures.extend( _package_final_failures( package, expected_commit=str(expected_commit), expected_project_config_sha256=str(state.get("project_config_sha256")), expected_td_source_manifest_sha256=str(state.get("td_source_manifest_sha256")), expected_bitstream_sha256=str(primary.get("bitstream_sha256", "")), expected_primary_td_receipt_sha256=sha256_file(paths["td"]), expected_confirmation_td_receipt_sha256=sha256_file( paths["td_confirmation"] ), ) ) if primary.get("synthesis_input_hash") != confirmation.get("synthesis_input_hash"): failures.append("td_synthesis_input_hash_mismatch") if ( not valid_td_run_id(primary.get("run_id")) or not valid_td_run_id(confirmation.get("run_id")) or primary.get("run_id") == confirmation.get("run_id") ): failures.append("td_run_id_not_independent") primary_work_root = normalized_td_work_root(primary.get("work_root")) confirmation_work_root = normalized_td_work_root(confirmation.get("work_root")) if ( primary_work_root is None or confirmation_work_root is None or primary_work_root == confirmation_work_root ): failures.append("td_work_root_not_independent") if primary.get("td_tool") != confirmation.get("td_tool"): failures.append("td_tool_mismatch") if primary.get("synthesis_input_manifest") != confirmation.get("synthesis_input_manifest"): failures.append("td_synthesis_input_manifest_mismatch") if primary.get("bitstream_sha256") != package.get("bitstream_sha256"): failures.append("package_bitstream_mismatch") payload = { "schema": "prod2u-p4-normal-v3-final-gate-v3", "status": "pass" if not failures else "fail", "generated_at": utc_now(), "verification_run_id": verification_run_id, "commit": expected_commit, "commit_full": expected_commit, "canonical_bitstream_build": "primary", "primary_bitstream_sha256": primary.get("bitstream_sha256"), "confirmation_bitstream_sha256": confirmation.get("bitstream_sha256"), "bitstream_hash_equal": primary.get("bitstream_sha256") == confirmation.get("bitstream_sha256"), "commit_short": str(expected_commit)[:8], "project_config_sha256": state.get("project_config_sha256"), "td_source_manifest_sha256": state.get("td_source_manifest_sha256"), "source_state": state, "child_receipts": { name: {"path": str(paths[name]), "sha256": sha256_file(paths[name])} for name in paths }, "bitstream_sha256": primary.get("bitstream_sha256"), "synthesis_input_hash": primary.get("synthesis_input_hash"), "failures": sorted(set(failures)), "safety": dict(SAFETY_BOUNDARY), "authority_boundary": ( "This receipt aggregates offline, two independent TD builds, and package evidence. " "It does not prove board programming or mechanical direction." ), } return _emit(payload, args, "p4-normal-v3-final-gate") def _common_output_options(parser: argparse.ArgumentParser) -> None: parser.add_argument("--json", action="store_true") parser.add_argument("--report-file", type=Path) def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__) sub = parser.add_subparsers(dest="command", required=True) offline = sub.add_parser("p4-normal-v3-strict-offline-gate", help="run every required offline Normal v3 layer") offline.add_argument("--work-root", type=Path, required=True) offline.add_argument("--verification-run-id", required=True) _common_output_options(offline) offline.set_defaults(func=cmd_strict_offline) hdl = sub.add_parser("hdl-sim", help="run registered Icarus, Verilator, or cocotb targets") hdl.add_argument("--run", action="store_true") hdl.add_argument("--backend", choices=("icarus", "verilator", "cocotb", "all"), default="icarus") hdl.add_argument("--work-root", type=Path) hdl.add_argument("--verification-run-id", required=True) _common_output_options(hdl) hdl.set_defaults(func=cmd_hdl_sim) formal = sub.add_parser("formal", help="run all registered Normal v3 formal targets") formal.add_argument("--run", action="store_true") formal.add_argument("--work-root", type=Path) formal.add_argument("--verification-run-id", required=True) _common_output_options(formal) formal.set_defaults(func=cmd_formal) td = sub.add_parser("td-build", help="build the sole production TD top") td.add_argument("--run", action="store_true") td.add_argument("--top", choices=(PROFILE,), default=PROFILE) td.add_argument("--work-root", type=Path) td.add_argument("--verification-run-id", required=True) _common_output_options(td) td.set_defaults(func=cmd_td_build) package = sub.add_parser("package-selftest", help="validate a folder delivery without hardware access") package.add_argument("--package-dir", type=Path, required=True) package.add_argument("--verification-run-id", required=True) _common_output_options(package) package.set_defaults(func=cmd_package_selftest) final = sub.add_parser("p4-normal-v3-final-gate", help="aggregate clean offline, TD, and package receipts") final.add_argument("--offline-receipt", type=Path, required=True) final.add_argument("--td-receipt", type=Path, required=True, help="optimized production O-A receipt") final.add_argument("--confirmation-td-receipt", type=Path, required=True, help="independent optimized production O-B receipt") final.add_argument("--package-receipt", type=Path, required=True) final.add_argument("--verification-run-id", required=True) _common_output_options(final) final.set_defaults(func=cmd_final_gate) return parser def main(argv: Sequence[str] | None = None) -> int: args = build_parser().parse_args(argv) ensure_safe_sys_executable() return int(args.func(args)) if __name__ == "__main__": raise SystemExit(main())