test_debug_bundle.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. #!/usr/bin/env python3
  2. """Tests for debug-max bundle and agent analysis contracts."""
  3. from __future__ import annotations
  4. import json
  5. import sys
  6. import tempfile
  7. import unittest
  8. from pathlib import Path
  9. sys.dont_write_bytecode = True
  10. ROOT = Path(__file__).resolve().parents[2]
  11. sys.path.insert(0, str(ROOT / "tools"))
  12. from debug_contract import ( # noqa: E402
  13. DEBUG_EVENT_REQUIRED_FIELDS,
  14. analyze_debug_bundle,
  15. build_debug_bundle,
  16. check_debug_invariants,
  17. normalize_replay_trace,
  18. )
  19. from pid_harness import contract_replay_payload # noqa: E402
  20. class DebugBundleTests(unittest.TestCase):
  21. def test_replay_trace_normalizes_to_agent_parseable_events(self) -> None:
  22. replay = contract_replay_payload()
  23. events = normalize_replay_trace(replay["trace"])
  24. self.assertGreater(len(events), 0)
  25. first = events[0]
  26. for field in DEBUG_EVENT_REQUIRED_FIELDS:
  27. self.assertIn(field, first)
  28. self.assertEqual(first["timebase"], "replay_sample")
  29. self.assertIn(first["event_type"], {"control_updated", "force_off", "fault_raised"})
  30. json.loads(json.dumps(first))
  31. def test_invariants_pass_for_replay_and_fail_for_bad_ptc_fault(self) -> None:
  32. replay = contract_replay_payload()
  33. good = check_debug_invariants(normalize_replay_trace(replay["trace"]))
  34. self.assertEqual(good["status"], "pass")
  35. self.assertTrue(good["checks"]["ptc_off_when_force_off"]["pass"])
  36. self.assertTrue(good["checks"]["fan_fallback_on_thermal_fault"]["pass"])
  37. bad_events = normalize_replay_trace(replay["trace"])
  38. bad_events[0]["force_off"] = True
  39. bad_events[0]["ptc_pwm"] = 1
  40. bad = check_debug_invariants(bad_events)
  41. self.assertEqual(bad["status"], "fail")
  42. self.assertFalse(bad["checks"]["ptc_off_when_force_off"]["pass"])
  43. def test_bundle_builder_creates_agent_entrypoints(self) -> None:
  44. replay = contract_replay_payload()
  45. with tempfile.TemporaryDirectory() as tmp:
  46. raw_capture = Path(tmp) / "uart-debug.png"
  47. raw_capture.write_bytes(b"\x89PNG\r\n\x1a\nfake")
  48. bundle = build_debug_bundle(
  49. output_dir=Path(tmp) / "bundle",
  50. source="replay",
  51. trace=normalize_replay_trace(replay["trace"]),
  52. pipeline={"status": "not_run"},
  53. register_dump={"0x60": 1},
  54. raw_artifacts=[raw_capture],
  55. )
  56. bundle_dir = Path(bundle["path"])
  57. for name in [
  58. "manifest.json",
  59. "provenance.json",
  60. "toolchain.json",
  61. "scenario.json",
  62. "sim_results.json",
  63. "formal_results.json",
  64. "detector_selftest_results.json",
  65. "td_results.json",
  66. "hardware_observations.json",
  67. "pipeline.json",
  68. "config.json",
  69. "register_dump.json",
  70. "trace.jsonl",
  71. "events.csv",
  72. "invariants.json",
  73. "agent_context.md",
  74. ]:
  75. self.assertTrue((bundle_dir / name).is_file(), name)
  76. manifest = json.loads((bundle_dir / "manifest.json").read_text(encoding="utf-8"))
  77. self.assertEqual(manifest["schema"], "pid-debug-bundle-v1")
  78. self.assertEqual(manifest["agent_entrypoint"], "agent_context.md")
  79. self.assertEqual(manifest["provenance_file"], "provenance.json")
  80. self.assertEqual(manifest["detector_selftest_results_file"], "detector_selftest_results.json")
  81. provenance = json.loads((bundle_dir / "provenance.json").read_text(encoding="utf-8"))
  82. self.assertEqual(provenance["fact_classes"]["debug_bundle"], "project_defined_strategy")
  83. hardware = json.loads((bundle_dir / "hardware_observations.json").read_text(encoding="utf-8"))
  84. self.assertEqual(hardware["status"], "not_run")
  85. raw_copy = bundle_dir / "raw" / "uart-debug.png"
  86. self.assertTrue(raw_copy.is_file())
  87. self.assertEqual(raw_copy.read_bytes(), raw_capture.read_bytes())
  88. self.assertEqual(len(bundle["manifest"]["raw_files"]), 1)
  89. self.assertEqual(bundle["manifest"]["raw_files"][0]["csv"]["status"], "not_csv")
  90. context = (bundle_dir / "agent_context.md").read_text(encoding="utf-8")
  91. self.assertIn("trace.jsonl", context)
  92. self.assertIn("invariants.json", context)
  93. def test_uart_bundle_marks_missing_manual_export(self) -> None:
  94. event = {field: 0 for field in DEBUG_EVENT_REQUIRED_FIELDS}
  95. event.update({
  96. "timebase": "uart_manual_export",
  97. "trace_seq": 1,
  98. "event_type": "manual_export_missing",
  99. "state": "manual_export",
  100. "reason": "uart_manual_export_missing",
  101. })
  102. with tempfile.TemporaryDirectory() as tmp:
  103. bundle = build_debug_bundle(
  104. output_dir=Path(tmp) / "bundle",
  105. source="uart",
  106. trace=[event],
  107. pipeline={"status": "not_run"},
  108. register_dump={},
  109. )
  110. analysis = analyze_debug_bundle(Path(bundle["path"]))
  111. hardware = json.loads((Path(bundle["path"]) / "hardware_observations.json").read_text(encoding="utf-8"))
  112. self.assertEqual(hardware["status"], "uart_manual_export_missing")
  113. self.assertEqual(hardware["instruments"]["uart_ttl"], "manual_export_missing")
  114. self.assertTrue(any("manual export is missing" in hint for hint in analysis["root_cause_hints"]))
  115. def test_uart_bundle_marks_attached_manual_export_and_csv_headers(self) -> None:
  116. event = {field: 0 for field in DEBUG_EVENT_REQUIRED_FIELDS}
  117. event.update({
  118. "timebase": "uart_manual_export",
  119. "trace_seq": 1,
  120. "event_type": "manual_export_attached",
  121. "state": "manual_export",
  122. "reason": "uart_manual_export_attached",
  123. })
  124. with tempfile.TemporaryDirectory() as tmp:
  125. csv_path = Path(tmp) / "uart_debug.csv"
  126. csv_path.write_text(",".join(DEBUG_EVENT_REQUIRED_FIELDS) + "\n" + ",".join("0" for _ in DEBUG_EVENT_REQUIRED_FIELDS) + "\n", encoding="utf-8")
  127. bundle = build_debug_bundle(
  128. output_dir=Path(tmp) / "bundle",
  129. source="uart",
  130. trace=[event],
  131. pipeline={"status": "not_run"},
  132. register_dump={},
  133. raw_artifacts=[csv_path],
  134. )
  135. analysis = analyze_debug_bundle(Path(bundle["path"]))
  136. hardware = json.loads((Path(bundle["path"]) / "hardware_observations.json").read_text(encoding="utf-8"))
  137. self.assertEqual(hardware["status"], "uart_manual_export_attached")
  138. self.assertEqual(hardware["raw_file_count"], 1)
  139. self.assertEqual(hardware["raw_files"][0]["csv"]["status"], "recognized_debug_event_fields")
  140. hints = "\n".join(analysis["root_cause_hints"])
  141. self.assertIn("manual export is attached", hints)
  142. self.assertIn("standard debug_event_v1 headers", hints)
  143. def test_uart_bundle_marks_board_sram_as_current_evidence(self) -> None:
  144. event = {field: 0 for field in DEBUG_EVENT_REQUIRED_FIELDS}
  145. event.update({
  146. "timebase": "uart_board_sram",
  147. "trace_seq": 1,
  148. "event_type": "control_updated",
  149. "state": "uart",
  150. "reason": "uart_board_sram_pass",
  151. })
  152. with tempfile.TemporaryDirectory() as tmp:
  153. csv_path = Path(tmp) / "uart_board_sram.csv"
  154. csv_path.write_text(",".join(DEBUG_EVENT_REQUIRED_FIELDS) + "\n" + ",".join("0" for _ in DEBUG_EVENT_REQUIRED_FIELDS) + "\n", encoding="utf-8")
  155. hardware_observations = {
  156. "schema": "pid-hardware-observations-v1",
  157. "status": "uart_board_sram_pass",
  158. "reason": "UART board SRAM transcript and debug dump completed.",
  159. "instruments": {"uart_ttl": "board_sram_pass"},
  160. }
  161. bundle = build_debug_bundle(
  162. output_dir=Path(tmp) / "bundle",
  163. source="uart",
  164. trace=[event],
  165. pipeline={"status": "pass"},
  166. register_dump={},
  167. raw_artifacts=[csv_path],
  168. hardware_observations=hardware_observations,
  169. )
  170. analysis = analyze_debug_bundle(Path(bundle["path"]))
  171. hardware = json.loads((Path(bundle["path"]) / "hardware_observations.json").read_text(encoding="utf-8"))
  172. provenance = json.loads((Path(bundle["path"]) / "provenance.json").read_text(encoding="utf-8"))
  173. self.assertEqual(hardware["status"], "uart_board_sram_pass")
  174. self.assertEqual(provenance["fact_classes"]["hardware_observations"], "local_detected_fact")
  175. self.assertEqual(hardware["raw_files"][0]["artifact_role"], "uart_transcript_or_debug_export")
  176. hints = "\n".join(analysis["root_cause_hints"])
  177. self.assertIn("UART board SRAM evidence", hints)
  178. def test_uart_bundle_distinguishes_preflight_artifacts_from_manual_export(self) -> None:
  179. event = {field: 0 for field in DEBUG_EVENT_REQUIRED_FIELDS}
  180. event.update({
  181. "timebase": "uart_manual_export",
  182. "trace_seq": 1,
  183. "event_type": "manual_export_missing",
  184. "state": "manual_export",
  185. "reason": "uart_preflight_artifacts_attached_without_manual_export",
  186. })
  187. with tempfile.TemporaryDirectory() as tmp:
  188. report_path = Path(tmp) / "uart-preflight.json"
  189. report_path.write_text('{"status":"manual_required"}\n', encoding="utf-8")
  190. log_path = Path(tmp) / "uart-preflight.log"
  191. log_path.write_text("COM7 allowlist missing\n", encoding="utf-8")
  192. bundle = build_debug_bundle(
  193. output_dir=Path(tmp) / "bundle",
  194. source="uart",
  195. trace=[event],
  196. pipeline={"status": "not_run"},
  197. register_dump={},
  198. raw_artifacts=[report_path, log_path],
  199. )
  200. analysis = analyze_debug_bundle(Path(bundle["path"]))
  201. hardware = json.loads((Path(bundle["path"]) / "hardware_observations.json").read_text(encoding="utf-8"))
  202. self.assertEqual(hardware["status"], "uart_preflight_artifacts_attached")
  203. self.assertEqual(hardware["instruments"]["uart_ttl"], "manual_export_missing")
  204. self.assertTrue(all(item["artifact_role"] == "uart_preflight_artifact" for item in hardware["raw_files"]))
  205. hints = "\n".join(analysis["root_cause_hints"])
  206. self.assertIn("preflight/build artifacts are archived", hints)
  207. self.assertIn("no UART transcript/debug CSV/manual export", hints)
  208. def test_analyzer_reports_toolchain_result_hints(self) -> None:
  209. event = {field: 0 for field in DEBUG_EVENT_REQUIRED_FIELDS}
  210. event.update({
  211. "timebase": "hdl_sim",
  212. "trace_seq": 1,
  213. "event_type": "control_updated",
  214. "state": "ok",
  215. "reason": "ok",
  216. })
  217. with tempfile.TemporaryDirectory() as tmp:
  218. bundle = build_debug_bundle(
  219. output_dir=Path(tmp) / "bundle",
  220. source="hdl",
  221. trace=[event],
  222. pipeline={"status": "not_run"},
  223. register_dump={},
  224. sim_results={"status": "blocked_missing_tool", "missing_tools": ["iverilog", "vvp"]},
  225. formal_results={"status": "fail", "targets": [{"name": "fault_implies_ptc_off"}]},
  226. detector_selftest_results={"status": "partial", "results": []},
  227. td_results={"status": "pass"},
  228. )
  229. analysis = analyze_debug_bundle(Path(bundle["path"]))
  230. hints = "\n".join(analysis["root_cause_hints"])
  231. self.assertIn("HDL simulation did not run", hints)
  232. self.assertIn("iverilog", hints)
  233. self.assertIn("formal verification failed", hints)
  234. self.assertIn("detector selftest partially ran", hints)
  235. def test_analyzer_accepts_detector_selftest_dict_targets(self) -> None:
  236. event = {field: 0 for field in DEBUG_EVENT_REQUIRED_FIELDS}
  237. event.update({
  238. "timebase": "hdl_sim",
  239. "trace_seq": 1,
  240. "event_type": "control_updated",
  241. "state": "ok",
  242. "reason": "ok",
  243. })
  244. with tempfile.TemporaryDirectory() as tmp:
  245. bundle = build_debug_bundle(
  246. output_dir=Path(tmp) / "bundle",
  247. source="hdl",
  248. trace=[event],
  249. pipeline={"status": "not_run"},
  250. register_dump={},
  251. detector_selftest_results={
  252. "status": "blocked_missing_tool",
  253. "targets": {
  254. "icarus": {"required_tools": ["iverilog"]},
  255. },
  256. "results": [
  257. {"name": "icarus", "missing_tools": ["iverilog"]},
  258. ],
  259. },
  260. )
  261. analysis = analyze_debug_bundle(Path(bundle["path"]))
  262. self.assertEqual(analysis["status"], "pass")
  263. self.assertTrue(any("detector selftest did not run" in hint for hint in analysis["root_cause_hints"]))
  264. def test_analyzer_reports_root_cause_hints(self) -> None:
  265. event = {
  266. field: 0 for field in DEBUG_EVENT_REQUIRED_FIELDS
  267. }
  268. event.update({
  269. "timebase": "register_poll",
  270. "trace_seq": 7,
  271. "event_type": "sample_wait",
  272. "state": "idle",
  273. "reason": "waiting_for_sensor_ready",
  274. "sensor_ready": False,
  275. "force_off": False,
  276. })
  277. with tempfile.TemporaryDirectory() as tmp:
  278. bundle = build_debug_bundle(
  279. output_dir=Path(tmp) / "bundle",
  280. source="register",
  281. trace=[event],
  282. pipeline={"status": "not_run"},
  283. register_dump={},
  284. )
  285. analysis = analyze_debug_bundle(Path(bundle["path"]))
  286. self.assertEqual(analysis["status"], "pass")
  287. self.assertTrue(any("sensor_ready=0" in hint for hint in analysis["root_cause_hints"]))
  288. def test_analyzer_reports_host_safety_pwm_and_trace_gap_hints(self) -> None:
  289. base = {field: 0 for field in DEBUG_EVENT_REQUIRED_FIELDS}
  290. events = []
  291. for index, reason in enumerate(["host_disabled", "safety_gate", "force_off", "fan_fallback"]):
  292. event = dict(base)
  293. event.update({
  294. "timebase": "hdl_sim",
  295. "trace_seq": index + 1,
  296. "event_type": "control_updated",
  297. "state": "safe_off",
  298. "reason": reason,
  299. "source_id": 0,
  300. "channel": index,
  301. "sample_seq": index + 1,
  302. "config_seq": 1,
  303. "fault_code": 1 if reason == "host_disabled" else 0,
  304. "force_off": reason == "force_off",
  305. "host_enable": reason != "host_disabled",
  306. "fan_duty": 127 if reason == "fan_fallback" else 38,
  307. })
  308. events.append(event)
  309. events[-1]["trace_seq"] = 9
  310. with tempfile.TemporaryDirectory() as tmp:
  311. bundle = build_debug_bundle(
  312. output_dir=Path(tmp) / "bundle",
  313. source="hdl",
  314. trace=events,
  315. pipeline={"status": "not_run"},
  316. register_dump={},
  317. )
  318. analysis = analyze_debug_bundle(Path(bundle["path"]))
  319. hints = "\n".join(analysis["root_cause_hints"])
  320. self.assertIn("host disabled", hints)
  321. self.assertIn("safety gate", hints)
  322. self.assertIn("PTC/PWM force_off", hints)
  323. self.assertIn("fan fallback", hints)
  324. self.assertIn("trace sequence gap", hints)
  325. if __name__ == "__main__":
  326. unittest.main()