test_phase2_contract.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. #!/usr/bin/env python3
  2. """Contract-first checks for door-percent RTL and verification boundary."""
  3. from __future__ import annotations
  4. import json
  5. import re
  6. import tempfile
  7. import unittest
  8. import xml.etree.ElementTree as ET
  9. from pathlib import Path
  10. from tools.generate_project import generate_project, load_project, render_adc
  11. from tools.prod2u_p4_normal_v3_build import PRODUCTION_RTL_SOURCES
  12. ROOT = Path(__file__).resolve().parents[2]
  13. PROJECT_PATH = ROOT / "projects" / "prod2u-door-temp" / "project.json"
  14. MANIFEST_PATH = ROOT / "src" / "generated" / "td-source-manifest.json"
  15. TOP_PATH = ROOT / "src" / "top" / "prod2u_p4_normal_v3_top.v"
  16. ADC_PATH = ROOT / "constraints" / "prod2u_p4_normal_v3.adc"
  17. ACTIVE_LEGACY_SCAN_PATHS = (
  18. "src/generated/td-source-manifest.json",
  19. "src/modules/output_target_ram.v",
  20. "src/modules/pwm_scheduler.v",
  21. "src/modules/door_percent_planner.v",
  22. "src/modules/door_motion_controller.v",
  23. "src/project/command_controller.v",
  24. "src/project/project_adapter.v",
  25. "src/top/prod2u_p4_normal_v3_top.v",
  26. "tests/sim/pwm_scheduler_tb.v",
  27. "tests/sim/door_percent_planner_tb.v",
  28. "tests/sim/prod2u_p4_normal_v3_top_tb.v",
  29. "tests/formal/simple_frame_contract_formal.v",
  30. "tests/formal/simple_motor_temperature_contract_formal.v",
  31. "tests/cocotb/prod2u_door_temp_uart_top.v",
  32. "tests/cocotb/test_prod2u_door_temp_uart_e2e.py",
  33. )
  34. LEGACY_MARKERS = (
  35. re.compile(r"\bptc_count\s*=\s*24\b", re.IGNORECASE),
  36. re.compile(r"\bset_all_payload_length\s*=\s*30\b", re.IGNORECASE),
  37. re.compile(r"\b30[- ]byte(?:s)?\b", re.IGNORECASE),
  38. re.compile(r"\b(?:inlet|serial)[-_ ]motor\b", re.IGNORECASE),
  39. re.compile(r"\b(?:watchdog prohibited|no watchdog)\b", re.IGNORECASE),
  40. re.compile(r"\bptc(?:9|1[0-9]|2[0-4])\b", re.IGNORECASE),
  41. re.compile(r"\b0x1a\b", re.IGNORECASE),
  42. re.compile(r"\bintake_solenoid\b", re.IGNORECASE),
  43. re.compile(r"\bmotor_compat\b", re.IGNORECASE),
  44. re.compile(r"\bP4_FIXED_MOTOR_STEPS\b"),
  45. )
  46. def _read(relative: str) -> str:
  47. return (ROOT / relative).read_text(encoding="utf-8", errors="replace")
  48. def _flattened_top_level_io_bits(source: str) -> int:
  49. declaration = re.search(
  50. r"module\s+prod2u_p4_normal_v3_top\s*\((.*?)\);",
  51. source,
  52. flags=re.DOTALL,
  53. )
  54. if declaration is None:
  55. raise AssertionError("top module declaration missing")
  56. total = 0
  57. for match in re.finditer(
  58. r"\b(?:input|output|inout)\s+(?:wire\s+)?(?:\[(\d+):(\d+)\]\s+)?([A-Za-z_]\w*)",
  59. declaration.group(1),
  60. ):
  61. high, low = match.group(1), match.group(2)
  62. total += abs(int(high) - int(low)) + 1 if high is not None else 1
  63. return total
  64. class Phase2ContractTests(unittest.TestCase):
  65. def test_project_contract_has_exact_percent_values(self):
  66. project = load_project(PROJECT_PATH)
  67. outputs = project["outputs"]
  68. motors = project["motors"]
  69. protocol = project["protocol"]
  70. self.assertEqual(outputs["ptc_count"], len(outputs["ptc_channels"]))
  71. self.assertEqual(outputs["fan_count"], len(outputs["fan_channels"]))
  72. self.assertEqual(outputs["ptc_count"] + outputs["fan_count"], 12)
  73. self.assertEqual(outputs["pwm_phase_count"], 100)
  74. self.assertEqual(outputs["pwm_slot_clks"], 1042)
  75. self.assertAlmostEqual(outputs["pwm_actual_frequency_hz"], 19.993602047, places=9)
  76. self.assertEqual(motors["positioning"]["mode"], "percent_close")
  77. self.assertEqual(motors["positioning"]["percent_max"], 100)
  78. self.assertEqual(motors["execution"], "overlap")
  79. self.assertNotIn("fixed_steps", motors)
  80. self.assertNotIn("command_values", motors)
  81. self.assertEqual(protocol["set_all"]["payload_length"], 11)
  82. self.assertEqual(protocol["commands"]["get_motor_status"], 3)
  83. self.assertEqual(protocol["commands"]["motor_status_data"], 0x83)
  84. self.assertEqual(project["doors"]["door_axes"], ["x", "y", "z"])
  85. self.assertEqual(project["motors"]["count"], 3)
  86. self.assertEqual(project["watchdog"]["timeout_ticks"], 60000)
  87. def test_active_interface_matches_project_manifest_and_adc(self):
  88. project = load_project(PROJECT_PATH)
  89. expected_interface = tuple(render_adc(project))
  90. manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
  91. actual_manifest = tuple(
  92. (item["signal"], item["ball"]) for item in manifest["active_interface"]
  93. )
  94. self.assertEqual(actual_manifest, expected_interface)
  95. assignments = re.findall(
  96. r"set_pin_assignment\s+\{\s*([^}]+?)\s*\}\s+\{\s*LOCATION\s*=\s*([A-Z][0-9]+)",
  97. ADC_PATH.read_text(encoding="ascii"),
  98. )
  99. self.assertEqual(tuple((signal.strip(), ball) for signal, ball in assignments), expected_interface)
  100. self.assertEqual(len(assignments), 30)
  101. def test_top_has_30_flattened_io_bits_and_three_axis_ports(self):
  102. source = TOP_PATH.read_text(encoding="ascii")
  103. self.assertEqual(_flattened_top_level_io_bits(source), 30)
  104. for port in (
  105. "z_step", "z_dir", "x_limit_ls", "y_limit_hs", "z_limit_ls", "motor_en_n",
  106. ):
  107. self.assertIn(port, source)
  108. def test_all_source_lists_register_tick_watchdog_and_match(self):
  109. manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
  110. manifest_sources = tuple(manifest["sources"])
  111. self.assertEqual(manifest_sources, tuple(PRODUCTION_RTL_SOURCES))
  112. self.assertIn("src/modules/door_percent_planner.v", manifest_sources)
  113. self.assertIn("src/modules/door_motion_controller.v", manifest_sources)
  114. self.assertTrue(any("watchdog" in Path(path).stem.lower() for path in manifest_sources))
  115. tree = ET.parse(ROOT / "td" / "prod2u_p4_normal_v3.prj")
  116. project_sources = tuple(
  117. str(node.get("Path", "")).removeprefix("../")
  118. for node in tree.findall(".//Verilog/File")
  119. )
  120. self.assertEqual(project_sources, manifest_sources)
  121. syn = _read("td/syn/prod2u_p4_normal_v3.tcl")
  122. analyzed = tuple(re.findall(r"^analyze -file \{([^}]+)\}$", syn, flags=re.MULTILINE))
  123. self.assertEqual(analyzed, manifest_sources)
  124. def test_phase2_rtl_contains_percent_and_status_contracts(self):
  125. controller = _read("src/project/command_controller.v")
  126. planner = _read("src/modules/door_percent_planner.v")
  127. motion = _read("src/modules/door_motion_controller.v")
  128. self.assertIn("motor_request_valid", controller)
  129. self.assertIn("door_percent_z", controller)
  130. self.assertIn("GET_MOTOR_STATUS", controller.upper().replace("CMD_", ""))
  131. self.assertIn("status_capture", controller)
  132. self.assertIn("acc <= 8'd50", planner)
  133. self.assertIn("startup_complete", motion)
  134. self.assertIn("snap[0]", motion)
  135. def test_generated_outputs_are_byte_for_byte_deterministic(self):
  136. with tempfile.TemporaryDirectory() as first, tempfile.TemporaryDirectory() as second:
  137. generate_project(PROJECT_PATH, Path(first))
  138. generate_project(PROJECT_PATH, Path(second))
  139. first_files = {
  140. path.relative_to(Path(first)).as_posix(): path.read_bytes()
  141. for path in Path(first).rglob("*")
  142. if path.is_file()
  143. }
  144. second_files = {
  145. path.relative_to(Path(second)).as_posix(): path.read_bytes()
  146. for path in Path(second).rglob("*")
  147. if path.is_file()
  148. }
  149. self.assertEqual(first_files, second_files)
  150. def test_active_legacy_scan_has_no_unapproved_old_design_markers(self):
  151. violations = []
  152. for relative in ACTIVE_LEGACY_SCAN_PATHS:
  153. path = ROOT / relative
  154. self.assertTrue(path.is_file(), relative)
  155. content = path.read_text(encoding="utf-8", errors="replace")
  156. for marker in LEGACY_MARKERS:
  157. if marker.search(content):
  158. violations.append(f"{relative}:{marker.pattern}")
  159. self.assertEqual(violations, [])
  160. def test_formal_scripts_lower_processes_before_setundef(self):
  161. for relative in (
  162. "tests/formal/simple_frame_contract.sby",
  163. "tests/formal/simple_motor_temperature_contract.sby",
  164. "tests/formal/pwm_scheduler_contract.sby",
  165. "tests/formal/host_watchdog_contract.sby",
  166. "tests/formal/door_percent_planner.sby",
  167. ):
  168. source = _read(relative)
  169. self.assertIn("proc", source, relative)
  170. self.assertLess(source.index("proc"), source.index("setundef"), relative)
  171. def test_formal_wrappers_use_real_clock_reset_and_controlled_inputs(self):
  172. for path in sorted((ROOT / "tests/formal").glob("*_formal.v")):
  173. source = path.read_text(encoding="utf-8", errors="replace")
  174. with self.subTest(path=path.name):
  175. self.assertRegex(source, r"input\s+wire\s+clk\b")
  176. self.assertRegex(source, r"input\s+wire\s+rst_n\b")
  177. self.assertRegex(source, r"always\s*@\(posedge\s+clk\)")
  178. self.assertRegex(source, r"assume\s*\(")
  179. def test_production_boundary_sim_fixtures_cover_planner_and_watchdog(self):
  180. planner = _read("tests/sim/door_percent_planner_tb.v")
  181. watchdog = _read("tests/sim/host_watchdog_tb.v")
  182. pwm = _read("tests/sim/pwm_scheduler_tb.v")
  183. self.assertIn("run_case(13'd100, 8'd50, 13'd50)", planner)
  184. self.assertIn(".TIMEOUT_TICKS(20000)", watchdog)
  185. self.assertIn(".enable(enable)", watchdog)
  186. self.assertIn("19999", watchdog)
  187. self.assertRegex(pwm, r"one[- ]cycle|latency|registered", re.IGNORECASE)
  188. def test_formal_properties_cover_percent_safety_contract(self):
  189. sources = "\n".join(
  190. path.read_text(encoding="utf-8", errors="replace")
  191. for path in sorted((ROOT / "tests/formal").glob("*_formal.v"))
  192. )
  193. for marker in (
  194. "bad_crc",
  195. "wrong_length",
  196. "unknown_type",
  197. "watchdog",
  198. "door_percent_planner",
  199. "WATCHDOG_FAN_TARGET",
  200. "gated_step",
  201. "selected_limit",
  202. ):
  203. self.assertIn(marker, sources)
  204. if __name__ == "__main__":
  205. unittest.main()