prod2u_p4_harness.py 173 KB

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