prod2u_p4_harness.py 132 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506
  1. #!/usr/bin/env python3
  2. """Offline verification and TD build harness for Prod2U Profile 4 Normal v3."""
  3. from __future__ import annotations
  4. import argparse
  5. import hashlib
  6. import json
  7. import os
  8. import re
  9. import shutil
  10. import subprocess
  11. import sys
  12. import uuid
  13. from concurrent.futures import ThreadPoolExecutor
  14. from datetime import datetime, timezone
  15. from pathlib import Path
  16. from typing import Any, Mapping, Sequence
  17. sys.dont_write_bytecode = True
  18. ROOT = Path(__file__).resolve().parents[1]
  19. TOOLS = ROOT / "tools"
  20. if str(TOOLS) not in sys.path:
  21. sys.path.insert(0, str(TOOLS))
  22. from prod2u_p4_normal_v3_build import ( # noqa: E402
  23. PRODUCTION_RTL_SOURCES,
  24. build_synthesis_input_manifest,
  25. )
  26. PROFILE = "prod2u_p4_normal_v3"
  27. RUNTIME_PROFILE = "prod2u-p4-normal-actuator-binary921-v3"
  28. TOP_MODULE = "prod2u_p4_normal_v3_top"
  29. PIN_PROFILE = "prod2u-p4-normal-v3"
  30. TARGET_DEVICE = "EF2L45BG256B"
  31. TD_EXE = Path(r"C:\Anlogic\TD_Release_2026.1_SP1.198.412\bin\td_commands_prompt.exe")
  32. DEFAULT_TOOLCHAIN_ROOT = Path.home() / "CodexToolchains" / "CPLD" / "oss-cad-suite" / "latest"
  33. DEFAULT_VENV_ROOT = Path.home() / "CodexToolchains" / "CPLD" / "venvs"
  34. DEFAULT_TIMEOUT_SECONDS = {
  35. "icarus_compile": 120.0,
  36. "icarus_run": 180.0,
  37. "verilator": 300.0,
  38. "cocotb": 600.0,
  39. "formal": 600.0,
  40. "td": 1800.0,
  41. }
  42. FORMAL_MAX_WORKERS = 4
  43. HDL_RECEIPT_SCHEMA = "prod2u-p4-normal-v3-hdl-sim-receipt-v1"
  44. FORMAL_RECEIPT_SCHEMA = "prod2u-p4-normal-v3-formal-receipt-v1"
  45. TD_RECEIPT_SCHEMA = "prod2u-p4-normal-v3-td-build-receipt-v2"
  46. TD_BUILD_MODE_PRODUCTION = "production"
  47. RESOURCE_VARIANT_PRODUCTION = "minimal_production"
  48. OFFLINE_RECEIPT_SCHEMA = "prod2u-p4-normal-v3-strict-offline-gate-v1"
  49. PACKAGE_RECEIPT_SCHEMA = "prod2u-p4-normal-v3-package-selftest-v1"
  50. CDC_REPORT_SCHEMA = "prod2u-p4-normal-v3-cdc-v2"
  51. FSM_REPORT_SCHEMA = "prod2u-p4-normal-v3-fsm-encoding-v2"
  52. TARGET_MANIFEST_SCHEMA = "prod2u-p4-verification-target-manifest-v1"
  53. TARGET_MANIFEST_PATH = ROOT / "config" / "prod2u_p4_verification_targets_v1.json"
  54. TARGET_MANIFEST_LAYERS = ("unit", "icarus", "verilator", "cocotb", "formal")
  55. EXPECTED_CDC_SYNC_REGISTERS = frozenset(
  56. {
  57. "u_uart_rx/rx_sync_pipe[0]",
  58. "u_uart_rx/rx_sync_pipe[1]",
  59. "u_core/u_motors/u_x_axis/limit_sync_pipe[0]",
  60. "u_core/u_motors/u_x_axis/limit_sync_pipe[1]",
  61. "u_core/u_motors/u_x_axis/limit_sync_pipe[2]",
  62. "u_core/u_motors/u_y_axis/limit_sync_pipe[0]",
  63. "u_core/u_motors/u_y_axis/limit_sync_pipe[1]",
  64. "u_core/u_motors/u_y_axis/limit_sync_pipe[2]",
  65. }
  66. )
  67. EXPECTED_CDC_FALSE_PATH_ENDPOINTS = frozenset(
  68. {
  69. "u_uart_rx/rx_sync_pipe[0]",
  70. "u_core/u_motors/u_x_axis/limit_sync_pipe[0]",
  71. "u_core/u_motors/u_y_axis/limit_sync_pipe[0]",
  72. }
  73. )
  74. EXPECTED_FSM_AXES = {"x": 3, "y": 3}
  75. BUILD_ROOT_RELATIVE = Path("td") / PROFILE
  76. TD_SCRIPTS = {
  77. "syn": ROOT / "td" / "syn" / f"{PROFILE}.tcl",
  78. "phy": ROOT / "td" / "phy" / f"{PROFILE}.tcl",
  79. "bitgen": ROOT / "td" / "bitgen" / f"{PROFILE}.tcl",
  80. }
  81. SAFETY_BOUNDARY = {
  82. "opens_serial": False,
  83. "programs_hardware": False,
  84. "installs_drivers": False,
  85. }
  86. ICARUS_EXCLUDED_TESTBENCHES = {"prod2u_p4_axis_executor_z_tb"}
  87. FORBIDDEN_TD_COMMANDS = {
  88. "connect_cable",
  89. "download",
  90. "erase_flash",
  91. "open_cable",
  92. "program",
  93. "program_flash",
  94. "program_sram",
  95. "program_spibin",
  96. }
  97. def utc_now() -> str:
  98. return datetime.now(timezone.utc).isoformat()
  99. def new_td_run_id() -> str:
  100. return uuid.uuid4().hex
  101. def normalize_verification_run_id(value: str | None) -> str:
  102. normalized = uuid.uuid4().hex if value is None else str(value).strip().lower()
  103. if not re.fullmatch(r"[0-9a-f]{32}", normalized):
  104. raise ValueError("verification_run_id must be 32 lowercase hex digits")
  105. return normalized
  106. def sha256_file(path: Path) -> str:
  107. digest = hashlib.sha256()
  108. with Path(path).open("rb") as stream:
  109. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  110. digest.update(chunk)
  111. return digest.hexdigest()
  112. def td_receipt_bitstream_binding_status(receipt: Mapping[str, Any]) -> str:
  113. digest = receipt.get("bitstream_sha256")
  114. if digest is None or digest == "":
  115. return "not_run"
  116. if not re.fullmatch(r"[0-9a-f]{64}", str(digest)):
  117. return "fail"
  118. candidates: list[Mapping[str, Any]] = []
  119. direct = receipt.get("bitstream")
  120. if isinstance(direct, Mapping):
  121. candidates.append(direct)
  122. measurements = receipt.get("measurement_artifacts")
  123. measured = measurements.get("bitstream") if isinstance(measurements, Mapping) else None
  124. if isinstance(measured, Mapping):
  125. candidates.append(measured)
  126. for candidate in candidates:
  127. if candidate.get("sha256") != digest:
  128. continue
  129. path = Path(str(candidate.get("path", "")))
  130. if not path.is_file() or sha256_file(path) == digest:
  131. return "pass"
  132. return "fail"
  133. def canonical_sha256(value: object) -> str:
  134. encoded = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("ascii")
  135. return hashlib.sha256(encoded).hexdigest()
  136. def load_receipt(path: Path) -> dict[str, Any]:
  137. payload = json.loads(Path(path).read_text(encoding="utf-8-sig"))
  138. if not isinstance(payload, dict):
  139. raise ValueError(f"receipt root must be an object: {path}")
  140. return payload
  141. def load_target_manifest() -> dict[str, Any]:
  142. payload = json.loads(TARGET_MANIFEST_PATH.read_text(encoding="utf-8"))
  143. if not isinstance(payload, dict):
  144. raise ValueError("target manifest root must be an object")
  145. if payload.get("schema") != TARGET_MANIFEST_SCHEMA:
  146. raise ValueError("target manifest schema mismatch")
  147. if payload.get("version") != 1:
  148. raise ValueError("target manifest version mismatch")
  149. if payload.get("profile") != PROFILE:
  150. raise ValueError("target manifest profile mismatch")
  151. layers = payload.get("layers")
  152. if not isinstance(layers, dict) or set(layers) != set(TARGET_MANIFEST_LAYERS):
  153. raise ValueError("target manifest layers mismatch")
  154. for layer in TARGET_MANIFEST_LAYERS:
  155. values = layers.get(layer)
  156. if not isinstance(values, list) or not values:
  157. raise ValueError(f"target manifest layer must be a non-empty list: {layer}")
  158. for layer in ("unit", "icarus", "verilator", "cocotb"):
  159. values = layers[layer]
  160. if any(not isinstance(value, str) or not value for value in values):
  161. raise ValueError(f"target manifest contains invalid name: {layer}")
  162. if len(values) != len(set(values)):
  163. raise ValueError(f"target manifest contains duplicate names: {layer}")
  164. formal_names: list[str] = []
  165. for entry in layers["formal"]:
  166. if not isinstance(entry, dict) or set(entry) != {"name", "tasks"}:
  167. raise ValueError("target manifest formal entry invalid")
  168. name = entry.get("name")
  169. tasks = entry.get("tasks")
  170. if not isinstance(name, str) or not name or not isinstance(tasks, list):
  171. raise ValueError("target manifest formal entry invalid")
  172. if any(not isinstance(task, str) or not task for task in tasks):
  173. raise ValueError(f"target manifest formal task invalid: {name}")
  174. if len(tasks) != len(set(tasks)):
  175. raise ValueError(f"target manifest formal task duplicate: {name}")
  176. formal_names.append(name)
  177. if len(formal_names) != len(set(formal_names)):
  178. raise ValueError("target manifest contains duplicate formal names")
  179. return payload
  180. def _normalized_target_layer(layer: str, value: object) -> object:
  181. if layer == "formal":
  182. if isinstance(value, Mapping):
  183. items = value.items()
  184. elif isinstance(value, Sequence) and not isinstance(value, (str, bytes)):
  185. items = (
  186. (entry.get("name"), entry.get("tasks"))
  187. for entry in value
  188. if isinstance(entry, Mapping)
  189. )
  190. else:
  191. return {}
  192. normalized: dict[str, list[str]] = {}
  193. for name, tasks in items:
  194. if isinstance(name, str) and isinstance(tasks, Sequence) and not isinstance(tasks, (str, bytes)):
  195. normalized[name] = [str(task) for task in tasks]
  196. return dict(sorted(normalized.items()))
  197. if not isinstance(value, Sequence) or isinstance(value, (str, bytes)):
  198. return []
  199. return sorted(str(item) for item in value)
  200. def target_manifest_evidence(layer: str, observed: object) -> dict[str, Any]:
  201. failures: list[str] = []
  202. try:
  203. manifest = load_target_manifest()
  204. except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as exc:
  205. return {
  206. "schema": TARGET_MANIFEST_SCHEMA,
  207. "version": 1,
  208. "sha256": "0" * 64,
  209. "layer": layer,
  210. "status": "fail",
  211. "expected": {},
  212. "observed": observed,
  213. "failures": [f"target_manifest_unavailable:{type(exc).__name__}:{exc}"],
  214. }
  215. layers = manifest["layers"]
  216. manifest_sha256 = canonical_sha256(manifest)
  217. if layer == "all":
  218. expected_all = {
  219. name: _normalized_target_layer(name, layers[name])
  220. for name in TARGET_MANIFEST_LAYERS
  221. }
  222. observed_mapping = observed if isinstance(observed, Mapping) else {}
  223. observed_all = {
  224. name: _normalized_target_layer(name, observed_mapping.get(name))
  225. for name in TARGET_MANIFEST_LAYERS
  226. }
  227. for name in TARGET_MANIFEST_LAYERS:
  228. child = target_manifest_evidence(name, observed_all[name])
  229. failures.extend(child["failures"])
  230. return {
  231. "schema": TARGET_MANIFEST_SCHEMA,
  232. "version": manifest["version"],
  233. "sha256": manifest_sha256,
  234. "layer": layer,
  235. "status": "pass" if not failures else "fail",
  236. "expected": expected_all,
  237. "observed": observed_all,
  238. "failures": sorted(set(failures)),
  239. }
  240. if layer not in TARGET_MANIFEST_LAYERS:
  241. failures.append(f"target_manifest_layer_unknown:{layer}")
  242. expected = []
  243. normalized_observed = _normalized_target_layer(layer, observed)
  244. else:
  245. expected = _normalized_target_layer(layer, layers[layer])
  246. normalized_observed = _normalized_target_layer(layer, observed)
  247. if not normalized_observed:
  248. failures.append(f"target_manifest_empty_observed:{layer}")
  249. if layer == "formal":
  250. expected_names = set(expected)
  251. observed_names = set(normalized_observed)
  252. for name in sorted(expected_names - observed_names):
  253. failures.append(f"target_manifest_missing:{layer}:{name}")
  254. for name in sorted(observed_names - expected_names):
  255. failures.append(f"target_manifest_extra:{layer}:{name}")
  256. for name in sorted(expected_names & observed_names):
  257. if normalized_observed[name] != expected[name]:
  258. failures.append(f"target_manifest_task_drift:{name}")
  259. else:
  260. expected_names = set(expected)
  261. observed_names = set(normalized_observed)
  262. if len(normalized_observed) != len(observed_names):
  263. failures.append(f"target_manifest_duplicate:{layer}")
  264. for name in sorted(expected_names - observed_names):
  265. failures.append(f"target_manifest_missing:{layer}:{name}")
  266. for name in sorted(observed_names - expected_names):
  267. failures.append(f"target_manifest_extra:{layer}:{name}")
  268. return {
  269. "schema": TARGET_MANIFEST_SCHEMA,
  270. "version": manifest["version"],
  271. "sha256": manifest_sha256,
  272. "layer": layer,
  273. "status": "pass" if not failures else "fail",
  274. "expected": expected,
  275. "observed": normalized_observed,
  276. "failures": sorted(set(failures)),
  277. }
  278. def _tail(value: str, limit: int = 4000) -> str:
  279. return value[-limit:]
  280. def configured_timeout(name: str) -> float:
  281. default = DEFAULT_TIMEOUT_SECONDS[name]
  282. raw = os.environ.get(f"PROD2U_P4_TIMEOUT_{name.upper()}_SECONDS", "").strip()
  283. if not raw:
  284. return default
  285. try:
  286. value = float(raw)
  287. except ValueError:
  288. return default
  289. return value if value > 0 else default
  290. def _timeout_text(value: str | bytes | None) -> str:
  291. if isinstance(value, bytes):
  292. return value.decode(errors="replace")
  293. return value or ""
  294. def _timed_out_result(command: Sequence[str], exc: subprocess.TimeoutExpired) -> subprocess.CompletedProcess[str]:
  295. completed = subprocess.CompletedProcess(
  296. list(command),
  297. None,
  298. _timeout_text(exc.stdout or exc.output),
  299. _timeout_text(exc.stderr),
  300. )
  301. completed.timed_out = True # type: ignore[attr-defined]
  302. return completed
  303. def _run_bounded(command: Sequence[str], *, timeout_name: str, **kwargs: Any) -> subprocess.CompletedProcess[str]:
  304. try:
  305. return subprocess.run(list(command), timeout=configured_timeout(timeout_name), **kwargs)
  306. except subprocess.TimeoutExpired as exc:
  307. return _timed_out_result(command, exc)
  308. def _was_timed_out(completed: subprocess.CompletedProcess[str] | None) -> bool:
  309. return bool(completed is not None and getattr(completed, "timed_out", False))
  310. def write_json_report(payload: Mapping[str, Any], path: Path) -> None:
  311. target = Path(path)
  312. target.parent.mkdir(parents=True, exist_ok=True)
  313. target.write_text(json.dumps(dict(payload), indent=2) + "\n", encoding="utf-8", newline="\n")
  314. def _git(*args: str) -> subprocess.CompletedProcess[str]:
  315. return subprocess.run(
  316. ["git", *args],
  317. cwd=ROOT,
  318. text=True,
  319. stdout=subprocess.PIPE,
  320. stderr=subprocess.PIPE,
  321. check=False,
  322. )
  323. def source_state() -> dict[str, Any]:
  324. commit_result = _git("rev-parse", "HEAD")
  325. status_result = _git("status", "--porcelain", "--untracked-files=all")
  326. commit = commit_result.stdout.strip().lower()
  327. changes = []
  328. for line in status_result.stdout.splitlines():
  329. if not line.strip():
  330. continue
  331. relative = line[3:].replace("\\", "/") if len(line) >= 4 else line.strip()
  332. if relative == ".planning" or relative.startswith(".planning/"):
  333. continue
  334. changes.append(line)
  335. failures: list[str] = []
  336. if commit_result.returncode != 0 or not re.fullmatch(r"[0-9a-f]{40}", commit):
  337. failures.append("git_commit_unavailable")
  338. if status_result.returncode != 0:
  339. failures.append("git_status_unavailable")
  340. return {
  341. "status": "pass" if not failures else "fail",
  342. "commit": commit,
  343. "clean": status_result.returncode == 0 and not changes,
  344. "tracked_changes": changes,
  345. "failures": failures,
  346. }
  347. def current_commit() -> str:
  348. state = source_state()
  349. if state["status"] != "pass":
  350. raise RuntimeError("unable to bind verification evidence to the current Git commit")
  351. return str(state["commit"])
  352. def resolve_work_root(work_root: Path | None, *, run: bool) -> Path | None:
  353. if work_root is None:
  354. if run:
  355. raise ValueError("--work-root is required when tools are executed")
  356. return None
  357. resolved = Path(work_root).expanduser().resolve()
  358. repository = ROOT.resolve()
  359. if resolved == repository or repository in resolved.parents:
  360. raise ValueError("work root must be outside the repository")
  361. if resolved.exists() and not resolved.is_dir():
  362. raise ValueError("work root must be a directory")
  363. if run:
  364. resolved.mkdir(parents=True, exist_ok=True)
  365. return resolved
  366. def resolve_report_file(report_file: Path) -> Path:
  367. resolved = Path(report_file).expanduser().resolve()
  368. repository = ROOT.resolve()
  369. if resolved == repository or repository in resolved.parents:
  370. raise ValueError("report file must be outside the repository")
  371. return resolved
  372. def resolve_input_receipt(receipt_file: Path) -> Path:
  373. resolved = Path(receipt_file).expanduser().resolve()
  374. repository = ROOT.resolve()
  375. if resolved == repository or repository in resolved.parents:
  376. raise ValueError("input receipt must be outside the repository")
  377. if not resolved.is_file():
  378. raise ValueError(f"input receipt is missing: {resolved}")
  379. return resolved
  380. def _tool_candidates(name: str) -> list[Path]:
  381. if name == "verilator":
  382. executable_names = ["verilator_bin.exe", "verilator.exe"]
  383. else:
  384. executable_names = [name, f"{name}.exe"]
  385. roots: list[Path] = []
  386. configured = os.environ.get("OSS_CAD_SUITE_ROOT", "").strip()
  387. if configured:
  388. roots.append(Path(configured))
  389. roots.append(DEFAULT_TOOLCHAIN_ROOT)
  390. candidates: list[Path] = []
  391. for root in roots:
  392. for directory in (root / "bin", root):
  393. candidates.extend(directory / executable for executable in executable_names)
  394. return candidates
  395. def _native_verilator_binary(path: str | Path) -> str | None:
  396. candidate = Path(path).expanduser().resolve()
  397. if candidate.name.lower() not in {"verilator_bin.exe", "verilator.exe"}:
  398. return None
  399. return str(candidate) if candidate.is_file() else None
  400. def toolchain_roots() -> list[Path]:
  401. roots: list[Path] = []
  402. configured = os.environ.get("OSS_CAD_SUITE_ROOT", "").strip()
  403. if configured:
  404. roots.append(Path(configured))
  405. roots.append(DEFAULT_TOOLCHAIN_ROOT)
  406. return list(dict.fromkeys(path.expanduser().resolve() for path in roots))
  407. def resolve_tool(name: str) -> str | None:
  408. if name == "verilator":
  409. for candidate in _tool_candidates(name):
  410. resolved = _native_verilator_binary(candidate)
  411. if resolved:
  412. return resolved
  413. for executable in ("verilator_bin.exe", "verilator.exe"):
  414. located = shutil.which(executable)
  415. if located:
  416. resolved = _native_verilator_binary(located)
  417. if resolved:
  418. return resolved
  419. return None
  420. located = shutil.which(name)
  421. if located:
  422. return located
  423. for candidate in _tool_candidates(name):
  424. if candidate.is_file():
  425. return str(candidate)
  426. return None
  427. def tool_env(extra: Mapping[str, str] | None = None) -> dict[str, str]:
  428. env = os.environ.copy()
  429. path_parts: list[str] = []
  430. for root in toolchain_roots():
  431. bin_dir = root / "bin"
  432. lib_dir = root / "lib"
  433. verilator_root = root / "share" / "verilator"
  434. smtbmc = bin_dir / "yosys-smtbmc.exe.exe"
  435. if bin_dir.is_dir():
  436. path_parts.append(str(bin_dir))
  437. if lib_dir.is_dir():
  438. path_parts.append(str(lib_dir))
  439. if verilator_root.is_dir():
  440. env.setdefault("VERILATOR_ROOT", str(verilator_root))
  441. if smtbmc.is_file():
  442. env.setdefault("SMTBMC", str(smtbmc))
  443. for name in ("iverilog", "sby", "yosys"):
  444. resolved = resolve_tool(name)
  445. if resolved:
  446. path_parts.append(str(Path(resolved).parent))
  447. if path_parts:
  448. env["PATH"] = os.pathsep.join(dict.fromkeys([*path_parts, env.get("PATH", "")]))
  449. env["PYTHONDONTWRITEBYTECODE"] = "1"
  450. if extra:
  451. env.update({str(key): str(value) for key, value in extra.items()})
  452. return env
  453. def formal_tool_env(work_root: Path) -> dict[str, str]:
  454. resolved = resolve_work_root(work_root, run=True)
  455. assert resolved is not None
  456. env = tool_env()
  457. wrapper_dir = resolved / "formal-tool-wrappers"
  458. wrappers: list[Path] = []
  459. for command in ("yosys-smtbmc", "yosys-witness"):
  460. executable = next(
  461. (
  462. root / "bin" / f"{command}.exe.exe"
  463. for root in toolchain_roots()
  464. if (root / "bin" / f"{command}.exe.exe").is_file()
  465. ),
  466. None,
  467. )
  468. if executable is None:
  469. continue
  470. wrapper_dir.mkdir(parents=True, exist_ok=True)
  471. wrapper = wrapper_dir / f"{command}.cmd"
  472. wrapper.write_text(
  473. f'@echo off\r\n"{executable}" %*\r\n',
  474. encoding="ascii",
  475. newline="",
  476. )
  477. wrappers.append(wrapper)
  478. if wrappers:
  479. env["PATH"] = os.pathsep.join([str(wrapper_dir), env.get("PATH", "")])
  480. return env
  481. def active_rtl_sources() -> list[str]:
  482. return [relative for relative in PRODUCTION_RTL_SOURCES if (ROOT / relative).is_file()]
  483. def hdl_testbenches() -> list[dict[str, Any]]:
  484. rtl = active_rtl_sources()
  485. return [
  486. {
  487. "name": path.stem,
  488. "testbench": path.relative_to(ROOT).as_posix(),
  489. "sources": [*rtl, path.relative_to(ROOT).as_posix()],
  490. }
  491. for path in sorted((ROOT / "tests" / "sim").glob("*_tb.v"))
  492. if path.stem not in ICARUS_EXCLUDED_TESTBENCHES
  493. ]
  494. def cocotb_tests() -> list[dict[str, str]]:
  495. candidates = (
  496. (
  497. "prod2u_p4_normal_v3_ack_only_top_e2e",
  498. "run_prod2u_p4_normal_v3_ack_only_top_e2e.py",
  499. ),
  500. )
  501. return [
  502. {"name": name, "runner": f"tests/cocotb/{runner}"}
  503. for name, runner in candidates
  504. if (ROOT / "tests" / "cocotb" / runner).is_file()
  505. ]
  506. def _formal_tasks(path: Path) -> list[str]:
  507. tasks: list[str] = []
  508. in_tasks = False
  509. for raw_line in path.read_text(encoding="utf-8", errors="replace").splitlines():
  510. line = raw_line.strip()
  511. if line == "[tasks]":
  512. in_tasks = True
  513. continue
  514. if in_tasks and line.startswith("["):
  515. break
  516. if in_tasks and line and not line.startswith("#"):
  517. tasks.append(line.split()[0])
  518. return tasks
  519. def formal_targets() -> list[dict[str, Any]]:
  520. targets: list[dict[str, Any]] = []
  521. for path in sorted((ROOT / "tests" / "formal").glob("*.sby")):
  522. targets.append(
  523. {
  524. "name": path.stem,
  525. "sby": path.relative_to(ROOT).as_posix(),
  526. "tasks": _formal_tasks(path),
  527. }
  528. )
  529. return targets
  530. def formal_source_files(sby_file: Path) -> list[Path]:
  531. sources: list[Path] = []
  532. in_files = False
  533. for raw_line in sby_file.read_text(encoding="utf-8", errors="replace").splitlines():
  534. line = raw_line.strip()
  535. if line == "[files]":
  536. in_files = True
  537. continue
  538. if in_files and line.startswith("["):
  539. break
  540. if not in_files or not line or line.startswith("#"):
  541. continue
  542. candidate = (sby_file.parent / line.split()[0]).resolve()
  543. if candidate.suffix.casefold() in {".v", ".sv"} and candidate.is_file():
  544. sources.append(candidate)
  545. return sources
  546. def _evidence_path(path: Path) -> str:
  547. resolved = Path(path).resolve()
  548. try:
  549. return resolved.relative_to(ROOT.resolve()).as_posix()
  550. except ValueError:
  551. return str(resolved)
  552. def formal_task_engines(sby_file: Path, tasks: Sequence[str]) -> dict[str, list[str]]:
  553. task_engines: dict[str, list[str]] = {}
  554. global_engines: list[str] = []
  555. in_engines = False
  556. for raw_line in sby_file.read_text(encoding="utf-8", errors="replace").splitlines():
  557. line = raw_line.strip()
  558. if line == "[engines]":
  559. in_engines = True
  560. continue
  561. if in_engines and line.startswith("["):
  562. break
  563. if not in_engines or not line or line.startswith("#"):
  564. continue
  565. match = re.fullmatch(r"(?:(\S+)\s*:\s*)?(.+)", line)
  566. if match is None:
  567. continue
  568. task_name, engine = match.groups()
  569. normalized = engine.strip()
  570. if task_name is None:
  571. global_engines.append(normalized)
  572. else:
  573. task_engines.setdefault(task_name, []).append(normalized)
  574. names = list(tasks) or ["default"]
  575. return {
  576. name: list(task_engines.get(name, global_engines))
  577. for name in names
  578. }
  579. def formal_input_evidence(sby_file: Path, tasks: Sequence[str]) -> dict[str, Any]:
  580. sources = formal_source_files(sby_file)
  581. payload: dict[str, Any] = {
  582. "sby": {
  583. "path": _evidence_path(sby_file),
  584. "sha256": sha256_file(sby_file),
  585. },
  586. "sources": [
  587. {"path": _evidence_path(source), "sha256": sha256_file(source)}
  588. for source in sources
  589. ],
  590. "task_engines": formal_task_engines(sby_file, tasks),
  591. }
  592. payload["sha256"] = canonical_sha256(payload)
  593. return payload
  594. def formal_runtime_evidence(
  595. workdir: Path,
  596. configured_engines: Sequence[str],
  597. ) -> dict[str, Any]:
  598. texts: list[str] = []
  599. logfile = workdir / "logfile.txt"
  600. main_log = ""
  601. if logfile.is_file():
  602. main_log = logfile.read_text(encoding="utf-8", errors="replace")
  603. texts.append(main_log)
  604. if workdir.is_dir():
  605. for engine_log in sorted(workdir.glob("engine_*/logfile.txt")):
  606. texts.append(engine_log.read_text(encoding="utf-8", errors="replace"))
  607. combined = "\n".join(texts)
  608. observed_by_index: dict[int, str] = {}
  609. for match in re.finditer(r"(?im)^.*\]\s+engine_(\d+):\s+([^\r\n]+)$", main_log):
  610. index = int(match.group(1))
  611. candidate = match.group(2).strip()
  612. if candidate and index not in observed_by_index:
  613. observed_by_index[index] = candidate
  614. solvers = sorted(set(re.findall(r"(?im)\bSolver:\s*([A-Za-z0-9_.+-]+)", combined)))
  615. configured = [str(engine).strip() for engine in configured_engines if str(engine).strip()]
  616. observed = [observed_by_index[index] for index in sorted(observed_by_index)]
  617. failures: list[str] = []
  618. if not configured:
  619. failures.append("formal_engine_config_missing")
  620. if not observed:
  621. failures.append("formal_engine_observation_missing")
  622. elif set(observed) != set(configured):
  623. failures.append("formal_engine_observation_mismatch")
  624. if any(engine.split()[0].casefold() == "smtbmc" for engine in configured) and not solvers:
  625. failures.append("formal_solver_observation_missing")
  626. explicit_solvers = sorted(
  627. {
  628. parts[1].casefold()
  629. for engine in configured
  630. if len(parts := engine.split()) > 1 and parts[0].casefold() == "smtbmc"
  631. }
  632. )
  633. if explicit_solvers and set(solver.casefold() for solver in solvers) != set(explicit_solvers):
  634. failures.append("formal_solver_observation_mismatch")
  635. return {
  636. "configured_engines": configured,
  637. "observed_engines": observed,
  638. "solvers": solvers,
  639. "failures": failures,
  640. }
  641. def formal_compiled_property_counts(workdir: Path) -> dict[str, Any]:
  642. design_json = workdir / "model" / "design.json"
  643. failures: list[str] = []
  644. assertion_ids: set[str] = set()
  645. cover_ids: set[str] = set()
  646. design_sha256 = "0" * 64
  647. try:
  648. payload = json.loads(design_json.read_text(encoding="utf-8"))
  649. except (OSError, UnicodeError, json.JSONDecodeError) as exc:
  650. payload = None
  651. failures.append(f"formal_compiled_properties_unavailable:{type(exc).__name__}")
  652. if isinstance(payload, Mapping):
  653. design_sha256 = sha256_file(design_json)
  654. modules = payload.get("modules")
  655. if isinstance(modules, Sequence) and not isinstance(modules, (str, bytes)):
  656. for module in modules:
  657. if not isinstance(module, Mapping):
  658. continue
  659. module_name = str(module.get("name", "")).strip()
  660. cell_sorts = module.get("cell_sorts")
  661. if not module_name or not isinstance(cell_sorts, Sequence) or isinstance(cell_sorts, (str, bytes)):
  662. continue
  663. for cell_sort in cell_sorts:
  664. cells = cell_sort.get("cells") if isinstance(cell_sort, Mapping) else None
  665. if not isinstance(cells, Sequence) or isinstance(cells, (str, bytes)):
  666. continue
  667. for cell in cells:
  668. if not isinstance(cell, Mapping):
  669. continue
  670. parameters = cell.get("parameters")
  671. flavor = parameters.get("FLAVOR") if isinstance(parameters, Mapping) else None
  672. cell_name = str(cell.get("name", "")).strip()
  673. if not cell_name:
  674. continue
  675. property_id = f"{module_name}.{cell_name}"
  676. if flavor == "assert":
  677. assertion_ids.add(property_id)
  678. elif flavor == "cover":
  679. cover_ids.add(property_id)
  680. return {
  681. "design_json": str(design_json),
  682. "design_sha256": design_sha256,
  683. "assertion_count": len(assertion_ids),
  684. "assertion_ids": sorted(assertion_ids),
  685. "cover_count": len(cover_ids),
  686. "cover_ids": sorted(cover_ids),
  687. "failures": failures,
  688. }
  689. def formal_tool_version_evidence(
  690. name: str,
  691. executable: str,
  692. version_args: Sequence[str],
  693. env: Mapping[str, str],
  694. ) -> dict[str, Any]:
  695. path = Path(executable).resolve()
  696. failures: list[str] = []
  697. digest = "0" * 64
  698. if path.is_file():
  699. digest = sha256_file(path)
  700. else:
  701. failures.append(f"formal_tool_path_invalid:{name}")
  702. try:
  703. completed = subprocess.run(
  704. [str(path), *version_args],
  705. cwd=ROOT,
  706. env=dict(env),
  707. text=True,
  708. stdout=subprocess.PIPE,
  709. stderr=subprocess.PIPE,
  710. timeout=30,
  711. check=False,
  712. )
  713. except (OSError, subprocess.TimeoutExpired) as exc:
  714. completed = None
  715. failures.append(f"formal_tool_version_probe_failed:{name}:{type(exc).__name__}")
  716. output = "" if completed is None else "\n".join((completed.stdout, completed.stderr)).strip()
  717. version = next((line.strip() for line in output.splitlines() if line.strip()), "")
  718. if completed is not None and completed.returncode != 0:
  719. failures.append(f"formal_tool_version_probe_returncode:{name}:{completed.returncode}")
  720. if not version:
  721. failures.append(f"formal_tool_version_missing:{name}")
  722. return {
  723. "name": name,
  724. "path": str(path),
  725. "sha256": digest,
  726. "version": version,
  727. "status": "pass" if not failures else "fail",
  728. "failures": failures,
  729. }
  730. def formal_toolchain_evidence(
  731. sby: str,
  732. yosys: str,
  733. solvers: Sequence[str],
  734. work_root: Path,
  735. ) -> dict[str, Any]:
  736. env = formal_tool_env(work_root)
  737. sby_evidence = formal_tool_version_evidence("sby", sby, ["--version"], env)
  738. yosys_evidence = formal_tool_version_evidence("yosys", yosys, ["-V"], env)
  739. solver_args = {
  740. "yices": ("yices-smt2", ["--version"]),
  741. "boolector": ("boolector", ["--version"]),
  742. "z3": ("z3", ["-version"]),
  743. }
  744. solver_evidence: list[dict[str, Any]] = []
  745. failures = [*sby_evidence["failures"], *yosys_evidence["failures"]]
  746. for solver in sorted(set(str(value).casefold() for value in solvers if str(value).strip())):
  747. command, args = solver_args.get(solver, (solver, ["--version"]))
  748. executable = resolve_tool(command)
  749. if executable is None:
  750. evidence = {
  751. "name": solver,
  752. "path": "",
  753. "sha256": "0" * 64,
  754. "version": "",
  755. "status": "fail",
  756. "failures": [f"formal_solver_tool_missing:{solver}"],
  757. }
  758. else:
  759. evidence = formal_tool_version_evidence(solver, executable, args, env)
  760. solver_evidence.append(evidence)
  761. failures.extend(evidence["failures"])
  762. return {
  763. "status": "pass" if not failures else "fail",
  764. "sby": sby_evidence,
  765. "yosys": yosys_evidence,
  766. "solvers": solver_evidence,
  767. "failures": failures,
  768. }
  769. def formal_property_counts(sby_file: Path) -> dict[str, int | bool]:
  770. text = "\n".join(
  771. re.sub(r"//.*$", "", source.read_text(encoding="utf-8", errors="replace"), flags=re.MULTILINE)
  772. for source in formal_source_files(sby_file)
  773. )
  774. sby_text = sby_file.read_text(encoding="utf-8", errors="replace")
  775. mode_cover = bool(re.search(r"(?mi)^\s*mode\s+cover\s*$", sby_text))
  776. return {
  777. "assertion_count": len(re.findall(r"\bassert\s*\(", text)),
  778. "cover_count": len(re.findall(r"\bcover\s*\(", text)),
  779. "mode_cover": mode_cover,
  780. }
  781. def formal_cover_hit_count(stdout: str, stderr: str) -> int:
  782. return len(formal_cover_hit_ids(stdout, stderr))
  783. def formal_cover_hit_ids(*texts: str) -> list[str]:
  784. hits: set[str] = set()
  785. for text in texts:
  786. hits.update(
  787. re.findall(
  788. r"(?im)^\s*reached cover statement\s+(\S+)\s+at\s+\S+:\d+",
  789. text,
  790. )
  791. )
  792. return sorted(hits)
  793. def formal_task_modes(sby_file: Path, tasks: Sequence[str]) -> dict[str, str]:
  794. task_modes: dict[str, str] = {}
  795. global_mode = ""
  796. in_options = False
  797. for raw_line in sby_file.read_text(encoding="utf-8", errors="replace").splitlines():
  798. line = raw_line.strip()
  799. if line == "[options]":
  800. in_options = True
  801. continue
  802. if in_options and line.startswith("["):
  803. break
  804. if not in_options or not line or line.startswith("#"):
  805. continue
  806. match = re.fullmatch(r"(?:(\S+)\s*:\s*)?mode\s+(\S+)", line, flags=re.IGNORECASE)
  807. if match is None:
  808. continue
  809. task_name, mode = match.groups()
  810. if task_name is None:
  811. global_mode = mode.casefold()
  812. else:
  813. task_modes[task_name] = mode.casefold()
  814. names = list(tasks) or ["default"]
  815. return {
  816. name: task_modes.get(name, global_mode or ("cover" if name == "cover" else ""))
  817. for name in names
  818. }
  819. def formal_task_evidence(
  820. *,
  821. name: str,
  822. mode: str,
  823. workdir: Path,
  824. configured_engines: Sequence[str],
  825. ) -> dict[str, Any]:
  826. status_path = workdir / "status"
  827. status_raw = ""
  828. if status_path.is_file():
  829. status_raw = status_path.read_text(encoding="utf-8", errors="replace").strip()
  830. status = status_raw.split()[0].upper() if status_raw else "MISSING"
  831. trace_files = sorted(str(path) for path in workdir.rglob("*.vcd")) if workdir.is_dir() else []
  832. pass_summary = workdir / "PASS"
  833. artifact_texts = [
  834. pass_summary.read_text(encoding="utf-8", errors="replace")
  835. ] if pass_summary.is_file() else []
  836. cover_hit_ids = formal_cover_hit_ids(*artifact_texts)
  837. runtime_evidence = formal_runtime_evidence(workdir, configured_engines)
  838. compiled_properties = formal_compiled_property_counts(workdir)
  839. evidence_failures: list[str] = [
  840. *runtime_evidence["failures"],
  841. *compiled_properties["failures"],
  842. ]
  843. if status != "PASS":
  844. evidence_failures.append(f"formal_task_status_not_pass:{name}:{status}")
  845. if mode in {"prove", "bmc"} and compiled_properties["assertion_count"] <= 0:
  846. evidence_failures.append(f"formal_compiled_assertions_missing:{name}")
  847. if mode == "cover" and compiled_properties["cover_count"] <= 0:
  848. evidence_failures.append(f"formal_compiled_covers_missing:{name}")
  849. if mode == "cover":
  850. if not trace_files:
  851. evidence_failures.append(f"formal_cover_trace_missing:{name}")
  852. compiled_cover_count = int(compiled_properties["cover_count"])
  853. if len(cover_hit_ids) < compiled_cover_count:
  854. evidence_failures.append(
  855. f"formal_cover_hits_incomplete:{name}:{len(cover_hit_ids)}/{compiled_cover_count}"
  856. )
  857. if set(cover_hit_ids) != set(compiled_properties["cover_ids"]):
  858. evidence_failures.append(f"formal_cover_hit_set_mismatch:{name}")
  859. return {
  860. "name": name,
  861. "mode": mode,
  862. "status": status,
  863. "status_raw": status_raw,
  864. "status_file": str(status_path),
  865. "workdir": str(workdir),
  866. "trace_files": trace_files,
  867. "cover_hit_ids": cover_hit_ids,
  868. "configured_engines": runtime_evidence["configured_engines"],
  869. "observed_engines": runtime_evidence["observed_engines"],
  870. "solvers": runtime_evidence["solvers"],
  871. "compiled_design_json": compiled_properties["design_json"],
  872. "compiled_design_sha256": compiled_properties["design_sha256"],
  873. "compiled_assertion_count": compiled_properties["assertion_count"],
  874. "compiled_assertion_ids": compiled_properties["assertion_ids"],
  875. "compiled_cover_count": compiled_properties["cover_count"],
  876. "compiled_cover_ids": compiled_properties["cover_ids"],
  877. "evidence_failures": evidence_failures,
  878. }
  879. def _missing_tools(schema: str, layer: str, missing: Sequence[str], **extra: Any) -> dict[str, Any]:
  880. return {
  881. "schema": schema,
  882. "status": "blocked_missing_tool",
  883. "verification_layer": layer,
  884. "profile": PROFILE,
  885. "missing_tools": sorted(set(missing)),
  886. "safety": dict(SAFETY_BOUNDARY),
  887. **extra,
  888. }
  889. def _run_icarus(work_root: Path) -> dict[str, Any]:
  890. iverilog = resolve_tool("iverilog")
  891. vvp = resolve_tool("vvp")
  892. missing = [name for name, value in (("iverilog", iverilog), ("vvp", vvp)) if not value]
  893. targets = hdl_testbenches()
  894. target_manifest = target_manifest_evidence("icarus", [target["name"] for target in targets])
  895. if missing:
  896. return _missing_tools(
  897. HDL_RECEIPT_SCHEMA,
  898. "hdl_sim",
  899. missing,
  900. backend="icarus",
  901. tests=targets,
  902. target_manifest=target_manifest,
  903. )
  904. run_dir = work_root / "hdl" / "icarus"
  905. run_dir.mkdir(parents=True, exist_ok=True)
  906. results: list[dict[str, Any]] = []
  907. for target in targets:
  908. output = run_dir / f"{target['name']}.vvp"
  909. compile_command = [
  910. str(iverilog),
  911. "-g2005-sv",
  912. "-s",
  913. str(target["name"]),
  914. "-o",
  915. str(output),
  916. *[str(ROOT / source) for source in target["sources"]],
  917. ]
  918. compile_result = _run_bounded(
  919. compile_command,
  920. timeout_name="icarus_compile",
  921. cwd=run_dir,
  922. env=tool_env(),
  923. text=True,
  924. stdout=subprocess.PIPE,
  925. stderr=subprocess.PIPE,
  926. check=False,
  927. )
  928. run_result: subprocess.CompletedProcess[str] | None = None
  929. if compile_result.returncode == 0 and not _was_timed_out(compile_result):
  930. run_result = _run_bounded(
  931. [str(vvp), str(output)],
  932. timeout_name="icarus_run",
  933. cwd=run_dir,
  934. env=tool_env(),
  935. text=True,
  936. stdout=subprocess.PIPE,
  937. stderr=subprocess.PIPE,
  938. check=False,
  939. )
  940. timed_out = _was_timed_out(compile_result) or _was_timed_out(run_result)
  941. passed = not timed_out and compile_result.returncode == 0 and run_result is not None and run_result.returncode == 0
  942. results.append(
  943. {
  944. "name": target["name"],
  945. "status": "pass" if passed else ("fail_timeout" if timed_out else "fail"),
  946. "timed_out": timed_out,
  947. "compile_returncode": compile_result.returncode,
  948. "run_returncode": None if run_result is None else run_result.returncode,
  949. "compile_stdout_tail": _tail(compile_result.stdout, 2000),
  950. "compile_stderr_tail": _tail(compile_result.stderr, 2000),
  951. "run_stdout_tail": "" if run_result is None else _tail(run_result.stdout, 2000),
  952. "run_stderr_tail": "" if run_result is None else _tail(run_result.stderr, 2000),
  953. }
  954. )
  955. passed = (
  956. bool(results) and
  957. all(item["status"] == "pass" for item in results) and
  958. target_manifest["status"] == "pass"
  959. )
  960. return {
  961. "schema": HDL_RECEIPT_SCHEMA,
  962. "status": "pass" if passed else "fail",
  963. "verification_layer": "hdl_sim",
  964. "profile": PROFILE,
  965. "backend": "icarus",
  966. "work_root": str(work_root),
  967. "tests": results,
  968. "target_manifest": target_manifest,
  969. "safety": dict(SAFETY_BOUNDARY),
  970. }
  971. def _write_verilator_stubs(work_root: Path) -> Path:
  972. path = work_root / "hdl" / "verilator" / "prod2u_p4_guard_stubs.v"
  973. path.parent.mkdir(parents=True, exist_ok=True)
  974. path.write_text(
  975. "/* verilator lint_off DECLFILENAME */\n"
  976. "module prod2u_p4_solenoid_polarity_must_be_confirmed(); endmodule\n"
  977. "/* verilator lint_on DECLFILENAME */\n",
  978. encoding="ascii",
  979. newline="\n",
  980. )
  981. return path
  982. def verilator_warning_lines(stdout: str, stderr: str) -> list[str]:
  983. return [
  984. line.strip()
  985. for line in f"{stdout}\n{stderr}".splitlines()
  986. if re.match(r"^\s*%Warning(?:-[A-Z0-9_]+)?:", line)
  987. ]
  988. def _run_verilator(work_root: Path) -> dict[str, Any]:
  989. verilator = resolve_tool("verilator")
  990. target_names = ["prod2u_p4_normal_v3_top_lint"]
  991. target_manifest = target_manifest_evidence("verilator", target_names)
  992. if not verilator:
  993. return _missing_tools(
  994. HDL_RECEIPT_SCHEMA,
  995. "hdl_sim",
  996. ["verilator"],
  997. backend="verilator",
  998. tests=[{"name": target_names[0]}],
  999. target_manifest=target_manifest,
  1000. )
  1001. run_dir = work_root / "hdl" / "verilator"
  1002. run_dir.mkdir(parents=True, exist_ok=True)
  1003. stubs = _write_verilator_stubs(work_root)
  1004. command = [
  1005. verilator,
  1006. "--lint-only",
  1007. "--timing",
  1008. "-Wall",
  1009. "--top-module",
  1010. TOP_MODULE,
  1011. "-GSOLENOID_ACTIVE_HIGH=1",
  1012. str(ROOT / "tests" / "verilator_waivers.vlt"),
  1013. *[str(ROOT / source) for source in active_rtl_sources()],
  1014. str(stubs),
  1015. ]
  1016. completed = _run_bounded(
  1017. command,
  1018. timeout_name="verilator",
  1019. cwd=run_dir,
  1020. env=tool_env(),
  1021. text=True,
  1022. stdout=subprocess.PIPE,
  1023. stderr=subprocess.PIPE,
  1024. check=False,
  1025. )
  1026. timed_out = _was_timed_out(completed)
  1027. warning_lines = verilator_warning_lines(completed.stdout, completed.stderr)
  1028. if timed_out:
  1029. result_status = "fail_timeout"
  1030. elif warning_lines:
  1031. result_status = "fail_warning"
  1032. else:
  1033. result_status = "pass" if completed.returncode == 0 else "fail"
  1034. result = {
  1035. "name": target_names[0],
  1036. "status": result_status,
  1037. "timed_out": timed_out,
  1038. "returncode": completed.returncode,
  1039. "unwaived_warning_count": len(warning_lines),
  1040. "unwaived_warnings": warning_lines,
  1041. "waiver_file": str(ROOT / "tests" / "verilator_waivers.vlt"),
  1042. "stdout_tail": _tail(completed.stdout),
  1043. "stderr_tail": _tail(completed.stderr),
  1044. }
  1045. return {
  1046. "schema": HDL_RECEIPT_SCHEMA,
  1047. "status": "pass"
  1048. if result["status"] == "pass" and target_manifest["status"] == "pass"
  1049. else "fail",
  1050. "verification_layer": "hdl_sim",
  1051. "profile": PROFILE,
  1052. "backend": "verilator",
  1053. "work_root": str(work_root),
  1054. "tests": [result],
  1055. "target_manifest": target_manifest,
  1056. "safety": dict(SAFETY_BOUNDARY),
  1057. }
  1058. def _run_cocotb(work_root: Path) -> dict[str, Any]:
  1059. python_exe = cocotb_python()
  1060. probe_ok = python_has_cocotb(python_exe)
  1061. missing: list[str] = []
  1062. if not probe_ok:
  1063. missing.append("python_module:cocotb")
  1064. for name in ("iverilog", "vvp"):
  1065. if not resolve_tool(name):
  1066. missing.append(name)
  1067. targets = cocotb_tests()
  1068. target_manifest = target_manifest_evidence("cocotb", [target["name"] for target in targets])
  1069. if missing:
  1070. return _missing_tools(
  1071. HDL_RECEIPT_SCHEMA,
  1072. "hdl_sim",
  1073. missing,
  1074. backend="cocotb",
  1075. tests=targets,
  1076. target_manifest=target_manifest,
  1077. )
  1078. results: list[dict[str, Any]] = []
  1079. for target in targets:
  1080. target_root = work_root / "hdl" / "cocotb" / target["name"]
  1081. target_root.mkdir(parents=True, exist_ok=True)
  1082. completed = _run_bounded(
  1083. [python_exe, "-B", str(ROOT / target["runner"])],
  1084. timeout_name="cocotb",
  1085. cwd=ROOT / "tests" / "cocotb",
  1086. env=tool_env(
  1087. {
  1088. "TEMP": str(target_root),
  1089. "TMP": str(target_root),
  1090. "TMPDIR": str(target_root),
  1091. "PYTHONPYCACHEPREFIX": str(target_root / "pycache"),
  1092. }
  1093. ),
  1094. text=True,
  1095. stdout=subprocess.PIPE,
  1096. stderr=subprocess.PIPE,
  1097. check=False,
  1098. )
  1099. timed_out = _was_timed_out(completed)
  1100. results.append(
  1101. {
  1102. "name": target["name"],
  1103. "status": "pass" if completed.returncode == 0 else ("fail_timeout" if timed_out else "fail"),
  1104. "timed_out": timed_out,
  1105. "returncode": completed.returncode,
  1106. "stdout_tail": _tail(completed.stdout),
  1107. "stderr_tail": _tail(completed.stderr),
  1108. }
  1109. )
  1110. passed = (
  1111. bool(results) and
  1112. all(item["status"] == "pass" for item in results) and
  1113. target_manifest["status"] == "pass"
  1114. )
  1115. return {
  1116. "schema": HDL_RECEIPT_SCHEMA,
  1117. "status": "pass" if passed else "fail",
  1118. "verification_layer": "hdl_sim",
  1119. "profile": PROFILE,
  1120. "backend": "cocotb",
  1121. "work_root": str(work_root),
  1122. "tests": results,
  1123. "target_manifest": target_manifest,
  1124. "safety": dict(SAFETY_BOUNDARY),
  1125. }
  1126. def python_has_cocotb(python_exe: str | Path) -> bool:
  1127. completed = subprocess.run(
  1128. [str(python_exe), "-B", "-c", "import cocotb"],
  1129. cwd=ROOT,
  1130. env=tool_env(),
  1131. text=True,
  1132. stdout=subprocess.PIPE,
  1133. stderr=subprocess.PIPE,
  1134. timeout=20,
  1135. check=False,
  1136. )
  1137. return completed.returncode == 0
  1138. def cocotb_python() -> str:
  1139. candidates: list[Path] = []
  1140. configured = os.environ.get("PROD2U_P4_COCOTB_PYTHON", "").strip()
  1141. if configured:
  1142. candidates.append(Path(configured))
  1143. candidates.append(Path(sys.executable))
  1144. if DEFAULT_VENV_ROOT.is_dir():
  1145. candidates.extend(sorted(DEFAULT_VENV_ROOT.glob("*/Scripts/python.exe")))
  1146. for candidate in dict.fromkeys(path.expanduser().resolve() for path in candidates):
  1147. if candidate.is_file() and python_has_cocotb(candidate):
  1148. return str(candidate)
  1149. return str(Path(sys.executable).resolve())
  1150. def hdl_target_manifest_evidence(backend: str) -> dict[str, Any]:
  1151. inventory = target_inventory()
  1152. if backend == "all":
  1153. return target_manifest_evidence("all", inventory)
  1154. observed = inventory.get(backend, [])
  1155. return target_manifest_evidence(backend, observed)
  1156. def hdl_sim_payload(
  1157. run: bool,
  1158. backend: str = "icarus",
  1159. *,
  1160. work_root: Path | None = None,
  1161. ) -> dict[str, Any]:
  1162. try:
  1163. resolved = resolve_work_root(work_root, run=run)
  1164. except ValueError as exc:
  1165. return {
  1166. "schema": HDL_RECEIPT_SCHEMA,
  1167. "status": "blocked_invalid_work_root",
  1168. "verification_layer": "hdl_sim",
  1169. "profile": PROFILE,
  1170. "backend": backend,
  1171. "reason": str(exc),
  1172. "tests": hdl_testbenches(),
  1173. "target_manifest": hdl_target_manifest_evidence(backend),
  1174. "safety": dict(SAFETY_BOUNDARY),
  1175. }
  1176. if not run:
  1177. if backend == "icarus":
  1178. tests: list[dict[str, Any]] = hdl_testbenches()
  1179. elif backend == "verilator":
  1180. tests = [{"name": "prod2u_p4_normal_v3_top_lint"}]
  1181. elif backend == "cocotb":
  1182. tests = list(cocotb_tests())
  1183. else:
  1184. inventory = target_inventory()
  1185. tests = [
  1186. {"name": name}
  1187. for layer in ("icarus", "verilator", "cocotb")
  1188. for name in inventory[layer]
  1189. ]
  1190. return {
  1191. "schema": HDL_RECEIPT_SCHEMA,
  1192. "status": "skipped",
  1193. "verification_layer": "hdl_sim",
  1194. "profile": PROFILE,
  1195. "backend": backend,
  1196. "work_root": None if resolved is None else str(resolved),
  1197. "tests": tests,
  1198. "target_manifest": hdl_target_manifest_evidence(backend),
  1199. "safety": dict(SAFETY_BOUNDARY),
  1200. }
  1201. assert resolved is not None
  1202. if backend == "icarus":
  1203. return _run_icarus(resolved)
  1204. if backend == "verilator":
  1205. return _run_verilator(resolved)
  1206. if backend == "cocotb":
  1207. return _run_cocotb(resolved)
  1208. if backend != "all":
  1209. return {
  1210. "schema": HDL_RECEIPT_SCHEMA,
  1211. "status": "fail",
  1212. "verification_layer": "hdl_sim",
  1213. "profile": PROFILE,
  1214. "backend": backend,
  1215. "reason": f"unsupported HDL backend: {backend}",
  1216. "tests": [],
  1217. "target_manifest": hdl_target_manifest_evidence(backend),
  1218. "safety": dict(SAFETY_BOUNDARY),
  1219. }
  1220. children = {
  1221. name: hdl_sim_payload(run=True, backend=name, work_root=resolved)
  1222. for name in ("icarus", "verilator", "cocotb")
  1223. }
  1224. aggregate_manifest = hdl_target_manifest_evidence("all")
  1225. passed = (
  1226. all(child.get("status") == "pass" for child in children.values()) and
  1227. aggregate_manifest["status"] == "pass"
  1228. )
  1229. return {
  1230. "schema": HDL_RECEIPT_SCHEMA,
  1231. "status": "pass" if passed else "fail",
  1232. "verification_layer": "hdl_sim",
  1233. "profile": PROFILE,
  1234. "backend": "all",
  1235. "work_root": str(resolved),
  1236. "backend_results": children,
  1237. "tests": [
  1238. item
  1239. for child in children.values()
  1240. for item in child.get("tests", [])
  1241. ],
  1242. "target_manifest": aggregate_manifest,
  1243. "safety": dict(SAFETY_BOUNDARY),
  1244. }
  1245. def formal_payload(run: bool, *, work_root: Path | None = None) -> dict[str, Any]:
  1246. targets = formal_targets()
  1247. target_manifest = target_manifest_evidence(
  1248. "formal",
  1249. {target["name"]: list(target.get("tasks", [])) for target in targets},
  1250. )
  1251. try:
  1252. resolved = resolve_work_root(work_root, run=run)
  1253. except ValueError as exc:
  1254. return {
  1255. "schema": FORMAL_RECEIPT_SCHEMA,
  1256. "status": "blocked_invalid_work_root",
  1257. "verification_layer": "formal",
  1258. "profile": PROFILE,
  1259. "reason": str(exc),
  1260. "targets": targets,
  1261. "target_manifest": target_manifest,
  1262. "safety": dict(SAFETY_BOUNDARY),
  1263. }
  1264. if not run:
  1265. return {
  1266. "schema": FORMAL_RECEIPT_SCHEMA,
  1267. "status": "skipped",
  1268. "verification_layer": "formal",
  1269. "profile": PROFILE,
  1270. "work_root": None if resolved is None else str(resolved),
  1271. "targets": targets,
  1272. "target_manifest": target_manifest,
  1273. "safety": dict(SAFETY_BOUNDARY),
  1274. }
  1275. sby = resolve_tool("sby")
  1276. yosys = resolve_tool("yosys")
  1277. missing = [name for name, value in (("sby", sby), ("yosys", yosys)) if not value]
  1278. if missing:
  1279. return _missing_tools(
  1280. FORMAL_RECEIPT_SCHEMA,
  1281. "formal",
  1282. missing,
  1283. targets=targets,
  1284. target_manifest=target_manifest,
  1285. )
  1286. assert resolved is not None
  1287. results: list[dict[str, Any]] = []
  1288. for target in targets:
  1289. sby_file = ROOT / target["sby"]
  1290. property_counts = formal_property_counts(sby_file)
  1291. input_evidence = formal_input_evidence(sby_file, target.get("tasks", []))
  1292. workdir = resolved / "formal" / target["name"]
  1293. tasks = list(target.get("tasks", []))
  1294. task_names = tasks or ["default"]
  1295. task_workdirs = [workdir / task_name for task_name in task_names]
  1296. task_modes = formal_task_modes(sby_file, tasks)
  1297. task_timeout = configured_timeout("formal")
  1298. task_env = formal_tool_env(resolved)
  1299. def run_task(task_name: str, task_workdir: Path) -> dict[str, Any]:
  1300. command = [str(sby), "-f", "-d", str(task_workdir), str(sby_file)]
  1301. if tasks:
  1302. command.append(task_name)
  1303. try:
  1304. completed = subprocess.run(
  1305. command,
  1306. cwd=sby_file.parent,
  1307. env=task_env,
  1308. text=True,
  1309. stdout=subprocess.PIPE,
  1310. stderr=subprocess.PIPE,
  1311. timeout=task_timeout,
  1312. check=False,
  1313. )
  1314. return {
  1315. "status": "pass" if completed.returncode == 0 else "fail",
  1316. "returncode": completed.returncode,
  1317. "stdout": completed.stdout,
  1318. "stderr": completed.stderr,
  1319. }
  1320. except subprocess.TimeoutExpired as exc:
  1321. return {
  1322. "status": "fail_timeout",
  1323. "returncode": None,
  1324. "stdout": (
  1325. exc.stdout.decode(errors="replace")
  1326. if isinstance(exc.stdout, bytes)
  1327. else (exc.stdout or "")
  1328. ),
  1329. "stderr": (
  1330. exc.stderr.decode(errors="replace")
  1331. if isinstance(exc.stderr, bytes)
  1332. else (exc.stderr or "")
  1333. ),
  1334. }
  1335. with ThreadPoolExecutor(
  1336. max_workers=min(FORMAL_MAX_WORKERS, len(task_names))
  1337. ) as executor:
  1338. task_futures = [
  1339. executor.submit(run_task, task_name, task_workdir)
  1340. for task_name, task_workdir in zip(
  1341. task_names, task_workdirs, strict=True
  1342. )
  1343. ]
  1344. task_process_results = [future.result() for future in task_futures]
  1345. if any(item["status"] == "fail_timeout" for item in task_process_results):
  1346. result_status = "fail_timeout"
  1347. elif any(item["status"] != "pass" for item in task_process_results):
  1348. result_status = "fail"
  1349. else:
  1350. result_status = "pass"
  1351. nonzero_returncodes = [
  1352. item["returncode"]
  1353. for item in task_process_results
  1354. if item["returncode"] not in (None, 0)
  1355. ]
  1356. returncode: int | None = (
  1357. int(nonzero_returncodes[0])
  1358. if nonzero_returncodes
  1359. else (None if result_status == "fail_timeout" else 0)
  1360. )
  1361. stdout = "\n".join(
  1362. f"[{task_name}]\n{item['stdout']}".rstrip()
  1363. for task_name, item in zip(task_names, task_process_results, strict=True)
  1364. if item["stdout"]
  1365. )
  1366. stderr = "\n".join(
  1367. f"[{task_name}]\n{item['stderr']}".rstrip()
  1368. for task_name, item in zip(task_names, task_process_results, strict=True)
  1369. if item["stderr"]
  1370. )
  1371. task_results = [
  1372. formal_task_evidence(
  1373. name=task_name,
  1374. mode=task_modes[task_name],
  1375. workdir=task_workdir,
  1376. configured_engines=input_evidence["task_engines"].get(task_name, []),
  1377. )
  1378. for task_name, task_workdir in zip(task_names, task_workdirs, strict=True)
  1379. ]
  1380. trace_files = sorted(
  1381. {
  1382. trace_file
  1383. for task_result in task_results
  1384. for trace_file in task_result["trace_files"]
  1385. }
  1386. )
  1387. cover_tasks = [result for result in task_results if result["mode"] == "cover"]
  1388. cover_required = bool(cover_tasks)
  1389. cover_hit_ids = sorted(
  1390. {
  1391. hit_id
  1392. for task_result in cover_tasks
  1393. for hit_id in task_result["cover_hit_ids"]
  1394. }
  1395. )
  1396. cover_hit_count = len(cover_hit_ids)
  1397. evidence_failures: list[str] = []
  1398. for task_result in task_results:
  1399. evidence_failures.extend(task_result["evidence_failures"])
  1400. if int(property_counts["assertion_count"]) <= 0:
  1401. evidence_failures.append("formal_assertions_missing")
  1402. if cover_required and int(property_counts["cover_count"]) <= 0:
  1403. evidence_failures.append("formal_cover_properties_missing")
  1404. if result_status != "fail_timeout" and evidence_failures:
  1405. result_status = "fail_evidence"
  1406. results.append(
  1407. {
  1408. "name": target["name"],
  1409. "status": result_status,
  1410. "returncode": returncode,
  1411. "tasks": tasks,
  1412. "workdirs": [str(path) for path in task_workdirs],
  1413. "trace_files": trace_files,
  1414. "counterexamples": [] if result_status == "pass" else trace_files,
  1415. "assertion_count": property_counts["assertion_count"],
  1416. "cover_count": property_counts["cover_count"],
  1417. "cover_required": cover_required,
  1418. "cover_hit_count": cover_hit_count,
  1419. "cover_hit_ids": cover_hit_ids,
  1420. "input_evidence": input_evidence,
  1421. "task_results": task_results,
  1422. "evidence_failures": evidence_failures,
  1423. "stdout_tail": _tail(stdout),
  1424. "stderr_tail": _tail(stderr),
  1425. }
  1426. )
  1427. observed_solvers = sorted(
  1428. {
  1429. solver
  1430. for result in results
  1431. for task_result in result.get("task_results", [])
  1432. for solver in task_result.get("solvers", [])
  1433. }
  1434. )
  1435. toolchain = formal_toolchain_evidence(sby, yosys, observed_solvers, resolved)
  1436. passed = (
  1437. bool(results) and
  1438. all(item["status"] == "pass" for item in results) and
  1439. target_manifest["status"] == "pass" and
  1440. toolchain["status"] == "pass"
  1441. )
  1442. return {
  1443. "schema": FORMAL_RECEIPT_SCHEMA,
  1444. "status": "pass" if passed else "fail",
  1445. "verification_layer": "formal",
  1446. "profile": PROFILE,
  1447. "work_root": str(resolved),
  1448. "targets": results,
  1449. "toolchain": toolchain,
  1450. "target_manifest": target_manifest,
  1451. "safety": dict(SAFETY_BOUNDARY),
  1452. }
  1453. def unit_test_modules() -> list[str]:
  1454. unit_root = ROOT / "tests" / "unit"
  1455. selected = set(unit_root.glob("test_prod2u_p4*.py"))
  1456. selected.update(unit_root.glob("test_bootstrap_oss_cad_suite.py"))
  1457. selected.update(unit_root.glob("test_prod2u_programmer*.py"))
  1458. modules = [f"tests.unit.{path.stem}" for path in sorted(selected)]
  1459. if (ROOT / "tests" / "test_project_structure.py").is_file():
  1460. modules.append("tests.test_project_structure")
  1461. return modules
  1462. def target_inventory() -> dict[str, Any]:
  1463. return {
  1464. "unit": list(unit_test_modules()),
  1465. "icarus": [target["name"] for target in hdl_testbenches()],
  1466. "verilator": ["prod2u_p4_normal_v3_top_lint"],
  1467. "cocotb": [target["name"] for target in cocotb_tests()],
  1468. "formal": {
  1469. target["name"]: list(target.get("tasks", []))
  1470. for target in formal_targets()
  1471. },
  1472. }
  1473. def unit_payload(work_root: Path) -> dict[str, Any]:
  1474. modules = unit_test_modules()
  1475. target_manifest = target_manifest_evidence("unit", modules)
  1476. command = [sys.executable, "-B", "-m", "unittest", "-v", *modules]
  1477. completed = subprocess.run(
  1478. command,
  1479. cwd=ROOT,
  1480. env=tool_env({"PYTHONPYCACHEPREFIX": str(work_root / "python-cache")}),
  1481. text=True,
  1482. stdout=subprocess.PIPE,
  1483. stderr=subprocess.PIPE,
  1484. timeout=1800,
  1485. check=False,
  1486. )
  1487. passed = completed.returncode == 0 and target_manifest["status"] == "pass"
  1488. return {
  1489. "status": "pass" if passed else "fail",
  1490. "returncode": completed.returncode,
  1491. "modules": modules,
  1492. "target_manifest": target_manifest,
  1493. "stdout_tail": _tail(completed.stdout, 12000),
  1494. "stderr_tail": _tail(completed.stderr, 12000),
  1495. }
  1496. def source_integrity_payload() -> dict[str, Any]:
  1497. completed = _git("diff", "--check", "HEAD")
  1498. state = source_state()
  1499. passed = (
  1500. completed.returncode == 0 and
  1501. state["status"] == "pass" and
  1502. state.get("clean") is True
  1503. )
  1504. return {
  1505. "status": "pass" if passed else "fail",
  1506. "returncode": completed.returncode,
  1507. "stdout_tail": _tail(completed.stdout),
  1508. "stderr_tail": _tail(completed.stderr),
  1509. "source_state": state,
  1510. }
  1511. def strict_offline_gate_payload(
  1512. *,
  1513. work_root: Path,
  1514. verification_run_id: str | None = None,
  1515. ) -> dict[str, Any]:
  1516. state = source_state()
  1517. run_id = normalize_verification_run_id(verification_run_id)
  1518. try:
  1519. resolved = resolve_work_root(work_root, run=True)
  1520. except ValueError as exc:
  1521. return {
  1522. "schema": OFFLINE_RECEIPT_SCHEMA,
  1523. "status": "fail",
  1524. "verification_run_id": run_id,
  1525. "commit": state["commit"],
  1526. "source_state": state,
  1527. "required_layers": ["source_integrity", "unit", "hdl_sim", "formal"],
  1528. "layers": {},
  1529. "failures": [f"work_root_invalid:{exc}"],
  1530. "safety": dict(SAFETY_BOUNDARY),
  1531. }
  1532. assert resolved is not None
  1533. layers = {
  1534. "source_integrity": source_integrity_payload(),
  1535. "unit": unit_payload(resolved),
  1536. "hdl_sim": hdl_sim_payload(run=True, backend="all", work_root=resolved),
  1537. "formal": formal_payload(run=True, work_root=resolved),
  1538. }
  1539. required = list(layers)
  1540. failures = [
  1541. f"required_layer_not_pass:{name}:{layers[name].get('status', 'missing')}"
  1542. for name in required
  1543. if layers[name].get("status") != "pass"
  1544. ]
  1545. receipt_dir = resolved / "receipts"
  1546. receipt_dir.mkdir(parents=True, exist_ok=True)
  1547. for name, layer in layers.items():
  1548. write_json_report(layer, receipt_dir / f"{name}.json")
  1549. return {
  1550. "schema": OFFLINE_RECEIPT_SCHEMA,
  1551. "generated_at": utc_now(),
  1552. "status": "pass" if not failures else "fail",
  1553. "verification_run_id": run_id,
  1554. "commit": state["commit"],
  1555. "source_state": state,
  1556. "profile": PROFILE,
  1557. "runtime_profile": RUNTIME_PROFILE,
  1558. "required_layers": required,
  1559. "layers": layers,
  1560. "failures": failures,
  1561. "work_root": str(resolved),
  1562. "child_receipt_dir": str(receipt_dir),
  1563. "safety": dict(SAFETY_BOUNDARY),
  1564. "authority_boundary": "This receipt covers offline source, software, HDL and formal checks only. It does not access serial, JTAG, or a board.",
  1565. }
  1566. class StagedBuild:
  1567. def __init__(
  1568. self,
  1569. root: Path,
  1570. syn: Path,
  1571. phy: Path,
  1572. bitgen: Path,
  1573. clean: Mapping[str, Any],
  1574. source_state: Mapping[str, Any],
  1575. source_manifest: Mapping[str, Any],
  1576. synthesis_input_manifest: Mapping[str, Any],
  1577. ) -> None:
  1578. self.root = root
  1579. self.syn = syn
  1580. self.phy = phy
  1581. self.bitgen = bitgen
  1582. self.clean = clean
  1583. self.source_state = source_state
  1584. self.source_manifest = source_manifest
  1585. self.synthesis_input_manifest = synthesis_input_manifest
  1586. def _safe_build_root(work_root: Path) -> Path:
  1587. resolved = resolve_work_root(work_root, run=True)
  1588. assert resolved is not None
  1589. target = (resolved / BUILD_ROOT_RELATIVE).resolve()
  1590. if resolved != target and resolved not in target.parents:
  1591. raise ValueError("TD build root escaped the external work root")
  1592. return target
  1593. def clean_td_outputs(work_root: Path) -> dict[str, Any]:
  1594. target = _safe_build_root(work_root)
  1595. deleted: list[str] = []
  1596. if target.exists():
  1597. deleted.append(str(target))
  1598. shutil.rmtree(target)
  1599. return {"status": "pass", "deleted": deleted, "target": str(target)}
  1600. def _copy_active_sources(target: Path) -> None:
  1601. for relative in active_rtl_sources():
  1602. source = ROOT / relative
  1603. destination = target / relative
  1604. destination.parent.mkdir(parents=True, exist_ok=True)
  1605. shutil.copy2(source, destination)
  1606. for relative in (
  1607. "constraints/prod2u_p4_normal_v3.adc",
  1608. "constraints/prod2u_p4_normal_v3.sdc",
  1609. "td/prod2u_p4_normal_v3.prj",
  1610. ):
  1611. source = ROOT / relative
  1612. destination = target / relative
  1613. destination.parent.mkdir(parents=True, exist_ok=True)
  1614. shutil.copy2(source, destination)
  1615. def prepare_td_build_dirs(*, work_root: Path) -> StagedBuild:
  1616. build_root = _safe_build_root(work_root)
  1617. clean = clean_td_outputs(work_root)
  1618. state = source_state()
  1619. if state.get("status") != "pass" or state.get("clean") is not True:
  1620. raise RuntimeError("TD build requires a clean committed source state")
  1621. synthesis_input_manifest = build_synthesis_input_manifest(ROOT)
  1622. syn = build_root / "syn"
  1623. phy = build_root / "phy"
  1624. bitgen = build_root / "bitgen"
  1625. for directory in (syn, phy, bitgen):
  1626. directory.mkdir(parents=True, exist_ok=True)
  1627. _copy_active_sources(directory)
  1628. for directory in (syn, phy, bitgen):
  1629. write_json_report(state, directory / "source-state.json")
  1630. staged_dirs = {"syn": syn, "phy": phy, "bitgen": bitgen}
  1631. for phase, source in TD_SCRIPTS.items():
  1632. shutil.copy2(source, staged_dirs[phase] / source.name)
  1633. phases: dict[str, Any] = {}
  1634. for phase, directory in staged_dirs.items():
  1635. files = {
  1636. path.relative_to(directory).as_posix(): sha256_file(path)
  1637. for path in sorted(directory.rglob("*"))
  1638. if path.is_file()
  1639. }
  1640. phases[phase] = {"files": files, "manifest_sha256": canonical_sha256(files)}
  1641. source_manifest = {
  1642. "schema": "prod2u-p4-normal-v3-staged-source-manifest-v1",
  1643. "status": "pass",
  1644. "commit": state["commit"],
  1645. "source_state_clean": state["clean"],
  1646. "phases": phases,
  1647. "failures": [],
  1648. }
  1649. return StagedBuild(
  1650. build_root,
  1651. syn,
  1652. phy,
  1653. bitgen,
  1654. clean,
  1655. state,
  1656. source_manifest,
  1657. synthesis_input_manifest,
  1658. )
  1659. def _staged_synthesis_input_manifest(staged: StagedBuild) -> dict[str, Any]:
  1660. expected_inputs = staged.synthesis_input_manifest.get("inputs")
  1661. if not isinstance(expected_inputs, Mapping) or not expected_inputs:
  1662. raise ValueError("expected synthesis input manifest is missing")
  1663. observed: dict[str, str | None] = {}
  1664. for relative in expected_inputs:
  1665. relative_text = str(relative)
  1666. if relative_text.startswith("td/syn/"):
  1667. path = staged.syn / Path(relative_text).name
  1668. elif relative_text.startswith("td/phy/"):
  1669. path = staged.phy / Path(relative_text).name
  1670. elif relative_text.startswith("td/bitgen/"):
  1671. path = staged.bitgen / Path(relative_text).name
  1672. else:
  1673. path = staged.syn / relative_text
  1674. observed[relative_text] = sha256_file(path) if path.is_file() else None
  1675. return {
  1676. "schema": staged.synthesis_input_manifest.get("schema"),
  1677. "inputs": observed,
  1678. "sha256": canonical_sha256(observed),
  1679. }
  1680. def verify_staged_source_manifest(staged: StagedBuild) -> dict[str, Any]:
  1681. failures: list[str] = []
  1682. verified_phases: dict[str, Any] = {}
  1683. for phase in ("syn", "phy", "bitgen"):
  1684. directory = getattr(staged, phase)
  1685. expected_phase = staged.source_manifest.get("phases", {}).get(phase, {})
  1686. expected_files = expected_phase.get("files") if isinstance(expected_phase, Mapping) else None
  1687. if not isinstance(expected_files, Mapping) or not expected_files:
  1688. failures.append(f"manifest_missing:{phase}")
  1689. continue
  1690. observed: dict[str, str | None] = {}
  1691. for relative, expected_digest in expected_files.items():
  1692. path = directory / str(relative)
  1693. digest = sha256_file(path) if path.is_file() else None
  1694. observed[str(relative)] = digest
  1695. if digest != expected_digest:
  1696. failures.append(f"staged_input_mismatch:{phase}:{relative}")
  1697. observed_digest = canonical_sha256(observed)
  1698. expected_digest = expected_phase.get("manifest_sha256")
  1699. if observed_digest != expected_digest:
  1700. failures.append(f"phase_manifest_mismatch:{phase}")
  1701. verified_phases[phase] = {
  1702. "files": dict(expected_files),
  1703. "manifest_sha256": expected_digest,
  1704. "observed_manifest_sha256": observed_digest,
  1705. }
  1706. expected_synthesis_inputs = staged.synthesis_input_manifest.get("inputs")
  1707. synthesis_phase_bindings: dict[str, dict[str, str | None]] = {}
  1708. if not isinstance(expected_synthesis_inputs, Mapping):
  1709. failures.append("expected_synthesis_inputs_missing")
  1710. else:
  1711. for relative, expected_digest in expected_synthesis_inputs.items():
  1712. relative_text = str(relative)
  1713. if relative_text.startswith("td/syn/"):
  1714. phase_paths = {"syn": staged.syn / Path(relative_text).name}
  1715. elif relative_text.startswith("td/phy/"):
  1716. phase_paths = {"phy": staged.phy / Path(relative_text).name}
  1717. elif relative_text.startswith("td/bitgen/"):
  1718. phase_paths = {"bitgen": staged.bitgen / Path(relative_text).name}
  1719. else:
  1720. phase_paths = {
  1721. phase: getattr(staged, phase) / relative_text
  1722. for phase in ("syn", "phy", "bitgen")
  1723. }
  1724. observed_by_phase = {
  1725. phase: sha256_file(path) if path.is_file() else None
  1726. for phase, path in phase_paths.items()
  1727. }
  1728. synthesis_phase_bindings[relative_text] = observed_by_phase
  1729. for phase, observed_digest in observed_by_phase.items():
  1730. if observed_digest != expected_digest:
  1731. failures.append(f"staged_synthesis_input_mismatch:{phase}:{relative_text}")
  1732. observed_synthesis = _staged_synthesis_input_manifest(staged)
  1733. expected_synthesis = staged.synthesis_input_manifest
  1734. if observed_synthesis.get("inputs") != expected_synthesis.get("inputs"):
  1735. failures.append("staged_synthesis_inputs_mismatch")
  1736. if observed_synthesis.get("sha256") != expected_synthesis.get("sha256"):
  1737. failures.append("staged_synthesis_hash_mismatch")
  1738. return {
  1739. "schema": "prod2u-p4-normal-v3-staged-source-manifest-v1",
  1740. "status": "pass" if not failures else "fail",
  1741. "commit": staged.source_manifest.get("commit"),
  1742. "source_state_clean": staged.source_manifest.get("source_state_clean"),
  1743. "phases": verified_phases,
  1744. "synthesis_input_manifest": observed_synthesis,
  1745. "synthesis_phase_bindings": synthesis_phase_bindings,
  1746. "expected_synthesis_input_hash": expected_synthesis.get("sha256"),
  1747. "observed_synthesis_input_hash": observed_synthesis.get("sha256"),
  1748. "failures": sorted(set(failures)),
  1749. }
  1750. def td_process_env(
  1751. run_dir: Path,
  1752. extra: Mapping[str, str] | None = None,
  1753. ) -> dict[str, str]:
  1754. temp_dir = run_dir / "td-user" / "temp"
  1755. temp_dir.mkdir(parents=True, exist_ok=True)
  1756. values = {"TEMP": str(temp_dir), "TMP": str(temp_dir)}
  1757. if extra:
  1758. values.update({str(key): str(value) for key, value in extra.items()})
  1759. return tool_env(values)
  1760. def run_td_script(
  1761. run_dir: Path,
  1762. script_name: str,
  1763. *,
  1764. extra_env: Mapping[str, str] | None = None,
  1765. ) -> subprocess.CompletedProcess[str]:
  1766. return _run_bounded(
  1767. [str(TD_EXE), script_name],
  1768. timeout_name="td",
  1769. cwd=run_dir,
  1770. env=td_process_env(run_dir, extra_env),
  1771. text=True,
  1772. encoding="utf-8",
  1773. errors="replace",
  1774. stdout=subprocess.PIPE,
  1775. stderr=subprocess.PIPE,
  1776. check=False,
  1777. )
  1778. def td_forbidden_script_markers(script_text: str) -> list[str]:
  1779. markers: set[str] = set()
  1780. for raw_line in script_text.splitlines():
  1781. line = raw_line.strip().casefold()
  1782. if not line or line.startswith("#"):
  1783. continue
  1784. command = re.split(r"\s+", line, maxsplit=1)[0]
  1785. if command == "source":
  1786. markers.add("source")
  1787. for forbidden in FORBIDDEN_TD_COMMANDS:
  1788. if re.search(rf"(?<![a-z0-9_]){re.escape(forbidden)}(?![a-z0-9_])", line):
  1789. markers.add(forbidden)
  1790. return sorted(markers)
  1791. def td_log_has_error(*chunks: str) -> bool:
  1792. text = "\n".join(chunks)
  1793. return bool(
  1794. re.search(
  1795. r"(^|\n)\s*(?:[A-Z]+-\d+\s+)?(?:error|fatal)\s*[:|]",
  1796. text,
  1797. re.IGNORECASE,
  1798. )
  1799. )
  1800. def td_critical_warning_count(*chunks: str) -> int:
  1801. return len(re.findall(r"critical[-\s]+warning", "\n".join(chunks), re.IGNORECASE))
  1802. def parse_qor_attribute_count(path: Path, attribute: str) -> int | None:
  1803. if not path.is_file() or not re.fullmatch(r"[a-z][a-z0-9_]*", attribute):
  1804. return None
  1805. text = path.read_text(encoding="utf-8", errors="replace")
  1806. match = re.search(
  1807. rf"^\|\s*#{re.escape(attribute)}\s*\|\s*(\d+)\s*\|\s*$",
  1808. text,
  1809. re.MULTILINE,
  1810. )
  1811. return int(match.group(1)) if match else None
  1812. def parse_td_cdc_report(path: Path) -> dict[str, Any] | None:
  1813. if not path.is_file():
  1814. return None
  1815. rows: dict[str, list[str]] = {
  1816. "schema": [],
  1817. "retained_sync_register": [],
  1818. "false_path_endpoint": [],
  1819. "false_path_source": [],
  1820. "structural_failure": [],
  1821. }
  1822. for raw_line in path.read_text(encoding="utf-8", errors="replace").splitlines():
  1823. line = raw_line.strip()
  1824. if not line:
  1825. continue
  1826. if "=" not in line:
  1827. return None
  1828. key, value = line.split("=", 1)
  1829. if key not in rows or not value:
  1830. return None
  1831. rows[key].append(value)
  1832. if rows["schema"] != [CDC_REPORT_SCHEMA]:
  1833. return None
  1834. registers = rows["retained_sync_register"]
  1835. endpoints = rows["false_path_endpoint"]
  1836. sources = rows["false_path_source"]
  1837. failures = rows["structural_failure"]
  1838. if (
  1839. len(registers) != len(set(registers))
  1840. or len(endpoints) != len(set(endpoints))
  1841. or len(sources) != len(set(sources))
  1842. ):
  1843. return None
  1844. return {
  1845. "schema": CDC_REPORT_SCHEMA,
  1846. "retained_sync_registers": registers,
  1847. "false_path_endpoints": endpoints,
  1848. "source_only_false_paths": sources,
  1849. "structural_failures": failures,
  1850. }
  1851. def parse_td_fsm_report(path: Path) -> dict[str, Any] | None:
  1852. if not path.is_file():
  1853. return None
  1854. schema: str | None = None
  1855. axes: dict[str, int] = {}
  1856. encodings: dict[str, str] = {}
  1857. failures: list[str] = []
  1858. for raw_line in path.read_text(encoding="utf-8", errors="replace").splitlines():
  1859. line = raw_line.strip()
  1860. if not line or "=" not in line:
  1861. return None
  1862. key, value = line.split("=", 1)
  1863. if key == "schema":
  1864. if schema is not None or value != FSM_REPORT_SCHEMA:
  1865. return None
  1866. schema = value
  1867. continue
  1868. if key == "structural_failure":
  1869. failures.append(value)
  1870. continue
  1871. if key != "motion_phase":
  1872. return None
  1873. match = re.fullmatch(r"([xy]):(\d+):([a-z][a-z0-9_]*)", value)
  1874. if match is None or match.group(1) in axes:
  1875. return None
  1876. axis = match.group(1)
  1877. axes[axis] = int(match.group(2))
  1878. encodings[axis] = match.group(3)
  1879. if schema != FSM_REPORT_SCHEMA:
  1880. return None
  1881. return {
  1882. "schema": schema,
  1883. "axes": axes,
  1884. "encodings": encodings,
  1885. "structural_failures": failures,
  1886. }
  1887. def structural_cdc_gate(
  1888. report: Mapping[str, Any] | None,
  1889. *,
  1890. async_reg_count: int | None,
  1891. input_register_count: int | None,
  1892. ) -> dict[str, Any]:
  1893. failures: list[str] = []
  1894. registers = report.get("retained_sync_registers") if isinstance(report, Mapping) else None
  1895. endpoints = report.get("false_path_endpoints") if isinstance(report, Mapping) else None
  1896. source_only = report.get("source_only_false_paths") if isinstance(report, Mapping) else None
  1897. reported = report.get("structural_failures") if isinstance(report, Mapping) else None
  1898. register_set = set(registers) if isinstance(registers, list) and all(isinstance(item, str) for item in registers) else set()
  1899. endpoint_set = set(endpoints) if isinstance(endpoints, list) and all(isinstance(item, str) for item in endpoints) else set()
  1900. source_set = set(source_only) if isinstance(source_only, list) and all(isinstance(item, str) for item in source_only) else set()
  1901. reported_failures = list(reported) if isinstance(reported, list) and all(isinstance(item, str) for item in reported) else []
  1902. if async_reg_count != len(EXPECTED_CDC_SYNC_REGISTERS):
  1903. failures.append(f"async_reg_used:{async_reg_count}")
  1904. if input_register_count != 0:
  1905. failures.append(f"input_registers_used:{input_register_count}")
  1906. if register_set != EXPECTED_CDC_SYNC_REGISTERS:
  1907. failures.append("retained_sync_registers_mismatch")
  1908. if endpoint_set != EXPECTED_CDC_FALSE_PATH_ENDPOINTS:
  1909. failures.append("false_path_endpoints_mismatch")
  1910. if source_set:
  1911. failures.append(f"source_only_false_paths_used:{','.join(sorted(source_set))}")
  1912. failures.extend(f"td_report:{failure}" for failure in reported_failures)
  1913. return {
  1914. "status": "pass" if not failures else "fail",
  1915. "async_reg": {
  1916. "status": "pass" if async_reg_count == len(EXPECTED_CDC_SYNC_REGISTERS) else "fail",
  1917. "used": async_reg_count,
  1918. },
  1919. "input_registers": {
  1920. "status": "pass" if input_register_count == 0 else "fail",
  1921. "used": input_register_count,
  1922. },
  1923. "retained_sync_registers": {
  1924. "status": "pass" if register_set == EXPECTED_CDC_SYNC_REGISTERS else "fail",
  1925. "used": len(register_set),
  1926. },
  1927. "first_stage_endpoints": {
  1928. "status": "pass" if endpoint_set == EXPECTED_CDC_FALSE_PATH_ENDPOINTS else "fail",
  1929. "used": len(endpoint_set),
  1930. },
  1931. "source_only_false_paths": sorted(source_set),
  1932. "reported_failures": reported_failures,
  1933. "failures": failures,
  1934. }
  1935. def structural_fsm_gate(
  1936. report: Mapping[str, Any] | None,
  1937. *,
  1938. syn_log: str,
  1939. ) -> dict[str, Any]:
  1940. failures: list[str] = []
  1941. axes = report.get("axes") if isinstance(report, Mapping) else None
  1942. encodings = report.get("encodings") if isinstance(report, Mapping) else None
  1943. reported = report.get("structural_failures") if isinstance(report, Mapping) else None
  1944. normalized_axes = dict(axes) if isinstance(axes, Mapping) else {}
  1945. normalized_encodings = dict(encodings) if isinstance(encodings, Mapping) else {}
  1946. reported_failures = list(reported) if isinstance(reported, list) and all(isinstance(item, str) for item in reported) else []
  1947. if normalized_axes != EXPECTED_FSM_AXES:
  1948. failures.append("motion_phase_width_or_axis_mismatch")
  1949. if normalized_encodings != {axis: "sequential" for axis in EXPECTED_FSM_AXES}:
  1950. failures.append("motion_phase_encoding_mismatch")
  1951. marker_seen = "FSM_ENCODING_GATE_PASS=sequential" in syn_log
  1952. if not marker_seen:
  1953. failures.append("fsm_td_log_marker_missing")
  1954. reencoded = re.findall(
  1955. r"SYN-1067\s*:.*?state register '[^']*motion_phase(?:_reg)?[^']*'"
  1956. r".*?encoding '([^']+)'",
  1957. syn_log,
  1958. re.IGNORECASE,
  1959. )
  1960. for encoding in reencoded:
  1961. failures.append(f"motion_phase_reencoded:{encoding.casefold()}")
  1962. failures.extend(f"td_report:{failure}" for failure in reported_failures)
  1963. return {
  1964. "status": "pass" if not failures else "fail",
  1965. "encoding": "sequential" if not failures else None,
  1966. "axes": normalized_axes,
  1967. "td_log_marker": marker_seen,
  1968. "reencoded_motion_phase_count": len(reencoded),
  1969. "reported_failures": reported_failures,
  1970. "failures": failures,
  1971. }
  1972. def parse_area_report(path: Path) -> dict[str, Any] | None:
  1973. if not path.is_file():
  1974. return None
  1975. text = path.read_text(encoding="utf-8", errors="replace")
  1976. result: dict[str, Any] = {"path": str(path), "utilization": {}, "hierarchy": []}
  1977. columns: list[str] = []
  1978. for line in text.splitlines():
  1979. match = re.match(
  1980. r"#(lut|reg|dsp|bram|bram32k|bram128k|bram256k|pad|pll)\s+"
  1981. r"(\d+)\s+out of\s+(\d+)\s+([0-9.]+)%",
  1982. line.strip(),
  1983. )
  1984. if match:
  1985. result["utilization"][match.group(1)] = {
  1986. "used": int(match.group(2)),
  1987. "total": int(match.group(3)),
  1988. "percent": float(match.group(4)),
  1989. }
  1990. continue
  1991. detail = re.match(r"#(ireg|oreg|treg)\s+(\d+)\s*$", line.strip())
  1992. if detail:
  1993. result["utilization"][detail.group(1)] = {"used": int(detail.group(2))}
  1994. continue
  1995. if line.startswith("|") and "Instance" in line and "Module" in line:
  1996. columns = [part.strip().lower() for part in line.strip("|").split("|")]
  1997. continue
  1998. if line.startswith("|") and columns:
  1999. values = [part.strip() for part in line.strip("|").split("|")]
  2000. if len(values) != len(columns):
  2001. continue
  2002. row = dict(zip(columns, values))
  2003. if not row.get("instance") or row.get("instance") == "Instance":
  2004. continue
  2005. parsed: dict[str, Any] = {"instance": row["instance"], "module": row["module"]}
  2006. try:
  2007. for key, value in row.items():
  2008. if key not in {"instance", "module"}:
  2009. parsed[key] = int(value)
  2010. except ValueError:
  2011. continue
  2012. result["hierarchy"].append(parsed)
  2013. if "pad" in result["utilization"]:
  2014. for name in ("ireg", "oreg", "treg"):
  2015. result["utilization"].setdefault(name, {"used": 0})
  2016. return result
  2017. def parse_td_io_report(path: Path) -> list[dict[str, str]] | None:
  2018. target = Path(path)
  2019. if not target.is_file():
  2020. return None
  2021. lines = target.read_text(encoding="utf-8", errors="replace").splitlines()
  2022. try:
  2023. start = next(index for index, line in enumerate(lines) if line.strip() == "Detailed IO Report")
  2024. header = next(
  2025. index
  2026. for index in range(start + 1, len(lines))
  2027. if lines[index].split()[:4] == ["Name", "Direction", "Location", "IOStandard"]
  2028. )
  2029. except StopIteration:
  2030. return None
  2031. rows: list[dict[str, str]] = []
  2032. for line in lines[header + 1 :]:
  2033. fields = line.split()
  2034. if not fields:
  2035. if rows:
  2036. break
  2037. continue
  2038. if len(fields) != 9:
  2039. if rows:
  2040. break
  2041. continue
  2042. rows.append(
  2043. dict(
  2044. zip(
  2045. (
  2046. "name",
  2047. "direction",
  2048. "location",
  2049. "io_standard",
  2050. "io_type",
  2051. "drive_strength",
  2052. "pull_type",
  2053. "pack_reg",
  2054. "diff_resistor",
  2055. ),
  2056. fields,
  2057. strict=True,
  2058. )
  2059. )
  2060. )
  2061. return rows or None
  2062. def post_route_pin_gate(rows: Sequence[Mapping[str, str]] | None) -> dict[str, Any]:
  2063. failures: list[str] = []
  2064. normalized = [dict(row) for row in rows or []]
  2065. by_name = {row.get("name"): row for row in normalized if row.get("name")}
  2066. locations = [str(row.get("location", "")) for row in normalized]
  2067. if len(normalized) != 41:
  2068. failures.append(f"io_row_count:{len(normalized)}")
  2069. if len(by_name) != len(normalized):
  2070. failures.append("io_name_not_unique")
  2071. if len(set(locations)) != len(locations):
  2072. failures.append("io_location_not_unique")
  2073. if "A5" in locations:
  2074. failures.append("forbidden_location_assigned:A5")
  2075. required = {
  2076. "x_limit_raw": {"location": "B9", "io_standard": "LVCMOS33", "pull_type": "PULLUP"},
  2077. "y_limit_raw": {"location": "A11", "io_standard": "LVCMOS33", "pull_type": "PULLUP"},
  2078. }
  2079. for name, expected in required.items():
  2080. observed = by_name.get(name)
  2081. if observed is None:
  2082. failures.append(f"io_signal_missing:{name}")
  2083. continue
  2084. for field, value in expected.items():
  2085. if observed.get(field) != value:
  2086. failures.append(f"io_binding_mismatch:{name}:{field}")
  2087. return {
  2088. "status": "pass" if not failures else "fail",
  2089. "row_count": len(normalized),
  2090. "required": required,
  2091. "observed": {name: by_name.get(name) for name in required},
  2092. "forbidden_location": "A5",
  2093. "failures": failures,
  2094. }
  2095. def parse_packing_summary(*texts: str) -> dict[str, int] | None:
  2096. matches = [
  2097. (int(match.group(1)), int(match.group(2)))
  2098. for text in texts
  2099. for match in re.finditer(r"\b(\d+)\s+mslices,\s+(\d+)\s+lslices\b", text, re.IGNORECASE)
  2100. ]
  2101. if not matches:
  2102. return None
  2103. mslice, lslice = matches[-1]
  2104. return {"mslice": mslice, "lslice": lslice, "total_slices": mslice + lslice}
  2105. def parse_timing_report(path: Path) -> dict[str, Any] | None:
  2106. if not path.is_file():
  2107. return None
  2108. text = path.read_text(encoding="utf-8", errors="replace")
  2109. result: dict[str, Any] = {"path": str(path)}
  2110. row = re.search(
  2111. r"^\s*clk\d+\s+\S+\s+[0-9.]+\s+[0-9.]+\s+"
  2112. r"([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s+"
  2113. r"([0-9.+-]+)\s+([0-9.+-]+)\s+([0-9.+-]+)\s+([0-9.+-]+)",
  2114. text,
  2115. re.MULTILINE,
  2116. )
  2117. if row:
  2118. result.update(
  2119. {
  2120. "period_ns": float(row.group(1)),
  2121. "clock_frequency_mhz": float(row.group(2)),
  2122. "minimum_period_ns": float(row.group(3)),
  2123. "fmax_mhz": float(row.group(4)),
  2124. "worst_setup_slack_ns": float(row.group(5)),
  2125. "setup_total_negative_slack_ns": float(row.group(6)),
  2126. "worst_hold_slack_ns": float(row.group(7)),
  2127. "hold_total_negative_slack_ns": float(row.group(8)),
  2128. }
  2129. )
  2130. errors = re.search(r"(\d+) errors detected : (\d+) setup errors .*?, (\d+) hold errors", text)
  2131. if errors:
  2132. result["error_count"] = int(errors.group(1))
  2133. result["setup_error_count"] = int(errors.group(2))
  2134. result["hold_error_count"] = int(errors.group(3))
  2135. else:
  2136. setup_violations = re.search(
  2137. r"^\s*Max\s*:.*?\b(\d+)\s+Viol Endpoints\b",
  2138. text,
  2139. re.MULTILINE,
  2140. )
  2141. hold_violations = re.search(
  2142. r"^\s*Min\s*:.*?\b(\d+)\s+Viol Endpoints\b",
  2143. text,
  2144. re.MULTILINE,
  2145. )
  2146. if setup_violations and hold_violations:
  2147. setup_count = int(setup_violations.group(1))
  2148. hold_count = int(hold_violations.group(1))
  2149. result["error_count"] = setup_count + hold_count
  2150. result["setup_error_count"] = setup_count
  2151. result["hold_error_count"] = hold_count
  2152. return result
  2153. def pin_binding_gate() -> dict[str, Any]:
  2154. path = ROOT / "constraints" / "prod2u_p4_normal_v3.adc"
  2155. text = path.read_text(encoding="utf-8", errors="replace")
  2156. assignments = re.findall(
  2157. r"set_pin_assignment\s+\{\s*([^}]+?)\s*\}\s+\{\s*LOCATION\s*=\s*([^;\s]+);\s*"
  2158. r"IOSTANDARD\s*=\s*([^;\s]+);\s*PULLTYPE\s*=\s*([^;\s]+);",
  2159. text,
  2160. )
  2161. by_signal = {signal.strip(): (ball.strip(), standard.strip(), pull.strip()) for signal, ball, standard, pull in assignments}
  2162. failures: list[str] = []
  2163. if len(assignments) != 41:
  2164. failures.append(f"pad_count:{len(assignments)}")
  2165. if len(by_signal) != len(assignments):
  2166. failures.append("duplicate_signal")
  2167. if len({item[0] for item in by_signal.values()}) != len(assignments):
  2168. failures.append("duplicate_ball")
  2169. if any(ball == "A5" for ball, _standard, _pull in by_signal.values()):
  2170. failures.append("forbidden_ball_assigned:A5")
  2171. required = {
  2172. "sys_clk": ("J1", "NONE"),
  2173. "host_uart_rx": ("N11", "NONE"),
  2174. "host_uart_tx": ("M10", "NONE"),
  2175. "x_limit_raw": ("B9", "PULLUP"),
  2176. "y_limit_raw": ("A11", "PULLUP"),
  2177. }
  2178. for signal, (ball, pull) in required.items():
  2179. observed = by_signal.get(signal)
  2180. if observed is None:
  2181. failures.append(f"missing_signal:{signal}")
  2182. elif observed[0] != ball or observed[2] != pull:
  2183. failures.append(f"binding_mismatch:{signal}")
  2184. return {
  2185. "status": "pass" if not failures else "fail",
  2186. "path": str(path),
  2187. "pad_count": len(assignments),
  2188. "failures": failures,
  2189. }
  2190. def timing_gate(timing: Mapping[str, Any] | None) -> dict[str, Any]:
  2191. failures: list[str] = []
  2192. if not isinstance(timing, Mapping):
  2193. failures.append("timing_report_missing")
  2194. else:
  2195. for name in ("fmax_mhz", "worst_setup_slack_ns", "worst_hold_slack_ns"):
  2196. value = timing.get(name)
  2197. if not isinstance(value, (int, float)) or value <= 0:
  2198. failures.append(f"nonpositive_or_missing:{name}")
  2199. error_count = timing.get("error_count")
  2200. if not isinstance(error_count, int) or isinstance(error_count, bool):
  2201. failures.append("timing_error_count_missing")
  2202. elif error_count != 0:
  2203. failures.append("timing_errors_present")
  2204. return {"status": "pass" if not failures else "fail", "failures": failures}
  2205. def td_bitgen_eligible(
  2206. *,
  2207. route_artifact_usable: bool,
  2208. timing_status: str,
  2209. structural_status: str,
  2210. ) -> bool:
  2211. """Permit bit generation after a usable routed database exists.
  2212. Timing and structural results remain recorded in the receipt, but the
  2213. temporary-image policy does not let those validation failures suppress a
  2214. bitstream that TD can still generate.
  2215. """
  2216. del timing_status, structural_status
  2217. return bool(route_artifact_usable)
  2218. def td_stage_artifact_usable(
  2219. completed: subprocess.CompletedProcess[str] | None,
  2220. artifact: Path,
  2221. ) -> bool:
  2222. return bool(
  2223. completed is not None
  2224. and completed.returncode == 0
  2225. and not td_log_has_error(completed.stdout, completed.stderr)
  2226. and artifact.is_file()
  2227. and artifact.stat().st_size > 0
  2228. )
  2229. def structural_resource_gate(
  2230. resources: Mapping[str, Any] | None,
  2231. ) -> dict[str, Any]:
  2232. failures: list[str] = []
  2233. utilization = resources.get("utilization") if isinstance(resources, Mapping) else None
  2234. if not isinstance(utilization, Mapping):
  2235. failures.append("resource_report_missing")
  2236. else:
  2237. expected = {
  2238. "bram": 0,
  2239. "bram32k": 0,
  2240. "bram128k": 0,
  2241. "bram256k": 0,
  2242. "dsp": 0,
  2243. "pad": 41,
  2244. "ireg": 0,
  2245. }
  2246. for name, value in expected.items():
  2247. observed = utilization.get(name)
  2248. used = observed.get("used") if isinstance(observed, Mapping) else None
  2249. if used != value:
  2250. failures.append(f"{name}_used:{used}")
  2251. return {
  2252. "status": "pass" if not failures else "fail",
  2253. "required": {
  2254. "bram": 0,
  2255. "bram32k": 0,
  2256. "bram128k": 0,
  2257. "bram256k": 0,
  2258. "dsp": 0,
  2259. "pad": 41,
  2260. "ireg": 0,
  2261. },
  2262. "failures": failures,
  2263. }
  2264. def _stage_result(completed: subprocess.CompletedProcess[str] | None) -> dict[str, Any] | None:
  2265. if completed is None:
  2266. return None
  2267. timed_out = _was_timed_out(completed)
  2268. command = (
  2269. [str(value) for value in completed.args]
  2270. if isinstance(completed.args, Sequence) and not isinstance(completed.args, (str, bytes))
  2271. else [str(completed.args)]
  2272. )
  2273. return {
  2274. "status": "fail_timeout" if timed_out else ("pass" if completed.returncode == 0 else "fail"),
  2275. "timed_out": timed_out,
  2276. "returncode": completed.returncode,
  2277. "log_has_error": td_log_has_error(completed.stdout, completed.stderr),
  2278. "critical_warning_count": td_critical_warning_count(completed.stdout, completed.stderr),
  2279. "command": command,
  2280. "stdout_tail": _tail(completed.stdout),
  2281. "stderr_tail": _tail(completed.stderr),
  2282. }
  2283. def _td_artifact(path: Path) -> dict[str, Any]:
  2284. target = Path(path).resolve()
  2285. return {
  2286. "path": str(target),
  2287. "size": target.stat().st_size,
  2288. "sha256": sha256_file(target),
  2289. }
  2290. def _write_td_console_log(
  2291. path: Path,
  2292. completed: subprocess.CompletedProcess[str],
  2293. ) -> Path:
  2294. target = Path(path).resolve()
  2295. target.parent.mkdir(parents=True, exist_ok=True)
  2296. target.write_text(
  2297. "=== STDOUT ===\n"
  2298. + str(completed.stdout or "")
  2299. + "\n=== STDERR ===\n"
  2300. + str(completed.stderr or "")
  2301. + "\n",
  2302. encoding="utf-8",
  2303. newline="\n",
  2304. )
  2305. return target
  2306. def td_measurement_artifacts(
  2307. *,
  2308. syn_dir: Path,
  2309. phy_dir: Path,
  2310. bitgen_dir: Path,
  2311. bitstream: Path,
  2312. syn: subprocess.CompletedProcess[str] | None,
  2313. phy: subprocess.CompletedProcess[str] | None,
  2314. bitgen: subprocess.CompletedProcess[str] | None,
  2315. ) -> tuple[dict[str, dict[str, Any]], list[str]]:
  2316. directories = {
  2317. "syn": Path(syn_dir).resolve(),
  2318. "phy": Path(phy_dir).resolve(),
  2319. "bitgen": Path(bitgen_dir).resolve(),
  2320. }
  2321. stage_results = {"syn": syn, "phy": phy, "bitgen": bitgen}
  2322. paths = {
  2323. "bitstream": Path(bitstream).resolve(),
  2324. "syn_area": directories["syn"] / f"{PROFILE}_gate.area",
  2325. "phy_area": directories["phy"] / f"{PROFILE}_phy.area",
  2326. "timing": directories["phy"] / f"{PROFILE}_pr.timing",
  2327. "syn_qor": directories["syn"] / f"{PROFILE}_gate.qor",
  2328. "syn_cdc": directories["syn"] / f"{PROFILE}_cdc.rpt",
  2329. "phy_cdc": directories["phy"] / f"{PROFILE}_cdc.rpt",
  2330. "syn_fsm": directories["syn"] / f"{PROFILE}_fsm_encoding.rpt",
  2331. "phy_fsm": directories["phy"] / f"{PROFILE}_fsm_encoding.rpt",
  2332. }
  2333. failures: list[str] = []
  2334. for phase, completed in stage_results.items():
  2335. if completed is None:
  2336. failures.append(f"measurement_stage_missing:{phase}")
  2337. continue
  2338. try:
  2339. paths[f"{phase}_log"] = _write_td_console_log(
  2340. directories[phase] / f"{PROFILE}_{phase}.console.log",
  2341. completed,
  2342. )
  2343. except OSError as exc:
  2344. failures.append(f"measurement_stage_log_failed:{phase}:{type(exc).__name__}")
  2345. artifacts: dict[str, dict[str, Any]] = {}
  2346. for name, path in paths.items():
  2347. if not path.is_file() or path.stat().st_size <= 0:
  2348. failures.append(f"measurement_artifact_missing:{name}")
  2349. continue
  2350. try:
  2351. artifacts[name] = _td_artifact(path)
  2352. except OSError as exc:
  2353. failures.append(f"measurement_artifact_unreadable:{name}:{type(exc).__name__}")
  2354. return artifacts, sorted(set(failures))
  2355. def _resource_delta_unavailable(reason: str) -> dict[str, Any]:
  2356. return {
  2357. "schema": "prod2u-p4-normal-v3-resource-delta-v1",
  2358. "advisory_only": True,
  2359. "affects_build_status": False,
  2360. "available": False,
  2361. "reason": reason,
  2362. }
  2363. def td_source_states_clean(
  2364. source_before: Mapping[str, Any],
  2365. source_after: Mapping[str, Any],
  2366. staged_manifest: Mapping[str, Any],
  2367. ) -> bool:
  2368. return (
  2369. source_before.get("clean") is True
  2370. and source_after.get("clean") is True
  2371. and staged_manifest.get("source_state_clean") is True
  2372. )
  2373. def td_build_payload(
  2374. run: bool,
  2375. top: str = PROFILE,
  2376. *,
  2377. work_root: Path | None = None,
  2378. verification_run_id: str | None = None,
  2379. ) -> dict[str, Any]:
  2380. shared_run_id = normalize_verification_run_id(verification_run_id)
  2381. metadata = {
  2382. "schema": TD_RECEIPT_SCHEMA,
  2383. "build_mode": TD_BUILD_MODE_PRODUCTION,
  2384. "resource_variant": RESOURCE_VARIANT_PRODUCTION,
  2385. "top": top,
  2386. "top_module": TOP_MODULE,
  2387. "pin_profile": PIN_PROFILE,
  2388. "profile": PROFILE,
  2389. "runtime_profile": RUNTIME_PROFILE,
  2390. "verification_run_id": shared_run_id,
  2391. "safety": dict(SAFETY_BOUNDARY),
  2392. }
  2393. if top != PROFILE:
  2394. return {**metadata, "status": "fail", "reason": f"unsupported TD top: {top}"}
  2395. try:
  2396. resolved = resolve_work_root(work_root, run=run)
  2397. except ValueError as exc:
  2398. return {**metadata, "status": "blocked_invalid_work_root", "reason": str(exc)}
  2399. if not run:
  2400. return {
  2401. **metadata,
  2402. "status": "skipped",
  2403. "reason": "TD build not requested; pass --run to execute it.",
  2404. "work_root": None if resolved is None else str(resolved),
  2405. }
  2406. assert resolved is not None
  2407. generated_at = utc_now()
  2408. run_id = new_td_run_id()
  2409. if not TD_EXE.is_file():
  2410. return {**metadata, "status": "blocked", "reason": f"missing TD executable: {TD_EXE}"}
  2411. script_failures: list[str] = []
  2412. for phase, script in TD_SCRIPTS.items():
  2413. if not script.is_file():
  2414. script_failures.append(f"missing_script:{phase}")
  2415. continue
  2416. for marker in td_forbidden_script_markers(
  2417. script.read_text(encoding="utf-8", errors="replace")
  2418. ):
  2419. script_failures.append(f"forbidden_script_command:{phase}:{marker}")
  2420. pins = pin_binding_gate()
  2421. if script_failures or pins["status"] != "pass":
  2422. return {
  2423. **metadata,
  2424. "status": "blocked_pin_binding_invalid" if pins["status"] != "pass" else "fail",
  2425. "script_failures": script_failures,
  2426. "pin_binding_gate": pins,
  2427. }
  2428. try:
  2429. staged = prepare_td_build_dirs(work_root=resolved)
  2430. except (OSError, RuntimeError, ValueError) as exc:
  2431. return {**metadata, "status": "fail_build_preparation", "reason": str(exc)}
  2432. syn = run_td_script(staged.syn, TD_SCRIPTS["syn"].name)
  2433. syn_resources = parse_area_report(staged.syn / f"{PROFILE}_gate.area")
  2434. syn_utilization = syn_resources.get("utilization") if isinstance(syn_resources, Mapping) else None
  2435. syn_ireg = syn_utilization.get("ireg") if isinstance(syn_utilization, Mapping) else None
  2436. syn_cdc = structural_cdc_gate(
  2437. parse_td_cdc_report(staged.syn / f"{PROFILE}_cdc.rpt"),
  2438. async_reg_count=parse_qor_attribute_count(
  2439. staged.syn / f"{PROFILE}_gate.qor",
  2440. "async_reg",
  2441. ),
  2442. input_register_count=syn_ireg.get("used") if isinstance(syn_ireg, Mapping) else None,
  2443. )
  2444. syn_fsm = structural_fsm_gate(
  2445. parse_td_fsm_report(staged.syn / f"{PROFILE}_fsm_encoding.rpt"),
  2446. syn_log=syn.stdout,
  2447. )
  2448. syn_ok = (
  2449. syn.returncode == 0
  2450. and not td_log_has_error(syn.stdout, syn.stderr)
  2451. and td_critical_warning_count(syn.stdout, syn.stderr) == 0
  2452. and syn_cdc["status"] == "pass"
  2453. and syn_fsm["status"] == "pass"
  2454. and "CDC_GATE_PASS=1" in syn.stdout
  2455. and "FSM_ENCODING_GATE_PASS=sequential" in syn.stdout
  2456. )
  2457. syn_artifact_usable = td_stage_artifact_usable(
  2458. syn,
  2459. staged.syn / f"{PROFILE}_gate.db",
  2460. )
  2461. phy: subprocess.CompletedProcess[str] | None = None
  2462. if syn_artifact_usable:
  2463. phy = run_td_script(staged.phy, TD_SCRIPTS["phy"].name)
  2464. phy_ok = bool(
  2465. phy
  2466. and phy.returncode == 0
  2467. and not td_log_has_error(phy.stdout, phy.stderr)
  2468. and td_critical_warning_count(phy.stdout, phy.stderr) == 0
  2469. )
  2470. route_artifact_usable = td_stage_artifact_usable(
  2471. phy,
  2472. staged.phy / f"{PROFILE}_pr.db",
  2473. )
  2474. resources = parse_area_report(staged.phy / f"{PROFILE}_phy.area")
  2475. if resources is not None and phy is not None:
  2476. resources["packing"] = parse_packing_summary(phy.stdout, phy.stderr)
  2477. timing = parse_timing_report(staged.phy / f"{PROFILE}_pr.timing")
  2478. timing_result = timing_gate(timing)
  2479. resource_structural = structural_resource_gate(resources)
  2480. routed_pins = post_route_pin_gate(
  2481. parse_td_io_report(staged.phy / f"{PROFILE}_phy.area")
  2482. )
  2483. utilization = resources.get("utilization") if isinstance(resources, Mapping) else None
  2484. ireg = utilization.get("ireg") if isinstance(utilization, Mapping) else None
  2485. cdc_structural = structural_cdc_gate(
  2486. parse_td_cdc_report(staged.phy / f"{PROFILE}_cdc.rpt"),
  2487. async_reg_count=parse_qor_attribute_count(
  2488. staged.syn / f"{PROFILE}_gate.qor",
  2489. "async_reg",
  2490. ),
  2491. input_register_count=ireg.get("used") if isinstance(ireg, Mapping) else None,
  2492. )
  2493. fsm_structural = structural_fsm_gate(
  2494. parse_td_fsm_report(staged.phy / f"{PROFILE}_fsm_encoding.rpt"),
  2495. syn_log=syn.stdout,
  2496. )
  2497. structural = {
  2498. "status": (
  2499. "pass"
  2500. if resource_structural["status"] == "pass"
  2501. and routed_pins["status"] == "pass"
  2502. and cdc_structural["status"] == "pass"
  2503. and fsm_structural["status"] == "pass"
  2504. else "fail"
  2505. ),
  2506. "resources": resource_structural,
  2507. "pins": routed_pins,
  2508. "cdc": cdc_structural,
  2509. "fsm_encoding": fsm_structural,
  2510. "failures": [
  2511. *resource_structural["failures"],
  2512. *(f"pins:{failure}" for failure in routed_pins["failures"]),
  2513. *(f"cdc:{failure}" for failure in cdc_structural["failures"]),
  2514. *(f"fsm:{failure}" for failure in fsm_structural["failures"]),
  2515. ],
  2516. }
  2517. bitgen: subprocess.CompletedProcess[str] | None = None
  2518. if td_bitgen_eligible(
  2519. route_artifact_usable=route_artifact_usable,
  2520. timing_status=str(timing_result["status"]),
  2521. structural_status=str(structural["status"]),
  2522. ):
  2523. bitgen = run_td_script(staged.bitgen, TD_SCRIPTS["bitgen"].name)
  2524. bitgen_ok = bool(
  2525. bitgen
  2526. and bitgen.returncode == 0
  2527. and not td_log_has_error(bitgen.stdout, bitgen.stderr)
  2528. and td_critical_warning_count(bitgen.stdout, bitgen.stderr) == 0
  2529. )
  2530. bitstream = staged.bitgen / f"{PROFILE}.bit"
  2531. bitstream_sha256 = (
  2532. sha256_file(bitstream)
  2533. if bitstream.is_file() and bitstream.stat().st_size > 0
  2534. else None
  2535. )
  2536. measurement_artifacts, measurement_failures = td_measurement_artifacts(
  2537. syn_dir=staged.syn,
  2538. phy_dir=staged.phy,
  2539. bitgen_dir=staged.bitgen,
  2540. bitstream=bitstream,
  2541. syn=syn,
  2542. phy=phy,
  2543. bitgen=bitgen,
  2544. )
  2545. state_after = source_state()
  2546. staged_source_manifest = verify_staged_source_manifest(staged)
  2547. source_state_stable = state_after == staged.source_state
  2548. source_binding_gate = {
  2549. "status": (
  2550. "pass"
  2551. if staged_source_manifest["status"] == "pass"
  2552. and source_state_stable
  2553. and td_source_states_clean(staged.source_state, state_after, staged_source_manifest)
  2554. else "fail"
  2555. ),
  2556. "source_state_stable": source_state_stable,
  2557. "failures": [
  2558. *staged_source_manifest["failures"],
  2559. *([] if source_state_stable else ["repository_source_state_changed_during_build"]),
  2560. *([] if staged.source_state.get("clean") is True else ["repository_source_state_dirty_at_start"]),
  2561. *([] if state_after.get("clean") is True else ["repository_source_state_dirty_after_build"]),
  2562. ],
  2563. }
  2564. passed = (
  2565. syn_ok
  2566. and phy_ok
  2567. and timing_result["status"] == "pass"
  2568. and structural["status"] == "pass"
  2569. and bitgen_ok
  2570. and bitstream_sha256 is not None
  2571. and source_binding_gate["status"] == "pass"
  2572. and not measurement_failures
  2573. )
  2574. payload = {
  2575. **metadata,
  2576. "status": "pass" if passed else "fail",
  2577. "generated_at": generated_at,
  2578. "run_id": run_id,
  2579. "commit": staged.source_state["commit"],
  2580. "source_state": dict(staged.source_state),
  2581. "repository_state_after": state_after,
  2582. "bitstream_sha256": bitstream_sha256,
  2583. "synthesis_input_manifest": dict(staged.synthesis_input_manifest),
  2584. "synthesis_input_hash": staged.synthesis_input_manifest["sha256"],
  2585. "clean": dict(staged.clean),
  2586. "staged_source_manifest": staged_source_manifest,
  2587. "source_binding_gate": source_binding_gate,
  2588. "work_root": str(resolved),
  2589. "build_dirs": {
  2590. "syn": str(staged.syn),
  2591. "phy": str(staged.phy),
  2592. "bitgen": str(staged.bitgen),
  2593. },
  2594. "td_tool": {
  2595. "path": str(TD_EXE.resolve()),
  2596. "executable": TD_EXE.name,
  2597. "version": "6.2.2.198412",
  2598. "sha256": sha256_file(TD_EXE),
  2599. },
  2600. "pin_binding_gate": pins,
  2601. "post_route_pin_gate": routed_pins,
  2602. "binding_gate": {"status": "pass", "target_device": TARGET_DEVICE},
  2603. "syn": _stage_result(syn),
  2604. "phy": _stage_result(phy),
  2605. "bitgen": _stage_result(bitgen),
  2606. "bitstream": (
  2607. None
  2608. if bitstream_sha256 is None
  2609. else {"path": str(bitstream), "size": bitstream.stat().st_size}
  2610. ),
  2611. "resources": resources,
  2612. "resource_gate": {
  2613. "status": "pass" if resources is not None else "fail",
  2614. "advisory_only": True,
  2615. "affects_build_status": False,
  2616. },
  2617. "resource_delta": _resource_delta_unavailable("new_minimal_baseline_pending"),
  2618. "structural_gate": structural,
  2619. "timing": timing,
  2620. "timing_gate": timing_result,
  2621. "error_summary": {
  2622. "error_count": sum(
  2623. int(bool(item and item.get("log_has_error")))
  2624. for item in (_stage_result(syn), _stage_result(phy), _stage_result(bitgen))
  2625. ),
  2626. "critical_warning_count": sum(
  2627. int(item.get("critical_warning_count", 0))
  2628. for item in (_stage_result(syn), _stage_result(phy), _stage_result(bitgen))
  2629. if item
  2630. ),
  2631. },
  2632. "authority_boundary": (
  2633. "This TD receipt covers synthesis, placement, routing, bit generation, timing, "
  2634. "resources, and source binding only. It performs no cable or board action."
  2635. ),
  2636. }
  2637. if measurement_failures:
  2638. payload["measurement_artifact_failures"] = measurement_failures
  2639. else:
  2640. payload["measurement_artifacts"] = measurement_artifacts
  2641. return payload
  2642. def _emit(payload: Mapping[str, Any], args: argparse.Namespace, label: str) -> int:
  2643. if getattr(args, "report_file", None):
  2644. try:
  2645. report_file = resolve_report_file(args.report_file)
  2646. except ValueError as exc:
  2647. print(json.dumps({"status": "fail", "reason": str(exc)}, indent=2) if getattr(args, "json", False) else f"{label}: fail")
  2648. return 1
  2649. write_json_report(payload, report_file)
  2650. print(json.dumps(dict(payload), indent=2) if getattr(args, "json", False) else f"{label}: {payload.get('status', 'unknown')}")
  2651. return 0 if payload.get("status") == "pass" else 1
  2652. def package_required_files() -> tuple[str, ...]:
  2653. return (
  2654. "fw.bit",
  2655. "package-info.json",
  2656. "evidence/td-primary-receipt.json",
  2657. "evidence/td-confirmation-receipt.json",
  2658. "evidence/validation-summary.json",
  2659. "evidence/package-selftest-result.json",
  2660. "config/host-contract.json",
  2661. "schemas/host-contract.schema.json",
  2662. "bootstrap.ps1",
  2663. "selftest.ps1",
  2664. "run.ps1",
  2665. "SEND_HEX.ps1",
  2666. "INITIALIZE_DISABLE.ps1",
  2667. "PROGRAM_SRAM.ps1",
  2668. "README.zh-CN.md",
  2669. )
  2670. def package_selftest_payload(
  2671. package_dir: Path,
  2672. *,
  2673. verification_run_id: str | None = None,
  2674. ) -> dict[str, Any]:
  2675. package = Path(package_dir).expanduser().resolve()
  2676. run_id = normalize_verification_run_id(verification_run_id)
  2677. info_path = package / "package-info.json"
  2678. primary_td_path = package / "evidence" / "td-primary-receipt.json"
  2679. confirmation_td_path = package / "evidence" / "td-confirmation-receipt.json"
  2680. validation_path = package / "evidence" / "validation-summary.json"
  2681. packaged_selftest_path = package / "evidence" / "package-selftest-result.json"
  2682. bitstream = package / "fw.bit"
  2683. failures: list[str] = []
  2684. info: Mapping[str, Any] = {}
  2685. primary_td: Mapping[str, Any] = {}
  2686. confirmation_td: Mapping[str, Any] = {}
  2687. validation: Mapping[str, Any] = {}
  2688. packaged_selftest: Mapping[str, Any] = {}
  2689. inputs = (
  2690. (info_path, "package_info"),
  2691. (primary_td_path, "primary_td"),
  2692. (confirmation_td_path, "confirmation_td"),
  2693. (validation_path, "validation"),
  2694. (packaged_selftest_path, "packaged_selftest"),
  2695. )
  2696. loaded_inputs: dict[str, Mapping[str, Any]] = {}
  2697. for path, label in inputs:
  2698. try:
  2699. loaded = json.loads(path.read_text(encoding="utf-8-sig"))
  2700. except (OSError, UnicodeError, json.JSONDecodeError) as exc:
  2701. failures.append(f"{label}_unreadable:{exc}")
  2702. continue
  2703. if not isinstance(loaded, Mapping):
  2704. failures.append(f"{label}_not_object")
  2705. else:
  2706. loaded_inputs[label] = loaded
  2707. info = loaded_inputs.get("package_info", {})
  2708. primary_td = loaded_inputs.get("primary_td", {})
  2709. confirmation_td = loaded_inputs.get("confirmation_td", {})
  2710. validation = loaded_inputs.get("validation", {})
  2711. packaged_selftest = loaded_inputs.get("packaged_selftest", {})
  2712. digest = None
  2713. if not bitstream.is_file() or bitstream.stat().st_size <= 0:
  2714. failures.append("bitstream_missing")
  2715. else:
  2716. digest = sha256_file(bitstream)
  2717. if info:
  2718. if info.get("schema") != "prod2u-p4-normal-v3-folder-package-info-v3":
  2719. failures.append("package_info_schema_mismatch")
  2720. if info.get("profile") != RUNTIME_PROFILE:
  2721. failures.append("package_profile_mismatch")
  2722. commit = str(info.get("commit", ""))
  2723. if not re.fullmatch(r"[0-9a-f]{40}", commit):
  2724. failures.append("package_commit_invalid")
  2725. if info.get("bitstream_sha256") != digest:
  2726. failures.append("package_bitstream_sha256_mismatch")
  2727. expected_name = (
  2728. f"prod2u-p4-normal-{commit}-{digest[:16]}"
  2729. if digest is not None and re.fullmatch(r"[0-9a-f]{40}", commit)
  2730. else None
  2731. )
  2732. if expected_name is not None and package.name != expected_name:
  2733. failures.append("package_folder_name_mismatch")
  2734. if re.fullmatch(r"[0-9a-f]{40}", commit) and package.parent.name != commit:
  2735. failures.append("package_commit_parent_mismatch")
  2736. if info.get("td_receipt_sha256") != (
  2737. sha256_file(primary_td_path) if primary_td_path.is_file() else None
  2738. ):
  2739. failures.append("package_td_receipt_sha256_mismatch")
  2740. if info.get("confirmation_td_receipt_sha256") != (
  2741. sha256_file(confirmation_td_path) if confirmation_td_path.is_file() else None
  2742. ):
  2743. failures.append("package_confirmation_td_receipt_sha256_mismatch")
  2744. if info.get("validation_summary_sha256") != (
  2745. sha256_file(validation_path) if validation_path.is_file() else None
  2746. ):
  2747. failures.append("package_validation_summary_sha256_mismatch")
  2748. if info.get("package_selftest_result_sha256") != (
  2749. sha256_file(packaged_selftest_path) if packaged_selftest_path.is_file() else None
  2750. ):
  2751. failures.append("package_selftest_result_sha256_mismatch")
  2752. actual_files = {
  2753. path.relative_to(package).as_posix(): sha256_file(path)
  2754. for path in sorted(package.rglob("*"))
  2755. if path.is_file() and path not in {info_path, packaged_selftest_path}
  2756. }
  2757. expected_files = info.get("file_sha256") if isinstance(info, Mapping) else None
  2758. if not isinstance(expected_files, Mapping) or dict(expected_files) != actual_files:
  2759. failures.append("package_file_hash_map_mismatch")
  2760. checked_files = [
  2761. relative
  2762. for relative in package_required_files()
  2763. if (package / relative).is_file()
  2764. ]
  2765. for relative in package_required_files():
  2766. if not (package / relative).is_file():
  2767. failures.append(f"package_file_missing:{relative}")
  2768. commit = info.get("commit") if info else None
  2769. if primary_td:
  2770. if primary_td.get("commit") != commit:
  2771. failures.append("primary_td_commit_mismatch")
  2772. if primary_td.get("bitstream_sha256") != digest:
  2773. failures.append("primary_td_bitstream_sha256_mismatch")
  2774. if info.get("synthesis_input_hash") != primary_td.get("synthesis_input_hash"):
  2775. failures.append("primary_td_synthesis_input_hash_mismatch")
  2776. if confirmation_td:
  2777. if confirmation_td.get("commit") != commit:
  2778. failures.append("confirmation_td_commit_mismatch")
  2779. if info.get("confirmation_bitstream_sha256") != confirmation_td.get(
  2780. "bitstream_sha256"
  2781. ):
  2782. failures.append("confirmation_td_bitstream_sha256_binding_mismatch")
  2783. if info.get("confirmation_synthesis_input_hash") != confirmation_td.get(
  2784. "synthesis_input_hash"
  2785. ):
  2786. failures.append("confirmation_td_synthesis_input_hash_mismatch")
  2787. if validation:
  2788. if validation.get("schema") != "prod2u-p4-normal-v3-validation-summary-v1":
  2789. failures.append("validation_summary_schema_mismatch")
  2790. if validation.get("commit") != commit or validation.get("bitstream_sha256") != digest:
  2791. failures.append("validation_summary_binding_mismatch")
  2792. layers = validation.get("layers")
  2793. if not isinstance(layers, Mapping):
  2794. failures.append("validation_layers_missing")
  2795. else:
  2796. for name, layer in layers.items():
  2797. status = layer.get("status") if isinstance(layer, Mapping) else None
  2798. if status not in {"pass", "fail", "not_run"}:
  2799. failures.append(f"validation_layer_status_invalid:{name}")
  2800. comparisons = {
  2801. "td_confirmation_synthesis": (
  2802. confirmation_td.get("synthesis_input_hash"),
  2803. primary_td.get("synthesis_input_hash"),
  2804. ),
  2805. "td_confirmation_manifest": (
  2806. (
  2807. confirmation_td.get("synthesis_input_manifest", {}).get("sha256")
  2808. if isinstance(confirmation_td.get("synthesis_input_manifest"), Mapping)
  2809. else None
  2810. ),
  2811. (
  2812. primary_td.get("synthesis_input_manifest", {}).get("sha256")
  2813. if isinstance(primary_td.get("synthesis_input_manifest"), Mapping)
  2814. else None
  2815. ),
  2816. ),
  2817. }
  2818. bitstream_layer = layers.get("td_confirmation_bitstream")
  2819. if (
  2820. not isinstance(bitstream_layer, Mapping)
  2821. or bitstream_layer.get("status")
  2822. != td_receipt_bitstream_binding_status(confirmation_td)
  2823. ):
  2824. failures.append(
  2825. "validation_layer_semantic_mismatch:td_confirmation_bitstream"
  2826. )
  2827. for name, (observed, expected) in comparisons.items():
  2828. expected_status = (
  2829. "not_run"
  2830. if observed in {None, ""}
  2831. else "pass" if observed == expected else "fail"
  2832. )
  2833. layer = layers.get(name)
  2834. if not isinstance(layer, Mapping) or layer.get("status") != expected_status:
  2835. failures.append(f"validation_layer_semantic_mismatch:{name}")
  2836. script_result: dict[str, Any] = {"status": "not_run", "returncode": None}
  2837. selftest = package / "selftest.ps1"
  2838. if not failures and selftest.is_file():
  2839. completed = subprocess.run(
  2840. [
  2841. "powershell.exe",
  2842. "-NoProfile",
  2843. "-ExecutionPolicy",
  2844. "Bypass",
  2845. "-File",
  2846. str(selftest),
  2847. ],
  2848. cwd=package,
  2849. env=tool_env(),
  2850. text=True,
  2851. stdout=subprocess.PIPE,
  2852. stderr=subprocess.PIPE,
  2853. timeout=60,
  2854. check=False,
  2855. )
  2856. script_result = {
  2857. "status": "pass" if completed.returncode == 0 else "fail",
  2858. "returncode": completed.returncode,
  2859. "stdout_tail": _tail(completed.stdout),
  2860. "stderr_tail": _tail(completed.stderr),
  2861. }
  2862. if completed.returncode != 0:
  2863. failures.append("package_selftest_script_failed")
  2864. return {
  2865. "schema": PACKAGE_RECEIPT_SCHEMA,
  2866. "status": "pass" if not failures else "fail",
  2867. "generated_at": utc_now(),
  2868. "verification_run_id": run_id,
  2869. "commit": info.get("commit") if info else None,
  2870. "bitstream_sha256": digest,
  2871. "package_dir": str(package),
  2872. "package_info_sha256": sha256_file(info_path) if info_path.is_file() else None,
  2873. "td_receipt_sha256": sha256_file(primary_td_path) if primary_td_path.is_file() else None,
  2874. "confirmation_td_receipt_sha256": (
  2875. sha256_file(confirmation_td_path) if confirmation_td_path.is_file() else None
  2876. ),
  2877. "validation_summary_sha256": sha256_file(validation_path) if validation_path.is_file() else None,
  2878. "package_selftest_result_sha256": (
  2879. sha256_file(packaged_selftest_path) if packaged_selftest_path.is_file() else None
  2880. ),
  2881. "td_run_id": primary_td.get("run_id") if primary_td else None,
  2882. "confirmation_td_run_id": confirmation_td.get("run_id") if confirmation_td else None,
  2883. "synthesis_input_hash": primary_td.get("synthesis_input_hash") if primary_td else None,
  2884. "confirmation_synthesis_input_hash": (
  2885. confirmation_td.get("synthesis_input_hash") if confirmation_td else None
  2886. ),
  2887. "confirmation_bitstream_sha256": (
  2888. confirmation_td.get("bitstream_sha256") if confirmation_td else None
  2889. ),
  2890. "validation_status": (
  2891. "fail"
  2892. if isinstance(validation.get("layers"), Mapping)
  2893. and any(
  2894. isinstance(layer, Mapping) and layer.get("status") == "fail"
  2895. for layer in validation["layers"].values()
  2896. )
  2897. else "pass"
  2898. ),
  2899. "packaged_selftest_status": packaged_selftest.get("status") if packaged_selftest else None,
  2900. "package_file_sha256": actual_files,
  2901. "package_file_manifest_sha256": canonical_sha256(actual_files) if actual_files else None,
  2902. "bound_files": checked_files,
  2903. "failures": sorted(set(failures)),
  2904. "selftest": script_result,
  2905. "safety": dict(SAFETY_BOUNDARY),
  2906. }
  2907. def cmd_strict_offline(args: argparse.Namespace) -> int:
  2908. return _emit(
  2909. strict_offline_gate_payload(
  2910. work_root=args.work_root,
  2911. verification_run_id=args.verification_run_id,
  2912. ),
  2913. args,
  2914. "p4-normal-v3-strict-offline-gate",
  2915. )
  2916. def cmd_hdl_sim(args: argparse.Namespace) -> int:
  2917. return _emit(hdl_sim_payload(run=args.run, backend=args.backend, work_root=args.work_root), args, "hdl-sim")
  2918. def cmd_formal(args: argparse.Namespace) -> int:
  2919. return _emit(formal_payload(run=args.run, work_root=args.work_root), args, "formal")
  2920. def cmd_td_build(args: argparse.Namespace) -> int:
  2921. return _emit(
  2922. td_build_payload(
  2923. run=args.run,
  2924. top=args.top,
  2925. work_root=args.work_root,
  2926. verification_run_id=args.verification_run_id,
  2927. ),
  2928. args,
  2929. "td-build",
  2930. )
  2931. def cmd_package_selftest(args: argparse.Namespace) -> int:
  2932. return _emit(
  2933. package_selftest_payload(
  2934. args.package_dir,
  2935. verification_run_id=args.verification_run_id,
  2936. ),
  2937. args,
  2938. "package-selftest",
  2939. )
  2940. def _gate_is_pass(receipt: Mapping[str, Any], name: str) -> bool:
  2941. value = receipt.get(name)
  2942. return isinstance(value, Mapping) and value.get("status") == "pass"
  2943. def _td_final_failures(
  2944. receipt: Mapping[str, Any],
  2945. *,
  2946. label: str,
  2947. expected_commit: str,
  2948. ) -> list[str]:
  2949. failures: list[str] = []
  2950. prefix = f"{label}:"
  2951. if receipt.get("schema") != TD_RECEIPT_SCHEMA:
  2952. failures.append(prefix + "schema")
  2953. if receipt.get("status") != "pass":
  2954. failures.append(prefix + "status")
  2955. if receipt.get("commit") != expected_commit:
  2956. failures.append(prefix + "commit")
  2957. if not re.fullmatch(r"[0-9a-f]{64}", str(receipt.get("bitstream_sha256", ""))):
  2958. failures.append(prefix + "bitstream_sha256")
  2959. if not re.fullmatch(r"[0-9a-f]{64}", str(receipt.get("synthesis_input_hash", ""))):
  2960. failures.append(prefix + "synthesis_input_hash")
  2961. source = receipt.get("source_state")
  2962. if not isinstance(source, Mapping) or source.get("clean") is not True or source.get("commit") != expected_commit:
  2963. failures.append(prefix + "source_state")
  2964. for gate_name in (
  2965. "source_binding_gate",
  2966. "pin_binding_gate",
  2967. "post_route_pin_gate",
  2968. "binding_gate",
  2969. "timing_gate",
  2970. "structural_gate",
  2971. ):
  2972. if not _gate_is_pass(receipt, gate_name):
  2973. failures.append(prefix + gate_name)
  2974. resources = receipt.get("resources")
  2975. utilization = resources.get("utilization") if isinstance(resources, Mapping) else None
  2976. required_resources = {
  2977. "bram": 0,
  2978. "bram32k": 0,
  2979. "bram128k": 0,
  2980. "bram256k": 0,
  2981. "dsp": 0,
  2982. "pad": 41,
  2983. "ireg": 0,
  2984. }
  2985. for name, expected in required_resources.items():
  2986. item = utilization.get(name) if isinstance(utilization, Mapping) else None
  2987. used = item.get("used") if isinstance(item, Mapping) else None
  2988. if used != expected:
  2989. failures.append(prefix + f"resource:{name}:{used}")
  2990. timing = receipt.get("timing")
  2991. if not isinstance(timing, Mapping):
  2992. failures.append(prefix + "timing")
  2993. else:
  2994. for name in ("fmax_mhz", "worst_setup_slack_ns", "worst_hold_slack_ns"):
  2995. value = timing.get(name)
  2996. if not isinstance(value, (int, float)) or isinstance(value, bool) or value <= 0:
  2997. failures.append(prefix + f"timing:{name}")
  2998. if timing.get("error_count") != 0:
  2999. failures.append(prefix + "timing:error_count")
  3000. routed_pins = receipt.get("post_route_pin_gate")
  3001. if isinstance(routed_pins, Mapping):
  3002. if routed_pins.get("row_count") != 41:
  3003. failures.append(prefix + "post_route_pin_count")
  3004. observed = routed_pins.get("observed")
  3005. expected_limits = {
  3006. "x_limit_raw": ("B9", "LVCMOS33", "PULLUP"),
  3007. "y_limit_raw": ("A11", "LVCMOS33", "PULLUP"),
  3008. }
  3009. for signal, expected in expected_limits.items():
  3010. row = observed.get(signal) if isinstance(observed, Mapping) else None
  3011. values = (
  3012. row.get("location"),
  3013. row.get("io_standard"),
  3014. row.get("pull_type"),
  3015. ) if isinstance(row, Mapping) else None
  3016. if values != expected:
  3017. failures.append(prefix + f"post_route_pin:{signal}")
  3018. for phase_name in ("syn", "phy", "bitgen"):
  3019. phase = receipt.get(phase_name)
  3020. if (
  3021. not isinstance(phase, Mapping)
  3022. or phase.get("status") != "pass"
  3023. or phase.get("returncode") != 0
  3024. or phase.get("log_has_error") is not False
  3025. or phase.get("critical_warning_count") != 0
  3026. ):
  3027. failures.append(prefix + f"phase:{phase_name}")
  3028. bitstream = receipt.get("bitstream")
  3029. if not isinstance(bitstream, Mapping) or not isinstance(bitstream.get("size"), int) or bitstream.get("size") <= 0:
  3030. failures.append(prefix + "bitstream_artifact")
  3031. else:
  3032. path = Path(str(bitstream.get("path", "")))
  3033. if not path.is_file() or path.stat().st_size != bitstream.get("size"):
  3034. failures.append(prefix + "bitstream_path")
  3035. elif sha256_file(path) != receipt.get("bitstream_sha256"):
  3036. failures.append(prefix + "bitstream_file_hash")
  3037. return failures
  3038. def _offline_final_failures(
  3039. receipt: Mapping[str, Any],
  3040. *,
  3041. expected_commit: str,
  3042. ) -> list[str]:
  3043. failures: list[str] = []
  3044. if receipt.get("schema") != OFFLINE_RECEIPT_SCHEMA:
  3045. failures.append("offline:schema")
  3046. if receipt.get("status") != "pass" or receipt.get("commit") != expected_commit:
  3047. failures.append("offline:status_or_commit")
  3048. source = receipt.get("source_state")
  3049. if not isinstance(source, Mapping) or source.get("clean") is not True:
  3050. failures.append("offline:source_state")
  3051. layers = receipt.get("layers")
  3052. required = receipt.get("required_layers")
  3053. if required != ["source_integrity", "unit", "hdl_sim", "formal"]:
  3054. failures.append("offline:required_layers")
  3055. for name in required if isinstance(required, list) else []:
  3056. layer = layers.get(name) if isinstance(layers, Mapping) else None
  3057. if not isinstance(layer, Mapping) or layer.get("status") != "pass":
  3058. failures.append(f"offline:layer:{name}")
  3059. if receipt.get("failures") != []:
  3060. failures.append("offline:failures")
  3061. return failures
  3062. def _package_final_failures(
  3063. receipt: Mapping[str, Any],
  3064. *,
  3065. expected_commit: str,
  3066. expected_bitstream_sha256: str,
  3067. ) -> list[str]:
  3068. failures: list[str] = []
  3069. if receipt.get("schema") != PACKAGE_RECEIPT_SCHEMA:
  3070. failures.append("package:schema")
  3071. if receipt.get("status") != "pass" or receipt.get("commit") != expected_commit:
  3072. failures.append("package:status_or_commit")
  3073. if receipt.get("bitstream_sha256") != expected_bitstream_sha256:
  3074. failures.append("package:bitstream_sha256")
  3075. if receipt.get("failures") != []:
  3076. failures.append("package:failures")
  3077. selftest = receipt.get("selftest")
  3078. if not isinstance(selftest, Mapping) or selftest.get("status") != "pass" or selftest.get("returncode") != 0:
  3079. failures.append("package:selftest")
  3080. package_dir = Path(str(receipt.get("package_dir", "")))
  3081. info_path = package_dir / "package-info.json"
  3082. bitstream = package_dir / "fw.bit"
  3083. if not info_path.is_file() or not bitstream.is_file():
  3084. failures.append("package:artifacts")
  3085. else:
  3086. try:
  3087. info = load_receipt(info_path)
  3088. except (OSError, UnicodeError, json.JSONDecodeError, ValueError):
  3089. failures.append("package:info_unreadable")
  3090. else:
  3091. if info.get("commit") != expected_commit or info.get("bitstream_sha256") != expected_bitstream_sha256:
  3092. failures.append("package:info_binding")
  3093. if sha256_file(bitstream) != expected_bitstream_sha256:
  3094. failures.append("package:file_hash")
  3095. return failures
  3096. def cmd_final_gate(args: argparse.Namespace) -> int:
  3097. try:
  3098. paths = {
  3099. "offline": resolve_input_receipt(args.offline_receipt),
  3100. "td": resolve_input_receipt(args.td_receipt),
  3101. "td_confirmation": resolve_input_receipt(args.confirmation_td_receipt),
  3102. "package": resolve_input_receipt(args.package_receipt),
  3103. }
  3104. except ValueError as exc:
  3105. return _emit({"status": "fail", "reason": str(exc)}, args, "p4-normal-v3-final-gate")
  3106. try:
  3107. child_receipts = {name: load_receipt(path) for name, path in paths.items()}
  3108. except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as exc:
  3109. return _emit(
  3110. {"status": "fail", "reason": f"input_receipt_unreadable:{exc}"},
  3111. args,
  3112. "p4-normal-v3-final-gate",
  3113. )
  3114. state = source_state()
  3115. expected_commit = state.get("commit")
  3116. if (
  3117. state.get("status") != "pass"
  3118. or state.get("clean") is not True
  3119. or not re.fullmatch(r"[0-9a-f]{40}", str(expected_commit))
  3120. ):
  3121. failures = ["final_source_state_not_clean"]
  3122. else:
  3123. failures = []
  3124. failures.extend(
  3125. _offline_final_failures(
  3126. child_receipts["offline"],
  3127. expected_commit=str(expected_commit),
  3128. )
  3129. )
  3130. failures.extend(
  3131. _td_final_failures(
  3132. child_receipts["td"],
  3133. label="td",
  3134. expected_commit=str(expected_commit),
  3135. )
  3136. )
  3137. failures.extend(
  3138. _td_final_failures(
  3139. child_receipts["td_confirmation"],
  3140. label="td_confirmation",
  3141. expected_commit=str(expected_commit),
  3142. )
  3143. )
  3144. for name, receipt in child_receipts.items():
  3145. if args.verification_run_id and receipt.get("verification_run_id") != args.verification_run_id:
  3146. failures.append(f"verification_run_id_mismatch:{name}")
  3147. primary = child_receipts["td"]
  3148. confirmation = child_receipts["td_confirmation"]
  3149. package = child_receipts["package"]
  3150. failures.extend(
  3151. _package_final_failures(
  3152. package,
  3153. expected_commit=str(expected_commit),
  3154. expected_bitstream_sha256=str(primary.get("bitstream_sha256", "")),
  3155. )
  3156. )
  3157. if primary.get("synthesis_input_hash") != confirmation.get("synthesis_input_hash"):
  3158. failures.append("td_synthesis_input_hash_mismatch")
  3159. if primary.get("run_id") == confirmation.get("run_id"):
  3160. failures.append("td_run_id_not_independent")
  3161. if primary.get("work_root") == confirmation.get("work_root"):
  3162. failures.append("td_work_root_not_independent")
  3163. if primary.get("td_tool") != confirmation.get("td_tool"):
  3164. failures.append("td_tool_mismatch")
  3165. if primary.get("synthesis_input_manifest") != confirmation.get("synthesis_input_manifest"):
  3166. failures.append("td_synthesis_input_manifest_mismatch")
  3167. if primary.get("bitstream_sha256") != package.get("bitstream_sha256"):
  3168. failures.append("package_bitstream_mismatch")
  3169. payload = {
  3170. "schema": "prod2u-p4-normal-v3-final-gate-v3",
  3171. "status": "pass" if not failures else "fail",
  3172. "generated_at": utc_now(),
  3173. "verification_run_id": args.verification_run_id,
  3174. "commit": expected_commit,
  3175. "source_state": state,
  3176. "child_receipts": {
  3177. name: {"path": str(paths[name]), "sha256": sha256_file(paths[name])}
  3178. for name in paths
  3179. },
  3180. "bitstream_sha256": primary.get("bitstream_sha256"),
  3181. "synthesis_input_hash": primary.get("synthesis_input_hash"),
  3182. "failures": sorted(set(failures)),
  3183. "safety": dict(SAFETY_BOUNDARY),
  3184. "authority_boundary": (
  3185. "This receipt aggregates offline, two independent TD builds, and package evidence. "
  3186. "It does not prove board programming or mechanical direction."
  3187. ),
  3188. }
  3189. return _emit(payload, args, "p4-normal-v3-final-gate")
  3190. def _common_output_options(parser: argparse.ArgumentParser) -> None:
  3191. parser.add_argument("--json", action="store_true")
  3192. parser.add_argument("--report-file", type=Path)
  3193. def build_parser() -> argparse.ArgumentParser:
  3194. parser = argparse.ArgumentParser(description=__doc__)
  3195. sub = parser.add_subparsers(dest="command", required=True)
  3196. offline = sub.add_parser("p4-normal-v3-strict-offline-gate", help="run every required offline Normal v3 layer")
  3197. offline.add_argument("--work-root", type=Path, required=True)
  3198. offline.add_argument("--verification-run-id")
  3199. _common_output_options(offline)
  3200. offline.set_defaults(func=cmd_strict_offline)
  3201. hdl = sub.add_parser("hdl-sim", help="run registered Icarus, Verilator, or cocotb targets")
  3202. hdl.add_argument("--run", action="store_true")
  3203. hdl.add_argument("--backend", choices=("icarus", "verilator", "cocotb", "all"), default="icarus")
  3204. hdl.add_argument("--work-root", type=Path)
  3205. _common_output_options(hdl)
  3206. hdl.set_defaults(func=cmd_hdl_sim)
  3207. formal = sub.add_parser("formal", help="run all registered Normal v3 formal targets")
  3208. formal.add_argument("--run", action="store_true")
  3209. formal.add_argument("--work-root", type=Path)
  3210. _common_output_options(formal)
  3211. formal.set_defaults(func=cmd_formal)
  3212. td = sub.add_parser("td-build", help="build the sole production TD top")
  3213. td.add_argument("--run", action="store_true")
  3214. td.add_argument("--top", choices=(PROFILE,), default=PROFILE)
  3215. td.add_argument("--work-root", type=Path)
  3216. td.add_argument("--verification-run-id")
  3217. _common_output_options(td)
  3218. td.set_defaults(func=cmd_td_build)
  3219. package = sub.add_parser("package-selftest", help="validate a folder delivery without hardware access")
  3220. package.add_argument("--package-dir", type=Path, required=True)
  3221. package.add_argument("--verification-run-id")
  3222. _common_output_options(package)
  3223. package.set_defaults(func=cmd_package_selftest)
  3224. final = sub.add_parser("p4-normal-v3-final-gate", help="aggregate clean offline, TD, and package receipts")
  3225. final.add_argument("--offline-receipt", type=Path, required=True)
  3226. final.add_argument("--td-receipt", type=Path, required=True, help="optimized production O-A receipt")
  3227. final.add_argument("--confirmation-td-receipt", type=Path, required=True, help="independent optimized production O-B receipt")
  3228. final.add_argument("--package-receipt", type=Path, required=True)
  3229. final.add_argument("--verification-run-id")
  3230. _common_output_options(final)
  3231. final.set_defaults(func=cmd_final_gate)
  3232. return parser
  3233. def main(argv: Sequence[str] | None = None) -> int:
  3234. args = build_parser().parse_args(argv)
  3235. return int(args.func(args))
  3236. if __name__ == "__main__":
  3237. raise SystemExit(main())