#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """A gate that cannot fail proves nothing: break this crate one rule at a time and check that the ladder catches every break. python3 scripts/seeded_faults.py [--jobs 3] [NAME ...] The faults are pokey-python's 64 (its ``scripts/seeded_faults.py`` at 6ed1ffa), each the same rule broken the same way in ``src/chip.rs``, then faults of our own in what is Rust-specific (the seeding of ``power_on``, the snapshot, the wiring calls, ``take_outputs``, the register masks, the variant rows' arithmetic, the RC helper). Each is applied to a copy of the repository under ``external/faults//`` (the working tree is never touched), every file of the copy stamped now (methodology: a copy with old timestamps can let cargo reuse a stale build), and judged by every rung: - rung 1: ``scripts/rung1.sh`` on the copy (the transcribed tests, AcidSAP included); - rung 2: the lockstep scripts against the reference traces ``scripts/rung2.sh`` wrote with its defaults (run it first); - rung 3: ``scripts/rung3.sh``: the conformance kit (``cargo test`` in the copy) and the validation streams against the reference traces already written. A fault is caught when any rung fails; the table says which. The unbroken copy is judged first and must pass every rung. """ from __future__ import annotations import argparse import os import queue import shutil import subprocess import sys from concurrent.futures import ThreadPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parent.parent CONTROL = """let control = if self.w_reg == 2 * ch as i32 + 1 {""" #: (name, file under src/, exact text (must occur once), replacement) FAULTS: list[tuple[str, str, str, str]] = [ # -- the reference's 64, in its order -- ("STIMER reload a tick late", "chip.rs", "self.stimer_q |= 0b100;", "self.stimer_q |= 0b1000;"), ("borrow pipeline 2 instead of 3", "chip.rs", "self.pend[ch] = 3;", "self.pend[ch] = 2;"), ("17-bit tap moved", "chip.rs", "(r ^ (r >> 5) ^ 1) & 1", "(r ^ (r >> 4) ^ 1) & 1"), ("9-bit tap moved", "chip.rs", "((r >> 8) ^ (r >> 13) ^ 1) & 1", "((r >> 8) ^ (r >> 12) ^ 1) & 1"), ("RANDOM not inverted", "chip.rs", "(!(self.poly17 >> 9) & 0xFF) as u8", "((self.poly17 >> 9) & 0xFF) as u8"), ("RANDOM one stage off", "chip.rs", "(!(self.poly17 >> 9) & 0xFF) as u8", "(!(self.poly17 >> 8) & 0xFF) as u8"), ("15 kHz special state", "chip.rs", "p15 = c == 0b1001001;", "p15 = c == 0b1001000;"), ("64 kHz feedback tap", "chip.rs", "((c >> 4) ^ (c >> 2)) & 1", "((c >> 4) ^ (c >> 1)) & 1"), # C64_RESET is only the power-on value: init mode shifts the reset in (B2.1a), so changing # it is an equivalent mutant (the reference notes it and does not count it either). ("64 kHz special state", "chip.rs", "p64 = c == 0b00010;", "p64 = c == 0b00100;"), ("joined pair: low not reloaded by high", "chip.rs", "self.count[ch - 1] = self.audf[ch - 1];", ""), ("joined pair: low reloads itself", "chip.rs", "if !low {", "if true {"), ("timer 4 IRQ bit", "chip.rs", "(if fired[3] { 0x04 } else { 0 })", "(if fired[3] { 0x08 } else { 0 })"), ("unmapped read", "chip.rs", "0xFF // B1.2", "0x00 // B1.2"), ("IRQST bit 3 latched", "chip.rs", "return !(self.latched | 0x08);", "return !self.latched;"), ("SKRES misses kb overrun", "chip.rs", "\n self.kb_overrun = 0;", ""), ("init mode feeds 1s into the long counter", "chip.rs", "let fb = if init {\n 0\n } else if self.audctl & 0x80", "let fb = if init {\n 1\n } else if self.audctl & 0x80"), ("base clock select bit", "chip.rs", "self.timers(if self.audctl & 0x01 != 0 { p15 } else { p64 });", "self.timers(if self.audctl & 0x02 != 0 { p15 } else { p64 });"), ("channel 3 fast-clock bit", "chip.rs", "if audctl & 0x20 == 0 {", "if audctl & 0x40 == 0 {"), ("poly4 tap", "chip.rs", "((r >> 5) ^ (r >> 6) ^ 1) & 1", "((r >> 5) ^ (r >> 7) ^ 1) & 1"), ("poly5 tap", "chip.rs", "((r >> 5) ^ (r >> 7) ^ 1) & 1", "((r >> 5) ^ (r >> 6) ^ 1) & 1"), ("IRQEN disable keeps latch", "chip.rs", "self.latched &= value; // B1.4", "// B1.4"), ("SKSTAT SID inverted", "chip.rs", "if self.sid != 0 { 0x10 } else { 0 }", "if self.sid != 0 { 0 } else { 0x10 }"), ("STIMER does not cancel pending", "chip.rs", "self.pend[ch] = 0;", ""), ("init clock reset shifts 0 into 64 kHz", "chip.rs", "self.c64 = ((self.c64 << 1) & 0x1F) | 1;", "self.c64 = (self.c64 << 1) & 0x1F;"), ("square does not toggle", "chip.rs", "self.ff[ch] ^= 1; // B3.5", "self.ff[ch] = 1; // B3.5"), ("high-pass off holds 0", "chip.rs", " self.hp[0] = 1;\n", " self.hp[0] = 0;\n"), ("STIMER sets flip-flops to 0", "chip.rs", "self.ff = [1, 1, 1, 1];", "self.ff = [0, 0, 0, 0];"), ("volume-only ignored on channel 3", "chip.rs", "let o3 = if c & 0x10 != 0 { 1 } else { ff[2] };", "let o3 = ff[2];"), ("noise inverted in init", "chip.rs", "((p17 >> (Self::TAP17 - ch)) & 1) as u8", "(!(p17 >> (Self::TAP17 - ch)) & 1) as u8"), # rung 3: the 5-bit gate (B3.2) and the STIMER hold (B3.7) ("gate not loaded at a fire", "chip.rs", "self.gate5[ch] = self.gate(ch); // B3.2: and", "// B3.2: and"), ("gate not held open while ungated", "chip.rs", "self.gate5[ch] = 1; // B3.2: held open", "// B3.2: held open"), ("gate one stage off", "chip.rs", "((self.poly5 >> (Self::TAP5 - ch)) & 1) as u8", "((self.poly5 >> (Self::TAP5 - ch + 1)) & 1) as u8"), ("gate load misses this cycle's write", "chip.rs", CONTROL, "let control = if false {"), ("gate shut in init mode", "chip.rs", "if !init && passed[ch] == 0 {", "if passed[ch] == 0 {"), ("STIMER holds the flip-flops one tick", "chip.rs", "self.stimer_set = 2;", "self.stimer_set = 1;"), ("STIMER does not load the gates", "chip.rs", "self.gate5[ch] = self.gate(ch);\n", "\n"), ("4-bit noise one stage off", "chip.rs", "(p4 >> (Self::TAP4 - ch))", "(p4 >> (Self::TAP4 - ch + 1))"), ("high-pass copies the new flip-flop", "chip.rs", "self.hp[0] = if Self::HP_OLD { old0 } else { self.ff[0] };", "self.hp[0] = self.ff[0];"), # rung 4: interrupts (B4.x) and the clocks' init lag (B2.1b) ("clocks see init mode at once", "chip.rs", "let clocks_init = self.clocks_init;", "let clocks_init = init;"), ("timer latched though disabled", "chip.rs", "self.latched |= irq & self.irqen;", "self.latched |= irq;"), ("IRQ line not settled each tick", "chip.rs", "self.update_irq(); // B4.2", "// B4.2"), ("timer 2 IRQ bit", "chip.rs", "(if fired[1] { 0x02 } else { 0 })", "(if fired[1] { 0x01 } else { 0 })"), ("bit-3 pin ignores IRQEN", "chip.rs", "let level = self.latched != 0 || self.irqen & 0x08 != 0;", "let level = self.latched != 0;"), ("IRQEN write leaves the enable", "chip.rs", "self.irqen = value; // B4.1", "// B4.1"), # rung 5: the pot scan (B5.x) ("pot scan ends at 227", "chip.rs", "ending = self.pot_count == 228;", "ending = self.pot_count == 227;"), ("live pot read not transitional", "chip.rs", "return value\n & (if step == 2 {", "return value | 0 & (if step == 2 {"), ("POTGO does not clear the counter", "chip.rs", "self.pot_count = 0;\n self.pot_scan = true;", "self.pot_scan = true;"), ("slow scan never steps", "chip.rs", "self.pot_step = if p15 { 1 } else { 0 };", "self.pot_step = 0;"), ("ALLPOT not forced at the end", "chip.rs", "allpot = 0; // B5.4", "// B5.4"), ("dump ignores fast scan", "chip.rs", "let dump = self.skctl & 0x04 == 0 && !self.pot_scan;", "let dump = !self.pot_scan;"), ("live pot does not follow the counter", "chip.rs", "self.pot[n] = count as u8;", ""), # rung 6: the keyboard scan (B6.x) ("keyboard counter steps down", "chip.rs", "let code = (self.scan_code + 1) & 0x3F;", "let code = self.scan_code.wrapping_sub(1) & 0x3F;"), ("debounce ignored", "chip.rs", "let matched = code == self.kb_compare || self.skctl & 0x01 == 0;", "let matched = true;"), ("no keyboard overrun", "chip.rs", "self.kb_overrun = 1; // B6.5", "// B6.5"), ("Break repeats while held", "chip.rs", "if kr2 != 0 && self.break_prev == 0 && self.irqen & 0x80 != 0 {", "if kr2 != 0 && self.irqen & 0x80 != 0 {"), ("KBCODE without Shift", "chip.rs", "self.kbcode = code | self.shift_latch << 6 | self.ctrl_latch << 7;", "self.kbcode = code | self.ctrl_latch << 7;"), ("scan not reset when disabled", "chip.rs", "self.kb_state = 0; // B6.2", "// B6.2"), ("release never debounced", "chip.rs", "self.key_held = 0;\n self.kb_state = 0;", "self.kb_state = 0;"), ("Shift read at the wrong code", "chip.rs", "pub const SHIFT_CODE: u8 = 0x10;", "pub const SHIFT_CODE: u8 = 0x11;"), # rung 7: the serial port's audio-affecting parts (B7.x) ("two-tone resync a tick early", "chip.rs", "self.resync_q |= 0b10;", "self.resync_q |= 0b1;"), ("async receive does not hold", "chip.rs", "let held = skctl & 0x10;", "let held = 0;"), ("force break ignored by two-tone", "chip.rs", "let bit = self.sod_bit != 0 && skctl & 0x80 == 0;", "let bit = self.sod_bit != 0;"), ("timer 2 does not resync", "chip.rs", "if (fired[0] && bit) || fired[1] {", "if fired[0] && bit {"), ("output clock from channel 3", "chip.rs", "if (fired[3] && (2..=5).contains(&mode))", "if (fired[2] && (2..=5).contains(&mode))"), # -- our own: what is Rust-specific -- ("seed: one word only for seeds of 2**32 and over", "pyrandom.rs", "if seed >> 32 != 0 {", "if false {"), ("getrandbits takes the low bits", "pyrandom.rs", "self.genrand_u32() >> (32 - bits)", "self.genrand_u32() & ((1u64 << bits) - 1) as u32"), ("seeded power-on draws poly5 before poly4", "chip.rs", "self.poly4 = value(9);\n self.poly5 = value(10);", "self.poly5 = value(10);\n self.poly4 = value(9);"), ("restore drops the borrow pipeline", "chip.rs", "$(self.$sname = state.$sname.clone();)*\n", "$(self.$sname = state.$sname.clone();)*\n self.pend = [0; 4];\n"), ("read consults pot_level outside a scan", "chip.rs", "if step != 0 && (self.pot_scan || step == 2) && {", "if (step != 0 && (self.pot_scan || step == 2)) & {"), ("take_outputs does not empty the record", "chip.rs", "std::mem::take(&mut self.outputs)", "self.outputs.clone()"), ("on_dump handed the next tick's clock", "chip.rs", "let look = self.look();\n if let Some(on_dump)", "let look = Look { clock: self.clock + 1, dump_active: self.dump_active };\n if let Some(on_dump)"), ("mix() truncates instead of rounding", "chip.rs", "(total * 4.0 + 0.5) as usize", "(total * 4.0) as usize"), ("fitted DAC through f32", "variants.rs", ".map(|v| (v & 3) as f64 + HIGH_BIT_RATIO * (v & 12) as f64)", ".map(|v| (v & 3) as f64 + (HIGH_BIT_RATIO * (v & 12) as f64) as f32 as f64)"), ("linear curve off by one step", "variants.rs", "let top = 4.0 * dac[15];", "let top = 4.0 * dac[15] + 0.25;"), ("RC helper without the overcharge limit", "rc.rs", "let b = OVERCHARGE * target as f64;", "let b = f64::MAX;"), ("write ignores the A3-A0 mask", "chip.rs", "self.w_reg = (register & 0x0F) as i32;", "self.w_reg = register as i32;"), ("read ignores the A3-A0 mask", "chip.rs", "let register = register & 0x0F;\n if register < 8 {", "if register < 8 {"), ("SID idles low", "chip.rs", "chip.sid = 1;", "chip.sid = 0;"), ] # fmt: skip def slug(name: str) -> str: out = "".join(c if c.isalnum() else "-" for c in name.lower()).strip("-") while "--" in out: out = out.replace("--", "-") return out def run(cmd: list[str], cwd: Path, env: dict | None = None, timeout: int = 3600) -> subprocess.CompletedProcess: return subprocess.run( ["nice", "-n", "19", *cmd], cwd=cwd, env=dict(os.environ, **(env or {})), capture_output=True, text=True, timeout=timeout, ) # fmt: skip def judge(fault: tuple | None, targets: queue.Queue) -> tuple[str, list[str], str]: name = fault[0] if fault else "unbroken" copy = ROOT / "external" / "faults" / slug(name) copy.mkdir(parents=True, exist_ok=True) for item in ("Cargo.toml", "Cargo.lock", "src", "tests", "examples"): source = ROOT / item if source.is_dir(): shutil.copytree(source, copy / item, dirs_exist_ok=True) else: shutil.copy2(source, copy / item) if fault: _, file, old, new = fault text = (ROOT / "src" / file).read_text() count = text.count(old) if count != 1: return name, [], f"STALE: fault text found {count} times in {file}" (copy / "src" / file).write_text(text.replace(old, new)) target = targets.get() try: for path in copy.rglob("*"): if path.is_file() and not path.parts[len(copy.parts)].startswith("traces"): os.utime(path) env = {"CARGO_TARGET_DIR": str(target), "CARGO_NET_OFFLINE": "true", "JOBS": "1"} build = run(["cargo", "build", "--release", "-q", "--tests", "--examples"], copy, env) if build.returncode: return name, [], "does not build: " + (build.stderr.strip().splitlines() or ["?"])[-1] caught = [] rung1 = run([str(ROOT / "scripts" / "rung1.sh")], ROOT, dict(env, CRATE=str(copy))) if rung1.returncode == 2: return name, caught, "rung 1 could not run: " + rung1.stderr.strip() if rung1.returncode: caught.append("1") trace_bin = str(target / "release" / "examples" / "pokey-trace") rung2 = run([str(ROOT / "scripts" / "rung2.sh")], ROOT, dict(env, BIN=trace_bin, REUSE="1", OURS=str(copy / "traces2"))) # fmt: skip if rung2.returncode == 2: return name, caught, "rung 2 could not run: " + rung2.stderr.strip() if rung2.returncode: caught.append("2") rung3 = run([str(ROOT / "scripts" / "rung3.sh")], ROOT, dict(env, BIN=trace_bin, REUSE="1", OURS=str(copy / "traces3"), CRATE=str(copy))) # fmt: skip if rung3.returncode == 2: return name, caught, "rung 3 could not run: " + rung3.stderr.strip() if rung3.returncode: caught.append("3") detail = next((ln for ln in rung2.stdout.splitlines() if " traces identical" in ln), "") return name, caught, "lockstep " + detail.removeprefix("rung 2: ").split(" (")[0] finally: targets.put(target) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--jobs", type=int, default=3) parser.add_argument("names", nargs="*", help="only faults whose name contains one of these") args = parser.parse_args() faults = [f for f in FAULTS if not args.names or any(n in f[0] for n in args.names)] targets: queue.Queue = queue.Queue() for i in range(args.jobs): targets.put(ROOT / "external" / "faults-target" / str(i)) name, caught, detail = judge(None, targets) if caught or not detail.startswith("lockstep"): print(f"the unbroken copy fails rungs {'+'.join(caught)} ({detail})") return 1 print(f"unbroken copy: every rung passes ({detail})\n", flush=True) missed = [] per_rung = dict.fromkeys("123", 0) ours_from = next(i for i, f in enumerate(FAULTS) if f[1] == "pyrandom.rs") with ThreadPoolExecutor(args.jobs) as pool: futures = [pool.submit(judge, fault, targets) for fault in faults] for index, future in enumerate(futures, start=1): name, caught, detail = future.result() for rung in caught: per_rung[rung] += 1 rungs = "+".join(caught) if caught else "-" print(f"{index:2d}. {'caught' if caught else 'MISSED'} rungs {rungs:6} {name} ({detail})", flush=True) if not caught: missed.append(name) print() for rung, count in per_rung.items(): print(f"rung {rung}: catches {count} of {len(faults)}") if not args.names: print(f"the reference's faults: {ours_from}; ours (Rust-specific): {len(FAULTS) - ours_from}") print(f"{len(faults) - len(missed)} of {len(faults)} caught") if missed: print("missed: " + "; ".join(missed)) return 1 if missed else 0 if __name__ == "__main__": sys.exit(main())