test_alt_config_rtl_matrix.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. """Real RTL Icarus matrix for compile-time motor polarity / endpoint masks.
  2. Authority path (feature acceptance):
  3. temp project.json → public generate_project / CLI → temp generated params
  4. → compile real production RTL + real top + TB
  5. ``_render_params`` is not used here.
  6. """
  7. from __future__ import annotations
  8. import copy
  9. import itertools
  10. import json
  11. import os
  12. import subprocess
  13. import tempfile
  14. import unittest
  15. from pathlib import Path
  16. from tools.generate_project import generate_project, load_project
  17. from tools.prod2u_p4_harness import PRODUCTION_RTL_SOURCES, ROOT, resolve_tool
  18. POLARITY_TB = "prod2u_p4_alt_config_polarity_tb"
  19. STARTUP_TB = "prod2u_p4_alt_config_startup_tb"
  20. PROJECT_PATH = ROOT / "projects" / "prod2u-door-temp" / "project.json"
  21. def _write_alt_project(
  22. directory: Path,
  23. *,
  24. limit_active_high: list[bool],
  25. dir_close_level: list[int],
  26. close_limit_is_ls: list[bool],
  27. ) -> Path:
  28. """Deep-copy canonical project.json and mutate only the three public arrays."""
  29. project = json.loads(PROJECT_PATH.read_text(encoding="utf-8"))
  30. project["limits"]["limit_active_high"] = list(limit_active_high)
  31. project["motors"]["dir_close_level"] = list(dir_close_level)
  32. project["limits"]["close_limit_is_ls"] = list(close_limit_is_ls)
  33. # Leave legacy limits.active_level untouched (non-authoritative).
  34. path = directory / "project.json"
  35. path.write_text(json.dumps(project, indent=2) + "\n", encoding="utf-8")
  36. return path
  37. class AltConfigRtlMatrixTests(unittest.TestCase):
  38. @classmethod
  39. def setUpClass(cls) -> None:
  40. cls.iverilog = resolve_tool("iverilog")
  41. cls.vvp = resolve_tool("vvp")
  42. if not cls.iverilog or not cls.vvp:
  43. raise unittest.SkipTest("iverilog/vvp unavailable")
  44. # Confirm canonical load still works (defaults).
  45. cls.base_project = load_project(PROJECT_PATH)
  46. def _run_public_case(
  47. self,
  48. name: str,
  49. *,
  50. tb_name: str,
  51. limit_active_high: list[bool],
  52. dir_close_level: list[int],
  53. close_limit_is_ls: list[bool],
  54. timeout_s: int = 180,
  55. ) -> None:
  56. with tempfile.TemporaryDirectory(prefix=f"alt-rtl-{name}-") as tmp:
  57. tmp_path = Path(tmp)
  58. pj = _write_alt_project(
  59. tmp_path,
  60. limit_active_high=limit_active_high,
  61. dir_close_level=dir_close_level,
  62. close_limit_is_ls=close_limit_is_ls,
  63. )
  64. gen_out = tmp_path / "generated-out"
  65. # Public API path (not _render_params).
  66. generate_project(pj, gen_out)
  67. # Include layout: generated-out/generated/params.vh must win via
  68. # -I <include_root> where include_root/src/generated/... exists.
  69. include_root = tmp_path / "include"
  70. gen_dir = include_root / "src" / "generated"
  71. gen_dir.mkdir(parents=True)
  72. params_src = gen_out / "generated" / "prod2u_door_temp_params.vh"
  73. self.assertTrue(params_src.is_file(), params_src)
  74. (gen_dir / "prod2u_door_temp_params.vh").write_text(
  75. params_src.read_text(encoding="ascii"),
  76. encoding="ascii",
  77. )
  78. work = tmp_path / "work"
  79. work.mkdir()
  80. vvp_out = work / f"{tb_name}.vvp"
  81. # Omit checked-in params.vh so public-generate include_root is sole
  82. # authority (cwd=work → `include "src/generated/..."` hits -I first).
  83. sources = [
  84. str(ROOT / rel)
  85. for rel in PRODUCTION_RTL_SOURCES
  86. if Path(rel).name != "prod2u_door_temp_params.vh"
  87. ]
  88. sources.append(str(ROOT / "tests" / "sim" / f"{tb_name}.v"))
  89. compile_cmd = [
  90. str(self.iverilog),
  91. "-g2005-sv",
  92. "-I",
  93. str(include_root),
  94. "-I",
  95. str(ROOT),
  96. "-s",
  97. tb_name,
  98. "-o",
  99. str(vvp_out),
  100. *sources,
  101. ]
  102. compiled = subprocess.run(
  103. compile_cmd,
  104. cwd=work,
  105. text=True,
  106. stdout=subprocess.PIPE,
  107. stderr=subprocess.PIPE,
  108. check=False,
  109. timeout=120,
  110. )
  111. self.assertEqual(
  112. compiled.returncode,
  113. 0,
  114. f"{name}/{tb_name} iverilog failed:\n{compiled.stdout}\n{compiled.stderr}",
  115. )
  116. ran = subprocess.run(
  117. [str(self.vvp), str(vvp_out)],
  118. cwd=work,
  119. text=True,
  120. stdout=subprocess.PIPE,
  121. stderr=subprocess.PIPE,
  122. check=False,
  123. timeout=timeout_s,
  124. )
  125. self.assertEqual(
  126. ran.returncode,
  127. 0,
  128. f"{name}/{tb_name} vvp failed:\n{ran.stdout}\n{ran.stderr}",
  129. )
  130. self.assertIn(f"PASS {tb_name}", ran.stdout, ran.stdout)
  131. def _run_polarity(self, name: str, **kwargs) -> None:
  132. self._run_public_case(name, tb_name=POLARITY_TB, timeout_s=180, **kwargs)
  133. def _run_startup(self, name: str, **kwargs) -> None:
  134. # 5000+500 with force tick is heavier.
  135. self._run_public_case(name, tb_name=STARTUP_TB, timeout_s=600, **kwargs)
  136. def test_default_production_masks_rtl(self) -> None:
  137. self._run_polarity(
  138. "all_default",
  139. limit_active_high=[True, True, True],
  140. dir_close_level=[1, 1, 1],
  141. close_limit_is_ls=[True, True, True],
  142. )
  143. def test_single_axis_x_2x2x2_matrix(self) -> None:
  144. """Eight X-axis configs; Y/Z stay production default."""
  145. for ah, dcl, cls in itertools.product((False, True), (0, 1), (False, True)):
  146. name = f"x_ah{int(ah)}_dcl{dcl}_cls{int(cls)}"
  147. with self.subTest(name=name):
  148. self._run_polarity(
  149. name,
  150. limit_active_high=[ah, True, True],
  151. dir_close_level=[dcl, 1, 1],
  152. close_limit_is_ls=[cls, True, True],
  153. )
  154. def test_all_active_low(self) -> None:
  155. self._run_polarity(
  156. "all_active_low",
  157. limit_active_high=[False, False, False],
  158. dir_close_level=[1, 1, 1],
  159. close_limit_is_ls=[True, True, True],
  160. )
  161. def test_dir_all_invert(self) -> None:
  162. self._run_polarity(
  163. "dir_all_invert",
  164. limit_active_high=[True, True, True],
  165. dir_close_level=[0, 0, 0],
  166. close_limit_is_ls=[True, True, True],
  167. )
  168. def test_ls_hs_all_swap(self) -> None:
  169. self._run_polarity(
  170. "ls_hs_all_swap",
  171. limit_active_high=[True, True, True],
  172. dir_close_level=[1, 1, 1],
  173. close_limit_is_ls=[False, False, False],
  174. )
  175. def test_all_three_inverted(self) -> None:
  176. self._run_polarity(
  177. "all_three_inverted",
  178. limit_active_high=[False, False, False],
  179. dir_close_level=[0, 0, 0],
  180. close_limit_is_ls=[False, False, False],
  181. )
  182. def test_mixed_xyz_asymmetric(self) -> None:
  183. """X default / Y active-low+DIR invert / Z LS-HS swap (bit order check)."""
  184. self._run_polarity(
  185. "mixed_xyz",
  186. limit_active_high=[True, False, True],
  187. dir_close_level=[1, 0, 1],
  188. close_limit_is_ls=[True, True, False],
  189. )
  190. # --- Startup 5000+500 behavioral matrix (public generate path) ---
  191. def test_startup_default(self) -> None:
  192. self._run_startup(
  193. "startup_default",
  194. limit_active_high=[True, True, True],
  195. dir_close_level=[1, 1, 1],
  196. close_limit_is_ls=[True, True, True],
  197. )
  198. def test_startup_all_active_low(self) -> None:
  199. self._run_startup(
  200. "startup_all_active_low",
  201. limit_active_high=[False, False, False],
  202. dir_close_level=[1, 1, 1],
  203. close_limit_is_ls=[True, True, True],
  204. )
  205. def test_startup_ls_hs_swap(self) -> None:
  206. self._run_startup(
  207. "startup_ls_hs_swap",
  208. limit_active_high=[True, True, True],
  209. dir_close_level=[1, 1, 1],
  210. close_limit_is_ls=[False, False, False],
  211. )
  212. def test_startup_dir_invert(self) -> None:
  213. self._run_startup(
  214. "startup_dir_invert",
  215. limit_active_high=[True, True, True],
  216. dir_close_level=[0, 0, 0],
  217. close_limit_is_ls=[True, True, True],
  218. )
  219. def test_startup_mixed_xyz(self) -> None:
  220. self._run_startup(
  221. "startup_mixed_xyz",
  222. limit_active_high=[True, False, True],
  223. dir_close_level=[1, 0, 1],
  224. close_limit_is_ls=[True, True, False],
  225. )
  226. class AltConfigPublicCliTests(unittest.TestCase):
  227. """Python/CLI-only — must run even when Icarus is unavailable."""
  228. def test_public_cli_generates_alt_params_for_rtl(self) -> None:
  229. """CLI path (not only Python API) must feed the same include layout."""
  230. import sys
  231. with tempfile.TemporaryDirectory(prefix="alt-cli-") as tmp:
  232. tmp_path = Path(tmp)
  233. pj = _write_alt_project(
  234. tmp_path,
  235. limit_active_high=[False, True, True],
  236. dir_close_level=[1, 1, 1],
  237. close_limit_is_ls=[True, True, True],
  238. )
  239. out = tmp_path / "out"
  240. proc = subprocess.run(
  241. [sys.executable, str(ROOT / "tools" / "generate_project.py"), str(pj), str(out)],
  242. capture_output=True,
  243. text=True,
  244. check=False,
  245. )
  246. self.assertEqual(proc.returncode, 0, proc.stderr or proc.stdout)
  247. params = (out / "generated" / "prod2u_door_temp_params.vh").read_text(encoding="ascii")
  248. self.assertIn("`define P4_LIMIT_ACTIVE_HIGH_MASK 3'b110", params)
  249. class AltConfigFormalNormalizeTests(unittest.TestCase):
  250. """BMC/cover only — never claim infinite prove for alt-config normalize."""
  251. def test_alt_config_normalize_bmc_cover(self) -> None:
  252. sby = resolve_tool("sby")
  253. if not sby:
  254. candidate = Path("/data/prod2u/oss-cad-suite/latest/bin/sby")
  255. sby = str(candidate) if candidate.is_file() else None
  256. if not sby:
  257. self.skipTest("sby unavailable")
  258. formal_dir = ROOT / "tests" / "formal"
  259. sby_path = formal_dir / "alt_config_limit_normalize.sby"
  260. self.assertTrue(sby_path.is_file(), sby_path)
  261. env = os.environ.copy()
  262. oss_bin = str(Path(sby).resolve().parent)
  263. env["PATH"] = oss_bin + os.pathsep + env.get("PATH", "")
  264. env.pop("LD_LIBRARY_PATH", None)
  265. env.pop("LD_PRELOAD", None)
  266. env.pop("QT_PLUGIN_PATH", None)
  267. tmp_root = Path(os.environ.get("TMPDIR", "/tmp"))
  268. for task in ("bmc", "cover"):
  269. with self.subTest(task=task):
  270. # Isolate SBY workdirs under TMPDIR — never pollute tests/formal.
  271. work = Path(
  272. tempfile.mkdtemp(
  273. prefix=f"prod2u-sby-alt-config-{task}-",
  274. dir=str(tmp_root),
  275. )
  276. )
  277. completed = subprocess.run(
  278. [sby, "-f", "-d", str(work), str(sby_path), task],
  279. cwd=formal_dir,
  280. text=True,
  281. stdout=subprocess.PIPE,
  282. stderr=subprocess.STDOUT,
  283. check=False,
  284. timeout=300,
  285. env=env,
  286. )
  287. self.assertEqual(
  288. completed.returncode,
  289. 0,
  290. f"sby {task} failed:\n{completed.stdout}",
  291. )
  292. # Honesty: this is BMC/cover depth-bounded, not unbounded proof.
  293. self.assertNotIn("UNBOUNDED PROOF", completed.stdout.upper())
  294. self.assertNotIn("prove", task)
  295. self.assertTrue(
  296. str(work.resolve()).startswith(str(tmp_root.resolve())),
  297. f"sby workdir not under TMPDIR: {work}",
  298. )
  299. self.assertTrue(
  300. (work / "PASS").is_file(),
  301. f"missing PASS marker in isolated workdir {work}\n{completed.stdout}",
  302. )
  303. def test_formal_model_structurally_tracks_top(self) -> None:
  304. """Helper BMC model must keep the same normalize identifiers as real top.
  305. Formal evidence type remains BMC/cover only — not unbounded proof and not
  306. a substitute for the real-top Icarus matrix above.
  307. """
  308. top = (ROOT / "src" / "top" / "prod2u_p4_normal_v3_top.v").read_text(
  309. encoding="utf-8"
  310. )
  311. formal = (
  312. ROOT / "tests" / "formal" / "alt_config_limit_normalize_formal.v"
  313. ).read_text(encoding="utf-8")
  314. # Top uses localparam names; formal shell uses lowercase ports that
  315. # mirror the same normalize / selected_limit / DIR edge equations.
  316. for needle in (
  317. "selected_limit",
  318. "close_limit",
  319. "open_limit",
  320. "ls_reached",
  321. "hs_reached",
  322. ):
  323. self.assertIn(needle, top)
  324. self.assertIn(needle, formal)
  325. self.assertIn("LIMIT_ACTIVE_HIGH", top)
  326. self.assertIn("limit_active_high", formal)
  327. self.assertIn("DIR_CLOSE_LEVEL", top)
  328. self.assertIn("dir_close_level", formal)
  329. self.assertIn("CLOSE_LIMIT_IS_LS", top)
  330. self.assertIn("close_limit_is_ls", formal)
  331. self.assertIn("BMC/cover only", formal)
  332. if __name__ == "__main__":
  333. unittest.main()