prod2u_p4_harness.py 182 KB

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