#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Rung 6: a gate that cannot fail proves nothing. Seed one fault at a time into a copy of the crate and show that a named rung catches each. Each fault is one exact text replacement in a fresh copy of ``src/`` and ``tests/`` (written anew, so every file has a new timestamp and cargo cannot reuse a stale build: the methodology's lesson of 2026-11-13), built into its worker's own target directory; then every judge runs on it and the matrix says which caught it: - rung 1: every row's table against the reference's ``opcodes_for``, and the rung-1 lockstep scenarios (the workout; the first 300,000 boundaries of Dormann's and Clark's programs on every row); - rung 2: SingleStepTests, all 7,660,000 cases, the counts against the reference's; - rung 3: Dormann's and Clark's programs natively, the lines against the reference's; - rung 4: the capture lockstep, all ten replays to the end, against the reference's reports; and the 80 interrupt, WAI, STP and random-memory lockstep scenarios; - rung 5: ``tests/rows_on_frame.rs``. The lockstep judges compare against a cache of the reference's traces: each scenario is run once on w65c02-python (``scripts/reference_trace.py``), its trace normalised (the ``mnemonic`` and ``operands`` the reference's disassembler adds are dropped; keys sorted, no spaces, as both cores write them) and hashed, and a faulted build's trace must hash the same. The control run (no fault) must match every cached hash and pass every judge, or nothing is concluded. Text equality is stricter than the reference's ``first_trace_divergence``, so a fault "caught" this way is caught; rungs 1 and 4 run the reference's own comparison on the unfaulted tree. The faults are the reference's 44 (w65c02-python ``scripts/seeded_faults.py``, docs/validation.md "Rung 7") as they apply to the transcription, plus two of this crate's own (the ``fetch`` signal, the frame's ``access()``). seeded_faults.py [--only WORD] [--jobs N] [--json OUT] """ from __future__ import annotations import argparse import hashlib import json import os import shutil import subprocess import sys from concurrent.futures import ThreadPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] WORK = ROOT / "external" / "faults" NICE = ["nice", "-n", "19"] ENV = {**os.environ, "PYPY_GC_NURSERY": "1M"} # (name, file under src/ or tests/, exact text, replacement). The text must occur exactly once. FAULTS = [ # -- cycles: dropped, added, a write for a read ---------------------------------------- ("a dropped dummy cycle: PLA without its read of the stack", "src/control.rs", " self.fetch_discard();\n self.read(0x0100 | self.s as u16);\n let value = self.pull();\n self.a = ", " self.fetch_discard();\n self.extra = self.extra.wrapping_sub(1);\n let value = self.pull();\n self.a = "), ("a dropped dummy cycle: one-byte instructions take one cycle (TAX)", "src/loads.rs", " pub(crate) fn op_tax(&mut self) {\n self.fetch_discard();", " pub(crate) fn op_tax(&mut self) {\n self.extra = self.extra.wrapping_sub(1);"), ("a write for a read: read-modify-write writes twice, as the NMOS part", "src/core.rs", " let value = self.read(address);\n self.read(address);\n", " let value = self.read(address);\n self.write(address, value);\n"), ("the decimal cycle missing", "src/alu.rs", " fn decimal_cycle(&mut self) {\n // MEASURED (CAP: the cycle and its address); DOC (DS Table 7-1: the cycle).\n self.fetch_discard();\n self.extra += 1;\n }", " fn decimal_cycle(&mut self) {}"), ("INC and DEC abs,X take six cycles within a page, as the shifts (C11)", "src/dispatch.rs", '(Op::Inc, Mode::EaAbxFixed, "INC", Form::Abx, 7)', '(Op::Inc, Mode::EaAbx, "INC", Form::Abx, 6)'), ("ASL abs,X always takes seven cycles, as the NMOS part", "src/dispatch.rs", '(Op::Asl, Mode::EaAbx, "ASL", Form::Abx, 6)', '(Op::Asl, Mode::EaAbxFixed, "ASL", Form::Abx, 7)'), ("STA abs,X takes four cycles within a page", "src/dispatch.rs", '(Op::Sta, Mode::EaAbxFixed, "STA", Form::Abx, 5)', '(Op::Sta, Mode::EaAbx, "STA", Form::Abx, 4)'), ("JMP (abs) keeps the NMOS part's page-wrap bug", "src/control.rs", " self.pc = ((self.read(pointer.wrapping_add(1)) as u16) << 8) | low;\n }\n\n /// JMP (abs,X)", " self.pc = ((self.read((pointer & 0xFF00) | (pointer.wrapping_add(1) & 0xFF)) as u16) << 8) | low;\n }\n\n /// JMP (abs,X)"), # -- the NOP classes -------------------------------------------------------------------- ("a wrong NOP length: the x2 NOPs are one byte", "src/nops.rs", " pub(crate) fn op_nop_imm(&mut self) {\n self.fetch_byte();", " pub(crate) fn op_nop_imm(&mut self) {\n self.fetch_discard();"), ("a wrong NOP length: one-cycle NOPs take two cycles, as $EA", "src/dispatch.rs", 'pub const ONE_CYCLE_NOP: OpcodeRow = (Op::NopOneCycle, Mode::Implied, "NOP", Form::Imp, 1);', 'pub const ONE_CYCLE_NOP: OpcodeRow = (Op::Nop, Mode::Implied, "NOP", Form::Imp, 2);'), ("a wrong NOP length: $5C takes four cycles, as the corpus has it (C1)", "src/nops.rs", " for _ in 0..4 {\n self.read(0xFFFF);\n }", " self.extra = self.extra.wrapping_sub(4);"), ("a wrong NOP length: $44 is three bytes", "src/dispatch.rs", '(Op::NopZp, Mode::Implied, "NOP", Form::Zp, 3)', '(Op::NopAbs, Mode::Implied, "NOP", Form::Abs, 4)'), ("a wrong NOP length: $DC and $FC are two bytes", "src/nops.rs", " let address = self.fetch_word();\n if self.row.nop_dc_fc_reads", " let address = self.fetch_byte() as u16;\n self.fetch_discard();\n if self.row.nop_dc_fc_reads"), # -- the rows' distinguishing cells ----------------------------------------------------- ("rows swapped: the G65SC02 has the bit instructions", "src/cpu.rs", " bit_instructions: false, // C2\n", " bit_instructions: true, // C2\n"), ("rows swapped: the R65C02 has WAI and STP, as MAME's (C5)", "src/cpu.rs", " wai_stp: false, // U3: `$CB`", " wai_stp: true, // U3: `$CB`"), ("rows swapped: the R65C02 writes the stack at reset", "src/cpu.rs", " reset_writes_stack: false, // CAP\n", " reset_writes_stack: true, // CAP\n"), ("rows swapped: the G65SC02 reads the stack at reset", "src/cpu.rs", " reset_writes_stack: true, // CAP; GDS Table V\n", " reset_writes_stack: false, // CAP; GDS Table V\n"), ("rows swapped: the Lynx II's cell has no bit instructions (C12)", "src/cpu.rs", " bit_instructions: true, // C12", " bit_instructions: false, // C12"), ("rows swapped: the W65C02S has no WAI or STP", "src/cpu.rs", " wai_stp: true,\n reset_writes_stack: false, // U1", " wai_stp: false,\n reset_writes_stack: false, // U1"), # -- flags and results ------------------------------------------------------------------ ("D not cleared by an interrupt entry", "src/control.rs", " self.p = (self.p | I) & !D; // D cleared by interrupts too (DS Table 7-1)\n", " self.p |= I;\n"), ("D not cleared by BRK", "src/control.rs", ' // D is cleared on the 65C02 (DS Table 7-1 "Decimal flag"; CL section 6).\n self.p = (self.p | I) & !D;\n', " self.p |= I;\n"), ("D not cleared by reset", "src/control.rs", ' self.p = (self.p | I) & !D; // DS Table 7-1 "Decimal flag"\n', " self.p |= I;\n"), ("an interrupt entry pushes P with B set", "src/control.rs", " self.push(self.p | U); // B clear: what tells an IRQ from a BRK (CL section 6)\n", " self.push(self.p | U | B);\n"), ("BRK is one byte: the return address is PC + 1", "src/control.rs", " self.fetch_byte(); // the signature byte: read and skipped\n", " self.fetch_discard();\n"), ("BIT #imm copies N and V from the operand", "src/alu.rs", " self.p = (self.p & !Z) | if self.a & operand != 0 { 0 } else { Z };\n", " self.p = (self.p & !(N | V | Z)) | (operand & (N | V)) | if self.a & operand != 0 { 0 } else { Z };\n"), ("TSB takes Z from the stored result, as the HuC6280", "src/bits.rs", " self.p = (self.p & !Z) | if self.a & value != 0 { 0 } else { Z }; // Z from the test, not the result\n", " self.p = (self.p & !Z) | if self.a | value != 0 { 0 } else { Z };\n"), ("decimal ADC takes V from the binary sum", "src/alu.rs", " overflow = decimal_add_overflow(a, operand, p & C);\n", " overflow = !(a ^ operand) & (a ^ a.wrapping_add(operand).wrapping_add(p & C)) & 0x80 != 0;\n"), ("decimal SBC keeps the NMOS part's result for invalid digits (BC 4d dropped)", "src/alu.rs", " if low < 0 {\n total -= 0x06; // BC 4d\n }\n", " if low < 0 && (total & 0x0F) > 0x09 {\n total -= 0x06;\n }\n"), ("decimal ADC gives N and Z of the binary sum, as the NMOS part", "src/alu.rs", '"valid flags" (DS Table 7-1).\n self.p =\n (p & !(N | V | Z | C)) | NZ[result as usize]', '"valid flags" (DS Table 7-1).\n self.p =\n (p & !(N | V | Z | C)) | NZ[(a as usize + operand as usize + (p & C) as usize) & 0xFF]'), ("RMB and SMB act on the wrong bit", "src/bits.rs", " let mask = 1u8 << ((self.opcode >> 4) & 7);\n let zp = self.fetch_byte() as u16;\n let value = self.read(zp);\n self.read(zp); // read-modify-write", " let mask = 1u8 << ((self.opcode >> 5) & 7);\n let zp = self.fetch_byte() as u16;\n let value = self.read(zp);\n self.read(zp); // read-modify-write"), # -- dummy-read addresses: the corpus's, back in (C10, C13 to C18) and MAME's (U9) ------ ("corpus address: zp,X reads the unindexed zero-page address (C18)", "src/core.rs", " self.read(self.pc.wrapping_sub(1)); // CAP, both parts; SST reads `zp` instead (C18)\n", " self.read(zp as u16);\n"), ("corpus address: an indexed store within a page re-reads PC+2 (C14)", "src/core.rs", " let address = base.wrapping_add(self.x as u16);\n self.read(if (address ^ base) & 0xFF00 != 0 {", " let address = base.wrapping_add(self.x as u16);\n self.read(if true {"), ("corpus address: STA (zp),Y re-reads PC+1 (C15)", "src/core.rs", " let base = ((self.read(high_address) as u16) << 8) | low;\n self.read(high_address);\n", " let base = ((self.read(high_address) as u16) << 8) | low;\n self.read(self.pc.wrapping_sub(1));\n"), ("corpus address: a branch across a page reads the old page (C16)", "src/control.rs", " if (target ^ pc) & 0xFF00 != 0 {\n self.fetch_discard();\n self.extra += 1;\n }\n self.pc = target;\n }\n\n /// BPL", " if (target ^ pc) & 0xFF00 != 0 {\n self.read((pc & 0xFF00) | (target & 0x00FF));\n self.extra += 1;\n }\n self.pc = target;\n }\n\n /// BPL"), ("corpus address: JMP (abs) reads the pointer first (C17)", "src/control.rs", " self.read(self.pc.wrapping_sub(1));\n let low = self.read(pointer) as u16;\n self.pc = ((self.read(pointer.wrapping_add(1)) as u16) << 8) | low;\n }\n\n /// JMP (abs,X)", " let low = self.read(pointer) as u16;\n self.read((pointer & 0xFF00) | (pointer.wrapping_add(1) & 0x00FF));\n self.pc = ((self.read(pointer.wrapping_add(1)) as u16) << 8) | low;\n }\n\n /// JMP (abs,X)"), ("corpus address: the decimal cycle re-reads the last operand byte (C13)", "src/alu.rs", " fn decimal_cycle(&mut self) {\n // MEASURED (CAP: the cycle and its address); DOC (DS Table 7-1: the cycle).\n self.fetch_discard();", " fn decimal_cycle(&mut self) {\n self.read(self.pc.wrapping_sub(1));"), ("corpus address: $DC and $FC re-read PC+2 (C10)", "src/cpu.rs", " nop_dc_fc_reads: NopDcFcReads::Absolute,", " nop_dc_fc_reads: NopDcFcReads::Operand,"), ("MAME's reading: $5C reads the next opcode's address (U9)", "src/cpu.rs", " nop_5c_reads: Nop5cReads::FfPage,", " nop_5c_reads: Nop5cReads::Pc,"), # -- the poll, the pins, WAI ------------------------------------------------------------ ("CLI admits a pending IRQ at once", "src/control.rs", " self.frame.polled_i = Some(self.p & I); // this instruction's poll saw the old I (U5)\n", ""), ("one-cycle NOPs poll (U7)", "src/cpu.rs", " one_cycle_nops_poll: false,", " one_cycle_nops_poll: true,"), ("a bus access skips the frame's confirmation (the Rust form of the reference's lookup trap)", "src/core.rs", " pub(crate) fn read(&mut self, address: u16) -> u8 {\n self.frame.access();", " pub(crate) fn read(&mut self, address: u16) -> u8 {"), ("SYNC is not raised in the first cycle of an interrupt entry", "src/control.rs", " self.sync = true;\n self.fetch = true;\n self.read(pc);\n self.sync = false;\n self.read(pc);\n self.fetch = false;\n let vector", " self.fetch = true;\n self.read(pc);\n self.sync = false;\n self.read(pc);\n self.fetch = false;\n let vector"), ("WAI waits even when IRQ is already low", "src/control.rs", " if self.frame.requests & (IRQ_LINE | NMI_LATCH) == 0 {\n self.waiting = true;\n self.frame.halted = true;\n }", " let _ = IRQ_LINE;\n self.waiting = true;\n self.frame.halted = true;"), ("the instruction length of BBR and BBS is two bytes", "src/dispatch.rs", " Form::Zprel => 3,", " Form::Zprel => 2,"), # -- this crate's own ------------------------------------------------------------------- ("the fetch signal is not raised for operand bytes", "src/core.rs", " self.pc = pc.wrapping_add(1);\n self.fetch = true;\n let value = self.read(pc);", " self.pc = pc.wrapping_add(1);\n let value = self.read(pc);"), ("the sync signal stays high after the opcode fetch", "src/cpu.rs", " let opcode = self.read(pc);\n self.sync = false;\n", " let opcode = self.read(pc);\n"), ] def env_paths() -> dict[str, str]: """scripts/env.sh's variables, as the rung scripts see them.""" out = subprocess.run( ["bash", "-c", f"source {ROOT / 'scripts' / 'env.sh'} && env"], capture_output=True, text=True, check=True, ).stdout return dict(line.split("=", 1) for line in out.splitlines() if "=" in line) def lockstep_scenarios() -> dict[str, list[Path]]: scenarios = ROOT / "conformance" / "scenarios" external = ROOT / "external" / "scenarios" return { "1": sorted(scenarios.glob("tour-*.json")) + sorted(external.glob("program-*.json")), "4": sorted(scenarios.glob("interrupts-*.json")) + sorted(scenarios.glob("wai-stp-*.json")) + sorted(scenarios.glob("one-cycle-nops-*.json")) + sorted(external.glob("random-memory-*.json")), } def hash_stream(command: list[str]) -> str: digest = hashlib.sha256() process = subprocess.Popen(command, stdout=subprocess.PIPE) assert process.stdout is not None for chunk in iter(lambda: process.stdout.read(1 << 20), b""): digest.update(chunk) if process.wait(): return "failed" return digest.hexdigest() def reference_hashes(paths: dict[str, str], scenarios: list[Path]) -> dict[str, str]: """The cache: each scenario's reference trace, normalised and hashed (made once).""" cache_file = WORK / "reference-hashes.json" cache = json.loads(cache_file.read_text()) if cache_file.exists() else {} head = subprocess.run(["git", "-C", paths["W65C02_PYTHON"], "rev-parse", "HEAD"], capture_output=True, text=True, check=True).stdout.strip() if cache.get("reference") != head: cache = {"reference": head} def key(scenario: Path) -> str: # A scenario's cached hash belongs to its exact text (the generator may change). return f"{scenario.stem}:{hashlib.sha256(scenario.read_bytes()).hexdigest()[:16]}" missing = [s for s in scenarios if key(s) not in cache] def make(scenario: Path) -> tuple[str, str]: trace = WORK / "refcache" / f"{scenario.stem}.jsonl" trace.parent.mkdir(parents=True, exist_ok=True) subprocess.run([*NICE, paths["REFERENCE_PYTHON"], str(ROOT / "scripts" / "reference_trace.py"), str(scenario), "--out", str(trace)], check=True, env=ENV) normalise = ( "import json,sys,hashlib\n" "h=hashlib.sha256()\n" "for line in open(sys.argv[1]):\n" " r=json.loads(line)\n" " if r['instruction']:\n" " r['instruction'].pop('mnemonic',None); r['instruction'].pop('operands',None)\n" " h.update((json.dumps(r,sort_keys=True,separators=(',',':'))+'\\n').encode())\n" "print(h.hexdigest())\n" ) digest = subprocess.run([*NICE, paths["REFERENCE_PYTHON"], "-c", normalise, str(trace)], capture_output=True, text=True, check=True, env=ENV).stdout.strip() trace.unlink() return key(scenario), digest if missing: print(f"caching {len(missing)} reference traces", flush=True) with ThreadPoolExecutor(4) as pool: for name, digest in pool.map(make, missing): cache[name] = digest cache_file.write_text(json.dumps(cache, indent=1, sort_keys=True)) return {scenario.stem: cache[key(scenario)] for scenario in scenarios} def run(command: list[str], **kwargs) -> subprocess.CompletedProcess: return subprocess.run([*NICE, *command], capture_output=True, text=True, env=ENV, **kwargs) def judge(tree: Path, target: Path, paths: dict[str, str], hashes: dict[str, str], scenarios: dict[str, list[Path]]) -> dict[str, bool]: """Every rung on one built tree; rung -> whether it failed (caught the fault).""" binaries = target / "release" expected = ROOT / "conformance" / "expected" caught: dict[str, bool] = {} def lockstep(rung: str) -> bool: for scenario in scenarios[rung]: if hash_stream([*NICE, str(binaries / "trace"), str(scenario)]) != hashes[scenario.stem]: return True return False tables = run([paths["REFERENCE_PYTHON"], str(ROOT / "scripts" / "check_tables.py"), str(binaries / "trace")]) caught["1"] = tables.returncode != 0 or lockstep("1") sst = run([str(binaries / "sst"), paths["SST_65X02"], "--jobs", "2"]) lines = [line for line in sst.stdout.splitlines() if " on " in line and "cases," in line] caught["2"] = sst.returncode != 0 or lines != (expected / "sst.txt").read_text().splitlines() programs = run([str(binaries / "programs"), paths["DORMANN_BUILT"], paths["DORMANN_FUNCTIONAL"]]) caught["3"] = programs.returncode != 0 or programs.stdout != (expected / "programs.txt").read_text() captures = run([str(binaries / "capture"), paths["CAPTURES"], str(ROOT / "external" / "capture-starts.json"), str(Path(paths["CAPTURES"]) / "foot_data14.bin"), "--jobs", "2"]) caught["4"] = (captures.returncode != 0 or captures.stdout != (expected / "capture.txt").read_text() or lockstep("4")) tests = run(["cargo", "test", "--release", "-q", "--manifest-path", str(tree / "Cargo.toml"), "--target-dir", str(target), "--test", "rows_on_frame"]) caught["5"] = tests.returncode != 0 return caught def faulted_tree(name: str, fault: tuple | None) -> Path: """A fresh copy of the crate with one fault (none: the control). Files are written anew.""" tree = WORK / "trees" / name for sub in ("src", "tests"): for source in (ROOT / sub).rglob("*.rs"): target = tree / source.relative_to(ROOT) target.parent.mkdir(parents=True, exist_ok=True) target.write_text(source.read_text()) for file in ("Cargo.toml", "Cargo.lock"): (tree / file).write_text((ROOT / file).read_text()) if fault is not None: _, file, old, new = fault path = tree / file text = path.read_text() if text.count(old) != 1: raise SystemExit(f"fault {fault[0]!r}: its text occurs {text.count(old)} times in {file}") path.write_text(text.replace(old, new)) return tree def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--only", action="append", help="faults whose name contains this") parser.add_argument("--jobs", type=int, default=2) parser.add_argument("--json", type=Path) parser.add_argument("--check", action="store_true", help="apply every fault, build nothing") args = parser.parse_args() if len({fault[0] for fault in FAULTS}) != len(FAULTS): raise SystemExit("two faults share a name") faults = [f for f in FAULTS if not args.only or any(word in f[0] for word in args.only)] WORK.mkdir(parents=True, exist_ok=True) for index, fault in enumerate(faults): faulted_tree(f"check-{index}", fault) if args.check: print(f"{len(faults)} faults apply, each to exactly one place") return 0 paths = env_paths() subprocess.run([*NICE, "python3", str(ROOT / "scripts" / "make_scenarios.py"), "--programs", paths["DORMANN_BUILT"], paths["DORMANN_FUNCTIONAL"]], check=True, capture_output=True) scenarios = lockstep_scenarios() hashes = reference_hashes(paths, scenarios["1"] + scenarios["4"]) slots = [f"slot{n}" for n in range(args.jobs)] def one(task: tuple[int, tuple | None]) -> tuple[str, dict[str, bool] | str]: index, fault = task name = "control: no fault" if fault is None else fault[0] slot = slots[index % len(slots)] tree = faulted_tree(slot + f"-{index}", fault) target = WORK / "target" / slot build = run(["cargo", "build", "--release", "-q", "--manifest-path", str(tree / "Cargo.toml"), "--target-dir", str(target)]) if build.returncode: return name, "does not build: " + build.stderr[-600:] return name, judge(tree, target, paths, hashes, scenarios) # One fault per slot at a time (each slot has its own target directory). tasks = [(0, None)] + [(i + 1, f) for i, f in enumerate(faults)] results: dict[str, dict[str, bool]] = {} control = one(tasks[0]) if not isinstance(control[1], dict) or any(control[1].values()): raise SystemExit(f"the control run fails a judge ({control[1]}): nothing can be concluded") print("control: no fault: every judge passes", flush=True) missed = [] pending = tasks[1:] with ThreadPoolExecutor(len(slots)) as pool: while pending: batch, pending = pending[: len(slots)], pending[len(slots):] # Re-key each batch so task i of the batch uses slot i. batch = [(n, fault) for n, (_, fault) in enumerate(batch)] for name, outcome in pool.map(one, batch): if isinstance(outcome, str): raise SystemExit(f"{name}: {outcome}") results[name] = outcome by = [rung for rung, failed in outcome.items() if failed] print(f"{name}: caught by rungs {' '.join(by) if by else '(none)'}", flush=True) if not by: missed.append(name) caught = len(results) - len(missed) print(f"\n{len(results)} faults, {caught} caught, {len(missed)} missed") for name in missed: print(f" NOT CAUGHT: {name}") only2 = [n for n, o in results.items() if [r for r, f in o.items() if f] == ["2"]] for name in only2: print(f" caught only by rung 2, so resting on the emulator-generated corpus: {name}") if args.json: args.json.write_text(json.dumps(results, indent=1)) return 1 if missed else 0 if __name__ == "__main__": sys.exit(main())