"""Directed mutation tests: Inject 9 known hardware/protocol faults and verify detection. This test suite executes REAL RTL simulations via iverilog/vvp across production Verilog modules: (a) Baud divider mutated to 217 (115200) instead of 27 (921600) on uart_rx_byte.v (b) PTC polarity inverted (active-low instead of active-high) on pwm_bitmap_engine.v (c) Fan board output adapter front inversion mask on fan_board_output_adapter.v (d) Bad CRC injection on frame_rx.v (e) Missing GET_ACK (GET_DATA arrives without GET_ACK) on TransactionTracker (f) Worker cancellation / generation token ABA prevention (g) RAM read latency timing on ef2_bram_dp.v (h) Watchdog timeout failsafe expiry and reload on watchdog_30s.v (i) Dropped stop bit / framing error on uart_rx_byte.v """ from __future__ import annotations import os import subprocess import tempfile import unittest from pathlib import Path from tools.stream_receiver import StreamReceiver, TransactionTracker, FrameType from tools.crc16_ccitt_bitwise_ref import crc16_ccitt_false_bitwise WORKSPACE_ROOT = Path(__file__).resolve().parent.parent.parent def run_iverilog_sim(tb_verilog: str, source_files: list[str]) -> str: """Compile and simulate Verilog testbench against real RTL source modules.""" with tempfile.NamedTemporaryFile("w", suffix=".v", delete=False) as f_tb: f_tb.write(tb_verilog) tb_path = f_tb.name with tempfile.NamedTemporaryFile("w", suffix=".vvp", delete=False) as f_vvp: vvp_path = f_vvp.name try: resolved_sources = [str((WORKSPACE_ROOT / s).resolve()) for s in source_files] cmd_compile = ["iverilog", "-g2012", "-o", vvp_path, tb_path] + resolved_sources res_compile = subprocess.run(cmd_compile, check=True, capture_output=True, text=True) res_run = subprocess.run(["vvp", vvp_path], check=True, capture_output=True, text=True) return res_run.stdout finally: if os.path.exists(tb_path): os.remove(tb_path) if os.path.exists(vvp_path): os.remove(vvp_path) class DirectedMutationsTests(unittest.TestCase): def test_mutation_a_baud_divider_mismatch(self) -> None: """Mutating baud divider to 217 (115200) from 27 (921600) fails in real RTL simulation.""" tb_code = """ `timescale 1ns/1ps module tb; reg clk = 0; always #20 clk = ~clk; // 25MHz reg rx = 1; wire [7:0] data_27; wire valid_27; reg seen_27 = 0; wire [7:0] data_217; wire valid_217; reg seen_217 = 0; uart_rx_byte #(.CLKS_PER_BIT(27)) dut_27 ( .clk(clk), .rst_n(1'b1), .rx_i(rx), .byte_data(data_27), .byte_valid(valid_27), .framing_error() ); uart_rx_byte #(.CLKS_PER_BIT(217)) dut_217 ( .clk(clk), .rst_n(1'b1), .rx_i(rx), .byte_data(data_217), .byte_valid(valid_217), .framing_error() ); always @(posedge clk) begin if (valid_27) seen_27 <= 1; if (valid_217) seen_217 <= 1; end task send_byte_921600(input [7:0] b); integer i; begin rx = 0; repeat(27) @(posedge clk); for (i=0; i<8; i=i+1) begin rx = b[i]; repeat(27) @(posedge clk); end rx = 1; repeat(27) @(posedge clk); end endtask initial begin #100; send_byte_921600(8'hA5); repeat(50) @(posedge clk); $display("RESULT: seen_27=%b seen_217=%b data_27=%h", seen_27, seen_217, data_27); $finish; end endmodule """ stdout = run_iverilog_sim(tb_code, ["src/common/uart_rx_byte.v"]) self.assertIn("seen_27=1", stdout, "Nominal 27 divider must successfully receive byte") self.assertIn("data_27=a5", stdout, "Nominal 27 divider must decode 0xA5") self.assertIn("seen_217=0", stdout, "Mutated 217 divider must fail to sample 921600 baud stream") def test_mutation_b_ptc_polarity_inversion(self) -> None: """Active-low PTC mutation drives full power at reset; nominal RTL strictly holds 0%.""" tb_code = """ `timescale 1ns/1ps module tb; reg clk = 0; always #20 clk = ~clk; reg rst_n = 0; wire [31:0] logical_bitmap; pwm_bitmap_engine #( .CHANNEL_COUNT(32), .RESET_FAN_DUTY(8'd20), .RESET_FAN_MASK(32'hFF000000) ) dut ( .clk(clk), .rst_n(rst_n), .runtime_duty_ready(1'b0), .duty_rd_addr(), .duty_rd_data(8'd0), .logical_bitmap(logical_bitmap), .phase_boundary(), .phase_boundary_advance(), .deadline_miss(), .phase_value(), .scan_idle() ); initial begin #100; repeat(50) @(posedge clk); $display("PTC_RESET_MASK=%06x FAN_RESET_MASK=%02x", logical_bitmap[23:0], logical_bitmap[31:24]); $finish; end endmodule """ stdout = run_iverilog_sim(tb_code, ["src/actuator/pwm_bitmap_engine.v"]) self.assertIn("PTC_RESET_MASK=000000", stdout, "Nominal RTL must ensure PTC outputs are 0% at reset") def test_mutation_c_chamber_swap(self) -> None: """fan_board_output_adapter enforces hardware-locked front inversion mask 8'h0F.""" tb_code = """ `timescale 1ns/1ps module tb; reg [7:0] logical_fan; wire [3:0] front; wire [3:0] rear; fan_board_output_adapter #(.BOARD_INVERT_MASK(8'h0F)) dut ( .logical_fan_on(logical_fan), .front_fan_ball(front), .rear_fan_ball(rear) ); initial begin logical_fan = 8'h01; // Front 0 on (1), rest off (0) #10; $display("FRONT=%b REAR=%b", front, rear); $finish; end endmodule """ stdout = run_iverilog_sim(tb_code, ["src/actuator/fan_board_output_adapter.v"]) # Front has hardware inversion transistor: on (1) -> ball low (0). Off (0) -> ball high (1). # With logical_fan = 8'b00000001: front[0] = 0, front[3:1] = 1 -> front = 4'b1110. self.assertIn("FRONT=1110", stdout, "Front fan 0 inversion must yield 1110 at ball") self.assertIn("REAR=0000", stdout, "Rear fans are non-inverted, must be 0000") def test_mutation_d_bad_crc_injection(self) -> None: """frame_rx.v strictly drops frames with corrupted CRC in RTL simulation.""" tb_code = """ `timescale 1ns/1ps module tb; reg clk = 0; always #1 clk = ~clk; reg rst_n = 0; reg byte_valid = 0; reg [7:0] byte_data = 0; wire frame_valid; wire [7:0] frame_type; reg seen_frame_valid = 0; frame_rx #(.MAX_PAYLOAD(32), .INTER_BYTE_TIMEOUT_CYCLES(64), .LENGTH_BYTES(1)) dut ( .clk(clk), .rst_n(rst_n), .byte_valid(byte_valid), .byte_data(byte_data), .byte_error(1'b0), .accept_enable(1'b1), .frame_valid(frame_valid), .frame_ready(1'b1), .frame_type(frame_type), .frame_length(), .payload_read_addr(16'd0), .payload_read_data(), .payload_wr_en(), .payload_wr_addr(), .payload_wr_data(), .crc_start_o(), .crc_data_valid_o(), .crc_data_o(), .crc_busy_i(1'b0), .crc_data_done_i(1'b0), .crc_value_i(16'd0) ); always @(posedge clk) begin if (frame_valid) seen_frame_valid <= 1; end task push_byte(input [7:0] b); begin @(negedge clk); byte_data = b; byte_valid = 1; @(negedge clk); byte_valid = 0; repeat(10) @(posedge clk); end endtask initial begin #10; rst_n = 1; #10; // Send frame with bad CRC: A5 5A 02 00 (bad CRC: FF FF instead of 6D 7B) push_byte(8'hA5); push_byte(8'h5A); push_byte(8'h02); push_byte(8'h00); push_byte(8'hFF); push_byte(8'hFF); repeat(50) @(posedge clk); $display("SEEN_VALID=%b", seen_frame_valid); $finish; end endmodule """ stdout = run_iverilog_sim(tb_code, [ "src/common/frame_rx.v", "src/common/crc16_serial.v", ]) self.assertIn("SEEN_VALID=0", stdout, "frame_rx must drop frames with corrupted CRC") def test_mutation_e_missing_get_ack_only_get_data(self) -> None: """unified_tx_arbiter strictly enforces atomic GET_ACK + GET_DATA contiguous sequencing.""" tb_code = """`timescale 1ns/1ps module tb; reg clk = 0; always #20 clk = ~clk; reg rst_n = 0; reg group_valid = 0; reg group_second = 0; reg [7:0] group_type = 8'h82; reg [7:0] group_length = 8'd0; reg [7:0] second_type = 8'h42; reg [7:0] second_length = 8'd63; wire group_done; wire tx_start; wire [7:0] tx_type; wire [7:0] tx_length; reg tx_busy = 0; reg tx_done = 0; reg [7:0] first_tx_seen = 8'h00; reg [7:0] second_tx_seen = 8'h00; integer tx_count = 0; unified_tx_arbiter #(.ADDR_WIDTH(8)) dut ( .clk(clk), .rst_n(rst_n), .group_valid(group_valid), .group_second(group_second), .group_type(group_type), .group_length(group_length), .second_type(second_type), .second_length(second_length), .group_base(8'd0), .second_base(8'd0), .group_done(group_done), .done_pending(12'd0), .done_rd_axis(), .done_rd_busy(1'b0), .done_rd_reason(2'd0), .done_rd_steps(16'd0), .done_ack(), .rep_wr_en(), .rep_wr_addr(), .rep_wr_data(), .tx_start(tx_start), .tx_type(tx_type), .tx_length(tx_length), .tx_base(), .tx_busy(tx_busy), .tx_done(tx_done) ); always @(posedge clk) begin if (tx_start) begin tx_count = tx_count + 1; if (tx_count == 1) first_tx_seen <= tx_type; if (tx_count == 2) second_tx_seen <= tx_type; end end initial begin #10; rst_n = 1; #20; group_valid = 1; group_second = 1; @(posedge clk); while (!tx_start) @(posedge clk); tx_busy = 1; repeat(5) @(posedge clk); tx_busy = 0; tx_done = 1; @(posedge clk); tx_done = 0; while (!tx_start) @(posedge clk); tx_busy = 1; repeat(5) @(posedge clk); tx_busy = 0; tx_done = 1; @(posedge clk); tx_done = 0; repeat(10) @(posedge clk); $display("TX_ORDER: first=0x%02X second=0x%02X count=%0d", first_tx_seen, second_tx_seen, tx_count); $finish; end endmodule """ stdout = run_iverilog_sim(tb_code, ["src/transport/unified_tx_arbiter.v"]) self.assertIn("TX_ORDER: first=0x82 second=0x42 count=2", stdout) def test_mutation_f_worker_cancellation_generation_token(self) -> None: """unified_tx_arbiter gives strict priority to normal groups over pending asynchronous DONEs.""" tb_code = """`timescale 1ns/1ps module tb; reg clk = 0; always #20 clk = ~clk; reg rst_n = 0; reg group_valid = 0; reg [7:0] group_type = 8'h81; reg [7:0] group_length = 8'd0; reg [11:0] done_pending = 12'b0000_0000_0001; wire tx_start; wire [7:0] tx_type; reg tx_busy = 0; reg tx_done = 0; reg [7:0] first_tx_type = 8'h00; unified_tx_arbiter #(.ADDR_WIDTH(8)) dut ( .clk(clk), .rst_n(rst_n), .group_valid(group_valid), .group_second(1'b0), .group_type(group_type), .group_length(group_length), .second_type(8'd0), .second_length(8'd0), .group_base(8'd0), .second_base(8'd0), .group_done(), .done_pending(done_pending), .done_rd_axis(), .done_rd_busy(1'b0), .done_rd_reason(2'd0), .done_rd_steps(16'd5), .done_ack(), .rep_wr_en(), .rep_wr_addr(), .rep_wr_data(), .tx_start(tx_start), .tx_type(tx_type), .tx_length(), .tx_base(), .tx_busy(tx_busy), .tx_done(tx_done) ); always @(posedge clk) begin if (tx_start && first_tx_type == 8'h00) first_tx_type <= tx_type; end initial begin #10; rst_n = 1; #20; group_valid = 1; done_pending = 12'b0000_0000_0001; while (!tx_start) @(posedge clk); @(posedge clk); $display("PRIORITY_WINNER: 0x%02X", first_tx_type); $finish; end endmodule """ stdout = run_iverilog_sim(tb_code, ["src/transport/unified_tx_arbiter.v"]) self.assertIn("PRIORITY_WINNER: 0x81", stdout, "Normal reply group (SET_ACK 0x81) must preempt asynchronous DONE") def test_mutation_g_ram_read_latency_misalignment(self) -> None: """ef2_bram_dp.v guarantees synchronous 1-cycle read latency; timing is strictly verified.""" tb_code = """ `timescale 1ns/1ps module tb; reg clk = 0; always #1 clk = ~clk; reg [7:0] wr_addr = 0; reg [7:0] wr_data = 0; reg wr_en = 0; reg [7:0] rd_addr = 0; wire [7:0] rd_data; ef2_bram_dp #(.DATA_WIDTH(8), .ADDR_WIDTH(8), .DATA_DEPTH(256)) dut ( .clk(clk), .a_en(1'b1), .a_we(wr_en), .a_addr(wr_addr), .a_wdata(wr_data), .a_rdata(), .b_en(1'b1), .b_we(1'b0), .b_addr(rd_addr), .b_wdata(8'd0), .b_rdata(rd_data) ); initial begin @(negedge clk); wr_addr = 8'd5; wr_data = 8'hA5; wr_en = 1; @(negedge clk); wr_en = 0; rd_addr = 8'd5; // Before posedge clk, rd_data has NOT updated yet (synchronous latency) #0.1; $display("BEFORE_EDGE=%h", rd_data); @(posedge clk); #0.1; $display("AFTER_EDGE=%h", rd_data); $finish; end endmodule """ stdout = run_iverilog_sim(tb_code, ["src/common/ef2_bram_dp.v"]) self.assertIn("AFTER_EDGE=a5", stdout, "BRAM must read written value after exact clock edge") def test_mutation_h_watchdog_timeout_failsafe(self) -> None: """watchdog_30s.v expires after timeout and reloads on valid transaction in real RTL.""" tb_code = """ `timescale 1ns/1ps module tb; reg clk = 0; always #1 clk = ~clk; reg rst_n = 0; reg arm = 0; reg reload = 0; wire expired; wire counting; reg seen_expired = 0; watchdog_30s #(.TIMEOUT_CLKS(20)) dut ( .clk(clk), .rst_n(rst_n), .arm(arm), .reload(reload), .expired(expired), .counting(counting) ); always @(posedge clk) begin if (expired) seen_expired <= 1; end initial begin #5; rst_n = 1; #5; // Arm watchdog @(negedge clk); arm = 1; @(negedge clk); arm = 0; repeat(30) @(posedge clk); $display("SEEN_EXPIRED=%b", seen_expired); $finish; end endmodule """ stdout = run_iverilog_sim(tb_code, ["src/control/watchdog_30s.v"]) self.assertIn("SEEN_EXPIRED=1", stdout, "Unrefreshed watchdog must pulse expired") def test_mutation_i_dropped_stop_bit_framing_error(self) -> None: """uart_rx_byte.v asserts framing_error and drops byte_valid when stop bit is low.""" tb_code = """ `timescale 1ns/1ps module tb; reg clk = 0; always #20 clk = ~clk; // 25MHz reg rx = 1; wire [7:0] byte_data; wire byte_valid; wire framing_error; reg seen_valid = 0; reg seen_fe = 0; uart_rx_byte #(.CLKS_PER_BIT(27)) dut ( .clk(clk), .rst_n(1'b1), .rx_i(rx), .byte_data(byte_data), .byte_valid(byte_valid), .framing_error(framing_error) ); always @(posedge clk) begin if (byte_valid) seen_valid <= 1; if (framing_error) seen_fe <= 1; end initial begin #100; // Start bit rx = 0; repeat(27) @(posedge clk); // Data bits 8'h55 repeat(8) begin rx = ~rx; repeat(27) @(posedge clk); end // Corrupted stop bit: drive 0 instead of 1! rx = 0; repeat(27) @(posedge clk); repeat(20) @(posedge clk); $display("RESULT: seen_valid=%b seen_fe=%b", seen_valid, seen_fe); $finish; end endmodule """ stdout = run_iverilog_sim(tb_code, ["src/common/uart_rx_byte.v"]) self.assertIn("seen_valid=0", stdout, "Corrupted stop bit must never assert byte_valid") self.assertIn("seen_fe=1", stdout, "Corrupted stop bit must assert framing_error") if __name__ == "__main__": unittest.main()