test_phase3_formal_contract.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. #!/usr/bin/env python3
  2. """Static contract checks for the Phase 3 formal harness quality boundary."""
  3. from __future__ import annotations
  4. import json
  5. import os
  6. import re
  7. import unittest
  8. from collections.abc import Mapping
  9. from pathlib import Path
  10. ROOT = Path(__file__).resolve().parents[2]
  11. FORMAL_ROOT = ROOT / "tests" / "formal"
  12. def _formal_receipt_evidence_failures(receipt: Mapping[str, object]) -> list[str]:
  13. failures: list[str] = []
  14. if receipt.get("status") != "pass":
  15. failures.append("receipt_status_not_pass")
  16. targets = receipt.get("targets")
  17. if not isinstance(targets, list):
  18. return failures + ["targets_missing_or_invalid"]
  19. for target_index, target in enumerate(targets):
  20. prefix = f"targets[{target_index}]"
  21. if not isinstance(target, Mapping):
  22. failures.append(f"{prefix}_invalid")
  23. continue
  24. if target.get("status") != "pass":
  25. failures.append(f"{prefix}_status_not_pass")
  26. task_results = target.get("task_results")
  27. if not isinstance(task_results, list):
  28. failures.append(f"{prefix}.task_results_missing_or_invalid")
  29. else:
  30. for task_index, task in enumerate(task_results):
  31. task_prefix = f"{prefix}.task_results[{task_index}]"
  32. if not isinstance(task, Mapping):
  33. failures.append(f"{task_prefix}_invalid")
  34. continue
  35. if task.get("status") != "PASS":
  36. failures.append(f"{task_prefix}_status_not_PASS")
  37. if not task.get("compiled_assertion_ids"):
  38. failures.append(f"{task_prefix}_compiled_assertion_ids_missing")
  39. if target.get("cover_required"):
  40. trace_files = target.get("trace_files")
  41. if not isinstance(trace_files, list):
  42. failures.append(f"{prefix}.trace_files_missing_or_invalid")
  43. trace_files = []
  44. cover_hit_count = target.get("cover_hit_count")
  45. if not isinstance(cover_hit_count, int) or cover_hit_count <= 0:
  46. failures.append(f"{prefix}_cover_hit_count_invalid")
  47. elif cover_hit_count != len(trace_files):
  48. failures.append(f"{prefix}_cover_trace_count_mismatch")
  49. for trace_index, trace_path in enumerate(trace_files):
  50. if not isinstance(trace_path, str) or not Path(trace_path).exists():
  51. failures.append(f"{prefix}.trace_files[{trace_index}]_missing")
  52. return failures
  53. def _read(relative: str) -> str:
  54. return (ROOT / relative).read_text(encoding="ascii")
  55. class Phase3FormalContractTests(unittest.TestCase):
  56. def test_formal_scripts_zero_undefined_values(self):
  57. for path in sorted(FORMAL_ROOT.glob("*.sby")):
  58. source = path.read_text(encoding="ascii")
  59. with self.subTest(path=path.name):
  60. self.assertIn("setundef -zero", source)
  61. self.assertNotIn("setundef -anyseq", source)
  62. def test_startup_and_runtime_limit_formal_assert_runtime_hard_stop(self):
  63. startup = _read("tests/formal/startup_close_seek_formal.v")
  64. runtime = _read("tests/formal/runtime_limit_hard_stop_formal.v")
  65. self.assertRegex(startup, r"assert\s*\(\s*motor_stop_mask\s*==\s*3'b000\s*\)")
  66. self.assertRegex(startup, r"\$past\(startup_done\)")
  67. self.assertIn("startup_done ? runtime_limit_stop_mask", runtime)
  68. self.assertRegex(runtime, r"assert\s*\(\s*motor_stop_mask\s*==\s*runtime_limit_stop_mask\s*\)")
  69. sby = _read("tests/formal/runtime_limit_hard_stop.sby")
  70. self.assertIn("mode bmc", sby)
  71. self.assertIn("setundef -zero", sby)
  72. self.assertLessEqual(int(re.search(r"depth\s+(\d+)", sby).group(1)), 64)
  73. def test_motor_wrapper_has_explicit_known_inputs_and_step_edge_model(self):
  74. source = _read("tests/formal/simple_motor_temperature_contract_formal.v")
  75. for signal in ("rst_n", "start", "active_mask", "dir_mask", "tick_500us", "abort"):
  76. self.assertRegex(source, rf"assume\s*\([^\n]*\b{signal}\b")
  77. self.assertRegex(source, r"initial\s+begin")
  78. self.assertRegex(source, r"assume\s*\(!?dut_rst_n\)")
  79. self.assertRegex(source, r"assume\s*\(\s*dut_rst_n\s*\)")
  80. self.assertIn("previous_step", source)
  81. self.assertIn("rising_edges", source)
  82. self.assertIn("$past(tick_500us)", source)
  83. self.assertRegex(source, r"assert\s*\([^\n]*rising_edges")
  84. def test_watchdog_wrapper_checks_effective_target_and_next_clock_motor_abort(self):
  85. source = _read("tests/formal/host_watchdog_contract_formal.v")
  86. self.assertIn("output_target_ram", source)
  87. self.assertIn("door_motor_engine", source)
  88. self.assertIn("WATCHDOG_PTC_TARGET", source)
  89. self.assertIn("WATCHDOG_FAN_TARGET", source)
  90. self.assertIn("timeout_seen", source)
  91. self.assertRegex(source, r"assert\s*\([^\n]*step[^\n]*2'b00")
  92. self.assertRegex(source, r"assert\s*\([^\n]*WATCHDOG_(?:PTC|FAN)_TARGET")
  93. def test_frame_command_wrapper_checks_invalid_get_feed_and_commit_invariants(self):
  94. source = _read("tests/formal/frame_command_contract_formal.v")
  95. for marker in (
  96. "SCENARIO_BAD_OUTPUT",
  97. "SCENARIO_BAD_MOTOR",
  98. "target_wr_en",
  99. "temperature_start",
  100. "tx_start",
  101. "motor_start",
  102. "valid_set_all_commit",
  103. "invalid_frame",
  104. "byte_valid",
  105. ):
  106. self.assertIn(marker, source)
  107. self.assertRegex(source, r"assert\s*\([^\n]*invalid_frame")
  108. self.assertRegex(source, r"if\s*\(get_temperature\)")
  109. self.assertRegex(source, r"assert\s*\([^\n]*valid_set_all_commit")
  110. def test_frame_tx_wrapper_checks_accepted_byte_progression_without_duplicates(self):
  111. sby = _read("tests/formal/frame_tx_contract.sby")
  112. self.assertIn("mode bmc", sby)
  113. self.assertRegex(sby, r"(?m)^bmc\s*$")
  114. self.assertNotRegex(sby, r"(?m)^prove\s*$")
  115. # BMC depth kept at 64 for host-feasible closed-loop runs (Mem≈2GiB);
  116. # assertions themselves are unchanged. Prefer bitwuzla when available.
  117. depth_match = re.search(r"(?m)^depth\s+(\d+)\s*$", sby)
  118. self.assertIsNotNone(depth_match, "frame_tx_contract.sby missing depth")
  119. self.assertEqual(int(depth_match.group(1)), 64)
  120. self.assertIn("smtbmc bitwuzla", sby)
  121. source = _read("tests/formal/frame_tx_contract_formal.v")
  122. for marker in (
  123. "accepted_byte_count",
  124. "expected_frame_byte",
  125. "duplicate",
  126. "$past(byte_valid && byte_ready)",
  127. "byte_valid && byte_ready",
  128. ):
  129. self.assertIn(marker, source)
  130. self.assertRegex(source, r"assert\s*\([^\n]*byte_data")
  131. self.assertRegex(source, r"assert\s*\([^\n]*accepted_byte_count")
  132. def test_bmc_targets_name_tasks_bmc_not_prove(self):
  133. """Receipt honesty: BMC .sby tasks must not be labeled prove."""
  134. for relative in (
  135. "tests/formal/frame_command_contract.sby",
  136. "tests/formal/frame_tx_contract.sby",
  137. "tests/formal/simple_frame_contract.sby",
  138. "tests/formal/startup_close_seek.sby",
  139. "tests/formal/runtime_limit_hard_stop.sby",
  140. "tests/formal/door_action_dispatcher_axis3.sby",
  141. ):
  142. sby = _read(relative)
  143. with self.subTest(relative=relative):
  144. self.assertIn("mode bmc", sby)
  145. self.assertRegex(sby, r"(?m)^bmc\s*$")
  146. self.assertNotRegex(sby, r"(?m)^prove\s*$")
  147. def test_priority_formal_targets_require_cover_nonvacuity(self):
  148. for relative in (
  149. "tests/formal/startup_close_seek.sby",
  150. "tests/formal/runtime_limit_hard_stop.sby",
  151. "tests/formal/simple_frame_contract.sby",
  152. "tests/formal/door_action_dispatcher_axis3.sby",
  153. ):
  154. sby = _read(relative)
  155. with self.subTest(relative=relative):
  156. self.assertRegex(sby, r"(?m)^cover\s*$")
  157. self.assertIn("mode cover", sby)
  158. # frame_command keeps cover() in the wrapper for non-vacuity review, but the
  159. # registered sby task stays BMC-only on low-memory hosts (depth-96 cover OOMs).
  160. self.assertIn("cover (", _read("tests/formal/frame_command_contract_formal.v"))
  161. frame_cmd = _read("tests/formal/frame_command_contract.sby")
  162. self.assertRegex(frame_cmd, r"(?m)^bmc\s*$")
  163. self.assertNotRegex(frame_cmd, r"(?m)^cover\s*$")
  164. def test_formal_wrappers_have_real_stimulus_and_no_vacuous_constant_inputs(self):
  165. source = _read("tests/formal/simple_frame_contract_formal.v")
  166. self.assertIn("SCENARIO_VALID", source)
  167. self.assertIn("SCENARIO_BAD_CRC", source)
  168. self.assertIn("stream_index", source)
  169. self.assertIn("payload_value", source)
  170. self.assertNotIn("assume (byte_valid == 1'b0)", source)
  171. self.assertNotIn("assume (byte_data == 8'h00)", source)
  172. self.assertNotIn("assume (accept_enable == 1'b1)", source)
  173. def test_cocotb_cleans_clock_and_observer_tasks_with_stage_timeouts(self):
  174. source = _read("tests/cocotb/test_prod2u_door_temp_uart_e2e.py")
  175. self.assertIn("try:", source)
  176. self.assertIn("finally:", source)
  177. self.assertRegex(source, r"\.kill\(\)|\.cancel\(\)")
  178. self.assertIn("stage=", source)
  179. self.assertIn("byte_index=", source)
  180. def test_simulation_fixtures_cover_production_timeout_and_motor_boundaries(self):
  181. motor = _read("tests/sim/door_motor_engine_tb.v")
  182. watchdog = _read("tests/sim/host_watchdog_tb.v")
  183. self.assertIn("HOST_STEPS = 450", motor)
  184. self.assertIn("x_rises !== HOST_STEPS", motor)
  185. self.assertIn("y_rises !== HOST_STEPS", motor)
  186. self.assertIn(".TIMEOUT_TICKS(20000)", watchdog)
  187. self.assertIn("19999", watchdog)
  188. self.assertIn("20000", watchdog)
  189. def test_formal_receipt_runtime_evidence_contract(self):
  190. raw_path = os.environ.get("PROD2U_FORMAL_RECEIPT")
  191. if not raw_path:
  192. self.skipTest("PROD2U_FORMAL_RECEIPT is not set; no formal receipt to verify")
  193. receipt_path = Path(raw_path).expanduser()
  194. self.assertTrue(receipt_path.is_file(), f"formal receipt is missing: {receipt_path}")
  195. receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
  196. failures = _formal_receipt_evidence_failures(receipt)
  197. self.assertEqual([], failures, "\n".join(failures))
  198. if __name__ == "__main__":
  199. unittest.main()