#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Seeded faults: one-line faults, each built and run through the ladder's judges. seeded_faults.py [--jobs N] [--only NAME] [--json OUT] Each fault replaces one line of the crate (the old text must occur exactly once in its file) in a fresh copy (``external/faults/job/``, written with new timestamps so cargo cannot reuse a stale build: the 2026-11-13 lesson), builds it, and runs every judge on it. The gate passes when the control (no fault) passes every judge and every fault is caught by at least one. Judges, cheapest first, each against the reference's results already measured (scripts/env.sh's ``REFERENCE_CACHE`` and ``conformance/expected/``): - ``tables`` the opcode table equals the reference's (check_tables.py) - ``tests`` cargo test (tests/interrupts.rs and the doc test) - ``rung0`` the reference's rung 0 states, every cycle (sst --dump vs the cache) - ``rung1`` SingleStepTests judged natively, counts equal the reference's - ``rung2-3`` cputest and krom's tests natively, every line the reference's - ``rung4`` the seven MAME replays, every summary the reference's - ``rung5`` the first 1,000 SingleStepTests states of each file, every cycle - ``lockstep`` the conformance scenarios, traces equal the reference's digests Stdlib only; run after scripts/ladder.sh has filled the caches. """ from __future__ import annotations import argparse import json import os import subprocess import sys from concurrent.futures import ThreadPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] FAULTS_DIR = ROOT / "external" / "faults" NICE = ["nice", "-n", "19"] # (name, file, old text, new text): one line each. FAULTS = [ ("io-skips-confirm", "src/core.rs", " if self.frame.deferred.is_some() {\n self.frame.access();\n }\n let signals = self.signals();\n self.bus.idle", " let signals = self.signals();\n self.bus.idle"), ("next-always-carries", "src/core.rs", " if self.in_bank {\n return (address & 0xFF0000)", " if false {\n return (address & 0xFF0000)"), ("indexed-ignores-16-bit-index", "src/core.rs", "if write || self.p & X == 0 || (base & 0xFF) + index > 0xFF {", "if write || (base & 0xFF) + index > 0xFF {"), ("no-u1-page-wrap", "src/core.rs", "if self.e != 0 && self.d & 0xFF == 0 {\n return (self.d as u32 & 0xFF00)", "if false {\n return (self.d as u32 & 0xFF00)"), ("no-u3-pointer-page", "src/core.rs", "let pointer = if self.e != 0 && self.d & 0xFF != 0 {", "let pointer = if false {"), ("modify-no-emulation-write", "src/core.rs", " if self.e != 0 {\n self.cycle_write(address, value as u8, MLB);", " if false {\n self.cycle_write(address, value as u8, MLB);"), ("push-no-page-one-wrap", "src/core.rs", " self.s = if self.e != 0 {\n (s & 0xFF00) | (s.wrapping_sub(1) & 0xFF)", " self.s = if false {\n (s & 0xFF00) | (s.wrapping_sub(1) & 0xFF)"), ("fix-stack-does-nothing", "src/core.rs", " self.s = 0x0100 | (self.s & 0xFF);\n }\n }\n}", " }\n }\n}"), ("no-note-2-cycle", "src/core.rs", " if self.d & 0xFF != 0 {\n self.io_operand();\n }\n offset", " offset"), ("m-pin-inverted", "src/core.rs", " m: self.p & M != 0,", " m: self.p & M == 0,"), ("sr-y-io-address", "src/core.rs", " self.io((base + 1) & 0xFFFF, IO);", " self.io(base & 0xFFFF, IO);"), ("decimal-add-adjusts-at-9", "src/alu.rs", "if shift < last && digit > ((9_i64 << shift) | ((1_i64 << shift) - 1)) {", "if shift < last && digit >= ((9_i64 << shift) | ((1_i64 << shift) - 1)) {"), ("subtract-no-overflow", "src/alu.rs", " if !(a ^ value) & (a ^ result) & top != 0 {\n p |= V;\n }\n if p & 0x08 != 0 && result <= mask {", " if p & 0x08 != 0 && result <= mask {"), ("compare-strict", "src/alu.rs", " if register >= value {", " if register > value {"), ("bit-flags-from-low-byte", "src/alu.rs", "let top = if wide { value >> 8 } else { value };", "let top = value;"), ("x-high-byte-kept", "src/loads.rs", " let value = value & 0xFF;\n self.p = (self.p & !(N | Z)) | nz8(value);\n value\n } else {", " let value = value & 0xFFFF;\n self.p = (self.p & !(N | Z)) | nz8(value);\n value\n } else {"), ("xba-flags-from-b", "src/loads.rs", "nz8((self.a & 0xFF) as u32)", "nz8((self.a >> 8) as u32)"), ("xce-keeps-sh", "src/loads.rs", " self.y &= 0xFF;\n self.s = 0x0100 | (self.s & 0xFF);", " self.y &= 0xFF;"), ("txs-16-bit-in-emulation", "src/loads.rs", " 0x0100 | (self.x & 0xFF)", " self.x"), ("branch-cross-cycle-native", "src/control.rs", "if self.e != 0 && (target ^ pc) & 0xFF00 != 0 {", "if (target ^ pc) & 0xFF00 != 0 {"), ("cli-no-delay", "src/control.rs", " self.frame.polled_i = Some(self.p & I);\n self.p &= !I;", " self.p &= !I;"), ("rep-no-delay", "src/control.rs", " self.frame.polled_i = Some(self.p & I);\n self.set_p(self.p & !mask);", " self.set_p(self.p & !mask);"), ("plp-no-delay", "src/control.rs", " self.frame.polled_i = Some(self.p & I); // the poll has already happened, on the old I\n", ""), ("interrupt-pushes-pbr-always", "src/control.rs", " if self.e == 0 {\n self.push(self.pbr); // note 7", " if true {\n self.push(self.pbr); // note 7"), ("interrupt-b-set", "src/control.rs", "let pushed = if self.e != 0 { self.p & !X } else { self.p };", "let pushed = self.p;"), ("entry-polls", "src/control.rs", " self.frame.polled = Some(NO_POLL);\n self.frame.deferred = None;\n self.cycles\n }\n\n /// Latch", " self.frame.deferred = None;\n self.cycles\n }\n\n /// Latch"), ("wai-ignores-abort", "src/control.rs", "self.frame.requests & (NMI_LATCH | IRQ_LINE | ABORT_LATCH) != 0", "self.frame.requests & (NMI_LATCH | IRQ_LINE) != 0"), ("abort-after-entry", "src/control.rs", "&& (polled.is_none() || polled.unwrap() & NO_POLL == 0)", ""), ("reset-two-stack-cycles", "src/control.rs", " for _ in 0..3 {", " for _ in 0..2 {"), ("rtl-no-fix-stack", "src/control.rs", " self.pbr = self.pull_new();\n self.fix_stack();", " self.pbr = self.pull_new();"), ("jsl-io-address", "src/control.rs", " self.io(s as u32, IO);\n self.s = s.wrapping_sub(1);", " self.io(s.wrapping_sub(1) as u32, IO);\n self.s = s.wrapping_sub(1);"), ("move-stops-early", "src/block.rs", " if count != 0 {", " if count > 1 {"), ("move-index-always-16", "src/block.rs", "let mask: u32 = if self.p & X != 0 { 0xFF } else { 0xFFFF };", "let mask: u32 = 0xFFFF;"), ("opcode-fetch-kind", "src/cpu.rs", "let opcode = self.cycle_read((self.pbr as u32) << 16 | pc as u32, OPCODE);", "let opcode = self.cycle_read((self.pbr as u32) << 16 | pc as u32, crate::core::PROGRAM);"), ("abort-not-captured", "src/cpu.rs", "abort_pending: self.frame.requests & ABORT_LATCH != 0,", "abort_pending: false,"), ("boundary-abort-first", "src/trace.rs", " if state.skipped_poll {\n return BoundaryKind::Instruction;\n }\n if state.abort_pending {\n return BoundaryKind::Abort;\n }", " if state.abort_pending {\n return BoundaryKind::Abort;\n }\n if state.skipped_poll {\n return BoundaryKind::Instruction;\n }"), ("harness-nmi-late", "src/harness.rs", " if position == self.frame_cycles - self.frame_cycles / 8 {", " if position == self.frame_cycles - self.frame_cycles / 8 + 1 {"), ("harness-dma-pattern", "src/harness.rs", "let b_target = 0x2100 | (b_address + pattern[index % pattern.len()] as u32) & 0xFF;", "let b_target = 0x2100 | b_address & 0xFF;"), ] JUDGES = ("tables", "tests", "rung0", "rung1", "rung2-3", "rung4", "rung5", "lockstep") def env() -> dict[str, str]: """scripts/env.sh's variables, as a shell that sourced it sees them.""" script = f"source {ROOT / 'scripts' / 'env.sh'} && env -0" output = subprocess.run(["bash", "-c", script], capture_output=True, check=True).stdout return dict(item.split("=", 1) for item in output.decode().split("\0") if "=" in item) def fresh_copy(target: Path) -> None: """The crate's sources at ``target``, every file rewritten now (so its timestamp is new, and the last fault's edit is undone).""" for path in [*ROOT.glob("src/**/*.rs"), *ROOT.glob("tests/*.rs"), ROOT / "Cargo.toml", ROOT / "Cargo.lock"]: destination = target / path.relative_to(ROOT) destination.parent.mkdir(parents=True, exist_ok=True) destination.write_bytes(path.read_bytes()) def judge(name: str, crate: Path, variables: dict[str, str]) -> bool: binaries = crate / "target" / "release" cache = Path(variables["REFERENCE_CACHE"]) python = variables["REFERENCE_PYTHON"] quiet = {"stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL} if name == "tables": return subprocess.run([python, str(ROOT / "scripts" / "check_tables.py"), str(binaries / "trace")], **quiet).returncode == 0 if name == "tests": command = [*NICE, "cargo", "test", "--release", "-q", "--manifest-path", str(crate / "Cargo.toml")] return subprocess.run(command, env={**os.environ, "CARGO_TARGET_DIR": str(crate / "target")}, **quiet).returncode == 0 if name in ("rung0", "rung5"): corpus, expected = ( (ROOT / "external" / "rung0", cache / "rung0-200.txt") if name == "rung0" else (Path(variables["SST_65816"]), cache / "sst-1000.txt") ) out = crate / f"{name}.txt" command = [*NICE, str(binaries / "sst"), str(corpus), "--dump", str(out), "--jobs", "2"] if name == "rung5": command += ["--limit", "1000"] if subprocess.run(command, **quiet).returncode: return False return out.read_bytes() == expected.read_bytes() if name == "rung1": result = subprocess.run([*NICE, str(binaries / "sst"), variables["SST_65816"], "--jobs", "2"], capture_output=True, text=True) # fmt: skip last = result.stdout.strip().splitlines()[-1:] or [""] return result.returncode == 0 and last[0] == (ROOT / "conformance/expected/sst.txt").read_text().strip() if name == "rung2-3": result = subprocess.run([*NICE, str(binaries / "roms"), variables["CPUTEST"], variables["KROM"]], capture_output=True, text=True) # fmt: skip return result.returncode == 0 and result.stdout == (ROOT / "conformance/expected/roms.txt").read_text() if name == "rung4": for expected in sorted((ROOT / "conformance" / "expected" / "mame").glob("*.txt")): game = Path(variables["MAME_TRACES"]) / expected.stem result = subprocess.run([*NICE, str(binaries / "mame_replay"), str(game)], capture_output=True, text=True) if result.returncode or result.stdout != expected.read_text(): return False return True if name == "lockstep": scenarios = sorted(str(p) for p in (ROOT / "conformance" / "scenarios").glob("*.json")) command = [sys.executable, str(ROOT / "scripts" / "lockstep.py"), *scenarios, "--python", python, "--rust", str(binaries / "trace"), "--reference-cache", str(cache / "traces"), "--jobs", "2"] # fmt: skip return subprocess.run(command, **quiet).returncode == 0 raise ValueError(name) def run_fault(fault: tuple | None, slot: int, variables: dict[str, str]) -> tuple[str, dict[str, bool]]: crate = FAULTS_DIR / f"job{slot}" crate.mkdir(parents=True, exist_ok=True) fresh_copy(crate) name = "control" if fault is not None: name, file, old, new = fault path = crate / file text = path.read_text() if text.count(old) != 1: return name, {"applies": False} path.write_text(text.replace(old, new)) build = subprocess.run([*NICE, "cargo", "build", "--release", "-q", "--manifest-path", str(crate / "Cargo.toml")], env={**os.environ, "CARGO_TARGET_DIR": str(crate / "target")}, capture_output=True, text=True) # fmt: skip if build.returncode: return name, {"builds": False} return name, {judge_name: judge(judge_name, crate, variables) for judge_name in JUDGES} def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--jobs", type=int, default=2) parser.add_argument("--only") parser.add_argument("--json", type=Path) args = parser.parse_args() variables = env() todo = [None] + [f for f in FAULTS if not args.only or args.only in f[0]] slots = list(range(min(args.jobs, 3))) results: dict[str, dict[str, bool]] = {} def worker(slot: int) -> None: while todo_queue: fault = todo_queue.pop(0) name, verdicts = run_fault(fault, slot, variables) results[name] = verdicts caught = [j for j, ok in verdicts.items() if not ok] print(f"{name}: " + ("passes every judge" if not caught else "caught by " + ", ".join(caught)), flush=True) todo_queue = list(todo) with ThreadPoolExecutor(len(slots)) as pool: list(pool.map(worker, slots)) control = results.get("control", {}) control_ok = bool(control) and all(control.values()) faults = [name for name in results if name != "control"] caught = [name for name in faults if any(not ok for ok in results[name].values()) and results[name].get("applies", True) and results[name].get("builds", True)] # fmt: skip broken = [name for name in faults if not results[name].get("applies", True) or not results[name].get("builds", True)] by_judge = {j: sum(1 for name in faults if results[name].get(j) is False) for j in JUDGES} print(f"control: {'passes every judge' if control_ok else 'FAILS'}") print(f"faults: {len(caught)} of {len(faults) - len(broken)} caught; not applied or not built: {broken or 'none'}") print("caught by: " + ", ".join(f"{j} {n}" for j, n in by_judge.items())) if args.json: args.json.parent.mkdir(parents=True, exist_ok=True) args.json.write_text(json.dumps(results, indent=1, sort_keys=True)) return 0 if control_ok and len(caught) == len(faults) and not broken else 1 if __name__ == "__main__": sys.exit(main())