prod2u_p4_harness.py 186 KB

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