test_final_temperature_chain.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. """End-to-end unit test of the CPLD temperature chain (ulw-loop goal G002).
  2. The vectors start from the physical temperature (or from an explicitly given
  3. raw word) and are turned into the raw 16-bit register combination using the
  4. basis recorded in ``contracts/ct7428-format.json``: one raw count is
  5. ``1 / (16 * 2^3) = 1/128`` degrees Celsius, so the integer Celsius byte is the
  6. raw word shifted right by ``discard_low_bits + log2(degrees_denominator)``.
  7. Every expected byte is computed in Python with exact ``Fraction`` arithmetic
  8. and the invalid cases are tested *before* the candidate is truncated.
  9. Those raw words are then driven through the real ``src/acquisition/ct7428_scan.v``
  10. RTL (with the virtual CT7428 device model of ``tests/sim/ct7428_scan_tb.v``)
  11. and the byte the RTL actually stored in ``temp_ram`` is compared with the
  12. Python expectation. No expectation is derived from a DUT output; the only DUT
  13. values used are the observed result bytes under test.
  14. Two classic defects are pinned by this test: taking the low eight bits of the
  15. raw word (which would fabricate a valid 0 C from 0x8000) and rounding the
  16. fraction up (25.996 C must stay 25 C, not become 26 C).
  17. Real hardware was not used: ``contracts/ct7428-format.json`` records
  18. ``physical_validation: NOT_RUN``; this is a simulation and software test.
  19. """
  20. from __future__ import annotations
  21. import json
  22. import shutil
  23. import subprocess
  24. from dataclasses import dataclass
  25. from fractions import Fraction
  26. from pathlib import Path
  27. import pytest
  28. REPO_ROOT = Path(__file__).resolve().parents[2]
  29. CT_FORMAT_PATH = REPO_ROOT / "contracts" / "ct7428-format.json"
  30. INVALID = 0xFF
  31. SIGN_BIT = 0x8000
  32. MAX_VALID_CELSIUS = 254
  33. # The temperature section of AGENTS.md: BMC and CT are one uint8 per channel,
  34. # 00..FE = 0..254 C, FF = invalid.
  35. SCAN_TB = "ct7428_scan_tb"
  36. RTL_SOURCES = (
  37. "src/rtl/prod2u_p4_i2c_stop_start_read.v",
  38. "src/modules/i2c_word_reader.v",
  39. "src/acquisition/ct7428_scan.v",
  40. "src/acquisition/temp_ram.v",
  41. "tests/sim/ct7428_scan_tb.v",
  42. )
  43. def _resolve_tool(name: str) -> str | None:
  44. """Locate a simulator binary without importing the heavy tool modules."""
  45. located = shutil.which(name)
  46. if located:
  47. return located
  48. for candidate in (
  49. Path("/usr/bin") / name,
  50. Path("/usr/local/bin") / name,
  51. Path("/opt/oss-cad-suite/bin") / name,
  52. Path("/opt/oss-cad-suite/libexec") / name,
  53. ):
  54. if candidate.is_file():
  55. return str(candidate)
  56. return None
  57. def _contract() -> dict:
  58. return json.loads(CT_FORMAT_PATH.read_text(encoding="utf-8"))["temperature"]
  59. _BASIS = _contract()
  60. _DISCARD_LOW_BITS: int = int(_BASIS["discard_low_bits"])
  61. _DEGREES_DENOMINATOR: int = int(_BASIS["degrees_denominator"])
  62. # One raw count in degrees Celsius, derived from the contract (never hardcoded).
  63. CELSIUS_PER_COUNT = Fraction(1, _DEGREES_DENOMINATOR * (1 << _DISCARD_LOW_BITS))
  64. # The contract stores (raw >> discard_low_bits) in 1/degrees_denominator units,
  65. # so the integer Celsius candidate is the raw word shifted by this amount.
  66. INTEGER_SHIFT = _DISCARD_LOW_BITS + (
  67. _DEGREES_DENOMINATOR.bit_length() - 1
  68. )
  69. def raw_for_celsius(celsius: Fraction | int) -> int:
  70. """Raw 16-bit word a sensor would report for this positive temperature."""
  71. value = Fraction(celsius)
  72. assert value >= 0, "use an explicit raw word for negative temperatures"
  73. return int(value / CELSIUS_PER_COUNT)
  74. def celsius_from_raw(raw: int) -> Fraction:
  75. """The historical ct7428_conv_temp result, exactly (contract algorithm)."""
  76. assert 0 <= raw <= 0xFFFF
  77. if raw > 0x7FFF:
  78. magnitude = ((~raw) & 0xFFFF) + 1
  79. return -Fraction(magnitude >> _DISCARD_LOW_BITS, _DEGREES_DENOMINATOR)
  80. return Fraction(raw >> _DISCARD_LOW_BITS, _DEGREES_DENOMINATOR)
  81. def expected_byte(raw: int, error: bool = False) -> int:
  82. """Final uint8 Celsius byte, with every invalid case tested first."""
  83. if error:
  84. return INVALID
  85. if raw >= SIGN_BIT:
  86. return INVALID
  87. candidate = raw >> INTEGER_SHIFT
  88. if candidate >= INVALID:
  89. return INVALID
  90. return candidate
  91. @dataclass(frozen=True)
  92. class Vector:
  93. name: str
  94. raw: int
  95. error: bool
  96. @property
  97. def expected(self) -> int:
  98. return expected_byte(self.raw, self.error)
  99. def _vectors() -> list[Vector]:
  100. """27 vectors: the required coverage plus fillers, one per CT channel."""
  101. vectors = [
  102. Vector("0.0 C", raw_for_celsius(0), False),
  103. Vector("+25.4 C", raw_for_celsius(Fraction("25.4")), False),
  104. Vector("+40.0 C", raw_for_celsius(40), False),
  105. Vector("+70.9375 C", raw_for_celsius(Fraction(9080, 128)), False),
  106. Vector("+100.0 C", raw_for_celsius(100), False),
  107. Vector("raw 0xFFFF (magnitude 1 -> -0.0 C)", 0xFFFF, False),
  108. Vector("raw 0x8000 (negative zero)", 0x8000, False),
  109. Vector("raw 0x8008 (magnitude 32760 -> -255.9375 C)", 0x8008, False),
  110. Vector("I2C error at +25.4 C", raw_for_celsius(Fraction("25.4")), True),
  111. Vector("+254.0 C (highest valid)", raw_for_celsius(254), False),
  112. Vector("+255.0 C (>= 255 is invalid)", raw_for_celsius(255), False),
  113. Vector("+510.0 C (raw 0xFF00, low byte 0x00)", raw_for_celsius(510), False),
  114. Vector("+0.0546875 C (raw 7, fraction dropped)", raw_for_celsius(Fraction(7, 128)), False),
  115. Vector("+25.996 C (never rounded up)", raw_for_celsius(Fraction("25.996")), False),
  116. ]
  117. for celsius in range(14, 27):
  118. vectors.append(Vector(f"+{celsius}.0 C", raw_for_celsius(celsius), False))
  119. return vectors
  120. def _run_rtl_scan(vector_list: list[Vector], workdir: Path) -> dict[int, int]:
  121. """Compile and run the real scan RTL, returning the observed bytes."""
  122. iverilog = _resolve_tool("iverilog")
  123. vvp = _resolve_tool("vvp")
  124. if not iverilog or not vvp:
  125. pytest.skip("iverilog/vvp unavailable")
  126. vector_file = workdir / "ct7428_vectors.txt"
  127. vector_file.write_text(
  128. "".join(f"{vector.raw:04X} {int(vector.error)}\n" for vector in vector_list),
  129. encoding="ascii",
  130. )
  131. executable = workdir / f"{SCAN_TB}.vvp"
  132. compile_cmd = [
  133. iverilog,
  134. "-g2012",
  135. "-Wall",
  136. "-I",
  137. str(REPO_ROOT),
  138. "-s",
  139. SCAN_TB,
  140. "-o",
  141. str(executable),
  142. *[str(REPO_ROOT / source) for source in RTL_SOURCES],
  143. ]
  144. compiled = subprocess.run(
  145. compile_cmd, cwd=REPO_ROOT, capture_output=True, text=True, timeout=300
  146. )
  147. assert compiled.returncode == 0, (
  148. f"iverilog failed for the temperature chain:\n{compiled.stdout}\n{compiled.stderr}"
  149. )
  150. run = subprocess.run(
  151. [vvp, str(executable), f"+VECTOR_FILE={vector_file}"],
  152. cwd=REPO_ROOT,
  153. capture_output=True,
  154. text=True,
  155. timeout=300,
  156. )
  157. assert run.returncode == 0, (
  158. f"{SCAN_TB} exited non-zero:\n{run.stdout}\n{run.stderr}"
  159. )
  160. assert f"{SCAN_TB} PASS" in run.stdout, (
  161. f"{SCAN_TB} did not pass:\n{run.stdout}\n{run.stderr}"
  162. )
  163. observed: dict[int, int] = {}
  164. for line in run.stdout.splitlines():
  165. if line.startswith("RESULT "):
  166. _, channel, byte = line.split()
  167. observed[int(channel)] = int(byte, 16)
  168. return observed
  169. def test_contract_basis_is_one_sixteenth_degree_per_count() -> None:
  170. """The 0.625 / 0.0625 confusion must be visible in the contract numbers."""
  171. assert _DISCARD_LOW_BITS == 3
  172. assert _DEGREES_DENOMINATOR == 16
  173. assert CELSIUS_PER_COUNT == Fraction(1, 128)
  174. assert INTEGER_SHIFT == 7
  175. # 0x0780 counts must be exactly 15 C (a 0.625 C basis would read 150 C).
  176. assert celsius_from_raw(0x0780) == Fraction(15)
  177. # The signed decode keeps a fractional negative part.
  178. assert celsius_from_raw(0x8008) == Fraction(-32760 >> 3, 16)
  179. assert celsius_from_raw(0xFFFF) == Fraction(0)
  180. def test_invalid_cases_are_detected_before_truncation() -> None:
  181. """Expected bytes come from Python, with the classic traps spelled out."""
  182. # 0 C is a real, valid reading and must survive as 0x00.
  183. assert expected_byte(raw_for_celsius(0)) == 0x00
  184. # -0.0 C (raw 0xFFFF) and negative zero (0x8000) are invalid, not 0.
  185. assert celsius_from_raw(0xFFFF) == 0
  186. assert expected_byte(0xFFFF) == INVALID
  187. assert expected_byte(0x8000) == INVALID
  188. # Taking the low eight bits of 0x8000 would fabricate a valid 0 C.
  189. assert (0x8000 & 0xFF) == 0x00
  190. assert expected_byte(0x8000) != 0x00
  191. # 255 C and above must not wrap: 0xFF00's low byte is 0x00 as well.
  192. assert (0xFF00 & 0xFF) == 0x00
  193. assert expected_byte(0xFF00) == INVALID
  194. assert expected_byte(raw_for_celsius(255)) == INVALID
  195. # Fractions are discarded, never rounded.
  196. assert expected_byte(raw_for_celsius(Fraction("25.996"))) == 25
  197. assert expected_byte(raw_for_celsius(Fraction(7, 128))) == 0x00
  198. def test_rtl_scan_converts_real_raw_words_to_the_expected_bytes(tmp_path: Path) -> None:
  199. """The real ct7428_scan RTL must produce every independently expected byte."""
  200. vector_list = _vectors()
  201. assert len(vector_list) == 27, "one vector per CT channel"
  202. observed = _run_rtl_scan(vector_list, tmp_path)
  203. assert len(observed) == 27, f"scan did not report all channels: {observed}"
  204. for channel, vector in enumerate(vector_list):
  205. assert channel in observed, f"channel {channel} missing from the scan"
  206. assert observed[channel] == vector.expected, (
  207. f"channel {channel} ({vector.name}): raw 0x{vector.raw:04X} "
  208. f"produced 0x{observed[channel]:02X}, expected 0x{vector.expected:02X}"
  209. )
  210. # The specific traps, checked through the RTL result rather than a helper.
  211. assert observed[6] == INVALID, "raw 0x8000 must be invalid through the RTL"
  212. assert observed[8] == INVALID, "an I2C error must write 0xFF through the RTL"
  213. assert observed[7] == INVALID, "raw 0x8008 must be invalid through the RTL"
  214. assert observed[13] == 25, "+25.996 C must be 25 C through the RTL"
  215. assert observed[0] == 0x00, "a real 0 C sample must be a valid 0x00"