#!/usr/bin/env python3 """Static contract checks for the Phase 3 formal harness quality boundary.""" from __future__ import annotations import json import os import re import unittest from collections.abc import Mapping from pathlib import Path ROOT = Path(__file__).resolve().parents[2] FORMAL_ROOT = ROOT / "tests" / "formal" def _formal_receipt_evidence_failures(receipt: Mapping[str, object]) -> list[str]: failures: list[str] = [] if receipt.get("status") != "pass": failures.append("receipt_status_not_pass") targets = receipt.get("targets") if not isinstance(targets, list): return failures + ["targets_missing_or_invalid"] for target_index, target in enumerate(targets): prefix = f"targets[{target_index}]" if not isinstance(target, Mapping): failures.append(f"{prefix}_invalid") continue if target.get("status") != "pass": failures.append(f"{prefix}_status_not_pass") task_results = target.get("task_results") if not isinstance(task_results, list): failures.append(f"{prefix}.task_results_missing_or_invalid") else: for task_index, task in enumerate(task_results): task_prefix = f"{prefix}.task_results[{task_index}]" if not isinstance(task, Mapping): failures.append(f"{task_prefix}_invalid") continue if task.get("status") != "PASS": failures.append(f"{task_prefix}_status_not_PASS") if not task.get("compiled_assertion_ids"): failures.append(f"{task_prefix}_compiled_assertion_ids_missing") if target.get("cover_required"): trace_files = target.get("trace_files") if not isinstance(trace_files, list): failures.append(f"{prefix}.trace_files_missing_or_invalid") trace_files = [] cover_hit_count = target.get("cover_hit_count") if not isinstance(cover_hit_count, int) or cover_hit_count <= 0: failures.append(f"{prefix}_cover_hit_count_invalid") elif cover_hit_count != len(trace_files): failures.append(f"{prefix}_cover_trace_count_mismatch") for trace_index, trace_path in enumerate(trace_files): if not isinstance(trace_path, str) or not Path(trace_path).exists(): failures.append(f"{prefix}.trace_files[{trace_index}]_missing") return failures def _read(relative: str) -> str: return (ROOT / relative).read_text(encoding="ascii") class Phase3FormalContractTests(unittest.TestCase): def test_formal_scripts_zero_undefined_values(self): for path in sorted(FORMAL_ROOT.glob("*.sby")): source = path.read_text(encoding="ascii") with self.subTest(path=path.name): self.assertIn("setundef -zero", source) self.assertNotIn("setundef -anyseq", source) def test_motor_wrapper_has_explicit_known_inputs_and_step_edge_model(self): source = _read("tests/formal/simple_motor_temperature_contract_formal.v") for signal in ("rst_n", "start", "active_mask", "dir_mask", "tick_500us", "abort"): self.assertRegex(source, rf"assume\s*\([^\n]*\b{signal}\b") self.assertRegex(source, r"initial\s+begin") self.assertRegex(source, r"assume\s*\(!?dut_rst_n\)") self.assertRegex(source, r"assume\s*\(\s*dut_rst_n\s*\)") self.assertIn("previous_step", source) self.assertIn("rising_edges", source) self.assertIn("$past(tick_500us)", source) self.assertRegex(source, r"assert\s*\([^\n]*rising_edges") def test_watchdog_wrapper_checks_effective_target_and_next_clock_motor_abort(self): source = _read("tests/formal/host_watchdog_contract_formal.v") self.assertIn("output_target_ram", source) self.assertIn("door_motor_engine", source) self.assertIn("WATCHDOG_PTC_TARGET", source) self.assertIn("WATCHDOG_FAN_TARGET", source) self.assertIn("timeout_seen", source) self.assertRegex(source, r"assert\s*\([^\n]*step[^\n]*2'b00") self.assertRegex(source, r"assert\s*\([^\n]*WATCHDOG_(?:PTC|FAN)_TARGET") def test_frame_command_wrapper_checks_invalid_get_feed_and_commit_invariants(self): source = _read("tests/formal/frame_command_contract_formal.v") for marker in ( "SCENARIO_BAD_OUTPUT", "SCENARIO_BAD_MOTOR", "target_wr_en", "temperature_start", "tx_start", "motor_start", "valid_set_all_commit", "invalid_frame", "byte_valid", ): self.assertIn(marker, source) self.assertRegex(source, r"assert\s*\([^\n]*invalid_frame") self.assertRegex(source, r"if\s*\(get_temperature\)") self.assertRegex(source, r"assert\s*\([^\n]*valid_set_all_commit") def test_frame_tx_wrapper_checks_accepted_byte_progression_without_duplicates(self): sby = _read("tests/formal/frame_tx_contract.sby") self.assertIn("mode bmc", sby) self.assertIn("depth 64", sby) source = _read("tests/formal/frame_tx_contract_formal.v") for marker in ( "accepted_byte_count", "expected_frame_byte", "duplicate", "$past(byte_valid && byte_ready)", "byte_valid && byte_ready", ): self.assertIn(marker, source) self.assertRegex(source, r"assert\s*\([^\n]*byte_data") self.assertRegex(source, r"assert\s*\([^\n]*accepted_byte_count") def test_formal_wrappers_have_real_stimulus_and_no_vacuous_constant_inputs(self): source = _read("tests/formal/simple_frame_contract_formal.v") self.assertIn("SCENARIO_VALID", source) self.assertIn("SCENARIO_BAD_CRC", source) self.assertIn("stream_index", source) self.assertIn("payload_value", source) self.assertNotIn("assume (byte_valid == 1'b0)", source) self.assertNotIn("assume (byte_data == 8'h00)", source) self.assertNotIn("assume (accept_enable == 1'b1)", source) def test_cocotb_cleans_clock_and_observer_tasks_with_stage_timeouts(self): source = _read("tests/cocotb/test_prod2u_door_temp_uart_e2e.py") self.assertIn("try:", source) self.assertIn("finally:", source) self.assertRegex(source, r"\.kill\(\)|\.cancel\(\)") self.assertIn("stage=", source) self.assertIn("byte_index=", source) def test_simulation_fixtures_cover_production_timeout_and_motor_boundaries(self): motor = _read("tests/sim/door_motor_engine_tb.v") watchdog = _read("tests/sim/host_watchdog_tb.v") self.assertIn(".FIXED_STEPS(450)", motor) self.assertIn("x_rises !== 450", motor) self.assertIn("y_rises !== 450", motor) self.assertIn(".TIMEOUT_TICKS(20000)", watchdog) self.assertIn("19999", watchdog) self.assertIn("20000", watchdog) def test_formal_receipt_runtime_evidence_contract(self): raw_path = os.environ.get("PROD2U_FORMAL_RECEIPT") if not raw_path: self.skipTest("PROD2U_FORMAL_RECEIPT is not set; no formal receipt to verify") receipt_path = Path(raw_path).expanduser() self.assertTrue(receipt_path.is_file(), f"formal receipt is missing: {receipt_path}") receipt = json.loads(receipt_path.read_text(encoding="utf-8")) failures = _formal_receipt_evidence_failures(receipt) self.assertEqual([], failures, "\n".join(failures)) if __name__ == "__main__": unittest.main()