prod2u_p4_harness.py 147 KB

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