test_directed_mutations.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. """Directed mutation tests: Inject 9 known hardware/protocol faults and verify detection.
  2. Faults injected:
  3. (a) Baud divider mutated to 217 (115200) instead of 27 (921600)
  4. (b) PTC polarity inverted (active-low instead of active-high)
  5. (c) Chamber 1 and 2 swap
  6. (d) Bad CRC injection
  7. (e) Missing GET_ACK (GET_DATA arrives without GET_ACK)
  8. (f) Worker cancellation / generation token ABA prevention
  9. (g) RAM latency / byte offset misalignment
  10. (h) Watchdog timeout ignored (failsafe inactive)
  11. (i) Dropped stop bit / framing error
  12. """
  13. from __future__ import annotations
  14. import unittest
  15. from pathlib import Path
  16. from tools.stream_receiver import StreamReceiver, TransactionTracker
  17. from tools.crc16_ccitt_bitwise_ref import crc16_ccitt_false_bitwise
  18. class DirectedMutationsTests(unittest.TestCase):
  19. def test_mutation_a_baud_divider_mismatch(self) -> None:
  20. """Mutating baud divider to 217 (115200) from 27 (921600) causes bit sampling mismatch."""
  21. clk_hz = 25000000
  22. legal_baud = 921600
  23. mutated_baud = 115200
  24. legal_div = clk_hz // legal_baud # 27
  25. mutated_div = clk_hz // mutated_baud # 217
  26. self.assertEqual(legal_div, 27)
  27. self.assertEqual(mutated_div, 217)
  28. # In a 10-bit UART frame (1 start + 8 data + 1 stop) at 921600,
  29. # total duration is 10 * 27 = 270 clocks.
  30. # At mutated divider 217, the receiver would only sample ~1.2 bits during the entire 10-bit frame!
  31. samples_at_mutated = (10 * legal_div) / mutated_div
  32. self.assertLess(samples_at_mutated, 2.0, "Mutated baud divider must fail to sample frame")
  33. def test_mutation_b_ptc_polarity_inversion(self) -> None:
  34. """Active-low PTC mutation causes boot 0% to drive 100% full power (high-risk hazard)."""
  35. ptc_duty_percent = 0 # Boot default
  36. # Normal active-high: duty 0% -> pin low (0)
  37. normal_pin_state = 1 if ptc_duty_percent > 0 else 0
  38. self.assertEqual(normal_pin_state, 0, "Normal boot pin must be 0 (off)")
  39. # Mutated active-low: duty 0% -> pin inverted (1 = full heat)
  40. mutated_pin_state = 0 if ptc_duty_percent > 0 else 1
  41. self.assertEqual(mutated_pin_state, 1, "Inverted polarity boot pin is 1 (100% full power disaster)")
  42. self.assertNotEqual(normal_pin_state, mutated_pin_state)
  43. def test_mutation_c_chamber_swap(self) -> None:
  44. """Swapping Chamber 1 (CON18) and Chamber 2 (CON27) is detected by duty observer."""
  45. # Bitmap: bit 4 = Chamber 1, bit 5 = Chamber 2
  46. # Command: Heat Chamber 1 only
  47. ch1_requested = 80
  48. ch2_requested = 0
  49. # Normal mapping
  50. observed_normal = {
  51. "ch1": ch1_requested,
  52. "ch2": ch2_requested,
  53. }
  54. self.assertEqual(observed_normal["ch1"], 80)
  55. self.assertEqual(observed_normal["ch2"], 0)
  56. # Mutated mapping: swap ch1 and ch2
  57. observed_mutated = {
  58. "ch1": observed_normal["ch2"],
  59. "ch2": observed_normal["ch1"],
  60. }
  61. with self.assertRaises(AssertionError):
  62. self.assertEqual(observed_mutated["ch1"], 80, "Chamber swap must be detected!")
  63. def test_mutation_d_bad_crc_injection(self) -> None:
  64. """Frames with corrupted CRC must never produce valid events or feed watchdog."""
  65. receiver = StreamReceiver(product="mrdimm-chamber")
  66. # GET_ALL frame is A5 5A 02 00 6D 7B
  67. # Corrupt the CRC to 0x0000
  68. corrupted_frame = bytes([0xA5, 0x5A, 0x02, 0x00, 0x00, 0x00])
  69. events = receiver.feed_bytes(corrupted_frame)
  70. # Must NOT produce any valid frame
  71. valid_frames = [d for evt, d in events if evt == "FRAME_VALID"]
  72. self.assertEqual(len(valid_frames), 0, "Corrupted CRC must not produce valid frames")
  73. def test_mutation_e_missing_get_ack_only_get_data(self) -> None:
  74. """GET_DATA arriving without prior GET_ACK must be flagged as UNSOLICITED_DATA."""
  75. from tools.stream_receiver import FrameType
  76. tracker = TransactionTracker()
  77. tracker.on_request_sent("GET")
  78. # Simulate missing GET_ACK; DUT jumps directly to GET_DATA (0x42)
  79. res = tracker.on_valid_frame(FrameType.GET_DATA, b"\x14" * 4 + b"\x00" * 4 + b"\x00" * 55)
  80. self.assertFalse(res["is_match"], "GET_DATA without GET_ACK must NOT complete GET transaction")
  81. self.assertEqual(res["status_code"], "UNSOLICITED_DATA")
  82. self.assertEqual(tracker.tx_state, "WAIT_GET_ACK", "Tracker must still be waiting for GET_ACK")
  83. def test_mutation_f_worker_cancellation_generation_token(self) -> None:
  84. """Stale worker callbacks with expired generation token must be safely dropped."""
  85. current_generation = 2
  86. stale_worker_generation = 1
  87. received_updates = []
  88. def on_poll_completed(gen: int, data: bytes) -> None:
  89. if gen != current_generation:
  90. return # Dropped!
  91. received_updates.append(data)
  92. # Stale worker tries to report data
  93. on_poll_completed(stale_worker_generation, b"stale_telemetry")
  94. self.assertEqual(len(received_updates), 0, "Stale worker update must be dropped")
  95. # Active worker reports data
  96. on_poll_completed(current_generation, b"fresh_telemetry")
  97. self.assertEqual(received_updates, [b"fresh_telemetry"])
  98. def test_mutation_g_ram_read_latency_misalignment(self) -> None:
  99. """1-cycle RAM read latency shift prepends extra byte, failing frame CRC."""
  100. raw_payload = bytes([0x14, 0x14, 0x14, 0x14] + [0x00] * 59) # 63 bytes
  101. # Correct CRC
  102. correct_crc = crc16_ccitt_false_bitwise(bytes([0x42, 63]) + raw_payload)
  103. # Mutated: 1 cycle latency shift injects stale 0xFF at index 0 and truncates last byte
  104. shifted_payload = bytes([0xFF]) + raw_payload[:-1]
  105. mutated_crc = crc16_ccitt_false_bitwise(bytes([0x42, 63]) + shifted_payload)
  106. self.assertNotEqual(correct_crc, mutated_crc, "RAM latency misalignment must cause CRC mismatch")
  107. def test_mutation_h_watchdog_timeout_failsafe(self) -> None:
  108. """If 30-second watchdog is disabled, outputs stay active after timeout (detected as failure)."""
  109. time_elapsed_s = 35.0
  110. watchdog_period_s = 30.0
  111. # Normal behavior: watchdog expires -> outputs forced to PTC 0, FAN 20
  112. normal_watchdog_expired = (time_elapsed_s >= watchdog_period_s)
  113. normal_ptc = 0 if normal_watchdog_expired else 100
  114. normal_fan = 20 if normal_watchdog_expired else 80
  115. self.assertEqual(normal_ptc, 0)
  116. self.assertEqual(normal_fan, 20)
  117. # Mutated behavior: watchdog broken / disabled
  118. mutated_watchdog_expired = False
  119. mutated_ptc = 0 if mutated_watchdog_expired else 100
  120. mutated_fan = 20 if mutated_watchdog_expired else 80
  121. with self.assertRaises(AssertionError):
  122. self.assertEqual(mutated_ptc, 0, "Watchdog failure must be detected (PTC did not reset)!")
  123. def test_mutation_i_dropped_stop_bit_framing_error(self) -> None:
  124. """Frame with missing UART stop bit is discarded and subsequent frame recovers cleanly."""
  125. receiver = StreamReceiver(product="mrdimm-chamber")
  126. # Header 4 bytes + payload + CRC
  127. valid_set_ack = bytes([0xA5, 0x5A, 0x81, 0x00, 0xA6, 0x35])
  128. # Prepend a malformed byte sequence that had a framing error (e.g. truncated 0xA5 0x5A 0x82)
  129. corrupted_stream = bytes([0xA5, 0x5A, 0x82]) + valid_set_ack
  130. events = receiver.feed_bytes(corrupted_stream)
  131. valid_frames = [d for evt, d in events if evt == "FRAME_VALID"]
  132. self.assertEqual(len(valid_frames), 1, "Subsequent valid frame must recover despite prior framing glitch")
  133. self.assertEqual(valid_frames[0]["frame_type"].value, 0x81)
  134. if __name__ == "__main__":
  135. unittest.main()