prod2u_p4_harness.py 151 KB

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