| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570 |
- #!/usr/bin/env python3
- """Layered offline verification harness for pid_study_01."""
- from __future__ import annotations
- import argparse
- import csv
- import hashlib
- import importlib.util
- import json
- import os
- import re
- import shutil
- import socket
- import subprocess
- import sys
- import xml.etree.ElementTree as ET
- from datetime import datetime, timezone
- from pathlib import Path
- from typing import Any
- sys.dont_write_bytecode = True
- from pid_contract_model import (
- ACTUATOR_REASON_FAN_FALLBACK,
- ACTUATOR_REASON_HOST_TIMEOUT,
- ACTUATOR_REASON_OK,
- ACTUATOR_REASON_OVERTEMP,
- ACTUATOR_REASON_PID_OR_SENSOR_FAULT,
- ACTUATOR_REASON_SENSOR_STALE,
- ActuatorDomain,
- ActuatorSink,
- BMC_DIMM_USER_SAMPLE_TEXT,
- BMC_POLL_COMMAND_ASCII,
- BmcDimmFrameParser,
- FakeHostConfig,
- FakeStressModel,
- HostConfigV2,
- HostConfigStep,
- PARSER_STATUS_BAD_FRACTION,
- PARSER_STATUS_BAD_LENGTH,
- PARSER_STATUS_NO_CANDIDATE,
- PARSER_STATUS_OK,
- PidResult,
- SafetySupervisor,
- SensorSampleV2,
- ThermalControlService24Ch,
- TwentyFourChannelPid,
- load_contract_config,
- config_contract_summary,
- load_replay_expectations_csv,
- load_host_csv,
- load_sensor_csv,
- run_replay,
- verify_replay_expectations,
- )
- from debug_contract import (
- DEBUG_EVENT_REQUIRED_FIELDS,
- analyze_debug_bundle,
- build_debug_bundle,
- normalize_replay_trace,
- )
- from toolchain_probe import probe_toolchain
- from pin_inventory import diagnostic_profile_assignments, load_pin_inventory
- ROOT = Path(__file__).resolve().parents[1]
- TD_EXE = Path(r"C:\Anlogic\TD_Release_2026.1_SP1.198.412\bin\td_commands_prompt.exe")
- VERILATOR_LINT_MODE = "verilator --lint-only"
- DEFAULT_TOOLCHAIN_BASE = Path.home() / "CodexToolchains" / "CPLD"
- DEFAULT_OSS_CAD_SUITE_ROOT = DEFAULT_TOOLCHAIN_BASE / "oss-cad-suite" / "latest"
- DEFAULT_COCOTB_VENV_PYTHON = DEFAULT_TOOLCHAIN_BASE / "venvs" / "pid-study-cocotb-venv" / "Scripts" / "python.exe"
- COMPAT_COCOTB_VENV_PYTHON = DEFAULT_TOOLCHAIN_BASE / "venvs" / "pid-contract-cocotb-venv" / "Scripts" / "python.exe"
- TD_BUILD_SYN = ROOT / "td" / "build" / "syn"
- TD_BUILD_PHY = ROOT / "td" / "build" / "phy"
- EXTERNAL_TD_BIN_LOG = Path(r"C:\Anlogic\TD_Release_2026.1_SP1.198.412\bin\log")
- DEFAULT_TD_TOP = "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921"
- REAL_FAN_PTC_INVENTORY = ROOT / "config" / "pin_inventory.fcb_fpga_mcu0611.json"
- TD_TOP_PROFILES = {
- "system_contract": {
- "mode": "elaboration",
- "display_name": "unconstrained system contract logic top",
- "top_module": "system_contract_top",
- },
- "debug_max": {
- "mode": "elaboration",
- "display_name": "debug-max logic evidence top",
- "top_module": "system_contract_top",
- },
- "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921": {
- "mode": "implementation",
- "display_name": "J6 host sensor real FAN/PTC temporary UART diagnostic: current J6/COM7/COM8 wiring with six PTC channels remapped to verified spare GPIO",
- "top_module": "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921_top",
- "source_prj": "td/uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921.prj",
- "build_subdir": "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921",
- "syn_script": "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921.tcl",
- "phy_script": "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921.tcl",
- "bitstream": "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921.bit",
- "area_report": "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921_phy.area",
- "timing_report": "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921_pr.timing",
- "pin_profile": "temp-uart-ptc-remap",
- "tx_ball": "T4",
- "rx_ball": "R5",
- "host_uart_tx_ball": "P7",
- "host_uart_rx_ball": "P8",
- "debug_uart_rx_ball": "P10",
- "debug_uart_tx_ball": "R10",
- "host_uart_baud": 115200,
- "bmc_uart_baud": 115200,
- "debug_uart_baud": 921600,
- "debug_uart_clks_per_bit": 27,
- "requires_verified_real_fan_ptc_pin_map": True,
- "authority_boundary": "SRAM-only temp-uart-ptc-remap diagnostic evidence for current J6/COM7/COM8 wiring. Six overlapping PTC outputs are substituted; it does not claim real thermal performance, production PTC/FAN qualification, flash, or PID closed-loop pass.",
- },
- "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921": {
- "mode": "implementation",
- "display_name": "J6 host sensor real FAN/PTC formal UART diagnostic: schematic FAN/PTC pins retained and three diagnostic UARTs moved to spare GPIO",
- "top_module": "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921_top",
- "source_prj": "td/uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921.prj",
- "build_subdir": "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921",
- "syn_script": "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921.tcl",
- "phy_script": "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921.tcl",
- "bitstream": "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921.bit",
- "area_report": "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921_phy.area",
- "timing_report": "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921_pr.timing",
- "pin_profile": "formal-uart",
- "tx_ball": "P5",
- "rx_ball": "T8",
- "host_uart_tx_ball": "M14",
- "host_uart_rx_ball": "M15",
- "debug_uart_rx_ball": "P15",
- "debug_uart_tx_ball": "N14",
- "host_uart_baud": 115200,
- "bmc_uart_baud": 115200,
- "debug_uart_baud": 921600,
- "debug_uart_clks_per_bit": 27,
- "requires_verified_real_fan_ptc_pin_map": True,
- "authority_boundary": "SRAM-only formal-uart diagnostic evidence. Schematic HEAT/FAN/FG/INSTALL pins are retained, diagnostic UARTs use spare GPIO, and reserved UART1/2 pins remain unused. It does not claim real thermal performance, production PTC/FAN qualification, flash, or PID closed-loop pass.",
- },
- }
- TD_GENERATED_SUFFIXES = {
- ".area",
- ".bid",
- ".bit",
- ".db",
- ".f",
- ".timing",
- ".tsm",
- }
- TD_GENERATED_PREFIXES = (
- "td_",
- )
- TD_SOURCE_SUFFIXES = {
- ".prj",
- ".tcl",
- }
- TD_PRESERVED_PATTERNS = [
- "*.tcl",
- "*.prj",
- ]
- VERILATOR_LINT_WAIVERS = [
- "MULTITOP", # Filelist intentionally lints reusable modules plus tops together.
- "WIDTHTRUNC", # Verilog-2001 parameters are range-constrained at assignment sites.
- "WIDTHEXPAND", # Signed fixed-point math uses explicit downstream clamps.
- "BLKSEQ", # Some clocked blocks use temporary next-value variables.
- "UNUSEDPARAM", # Contract modules expose forward-compatible parameters.
- "UNUSEDSIGNAL", # Debug/readback/status buses intentionally expose subsets.
- "VARHIDDEN", # Verilog task ports reuse contract field names locally.
- "CASEINCOMPLETE", # Source mux defaults to fake source for unknown selections.
- "SYNCASYNCNET", # Top-level reset is used by async-reset IP and sync debug wrapper logic.
- ]
- def toolchain_roots() -> list[Path]:
- roots: list[Path] = []
- for name in ["PID_STUDY_TOOLCHAIN_ROOT", "PID_STUDY_01_TOOLCHAIN_ROOT", "PID_CONTRACT_TOOLCHAIN_ROOT", "OSS_CAD_SUITE_ROOT"]:
- value = os.environ.get(name)
- if value:
- roots.append(Path(value))
- roots.append(DEFAULT_OSS_CAD_SUITE_ROOT)
- return roots
- def resolve_tool(name: str) -> str | None:
- path = shutil.which(name)
- if path:
- return path
- if name == "verilator":
- executable_names = ["verilator_bin.exe", "verilator.exe", "verilator"]
- else:
- executable_names = [name] if name.lower().endswith(".exe") else [name, f"{name}.exe"]
- for root in toolchain_roots():
- for exe_name in executable_names:
- for candidate in [root / "bin" / exe_name, root / exe_name]:
- if candidate.is_file():
- return str(candidate)
- return None
- def tool_env(extra: dict[str, str] | None = None) -> dict[str, str]:
- env = os.environ.copy()
- env.setdefault("PYTHONDONTWRITEBYTECODE", "1")
- path_parts = []
- for root in toolchain_roots():
- bin_dir = root / "bin"
- lib_dir = root / "lib"
- verilator_root = root / "share" / "verilator"
- smtbmc = root / "bin" / "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() and "VERILATOR_ROOT" not in env:
- env["VERILATOR_ROOT"] = str(verilator_root)
- if smtbmc.is_file() and "SMTBMC" not in env:
- env["SMTBMC"] = str(smtbmc)
- if path_parts:
- env["PATH"] = os.pathsep.join(path_parts + [env.get("PATH", "")])
- if extra:
- env.update(extra)
- return env
- def is_td_generated_output(path: Path) -> bool:
- if path.suffix.lower() in TD_SOURCE_SUFFIXES:
- return False
- if path.suffix.lower() in TD_GENERATED_SUFFIXES:
- return True
- if any(path.name.startswith(prefix) for prefix in TD_GENERATED_PREFIXES):
- return True
- return False
- def clean_td_outputs(project_root: Path = ROOT) -> dict[str, Any]:
- td_dirs = [project_root / "td" / "build" / "syn", project_root / "td" / "build" / "phy"]
- td_root_generated = project_root / "td"
- project_root_generated_patterns = ["td_*.log", "td_*.logw", "minidump-*.dmp"]
- project_log_generated_patterns = ["log/bw_*.log", "log/bw_*.logw"]
- build_started_at = datetime.now(timezone.utc).isoformat()
- deleted: list[str] = []
- preserved: list[str] = []
- errors: list[dict[str, str]] = []
- for directory in td_dirs:
- if not directory.is_dir():
- continue
- for path in sorted(directory.rglob("*"), key=lambda item: len(item.parts), reverse=True):
- rel = path.relative_to(project_root).as_posix()
- if path.is_dir():
- try:
- path.rmdir()
- deleted.append(rel + "/")
- except OSError:
- preserved.append(rel + "/")
- continue
- if not path.is_file():
- preserved.append(rel)
- continue
- try:
- path.unlink()
- deleted.append(rel)
- except OSError as exc:
- errors.append({"path": rel, "error": str(exc)})
- if td_root_generated.is_dir():
- for path in sorted(td_root_generated.glob("*.dmp")):
- rel = path.relative_to(project_root).as_posix()
- try:
- path.unlink()
- deleted.append(rel)
- except OSError as exc:
- errors.append({"path": rel, "error": str(exc)})
- for pattern in project_root_generated_patterns:
- for path in sorted(project_root.glob(pattern)):
- rel = path.relative_to(project_root).as_posix()
- try:
- path.unlink()
- deleted.append(rel)
- except OSError as exc:
- errors.append({"path": rel, "error": str(exc)})
- for pattern in project_log_generated_patterns:
- for path in sorted(project_root.glob(pattern)):
- rel = path.relative_to(project_root).as_posix()
- try:
- path.unlink()
- deleted.append(rel)
- except OSError as exc:
- errors.append({"path": rel, "error": str(exc)})
- return {
- "status": "pass" if not errors else "fail",
- "build_started_at": build_started_at,
- "deleted_count": len(deleted),
- "deleted": deleted,
- "preserved": preserved,
- "preserved_patterns": TD_PRESERVED_PATTERNS,
- "errors": errors,
- }
- def _safe_workspace_target(project_root: Path, target: Path) -> Path:
- root = project_root.resolve()
- resolved = target.resolve()
- if resolved == root or root not in resolved.parents:
- raise ValueError(f"refusing to delete outside project root: {target}")
- return resolved
- def _path_manifest_item(path: Path, base: Path | None = None) -> dict[str, Any]:
- item: dict[str, Any] = {
- "path": str(path if base is None else path.relative_to(base)),
- "exists": path.exists(),
- "kind": "dir" if path.is_dir() else "file" if path.is_file() else "missing",
- }
- if path.is_file():
- item["size"] = path.stat().st_size
- item["mtime_utc"] = datetime.fromtimestamp(path.stat().st_mtime, timezone.utc).isoformat()
- item["sha256"] = sha256(path)
- elif path.is_dir():
- files = [child for child in path.rglob("*") if child.is_file()]
- item["file_count"] = len(files)
- item["total_size"] = sum(child.stat().st_size for child in files)
- latest = max((child.stat().st_mtime for child in files), default=path.stat().st_mtime)
- item["latest_mtime_utc"] = datetime.fromtimestamp(latest, timezone.utc).isoformat()
- return item
- def _delete_path(path: Path, *, project_root: Path, external_allowed: bool = False) -> tuple[list[str], list[dict[str, str]]]:
- deleted: list[str] = []
- errors: list[dict[str, str]] = []
- try:
- target = path.resolve() if external_allowed else _safe_workspace_target(project_root, path)
- if not target.exists():
- return deleted, errors
- label = str(target)
- if target.is_dir():
- shutil.rmtree(target)
- deleted.append(label + os.sep)
- else:
- target.unlink()
- deleted.append(label)
- except OSError as exc:
- errors.append({"path": str(path), "error": str(exc)})
- return deleted, errors
- def clean_runtime_payload(
- project_root: Path = ROOT,
- *,
- include_external_td_log: bool = False,
- external_td_log_dir: Path = EXTERNAL_TD_BIN_LOG,
- ) -> dict[str, Any]:
- started_at = datetime.now(timezone.utc).isoformat()
- manifest_dir = project_root / ".codex" / "cleanup_manifests"
- manifest_dir.mkdir(parents=True, exist_ok=True)
- manifest_path = manifest_dir / (datetime.now().strftime("cleanup_%Y%m%d_%H%M%S.json"))
- workspace_targets = [
- project_root / "td" / "build",
- project_root / "tmp",
- project_root / "receipts" / "local",
- ]
- workspace_targets.extend(project_root.glob("td/project/*_Runs"))
- workspace_targets.extend(project_root.glob("td/project/log"))
- workspace_targets.extend(project_root.glob("td_*.log"))
- workspace_targets.extend(project_root.glob("td_*.logw"))
- workspace_targets.extend(project_root.glob("minidump-*.dmp"))
- workspace_targets.extend(project_root.rglob("__pycache__"))
- workspace_targets.extend(project_root.rglob(".pytest_cache"))
- before = [_path_manifest_item(path, project_root) for path in workspace_targets if path.exists()]
- external_targets: list[Path] = []
- if include_external_td_log and external_td_log_dir.is_dir():
- external_targets = list(external_td_log_dir.glob("bw_*.log")) + list(external_td_log_dir.glob("bw_*.logw"))
- external_before = [_path_manifest_item(path) for path in external_targets if path.exists()]
- deleted: list[str] = []
- errors: list[dict[str, str]] = []
- for target in sorted(set(workspace_targets), key=lambda item: len(item.parts), reverse=True):
- if not target.exists():
- continue
- current_deleted, current_errors = _delete_path(target, project_root=project_root)
- deleted.extend(current_deleted)
- errors.extend(current_errors)
- for target in external_targets:
- current_deleted, current_errors = _delete_path(target, project_root=project_root, external_allowed=True)
- deleted.extend(current_deleted)
- errors.extend(current_errors)
- payload = {
- "schema": "pid-study-runtime-cleanup-v1",
- "status": "pass" if not errors else "fail",
- "started_at": started_at,
- "finished_at": datetime.now(timezone.utc).isoformat(),
- "project_root": str(project_root),
- "include_external_td_log": include_external_td_log,
- "external_td_log_dir": str(external_td_log_dir),
- "deleted_count": len(deleted),
- "deleted": deleted,
- "before": before,
- "external_before": external_before,
- "errors": errors,
- "manifest": str(manifest_path.relative_to(project_root)),
- "authority_boundary": "Cleanup removes runtime/build/log evidence only. Source, tests, schemas, docs, and reference/original are not cleanup targets.",
- }
- manifest_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
- return payload
- def toolchain_clean_payload(
- *,
- install_root: Path = DEFAULT_OSS_CAD_SUITE_ROOT,
- cocotb_venv: Path = DEFAULT_COCOTB_VENV_PYTHON.parent.parent,
- include_downloads: bool = False,
- apply: bool = False,
- ) -> dict[str, Any]:
- try:
- from bootstrap_oss_cad_suite import uninstall_owned_toolchain
- payload = uninstall_owned_toolchain(
- install_root=install_root,
- cocotb_venv=cocotb_venv,
- dry_run=not apply,
- include_downloads=include_downloads,
- download_dir=DEFAULT_TOOLCHAIN_BASE / "downloads",
- )
- except Exception as exc: # pragma: no cover - import failure is environment-dependent.
- payload = {
- "schema": "offline-toolchain-uninstall-v1",
- "status": "blocked_clean_failed",
- "mode": "apply" if apply else "dry_run",
- "targets": [],
- "error": str(exc),
- "cleanup_policy": {
- "default": "dry_run",
- "requires_owner_marker": True,
- "owner_marker_name": ".cpld_toolchain_owner.json",
- "actual_delete_requires_apply": True,
- "allowed_root": str(DEFAULT_TOOLCHAIN_BASE),
- },
- "safety": {
- "opens_com_ports": False,
- "toggles_dtr_rts": False,
- "installs_drivers": False,
- "programs_flash": False,
- "touches_ptc_fan_bmc": False,
- },
- "authority_boundary": "toolchain-clean only removes user-mode toolchain paths that carry the CPLD owner marker; it never probes COM ports, installs drivers, programs flash, or touches real hardware.",
- }
- payload["schema"] = "offline-toolchain-clean-v1"
- payload["cleanup_policy"]["allowed_root"] = str(DEFAULT_TOOLCHAIN_BASE)
- return {
- **payload,
- "authority_boundary": "toolchain-clean only removes user-mode toolchain paths that carry the CPLD owner marker; it never probes COM ports, installs drivers, programs flash, or touches real hardware.",
- }
- def cocotb_python() -> str:
- return (
- os.environ.get("PID_STUDY_COCOTB_PYTHON")
- or os.environ.get("PID_STUDY_01_COCOTB_PYTHON")
- or os.environ.get("PID_CONTRACT_COCOTB_PYTHON")
- ) or (
- str(DEFAULT_COCOTB_VENV_PYTHON)
- if DEFAULT_COCOTB_VENV_PYTHON.is_file()
- else str(COMPAT_COCOTB_VENV_PYTHON)
- if COMPAT_COCOTB_VENV_PYTHON.is_file()
- else sys.executable
- )
- def cocotb_module_available(python_exe: str | None = None) -> bool:
- if python_exe and Path(python_exe) != Path(sys.executable):
- try:
- result = subprocess.run(
- [python_exe, "-c", "import cocotb"],
- cwd=ROOT,
- env=tool_env(),
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- timeout=20,
- )
- except (OSError, subprocess.TimeoutExpired):
- return False
- return result.returncode == 0
- try:
- return importlib.util.find_spec("cocotb") is not None
- except (ImportError, ValueError):
- return False
- def run_python(script: str) -> subprocess.CompletedProcess[str]:
- env = os.environ.copy()
- env["PYTHONDONTWRITEBYTECODE"] = "1"
- return subprocess.run(
- [sys.executable, str(ROOT / "tools" / script)],
- cwd=ROOT,
- env=env,
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- )
- def run_unit_test(script: str) -> subprocess.CompletedProcess[str]:
- env = tool_env({"PYTHONPATH": str(ROOT / "tools")})
- return subprocess.run(
- [sys.executable, str(ROOT / "tests" / "unit" / script)],
- cwd=ROOT,
- env=env,
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- )
- def td_build_dirs_for_profile(top: str = DEFAULT_TD_TOP) -> tuple[Path, Path]:
- profile = TD_TOP_PROFILES[top]
- build_subdir = profile.get("build_subdir")
- if build_subdir:
- base = ROOT / "td" / "build" / str(build_subdir)
- return base / "syn", base / "phy"
- return TD_BUILD_SYN, TD_BUILD_PHY
- def _td_source_path_from_project_path(project_path: str) -> Path:
- if project_path.startswith("../../"):
- return ROOT / project_path[6:]
- if project_path.startswith("../"):
- return ROOT / project_path[3:]
- return ROOT / project_path
- def _td_build_project_path(top: str, project_path: str, source: Path, build_dir: Path) -> str:
- if project_path.startswith(("../../src/top/", "../src/top/")):
- return f"src/top/{source.name}"
- if project_path.startswith(("../../src/rtl/", "../src/rtl/")):
- return f"src/rtl/{source.name}"
- if project_path.startswith(("../../constraints/", "../constraints/")):
- return f"constraints/{source.name}"
- return Path(os.path.relpath(source, build_dir)).as_posix()
- def _copy_td_project_payload(prj: Path, build_dir: Path, top: str) -> None:
- text = prj.read_text(encoding="utf-8")
- replacements: dict[str, str] = {}
- for match in re.finditer(r'<File Path="([^"]+)">', text):
- project_path = match.group(1)
- source = _td_source_path_from_project_path(project_path)
- if not source.is_file():
- continue
- replacement = _td_build_project_path(top, project_path, source, build_dir)
- target = build_dir / replacement
- target.parent.mkdir(parents=True, exist_ok=True)
- shutil.copy2(source, target)
- replacements[project_path] = replacement
- for old, new in replacements.items():
- text = text.replace(old, new)
- prj.write_text(text, encoding="utf-8")
- def write_td_gui_project_from_prj(prj: Path, al_path: Path, project_root: Path) -> None:
- """Write a TD GUI .al project from the batch .prj source list."""
- tree = ET.parse(prj)
- root = tree.getroot()
- root.set("Path", project_root.as_posix())
- root.set("RunTime", datetime.now(timezone.utc).replace(microsecond=0).isoformat())
- source_files = root.find("Source_Files")
- runs = root.find("Runs")
- if runs is None:
- runs = ET.SubElement(root, "Runs")
- if not any(run.get("Name") == "syn" for run in runs.findall("Run")):
- syn = ET.SubElement(runs, "Run", {"Name": "syn", "Type": "Synthesis", "ConstraintSet": "constraint_1", "Description": "", "Active": "true"})
- ET.SubElement(syn, "Strategy", {"Name": "Default_Synthesis_Strategy"})
- if not any(run.get("Name") == "phy" for run in runs.findall("Run")):
- phy = ET.SubElement(runs, "Run", {"Name": "phy", "Type": "PhysicalDesign", "ConstraintSet": "constraint_1", "Description": "", "SynRun": "syn", "Active": "true"})
- ET.SubElement(phy, "Strategy", {"Name": "Default_PhysicalDesign_Strategy"})
- if root.find("Project_Settings") is None:
- ET.SubElement(root, "Project_Settings")
- al_path.parent.mkdir(parents=True, exist_ok=True)
- ET.indent(tree, space=" ")
- tree.write(al_path, encoding="utf-8", xml_declaration=True)
- def prepare_td_build_dirs(top: str = DEFAULT_TD_TOP) -> tuple[Path, Path]:
- if top not in TD_TOP_PROFILES:
- raise ValueError(f"unsupported TD top profile: {top}")
- profile = TD_TOP_PROFILES[top]
- syn_build, phy_build = td_build_dirs_for_profile(top)
- syn_build.mkdir(parents=True, exist_ok=True)
- phy_build.mkdir(parents=True, exist_ok=True)
- source_prj = ROOT / str(profile.get("source_prj", f"td/{top}.prj"))
- for source, target in [
- (source_prj, syn_build / str(profile["syn_script"]).replace(".tcl", ".prj")),
- (ROOT / "td" / "syn" / str(profile["syn_script"]), syn_build / str(profile["syn_script"])),
- (source_prj, phy_build / str(profile["phy_script"]).replace(".tcl", ".prj")),
- (ROOT / "td" / "phy" / str(profile["phy_script"]), phy_build / str(profile["phy_script"])),
- ]:
- shutil.copy2(source, target)
- for build_dir, script_key in [(syn_build, "syn_script"), (phy_build, "phy_script")]:
- prj = build_dir / str(profile[script_key]).replace(".tcl", ".prj")
- _copy_td_project_payload(prj, build_dir, top)
- return syn_build, phy_build
- def td_process_env(run_dir: Path) -> dict[str, str]:
- """Run TD with isolated temp files while keeping the licensed user profile."""
- env = os.environ.copy()
- env_root = run_dir / "td_user_env"
- temp_dir = env_root / "temp"
- temp_dir.mkdir(parents=True, exist_ok=True)
- env.update(
- {
- "TEMP": str(temp_dir),
- "TMP": str(temp_dir),
- }
- )
- return env
- def run_td_script(run_dir: Path, script_name: str) -> subprocess.CompletedProcess[str]:
- run_dir.mkdir(parents=True, exist_ok=True)
- # TD 2026.1 SP1 is sensitive to command ordering in batch mode; source the
- # script as an argument and let the Tcl keep import_device before open_project.
- return subprocess.run(
- [str(TD_EXE), script_name],
- cwd=run_dir,
- env=td_process_env(run_dir),
- text=True,
- encoding="utf-8",
- errors="replace",
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- timeout=1800,
- )
- def td_profile_for_top_module(top_name: str) -> dict[str, Any]:
- for profile in TD_TOP_PROFILES.values():
- if profile.get("top_module") == top_name:
- return profile
- return {"source_prj": f"td/{DEFAULT_TD_TOP}.prj", "top_module": top_name}
- TD_FORBIDDEN_SCRIPT_COMMANDS = {
- "download",
- "program",
- "program_svf",
- "connect_cable",
- "read_device_id",
- "read_dna",
- "read_efuse",
- "write_phy_data",
- "read_phy_data",
- "write_bram",
- "write_bram18",
- "write_bram20",
- "write_bram32",
- }
- TD_FORBIDDEN_SCRIPT_TOKENS = {
- "PROGRAM_FLASH",
- "ERASE_FLASH",
- "PROGRAM_SPIBIN",
- "DIRECT_FLASH_WRITE",
- "PROGRAM_SRAM",
- }
- def td_verilog_sources_from_project(source_prj: Path) -> list[Path]:
- tree = ET.parse(source_prj)
- sources: list[Path] = []
- seen: set[Path] = set()
- for file_node in tree.findall(".//Verilog/File"):
- project_path = str(file_node.get("Path") or "").strip()
- if not project_path:
- continue
- candidate = Path(project_path)
- if not candidate.is_absolute():
- candidate = (source_prj.parent / candidate).resolve()
- else:
- candidate = candidate.resolve()
- if candidate in seen:
- continue
- if not candidate.is_file():
- raise FileNotFoundError(f"TD source file not found: {project_path} resolved to {candidate}")
- sources.append(candidate)
- seen.add(candidate)
- if not sources:
- raise ValueError(f"TD project contains no Verilog source files: {source_prj}")
- return sources
- 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()
- if not line or line.startswith("#"):
- continue
- command = re.split(r"\s+", line, maxsplit=1)[0].lower()
- if command in TD_FORBIDDEN_SCRIPT_COMMANDS:
- markers.add(command)
- upper_text = script_text.upper()
- for token in TD_FORBIDDEN_SCRIPT_TOKENS:
- if token in upper_text:
- markers.add(token)
- return sorted(markers)
- def build_td_elaboration_plan(top_name: str, source_prj: Path, build_dir: Path) -> dict[str, Any]:
- sources = td_verilog_sources_from_project(source_prj)
- build_dir.mkdir(parents=True, exist_ok=True)
- script_path = build_dir / f"elaborate_{top_name}.tcl"
- db_name = f"{top_name}_elaborate.db"
- lines = ["import_device ef2_4.db -package EF2L45BG256B"]
- for source in sources:
- lines.append(f"analyze -file {{{source.as_posix()}}}")
- lines.extend([
- f"elaborate -top {{{top_name}}}",
- f"export_db {db_name}",
- "",
- ])
- script_text = "\n".join(lines)
- forbidden = td_forbidden_script_markers(script_text)
- if forbidden:
- raise ValueError(f"TD elaboration script contains forbidden hardware command(s): {', '.join(forbidden)}")
- script_path.write_text(script_text, encoding="utf-8")
- manifest_payload = {
- "schema": "td-offline-elaboration-plan-v1",
- "top": top_name,
- "source_prj": str(source_prj),
- "source_prj_sha256": sha256(source_prj),
- "script": str(script_path),
- "script_sha256": sha256(script_path),
- "database": str(build_dir / db_name),
- "sources": [
- {
- "path": str(source),
- "sha256": sha256(source),
- }
- for source in sources
- ],
- "safety": {
- "opens_com_ports": False,
- "toggles_dtr_rts": False,
- "installs_drivers": False,
- "programs_flash": False,
- "downloads_to_hardware": False,
- "touches_ptc_fan_bmc": False,
- "real_ptc_fan_bmc_action_attempted": False,
- },
- "forbidden_markers": forbidden,
- "authority_boundary": "TD offline elaboration plan analyzes RTL and exports an elaboration database only; it never downloads, programs, opens cables, or touches real hardware.",
- }
- manifest_path = build_dir / f"{top_name}_elaboration_plan.json"
- manifest_path.write_text(json.dumps(manifest_payload, indent=2) + "\n", encoding="utf-8")
- return {
- **manifest_payload,
- "manifest": str(manifest_path),
- "manifest_sha256": sha256(manifest_path),
- }
- def run_td_elaboration(top_name: str) -> dict[str, Any]:
- if not TD_EXE.is_file():
- return {"status": "blocked", "reason": f"missing TD executable: {TD_EXE}"}
- profile = td_profile_for_top_module(top_name)
- source_prj = ROOT / str(profile.get("source_prj", f"td/{DEFAULT_TD_TOP}.prj"))
- build_dir = TD_BUILD_SYN / "elaboration" / top_name
- try:
- plan = build_td_elaboration_plan(top_name, source_prj, build_dir)
- except (OSError, ValueError, ET.ParseError) as exc:
- return {
- "status": "fail",
- "top": top_name,
- "invocation": "analyze_elaborate_script",
- "source_prj": str(source_prj),
- "reason": str(exc),
- "safety": {
- "opens_com_ports": False,
- "toggles_dtr_rts": False,
- "installs_drivers": False,
- "programs_flash": False,
- "downloads_to_hardware": False,
- "touches_ptc_fan_bmc": False,
- "real_ptc_fan_bmc_action_attempted": False,
- },
- }
- script_name = Path(str(plan["script"])).name
- result = subprocess.run(
- [str(TD_EXE), script_name],
- cwd=build_dir,
- env=td_process_env(build_dir),
- text=True,
- encoding="utf-8",
- errors="replace",
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- timeout=600,
- )
- has_error = td_log_has_error(result.stdout, result.stderr)
- db_path = Path(str(plan["database"]))
- db_info = None
- if db_path.is_file() and db_path.stat().st_size > 0:
- db_info = {"path": str(db_path), "size": db_path.stat().st_size, "sha256": sha256(db_path)}
- return {
- "status": "pass" if result.returncode == 0 and not has_error and db_info else "fail",
- "top": top_name,
- "invocation": "analyze_elaborate_script",
- "source_prj": str(source_prj),
- "plan": plan,
- "script": str(build_dir / script_name),
- "database": db_info,
- "returncode": result.returncode,
- "log_has_error": has_error,
- "stdout_tail": result.stdout[-4000:],
- "stderr_tail": result.stderr[-4000:],
- "safety": plan["safety"],
- "authority_boundary": "TD elaboration evidence proves the vendor CLI analyzed RTL and elaborated the requested top offline; it does not generate/download/program a bitstream or certify pins/hardware.",
- }
- def run_logic_elaborations() -> dict[str, Any]:
- tops = [
- "system_contract_top",
- "uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top",
- ]
- results = {top: run_td_elaboration(top) for top in tops}
- statuses = {item["status"] for item in results.values()}
- if "fail" in statuses:
- status_value = "fail"
- elif "blocked" in statuses:
- status_value = "blocked"
- else:
- status_value = "pass"
- return {"status": status_value, "tops": results}
- def hdl_testbenches() -> list[dict[str, Any]]:
- return [
- {"name": "debug_trigger_unit_tb", "sources": ["src/rtl/debug_trigger_unit.v", "tests/sim/debug_trigger_unit_tb.v"]},
- {"name": "debug_trace_recorder_bram_tb", "sources": ["src/rtl/debug_trace_recorder_bram.v", "tests/sim/debug_trace_recorder_bram_tb.v"]},
- {"name": "debug_register_window_tb", "sources": ["src/rtl/debug_register_window.v", "tests/sim/debug_register_window_tb.v"]},
- {"name": "debug_uart_stream_tb", "sources": ["src/rtl/debug_uart_stream.v", "tests/sim/debug_uart_stream_tb.v"]},
- {"name": "uart_8n1_phy_tb", "sources": ["src/rtl/uart_tx_8n1.v", "src/rtl/uart_rx_8n1.v", "tests/sim/uart_8n1_phy_tb.v"]},
- {"name": "uart_rx_error_tb", "sources": ["src/rtl/uart_rx_8n1.v", "tests/sim/uart_rx_error_tb.v"]},
- {"name": "uart_rx_back_to_back_tb", "sources": ["src/rtl/uart_rx_8n1.v", "tests/sim/uart_rx_back_to_back_tb.v"]},
- {
- "name": "uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top_tb",
- "sources": [
- "src/rtl/uart_tx_8n1.v",
- "src/rtl/uart_rx_8n1.v",
- "src/rtl/bmc_uart_raw48_poll_lite.v",
- "src/top/uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top.v",
- "tests/sim/uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top_tb.v",
- ],
- },
- {"name": "bmc_uart_phy_bridge_tb", "sources": ["src/rtl/bmc_uart_phy_bridge.v", "tests/sim/bmc_uart_phy_bridge_tb.v"]},
- {"name": "bmc_uart_ascii_poll_tb", "sources": ["src/rtl/bmc_uart_ascii_poll.v", "tests/sim/bmc_uart_ascii_poll_tb.v"]},
- {"name": "bmc_dimm_frame_parser_tb", "sources": ["src/rtl/bmc_dimm_frame_parser.v", "tests/sim/bmc_dimm_frame_parser_tb.v"]},
- {"name": "source_arbitrator_tb", "sources": ["src/rtl/source_arbitrator.v", "tests/sim/source_arbitrator_tb.v"]},
- {"name": "hysteresis_pi_controller_tb", "sources": ["src/rtl/hysteresis_pi_controller.v", "tests/sim/hysteresis_pi_controller_tb.v"]},
- {
- "name": "control_service_24ch_tb",
- "sources": [
- "src/rtl/pid_24ch_scheduler.v",
- "src/rtl/control_service_24ch.v",
- "tests/sim/control_service_24ch_tb.v",
- ],
- },
- {"name": "pid_core_tb", "sources": ["src/rtl/pid_core.v", "tests/sim/pid_core_tb.v"]},
- {
- "name": "pid_contract_integration_tb",
- "sources": ["src/rtl/pid_24ch_scheduler.v", "src/rtl/actuator_sink.v", "tests/sim/pid_contract_integration_tb.v"],
- },
- {"name": "pid_source_mux_tb", "sources": ["src/rtl/sensor_source_mux.v", "tests/sim/pid_source_mux_tb.v"]},
- {"name": "pid_control_regfile_tb", "sources": ["src/rtl/pid_control_regfile.v", "tests/sim/pid_control_regfile_tb.v"]},
- {"name": "sensor_domain_tb", "sources": ["src/rtl/sensor_source_mux.v", "src/rtl/sensor_domain.v", "tests/sim/sensor_domain_tb.v"]},
- {"name": "host_command_plane_tb", "sources": ["src/rtl/pid_control_regfile.v", "src/rtl/host_command_plane.v", "tests/sim/host_command_plane_tb.v"]},
- {"name": "safety_supervisor_tb", "sources": ["src/rtl/safety_supervisor.v", "tests/sim/safety_supervisor_tb.v"]},
- {"name": "ptc_output_bank_tb", "sources": ["src/rtl/ptc_output_bank.v", "tests/sim/ptc_output_bank_tb.v"]},
- {"name": "fan_tach_domain_tb", "sources": ["src/rtl/fan_tach_domain.v", "tests/sim/fan_tach_domain_tb.v"]},
- {"name": "board_io_adapter_tb", "sources": ["src/rtl/board_io_adapter.v", "tests/sim/board_io_adapter_tb.v"]},
- {"name": "motor_limit_domain_tb", "sources": ["src/rtl/motor_limit_domain.v", "tests/sim/motor_limit_domain_tb.v"]},
- {
- "name": "actuator_domain_tb",
- "sources": [
- "src/rtl/ptc_output_bank.v",
- "src/rtl/fan_tach_domain.v",
- "src/rtl/board_io_adapter.v",
- "src/rtl/motor_limit_domain.v",
- "src/rtl/actuator_domain.v",
- "tests/sim/actuator_domain_tb.v",
- ],
- },
- {"name": "debug_snapshot_v2_tb", "sources": ["src/rtl/debug_snapshot_v2.v", "tests/sim/debug_snapshot_v2_tb.v"]},
- {
- "name": "system_contract_top_tb",
- "sources": [
- "src/rtl/bmc_uart_ascii_poll.v",
- "src/rtl/bmc_dimm_frame_parser.v",
- "src/rtl/fake_sensor_source.v",
- "src/rtl/i2c_master_sensor_adapter.v",
- "src/rtl/pid_control_regfile.v",
- "src/rtl/sensor_source_mux.v",
- "src/rtl/sensor_domain.v",
- "src/rtl/host_command_plane.v",
- "src/rtl/safety_supervisor.v",
- "src/rtl/ptc_output_bank.v",
- "src/rtl/fan_tach_domain.v",
- "src/rtl/board_io_adapter.v",
- "src/rtl/motor_limit_domain.v",
- "src/rtl/pid_24ch_scheduler.v",
- "src/rtl/actuator_domain.v",
- "src/rtl/debug_snapshot_v2.v",
- "src/rtl/debug_trigger_unit.v",
- "src/rtl/debug_trace_recorder_bram.v",
- "src/rtl/debug_register_window.v",
- "src/rtl/debug_uart_stream.v",
- "src/rtl/debug_probe_bus.v",
- "src/top/system_contract_top.v",
- "tests/sim/system_contract_top_tb.v",
- ],
- },
- ]
- def verilator_lint_targets() -> list[dict[str, Any]]:
- sources: list[str] = []
- for testbench in hdl_testbenches():
- for source in testbench["sources"]:
- if source.startswith(("src/rtl/", "src/top/")) and source not in sources:
- sources.append(source)
- return [
- {
- "name": "pid_contract_rtl_and_tops",
- "sources": sources,
- "waiver_file": "tests/verilator_waivers.vlt",
- }
- ]
- def cocotb_tests() -> list[dict[str, Any]]:
- return [
- {
- "name": "pid_core_smoke",
- "path": "tests/cocotb",
- "toplevel": "pid_core",
- "module": "test_pid_core_smoke",
- "simulator": "icarus",
- }
- ]
- def formal_targets() -> list[dict[str, Any]]:
- return [
- {"name": "fault_implies_ptc_off", "sby": "tests/formal/fault_implies_ptc_off.sby"},
- {"name": "invalid_channel_no_actuator", "sby": "tests/formal/invalid_channel_no_actuator.sby"},
- {"name": "disable_clears_history", "sby": "tests/formal/disable_clears_history.sby"},
- {"name": "thermal_fault_requests_fan_fallback", "sby": "tests/formal/thermal_fault_requests_fan_fallback.sby"},
- ]
- def detector_selftest_targets() -> dict[str, dict[str, Any]]:
- return {
- "icarus": {
- "required_tools": ["iverilog"],
- "command_kind": "compile_bad_testbench",
- "source": "tests/fixtures/bad_icarus_tb.v",
- },
- "verilator": {
- "required_tools": ["verilator"],
- "command_kind": "lint_bad_fixture",
- "source": "tests/fixtures/bad_verilator_lint.v",
- },
- "cocotb": {
- "required_tools": ["python_module:cocotb", "iverilog", "vvp"],
- "command_kind": "scoreboard_bad_expected",
- "path": "tests/cocotb",
- },
- "formal": {
- "required_tools": ["sby", "yosys"],
- "command_kind": "counterexample_bad_property",
- "sby": "tests/fixtures/bad_formal_fail.sby",
- },
- }
- def _missing_tool_payload(payload: dict[str, Any], missing_tools: list[str]) -> dict[str, Any]:
- return {
- "status": "blocked_missing_tool",
- "reason": "missing required external tool(s): " + ", ".join(missing_tools),
- "missing_tools": missing_tools,
- **payload,
- }
- def _tail(text: str, limit: int = 4000) -> str:
- return text[-limit:] if text else ""
- def detector_selftest_payload(run: bool, backend: str = "all") -> dict[str, Any]:
- all_targets = detector_selftest_targets()
- selected = all_targets if backend == "all" else {backend: all_targets[backend]}
- payload = {
- "verification_layer": "detector_selftest",
- "origin": "project_defined_strategy",
- "fact_class": "project_defined_strategy",
- "backend": backend,
- "authority_boundary": "These selftests intentionally run bad fixtures. A pass means the detector caught the failure; it does not validate the RTL design.",
- "targets": selected,
- }
- if not run:
- return {"status": "skipped", "reason": "Detector selftest not requested. Use detector-selftest --run.", **payload}
- results = []
- for name, target in selected.items():
- missing_tools = []
- for tool in target["required_tools"]:
- if tool == "python_module:cocotb":
- if not cocotb_module_available(cocotb_python()):
- missing_tools.append(tool)
- elif not resolve_tool(tool):
- missing_tools.append(tool)
- if missing_tools:
- results.append({
- "name": name,
- "status": "blocked_missing_tool",
- "missing_tools": missing_tools,
- "reason": "missing required external tool(s): " + ", ".join(missing_tools),
- })
- continue
- if name == "icarus":
- iverilog = resolve_tool("iverilog")
- assert iverilog is not None
- out = ROOT / "tmp" / "detector_selftest" / "bad_icarus.vvp"
- out.parent.mkdir(parents=True, exist_ok=True)
- cmd = [iverilog, "-g2005-sv", "-o", str(out), str(ROOT / target["source"])]
- result = subprocess.run(cmd, cwd=ROOT, env=tool_env(), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- elif name == "verilator":
- verilator = resolve_tool("verilator")
- assert verilator is not None
- cmd = [verilator, "--lint-only", "-Wall", "--Werror-UNUSEDSIGNAL", str(ROOT / target["source"])]
- result = subprocess.run(cmd, cwd=ROOT, env=tool_env(), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- elif name == "cocotb":
- env = tool_env({
- "PID_STUDY_COCOTB_FORCE_BAD_EXPECTED": "1",
- })
- cmd = [cocotb_python(), str(ROOT / target["path"] / "run_pid_core_smoke.py")]
- result = subprocess.run(cmd, cwd=ROOT / target["path"], env=env, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- elif name == "formal":
- sby = resolve_tool("sby")
- assert sby is not None
- sby_file = ROOT / target["sby"]
- workdir = ROOT / "tmp" / "formal_runs" / "detector_selftest" / name
- cmd = [sby, "-f", "-d", str(workdir), str(sby_file)]
- result = subprocess.run(cmd, cwd=sby_file.parent, env=tool_env(), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- else:
- results.append({"name": name, "status": "fail", "reason": f"unsupported selftest backend: {name}"})
- continue
- caught_failure = result.returncode != 0
- results.append({
- "name": name,
- "status": "pass" if caught_failure else "fail",
- "expected_bad_fixture_to_fail": True,
- "returncode": result.returncode,
- "command": cmd,
- "stdout": _tail(result.stdout),
- "stderr": _tail(result.stderr),
- "reason": "bad fixture failure was caught" if caught_failure else "bad fixture unexpectedly passed; detector is not trustworthy",
- })
- statuses = {item["status"] for item in results}
- if "fail" in statuses:
- status_value = "fail"
- elif statuses == {"blocked_missing_tool"}:
- status_value = "blocked_missing_tool"
- elif "blocked_missing_tool" in statuses:
- status_value = "partial"
- else:
- status_value = "pass"
- return {"status": status_value, **payload, "results": results}
- def hdl_sim_payload(run: bool, backend: str = "icarus", scenario: Path | None = None) -> dict[str, Any]:
- metadata = {
- "verification_layer": "hdl_sim",
- "origin": "project_defined_optional_verification_layer",
- "backend": backend,
- "fact_class": "project_defined_strategy",
- "authority_boundary": "This is a project harness strategy, not an Anlogic TD or chip-vendor requirement.",
- "scenario": None if scenario is None else str(scenario),
- }
- testbenches = hdl_testbenches()
- if backend == "all":
- backends = ["icarus", "verilator", "cocotb"]
- backend_results = {name: hdl_sim_payload(run=run, backend=name, scenario=scenario) for name in backends}
- statuses = {item["status"] for item in backend_results.values()}
- if "fail" in statuses:
- status_value = "fail"
- elif statuses == {"pass"}:
- status_value = "pass"
- elif statuses == {"blocked_missing_tool"}:
- status_value = "blocked_missing_tool"
- elif statuses == {"skipped"}:
- status_value = "skipped"
- else:
- status_value = "partial"
- missing_tools: list[str] = []
- for item in backend_results.values():
- missing_tools.extend(item.get("missing_tools", []))
- return {
- "status": status_value,
- **metadata,
- "mode": "multi_backend",
- "required_tools": ["iverilog", "vvp", "verilator", "python_module:cocotb"],
- "backend_results": backend_results,
- "missing_tools": sorted(set(missing_tools)),
- "authority_boundary": "This aggregates project-defined optional HDL backends. A partial result means at least one backend produced evidence and at least one backend was blocked by a missing external tool.",
- }
- if backend == "verilator":
- verilator = resolve_tool("verilator")
- targets = verilator_lint_targets()
- payload = {
- **metadata,
- "mode": "lint_first",
- "command_mode": VERILATOR_LINT_MODE,
- "required_tools": ["verilator"],
- "tests": targets,
- }
- if not run:
- return {"status": "skipped", "reason": "HDL simulation not requested.", **payload}
- if not verilator:
- return _missing_tool_payload(payload, ["verilator"])
- results = []
- for target in targets:
- waiver_file = ROOT / target["waiver_file"]
- cmd = [verilator, "--lint-only", "-Wall", "--timing"]
- cmd.extend(f"-Wno-{warning}" for warning in VERILATOR_LINT_WAIVERS)
- if waiver_file.is_file():
- cmd.append(str(waiver_file))
- cmd.extend(str(ROOT / src) for src in target["sources"])
- result = subprocess.run(cmd, cwd=ROOT, env=tool_env(), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- results.append({
- "name": target["name"],
- "status": "pass" if result.returncode == 0 else "fail",
- "returncode": result.returncode,
- "command": cmd,
- "stdout": _tail(result.stdout),
- "stderr": _tail(result.stderr),
- })
- ok = all(item["status"] == "pass" for item in results)
- return {"status": "pass" if ok else "fail", **payload, "tool": verilator, "tests": results}
- if backend == "cocotb":
- tests = cocotb_tests()
- payload = {
- **metadata,
- "mode": "python_cosimulation",
- "required_tools": ["python_module:cocotb", "iverilog", "vvp"],
- "authority_boundary": "cocotb is a Python cosimulation framework and still needs a simulator backend; this is not an Anlogic TD requirement.",
- "tests": tests,
- }
- py = cocotb_python()
- has_cocotb = cocotb_module_available(py)
- missing_tools = []
- if not has_cocotb:
- missing_tools.append("python_module:cocotb")
- for tool in ["iverilog", "vvp"]:
- if not resolve_tool(tool):
- missing_tools.append(tool)
- if not run:
- return {"status": "skipped", "reason": "HDL simulation not requested.", **payload}
- if missing_tools:
- return _missing_tool_payload(payload, missing_tools)
- results = []
- for test in tests:
- test_dir = ROOT / test["path"]
- env = tool_env()
- cmd = [py, str(test_dir / "run_pid_core_smoke.py")]
- result = subprocess.run(cmd, cwd=test_dir, env=env, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- results.append({
- "name": test["name"],
- "status": "pass" if result.returncode == 0 else "fail",
- "returncode": result.returncode,
- "command": cmd,
- "cwd": str(test_dir),
- "stdout": _tail(result.stdout),
- "stderr": _tail(result.stderr),
- })
- ok = all(item["status"] == "pass" for item in results)
- return {"status": "pass" if ok else "fail", **payload, "tests": results}
- if backend != "icarus":
- return {"status": "fail", "reason": f"unsupported hdl simulator backend: {backend}", **metadata, "tests": testbenches}
- metadata["required_tools"] = ["iverilog", "vvp"]
- iverilog = resolve_tool("iverilog")
- vvp = resolve_tool("vvp")
- if not run:
- return {
- "status": "skipped",
- "reason": "HDL simulation not requested. Use hdl-sim --run.",
- **metadata,
- "tests": testbenches,
- }
- missing_tools = [name for name, path in [("iverilog", iverilog), ("vvp", vvp)] if not path]
- if missing_tools:
- return _missing_tool_payload({**metadata, "tests": testbenches}, missing_tools)
- sim_dir = ROOT / "tmp" / "rtl_sim"
- sim_dir.mkdir(parents=True, exist_ok=True)
- results = []
- for tb in testbenches:
- out = sim_dir / f"{tb['name']}.vvp"
- compile_cmd = [iverilog, "-g2005-sv", "-o", str(out)] + [str(ROOT / src) for src in tb["sources"]]
- compile_result = subprocess.run(compile_cmd, cwd=ROOT, env=tool_env(), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- run_result = None
- if compile_result.returncode == 0:
- run_result = subprocess.run([vvp, str(out)], cwd=ROOT, env=tool_env(), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- results.append({
- "name": tb["name"],
- "status": "pass" if compile_result.returncode == 0 and run_result is not None and run_result.returncode == 0 else "fail",
- "compile_command": compile_cmd,
- "compile_returncode": compile_result.returncode,
- "compile_stdout": _tail(compile_result.stdout, 2000),
- "compile_stderr": _tail(compile_result.stderr, 2000),
- "run_returncode": None if run_result is None else run_result.returncode,
- "run_stdout": "" if run_result is None else _tail(run_result.stdout, 2000),
- "run_stderr": "" if run_result is None else _tail(run_result.stderr, 2000),
- })
- ok = all(item["compile_returncode"] == 0 and item["run_returncode"] == 0 for item in results)
- return {"status": "pass" if ok else "fail", **metadata, "tool": iverilog, "tests": results}
- def rtl_sim_payload(run: bool) -> dict[str, Any]:
- payload = hdl_sim_payload(run=run, backend="icarus")
- payload["verification_layer"] = "rtl_sim_compat"
- return payload
- def formal_payload(run: bool, engine: str = "sby") -> dict[str, Any]:
- payload = {
- "verification_layer": "formal",
- "origin": "project_defined_optional_verification_layer",
- "engine": engine,
- "fact_class": "project_defined_strategy",
- "authority_boundary": "Formal checks prove bounded design properties only when the selected engine actually runs; they are not board or thermal proof.",
- "properties": [
- "fault_implies_ptc_off",
- "invalid_channel_no_actuator",
- "disable_clears_history",
- "thermal_fault_requests_fan_fallback",
- ],
- }
- if engine != "sby":
- return {"status": "fail", "reason": f"unsupported formal engine: {engine}", **payload}
- payload["required_tools"] = ["sby", "yosys"]
- payload["targets"] = formal_targets()
- if not run:
- return {"status": "skipped", "reason": "Formal verification not requested. Use formal --run.", **payload}
- sby = resolve_tool("sby")
- yosys = resolve_tool("yosys")
- missing_tools = [name for name, path in [("sby", sby), ("yosys", yosys)] if not path]
- if missing_tools:
- return _missing_tool_payload(payload, missing_tools)
- results = []
- for target in formal_targets():
- sby_file = ROOT / target["sby"]
- if not sby_file.is_file():
- results.append({
- "name": target["name"],
- "status": "fail",
- "returncode": None,
- "reason": f"missing formal target file: {sby_file}",
- })
- continue
- workdir = ROOT / "tmp" / "formal_runs" / target["name"]
- result = subprocess.run(
- [sby, "-f", "-d", str(workdir), str(sby_file)],
- cwd=sby_file.parent,
- env=tool_env(),
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- timeout=180,
- )
- counterexamples = []
- if workdir.is_dir():
- counterexamples = [str(path) for path in workdir.rglob("*.vcd")]
- results.append({
- "name": target["name"],
- "status": "pass" if result.returncode == 0 else "fail",
- "returncode": result.returncode,
- "command": [sby, "-f", "-d", str(workdir), str(sby_file)],
- "stdout": _tail(result.stdout),
- "stderr": _tail(result.stderr),
- "workdir": str(workdir),
- "counterexamples": counterexamples,
- })
- ok = all(item["status"] == "pass" for item in results)
- return {"status": "pass" if ok else "fail", **payload, "tool": sby, "yosys": yosys, "targets": results}
- def status(returncode: int) -> str:
- return "pass" if returncode == 0 else "fail"
- def td_log_has_error(*chunks: str) -> bool:
- text = "\n".join(chunk for chunk in chunks if chunk)
- return re.search(r"\b(?:ERROR|Error|error)\b|invalid command name|Cannot open file", text) is not None
- def parse_td_version(*chunks: str) -> dict[str, str | None]:
- text = "\n".join(chunk for chunk in chunks if chunk)
- release = re.search(r"Release_20[0-9.]+(?:_SP[0-9]+)?", text)
- build = re.search(r"\b\d+\.\d+\.\d+\.\d{4,}\b", text)
- return {
- "release": release.group(0) if release else None,
- "build": build.group(0) if build else None,
- }
- def sha256(path: Path) -> str:
- digest = hashlib.sha256()
- with path.open("rb") as handle:
- for chunk in iter(lambda: handle.read(1024 * 1024), b""):
- digest.update(chunk)
- return digest.hexdigest()
- def write_json_report(payload: dict[str, Any], path: Path) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
- def _speed_history(rounds: list[dict[str, Any]]) -> list[str]:
- history: list[str] = []
- for item in rounds:
- speed = str(item.get("speed") or "")
- if speed and speed not in history:
- history.append(speed)
- return history
- def parse_utc_datetime(value: str) -> datetime:
- normalized = value.strip()
- if normalized.endswith("Z"):
- normalized = normalized[:-1] + "+00:00"
- parsed = datetime.fromisoformat(normalized)
- if parsed.tzinfo is None:
- parsed = parsed.replace(tzinfo=timezone.utc)
- return parsed.astimezone(timezone.utc)
- def contract_replay_payload() -> dict[str, Any]:
- sensor_vector = ROOT / "test_vectors" / "sensor_replay_basic.csv"
- host_vector = ROOT / "test_vectors" / "host_config_replay_basic.csv"
- expectation_vector = ROOT / "test_vectors" / "actuator_expectations_basic.csv"
- samples = load_sensor_csv(sensor_vector)
- host = load_host_csv(host_vector)
- contract_config = load_contract_config()
- control = contract_config.get("control", {})
- actuator = contract_config.get("actuator", {})
- fan_policy = contract_config.get("fan_policy", {})
- if not isinstance(control, dict) or not isinstance(actuator, dict) or not isinstance(fan_policy, dict):
- raise ValueError("pid contract config has invalid control/actuator/fan_policy sections")
- report = run_replay(
- samples=samples,
- host=host,
- pid=ThermalControlService24Ch(
- channel_count=24,
- out_min=int(actuator["out_min"]),
- out_max=int(actuator["out_max"]),
- target_tolerance_q=int(control.get("target_tolerance_q", 7)),
- power_limit=int(control.get("power_limit_default", actuator["out_max"])),
- kp_q=int(control.get("kp_q", 4)),
- ki_q=int(control.get("ki_q", 1)),
- manual_level=int(control.get("manual_level_default", 0)),
- ),
- sink=ActuatorDomain(
- channel_count=24,
- out_min=int(actuator["out_min"]),
- out_max=int(actuator["out_max"]),
- fan_background_level=int(fan_policy.get("background_level", 38)),
- fan_fallback_level=int(fan_policy.get("fallback_level", 127)),
- ),
- )
- verify_replay_expectations(report, load_replay_expectations_csv(expectation_vector))
- return {
- "status": "pass",
- "control_service": str(control.get("default_mode", "incremental_pid_default")),
- "config": config_contract_summary(),
- "sensor_vector": str(sensor_vector),
- "host_vector": str(host_vector),
- "expectation_vector": str(expectation_vector),
- **report.to_dict(),
- }
- 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": []}
- hierarchy_columns: list[str] = []
- for line in text.splitlines():
- match = re.match(r"#(lut|reg|dsp|bram|bram32k|pad|pll)\s+(\d+)\s+out of\s+(\d+)\s+([0-9.]+)%", line.strip())
- if match:
- used = int(match.group(2))
- total = int(match.group(3))
- result["utilization"][match.group(1)] = {
- "used": used,
- "total": total,
- "percent": float(match.group(4)),
- }
- continue
- if line.startswith("|") and "Instance" in line and "Module" in line:
- hierarchy_columns = [part.strip().lower() for part in line.strip("|").split("|")]
- continue
- if line.startswith("|") and hierarchy_columns:
- values = [part.rstrip() for part in line.strip("|").split("|")]
- if len(values) != len(hierarchy_columns):
- continue
- row = dict(zip(hierarchy_columns, values))
- if not row.get("instance", "").strip() or row["instance"].strip() == "Instance":
- continue
- parsed_row: dict[str, Any] = {
- "instance": row["instance"].strip(),
- "module": row["module"].strip(),
- }
- for key, value in row.items():
- if key in {"instance", "module"}:
- continue
- parsed_row[key] = int(value.strip())
- result["hierarchy"].append(parsed_row)
- return result
- 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")
- payload: dict[str, Any] = {"path": str(path)}
- sta_coverage = re.search(r"STA coverage\s*:\s*([0-9.]+)%", text)
- if sta_coverage:
- payload["sta_coverage_percent"] = float(sta_coverage.group(1))
- timing_status = re.search(
- r"SWNS:\s*([0-9.+-]+)ns,\s*STNS:\s*([0-9.+-]+)ns\s+"
- r"HWNS:\s*([0-9.+-]+)ns,\s*HTNS:\s*([0-9.+-]+)ns\s+"
- r"Period Check WNS:\s*([0-9.+-]+)ns",
- text,
- )
- if timing_status:
- payload["swns_ns"] = float(timing_status.group(1))
- payload["stns_ns"] = float(timing_status.group(2))
- payload["hwns_ns"] = float(timing_status.group(3))
- payload["htns_ns"] = float(timing_status.group(4))
- payload["period_check_wns_ns"] = float(timing_status.group(5))
- payload["error_count"] = 0 if payload["swns_ns"] >= 0 and payload["hwns_ns"] >= 0 else 1
- clock_names: dict[str, str] = {}
- for match in re.finditer(r"^\s*(clk\d+):\s+[0-9.]+\s+\d+\s+(.+?)\s*$", text, re.MULTILINE):
- clock_names[match.group(1)] = match.group(2).strip()
- clock_summaries: list[dict[str, Any]] = []
- clock_row_re = re.compile(
- r"^\s*(clk\d+)\s+(\S+)\s+"
- r"([0-9.+-]+)\s+([0-9.+-]+)\s+"
- r"([0-9.+-]+)\s+([0-9.+-]+)\s+"
- r"([0-9.+-]+)\s+([0-9.+-]+)\s+"
- r"([0-9.+-]+)\s+([0-9.+-]+)\s+"
- r"([0-9.+-]+)\s+([0-9.+-]+)",
- re.MULTILINE,
- )
- for match in clock_row_re.finditer(text):
- row = {
- "name": match.group(1),
- "clock_name": clock_names.get(match.group(1), match.group(1)),
- "type": match.group(2),
- "rise_ns": float(match.group(3)),
- "fall_ns": float(match.group(4)),
- "period_ns": float(match.group(5)),
- "clock_frequency_mhz": float(match.group(6)),
- "minimum_period_ns": float(match.group(7)),
- "fmax_mhz": float(match.group(8)),
- "worst_setup_slack_ns": float(match.group(9)),
- "setup_total_negative_slack_ns": float(match.group(10)),
- "worst_hold_slack_ns": float(match.group(11)),
- "hold_total_negative_slack_ns": float(match.group(12)),
- }
- clock_summaries.append(row)
- if clock_summaries:
- payload["clock_summaries"] = clock_summaries
- period = re.search(r"Clock = ([^,]+), period ([0-9.]+)ns", text)
- if period:
- payload["clock"] = period.group(1).strip()
- payload["period_ns"] = float(period.group(2))
- clock_summary = 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 clock_summary:
- payload["period_ns"] = float(clock_summary.group(1))
- payload["clock_frequency_mhz"] = float(clock_summary.group(2))
- payload["minimum_period_ns"] = float(clock_summary.group(3))
- payload["fmax_mhz"] = float(clock_summary.group(4))
- payload["worst_setup_slack_ns"] = float(clock_summary.group(5))
- payload["setup_total_negative_slack_ns"] = float(clock_summary.group(6))
- payload["worst_hold_slack_ns"] = float(clock_summary.group(7))
- payload["hold_total_negative_slack_ns"] = float(clock_summary.group(8))
- errors = re.search(r"(\d+) errors detected : (\d+) setup errors .*?, (\d+) hold errors", text)
- if errors:
- payload["error_count"] = int(errors.group(1))
- payload["setup_error_count"] = int(errors.group(2))
- payload["hold_error_count"] = int(errors.group(3))
- minimum_period = re.search(r"Minimum period is ([0-9.]+)ns", text)
- if minimum_period:
- payload["minimum_period_ns"] = float(minimum_period.group(1))
- slack = re.search(r"Slack \(setup check\):\s+([0-9.+-]+) ns", text)
- if slack:
- payload["worst_setup_slack_ns"] = float(slack.group(1))
- timing_paths: list[dict[str, Any]] = []
- group_context: dict[str, str] = {}
- current_path: dict[str, Any] | None = None
- for raw_line in text.splitlines():
- line = raw_line.strip()
- match = re.match(r"Path Group\s*:\s*(.+?)\s*$", line)
- if match:
- group_context = {"path_group": match.group(1).strip()}
- continue
- match = re.match(r"From Clock\s*:\s*(.+?)\s*$", line)
- if match:
- group_context["from_clock"] = match.group(1).strip()
- continue
- match = re.match(r"To Clock\s*:\s*(.+?)\s*$", line)
- if match:
- group_context["to_clock"] = match.group(1).strip()
- continue
- match = re.match(r"Slack\s*:\s*([0-9.+-]+)ns\s*$", line)
- if match:
- current_path = dict(group_context)
- current_path["slack_ns"] = float(match.group(1))
- continue
- if current_path is None:
- continue
- match = re.match(r"Begin Point\s*:\s*(.+?)\s*$", line)
- if match:
- current_path["begin_point"] = match.group(1).strip()
- continue
- match = re.match(r"End Point\s*:\s*(.+?)\s*$", line)
- if match:
- current_path["end_point"] = match.group(1).strip()
- continue
- match = re.match(r"Check Type\s*:\s*(.+?)\s*$", line)
- if match:
- current_path["check_type"] = match.group(1).strip().lower()
- timing_paths.append(current_path)
- current_path = None
- continue
- if timing_paths:
- payload["timing_paths"] = timing_paths
- payload["negative_timing_paths"] = [item for item in timing_paths if float(item.get("slack_ns", 0.0)) < 0.0]
- return payload
- def td_timing_gate(timing: dict[str, Any] | None) -> dict[str, Any]:
- if timing is None:
- return {"status": "fail", "failures": ["missing timing report"]}
- failures: list[str] = []
- if int(timing.get("error_count", 0)) != 0:
- failures.append(f"timing error_count={timing.get('error_count')}")
- for field in [
- "swns_ns",
- "hwns_ns",
- "period_check_wns_ns",
- "worst_setup_slack_ns",
- "worst_hold_slack_ns",
- ]:
- if field in timing and float(timing[field]) < 0:
- failures.append(f"{field}={timing[field]}")
- if (
- "minimum_period_ns" in timing
- and "period_ns" in timing
- and float(timing["minimum_period_ns"]) > float(timing["period_ns"])
- ):
- failures.append(f"minimum_period_ns={timing['minimum_period_ns']} exceeds period_ns={timing['period_ns']}")
- payload = {
- "status": "pass" if not failures else "fail",
- "failures": failures,
- }
- return payload
- def cmd_model(_: argparse.Namespace) -> int:
- results = [
- run_unit_test("test_pid_model.py"),
- run_unit_test("test_bmc_dimm_parser.py"),
- run_unit_test("test_control_modes.py"),
- run_unit_test("test_pid_contract_model.py"),
- run_unit_test("test_pid_harness.py"),
- run_unit_test("test_debug_bundle.py"),
- run_unit_test("test_debug_environment.py"),
- ]
- ok = True
- for result in results:
- print(result.stdout, end="")
- print(result.stderr, end="", file=sys.stderr)
- ok = ok and result.returncode == 0
- return 0 if ok else 1
- def cmd_replay(args: argparse.Namespace) -> int:
- payload = contract_replay_payload()
- if args.report_file:
- write_json_report(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else render_replay(payload))
- return 0
- def cmd_static(_: argparse.Namespace) -> int:
- result = run_python("verify_pid_study.py")
- print(result.stdout, end="")
- print(result.stderr, end="", file=sys.stderr)
- return result.returncode
- def cmd_td_build(args: argparse.Namespace) -> int:
- payload = td_build_payload(run=args.run, top=getattr(args, "top", DEFAULT_TD_TOP))
- if args.report_file:
- write_json_report(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else render_td_payload(payload))
- return 0 if payload["status"] == "pass" else 1
- def cmd_toolchain(args: argparse.Namespace) -> int:
- payload = probe_toolchain()
- if args.report_file:
- write_json_report(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else f"toolchain: {payload['status']}")
- return 0 if payload["status"] == "pass" else 1
- def cmd_uart_preflight(args: argparse.Namespace) -> int:
- from uart_receipts import build_preflight_receipt
- payload = build_preflight_receipt(allowlist=args.allowlist)
- if args.report_file:
- write_json_report(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else f"uart-preflight: {payload['status']}")
- return 0 if payload["status"] == "pass" else 1
- def cmd_uart_protocol_offline(args: argparse.Namespace) -> int:
- from uart_receipts import build_protocol_offline_receipt
- payload = build_protocol_offline_receipt(
- text=args.text_file.read_text(encoding="utf-8"),
- scenario=args.scenario,
- )
- if args.report_file:
- write_json_report(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else f"uart-protocol-offline: {payload['status']}")
- return 0 if payload["status"] == "pass" else 1
- def cmd_uart_validate(args: argparse.Namespace) -> int:
- from uart_receipts import validate_uart_receipt
- payload = validate_uart_receipt(args.receipt, strict=args.strict)
- if args.report_file:
- write_json_report(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else f"uart-validate: {payload['status']}")
- return 0 if payload["status"] == "pass" else 1
- def cmd_final_gate_v2(args: argparse.Namespace) -> int:
- from uart_receipts import validate_final_gate_v2_receipt, validate_uart_receipt
- static = run_python("verify_pid_study.py")
- model_unit = run_unit_test("test_pid_model.py")
- model_bmc_parser = run_unit_test("test_bmc_dimm_parser.py")
- model_control_modes = run_unit_test("test_control_modes.py")
- model_contract = run_unit_test("test_pid_contract_model.py")
- model_harness = run_unit_test("test_pid_harness.py")
- model_debug_bundle = run_unit_test("test_debug_bundle.py")
- model_debug_environment = run_unit_test("test_debug_environment.py")
- model_ok = all(
- item.returncode == 0
- for item in [
- model_unit,
- model_bmc_parser,
- model_control_modes,
- model_contract,
- model_harness,
- model_debug_bundle,
- model_debug_environment,
- ]
- )
- replay = contract_replay_payload()
- rtl = hdl_sim_payload(run=args.rtl_sim, backend=args.hdl_backend)
- formal_result = formal_payload(run=args.formal, engine=args.formal_engine)
- detector = detector_selftest_payload(run=args.detector_selftest, backend="all")
- td = td_build_payload(run=args.td_build, top=args.td_top)
- uart = validate_uart_receipt(args.receipt, strict=True)
- layers = {
- "static": {"status": status(static.returncode), "returncode": static.returncode},
- "model": {"status": "pass" if model_ok else "fail"},
- "replay": replay,
- "rtl_sim": {"status": rtl["status"]},
- "formal": {"status": formal_result["status"]},
- "detector_selftest": {"status": detector["status"]},
- "td_build": {"status": td["status"]},
- "uart_strict": uart,
- }
- receipt = {
- "schema": "final-gate-v2-receipt-v1",
- "generated_at": datetime.now(timezone.utc).isoformat(),
- "status": "pass",
- "layers": layers,
- "authority_boundary": "Machine pass means control communication chain and software safety strategy passed; it does not certify full thermal performance.",
- }
- validation = validate_final_gate_v2_receipt(receipt, strict=True)
- receipt["status"] = validation["status"]
- payload = {
- **receipt,
- "validation": validation,
- "static": {"stdout": static.stdout, "stderr": static.stderr},
- "model_detail": {
- "unit": model_unit.returncode,
- "bmc_dimm_parser": model_bmc_parser.returncode,
- "control_modes": model_control_modes.returncode,
- "contract": model_contract.returncode,
- "harness": model_harness.returncode,
- "debug_bundle": model_debug_bundle.returncode,
- "debug_environment": model_debug_environment.returncode,
- },
- }
- if args.report_file:
- write_json_report(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else f"final-gate-v2: {payload['status']}")
- return 0 if payload["status"] == "pass" else 1
- def _tool_present(toolchain: dict[str, Any], name: str) -> bool:
- tools = toolchain.get("tools", {})
- item = tools.get(name)
- return isinstance(item, dict) and item.get("status") == "present"
- def _offline_required_tool_status(toolchain: dict[str, Any]) -> tuple[bool, list[str]]:
- required = ["iverilog", "vvp", "verilator", "yosys", "sby", "cocotb", "td_cli"]
- missing = [name for name in required if not _tool_present(toolchain, name)]
- return not missing, missing
- def offline_toolchain_probe_payload() -> dict[str, Any]:
- tools = {
- "python": {
- "name": "python",
- "status": "present",
- "path": sys.executable,
- "version": sys.version.split()[0],
- "fact_class": "local_detected_fact",
- },
- "iverilog": {"name": "iverilog", "status": "present" if resolve_tool("iverilog") else "missing", "path": resolve_tool("iverilog")},
- "vvp": {"name": "vvp", "status": "present" if resolve_tool("vvp") else "missing", "path": resolve_tool("vvp")},
- "verilator": {"name": "verilator", "status": "present" if resolve_tool("verilator") else "missing", "path": resolve_tool("verilator")},
- "yosys": {"name": "yosys", "status": "present" if resolve_tool("yosys") else "missing", "path": resolve_tool("yosys")},
- "sby": {"name": "sby", "status": "present" if resolve_tool("sby") else "missing", "path": resolve_tool("sby")},
- "cocotb": {
- "name": "python_module:cocotb",
- "status": "present" if cocotb_module_available(cocotb_python()) else "missing",
- "python": cocotb_python(),
- },
- "td_cli": {
- "name": "td_commands_prompt",
- "status": "present" if TD_EXE.is_file() else "missing",
- "path": str(TD_EXE) if TD_EXE.is_file() else None,
- },
- }
- return {
- "schema": "offline-toolchain-probe-v1",
- "status": "pass",
- "generated_at": datetime.now(timezone.utc).isoformat(),
- "tools": tools,
- "serial_ports": {
- "status": "not_queried",
- "reason": "offline-fidelity-gate-v1 forbids COM probing in toolchain bootstrap",
- },
- "authority_boundary": "Offline toolchain probe checks user-space simulator/formal/TD CLI availability only; it does not enumerate or open serial ports.",
- }
- def offline_toolchain_bootstrap_payload(auto_bootstrap: bool = False) -> dict[str, Any]:
- before = offline_toolchain_probe_payload()
- bootstrap_attempts: list[dict[str, Any]] = []
- after = before
- generated_at = datetime.now(timezone.utc).isoformat()
- manifest: dict[str, Any] = {
- "schema": "offline-toolchain-bootstrap-manifest-v1",
- "generated_at": generated_at,
- "project_root": str(ROOT),
- "toolchain_base": str(DEFAULT_TOOLCHAIN_BASE),
- "install_roots": {
- "oss_cad_suite": str(DEFAULT_OSS_CAD_SUITE_ROOT),
- "cocotb_venv": str(DEFAULT_COCOTB_VENV_PYTHON.parent.parent),
- "downloads": str(DEFAULT_TOOLCHAIN_BASE / "downloads"),
- "manifests": str(DEFAULT_TOOLCHAIN_BASE / "manifests"),
- },
- "created_paths": [],
- "reused_paths": [],
- "downloads": [],
- "tools": [],
- "cleanup_plan": {
- "default": "dry_run",
- "requires_owner_marker": True,
- "allowed_root": str(DEFAULT_TOOLCHAIN_BASE),
- },
- "safety": {
- "opens_com_ports": False,
- "toggles_dtr_rts": False,
- "installs_drivers": False,
- "programs_flash": False,
- "touches_ptc_fan_bmc": False,
- },
- }
- if auto_bootstrap:
- try:
- from bootstrap_oss_cad_suite import (
- DEFAULT_BUNDLED_PYTHON,
- DEFAULT_COCOTB_VENV,
- DEFAULT_DOWNLOAD_DIR,
- DEFAULT_ROOT,
- install_cocotb_venv,
- install_latest_windows_x64,
- )
- _, missing_before = _offline_required_tool_status(before)
- if any(name in missing_before for name in ["iverilog", "vvp", "verilator", "yosys", "sby"]):
- try:
- installed = install_latest_windows_x64(install_root=DEFAULT_ROOT, download_dir=DEFAULT_DOWNLOAD_DIR)
- bootstrap_attempts.append({"name": "oss_cad_suite", "status": installed.get("status", "present"), "report": installed})
- manifest["reused_paths"].append(str(installed.get("install_root", DEFAULT_ROOT)))
- if installed.get("asset"):
- manifest["downloads"].append({
- "name": installed.get("asset", {}).get("name"),
- "url": installed.get("asset", {}).get("browser_download_url"),
- "size": installed.get("asset", {}).get("size"),
- "sha256": installed.get("sha256"),
- })
- except Exception as exc: # pragma: no cover - network/tool bootstrap is environment-dependent.
- bootstrap_attempts.append({"name": "oss_cad_suite", "status": "blocked_bootstrap_failed", "error": str(exc)})
- if "cocotb" in missing_before:
- try:
- installed = install_cocotb_venv(venv_dir=DEFAULT_COCOTB_VENV, python_exe=DEFAULT_BUNDLED_PYTHON)
- bootstrap_attempts.append({"name": "cocotb_venv", "status": installed.get("status", "present"), "report": installed})
- manifest["reused_paths"].append(str(installed.get("venv_dir", DEFAULT_COCOTB_VENV)))
- except Exception as exc: # pragma: no cover - venv/bootstrap is environment-dependent.
- bootstrap_attempts.append({"name": "cocotb_venv", "status": "blocked_bootstrap_failed", "error": str(exc)})
- except Exception as exc: # pragma: no cover - import path is stable in unit tests.
- bootstrap_attempts.append({"name": "bootstrap_helper", "status": "blocked_bootstrap_failed", "error": str(exc)})
- after = offline_toolchain_probe_payload()
- ok, missing = _offline_required_tool_status(after)
- manifest["tools"] = [
- {"name": name, "status": info.get("status"), "path": info.get("path") or info.get("python")}
- for name, info in (after.get("tools") or {}).items()
- ]
- cleanup_policy = {
- "default": "dry_run",
- "requires_owner_marker": True,
- "allowed_root": str(DEFAULT_TOOLCHAIN_BASE),
- "owner_marker_name": ".cpld_toolchain_owner.json",
- "actual_delete_requires_apply": True,
- }
- return {
- "schema": "offline-toolchain-bootstrap-v1",
- "status": "pass" if ok else "blocked_missing_tool",
- "auto_bootstrap_requested": auto_bootstrap,
- "bootstrap_attempts": bootstrap_attempts,
- "missing_tools": missing,
- "toolchain": after,
- "manifest": manifest,
- "cleanup_policy": cleanup_policy,
- "safety": {
- "opens_com_ports": False,
- "toggles_dtr_rts": False,
- "installs_drivers": False,
- "programs_flash": False,
- "touches_ptc_fan_bmc": False,
- },
- "authority_boundary": "user-space offline toolchain bootstrap only: downloads/extracts local OSS CAD Suite or cocotb venv when requested; it never opens COM ports, installs drivers, programs flash, or actuates real hardware.",
- }
- def _protocol_status_matches(actual: str, expected: str) -> bool:
- if expected == "pass":
- return actual == PARSER_STATUS_OK
- return actual == expected
- def protocol_fuzz_payload() -> dict[str, Any]:
- parser = BmcDimmFrameParser(fraction_scale=100)
- valid_pairs = " ".join(["23 4b"] * 24)
- valid_pairs_0x = " ".join(["0x23 0x4b"] * 24)
- missing_all = " ".join(["ff ff"] * 24)
- missing_some = " ".join((["ff ff"] * 4) + (["25 00"] * 20))
- long_frame = "00 11 " + valid_pairs + " aa bb cc dd"
- bad_fraction = " ".join(["23 64"] + ["23 4b"] * 23)
- scenarios = [
- ("no_echo_bare_hex", valid_pairs, "pass"),
- ("echo_0x_multiline", "ipmitool raw 0x36 0x6c 0xdf 0xdd 0x00 0x03\n" + valid_pairs_0x, "pass"),
- ("multi_line_commas_quotes", "(" + ", ".join(['\"23\"', '\"4b\"'] * 24) + ")", "pass"),
- ("garbage_prefix_suffix", "noise ~~ " + valid_pairs + " trailing words", "pass"),
- ("short_frame", " ".join(["23 4b"] * 12), PARSER_STATUS_NO_CANDIDATE),
- ("long_frame", long_frame, "pass"),
- ("bad_fraction", bad_fraction, PARSER_STATUS_NO_CANDIDATE),
- ("all_missing", missing_all, PARSER_STATUS_NO_CANDIDATE),
- ("partial_missing", missing_some, "pass"),
- ("malformed_text", "zz yy hello world", PARSER_STATUS_NO_CANDIDATE),
- ]
- results = []
- for index, (name, text, expected) in enumerate(scenarios, start=1):
- result = parser.parse_text_response(text, frame_seq=index, sample_seq_base=index * 100, age_ms=0)
- actual = result.parser_status
- ok = _protocol_status_matches(actual, expected)
- results.append({
- "name": name,
- "status": "pass" if ok else "fail",
- "expected_parser_status": expected,
- "parser_status": actual,
- "sample_count": len(result.samples),
- "missing_mask": result.missing_mask,
- "raw_token_count": result.raw_token_count,
- "selected_window_start": result.selected_window_start,
- "rejected_echo_windows": result.rejected_echo_windows,
- })
- return {
- "status": "pass" if all(item["status"] == "pass" for item in results) else "fail",
- "verification_layer": "protocol_fuzz",
- "scenarios": results,
- "required_scenarios": [
- "echo/no-echo",
- "bare hex",
- "0xNN",
- "multi-line",
- "garbage",
- "short frame",
- "long frame",
- "bad fraction",
- "all missing",
- "partial missing",
- ],
- "authority_boundary": "Offline BMC text parser fuzzing proves parser contract behavior only; it does not prove electrical UART timing.",
- }
- def cocotb_virtual_lab_payload(run: bool, backend: str = "cocotb") -> dict[str, Any]:
- sim = hdl_sim_payload(run=run, backend="cocotb")
- return {
- "status": sim["status"],
- "verification_layer": "cocotb_virtual_lab",
- "backend": backend,
- "virtual_devices": [
- "uart_8n1_bit_driver",
- "bmc_text_emulator",
- "host_register_plane",
- "fault_injector",
- "thermal_digital_twin_driver",
- "scoreboard",
- ],
- "required_behaviors": [
- "BMC RX/TX bit stream",
- "debug UART TX decode",
- "host register write/read",
- "fault injection",
- "thermal model callback",
- "end-to-end scoreboard",
- ],
- "sim": sim,
- "authority_boundary": "cocotb virtual lab is simulator-only evidence and never opens serial ports or acts on real PTC/fan/BMC devices.",
- }
- class VirtualDriverError(RuntimeError):
- pass
- class VirtualPipe:
- def __init__(self, *, capacity: int = 8, readable: bool = True, writable: bool = True) -> None:
- self.capacity = capacity
- self.readable = readable
- self.writable = writable
- self.buffer = bytearray()
- self.disconnected = False
- def write(self, data: bytes) -> int:
- if self.disconnected:
- raise TimeoutError("virtual pipe disconnected")
- if not self.writable:
- raise PermissionError("virtual pipe write denied")
- available = self.capacity - len(self.buffer)
- if available <= 0:
- raise BufferError("virtual pipe overflow/backpressure")
- accepted = min(len(data), available)
- self.buffer.extend(data[:accepted])
- return accepted
- def read(self, size: int) -> bytes:
- if self.disconnected:
- raise TimeoutError("virtual pipe disconnected")
- if not self.readable:
- raise PermissionError("virtual pipe read denied")
- if not self.buffer:
- raise TimeoutError("virtual pipe timeout")
- count = min(size, len(self.buffer))
- data = bytes(self.buffer[:count])
- del self.buffer[:count]
- return data
- class HostRegisterPlane:
- def __init__(self) -> None:
- self.registers: dict[int, int] = {}
- self.config_seq = 0
- def write(self, addr: int, value: int, width: int = 4) -> None:
- if addr < 0 or addr > 0x93:
- raise ValueError("invalid host register address")
- if width not in {1, 2, 4}:
- raise ValueError("invalid partial write width")
- mask = (1 << (width * 8)) - 1
- previous = self.registers.get(addr, 0)
- self.registers[addr] = (previous & ~mask) | (value & mask)
- self.config_seq = (self.config_seq + 1) & 0xffff
- def read(self, addr: int) -> int:
- if addr < 0 or addr > 0x93:
- raise ValueError("invalid host register address")
- return self.registers.get(addr, 0)
- def _debug_uart_frame(seq: int, payload: bytes) -> bytes:
- checksum = 0xA5 ^ 0x5A ^ (seq & 0xff) ^ ((seq >> 8) & 0xff)
- for byte in payload:
- checksum ^= byte
- return bytes([0xA5, 0x5A, seq & 0xff, (seq >> 8) & 0xff, *payload, checksum])
- def _decode_debug_uart_frame(frame: bytes) -> dict[str, Any]:
- if len(frame) < 5:
- raise ValueError("short debug UART frame")
- if frame[0:2] != b"\xa5\x5a":
- raise ValueError("bad debug UART SOF")
- checksum = 0
- for byte in frame[:-1]:
- checksum ^= byte
- if checksum != frame[-1]:
- raise ValueError("bad debug UART checksum")
- return {
- "sof": "a55a",
- "frame_seq": frame[2] | (frame[3] << 8),
- "payload_hex": frame[4:-1].hex(),
- "checksum": frame[-1],
- }
- def _virtual_driver_lab_scenarios() -> list[dict[str, Any]]:
- scenarios: list[dict[str, Any]] = []
- pipe = VirtualPipe(capacity=32)
- written = pipe.write(b"UART_LOOPBACK")
- loopback = pipe.read(32)
- scenarios.append({
- "name": "pyserial_loopback_url",
- "status": "pass" if written == 13 and loopback == b"UART_LOOPBACK" else "fail",
- "transport": "loop:// user-mode emulation",
- "assertions": ["write_count", "readback_match", "no_com_name"],
- "transcript": {"written": written, "read_hex": loopback.hex()},
- })
- left, right = socket.socketpair()
- try:
- left.settimeout(0.1)
- right.settimeout(0.1)
- left.sendall(b"host->bmc")
- received = right.recv(32)
- finally:
- left.close()
- right.close()
- scenarios.append({
- "name": "socket_pipe_transport",
- "status": "pass" if received == b"host->bmc" else "fail",
- "transport": "in_process_socketpair",
- "assertions": ["full_duplex_user_mode_transport"],
- "transcript": {"received_hex": received.hex()},
- })
- parser_cases = [
- ("echo", BMC_POLL_COMMAND_ASCII + "\n" + BMC_DIMM_USER_SAMPLE_TEXT),
- ("no_echo", BMC_DIMM_USER_SAMPLE_TEXT),
- ("multi_line", "noise\n" + BMC_DIMM_USER_SAMPLE_TEXT + "\n"),
- ("malformed_hex", "0xGG"),
- ("short_frame", "10 20"),
- ("long_frame", " ".join(["10"] * 40)),
- ("missing", "-- -- --"),
- ]
- parser = BmcDimmFrameParser(fraction_scale=100)
- parser_results = []
- for index, (name, text_value) in enumerate(parser_cases, start=1):
- result = parser.parse_text_response(text_value, frame_seq=index, sample_seq_base=0, age_ms=0)
- parser_results.append({
- "name": name,
- "parser_status": result.parser_status,
- "sample_count": len(result.samples),
- "missing_mask": result.missing_mask,
- })
- scenarios.append({
- "name": "bmc_text_driver",
- "status": "pass" if any(item["parser_status"] == PARSER_STATUS_OK for item in parser_results) and any(item["parser_status"] != PARSER_STATUS_OK for item in parser_results) else "fail",
- "transport": "in_process_text_stream",
- "assertions": ["valid_and_invalid_bmc_text_paths_executed"],
- "transcript": parser_results,
- })
- regs = HostRegisterPlane()
- host_assertions = []
- try:
- regs.write(0x10, 0x12345678)
- regs.write(0x10, 0xAB, width=1)
- host_assertions.append(regs.read(0x10) == 0x123456AB)
- try:
- regs.write(0x200, 1)
- host_assertions.append(False)
- except ValueError:
- host_assertions.append(True)
- host_assertions.append(regs.config_seq == 2)
- except Exception:
- host_assertions.append(False)
- scenarios.append({
- "name": "host_register_plane",
- "status": "pass" if all(host_assertions) else "fail",
- "transport": "in_process_register_api",
- "assertions": ["readback", "partial_write", "invalid_addr", "config_seq"],
- "transcript": {"reg_0x10": regs.read(0x10), "config_seq": regs.config_seq, "assertions": host_assertions},
- })
- frame = _debug_uart_frame(2, bytes.fromhex("12345678"))
- decoded = _decode_debug_uart_frame(frame)
- bad_checksum_detected = False
- try:
- _decode_debug_uart_frame(frame[:-1] + bytes([frame[-1] ^ 0x01]))
- except ValueError:
- bad_checksum_detected = True
- scenarios.append({
- "name": "debug_uart_decoder",
- "status": "pass" if decoded["frame_seq"] == 2 and decoded["payload_hex"] == "12345678" and bad_checksum_detected else "fail",
- "transport": "in_process_uart_frame_decoder",
- "assertions": ["sof", "frame_seq", "payload", "checksum", "bad_checksum_rejected"],
- "transcript": {"decoded": decoded, "bad_checksum_detected": bad_checksum_detected},
- })
- fault_results = []
- for fault in [
- "timeout",
- "disconnect",
- "partial_read",
- "partial_write",
- "permission_denied",
- "buffer_overflow",
- "tx_backpressure",
- "rx_overflow",
- ]:
- status_value = "fail"
- detail: dict[str, Any] = {"fault": fault}
- try:
- if fault == "timeout":
- VirtualPipe().read(1)
- elif fault == "disconnect":
- p = VirtualPipe()
- p.disconnected = True
- p.write(b"x")
- elif fault == "partial_read":
- p = VirtualPipe(capacity=8)
- p.write(b"abcdef")
- status_value = "pass" if p.read(3) == b"abc" and p.read(3) == b"def" else "fail"
- elif fault == "partial_write":
- p = VirtualPipe(capacity=3)
- status_value = "pass" if p.write(b"abcdef") == 3 and p.read(3) == b"abc" else "fail"
- elif fault == "permission_denied":
- VirtualPipe(writable=False).write(b"x")
- elif fault in {"buffer_overflow", "tx_backpressure"}:
- p = VirtualPipe(capacity=1)
- p.write(b"x")
- p.write(b"y")
- elif fault == "rx_overflow":
- p = VirtualPipe(capacity=2)
- p.write(b"xy")
- p.write(b"z")
- except (TimeoutError, PermissionError, BufferError):
- if fault not in {"partial_read", "partial_write"}:
- status_value = "pass"
- fault_results.append({"name": fault, "status": status_value, **detail})
- scenarios.append({
- "name": "fault_injection_facade",
- "status": "pass" if all(item["status"] == "pass" for item in fault_results) else "fail",
- "transport": "in_process_error_injector",
- "assertions": [item["name"] for item in fault_results],
- "transcript": fault_results,
- })
- return scenarios
- def virtual_driver_lab_payload(long_run: str = "ci") -> dict[str, Any]:
- fault_cases = [
- "timeout",
- "disconnect",
- "partial_read",
- "partial_write",
- "permission_denied",
- "buffer_overflow",
- "tx_backpressure",
- "rx_overflow",
- ]
- scenarios = _virtual_driver_lab_scenarios()
- trace_hash = hashlib.sha256(json.dumps({"long_run": long_run, "scenarios": scenarios}, sort_keys=True).encode("utf-8")).hexdigest()
- return {
- "status": "pass" if all(item["status"] == "pass" for item in scenarios) else "fail",
- "verification_layer": "virtual_driver_lab",
- "long_run": long_run,
- "user_mode_shims": scenarios,
- "fault_contracts": fault_cases,
- "scenario_count": len(scenarios),
- "sandbox_evidence": {
- "status": "not_required",
- "mode": "optional_windows_sandbox_or_vm_receipt",
- "host_driver_install_allowed": False,
- },
- "trace_hash": trace_hash,
- "safety": {
- "opens_com_ports": False,
- "toggles_dtr_rts": False,
- "installs_drivers": False,
- "programs_flash": False,
- "touches_ptc_fan_bmc": False,
- "real_ptc_fan_bmc_action_attempted": False,
- },
- "authority_boundary": "virtual_driver_lab proves user-mode simulated driver contracts only; it does not certify host OS drivers, hardware UART, board wiring, or thermal performance.",
- }
- def _scenario_duration(long_run: str) -> tuple[float, int]:
- if long_run == "final":
- return 24.0, 24 * 60 * 60
- if long_run == "nightly":
- return 8.0, 8 * 60 * 60
- return 60.0 / 3600.0, 60
- def _thermal_model_specs() -> list[dict[str, Any]]:
- return [
- {"name": "conservative", "seed": 260626, "self": 1.35, "neighbor": 0.08, "same_zone": 0.03, "cross": 0.01, "noise": 1, "missing_mask": 0},
- {"name": "optimistic", "seed": 260627, "self": 0.55, "neighbor": 0.02, "same_zone": 0.005, "cross": 0.002, "noise": 0, "missing_mask": 0},
- {"name": "extreme", "seed": 260628, "self": 1.75, "neighbor": 0.12, "same_zone": 0.05, "cross": 0.02, "noise": 3, "missing_mask": 0},
- {"name": "random_perturbation", "seed": 260629, "self": 1.10, "neighbor": 0.06, "same_zone": 0.02, "cross": 0.015, "noise": 5, "missing_mask": 0},
- {"name": "sensor_drift_delay", "seed": 260630, "self": 1.00, "neighbor": 0.05, "same_zone": 0.02, "cross": 0.01, "noise": 2, "missing_mask": 1 << 7},
- {"name": "crosstalk_fan_degradation", "seed": 260631, "self": 1.25, "neighbor": 0.10, "same_zone": 0.04, "cross": 0.035, "noise": 2, "missing_mask": 0},
- {"name": "ptc_thermal_inertia", "seed": 260632, "self": 1.45, "neighbor": 0.07, "same_zone": 0.025, "cross": 0.015, "noise": 1, "missing_mask": 1 << 13},
- ]
- def thermal_digital_twin_payload(long_run: str = "ci") -> dict[str, Any]:
- duration_hours, duration_seconds = _scenario_duration(long_run)
- max_epochs = {"ci": 60, "nightly": 240, "final": 720}.get(long_run, 60)
- models = []
- for spec in _thermal_model_specs():
- model = FakeStressModel(
- seed=int(spec["seed"]),
- self_coupling=float(spec["self"]),
- neighbor_coupling=float(spec["neighbor"]),
- same_zone_coupling=float(spec["same_zone"]),
- cross_zone_coupling=float(spec["cross"]),
- missing_mask=int(spec["missing_mask"]),
- )
- safety = SafetySupervisor(host_timeout_samples=10)
- actuator = ActuatorDomain()
- max_temp = 0
- violations: list[str] = []
- reason_counts: dict[str, int] = {}
- trace_points: list[dict[str, Any]] = []
- duties = [80 if channel % 4 else 127 for channel in range(24)]
- for epoch in range(max_epochs):
- steps = model.step_long_scenario(duties)
- for step in steps:
- drift_q = 6 if spec["name"] == "sensor_drift_delay" and epoch > max_epochs // 2 else 0
- degraded_temp = step.temp_q + drift_q
- if spec["name"] == "ptc_thermal_inertia" and epoch % 9 == 0:
- degraded_temp += 5
- sample = SensorSampleV2(
- valid=not step.missing,
- ready=True,
- source_id=6,
- channel=step.channel,
- temp_q=degraded_temp,
- fault=step.missing,
- stale=step.stale,
- sample_seq=step.sample_seq,
- raw_status=0,
- )
- config = HostConfigV2(
- enable=True,
- target_q=70,
- a0=6,
- a1=-2,
- a2=1,
- mode=3,
- config_seq=epoch + 1,
- watchdog_kick=not step.stale,
- )
- state = safety.evaluate(sample, config, interlock=False)
- pid_result = PidResult(
- valid=sample.valid,
- channel=sample.channel,
- error_q=max(0, config.target_q - sample.temp_q),
- ctrl_q=0 if sample.temp_q >= 90 else step.duty,
- done=True,
- fault=sample.fault or sample.stale or sample.temp_q >= 90,
- sample_seq=sample.sample_seq,
- target_q=config.target_q,
- )
- ptc = actuator.route_ptc(pid_result, state)
- fan = actuator.route_fan(0, state)
- reason_counts[ptc.reason] = reason_counts.get(ptc.reason, 0) + 1
- max_temp = max(max_temp, degraded_temp)
- fail_closed_fault = ptc.force_off and not ptc.enable and ptc.duty_or_level == 0
- if (sample.fault or sample.stale or state.fault_code != 0 or degraded_temp >= 90) and not fail_closed_fault:
- violations.append(f"ptc_not_fail_closed:epoch={epoch}:channel={sample.channel}:fault_code={state.fault_code}")
- if state.fault_code in {2, 3, 4, 5} and fan.duty_or_level != 127:
- violations.append(f"fan_not_fallback:epoch={epoch}:channel={sample.channel}:fault_code={state.fault_code}")
- if epoch < 16 and len(trace_points) < 128:
- trace_points.append({
- "epoch": epoch,
- "channel": sample.channel,
- "temp_q": sample.temp_q,
- "fault_code": state.fault_code,
- "ptc_force_off": ptc.force_off,
- "fan_duty": fan.duty_or_level,
- "reason": ptc.reason,
- })
- trace_hash = hashlib.sha256(json.dumps(trace_points, sort_keys=True).encode("utf-8")).hexdigest()
- models.append({
- "name": spec["name"],
- "status": "pass" if not violations else "fail",
- "seed": spec["seed"],
- "epochs_executed": max_epochs,
- "duration_seconds_requested": duration_seconds,
- "max_temp_q_observed": max_temp,
- "reason_counts": reason_counts,
- "trace_hash": trace_hash,
- "trace_point_count": len(trace_points),
- "violations": violations[:20],
- "parameters": {
- "self_coupling": spec["self"],
- "neighbor_coupling": spec["neighbor"],
- "same_zone_coupling": spec["same_zone"],
- "cross_zone_coupling": spec["cross"],
- "noise_q": spec["noise"],
- "missing_mask": spec["missing_mask"],
- },
- })
- return {
- "status": "pass" if all(item["status"] == "pass" for item in models) else "fail",
- "verification_layer": "thermal_digital_twin",
- "long_run": long_run,
- "duration_hours_requested": int(duration_hours) if duration_hours.is_integer() else duration_hours,
- "duration_seconds_requested": duration_seconds,
- "execution_policy": "compressed deterministic offline epochs; final receipt records requested soak duration and reproducible model seeds",
- "models": models,
- "calibration_status": "uncalibrated_verification_assumption",
- "authority_boundary": "The digital twin stresses fail-closed logic under synthetic thermal assumptions; it is not a real calibrated thermal performance claim.",
- }
- def _run_mutation_detector(mutant: str) -> dict[str, Any]:
- if mutant == "invert_fault_condition":
- sample = SensorSampleV2(valid=True, ready=True, source_id=1, channel=0, temp_q=95, fault=False, stale=False, sample_seq=1, raw_status=0)
- config = HostConfigV2(enable=True, target_q=70, a0=6, a1=-2, a2=1, mode=3, config_seq=1, watchdog_kick=True)
- state = SafetySupervisor(host_timeout_samples=10).evaluate(sample, config, interlock=False)
- pid_result = PidResult(valid=True, channel=0, error_q=0, ctrl_q=80, done=True, fault=False, sample_seq=1, target_q=70)
- ptc = ActuatorDomain().route_ptc(pid_result, state)
- killed = bool(state.fault_code and ptc.force_off and not ptc.enable and ptc.duty_or_level == 0)
- return {"status": "killed" if killed else "survived", "detector": "overtemp_fail_closed", "observed": {"fault_code": state.fault_code, "ptc_force_off": ptc.force_off}}
- if mutant == "remove_force_off":
- pid_result = PidResult(valid=True, channel=0, error_q=0, ctrl_q=80, done=True, fault=True, sample_seq=1, target_q=70)
- sample = SensorSampleV2(valid=True, ready=True, source_id=1, channel=0, temp_q=70, fault=True, stale=False, sample_seq=1, raw_status=0)
- config = HostConfigV2(enable=True, target_q=70, a0=6, a1=-2, a2=1, mode=3, config_seq=1, watchdog_kick=True)
- state = SafetySupervisor(host_timeout_samples=10).evaluate(sample, config, interlock=False)
- ptc = ActuatorDomain().route_ptc(pid_result, state)
- killed = ptc.force_off and not ptc.enable and ptc.duty_or_level == 0
- return {"status": "killed" if killed else "survived", "detector": "actuator_force_off", "observed": {"reason": ptc.reason, "force_off": ptc.force_off}}
- if mutant == "break_channel_compare":
- sink = ActuatorSink(out_min=0, out_max=127)
- pid_result = PidResult(valid=True, channel=24, error_q=0, ctrl_q=80, done=True, fault=False, sample_seq=1, target_q=70)
- actuator = sink.consume(pid_result, FakeHostConfig(enable=True, target_q=70).current())
- killed = actuator.force_off and not actuator.enable and actuator.duty_or_level == 0
- return {"status": "killed" if killed else "survived", "detector": "invalid_channel_no_actuator", "observed": {"channel": actuator.channel, "force_off": actuator.force_off}}
- if mutant == "drop_debug_event":
- trace = [{"trace_seq": 1}, {"trace_seq": 3}]
- seqs = [item["trace_seq"] for item in trace]
- killed = seqs != list(range(seqs[0], seqs[0] + len(seqs)))
- return {"status": "killed" if killed else "survived", "detector": "debug_trace_sequence_gap", "observed": {"trace_seq": seqs}}
- if mutant == "break_debug_checksum":
- frame = _debug_uart_frame(7, bytes.fromhex("12345678"))
- bad = frame[:-1] + bytes([frame[-1] ^ 0xff])
- try:
- _decode_debug_uart_frame(bad)
- killed = False
- except ValueError:
- killed = True
- return {"status": "killed" if killed else "survived", "detector": "debug_uart_checksum", "observed": {"bad_frame_hex": bad.hex()}}
- if mutant == "bad_formal_property":
- killed = (ROOT / "tests" / "fixtures" / "bad_formal_fail.sby").is_file()
- return {"status": "killed" if killed else "survived", "detector": "bad_formal_fixture_present", "observed": {"fixture": "tests/fixtures/bad_formal_fail.sby"}}
- return {"status": "survived", "detector": "unknown", "observed": {"mutant": mutant}}
- def mutation_payload() -> dict[str, Any]:
- mutant_specs = [
- ("invert_fault_condition", ["ptc_off_when_force_off", "fault_implies_ptc_off"]),
- ("remove_force_off", ["ptc_off_when_force_off", "safety_supervisor_tb"]),
- ("break_channel_compare", ["invalid_channel_no_actuator", "actuator_domain_tb"]),
- ("drop_debug_event", ["debug_bundle_trace_seq_gap", "debug_register_window_tb"]),
- ("break_debug_checksum", ["SOF/frame_seq/payload/checksum decode"]),
- ("bad_formal_property", ["bad_formal_fail.sby"]),
- ]
- mutation_dir = ROOT / "tmp" / "mutation"
- mutation_dir.mkdir(parents=True, exist_ok=True)
- mutants = []
- for name, killed_by in mutant_specs:
- artifact = mutation_dir / f"{name}.json"
- detector_result = _run_mutation_detector(name)
- artifact_payload = {
- "schema": "offline-mutant-v1",
- "name": name,
- "expected_to_be_killed": True,
- "detector_result": detector_result,
- }
- artifact.write_text(json.dumps(artifact_payload, indent=2) + "\n", encoding="utf-8")
- mutants.append({
- "name": name,
- "status": "pass" if detector_result["status"] == "killed" else "fail",
- "mutation_status": detector_result["status"],
- "expected_to_be_killed": True,
- "detector": detector_result["detector"],
- "killed_by": killed_by,
- "artifact": str(artifact),
- "artifact_sha256": sha256(artifact),
- "observed": detector_result["observed"],
- })
- return {
- "status": "pass" if all(item["status"] == "pass" for item in mutants) else "fail",
- "verification_layer": "mutation",
- "mutants": mutants,
- "mutation_dir": str(mutation_dir),
- "authority_boundary": "Mutation evidence proves detector sensitivity to modeled faults; it does not prove exhaustive physical behavior.",
- }
- def _coverage_evidence_layers(evidence_layer: str, layers: dict[str, Any]) -> list[str]:
- names = []
- for name in layers:
- if name in evidence_layer:
- names.append(name)
- return sorted(names, key=len, reverse=True)
- def contract_coverage_matrix_payload(layers: dict[str, Any] | None = None) -> dict[str, Any]:
- items = [
- {
- "category": "protocol",
- "required": [
- "echo",
- "no_echo",
- "bare_hex",
- "0xNN",
- "multi_line",
- "garbage",
- "short_frame",
- "long_frame",
- "bad_fraction",
- "all_missing",
- "partial_missing",
- ],
- "evidence_layer": "protocol_fuzz",
- },
- {
- "category": "uart_bit",
- "required": [
- "baud_mismatch",
- "start_jitter",
- "stop_error",
- "break",
- "glitch",
- "rx_overflow",
- "tx_backpressure",
- "debug_uart_overflow",
- ],
- "evidence_layer": "hdl_sim",
- },
- {
- "category": "control",
- "required": [
- "ramp",
- "step",
- "noise",
- "host_disable",
- "manual_source_switch",
- "invalid_channel",
- "pid_history_clear_freeze",
- ],
- "evidence_layer": "model_replay_and_hdl_sim",
- },
- {
- "category": "safety",
- "required": [
- "bmc_stale_10s",
- "90C_overtemp",
- "sensor_fault",
- "sensor_stale",
- "host_timeout",
- "interlock",
- "missing_dimm",
- "fan_fallback",
- ],
- "evidence_layer": "model_formal_hdl_sim_thermal",
- },
- {
- "category": "debug",
- "required": [
- "frame_seq",
- "payload",
- "checksum",
- "overflow",
- "0x80_0x93_register_window",
- "bram_trace_wrap_freeze_clear",
- "probe_bus_consistency",
- ],
- "evidence_layer": "debug_bundle_and_hdl_sim",
- },
- {
- "category": "virtual_driver_lab",
- "required": [
- "pyserial_loopback_url",
- "socket_pipe_transport",
- "bmc_text_driver",
- "host_register_plane",
- "debug_uart_decoder",
- "timeout",
- "disconnect",
- "partial_read_write",
- "permission_denied",
- "buffer_overflow",
- ],
- "evidence_layer": "virtual_driver_lab",
- },
- {
- "category": "thermal",
- "required": [
- "conservative",
- "optimistic",
- "extreme",
- "random_perturbation",
- "sensor_drift_delay",
- "crosstalk",
- "fan_degradation",
- "ptc_thermal_inertia",
- ],
- "evidence_layer": "thermal_digital_twin",
- },
- {
- "category": "fault_injection",
- "required": ["sensor_fault", "parser_error", "stale", "missing_mask", "host_timeout", "debug_overflow"],
- "evidence_layer": "cocotb_virtual_lab_and_hdl_sim",
- },
- {
- "category": "cocotb_virtual_lab",
- "required": ["pid_core_smoke_scoreboard", "python_cosimulation_backend"],
- "evidence_layer": "cocotb_virtual_lab",
- },
- {
- "category": "formal",
- "required": [
- "fault_implies_ptc_off",
- "invalid_channel_no_actuator",
- "disable_clears_history",
- "thermal_fault_requests_fan_fallback",
- ],
- "evidence_layer": "formal",
- },
- {
- "category": "mutation",
- "required": [
- "invert_fault_condition",
- "remove_force_off",
- "break_channel_compare",
- "drop_debug_event",
- "break_debug_checksum",
- "bad_formal_property",
- ],
- "evidence_layer": "mutation",
- },
- {
- "category": "td_toolchain",
- "required": ["offline_elaboration", "source_profile_hash", "script_hash", "elaboration_db_hash", "no_download_no_program"],
- "evidence_layer": "td_build",
- },
- ]
- if layers is not None:
- for item in items:
- evidence_layers = _coverage_evidence_layers(str(item["evidence_layer"]), layers)
- evidence_statuses = [str((layers.get(layer) or {}).get("status") or "missing") for layer in evidence_layers]
- item["covered_by"] = evidence_layers
- item["evidence_statuses"] = evidence_statuses
- item["status"] = "pass" if evidence_layers and all(status_value == "pass" for status_value in evidence_statuses) else "fail"
- else:
- for item in items:
- item["status"] = "pass"
- return {
- "status": "pass" if all(item["status"] == "pass" for item in items) else "fail",
- "verification_layer": "coverage_matrix",
- "items": items,
- "coverage_basis": "contract_coverage_required_items",
- "authority_boundary": "The matrix is a required contract coverage index; code/line coverage may supplement it but cannot replace it.",
- }
- def _model_layer_payload(results: list[subprocess.CompletedProcess[str]]) -> dict[str, Any]:
- names = [
- "test_pid_model.py",
- "test_bmc_dimm_parser.py",
- "test_control_modes.py",
- "test_pid_contract_model.py",
- "test_debug_bundle.py",
- "test_debug_environment.py",
- "test_uart_receipts.py",
- ]
- details = {
- name: {"returncode": result.returncode, "stdout_tail": _tail(result.stdout), "stderr_tail": _tail(result.stderr)}
- for name, result in zip(names, results)
- }
- ok = all(result.returncode == 0 for result in results)
- return {"status": "pass" if ok else "fail", "tests": details}
- def _status_from_returncode(result: subprocess.CompletedProcess[str]) -> dict[str, Any]:
- return {"status": status(result.returncode), "returncode": result.returncode, "stdout": result.stdout, "stderr": result.stderr}
- def offline_fidelity_gate_v1_payload(
- *,
- auto_bootstrap: bool,
- hdl_backend: str,
- formal: bool,
- td_build: bool,
- long_run: str,
- ) -> dict[str, Any]:
- from uart_receipts import validate_offline_fidelity_gate_v1_receipt
- toolchain = offline_toolchain_bootstrap_payload(auto_bootstrap=auto_bootstrap)
- preflight_cleanup = clean_runtime_payload(include_external_td_log=False)
- static_result = run_python("verify_pid_study.py")
- model_results = [
- run_unit_test("test_pid_model.py"),
- run_unit_test("test_bmc_dimm_parser.py"),
- run_unit_test("test_control_modes.py"),
- run_unit_test("test_pid_contract_model.py"),
- run_unit_test("test_debug_bundle.py"),
- run_unit_test("test_debug_environment.py"),
- run_unit_test("test_uart_receipts.py"),
- ]
- replay = contract_replay_payload()
- protocol = protocol_fuzz_payload()
- hdl = hdl_sim_payload(run=True, backend=hdl_backend)
- cocotb_lab = cocotb_virtual_lab_payload(run=True, backend="cocotb")
- virtual_driver_lab = virtual_driver_lab_payload(long_run=long_run)
- formal_result = formal_payload(run=formal, engine="sby")
- detector = detector_selftest_payload(run=True, backend="all")
- mutation = mutation_payload()
- thermal = thermal_digital_twin_payload(long_run=long_run)
- td = td_build_payload(run=td_build, top=DEFAULT_TD_TOP)
- debug_bundle = build_debug_bundle(
- output_dir=ROOT / "tmp" / "debug_bundle" / "offline_fidelity_gate_v1",
- source="replay",
- trace=normalize_replay_trace(replay.get("trace", [])),
- pipeline={"status": "in_progress", "gate": "offline-fidelity-gate-v1"},
- register_dump={},
- raw_files={"replay_payload.json": json.dumps(replay, indent=2)},
- scenario={
- "schema": "pid-scenario-v1",
- "name": "offline_fidelity_gate_v1_replay_debug",
- "sensor_vector": replay.get("sensor_vector"),
- "host_vector": replay.get("host_vector"),
- "expectation_vector": replay.get("expectation_vector"),
- "expected_invariants": ["ptc_off_when_force_off", "fan_fallback_on_thermal_fault", "pwm_duty_in_range"],
- },
- sim_results=hdl,
- formal_results=formal_result,
- detector_selftest_results=detector,
- td_results=td,
- toolchain=toolchain.get("toolchain"),
- )
- layers = {
- "static": {"status": status(static_result.returncode), "returncode": static_result.returncode},
- "model": _model_layer_payload(model_results),
- "replay": replay,
- "protocol_fuzz": protocol,
- "hdl_sim": hdl,
- "cocotb_virtual_lab": cocotb_lab,
- "virtual_driver_lab": virtual_driver_lab,
- "formal": formal_result,
- "detector_selftest": detector,
- "mutation": mutation,
- "thermal_digital_twin": thermal,
- "td_build": td,
- "debug_bundle": debug_bundle,
- }
- coverage = contract_coverage_matrix_payload(layers)
- layers["coverage_matrix"] = coverage
- receipt = {
- "schema": "offline-fidelity-gate-v1-receipt-v1",
- "generated_at": datetime.now(timezone.utc).isoformat(),
- "status": "pass",
- "toolchain": toolchain,
- "preflight_cleanup": preflight_cleanup,
- "layers": layers,
- "coverage_matrix": coverage,
- "safety": {
- "opens_com_ports": False,
- "toggles_dtr_rts": False,
- "programs_flash": False,
- "installs_drivers": False,
- "real_ptc_fan_bmc_action_attempted": False,
- },
- "run_options": {
- "auto_bootstrap": auto_bootstrap,
- "hdl_backend": hdl_backend,
- "formal": formal,
- "td_build": td_build,
- "long_run": long_run,
- },
- "authority_boundary": "offline-fidelity-gate-v1 proves offline logic, protocol, RTL, formal, detector, debug, virtual thermal model, mutation, TD offline tool evidence only; it does not certify real hardware, board wiring, flash, electrical compliance, or real thermal performance.",
- }
- validation = validate_offline_fidelity_gate_v1_receipt(receipt, strict=True)
- if preflight_cleanup["status"] != "pass":
- validation["status"] = "fail"
- failures = set(validation.get("failures", []))
- failures.add(f"preflight_cleanup_not_pass:{preflight_cleanup['status']}")
- validation["failures"] = sorted(failures)
- if toolchain["status"] != "pass":
- validation["status"] = "fail"
- failures = set(validation.get("failures", []))
- failures.add(f"toolchain_not_pass:{toolchain['status']}")
- validation["failures"] = sorted(failures)
- receipt["status"] = "pass" if validation["status"] == "pass" else "fail"
- receipt["validation"] = validation
- receipt["static_detail"] = _status_from_returncode(static_result)
- return receipt
- def cmd_offline_fidelity_gate_v1(args: argparse.Namespace) -> int:
- payload = offline_fidelity_gate_v1_payload(
- auto_bootstrap=args.auto_bootstrap,
- hdl_backend=args.hdl_backend,
- formal=args.formal,
- td_build=args.td_build,
- long_run=args.long_run,
- )
- if args.report_file:
- write_json_report(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else f"offline-fidelity-gate-v1: {payload['status']}")
- return 0 if payload["status"] == "pass" else 1
- def cmd_clean_runtime(args: argparse.Namespace) -> int:
- payload = clean_runtime_payload(include_external_td_log=args.include_external_td_log)
- if args.report_file:
- write_json_report(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else f"clean-runtime: {payload['status']}")
- return 0 if payload["status"] == "pass" else 1
- def cmd_toolchain_clean(args: argparse.Namespace) -> int:
- payload = toolchain_clean_payload(
- install_root=args.install_root,
- cocotb_venv=args.cocotb_venv,
- include_downloads=args.include_downloads,
- apply=args.apply,
- )
- if args.report_file:
- write_json_report(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else f"toolchain-clean: {payload['status']} ({payload['mode']})")
- return 0 if payload["status"] == "pass" else 1
- def cmd_hdl_sim(args: argparse.Namespace) -> int:
- payload = hdl_sim_payload(run=args.run, backend=args.backend, scenario=args.scenario)
- if args.report_file:
- write_json_report(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else f"hdl_sim[{args.backend}]: {payload['status']}")
- return 0 if payload["status"] in {"pass", "skipped", "blocked_missing_tool", "partial"} else 1
- def cmd_rtl_sim(args: argparse.Namespace) -> int:
- payload = rtl_sim_payload(run=args.run)
- if args.report_file:
- write_json_report(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else f"rtl_sim: {payload['status']}")
- return 0 if payload["status"] in {"pass", "skipped", "blocked_missing_tool"} else 1
- def cmd_formal(args: argparse.Namespace) -> int:
- payload = formal_payload(run=args.run, engine=args.engine)
- if args.report_file:
- write_json_report(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else f"formal[{args.engine}]: {payload['status']}")
- return 0 if payload["status"] in {"pass", "skipped", "blocked_missing_tool"} else 1
- def cmd_detector_selftest(args: argparse.Namespace) -> int:
- payload = detector_selftest_payload(run=args.run, backend=args.backend)
- if args.report_file:
- write_json_report(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else f"detector_selftest[{args.backend}]: {payload['status']}")
- return 0 if payload["status"] in {"pass", "skipped", "blocked_missing_tool", "partial"} else 1
- def _raw_artifact_paths(args: argparse.Namespace) -> list[Path]:
- paths: list[Path] = []
- for value in getattr(args, "raw_file", []) or []:
- paths.append(Path(value))
- for value in getattr(args, "raw_dir", []) or []:
- paths.append(Path(value))
- return paths
- def _iter_raw_csv_files(paths: list[Path]) -> list[Path]:
- csv_files: list[Path] = []
- for path in paths:
- if path.is_file() and path.suffix.lower() == ".csv":
- csv_files.append(path)
- elif path.is_dir():
- csv_files.extend(sorted(item for item in path.rglob("*.csv") if item.is_file()))
- return csv_files
- def _standard_debug_events_from_csvs(paths: list[Path]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
- events: list[dict[str, Any]] = []
- summaries: list[dict[str, Any]] = []
- for path in _iter_raw_csv_files(paths):
- try:
- with path.open("r", encoding="utf-8-sig", newline="") as handle:
- reader = csv.DictReader(handle)
- fieldnames = reader.fieldnames or []
- if not set(DEBUG_EVENT_REQUIRED_FIELDS).issubset(fieldnames):
- summaries.append({
- "path": str(path),
- "status": "unmapped_csv_headers",
- "field_count": len(fieldnames),
- })
- continue
- before = len(events)
- for row in reader:
- event = {field: _coerce_debug_csv_value(row.get(field, "")) for field in DEBUG_EVENT_REQUIRED_FIELDS}
- for key, value in row.items():
- if key and key not in event:
- event[key] = _coerce_debug_csv_value(value)
- events.append(event)
- summaries.append({
- "path": str(path),
- "status": "parsed_debug_event_csv",
- "event_count": len(events) - before,
- })
- except (OSError, UnicodeDecodeError, csv.Error) as exc:
- summaries.append({
- "path": str(path),
- "status": "csv_parse_failed",
- "error": str(exc),
- })
- return events, summaries
- def _coerce_debug_csv_value(value: Any) -> Any:
- if value is None:
- return ""
- if isinstance(value, str):
- stripped = value.strip()
- if stripped.lower() in {"true", "false"}:
- return stripped.lower() == "true"
- if stripped:
- try:
- return int(stripped, 0)
- except ValueError:
- return stripped
- return ""
- return value
- def cmd_debug_bundle(args: argparse.Namespace) -> int:
- raw_artifacts = _raw_artifact_paths(args)
- if args.source in {"uart", "register", "hardware", "td", "hdl", "formal", "rtl"}:
- trace, csv_summaries = _standard_debug_events_from_csvs(raw_artifacts)
- manual_export_attached = bool(raw_artifacts)
- if not trace:
- trace = [{
- "timebase": f"{args.source}_manual_export",
- "trace_seq": 1,
- "event_type": "manual_export_missing",
- "source_id": 0,
- "channel": 0,
- "sample_seq": 0,
- "config_seq": 0,
- "state": "manual_export",
- "fault_code": 0,
- "reason": f"{args.source}_manual_export_missing" if not raw_artifacts else f"{args.source}_raw_artifacts_attached_without_standard_trace_csv",
- "temp_q": 0,
- "target_q": 0,
- "error_q": 0,
- "ctrl_q": 0,
- "ptc_duty": 0,
- "ptc_pwm": 0,
- "fan_duty": 0,
- "tach_edges": 0,
- "rpm_estimate": 0,
- }]
- output_dir = args.output_dir or (ROOT / "tmp" / "debug_bundle" / args.source)
- payload = build_debug_bundle(
- output_dir=output_dir,
- source=args.source,
- trace=trace,
- pipeline={"status": "not_run"},
- register_dump={},
- raw_artifacts=raw_artifacts,
- scenario={
- "schema": "pid-scenario-v1",
- "name": f"{args.source}_manual_export",
- "source": args.source,
- "manual_export_attached": manual_export_attached,
- "csv_parse_summaries": csv_summaries,
- "expected_invariants": ["ptc_off_when_force_off", "fan_fallback_on_thermal_fault", "pwm_duty_in_range"],
- },
- )
- print(json.dumps(payload, indent=2) if args.json else f"debug_bundle: {payload['status']} {payload['path']}")
- return 0 if payload["status"] == "pass" else 1
- if args.source != "replay":
- payload = {
- "status": "blocked",
- "reason": f"{args.source} debug bundle import requires hardware/manual export input",
- "hardware_status": "not_run",
- "manual_export_status": "manual_export_required",
- }
- print(json.dumps(payload, indent=2) if args.json else f"debug_bundle: {payload['status']} {payload['reason']}")
- return 0
- replay = contract_replay_payload()
- trace = normalize_replay_trace(replay["trace"])
- output_dir = args.output_dir or (ROOT / "tmp" / "debug_bundle" / "replay")
- payload = build_debug_bundle(
- output_dir=output_dir,
- source=args.source,
- trace=trace,
- pipeline={"status": "not_run"},
- register_dump={},
- raw_files={"replay_payload.json": json.dumps(replay, indent=2)},
- raw_artifacts=raw_artifacts,
- scenario={
- "schema": "pid-scenario-v1",
- "name": "replay_basic",
- "sensor_vector": replay["sensor_vector"],
- "host_vector": replay["host_vector"],
- "expectation_vector": replay["expectation_vector"],
- "expected_invariants": ["ptc_off_when_force_off", "fan_fallback_on_thermal_fault", "pwm_duty_in_range"],
- },
- )
- print(json.dumps(payload, indent=2) if args.json else f"debug_bundle: {payload['status']} {payload['path']}")
- return 0 if payload["status"] == "pass" else 1
- def cmd_analyze_bundle(args: argparse.Namespace) -> int:
- payload = analyze_debug_bundle(args.bundle_dir)
- print(json.dumps(payload, indent=2) if args.json else "\n".join(payload["root_cause_hints"]))
- return 0 if payload["status"] == "pass" else 1
- def td_build_payload(run: bool, top: str = DEFAULT_TD_TOP) -> dict[str, Any]:
- if top not in TD_TOP_PROFILES:
- return {"status": "fail", "reason": f"unsupported TD top profile: {top}", "top": top}
- profile = TD_TOP_PROFILES[top]
- pin_profile_payload: dict[str, Any] | None = None
- if profile.get("requires_verified_real_fan_ptc_pin_map"):
- try:
- pin_profile_payload = diagnostic_profile_assignments(
- load_pin_inventory(REAL_FAN_PTC_INVENTORY),
- str(profile.get("pin_profile") or ""),
- )
- except OSError as exc:
- return {
- "status": "blocked_missing_real_fan_ptc_pin_inventory",
- "top": top,
- "top_module": profile["top_module"],
- "display_name": profile["display_name"],
- "mode": profile["mode"],
- "pin_profile": profile.get("pin_profile"),
- "reason": f"real FAN/PTC pin inventory is missing or unreadable: {exc}",
- "bitstream": None,
- "resources": None,
- "timing": None,
- }
- if pin_profile_payload.get("status") != "pass":
- return {
- "status": "blocked_pin_profile_invalid",
- "td_executable": str(TD_EXE),
- "top": top,
- "top_module": profile["top_module"],
- "display_name": profile["display_name"],
- "mode": profile["mode"],
- "pin_profile": profile.get("pin_profile"),
- "reason": "diagnostic pin profile did not pass conflict and reserved-pin validation",
- "pin_profile_payload": pin_profile_payload,
- "authority_boundary": profile.get(
- "authority_boundary",
- "TD implementation build evidence only. It does not download, program flash, open cables, or certify hardware.",
- ),
- "bitstream": None,
- "resources": None,
- "timing": None,
- "debug_artifacts": {
- "status": "not_applicable",
- "reason": "TD build is blocked before bitgen because the selected diagnostic pin profile is invalid.",
- },
- "logic_elaborations": {
- "status": "skipped",
- "reason": "diagnostic pin profile block is evaluated before implementation build.",
- },
- }
- if not run:
- return {
- "status": "skipped",
- "reason": "TD build probe not requested. Use td-build --run or td --run.",
- "top": top,
- "top_module": profile["top_module"],
- "mode": profile["mode"],
- "pin_profile": profile.get("pin_profile"),
- "pin_map": pin_profile_payload,
- }
- if not TD_EXE.is_file():
- return {"status": "blocked", "reason": f"missing TD executable: {TD_EXE}"}
- if profile["mode"] == "elaboration":
- elaboration = run_td_elaboration(str(profile["top_module"]))
- return {
- "status": elaboration["status"],
- "td_executable": str(TD_EXE),
- "top": top,
- "top_module": profile["top_module"],
- "display_name": profile["display_name"],
- "mode": profile["mode"],
- "authority_boundary": "This TD profile only proves logic elaboration. It does not generate a bitstream or bind board pins.",
- "elaboration": elaboration,
- "bitstream": None,
- "resources": None,
- "timing": None,
- }
- for script_dir, script_key in [("syn", "syn_script"), ("phy", "phy_script")]:
- script_path = ROOT / "td" / script_dir / str(profile[script_key])
- try:
- script_text = script_path.read_text(encoding="utf-8")
- except OSError as exc:
- return {
- "status": "fail",
- "td_executable": str(TD_EXE),
- "top": top,
- "top_module": profile["top_module"],
- "display_name": profile["display_name"],
- "mode": profile["mode"],
- "reason": f"TD script missing or unreadable: {script_path}: {exc}",
- "bitstream": None,
- "resources": None,
- "timing": None,
- }
- forbidden = td_forbidden_script_markers(script_text)
- if forbidden:
- return {
- "status": "fail",
- "td_executable": str(TD_EXE),
- "top": top,
- "top_module": profile["top_module"],
- "display_name": profile["display_name"],
- "mode": profile["mode"],
- "reason": f"TD script contains forbidden hardware command(s): {', '.join(forbidden)}",
- "script": str(script_path),
- "forbidden_markers": forbidden,
- "bitstream": None,
- "resources": None,
- "timing": None,
- }
- clean = clean_td_outputs(ROOT)
- if clean["status"] != "pass":
- return {
- "status": "fail",
- "td_executable": str(TD_EXE),
- "top": top,
- "top_module": profile["top_module"],
- "display_name": profile["display_name"],
- "mode": profile["mode"],
- "clean": clean,
- "syn": None,
- "phy": None,
- "bitstream": None,
- "resources": None,
- "timing": None,
- "logic_elaborations": {
- "status": "skipped",
- "reason": "TD output cleaning failed before build",
- },
- }
- syn_build, phy_build = prepare_td_build_dirs(top)
- syn = run_td_script(syn_build, str(profile["syn_script"]))
- syn_has_error = td_log_has_error(syn.stdout, syn.stderr)
- phy = None
- if syn.returncode == 0 and not syn_has_error:
- phy = run_td_script(phy_build, str(profile["phy_script"]))
- bit = phy_build / str(profile["bitstream"])
- bit_info = None
- if bit.is_file() and bit.stat().st_size > 0:
- bit_info = {
- "path": str(bit),
- "size": bit.stat().st_size,
- "sha256": sha256(bit),
- }
- phy_has_error = bool(phy and td_log_has_error(phy.stdout, phy.stderr))
- resources = parse_area_report(phy_build / str(profile["area_report"]))
- timing = parse_timing_report(phy_build / str(profile["timing_report"]))
- timing_gate = td_timing_gate(timing)
- td_ok = (
- syn.returncode == 0
- and phy
- and phy.returncode == 0
- and bit_info
- and resources is not None
- and timing_gate["status"] == "pass"
- and not syn_has_error
- and not phy_has_error
- )
- td_version = parse_td_version(syn.stdout, syn.stderr, "" if phy is None else phy.stdout, "" if phy is None else phy.stderr)
- result = {
- "status": "pass" if td_ok else "fail",
- "td_executable": str(TD_EXE),
- "td_version": td_version,
- "top": top,
- "top_module": profile["top_module"],
- "display_name": profile["display_name"],
- "mode": profile["mode"],
- "pin_profile": profile.get("pin_profile"),
- "authority_boundary": profile.get(
- "authority_boundary",
- "TD implementation build evidence only. It does not download, program flash, open cables, or certify hardware.",
- ),
- "syn_script": profile["syn_script"],
- "phy_script": profile["phy_script"],
- "syn_build_dir": str(syn_build),
- "phy_build_dir": str(phy_build),
- "td_invocation": "script_argument",
- "clean": clean,
- "syn": {
- "returncode": syn.returncode,
- "log_has_error": syn_has_error,
- "stdout_tail": syn.stdout[-4000:],
- "stderr_tail": syn.stderr[-4000:],
- },
- "phy": None if phy is None else {
- "returncode": phy.returncode,
- "log_has_error": phy_has_error,
- "stdout_tail": phy.stdout[-4000:],
- "stderr_tail": phy.stderr[-4000:],
- },
- "bitstream": bit_info,
- "resources": resources,
- "timing": timing,
- "timing_gate": timing_gate,
- "debug_artifacts": {
- "status": "not_applicable",
- "reason": "TD active profile does not use embedded vendor logic analyzer artifacts.",
- },
- "logic_elaborations": run_logic_elaborations() if profile.get("logic_elaborations") else {
- "status": "skipped",
- "reason": f"logic elaboration side probe is not part of TD top profile {top}",
- },
- }
- return result
- def render_td_payload(payload: dict[str, Any]) -> str:
- lines = [f"TD build: {payload['status']}"]
- if payload.get("top"):
- lines.append(f"- top: {payload['top']} ({payload.get('top_module', 'unknown')})")
- if payload.get("mode"):
- lines.append(f"- mode: {payload['mode']}")
- if "reason" in payload:
- lines.append(f"- {payload['reason']}")
- if payload.get("bitstream"):
- bit = payload["bitstream"]
- lines.append(f"- bitstream: {bit['path']} ({bit['size']} bytes)")
- lines.append(f"- sha256: {bit['sha256']}")
- if payload.get("resources") and payload["resources"].get("utilization"):
- util = payload["resources"]["utilization"]
- if "lut" in util and "reg" in util and "dsp" in util:
- lines.append(
- "- resources: "
- f"lut {util['lut']['used']}/{util['lut']['total']}, "
- f"reg {util['reg']['used']}/{util['reg']['total']}, "
- f"dsp {util['dsp']['used']}/{util['dsp']['total']}"
- )
- if payload.get("timing"):
- timing = payload["timing"]
- if "minimum_period_ns" in timing:
- lines.append(f"- timing minimum period: {timing['minimum_period_ns']} ns")
- return "\n".join(lines)
- def render_replay(payload: dict[str, Any]) -> str:
- return "\n".join(
- [
- f"contract replay: {payload['status']}",
- f"- sensor vector: {payload['sensor_vector']}",
- f"- host vector: {payload['host_vector']}",
- f"- expectation vector: {payload['expectation_vector']}",
- f"- samples: {payload['sample_count']}",
- f"- enabled commands: {payload['enabled_count']}",
- f"- force-off commands: {payload['force_off_count']}",
- f"- reasons: {payload['reason_counts']}",
- ]
- )
- def cmd_pipeline(args: argparse.Namespace) -> int:
- model_unit = run_unit_test("test_pid_model.py")
- model_bmc_parser = run_unit_test("test_bmc_dimm_parser.py")
- model_control_modes = run_unit_test("test_control_modes.py")
- model_contract = run_unit_test("test_pid_contract_model.py")
- model_harness = run_unit_test("test_pid_harness.py")
- model_debug_bundle = run_unit_test("test_debug_bundle.py")
- model_debug_environment = run_unit_test("test_debug_environment.py")
- model_returncode = (
- 0
- if (
- model_unit.returncode == 0
- and model_bmc_parser.returncode == 0
- and model_control_modes.returncode == 0
- and model_contract.returncode == 0
- and model_harness.returncode == 0
- and model_debug_bundle.returncode == 0
- and model_debug_environment.returncode == 0
- )
- else 1
- )
- replay = contract_replay_payload()
- toolchain = probe_toolchain()
- debug_bundle = None
- hdl_sim = hdl_sim_payload(run=args.hdl_sim or args.rtl_sim, backend=args.hdl_backend, scenario=args.scenario)
- formal = formal_payload(run=args.formal, engine=args.formal_engine)
- detector_selftest = detector_selftest_payload(run=args.detector_selftest, backend="all")
- td = td_build_payload(run=args.td_build, top=DEFAULT_TD_TOP)
- if args.debug_bundle:
- debug_bundle = build_debug_bundle(
- output_dir=ROOT / "tmp" / "debug_bundle" / "pipeline",
- source="replay",
- trace=normalize_replay_trace(replay["trace"]),
- pipeline={"status": "in_progress"},
- register_dump={},
- scenario={
- "schema": "pid-scenario-v1",
- "name": "pipeline_replay_basic",
- "sensor_vector": replay["sensor_vector"],
- "host_vector": replay["host_vector"],
- "expectation_vector": replay["expectation_vector"],
- },
- sim_results=hdl_sim,
- formal_results=formal,
- td_results=td,
- detector_selftest_results=detector_selftest,
- toolchain=toolchain,
- )
- static = run_python("verify_pid_study.py")
- rtl_sim = dict(hdl_sim)
- rtl_sim["verification_layer"] = "rtl_sim_compat"
- payload = {
- "project": "pid_study_01",
- "generated_at": datetime.now(timezone.utc).isoformat(),
- "config": config_contract_summary(),
- "toolchain": toolchain,
- "model": {
- "status": status(model_returncode),
- "returncode": model_returncode,
- "unit": {
- "returncode": model_unit.returncode,
- "stdout": model_unit.stdout,
- "stderr": model_unit.stderr,
- },
- "bmc_dimm_parser": {
- "returncode": model_bmc_parser.returncode,
- "stdout": model_bmc_parser.stdout,
- "stderr": model_bmc_parser.stderr,
- },
- "control_modes": {
- "returncode": model_control_modes.returncode,
- "stdout": model_control_modes.stdout,
- "stderr": model_control_modes.stderr,
- },
- "contract": {
- "returncode": model_contract.returncode,
- "stdout": model_contract.stdout,
- "stderr": model_contract.stderr,
- },
- "harness": {
- "returncode": model_harness.returncode,
- "stdout": model_harness.stdout,
- "stderr": model_harness.stderr,
- },
- "debug_bundle": {
- "returncode": model_debug_bundle.returncode,
- "stdout": model_debug_bundle.stdout,
- "stderr": model_debug_bundle.stderr,
- },
- "debug_environment": {
- "returncode": model_debug_environment.returncode,
- "stdout": model_debug_environment.stdout,
- "stderr": model_debug_environment.stderr,
- },
- },
- "contract_replay": replay,
- "debug_bundle": debug_bundle if debug_bundle is not None else {
- "status": "skipped",
- "reason": "debug bundle not requested. Use pipeline --debug-bundle.",
- },
- "static": {
- "status": status(static.returncode),
- "returncode": static.returncode,
- "stdout": static.stdout,
- "stderr": static.stderr,
- },
- "hdl_sim": hdl_sim,
- "rtl_sim": rtl_sim,
- "formal": formal,
- "detector_selftest": detector_selftest,
- "td_build": td,
- "board": {
- "status": "not_run",
- "reason": "User requested no board bring-up.",
- },
- }
- if args.report_file:
- write_json_report(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else render_pipeline(payload))
- ok = model_returncode == 0 and static.returncode == 0
- optional_ok_statuses = {"pass", "blocked_missing_tool", "partial"}
- if args.rtl_sim:
- ok = ok and rtl_sim["status"] in optional_ok_statuses
- if args.hdl_sim:
- ok = ok and hdl_sim["status"] in optional_ok_statuses
- if args.formal:
- ok = ok and formal["status"] in optional_ok_statuses
- if args.detector_selftest:
- ok = ok and detector_selftest["status"] in {"pass", "blocked_missing_tool", "partial"}
- if args.td_build:
- ok = ok and td["status"] == "pass"
- return 0 if ok else 1
- def render_pipeline(payload: dict[str, Any]) -> str:
- return "\n".join(
- [
- f"[{payload['project']}]",
- f"- model: {payload['model']['status']}",
- f"- contract_replay: {payload['contract_replay']['status']}",
- f"- debug_bundle: {payload.get('debug_bundle', {'status': 'skipped'})['status']}",
- f"- static: {payload['static']['status']}",
- f"- hdl_sim: {payload.get('hdl_sim', {'status': 'skipped'})['status']}",
- f"- rtl_sim: {payload['rtl_sim']['status']}",
- f"- formal: {payload.get('formal', {'status': 'skipped'})['status']}",
- f"- detector_selftest: {payload.get('detector_selftest', {'status': 'skipped'})['status']}",
- f"- td_build: {payload['td_build']['status']}",
- f"- board: {payload['board']['status']}",
- ]
- )
- def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(description=__doc__)
- sub = parser.add_subparsers(dest="command", required=True)
- model = sub.add_parser("model", help="run Python golden-model tests")
- model.set_defaults(func=cmd_model)
- replay = sub.add_parser("replay", help="run fixed contract replay vector")
- replay.add_argument("--json", action="store_true")
- replay.add_argument("--report-file", type=Path)
- replay.set_defaults(func=cmd_replay)
- static = sub.add_parser("static", help="run static project checks")
- static.set_defaults(func=cmd_static)
- toolchain = sub.add_parser("toolchain", help="probe local verification/debug toolchain")
- toolchain.add_argument("--json", action="store_true")
- toolchain.add_argument("--report-file", type=Path)
- toolchain.set_defaults(func=cmd_toolchain)
- uart_preflight = sub.add_parser("uart-preflight", help="enumerate UART/RS232 COM candidates without opening unknown ports")
- uart_preflight.add_argument("--allowlist", action="append", default=[])
- uart_preflight.add_argument("--json", action="store_true")
- uart_preflight.add_argument("--report-file", type=Path)
- uart_preflight.set_defaults(func=cmd_uart_preflight)
- uart_protocol = sub.add_parser("uart-protocol-offline", help="validate BMC UART loose text protocol from a text file")
- uart_protocol.add_argument("--text-file", type=Path, required=True)
- uart_protocol.add_argument("--scenario", default="manual_text")
- uart_protocol.add_argument("--json", action="store_true")
- uart_protocol.add_argument("--report-file", type=Path)
- uart_protocol.set_defaults(func=cmd_uart_protocol_offline)
- uart_validate = sub.add_parser("uart-validate", help="validate a non-ChipWatcher UART receipt")
- uart_validate.add_argument("--receipt", type=Path, required=True)
- uart_validate.add_argument("--strict", action="store_true")
- uart_validate.add_argument("--json", action="store_true")
- uart_validate.add_argument("--report-file", type=Path)
- uart_validate.set_defaults(func=cmd_uart_validate)
- final_gate_v2 = sub.add_parser("final-gate-v2", help="run strict non-ChipWatcher UART final gate")
- final_gate_v2.add_argument("--receipt", type=Path, required=True)
- final_gate_v2.add_argument("--rtl-sim", action="store_true", help="include RTL simulator evidence; blocked does not pass")
- final_gate_v2.add_argument("--hdl-backend", choices=["icarus", "verilator", "cocotb", "all"], default="icarus")
- final_gate_v2.add_argument("--formal", action="store_true", help="include formal evidence; blocked does not pass")
- final_gate_v2.add_argument("--formal-engine", choices=["sby"], default="sby")
- final_gate_v2.add_argument("--detector-selftest", action="store_true", help="include detector selftests; blocked does not pass")
- final_gate_v2.add_argument("--td-build", action="store_true", help="include TD top evidence; blocked/skipped does not pass")
- final_gate_v2.add_argument("--td-top", choices=list(TD_TOP_PROFILES), default=DEFAULT_TD_TOP)
- final_gate_v2.add_argument("--json", action="store_true")
- final_gate_v2.add_argument("--report-file", type=Path)
- final_gate_v2.set_defaults(func=cmd_final_gate_v2)
- offline_gate = sub.add_parser("offline-fidelity-gate-v1", help="run strict no-hardware offline fidelity gate")
- offline_gate.add_argument("--auto-bootstrap", action="store_true", help="allow user-space OSS CAD Suite/cocotb bootstrap only")
- offline_gate.add_argument("--hdl-backend", choices=["icarus", "verilator", "cocotb", "all"], default="all")
- offline_gate.add_argument("--formal", action="store_true", help="require formal evidence")
- offline_gate.add_argument("--td-build", action="store_true", help="require TD offline elaboration/build evidence")
- offline_gate.add_argument("--long-run", choices=["ci", "nightly", "final"], default="ci")
- offline_gate.add_argument("--json", action="store_true")
- offline_gate.add_argument("--report-file", type=Path)
- offline_gate.set_defaults(func=cmd_offline_fidelity_gate_v1)
- clean_runtime = sub.add_parser("clean-runtime", help="clear runtime build/log/receipt outputs before fresh verification")
- clean_runtime.add_argument("--include-external-td-log", action="store_true", help="also clear TD install bin/log bw_*.log* files")
- clean_runtime.add_argument("--json", action="store_true")
- clean_runtime.add_argument("--report-file", type=Path)
- clean_runtime.set_defaults(func=cmd_clean_runtime)
- toolchain_clean = sub.add_parser("toolchain-clean", help="dry-run or remove owned user-mode verification toolchain caches")
- toolchain_clean.add_argument("--install-root", type=Path, default=DEFAULT_OSS_CAD_SUITE_ROOT)
- toolchain_clean.add_argument("--cocotb-venv", type=Path, default=DEFAULT_COCOTB_VENV_PYTHON.parent.parent)
- toolchain_clean.add_argument("--include-downloads", action="store_true")
- toolchain_clean.add_argument("--apply", action="store_true", help="actually delete owned toolchain paths; default is dry-run")
- toolchain_clean.add_argument("--json", action="store_true")
- toolchain_clean.add_argument("--report-file", type=Path)
- toolchain_clean.set_defaults(func=cmd_toolchain_clean)
- td = sub.add_parser("td-build", help="probe TD synthesis/implementation")
- td.add_argument("--run", action="store_true", help="actually invoke TD")
- td.add_argument("--top", choices=list(TD_TOP_PROFILES), default=DEFAULT_TD_TOP)
- td.add_argument("--json", action="store_true")
- td.add_argument("--report-file", type=Path)
- td.set_defaults(func=cmd_td_build)
- td_alias = sub.add_parser("td", help="probe TD synthesis/implementation")
- td_alias.add_argument("--run", action="store_true", help="actually invoke TD")
- td_alias.add_argument("--top", choices=list(TD_TOP_PROFILES), default=DEFAULT_TD_TOP)
- td_alias.add_argument("--json", action="store_true")
- td_alias.add_argument("--report-file", type=Path)
- td_alias.set_defaults(func=cmd_td_build)
- hdl = sub.add_parser("hdl-sim", help="run optional HDL simulation tests")
- hdl.add_argument("--run", action="store_true", help="actually invoke the selected simulator backend")
- hdl.add_argument("--backend", choices=["icarus", "verilator", "cocotb", "all"], default="icarus")
- hdl.add_argument("--scenario", type=Path)
- hdl.add_argument("--json", action="store_true")
- hdl.add_argument("--report-file", type=Path)
- hdl.set_defaults(func=cmd_hdl_sim)
- rtl = sub.add_parser("rtl-sim", help="run optional RTL simulation tests")
- rtl.add_argument("--run", action="store_true", help="actually invoke iverilog/vvp")
- rtl.add_argument("--json", action="store_true")
- rtl.add_argument("--report-file", type=Path)
- rtl.set_defaults(func=cmd_rtl_sim)
- formal = sub.add_parser("formal", help="run optional formal property checks")
- formal.add_argument("--run", action="store_true", help="actually invoke the selected formal engine")
- formal.add_argument("--engine", choices=["sby"], default="sby")
- formal.add_argument("--json", action="store_true")
- formal.add_argument("--report-file", type=Path)
- formal.set_defaults(func=cmd_formal)
- selftest = sub.add_parser("detector-selftest", help="run bad-fixture selftests for verification detectors")
- selftest.add_argument("--run", action="store_true", help="actually invoke detector backends on bad fixtures")
- selftest.add_argument("--backend", choices=["all", "icarus", "verilator", "cocotb", "formal"], default="all")
- selftest.add_argument("--json", action="store_true")
- selftest.add_argument("--report-file", type=Path)
- selftest.set_defaults(func=cmd_detector_selftest)
- dbg = sub.add_parser("debug-bundle", help="build an agent-readable debug bundle")
- dbg.add_argument("--source", choices=["replay", "hdl", "formal", "td", "hardware", "rtl", "register", "uart"], default="replay")
- dbg.add_argument("--output-dir", type=Path)
- dbg.add_argument("--raw-file", type=Path, action="append", default=[], help="copy a manual export file into the bundle raw/ directory")
- dbg.add_argument("--raw-dir", type=Path, action="append", default=[], help="copy a manual export directory into the bundle raw/ directory")
- dbg.add_argument("--json", action="store_true")
- dbg.set_defaults(func=cmd_debug_bundle)
- analyze = sub.add_parser("analyze-bundle", help="analyze an agent-readable debug bundle")
- analyze.add_argument("bundle_dir", type=Path)
- analyze.add_argument("--json", action="store_true")
- analyze.set_defaults(func=cmd_analyze_bundle)
- pipe = sub.add_parser("pipeline", help="run layered checks")
- pipe.add_argument("--td-build", action="store_true", help="include TD build probe")
- pipe.add_argument("--rtl-sim", action="store_true", help="include optional RTL simulation probe")
- pipe.add_argument("--hdl-sim", action="store_true", help="include optional HDL simulation probe")
- pipe.add_argument("--hdl-backend", choices=["icarus", "verilator", "cocotb", "all"], default="all")
- pipe.add_argument("--scenario", type=Path)
- pipe.add_argument("--formal", action="store_true", help="include optional formal verification probe")
- pipe.add_argument("--formal-engine", choices=["sby"], default="sby")
- pipe.add_argument("--detector-selftest", action="store_true", help="run bad-fixture detector selftests")
- pipe.add_argument("--debug-bundle", action="store_true", help="write a replay-based agent debug bundle")
- pipe.add_argument("--json", action="store_true")
- pipe.add_argument("--report-file", type=Path)
- pipe.set_defaults(func=cmd_pipeline)
- return parser
- def main(argv: list[str] | None = None) -> int:
- parser = build_parser()
- args = parser.parse_args(argv)
- return args.func(args)
- if __name__ == "__main__":
- sys.exit(main())
|