| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871 |
- #!/usr/bin/env python3
- """Offline verification and TD build harness for Prod2U Profile 4 Normal v3."""
- from __future__ import annotations
- import argparse
- import hashlib
- import json
- import os
- import re
- import shutil
- import subprocess
- import sys
- import uuid
- from concurrent.futures import ThreadPoolExecutor
- from datetime import datetime, timezone
- from pathlib import Path
- from typing import Any, Mapping, Sequence
- sys.dont_write_bytecode = True
- ROOT = Path(__file__).resolve().parents[1]
- TOOLS = ROOT / "tools"
- if str(TOOLS) not in sys.path:
- sys.path.insert(0, str(TOOLS))
- from prod2u_p4_normal_v3_build import ( # noqa: E402
- PRODUCTION_RTL_SOURCES,
- build_synthesis_input_manifest,
- )
- PROFILE = "prod2u_p4_normal_v3"
- RUNTIME_PROFILE = "prod2u-p4-normal-actuator-binary921-v3"
- TOP_MODULE = "prod2u_p4_normal_v3_top"
- PIN_PROFILE = "prod2u-p4-normal-v3"
- TARGET_DEVICE = "EF2L45BG256B"
- TD_EXE = Path(r"C:\Anlogic\TD_Release_2026.1_SP1.198.412\bin\td_commands_prompt.exe")
- DEFAULT_TOOLCHAIN_ROOT = Path.home() / "CodexToolchains" / "CPLD" / "oss-cad-suite" / "latest"
- DEFAULT_VENV_ROOT = Path.home() / "CodexToolchains" / "CPLD" / "venvs"
- DEFAULT_TIMEOUT_SECONDS = {
- "icarus_compile": 120.0,
- "icarus_run": 180.0,
- "verilator": 300.0,
- "cocotb": 600.0,
- "formal": 600.0,
- "td": 1800.0,
- }
- FORMAL_MAX_WORKERS = 4
- HDL_RECEIPT_SCHEMA = "prod2u-p4-normal-v3-hdl-sim-receipt-v1"
- FORMAL_RECEIPT_SCHEMA = "prod2u-p4-normal-v3-formal-receipt-v1"
- TD_RECEIPT_SCHEMA = "prod2u-p4-normal-v3-td-build-receipt-v2"
- TD_BUILD_MODE_PRODUCTION = "production"
- RESOURCE_VARIANT_PRODUCTION = "minimal_production"
- OFFLINE_RECEIPT_SCHEMA = "prod2u-p4-normal-v3-strict-offline-gate-v1"
- PACKAGE_RECEIPT_SCHEMA = "prod2u-p4-normal-v3-package-selftest-v1"
- CDC_REPORT_SCHEMA = "prod2u-p4-normal-v3-cdc-v2"
- FSM_REPORT_SCHEMA = "prod2u-p4-normal-v3-fsm-encoding-v2"
- TARGET_MANIFEST_SCHEMA = "prod2u-p4-verification-target-manifest-v1"
- TARGET_MANIFEST_PATH = ROOT / "config" / "prod2u_p4_verification_targets_v1.json"
- TARGET_MANIFEST_LAYERS = ("unit", "icarus", "verilator", "cocotb", "formal")
- EXPECTED_CDC_SYNC_REGISTERS = frozenset(
- {
- "u_uart_rx/rx_sync_pipe[0]",
- "u_uart_rx/rx_sync_pipe[1]",
- }
- )
- EXPECTED_CDC_FALSE_PATH_ENDPOINTS = frozenset(
- {
- "u_uart_rx/rx_sync_pipe[0]",
- }
- )
- EXPECTED_FSM_AXES = {"x": 2, "y": 2}
- REQUIRED_MOTOR_LIMIT_PINS = {
- "motor_en_n": {"location": "A10", "direction": "OUTPUT", "pull_type": "NONE"},
- "x_step": {"location": "C11", "direction": "OUTPUT", "pull_type": "NONE"},
- "x_dir": {"location": "B12", "direction": "OUTPUT", "pull_type": "NONE"},
- "y_step": {"location": "D15", "direction": "OUTPUT", "pull_type": "NONE"},
- "y_dir": {"location": "H14", "direction": "OUTPUT", "pull_type": "NONE"},
- "x_limit_raw": {"location": "B9", "direction": "INPUT", "pull_type": "PULLUP"},
- "y_limit_raw": {"location": "A11", "direction": "INPUT", "pull_type": "PULLUP"},
- }
- BUILD_ROOT_RELATIVE = Path("td") / PROFILE
- TD_SCRIPTS = {
- "syn": ROOT / "td" / "syn" / f"{PROFILE}.tcl",
- "phy": ROOT / "td" / "phy" / f"{PROFILE}.tcl",
- "bitgen": ROOT / "td" / "bitgen" / f"{PROFILE}.tcl",
- }
- SAFETY_BOUNDARY = {
- "opens_serial": False,
- "programs_hardware": False,
- "installs_drivers": False,
- }
- ICARUS_EXCLUDED_TESTBENCHES = {"prod2u_p4_axis_executor_z_tb"}
- FORBIDDEN_TD_COMMANDS = {
- "connect_cable",
- "download",
- "erase_flash",
- "open_cable",
- "program",
- "program_flash",
- "program_sram",
- "program_spibin",
- }
- def utc_now() -> str:
- return datetime.now(timezone.utc).isoformat()
- def new_td_run_id() -> str:
- return uuid.uuid4().hex
- def normalize_verification_run_id(value: str | None) -> str:
- if value is None or not str(value).strip():
- raise ValueError("verification_run_id is required")
- normalized = str(value).strip().lower()
- if not re.fullmatch(r"[0-9a-f]{32}", normalized):
- raise ValueError("verification_run_id must be 32 lowercase hex digits")
- return normalized
- def valid_td_run_id(value: object) -> bool:
- return isinstance(value, str) and re.fullmatch(r"[0-9a-f]{32}", value) is not None
- def normalized_td_work_root(value: object) -> str | None:
- if not isinstance(value, str) or not value.strip():
- return None
- candidate = Path(value)
- if not candidate.is_absolute():
- return None
- return os.path.normcase(os.path.normpath(str(candidate.resolve(strict=False))))
- def td_receipts_are_independent(
- primary: Mapping[str, Any],
- confirmation: Mapping[str, Any],
- ) -> bool:
- primary_run_id = primary.get("run_id")
- confirmation_run_id = confirmation.get("run_id")
- primary_work_root = normalized_td_work_root(primary.get("work_root"))
- confirmation_work_root = normalized_td_work_root(confirmation.get("work_root"))
- return bool(
- valid_td_run_id(primary_run_id)
- and valid_td_run_id(confirmation_run_id)
- and primary_run_id != confirmation_run_id
- and primary_work_root is not None
- and confirmation_work_root is not None
- and primary_work_root != confirmation_work_root
- )
- def sha256_file(path: Path) -> str:
- digest = hashlib.sha256()
- with Path(path).open("rb") as stream:
- for chunk in iter(lambda: stream.read(1024 * 1024), b""):
- digest.update(chunk)
- return digest.hexdigest()
- def td_receipt_bitstream_binding_status(receipt: Mapping[str, Any]) -> str:
- digest = receipt.get("bitstream_sha256")
- if digest is None or digest == "":
- return "not_run"
- if not re.fullmatch(r"[0-9a-f]{64}", str(digest)):
- return "fail"
- candidates: list[Mapping[str, Any]] = []
- direct = receipt.get("bitstream")
- if isinstance(direct, Mapping):
- candidates.append(direct)
- measurements = receipt.get("measurement_artifacts")
- measured = measurements.get("bitstream") if isinstance(measurements, Mapping) else None
- if isinstance(measured, Mapping):
- candidates.append(measured)
- for candidate in candidates:
- if candidate.get("sha256") != digest:
- continue
- path = Path(str(candidate.get("path", "")))
- if path.is_file() and sha256_file(path) == digest:
- return "pass"
- return "fail"
- def canonical_sha256(value: object) -> str:
- encoded = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("ascii")
- return hashlib.sha256(encoded).hexdigest()
- def validation_layer_summary(layers: object) -> str:
- if not isinstance(layers, Mapping):
- return "fail"
- statuses = {
- layer.get("status") if isinstance(layer, Mapping) else None
- for layer in layers.values()
- }
- for status in ("fail", "running", "not_run"):
- if status in statuses:
- return status
- return "pass" if statuses and statuses == {"pass"} else "fail"
- def load_receipt(path: Path) -> dict[str, Any]:
- payload = json.loads(Path(path).read_text(encoding="utf-8-sig"))
- if not isinstance(payload, dict):
- raise ValueError(f"receipt root must be an object: {path}")
- return payload
- def load_target_manifest() -> dict[str, Any]:
- payload = json.loads(TARGET_MANIFEST_PATH.read_text(encoding="utf-8"))
- if not isinstance(payload, dict):
- raise ValueError("target manifest root must be an object")
- if payload.get("schema") != TARGET_MANIFEST_SCHEMA:
- raise ValueError("target manifest schema mismatch")
- if payload.get("version") != 1:
- raise ValueError("target manifest version mismatch")
- if payload.get("profile") != PROFILE:
- raise ValueError("target manifest profile mismatch")
- layers = payload.get("layers")
- if not isinstance(layers, dict) or set(layers) != set(TARGET_MANIFEST_LAYERS):
- raise ValueError("target manifest layers mismatch")
- for layer in TARGET_MANIFEST_LAYERS:
- values = layers.get(layer)
- if not isinstance(values, list) or not values:
- raise ValueError(f"target manifest layer must be a non-empty list: {layer}")
- for layer in ("unit", "icarus", "verilator", "cocotb"):
- values = layers[layer]
- if any(not isinstance(value, str) or not value for value in values):
- raise ValueError(f"target manifest contains invalid name: {layer}")
- if len(values) != len(set(values)):
- raise ValueError(f"target manifest contains duplicate names: {layer}")
- formal_names: list[str] = []
- for entry in layers["formal"]:
- if not isinstance(entry, dict) or set(entry) != {"name", "tasks"}:
- raise ValueError("target manifest formal entry invalid")
- name = entry.get("name")
- tasks = entry.get("tasks")
- if not isinstance(name, str) or not name or not isinstance(tasks, list):
- raise ValueError("target manifest formal entry invalid")
- if any(not isinstance(task, str) or not task for task in tasks):
- raise ValueError(f"target manifest formal task invalid: {name}")
- if len(tasks) != len(set(tasks)):
- raise ValueError(f"target manifest formal task duplicate: {name}")
- formal_names.append(name)
- if len(formal_names) != len(set(formal_names)):
- raise ValueError("target manifest contains duplicate formal names")
- return payload
- def _normalized_target_layer(layer: str, value: object) -> object:
- if layer == "formal":
- if isinstance(value, Mapping):
- items = value.items()
- elif isinstance(value, Sequence) and not isinstance(value, (str, bytes)):
- items = (
- (entry.get("name"), entry.get("tasks"))
- for entry in value
- if isinstance(entry, Mapping)
- )
- else:
- return {}
- normalized: dict[str, list[str]] = {}
- for name, tasks in items:
- if isinstance(name, str) and isinstance(tasks, Sequence) and not isinstance(tasks, (str, bytes)):
- normalized[name] = [str(task) for task in tasks]
- return dict(sorted(normalized.items()))
- if not isinstance(value, Sequence) or isinstance(value, (str, bytes)):
- return []
- return sorted(str(item) for item in value)
- def target_manifest_evidence(layer: str, observed: object) -> dict[str, Any]:
- failures: list[str] = []
- try:
- manifest = load_target_manifest()
- except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as exc:
- return {
- "schema": TARGET_MANIFEST_SCHEMA,
- "version": 1,
- "sha256": "0" * 64,
- "layer": layer,
- "status": "fail",
- "expected": {},
- "observed": observed,
- "failures": [f"target_manifest_unavailable:{type(exc).__name__}:{exc}"],
- }
- layers = manifest["layers"]
- manifest_sha256 = canonical_sha256(manifest)
- if layer == "all":
- expected_all = {
- name: _normalized_target_layer(name, layers[name])
- for name in TARGET_MANIFEST_LAYERS
- }
- observed_mapping = observed if isinstance(observed, Mapping) else {}
- observed_all = {
- name: _normalized_target_layer(name, observed_mapping.get(name))
- for name in TARGET_MANIFEST_LAYERS
- }
- for name in TARGET_MANIFEST_LAYERS:
- child = target_manifest_evidence(name, observed_all[name])
- failures.extend(child["failures"])
- return {
- "schema": TARGET_MANIFEST_SCHEMA,
- "version": manifest["version"],
- "sha256": manifest_sha256,
- "layer": layer,
- "status": "pass" if not failures else "fail",
- "expected": expected_all,
- "observed": observed_all,
- "failures": sorted(set(failures)),
- }
- if layer not in TARGET_MANIFEST_LAYERS:
- failures.append(f"target_manifest_layer_unknown:{layer}")
- expected = []
- normalized_observed = _normalized_target_layer(layer, observed)
- else:
- expected = _normalized_target_layer(layer, layers[layer])
- normalized_observed = _normalized_target_layer(layer, observed)
- if not normalized_observed:
- failures.append(f"target_manifest_empty_observed:{layer}")
- if layer == "formal":
- expected_names = set(expected)
- observed_names = set(normalized_observed)
- for name in sorted(expected_names - observed_names):
- failures.append(f"target_manifest_missing:{layer}:{name}")
- for name in sorted(observed_names - expected_names):
- failures.append(f"target_manifest_extra:{layer}:{name}")
- for name in sorted(expected_names & observed_names):
- if normalized_observed[name] != expected[name]:
- failures.append(f"target_manifest_task_drift:{name}")
- else:
- expected_names = set(expected)
- observed_names = set(normalized_observed)
- if len(normalized_observed) != len(observed_names):
- failures.append(f"target_manifest_duplicate:{layer}")
- for name in sorted(expected_names - observed_names):
- failures.append(f"target_manifest_missing:{layer}:{name}")
- for name in sorted(observed_names - expected_names):
- failures.append(f"target_manifest_extra:{layer}:{name}")
- return {
- "schema": TARGET_MANIFEST_SCHEMA,
- "version": manifest["version"],
- "sha256": manifest_sha256,
- "layer": layer,
- "status": "pass" if not failures else "fail",
- "expected": expected,
- "observed": normalized_observed,
- "failures": sorted(set(failures)),
- }
- def _tail(value: str, limit: int = 4000) -> str:
- return value[-limit:]
- def configured_timeout(name: str) -> float:
- default = DEFAULT_TIMEOUT_SECONDS[name]
- raw = os.environ.get(f"PROD2U_P4_TIMEOUT_{name.upper()}_SECONDS", "").strip()
- if not raw:
- return default
- try:
- value = float(raw)
- except ValueError:
- return default
- return value if value > 0 else default
- def _timeout_text(value: str | bytes | None) -> str:
- if isinstance(value, bytes):
- return value.decode(errors="replace")
- return value or ""
- def _timed_out_result(command: Sequence[str], exc: subprocess.TimeoutExpired) -> subprocess.CompletedProcess[str]:
- completed = subprocess.CompletedProcess(
- list(command),
- None,
- _timeout_text(exc.stdout or exc.output),
- _timeout_text(exc.stderr),
- )
- completed.timed_out = True # type: ignore[attr-defined]
- return completed
- def _run_bounded(command: Sequence[str], *, timeout_name: str, **kwargs: Any) -> subprocess.CompletedProcess[str]:
- try:
- return subprocess.run(list(command), timeout=configured_timeout(timeout_name), **kwargs)
- except subprocess.TimeoutExpired as exc:
- return _timed_out_result(command, exc)
- def _was_timed_out(completed: subprocess.CompletedProcess[str] | None) -> bool:
- return bool(completed is not None and getattr(completed, "timed_out", False))
- def write_json_report(payload: Mapping[str, Any], path: Path) -> None:
- target = Path(path)
- target.parent.mkdir(parents=True, exist_ok=True)
- target.write_text(json.dumps(dict(payload), indent=2) + "\n", encoding="utf-8", newline="\n")
- def _git(*args: str) -> subprocess.CompletedProcess[str]:
- return subprocess.run(
- ["git", *args],
- cwd=ROOT,
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- check=False,
- )
- def source_state() -> dict[str, Any]:
- commit_result = _git("rev-parse", "HEAD")
- status_result = _git("status", "--porcelain", "--untracked-files=all")
- commit = commit_result.stdout.strip().lower()
- changes = []
- for line in status_result.stdout.splitlines():
- if not line.strip():
- continue
- relative = line[3:].replace("\\", "/") if len(line) >= 4 else line.strip()
- if relative == ".planning" or relative.startswith(".planning/"):
- continue
- changes.append(line)
- failures: list[str] = []
- if commit_result.returncode != 0 or not re.fullmatch(r"[0-9a-f]{40}", commit):
- failures.append("git_commit_unavailable")
- if status_result.returncode != 0:
- failures.append("git_status_unavailable")
- return {
- "status": "pass" if not failures else "fail",
- "commit": commit,
- "clean": status_result.returncode == 0 and not changes,
- "tracked_changes": changes,
- "failures": failures,
- }
- def current_commit() -> str:
- state = source_state()
- if state["status"] != "pass":
- raise RuntimeError("unable to bind verification evidence to the current Git commit")
- return str(state["commit"])
- def resolve_work_root(work_root: Path | None, *, run: bool) -> Path | None:
- if work_root is None:
- if run:
- raise ValueError("--work-root is required when tools are executed")
- return None
- resolved = Path(work_root).expanduser().resolve()
- repository = ROOT.resolve()
- if resolved == repository or repository in resolved.parents:
- raise ValueError("work root must be outside the repository")
- if resolved.exists() and not resolved.is_dir():
- raise ValueError("work root must be a directory")
- if run:
- resolved.mkdir(parents=True, exist_ok=True)
- return resolved
- def resolve_report_file(report_file: Path) -> Path:
- resolved = Path(report_file).expanduser().resolve()
- repository = ROOT.resolve()
- if resolved == repository or repository in resolved.parents:
- raise ValueError("report file must be outside the repository")
- return resolved
- def resolve_input_receipt(receipt_file: Path) -> Path:
- resolved = Path(receipt_file).expanduser().resolve()
- repository = ROOT.resolve()
- if resolved == repository or repository in resolved.parents:
- raise ValueError("input receipt must be outside the repository")
- if not resolved.is_file():
- raise ValueError(f"input receipt is missing: {resolved}")
- return resolved
- def _tool_candidates(name: str) -> list[Path]:
- if name == "verilator":
- executable_names = ["verilator_bin.exe", "verilator.exe"]
- else:
- executable_names = [name, f"{name}.exe"]
- roots: list[Path] = []
- configured = os.environ.get("OSS_CAD_SUITE_ROOT", "").strip()
- if configured:
- roots.append(Path(configured))
- roots.append(DEFAULT_TOOLCHAIN_ROOT)
- candidates: list[Path] = []
- for root in roots:
- for directory in (root / "bin", root):
- candidates.extend(directory / executable for executable in executable_names)
- return candidates
- def _native_verilator_binary(path: str | Path) -> str | None:
- candidate = Path(path).expanduser().resolve()
- if candidate.name.lower() not in {"verilator_bin.exe", "verilator.exe"}:
- return None
- return str(candidate) if candidate.is_file() else None
- def toolchain_roots() -> list[Path]:
- roots: list[Path] = []
- configured = os.environ.get("OSS_CAD_SUITE_ROOT", "").strip()
- if configured:
- roots.append(Path(configured))
- roots.append(DEFAULT_TOOLCHAIN_ROOT)
- return list(dict.fromkeys(path.expanduser().resolve() for path in roots))
- def resolve_tool(name: str) -> str | None:
- if name == "verilator":
- for candidate in _tool_candidates(name):
- resolved = _native_verilator_binary(candidate)
- if resolved:
- return resolved
- for executable in ("verilator_bin.exe", "verilator.exe"):
- located = shutil.which(executable)
- if located:
- resolved = _native_verilator_binary(located)
- if resolved:
- return resolved
- return None
- located = shutil.which(name)
- if located:
- return located
- for candidate in _tool_candidates(name):
- if candidate.is_file():
- return str(candidate)
- return None
- def tool_env(extra: Mapping[str, str] | None = None) -> dict[str, str]:
- env = os.environ.copy()
- path_parts: list[str] = []
- for root in toolchain_roots():
- bin_dir = root / "bin"
- lib_dir = root / "lib"
- verilator_root = root / "share" / "verilator"
- smtbmc = bin_dir / "yosys-smtbmc.exe.exe"
- if bin_dir.is_dir():
- path_parts.append(str(bin_dir))
- if lib_dir.is_dir():
- path_parts.append(str(lib_dir))
- if verilator_root.is_dir():
- env.setdefault("VERILATOR_ROOT", str(verilator_root))
- if smtbmc.is_file():
- env.setdefault("SMTBMC", str(smtbmc))
- for name in ("iverilog", "sby", "yosys"):
- resolved = resolve_tool(name)
- if resolved:
- path_parts.append(str(Path(resolved).parent))
- if path_parts:
- env["PATH"] = os.pathsep.join(dict.fromkeys([*path_parts, env.get("PATH", "")]))
- env["PYTHONDONTWRITEBYTECODE"] = "1"
- if extra:
- env.update({str(key): str(value) for key, value in extra.items()})
- return env
- def formal_tool_env(work_root: Path) -> dict[str, str]:
- resolved = resolve_work_root(work_root, run=True)
- assert resolved is not None
- env = tool_env()
- wrapper_dir = resolved / "formal-tool-wrappers"
- wrappers: list[Path] = []
- for command in ("yosys-smtbmc", "yosys-witness"):
- executable = next(
- (
- root / "bin" / f"{command}.exe.exe"
- for root in toolchain_roots()
- if (root / "bin" / f"{command}.exe.exe").is_file()
- ),
- None,
- )
- if executable is None:
- continue
- wrapper_dir.mkdir(parents=True, exist_ok=True)
- wrapper = wrapper_dir / f"{command}.cmd"
- wrapper.write_text(
- f'@echo off\r\n"{executable}" %*\r\n',
- encoding="ascii",
- newline="",
- )
- wrappers.append(wrapper)
- if wrappers:
- env["PATH"] = os.pathsep.join([str(wrapper_dir), env.get("PATH", "")])
- return env
- def active_rtl_sources() -> list[str]:
- return [relative for relative in PRODUCTION_RTL_SOURCES if (ROOT / relative).is_file()]
- def hdl_testbenches() -> list[dict[str, Any]]:
- rtl = active_rtl_sources()
- return [
- {
- "name": path.stem,
- "testbench": path.relative_to(ROOT).as_posix(),
- "sources": [*rtl, path.relative_to(ROOT).as_posix()],
- }
- for path in sorted((ROOT / "tests" / "sim").glob("*_tb.v"))
- if path.stem not in ICARUS_EXCLUDED_TESTBENCHES
- ]
- def cocotb_tests() -> list[dict[str, str]]:
- candidates = (
- (
- "prod2u_p4_fast_jog_top",
- "run_prod2u_p4_fast_jog_top.py",
- ),
- (
- "prod2u_p4_normal_v3_ack_only_top_e2e",
- "run_prod2u_p4_normal_v3_ack_only_top_e2e.py",
- ),
- )
- return [
- {"name": name, "runner": f"tests/cocotb/{runner}"}
- for name, runner in candidates
- if (ROOT / "tests" / "cocotb" / runner).is_file()
- ]
- def _formal_tasks(path: Path) -> list[str]:
- tasks: list[str] = []
- in_tasks = False
- for raw_line in path.read_text(encoding="utf-8", errors="replace").splitlines():
- line = raw_line.strip()
- if line == "[tasks]":
- in_tasks = True
- continue
- if in_tasks and line.startswith("["):
- break
- if in_tasks and line and not line.startswith("#"):
- tasks.append(line.split()[0])
- return tasks
- def formal_targets() -> list[dict[str, Any]]:
- targets: list[dict[str, Any]] = []
- for path in sorted((ROOT / "tests" / "formal").glob("*.sby")):
- targets.append(
- {
- "name": path.stem,
- "sby": path.relative_to(ROOT).as_posix(),
- "tasks": _formal_tasks(path),
- }
- )
- return targets
- def formal_source_files(sby_file: Path) -> list[Path]:
- sources: list[Path] = []
- in_files = False
- for raw_line in sby_file.read_text(encoding="utf-8", errors="replace").splitlines():
- line = raw_line.strip()
- if line == "[files]":
- in_files = True
- continue
- if in_files and line.startswith("["):
- break
- if not in_files or not line or line.startswith("#"):
- continue
- candidate = (sby_file.parent / line.split()[0]).resolve()
- if candidate.suffix.casefold() in {".v", ".sv"} and candidate.is_file():
- sources.append(candidate)
- return sources
- def _evidence_path(path: Path) -> str:
- resolved = Path(path).resolve()
- try:
- return resolved.relative_to(ROOT.resolve()).as_posix()
- except ValueError:
- return str(resolved)
- def formal_task_engines(sby_file: Path, tasks: Sequence[str]) -> dict[str, list[str]]:
- task_engines: dict[str, list[str]] = {}
- global_engines: list[str] = []
- in_engines = False
- for raw_line in sby_file.read_text(encoding="utf-8", errors="replace").splitlines():
- line = raw_line.strip()
- if line == "[engines]":
- in_engines = True
- continue
- if in_engines and line.startswith("["):
- break
- if not in_engines or not line or line.startswith("#"):
- continue
- match = re.fullmatch(r"(?:(\S+)\s*:\s*)?(.+)", line)
- if match is None:
- continue
- task_name, engine = match.groups()
- normalized = engine.strip()
- if task_name is None:
- global_engines.append(normalized)
- else:
- task_engines.setdefault(task_name, []).append(normalized)
- names = list(tasks) or ["default"]
- return {
- name: list(task_engines.get(name, global_engines))
- for name in names
- }
- def formal_input_evidence(sby_file: Path, tasks: Sequence[str]) -> dict[str, Any]:
- sources = formal_source_files(sby_file)
- payload: dict[str, Any] = {
- "sby": {
- "path": _evidence_path(sby_file),
- "sha256": sha256_file(sby_file),
- },
- "sources": [
- {"path": _evidence_path(source), "sha256": sha256_file(source)}
- for source in sources
- ],
- "task_engines": formal_task_engines(sby_file, tasks),
- }
- payload["sha256"] = canonical_sha256(payload)
- return payload
- def formal_runtime_evidence(
- workdir: Path,
- configured_engines: Sequence[str],
- ) -> dict[str, Any]:
- texts: list[str] = []
- logfile = workdir / "logfile.txt"
- main_log = ""
- if logfile.is_file():
- main_log = logfile.read_text(encoding="utf-8", errors="replace")
- texts.append(main_log)
- if workdir.is_dir():
- for engine_log in sorted(workdir.glob("engine_*/logfile.txt")):
- texts.append(engine_log.read_text(encoding="utf-8", errors="replace"))
- combined = "\n".join(texts)
- observed_by_index: dict[int, str] = {}
- for match in re.finditer(r"(?im)^.*\]\s+engine_(\d+):\s+([^\r\n]+)$", main_log):
- index = int(match.group(1))
- candidate = match.group(2).strip()
- if candidate and index not in observed_by_index:
- observed_by_index[index] = candidate
- solvers = sorted(set(re.findall(r"(?im)\bSolver:\s*([A-Za-z0-9_.+-]+)", combined)))
- configured = [str(engine).strip() for engine in configured_engines if str(engine).strip()]
- observed = [observed_by_index[index] for index in sorted(observed_by_index)]
- failures: list[str] = []
- if not configured:
- failures.append("formal_engine_config_missing")
- if not observed:
- failures.append("formal_engine_observation_missing")
- elif set(observed) != set(configured):
- failures.append("formal_engine_observation_mismatch")
- if any(engine.split()[0].casefold() == "smtbmc" for engine in configured) and not solvers:
- failures.append("formal_solver_observation_missing")
- explicit_solvers = sorted(
- {
- parts[1].casefold()
- for engine in configured
- if len(parts := engine.split()) > 1 and parts[0].casefold() == "smtbmc"
- }
- )
- if explicit_solvers and set(solver.casefold() for solver in solvers) != set(explicit_solvers):
- failures.append("formal_solver_observation_mismatch")
- return {
- "configured_engines": configured,
- "observed_engines": observed,
- "solvers": solvers,
- "failures": failures,
- }
- def formal_compiled_property_counts(workdir: Path) -> dict[str, Any]:
- design_json = workdir / "model" / "design.json"
- failures: list[str] = []
- assertion_ids: set[str] = set()
- cover_ids: set[str] = set()
- design_sha256 = "0" * 64
- try:
- payload = json.loads(design_json.read_text(encoding="utf-8"))
- except (OSError, UnicodeError, json.JSONDecodeError) as exc:
- payload = None
- failures.append(f"formal_compiled_properties_unavailable:{type(exc).__name__}")
- if isinstance(payload, Mapping):
- design_sha256 = sha256_file(design_json)
- modules = payload.get("modules")
- if isinstance(modules, Sequence) and not isinstance(modules, (str, bytes)):
- for module in modules:
- if not isinstance(module, Mapping):
- continue
- module_name = str(module.get("name", "")).strip()
- cell_sorts = module.get("cell_sorts")
- if not module_name or not isinstance(cell_sorts, Sequence) or isinstance(cell_sorts, (str, bytes)):
- continue
- for cell_sort in cell_sorts:
- cells = cell_sort.get("cells") if isinstance(cell_sort, Mapping) else None
- if not isinstance(cells, Sequence) or isinstance(cells, (str, bytes)):
- continue
- for cell in cells:
- if not isinstance(cell, Mapping):
- continue
- parameters = cell.get("parameters")
- flavor = parameters.get("FLAVOR") if isinstance(parameters, Mapping) else None
- cell_name = str(cell.get("name", "")).strip()
- if not cell_name:
- continue
- property_id = f"{module_name}.{cell_name}"
- if flavor == "assert":
- assertion_ids.add(property_id)
- elif flavor == "cover":
- cover_ids.add(property_id)
- return {
- "design_json": str(design_json),
- "design_sha256": design_sha256,
- "assertion_count": len(assertion_ids),
- "assertion_ids": sorted(assertion_ids),
- "cover_count": len(cover_ids),
- "cover_ids": sorted(cover_ids),
- "failures": failures,
- }
- def formal_tool_version_evidence(
- name: str,
- executable: str,
- version_args: Sequence[str],
- env: Mapping[str, str],
- ) -> dict[str, Any]:
- path = Path(executable).resolve()
- failures: list[str] = []
- digest = "0" * 64
- if path.is_file():
- digest = sha256_file(path)
- else:
- failures.append(f"formal_tool_path_invalid:{name}")
- try:
- completed = subprocess.run(
- [str(path), *version_args],
- cwd=ROOT,
- env=dict(env),
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- timeout=30,
- check=False,
- )
- except (OSError, subprocess.TimeoutExpired) as exc:
- completed = None
- failures.append(f"formal_tool_version_probe_failed:{name}:{type(exc).__name__}")
- output = "" if completed is None else "\n".join((completed.stdout, completed.stderr)).strip()
- version = next((line.strip() for line in output.splitlines() if line.strip()), "")
- if completed is not None and completed.returncode != 0:
- failures.append(f"formal_tool_version_probe_returncode:{name}:{completed.returncode}")
- if not version:
- failures.append(f"formal_tool_version_missing:{name}")
- return {
- "name": name,
- "path": str(path),
- "sha256": digest,
- "version": version,
- "status": "pass" if not failures else "fail",
- "failures": failures,
- }
- def formal_toolchain_evidence(
- sby: str,
- yosys: str,
- solvers: Sequence[str],
- work_root: Path,
- ) -> dict[str, Any]:
- env = formal_tool_env(work_root)
- sby_evidence = formal_tool_version_evidence("sby", sby, ["--version"], env)
- yosys_evidence = formal_tool_version_evidence("yosys", yosys, ["-V"], env)
- solver_args = {
- "yices": ("yices-smt2", ["--version"]),
- "boolector": ("boolector", ["--version"]),
- "z3": ("z3", ["-version"]),
- }
- solver_evidence: list[dict[str, Any]] = []
- failures = [*sby_evidence["failures"], *yosys_evidence["failures"]]
- for solver in sorted(set(str(value).casefold() for value in solvers if str(value).strip())):
- command, args = solver_args.get(solver, (solver, ["--version"]))
- executable = resolve_tool(command)
- if executable is None:
- evidence = {
- "name": solver,
- "path": "",
- "sha256": "0" * 64,
- "version": "",
- "status": "fail",
- "failures": [f"formal_solver_tool_missing:{solver}"],
- }
- else:
- evidence = formal_tool_version_evidence(solver, executable, args, env)
- solver_evidence.append(evidence)
- failures.extend(evidence["failures"])
- return {
- "status": "pass" if not failures else "fail",
- "sby": sby_evidence,
- "yosys": yosys_evidence,
- "solvers": solver_evidence,
- "failures": failures,
- }
- def formal_property_counts(sby_file: Path) -> dict[str, int | bool]:
- text = "\n".join(
- re.sub(r"//.*$", "", source.read_text(encoding="utf-8", errors="replace"), flags=re.MULTILINE)
- for source in formal_source_files(sby_file)
- )
- sby_text = sby_file.read_text(encoding="utf-8", errors="replace")
- mode_cover = bool(re.search(r"(?mi)^\s*mode\s+cover\s*$", sby_text))
- return {
- "assertion_count": len(re.findall(r"\bassert\s*\(", text)),
- "cover_count": len(re.findall(r"\bcover\s*\(", text)),
- "mode_cover": mode_cover,
- }
- def formal_cover_hit_count(stdout: str, stderr: str) -> int:
- return len(formal_cover_hit_ids(stdout, stderr))
- def formal_cover_hit_ids(*texts: str) -> list[str]:
- hits: set[str] = set()
- for text in texts:
- hits.update(
- re.findall(
- r"(?im)^\s*reached cover statement\s+(\S+)\s+at\s+\S+:\d+",
- text,
- )
- )
- return sorted(hits)
- def formal_task_modes(sby_file: Path, tasks: Sequence[str]) -> dict[str, str]:
- task_modes: dict[str, str] = {}
- global_mode = ""
- in_options = False
- for raw_line in sby_file.read_text(encoding="utf-8", errors="replace").splitlines():
- line = raw_line.strip()
- if line == "[options]":
- in_options = True
- continue
- if in_options and line.startswith("["):
- break
- if not in_options or not line or line.startswith("#"):
- continue
- match = re.fullmatch(r"(?:(\S+)\s*:\s*)?mode\s+(\S+)", line, flags=re.IGNORECASE)
- if match is None:
- continue
- task_name, mode = match.groups()
- if task_name is None:
- global_mode = mode.casefold()
- else:
- task_modes[task_name] = mode.casefold()
- names = list(tasks) or ["default"]
- return {
- name: task_modes.get(name, global_mode or ("cover" if name == "cover" else ""))
- for name in names
- }
- def formal_task_evidence(
- *,
- name: str,
- mode: str,
- workdir: Path,
- configured_engines: Sequence[str],
- ) -> dict[str, Any]:
- status_path = workdir / "status"
- status_raw = ""
- if status_path.is_file():
- status_raw = status_path.read_text(encoding="utf-8", errors="replace").strip()
- status = status_raw.split()[0].upper() if status_raw else "MISSING"
- trace_files = sorted(str(path) for path in workdir.rglob("*.vcd")) if workdir.is_dir() else []
- pass_summary = workdir / "PASS"
- artifact_texts = [
- pass_summary.read_text(encoding="utf-8", errors="replace")
- ] if pass_summary.is_file() else []
- cover_hit_ids = formal_cover_hit_ids(*artifact_texts)
- runtime_evidence = formal_runtime_evidence(workdir, configured_engines)
- compiled_properties = formal_compiled_property_counts(workdir)
- evidence_failures: list[str] = [
- *runtime_evidence["failures"],
- *compiled_properties["failures"],
- ]
- if status != "PASS":
- evidence_failures.append(f"formal_task_status_not_pass:{name}:{status}")
- if mode in {"prove", "bmc"} and compiled_properties["assertion_count"] <= 0:
- evidence_failures.append(f"formal_compiled_assertions_missing:{name}")
- if mode == "cover" and compiled_properties["cover_count"] <= 0:
- evidence_failures.append(f"formal_compiled_covers_missing:{name}")
- if mode == "cover":
- if not trace_files:
- evidence_failures.append(f"formal_cover_trace_missing:{name}")
- compiled_cover_count = int(compiled_properties["cover_count"])
- if len(cover_hit_ids) < compiled_cover_count:
- evidence_failures.append(
- f"formal_cover_hits_incomplete:{name}:{len(cover_hit_ids)}/{compiled_cover_count}"
- )
- if set(cover_hit_ids) != set(compiled_properties["cover_ids"]):
- evidence_failures.append(f"formal_cover_hit_set_mismatch:{name}")
- return {
- "name": name,
- "mode": mode,
- "status": status,
- "status_raw": status_raw,
- "status_file": str(status_path),
- "workdir": str(workdir),
- "trace_files": trace_files,
- "cover_hit_ids": cover_hit_ids,
- "configured_engines": runtime_evidence["configured_engines"],
- "observed_engines": runtime_evidence["observed_engines"],
- "solvers": runtime_evidence["solvers"],
- "compiled_design_json": compiled_properties["design_json"],
- "compiled_design_sha256": compiled_properties["design_sha256"],
- "compiled_assertion_count": compiled_properties["assertion_count"],
- "compiled_assertion_ids": compiled_properties["assertion_ids"],
- "compiled_cover_count": compiled_properties["cover_count"],
- "compiled_cover_ids": compiled_properties["cover_ids"],
- "evidence_failures": evidence_failures,
- }
- def _missing_tools(schema: str, layer: str, missing: Sequence[str], **extra: Any) -> dict[str, Any]:
- return {
- "schema": schema,
- "status": "blocked_missing_tool",
- "verification_layer": layer,
- "profile": PROFILE,
- "missing_tools": sorted(set(missing)),
- "safety": dict(SAFETY_BOUNDARY),
- **extra,
- }
- def _run_icarus(work_root: Path) -> dict[str, Any]:
- iverilog = resolve_tool("iverilog")
- vvp = resolve_tool("vvp")
- missing = [name for name, value in (("iverilog", iverilog), ("vvp", vvp)) if not value]
- targets = hdl_testbenches()
- target_manifest = target_manifest_evidence("icarus", [target["name"] for target in targets])
- if missing:
- return _missing_tools(
- HDL_RECEIPT_SCHEMA,
- "hdl_sim",
- missing,
- backend="icarus",
- tests=targets,
- target_manifest=target_manifest,
- )
- run_dir = work_root / "hdl" / "icarus"
- run_dir.mkdir(parents=True, exist_ok=True)
- results: list[dict[str, Any]] = []
- for target in targets:
- output = run_dir / f"{target['name']}.vvp"
- compile_command = [
- str(iverilog),
- "-g2005-sv",
- "-s",
- str(target["name"]),
- "-o",
- str(output),
- *[str(ROOT / source) for source in target["sources"]],
- ]
- compile_result = _run_bounded(
- compile_command,
- timeout_name="icarus_compile",
- cwd=run_dir,
- env=tool_env(),
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- check=False,
- )
- run_result: subprocess.CompletedProcess[str] | None = None
- if compile_result.returncode == 0 and not _was_timed_out(compile_result):
- run_result = _run_bounded(
- [str(vvp), str(output)],
- timeout_name="icarus_run",
- cwd=run_dir,
- env=tool_env(),
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- check=False,
- )
- timed_out = _was_timed_out(compile_result) or _was_timed_out(run_result)
- passed = not timed_out and compile_result.returncode == 0 and run_result is not None and run_result.returncode == 0
- results.append(
- {
- "name": target["name"],
- "status": "pass" if passed else ("fail_timeout" if timed_out else "fail"),
- "timed_out": timed_out,
- "compile_returncode": compile_result.returncode,
- "run_returncode": None if run_result is None else run_result.returncode,
- "compile_stdout_tail": _tail(compile_result.stdout, 2000),
- "compile_stderr_tail": _tail(compile_result.stderr, 2000),
- "run_stdout_tail": "" if run_result is None else _tail(run_result.stdout, 2000),
- "run_stderr_tail": "" if run_result is None else _tail(run_result.stderr, 2000),
- }
- )
- passed = (
- bool(results) and
- all(item["status"] == "pass" for item in results) and
- target_manifest["status"] == "pass"
- )
- return {
- "schema": HDL_RECEIPT_SCHEMA,
- "status": "pass" if passed else "fail",
- "verification_layer": "hdl_sim",
- "profile": PROFILE,
- "backend": "icarus",
- "work_root": str(work_root),
- "tests": results,
- "target_manifest": target_manifest,
- "safety": dict(SAFETY_BOUNDARY),
- }
- def _write_verilator_stubs(work_root: Path) -> Path:
- path = work_root / "hdl" / "verilator" / "prod2u_p4_guard_stubs.v"
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(
- "/* verilator lint_off DECLFILENAME */\n"
- "module prod2u_p4_solenoid_polarity_must_be_confirmed(); endmodule\n"
- "/* verilator lint_on DECLFILENAME */\n",
- encoding="ascii",
- newline="\n",
- )
- return path
- def verilator_warning_lines(stdout: str, stderr: str) -> list[str]:
- return [
- line.strip()
- for line in f"{stdout}\n{stderr}".splitlines()
- if re.match(r"^\s*%Warning(?:-[A-Z0-9_]+)?:", line)
- ]
- def _run_verilator(work_root: Path) -> dict[str, Any]:
- verilator = resolve_tool("verilator")
- target_names = ["prod2u_p4_normal_v3_top_lint"]
- target_manifest = target_manifest_evidence("verilator", target_names)
- if not verilator:
- return _missing_tools(
- HDL_RECEIPT_SCHEMA,
- "hdl_sim",
- ["verilator"],
- backend="verilator",
- tests=[{"name": target_names[0]}],
- target_manifest=target_manifest,
- )
- run_dir = work_root / "hdl" / "verilator"
- run_dir.mkdir(parents=True, exist_ok=True)
- stubs = _write_verilator_stubs(work_root)
- command = [
- verilator,
- "--lint-only",
- "--timing",
- "-Wall",
- "--top-module",
- TOP_MODULE,
- "-GSOLENOID_ACTIVE_HIGH=1",
- str(ROOT / "tests" / "verilator_waivers.vlt"),
- *[str(ROOT / source) for source in active_rtl_sources()],
- str(stubs),
- ]
- completed = _run_bounded(
- command,
- timeout_name="verilator",
- cwd=run_dir,
- env=tool_env(),
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- check=False,
- )
- timed_out = _was_timed_out(completed)
- warning_lines = verilator_warning_lines(completed.stdout, completed.stderr)
- if timed_out:
- result_status = "fail_timeout"
- elif warning_lines:
- result_status = "fail_warning"
- else:
- result_status = "pass" if completed.returncode == 0 else "fail"
- result = {
- "name": target_names[0],
- "status": result_status,
- "timed_out": timed_out,
- "returncode": completed.returncode,
- "unwaived_warning_count": len(warning_lines),
- "unwaived_warnings": warning_lines,
- "waiver_file": str(ROOT / "tests" / "verilator_waivers.vlt"),
- "stdout_tail": _tail(completed.stdout),
- "stderr_tail": _tail(completed.stderr),
- }
- return {
- "schema": HDL_RECEIPT_SCHEMA,
- "status": "pass"
- if result["status"] == "pass" and target_manifest["status"] == "pass"
- else "fail",
- "verification_layer": "hdl_sim",
- "profile": PROFILE,
- "backend": "verilator",
- "work_root": str(work_root),
- "tests": [result],
- "target_manifest": target_manifest,
- "safety": dict(SAFETY_BOUNDARY),
- }
- def _run_cocotb(work_root: Path) -> dict[str, Any]:
- python_exe = cocotb_python()
- probe_ok = python_has_cocotb(python_exe)
- missing: list[str] = []
- if not probe_ok:
- missing.append("python_module:cocotb")
- for name in ("iverilog", "vvp"):
- if not resolve_tool(name):
- missing.append(name)
- targets = cocotb_tests()
- target_manifest = target_manifest_evidence("cocotb", [target["name"] for target in targets])
- if missing:
- return _missing_tools(
- HDL_RECEIPT_SCHEMA,
- "hdl_sim",
- missing,
- backend="cocotb",
- tests=targets,
- target_manifest=target_manifest,
- )
- results: list[dict[str, Any]] = []
- for target in targets:
- target_root = work_root / "hdl" / "cocotb" / target["name"]
- target_root.mkdir(parents=True, exist_ok=True)
- completed = _run_bounded(
- [python_exe, "-B", str(ROOT / target["runner"])],
- timeout_name="cocotb",
- cwd=ROOT / "tests" / "cocotb",
- env=tool_env(
- {
- "TEMP": str(target_root),
- "TMP": str(target_root),
- "TMPDIR": str(target_root),
- "PYTHONPYCACHEPREFIX": str(target_root / "pycache"),
- }
- ),
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- check=False,
- )
- timed_out = _was_timed_out(completed)
- results.append(
- {
- "name": target["name"],
- "status": "pass" if completed.returncode == 0 else ("fail_timeout" if timed_out else "fail"),
- "timed_out": timed_out,
- "returncode": completed.returncode,
- "stdout_tail": _tail(completed.stdout),
- "stderr_tail": _tail(completed.stderr),
- }
- )
- passed = (
- bool(results) and
- all(item["status"] == "pass" for item in results) and
- target_manifest["status"] == "pass"
- )
- return {
- "schema": HDL_RECEIPT_SCHEMA,
- "status": "pass" if passed else "fail",
- "verification_layer": "hdl_sim",
- "profile": PROFILE,
- "backend": "cocotb",
- "work_root": str(work_root),
- "tests": results,
- "target_manifest": target_manifest,
- "safety": dict(SAFETY_BOUNDARY),
- }
- def python_has_cocotb(python_exe: str | Path) -> bool:
- completed = subprocess.run(
- [str(python_exe), "-B", "-c", "import cocotb"],
- cwd=ROOT,
- env=tool_env(),
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- timeout=20,
- check=False,
- )
- return completed.returncode == 0
- def cocotb_python() -> str:
- candidates: list[Path] = []
- configured = os.environ.get("PROD2U_P4_COCOTB_PYTHON", "").strip()
- if configured:
- candidates.append(Path(configured))
- candidates.append(Path(sys.executable))
- if DEFAULT_VENV_ROOT.is_dir():
- candidates.extend(sorted(DEFAULT_VENV_ROOT.glob("*/Scripts/python.exe")))
- for candidate in dict.fromkeys(path.expanduser().resolve() for path in candidates):
- if candidate.is_file() and python_has_cocotb(candidate):
- return str(candidate)
- return str(Path(sys.executable).resolve())
- def hdl_target_manifest_evidence(backend: str) -> dict[str, Any]:
- inventory = target_inventory()
- if backend == "all":
- return target_manifest_evidence("all", inventory)
- observed = inventory.get(backend, [])
- return target_manifest_evidence(backend, observed)
- def hdl_sim_payload(
- run: bool,
- backend: str = "icarus",
- *,
- work_root: Path | None = None,
- ) -> dict[str, Any]:
- try:
- resolved = resolve_work_root(work_root, run=run)
- except ValueError as exc:
- return {
- "schema": HDL_RECEIPT_SCHEMA,
- "status": "blocked_invalid_work_root",
- "verification_layer": "hdl_sim",
- "profile": PROFILE,
- "backend": backend,
- "reason": str(exc),
- "tests": hdl_testbenches(),
- "target_manifest": hdl_target_manifest_evidence(backend),
- "safety": dict(SAFETY_BOUNDARY),
- }
- if not run:
- if backend == "icarus":
- tests: list[dict[str, Any]] = hdl_testbenches()
- elif backend == "verilator":
- tests = [{"name": "prod2u_p4_normal_v3_top_lint"}]
- elif backend == "cocotb":
- tests = list(cocotb_tests())
- else:
- inventory = target_inventory()
- tests = [
- {"name": name}
- for layer in ("icarus", "verilator", "cocotb")
- for name in inventory[layer]
- ]
- return {
- "schema": HDL_RECEIPT_SCHEMA,
- "status": "skipped",
- "verification_layer": "hdl_sim",
- "profile": PROFILE,
- "backend": backend,
- "work_root": None if resolved is None else str(resolved),
- "tests": tests,
- "target_manifest": hdl_target_manifest_evidence(backend),
- "safety": dict(SAFETY_BOUNDARY),
- }
- assert resolved is not None
- if backend == "icarus":
- return _run_icarus(resolved)
- if backend == "verilator":
- return _run_verilator(resolved)
- if backend == "cocotb":
- return _run_cocotb(resolved)
- if backend != "all":
- return {
- "schema": HDL_RECEIPT_SCHEMA,
- "status": "fail",
- "verification_layer": "hdl_sim",
- "profile": PROFILE,
- "backend": backend,
- "reason": f"unsupported HDL backend: {backend}",
- "tests": [],
- "target_manifest": hdl_target_manifest_evidence(backend),
- "safety": dict(SAFETY_BOUNDARY),
- }
- children = {
- name: hdl_sim_payload(run=True, backend=name, work_root=resolved)
- for name in ("icarus", "verilator", "cocotb")
- }
- aggregate_manifest = hdl_target_manifest_evidence("all")
- passed = (
- all(child.get("status") == "pass" for child in children.values()) and
- aggregate_manifest["status"] == "pass"
- )
- return {
- "schema": HDL_RECEIPT_SCHEMA,
- "status": "pass" if passed else "fail",
- "verification_layer": "hdl_sim",
- "profile": PROFILE,
- "backend": "all",
- "work_root": str(resolved),
- "backend_results": children,
- "tests": [
- item
- for child in children.values()
- for item in child.get("tests", [])
- ],
- "target_manifest": aggregate_manifest,
- "safety": dict(SAFETY_BOUNDARY),
- }
- def formal_payload(run: bool, *, work_root: Path | None = None) -> dict[str, Any]:
- targets = formal_targets()
- target_manifest = target_manifest_evidence(
- "formal",
- {target["name"]: list(target.get("tasks", [])) for target in targets},
- )
- try:
- resolved = resolve_work_root(work_root, run=run)
- except ValueError as exc:
- return {
- "schema": FORMAL_RECEIPT_SCHEMA,
- "status": "blocked_invalid_work_root",
- "verification_layer": "formal",
- "profile": PROFILE,
- "reason": str(exc),
- "targets": targets,
- "target_manifest": target_manifest,
- "safety": dict(SAFETY_BOUNDARY),
- }
- if not run:
- return {
- "schema": FORMAL_RECEIPT_SCHEMA,
- "status": "skipped",
- "verification_layer": "formal",
- "profile": PROFILE,
- "work_root": None if resolved is None else str(resolved),
- "targets": targets,
- "target_manifest": target_manifest,
- "safety": dict(SAFETY_BOUNDARY),
- }
- sby = resolve_tool("sby")
- yosys = resolve_tool("yosys")
- missing = [name for name, value in (("sby", sby), ("yosys", yosys)) if not value]
- if missing:
- return _missing_tools(
- FORMAL_RECEIPT_SCHEMA,
- "formal",
- missing,
- targets=targets,
- target_manifest=target_manifest,
- )
- assert resolved is not None
- results: list[dict[str, Any]] = []
- for target in targets:
- sby_file = ROOT / target["sby"]
- property_counts = formal_property_counts(sby_file)
- input_evidence = formal_input_evidence(sby_file, target.get("tasks", []))
- workdir = resolved / "formal" / target["name"]
- tasks = list(target.get("tasks", []))
- task_names = tasks or ["default"]
- task_workdirs = [workdir / task_name for task_name in task_names]
- task_modes = formal_task_modes(sby_file, tasks)
- task_timeout = configured_timeout("formal")
- task_env = formal_tool_env(resolved)
- def run_task(task_name: str, task_workdir: Path) -> dict[str, Any]:
- command = [str(sby), "-f", "-d", str(task_workdir), str(sby_file)]
- if tasks:
- command.append(task_name)
- try:
- completed = subprocess.run(
- command,
- cwd=sby_file.parent,
- env=task_env,
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- timeout=task_timeout,
- check=False,
- )
- return {
- "status": "pass" if completed.returncode == 0 else "fail",
- "returncode": completed.returncode,
- "stdout": completed.stdout,
- "stderr": completed.stderr,
- }
- except subprocess.TimeoutExpired as exc:
- return {
- "status": "fail_timeout",
- "returncode": None,
- "stdout": (
- exc.stdout.decode(errors="replace")
- if isinstance(exc.stdout, bytes)
- else (exc.stdout or "")
- ),
- "stderr": (
- exc.stderr.decode(errors="replace")
- if isinstance(exc.stderr, bytes)
- else (exc.stderr or "")
- ),
- }
- with ThreadPoolExecutor(
- max_workers=min(FORMAL_MAX_WORKERS, len(task_names))
- ) as executor:
- task_futures = [
- executor.submit(run_task, task_name, task_workdir)
- for task_name, task_workdir in zip(
- task_names, task_workdirs, strict=True
- )
- ]
- task_process_results = [future.result() for future in task_futures]
- if any(item["status"] == "fail_timeout" for item in task_process_results):
- result_status = "fail_timeout"
- elif any(item["status"] != "pass" for item in task_process_results):
- result_status = "fail"
- else:
- result_status = "pass"
- nonzero_returncodes = [
- item["returncode"]
- for item in task_process_results
- if item["returncode"] not in (None, 0)
- ]
- returncode: int | None = (
- int(nonzero_returncodes[0])
- if nonzero_returncodes
- else (None if result_status == "fail_timeout" else 0)
- )
- stdout = "\n".join(
- f"[{task_name}]\n{item['stdout']}".rstrip()
- for task_name, item in zip(task_names, task_process_results, strict=True)
- if item["stdout"]
- )
- stderr = "\n".join(
- f"[{task_name}]\n{item['stderr']}".rstrip()
- for task_name, item in zip(task_names, task_process_results, strict=True)
- if item["stderr"]
- )
- task_results = [
- formal_task_evidence(
- name=task_name,
- mode=task_modes[task_name],
- workdir=task_workdir,
- configured_engines=input_evidence["task_engines"].get(task_name, []),
- )
- for task_name, task_workdir in zip(task_names, task_workdirs, strict=True)
- ]
- trace_files = sorted(
- {
- trace_file
- for task_result in task_results
- for trace_file in task_result["trace_files"]
- }
- )
- cover_tasks = [result for result in task_results if result["mode"] == "cover"]
- cover_required = bool(cover_tasks)
- cover_hit_ids = sorted(
- {
- hit_id
- for task_result in cover_tasks
- for hit_id in task_result["cover_hit_ids"]
- }
- )
- cover_hit_count = len(cover_hit_ids)
- evidence_failures: list[str] = []
- for task_result in task_results:
- evidence_failures.extend(task_result["evidence_failures"])
- if int(property_counts["assertion_count"]) <= 0:
- evidence_failures.append("formal_assertions_missing")
- if cover_required and int(property_counts["cover_count"]) <= 0:
- evidence_failures.append("formal_cover_properties_missing")
- if result_status != "fail_timeout" and evidence_failures:
- result_status = "fail_evidence"
- results.append(
- {
- "name": target["name"],
- "status": result_status,
- "returncode": returncode,
- "tasks": tasks,
- "workdirs": [str(path) for path in task_workdirs],
- "trace_files": trace_files,
- "counterexamples": [] if result_status == "pass" else trace_files,
- "assertion_count": property_counts["assertion_count"],
- "cover_count": property_counts["cover_count"],
- "cover_required": cover_required,
- "cover_hit_count": cover_hit_count,
- "cover_hit_ids": cover_hit_ids,
- "input_evidence": input_evidence,
- "task_results": task_results,
- "evidence_failures": evidence_failures,
- "stdout_tail": _tail(stdout),
- "stderr_tail": _tail(stderr),
- }
- )
- observed_solvers = sorted(
- {
- solver
- for result in results
- for task_result in result.get("task_results", [])
- for solver in task_result.get("solvers", [])
- }
- )
- toolchain = formal_toolchain_evidence(sby, yosys, observed_solvers, resolved)
- passed = (
- bool(results) and
- all(item["status"] == "pass" for item in results) and
- target_manifest["status"] == "pass" and
- toolchain["status"] == "pass"
- )
- return {
- "schema": FORMAL_RECEIPT_SCHEMA,
- "status": "pass" if passed else "fail",
- "verification_layer": "formal",
- "profile": PROFILE,
- "work_root": str(resolved),
- "targets": results,
- "toolchain": toolchain,
- "target_manifest": target_manifest,
- "safety": dict(SAFETY_BOUNDARY),
- }
- def unit_test_modules() -> list[str]:
- unit_root = ROOT / "tests" / "unit"
- selected = set(unit_root.glob("test_prod2u_p4*.py"))
- selected.update(unit_root.glob("test_bootstrap_oss_cad_suite.py"))
- selected.update(unit_root.glob("test_prod2u_programmer*.py"))
- modules = [f"tests.unit.{path.stem}" for path in sorted(selected)]
- if (ROOT / "tests" / "test_project_structure.py").is_file():
- modules.append("tests.test_project_structure")
- return modules
- def target_inventory() -> dict[str, Any]:
- return {
- "unit": list(unit_test_modules()),
- "icarus": [target["name"] for target in hdl_testbenches()],
- "verilator": ["prod2u_p4_normal_v3_top_lint"],
- "cocotb": [target["name"] for target in cocotb_tests()],
- "formal": {
- target["name"]: list(target.get("tasks", []))
- for target in formal_targets()
- },
- }
- def unit_payload(work_root: Path) -> dict[str, Any]:
- modules = unit_test_modules()
- target_manifest = target_manifest_evidence("unit", modules)
- command = [
- sys.executable,
- "-B",
- "-m",
- "pytest",
- "-q",
- "-p",
- "no:cacheprovider",
- "tests/unit",
- "tests/test_project_structure.py",
- ]
- completed = subprocess.run(
- command,
- cwd=ROOT,
- env=tool_env({"PYTHONPYCACHEPREFIX": str(work_root / "python-cache")}),
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- timeout=1800,
- check=False,
- )
- passed = completed.returncode == 0 and target_manifest["status"] == "pass"
- return {
- "status": "pass" if passed else "fail",
- "returncode": completed.returncode,
- "modules": modules,
- "target_manifest": target_manifest,
- "stdout_tail": _tail(completed.stdout, 12000),
- "stderr_tail": _tail(completed.stderr, 12000),
- }
- def source_integrity_payload() -> dict[str, Any]:
- completed = _git("diff", "--check", "HEAD")
- state = source_state()
- passed = (
- completed.returncode == 0 and
- state["status"] == "pass" and
- state.get("clean") is True
- )
- return {
- "status": "pass" if passed else "fail",
- "returncode": completed.returncode,
- "stdout_tail": _tail(completed.stdout),
- "stderr_tail": _tail(completed.stderr),
- "source_state": state,
- }
- def strict_offline_gate_payload(
- *,
- work_root: Path,
- verification_run_id: str | None = None,
- ) -> dict[str, Any]:
- state = source_state()
- run_id = normalize_verification_run_id(verification_run_id)
- try:
- resolved = resolve_work_root(work_root, run=True)
- except ValueError as exc:
- return {
- "schema": OFFLINE_RECEIPT_SCHEMA,
- "status": "fail",
- "verification_run_id": run_id,
- "commit": state["commit"],
- "source_state": state,
- "required_layers": ["source_integrity", "unit", "hdl_sim", "formal"],
- "layers": {},
- "failures": [f"work_root_invalid:{exc}"],
- "safety": dict(SAFETY_BOUNDARY),
- }
- assert resolved is not None
- layers = {
- "source_integrity": source_integrity_payload(),
- "unit": unit_payload(resolved),
- "hdl_sim": hdl_sim_payload(run=True, backend="all", work_root=resolved),
- "formal": formal_payload(run=True, work_root=resolved),
- }
- required = list(layers)
- failures = [
- f"required_layer_not_pass:{name}:{layers[name].get('status', 'missing')}"
- for name in required
- if layers[name].get("status") != "pass"
- ]
- receipt_dir = resolved / "receipts"
- receipt_dir.mkdir(parents=True, exist_ok=True)
- for name, layer in layers.items():
- write_json_report(layer, receipt_dir / f"{name}.json")
- return {
- "schema": OFFLINE_RECEIPT_SCHEMA,
- "generated_at": utc_now(),
- "status": "pass" if not failures else "fail",
- "verification_run_id": run_id,
- "commit": state["commit"],
- "source_state": state,
- "profile": PROFILE,
- "runtime_profile": RUNTIME_PROFILE,
- "required_layers": required,
- "layers": layers,
- "failures": failures,
- "work_root": str(resolved),
- "child_receipt_dir": str(receipt_dir),
- "safety": dict(SAFETY_BOUNDARY),
- "authority_boundary": "This receipt covers offline source, software, HDL and formal checks only. It does not access serial, JTAG, or a board.",
- }
- class StagedBuild:
- def __init__(
- self,
- root: Path,
- syn: Path,
- phy: Path,
- bitgen: Path,
- clean: Mapping[str, Any],
- source_state: Mapping[str, Any],
- source_manifest: Mapping[str, Any],
- synthesis_input_manifest: Mapping[str, Any],
- ) -> None:
- self.root = root
- self.syn = syn
- self.phy = phy
- self.bitgen = bitgen
- self.clean = clean
- self.source_state = source_state
- self.source_manifest = source_manifest
- self.synthesis_input_manifest = synthesis_input_manifest
- def _safe_build_root(work_root: Path) -> Path:
- resolved = resolve_work_root(work_root, run=True)
- assert resolved is not None
- target = (resolved / BUILD_ROOT_RELATIVE).resolve()
- if resolved != target and resolved not in target.parents:
- raise ValueError("TD build root escaped the external work root")
- return target
- def clean_td_outputs(work_root: Path) -> dict[str, Any]:
- target = _safe_build_root(work_root)
- deleted: list[str] = []
- if target.exists():
- deleted.append(str(target))
- shutil.rmtree(target)
- return {"status": "pass", "deleted": deleted, "target": str(target)}
- def _copy_active_sources(target: Path) -> None:
- for relative in active_rtl_sources():
- source = ROOT / relative
- destination = target / relative
- destination.parent.mkdir(parents=True, exist_ok=True)
- shutil.copy2(source, destination)
- for relative in (
- "constraints/prod2u_p4_normal_v3.adc",
- "constraints/prod2u_p4_normal_v3.sdc",
- "td/prod2u_p4_normal_v3.prj",
- ):
- source = ROOT / relative
- destination = target / relative
- destination.parent.mkdir(parents=True, exist_ok=True)
- shutil.copy2(source, destination)
- def prepare_td_build_dirs(*, work_root: Path) -> StagedBuild:
- build_root = _safe_build_root(work_root)
- clean = clean_td_outputs(work_root)
- state = source_state()
- if state.get("status") != "pass" or state.get("clean") is not True:
- raise RuntimeError("TD build requires a clean committed source state")
- synthesis_input_manifest = build_synthesis_input_manifest(ROOT)
- syn = build_root / "syn"
- phy = build_root / "phy"
- bitgen = build_root / "bitgen"
- for directory in (syn, phy, bitgen):
- directory.mkdir(parents=True, exist_ok=True)
- _copy_active_sources(directory)
- for directory in (syn, phy, bitgen):
- write_json_report(state, directory / "source-state.json")
- staged_dirs = {"syn": syn, "phy": phy, "bitgen": bitgen}
- for phase, source in TD_SCRIPTS.items():
- shutil.copy2(source, staged_dirs[phase] / source.name)
- phases: dict[str, Any] = {}
- for phase, directory in staged_dirs.items():
- files = {
- path.relative_to(directory).as_posix(): sha256_file(path)
- for path in sorted(directory.rglob("*"))
- if path.is_file()
- }
- phases[phase] = {"files": files, "manifest_sha256": canonical_sha256(files)}
- source_manifest = {
- "schema": "prod2u-p4-normal-v3-staged-source-manifest-v1",
- "status": "pass",
- "commit": state["commit"],
- "source_state_clean": state["clean"],
- "phases": phases,
- "failures": [],
- }
- return StagedBuild(
- build_root,
- syn,
- phy,
- bitgen,
- clean,
- state,
- source_manifest,
- synthesis_input_manifest,
- )
- def _staged_synthesis_input_manifest(staged: StagedBuild) -> dict[str, Any]:
- expected_inputs = staged.synthesis_input_manifest.get("inputs")
- if not isinstance(expected_inputs, Mapping) or not expected_inputs:
- raise ValueError("expected synthesis input manifest is missing")
- observed: dict[str, str | None] = {}
- for relative in expected_inputs:
- relative_text = str(relative)
- if relative_text.startswith("td/syn/"):
- path = staged.syn / Path(relative_text).name
- elif relative_text.startswith("td/phy/"):
- path = staged.phy / Path(relative_text).name
- elif relative_text.startswith("td/bitgen/"):
- path = staged.bitgen / Path(relative_text).name
- else:
- path = staged.syn / relative_text
- observed[relative_text] = sha256_file(path) if path.is_file() else None
- return {
- "schema": staged.synthesis_input_manifest.get("schema"),
- "inputs": observed,
- "sha256": canonical_sha256(observed),
- }
- def verify_staged_source_manifest(staged: StagedBuild) -> dict[str, Any]:
- failures: list[str] = []
- verified_phases: dict[str, Any] = {}
- for phase in ("syn", "phy", "bitgen"):
- directory = getattr(staged, phase)
- expected_phase = staged.source_manifest.get("phases", {}).get(phase, {})
- expected_files = expected_phase.get("files") if isinstance(expected_phase, Mapping) else None
- if not isinstance(expected_files, Mapping) or not expected_files:
- failures.append(f"manifest_missing:{phase}")
- continue
- observed: dict[str, str | None] = {}
- for relative, expected_digest in expected_files.items():
- path = directory / str(relative)
- digest = sha256_file(path) if path.is_file() else None
- observed[str(relative)] = digest
- if digest != expected_digest:
- failures.append(f"staged_input_mismatch:{phase}:{relative}")
- observed_digest = canonical_sha256(observed)
- expected_digest = expected_phase.get("manifest_sha256")
- if observed_digest != expected_digest:
- failures.append(f"phase_manifest_mismatch:{phase}")
- verified_phases[phase] = {
- "files": dict(expected_files),
- "manifest_sha256": expected_digest,
- "observed_manifest_sha256": observed_digest,
- }
- expected_synthesis_inputs = staged.synthesis_input_manifest.get("inputs")
- synthesis_phase_bindings: dict[str, dict[str, str | None]] = {}
- if not isinstance(expected_synthesis_inputs, Mapping):
- failures.append("expected_synthesis_inputs_missing")
- else:
- for relative, expected_digest in expected_synthesis_inputs.items():
- relative_text = str(relative)
- if relative_text.startswith("td/syn/"):
- phase_paths = {"syn": staged.syn / Path(relative_text).name}
- elif relative_text.startswith("td/phy/"):
- phase_paths = {"phy": staged.phy / Path(relative_text).name}
- elif relative_text.startswith("td/bitgen/"):
- phase_paths = {"bitgen": staged.bitgen / Path(relative_text).name}
- else:
- phase_paths = {
- phase: getattr(staged, phase) / relative_text
- for phase in ("syn", "phy", "bitgen")
- }
- observed_by_phase = {
- phase: sha256_file(path) if path.is_file() else None
- for phase, path in phase_paths.items()
- }
- synthesis_phase_bindings[relative_text] = observed_by_phase
- for phase, observed_digest in observed_by_phase.items():
- if observed_digest != expected_digest:
- failures.append(f"staged_synthesis_input_mismatch:{phase}:{relative_text}")
- observed_synthesis = _staged_synthesis_input_manifest(staged)
- expected_synthesis = staged.synthesis_input_manifest
- if observed_synthesis.get("inputs") != expected_synthesis.get("inputs"):
- failures.append("staged_synthesis_inputs_mismatch")
- if observed_synthesis.get("sha256") != expected_synthesis.get("sha256"):
- failures.append("staged_synthesis_hash_mismatch")
- return {
- "schema": "prod2u-p4-normal-v3-staged-source-manifest-v1",
- "status": "pass" if not failures else "fail",
- "commit": staged.source_manifest.get("commit"),
- "source_state_clean": staged.source_manifest.get("source_state_clean"),
- "phases": verified_phases,
- "synthesis_input_manifest": observed_synthesis,
- "synthesis_phase_bindings": synthesis_phase_bindings,
- "expected_synthesis_input_hash": expected_synthesis.get("sha256"),
- "observed_synthesis_input_hash": observed_synthesis.get("sha256"),
- "failures": sorted(set(failures)),
- }
- def td_process_env(
- run_dir: Path,
- extra: Mapping[str, str] | None = None,
- ) -> dict[str, str]:
- temp_dir = run_dir / "td-user" / "temp"
- temp_dir.mkdir(parents=True, exist_ok=True)
- values = {"TEMP": str(temp_dir), "TMP": str(temp_dir)}
- if extra:
- values.update({str(key): str(value) for key, value in extra.items()})
- return tool_env(values)
- def run_td_script(
- run_dir: Path,
- script_name: str,
- *,
- extra_env: Mapping[str, str] | None = None,
- ) -> subprocess.CompletedProcess[str]:
- return _run_bounded(
- [str(TD_EXE), script_name],
- timeout_name="td",
- cwd=run_dir,
- env=td_process_env(run_dir, extra_env),
- text=True,
- encoding="utf-8",
- errors="replace",
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- check=False,
- )
- def td_forbidden_script_markers(script_text: str) -> list[str]:
- markers: set[str] = set()
- for raw_line in script_text.splitlines():
- line = raw_line.strip().casefold()
- if not line or line.startswith("#"):
- continue
- command = re.split(r"\s+", line, maxsplit=1)[0]
- if command == "source":
- markers.add("source")
- for forbidden in FORBIDDEN_TD_COMMANDS:
- if re.search(rf"(?<![a-z0-9_]){re.escape(forbidden)}(?![a-z0-9_])", line):
- markers.add(forbidden)
- return sorted(markers)
- def td_log_has_error(*chunks: str) -> bool:
- text = "\n".join(chunks)
- return bool(
- re.search(
- r"(^|\n)\s*(?:[A-Z]+-\d+\s+)?(?:error|fatal)\s*[:|]",
- text,
- re.IGNORECASE,
- )
- )
- def td_critical_warning_count(*chunks: str) -> int:
- return len(re.findall(r"critical[-\s]+warning", "\n".join(chunks), re.IGNORECASE))
- def parse_qor_attribute_count(path: Path, attribute: str) -> int | None:
- if not path.is_file() or not re.fullmatch(r"[a-z][a-z0-9_]*", attribute):
- return None
- text = path.read_text(encoding="utf-8", errors="replace")
- match = re.search(
- rf"^\|\s*#{re.escape(attribute)}\s*\|\s*(\d+)\s*\|\s*$",
- text,
- re.MULTILINE,
- )
- return int(match.group(1)) if match else None
- def parse_td_cdc_report(path: Path) -> dict[str, Any] | None:
- if not path.is_file():
- return None
- rows: dict[str, list[str]] = {
- "schema": [],
- "retained_sync_register": [],
- "false_path_endpoint": [],
- "false_path_source": [],
- "structural_failure": [],
- }
- for raw_line in path.read_text(encoding="utf-8", errors="replace").splitlines():
- line = raw_line.strip()
- if not line:
- continue
- if "=" not in line:
- return None
- key, value = line.split("=", 1)
- if key not in rows or not value:
- return None
- rows[key].append(value)
- if rows["schema"] != [CDC_REPORT_SCHEMA]:
- return None
- registers = rows["retained_sync_register"]
- endpoints = rows["false_path_endpoint"]
- sources = rows["false_path_source"]
- failures = rows["structural_failure"]
- if (
- len(registers) != len(set(registers))
- or len(endpoints) != len(set(endpoints))
- or len(sources) != len(set(sources))
- ):
- return None
- return {
- "schema": CDC_REPORT_SCHEMA,
- "retained_sync_registers": registers,
- "false_path_endpoints": endpoints,
- "source_only_false_paths": sources,
- "structural_failures": failures,
- }
- def parse_td_fsm_report(path: Path) -> dict[str, Any] | None:
- if not path.is_file():
- return None
- schema: str | None = None
- axes: dict[str, int] = {}
- encodings: dict[str, str] = {}
- failures: list[str] = []
- for raw_line in path.read_text(encoding="utf-8", errors="replace").splitlines():
- line = raw_line.strip()
- if not line or "=" not in line:
- return None
- key, value = line.split("=", 1)
- if key == "schema":
- if schema is not None or value != FSM_REPORT_SCHEMA:
- return None
- schema = value
- continue
- if key == "structural_failure":
- failures.append(value)
- continue
- if key != "motion_phase":
- return None
- match = re.fullmatch(r"([xy]):(\d+):([a-z][a-z0-9_]*)", value)
- if match is None or match.group(1) in axes:
- return None
- axis = match.group(1)
- axes[axis] = int(match.group(2))
- encodings[axis] = match.group(3)
- if schema != FSM_REPORT_SCHEMA:
- return None
- return {
- "schema": schema,
- "axes": axes,
- "encodings": encodings,
- "structural_failures": failures,
- }
- def structural_cdc_gate(
- report: Mapping[str, Any] | None,
- *,
- async_reg_count: int | None,
- input_register_count: int | None,
- ) -> dict[str, Any]:
- failures: list[str] = []
- registers = report.get("retained_sync_registers") if isinstance(report, Mapping) else None
- endpoints = report.get("false_path_endpoints") if isinstance(report, Mapping) else None
- source_only = report.get("source_only_false_paths") if isinstance(report, Mapping) else None
- reported = report.get("structural_failures") if isinstance(report, Mapping) else None
- register_set = set(registers) if isinstance(registers, list) and all(isinstance(item, str) for item in registers) else set()
- endpoint_set = set(endpoints) if isinstance(endpoints, list) and all(isinstance(item, str) for item in endpoints) else set()
- source_set = set(source_only) if isinstance(source_only, list) and all(isinstance(item, str) for item in source_only) else set()
- reported_failures = list(reported) if isinstance(reported, list) and all(isinstance(item, str) for item in reported) else []
- if async_reg_count != len(EXPECTED_CDC_SYNC_REGISTERS):
- failures.append(f"async_reg_used:{async_reg_count}")
- if input_register_count != 0:
- failures.append(f"input_registers_used:{input_register_count}")
- if register_set != EXPECTED_CDC_SYNC_REGISTERS:
- failures.append("retained_sync_registers_mismatch")
- if endpoint_set != EXPECTED_CDC_FALSE_PATH_ENDPOINTS:
- failures.append("false_path_endpoints_mismatch")
- if source_set:
- failures.append(f"source_only_false_paths_used:{','.join(sorted(source_set))}")
- failures.extend(f"td_report:{failure}" for failure in reported_failures)
- return {
- "status": "pass" if not failures else "fail",
- "async_reg": {
- "status": "pass" if async_reg_count == len(EXPECTED_CDC_SYNC_REGISTERS) else "fail",
- "used": async_reg_count,
- },
- "input_registers": {
- "status": "pass" if input_register_count == 0 else "fail",
- "used": input_register_count,
- },
- "retained_sync_registers": {
- "status": "pass" if register_set == EXPECTED_CDC_SYNC_REGISTERS else "fail",
- "used": len(register_set),
- },
- "first_stage_endpoints": {
- "status": "pass" if endpoint_set == EXPECTED_CDC_FALSE_PATH_ENDPOINTS else "fail",
- "used": len(endpoint_set),
- },
- "source_only_false_paths": sorted(source_set),
- "reported_failures": reported_failures,
- "failures": failures,
- }
- def structural_fsm_gate(
- report: Mapping[str, Any] | None,
- *,
- syn_log: str,
- ) -> dict[str, Any]:
- failures: list[str] = []
- axes = report.get("axes") if isinstance(report, Mapping) else None
- encodings = report.get("encodings") if isinstance(report, Mapping) else None
- reported = report.get("structural_failures") if isinstance(report, Mapping) else None
- normalized_axes = dict(axes) if isinstance(axes, Mapping) else {}
- normalized_encodings = dict(encodings) if isinstance(encodings, Mapping) else {}
- reported_failures = list(reported) if isinstance(reported, list) and all(isinstance(item, str) for item in reported) else []
- if normalized_axes != EXPECTED_FSM_AXES:
- failures.append("motion_phase_width_or_axis_mismatch")
- if normalized_encodings != {axis: "sequential" for axis in EXPECTED_FSM_AXES}:
- failures.append("motion_phase_encoding_mismatch")
- marker_seen = "FSM_ENCODING_GATE_PASS=sequential" in syn_log
- if not marker_seen:
- failures.append("fsm_td_log_marker_missing")
- reencoded = re.findall(
- r"SYN-1067\s*:.*?state register '[^']*motion_phase(?:_reg)?[^']*'"
- r".*?encoding '([^']+)'",
- syn_log,
- re.IGNORECASE,
- )
- for encoding in reencoded:
- failures.append(f"motion_phase_reencoded:{encoding.casefold()}")
- failures.extend(f"td_report:{failure}" for failure in reported_failures)
- return {
- "status": "pass" if not failures else "fail",
- "encoding": "sequential" if not failures else None,
- "axes": normalized_axes,
- "td_log_marker": marker_seen,
- "reencoded_motion_phase_count": len(reencoded),
- "reported_failures": reported_failures,
- "failures": failures,
- }
- def parse_area_report(path: Path) -> dict[str, Any] | None:
- if not path.is_file():
- return None
- text = path.read_text(encoding="utf-8", errors="replace")
- result: dict[str, Any] = {"path": str(path), "utilization": {}, "hierarchy": []}
- columns: list[str] = []
- for line in text.splitlines():
- match = re.match(
- r"#(lut|reg|dsp|bram|bram32k|bram128k|bram256k|pad|pll)\s+"
- r"(\d+)\s+out of\s+(\d+)\s+([0-9.]+)%",
- line.strip(),
- )
- if match:
- result["utilization"][match.group(1)] = {
- "used": int(match.group(2)),
- "total": int(match.group(3)),
- "percent": float(match.group(4)),
- }
- continue
- detail = re.match(r"#(ireg|oreg|treg)\s+(\d+)\s*$", line.strip())
- if detail:
- result["utilization"][detail.group(1)] = {"used": int(detail.group(2))}
- continue
- if line.startswith("|") and "Instance" in line and "Module" in line:
- columns = [part.strip().lower() for part in line.strip("|").split("|")]
- continue
- if line.startswith("|") and columns:
- values = [part.strip() for part in line.strip("|").split("|")]
- if len(values) != len(columns):
- continue
- row = dict(zip(columns, values))
- if not row.get("instance") or row.get("instance") == "Instance":
- continue
- parsed: dict[str, Any] = {"instance": row["instance"], "module": row["module"]}
- try:
- for key, value in row.items():
- if key not in {"instance", "module"}:
- parsed[key] = int(value)
- except ValueError:
- continue
- result["hierarchy"].append(parsed)
- if "pad" in result["utilization"]:
- for name in ("ireg", "oreg", "treg"):
- result["utilization"].setdefault(name, {"used": 0})
- return result
- def parse_td_io_report(path: Path) -> list[dict[str, str]] | None:
- target = Path(path)
- if not target.is_file():
- return None
- lines = target.read_text(encoding="utf-8", errors="replace").splitlines()
- try:
- start = next(index for index, line in enumerate(lines) if line.strip() == "Detailed IO Report")
- header = next(
- index
- for index in range(start + 1, len(lines))
- if lines[index].split()[:4] == ["Name", "Direction", "Location", "IOStandard"]
- )
- except StopIteration:
- return None
- rows: list[dict[str, str]] = []
- for line in lines[header + 1 :]:
- fields = line.split()
- if not fields:
- if rows:
- break
- continue
- if len(fields) != 9:
- if rows:
- break
- continue
- rows.append(
- dict(
- zip(
- (
- "name",
- "direction",
- "location",
- "io_standard",
- "io_type",
- "drive_strength",
- "pull_type",
- "pack_reg",
- "diff_resistor",
- ),
- fields,
- strict=True,
- )
- )
- )
- return rows or None
- def post_route_pin_gate(rows: Sequence[Mapping[str, str]] | None) -> dict[str, Any]:
- failures: list[str] = []
- normalized = [dict(row) for row in rows or []]
- by_name = {row.get("name"): row for row in normalized if row.get("name")}
- locations = [str(row.get("location", "")) for row in normalized]
- if len(normalized) != 41:
- failures.append(f"io_row_count:{len(normalized)}")
- if len(by_name) != len(normalized):
- failures.append("io_name_not_unique")
- if len(set(locations)) != len(locations):
- failures.append("io_location_not_unique")
- if "A5" in locations:
- failures.append("forbidden_location_assigned:A5")
- required = {
- name: {**expected, "io_standard": "LVCMOS33"}
- for name, expected in REQUIRED_MOTOR_LIMIT_PINS.items()
- }
- for name, expected in required.items():
- observed = by_name.get(name)
- if observed is None:
- failures.append(f"io_signal_missing:{name}")
- continue
- for field, value in expected.items():
- if observed.get(field) != value:
- failures.append(f"io_binding_mismatch:{name}:{field}")
- return {
- "status": "pass" if not failures else "fail",
- "row_count": len(normalized),
- "required": required,
- "observed": {name: by_name.get(name) for name in required},
- "forbidden_location": "A5",
- "failures": failures,
- }
- def parse_packing_summary(*texts: str) -> dict[str, int] | None:
- matches = [
- (int(match.group(1)), int(match.group(2)))
- for text in texts
- for match in re.finditer(r"\b(\d+)\s+mslices,\s+(\d+)\s+lslices\b", text, re.IGNORECASE)
- ]
- if not matches:
- return None
- mslice, lslice = matches[-1]
- return {"mslice": mslice, "lslice": lslice, "total_slices": mslice + lslice}
- def parse_timing_report(path: Path) -> dict[str, Any] | None:
- if not path.is_file():
- return None
- text = path.read_text(encoding="utf-8", errors="replace")
- result: dict[str, Any] = {"path": str(path)}
- row = re.search(
- r"^\s*clk\d+\s+\S+\s+[0-9.]+\s+[0-9.]+\s+"
- r"([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s+"
- r"([0-9.+-]+)\s+([0-9.+-]+)\s+([0-9.+-]+)\s+([0-9.+-]+)",
- text,
- re.MULTILINE,
- )
- if row:
- result.update(
- {
- "period_ns": float(row.group(1)),
- "clock_frequency_mhz": float(row.group(2)),
- "minimum_period_ns": float(row.group(3)),
- "fmax_mhz": float(row.group(4)),
- "worst_setup_slack_ns": float(row.group(5)),
- "setup_total_negative_slack_ns": float(row.group(6)),
- "worst_hold_slack_ns": float(row.group(7)),
- "hold_total_negative_slack_ns": float(row.group(8)),
- }
- )
- errors = re.search(r"(\d+) errors detected : (\d+) setup errors .*?, (\d+) hold errors", text)
- if errors:
- result["error_count"] = int(errors.group(1))
- result["setup_error_count"] = int(errors.group(2))
- result["hold_error_count"] = int(errors.group(3))
- else:
- setup_violations = re.search(
- r"^\s*Max\s*:.*?\b(\d+)\s+Viol Endpoints\b",
- text,
- re.MULTILINE,
- )
- hold_violations = re.search(
- r"^\s*Min\s*:.*?\b(\d+)\s+Viol Endpoints\b",
- text,
- re.MULTILINE,
- )
- if setup_violations and hold_violations:
- setup_count = int(setup_violations.group(1))
- hold_count = int(hold_violations.group(1))
- result["error_count"] = setup_count + hold_count
- result["setup_error_count"] = setup_count
- result["hold_error_count"] = hold_count
- return result
- def pin_binding_gate() -> dict[str, Any]:
- path = ROOT / "constraints" / "prod2u_p4_normal_v3.adc"
- text = path.read_text(encoding="utf-8", errors="replace")
- assignments = re.findall(
- r"set_pin_assignment\s+\{\s*([^}]+?)\s*\}\s+\{\s*LOCATION\s*=\s*([^;\s]+);\s*"
- r"IOSTANDARD\s*=\s*([^;\s]+);\s*PULLTYPE\s*=\s*([^;\s]+);",
- text,
- )
- by_signal = {signal.strip(): (ball.strip(), standard.strip(), pull.strip()) for signal, ball, standard, pull in assignments}
- failures: list[str] = []
- if len(assignments) != 41:
- failures.append(f"pad_count:{len(assignments)}")
- if len(by_signal) != len(assignments):
- failures.append("duplicate_signal")
- if len({item[0] for item in by_signal.values()}) != len(assignments):
- failures.append("duplicate_ball")
- if any(ball == "A5" for ball, _standard, _pull in by_signal.values()):
- failures.append("forbidden_ball_assigned:A5")
- required = {
- "sys_clk": ("J1", "NONE"),
- "host_uart_rx": ("N11", "NONE"),
- "host_uart_tx": ("M10", "NONE"),
- **{
- signal: (expected["location"], expected["pull_type"])
- for signal, expected in REQUIRED_MOTOR_LIMIT_PINS.items()
- },
- }
- for signal, (ball, pull) in required.items():
- observed = by_signal.get(signal)
- if observed is None:
- failures.append(f"missing_signal:{signal}")
- elif observed[0] != ball or observed[2] != pull:
- failures.append(f"binding_mismatch:{signal}")
- return {
- "status": "pass" if not failures else "fail",
- "path": str(path),
- "pad_count": len(assignments),
- "failures": failures,
- }
- def timing_gate(timing: Mapping[str, Any] | None) -> dict[str, Any]:
- failures: list[str] = []
- if not isinstance(timing, Mapping):
- failures.append("timing_report_missing")
- else:
- for name in ("fmax_mhz", "worst_setup_slack_ns", "worst_hold_slack_ns"):
- value = timing.get(name)
- if not isinstance(value, (int, float)) or value <= 0:
- failures.append(f"nonpositive_or_missing:{name}")
- error_count = timing.get("error_count")
- if not isinstance(error_count, int) or isinstance(error_count, bool):
- failures.append("timing_error_count_missing")
- elif error_count != 0:
- failures.append("timing_errors_present")
- return {"status": "pass" if not failures else "fail", "failures": failures}
- def td_bitgen_eligible(
- *,
- route_artifact_usable: bool,
- timing_status: str,
- structural_status: str,
- ) -> bool:
- """Permit bit generation after a usable routed database exists.
- Timing and structural results remain recorded in the receipt, but the
- temporary-image policy does not let those validation failures suppress a
- bitstream that TD can still generate.
- """
- del timing_status, structural_status
- return bool(route_artifact_usable)
- def td_stage_artifact_usable(
- completed: subprocess.CompletedProcess[str] | None,
- artifact: Path,
- ) -> bool:
- return bool(
- completed is not None
- and completed.returncode == 0
- and not td_log_has_error(completed.stdout, completed.stderr)
- and artifact.is_file()
- and artifact.stat().st_size > 0
- )
- def structural_resource_gate(
- resources: Mapping[str, Any] | None,
- ) -> dict[str, Any]:
- failures: list[str] = []
- utilization = resources.get("utilization") if isinstance(resources, Mapping) else None
- if not isinstance(utilization, Mapping):
- failures.append("resource_report_missing")
- else:
- expected = {
- "bram": 0,
- "bram32k": 0,
- "bram128k": 0,
- "bram256k": 0,
- "dsp": 0,
- "pad": 41,
- "ireg": 0,
- }
- for name, value in expected.items():
- observed = utilization.get(name)
- used = observed.get("used") if isinstance(observed, Mapping) else None
- if used != value:
- failures.append(f"{name}_used:{used}")
- return {
- "status": "pass" if not failures else "fail",
- "required": {
- "bram": 0,
- "bram32k": 0,
- "bram128k": 0,
- "bram256k": 0,
- "dsp": 0,
- "pad": 41,
- "ireg": 0,
- },
- "failures": failures,
- }
- def _stage_result(completed: subprocess.CompletedProcess[str] | None) -> dict[str, Any] | None:
- if completed is None:
- return None
- timed_out = _was_timed_out(completed)
- command = (
- [str(value) for value in completed.args]
- if isinstance(completed.args, Sequence) and not isinstance(completed.args, (str, bytes))
- else [str(completed.args)]
- )
- return {
- "status": "fail_timeout" if timed_out else ("pass" if completed.returncode == 0 else "fail"),
- "timed_out": timed_out,
- "returncode": completed.returncode,
- "log_has_error": td_log_has_error(completed.stdout, completed.stderr),
- "critical_warning_count": td_critical_warning_count(completed.stdout, completed.stderr),
- "command": command,
- "stdout_tail": _tail(completed.stdout),
- "stderr_tail": _tail(completed.stderr),
- }
- def _td_artifact(path: Path) -> dict[str, Any]:
- target = Path(path).resolve()
- return {
- "path": str(target),
- "size": target.stat().st_size,
- "sha256": sha256_file(target),
- }
- def _write_td_console_log(
- path: Path,
- completed: subprocess.CompletedProcess[str],
- ) -> Path:
- target = Path(path).resolve()
- target.parent.mkdir(parents=True, exist_ok=True)
- target.write_text(
- "=== STDOUT ===\n"
- + str(completed.stdout or "")
- + "\n=== STDERR ===\n"
- + str(completed.stderr or "")
- + "\n",
- encoding="utf-8",
- newline="\n",
- )
- return target
- def td_measurement_artifacts(
- *,
- syn_dir: Path,
- phy_dir: Path,
- bitgen_dir: Path,
- bitstream: Path,
- syn: subprocess.CompletedProcess[str] | None,
- phy: subprocess.CompletedProcess[str] | None,
- bitgen: subprocess.CompletedProcess[str] | None,
- ) -> tuple[dict[str, dict[str, Any]], list[str]]:
- directories = {
- "syn": Path(syn_dir).resolve(),
- "phy": Path(phy_dir).resolve(),
- "bitgen": Path(bitgen_dir).resolve(),
- }
- stage_results = {"syn": syn, "phy": phy, "bitgen": bitgen}
- paths = {
- "bitstream": Path(bitstream).resolve(),
- "syn_area": directories["syn"] / f"{PROFILE}_gate.area",
- "phy_area": directories["phy"] / f"{PROFILE}_phy.area",
- "timing": directories["phy"] / f"{PROFILE}_pr.timing",
- "syn_qor": directories["syn"] / f"{PROFILE}_gate.qor",
- "syn_cdc": directories["syn"] / f"{PROFILE}_cdc.rpt",
- "phy_cdc": directories["phy"] / f"{PROFILE}_cdc.rpt",
- "syn_fsm": directories["syn"] / f"{PROFILE}_fsm_encoding.rpt",
- "phy_fsm": directories["phy"] / f"{PROFILE}_fsm_encoding.rpt",
- }
- failures: list[str] = []
- for phase, completed in stage_results.items():
- if completed is None:
- failures.append(f"measurement_stage_missing:{phase}")
- continue
- try:
- paths[f"{phase}_log"] = _write_td_console_log(
- directories[phase] / f"{PROFILE}_{phase}.console.log",
- completed,
- )
- except OSError as exc:
- failures.append(f"measurement_stage_log_failed:{phase}:{type(exc).__name__}")
- artifacts: dict[str, dict[str, Any]] = {}
- for name, path in paths.items():
- if not path.is_file() or path.stat().st_size <= 0:
- failures.append(f"measurement_artifact_missing:{name}")
- continue
- try:
- artifacts[name] = _td_artifact(path)
- except OSError as exc:
- failures.append(f"measurement_artifact_unreadable:{name}:{type(exc).__name__}")
- return artifacts, sorted(set(failures))
- def _resource_delta_unavailable(reason: str) -> dict[str, Any]:
- return {
- "schema": "prod2u-p4-normal-v3-resource-delta-v1",
- "advisory_only": True,
- "affects_build_status": False,
- "available": False,
- "reason": reason,
- }
- def td_source_states_clean(
- source_before: Mapping[str, Any],
- source_after: Mapping[str, Any],
- staged_manifest: Mapping[str, Any],
- ) -> bool:
- return (
- source_before.get("clean") is True
- and source_after.get("clean") is True
- and staged_manifest.get("source_state_clean") is True
- )
- def td_build_payload(
- run: bool,
- top: str = PROFILE,
- *,
- work_root: Path | None = None,
- verification_run_id: str | None = None,
- ) -> dict[str, Any]:
- shared_run_id = normalize_verification_run_id(verification_run_id)
- metadata = {
- "schema": TD_RECEIPT_SCHEMA,
- "build_mode": TD_BUILD_MODE_PRODUCTION,
- "resource_variant": RESOURCE_VARIANT_PRODUCTION,
- "top": top,
- "top_module": TOP_MODULE,
- "pin_profile": PIN_PROFILE,
- "profile": PROFILE,
- "runtime_profile": RUNTIME_PROFILE,
- "verification_run_id": shared_run_id,
- "safety": dict(SAFETY_BOUNDARY),
- }
- if top != PROFILE:
- return {**metadata, "status": "fail", "reason": f"unsupported TD top: {top}"}
- try:
- resolved = resolve_work_root(work_root, run=run)
- except ValueError as exc:
- return {**metadata, "status": "blocked_invalid_work_root", "reason": str(exc)}
- if not run:
- return {
- **metadata,
- "status": "skipped",
- "reason": "TD build not requested; pass --run to execute it.",
- "work_root": None if resolved is None else str(resolved),
- }
- assert resolved is not None
- generated_at = utc_now()
- run_id = new_td_run_id()
- if not TD_EXE.is_file():
- return {**metadata, "status": "blocked", "reason": f"missing TD executable: {TD_EXE}"}
- script_failures: list[str] = []
- for phase, script in TD_SCRIPTS.items():
- if not script.is_file():
- script_failures.append(f"missing_script:{phase}")
- continue
- for marker in td_forbidden_script_markers(
- script.read_text(encoding="utf-8", errors="replace")
- ):
- script_failures.append(f"forbidden_script_command:{phase}:{marker}")
- pins = pin_binding_gate()
- if script_failures or pins["status"] != "pass":
- return {
- **metadata,
- "status": "blocked_pin_binding_invalid" if pins["status"] != "pass" else "fail",
- "script_failures": script_failures,
- "pin_binding_gate": pins,
- }
- try:
- staged = prepare_td_build_dirs(work_root=resolved)
- except (OSError, RuntimeError, ValueError) as exc:
- return {**metadata, "status": "fail_build_preparation", "reason": str(exc)}
- syn = run_td_script(staged.syn, TD_SCRIPTS["syn"].name)
- syn_resources = parse_area_report(staged.syn / f"{PROFILE}_gate.area")
- syn_utilization = syn_resources.get("utilization") if isinstance(syn_resources, Mapping) else None
- syn_ireg = syn_utilization.get("ireg") if isinstance(syn_utilization, Mapping) else None
- syn_cdc = structural_cdc_gate(
- parse_td_cdc_report(staged.syn / f"{PROFILE}_cdc.rpt"),
- async_reg_count=parse_qor_attribute_count(
- staged.syn / f"{PROFILE}_gate.qor",
- "async_reg",
- ),
- input_register_count=syn_ireg.get("used") if isinstance(syn_ireg, Mapping) else None,
- )
- syn_fsm = structural_fsm_gate(
- parse_td_fsm_report(staged.syn / f"{PROFILE}_fsm_encoding.rpt"),
- syn_log=syn.stdout,
- )
- syn_ok = (
- syn.returncode == 0
- and not td_log_has_error(syn.stdout, syn.stderr)
- and td_critical_warning_count(syn.stdout, syn.stderr) == 0
- and syn_cdc["status"] == "pass"
- and syn_fsm["status"] == "pass"
- and "CDC_GATE_PASS=1" in syn.stdout
- and "FSM_ENCODING_GATE_PASS=sequential" in syn.stdout
- )
- syn_artifact_usable = td_stage_artifact_usable(
- syn,
- staged.syn / f"{PROFILE}_gate.db",
- )
- phy: subprocess.CompletedProcess[str] | None = None
- if syn_artifact_usable:
- phy = run_td_script(staged.phy, TD_SCRIPTS["phy"].name)
- phy_ok = bool(
- phy
- and phy.returncode == 0
- and not td_log_has_error(phy.stdout, phy.stderr)
- and td_critical_warning_count(phy.stdout, phy.stderr) == 0
- )
- route_artifact_usable = td_stage_artifact_usable(
- phy,
- staged.phy / f"{PROFILE}_pr.db",
- )
- resources = parse_area_report(staged.phy / f"{PROFILE}_phy.area")
- if resources is not None and phy is not None:
- resources["packing"] = parse_packing_summary(phy.stdout, phy.stderr)
- timing = parse_timing_report(staged.phy / f"{PROFILE}_pr.timing")
- timing_result = timing_gate(timing)
- resource_structural = structural_resource_gate(resources)
- routed_pins = post_route_pin_gate(
- parse_td_io_report(staged.phy / f"{PROFILE}_phy.area")
- )
- utilization = resources.get("utilization") if isinstance(resources, Mapping) else None
- ireg = utilization.get("ireg") if isinstance(utilization, Mapping) else None
- cdc_structural = structural_cdc_gate(
- parse_td_cdc_report(staged.phy / f"{PROFILE}_cdc.rpt"),
- async_reg_count=parse_qor_attribute_count(
- staged.syn / f"{PROFILE}_gate.qor",
- "async_reg",
- ),
- input_register_count=ireg.get("used") if isinstance(ireg, Mapping) else None,
- )
- fsm_structural = structural_fsm_gate(
- parse_td_fsm_report(staged.phy / f"{PROFILE}_fsm_encoding.rpt"),
- syn_log=syn.stdout,
- )
- structural = {
- "status": (
- "pass"
- if resource_structural["status"] == "pass"
- and routed_pins["status"] == "pass"
- and cdc_structural["status"] == "pass"
- and fsm_structural["status"] == "pass"
- else "fail"
- ),
- "resources": resource_structural,
- "pins": routed_pins,
- "cdc": cdc_structural,
- "fsm_encoding": fsm_structural,
- "failures": [
- *resource_structural["failures"],
- *(f"pins:{failure}" for failure in routed_pins["failures"]),
- *(f"cdc:{failure}" for failure in cdc_structural["failures"]),
- *(f"fsm:{failure}" for failure in fsm_structural["failures"]),
- ],
- }
- bitgen: subprocess.CompletedProcess[str] | None = None
- if td_bitgen_eligible(
- route_artifact_usable=route_artifact_usable,
- timing_status=str(timing_result["status"]),
- structural_status=str(structural["status"]),
- ):
- bitgen = run_td_script(staged.bitgen, TD_SCRIPTS["bitgen"].name)
- bitgen_ok = bool(
- bitgen
- and bitgen.returncode == 0
- and not td_log_has_error(bitgen.stdout, bitgen.stderr)
- and td_critical_warning_count(bitgen.stdout, bitgen.stderr) == 0
- )
- bitstream = staged.bitgen / f"{PROFILE}.bit"
- bitstream_sha256 = (
- sha256_file(bitstream)
- if bitstream.is_file() and bitstream.stat().st_size > 0
- else None
- )
- measurement_artifacts, measurement_failures = td_measurement_artifacts(
- syn_dir=staged.syn,
- phy_dir=staged.phy,
- bitgen_dir=staged.bitgen,
- bitstream=bitstream,
- syn=syn,
- phy=phy,
- bitgen=bitgen,
- )
- state_after = source_state()
- staged_source_manifest = verify_staged_source_manifest(staged)
- source_state_stable = state_after == staged.source_state
- source_binding_gate = {
- "status": (
- "pass"
- if staged_source_manifest["status"] == "pass"
- and source_state_stable
- and td_source_states_clean(staged.source_state, state_after, staged_source_manifest)
- else "fail"
- ),
- "source_state_stable": source_state_stable,
- "failures": [
- *staged_source_manifest["failures"],
- *([] if source_state_stable else ["repository_source_state_changed_during_build"]),
- *([] if staged.source_state.get("clean") is True else ["repository_source_state_dirty_at_start"]),
- *([] if state_after.get("clean") is True else ["repository_source_state_dirty_after_build"]),
- ],
- }
- passed = (
- syn_ok
- and phy_ok
- and timing_result["status"] == "pass"
- and structural["status"] == "pass"
- and bitgen_ok
- and bitstream_sha256 is not None
- and source_binding_gate["status"] == "pass"
- and not measurement_failures
- )
- payload = {
- **metadata,
- "status": "pass" if passed else "fail",
- "generated_at": generated_at,
- "run_id": run_id,
- "commit": staged.source_state["commit"],
- "source_state": dict(staged.source_state),
- "repository_state_after": state_after,
- "bitstream_sha256": bitstream_sha256,
- "synthesis_input_manifest": dict(staged.synthesis_input_manifest),
- "synthesis_input_hash": staged.synthesis_input_manifest["sha256"],
- "clean": dict(staged.clean),
- "staged_source_manifest": staged_source_manifest,
- "source_binding_gate": source_binding_gate,
- "work_root": str(resolved),
- "build_dirs": {
- "syn": str(staged.syn),
- "phy": str(staged.phy),
- "bitgen": str(staged.bitgen),
- },
- "td_tool": {
- "path": str(TD_EXE.resolve()),
- "executable": TD_EXE.name,
- "version": "6.2.2.198412",
- "sha256": sha256_file(TD_EXE),
- },
- "pin_binding_gate": pins,
- "post_route_pin_gate": routed_pins,
- "binding_gate": {"status": "pass", "target_device": TARGET_DEVICE},
- "syn": _stage_result(syn),
- "phy": _stage_result(phy),
- "bitgen": _stage_result(bitgen),
- "bitstream": (
- None
- if bitstream_sha256 is None
- else {"path": str(bitstream), "size": bitstream.stat().st_size}
- ),
- "resources": resources,
- "resource_gate": {
- "status": "pass" if resources is not None else "fail",
- "advisory_only": True,
- "affects_build_status": False,
- },
- "resource_delta": _resource_delta_unavailable("new_minimal_baseline_pending"),
- "structural_gate": structural,
- "timing": timing,
- "timing_gate": timing_result,
- "error_summary": {
- "error_count": sum(
- int(bool(item and item.get("log_has_error")))
- for item in (_stage_result(syn), _stage_result(phy), _stage_result(bitgen))
- ),
- "critical_warning_count": sum(
- int(item.get("critical_warning_count", 0))
- for item in (_stage_result(syn), _stage_result(phy), _stage_result(bitgen))
- if item
- ),
- },
- "authority_boundary": (
- "This TD receipt covers synthesis, placement, routing, bit generation, timing, "
- "resources, and source binding only. It performs no cable or board action."
- ),
- }
- if measurement_failures:
- payload["measurement_artifact_failures"] = measurement_failures
- else:
- payload["measurement_artifacts"] = measurement_artifacts
- return payload
- def _emit(payload: Mapping[str, Any], args: argparse.Namespace, label: str) -> int:
- if getattr(args, "report_file", None):
- try:
- report_file = resolve_report_file(args.report_file)
- except ValueError as exc:
- print(json.dumps({"status": "fail", "reason": str(exc)}, indent=2) if getattr(args, "json", False) else f"{label}: fail")
- return 1
- write_json_report(payload, report_file)
- print(json.dumps(dict(payload), indent=2) if getattr(args, "json", False) else f"{label}: {payload.get('status', 'unknown')}")
- return 0 if payload.get("status") == "pass" else 1
- def package_required_files(*, confirmation_td_present: bool = True) -> tuple[str, ...]:
- required = (
- "fw.bit",
- "package-info.json",
- "evidence/td-primary-receipt.json",
- "evidence/validation-summary.json",
- "evidence/package-selftest-result.json",
- "config/host-contract.json",
- "config/prod2u_p4_normal_v3_hw_binding.json",
- "config/prod2u_p4_verification_targets_v1.json",
- "schemas/host-contract.schema.json",
- "bootstrap.ps1",
- "selftest.ps1",
- "run.ps1",
- "SEND_HEX.ps1",
- "INITIALIZE_DISABLE.ps1",
- "PROGRAM_SRAM.ps1",
- "README.zh-CN.md",
- )
- if confirmation_td_present:
- return required + ("evidence/td-confirmation-receipt.json",)
- return required
- def package_selftest_payload(
- package_dir: Path,
- *,
- verification_run_id: str | None = None,
- ) -> dict[str, Any]:
- package = Path(package_dir).expanduser().resolve()
- run_id = normalize_verification_run_id(verification_run_id)
- info_path = package / "package-info.json"
- primary_td_path = package / "evidence" / "td-primary-receipt.json"
- confirmation_td_path = package / "evidence" / "td-confirmation-receipt.json"
- validation_path = package / "evidence" / "validation-summary.json"
- packaged_selftest_path = package / "evidence" / "package-selftest-result.json"
- bitstream = package / "fw.bit"
- failures: list[str] = []
- info: Mapping[str, Any] = {}
- primary_td: Mapping[str, Any] = {}
- confirmation_td: Mapping[str, Any] = {}
- validation: Mapping[str, Any] = {}
- packaged_selftest: Mapping[str, Any] = {}
- inputs = (
- (info_path, "package_info"),
- (primary_td_path, "primary_td"),
- (validation_path, "validation"),
- (packaged_selftest_path, "packaged_selftest"),
- )
- loaded_inputs: dict[str, Mapping[str, Any]] = {}
- for path, label in inputs:
- try:
- loaded = json.loads(path.read_text(encoding="utf-8-sig"))
- except (OSError, UnicodeError, json.JSONDecodeError) as exc:
- failures.append(f"{label}_unreadable:{exc}")
- continue
- if not isinstance(loaded, Mapping):
- failures.append(f"{label}_not_object")
- else:
- loaded_inputs[label] = loaded
- info = loaded_inputs.get("package_info", {})
- delivery_mode = info.get("delivery_mode") if info else None
- if delivery_mode not in {"normal_dual_td", "urgent_single_td"}:
- failures.append("package_delivery_mode_invalid")
- confirmation_expected = delivery_mode != "urgent_single_td"
- if confirmation_expected or confirmation_td_path.exists():
- try:
- loaded = json.loads(confirmation_td_path.read_text(encoding="utf-8-sig"))
- except (OSError, UnicodeError, json.JSONDecodeError) as exc:
- failures.append(f"confirmation_td_unreadable:{exc}")
- else:
- if not isinstance(loaded, Mapping):
- failures.append("confirmation_td_not_object")
- else:
- loaded_inputs["confirmation_td"] = loaded
- primary_td = loaded_inputs.get("primary_td", {})
- confirmation_td = loaded_inputs.get("confirmation_td", {})
- validation = loaded_inputs.get("validation", {})
- packaged_selftest = loaded_inputs.get("packaged_selftest", {})
- for label, receipt in (
- ("package_info", info),
- ("primary_td", primary_td),
- ("confirmation_td", confirmation_td),
- ("validation", validation),
- ):
- if receipt and receipt.get("verification_run_id") != run_id:
- failures.append(f"verification_run_id_mismatch:{label}")
- digest = None
- if not bitstream.is_file() or bitstream.stat().st_size <= 0:
- failures.append("bitstream_missing")
- else:
- digest = sha256_file(bitstream)
- if info:
- if info.get("schema") != "prod2u-p4-normal-v3-folder-package-info-v3":
- failures.append("package_info_schema_mismatch")
- if info.get("profile") != RUNTIME_PROFILE:
- failures.append("package_profile_mismatch")
- verification_complete = info.get("verification_complete")
- confirmation_td_present = info.get("confirmation_td_present")
- if not isinstance(verification_complete, bool):
- failures.append("package_verification_complete_invalid")
- if not isinstance(confirmation_td_present, bool):
- failures.append("package_confirmation_td_present_invalid")
- elif confirmation_td_present != confirmation_td_path.is_file():
- failures.append("package_confirmation_td_presence_mismatch")
- if delivery_mode == "urgent_single_td":
- if verification_complete is not False:
- failures.append("urgent_verification_complete_must_be_false")
- if confirmation_td_present is not False:
- failures.append("urgent_confirmation_td_present_must_be_false")
- commit = str(info.get("commit", ""))
- if not re.fullmatch(r"[0-9a-f]{40}", commit):
- failures.append("package_commit_invalid")
- if info.get("bitstream_sha256") != digest:
- failures.append("package_bitstream_sha256_mismatch")
- expected_name = (
- f"prod2u-p4-normal-{commit}-{digest[:16]}"
- if digest is not None and re.fullmatch(r"[0-9a-f]{40}", commit)
- else None
- )
- if expected_name is not None and package.name != expected_name:
- failures.append("package_folder_name_mismatch")
- if re.fullmatch(r"[0-9a-f]{40}", commit) and package.parent.name != commit:
- failures.append("package_commit_parent_mismatch")
- if info.get("td_receipt_sha256") != (
- sha256_file(primary_td_path) if primary_td_path.is_file() else None
- ):
- failures.append("package_td_receipt_sha256_mismatch")
- if info.get("confirmation_td_receipt_sha256") != (
- sha256_file(confirmation_td_path) if confirmation_td_path.is_file() else None
- ):
- failures.append("package_confirmation_td_receipt_sha256_mismatch")
- if info.get("validation_summary_sha256") != (
- sha256_file(validation_path) if validation_path.is_file() else None
- ):
- failures.append("package_validation_summary_sha256_mismatch")
- if info.get("package_selftest_result_sha256") != (
- sha256_file(packaged_selftest_path) if packaged_selftest_path.is_file() else None
- ):
- failures.append("package_selftest_result_sha256_mismatch")
- actual_files = {
- path.relative_to(package).as_posix(): sha256_file(path)
- for path in sorted(package.rglob("*"))
- if path.is_file() and path not in {info_path, packaged_selftest_path}
- }
- expected_files = info.get("file_sha256") if isinstance(info, Mapping) else None
- if not isinstance(expected_files, Mapping) or dict(expected_files) != actual_files:
- failures.append("package_file_hash_map_mismatch")
- required_files = package_required_files(confirmation_td_present=confirmation_expected)
- checked_files = [
- relative
- for relative in required_files
- if (package / relative).is_file()
- ]
- for relative in required_files:
- if not (package / relative).is_file():
- failures.append(f"package_file_missing:{relative}")
- commit = info.get("commit") if info else None
- if primary_td:
- if primary_td.get("commit") != commit:
- failures.append("primary_td_commit_mismatch")
- if primary_td.get("bitstream_sha256") != digest:
- failures.append("primary_td_bitstream_sha256_mismatch")
- if info.get("synthesis_input_hash") != primary_td.get("synthesis_input_hash"):
- failures.append("primary_td_synthesis_input_hash_mismatch")
- if confirmation_td:
- if confirmation_td.get("commit") != commit:
- failures.append("confirmation_td_commit_mismatch")
- if (
- confirmation_td.get("bitstream_sha256") not in {None, ""}
- and confirmation_td.get("bitstream_sha256") != digest
- ):
- failures.append("confirmation_td_bitstream_sha256_mismatch")
- if info.get("confirmation_bitstream_sha256") != confirmation_td.get(
- "bitstream_sha256"
- ):
- failures.append("confirmation_td_bitstream_sha256_binding_mismatch")
- if info.get("confirmation_synthesis_input_hash") != confirmation_td.get(
- "synthesis_input_hash"
- ):
- failures.append("confirmation_td_synthesis_input_hash_mismatch")
- primary_run_id = primary_td.get("run_id")
- confirmation_run_id = confirmation_td.get("run_id")
- if (
- not valid_td_run_id(primary_run_id)
- or not valid_td_run_id(confirmation_run_id)
- or primary_run_id == confirmation_run_id
- ):
- failures.append("td_run_id_not_independent")
- primary_work_root = normalized_td_work_root(primary_td.get("work_root"))
- confirmation_work_root = normalized_td_work_root(
- confirmation_td.get("work_root")
- )
- if (
- primary_work_root is None
- or confirmation_work_root is None
- or primary_work_root == confirmation_work_root
- ):
- failures.append("td_work_root_not_independent")
- if validation:
- if validation.get("schema") != "prod2u-p4-normal-v3-validation-summary-v1":
- failures.append("validation_summary_schema_mismatch")
- if validation.get("commit") != commit or validation.get("bitstream_sha256") != digest:
- failures.append("validation_summary_binding_mismatch")
- for name in ("delivery_mode", "verification_complete", "confirmation_td_present"):
- if validation.get(name) != info.get(name):
- failures.append(f"validation_summary_{name}_mismatch")
- layers = validation.get("layers")
- if not isinstance(layers, Mapping):
- failures.append("validation_layers_missing")
- else:
- for name, layer in layers.items():
- status = layer.get("status") if isinstance(layer, Mapping) else None
- if status not in {"pass", "fail", "running", "not_run"}:
- failures.append(f"validation_layer_status_invalid:{name}")
- comparisons = {
- "td_confirmation_synthesis": (
- confirmation_td.get("synthesis_input_hash"),
- primary_td.get("synthesis_input_hash"),
- ),
- "td_confirmation_manifest": (
- (
- confirmation_td.get("synthesis_input_manifest", {}).get("sha256")
- if isinstance(confirmation_td.get("synthesis_input_manifest"), Mapping)
- else None
- ),
- (
- primary_td.get("synthesis_input_manifest", {}).get("sha256")
- if isinstance(primary_td.get("synthesis_input_manifest"), Mapping)
- else None
- ),
- ),
- }
- bitstream_layer = layers.get("td_confirmation_bitstream")
- expected_bitstream_status = td_receipt_bitstream_binding_status(
- confirmation_td
- )
- if (
- expected_bitstream_status == "pass"
- and confirmation_td.get("bitstream_sha256") != digest
- ):
- expected_bitstream_status = "fail"
- if (
- not isinstance(bitstream_layer, Mapping)
- or bitstream_layer.get("status")
- != expected_bitstream_status
- ):
- failures.append(
- "validation_layer_semantic_mismatch:td_confirmation_bitstream"
- )
- for name, (observed, expected) in comparisons.items():
- expected_status = (
- "not_run"
- if observed in {None, ""}
- else "pass" if observed == expected else "fail"
- )
- layer = layers.get(name)
- if not isinstance(layer, Mapping) or layer.get("status") != expected_status:
- failures.append(f"validation_layer_semantic_mismatch:{name}")
- if delivery_mode == "urgent_single_td":
- confirmation_layer = layers.get("td_confirmation")
- confirmation_status = (
- confirmation_layer.get("status")
- if isinstance(confirmation_layer, Mapping)
- else None
- )
- if confirmation_status not in {"not_run", "running"}:
- failures.append(
- "urgent_confirmation_layer_invalid:td_confirmation"
- )
- for name in (
- "td_confirmation_artifacts",
- "td_confirmation_bitstream",
- "td_confirmation_synthesis",
- "td_confirmation_manifest",
- "resource_confirmation",
- ):
- layer = layers.get(name)
- if not isinstance(layer, Mapping) or layer.get("status") != "not_run":
- failures.append(f"urgent_confirmation_layer_not_not_run:{name}")
- script_result: dict[str, Any] = {"status": "not_run", "returncode": None}
- selftest = package / "selftest.ps1"
- if not failures and selftest.is_file():
- completed = subprocess.run(
- [
- "powershell.exe",
- "-NoProfile",
- "-ExecutionPolicy",
- "Bypass",
- "-File",
- str(selftest),
- ],
- cwd=package,
- env=tool_env(),
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- timeout=60,
- check=False,
- )
- script_result = {
- "status": "pass" if completed.returncode == 0 else "fail",
- "returncode": completed.returncode,
- "stdout_tail": _tail(completed.stdout),
- "stderr_tail": _tail(completed.stderr),
- }
- if completed.returncode != 0:
- failures.append("package_selftest_script_failed")
- return {
- "schema": PACKAGE_RECEIPT_SCHEMA,
- "status": "pass" if not failures else "fail",
- "generated_at": utc_now(),
- "verification_run_id": run_id,
- "commit": info.get("commit") if info else None,
- "bitstream_sha256": digest,
- "package_dir": str(package),
- "delivery_mode": info.get("delivery_mode") if info else None,
- "verification_complete": info.get("verification_complete") if info else None,
- "confirmation_td_present": info.get("confirmation_td_present") if info else None,
- "package_info_sha256": sha256_file(info_path) if info_path.is_file() else None,
- "td_receipt_sha256": sha256_file(primary_td_path) if primary_td_path.is_file() else None,
- "confirmation_td_receipt_sha256": (
- sha256_file(confirmation_td_path) if confirmation_td_path.is_file() else None
- ),
- "validation_summary_sha256": sha256_file(validation_path) if validation_path.is_file() else None,
- "package_selftest_result_sha256": (
- sha256_file(packaged_selftest_path) if packaged_selftest_path.is_file() else None
- ),
- "td_run_id": primary_td.get("run_id") if primary_td else None,
- "confirmation_td_run_id": confirmation_td.get("run_id") if confirmation_td else None,
- "synthesis_input_hash": primary_td.get("synthesis_input_hash") if primary_td else None,
- "confirmation_synthesis_input_hash": (
- confirmation_td.get("synthesis_input_hash") if confirmation_td else None
- ),
- "confirmation_bitstream_sha256": (
- confirmation_td.get("bitstream_sha256") if confirmation_td else None
- ),
- "validation_status": validation_layer_summary(validation.get("layers")),
- "packaged_selftest_status": packaged_selftest.get("status") if packaged_selftest else None,
- "package_file_sha256": actual_files,
- "package_file_manifest_sha256": canonical_sha256(actual_files) if actual_files else None,
- "bound_files": checked_files,
- "failures": sorted(set(failures)),
- "selftest": script_result,
- "safety": dict(SAFETY_BOUNDARY),
- }
- def cmd_strict_offline(args: argparse.Namespace) -> int:
- return _emit(
- strict_offline_gate_payload(
- work_root=args.work_root,
- verification_run_id=args.verification_run_id,
- ),
- args,
- "p4-normal-v3-strict-offline-gate",
- )
- def cmd_hdl_sim(args: argparse.Namespace) -> int:
- return _emit(hdl_sim_payload(run=args.run, backend=args.backend, work_root=args.work_root), args, "hdl-sim")
- def cmd_formal(args: argparse.Namespace) -> int:
- return _emit(formal_payload(run=args.run, work_root=args.work_root), args, "formal")
- def cmd_td_build(args: argparse.Namespace) -> int:
- return _emit(
- td_build_payload(
- run=args.run,
- top=args.top,
- work_root=args.work_root,
- verification_run_id=args.verification_run_id,
- ),
- args,
- "td-build",
- )
- def cmd_package_selftest(args: argparse.Namespace) -> int:
- return _emit(
- package_selftest_payload(
- args.package_dir,
- verification_run_id=args.verification_run_id,
- ),
- args,
- "package-selftest",
- )
- def _gate_is_pass(receipt: Mapping[str, Any], name: str) -> bool:
- value = receipt.get(name)
- return isinstance(value, Mapping) and value.get("status") == "pass"
- def _td_final_failures(
- receipt: Mapping[str, Any],
- *,
- label: str,
- expected_commit: str,
- ) -> list[str]:
- failures: list[str] = []
- prefix = f"{label}:"
- if receipt.get("schema") != TD_RECEIPT_SCHEMA:
- failures.append(prefix + "schema")
- if receipt.get("status") != "pass":
- failures.append(prefix + "status")
- if receipt.get("commit") != expected_commit:
- failures.append(prefix + "commit")
- if not re.fullmatch(
- r"[0-9a-f]{32}", str(receipt.get("verification_run_id", ""))
- ):
- failures.append(prefix + "verification_run_id")
- if not valid_td_run_id(receipt.get("run_id")):
- failures.append(prefix + "run_id")
- if normalized_td_work_root(receipt.get("work_root")) is None:
- failures.append(prefix + "work_root")
- if not re.fullmatch(r"[0-9a-f]{64}", str(receipt.get("bitstream_sha256", ""))):
- failures.append(prefix + "bitstream_sha256")
- if not re.fullmatch(r"[0-9a-f]{64}", str(receipt.get("synthesis_input_hash", ""))):
- failures.append(prefix + "synthesis_input_hash")
- source = receipt.get("source_state")
- if not isinstance(source, Mapping) or source.get("clean") is not True or source.get("commit") != expected_commit:
- failures.append(prefix + "source_state")
- for gate_name in (
- "source_binding_gate",
- "pin_binding_gate",
- "post_route_pin_gate",
- "binding_gate",
- "timing_gate",
- "structural_gate",
- ):
- if not _gate_is_pass(receipt, gate_name):
- failures.append(prefix + gate_name)
- structural = receipt.get("structural_gate")
- cdc = structural.get("cdc") if isinstance(structural, Mapping) else None
- expected_cdc = {
- "async_reg": 2,
- "input_registers": 0,
- "retained_sync_registers": 2,
- "first_stage_endpoints": 1,
- }
- cdc_ok = isinstance(cdc, Mapping) and cdc.get("status") == "pass"
- for name, expected in expected_cdc.items():
- item = cdc.get(name) if isinstance(cdc, Mapping) else None
- cdc_ok = cdc_ok and isinstance(item, Mapping) and item.get("used") == expected
- if not cdc_ok:
- failures.append(prefix + "structural_gate:cdc")
- fsm = (
- structural.get("fsm_encoding")
- if isinstance(structural, Mapping)
- else None
- )
- if not (
- isinstance(fsm, Mapping)
- and fsm.get("status") == "pass"
- and fsm.get("encoding") == "sequential"
- and fsm.get("axes") == {"x": 2, "y": 2}
- and fsm.get("td_log_marker") is True
- and fsm.get("reencoded_motion_phase_count") == 0
- ):
- failures.append(prefix + "structural_gate:fsm_encoding")
- resources = receipt.get("resources")
- utilization = resources.get("utilization") if isinstance(resources, Mapping) else None
- required_resources = {
- "bram": 0,
- "bram32k": 0,
- "bram128k": 0,
- "bram256k": 0,
- "dsp": 0,
- "pad": 41,
- "ireg": 0,
- }
- for name, expected in required_resources.items():
- item = utilization.get(name) if isinstance(utilization, Mapping) else None
- used = item.get("used") if isinstance(item, Mapping) else None
- if used != expected:
- failures.append(prefix + f"resource:{name}:{used}")
- timing = receipt.get("timing")
- if not isinstance(timing, Mapping):
- failures.append(prefix + "timing")
- else:
- for name in ("fmax_mhz", "worst_setup_slack_ns", "worst_hold_slack_ns"):
- value = timing.get(name)
- if not isinstance(value, (int, float)) or isinstance(value, bool) or value <= 0:
- failures.append(prefix + f"timing:{name}")
- if timing.get("error_count") != 0:
- failures.append(prefix + "timing:error_count")
- routed_pins = receipt.get("post_route_pin_gate")
- if isinstance(routed_pins, Mapping):
- if routed_pins.get("row_count") != 41:
- failures.append(prefix + "post_route_pin_count")
- observed = routed_pins.get("observed")
- expected_pins = {
- signal: (
- expected["location"],
- expected["direction"],
- "LVCMOS33",
- expected["pull_type"],
- )
- for signal, expected in REQUIRED_MOTOR_LIMIT_PINS.items()
- }
- for signal, expected in expected_pins.items():
- row = observed.get(signal) if isinstance(observed, Mapping) else None
- values = (
- row.get("location"),
- row.get("direction"),
- row.get("io_standard"),
- row.get("pull_type"),
- ) if isinstance(row, Mapping) else None
- if values != expected:
- failures.append(prefix + f"post_route_pin:{signal}")
- for phase_name in ("syn", "phy", "bitgen"):
- phase = receipt.get(phase_name)
- if (
- not isinstance(phase, Mapping)
- or phase.get("status") != "pass"
- or phase.get("returncode") != 0
- or phase.get("log_has_error") is not False
- or phase.get("critical_warning_count") != 0
- ):
- failures.append(prefix + f"phase:{phase_name}")
- bitstream = receipt.get("bitstream")
- if not isinstance(bitstream, Mapping) or not isinstance(bitstream.get("size"), int) or bitstream.get("size") <= 0:
- failures.append(prefix + "bitstream_artifact")
- else:
- path = Path(str(bitstream.get("path", "")))
- if not path.is_file() or path.stat().st_size != bitstream.get("size"):
- failures.append(prefix + "bitstream_path")
- elif sha256_file(path) != receipt.get("bitstream_sha256"):
- failures.append(prefix + "bitstream_file_hash")
- return failures
- def _offline_final_failures(
- receipt: Mapping[str, Any],
- *,
- expected_commit: str,
- ) -> list[str]:
- failures: list[str] = []
- if receipt.get("schema") != OFFLINE_RECEIPT_SCHEMA:
- failures.append("offline:schema")
- if receipt.get("status") != "pass" or receipt.get("commit") != expected_commit:
- failures.append("offline:status_or_commit")
- source = receipt.get("source_state")
- if not isinstance(source, Mapping) or source.get("clean") is not True:
- failures.append("offline:source_state")
- layers = receipt.get("layers")
- required = receipt.get("required_layers")
- if required != ["source_integrity", "unit", "hdl_sim", "formal"]:
- failures.append("offline:required_layers")
- for name in required if isinstance(required, list) else []:
- layer = layers.get(name) if isinstance(layers, Mapping) else None
- if not isinstance(layer, Mapping) or layer.get("status") != "pass":
- failures.append(f"offline:layer:{name}")
- if receipt.get("failures") != []:
- failures.append("offline:failures")
- return failures
- def _package_final_failures(
- receipt: Mapping[str, Any],
- *,
- expected_commit: str,
- expected_bitstream_sha256: str,
- expected_primary_td_receipt_sha256: str,
- expected_confirmation_td_receipt_sha256: str,
- ) -> list[str]:
- failures: list[str] = []
- expected_verification_run_id = receipt.get("verification_run_id")
- if receipt.get("schema") != PACKAGE_RECEIPT_SCHEMA:
- failures.append("package:schema")
- if receipt.get("status") != "pass" or receipt.get("commit") != expected_commit:
- failures.append("package:status_or_commit")
- if receipt.get("bitstream_sha256") != expected_bitstream_sha256:
- failures.append("package:bitstream_sha256")
- if not re.fullmatch(
- r"[0-9a-f]{32}", str(expected_verification_run_id or "")
- ):
- failures.append("package:verification_run_id")
- if receipt.get("delivery_mode") != "normal_dual_td":
- failures.append("package:delivery_mode")
- if receipt.get("failures") != []:
- failures.append("package:failures")
- if receipt.get("verification_complete") is not True:
- failures.append("package:verification_incomplete")
- if receipt.get("confirmation_td_present") is not True:
- failures.append("package:confirmation_td_missing")
- if receipt.get("validation_status") != "pass":
- failures.append("package:validation_incomplete")
- if receipt.get("packaged_selftest_status") != "pass":
- failures.append("package:packaged_selftest")
- selftest = receipt.get("selftest")
- if not isinstance(selftest, Mapping) or selftest.get("status") != "pass" or selftest.get("returncode") != 0:
- failures.append("package:selftest")
- package_dir = Path(str(receipt.get("package_dir", "")))
- info_path = package_dir / "package-info.json"
- bitstream = package_dir / "fw.bit"
- primary_path = package_dir / "evidence" / "td-primary-receipt.json"
- confirmation_path = package_dir / "evidence" / "td-confirmation-receipt.json"
- validation_path = package_dir / "evidence" / "validation-summary.json"
- packaged_selftest_path = package_dir / "evidence" / "package-selftest-result.json"
- for relative in package_required_files(confirmation_td_present=True):
- if not (package_dir / relative).is_file():
- failures.append(f"package:required_file:{relative}")
- loaded: dict[str, Mapping[str, Any]] = {}
- for label, path in (
- ("info", info_path),
- ("primary_td", primary_path),
- ("confirmation_td", confirmation_path),
- ("validation", validation_path),
- ("packaged_selftest", packaged_selftest_path),
- ):
- if not path.is_file():
- continue
- try:
- loaded[label] = load_receipt(path)
- except (OSError, UnicodeError, json.JSONDecodeError, ValueError):
- failures.append(f"package:{label}_unreadable")
- info = loaded.get("info", {})
- primary_td = loaded.get("primary_td", {})
- confirmation_td = loaded.get("confirmation_td", {})
- validation = loaded.get("validation", {})
- packaged_selftest = loaded.get("packaged_selftest", {})
- if info:
- if (
- info.get("schema") != "prod2u-p4-normal-v3-folder-package-info-v3"
- or info.get("profile") != RUNTIME_PROFILE
- or info.get("verification_run_id") != expected_verification_run_id
- or info.get("commit") != expected_commit
- or info.get("bitstream_sha256") != expected_bitstream_sha256
- ):
- failures.append("package:info_binding")
- if info.get("delivery_mode") != "normal_dual_td":
- failures.append("package:info_delivery_mode")
- if info.get("verification_complete") is not True:
- failures.append("package:info_verification_incomplete")
- if info.get("confirmation_td_present") is not True:
- failures.append("package:info_confirmation_td_missing")
- if bitstream.is_file():
- if sha256_file(bitstream) != expected_bitstream_sha256:
- failures.append("package:file_hash")
- actual_hashes = {
- "package_info_sha256": sha256_file(info_path) if info_path.is_file() else None,
- "td_receipt_sha256": sha256_file(primary_path) if primary_path.is_file() else None,
- "confirmation_td_receipt_sha256": (
- sha256_file(confirmation_path) if confirmation_path.is_file() else None
- ),
- "validation_summary_sha256": (
- sha256_file(validation_path) if validation_path.is_file() else None
- ),
- "package_selftest_result_sha256": (
- sha256_file(packaged_selftest_path)
- if packaged_selftest_path.is_file()
- else None
- ),
- }
- for field, actual in actual_hashes.items():
- if receipt.get(field) != actual:
- failures.append(f"package:receipt_hash:{field}")
- for field in (
- "td_receipt_sha256",
- "confirmation_td_receipt_sha256",
- "validation_summary_sha256",
- "package_selftest_result_sha256",
- ):
- if info and info.get(field) != actual_hashes[field]:
- failures.append(f"package:info_hash:{field}")
- if actual_hashes["td_receipt_sha256"] != expected_primary_td_receipt_sha256:
- failures.append("package:primary_td_external_binding")
- if (
- actual_hashes["confirmation_td_receipt_sha256"]
- != expected_confirmation_td_receipt_sha256
- ):
- failures.append("package:confirmation_td_external_binding")
- actual_files = {
- path.relative_to(package_dir).as_posix(): sha256_file(path)
- for path in sorted(package_dir.rglob("*"))
- if path.is_file() and path not in {info_path, packaged_selftest_path}
- }
- if not info or info.get("file_sha256") != actual_files:
- failures.append("package:file_manifest:info")
- if receipt.get("package_file_sha256") != actual_files:
- failures.append("package:file_manifest:receipt")
- if receipt.get("package_file_manifest_sha256") != canonical_sha256(actual_files):
- failures.append("package:file_manifest:digest")
- if primary_td:
- if (
- primary_td.get("commit") != expected_commit
- or primary_td.get("verification_run_id")
- != expected_verification_run_id
- or primary_td.get("bitstream_sha256") != expected_bitstream_sha256
- or info.get("synthesis_input_hash") != primary_td.get("synthesis_input_hash")
- ):
- failures.append("package:primary_td_binding")
- if confirmation_td:
- if (
- confirmation_td.get("commit") != expected_commit
- or confirmation_td.get("verification_run_id")
- != expected_verification_run_id
- or confirmation_td.get("bitstream_sha256")
- != expected_bitstream_sha256
- or info.get("confirmation_bitstream_sha256")
- != confirmation_td.get("bitstream_sha256")
- or info.get("confirmation_synthesis_input_hash")
- != confirmation_td.get("synthesis_input_hash")
- ):
- failures.append("package:confirmation_td_binding")
- if validation:
- if (
- validation.get("schema")
- != "prod2u-p4-normal-v3-validation-summary-v1"
- or validation.get("verification_run_id")
- != expected_verification_run_id
- or validation.get("commit") != expected_commit
- or validation.get("bitstream_sha256") != expected_bitstream_sha256
- or validation.get("delivery_mode") != "normal_dual_td"
- or validation.get("verification_complete") is not True
- or validation.get("confirmation_td_present") is not True
- ):
- failures.append("package:validation_binding")
- if validation_layer_summary(validation.get("layers")) != "pass":
- failures.append("package:validation_layers")
- if (
- not packaged_selftest
- or packaged_selftest.get("status") != "pass"
- or packaged_selftest.get("returncode") != 0
- ):
- failures.append("package:packaged_selftest_content")
- return failures
- def cmd_final_gate(args: argparse.Namespace) -> int:
- try:
- verification_run_id = normalize_verification_run_id(
- args.verification_run_id
- )
- except ValueError as exc:
- return _emit(
- {"status": "fail", "reason": str(exc)},
- args,
- "p4-normal-v3-final-gate",
- )
- try:
- paths = {
- "offline": resolve_input_receipt(args.offline_receipt),
- "td": resolve_input_receipt(args.td_receipt),
- "td_confirmation": resolve_input_receipt(args.confirmation_td_receipt),
- "package": resolve_input_receipt(args.package_receipt),
- }
- except ValueError as exc:
- return _emit({"status": "fail", "reason": str(exc)}, args, "p4-normal-v3-final-gate")
- try:
- child_receipts = {name: load_receipt(path) for name, path in paths.items()}
- except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as exc:
- return _emit(
- {"status": "fail", "reason": f"input_receipt_unreadable:{exc}"},
- args,
- "p4-normal-v3-final-gate",
- )
- state = source_state()
- expected_commit = state.get("commit")
- if (
- state.get("status") != "pass"
- or state.get("clean") is not True
- or not re.fullmatch(r"[0-9a-f]{40}", str(expected_commit))
- ):
- failures = ["final_source_state_not_clean"]
- else:
- failures = []
- failures.extend(
- _offline_final_failures(
- child_receipts["offline"],
- expected_commit=str(expected_commit),
- )
- )
- failures.extend(
- _td_final_failures(
- child_receipts["td"],
- label="td",
- expected_commit=str(expected_commit),
- )
- )
- failures.extend(
- _td_final_failures(
- child_receipts["td_confirmation"],
- label="td_confirmation",
- expected_commit=str(expected_commit),
- )
- )
- for name, receipt in child_receipts.items():
- if receipt.get("verification_run_id") != verification_run_id:
- failures.append(f"verification_run_id_mismatch:{name}")
- primary = child_receipts["td"]
- confirmation = child_receipts["td_confirmation"]
- package = child_receipts["package"]
- failures.extend(
- _package_final_failures(
- package,
- expected_commit=str(expected_commit),
- expected_bitstream_sha256=str(primary.get("bitstream_sha256", "")),
- expected_primary_td_receipt_sha256=sha256_file(paths["td"]),
- expected_confirmation_td_receipt_sha256=sha256_file(
- paths["td_confirmation"]
- ),
- )
- )
- if primary.get("synthesis_input_hash") != confirmation.get("synthesis_input_hash"):
- failures.append("td_synthesis_input_hash_mismatch")
- if primary.get("bitstream_sha256") != confirmation.get("bitstream_sha256"):
- failures.append("td_bitstream_sha256_mismatch")
- if (
- not valid_td_run_id(primary.get("run_id"))
- or not valid_td_run_id(confirmation.get("run_id"))
- or primary.get("run_id") == confirmation.get("run_id")
- ):
- failures.append("td_run_id_not_independent")
- primary_work_root = normalized_td_work_root(primary.get("work_root"))
- confirmation_work_root = normalized_td_work_root(confirmation.get("work_root"))
- if (
- primary_work_root is None
- or confirmation_work_root is None
- or primary_work_root == confirmation_work_root
- ):
- failures.append("td_work_root_not_independent")
- if primary.get("td_tool") != confirmation.get("td_tool"):
- failures.append("td_tool_mismatch")
- if primary.get("synthesis_input_manifest") != confirmation.get("synthesis_input_manifest"):
- failures.append("td_synthesis_input_manifest_mismatch")
- if primary.get("bitstream_sha256") != package.get("bitstream_sha256"):
- failures.append("package_bitstream_mismatch")
- payload = {
- "schema": "prod2u-p4-normal-v3-final-gate-v3",
- "status": "pass" if not failures else "fail",
- "generated_at": utc_now(),
- "verification_run_id": verification_run_id,
- "commit": expected_commit,
- "source_state": state,
- "child_receipts": {
- name: {"path": str(paths[name]), "sha256": sha256_file(paths[name])}
- for name in paths
- },
- "bitstream_sha256": primary.get("bitstream_sha256"),
- "synthesis_input_hash": primary.get("synthesis_input_hash"),
- "failures": sorted(set(failures)),
- "safety": dict(SAFETY_BOUNDARY),
- "authority_boundary": (
- "This receipt aggregates offline, two independent TD builds, and package evidence. "
- "It does not prove board programming or mechanical direction."
- ),
- }
- return _emit(payload, args, "p4-normal-v3-final-gate")
- def _common_output_options(parser: argparse.ArgumentParser) -> None:
- parser.add_argument("--json", action="store_true")
- parser.add_argument("--report-file", type=Path)
- def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(description=__doc__)
- sub = parser.add_subparsers(dest="command", required=True)
- offline = sub.add_parser("p4-normal-v3-strict-offline-gate", help="run every required offline Normal v3 layer")
- offline.add_argument("--work-root", type=Path, required=True)
- offline.add_argument("--verification-run-id", required=True)
- _common_output_options(offline)
- offline.set_defaults(func=cmd_strict_offline)
- hdl = sub.add_parser("hdl-sim", help="run registered Icarus, Verilator, or cocotb targets")
- hdl.add_argument("--run", action="store_true")
- hdl.add_argument("--backend", choices=("icarus", "verilator", "cocotb", "all"), default="icarus")
- hdl.add_argument("--work-root", type=Path)
- _common_output_options(hdl)
- hdl.set_defaults(func=cmd_hdl_sim)
- formal = sub.add_parser("formal", help="run all registered Normal v3 formal targets")
- formal.add_argument("--run", action="store_true")
- formal.add_argument("--work-root", type=Path)
- _common_output_options(formal)
- formal.set_defaults(func=cmd_formal)
- td = sub.add_parser("td-build", help="build the sole production TD top")
- td.add_argument("--run", action="store_true")
- td.add_argument("--top", choices=(PROFILE,), default=PROFILE)
- td.add_argument("--work-root", type=Path)
- td.add_argument("--verification-run-id", required=True)
- _common_output_options(td)
- td.set_defaults(func=cmd_td_build)
- package = sub.add_parser("package-selftest", help="validate a folder delivery without hardware access")
- package.add_argument("--package-dir", type=Path, required=True)
- package.add_argument("--verification-run-id", required=True)
- _common_output_options(package)
- package.set_defaults(func=cmd_package_selftest)
- final = sub.add_parser("p4-normal-v3-final-gate", help="aggregate clean offline, TD, and package receipts")
- final.add_argument("--offline-receipt", type=Path, required=True)
- final.add_argument("--td-receipt", type=Path, required=True, help="optimized production O-A receipt")
- final.add_argument("--confirmation-td-receipt", type=Path, required=True, help="independent optimized production O-B receipt")
- final.add_argument("--package-receipt", type=Path, required=True)
- final.add_argument("--verification-run-id", required=True)
- _common_output_options(final)
- final.set_defaults(func=cmd_final_gate)
- return parser
- def main(argv: Sequence[str] | None = None) -> int:
- args = build_parser().parse_args(argv)
- return int(args.func(args))
- if __name__ == "__main__":
- raise SystemExit(main())
|