prod2u_p4_harness.py 177 KB

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