| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357 |
- #!/usr/bin/env python3
- """Tests for debug-max bundle and agent analysis contracts."""
- from __future__ import annotations
- import json
- import sys
- import tempfile
- import unittest
- from pathlib import Path
- sys.dont_write_bytecode = True
- ROOT = Path(__file__).resolve().parents[2]
- sys.path.insert(0, str(ROOT / "tools"))
- from debug_contract import ( # noqa: E402
- DEBUG_EVENT_REQUIRED_FIELDS,
- analyze_debug_bundle,
- build_debug_bundle,
- check_debug_invariants,
- normalize_replay_trace,
- )
- from pid_harness import contract_replay_payload # noqa: E402
- class DebugBundleTests(unittest.TestCase):
- def test_replay_trace_normalizes_to_agent_parseable_events(self) -> None:
- replay = contract_replay_payload()
- events = normalize_replay_trace(replay["trace"])
- self.assertGreater(len(events), 0)
- first = events[0]
- for field in DEBUG_EVENT_REQUIRED_FIELDS:
- self.assertIn(field, first)
- self.assertEqual(first["timebase"], "replay_sample")
- self.assertIn(first["event_type"], {"control_updated", "force_off", "fault_raised"})
- json.loads(json.dumps(first))
- def test_invariants_pass_for_replay_and_fail_for_bad_ptc_fault(self) -> None:
- replay = contract_replay_payload()
- good = check_debug_invariants(normalize_replay_trace(replay["trace"]))
- self.assertEqual(good["status"], "pass")
- self.assertTrue(good["checks"]["ptc_off_when_force_off"]["pass"])
- self.assertTrue(good["checks"]["fan_fallback_on_thermal_fault"]["pass"])
- bad_events = normalize_replay_trace(replay["trace"])
- bad_events[0]["force_off"] = True
- bad_events[0]["ptc_pwm"] = 1
- bad = check_debug_invariants(bad_events)
- self.assertEqual(bad["status"], "fail")
- self.assertFalse(bad["checks"]["ptc_off_when_force_off"]["pass"])
- def test_bundle_builder_creates_agent_entrypoints(self) -> None:
- replay = contract_replay_payload()
- with tempfile.TemporaryDirectory() as tmp:
- raw_capture = Path(tmp) / "uart-debug.png"
- raw_capture.write_bytes(b"\x89PNG\r\n\x1a\nfake")
- bundle = build_debug_bundle(
- output_dir=Path(tmp) / "bundle",
- source="replay",
- trace=normalize_replay_trace(replay["trace"]),
- pipeline={"status": "not_run"},
- register_dump={"0x60": 1},
- raw_artifacts=[raw_capture],
- )
- bundle_dir = Path(bundle["path"])
- for name in [
- "manifest.json",
- "provenance.json",
- "toolchain.json",
- "scenario.json",
- "sim_results.json",
- "formal_results.json",
- "detector_selftest_results.json",
- "td_results.json",
- "hardware_observations.json",
- "pipeline.json",
- "config.json",
- "register_dump.json",
- "trace.jsonl",
- "events.csv",
- "invariants.json",
- "agent_context.md",
- ]:
- self.assertTrue((bundle_dir / name).is_file(), name)
- manifest = json.loads((bundle_dir / "manifest.json").read_text(encoding="utf-8"))
- self.assertEqual(manifest["schema"], "pid-debug-bundle-v1")
- self.assertEqual(manifest["agent_entrypoint"], "agent_context.md")
- self.assertEqual(manifest["provenance_file"], "provenance.json")
- self.assertEqual(manifest["detector_selftest_results_file"], "detector_selftest_results.json")
- provenance = json.loads((bundle_dir / "provenance.json").read_text(encoding="utf-8"))
- self.assertEqual(provenance["fact_classes"]["debug_bundle"], "project_defined_strategy")
- hardware = json.loads((bundle_dir / "hardware_observations.json").read_text(encoding="utf-8"))
- self.assertEqual(hardware["status"], "not_run")
- raw_copy = bundle_dir / "raw" / "uart-debug.png"
- self.assertTrue(raw_copy.is_file())
- self.assertEqual(raw_copy.read_bytes(), raw_capture.read_bytes())
- self.assertEqual(len(bundle["manifest"]["raw_files"]), 1)
- self.assertEqual(bundle["manifest"]["raw_files"][0]["csv"]["status"], "not_csv")
- context = (bundle_dir / "agent_context.md").read_text(encoding="utf-8")
- self.assertIn("trace.jsonl", context)
- self.assertIn("invariants.json", context)
- def test_uart_bundle_marks_missing_manual_export(self) -> None:
- event = {field: 0 for field in DEBUG_EVENT_REQUIRED_FIELDS}
- event.update({
- "timebase": "uart_manual_export",
- "trace_seq": 1,
- "event_type": "manual_export_missing",
- "state": "manual_export",
- "reason": "uart_manual_export_missing",
- })
- with tempfile.TemporaryDirectory() as tmp:
- bundle = build_debug_bundle(
- output_dir=Path(tmp) / "bundle",
- source="uart",
- trace=[event],
- pipeline={"status": "not_run"},
- register_dump={},
- )
- analysis = analyze_debug_bundle(Path(bundle["path"]))
- hardware = json.loads((Path(bundle["path"]) / "hardware_observations.json").read_text(encoding="utf-8"))
- self.assertEqual(hardware["status"], "uart_manual_export_missing")
- self.assertEqual(hardware["instruments"]["uart_ttl"], "manual_export_missing")
- self.assertTrue(any("manual export is missing" in hint for hint in analysis["root_cause_hints"]))
- def test_uart_bundle_marks_attached_manual_export_and_csv_headers(self) -> None:
- event = {field: 0 for field in DEBUG_EVENT_REQUIRED_FIELDS}
- event.update({
- "timebase": "uart_manual_export",
- "trace_seq": 1,
- "event_type": "manual_export_attached",
- "state": "manual_export",
- "reason": "uart_manual_export_attached",
- })
- with tempfile.TemporaryDirectory() as tmp:
- csv_path = Path(tmp) / "uart_debug.csv"
- csv_path.write_text(",".join(DEBUG_EVENT_REQUIRED_FIELDS) + "\n" + ",".join("0" for _ in DEBUG_EVENT_REQUIRED_FIELDS) + "\n", encoding="utf-8")
- bundle = build_debug_bundle(
- output_dir=Path(tmp) / "bundle",
- source="uart",
- trace=[event],
- pipeline={"status": "not_run"},
- register_dump={},
- raw_artifacts=[csv_path],
- )
- analysis = analyze_debug_bundle(Path(bundle["path"]))
- hardware = json.loads((Path(bundle["path"]) / "hardware_observations.json").read_text(encoding="utf-8"))
- self.assertEqual(hardware["status"], "uart_manual_export_attached")
- self.assertEqual(hardware["raw_file_count"], 1)
- self.assertEqual(hardware["raw_files"][0]["csv"]["status"], "recognized_debug_event_fields")
- hints = "\n".join(analysis["root_cause_hints"])
- self.assertIn("manual export is attached", hints)
- self.assertIn("standard debug_event_v1 headers", hints)
- def test_uart_bundle_marks_board_sram_as_current_evidence(self) -> None:
- event = {field: 0 for field in DEBUG_EVENT_REQUIRED_FIELDS}
- event.update({
- "timebase": "uart_board_sram",
- "trace_seq": 1,
- "event_type": "control_updated",
- "state": "uart",
- "reason": "uart_board_sram_pass",
- })
- with tempfile.TemporaryDirectory() as tmp:
- csv_path = Path(tmp) / "uart_board_sram.csv"
- csv_path.write_text(",".join(DEBUG_EVENT_REQUIRED_FIELDS) + "\n" + ",".join("0" for _ in DEBUG_EVENT_REQUIRED_FIELDS) + "\n", encoding="utf-8")
- hardware_observations = {
- "schema": "pid-hardware-observations-v1",
- "status": "uart_board_sram_pass",
- "reason": "UART board SRAM transcript and debug dump completed.",
- "instruments": {"uart_ttl": "board_sram_pass"},
- }
- bundle = build_debug_bundle(
- output_dir=Path(tmp) / "bundle",
- source="uart",
- trace=[event],
- pipeline={"status": "pass"},
- register_dump={},
- raw_artifacts=[csv_path],
- hardware_observations=hardware_observations,
- )
- analysis = analyze_debug_bundle(Path(bundle["path"]))
- hardware = json.loads((Path(bundle["path"]) / "hardware_observations.json").read_text(encoding="utf-8"))
- provenance = json.loads((Path(bundle["path"]) / "provenance.json").read_text(encoding="utf-8"))
- self.assertEqual(hardware["status"], "uart_board_sram_pass")
- self.assertEqual(provenance["fact_classes"]["hardware_observations"], "local_detected_fact")
- self.assertEqual(hardware["raw_files"][0]["artifact_role"], "uart_transcript_or_debug_export")
- hints = "\n".join(analysis["root_cause_hints"])
- self.assertIn("UART board SRAM evidence", hints)
- def test_uart_bundle_distinguishes_preflight_artifacts_from_manual_export(self) -> None:
- event = {field: 0 for field in DEBUG_EVENT_REQUIRED_FIELDS}
- event.update({
- "timebase": "uart_manual_export",
- "trace_seq": 1,
- "event_type": "manual_export_missing",
- "state": "manual_export",
- "reason": "uart_preflight_artifacts_attached_without_manual_export",
- })
- with tempfile.TemporaryDirectory() as tmp:
- report_path = Path(tmp) / "uart-preflight.json"
- report_path.write_text('{"status":"manual_required"}\n', encoding="utf-8")
- log_path = Path(tmp) / "uart-preflight.log"
- log_path.write_text("COM7 allowlist missing\n", encoding="utf-8")
- bundle = build_debug_bundle(
- output_dir=Path(tmp) / "bundle",
- source="uart",
- trace=[event],
- pipeline={"status": "not_run"},
- register_dump={},
- raw_artifacts=[report_path, log_path],
- )
- analysis = analyze_debug_bundle(Path(bundle["path"]))
- hardware = json.loads((Path(bundle["path"]) / "hardware_observations.json").read_text(encoding="utf-8"))
- self.assertEqual(hardware["status"], "uart_preflight_artifacts_attached")
- self.assertEqual(hardware["instruments"]["uart_ttl"], "manual_export_missing")
- self.assertTrue(all(item["artifact_role"] == "uart_preflight_artifact" for item in hardware["raw_files"]))
- hints = "\n".join(analysis["root_cause_hints"])
- self.assertIn("preflight/build artifacts are archived", hints)
- self.assertIn("no UART transcript/debug CSV/manual export", hints)
- def test_analyzer_reports_toolchain_result_hints(self) -> None:
- event = {field: 0 for field in DEBUG_EVENT_REQUIRED_FIELDS}
- event.update({
- "timebase": "hdl_sim",
- "trace_seq": 1,
- "event_type": "control_updated",
- "state": "ok",
- "reason": "ok",
- })
- with tempfile.TemporaryDirectory() as tmp:
- bundle = build_debug_bundle(
- output_dir=Path(tmp) / "bundle",
- source="hdl",
- trace=[event],
- pipeline={"status": "not_run"},
- register_dump={},
- sim_results={"status": "blocked_missing_tool", "missing_tools": ["iverilog", "vvp"]},
- formal_results={"status": "fail", "targets": [{"name": "fault_implies_ptc_off"}]},
- detector_selftest_results={"status": "partial", "results": []},
- td_results={"status": "pass"},
- )
- analysis = analyze_debug_bundle(Path(bundle["path"]))
- hints = "\n".join(analysis["root_cause_hints"])
- self.assertIn("HDL simulation did not run", hints)
- self.assertIn("iverilog", hints)
- self.assertIn("formal verification failed", hints)
- self.assertIn("detector selftest partially ran", hints)
- def test_analyzer_accepts_detector_selftest_dict_targets(self) -> None:
- event = {field: 0 for field in DEBUG_EVENT_REQUIRED_FIELDS}
- event.update({
- "timebase": "hdl_sim",
- "trace_seq": 1,
- "event_type": "control_updated",
- "state": "ok",
- "reason": "ok",
- })
- with tempfile.TemporaryDirectory() as tmp:
- bundle = build_debug_bundle(
- output_dir=Path(tmp) / "bundle",
- source="hdl",
- trace=[event],
- pipeline={"status": "not_run"},
- register_dump={},
- detector_selftest_results={
- "status": "blocked_missing_tool",
- "targets": {
- "icarus": {"required_tools": ["iverilog"]},
- },
- "results": [
- {"name": "icarus", "missing_tools": ["iverilog"]},
- ],
- },
- )
- analysis = analyze_debug_bundle(Path(bundle["path"]))
- self.assertEqual(analysis["status"], "pass")
- self.assertTrue(any("detector selftest did not run" in hint for hint in analysis["root_cause_hints"]))
- def test_analyzer_reports_root_cause_hints(self) -> None:
- event = {
- field: 0 for field in DEBUG_EVENT_REQUIRED_FIELDS
- }
- event.update({
- "timebase": "register_poll",
- "trace_seq": 7,
- "event_type": "sample_wait",
- "state": "idle",
- "reason": "waiting_for_sensor_ready",
- "sensor_ready": False,
- "force_off": False,
- })
- with tempfile.TemporaryDirectory() as tmp:
- bundle = build_debug_bundle(
- output_dir=Path(tmp) / "bundle",
- source="register",
- trace=[event],
- pipeline={"status": "not_run"},
- register_dump={},
- )
- analysis = analyze_debug_bundle(Path(bundle["path"]))
- self.assertEqual(analysis["status"], "pass")
- self.assertTrue(any("sensor_ready=0" in hint for hint in analysis["root_cause_hints"]))
- def test_analyzer_reports_host_safety_pwm_and_trace_gap_hints(self) -> None:
- base = {field: 0 for field in DEBUG_EVENT_REQUIRED_FIELDS}
- events = []
- for index, reason in enumerate(["host_disabled", "safety_gate", "force_off", "fan_fallback"]):
- event = dict(base)
- event.update({
- "timebase": "hdl_sim",
- "trace_seq": index + 1,
- "event_type": "control_updated",
- "state": "safe_off",
- "reason": reason,
- "source_id": 0,
- "channel": index,
- "sample_seq": index + 1,
- "config_seq": 1,
- "fault_code": 1 if reason == "host_disabled" else 0,
- "force_off": reason == "force_off",
- "host_enable": reason != "host_disabled",
- "fan_duty": 127 if reason == "fan_fallback" else 38,
- })
- events.append(event)
- events[-1]["trace_seq"] = 9
- with tempfile.TemporaryDirectory() as tmp:
- bundle = build_debug_bundle(
- output_dir=Path(tmp) / "bundle",
- source="hdl",
- trace=events,
- pipeline={"status": "not_run"},
- register_dump={},
- )
- analysis = analyze_debug_bundle(Path(bundle["path"]))
- hints = "\n".join(analysis["root_cause_hints"])
- self.assertIn("host disabled", hints)
- self.assertIn("safety gate", hints)
- self.assertIn("PTC/PWM force_off", hints)
- self.assertIn("fan fallback", hints)
- self.assertIn("trace sequence gap", hints)
- if __name__ == "__main__":
- unittest.main()
|