test_6400_v1_host_protocol_integration.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. """Randomized full-UART Host framing and resynchronization coverage."""
  2. from __future__ import annotations
  3. from dataclasses import dataclass
  4. import warnings
  5. import cocotb
  6. from cocotb.triggers import RisingEdge, Timer, with_timeout
  7. from hypothesis import HealthCheck, given, settings, strategies as st
  8. from hypothesis.errors import HypothesisSideeffectWarning
  9. from thermal_6400_uart import (
  10. CLOCK_NS,
  11. HOST_CLKS_PER_BIT,
  12. SET_TARGET,
  13. SET_TARGET_ACK,
  14. clock_cycles,
  15. crc16,
  16. encode_frame,
  17. receive_frame,
  18. send_uart,
  19. wait_for,
  20. )
  21. @dataclass(frozen=True)
  22. class FrameCase:
  23. frame_type: int
  24. declared_length: int
  25. payload: bytes
  26. good_crc: bool
  27. @property
  28. def accepted_target(self) -> int | None:
  29. if not self.good_crc or self.frame_type != SET_TARGET or self.declared_length != 1:
  30. return None
  31. target = self.payload[0]
  32. return target if target == 0 or 20 <= target <= 70 else None
  33. def encode(self) -> bytes:
  34. body = bytes((self.frame_type, self.declared_length)) + self.payload
  35. checksum = crc16(body)
  36. if not self.good_crc:
  37. checksum ^= 0x0001
  38. return b"\xA5\x5A" + body + checksum.to_bytes(2, "little")
  39. @st.composite
  40. def frame_cases(draw) -> FrameCase:
  41. frame_type = draw(st.sampled_from((0x00, 0x01, 0x04, 0x7F, 0x80, 0x81, 0xFF)))
  42. declared_length = draw(st.integers(min_value=0, max_value=255))
  43. if declared_length <= 33:
  44. payload = draw(st.binary(min_size=declared_length, max_size=declared_length))
  45. else:
  46. # RTL rejects the oversized declaration before consuming payload. A
  47. # bounded tail exercises recovery without letting an embedded header
  48. # become a separate, accidental test case.
  49. tail = draw(st.binary(min_size=0, max_size=12))
  50. payload = tail.replace(b"\xA5", b"\xA4")
  51. return FrameCase(frame_type, declared_length, payload, draw(st.booleans()))
  52. def generated_cases() -> list[FrameCase]:
  53. values: list[FrameCase] = []
  54. @settings(
  55. max_examples=96,
  56. derandomize=True,
  57. database=None,
  58. deadline=None,
  59. suppress_health_check=(HealthCheck.too_slow,),
  60. )
  61. @given(frame_cases())
  62. def collect(value: FrameCase) -> None:
  63. values.append(value)
  64. # Cocotb imports tests through its pytest plugin, then invokes this
  65. # collector deliberately from the running coroutine. Hypothesis warns
  66. # about any strategy evaluation in plugin-owned code even though this is
  67. # the test body and the database/storage are both isolated.
  68. with warnings.catch_warnings():
  69. warnings.simplefilter("ignore", HypothesisSideeffectWarning)
  70. collect()
  71. return values
  72. async def send_uart_with_period(signal, data: bytes, clocks_per_bit: int) -> None:
  73. for value in data:
  74. signal.value = 0
  75. await Timer(clocks_per_bit * CLOCK_NS, units="ns")
  76. for bit in range(8):
  77. signal.value = (value >> bit) & 1
  78. await Timer(clocks_per_bit * CLOCK_NS, units="ns")
  79. signal.value = 1
  80. await Timer(clocks_per_bit * CLOCK_NS, units="ns")
  81. async def send_uart_jittered(signal, data: bytes) -> None:
  82. periods = (27, 26, 28, 27, 28, 26, 27, 26, 28, 27)
  83. for value in data:
  84. bits = (0, *((value >> bit) & 1 for bit in range(8)), 1)
  85. for level, clocks in zip(bits, periods, strict=True):
  86. signal.value = level
  87. await Timer(clocks * CLOCK_NS, units="ns")
  88. async def wait_unlocked(dut) -> None:
  89. await wait_for(
  90. dut,
  91. lambda: int(dut.host_locked_mon.value) == 0,
  92. cycles=1800,
  93. label="Host selector unlock",
  94. )
  95. async def target_transaction(dut, target: int, sender=send_uart) -> None:
  96. response = cocotb.start_soon(receive_frame(dut.host_rs232_tx))
  97. frame = encode_frame(SET_TARGET, bytes((target,)))
  98. if sender is send_uart:
  99. await sender(dut.host_rs232_rx, frame, HOST_CLKS_PER_BIT)
  100. else:
  101. await sender(dut.host_rs232_rx, frame)
  102. kind, payload = await with_timeout(response, 20, "ms")
  103. assert (kind, payload) == (SET_TARGET_ACK, b"")
  104. await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 2, units="ns")
  105. await wait_unlocked(dut)
  106. assert int(dut.current_target_mon.value) == target
  107. @cocotb.test()
  108. async def test_host_random_frames_timeout_resync_and_port_lock(dut):
  109. dut.host_rs232_rx.value = 1
  110. dut.host_ttl_rx.value = 1
  111. dut.bmc_rs232_rx.value = 1
  112. dut.tick_1s_test.value = 0
  113. await with_timeout(RisingEdge(dut.rst_n_mon), 1, "ms")
  114. await clock_cycles(dut, 8)
  115. # Hypothesis supplies arbitrary declared lengths, payloads, CRC validity,
  116. # legal targets, illegal targets, and unknown types. Every invalid case
  117. # is a silent drop and must leave both the target and response counters
  118. # unchanged; valid target frames commit exactly once and ACK exactly once.
  119. for case in generated_cases():
  120. commits_before = int(dut.target_commit_count_mon.value)
  121. responses_before = int(dut.host_response_count_mon.value)
  122. target_before = int(dut.current_target_mon.value)
  123. accepted = case.accepted_target
  124. if accepted is not None:
  125. response = cocotb.start_soon(receive_frame(dut.host_rs232_tx))
  126. await send_uart(dut.host_rs232_rx, case.encode(), HOST_CLKS_PER_BIT)
  127. assert await with_timeout(response, 20, "ms") == (SET_TARGET_ACK, b"")
  128. await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 2, units="ns")
  129. else:
  130. await send_uart(dut.host_rs232_rx, case.encode(), HOST_CLKS_PER_BIT)
  131. await wait_unlocked(dut)
  132. if accepted is None:
  133. assert int(dut.target_commit_count_mon.value) == commits_before
  134. assert int(dut.host_response_count_mon.value) == responses_before
  135. assert int(dut.current_target_mon.value) == target_before
  136. else:
  137. assert int(dut.target_commit_count_mon.value) == commits_before + 1
  138. assert int(dut.host_response_count_mon.value) == responses_before + 1
  139. assert int(dut.current_target_mon.value) == accepted
  140. assert int(dut.host_rs232_tx.value) == 1
  141. assert int(dut.host_ttl_tx.value) == 1
  142. # Noise and overlapping A5 candidates must resynchronize to the next full
  143. # header without resetting the UART or parser.
  144. response = cocotb.start_soon(receive_frame(dut.host_rs232_tx))
  145. noisy = b"\x00\xFF\xA5\xA5\x00\xA5" + encode_frame(SET_TARGET, b"\x3E")
  146. await send_uart(dut.host_rs232_rx, noisy, HOST_CLKS_PER_BIT)
  147. assert await with_timeout(response, 20, "ms") == (SET_TARGET_ACK, b"")
  148. await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 2, units="ns")
  149. await wait_unlocked(dut)
  150. assert int(dut.current_target_mon.value) == 62
  151. # A half-frame is discarded after the accelerated test timeout; the next
  152. # valid frame must not inherit its type, length, payload, or CRC state.
  153. commits_before = int(dut.target_commit_count_mon.value)
  154. responses_before = int(dut.host_response_count_mon.value)
  155. await send_uart(dut.host_rs232_rx, b"\xA5\x5A\x01\x01", HOST_CLKS_PER_BIT)
  156. await clock_cycles(dut, 1200)
  157. await wait_unlocked(dut)
  158. assert int(dut.target_commit_count_mon.value) == commits_before
  159. assert int(dut.host_response_count_mon.value) == responses_before
  160. await target_transaction(dut, 61)
  161. # There is no command queue: a second complete frame arriving while the
  162. # first physical ACK is active is dropped, and a later retransmission is
  163. # accepted after the response boundary retires.
  164. commits_before = int(dut.target_commit_count_mon.value)
  165. responses_before = int(dut.host_response_count_mon.value)
  166. response = cocotb.start_soon(receive_frame(dut.host_rs232_tx))
  167. await send_uart(dut.host_rs232_rx, encode_frame(SET_TARGET, b"\x14"), HOST_CLKS_PER_BIT)
  168. await send_uart(dut.host_rs232_rx, encode_frame(SET_TARGET, b"\x46"), HOST_CLKS_PER_BIT)
  169. assert await with_timeout(response, 20, "ms") == (SET_TARGET_ACK, b"")
  170. await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 2, units="ns")
  171. await wait_unlocked(dut)
  172. assert int(dut.target_commit_count_mon.value) == commits_before + 1
  173. assert int(dut.host_response_count_mon.value) == responses_before + 1
  174. assert int(dut.current_target_mon.value) == 20
  175. await target_transaction(dut, 70)
  176. # Simultaneous start bits deterministically select RS-232 for the entire
  177. # request/response lock. TTL traffic cannot splice payload or steal TX.
  178. commits_before = int(dut.target_commit_count_mon.value)
  179. response = cocotb.start_soon(receive_frame(dut.host_rs232_tx))
  180. rs232 = cocotb.start_soon(
  181. send_uart(dut.host_rs232_rx, encode_frame(SET_TARGET, b"\x3C"), HOST_CLKS_PER_BIT)
  182. )
  183. ttl = cocotb.start_soon(
  184. send_uart(dut.host_ttl_rx, encode_frame(SET_TARGET, b"\x46"), HOST_CLKS_PER_BIT)
  185. )
  186. await rs232
  187. await ttl
  188. assert await with_timeout(response, 20, "ms") == (SET_TARGET_ACK, b"")
  189. assert int(dut.host_ttl_tx.value) == 1
  190. await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 2, units="ns")
  191. await wait_unlocked(dut)
  192. assert int(dut.target_commit_count_mon.value) == commits_before + 1
  193. assert int(dut.current_target_mon.value) == 60
  194. # Integrate the raw UART tolerance proof with a legal frame: fixed -1/+1
  195. # clock baud error and balanced per-bit jitter must preserve framing/CRC.
  196. await target_transaction(dut, 64, lambda signal, data: send_uart_with_period(signal, data, 26))
  197. await target_transaction(dut, 63, lambda signal, data: send_uart_with_period(signal, data, 28))
  198. await target_transaction(dut, 65, send_uart_jittered)
  199. # A declared 255-byte unknown frame plus a long zero tail is discarded
  200. # without a response, state mutation, or loss of the next valid command.
  201. commits_before = int(dut.target_commit_count_mon.value)
  202. responses_before = int(dut.host_response_count_mon.value)
  203. long_invalid = b"\xA5\x5A\x7F\xFF" + bytes(260)
  204. await send_uart(dut.host_rs232_rx, long_invalid, HOST_CLKS_PER_BIT)
  205. await wait_unlocked(dut)
  206. assert int(dut.target_commit_count_mon.value) == commits_before
  207. assert int(dut.host_response_count_mon.value) == responses_before
  208. await target_transaction(dut, 66)