"""Hypothesis replay/fuzz coverage for the production BMC ASCII bank parser.""" from __future__ import annotations from dataclasses import dataclass import warnings import cocotb from cocotb.triggers import FallingEdge, RisingEdge, Timer, with_timeout from hypothesis import HealthCheck, given, settings, strategies as st from hypothesis.errors import HypothesisSideeffectWarning @dataclass(frozen=True) class SnapshotCase: channels: tuple[tuple[int, int] | None, ...] lower: bool separator: bytes @property def raw(self) -> bytes: values = bytearray() for channel in self.channels: values.extend((0xFF, 0xFF) if channel is None else channel) return bytes(values) @property def line(self) -> bytes: words = [f"{value:02x}" if self.lower else f"{value:02X}" for value in self.raw] return self.separator.join(value.encode("ascii") for value in words) @st.composite def snapshot_cases(draw) -> SnapshotCase: channel = st.one_of( st.none(), st.tuples(st.integers(min_value=0, max_value=99), st.integers(min_value=0, max_value=99)), ) channels = tuple(draw(st.lists(channel, min_size=24, max_size=24))) return SnapshotCase( channels=channels, lower=draw(st.booleans()), separator=draw(st.sampled_from((b"", b" ", b"\t"))), ) def generated_cases() -> list[SnapshotCase]: values: list[SnapshotCase] = [] @settings( max_examples=48, derandomize=True, database=None, deadline=None, suppress_health_check=(HealthCheck.too_slow,), ) @given(snapshot_cases()) def collect(value: SnapshotCase) -> None: values.append(value) with warnings.catch_warnings(): warnings.simplefilter("ignore", HypothesisSideeffectWarning) collect() return values async def clock_cycles(dut, count: int) -> None: for _ in range(count): await RisingEdge(dut.sys_clk) async def send_char(dut, value: int) -> None: await FallingEdge(dut.sys_clk) dut.rx_data.value = value dut.rx_valid.value = 1 await FallingEdge(dut.sys_clk) dut.rx_valid.value = 0 async def send_bytes(dut, values: bytes) -> None: for value in values: await send_char(dut, value) async def pulse_tick(dut, count: int = 1) -> None: for _ in range(count): await FallingEdge(dut.sys_clk) dut.tick_1s_test.value = 1 await FallingEdge(dut.sys_clk) dut.tick_1s_test.value = 0 async def read_channels(dut) -> tuple[list[int], int]: raw: list[int] = [] valid_mask = 0 for index in range(24): dut.rd_index.value = index await RisingEdge(dut.sys_clk) await Timer(1, units="ns") raw.append(int(dut.rd_raw.value)) valid_mask |= int(dut.rd_valid.value) << index return raw, valid_mask async def expect_commit(dut, case: SnapshotCase, terminator: bytes) -> None: commits = int(dut.commit_count_mon.value) epoch = int(dut.epoch.value) bank = int(dut.active_bank.value) await send_bytes(dut, case.line + terminator) await clock_cycles(dut, 3) assert int(dut.commit_count_mon.value) == commits + 1 assert int(dut.epoch.value) == (epoch + 1) & 0xFFFF assert int(dut.active_bank.value) == 1 - bank assert int(dut.age_seconds.value) == 0 expected_raw = [int.from_bytes(case.raw[index : index + 2], "big") for index in range(0, 48, 2)] expected_valid = sum( (case.raw[index : index + 2] != b"\xFF\xFF") << (index // 2) for index in range(0, 48, 2) ) observed_raw, observed_valid = await read_channels(dut) assert observed_raw == expected_raw assert observed_valid == expected_valid assert int(dut.active_valid_mask.value) == expected_valid async def expect_reject(dut, line: bytes, *, timeout: bool = False) -> None: commits = int(dut.commit_count_mon.value) errors = int(dut.error_count_mon.value) epoch = int(dut.epoch.value) bank = int(dut.active_bank.value) raw_before, valid_before = await read_channels(dut) await send_bytes(dut, line) if timeout: await clock_cycles(dut, 70) else: await clock_cycles(dut, 3) assert int(dut.commit_count_mon.value) == commits assert int(dut.error_count_mon.value) == errors + 1 assert int(dut.epoch.value) == epoch assert int(dut.active_bank.value) == bank raw_after, valid_after = await read_channels(dut) assert (raw_after, valid_after) == (raw_before, valid_before) @cocotb.test() async def test_bmc_replay_fuzz_timeout_banks_epoch_and_freshness(dut): dut.tick_1s_test.value = 0 dut.rx_valid.value = 0 dut.rx_data.value = 0 dut.rx_framing_error.value = 0 dut.snapshot_lock.value = 0 dut.snapshot_lock_bank.value = 0 dut.rd_index.value = 0 await with_timeout(RisingEdge(dut.rst_n_mon), 1, "ms") await clock_cycles(dut, 27) assert int(dut.age_seconds.value) == 0xFFFF assert int(dut.stale.value) == 1 cases = generated_cases() baseline = SnapshotCase( channels=tuple((30, 0) for _ in range(24)), lower=False, separator=b" ", ) # The optional six-byte command echo is a separate non-committing line. await send_bytes(dut, b"36 6c DF dd 00 03\r\n") await clock_cycles(dut, 3) assert int(dut.commit_count_mon.value) == 0 assert int(dut.error_count_mon.value) == 0 # Mixed upper/lower hex, space/tab/no separators, CR, LF, CRLF, FF FF, # consecutive snapshots, atomic bank flips, and exact epochs. for index, case in enumerate(cases): terminator = (b"\r", b"\n", b"\r\n")[index % 3] await expect_commit(dut, case, terminator) # Each valid replay also seeds a guaranteed-invalid-character mutation # which must preserve the previously active bank byte-for-byte. mutated = bytearray(case.line) mutated[0] = ord("G") await expect_reject(dut, bytes(mutated) + b"\r") # Freshness is reset by a commit, ages on distinct one-second ticks, and # becomes stale at the configured threshold. A new snapshot clears it. await pulse_tick(dut, 1) assert int(dut.age_seconds.value) == 1 and int(dut.stale.value) == 0 await pulse_tick(dut, 1) assert int(dut.age_seconds.value) == 2 and int(dut.stale.value) == 1 await expect_commit(dut, baseline, b"\r") assert int(dut.age_seconds.value) == 0 and int(dut.stale.value) == 0 raw = baseline.raw hex_line = b" ".join(f"{value:02X}".encode("ascii") for value in raw) await expect_reject(dut, b" ".join(f"{value:02X}".encode("ascii") for value in raw[:-1]) + b"\r") await expect_reject(dut, hex_line + b" 00\r") await expect_reject(dut, b"FF" + hex_line[2:] + b"\r") await expect_reject(dut, hex_line[:1] + b" " + hex_line[1:] + b"\r") # A UART framing error taints the complete line even when all ASCII bytes # that follow would otherwise be valid. commits = int(dut.commit_count_mon.value) errors = int(dut.error_count_mon.value) await FallingEdge(dut.sys_clk) dut.rx_framing_error.value = 1 await FallingEdge(dut.sys_clk) dut.rx_framing_error.value = 0 await send_bytes(dut, hex_line + b"\r") await clock_cycles(dut, 3) assert int(dut.commit_count_mon.value) == commits assert int(dut.error_count_mon.value) == errors + 1 # A half reply with no CR/LF is discarded by the inter-byte timeout. The # following complete reply starts from a clean nibble/count/echo state. await expect_reject(dut, hex_line[:20], timeout=True) await expect_commit(dut, baseline, b"\n") # Snapshot ownership of the inactive bank blocks partial writes and bank # flips until the lock is released. dut.snapshot_lock.value = 1 dut.snapshot_lock_bank.value = 1 - int(dut.active_bank.value) await expect_reject(dut, hex_line + b"\r") dut.snapshot_lock.value = 0 await expect_commit(dut, baseline, b"\r")