prod2u_p4_harness.py 175 KB

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