prod2u_p4_harness.py 160 KB

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