test_6400_formal_contract.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. #!/usr/bin/env python3
  2. """Contract checks for the 6400 P01-P17 formal acceptance suite."""
  3. from __future__ import annotations
  4. import json
  5. from pathlib import Path
  6. import re
  7. import signal
  8. import subprocess
  9. import pytest
  10. import tools.run_6400_formal as formal_runner
  11. from tools.run_6400_formal import compiled_property_ids, formal_run_base, property_cell_ids
  12. ROOT = Path(__file__).resolve().parents[2]
  13. FORMAL = ROOT / "tests" / "formal"
  14. def _manifest() -> dict:
  15. return json.loads((FORMAL / "6400-properties.json").read_text(encoding="utf-8"))
  16. def test_exact_p01_p18_manifest() -> None:
  17. manifest = _manifest()
  18. assert [item["id"] for item in manifest["properties"]] == [
  19. f"P{index:02d}" for index in range(1, 19)
  20. ]
  21. assert len({item["id"] for item in manifest["properties"]}) == 18
  22. def test_every_proof_runs_boolector_and_z3() -> None:
  23. manifest = _manifest()
  24. assert manifest["required_solvers"] == ["boolector", "z3"]
  25. harnesses = {target["sby"] for target in manifest["proof_targets"]}
  26. assert all(target["tasks"] == ["boolector", "z3"] for target in manifest["proof_targets"])
  27. assert all(item["harness"] in harnesses for item in manifest["properties"])
  28. def test_sby_mode_and_depth_match_manifest() -> None:
  29. manifest = _manifest()
  30. for target in [*manifest["proof_targets"], *manifest["cover_targets"]]:
  31. text = (FORMAL / target["sby"]).read_text(encoding="utf-8")
  32. assert re.search(rf"(?m)^mode\s+{re.escape(target['mode'])}\s*$", text)
  33. assert re.search(rf"(?m)^depth\s+{target['depth']}\s*$", text)
  34. def test_pwm_proof_and_reachability_compile_board_adapter() -> None:
  35. for name in ("6400_pwm_properties.sby", "6400_pwm_reachability.sby"):
  36. text = (FORMAL / name).read_text(encoding="utf-8")
  37. assert "fan_board_output_adapter.v" in text
  38. def test_boot_output_proof_uses_production_controller_and_board_adapter() -> None:
  39. for name in (
  40. "6400_boot_output_properties.sby",
  41. "6400_boot_output_reachability.sby",
  42. ):
  43. text = (FORMAL / name).read_text(encoding="utf-8")
  44. assert "fan_boot_safety_controller.v" in text
  45. assert "fan_board_output_adapter.v" in text
  46. p17 = next(item for item in _manifest()["properties"] if item["id"] == "P17")
  47. assert p17["harness"] == "6400_boot_output_properties.sby"
  48. def test_identification_transport_proves_fresh_ack_without_claiming_uart_stop_bit() -> None:
  49. manifest = _manifest()
  50. target = next(
  51. item for item in manifest["proof_targets"]
  52. if item["name"] == "transport_identification"
  53. )
  54. reachability = next(
  55. item for item in manifest["cover_targets"]
  56. if item["name"] == "transport_identification_reachability"
  57. )
  58. assert target["sby"] == "6400_transport_identification_properties.sby"
  59. assert reachability["sby"] == "6400_transport_identification_reachability.sby"
  60. assert reachability["witnesses"] == ["P18"]
  61. proof = (FORMAL / target["sby"]).read_text(encoding="utf-8")
  62. harness = (
  63. FORMAL / "6400_transport_identification_properties_formal.v"
  64. ).read_text(encoding="utf-8")
  65. assert "thermal_host_command.v" in proof
  66. assert "stimulus_atomic_bank.v" in proof
  67. assert "uart_tx_byte.v" not in proof
  68. assert "repeated_ack_seen" in harness
  69. assert "writes_seen == 32'hFFFF_FFFF" in harness
  70. assert "tx_frame_type == 8'h83 && tx_payload_length == 0" in harness
  71. assert "invalid_duration_silent_seen" in harness
  72. assert "invalid_duty_silent_seen" in harness
  73. assert "Physical UART serialization" in harness
  74. assert "u_command.state" not in harness
  75. assert ".formal_state_o(formal_state)" in harness
  76. assert "bank_commit_applied" in harness
  77. assert "formal_active_stimulus_data == 8'd50" in harness
  78. command = (ROOT / "src/transport/thermal_host_command.v").read_text(
  79. encoding="utf-8"
  80. )
  81. assert "`ifdef FORMAL\n , output wire [3:0] formal_state_o" in command
  82. p07 = next(item for item in manifest["properties"] if item["id"] == "P07")
  83. assert p07["harness"] == "6400_transport_properties.sby"
  84. assert p07["requirement"].startswith("SET_TARGET ACK")
  85. p18 = next(item for item in manifest["properties"] if item["id"] == "P18")
  86. assert p18["harness"] == "6400_transport_identification_properties.sby"
  87. assert p18["requirement"].startswith("Identification stimulus stages 32")
  88. def test_stimulus_reload_commit_has_priority_over_same_cycle_expiry_tick() -> None:
  89. core = (ROOT / "src/control/thermal_control_core.v").read_text(encoding="utf-8")
  90. runner = (ROOT / "tools/run_6400_v1.py").read_text(encoding="utf-8")
  91. directed_tb = (ROOT / "tests/sim/stimulus_reload_priority_tb.v").read_text(
  92. encoding="utf-8"
  93. )
  94. assert "end else if (tick_1s && stimulus_running) begin" in core
  95. assert "$past(stimulus_commit_applied &&" in core
  96. assert "stimulus_remaining ==\n $past(stimulus_duration_seconds)" in core
  97. assert '"stimulus_reload_priority_tb"' in runner
  98. assert "commit_vector(8'd7, 1'b1)" in directed_tb
  99. assert "same-cycle reload was overwritten by expiry" in directed_tb
  100. def test_critical_safety_and_crc_properties_have_reachable_witnesses() -> None:
  101. witnesses = {
  102. property_id
  103. for target in _manifest()["cover_targets"]
  104. for property_id in target["witnesses"]
  105. }
  106. assert {"P03", "P04", "P05", "P06"} <= witnesses
  107. def test_core_composes_detection_fill_and_active_bank() -> None:
  108. source = (ROOT / "src/control/thermal_control_core.v").read_text(encoding="utf-8")
  109. assert "formal_stale_preempt" in source
  110. assert "formal_inactive_applied" in source
  111. assert "formal_active_applied" in source
  112. assert "global_fault <= global_fault || bmc_stale" in source
  113. assert "safe_fill_value" in source
  114. def test_bad_crc_is_composed_through_target_engine() -> None:
  115. harness = (FORMAL / "6400_transport_properties_formal.v").read_text(encoding="utf-8")
  116. frame = (ROOT / "src/common/frame_rx.v").read_text(encoding="utf-8")
  117. command = (ROOT / "src/transport/thermal_host_command.v").read_text(encoding="utf-8")
  118. assert "bad_crc_quarantine" in harness
  119. assert "formal_bad_crc_event_o" in frame
  120. assert "target_celsius != $past(target_celsius)" in command
  121. assert "u_frame_rx.formal_" not in harness
  122. def test_runner_is_fail_closed_and_commit_bound() -> None:
  123. runner = (ROOT / "tools/run_6400_formal.py").read_text(encoding="utf-8")
  124. assert "formal acceptance requires a clean worktree" in runner
  125. assert "PROD2U_CONTAINER_DIGEST" in runner
  126. assert '"source_tree_sha256"' in runner
  127. assert '"bitstream_sha256": None' in runner
  128. assert "start_new_session=True" in runner
  129. assert "os.killpg" in runner
  130. assert "default=1" in runner
  131. assert "solver_map" in runner
  132. def test_core_formal_does_not_assume_pwm_scan_is_always_idle() -> None:
  133. harness = (FORMAL / "6400_core_properties_formal.v").read_text(encoding="utf-8")
  134. core = (ROOT / "src/control/thermal_control_core.v").read_text(encoding="utf-8")
  135. assert "(* anyseq *) reg pwm_scan_idle" in harness
  136. assert ".pwm_scan_idle(pwm_scan_idle)" in harness
  137. assert "active_output_bank != $past(active_output_bank)" in core
  138. assert "$past(pwm_scan_idle)" in core
  139. def test_formal_run_base_is_external_and_rejects_git_worktree(
  140. tmp_path: Path, monkeypatch: pytest.MonkeyPatch
  141. ) -> None:
  142. external = tmp_path / "formal-runs"
  143. monkeypatch.setenv("PRODU2_FORMAL_RUN_BASE", str(external))
  144. assert formal_run_base() == external.resolve()
  145. monkeypatch.setenv("PRODU2_FORMAL_RUN_BASE", str(ROOT / "receipts"))
  146. with pytest.raises(RuntimeError, match="outside the Git worktree"):
  147. formal_run_base()
  148. def test_runner_timeout_kills_process_group_and_keeps_task_log_name(
  149. tmp_path: Path, monkeypatch: pytest.MonkeyPatch
  150. ) -> None:
  151. if formal_runner.os.name != "posix":
  152. pytest.skip("process-group timeout policy is Linux authoritative")
  153. class StubbornProcess:
  154. pid = 4242
  155. returncode: int | None = None
  156. def __init__(self) -> None:
  157. self.communicate_calls = 0
  158. def communicate(self, timeout: int | None = None) -> tuple[str, None]:
  159. self.communicate_calls += 1
  160. if self.communicate_calls == 1:
  161. raise subprocess.TimeoutExpired("sby", timeout, output="partial\n")
  162. if self.communicate_calls == 2:
  163. raise subprocess.TimeoutExpired("sby", timeout, output="partial\nterm\n")
  164. self.returncode = -signal.SIGKILL
  165. return "partial\nterm\nkilled\n", None
  166. process = StubbornProcess()
  167. signals: list[tuple[int, signal.Signals]] = []
  168. monkeypatch.setattr(formal_runner.subprocess, "Popen", lambda *args, **kwargs: process)
  169. monkeypatch.setattr(
  170. formal_runner.os,
  171. "killpg",
  172. lambda pid, sent_signal: signals.append((pid, sent_signal)),
  173. )
  174. result = formal_runner.run_job(
  175. {
  176. "target": {
  177. "name": "core",
  178. "sby": "6400_core_properties.sby",
  179. "mode": "prove",
  180. "depth": 4,
  181. },
  182. "task": "boolector",
  183. },
  184. tmp_path,
  185. timeout=1,
  186. )
  187. assert signals == [(4242, signal.SIGTERM), (4242, signal.SIGKILL)]
  188. process_log = tmp_path / "work" / "core" / "boolector.process.log"
  189. assert process_log.read_text(encoding="utf-8") == "partial\nterm\nkilled\n"
  190. assert result["process_log"]["path"] == process_log.as_posix()
  191. assert result["timed_out"] is True
  192. assert "timeout" in result["evidence_failures"]
  193. def test_runner_reads_yosys_jny_property_cell_sorts(tmp_path: Path) -> None:
  194. model = tmp_path / "model"
  195. model.mkdir()
  196. (model / "design.json").write_text(json.dumps({
  197. "modules": [{
  198. "name": "formal_top",
  199. "cell_sorts": [
  200. {"type": "$assert", "cells": [{"name": "$assert$source.v:1$1"}]},
  201. {"type": "$cover", "cells": [{"name": "$cover$source.v:2$2"}]},
  202. ],
  203. }],
  204. }), encoding="utf-8")
  205. assertions, covers, design_hash, failures = compiled_property_ids(tmp_path)
  206. assert assertions == ["formal_top.$assert$source.v:1$1"]
  207. assert covers == ["formal_top.$cover$source.v:2$2"]
  208. assert len(design_hash) == 64
  209. assert failures == []
  210. assert property_cell_ids(["formal_top.dut.$cover$source.v:2$2"]) == {
  211. "$cover$source.v:2$2"
  212. }