#!/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 handler and opcode tables equal the reference's (check_tables.py) - ``tests`` cargo test (tests/core_contract.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), then every case unmasked, every cycle (sst --dump vs the cache) - ``rung2-3`` spctest and PeterLemon's tests natively, every line the reference's - ``rung4`` the six MAME replays, every summary the reference's - ``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 = [ ("dummy-flag-not-set", "src/core.rs", " self.dummy = true;\n", ""), ("dp-ignores-p", "src/core.rs", "((self.psw & FLAG_P) as u16) << 3", "((self.psw & FLAG_P) as u16) << 2"), ("absolute-indexed-no-idle", "src/core.rs", " let base = self.fetch_word();\n self.idle();\n", " let base = self.fetch_word();\n"), ("indirect-y-no-idle", "src/core.rs", " let offset = self.fetch() as u32;\n self.idle();\n self.load_pointer(offset).wrapping_add", " let offset = self.fetch() as u32;\n self.load_pointer(offset).wrapping_add"), ("push-steps-two", "src/core.rs", " self.sp = self.sp.wrapping_sub(1);", " self.sp = self.sp.wrapping_sub(2);"), ("nz16-from-bit-7", "src/core.rs", "let negative = if value & 0x8000 != 0", "let negative = if value & 0x80 != 0"), ("stopped-step-two", "src/core.rs", " return 1;\n }\n self.cycle = -1;", " return 2;\n }\n self.cycle = -1;"), ("cmp-carry-strict", "src/alu.rs", " let carry = if difference >= 0 { FLAG_C } else { 0 };", " let carry = if difference > 0 { FLAG_C } else { 0 };"), ("adc-half-carry-bit-3", "src/alu.rs", "if (x ^ y ^ total) & 0x10 != 0 {", "if (x ^ y ^ total) & 0x08 != 0 {"), ("adc-no-overflow", "src/alu.rs", " if !(x ^ y) & (x ^ total) & 0x80 != 0 {\n psw |= FLAG_V;\n }\n", ""), ("cmp-dd-ds-writes", "src/alu.rs", " if op >> 5 == 3 {\n self.idle(); // C8: CMP does not write; anomie", " if false {\n self.idle(); // C8: CMP does not write; anomie"), ("daa-ignores-h", "src/alu.rs", " if self.psw & FLAG_H != 0 || self.a & 0x0F > 9 {", " if self.a & 0x0F > 9 {"), ("das-ignores-h", "src/alu.rs", " if self.psw & FLAG_H == 0 || self.a & 0x0F > 9 {", " if self.a & 0x0F > 9 {"), ("xcn-rotates-three", "src/alu.rs", "self.a = self.a.rotate_left(4);", "self.a = self.a.rotate_left(3);"), ("tset1-flags-reversed", "src/bit.rs", " self.set_nz(self.a.wrapping_sub(value));\n self.read_dummy(address);\n self.write(address, value | self.a);", " self.set_nz(value.wrapping_sub(self.a));\n self.read_dummy(address);\n self.write(address, value | self.a);"), ("or1-no-idle", "src/bit.rs", " self.idle(); // anomie 23: \"cycle 5 only in EOR1 and OR1\"\n", ""), ("mov1-ignores-c", "src/bit.rs", " if self.psw & FLAG_C != 0 {\n value | mask\n } else {\n value & !mask\n },", " value | mask,"), ("addw-keeps-c", "src/word.rs", " self.psw &= !FLAG_C;\n let low = self.adc(", " let low = self.adc("), ("cmpw-carry-strict", "src/word.rs", "if difference >= 0 { FLAG_C } else { 0 };\n self.set_nz16(", "if difference > 0 { FLAG_C } else { 0 };\n self.set_nz16("), ("decw-no-borrow", "src/word.rs", "value = (value + ((self.load(offset + 1) as i32) << 8)) & 0xFFFF;", "value = ((value & 0xFF) + ((self.load(offset + 1) as i32) << 8)) & 0xFFFF;"), ("mul-six-idles", "src/word.rs", " for _ in 0..7 {", " for _ in 0..6 {"), ("div-half-strict", "src/word.rs", "let half = if self.y & 0x0F >= self.x & 0x0F", "let half = if self.y & 0x0F > self.x & 0x0F"), ("mov-a-ixp-steps-two", "src/moves.rs", " let value = self.load(self.x as u32);\n self.x = self.x.wrapping_add(1);", " let value = self.load(self.x as u32);\n self.x = self.x.wrapping_add(2);"), ("mov-ixp-a-reads", "src/moves.rs", " self.idle(); // anomie 13b: \"No RMW here\"", " self.read_dummy(self.pc); // anomie 13b: \"No RMW here\""), ("mov-d-imm-no-dummy", "src/moves.rs", " self.read_dummy(self.dp(target)); // anomie 10: \"Yes, RMW even for MOV\"\n", ""), ("pop-psw-into-a", "src/moves.rs", " 4 => self.psw = value,", " 4 => self.a = value,"), ("push-no-idle", "src/moves.rs", " self.idle(); // C6: SST and ares; anomie asks", " // C6: SST and ares; anomie asks"), ("taken-one-idle", "src/control.rs", " fn taken(&mut self, offset: u8) {\n self.idle();\n self.idle();", " fn taken(&mut self, offset: u8) {\n self.idle();"), ("branch-inverted", "src/control.rs", "!= 0) == (op & 0x20 != 0) {", "!= 0) != (op & 0x20 != 0) {"), ("bbs-bit-index", "src/control.rs", "if (value >> (op >> 5) & 1 != 0)", "if (value >> (op >> 4 & 7) & 1 != 0)"), ("dbnz-no-write", "src/control.rs", " let value = self.load(target).wrapping_sub(1);\n self.store(target, value);\n", " let value = self.load(target).wrapping_sub(1);\n"), ("call-one-idle-after", "src/control.rs", " self.push_pc();\n self.idle();\n self.idle();\n self.pc = target;", " self.push_pc();\n self.idle();\n self.pc = target;"), ("tcall-vector", "src/control.rs", "let vector = TCALL_BASE - 2 * (op >> 4) as u16;", "let vector = TCALL_BASE - 2 * (op >> 5) as u16;"), ("brk-no-b", "src/control.rs", "self.psw = self.psw & !FLAG_I | FLAG_B;", "self.psw &= !FLAG_I;"), ("ret1-keeps-psw", "src/control.rs", " self.psw = self.pull();\n self.pull_pc();", " self.pull();\n self.pull_pc();"), ("reset-keeps-p", "src/cpu.rs", "self.psw &= !(FLAG_P | FLAG_B | FLAG_I);", "self.psw &= !(FLAG_B | FLAG_I);"), ("harness-timer2-slow", "src/harness.rs", " if self.cycles & 15 == 0 {", " if self.cycles & 31 == 0 {"), ("harness-no-port-clear", "src/harness.rs", " if value & 0x10 != 0 {\n // every time a 1 is written", " if false {\n // every time a 1 is written"), ("replay-keeps-repeated-read", "src/replay.rs", "&& OPCODES[signals.opcode as usize].mnemonic == \"ADC\"", "&& OPCODES[signals.opcode as usize].mnemonic == \"ADCX\""), ("replay-dummy-unanswered", "src/replay.rs", " if signals.dummy {\n self.unlogged_dummy_reads += 1;", " if false {\n self.unlogged_dummy_reads += 1;"), ] JUDGES = ("tables", "tests", "rung0", "rung1", "rung2-3", "rung4", "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} environment = {**os.environ, **variables} if name == "tables": return subprocess.run([python, "-I", str(ROOT / "scripts" / "check_tables.py"), str(binaries / "trace")], env=environment, **quiet).returncode == 0 # fmt: skip 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 == "rung0": out = crate / "rung0.txt" command = [*NICE, str(binaries / "sst"), str(ROOT / "external" / "rung0"), "--dump", str(out), "--jobs", "2"] if subprocess.run(command, **quiet).returncode: return False return out.read_bytes() == (cache / "rung0.txt").read_bytes() if name == "rung1": result = subprocess.run([*NICE, str(binaries / "sst"), variables["SST_SPC700"], "--jobs", "2"], capture_output=True, text=True) # fmt: skip last = result.stdout.strip().splitlines()[-1:] or [""] if result.returncode or last[0] != (ROOT / "conformance/expected/sst.txt").read_text().strip(): return False out = crate / "rung1.txt" command = [*NICE, str(binaries / "sst"), variables["SST_SPC700"], "--dump", str(out), "--jobs", "2"] if subprocess.run(command, **quiet).returncode: return False return out.read_bytes() == (cache / "sst-all.txt").read_bytes() if name == "rung2-3": result = subprocess.run([*NICE, str(binaries / "programs"), variables["SPCTEST"], variables["CPUTEST"]], capture_output=True, text=True) # fmt: skip return result.returncode == 0 and result.stdout == (ROOT / "conformance/expected/programs.txt").read_text() if name == "rung4": for expected in sorted((ROOT / "conformance" / "expected" / "mame").glob("*.txt")): log = Path(variables["MAME_TRACES"]) / expected.stem / "error.log" result = subprocess.run([*NICE, str(binaries / "mame_replay"), variables["IPL_ROM"], str(log)], capture_output=True, text=True) # fmt: skip 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, env=environment, **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())