prod2u_p4_harness.py 184 KB

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