prod2u_p4_harness.py 151 KB

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