prod2u_p4_harness.py 176 KB

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