prod2u_p4_harness.py 188 KB

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