prod2u_p4_harness.py 164 KB

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