prod2u_p4_harness.py 177 KB

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