prod2u_p4_harness.py 172 KB

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