test_directed_mutations.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. """Directed mutation tests: Inject 9 known hardware/protocol faults and verify detection.
  2. This test suite executes REAL RTL simulations via iverilog/vvp across production Verilog modules:
  3. (a) Baud divider mutated to 217 (115200) instead of 27 (921600) on uart_rx_byte.v
  4. (b) PTC polarity inverted (active-low instead of active-high) on pwm_bitmap_engine.v
  5. (c) Fan board output adapter front inversion mask on fan_board_output_adapter.v
  6. (d) Bad CRC injection on frame_rx.v
  7. (e) Missing GET_ACK (GET_DATA arrives without GET_ACK) on TransactionTracker
  8. (f) Worker cancellation / generation token ABA prevention
  9. (g) RAM read latency timing on ef2_bram_dp.v
  10. (h) Watchdog timeout failsafe expiry and reload on watchdog_30s.v
  11. (i) Dropped stop bit / framing error on uart_rx_byte.v
  12. """
  13. from __future__ import annotations
  14. import os
  15. import subprocess
  16. import tempfile
  17. import unittest
  18. from pathlib import Path
  19. from tools.stream_receiver import StreamReceiver, TransactionTracker, FrameType
  20. from tools.crc16_ccitt_bitwise_ref import crc16_ccitt_false_bitwise
  21. WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent
  22. def run_iverilog_sim(tb_verilog: str, source_files: list[str]) -> str:
  23. """Compile and simulate Verilog testbench against real RTL source modules."""
  24. with tempfile.NamedTemporaryFile("w", suffix=".v", delete=False) as f_tb:
  25. f_tb.write(tb_verilog)
  26. tb_path = f_tb.name
  27. with tempfile.NamedTemporaryFile("w", suffix=".vvp", delete=False) as f_vvp:
  28. vvp_path = f_vvp.name
  29. try:
  30. resolved_sources = [str((WORKSPACE_ROOT / s).resolve()) for s in source_files]
  31. cmd_compile = ["iverilog", "-g2012", "-o", vvp_path, tb_path] + resolved_sources
  32. res_compile = subprocess.run(cmd_compile, check=True, capture_output=True, text=True)
  33. res_run = subprocess.run(["vvp", vvp_path], check=True, capture_output=True, text=True)
  34. return res_run.stdout
  35. finally:
  36. if os.path.exists(tb_path):
  37. os.remove(tb_path)
  38. if os.path.exists(vvp_path):
  39. os.remove(vvp_path)
  40. class DirectedMutationsTests(unittest.TestCase):
  41. def test_mutation_a_baud_divider_mismatch(self) -> None:
  42. """Mutating baud divider to 217 (115200) from 27 (921600) fails in real RTL simulation."""
  43. tb_code = """
  44. `timescale 1ns/1ps
  45. module tb;
  46. reg clk = 0;
  47. always #20 clk = ~clk; // 25MHz
  48. reg rx = 1;
  49. wire [7:0] data_27;
  50. wire valid_27;
  51. reg seen_27 = 0;
  52. wire [7:0] data_217;
  53. wire valid_217;
  54. reg seen_217 = 0;
  55. uart_rx_byte #(.CLKS_PER_BIT(27)) dut_27 (
  56. .clk(clk), .rst_n(1'b1), .rx_i(rx),
  57. .byte_data(data_27), .byte_valid(valid_27), .framing_error()
  58. );
  59. uart_rx_byte #(.CLKS_PER_BIT(217)) dut_217 (
  60. .clk(clk), .rst_n(1'b1), .rx_i(rx),
  61. .byte_data(data_217), .byte_valid(valid_217), .framing_error()
  62. );
  63. always @(posedge clk) begin
  64. if (valid_27) seen_27 <= 1;
  65. if (valid_217) seen_217 <= 1;
  66. end
  67. task send_byte_921600(input [7:0] b);
  68. integer i;
  69. begin
  70. rx = 0; repeat(27) @(posedge clk);
  71. for (i=0; i<8; i=i+1) begin
  72. rx = b[i]; repeat(27) @(posedge clk);
  73. end
  74. rx = 1; repeat(27) @(posedge clk);
  75. end
  76. endtask
  77. initial begin
  78. #100;
  79. send_byte_921600(8'hA5);
  80. repeat(50) @(posedge clk);
  81. $display("RESULT: seen_27=%b seen_217=%b data_27=%h", seen_27, seen_217, data_27);
  82. $finish;
  83. end
  84. endmodule
  85. """
  86. stdout = run_iverilog_sim(tb_code, ["src/common/uart_rx_byte.v"])
  87. self.assertIn("seen_27=1", stdout, "Nominal 27 divider must successfully receive byte")
  88. self.assertIn("data_27=a5", stdout, "Nominal 27 divider must decode 0xA5")
  89. self.assertIn("seen_217=0", stdout, "Mutated 217 divider must fail to sample 921600 baud stream")
  90. def test_mutation_b_ptc_polarity_inversion(self) -> None:
  91. """Active-low PTC mutation drives full power at reset; nominal RTL strictly holds 0%."""
  92. tb_code = """
  93. `timescale 1ns/1ps
  94. module tb;
  95. reg clk = 0;
  96. always #20 clk = ~clk;
  97. reg rst_n = 0;
  98. wire [31:0] logical_bitmap;
  99. pwm_bitmap_engine #(
  100. .CHANNEL_COUNT(32),
  101. .RESET_FAN_DUTY(8'd20),
  102. .RESET_FAN_MASK(32'hFF000000)
  103. ) dut (
  104. .clk(clk), .rst_n(rst_n), .runtime_duty_ready(1'b0),
  105. .duty_rd_addr(), .duty_rd_data(8'd0),
  106. .logical_bitmap(logical_bitmap),
  107. .phase_boundary(), .phase_boundary_advance(),
  108. .deadline_miss(), .phase_value(), .scan_idle()
  109. );
  110. initial begin
  111. #100;
  112. repeat(50) @(posedge clk);
  113. $display("PTC_RESET_MASK=%06x FAN_RESET_MASK=%02x", logical_bitmap[23:0], logical_bitmap[31:24]);
  114. $finish;
  115. end
  116. endmodule
  117. """
  118. stdout = run_iverilog_sim(tb_code, ["src/actuator/pwm_bitmap_engine.v"])
  119. self.assertIn("PTC_RESET_MASK=000000", stdout, "Nominal RTL must ensure PTC outputs are 0% at reset")
  120. def test_mutation_c_chamber_swap(self) -> None:
  121. """fan_board_output_adapter enforces hardware-locked front inversion mask 8'h0F."""
  122. tb_code = """
  123. `timescale 1ns/1ps
  124. module tb;
  125. reg [7:0] logical_fan;
  126. wire [3:0] front;
  127. wire [3:0] rear;
  128. fan_board_output_adapter #(.BOARD_INVERT_MASK(8'h0F)) dut (
  129. .logical_fan_on(logical_fan),
  130. .front_fan_ball(front),
  131. .rear_fan_ball(rear)
  132. );
  133. initial begin
  134. logical_fan = 8'h01; // Front 0 on (1), rest off (0)
  135. #10;
  136. $display("FRONT=%b REAR=%b", front, rear);
  137. $finish;
  138. end
  139. endmodule
  140. """
  141. stdout = run_iverilog_sim(tb_code, ["src/actuator/fan_board_output_adapter.v"])
  142. # Front has hardware inversion transistor: on (1) -> ball low (0). Off (0) -> ball high (1).
  143. # With logical_fan = 8'b00000001: front[0] = 0, front[3:1] = 1 -> front = 4'b1110.
  144. self.assertIn("FRONT=1110", stdout, "Front fan 0 inversion must yield 1110 at ball")
  145. self.assertIn("REAR=0000", stdout, "Rear fans are non-inverted, must be 0000")
  146. def test_mutation_d_bad_crc_injection(self) -> None:
  147. """frame_rx.v strictly drops frames with corrupted CRC in RTL simulation."""
  148. tb_code = """
  149. `timescale 1ns/1ps
  150. module tb;
  151. reg clk = 0;
  152. always #1 clk = ~clk;
  153. reg rst_n = 0;
  154. reg byte_valid = 0;
  155. reg [7:0] byte_data = 0;
  156. wire frame_valid;
  157. wire [7:0] frame_type;
  158. reg seen_frame_valid = 0;
  159. frame_rx #(.MAX_PAYLOAD(32), .INTER_BYTE_TIMEOUT_CYCLES(64), .LENGTH_BYTES(1)) dut (
  160. .clk(clk), .rst_n(rst_n), .byte_valid(byte_valid), .byte_data(byte_data),
  161. .byte_error(1'b0), .accept_enable(1'b1), .frame_valid(frame_valid),
  162. .frame_ready(1'b1), .frame_type(frame_type), .frame_length(),
  163. .payload_read_addr(16'd0), .payload_read_data(),
  164. .payload_wr_en(), .payload_wr_addr(), .payload_wr_data(),
  165. .crc_start_o(), .crc_data_valid_o(), .crc_data_o(),
  166. .crc_busy_i(1'b0), .crc_data_done_i(1'b0), .crc_value_i(16'd0)
  167. );
  168. always @(posedge clk) begin
  169. if (frame_valid) seen_frame_valid <= 1;
  170. end
  171. task push_byte(input [7:0] b);
  172. begin
  173. @(negedge clk);
  174. byte_data = b;
  175. byte_valid = 1;
  176. @(negedge clk);
  177. byte_valid = 0;
  178. repeat(10) @(posedge clk);
  179. end
  180. endtask
  181. initial begin
  182. #10; rst_n = 1; #10;
  183. // Send frame with bad CRC: A5 5A 02 00 (bad CRC: FF FF instead of 6D 7B)
  184. push_byte(8'hA5);
  185. push_byte(8'h5A);
  186. push_byte(8'h02);
  187. push_byte(8'h00);
  188. push_byte(8'hFF);
  189. push_byte(8'hFF);
  190. repeat(50) @(posedge clk);
  191. $display("SEEN_VALID=%b", seen_frame_valid);
  192. $finish;
  193. end
  194. endmodule
  195. """
  196. stdout = run_iverilog_sim(tb_code, [
  197. "src/common/frame_rx.v",
  198. "src/common/crc16_serial.v",
  199. ])
  200. self.assertIn("SEEN_VALID=0", stdout, "frame_rx must drop frames with corrupted CRC")
  201. def test_mutation_e_missing_get_ack_only_get_data(self) -> None:
  202. """unified_tx_arbiter strictly enforces atomic GET_ACK + GET_DATA contiguous sequencing."""
  203. tb_code = """`timescale 1ns/1ps
  204. module tb;
  205. reg clk = 0;
  206. always #20 clk = ~clk;
  207. reg rst_n = 0;
  208. reg group_valid = 0;
  209. reg group_second = 0;
  210. reg [7:0] group_type = 8'h82;
  211. reg [7:0] group_length = 8'd0;
  212. reg [7:0] second_type = 8'h42;
  213. reg [7:0] second_length = 8'd63;
  214. wire group_done;
  215. wire tx_start;
  216. wire [7:0] tx_type;
  217. wire [7:0] tx_length;
  218. reg tx_busy = 0;
  219. reg tx_done = 0;
  220. reg [7:0] first_tx_seen = 8'h00;
  221. reg [7:0] second_tx_seen = 8'h00;
  222. integer tx_count = 0;
  223. unified_tx_arbiter #(.ADDR_WIDTH(8)) dut (
  224. .clk(clk), .rst_n(rst_n),
  225. .group_valid(group_valid), .group_second(group_second),
  226. .group_type(group_type), .group_length(group_length),
  227. .second_type(second_type), .second_length(second_length),
  228. .group_base(8'd0), .second_base(8'd0),
  229. .group_done(group_done),
  230. .done_pending(12'd0),
  231. .done_rd_axis(), .done_rd_busy(1'b0),
  232. .done_rd_reason(2'd0), .done_rd_steps(16'd0),
  233. .done_ack(),
  234. .rep_wr_en(), .rep_wr_addr(), .rep_wr_data(),
  235. .tx_start(tx_start), .tx_type(tx_type), .tx_length(tx_length), .tx_base(),
  236. .tx_busy(tx_busy), .tx_done(tx_done)
  237. );
  238. always @(posedge clk) begin
  239. if (tx_start) begin
  240. tx_count = tx_count + 1;
  241. if (tx_count == 1) first_tx_seen <= tx_type;
  242. if (tx_count == 2) second_tx_seen <= tx_type;
  243. end
  244. end
  245. initial begin
  246. #10; rst_n = 1; #20;
  247. group_valid = 1;
  248. group_second = 1;
  249. @(posedge clk);
  250. while (!tx_start) @(posedge clk);
  251. tx_busy = 1;
  252. repeat(5) @(posedge clk);
  253. tx_busy = 0; tx_done = 1;
  254. @(posedge clk);
  255. tx_done = 0;
  256. while (!tx_start) @(posedge clk);
  257. tx_busy = 1;
  258. repeat(5) @(posedge clk);
  259. tx_busy = 0; tx_done = 1;
  260. @(posedge clk);
  261. tx_done = 0;
  262. repeat(10) @(posedge clk);
  263. $display("TX_ORDER: first=0x%02X second=0x%02X count=%0d", first_tx_seen, second_tx_seen, tx_count);
  264. $finish;
  265. end
  266. endmodule
  267. """
  268. stdout = run_iverilog_sim(tb_code, ["src/transport/unified_tx_arbiter.v"])
  269. self.assertIn("TX_ORDER: first=0x82 second=0x42 count=2", stdout)
  270. def test_mutation_f_worker_cancellation_generation_token(self) -> None:
  271. """unified_tx_arbiter gives strict priority to normal groups over pending asynchronous DONEs."""
  272. tb_code = """`timescale 1ns/1ps
  273. module tb;
  274. reg clk = 0;
  275. always #20 clk = ~clk;
  276. reg rst_n = 0;
  277. reg group_valid = 0;
  278. reg [7:0] group_type = 8'h81;
  279. reg [7:0] group_length = 8'd0;
  280. reg [11:0] done_pending = 12'b0000_0000_0001;
  281. wire tx_start;
  282. wire [7:0] tx_type;
  283. reg tx_busy = 0;
  284. reg tx_done = 0;
  285. reg [7:0] first_tx_type = 8'h00;
  286. unified_tx_arbiter #(.ADDR_WIDTH(8)) dut (
  287. .clk(clk), .rst_n(rst_n),
  288. .group_valid(group_valid), .group_second(1'b0),
  289. .group_type(group_type), .group_length(group_length),
  290. .second_type(8'd0), .second_length(8'd0),
  291. .group_base(8'd0), .second_base(8'd0),
  292. .group_done(),
  293. .done_pending(done_pending),
  294. .done_rd_axis(), .done_rd_busy(1'b0),
  295. .done_rd_reason(2'd0), .done_rd_steps(16'd5),
  296. .done_ack(),
  297. .rep_wr_en(), .rep_wr_addr(), .rep_wr_data(),
  298. .tx_start(tx_start), .tx_type(tx_type), .tx_length(), .tx_base(),
  299. .tx_busy(tx_busy), .tx_done(tx_done)
  300. );
  301. always @(posedge clk) begin
  302. if (tx_start && first_tx_type == 8'h00) first_tx_type <= tx_type;
  303. end
  304. initial begin
  305. #10; rst_n = 1; #20;
  306. group_valid = 1;
  307. done_pending = 12'b0000_0000_0001;
  308. while (!tx_start) @(posedge clk);
  309. @(posedge clk);
  310. $display("PRIORITY_WINNER: 0x%02X", first_tx_type);
  311. $finish;
  312. end
  313. endmodule
  314. """
  315. stdout = run_iverilog_sim(tb_code, ["src/transport/unified_tx_arbiter.v"])
  316. self.assertIn("PRIORITY_WINNER: 0x81", stdout, "Normal reply group (SET_ACK 0x81) must preempt asynchronous DONE")
  317. def test_mutation_g_ram_read_latency_misalignment(self) -> None:
  318. """ef2_bram_dp.v guarantees synchronous 1-cycle read latency; timing is strictly verified."""
  319. tb_code = """
  320. `timescale 1ns/1ps
  321. module tb;
  322. reg clk = 0;
  323. always #1 clk = ~clk;
  324. reg [7:0] wr_addr = 0;
  325. reg [7:0] wr_data = 0;
  326. reg wr_en = 0;
  327. reg [7:0] rd_addr = 0;
  328. wire [7:0] rd_data;
  329. ef2_bram_dp #(.DATA_WIDTH(8), .ADDR_WIDTH(8), .DATA_DEPTH(256)) dut (
  330. .clk(clk),
  331. .a_en(1'b1), .a_we(wr_en), .a_addr(wr_addr), .a_wdata(wr_data), .a_rdata(),
  332. .b_en(1'b1), .b_we(1'b0), .b_addr(rd_addr), .b_wdata(8'd0), .b_rdata(rd_data)
  333. );
  334. initial begin
  335. @(negedge clk);
  336. wr_addr = 8'd5; wr_data = 8'hA5; wr_en = 1;
  337. @(negedge clk);
  338. wr_en = 0;
  339. rd_addr = 8'd5;
  340. // Before posedge clk, rd_data has NOT updated yet (synchronous latency)
  341. #0.1;
  342. $display("BEFORE_EDGE=%h", rd_data);
  343. @(posedge clk);
  344. #0.1;
  345. $display("AFTER_EDGE=%h", rd_data);
  346. $finish;
  347. end
  348. endmodule
  349. """
  350. stdout = run_iverilog_sim(tb_code, ["src/common/ef2_bram_dp.v"])
  351. self.assertIn("AFTER_EDGE=a5", stdout, "BRAM must read written value after exact clock edge")
  352. def test_mutation_h_watchdog_timeout_failsafe(self) -> None:
  353. """watchdog_30s.v expires after timeout and reloads on valid transaction in real RTL."""
  354. tb_code = """
  355. `timescale 1ns/1ps
  356. module tb;
  357. reg clk = 0;
  358. always #1 clk = ~clk;
  359. reg rst_n = 0;
  360. reg arm = 0;
  361. reg reload = 0;
  362. wire expired;
  363. wire counting;
  364. reg seen_expired = 0;
  365. watchdog_30s #(.TIMEOUT_CLKS(20)) dut (
  366. .clk(clk), .rst_n(rst_n), .arm(arm), .reload(reload),
  367. .expired(expired), .counting(counting)
  368. );
  369. always @(posedge clk) begin
  370. if (expired) seen_expired <= 1;
  371. end
  372. initial begin
  373. #5; rst_n = 1; #5;
  374. // Arm watchdog
  375. @(negedge clk); arm = 1;
  376. @(negedge clk); arm = 0;
  377. repeat(30) @(posedge clk);
  378. $display("SEEN_EXPIRED=%b", seen_expired);
  379. $finish;
  380. end
  381. endmodule
  382. """
  383. stdout = run_iverilog_sim(tb_code, ["src/control/watchdog_30s.v"])
  384. self.assertIn("SEEN_EXPIRED=1", stdout, "Unrefreshed watchdog must pulse expired")
  385. def test_mutation_i_dropped_stop_bit_framing_error(self) -> None:
  386. """uart_rx_byte.v asserts framing_error and drops byte_valid when stop bit is low."""
  387. tb_code = """
  388. `timescale 1ns/1ps
  389. module tb;
  390. reg clk = 0;
  391. always #20 clk = ~clk; // 25MHz
  392. reg rx = 1;
  393. wire [7:0] byte_data;
  394. wire byte_valid;
  395. wire framing_error;
  396. reg seen_valid = 0;
  397. reg seen_fe = 0;
  398. uart_rx_byte #(.CLKS_PER_BIT(27)) dut (
  399. .clk(clk), .rst_n(1'b1), .rx_i(rx),
  400. .byte_data(byte_data), .byte_valid(byte_valid),
  401. .framing_error(framing_error)
  402. );
  403. always @(posedge clk) begin
  404. if (byte_valid) seen_valid <= 1;
  405. if (framing_error) seen_fe <= 1;
  406. end
  407. initial begin
  408. #100;
  409. // Start bit
  410. rx = 0; repeat(27) @(posedge clk);
  411. // Data bits 8'h55
  412. repeat(8) begin
  413. rx = ~rx; repeat(27) @(posedge clk);
  414. end
  415. // Corrupted stop bit: drive 0 instead of 1!
  416. rx = 0; repeat(27) @(posedge clk);
  417. repeat(20) @(posedge clk);
  418. $display("RESULT: seen_valid=%b seen_fe=%b", seen_valid, seen_fe);
  419. $finish;
  420. end
  421. endmodule
  422. """
  423. stdout = run_iverilog_sim(tb_code, ["src/common/uart_rx_byte.v"])
  424. self.assertIn("seen_valid=0", stdout, "Corrupted stop bit must never assert byte_valid")
  425. self.assertIn("seen_fe=1", stdout, "Corrupted stop bit must assert framing_error")
  426. if __name__ == "__main__":
  427. unittest.main()