run_6400_td.py 25 KB

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