#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Seeded one-line faults: each is applied to a copy of the tree and its judges must fail. A gate that cannot fail proves nothing (family methodology). 37 are the reference's own (a2600-python scripts/seeded_faults.py at 28fb095, same names: its 35 of 9475aa1 first, its two DPC-clock faults after the Rust-specific ones), applied to the transcription's text; their judges are the transcribed tests the reference names, plus the native gates and the lockstep where the fault reaches them. The rest are Rust-specific: faults in what this repository adds (save states, the softlist reader) and in transcription idioms Rust forced (tables, integer division, the snoop flag). A judge is ``test:FILE:NAME`` (``cargo test --test FILE NAME``; a test that no longer compiles counts, as the reference counts a collection error), ``gates:ARGS`` (``a2600-gates ARGS`` fails; ``gatesN:ARGS`` within N seconds), ``gate:REGEX`` (the lockstep on the cases matching REGEX differs from the cached reference traces), ``save:REGEX`` (the same with ``--save-at-half``), or ``timeout:`` (the headless window does not stop within a minute). A fault is caught when any of its judges fails. Mutations go into a git worktree (external/faults-tree) built into external/faults-target, never into this checkout; the worktree is checked out fresh for every fault, so sources carry new timestamps (methodology, the stale-build lesson). Run the gate once first to fill external/refcache. python3 scripts/seeded_faults.py [--only NAME] [--list] """ from __future__ import annotations import argparse import os import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] TREE = ROOT / "external" / "faults-tree" TARGET = ROOT / "external" / "faults-target" REF = Path(os.environ.get("A2600_PYTHON_ROOT") or ROOT.parent / "a2600-python") ENV = { **os.environ, "A2600_PYTHON_ROOT": str(REF), "MAME_HASHPATH": os.environ.get("MAME_HASHPATH") or str(REF / "reference/src/mame/hash"), "CARGO_BUILD_JOBS": os.environ.get("JOBS", "3"), # JOBS: at most this many processes } L, D, SK, C = "src/cartridge/licensed.rs", "src/cartridge/dpc.rs", "src/savekey.rs", "src/controllers.rs" # name: (file, old text, new text, judges) FAULTS = { # -- the reference's 35 -------------------------------------------------------- "e0-fixed-slice": (L, "slices: [a, b, c, 7],", "slices: [a, b, c, 6],", ["test:schemes:e0_slices_and_fixed_last", "gate:E0"]), "3f-latches-reads": (L, "if write && address < 0x40 {", "if address < 0x40 {", ["test:schemes:_3f_latches_on_writes_below_40_only"]), "fe-polarity": (L, "self.bank = if value & 0x20 != 0 { 0 } else { 0x1000 };", "self.bank = if value & 0x20 != 0 { 0x1000 } else { 0 };", ["test:schemes:fe_takes_d5_of_the_byte_after_01fe", "gate:FE"]), "e7-block-select": (L, "self.block = (address & 3) as usize;", "self.block = 0;", ["test:schemes:e7_rom_pages_ram_windows_and_fixed_area", "gate:E7"]), "e7-12k-map": (L, "[&pages[..2], &pages[..2], &pages[2..]]", "[&pages[..2], &pages[2..4], &pages[2..]]", ["test:schemes:e7_12k_maps_pages_0_1_twice", "gate:E7 BurgerTime 12K"]), "cv-windows-swapped": (L, " if offset < 0x400 {\n return Some(self.ram[offset]);", " if offset >= 0x400 {\n return Some(self.ram[offset & 0x3FF]);", ["test:schemes:commavid_ram_read_low_write_high", "gate:CV"]), "ua-bank-bit": (L, "self.bank = ((address & 0x40) as usize) << 6;", "self.bank = ((address & 0x20) as usize) << 7;", ["test:schemes:ua_banks_from_0220_and_0240", "gate:UA"]), "f0-no-step": (L, "self.bank = (self.bank + 1) & 15;", "self.bank &= 15;", ["test:schemes:f0_steps_on_each_1ff0_access", "gate:F0"]), "dpc-rng-tap": (D, "(r >> 4) ^ (r >> 3)) & 1;", "(r >> 4) ^ (r >> 2)) & 1;", ["test:schemes:dpc_random_number_generator_has_255_states", "gate:DPC"]), "dpc-mask": (D, "} else if !shown {\n 0", "} else if false {\n 0", ["test:schemes:dpc_fetcher_reads_decrement_and_mask_by_the_flag", "gate:DPC"]), "ar-four-transitions": ("src/cartridge/supercharger.rs", "WRITE_TRANSITIONS: i32 = 5;", "WRITE_TRANSITIONS: i32 = 4;", ["test:schemes:supercharger_writes_on_the_fifth_address_transition", "gate:AR"]), "ar-counts-cycles": ("src/cartridge/supercharger.rs", "if address as i32 != self.last_address {", "if true {", ["test:schemes:supercharger_counts_transitions_not_cycles", "gate:AR"]), "driving-pins-swapped": (C, "gray[n] = (1 - ((n as u8 >> 1) & 1)) | (1 - (((n as u8 >> 1) ^ n as u8) & 1)) << 1;", "gray[n] = (1 - ((n as u8 >> 1) & 1)) << 1 | (1 - (((n as u8 >> 1) ^ n as u8) & 1));", ["test:controllers:the_driving_controller_reads_nocash_s_gray_code", "gate:driving"]), "booster-wrong-pads": (C, "let first = 2 * self.port;", "let first = 2 * (1 - self.port);", ["test:controllers:a_booster_grip_button_charges_its_pad_after_the_dump", "gate:booster"]), "paddle-half-supply": (C, "NOCASH_LINES_AT_POT_MAX: f64 = 380.0;", "NOCASH_LINES_AT_POT_MAX: f64 = 742.0;", ["test:inputs:a_paddle_trips_after_its_rc_time", "gate:paddles"]), "savekey-no-page-rollover": (SK, "self.pointer = base | ((self.pointer + 1) & (PAGE - 1));", "self.pointer = (self.pointer + 1) % SIZE;", ["test:controllers:a_page_write_rolls_over_inside_its_64_byte_page"]), "savekey-acks-while-busy": (SK, "self.state = if cycle >= self.busy_until { CONTROL } else { IDLE };", "self.state = CONTROL;", ["test:controllers:the_chip_does_not_acknowledge_during_its_write_cycle"]), "savekey-any-chip-select": (SK, " || (value >> 1) & 7 != CHIP_SELECT {", " {", ["test:controllers:another_control_code_or_chip_select_is_ignored"]), "savekey-no-read-wrap": (SK, "self.pointer = (self.pointer + 1) % SIZE;\n self.bits = 0;", "self.pointer += 1;\n self.bits = 0;", ["test:controllers:a_sequential_read_wraps_from_the_last_byte_to_the_first"]), "savekey-sda-on-pin-2": (SK, "sda_bit: 1 << (shift + 2), // pin 3", "sda_bit: 1 << (shift + 1), // pin 3", ["test:controllers:go_fish_reads_its_block_back_through_the_savekey", "gate:savekey"]), "pal-hue-1-coloured": ("src/palettes.rs", "(0.000, 0.000), (0.000, 0.000), (-0.222, 0.032)", "(0.000, 0.000), (0.100, 0.000), (-0.222, 0.032)", ["test:misc:palette_structure_follows_nocash"]), "window-never-stops": ("src/bin/a2600-play.rs", "if frames >= limit {", "if frames >= limit && false {", ["timeout:"]), "secam-colour-switch": ("src/machine.rs", " palette: \"secam\",\n switches: 0x37,\n", " palette: \"secam\",\n", ["test:revisions:a_secam_console_has_no_colour_switch", "gate:SECAM Combat"]), "merge-always-steps": ("src/tia.rs", "let merge_step = merge & revision.merge_steps;", "let merge_step = merge;", ["test:revisions:a_console_row_matches_every_cell_of_its_table", "gate:early_HMOVE"]), "strobe-never-drops": ("src/tia.rs", "((c.strobe_left != 0 && revision.strobe_drops & bit == 0) || held)", "(c.strobe_left != 0 || held)", ["test:revisions:a_console_row_matches_every_cell_of_its_table", "gate:PAL_VADER"]), "vader-row-m0-only": ("src/machine.rs", " strobe_drops: M0 | M1,\n ..TIARevision::new(\"PAL Vader (#699)\"", " strobe_drops: M0,\n ..TIARevision::new(\"PAL Vader (#699)\"", ["test:revisions:a_console_row_matches_every_cell_of_its_table", "gate:PAL_VADER"]), "reference-merge-mask": ("src/machine.rs", " merge_steps: 0x1F,\n strobe_drops: 0x00,", " merge_steps: 0x0F,\n strobe_drops: 0x00,", ["gates:die", "gate:smoke/Pitfall"]), "serial-judge-blind": ("src/gates.rs", "if mine.as_ref() == Some(theirs) {", "if true {", ["test:revisions:the_serial_judge_counts_every_cell_and_finds_a_wrong_one"]), "board-ignores-riot": ("src/board.rs", "let riot = match riot {", "let riot = match None {", ["test:sockets:the_board_uses_handed_in_chips_as_they_stand"]), "board-restarts-count": ("src/board.rs", " cycles,\n", " cycles: 0,\n", ["test:sockets:the_board_uses_handed_in_chips_as_they_stand"]), "grid-unchecked": ("src/board.rs", "if machine.tia_clocks_cpu && (2", "if false && (2", ["test:sockets:a_2600_row_keeps_the_cycle_grid_and_a_hosted_row_does_not"]), "api-name-gone": ("src/machine.rs", "pub const HOSTED_MACHINES: [Machine; 2]", "pub const _HOSTED: [Machine; 2]", ["test:misc:every_listed_name_exists"]), "die-gate-own-tia": ("src/gates.rs", "let mut tia = tia_factory();", "let mut tia = TIA::default();", ["test:sockets:the_die_gate_runs_on_a_supplied_tia"]), "lockstep-blind": ("src/gates.rs", "if a[k] != b[k] {", "if false {", ["test:sockets:lockstep_finds_a_board_that_differs"]), "frame-hash-audio": ("src/audio.rs", "(2 * v) as f64 / (30 + v) as f64", "(2 * v) as f64 / (31 + v) as f64", ["gates:hashes", "gate:smoke/Pitfall"]), # -- Rust-specific: this repository's additions and Rust-forced idioms ------------ # Missed by every judge on 2026-11-14: at an instruction boundary the next cycle is an # opcode fetch the cartridge drives, so the floating bus is overwritten before anything # reads it, unless a scheme stores `value` on that fetch. Likely an equivalent mutant; # kept and reported, not counted as a catch. "state-forgets-data-bus": ("src/state.rs", " board.data_bus = whole.data_bus;\n", "", ["test:misc:a_state_loads_into_a_fresh_console_and_continues_identically", "save:^smoke"]), "state-forgets-halted": ("src/state.rs", " board.halted_cycles = whole.halted_cycles;\n", "", ["save:^smoke/(Pitfall|River|Combat)"]), "state-drops-line-callback": ("src/state.rs", " tia.on_line = board.tia.on_line.take();\n", "", ["save:^smoke/(Pitfall|River|Combat)"]), "state-skips-cartridge": ("src/state.rs", " board.cartridge.load_state(&whole.cartridge)?;\n", "", ["save:^scheme/(F6SC|E0|DPC)"]), "softlist-no-ram": ("src/cartridge/mod.rs", "p.ram = true;", "p.ram = false;", ["gate:scheme/F6SC"]), "riot-steps-off-by-one": ("src/riot.rs", "let steps = 1 + n.div_euclid(divider);", "let steps = n.div_euclid(divider);", ["test:riot:first_decrement_one_cycle_after_the_write_then_every_interval", "gate:timer/"]), "copies-table": ("src/tia.rs", " &[MEDIUM, FAR],\n", " &[MEDIUM],\n", ["gates:die", "gate:smoke"]), "board-never-snoops": ("src/board.rs", " if self.snoops {\n", " if false {\n", ["gate:scheme/FE"]), # The lockstep misses it (Pitfall II never reads the swapped group, $1018-$101F): # a recorded blind spot of the gate; schemes.rs's read-group test catches it. "dpc-nibble-swap": (D, "byte.rotate_left(4)", "byte.rotate_left(3)", ["test:schemes:dpc_read_groups_shape_the_byte", "gate:DPC"]), # -- a2600-rust-fast: one per shortcut, each must be caught by the gate -------------- "fast-edge-misdispatch": ("src/tia.rs", "(true, None) => self.edge::(-1, 0),", "(true, None) => self.edge::(-1, 0),", # the board hangs on it (RDY is never released, a WSYNC read # repeats for ever), so only the die gate judges it ["gates:die"]), "fast-edge-drops-a-write": ("src/tia.rs", "(false, Some((a, v))) => self.edge::(", "(false, Some((a, v))) => self.edge::(", ["gates:die", "gate:smoke/(Pitfall|Combat)"]), "fast-quiet-ignores-deferred": ("src/tia.rs", "c.strobe_left == 0 && c.window_history == 0 && !c.deferred)", "c.strobe_left == 0 && c.window_history == 0)", ["gates:die", "gate:."]), "fast-quiet-ignores-strobe": ("src/tia.rs", "let idle = !(RESP0..=RESBL).contains(&address)\n && self", "let idle = self", ["gates:die", "gate:smoke/(Pitfall|Combat)"]), "fast-quiet-ignores-resmp": ("src/tia.rs", "\n && !(self.resmp[1] && self.players[1].scan == 1 && !self.players[1].copy_flag);\n", # the lockstep misses it (no case starts and ends a lock in one # HBLANK with no object clock between): tests/fast.rs catches it ";\n", ["test:fast:a_resmp_lock_holds_the_ring_on_a_step_that_clocks_nothing", "gates:die", "gate:."]), "fast-quiet-ignores-nusiz": ("src/tia.rs", " && self.players[0].size_history == (self.nusiz[0], self.nusiz[0])\n", "", ["gates:die", "gate:."]), "fast-pixels-forget-ball-second": ("src/tia.rs", "|| ball.first || ball.second)", "|| ball.first)", ["gates:die", "gate:."]), "fast-pixels-forget-m1": ("src/tia.rs", "|| m1.first || m1.second ||", "|| m1.second ||", ["gates:die", "gate:."]), "fast-hm-settle-short": ("src/tia.rs", "if self.hm_settle < 4 {", "if self.hm_settle < 3 {", ["gates:die", "gate:."]), "fast-hm-settle-kept-on-hmclr": ("src/tia.rs", "self.hm = [0, 0, 0, 0, 0];\n self.hm_settle = 0;\n", "self.hm = [0, 0, 0, 0, 0];\n", ["gates:die", "gate:."]), "fast-idle-always": ("src/tia.rs", " if idle {\n", " if true {\n", ["gates:die", "gate:."]), "fast-idle-skips-a-strobe": ("src/tia.rs", "if IDLE && !clocked {", "if !clocked {", ["gates:die", "gate:."]), "fast-known-idle-kept": ("src/tia.rs", " self.counters_known_idle = false; // the full form", " // the full form", ["gates:die", "gate:."]), # -- the reference's two for the DPC oscillator's clock per row (28fb095) --------- "dpc-row-clock-dropped": ("src/system.rs", " options.cpu_hz = Some(machine.timing.cpu_hz());\n", " options.cpu_hz = None;\n", ["test:dpc_clock:from_rom_gives_the_oscillator_the_rows_clock", "gates:hashes-rows"]), "dpc-clock-ignored": (D, "ticks_per_cycle: music_hz / cpu_hz,", "ticks_per_cycle: music_hz / NTSC_CPU_HZ,", ["test:dpc_clock:load_with_the_rows_clock_keeps_the_oscillators_hertz", "gates:hashes-rows", "gate:music/DPC Pitfall II PAL"]), # -- Rust-specific, for the 28fb095 surface ----------------------------------------- "clocked-gate-shut": ("src/cartridge/mod.rs", " if !CLOCKED.contains(&family) {\n", " if true {\n", ["test:sockets:a_clocked_scheme_takes_the_row_clock_and_the_rest_ignore_it", "gate:music/DPC Pitfall II (PAL|SECAM)"]), "on-sample-silent": ("src/audio.rs", " on_sample(sample);\n", " on_sample(0.0);\n", ["test:sockets:on_sample_sees_every_sample_as_it_is_made"]), "adopted-cpu-reset": ("src/system.rs", "let old = std::mem::replace(&mut cpu.bus, board);", "let old = std::mem::replace(&mut cpu.bus, board);\n cpu.frame.request_reset();", ["test:sockets:a_running_cpu_is_adopted_as_it_stands", "test:sockets:a_hand_over_mid_run_continues_every_bus_cycle", "gate:handover/"]), "timer-row-ignored": ("src/gates.rs", "let mut system = factory(cartridge, machine);", "let mut system = factory(cartridge, crate::machine::VCS_NTSC);", ["test:sockets:the_timer_rom_gate_hands_its_row_to_the_factory"]), "smoke-keeps-comments": ("src/gates.rs", ".map(|line| line.split('#').next().unwrap_or(\"\").trim())", ".map(|line| line.trim())", ["test:sockets:the_smoke_list_is_on_gates"]), } # fmt: skip def run(cmd, **kw) -> subprocess.CompletedProcess: return subprocess.run(cmd, capture_output=True, text=True, env=ENV, **kw) def judge(kind: str, arg: str) -> bool: """True when the judge fails (the fault is caught).""" nice = ["nice", "-n", "19"] if kind == "test": file, name = arg.split(":", 1) result = run([*nice, "timeout", "3600", "cargo", "test", "--release", "-q", "--manifest-path", str(TREE / "Cargo.toml"), "--target-dir", str(TARGET), "--test", file, "--", "--exact", name]) # fmt: skip return result.returncode != 0 if kind.startswith("gates"): # gatesN: with an N-second timeout (a hang counts as failing) seconds = kind.removeprefix("gates") or "3600" result = run([*nice, "timeout", seconds, str(TARGET / "release" / "a2600-gates"), *arg.split()]) return result.returncode != 0 if kind in ("gate", "save"): extra = ["--save-at-half"] if kind == "save" else [] result = run(["timeout", "7200", sys.executable, str(ROOT / "scripts" / "lockstep.py"), "--rust", str(TARGET / "release" / "a2600-trace"), "--reference-cache", str(ROOT / "external" / "refcache"), "--traces", str(ROOT / "external" / "faults-traces"), "--jobs", os.environ.get("JOBS", "3"), "--only", arg, *extra]) # fmt: skip lines = result.stdout.strip().splitlines() if not lines or " cases identical" not in lines[-1] or lines[-1].startswith("0 of 0"): raise SystemExit(f"gate judge {arg!r} matched no case or did not run: {result.stdout[-500:]}") return result.returncode != 0 if kind == "timeout": build = run(["nice", "-n", "19", "timeout", "3600", "cargo", "build", "--release", "-q", "--features", "frontend", "--bin", "a2600-play", "--manifest-path", str(TREE / "Cargo.toml"), "--target-dir", str(TARGET)]) # fmt: skip if build.returncode: return True rom = Path(os.environ["NO_INTRO_DIR"]) / "Atari - Atari 2600" / "Combat ~ Tank-Plus (USA).zip" env = {**ENV, "SDL_VIDEODRIVER": "dummy", "SDL_AUDIODRIVER": "dummy"} result = subprocess.run(["timeout", "60", str(TARGET / "release" / "a2600-play"), str(rom), "--frames", "3", "--scale", "1"], capture_output=True, env=env) # fmt: skip return result.returncode == 124 raise SystemExit(f"unknown judge {kind}") def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--only") parser.add_argument("--list", action="store_true") args = parser.parse_args() if args.list: print("\n".join(FAULTS)) return 0 if not TREE.exists(): run(["git", "-C", str(ROOT), "worktree", "add", "--detach", str(TREE), "HEAD"], check=True) head = run(["git", "-C", str(ROOT), "rev-parse", "HEAD"]).stdout.strip() run(["git", "-C", str(TREE), "checkout", "--detach", head], check=True) caught = tried = 0 for name, (file, old, new, judges) in FAULTS.items(): if args.only and args.only not in name: continue run(["git", "-C", str(TREE), "checkout", "--", "."], check=True) path = TREE / file text = path.read_text() if text.count(old) != 1: print(f"{name}: SKIPPED (the old text occurs {text.count(old)} times)", flush=True) continue path.write_text(text.replace(old, new)) cargo = TREE / "Cargo.toml" # the path dependency, from the worktree's place cargo.write_text(cargo.read_text().replace('path = "../', f'path = "{ROOT.parent}/')) build = run(["nice", "-n", "19", "timeout", "3600", "cargo", "build", "--release", "-q", "--bins", "--manifest-path", str(cargo), "--target-dir", str(TARGET)]) # fmt: skip if build.returncode: print(f"{name}: BUILD FAILED, not counted {build.stderr[-300:]}", flush=True) continue tried += 1 found = [] for j in judges: kind, _, arg = j.partition(":") if judge(kind, arg): found.append(j) caught += bool(found) print(f"{name}: {'CAUGHT by ' + ', '.join(found) if found else 'MISSED'}", flush=True) run(["git", "-C", str(TREE), "checkout", "--", "."]) print(f"{caught} of {tried} faults caught") return 0 if caught == tried else 1 if __name__ == "__main__": raise SystemExit(main())