#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Rung 6: a gate that cannot fail proves nothing. Break the board in one place at a time and show the gate catches each. Each fault is a one-line change (a constant moved by one step, a rule bent) in a copy of this repository's src/ and tests/ (fresh timestamps, so cargo cannot reuse a stale build: the family's lesson of 2026-11-13), built into its own target directory, then checked: 1. ``cargo test`` (rung 2's unit vectors and the rest); 2. the lockstep (rung 3) on the cases below, against the reference traces scripts/lockstep.py cached (run it first: no Python runs here); 3. the save-state rung (rung 4) on five cases; 4. the ADEN = 0 rung (rung 1) on four of megadrive-rust's cases. A fault is caught when any check fails. A fault that changes nothing any check can see is reported as such (an equivalent mutant is noted, not counted; a real fault missed is a blind spot to record). python3 scripts/seeded_faults.py [--only N ...] [--jobs N] """ from __future__ import annotations import argparse import os import shutil import subprocess import sys import tempfile from concurrent.futures import ThreadPoolExecutor from pathlib import Path HERE = Path(__file__).resolve().parent REPO = HERE.parent LOCKSTEP_CASES = ["testpico", "mars-check", "pwm-demo", "nfl", "240p-suite", "chaotix-fm", "nba-jam-te", "vr-deluxe-pal", "runlength", "mk2"] # fmt: skip STATE_CASES = ["testpico", "nfl", "pwm-demo", "mars-check", "chaotix-fm"] PASSIVE_CASES = ["sonic", "board-bugs", "board-psolar", "castlevania"] #: (file, the line as it is, the line broken, what it breaks). FAULTS = [ ("src/vdp.rs", "pen_rise: at(rise_dot + timings.pen),", "pen_rise: at(rise_dot + timings.pen + 1),", "PEN one dot late"), ("src/vdp.rs", "let busy = (7 + 3 * words) * 7 / 3;", "let busy = (8 + 3 * words) * 7 / 3;", "auto fill's FEN one Sclk long"), ("src/vdp.rs", "self.latched_pri = (bitmap >> 7) & 1;", "self.latched_pri = (bitmap >> 6) & 1;", "PRI latched from the 240 bit"), ("src/vdp.rs", "let pen = vblank || pen_on || self.latched_mode == 0 || self.latched_mode == 2;", "let pen = vblank || pen_on || self.latched_mode == 0 || self.latched_mode == 3;", "PEN free in run-length mode, not direct colour"), ("src/vdp.rs", "let shift = usize::from(self.latched_shift != 0 && (address & 0xFF) != 0xFF);", "let shift = usize::from(self.latched_shift != 0);", "the shift's $FF exception lost"), ("src/vdp.rs", "while drop + 2 < timings.len() && timings[drop].end <= mclk {", "while drop + 1 < timings.len() && timings[drop].end <= mclk {", "line records pruned to one"), ("src/vdp.rs", "self.hint_counter = i64::from(links.hcount);", "self.hint_counter = i64::from(links.hcount) + 1;", "HINT counter reloaded one more"), ("src/pwm.rs", "(i64::from(cycle) - 1) & 0xFFF", "(i64::from(cycle) - 2) & 0xFFF", "PWM period one state short"), ("src/pwm.rs", "pub const FIFO_DEPTH: usize = 3;", "pub const FIFO_DEPTH: usize = 4;", "PWM FIFOs four deep"), ("src/pwm.rs", "if self.periods >= if tm != 0 { tm } else { 16 } {", "if self.periods >= if tm != 0 { tm } else { 15 } {", "TM 0 is 15 periods"), ("src/pwm.rs", "2 => left_height,", "2 => right_height,", "RMD 2 routes R"), ("src/composite.rs", "pub const KEEP: usize = 8;", "pub const KEEP: usize = 1;", "the composite keeps one line"), ("src/composite.rs", "} else if (word ^ pri) & 0x8000 != 0 || ys[index as usize] != 0 {", "} else if (word ^ pri) & 0x8000 != 0 {", "the Mega Drive's transparency ignored"), ("src/sh2side.rs", "pub const LEVELS: [(u32, u32); 5] = [(VRES, 14), (VINT, 12), (HINT, 10), (CMD, 8), (PWM, 6)];", "pub const LEVELS: [(u32, u32); 5] = [(VRES, 14), (VINT, 11), (HINT, 10), (CMD, 8), (PWM, 6)];", "VINT at level 11"), ("src/sh2side.rs", "start = start.max(now + self.slave_request);", "start = start.max(now + self.slave_request - 1);", "the slave asks one state sooner"), ("src/sh2side.rs", "if now < self.bus_until + self.master_return {", "if now < self.bus_until {", "the master's return free"), ("src/sh2side.rs", "self.fb_fifo.push(end.max(last) + self.fifo_drain);", "self.fb_fifo.push(end.max(last));", "the frame-buffer FIFO drains at once"), ("src/sh2side.rs", "sh2.add_wait(index, m68k_end - start);", "sh2.add_wait(index, m68k_end - start - 1);", "the 68000's cartridge cycle one state short for the SH-2"), ("src/sh2side.rs", "if extra > 0 && cx.wait_pin[area] {", "if extra > 1 && cx.wait_pin[area] {", "one WAIT state lost"), ("src/sh2side.rs", "let irl = level | (self.ftoa[index] ^ 1);", "let irl = level;", "FTOA off /IRL0"), ("src/sh2side.rs", "self.side().chip(index).dreq1 = 0;", "self.side().chip(index).dreq1 = 1;", "DREQ1 never dropped"), ("src/sh2side.rs", "let end = now + sh2.cx(index).cycle_states[3] + sh2.wait(index);\n sh2.release(index, end, address, width, false);", "let end = now + sh2.cx(index).cycle_states[3];\n sh2.release(index, end, address, width, false);", "an SDRAM read's waits left out of the bus's end"), ("src/slot.rs", "pub const M68K_CYCLE: i64 = 28;", "pub const M68K_CYCLE: i64 = 21;", "the 68000's cartridge cycle 3 clocks"), ("src/slot.rs", "if lanes == 0xFFFF && !overwrite {", "if lanes == 0xFFFF {", "the overwrite image writes zero words"), ("src/slot.rs", "board.hold(master, waits * 7);", "board.hold(master, waits * 6);", "the 68000's waits in the wrong clock"), ("src/slot.rs", "self.dreq_length = self.dreq_length.wrapping_sub(1);", "self.dreq_length = self.dreq_length.wrapping_sub(2);", "the DREQ length counts two"), ("src/slot.rs", "ranges.push((0x000100, 0x400000));", "ranges.push((0x000100, 0x380000));", "RV = 0 leaves the top of the cartridge range unclaimed"), ("src/slot.rs", "let cart = if self.has_cartridge { 0 } else { 0x100 };", "let cart = if self.has_cartridge { 0x100 } else { 0 };", "CART inverted on the SH-2 side"), ("src/slot.rs", " self.pending = Some(mclk);\n return true;", " self.pending = Some(mclk);\n return false;", "the Mega Drive's VDP not brought up first"), ("src/slot.rs", " board.cartridge.write_time_lanes(address, high, low, word);", " board.cartridge.write_time(address | 1, low);", "/TIME by bytes (the fixed reference bug)"), ("src/slot.rs", "self.hen = value & 0x80 != 0;", "self.hen = value & 0x40 != 0;", "HEN from the wrong bit"), ("src/state.rs", " d.pwm = s.pwm;", "", "the PWM not restored"), ("src/state.rs", " system.board().dev.update_claims();", "", "the claims not read again after a load"), ("src/state.rs", " side.done_composite = s.renderer_done_rows.into_iter().map(|r| r.map(|i| rows[i].clone())).collect();", "", "the finished frame's composite rows not restored"), ("src/console.rs", " cartridge.sda_line = true;", "", "the Acclaim EEPROM's SDA line not wired"), ("src/state.rs", " system.audio.set_source_side(s.audio_sources);", "", "the mixer's PWM resampling not restored"), ] def checks(root: Path, target: Path) -> list[str]: """Which checks fail on the broken copy at `root` (empty: not caught).""" env = dict(os.environ, CARGO_TARGET_DIR=str(target)) build = subprocess.run(["nice", "cargo", "build", "--release", "--offline", "--quiet"], cwd=root, env=env, capture_output=True, text=True) # fmt: skip if build.returncode: return ["build: " + build.stderr.strip()[-200:]] failed = [] test = subprocess.run(["nice", "cargo", "test", "--release", "--offline", "--quiet"], cwd=root, env=env, capture_output=True, text=True) # fmt: skip if test.returncode: failed.append("cargo test") rust = target / "release/s32x-trace" out = target / "traces" only = [x for c in LOCKSTEP_CASES for x in ("--only", c)] r = subprocess.run([sys.executable, str(HERE / "lockstep.py"), "--cached-only", "--jobs", "4", "--rust", str(rust), "--out", str(out), *only], capture_output=True, text=True) # fmt: skip failed += [f"lockstep {line.split()[0]}" for line in r.stdout.splitlines() if " DIFFERENT " in line or " ERROR " in line] # fmt: skip if r.returncode and not any(f.startswith("lockstep") for f in failed): failed.append("lockstep: " + (r.stdout + r.stderr).strip()[-200:]) only = [x for c in STATE_CASES for x in ("--only", c)] r = subprocess.run([sys.executable, str(HERE / "state_rung.py"), "--jobs", "2", "--rust", str(rust), "--out", str(target / "state"), *only], capture_output=True, text=True) # fmt: skip failed += [f"state {line.split()[0]}" for line in r.stdout.splitlines() if " DIFFERENT " in line or " ERROR " in line] only = [x for c in PASSIVE_CASES for x in ("--only", c)] r = subprocess.run([sys.executable, str(HERE / "passive.py"), "--jobs", "4", "--passive", str(target / "release/s32x-mdtrace"), "--out", str(target / "passive"), *only], capture_output=True, text=True) # fmt: skip failed += [f"passive {line.split()[0]}" for line in r.stdout.splitlines() if " DIFFERENT " in line or " ERROR " in line] return failed def run_fault(number: int, scratch: Path) -> tuple[int, list[str]]: path, old, new, _what = FAULTS[number] root = scratch / f"fault-{number}" root.mkdir() for name in ("src", "tests"): shutil.copytree(REPO / name, root / name, copy_function=shutil.copy) # fresh timestamps shutil.copy(REPO / "Cargo.toml", root / "Cargo.toml") shutil.copy(REPO / "Cargo.lock", root / "Cargo.lock") (root / "external").symlink_to(REPO / "external") source = (root / path).read_text() assert source.count(old) == 1, f"fault {number}: {old!r} is not in {path} once" (root / path).write_text(source.replace(old, new)) return number, checks(root, scratch / f"target-{number}") def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--only", type=int, action="append", default=[]) parser.add_argument("--jobs", type=int, default=3) parser.add_argument("--scratch", type=Path, help="where the copies go (default: a temporary folder)") args = parser.parse_args() selected = args.only or list(range(len(FAULTS))) scratch = args.scratch or Path(tempfile.mkdtemp(prefix="sega32x-faults-")) scratch.mkdir(parents=True, exist_ok=True) caught = 0 with ThreadPoolExecutor(args.jobs) as pool: for number, failed in pool.map(lambda n: run_fault(n, scratch), selected): path, _old, _new, what = FAULTS[number] caught += bool(failed) verdict = "caught" if failed else "MISSED" print(f"{number:2} {verdict:6} {path:18} {what}: {', '.join(failed[:6]) or '-'}", flush=True) print(f"{caught} of {len(selected)} caught (copies in {scratch})") return 0 if caught == len(selected) else 1 if __name__ == "__main__": sys.exit(main())