run_6400_td.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. #!/usr/bin/env python3
  2. """Run clean, source-bound TD synthesis, place/route, and bit generation."""
  3. from __future__ import annotations
  4. import argparse
  5. from datetime import datetime, timezone
  6. import hashlib
  7. import json
  8. import os
  9. from pathlib import Path
  10. import re
  11. import shutil
  12. import subprocess
  13. import sys
  14. import time
  15. import signal
  16. ROOT = Path(__file__).resolve().parents[1]
  17. if str(ROOT) not in sys.path:sys.path.insert(0,str(ROOT))
  18. from tools.source_identity import source_identity
  19. DEFAULT_PROFILE = "6400-front-rear"
  20. HARDWARE_PROFILES = {
  21. "mrdimm-chamber": {
  22. "project":"projects/mrdimm-chamber/project.json",
  23. "closure":"products/mrdimm-chamber/source-closure.json",
  24. "td_project":"td/prod2u_mrdimm.prj",
  25. "td_files":("td/syn/prod2u_mrdimm.tcl","td/phy/prod2u_mrdimm.tcl","td/bitgen/prod2u_mrdimm.tcl"),
  26. "constraints":("constraints/prod2u_mrdimm.adc","constraints/prod2u_mrdimm.sdc"),
  27. "artifact_basename":"prod2u_mrdimm","production":True,"stimulus":False,
  28. "hardware_host_interfaces":("host_rs232",),
  29. },
  30. "6400-front-rear": {
  31. "project": "products/6400-front-rear/project.json",
  32. "closure": "products/6400-front-rear/source-closure.json",
  33. "td_project": "td/prod2u_6400_front_back.prj",
  34. "td_files": (
  35. "td/syn/prod2u_6400_front_back.tcl",
  36. "td/phy/prod2u_6400_front_back.tcl",
  37. "td/bitgen/prod2u_6400_front_back.tcl",
  38. ),
  39. "artifact_basename": "prod2u_6400_front_back",
  40. "production": True,
  41. "stimulus": False,
  42. "hardware_host_interfaces": ("host_rs232", "host_i2c_con36_logic_bound"),
  43. },
  44. }
  45. # Backward-compatible aliases for callers importing the production defaults.
  46. PROJECT = ROOT / str(HARDWARE_PROFILES[DEFAULT_PROFILE]["project"])
  47. CLOSURE = ROOT / str(HARDWARE_PROFILES[DEFAULT_PROFILE]["closure"])
  48. TD_PROJECT = str(HARDWARE_PROFILES[DEFAULT_PROFILE]["td_project"])
  49. TD_FILES = tuple(HARDWARE_PROFILES[DEFAULT_PROFILE]["td_files"])
  50. CONSTRAINT_FILES = (
  51. "constraints/prod2u_6400_front_back.adc",
  52. "constraints/prod2u_6400_front_back.sdc",
  53. )
  54. EXPECTED_UNBOUND_PORTS: tuple[str, ...] = ()
  55. def sha256(path: Path) -> str:
  56. digest = hashlib.sha256()
  57. with path.open("rb") as stream:
  58. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  59. digest.update(chunk)
  60. return digest.hexdigest()
  61. def git(*args: str) -> str:
  62. return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
  63. def _load_inherited_json(path: Path, list_key: str, additional_key: str) -> tuple[list[str], list[str]]:
  64. payload = json.loads(path.read_text(encoding="utf-8"))
  65. inputs = [str(path.relative_to(ROOT))]
  66. values: list[str] = []
  67. inherited = payload.get("inherits")
  68. if inherited:
  69. parent_values, parent_inputs = _load_inherited_json(
  70. ROOT / inherited, list_key, additional_key
  71. )
  72. values.extend(parent_values)
  73. inputs.extend(parent_inputs)
  74. values.extend(payload.get(list_key, payload.get(additional_key, [])))
  75. return values, inputs
  76. def source_closure(profile_name: str) -> tuple[list[str], list[str]]:
  77. profile = HARDWARE_PROFILES[profile_name]
  78. return _load_inherited_json(ROOT / str(profile["closure"]), "sources", "additional_sources")
  79. def project_inputs(path: Path) -> list[str]:
  80. payload = json.loads(path.read_text(encoding="utf-8"))
  81. paths = [str(path.relative_to(ROOT))]
  82. if payload.get("inherits"):
  83. paths.extend(project_inputs(ROOT / payload["inherits"]))
  84. return paths
  85. def profile_receipt_fields(profile_name: str) -> dict[str, object]:
  86. profile = HARDWARE_PROFILES[profile_name]
  87. return {
  88. "profile": profile_name,
  89. "firmware_role": "production" if profile["production"] else "identification",
  90. "production": bool(profile["production"]),
  91. "stimulus": bool(profile["stimulus"]),
  92. "simulation_only": False,
  93. "artifact_basename": str(profile["artifact_basename"]),
  94. "hardware_host_interfaces": list(profile["hardware_host_interfaces"]),
  95. }
  96. def input_manifest(profile_name: str = DEFAULT_PROFILE) -> dict[str, str]:
  97. profile = HARDWARE_PROFILES[profile_name]
  98. sources, closure_inputs = source_closure(profile_name)
  99. project_path = ROOT / str(profile["project"])
  100. paths = [
  101. *sources,
  102. *profile.get("constraints",CONSTRAINT_FILES),
  103. str(profile["td_project"]),
  104. *profile["td_files"],
  105. *project_inputs(project_path),
  106. *closure_inputs,
  107. ]
  108. # Receipts are a cross-platform contract; never let a Windows-style
  109. # separator leak into the canonical input manifest.
  110. paths = [item.replace("\\", "/") for item in paths]
  111. paths = list(dict.fromkeys(paths))
  112. missing = [item for item in paths if not (ROOT / item).is_file()]
  113. if missing:
  114. raise RuntimeError(f"source closure contains missing inputs: {missing}")
  115. return {item: sha256(ROOT / item) for item in paths}
  116. def run_stage(name: str, command: list[str], cwd: Path, env: dict[str, str], timeout: float | None = None) -> dict[str, object]:
  117. log_path = cwd / f"{name}.log"
  118. started = time.monotonic()
  119. with log_path.open("wb") as log:
  120. limit=timeout if timeout is not None else {"syn":1200,"phy":1800,"bitgen":600}[name]
  121. process=subprocess.Popen(command,cwd=cwd,env=env,stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
  122. timed_out=False
  123. try:code=process.wait(timeout=limit)
  124. except subprocess.TimeoutExpired:
  125. timed_out=True;os.killpg(process.pid,signal.SIGKILL);process.wait();code=124
  126. duration = round(time.monotonic() - started, 3)
  127. return {
  128. "command": command,
  129. "cwd": str(cwd),
  130. "exit_code": code,
  131. "timeout_seconds": limit,
  132. "timed_out": timed_out,
  133. "duration_seconds": duration,
  134. "log": str(log_path),
  135. "log_sha256": sha256(log_path),
  136. }
  137. def first_int(text: str, patterns: tuple[str, ...]) -> int | None:
  138. for pattern in patterns:
  139. match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE)
  140. if match:
  141. return int(match.group(1))
  142. return None
  143. def first_float(text: str, patterns: tuple[str, ...]) -> float | None:
  144. for pattern in patterns:
  145. match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE)
  146. if match:
  147. return float(match.group(1))
  148. return None
  149. def parse_metrics(
  150. run_root: Path, artifact_basename: str = "prod2u_6400_front_back"
  151. ) -> dict[str, object]:
  152. area_paths = [
  153. run_root / f"phy/{artifact_basename}_phy.area",
  154. run_root / f"syn/{artifact_basename}_gate.area",
  155. ]
  156. area = "\n".join(path.read_text(encoding="utf-8", errors="replace") for path in area_paths if path.is_file())
  157. timing_path = run_root / f"phy/{artifact_basename}_pr.timing"
  158. timing = timing_path.read_text(encoding="utf-8", errors="replace") if timing_path.is_file() else ""
  159. logs = "\n".join(
  160. path.read_text(encoding="utf-8", errors="replace")
  161. for path in (run_root / "syn/syn.log", run_root / "phy/phy.log", run_root / "bitgen/bitgen.log")
  162. if path.is_file()
  163. )
  164. reported_total_luts = first_int(area, (r"^#Total_luts\s+(\d+)",))
  165. lut = first_int(area, (r"^#lut\s+(\d+)",))
  166. slice_matches = re.findall(r"(\d+)\s+mslices,\s+(\d+)\s+lslices", logs, re.IGNORECASE)
  167. mslice = int(slice_matches[-1][0]) if slice_matches else None
  168. lslice = int(slice_matches[-1][1]) if slice_matches else None
  169. violation_endpoint_counts = [
  170. int(value)
  171. for value in re.findall(r"(\d+)\s+Viol Endpoints", timing, re.IGNORECASE)
  172. ]
  173. return {
  174. "total_luts": reported_total_luts if reported_total_luts is not None else lut,
  175. "total_luts_source": "#Total_luts" if reported_total_luts is not None else "#lut_fallback",
  176. "lut": lut,
  177. "registers": first_int(area, (r"^#reg\s+(\d+)",)),
  178. "dsp": first_int(area, (r"^#dsp\s+(\d+)",)),
  179. "eram_bram": first_int(area, (r"^#(?:eram|bram)\s+(\d+)",)),
  180. "bram": first_int(area, (r"^#bram\s+(\d+)",)),
  181. "mslice": mslice,
  182. "lslice": lslice,
  183. "packed_slices": mslice + lslice if mslice is not None and lslice is not None else None,
  184. "packed_slices_derivation": "mslice_plus_lslice",
  185. "fmax_mhz": first_float(timing, (r"Fmax[^\n]*?([0-9]+(?:\.[0-9]+)?)\s*MHz", r"([0-9]+(?:\.[0-9]+)?)\s*MHz")),
  186. "setup_slack_ns": first_float(
  187. timing,
  188. (r"^\s*SWNS\s*:\s*(-?[0-9]+(?:\.[0-9]+)?)\s*ns",),
  189. ),
  190. "hold_slack_ns": first_float(
  191. timing,
  192. (r"^\s*HWNS\s*:\s*(-?[0-9]+(?:\.[0-9]+)?)\s*ns",),
  193. ),
  194. "setup_total_negative_slack_ns": first_float(
  195. timing,
  196. (r"^\s*SWNS\s*:\s*-?[0-9]+(?:\.[0-9]+)?\s*ns,\s*STNS\s*:\s*(-?[0-9]+(?:\.[0-9]+)?)\s*ns",),
  197. ),
  198. "hold_total_negative_slack_ns": first_float(
  199. timing,
  200. (r"^\s*HWNS\s*:\s*-?[0-9]+(?:\.[0-9]+)?\s*ns,\s*HTNS\s*:\s*(-?[0-9]+(?:\.[0-9]+)?)\s*ns",),
  201. ),
  202. "violation_endpoint_counts": violation_endpoint_counts,
  203. "all_violation_endpoint_counts_zero": all(
  204. value == 0 for value in violation_endpoint_counts
  205. ),
  206. "area_reports": [str(path) for path in area_paths if path.is_file()],
  207. "timing_report": str(timing_path) if timing_path.is_file() else None,
  208. }
  209. def warning_audit(stage_records: dict[str, dict[str, object]]) -> dict[str, object]:
  210. lines: list[str] = []
  211. blocking: list[str] = []
  212. unbound_ports: set[str] = set()
  213. severity = re.compile(
  214. r"^\s*(?:(?:[A-Z][A-Z0-9_-]*-\d+)\s+)?"
  215. r"(?:CRITICAL-WARNING|WARNING|ERROR|FATAL)\s*:",
  216. re.IGNORECASE,
  217. )
  218. noteworthy = re.compile(
  219. r"Bitgen will abort|No ADC ports:|\bunrouted\b|\bviolations?\b|"
  220. r"\bunconstrained\b|\bunassigned\b|\blatch\b|\bloop\b",
  221. re.IGNORECASE,
  222. )
  223. blocker_patterns = (
  224. # TD may exit zero and emit a bitstream after silently tying an
  225. # undriven command/status net low. Such a netlist is not functional.
  226. re.compile(r"\bUndriven (?:net|pin)\s*:|\bdoes not have a driver\b", re.IGNORECASE),
  227. re.compile(
  228. r"^\s*(?:(?:[A-Z][A-Z0-9_-]*-\d+)\s+)?(?:ERROR|FATAL)\s*:",
  229. re.IGNORECASE,
  230. ),
  231. re.compile(r"^\s*\[(?:ERROR|FATAL)\]", re.IGNORECASE),
  232. re.compile(
  233. r"\b(?:synthesis|placement|place\s*&\s*route|routing|route|fit|bitgen)"
  234. r"\s+(?:failed|failure)\b",
  235. re.IGNORECASE,
  236. ),
  237. re.compile(r"\b(?:setup|hold|timing)\s+(?:check\s+)?(?:failed|failure)\b", re.IGNORECASE),
  238. re.compile(r"(?:\b[1-9]\d*\s+unrouted\b|\bunrouted\s*[:=]\s*[1-9]\d*)", re.IGNORECASE),
  239. )
  240. for record in stage_records.values():
  241. log = Path(str(record["log"]))
  242. for line in log.read_text(encoding="utf-8", errors="replace").splitlines():
  243. if "No ADC ports:" in line:
  244. suffix = line.split("No ADC ports:", 1)[1]
  245. unbound_ports.update(
  246. re.findall(r"[A-Za-z_][A-Za-z0-9_]*(?:\[\d+(?::\d+)?\])?", suffix)
  247. )
  248. if severity.search(line) or noteworthy.search(line):
  249. compact = line.strip()
  250. if compact and compact not in lines:
  251. lines.append(compact)
  252. if any(pattern.search(compact) for pattern in blocker_patterns):
  253. blocking.append(compact)
  254. expected = set(EXPECTED_UNBOUND_PORTS)
  255. unexpected_unbound = sorted(unbound_ports - expected)
  256. missing_expected_unbound = sorted(expected - unbound_ports)
  257. if unexpected_unbound:
  258. blocking.append("unexpected unbound ports: " + ", ".join(unexpected_unbound))
  259. if missing_expected_unbound:
  260. blocking.append("expected unbound ports not reported: " + ", ".join(missing_expected_unbound))
  261. return {
  262. "status": "FAIL" if blocking else "PASS",
  263. "noteworthy_count": len(lines),
  264. "blocking_count": len(blocking),
  265. "expected_unbound_ports": sorted(expected),
  266. "observed_unbound_ports": sorted(unbound_ports),
  267. "unexpected_unbound_ports": unexpected_unbound,
  268. "missing_expected_unbound_ports": missing_expected_unbound,
  269. "blocking": blocking[:100],
  270. "noteworthy": lines[:300],
  271. }
  272. def timing_result(metrics: dict[str, object]) -> tuple[list[str], bool]:
  273. required_metrics = (
  274. "total_luts", "lut", "registers", "dsp", "eram_bram", "mslice",
  275. "lslice", "packed_slices", "fmax_mhz", "setup_slack_ns", "hold_slack_ns",
  276. "setup_total_negative_slack_ns", "hold_total_negative_slack_ns",
  277. )
  278. missing_metrics = [name for name in required_metrics if metrics[name] is None]
  279. timing_pass = bool(
  280. not missing_metrics
  281. and metrics["violation_endpoint_counts"]
  282. and metrics["all_violation_endpoint_counts_zero"]
  283. and metrics["fmax_mhz"] >= 25.0
  284. and metrics["setup_slack_ns"] >= 0.0
  285. and metrics["hold_slack_ns"] >= 0.0
  286. and metrics["setup_total_negative_slack_ns"] == 0.0
  287. and metrics["hold_total_negative_slack_ns"] == 0.0
  288. )
  289. return missing_metrics,timing_pass
  290. def reaudit_receipt(path: Path, output: Path) -> int:
  291. """Re-evaluate immutable native evidence; never overwrite the original receipt."""
  292. path=path.resolve();output=output.resolve()
  293. if output==ROOT or ROOT in output.parents or output==path.parent:
  294. raise ValueError('reaudit output must be new and external')
  295. old=json.loads(path.read_text(encoding='utf-8'))
  296. if old.get('schema') not in ('prod2u-6400-td-receipt-v1','prod2u-mrdimm-td-receipt-v1'):
  297. raise ValueError('unsupported native TD receipt schema')
  298. profile=old['profile'];current=input_manifest(profile)
  299. if current!=old['inputs']:raise ValueError('reaudit source inputs differ from the native build')
  300. manifest_sha=hashlib.sha256(json.dumps(current,sort_keys=True,separators=(',',':')).encode()).hexdigest()
  301. config=HARDWARE_PROFILES[profile];basename=config['artifact_basename']
  302. if old['source_manifest_sha256']!=manifest_sha or old['project_sha256']!=current[config['project']] or old['source_closure_sha256']!=current[config['closure']]:
  303. raise ValueError('reaudit input identity mismatch')
  304. if old.get('simulation_only') is not False or old.get('production') is not True or old.get('missing_outputs'):
  305. raise ValueError('reaudit requires a complete production native run')
  306. expected={'syn':path.parent/f'syn/{basename}_gate.db','phy':path.parent/f'phy/{basename}_pr.db',
  307. 'bitgen':path.parent/f'bitgen/{basename}.bit'}
  308. for name in ('syn','phy','bitgen'):
  309. stage=old['stages'][name];log=Path(stage['log'])
  310. if stage['exit_code']!=0 or stage.get('timed_out') or not expected[name].is_file():
  311. raise ValueError('reaudit cannot qualify an incomplete native stage: '+name)
  312. if sha256(log)!=stage['log_sha256']:raise ValueError('native stage log changed: '+name)
  313. if sha256(expected['bitgen'])!=old['bitstream_sha256']:raise ValueError('native bitstream changed')
  314. audit=warning_audit(old['stages']);metrics=parse_metrics(path.parent,basename)
  315. missing,timing=timing_result(metrics)
  316. status='PASS' if audit['status']=='PASS' and timing else 'FAIL'
  317. reviewed=dict(old)
  318. reviewed.update(run_id=output.name,generated_at=datetime.now(timezone.utc).isoformat(),status=status,
  319. warning_audit=audit,metrics=metrics,missing_metrics=missing,timing_pass_25mhz=timing,
  320. deployment_status='TD_QUALIFIED_HARDWARE_NOT_RUN' if status=='PASS' else 'NOT_QUALIFIED')
  321. reviewed['reaudit']={'native_run_id':old['run_id'],'native_receipt':str(path),
  322. 'native_receipt_sha256':sha256(path),'original_status':old['status'],'reviewer_source':source_identity(ROOT),
  323. 'reason':'current warning interpretation; native logs, inputs and bitstream verified and reused'}
  324. output.mkdir(parents=True,exist_ok=False)
  325. result=output/'td-receipt.json';result.write_text(json.dumps(reviewed,indent=2,sort_keys=True)+'\n')
  326. print(str(result));return 0 if status=='PASS' else 1
  327. def main(argv: list[str] | None = None) -> int:
  328. parser = argparse.ArgumentParser()
  329. parser.add_argument(
  330. "--profile", choices=tuple(HARDWARE_PROFILES), default=DEFAULT_PROFILE
  331. )
  332. parser.add_argument("--run-root", type=Path)
  333. parser.add_argument("--reaudit",type=Path,help="verify and re-audit an existing native run; no rebuild")
  334. args = parser.parse_args(argv)
  335. if args.reaudit:
  336. if args.run_root is None:parser.error('--reaudit requires a new --run-root')
  337. return reaudit_receipt(args.reaudit,args.run_root)
  338. profile_name = args.profile
  339. profile = HARDWARE_PROFILES[profile_name]
  340. project_path = ROOT / str(profile["project"])
  341. closure_path = ROOT / str(profile["closure"])
  342. artifact_basename = str(profile["artifact_basename"])
  343. td_files = tuple(profile["td_files"])
  344. td = shutil.which("td2026")
  345. local_td = ROOT / "tools/td2026"
  346. if td is None and local_td.is_file():
  347. td = str(local_td)
  348. if td is None:
  349. print("TD_MISSING: td2026 is not on PATH", file=sys.stderr)
  350. return 4
  351. identity=source_identity(ROOT)
  352. dirty_before = identity['git_status']
  353. if dirty_before:
  354. print("TD_BLOCKED: source worktree must be clean", file=sys.stderr)
  355. print(dirty_before, file=sys.stderr)
  356. return 3
  357. commit = identity['commit']
  358. tree = identity['tree']
  359. stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
  360. run_kind = profile_name+"-td"
  361. run_id = f"{run_kind}-{stamp}-{commit[:8]}"
  362. run_root = args.run_root or Path(os.environ.get("PROD2U_TD_RUN_ROOT", "/data/prod2u/cpld-runs")) / run_id
  363. for stage in ("syn", "phy", "bitgen"):
  364. (run_root / stage).mkdir(parents=True, exist_ok=False)
  365. inputs = input_manifest(profile_name)
  366. manifest_bytes = json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode()
  367. version_probe = subprocess.run([td, "-version"], capture_output=True, text=True, check=False,timeout=30)
  368. version_text = (version_probe.stdout + version_probe.stderr).strip()
  369. if not version_text:
  370. td_binary = Path("/data/anlogic/TD_Release_2026.1_SP2_NL/bin/td")
  371. binary_identity = sha256(td_binary) if td_binary.is_file() else "unavailable"
  372. version_text = (
  373. "Anlogic TD 2026.1 SP2 Linux host-mounted toolchain; "
  374. f"td_binary_sha256={binary_identity}"
  375. )
  376. env = os.environ.copy()
  377. env["PROD2U_SOURCE_ROOT"] = str(ROOT)
  378. sources,_=source_closure(profile_name)
  379. env["PROD2U_TD_SOURCE_FILES"]=" ".join("{"+p+"}" for p in sources if p.endswith('.v'))
  380. env["PATH"] = str(ROOT / "tools") + os.pathsep + env.get("PATH", "")
  381. stages: dict[str, dict[str, object]] = {}
  382. tcl = {
  383. "syn": ROOT / td_files[0],
  384. "phy": ROOT / td_files[1],
  385. "bitgen": ROOT / td_files[2],
  386. }
  387. status = "PASS"
  388. for name in ("syn", "phy", "bitgen"):
  389. stages[name] = run_stage(name, [td, str(tcl[name])], run_root / name, env)
  390. print(f"{name}: exit={stages[name]['exit_code']} duration_s={stages[name]['duration_seconds']}", flush=True)
  391. if stages[name]["exit_code"] != 0:
  392. status = "FAIL"
  393. break
  394. expected = {
  395. "syn": run_root / f"syn/{artifact_basename}_gate.db",
  396. "phy": run_root / f"phy/{artifact_basename}_pr.db",
  397. "bitgen": run_root / f"bitgen/{artifact_basename}.bit",
  398. }
  399. missing = [name for name, path in expected.items() if name in stages and stages[name]["exit_code"] == 0 and not path.is_file()]
  400. if missing:
  401. status = "FAIL"
  402. audit = warning_audit(stages)
  403. if audit["status"] != "PASS":
  404. status = "FAIL"
  405. bitstream = expected["bitgen"]
  406. metrics = parse_metrics(run_root, artifact_basename)
  407. missing_metrics,timing_pass=timing_result(metrics)
  408. if not timing_pass:
  409. status = "FAIL"
  410. receipt = {
  411. "schema": "prod2u-6400-td-receipt-v1" if profile_name==DEFAULT_PROFILE else "prod2u-mrdimm-td-receipt-v1",
  412. "run_id": run_id,
  413. "status": status,
  414. "generated_at": datetime.now(timezone.utc).isoformat(),
  415. "commit": commit,
  416. "tree": tree,
  417. "branch": identity['branch'],
  418. "source_kind":identity['source_kind'],
  419. "export_identity_sha256":identity.get('identity_file_sha256'),
  420. "clean_before": identity['clean'],
  421. "clean_after": source_identity(ROOT)['clean'],
  422. **profile_receipt_fields(profile_name),
  423. "project": str(project_path.relative_to(ROOT)),
  424. "project_sha256": sha256(project_path),
  425. "source_closure": str(closure_path.relative_to(ROOT)),
  426. "source_closure_sha256": sha256(closure_path),
  427. "source_manifest_sha256": hashlib.sha256(manifest_bytes).hexdigest(),
  428. "inputs": inputs,
  429. "tool": {
  430. "command": "td2026",
  431. "resolved": td,
  432. "version_probe_exit": version_probe.returncode,
  433. "version": version_text,
  434. "identity": "host-mounted toolchain /data/anlogic/TD_Release_2026.1_SP2_NL",
  435. "container_image_id": os.environ.get("PROD2U_CONTAINER_IMAGE_ID"),
  436. "container_digest": os.environ.get("PROD2U_CONTAINER_DIGEST"),
  437. },
  438. "safety": {"opens_serial": False, "programs_hardware": False, "jtag": False},
  439. "stages": stages,
  440. "missing_outputs": missing,
  441. "missing_metrics": missing_metrics,
  442. "warning_audit": audit,
  443. "metrics": metrics,
  444. "timing_pass_25mhz": timing_pass,
  445. "bitstream": str(bitstream) if bitstream.is_file() else None,
  446. "bitstream_sha256": sha256(bitstream) if bitstream.is_file() else None,
  447. "deployment_status": (
  448. "TD_QUALIFIED_HARDWARE_NOT_RUN" if status=="PASS" else "NOT_QUALIFIED"
  449. ),
  450. "known_unbound_ports": list(EXPECTED_UNBOUND_PORTS),
  451. }
  452. receipt_path = run_root / "td-receipt.json"
  453. receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  454. print(receipt_path)
  455. if status != "PASS":
  456. for name, record in stages.items():
  457. if record["exit_code"] != 0:
  458. log = Path(str(record["log"]))
  459. print(f"--- {name} log tail ---", file=sys.stderr)
  460. print("\n".join(log.read_text(encoding="utf-8", errors="replace").splitlines()[-120:]), file=sys.stderr)
  461. return 1
  462. print(f"TD_PASS bitstream_sha256={receipt['bitstream_sha256']}")
  463. return 0
  464. if __name__ == "__main__":
  465. raise SystemExit(main())