test_6400_pi_differential.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. """L7 bit-exact differential checks against the thermal-control-lab model."""
  2. from __future__ import annotations
  3. from pathlib import Path
  4. import sys
  5. import cocotb
  6. from cocotb.triggers import FallingEdge, ReadOnly, RisingEdge, Timer, with_timeout
  7. ROOT = Path(__file__).resolve().parents[2]
  8. LAB_ROOT = ROOT.parent / "thermal-control-lab"
  9. if not LAB_ROOT.is_dir():
  10. raise RuntimeError(f"thermal-control-lab sibling is required for L7: {LAB_ROOT}")
  11. sys.path.insert(0, str(LAB_ROOT))
  12. from thermal_control_lab.fixed_point import ControllerBank, PIConfig # noqa: E402
  13. FULL_VALID = (1 << 24) - 1
  14. def raw_from_centi(value: int) -> int:
  15. if not 0 <= value <= 25_499:
  16. raise ValueError(f"BMC test temperature out of range: {value}")
  17. integer, fraction = divmod(value, 100)
  18. return (integer << 8) | fraction
  19. def errors_for(target_c: int, temperatures: list[int]) -> list[int]:
  20. return [target_c * 100 - value for value in temperatures]
  21. async def clock_cycles(dut, count: int) -> None:
  22. for _ in range(count):
  23. await RisingEdge(dut.sys_clk)
  24. async def wait_for(dut, predicate, *, cycles: int, label: str) -> None:
  25. for _ in range(cycles):
  26. await RisingEdge(dut.sys_clk)
  27. await ReadOnly()
  28. if predicate():
  29. return
  30. raise AssertionError(f"timeout waiting for {label}")
  31. async def load_temperatures(dut, temperatures: list[int]) -> None:
  32. assert len(temperatures) == 24
  33. await FallingEdge(dut.sys_clk)
  34. dut.bmc_wr_en.value = 1
  35. for index, value in enumerate(temperatures):
  36. dut.bmc_wr_index.value = index
  37. dut.bmc_wr_raw.value = raw_from_centi(value)
  38. await FallingEdge(dut.sys_clk)
  39. dut.bmc_wr_en.value = 0
  40. async def set_epoch(
  41. dut,
  42. epoch: int,
  43. temperatures: list[int],
  44. *,
  45. valid_mask: int = FULL_VALID,
  46. ) -> None:
  47. await load_temperatures(dut, temperatures)
  48. await FallingEdge(dut.sys_clk)
  49. dut.bmc_valid_mask_test.value = valid_mask
  50. dut.bmc_epoch_test.value = epoch & 0xFFFF
  51. async def wait_commit(dut, previous_count: int, label: str) -> None:
  52. await wait_for(
  53. dut,
  54. lambda: int(dut.commit_count_mon.value) > previous_count,
  55. cycles=500,
  56. label=label,
  57. )
  58. async def read_outputs(dut) -> tuple[list[int], list[int], list[int], list[int]]:
  59. requested: list[int] = []
  60. applied: list[int] = []
  61. previous_error: list[int] = []
  62. previous_output: list[int] = []
  63. for index in range(32):
  64. await FallingEdge(dut.sys_clk)
  65. dut.rd_index.value = index
  66. await RisingEdge(dut.sys_clk)
  67. await ReadOnly()
  68. requested.append(int(dut.requested_data.value))
  69. applied.append(int(dut.applied_data.value))
  70. if index < 24:
  71. error = int(dut.previous_error_data.value)
  72. previous_error.append(error - 0x10000 if error & 0x8000 else error)
  73. previous_output.append(int(dut.previous_output_data.value))
  74. return requested, applied, previous_error, previous_output
  75. async def compare_epoch(
  76. dut,
  77. model: ControllerBank,
  78. epoch: int,
  79. temperatures: list[int],
  80. *,
  81. target_c: int = 70,
  82. valid_mask: int = FULL_VALID,
  83. override: list[bool] | None = None,
  84. expected_fans: list[int] | None = None,
  85. label: str,
  86. ) -> tuple[list[int], list[int]]:
  87. before = int(dut.commit_count_mon.value)
  88. await set_epoch(dut, epoch, temperatures, valid_mask=valid_mask)
  89. await wait_commit(dut, before, label)
  90. valid = [bool(valid_mask & (1 << index)) for index in range(24)]
  91. expected = model.update(
  92. epoch,
  93. errors_for(target_c, temperatures),
  94. valid,
  95. safety_override=override,
  96. )
  97. requested, applied, previous_error, previous_output = await read_outputs(dut)
  98. assert applied[:24] == expected, f"{label}: applied RTL/Python mismatch"
  99. assert all(0 <= value <= 100 for value in requested + applied)
  100. if override is None and valid_mask == FULL_VALID:
  101. assert requested[:24] == expected, f"{label}: requested RTL/Python mismatch"
  102. expected_state_error = [state.previous_error_centi for state in model.states]
  103. expected_state_output = [state.previous_output_q8_8 for state in model.states]
  104. assert previous_error == expected_state_error, f"{label}: error-state mismatch"
  105. assert previous_output == expected_state_output, f"{label}: output-state mismatch"
  106. fans = expected_fans or [30] * 8
  107. assert applied[24:] == fans, f"{label}: fan safety mismatch"
  108. return requested, applied
  109. async def bootstrap_auto(dut, temperatures: list[int], start_epoch: int = 1) -> int:
  110. await wait_for(
  111. dut,
  112. lambda: int(dut.control_state.value) == 2,
  113. cycles=50,
  114. label="PREHEAT_CT",
  115. )
  116. await set_epoch(dut, start_epoch, temperatures)
  117. await wait_for(
  118. dut,
  119. lambda: int(dut.control_state.value) == 3,
  120. cycles=50,
  121. label="WAIT_BMC_STABLE",
  122. )
  123. for epoch in (start_epoch + 1, start_epoch + 2):
  124. await set_epoch(dut, epoch, temperatures)
  125. await clock_cycles(dut, 8)
  126. return start_epoch + 3
  127. @cocotb.test()
  128. async def test_pi_python_rtl_differential_safety_epoch_target_and_recovery(dut):
  129. dut.tick_1s_test.value = 0
  130. dut.target_commit_test.value = 0
  131. dut.target_celsius_test.value = 70
  132. dut.bmc_epoch_test.value = 0
  133. dut.bmc_stale_test.value = 0
  134. dut.bmc_valid_mask_test.value = FULL_VALID
  135. dut.bmc_wr_en.value = 0
  136. dut.bmc_wr_index.value = 0
  137. dut.bmc_wr_raw.value = 0
  138. dut.ct_epoch_test.value = 1
  139. dut.ct_stale_test.value = 0
  140. dut.ct_valid_mask_test.value = (1 << 27) - 1
  141. dut.rd_index.value = 0
  142. await with_timeout(RisingEdge(dut.rst_n_mon), 1, "ms")
  143. model = ControllerBank(PIConfig(32, 4), PIConfig(24, 3))
  144. temperatures = [6500 + ((index * 37) % 400) for index in range(24)]
  145. epoch = await bootstrap_auto(dut, temperatures)
  146. await compare_epoch(dut, model, epoch, temperatures, label="initial mixed edge/center pass")
  147. # The same BMC epoch is a strict hold: no reintegration and no new bank flip.
  148. held_commit = int(dut.commit_count_mon.value)
  149. held_outputs = (await read_outputs(dut))[1]
  150. assert model.update(epoch, errors_for(70, temperatures), [True] * 24) == held_outputs[:24]
  151. await clock_cycles(dut, 300)
  152. assert int(dut.commit_count_mon.value) == held_commit
  153. assert (await read_outputs(dut))[1] == held_outputs
  154. # Mixed fractional errors cover both coefficient classes and half-away
  155. # rounding. Repeated cold epochs then hit slew and upper anti-windup.
  156. epoch += 1
  157. temperatures = [6999 - ((index * 7) % 180) for index in range(24)]
  158. await compare_epoch(dut, model, epoch, temperatures, label="fractional rounding")
  159. for iteration in range(24):
  160. epoch += 1
  161. temperatures = [2000 + ((index * 11 + iteration) % 90) for index in range(24)]
  162. await compare_epoch(dut, model, epoch, temperatures, label=f"positive slew {iteration}")
  163. assert max(model.outputs_q8_8) == 25_600
  164. # Hold at saturation, then prove the negative slew path is equally exact.
  165. for iteration in range(2):
  166. epoch += 1
  167. await compare_epoch(dut, model, epoch, temperatures, label=f"anti-windup hold {iteration}")
  168. for iteration in range(5):
  169. epoch += 1
  170. temperatures = [7399 - (index % 5) for index in range(24)]
  171. await compare_epoch(dut, model, epoch, temperatures, label=f"negative slew {iteration}")
  172. # A single invalid channel is off while its PI state freezes. When the
  173. # channel becomes valid, the Python and RTL paths resume from that state.
  174. invalid_mask = FULL_VALID ^ 1
  175. frozen_state = model.states[0]
  176. epoch += 1
  177. await compare_epoch(
  178. dut,
  179. model,
  180. epoch,
  181. temperatures,
  182. valid_mask=invalid_mask,
  183. label="single invalid freeze",
  184. )
  185. assert model.states[0] == frozen_state
  186. temperatures = [7100] * 24
  187. for iteration in range(3):
  188. epoch += 1
  189. await compare_epoch(dut, model, epoch, temperatures, label=f"invalid recovery {iteration}")
  190. assert int(dut.control_state.value) == 4
  191. # Pretrip clears one production controller, forces its PTC off, and raises
  192. # both lane fans. The reference is explicitly rebased for safe recovery.
  193. epoch += 1
  194. temperatures = [6900] * 24
  195. temperatures[6] = 7600
  196. override = [index == 6 for index in range(24)]
  197. await compare_epoch(
  198. dut,
  199. model,
  200. epoch,
  201. temperatures,
  202. override=override,
  203. expected_fans=[30, 80, 30, 30, 30, 80, 30, 30],
  204. label="76 C pretrip",
  205. )
  206. model.clear_channels([6])
  207. temperatures = [6900] * 24
  208. for iteration in range(3):
  209. epoch += 1
  210. await compare_epoch(dut, model, epoch, temperatures, label=f"pretrip recovery {iteration}")
  211. # A 77 C sample clamps and clears the complete six-channel lane. Three
  212. # safe epochs retain zero duty; the next epoch ramps from the cleared state.
  213. epoch += 1
  214. temperatures[12] = 7700
  215. lane_override = [12 <= index < 18 for index in range(24)]
  216. await compare_epoch(
  217. dut,
  218. model,
  219. epoch,
  220. temperatures,
  221. override=lane_override,
  222. expected_fans=[30, 30, 100, 30, 30, 30, 100, 30],
  223. label="77 C lane hard clamp",
  224. )
  225. assert int(dut.lane_fault_mask.value) & (1 << 2)
  226. model.clear_channels(range(12, 18))
  227. temperatures[12] = 6900
  228. for iteration in range(3):
  229. epoch += 1
  230. recovery_fans = (
  231. [30, 30, 100, 30, 30, 30, 100, 30]
  232. if iteration < 2
  233. else [30] * 8
  234. )
  235. await compare_epoch(
  236. dut,
  237. model,
  238. epoch,
  239. temperatures,
  240. override=lane_override,
  241. expected_fans=recovery_fans,
  242. label=f"hard-clamp recovery hold {iteration}",
  243. )
  244. assert int(dut.lane_fault_mask.value) == 0
  245. epoch += 1
  246. await compare_epoch(dut, model, epoch, temperatures, label="hard-clamp limited restart")
  247. # Runtime stale preempts without a new epoch, atomically fills 0/100 safe
  248. # outputs, and requires three fresh recovery epochs before limited restart.
  249. before = int(dut.commit_count_mon.value)
  250. await FallingEdge(dut.sys_clk)
  251. dut.bmc_stale_test.value = 1
  252. await wait_commit(dut, before, "global stale safe fill")
  253. _, stale_applied, _, _ = await read_outputs(dut)
  254. assert stale_applied == [0] * 24 + [100] * 8
  255. assert model.update(epoch, errors_for(70, temperatures), [True] * 24, stale=True) == [0] * 24
  256. model.stop()
  257. await FallingEdge(dut.sys_clk)
  258. dut.bmc_stale_test.value = 0
  259. all_override = [True] * 24
  260. for iteration in range(3):
  261. epoch += 1
  262. recovery_fans = [100] * 8 if iteration < 2 else [30] * 8
  263. await compare_epoch(
  264. dut,
  265. model,
  266. epoch,
  267. temperatures,
  268. override=all_override,
  269. expected_fans=recovery_fans,
  270. label=f"stale recovery hold {iteration}",
  271. )
  272. assert int(dut.global_fault.value) == 0
  273. epoch += 1
  274. await compare_epoch(dut, model, epoch, temperatures, label="stale limited restart")
  275. # Target changes clear the PI path, commit a safe image, and require the
  276. # CT/BMC qualification sequence before the new-target Python path runs.
  277. before = int(dut.commit_count_mon.value)
  278. await FallingEdge(dut.sys_clk)
  279. dut.target_celsius_test.value = 60
  280. dut.target_commit_test.value = 1
  281. await FallingEdge(dut.sys_clk)
  282. dut.target_commit_test.value = 0
  283. await wait_commit(dut, before, "target-change safe fill")
  284. assert (await read_outputs(dut))[1][:24] == [0] * 24
  285. model.stop()
  286. await FallingEdge(dut.sys_clk)
  287. dut.ct_epoch_test.value = 2
  288. temperatures = [5500 + (index % 20) for index in range(24)]
  289. next_epoch = await bootstrap_auto(dut, temperatures, start_epoch=epoch + 1)
  290. await compare_epoch(
  291. dut,
  292. model,
  293. next_epoch,
  294. temperatures,
  295. target_c=60,
  296. label="new-target qualified restart",
  297. )
  298. assert int(dut.current_target_celsius.value) == 60
  299. assert int(dut.control_state.value) == 4
  300. assert int(dut.work_state_mon.value) == 0