#!/usr/bin/env python3 """Kill high-risk motion regressions through real Icarus simulations.""" from __future__ import annotations import subprocess import sys import tempfile import textwrap import time import unittest from dataclasses import dataclass from pathlib import Path from typing import Iterable ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "tools")) import prod2u_p4_harness as harness # noqa: E402 AXIS_SOURCE = ROOT / "src/rtl/prod2u_p4_axis_executor.v" HUB_SOURCE = ROOT / "src/rtl/prod2u_p4_motor_hub.v" CORE_SOURCE = ROOT / "src/rtl/prod2u_p4_normal_v3_core.v" TOP_SOURCE = ROOT / "src/top/prod2u_p4_normal_v3_top.v" AXIS_16BIT_TB = ROOT / "tests/sim/prod2u_p4_axis_jog_16bit_tb.v" FAST_JOG_CORE_TB = ROOT / "tests/sim/prod2u_p4_fast_jog_core_tb.v" TOP_TB = ROOT / "tests/sim/prod2u_p4_normal_v3_top_tb.v" @dataclass(frozen=True) class IcarusResult: compile_returncode: int run_returncode: int | None output: str elapsed_seconds: float def _replace_exact( source: str, old: str, new: str, *, label: str, expected_count: int = 1, ) -> str: actual_count = source.count(old) if actual_count != expected_count: raise AssertionError( f"{label}: expected {expected_count} mutation sites, found {actual_count}" ) return source.replace(old, new) def _run_icarus( *, iverilog: Path, vvp: Path, top: str, sources: Iterable[Path], workdir: Path, timeout_seconds: float = 120.0, defines: Iterable[str] = (), ) -> IcarusResult: executable = workdir / f"{top}.vvp" started = time.perf_counter() compile_result = subprocess.run( [ str(iverilog), "-g2005-sv", *(f"-D{define}" for define in defines), "-s", top, "-o", str(executable), *(str(path) for path in sources), ], cwd=workdir, env=harness.tool_env(), capture_output=True, text=True, timeout=timeout_seconds, check=False, ) output = compile_result.stdout + compile_result.stderr if compile_result.returncode != 0: return IcarusResult( compile_result.returncode, None, output, time.perf_counter() - started, ) run_result = subprocess.run( [str(vvp), str(executable)], cwd=workdir, env=harness.tool_env(), capture_output=True, text=True, timeout=timeout_seconds, check=False, ) return IcarusResult( compile_result.returncode, run_result.returncode, output + run_result.stdout + run_result.stderr, time.perf_counter() - started, ) def _mutate_axis_with_800_step_clamp(source: str) -> str: return _replace_exact( source, " remaining_steps <= command_steps;", " remaining_steps <= (command_steps > 16'd800) ? " "16'd800 : command_steps;", label="800-step clamp", ) def _mutate_axis_with_speed_tiers(source: str) -> str: source = _replace_exact( source, " input wire [15:0] command_steps,\n" " output wire step_out,", " input wire [15:0] command_steps,\n" " input wire [1:0] command_speed,\n" " output wire step_out,", label="axis speed port", ) source = _replace_exact( source, " localparam integer MAX_PHASE_CYCLES =\n" " (DIR_SETUP_CYCLES > STEP_HALF_CYCLES) ?\n" " DIR_SETUP_CYCLES : STEP_HALF_CYCLES;", " localparam integer MAX_STEP_HALF_CYCLES = STEP_HALF_CYCLES * 8;\n" " localparam integer MAX_PHASE_CYCLES =\n" " (DIR_SETUP_CYCLES > MAX_STEP_HALF_CYCLES) ?\n" " DIR_SETUP_CYCLES : MAX_STEP_HALF_CYCLES;", label="axis speed counter width", ) source = _replace_exact( source, " reg dir_reg;\n reg [15:0] remaining_steps;", " reg dir_reg;\n" " reg [1:0] speed_reg;\n" " reg [15:0] remaining_steps;", label="axis speed register", ) source = _replace_exact( source, " assign step_out = (motion_phase == PHASE_STEP_HIGH);\n" " assign dir_out = dir_reg;", " assign step_out = (motion_phase == PHASE_STEP_HIGH);\n" " assign dir_out = dir_reg;\n" " wire [PHASE_COUNTER_BITS-1:0] speed_step_half_cycles =\n" " STEP_HALF_CYCLES << (3 - speed_reg);\n" " wire [PHASE_COUNTER_BITS-1:0] speed_step_half_last =\n" " speed_step_half_cycles - 1'b1;", label="axis speed reload", ) source = _replace_exact( source, " dir_reg <= 1'b0;\n" " remaining_steps <= 16'd0;", " dir_reg <= 1'b0;\n" " speed_reg <= 2'd0;\n" " remaining_steps <= 16'd0;", label="axis speed reset", ) source = _replace_exact( source, " dir_reg <= command_dir;\n" " remaining_steps <= command_steps;", " dir_reg <= command_dir;\n" " speed_reg <= command_speed;\n" " remaining_steps <= command_steps;", label="axis speed capture", ) return _replace_exact( source, "phase_counter <= STEP_HALF_LAST;", "phase_counter <= speed_step_half_last;", label="axis speed phase reloads", expected_count=3, ) def _mutate_core_with_request_ready_gate(source: str) -> str: return _replace_exact( source, " .jog_start(fast_jog_valid),", " .jog_start(fast_jog_valid && request_ready),", label="fast JOG request_ready gate", ) def _mutate_top_with_motor_safety_gates(source: str) -> str: return _replace_exact( source, " assign x_step = motor_steps[0];\n" " assign y_step = motor_steps[1];\n" " assign z_step = motor_steps[2];\n" " assign x_dir = motor_dirs[0];\n" " assign y_dir = motor_dirs[1];\n" " assign z_dir = motor_dirs[2];\n" " assign motor_en_n = 1'b0;", " wire motor_gate_open = !disabled && !watchdog_timeout;\n" " assign x_step = motor_steps[0] && motor_gate_open && !x_limit_raw;\n" " assign y_step = motor_steps[1] && motor_gate_open && !y_limit_raw;\n" " assign z_step = motor_steps[2] && motor_gate_open;\n" " assign x_dir = motor_dirs[0];\n" " assign y_dir = motor_dirs[1];\n" " assign z_dir = motor_dirs[2];\n" " assign motor_en_n = !motor_gate_open;", label="top LS/DISABLE/watchdog/EN safety gate", ) def _mutate_top_with_individual_step_gate( source: str, *, gate_expression: str, label: str, ) -> str: return _replace_exact( source, " assign x_step = motor_steps[0];", f" assign x_step = motor_steps[0] && {gate_expression};", label=label, ) def _top_individual_gate_tb( *, marker: str, x_limit_raw: int, disabled: int, watchdog_timeout: int, ) -> str: return textwrap.dedent( f""" `timescale 1ns/1ps module prod2u_p4_individual_safety_gate_mutation_tb; reg clk = 1'b0; reg x_limit_raw = 1'b{x_limit_raw}; reg y_limit_raw = 1'b0; wire x_step; integer x_rises = 0; integer guard = 0; always #5 clk = ~clk; always @(posedge x_step) x_rises = x_rises + 1; prod2u_p4_normal_v3_top #( .CLK_HZ(4000000), .HOST_UART_CLKS_PER_BIT(4), .POR_CYCLES(4), .INTER_BYTE_TIMEOUT_MS(2), .PTC_STEP_CLKS(1), .FAN_STEP_CLKS(1), .SOLENOID_ACTIVE_HIGH(1) ) dut ( .sys_clk(clk), .host_uart_rx(1'b1), .host_uart_tx(), .ptc_pwm_out(), .fan_pwm_out(), .solenoid_out(), .motor_en_n(), .x_step(x_step), .x_dir(), .y_step(), .y_dir(), .z_step(), .z_dir(), .x_limit_raw(x_limit_raw), .y_limit_raw(y_limit_raw) ); initial begin wait (dut.sys_rst_n === 1'b1); repeat (4) @(negedge clk); force dut.disabled = 1'b{disabled}; force dut.watchdog_timeout = 1'b{watchdog_timeout}; force dut.fast_jog_axis = 2'd0; force dut.fast_jog_dir = 1'b1; force dut.fast_jog_steps = 16'd1; force dut.fast_jog_valid = 1'b1; @(negedge clk); force dut.fast_jog_valid = 1'b0; while (x_rises == 0 && guard < 60000) begin @(negedge clk); guard = guard + 1; end if (x_rises != 1) $fatal(1, "{marker}"); $display("PASS: prod2u_p4_individual_safety_gate_mutation_tb"); $finish; end endmodule """ ).strip() + "\n" FIXED_SPEED_TB = textwrap.dedent( r""" `timescale 1ns/1ps module prod2u_p4_fixed_speed_contract_mutation_tb; reg clk = 1'b0; reg rst_n = 1'b0; reg command_start = 1'b0; reg command_dir = 1'b0; reg [1:0] command_speed = 2'd0; reg [15:0] command_steps = 16'd2; wire step_out; integer cycle_count = 0; integer interval0; integer interval1; integer interval2; integer interval3; always #5 clk = ~clk; always @(posedge clk) cycle_count = cycle_count + 1; prod2u_p4_axis_executor #( .DIR_SETUP_CYCLES(2), .STEP_HALF_CYCLES(2) ) dut ( .clk(clk), .rst_n(rst_n), .command_start(command_start), .command_dir(command_dir), .command_steps(command_steps), `ifdef MUTANT_SPEED_PORT .command_speed(command_speed), `endif .step_out(step_out), .dir_out(), .started_pulse() ); task reset_axis; begin rst_n = 1'b0; command_start = 1'b0; command_dir = 1'b0; command_speed = 2'd0; command_steps = 16'd2; repeat (3) @(negedge clk); rst_n = 1'b1; repeat (2) @(negedge clk); end endtask task measure_speed; input [1:0] speed_code; output integer interval; integer first_cycle; begin reset_axis(); @(negedge clk); command_speed = speed_code; command_steps = 16'd2; command_start = 1'b1; @(negedge clk); command_start = 1'b0; @(posedge step_out); first_cycle = cycle_count; @(posedge step_out); interval = cycle_count - first_cycle; if (interval <= 0) $fatal(1, "SPEED_FIXED_RATE_NO_SECOND_STEP"); end endtask initial begin measure_speed(2'd0, interval0); measure_speed(2'd1, interval1); measure_speed(2'd2, interval2); measure_speed(2'd3, interval3); if ((interval0 != interval1) || (interval0 != interval2) || (interval0 != interval3)) begin $fatal(1, "SPEED_FIXED_RATE_FAIL intervals=%0d/%0d/%0d/%0d", interval0, interval1, interval2, interval3); end $display("PASS: prod2u_p4_fixed_speed_contract_mutation_tb"); $finish; end endmodule """ ).strip() + "\n" class MotionSourceMutationTests(unittest.TestCase): @classmethod def setUpClass(cls) -> None: cls.iverilog = harness.resolve_tool("iverilog") cls.vvp = harness.resolve_tool("vvp") if cls.iverilog is None or cls.vvp is None: raise RuntimeError("Icarus Verilog and vvp are required for mutation tests") def assert_baseline_passed(self, result: IcarusResult, marker: str) -> None: self.assertEqual(result.compile_returncode, 0, result.output) self.assertEqual(result.run_returncode, 0, result.output) self.assertIn(marker, result.output) def assert_mutant_killed(self, result: IcarusResult, marker: str) -> None: self.assertEqual( result.compile_returncode, 0, "mutant must elaborate before it can count as killed:\n" + result.output, ) self.assertIsNotNone(result.run_returncode, result.output) self.assertNotEqual(result.run_returncode, 0, result.output) self.assertIn(marker, result.output) def assert_individual_top_gate_killed( self, *, gate_expression: str, label: str, marker: str, x_limit_raw: int, disabled: int, watchdog_timeout: int, ) -> None: with tempfile.TemporaryDirectory( prefix=f"p4-mutant-{label}-", dir=ROOT.parent ) as temporary: workdir = Path(temporary) testbench = workdir / "prod2u_p4_individual_safety_gate_mutation_tb.v" testbench.write_text( _top_individual_gate_tb( marker=marker, x_limit_raw=x_limit_raw, disabled=disabled, watchdog_timeout=watchdog_timeout, ), encoding="ascii", newline="\n", ) production_sources = tuple( ROOT / relative for relative in harness.active_rtl_sources() ) baseline = _run_icarus( iverilog=self.iverilog, vvp=self.vvp, top="prod2u_p4_individual_safety_gate_mutation_tb", sources=(*production_sources, testbench), workdir=workdir, ) self.assert_baseline_passed( baseline, "PASS: prod2u_p4_individual_safety_gate_mutation_tb", ) mutant_top = workdir / f"prod2u_p4_normal_v3_top_{label}.v" mutant_top.write_text( _mutate_top_with_individual_step_gate( TOP_SOURCE.read_text(encoding="ascii"), gate_expression=gate_expression, label=label, ), encoding="ascii", newline="\n", ) mutant_sources = tuple( mutant_top if source == TOP_SOURCE else source for source in production_sources ) mutant = _run_icarus( iverilog=self.iverilog, vvp=self.vvp, top="prod2u_p4_individual_safety_gate_mutation_tb", sources=(*mutant_sources, testbench), workdir=workdir, ) self.assert_mutant_killed(mutant, marker) def test_800_step_clamp_is_killed_by_real_16bit_boundary_tb(self) -> None: with tempfile.TemporaryDirectory( prefix="p4-mutant-clamp-", dir=ROOT.parent ) as temporary: workdir = Path(temporary) baseline = _run_icarus( iverilog=self.iverilog, vvp=self.vvp, top="prod2u_p4_axis_jog_16bit_tb", sources=(AXIS_SOURCE, AXIS_16BIT_TB), workdir=workdir, ) self.assert_baseline_passed( baseline, "PASS: prod2u_p4_axis_jog_16bit_tb" ) mutant_axis = workdir / "prod2u_p4_axis_executor_clamped.v" mutant_axis.write_text( _mutate_axis_with_800_step_clamp( AXIS_SOURCE.read_text(encoding="ascii") ), encoding="ascii", newline="\n", ) mutant = _run_icarus( iverilog=self.iverilog, vvp=self.vvp, top="prod2u_p4_axis_jog_16bit_tb", sources=(mutant_axis, AXIS_16BIT_TB), workdir=workdir, ) self.assert_mutant_killed(mutant, "16-bit JOG mismatch") def test_reintroduced_speed_tiers_are_killed_by_fixed_rate_rtl(self) -> None: with tempfile.TemporaryDirectory( prefix="p4-mutant-speed-", dir=ROOT.parent ) as temporary: workdir = Path(temporary) speed_tb = workdir / "prod2u_p4_fixed_speed_contract_mutation_tb.v" speed_tb.write_text(FIXED_SPEED_TB, encoding="ascii", newline="\n") baseline = _run_icarus( iverilog=self.iverilog, vvp=self.vvp, top="prod2u_p4_fixed_speed_contract_mutation_tb", sources=(AXIS_SOURCE, speed_tb), workdir=workdir, ) self.assert_baseline_passed( baseline, "PASS: prod2u_p4_fixed_speed_contract_mutation_tb" ) mutant_axis = workdir / "prod2u_p4_axis_executor_speed.v" mutant_axis.write_text( _mutate_axis_with_speed_tiers( AXIS_SOURCE.read_text(encoding="ascii") ), encoding="ascii", newline="\n", ) mutant = _run_icarus( iverilog=self.iverilog, vvp=self.vvp, top="prod2u_p4_fixed_speed_contract_mutation_tb", sources=(mutant_axis, speed_tb), workdir=workdir, defines=("MUTANT_SPEED_PORT",), ) self.assert_mutant_killed(mutant, "SPEED_FIXED_RATE_FAIL") def test_fast_jog_request_ready_gate_is_killed_by_core_bypass_tb(self) -> None: with tempfile.TemporaryDirectory( prefix="p4-mutant-request-ready-", dir=ROOT.parent ) as temporary: workdir = Path(temporary) sources = ( ROOT / "src/rtl/binary921_crc16.v", ROOT / "src/rtl/prod2u_p4_normal_v3_output_state.v", ROOT / "src/rtl/prod2u_p4_normal_v3_watchdog.v", AXIS_SOURCE, HUB_SOURCE, ROOT / "src/rtl/prod2u_p4_response_scheduler.v", ) baseline = _run_icarus( iverilog=self.iverilog, vvp=self.vvp, top="prod2u_p4_fast_jog_core_tb", sources=(*sources, CORE_SOURCE, FAST_JOG_CORE_TB), workdir=workdir, ) self.assert_baseline_passed( baseline, "PASS: prod2u_p4_fast_jog_core_tb" ) mutant_core = workdir / "prod2u_p4_normal_v3_core_request_ready.v" mutant_core.write_text( _mutate_core_with_request_ready_gate( CORE_SOURCE.read_text(encoding="ascii") ), encoding="ascii", newline="\n", ) mutant = _run_icarus( iverilog=self.iverilog, vvp=self.vvp, top="prod2u_p4_fast_jog_core_tb", sources=(*sources, mutant_core, FAST_JOG_CORE_TB), workdir=workdir, ) self.assert_mutant_killed( mutant, "fast X JOG did not finish while the old response was stalled", ) def test_top_motor_safety_gates_are_killed_by_real_uart_top_tb(self) -> None: with tempfile.TemporaryDirectory( prefix="p4-mutant-top-gates-", dir=ROOT.parent ) as temporary: workdir = Path(temporary) production_sources = tuple( ROOT / relative for relative in harness.active_rtl_sources() ) baseline = _run_icarus( iverilog=self.iverilog, vvp=self.vvp, top="prod2u_p4_normal_v3_top_tb", sources=(*production_sources, TOP_TB), workdir=workdir, ) self.assert_baseline_passed( baseline, "PASS: prod2u_p4_normal_v3_top_tb" ) mutant_top = workdir / "prod2u_p4_normal_v3_top_gated.v" mutant_top.write_text( _mutate_top_with_motor_safety_gates( TOP_SOURCE.read_text(encoding="ascii") ), encoding="ascii", newline="\n", ) mutant_sources = tuple( mutant_top if source == TOP_SOURCE else source for source in production_sources ) mutant = _run_icarus( iverilog=self.iverilog, vvp=self.vvp, top="prod2u_p4_normal_v3_top_tb", sources=(*mutant_sources, TOP_TB), workdir=workdir, ) self.assert_mutant_killed(mutant, "NO_GATES_TOP_FAIL") def test_limit_gate_is_independently_killed(self) -> None: self.assert_individual_top_gate_killed( gate_expression="!x_limit_raw", label="limit_gate", marker="LIMIT_GATE_FAIL", x_limit_raw=1, disabled=0, watchdog_timeout=0, ) def test_disable_gate_is_independently_killed(self) -> None: self.assert_individual_top_gate_killed( gate_expression="!disabled", label="disable_gate", marker="DISABLE_GATE_FAIL", x_limit_raw=0, disabled=1, watchdog_timeout=0, ) def test_watchdog_gate_is_independently_killed(self) -> None: self.assert_individual_top_gate_killed( gate_expression="!watchdog_timeout", label="watchdog_gate", marker="WATCHDOG_GATE_FAIL", x_limit_raw=0, disabled=0, watchdog_timeout=1, ) if __name__ == "__main__": unittest.main()