| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545 |
- #!/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_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"},
- }
- UART_ONLY_CDC_REGISTERS = frozenset(
- {
- "u_uart_rx/rx_sync_pipe[0]",
- "u_uart_rx/rx_sync_pipe[1]",
- }
- )
- UART_ONLY_CDC_ENDPOINTS = frozenset({"u_uart_rx/rx_sync_pipe[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": 2},
- "input_registers": {"used": 0},
- "retained_sync_registers": {"used": 2},
- "first_stage_endpoints": {"used": 1},
- },
- "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_only_synchronizers(self) -> None:
- uart_only_report = {
- "retained_sync_registers": sorted(UART_ONLY_CDC_REGISTERS),
- "false_path_endpoints": sorted(UART_ONLY_CDC_ENDPOINTS),
- "source_only_false_paths": [],
- "structural_failures": [],
- }
- accepted = harness.structural_cdc_gate(
- uart_only_report,
- async_reg_count=2,
- input_register_count=0,
- )
- self.assertEqual(accepted["status"], "pass", accepted["failures"])
- def test_cdc_gate_rejects_legacy_limit_synchronizers(self) -> None:
- legacy_registers = sorted(
- UART_ONLY_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(
- UART_ONLY_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=8,
- 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", "temperature", "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()
|