| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230 |
- #!/usr/bin/env python3
- """Contract-first checks for door-percent RTL and verification boundary."""
- from __future__ import annotations
- import json
- import re
- import tempfile
- import unittest
- import xml.etree.ElementTree as ET
- from pathlib import Path
- from tools.generate_project import generate_project, load_project, render_adc
- from tools.prod2u_p4_normal_v3_build import PRODUCTION_RTL_SOURCES
- ROOT = Path(__file__).resolve().parents[2]
- PROJECT_PATH = ROOT / "projects" / "prod2u-door-temp" / "project.json"
- MANIFEST_PATH = ROOT / "src" / "generated" / "td-source-manifest.json"
- TOP_PATH = ROOT / "src" / "top" / "prod2u_p4_normal_v3_top.v"
- ADC_PATH = ROOT / "constraints" / "prod2u_p4_normal_v3.adc"
- ACTIVE_LEGACY_SCAN_PATHS = (
- "src/generated/td-source-manifest.json",
- "src/modules/output_target_ram.v",
- "src/modules/pwm_scheduler.v",
- "src/modules/door_percent_planner.v",
- "src/modules/door_motion_controller.v",
- "src/project/command_controller.v",
- "src/project/project_adapter.v",
- "src/top/prod2u_p4_normal_v3_top.v",
- "tests/sim/pwm_scheduler_tb.v",
- "tests/sim/door_percent_planner_tb.v",
- "tests/sim/prod2u_p4_normal_v3_top_tb.v",
- "tests/formal/simple_frame_contract_formal.v",
- "tests/formal/simple_motor_temperature_contract_formal.v",
- "tests/cocotb/prod2u_door_temp_uart_top.v",
- "tests/cocotb/test_prod2u_door_temp_uart_e2e.py",
- )
- LEGACY_MARKERS = (
- re.compile(r"\bptc_count\s*=\s*24\b", re.IGNORECASE),
- re.compile(r"\bset_all_payload_length\s*=\s*30\b", re.IGNORECASE),
- re.compile(r"\b30[- ]byte(?:s)?\b", re.IGNORECASE),
- re.compile(r"\b(?:inlet|serial)[-_ ]motor\b", re.IGNORECASE),
- re.compile(r"\b(?:watchdog prohibited|no watchdog)\b", re.IGNORECASE),
- re.compile(r"\bptc(?:9|1[0-9]|2[0-4])\b", re.IGNORECASE),
- re.compile(r"\b0x1a\b", re.IGNORECASE),
- re.compile(r"\bintake_solenoid\b", re.IGNORECASE),
- re.compile(r"\bmotor_compat\b", re.IGNORECASE),
- re.compile(r"\bP4_FIXED_MOTOR_STEPS\b"),
- )
- def _read(relative: str) -> str:
- return (ROOT / relative).read_text(encoding="utf-8", errors="replace")
- def _flattened_top_level_io_bits(source: str) -> int:
- declaration = re.search(
- r"module\s+prod2u_p4_normal_v3_top\s*\((.*?)\);",
- source,
- flags=re.DOTALL,
- )
- if declaration is None:
- raise AssertionError("top module declaration missing")
- total = 0
- for match in re.finditer(
- r"\b(?:input|output|inout)\s+(?:wire\s+)?(?:\[(\d+):(\d+)\]\s+)?([A-Za-z_]\w*)",
- declaration.group(1),
- ):
- high, low = match.group(1), match.group(2)
- total += abs(int(high) - int(low)) + 1 if high is not None else 1
- return total
- class Phase2ContractTests(unittest.TestCase):
- def test_project_contract_has_exact_percent_values(self):
- project = load_project(PROJECT_PATH)
- outputs = project["outputs"]
- motors = project["motors"]
- protocol = project["protocol"]
- self.assertEqual(outputs["ptc_count"], len(outputs["ptc_channels"]))
- self.assertEqual(outputs["fan_count"], len(outputs["fan_channels"]))
- self.assertEqual(outputs["ptc_count"] + outputs["fan_count"], 12)
- self.assertEqual(outputs["pwm_phase_count"], 100)
- self.assertEqual(outputs["pwm_slot_clks"], 1042)
- self.assertAlmostEqual(outputs["pwm_actual_frequency_hz"], 19.993602047, places=9)
- self.assertEqual(motors["positioning"]["mode"], "percent_close")
- self.assertEqual(motors["positioning"]["percent_max"], 100)
- self.assertEqual(motors["execution"], "overlap")
- self.assertNotIn("fixed_steps", motors)
- self.assertNotIn("command_values", motors)
- self.assertEqual(protocol["set_all"]["payload_length"], 11)
- self.assertEqual(protocol["commands"]["get_motor_status"], 3)
- self.assertEqual(protocol["commands"]["motor_status_data"], 0x83)
- self.assertEqual(project["doors"]["door_axes"], ["x", "y", "z"])
- self.assertEqual(project["motors"]["count"], 3)
- self.assertEqual(project["watchdog"]["timeout_ticks"], 60000)
- def test_active_interface_matches_project_manifest_and_adc(self):
- project = load_project(PROJECT_PATH)
- expected_interface = tuple(render_adc(project))
- manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
- actual_manifest = tuple(
- (item["signal"], item["ball"]) for item in manifest["active_interface"]
- )
- self.assertEqual(actual_manifest, expected_interface)
- assignments = re.findall(
- r"set_pin_assignment\s+\{\s*([^}]+?)\s*\}\s+\{\s*LOCATION\s*=\s*([A-Z][0-9]+)",
- ADC_PATH.read_text(encoding="ascii"),
- )
- self.assertEqual(tuple((signal.strip(), ball) for signal, ball in assignments), expected_interface)
- self.assertEqual(len(assignments), 30)
- def test_top_has_30_flattened_io_bits_and_three_axis_ports(self):
- source = TOP_PATH.read_text(encoding="ascii")
- self.assertEqual(_flattened_top_level_io_bits(source), 30)
- for port in (
- "z_step", "z_dir", "x_limit_ls", "y_limit_hs", "z_limit_ls", "motor_en_n",
- ):
- self.assertIn(port, source)
- def test_all_source_lists_register_tick_watchdog_and_match(self):
- manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
- manifest_sources = tuple(manifest["sources"])
- self.assertEqual(manifest_sources, tuple(PRODUCTION_RTL_SOURCES))
- self.assertIn("src/modules/door_percent_planner.v", manifest_sources)
- self.assertIn("src/modules/door_motion_controller.v", manifest_sources)
- self.assertTrue(any("watchdog" in Path(path).stem.lower() for path in manifest_sources))
- tree = ET.parse(ROOT / "td" / "prod2u_p4_normal_v3.prj")
- project_sources = tuple(
- str(node.get("Path", "")).removeprefix("../")
- for node in tree.findall(".//Verilog/File")
- )
- self.assertEqual(project_sources, manifest_sources)
- syn = _read("td/syn/prod2u_p4_normal_v3.tcl")
- analyzed = tuple(re.findall(r"^analyze -file \{([^}]+)\}$", syn, flags=re.MULTILINE))
- self.assertEqual(analyzed, manifest_sources)
- def test_phase2_rtl_contains_percent_and_status_contracts(self):
- controller = _read("src/project/command_controller.v")
- planner = _read("src/modules/door_percent_planner.v")
- motion = _read("src/modules/door_motion_controller.v")
- self.assertIn("motor_request_valid", controller)
- self.assertIn("door_percent_z", controller)
- self.assertIn("GET_MOTOR_STATUS", controller.upper().replace("CMD_", ""))
- self.assertIn("status_capture", controller)
- self.assertIn("acc <= 8'd50", planner)
- self.assertIn("startup_complete", motion)
- self.assertIn("snap[0]", motion)
- def test_generated_outputs_are_byte_for_byte_deterministic(self):
- with tempfile.TemporaryDirectory() as first, tempfile.TemporaryDirectory() as second:
- generate_project(PROJECT_PATH, Path(first))
- generate_project(PROJECT_PATH, Path(second))
- first_files = {
- path.relative_to(Path(first)).as_posix(): path.read_bytes()
- for path in Path(first).rglob("*")
- if path.is_file()
- }
- second_files = {
- path.relative_to(Path(second)).as_posix(): path.read_bytes()
- for path in Path(second).rglob("*")
- if path.is_file()
- }
- self.assertEqual(first_files, second_files)
- def test_active_legacy_scan_has_no_unapproved_old_design_markers(self):
- violations = []
- for relative in ACTIVE_LEGACY_SCAN_PATHS:
- path = ROOT / relative
- self.assertTrue(path.is_file(), relative)
- content = path.read_text(encoding="utf-8", errors="replace")
- for marker in LEGACY_MARKERS:
- if marker.search(content):
- violations.append(f"{relative}:{marker.pattern}")
- self.assertEqual(violations, [])
- def test_formal_scripts_lower_processes_before_setundef(self):
- for relative in (
- "tests/formal/simple_frame_contract.sby",
- "tests/formal/simple_motor_temperature_contract.sby",
- "tests/formal/pwm_scheduler_contract.sby",
- "tests/formal/host_watchdog_contract.sby",
- "tests/formal/door_percent_planner.sby",
- ):
- source = _read(relative)
- self.assertIn("proc", source, relative)
- self.assertLess(source.index("proc"), source.index("setundef"), relative)
- def test_formal_wrappers_use_real_clock_reset_and_controlled_inputs(self):
- for path in sorted((ROOT / "tests/formal").glob("*_formal.v")):
- source = path.read_text(encoding="utf-8", errors="replace")
- with self.subTest(path=path.name):
- self.assertRegex(source, r"input\s+wire\s+clk\b")
- self.assertRegex(source, r"input\s+wire\s+rst_n\b")
- self.assertRegex(source, r"always\s*@\(posedge\s+clk\)")
- self.assertRegex(source, r"assume\s*\(")
- def test_production_boundary_sim_fixtures_cover_planner_and_watchdog(self):
- planner = _read("tests/sim/door_percent_planner_tb.v")
- watchdog = _read("tests/sim/host_watchdog_tb.v")
- pwm = _read("tests/sim/pwm_scheduler_tb.v")
- self.assertIn("run_case(13'd100, 8'd50, 13'd50)", planner)
- self.assertIn(".TIMEOUT_TICKS(20000)", watchdog)
- self.assertIn(".enable(enable)", watchdog)
- self.assertIn("19999", watchdog)
- self.assertRegex(pwm, r"one[- ]cycle|latency|registered", re.IGNORECASE)
- def test_formal_properties_cover_percent_safety_contract(self):
- sources = "\n".join(
- path.read_text(encoding="utf-8", errors="replace")
- for path in sorted((ROOT / "tests/formal").glob("*_formal.v"))
- )
- for marker in (
- "bad_crc",
- "wrong_length",
- "unknown_type",
- "watchdog",
- "door_percent_planner",
- "WATCHDOG_FAN_TARGET",
- "gated_step",
- "selected_limit",
- ):
- self.assertIn(marker, sources)
- if __name__ == "__main__":
- unittest.main()
|