#!/usr/bin/env python3 """Run clean, source-bound TD synthesis, place/route, and bit generation.""" from __future__ import annotations import argparse from datetime import datetime, timezone import hashlib import json import os from pathlib import Path import re import shutil import subprocess import sys import time import signal ROOT = Path(__file__).resolve().parents[1] sys.dont_write_bytecode=True if str(ROOT) not in sys.path:sys.path.insert(0,str(ROOT)) from tools.source_identity import source_identity DEFAULT_PROFILE = "6400-front-rear" HARDWARE_PROFILES = { "mrdimm-chamber": { "project":"projects/mrdimm-chamber/project.json", "closure":"products/mrdimm-chamber/source-closure.json", "td_project":"td/prod2u_mrdimm.prj", "td_files":("td/syn/prod2u_mrdimm.tcl","td/phy/prod2u_mrdimm.tcl","td/bitgen/prod2u_mrdimm.tcl"), "constraints":("constraints/prod2u_mrdimm.adc","constraints/prod2u_mrdimm.sdc"), "artifact_basename":"prod2u_mrdimm","production":True,"stimulus":False, "hardware_host_interfaces":("host_rs232", "host_ttl"), }, "6400-front-rear": { "project": "products/6400-front-rear/project.json", "closure": "products/6400-front-rear/source-closure.json", "td_project": "td/prod2u_6400_front_back.prj", "td_files": ( "td/syn/prod2u_6400_front_back.tcl", "td/phy/prod2u_6400_front_back.tcl", "td/bitgen/prod2u_6400_front_back.tcl", ), "artifact_basename": "prod2u_6400_front_back", "production": True, "stimulus": False, "hardware_host_interfaces": ("host_rs232", "host_ttl"), }, "6400-v2": { "project": "products/6400-v2/project.json", "closure": "products/6400-v2/source-closure.json", "td_project": "td/prod2u_6400_v2.prj", "td_files": ( "td/syn/prod2u_6400_v2.tcl", "td/phy/prod2u_6400_v2.tcl", "td/bitgen/prod2u_6400_v2.tcl", ), "constraints": ("constraints/prod2u_6400_v2.adc", "constraints/prod2u_6400_v2.sdc"), "artifact_basename": "prod2u_6400_v2", "production": True, "stimulus": False, "hardware_host_interfaces": ("host_ttl", "host_rs232"), }, } # Backward-compatible aliases for callers importing the production defaults. PROJECT = ROOT / str(HARDWARE_PROFILES[DEFAULT_PROFILE]["project"]) CLOSURE = ROOT / str(HARDWARE_PROFILES[DEFAULT_PROFILE]["closure"]) TD_PROJECT = str(HARDWARE_PROFILES[DEFAULT_PROFILE]["td_project"]) TD_FILES = tuple(HARDWARE_PROFILES[DEFAULT_PROFILE]["td_files"]) CONSTRAINT_FILES = ( "constraints/prod2u_6400_front_back.adc", "constraints/prod2u_6400_front_back.sdc", ) EXPECTED_UNBOUND_PORTS: tuple[str, ...] = () def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def git(*args: str) -> str: return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip() def _load_inherited_json(path: Path, list_key: str, additional_key: str) -> tuple[list[str], list[str]]: payload = json.loads(path.read_text(encoding="utf-8")) inputs = [str(path.relative_to(ROOT))] values: list[str] = [] inherited = payload.get("inherits") if inherited: parent_values, parent_inputs = _load_inherited_json( ROOT / inherited, list_key, additional_key ) values.extend(parent_values) inputs.extend(parent_inputs) values.extend(payload.get(list_key, payload.get(additional_key, []))) return values, inputs def source_closure(profile_name: str) -> tuple[list[str], list[str]]: profile = HARDWARE_PROFILES[profile_name] return _load_inherited_json(ROOT / str(profile["closure"]), "sources", "additional_sources") def project_inputs(path: Path) -> list[str]: payload = json.loads(path.read_text(encoding="utf-8")) paths = [str(path.relative_to(ROOT))] if payload.get("inherits"): paths.extend(project_inputs(ROOT / payload["inherits"])) return paths def profile_receipt_fields(profile_name: str) -> dict[str, object]: profile = HARDWARE_PROFILES[profile_name] return { "profile": profile_name, "firmware_role": "production" if profile["production"] else "identification", "production": bool(profile["production"]), "stimulus": bool(profile["stimulus"]), "simulation_only": False, "artifact_basename": str(profile["artifact_basename"]), "hardware_host_interfaces": list(profile["hardware_host_interfaces"]), } def input_manifest(profile_name: str = DEFAULT_PROFILE) -> dict[str, str]: profile = HARDWARE_PROFILES[profile_name] sources, closure_inputs = source_closure(profile_name) project_path = ROOT / str(profile["project"]) paths = [ *sources, "VERSION", "tools/run_6400_td.py", *profile.get("constraints",CONSTRAINT_FILES), str(profile["td_project"]), *profile["td_files"], *project_inputs(project_path), *closure_inputs, ] # Receipts are a cross-platform contract; never let a Windows-style # separator leak into the canonical input manifest. paths = [item.replace("\\", "/") for item in paths] paths = list(dict.fromkeys(paths)) missing = [item for item in paths if not (ROOT / item).is_file()] if missing: raise RuntimeError(f"source closure contains missing inputs: {missing}") return {item: sha256(ROOT / item) for item in paths} def run_stage(name: str, command: list[str], cwd: Path, env: dict[str, str], timeout: float | None = None) -> dict[str, object]: log_path = cwd / f"{name}.log" started = time.monotonic() with log_path.open("wb") as log: limit=timeout if timeout is not None else {"syn":1200,"phy":1800,"bitgen":600}[name] process=subprocess.Popen(command,cwd=cwd,env=env,stdin=subprocess.DEVNULL,stdout=log,stderr=subprocess.STDOUT,start_new_session=True) timed_out=False try:code=process.wait(timeout=limit) except subprocess.TimeoutExpired: timed_out=True;os.killpg(process.pid,signal.SIGKILL);process.wait();code=124 duration = round(time.monotonic() - started, 3) return { "command": command, "cwd": str(cwd), "exit_code": code, "timeout_seconds": limit, "timed_out": timed_out, "duration_seconds": duration, "log": str(log_path), "log_sha256": sha256(log_path), } def first_int(text: str, patterns: tuple[str, ...]) -> int | None: for pattern in patterns: match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE) if match: return int(match.group(1)) return None def first_float(text: str, patterns: tuple[str, ...]) -> float | None: for pattern in patterns: match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE) if match: return float(match.group(1)) return None def parse_metrics( run_root: Path, artifact_basename: str = "prod2u_6400_front_back" ) -> dict[str, object]: area_paths = [ run_root / f"phy/{artifact_basename}_phy.area", run_root / f"syn/{artifact_basename}_gate.area", ] area = "\n".join(path.read_text(encoding="utf-8", errors="replace") for path in area_paths if path.is_file()) timing_path = run_root / f"phy/{artifact_basename}_pr.timing" timing = timing_path.read_text(encoding="utf-8", errors="replace") if timing_path.is_file() else "" logs = "\n".join( path.read_text(encoding="utf-8", errors="replace") for path in (run_root / "syn/syn.log", run_root / "phy/phy.log", run_root / "bitgen/bitgen.log") if path.is_file() ) reported_total_luts = first_int(area, (r"^#Total_luts\s+(\d+)",)) lut = first_int(area, (r"^#lut\s+(\d+)",)) slice_matches = re.findall(r"(\d+)\s+mslices,\s+(\d+)\s+lslices", logs, re.IGNORECASE) mslice = int(slice_matches[-1][0]) if slice_matches else None lslice = int(slice_matches[-1][1]) if slice_matches else None violation_endpoint_counts = [ int(value) for value in re.findall(r"(\d+)\s+Viol Endpoints", timing, re.IGNORECASE) ] return { "total_luts": reported_total_luts if reported_total_luts is not None else lut, "total_luts_source": "#Total_luts" if reported_total_luts is not None else "#lut_fallback", "lut": lut, "registers": first_int(area, (r"^#reg\s+(\d+)",)), "dsp": first_int(area, (r"^#dsp\s+(\d+)",)), "eram_bram": first_int(area, (r"^#(?:eram|bram)\s+(\d+)",)), "bram": first_int(area, (r"^#bram\s+(\d+)",)), "mslice": mslice, "lslice": lslice, "packed_slices": mslice + lslice if mslice is not None and lslice is not None else None, "packed_slices_derivation": "mslice_plus_lslice", "fmax_mhz": first_float(timing, (r"Fmax[^\n]*?([0-9]+(?:\.[0-9]+)?)\s*MHz", r"([0-9]+(?:\.[0-9]+)?)\s*MHz")), "setup_slack_ns": first_float( timing, (r"^\s*SWNS\s*:\s*(-?[0-9]+(?:\.[0-9]+)?)\s*ns",), ), "hold_slack_ns": first_float( timing, (r"^\s*HWNS\s*:\s*(-?[0-9]+(?:\.[0-9]+)?)\s*ns",), ), "setup_total_negative_slack_ns": first_float( timing, (r"^\s*SWNS\s*:\s*-?[0-9]+(?:\.[0-9]+)?\s*ns,\s*STNS\s*:\s*(-?[0-9]+(?:\.[0-9]+)?)\s*ns",), ), "hold_total_negative_slack_ns": first_float( timing, (r"^\s*HWNS\s*:\s*-?[0-9]+(?:\.[0-9]+)?\s*ns,\s*HTNS\s*:\s*(-?[0-9]+(?:\.[0-9]+)?)\s*ns",), ), "violation_endpoint_counts": violation_endpoint_counts, "all_violation_endpoint_counts_zero": all( value == 0 for value in violation_endpoint_counts ), "area_reports": [str(path) for path in area_paths if path.is_file()], "timing_report": str(timing_path) if timing_path.is_file() else None, } def warning_audit(stage_records: dict[str, dict[str, object]]) -> dict[str, object]: lines: list[str] = [] blocking: list[str] = [] unbound_ports: set[str] = set() severity = re.compile( r"^\s*(?:(?:[A-Z][A-Z0-9_-]*-\d+)\s+)?" r"(?:CRITICAL-WARNING|WARNING|ERROR|FATAL)\s*:", re.IGNORECASE, ) noteworthy = re.compile( r"Bitgen will abort|No ADC ports:|\bunrouted\b|\bviolations?\b|" r"\bunconstrained\b|\bunassigned\b|\blatch\b|\bloop\b", re.IGNORECASE, ) blocker_patterns = ( # TD may exit zero and emit a bitstream after silently tying an # undriven command/status net low. Such a netlist is not functional. re.compile(r"\bUndriven (?:net|pin)\s*:|\bdoes not have a driver\b", re.IGNORECASE), re.compile( r"^\s*(?:(?:[A-Z][A-Z0-9_-]*-\d+)\s+)?(?:ERROR|FATAL)\s*:", re.IGNORECASE, ), re.compile(r"^\s*\[(?:ERROR|FATAL)\]", re.IGNORECASE), re.compile( r"\b(?:synthesis|placement|place\s*&\s*route|routing|route|fit|bitgen)" r"\s+(?:failed|failure)\b", re.IGNORECASE, ), re.compile(r"\b(?:setup|hold|timing)\s+(?:check\s+)?(?:failed|failure)\b", re.IGNORECASE), re.compile(r"(?:\b[1-9]\d*\s+unrouted\b|\bunrouted\s*[:=]\s*[1-9]\d*)", re.IGNORECASE), ) for record in stage_records.values(): log = Path(str(record["log"])) for line in log.read_text(encoding="utf-8", errors="replace").splitlines(): if "No ADC ports:" in line: suffix = line.split("No ADC ports:", 1)[1] unbound_ports.update( re.findall(r"[A-Za-z_][A-Za-z0-9_]*(?:\[\d+(?::\d+)?\])?", suffix) ) if severity.search(line) or noteworthy.search(line): compact = line.strip() if compact and compact not in lines: lines.append(compact) if any(pattern.search(compact) for pattern in blocker_patterns): blocking.append(compact) expected = set(EXPECTED_UNBOUND_PORTS) unexpected_unbound = sorted(unbound_ports - expected) missing_expected_unbound = sorted(expected - unbound_ports) if unexpected_unbound: blocking.append("unexpected unbound ports: " + ", ".join(unexpected_unbound)) if missing_expected_unbound: blocking.append("expected unbound ports not reported: " + ", ".join(missing_expected_unbound)) return { "status": "FAIL" if blocking else "PASS", "noteworthy_count": len(lines), "blocking_count": len(blocking), "expected_unbound_ports": sorted(expected), "observed_unbound_ports": sorted(unbound_ports), "unexpected_unbound_ports": unexpected_unbound, "missing_expected_unbound_ports": missing_expected_unbound, "blocking": blocking[:100], "noteworthy": lines[:300], } def timing_result(metrics: dict[str, object]) -> tuple[list[str], bool]: required_metrics = ( "total_luts", "lut", "registers", "dsp", "eram_bram", "mslice", "lslice", "packed_slices", "fmax_mhz", "setup_slack_ns", "hold_slack_ns", "setup_total_negative_slack_ns", "hold_total_negative_slack_ns", ) missing_metrics = [name for name in required_metrics if metrics[name] is None] timing_pass = bool( not missing_metrics and metrics["violation_endpoint_counts"] and metrics["all_violation_endpoint_counts_zero"] and metrics["fmax_mhz"] >= 25.0 and metrics["setup_slack_ns"] >= 0.0 and metrics["hold_slack_ns"] >= 0.0 and metrics["setup_total_negative_slack_ns"] == 0.0 and metrics["hold_total_negative_slack_ns"] == 0.0 ) return missing_metrics,timing_pass def reaudit_receipt(path: Path, output: Path) -> int: """Re-evaluate immutable native evidence; never overwrite the original receipt.""" path=path.resolve();output=output.resolve() if output==ROOT or ROOT in output.parents or output==path.parent: raise ValueError('reaudit output must be new and external') old=json.loads(path.read_text(encoding='utf-8')) if old.get('schema') not in ('prod2u-6400-td-receipt-v1','prod2u-mrdimm-td-receipt-v1'): raise ValueError('unsupported native TD receipt schema') profile=old['profile'];current=input_manifest(profile) if current!=old['inputs']:raise ValueError('reaudit source inputs differ from the native build') manifest_sha=hashlib.sha256(json.dumps(current,sort_keys=True,separators=(',',':')).encode()).hexdigest() config=HARDWARE_PROFILES[profile];basename=config['artifact_basename'] if old['source_manifest_sha256']!=manifest_sha or old['project_sha256']!=current[config['project']] or old['source_closure_sha256']!=current[config['closure']]: raise ValueError('reaudit input identity mismatch') if old.get('simulation_only') is not False or old.get('production') is not True or old.get('missing_outputs'): raise ValueError('reaudit requires a complete production native run') expected={'syn':path.parent/f'syn/{basename}_gate.db','phy':path.parent/f'phy/{basename}_pr.db', 'bitgen':path.parent/f'bitgen/{basename}.bit'} for name in ('syn','phy','bitgen'): stage=old['stages'][name];log=Path(stage['log']) if stage['exit_code']!=0 or stage.get('timed_out') or not expected[name].is_file(): raise ValueError('reaudit cannot qualify an incomplete native stage: '+name) if sha256(log)!=stage['log_sha256']:raise ValueError('native stage log changed: '+name) if sha256(expected['bitgen'])!=old['bitstream_sha256']:raise ValueError('native bitstream changed') audit=warning_audit(old['stages']);metrics=parse_metrics(path.parent,basename) missing,timing=timing_result(metrics) status='PASS' if audit['status']=='PASS' and timing else 'FAIL' reviewed=dict(old) reviewed.update(run_id=output.name,generated_at=datetime.now(timezone.utc).isoformat(),status=status, warning_audit=audit,metrics=metrics,missing_metrics=missing,timing_pass_25mhz=timing, deployment_status='TD_QUALIFIED_HARDWARE_NOT_RUN' if status=='PASS' else 'NOT_QUALIFIED') reviewed['reaudit']={'native_run_id':old['run_id'],'native_receipt':str(path), 'native_receipt_sha256':sha256(path),'original_status':old['status'],'reviewer_source':source_identity(ROOT), 'reason':'current warning interpretation; native logs, inputs and bitstream verified and reused'} output.mkdir(parents=True,exist_ok=False) result=output/'td-receipt.json';result.write_text(json.dumps(reviewed,indent=2,sort_keys=True)+'\n') print(str(result));return 0 if status=='PASS' else 1 def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser() parser.add_argument( "--profile", choices=tuple(HARDWARE_PROFILES), default=DEFAULT_PROFILE ) parser.add_argument("--run-root", type=Path) parser.add_argument("--allow-dirty", action="store_true", help="allow compilation with uncommitted changes") parser.add_argument("--host-baud", type=int, choices=(921600, 460800, 230400, 115200), help="compile-time Host UART baud; default 921600, BMC remains 115200") parser.add_argument("--reaudit",type=Path,help="verify and re-audit an existing native run; no rebuild") args = parser.parse_args(argv) if args.reaudit: if args.host_baud is not None: parser.error('--host-baud applies to fresh builds, not --reaudit') if args.run_root is None:parser.error('--reaudit requires a new --run-root') return reaudit_receipt(args.reaudit,args.run_root) profile_name = args.profile if args.host_baud is not None and profile_name not in ('mrdimm-chamber', '6400-v2'): parser.error('--host-baud is supported by MRDIMM V1.2 and 6400 V2.0') host_baud = args.host_baud or 921600 clks_per_bit = (25000000 + host_baud // 2) // host_baud build_parameters = { 'clock_hz': 25000000, 'host_baud': host_baud, 'bmc_baud': 115200, 'host_clks_per_bit': clks_per_bit, 'host_actual_baud': 25000000 / clks_per_bit, 'host_baud_error_percent': (25000000 / clks_per_bit / host_baud - 1) * 100, } profile = HARDWARE_PROFILES[profile_name] project_path = ROOT / str(profile["project"]) closure_path = ROOT / str(profile["closure"]) artifact_basename = str(profile["artifact_basename"]) td_files = tuple(profile["td_files"]) local_td = ROOT / "tools/td2026" if local_td.is_file() and os.access(local_td, os.X_OK): td = str(local_td) else: td = shutil.which("td2026") if td is None: print("TD_MISSING: td2026 is not on PATH", file=sys.stderr) return 4 identity=source_identity(ROOT) dirty_before = identity['git_status'] if dirty_before and not args.allow_dirty: print("TD_BLOCKED: source worktree must be clean", file=sys.stderr) print(dirty_before, file=sys.stderr) return 3 commit = identity['commit'] tree = identity['tree'] stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") run_kind = profile_name+"-td" run_id = f"{run_kind}-{stamp}-{commit[:8]}" run_root = args.run_root or Path(os.environ.get("PROD2U_TD_RUN_ROOT", "/data/prod2u/cpld-runs")) / run_id for stage in ("syn", "phy", "bitgen"): (run_root / stage).mkdir(parents=True, exist_ok=False) inputs = input_manifest(profile_name) manifest_bytes = json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode() version_probe = subprocess.run([td, "-version"], capture_output=True, text=True, check=False,timeout=30) version_text = (version_probe.stdout + version_probe.stderr).strip() if not version_text: td_binary = Path("/data/anlogic/TD_Release_2026.1_SP2_NL/bin/td") binary_identity = sha256(td_binary) if td_binary.is_file() else "unavailable" version_text = ( "Anlogic TD 2026.1 SP2 Linux host-mounted toolchain; " f"td_binary_sha256={binary_identity}" ) env = os.environ.copy() env["PROD2U_SOURCE_ROOT"] = str(ROOT) build_include = run_root / 'build-parameters.vh' build_include.write_text('`define PROD2U_HOST_BAUD ' + str(host_baud) + '\n') env['PROD2U_BUILD_INCLUDE'] = str(build_include.resolve()) sources,_=source_closure(profile_name) env["PROD2U_TD_SOURCE_FILES"]=" ".join("{"+p+"}" for p in sources if p.endswith('.v')) env["PATH"] = str(ROOT / "tools") + os.pathsep + env.get("PATH", "") stages: dict[str, dict[str, object]] = {} tcl = { "syn": ROOT / td_files[0], "phy": ROOT / td_files[1], "bitgen": ROOT / td_files[2], } status = "PASS" for name in ("syn", "phy", "bitgen"): stages[name] = run_stage(name, [td, str(tcl[name])], run_root / name, env) print(f"{name}: exit={stages[name]['exit_code']} duration_s={stages[name]['duration_seconds']}", flush=True) if stages[name]["exit_code"] != 0: status = "FAIL" break expected = { "syn": run_root / f"syn/{artifact_basename}_gate.db", "phy": run_root / f"phy/{artifact_basename}_pr.db", "bitgen": run_root / f"bitgen/{artifact_basename}.bit", } missing = [name for name, path in expected.items() if name in stages and stages[name]["exit_code"] == 0 and not path.is_file()] if missing: status = "FAIL" audit = warning_audit(stages) if audit["status"] != "PASS": status = "FAIL" bitstream = expected["bitgen"] metrics = parse_metrics(run_root, artifact_basename) missing_metrics,timing_pass=timing_result(metrics) if not timing_pass: status = "FAIL" inputs_unchanged = inputs == input_manifest(profile_name) if not inputs_unchanged: status = "FAIL" receipt = { "schema": "prod2u-6400-td-receipt-v1" if "6400" in profile_name else "prod2u-mrdimm-td-receipt-v1", "run_id": run_id, "status": status, "generated_at": datetime.now(timezone.utc).isoformat(), "commit": commit, "tree": tree, "branch": identity['branch'], "source_kind":identity['source_kind'], "export_identity_sha256":identity.get('identity_file_sha256'), "clean_before": identity['clean'], "clean_after": source_identity(ROOT)['clean'], **profile_receipt_fields(profile_name), "project": str(project_path.relative_to(ROOT)), "project_sha256": sha256(project_path), "source_closure": str(closure_path.relative_to(ROOT)), "source_closure_sha256": sha256(closure_path), "source_manifest_sha256": hashlib.sha256(manifest_bytes).hexdigest(), "inputs": inputs, "inputs_unchanged": inputs_unchanged, "release_version": (ROOT / 'VERSION').read_text().strip(), "build_parameters": build_parameters, "build_include": str(build_include), "build_include_sha256": sha256(build_include), "build_parameters_sha256": hashlib.sha256( json.dumps(build_parameters, sort_keys=True, separators=(',', ':')).encode() ).hexdigest(), "tool": { "command": "td2026", "resolved": td, "version_probe_exit": version_probe.returncode, "version": version_text, "identity": "host-mounted toolchain /data/anlogic/TD_Release_2026.1_SP2_NL", "container_image_id": os.environ.get("PROD2U_CONTAINER_IMAGE_ID"), "container_digest": os.environ.get("PROD2U_CONTAINER_DIGEST"), }, "safety": {"opens_serial": False, "programs_hardware": False, "jtag": False}, "stages": stages, "missing_outputs": missing, "missing_metrics": missing_metrics, "warning_audit": audit, "metrics": metrics, "timing_pass_25mhz": timing_pass, "bitstream": str(bitstream) if bitstream.is_file() else None, "bitstream_sha256": sha256(bitstream) if bitstream.is_file() else None, "deployment_status": ( "TD_QUALIFIED_HARDWARE_NOT_RUN" if status=="PASS" else "NOT_QUALIFIED" ), "known_unbound_ports": list(EXPECTED_UNBOUND_PORTS), } receipt_path = run_root / "td-receipt.json" receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8") print(receipt_path) if status != "PASS": for name, record in stages.items(): if record["exit_code"] != 0: log = Path(str(record["log"])) print(f"--- {name} log tail ---", file=sys.stderr) print("\n".join(log.read_text(encoding="utf-8", errors="replace").splitlines()[-120:]), file=sys.stderr) return 1 print(f"TD_PASS bitstream_sha256={receipt['bitstream_sha256']}") return 0 if __name__ == "__main__": raise SystemExit(main())