prod2u_p4_harness.py 150 KB

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