prod2u_p4_harness.py 150 KB

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