| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559 |
- #!/usr/bin/env python3
- """Focused contracts for the minimal Normal-v3 verification harness."""
- from __future__ import annotations
- import argparse
- import copy
- import hashlib
- import json
- import re
- import subprocess
- import tempfile
- import unittest
- from pathlib import Path
- from unittest import mock
- ROOT = Path(__file__).resolve().parents[2]
- import sys
- sys.path.insert(0, str(ROOT / "tools"))
- import prod2u_p4_harness as harness # noqa: E402
- EXPECTED_SOURCES = (
- "src/rtl/uart_rx_8n1.v",
- "src/rtl/uart_tx_8n1.v",
- "src/rtl/binary921_crc16.v",
- "src/rtl/binary921_frame_tx.v",
- "src/rtl/prod2u_por.v",
- "src/rtl/prod2u_p4_us_tick.v",
- "src/rtl/prod2u_p4_normal_v3_rx.v",
- "src/rtl/prod2u_p4_normal_v3_output_state.v",
- "src/rtl/prod2u_p4_normal_v3_watchdog.v",
- "src/rtl/prod2u_p4_axis_executor.v",
- "src/rtl/prod2u_p4_motor_hub.v",
- "src/rtl/prod2u_p4_response_scheduler.v",
- "src/rtl/prod2u_p4_i2c_stop_start_read.v",
- "src/rtl/prod2u_p4_temperature_read.v",
- "src/rtl/prod2u_p4_temperature_store.v",
- "src/rtl/prod2u_p4_temperature_short_tx.v",
- "src/rtl/prod2u_p4_normal_v3_tx.v",
- "src/rtl/prod2u_p4_pwm_outputs.v",
- "src/rtl/prod2u_p4_normal_v3_core.v",
- "src/top/prod2u_p4_normal_v3_top.v",
- )
- REQUIRED_MOTOR_LIMIT_PINS = {
- "motor_en_n": {"location": "A10", "direction": "OUTPUT", "pull_type": "NONE"},
- "x_step": {"location": "C11", "direction": "OUTPUT", "pull_type": "NONE"},
- "x_dir": {"location": "B12", "direction": "OUTPUT", "pull_type": "NONE"},
- "y_step": {"location": "D15", "direction": "OUTPUT", "pull_type": "NONE"},
- "y_dir": {"location": "H14", "direction": "OUTPUT", "pull_type": "NONE"},
- "x_limit_raw": {"location": "B9", "direction": "INPUT", "pull_type": "PULLUP"},
- "y_limit_raw": {"location": "A11", "direction": "INPUT", "pull_type": "PULLUP"},
- }
- EXPECTED_CDC_REGISTERS = frozenset(
- {
- "u_uart_rx/rx_sync_pipe[0]",
- "u_uart_rx/rx_sync_pipe[1]",
- "u_temperature_i2c/scl_sync[0]",
- "u_temperature_i2c/scl_sync[1]",
- "u_temperature_i2c/sda_sync[0]",
- "u_temperature_i2c/sda_sync[1]",
- }
- )
- EXPECTED_CDC_ENDPOINTS = frozenset(
- {
- "u_uart_rx/rx_sync_pipe[0]",
- "u_temperature_i2c/scl_sync[0]",
- "u_temperature_i2c/sda_sync[0]",
- }
- )
- VERIFICATION_RUN_ID = "d" * 32
- def valid_io_rows() -> list[dict[str, str]]:
- rows = [
- {
- "name": f"dummy_{index}",
- "direction": "OUTPUT",
- "location": f"DUMMY{index}",
- "io_standard": "LVCMOS33",
- "io_type": "PAD",
- "drive_strength": "8",
- "pull_type": "NONE",
- "pack_reg": "NONE",
- "diff_resistor": "NONE",
- }
- for index in range(43 - len(REQUIRED_MOTOR_LIMIT_PINS))
- ]
- template = rows[0]
- rows.extend(
- {
- **template,
- "name": name,
- "location": expected["location"],
- "direction": expected["direction"],
- "pull_type": expected["pull_type"],
- }
- for name, expected in REQUIRED_MOTOR_LIMIT_PINS.items()
- )
- return rows
- def valid_resources() -> dict[str, object]:
- return {
- "utilization": {
- name: {"used": used}
- for name, used in {
- "bram": 0,
- "bram32k": 0,
- "bram128k": 0,
- "bram256k": 0,
- "dsp": 0,
- "pad": 43,
- "ireg": 0,
- }.items()
- }
- }
- def valid_td_receipt(bitstream: Path, *, commit: str = "a" * 8) -> dict[str, object]:
- digest = harness.sha256_file(bitstream)
- observed_pins = {
- row["name"]: row
- for row in valid_io_rows()
- if row["name"] in REQUIRED_MOTOR_LIMIT_PINS
- }
- return {
- "schema": harness.TD_RECEIPT_SCHEMA,
- "status": "pass",
- "verification_run_id": VERIFICATION_RUN_ID,
- "commit": commit,
- "bitstream_sha256": digest,
- "synthesis_input_hash": "b" * 64,
- "source_state": {"clean": True, "commit": commit},
- "source_binding_gate": {"status": "pass"},
- "pin_binding_gate": {"status": "pass"},
- "post_route_pin_gate": {
- "status": "pass",
- "row_count": 43,
- "observed": observed_pins,
- },
- "binding_gate": {"status": "pass"},
- "timing_gate": {"status": "pass"},
- "structural_gate": {
- "status": "pass",
- "cdc": {
- "status": "pass",
- "async_reg": {"used": 6},
- "input_registers": {"used": 0},
- "retained_sync_registers": {"used": 6},
- "first_stage_endpoints": {"used": 3},
- },
- "fsm_encoding": {
- "status": "pass",
- "encoding": "sequential",
- "axes": {"x": 2, "y": 2},
- "td_log_marker": True,
- "reencoded_motion_phase_count": 0,
- },
- },
- "resources": valid_resources(),
- "timing": {
- "fmax_mhz": 50.0,
- "worst_setup_slack_ns": 0.1,
- "worst_hold_slack_ns": 0.1,
- "error_count": 0,
- },
- "syn": {
- "status": "pass",
- "returncode": 0,
- "log_has_error": False,
- "critical_warning_count": 0,
- },
- "phy": {
- "status": "pass",
- "returncode": 0,
- "log_has_error": False,
- "critical_warning_count": 0,
- },
- "bitgen": {
- "status": "pass",
- "returncode": 0,
- "log_has_error": False,
- "critical_warning_count": 0,
- },
- "bitstream": {
- "path": str(bitstream),
- "size": bitstream.stat().st_size,
- "sha256": digest,
- },
- "run_id": "1" * 32,
- "work_root": "C:/td-a",
- "td_tool": {"sha256": "c" * 64},
- "synthesis_input_manifest": {"sha256": "b" * 64},
- }
- def valid_offline_receipt(*, commit: str = "a" * 8) -> dict[str, object]:
- layers = {
- name: {"status": "pass"}
- for name in ("source_integrity", "unit", "hdl_sim", "formal")
- }
- return {
- "schema": harness.OFFLINE_RECEIPT_SCHEMA,
- "status": "pass",
- "verification_run_id": VERIFICATION_RUN_ID,
- "commit": commit,
- "source_state": {"clean": True, "commit": commit},
- "required_layers": ["source_integrity", "unit", "hdl_sim", "formal"],
- "layers": layers,
- "failures": [],
- }
- def valid_package_receipt(
- package: Path,
- *,
- digest: str,
- commit: str = "a" * 8,
- ) -> dict[str, object]:
- return {
- "schema": harness.PACKAGE_RECEIPT_SCHEMA,
- "status": "pass",
- "verification_run_id": VERIFICATION_RUN_ID,
- "commit": commit,
- "bitstream_sha256": digest,
- "package_dir": str(package),
- "delivery_mode": "normal_dual_td",
- "verification_complete": True,
- "confirmation_td_present": True,
- "validation_status": "pass",
- "packaged_selftest_status": "pass",
- "failures": [],
- "selftest": {"status": "pass", "returncode": 0},
- }
- def materialize_valid_package(
- package: Path,
- *,
- bitstream_bytes: bytes = b"package-final-gate",
- commit: str = "a" * 8,
- ) -> tuple[dict[str, object], dict[str, object], dict[str, object]]:
- package.mkdir(parents=True)
- bitstream = package / "fw.bit"
- bitstream.write_bytes(bitstream_bytes)
- digest = harness.sha256_file(bitstream)
- primary = valid_td_receipt(bitstream, commit=commit)
- confirmation = copy.deepcopy(primary)
- confirmation["run_id"] = "2" * 32
- confirmation["work_root"] = "C:/td-b"
- for relative in harness.package_required_files(confirmation_td_present=True):
- path = package / relative
- path.parent.mkdir(parents=True, exist_ok=True)
- if not path.exists():
- path.write_text(f"fixture:{relative}\n", encoding="utf-8")
- primary_path = package / "evidence" / "td-primary-receipt.json"
- confirmation_path = package / "evidence" / "td-confirmation-receipt.json"
- primary_path.write_text(json.dumps(primary), encoding="utf-8")
- confirmation_path.write_text(json.dumps(confirmation), encoding="utf-8")
- validation = {
- "schema": "prod2u-p4-normal-v3-validation-summary-v1",
- "verification_run_id": VERIFICATION_RUN_ID,
- "commit": commit,
- "bitstream_sha256": digest,
- "delivery_mode": "normal_dual_td",
- "verification_complete": True,
- "confirmation_td_present": True,
- "layers": {
- name: {"status": "pass"}
- for name in (
- "python",
- "icarus",
- "verilator",
- "cocotb",
- "formal",
- "td_primary",
- "td_confirmation",
- "td_primary_artifacts",
- "td_confirmation_artifacts",
- "td_confirmation_bitstream",
- "td_confirmation_synthesis",
- "td_confirmation_manifest",
- "resource_primary",
- "resource_confirmation",
- "package_selftest",
- )
- },
- }
- validation_path = package / "evidence" / "validation-summary.json"
- validation_path.write_text(json.dumps(validation), encoding="utf-8")
- packaged_selftest_path = package / "evidence" / "package-selftest-result.json"
- packaged_selftest_path.write_text(
- json.dumps(
- {
- "schema": "prod2u-p4-normal-v3-package-selftest-result-v1",
- "status": "pass",
- "returncode": 0,
- }
- ),
- encoding="utf-8",
- )
- info_path = package / "package-info.json"
- actual_files = {
- path.relative_to(package).as_posix(): harness.sha256_file(path)
- for path in sorted(package.rglob("*"))
- if path.is_file() and path not in {info_path, packaged_selftest_path}
- }
- info = {
- "schema": "prod2u-p4-normal-v3-folder-package-info-v3",
- "profile": harness.RUNTIME_PROFILE,
- "verification_run_id": VERIFICATION_RUN_ID,
- "commit": commit,
- "bitstream_sha256": digest,
- "delivery_mode": "normal_dual_td",
- "verification_complete": True,
- "confirmation_td_present": True,
- "confirmation_bitstream_sha256": digest,
- "td_receipt_sha256": harness.sha256_file(primary_path),
- "confirmation_td_receipt_sha256": harness.sha256_file(confirmation_path),
- "validation_summary_sha256": harness.sha256_file(validation_path),
- "package_selftest_result_sha256": harness.sha256_file(packaged_selftest_path),
- "synthesis_input_hash": primary["synthesis_input_hash"],
- "confirmation_synthesis_input_hash": confirmation["synthesis_input_hash"],
- "file_sha256": actual_files,
- }
- info_path.write_text(json.dumps(info), encoding="utf-8")
- receipt = valid_package_receipt(package, digest=digest, commit=commit)
- receipt.update(
- {
- "package_info_sha256": harness.sha256_file(info_path),
- "td_receipt_sha256": harness.sha256_file(primary_path),
- "confirmation_td_receipt_sha256": harness.sha256_file(confirmation_path),
- "validation_summary_sha256": harness.sha256_file(validation_path),
- "package_selftest_result_sha256": harness.sha256_file(packaged_selftest_path),
- "package_file_sha256": actual_files,
- "package_file_manifest_sha256": harness.canonical_sha256(actual_files),
- }
- )
- return receipt, primary, confirmation
- def refresh_package_bindings(package: Path, receipt: dict[str, object]) -> None:
- info_path = package / "package-info.json"
- primary_path = package / "evidence" / "td-primary-receipt.json"
- confirmation_path = package / "evidence" / "td-confirmation-receipt.json"
- validation_path = package / "evidence" / "validation-summary.json"
- packaged_selftest_path = package / "evidence" / "package-selftest-result.json"
- info = json.loads(info_path.read_text(encoding="utf-8"))
- info["td_receipt_sha256"] = harness.sha256_file(primary_path)
- info["confirmation_td_receipt_sha256"] = (
- harness.sha256_file(confirmation_path) if confirmation_path.is_file() else None
- )
- info["validation_summary_sha256"] = harness.sha256_file(validation_path)
- info["package_selftest_result_sha256"] = harness.sha256_file(packaged_selftest_path)
- actual_files = {
- path.relative_to(package).as_posix(): harness.sha256_file(path)
- for path in sorted(package.rglob("*"))
- if path.is_file() and path not in {info_path, packaged_selftest_path}
- }
- info["file_sha256"] = actual_files
- info_path.write_text(json.dumps(info), encoding="utf-8")
- receipt.update(
- {
- "delivery_mode": info["delivery_mode"],
- "verification_complete": info["verification_complete"],
- "confirmation_td_present": info["confirmation_td_present"],
- "package_info_sha256": harness.sha256_file(info_path),
- "td_receipt_sha256": info["td_receipt_sha256"],
- "confirmation_td_receipt_sha256": info[
- "confirmation_td_receipt_sha256"
- ],
- "validation_summary_sha256": info["validation_summary_sha256"],
- "package_selftest_result_sha256": info[
- "package_selftest_result_sha256"
- ],
- "package_file_sha256": actual_files,
- "package_file_manifest_sha256": harness.canonical_sha256(actual_files),
- }
- )
- def update_package_info(package: Path, **updates: object) -> None:
- info_path = package / "package-info.json"
- info = json.loads(info_path.read_text(encoding="utf-8"))
- info.update(updates)
- info_path.write_text(json.dumps(info), encoding="utf-8")
- class Prod2UP4HarnessTests(unittest.TestCase):
- def test_cdc_report_preserves_advisory_failures_and_source_only_paths(self) -> None:
- with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
- report_path = Path(temporary) / "cdc.rpt"
- report_path.write_text(
- "\n".join(
- (
- f"schema={harness.CDC_REPORT_SCHEMA}",
- "retained_sync_register=u_uart_rx/rx_sync_pipe[1]",
- "false_path_source=host_uart_rx",
- "structural_failure=retained_sync_register_count:host_uart_rx:0",
- )
- )
- + "\n",
- encoding="ascii",
- )
- report = harness.parse_td_cdc_report(report_path)
- self.assertIsNotNone(report)
- assert report is not None
- self.assertEqual(report["source_only_false_paths"], ["host_uart_rx"])
- self.assertEqual(
- report["structural_failures"],
- ["retained_sync_register_count:host_uart_rx:0"],
- )
- gate = harness.structural_cdc_gate(
- report,
- async_reg_count=1,
- input_register_count=0,
- )
- self.assertEqual(gate["status"], "fail")
- self.assertIn(
- "td_report:retained_sync_register_count:host_uart_rx:0",
- gate["failures"],
- )
- self.assertIn("source_only_false_paths_used:host_uart_rx", gate["failures"])
- def test_cdc_gate_accepts_uart_and_temperature_synchronizers(self) -> None:
- expected_report = {
- "retained_sync_registers": sorted(EXPECTED_CDC_REGISTERS),
- "false_path_endpoints": sorted(EXPECTED_CDC_ENDPOINTS),
- "source_only_false_paths": [],
- "structural_failures": [],
- }
- accepted = harness.structural_cdc_gate(
- expected_report,
- async_reg_count=6,
- input_register_count=0,
- )
- self.assertEqual(accepted["status"], "pass", accepted["failures"])
- def test_cdc_gate_rejects_legacy_limit_synchronizers(self) -> None:
- legacy_registers = sorted(
- EXPECTED_CDC_REGISTERS
- | {
- "u_core/u_motors/u_x_axis/limit_sync_pipe[0]",
- "u_core/u_motors/u_x_axis/limit_sync_pipe[1]",
- "u_core/u_motors/u_x_axis/limit_sync_pipe[2]",
- "u_core/u_motors/u_y_axis/limit_sync_pipe[0]",
- "u_core/u_motors/u_y_axis/limit_sync_pipe[1]",
- "u_core/u_motors/u_y_axis/limit_sync_pipe[2]",
- }
- )
- legacy_report = {
- "retained_sync_registers": legacy_registers,
- "false_path_endpoints": sorted(
- EXPECTED_CDC_ENDPOINTS
- | {
- "u_core/u_motors/u_x_axis/limit_sync_pipe[0]",
- "u_core/u_motors/u_y_axis/limit_sync_pipe[0]",
- }
- ),
- "source_only_false_paths": [],
- "structural_failures": [],
- }
- rejected = harness.structural_cdc_gate(
- legacy_report,
- async_reg_count=12,
- input_register_count=0,
- )
- self.assertEqual(rejected["status"], "fail")
- def test_fsm_report_preserves_advisory_discovery_failures(self) -> None:
- with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
- report_path = Path(temporary) / "fsm.rpt"
- report_path.write_text(
- "\n".join(
- (
- f"schema={harness.FSM_REPORT_SCHEMA}",
- "motion_phase=x:0:unknown",
- "motion_phase=y:3:sequential",
- "structural_failure=motion_phase_register_count:x:0",
- )
- )
- + "\n",
- encoding="ascii",
- )
- report = harness.parse_td_fsm_report(report_path)
- self.assertIsNotNone(report)
- assert report is not None
- self.assertEqual(
- report["structural_failures"],
- ["motion_phase_register_count:x:0"],
- )
- gate = harness.structural_fsm_gate(report, syn_log="")
- self.assertEqual(gate["status"], "fail")
- self.assertIn(
- "td_report:motion_phase_register_count:x:0",
- gate["failures"],
- )
- def test_fsm_gate_accepts_two_bit_simplified_axes(self) -> None:
- accepted = harness.structural_fsm_gate(
- {
- "axes": {"x": 2, "y": 2},
- "encodings": {"x": "sequential", "y": "sequential"},
- "structural_failures": [],
- },
- syn_log="FSM_ENCODING_GATE_PASS=sequential",
- )
- self.assertEqual(accepted["status"], "pass", accepted["failures"])
- def test_fsm_gate_rejects_legacy_three_bit_axes(self) -> None:
- rejected = harness.structural_fsm_gate(
- {
- "axes": {"x": 3, "y": 3},
- "encodings": {"x": "sequential", "y": "sequential"},
- "structural_failures": [],
- },
- syn_log="FSM_ENCODING_GATE_PASS=sequential",
- )
- self.assertEqual(rejected["status"], "fail")
- def test_bitgen_eligibility_depends_only_on_successful_route(self) -> None:
- self.assertTrue(
- harness.td_bitgen_eligible(
- route_artifact_usable=True,
- timing_status="fail",
- structural_status="fail",
- )
- )
- self.assertFalse(
- harness.td_bitgen_eligible(
- route_artifact_usable=False,
- timing_status="pass",
- structural_status="pass",
- )
- )
- def test_td_stage_artifact_usability_ignores_validation_warnings(self) -> None:
- with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
- artifact = Path(temporary) / "routed.db"
- artifact.write_bytes(b"routed database")
- warning_only = subprocess.CompletedProcess(
- ["td"],
- 0,
- stdout="CRITICAL WARNING: validation evidence remains advisory",
- stderr="",
- )
- self.assertTrue(harness.td_stage_artifact_usable(warning_only, artifact))
- error = subprocess.CompletedProcess(
- ["td"],
- 0,
- stdout="ERROR: routed database is unusable",
- stderr="",
- )
- self.assertFalse(harness.td_stage_artifact_usable(error, artifact))
- artifact.unlink()
- self.assertFalse(harness.td_stage_artifact_usable(warning_only, artifact))
- def test_parser_has_closed_commands_and_fixed_td_top(self) -> None:
- parser = harness.build_parser()
- commands = parser._subparsers._group_actions[0].choices
- self.assertEqual(
- set(commands),
- {
- "p4-normal-v3-strict-offline-gate",
- "hdl-sim",
- "formal",
- "td-build",
- "package-selftest",
- "p4-normal-v3-final-gate",
- },
- )
- td_parser = commands["td-build"]
- top_action = next(action for action in td_parser._actions if action.dest == "top")
- self.assertEqual(tuple(top_action.choices), ("prod2u_p4_normal_v3",))
- for retired in ("resource-baseline-produce", "normal-actuator-trace-gate", "uart-board-sram-test"):
- self.assertNotIn(retired, commands)
- def test_delivery_commands_require_one_explicit_verification_run_id(self) -> None:
- parser = harness.build_parser()
- commands = parser._subparsers._group_actions[0].choices
- for command in (
- "p4-normal-v3-strict-offline-gate",
- "td-build",
- "package-selftest",
- "p4-normal-v3-final-gate",
- ):
- action = next(
- item
- for item in commands[command]._actions
- if item.dest == "verification_run_id"
- )
- with self.subTest(command=command):
- self.assertTrue(action.required)
- with self.assertRaisesRegex(ValueError, "verification_run_id is required"):
- harness.normalize_verification_run_id(None)
- final_schema = json.loads(
- (
- ROOT
- / "schemas"
- / "prod2u_p4_normal_v3_final_gate_receipt.schema.json"
- ).read_text(encoding="utf-8")
- )
- self.assertEqual(
- final_schema["properties"]["verification_run_id"]["type"],
- "string",
- )
- def test_package_selftest_schema_matches_emitted_metadata_and_statuses(self) -> None:
- schema = json.loads(
- (
- ROOT
- / "schemas"
- / "prod2u_p4_normal_v3_package_selftest_receipt.schema.json"
- ).read_text(encoding="utf-8")
- )
- for field in (
- "delivery_mode",
- "verification_complete",
- "confirmation_td_present",
- ):
- with self.subTest(field=field):
- self.assertIn(field, schema["required"])
- self.assertIn(field, schema["properties"])
- self.assertEqual(
- set(schema["properties"]["validation_status"]["enum"]),
- {"pass", "fail", "running", "not_run"},
- )
- def test_all_external_commit_schemas_accept_only_lowercase_sha8(self) -> None:
- schema_fields = {
- "prod2u_p4_normal_v3_final_gate_receipt.schema.json": (
- "properties",
- "commit",
- ),
- "prod2u_p4_normal_v3_offline_gate_receipt.schema.json": (
- "properties",
- "commit",
- ),
- "prod2u_p4_normal_v3_package_selftest_receipt.schema.json": (
- "properties",
- "commit",
- ),
- "prod2u_p4_normal_v3_resource_baseline.schema.json": (
- "properties",
- "measured_commit",
- ),
- "prod2u_p4_normal_v3_td_build_receipt.schema.json": ("properties", "commit"),
- "prod2u_program_sram_receipt.schema.json": (
- "properties",
- "bitstream",
- "properties",
- "commit",
- ),
- }
- invalid = ("a" * 7, "a" * 9, "a" * 40, "ABCDEF12")
- for filename, path in schema_fields.items():
- with self.subTest(schema=filename):
- value = json.loads(
- (ROOT / "schemas" / filename).read_text(encoding="utf-8")
- )
- for component in path:
- value = value[component]
- pattern = value["pattern"]
- self.assertIsNotNone(re.fullmatch(pattern, "abcdef12"))
- for rejected in invalid:
- self.assertIsNone(re.fullmatch(pattern, rejected), rejected)
- def test_source_state_validates_full_head_but_exposes_only_sha8(self) -> None:
- full_commit = "abcdef12" + ("3" * 32)
- results = (
- subprocess.CompletedProcess(
- ["git"], 0, stdout=full_commit + "\n", stderr=""
- ),
- subprocess.CompletedProcess(["git"], 0, stdout="", stderr=""),
- )
- with mock.patch.object(harness, "_git", side_effect=results) as git:
- observed = harness.source_state()
- self.assertEqual(observed["status"], "pass")
- self.assertEqual(observed["commit"], "abcdef12")
- git.assert_any_call("rev-parse", "HEAD")
- invalid_results = (
- subprocess.CompletedProcess(["git"], 0, stdout="abcdef12\n", stderr=""),
- subprocess.CompletedProcess(["git"], 0, stdout="", stderr=""),
- )
- with mock.patch.object(harness, "_git", side_effect=invalid_results):
- invalid = harness.source_state()
- self.assertEqual(invalid["status"], "fail")
- self.assertIn("git_commit_unavailable", invalid["failures"])
- def test_td_receipt_identifiers_are_valid_and_canonically_independent(self) -> None:
- schema = json.loads(
- (
- ROOT
- / "schemas"
- / "prod2u_p4_normal_v3_td_build_receipt.schema.json"
- ).read_text(encoding="utf-8")
- )
- pass_required = schema["allOf"][0]["then"]["required"]
- self.assertIn("run_id", pass_required)
- self.assertIn("work_root", pass_required)
- self.assertEqual(
- schema["properties"]["run_id"]["pattern"],
- "^[0-9a-f]{32}$",
- )
- self.assertEqual(
- schema["properties"]["work_root"]["pattern"],
- "^[A-Za-z]:[\\\\/]",
- )
- primary = {"run_id": "1" * 32, "work_root": "C:/td-a"}
- confirmation = {"run_id": "2" * 32, "work_root": "C:/td-b"}
- self.assertTrue(harness.td_receipts_are_independent(primary, confirmation))
- invalid_run_primary = {**primary, "run_id": "invalid-a"}
- invalid_run_confirmation = {**confirmation, "run_id": "invalid-b"}
- self.assertFalse(
- harness.td_receipts_are_independent(
- invalid_run_primary,
- invalid_run_confirmation,
- )
- )
- self.assertFalse(
- harness.td_receipts_are_independent(
- {**primary, "work_root": "td-a"},
- {**confirmation, "work_root": "td-b"},
- )
- )
- self.assertFalse(
- harness.td_receipts_are_independent(
- primary,
- {**confirmation, "work_root": "c:\\TD-A\\child\\.."},
- )
- )
- def test_readme_documents_one_run_id_across_complete_delivery_chain(self) -> None:
- readme = (ROOT / "README.zh-CN.md").read_text(encoding="utf-8")
- run_id_assignment = "$verificationRunId = [Guid]::NewGuid().ToString('N')"
- self.assertLess(
- readme.index(run_id_assignment),
- readme.index("p4-normal-v3-strict-offline-gate"),
- )
- self.assertGreaterEqual(
- readme.count("--verification-run-id $verificationRunId"),
- 5,
- )
- self.assertIn("p4-normal-v3-minimal-td-b", readme)
- self.assertIn("-VerificationRunId $verificationRunId", readme)
- self.assertIn("package-selftest", readme)
- self.assertIn("p4-normal-v3-final-gate", readme)
- def test_unit_payload_uses_pytest_collection_for_function_tests(self) -> None:
- completed = subprocess.CompletedProcess(
- ["python", "-m", "pytest"],
- 0,
- stdout="195 passed",
- stderr="",
- )
- with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
- with mock.patch.object(
- harness.subprocess,
- "run",
- return_value=completed,
- ) as run:
- payload = harness.unit_payload(Path(temporary))
- command = run.call_args.args[0]
- self.assertEqual(payload["status"], "pass")
- self.assertIn("pytest", command)
- self.assertIn("-p", command)
- self.assertIn("no:cacheprovider", command)
- self.assertIn("tests/unit", command)
- self.assertIn("tests/test_project_structure.py", command)
- self.assertNotIn("unittest", command)
- def test_production_source_manifest_is_exact_and_has_no_retired_rtl(self) -> None:
- self.assertEqual(tuple(harness.PRODUCTION_RTL_SOURCES), EXPECTED_SOURCES)
- self.assertEqual(tuple(harness.active_rtl_sources()), EXPECTED_SOURCES)
- combined = "\n".join(EXPECTED_SOURCES).casefold()
- for retired in ("trace", "ct7428", "limit_filter", "build_identity"):
- self.assertNotIn(retired, combined)
- def test_versioned_target_manifest_matches_every_discovered_layer(self) -> None:
- inventory = harness.target_inventory()
- evidence = harness.target_manifest_evidence("all", inventory)
- self.assertEqual(evidence["status"], "pass", evidence["failures"])
- self.assertEqual(set(inventory), set(harness.TARGET_MANIFEST_LAYERS))
- def test_discovered_targets_exclude_retired_motion_and_trace_contracts(self) -> None:
- inventory = harness.target_inventory()
- names = [
- *inventory["unit"],
- *inventory["icarus"],
- *inventory["verilator"],
- *inventory["cocotb"],
- *inventory["formal"].keys(),
- ]
- retired_tokens = (
- "trace",
- "recovery",
- "mark",
- "late_evidence",
- "terminal",
- "locked",
- "learning",
- "limit_filter",
- "rx_bram",
- "build_identity",
- )
- offenders = [name for name in names if any(token in name.casefold() for token in retired_tokens)]
- self.assertEqual(offenders, [])
- def test_dry_run_layers_never_claim_pass_or_hardware_access(self) -> None:
- hdl = harness.hdl_sim_payload(run=False, backend="all")
- formal = harness.formal_payload(run=False)
- td = harness.td_build_payload(
- run=False,
- verification_run_id=VERIFICATION_RUN_ID,
- )
- for payload in (hdl, formal, td):
- with self.subTest(schema=payload["schema"]):
- self.assertEqual(payload["status"], "skipped")
- self.assertEqual(payload["safety"], harness.SAFETY_BOUNDARY)
- self.assertFalse(payload["safety"]["opens_serial"])
- self.assertFalse(payload["safety"]["programs_hardware"])
- def test_synthesis_manifest_hashes_only_exact_production_inputs(self) -> None:
- manifest = harness.build_synthesis_input_manifest(ROOT)
- expected = set(EXPECTED_SOURCES) | {
- "constraints/prod2u_p4_normal_v3.adc",
- "constraints/prod2u_p4_normal_v3.sdc",
- "td/prod2u_p4_normal_v3.prj",
- "td/syn/prod2u_p4_normal_v3.tcl",
- "td/phy/prod2u_p4_normal_v3.tcl",
- "td/bitgen/prod2u_p4_normal_v3.tcl",
- }
- self.assertEqual(set(manifest["inputs"]), expected)
- self.assertRegex(manifest["sha256"], r"^[0-9a-f]{64}$")
- self.assertNotIn("@build_identity", manifest["inputs"])
- def test_external_clean_staging_rechecks_synthesis_hash(self) -> None:
- clean_state = {
- "status": "pass",
- "commit": "a" * 8,
- "clean": True,
- "tracked_changes": [],
- "failures": [],
- }
- with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
- with mock.patch.object(harness, "source_state", return_value=clean_state):
- staged = harness.prepare_td_build_dirs(work_root=Path(temporary))
- verified = harness.verify_staged_source_manifest(staged)
- self.assertEqual(verified["status"], "pass", verified["failures"])
- self.assertEqual(staged.source_state["commit"], "a" * 8)
- self.assertEqual(
- staged.synthesis_input_manifest["sha256"],
- harness.build_synthesis_input_manifest(ROOT)["sha256"],
- )
- def test_work_and_receipt_paths_must_stay_outside_repository(self) -> None:
- with self.assertRaisesRegex(ValueError, "outside the repository"):
- harness.resolve_work_root(ROOT / "tmp", run=False)
- with self.assertRaisesRegex(ValueError, "outside the repository"):
- harness.resolve_report_file(ROOT / "receipt.json")
- def test_pin_binding_gate_blocks_every_motor_and_limit_ball_mutation(self) -> None:
- evidence = harness.pin_binding_gate()
- self.assertEqual(evidence["status"], "pass", evidence["failures"])
- self.assertEqual(evidence["pad_count"], 43)
- original = (ROOT / "constraints" / "prod2u_p4_normal_v3.adc").read_text(
- encoding="ascii"
- )
- with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
- temporary_root = Path(temporary)
- constraints = temporary_root / "constraints"
- constraints.mkdir()
- target = constraints / "prod2u_p4_normal_v3.adc"
- for signal, expected in REQUIRED_MOTOR_LIMIT_PINS.items():
- with self.subTest(signal=signal):
- pattern = re.compile(
- rf"(set_pin_assignment\s+\{{\s*{re.escape(signal)}\s*\}}\s+"
- rf"\{{\s*LOCATION\s*=\s*){re.escape(expected['location'])}(;)"
- )
- mutated, count = pattern.subn(r"\1WRONG_BALL\2", original)
- self.assertEqual(count, 1)
- target.write_text(mutated, encoding="ascii")
- with mock.patch.object(harness, "ROOT", temporary_root):
- rejected = harness.pin_binding_gate()
- self.assertEqual(rejected["status"], "fail", rejected)
- target.write_text(
- original.replace("LOCATION = A10;", "LOCATION = A5;", 1),
- encoding="ascii",
- )
- with mock.patch.object(harness, "ROOT", temporary_root):
- forbidden = harness.pin_binding_gate()
- self.assertEqual(forbidden["status"], "fail")
- self.assertIn("forbidden_ball_assigned:A5", forbidden["failures"])
- def test_post_route_pin_gate_blocks_motor_limit_a5_and_io_count_mutations(self) -> None:
- rows = valid_io_rows()
- with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
- report_path = Path(temporary) / "prod2u_p4_normal_v3_phy.area"
- report_path.write_text(
- "\n".join(
- [
- "Detailed IO Report",
- (
- "Name Direction Location IOStandard IOType "
- "DriveStrength PullType PackReg DiffResistor"
- ),
- *(
- " ".join(
- row[field]
- for field in (
- "name",
- "direction",
- "location",
- "io_standard",
- "io_type",
- "drive_strength",
- "pull_type",
- "pack_reg",
- "diff_resistor",
- )
- )
- for row in rows
- ),
- "",
- ]
- ),
- encoding="ascii",
- )
- parsed_rows = harness.parse_td_io_report(report_path)
- self.assertIsNotNone(parsed_rows)
- assert parsed_rows is not None
- self.assertEqual(len(parsed_rows), 43)
- evidence = harness.post_route_pin_gate(parsed_rows)
- self.assertEqual(evidence["status"], "pass", evidence["failures"])
- for signal in REQUIRED_MOTOR_LIMIT_PINS:
- with self.subTest(signal=signal):
- changed = copy.deepcopy(parsed_rows)
- row = next(item for item in changed if item["name"] == signal)
- row["location"] = "WRONG_BALL"
- rejected = harness.post_route_pin_gate(changed)
- self.assertEqual(rejected["status"], "fail", rejected)
- forbidden_rows = copy.deepcopy(parsed_rows)
- forbidden_rows[0]["location"] = "A5"
- forbidden = harness.post_route_pin_gate(forbidden_rows)
- self.assertEqual(forbidden["status"], "fail")
- self.assertIn("forbidden_location_assigned:A5", forbidden["failures"])
- missing_row = harness.post_route_pin_gate(parsed_rows[:-1])
- self.assertEqual(missing_row["status"], "fail")
- self.assertIn("io_row_count:42", missing_row["failures"])
- def test_structural_resource_gate_requires_reported_bram_dsp_and_io_43(self) -> None:
- accepted = harness.structural_resource_gate(valid_resources())
- self.assertEqual(accepted["status"], "pass", accepted["failures"])
- for resource in ("bram", "bram32k", "bram128k", "bram256k", "dsp"):
- with self.subTest(resource=resource):
- changed = valid_resources()
- changed["utilization"][resource]["used"] = 1
- accepted = harness.structural_resource_gate(changed)
- self.assertEqual(accepted["status"], "pass", accepted["failures"])
- missing = valid_resources()
- del missing["utilization"][resource]
- rejected = harness.structural_resource_gate(missing)
- self.assertEqual(rejected["status"], "fail")
- invalid = valid_resources()
- invalid["utilization"][resource]["used"] = "1"
- rejected = harness.structural_resource_gate(invalid)
- self.assertEqual(rejected["status"], "fail")
- wrong_pad = valid_resources()
- wrong_pad["utilization"]["pad"]["used"] = 41
- rejected = harness.structural_resource_gate(wrong_pad)
- self.assertEqual(rejected["status"], "fail")
- def test_timing_gate_requires_positive_setup_hold_fmax_and_zero_errors(self) -> None:
- accepted = harness.timing_gate(
- {
- "fmax_mhz": 50.0,
- "worst_setup_slack_ns": 0.01,
- "worst_hold_slack_ns": 0.01,
- "error_count": 0,
- }
- )
- self.assertEqual(accepted["status"], "pass")
- for field in ("fmax_mhz", "worst_setup_slack_ns", "worst_hold_slack_ns"):
- with self.subTest(field=field):
- timing = {
- "fmax_mhz": 50.0,
- "worst_setup_slack_ns": 0.01,
- "worst_hold_slack_ns": 0.01,
- "error_count": 0,
- }
- timing[field] = 0
- self.assertEqual(harness.timing_gate(timing)["status"], "fail")
- def test_td_bitstream_binding_requires_existing_hash_matching_file(self) -> None:
- digest = "a" * 64
- receipt = {
- "bitstream_sha256": digest,
- "bitstream": {
- "path": str(ROOT.parent / "definitely-missing-final-gate.bit"),
- "sha256": digest,
- },
- }
- self.assertEqual(
- harness.td_receipt_bitstream_binding_status(receipt),
- "fail",
- )
- def test_final_td_semantic_recheck_rejects_forged_pass_fields(self) -> None:
- with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
- bitstream = Path(temporary) / "fw.bit"
- bitstream.write_bytes(b"minimal-final-gate")
- baseline = valid_td_receipt(bitstream)
- self.assertEqual(
- harness._td_final_failures(baseline, label="td", expected_commit="a" * 8),
- [],
- )
- for resource in ("bram", "bram32k", "bram128k", "bram256k", "dsp"):
- with self.subTest(resource=resource):
- forged = copy.deepcopy(baseline)
- forged["resources"]["utilization"][resource]["used"] = 1
- failures = harness._td_final_failures(
- forged,
- label="td",
- expected_commit="a" * 8,
- )
- self.assertFalse(any(f"resource:{resource}:" in item for item in failures))
- missing = copy.deepcopy(baseline)
- del missing["resources"]["utilization"][resource]
- failures = harness._td_final_failures(
- missing,
- label="td",
- expected_commit="a" * 8,
- )
- self.assertTrue(any(f"resource:{resource}:" in item for item in failures))
- forged = copy.deepcopy(baseline)
- forged["resources"]["utilization"]["pad"]["used"] = 41
- failures = harness._td_final_failures(
- forged,
- label="td",
- expected_commit="a" * 8,
- )
- self.assertTrue(any("resource:pad:" in item for item in failures))
- mutations = {
- "timing": lambda value: value["timing"].__setitem__("worst_setup_slack_ns", 0),
- "pins": lambda value: value["post_route_pin_gate"]["observed"]["y_limit_raw"].__setitem__("location", "A5"),
- "motor_pin": lambda value: value["post_route_pin_gate"]["observed"]["x_step"].__setitem__("location", "WRONG_BALL"),
- "source": lambda value: value["source_state"].__setitem__("clean", False),
- "phase": lambda value: value["phy"].__setitem__("status", "fail"),
- }
- for name, mutate in mutations.items():
- with self.subTest(name=name):
- forged = copy.deepcopy(baseline)
- mutate(forged)
- self.assertTrue(
- harness._td_final_failures(
- forged,
- label="td",
- expected_commit="a" * 8,
- )
- )
- bitstream.write_bytes(b"minimal-final-gatE")
- failures = harness._td_final_failures(
- baseline,
- label="td",
- expected_commit="a" * 8,
- )
- self.assertIn("td:bitstream_file_hash", failures)
- def test_final_package_semantic_recheck_binds_info_and_firmware_hash(self) -> None:
- with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
- package = Path(temporary) / "package"
- receipt, _, _ = materialize_valid_package(package)
- digest = str(receipt["bitstream_sha256"])
- primary_sha = str(receipt["td_receipt_sha256"])
- confirmation_sha = str(receipt["confirmation_td_receipt_sha256"])
- self.assertEqual(
- harness._package_final_failures(
- receipt,
- expected_commit="a" * 8,
- expected_bitstream_sha256=digest,
- expected_primary_td_receipt_sha256=primary_sha,
- expected_confirmation_td_receipt_sha256=confirmation_sha,
- ),
- [],
- )
- info_path = package / "package-info.json"
- info = json.loads(info_path.read_text(encoding="utf-8"))
- info["commit"] = "b" * 8
- info_path.write_text(json.dumps(info), encoding="utf-8")
- self.assertIn(
- "package:info_binding",
- harness._package_final_failures(
- receipt,
- expected_commit="a" * 8,
- expected_bitstream_sha256=digest,
- expected_primary_td_receipt_sha256=primary_sha,
- expected_confirmation_td_receipt_sha256=confirmation_sha,
- ),
- )
- info["commit"] = "a" * 8
- info_path.write_text(json.dumps(info), encoding="utf-8")
- (package / "fw.bit").write_bytes(b"tampered")
- self.assertIn(
- "package:file_hash",
- harness._package_final_failures(
- receipt,
- expected_commit="a" * 8,
- expected_bitstream_sha256=digest,
- expected_primary_td_receipt_sha256=primary_sha,
- expected_confirmation_td_receipt_sha256=confirmation_sha,
- ),
- )
- incomplete = valid_package_receipt(package, digest=digest)
- incomplete["verification_complete"] = False
- self.assertIn(
- "package:verification_incomplete",
- harness._package_final_failures(
- incomplete,
- expected_commit="a" * 8,
- expected_bitstream_sha256=digest,
- expected_primary_td_receipt_sha256=primary_sha,
- expected_confirmation_td_receipt_sha256=confirmation_sha,
- ),
- )
- def test_final_package_rechecks_closed_normal_package_and_external_td_bindings(self) -> None:
- mutations = (
- ("urgent_receipt", "package:delivery_mode", lambda package, receipt: receipt.__setitem__("delivery_mode", "urgent_single_td")),
- ("urgent_info", "package:info_delivery_mode", lambda package, receipt: update_package_info(package, delivery_mode="urgent_single_td")),
- ("false_info_verification", "package:info_verification_incomplete", lambda package, receipt: update_package_info(package, verification_complete=False)),
- ("false_info_confirmation", "package:info_confirmation_td_missing", lambda package, receipt: update_package_info(package, confirmation_td_present=False)),
- ("missing_confirmation", "package:required_file", lambda package, receipt: (package / "evidence" / "td-confirmation-receipt.json").unlink()),
- ("missing_validation", "package:required_file", lambda package, receipt: (package / "evidence" / "validation-summary.json").unlink()),
- ("missing_selftest", "package:required_file", lambda package, receipt: (package / "evidence" / "package-selftest-result.json").unlink()),
- )
- for name, expected, mutate in mutations:
- with self.subTest(name=name), tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
- package = Path(temporary) / "package"
- receipt, _, _ = materialize_valid_package(package)
- mutate(package, receipt)
- failures = harness._package_final_failures(
- receipt,
- expected_commit="a" * 8,
- expected_bitstream_sha256=str(receipt["bitstream_sha256"]),
- expected_primary_td_receipt_sha256=str(receipt["td_receipt_sha256"]),
- expected_confirmation_td_receipt_sha256=str(
- receipt["confirmation_td_receipt_sha256"]
- ),
- )
- self.assertTrue(
- any(item.startswith(expected) for item in failures),
- failures,
- )
- with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
- package = Path(temporary) / "package"
- receipt, _, _ = materialize_valid_package(package)
- failures = harness._package_final_failures(
- receipt,
- expected_commit="a" * 8,
- expected_bitstream_sha256=str(receipt["bitstream_sha256"]),
- expected_primary_td_receipt_sha256="0" * 64,
- expected_confirmation_td_receipt_sha256="1" * 64,
- )
- self.assertIn("package:primary_td_external_binding", failures)
- self.assertIn("package:confirmation_td_external_binding", failures)
- def test_td_final_reopens_cdc_and_fsm_structure_contracts(self) -> None:
- with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
- bitstream = Path(temporary) / "td.bit"
- bitstream.write_bytes(b"td-structure-contract")
- receipt = valid_td_receipt(bitstream)
- receipt["structural_gate"]["cdc"]["retained_sync_registers"][
- "used"
- ] = 8
- receipt["structural_gate"]["fsm_encoding"]["axes"] = {
- "x": 3,
- "y": 3,
- }
- failures = harness._td_final_failures(
- receipt,
- label="td",
- expected_commit="a" * 8,
- )
- self.assertIn("td:structural_gate:cdc", failures)
- self.assertIn("td:structural_gate:fsm_encoding", failures)
- def test_package_selftest_rejects_a_different_verification_run(self) -> None:
- with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
- package = Path(temporary) / "package"
- materialize_valid_package(package)
- completed = subprocess.CompletedProcess(
- ["powershell.exe"], 0, stdout="selftest pass", stderr=""
- )
- with mock.patch.object(
- harness.subprocess,
- "run",
- return_value=completed,
- ):
- observed = harness.package_selftest_payload(
- package,
- verification_run_id="e" * 32,
- )
- self.assertEqual(observed["status"], "fail")
- self.assertIn(
- "verification_run_id_mismatch:package_info",
- observed["failures"],
- )
- def test_package_selftest_rejects_every_non_sha8_commit_form(self) -> None:
- invalid_commits = ("a" * 7, "a" * 9, "a" * 40, "ABCDEF12")
- for commit in invalid_commits:
- with self.subTest(commit=commit), tempfile.TemporaryDirectory(
- dir=ROOT.parent
- ) as temporary:
- digest = hashlib.sha256(b"invalid-commit-package").hexdigest()
- package = (
- Path(temporary)
- / commit
- / f"prod2u-p4-normal-{commit}-{digest[:16]}"
- )
- materialize_valid_package(
- package,
- bitstream_bytes=b"invalid-commit-package",
- commit=commit,
- )
- completed = subprocess.CompletedProcess(
- ["powershell.exe"], 0, stdout="selftest pass", stderr=""
- )
- with mock.patch.object(harness.subprocess, "run", return_value=completed):
- observed = harness.package_selftest_payload(
- package,
- verification_run_id=VERIFICATION_RUN_ID,
- )
- self.assertEqual(observed["status"], "fail")
- self.assertIn("package_commit_invalid", observed["failures"])
- def test_package_validator_preserves_running_but_final_gate_rejects_it(self) -> None:
- bitstream_bytes = b"running-validation-package"
- digest = hashlib.sha256(bitstream_bytes).hexdigest()
- commit = "a" * 8
- with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
- package = (
- Path(temporary)
- / commit
- / f"prod2u-p4-normal-{commit}-{digest[:16]}"
- )
- receipt, _, _ = materialize_valid_package(
- package,
- bitstream_bytes=bitstream_bytes,
- commit=commit,
- )
- validation_path = package / "evidence" / "validation-summary.json"
- validation = json.loads(validation_path.read_text(encoding="utf-8"))
- validation["layers"]["td_confirmation"]["status"] = "running"
- validation_path.write_text(json.dumps(validation), encoding="utf-8")
- refresh_package_bindings(package, receipt)
- completed = subprocess.CompletedProcess(
- ["powershell.exe"], 0, stdout="selftest pass", stderr=""
- )
- with mock.patch.object(harness.subprocess, "run", return_value=completed):
- observed = harness.package_selftest_payload(
- package,
- verification_run_id=VERIFICATION_RUN_ID,
- )
- self.assertEqual(observed["status"], "pass", observed["failures"])
- self.assertEqual(observed["validation_status"], "running")
- receipt.update(observed)
- failures = harness._package_final_failures(
- receipt,
- expected_commit=commit,
- expected_bitstream_sha256=digest,
- expected_primary_td_receipt_sha256=str(receipt["td_receipt_sha256"]),
- expected_confirmation_td_receipt_sha256=str(
- receipt["confirmation_td_receipt_sha256"]
- ),
- )
- self.assertIn("package:validation_incomplete", failures)
- def test_package_selftest_rejects_non_independent_td_receipts(self) -> None:
- cases = (
- ("run_id", "td_run_id_not_independent"),
- ("work_root", "td_work_root_not_independent"),
- )
- for field, failure in cases:
- with self.subTest(field=field), tempfile.TemporaryDirectory(
- dir=ROOT.parent
- ) as temporary:
- commit = "a" * 8
- digest = hashlib.sha256(b"independent-package-selftest").hexdigest()
- package = (
- Path(temporary)
- / commit
- / f"prod2u-p4-normal-{commit}-{digest[:16]}"
- )
- receipt, primary, confirmation = materialize_valid_package(
- package,
- bitstream_bytes=b"independent-package-selftest",
- commit=commit,
- )
- confirmation[field] = primary[field]
- (package / "evidence" / "td-confirmation-receipt.json").write_text(
- json.dumps(confirmation),
- encoding="utf-8",
- )
- refresh_package_bindings(package, receipt)
- completed = subprocess.CompletedProcess(
- ["powershell.exe"], 0, stdout="selftest pass", stderr=""
- )
- with mock.patch.object(harness.subprocess, "run", return_value=completed):
- observed = harness.package_selftest_payload(
- package,
- verification_run_id=VERIFICATION_RUN_ID,
- )
- self.assertEqual(observed["status"], "fail")
- self.assertIn(failure, observed["failures"])
- def test_urgent_validator_allows_running_td_confirmation_only(self) -> None:
- bitstream_bytes = b"urgent-running-confirmation"
- digest = hashlib.sha256(bitstream_bytes).hexdigest()
- commit = "a" * 8
- with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
- package = (
- Path(temporary)
- / commit
- / f"prod2u-p4-normal-{commit}-{digest[:16]}"
- )
- receipt, _, _ = materialize_valid_package(
- package,
- bitstream_bytes=bitstream_bytes,
- commit=commit,
- )
- (package / "evidence" / "td-confirmation-receipt.json").unlink()
- info_path = package / "package-info.json"
- info = json.loads(info_path.read_text(encoding="utf-8"))
- info.update(
- {
- "delivery_mode": "urgent_single_td",
- "verification_complete": False,
- "confirmation_td_present": False,
- "confirmation_bitstream_sha256": None,
- "confirmation_synthesis_input_hash": None,
- }
- )
- info_path.write_text(json.dumps(info), encoding="utf-8")
- validation_path = package / "evidence" / "validation-summary.json"
- validation = json.loads(validation_path.read_text(encoding="utf-8"))
- validation.update(
- {
- "delivery_mode": "urgent_single_td",
- "verification_complete": False,
- "confirmation_td_present": False,
- }
- )
- validation["layers"]["td_confirmation"]["status"] = "running"
- for name in (
- "td_confirmation_artifacts",
- "td_confirmation_bitstream",
- "td_confirmation_synthesis",
- "td_confirmation_manifest",
- "resource_confirmation",
- ):
- validation["layers"][name]["status"] = "not_run"
- validation_path.write_text(json.dumps(validation), encoding="utf-8")
- refresh_package_bindings(package, receipt)
- completed = subprocess.CompletedProcess(
- ["powershell.exe"], 0, stdout="selftest pass", stderr=""
- )
- with mock.patch.object(harness.subprocess, "run", return_value=completed):
- observed = harness.package_selftest_payload(
- package,
- verification_run_id=VERIFICATION_RUN_ID,
- )
- self.assertEqual(observed["status"], "pass", observed["failures"])
- self.assertEqual(observed["validation_status"], "running")
- def test_final_gate_rejects_two_td_receipts_from_same_run_or_work_root(self) -> None:
- with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
- root = Path(temporary)
- bitstream = root / "td.bit"
- bitstream.write_bytes(b"two-build-final-gate")
- digest = harness.sha256_file(bitstream)
- package = root / "package"
- package_receipt, packaged_primary, packaged_confirmation = (
- materialize_valid_package(
- package,
- bitstream_bytes=bitstream.read_bytes(),
- )
- )
- primary = packaged_primary
- confirmation = copy.deepcopy(packaged_primary)
- packaged_confirmation = confirmation
- receipts = {
- "offline": valid_offline_receipt(),
- "td": primary,
- "td_confirmation": confirmation,
- "package": package_receipt,
- }
- paths = {}
- for name, payload in receipts.items():
- path = root / f"{name}.json"
- path.write_text(json.dumps(payload), encoding="utf-8")
- paths[name] = path
- args = argparse.Namespace(
- offline_receipt=paths["offline"],
- td_receipt=paths["td"],
- confirmation_td_receipt=paths["td_confirmation"],
- package_receipt=paths["package"],
- verification_run_id=VERIFICATION_RUN_ID,
- report_file=None,
- json=False,
- )
- with (
- mock.patch.object(
- harness,
- "source_state",
- return_value={"status": "pass", "commit": "a" * 8, "clean": True},
- ),
- mock.patch.object(harness, "_emit", side_effect=lambda payload, _args, _label: payload),
- ):
- rejected = harness.cmd_final_gate(args)
- self.assertEqual(rejected["status"], "fail")
- self.assertIn("td_run_id_not_independent", rejected["failures"])
- self.assertIn("td_work_root_not_independent", rejected["failures"])
- confirmation["run_id"] = "2" * 32
- confirmation["work_root"] = "C:/td-b"
- packaged_confirmation["run_id"] = confirmation["run_id"]
- packaged_confirmation["work_root"] = confirmation["work_root"]
- packaged_primary_path = package / "evidence" / "td-primary-receipt.json"
- packaged_confirmation_path = (
- package / "evidence" / "td-confirmation-receipt.json"
- )
- packaged_primary_path.write_text(
- json.dumps(packaged_primary), encoding="utf-8"
- )
- packaged_confirmation_path.write_text(
- json.dumps(packaged_confirmation), encoding="utf-8"
- )
- refresh_package_bindings(package, package_receipt)
- paths["package"].write_text(json.dumps(package_receipt), encoding="utf-8")
- paths["td_confirmation"].write_text(json.dumps(confirmation), encoding="utf-8")
- with (
- mock.patch.object(
- harness,
- "source_state",
- return_value={"status": "pass", "commit": "a" * 8, "clean": True},
- ),
- mock.patch.object(harness, "_emit", side_effect=lambda payload, _args, _label: payload),
- ):
- accepted = harness.cmd_final_gate(args)
- self.assertEqual(accepted["status"], "pass", accepted["failures"])
- confirmation["bitstream_sha256"] = "f" * 64
- paths["td_confirmation"].write_text(
- json.dumps(confirmation), encoding="utf-8"
- )
- with (
- mock.patch.object(
- harness,
- "source_state",
- return_value={"status": "pass", "commit": "a" * 8, "clean": True},
- ),
- mock.patch.object(
- harness,
- "_emit",
- side_effect=lambda payload, _args, _label: payload,
- ),
- ):
- bitstream_mismatch = harness.cmd_final_gate(args)
- self.assertEqual(bitstream_mismatch["status"], "fail")
- self.assertIn(
- "td_bitstream_sha256_mismatch",
- bitstream_mismatch["failures"],
- )
- confirmation["bitstream_sha256"] = digest
- paths["td_confirmation"].write_text(
- json.dumps(confirmation), encoding="utf-8"
- )
- with (
- mock.patch.object(
- harness,
- "source_state",
- return_value={"status": "fail", "commit": "a" * 8, "clean": False},
- ),
- mock.patch.object(harness, "_emit", side_effect=lambda payload, _args, _label: payload),
- ):
- dirty = harness.cmd_final_gate(args)
- self.assertEqual(dirty["status"], "fail")
- self.assertIn("final_source_state_not_clean", dirty["failures"])
- if __name__ == "__main__":
- unittest.main()
|