prod2u_p4_harness.py 170 KB

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