|
|
@@ -0,0 +1,250 @@
|
|
|
+#!/usr/bin/env python3
|
|
|
+"""Contract-first checks for the Phase 2 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_motor_engine.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_motor_engine_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"\bsolenoid_out\b|\bz_step\b|\bz_dir\b", re.IGNORECASE),
|
|
|
+ re.compile(r"\bptc(?:9|1[0-9]|2[0-4])\b", re.IGNORECASE),
|
|
|
+ re.compile(r"\b0x1a\b", re.IGNORECASE),
|
|
|
+)
|
|
|
+
|
|
|
+
|
|
|
+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_phase2_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["fixed_steps"], 450)
|
|
|
+ self.assertEqual(motors["execution"], "overlap")
|
|
|
+ self.assertEqual(motors["command_values"], [0, 1, 2])
|
|
|
+ self.assertEqual(protocol["set_all"]["payload_length"], 14)
|
|
|
+ self.assertEqual(protocol["set_all"]["fan_offset"], 8)
|
|
|
+ self.assertEqual(protocol["set_all"]["motor_x_offset"], 12)
|
|
|
+ self.assertEqual(protocol["set_all"]["motor_y_offset"], 13)
|
|
|
+
|
|
|
+ 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), 24)
|
|
|
+ self.assertEqual(len({ball for _, ball in assignments}), 24)
|
|
|
+ self.assertNotRegex(ADC_PATH.read_text(encoding="ascii"), r"(?i)ground|solenoid|z_step|z_dir|ptc9")
|
|
|
+
|
|
|
+ def test_top_has_24_flattened_io_bits_and_only_phase2_active_ports(self):
|
|
|
+ source = TOP_PATH.read_text(encoding="ascii")
|
|
|
+ declaration = re.search(
|
|
|
+ r"module\s+prod2u_p4_normal_v3_top\s*\((.*?)\);",
|
|
|
+ source,
|
|
|
+ flags=re.DOTALL,
|
|
|
+ )
|
|
|
+ self.assertIsNotNone(declaration)
|
|
|
+ ports = declaration.group(1)
|
|
|
+ self.assertEqual(_flattened_top_level_io_bits(source), 24)
|
|
|
+ expected = (
|
|
|
+ "sys_clk", "host_uart_rx", "host_uart_tx", "ptc_pwm_out",
|
|
|
+ "fan_pwm_out", "motor_en_n", "x_step", "x_dir", "y_step", "y_dir",
|
|
|
+ "x_limit_raw", "y_limit_raw", "temp_scl", "temp_sda",
|
|
|
+ )
|
|
|
+ for port in expected:
|
|
|
+ self.assertRegex(ports, rf"\b{re.escape(port)}\b")
|
|
|
+ self.assertRegex(ports, r"output\s+wire\s+\[7:0\]\s+ptc_pwm_out")
|
|
|
+ self.assertRegex(ports, r"output\s+wire\s+\[3:0\]\s+fan_pwm_out")
|
|
|
+ for retired in ("solenoid_out", "z_step", "z_dir"):
|
|
|
+ self.assertNotRegex(ports, rf"\b{retired}\b")
|
|
|
+
|
|
|
+ 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.assertEqual(len(manifest_sources), len(set(manifest_sources)))
|
|
|
+ self.assertTrue(any("tick" in Path(path).stem.lower() for path in 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_atomic_commit_busy_and_motor_contracts(self):
|
|
|
+ ram = _read("src/modules/output_target_ram.v")
|
|
|
+ scheduler = _read("src/modules/pwm_scheduler.v")
|
|
|
+ controller = _read("src/project/command_controller.v")
|
|
|
+ motor = _read("src/modules/door_motor_engine.v")
|
|
|
+ self.assertRegex(ram, r"\bcommit\b")
|
|
|
+ self.assertRegex(ram, r"shadow|active", re.IGNORECASE)
|
|
|
+ self.assertRegex(scheduler, r"logical_pwm_on")
|
|
|
+ self.assertRegex(scheduler, r"phase_count|PWM_PHASE_COUNT", re.IGNORECASE)
|
|
|
+ self.assertRegex(scheduler, r"duty\s*>\s*phase|selected.*>.*phase", re.IGNORECASE)
|
|
|
+ self.assertRegex(controller, r"valid_set_all_commit")
|
|
|
+ self.assertRegex(controller, r"busy")
|
|
|
+ self.assertNotRegex(controller, r"24\s*\+\s*output_index")
|
|
|
+ for signal in ("active_mask", "dir_mask", "tick_500us", "abort"):
|
|
|
+ self.assertRegex(motor, rf"\b{signal}\b")
|
|
|
+ self.assertRegex(motor, r"450|FIXED_STEPS")
|
|
|
+
|
|
|
+ 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",
|
|
|
+ ):
|
|
|
+ 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="ascii")
|
|
|
+ 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*\(")
|
|
|
+ self.assertNotRegex(source, r"reg\s+clk\b|reg\s+rst_n\b")
|
|
|
+
|
|
|
+ def test_formal_wrappers_do_not_replace_production_parameters_with_toy_values(self):
|
|
|
+ sources = "\n".join(
|
|
|
+ path.read_text(encoding="ascii")
|
|
|
+ for path in sorted((ROOT / "tests/formal").glob("*_formal.v"))
|
|
|
+ )
|
|
|
+ for forbidden in ("FIXED_STEPS(4)", "PWM_PHASE_COUNT(4)", "PWM_SLOT_CLKS(1)", "TIMEOUT_TICKS(4)"):
|
|
|
+ self.assertNotIn(forbidden, sources)
|
|
|
+ self.assertRegex(sources, r"FIXED_STEPS\s*=\s*450|P4_FIXED_MOTOR_STEPS|FIXED_STEPS\s*\)\s*motor")
|
|
|
+ self.assertRegex(sources, r"PWM_PHASE_COUNT\s*=\s*100|P4_PWM_PHASE_COUNT|PWM_PHASE_COUNT\s*\)")
|
|
|
+ self.assertRegex(sources, r"PWM_SLOT_CLKS\s*=\s*1042|P4_PWM_SLOT_CLKS|PWM_SLOT_CLKS\s*\)")
|
|
|
+
|
|
|
+ def test_formal_properties_cover_phase2_safety_contract(self):
|
|
|
+ sources = "\n".join(
|
|
|
+ path.read_text(encoding="ascii")
|
|
|
+ for path in sorted((ROOT / "tests/formal").glob("*_formal.v"))
|
|
|
+ )
|
|
|
+ for marker in (
|
|
|
+ "bad_crc",
|
|
|
+ "wrong_length",
|
|
|
+ "unknown_type",
|
|
|
+ "valid_set_all_commit",
|
|
|
+ "watchdog",
|
|
|
+ "active_mask",
|
|
|
+ "dir_mask",
|
|
|
+ "step",
|
|
|
+ "WATCHDOG_PTC_TARGET",
|
|
|
+ "WATCHDOG_FAN_TARGET",
|
|
|
+ "byte_ready",
|
|
|
+ "payload_index",
|
|
|
+ ):
|
|
|
+ self.assertIn(marker, sources)
|
|
|
+
|
|
|
+
|
|
|
+if __name__ == "__main__":
|
|
|
+ unittest.main()
|