#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Seeded one-line faults: prove that each rule's judge can fail (the charter's proof obligations; the family methodology, "A gate that cannot fail proves nothing"). Each fault changes one line of the board in a fresh copy of src/ (fresh timestamps, the methodology's 2026-11-13 lesson), then runs the judge named for that rule against the copy. The fault is caught when the judge's result falls below its result on the unchanged source: - ``suite N``: the mGBA suite's sub-suite N (scripts/board_suite.py): fewer passes; - ``hw PATH``: a hw-test text ROM (scripts/board_screens.py): a line that passed now fails; - ``lib PATH``: a jsmolka or alyosha-tas ROM (scripts/judge_text.py): no longer "pass"; - ``hwpic NAME``: a hw-test picture (scripts/hw_pictures.py): no longer matches; - ``pic PATH``: a picture against NanoBoyAdvance's (scripts/board_pictures.py; a closed-box detector): more dots off by more than one step than on the unchanged board. Scenes (tests/referee_runs/scenes, scripts/build_scenes.py) always run with the free BIOS; - ``status``: hw-test ppu/status-irq-dma's twelve lines (scripts/hw_menus.py): fewer pass; - ``pram``: hw-test ppu/ram-access-timing's PRAM stall patterns against its comments (scripts/hw_menus.py): fewer agree; - ``lyc``: destoer lyc_midline's judged numbers against its photograph (scripts/hw_menus.py), always with Nintendo's BIOS from ``$NO_INTRO_DIR`` (the photograph's console ran it); - ``libfree PATH``: as ``lib``, always with the free BIOS (alyosha-tas ppu/Sprite_Last_VRAM_Access_Free passes only with it: docs/validation.md "Rung 4"); - ``lockstep PATH``: rung 4's lockstep of the dot model against rung 3's line renderer (scripts/lockstep_pictures.py): more mismatched quiet lines than on the unchanged board (none). Since rung 4 the board draws with gba_python.ppu.dots, so a fault in a rule that only ppu/line.py holds shows only here; the same rule's copy in ppu/dots.py gets its own fault and the rule's picture judge (``RUNG3_MIRRORS``); - ``aging NAME``: one of Nintendo's aging cartridges, by its No-Intro file name in ``$NO_INTRO_DIR`` (scripts/board_aging.py, three power cycles): fewer PASS lines; - ``pytest TEST``: a unit test, only where no passing hardware judge exercises the rule (a blind spot, recorded as such in docs/validation.md). A fault no judge catches is an equivalent mutant (noted, not counted) or a blind spot (recorded in docs/validation.md). python scripts/seeded_faults.py --bios "$NO_INTRO_DIR/.../(World).zip" --jobs 12 python scripts/seeded_faults.py --only timer-start-tick --keep """ from __future__ import annotations import argparse import json import os import shutil import subprocess import sys import tempfile from concurrent.futures import ThreadPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] SCRIPTS = ROOT / "scripts" HW = "reference/src/hw-test" JS = "reference/src/gba-tests" AL = "reference/src/gba-tests-alyosha" SC = "tests/referee_runs/scenes" # scripts/build_scenes.py AGS10 = "AGS Aging Cartridge (World) (v10.0) (Test Program).zip" # in $NO_INTRO_DIR def scratch_root() -> Path: """Fault copies live in the repository's ignored tests/referee_runs/, not the system's temporary directory (house rules).""" root = ROOT / "tests" / "referee_runs" / "faults" root.mkdir(parents=True, exist_ok=True) return root # (name, file under src/gba_python, line text to find, replacement, judge, nth occurrence). # Several lines recur in the bus's CPU and DMA paths: the nth occurrence picks the CPU's # read path (the first) where noted by nth = 1 on a repeated line. FAULTS = [ ( "ewram-mirror", "bus.py", "return self.read_mem(self.ewram, address & 0x3FFFF, width)", "return self.read_mem(self.ewram, address & 0x3FFFF if address < 0x02040000 else 0, width)", "suite 0", 1, ), ( "palette-byte-write", "bus.py", "self.write_mem(self.palette, address & 0x3FF, 16, (value & 0xFF) * 0x101)", "self.write_mem(self.palette, address & 0x3FF, 8, value & 0xFF)", f"lib {JS}-alyosha/memory/PAL_8_bit_writes.gba", 1, ), ( "oam-byte-write-ignored", "bus.py", "if width != 8: # 8-bit writes to OAM", "if True: # 8-bit writes to OAM", f"lib {JS}/memory/memory.gba", 1, ), ( "vram-bitmap-hole", "bus.py", " return -1", " return offset - 0x8000", f"hw {HW}/ppu/vram-mirror/vram-mirror.gba", 1, ), ( "sram-wide-read", "bus.py", "return byte * 0x0101\n", "return byte\n", f"lib {JS}/save/sram.gba", 1, ), ( "bios-protection", "bus.py", " value = self.bios_latch", " value = 0", f"lib {JS}/bios/bios.gba", 1, ), ( "io-open-bus-rule", "bus.py", "if io.read16((offset & 0x3FE) ^ 2) is not None:", "if False:", "suite 1", 1, ), ( "open-bus-16-bit-bus", "bus.py", "self.open_bus = half | half << 16", "self.open_bus = half", f"hw {HW}/dma/latch/latch.gba", 1, ), ("bg0cnt-read-mask", "ppu/timing.py", "0x08: 0xDFFF,", "0x08: 0xFFFF,", "suite 1", 1), ("nr50-vin-bits", "sound.py", "value &= 0x77", "value &= 0xFF", "suite 1", 1), ( "no-backup-reads-ff", "cartridge/backup.py", " return 0xFF", " return 0", f"lib {JS}/save/none.gba", 1, ), ( "flash-bank-switch", "cartridge/backup.py", "self.bank = value & 1", "self.bank = 0", f"lib {JS}/save/flash128.gba", 1, ), # Rung 2: the save chips and the clock (scripts/board_saves.py cases). ( "eeprom-fresh-request", "cartridge/backup.py", " if fresh:", " if False:", "saves lib-eeprom-p0", 1, ), ( "eeprom-ready-bit", "cartridge/backup.py", "return 1 if now >= self.busy_until else 0", "return 0", "saves lib-eeprom-p0", 1, ), ( "eeprom-four-ignored-bits", "cartridge/backup.py", "stream = [0, 0, 0, 0]", "stream = [0, 0, 0]", "saves lib-eeprom-p2", 1, ), ( "eeprom-512-address-bits", "cartridge/backup.py", "0x3FF if self.size == 0x2000 else 0x3F)", "0x3FF if self.size == 0x2000 else 0x1F)", "saves lib-eeprom-p2", 1, ), ( "flash-id-mode", "cartridge/backup.py", "if self.id_mode and offset < 2:", "if False:", "saves lib-flash-panasonic-p0", 1, ), ( "flash-sector-erase", "cartridge/backup.py", "start = (self.bank << 16) | (offset & 0xF000)", "start = (self.bank << 16) | (offset & 0xE000)", "saves lib-flash-panasonic-p0p5", 1, ), ( "flash-program-clears-bits", "cartridge/backup.py", "self.memory[address] &= value", "self.memory[address] |= value", "saves lib-flash-sanyo-p0", 1, ), ( "rtc-detected", "cartridge/detect.py", 'return find_aligned(rom, b"SIIRTC_V")', "return False", "saves emerald-rtc", 1, ), ( "rtc-command-bit-order", "cartridge/rtc.py", "self.shift = (self.shift << 1) | sio", "self.shift |= sio << self.bit_count", "saves emerald-rtc", 1, ), ( "rtc-data-lsb-first", "cartridge/rtc.py", "self.sio_out = (self.out_bytes[0] >> self.out_bit) & 1", "self.sio_out = (self.out_bytes[0] >> (7 - self.out_bit)) & 1", "saves emerald-rtc", 1, ), ( "rtc-bcd", "cartridge/rtc.py", "return ((value // 10) << 4) | (value % 10)", "return value", "saves emerald-rtc", 1, ), ( "gpio-sio-input", "cartridge/rtc.py", "value |= self.rtc.sio_out << 1", "value |= 0", "saves emerald-rtc", 1, ), ( "rtc-control-read", "cartridge/rtc.py", "self.out_bytes = [self.control]", "self.out_bytes = [0]", "saves emerald-rtc", 1, ), ( "rtc-pm-flag-24h", "cartridge/rtc.py", "value = bcd(hour) | (0x80 if hour >= 12 else 0)", "value = bcd(hour)", # A blind spot: Emerald accepts the clock without the PM flag (missed, 2026-11-21). "pytest tests/test_saves.py::test_rtc_reads_date_and_time_in_bcd", 1, ), ("keyinput", "keypad.py", "return 0x3FF & ~self.pressed", "return 0x3FF", "suite 9", 1), ( "ewram-waits", "bus.py", "ewram_waits = 15 - control", "ewram_waits = 14 - control", "suite 2", 1, ), ( "rom-32-bit-second-half-s", "bus.py", "sequential = seq or half == 1", "sequential = seq", "suite 2", 1, ), ( "write-lands-first-cycle", "bus.py", "self.write_region(region, address, width, value, start)", "self.write_region(region, address, width, value, self.now)", f"hw {HW}/timer/start-stop/start-stop.gba", 1, ), ( "events-before-access", "scheduler.py", "while heap and heap[0][0] <= bus.now:", "while heap and heap[0][0] < bus.now:", f"hw {HW}/timer/reload/reload.gba", 1, ), ( "cart-counter-s-uses-counter", "bus.py", " if not sequential:", " if True:", f"hw {HW}/dma/burst-into-tears/burst-into-tears.gba", 1, ), ( "cart-128k-wrap", "bus.py", "self.cart_wrapped = ((index + half) & 0xFFFF) == 0xFFFF", "self.cart_wrapped = False", f"hw {HW}/bus/128kb-boundary/128kb-boundary.gba", 1, ), ( "cpu-128k-block-start", "bus.py", "return self.cart_access(address, width, seq and (address & 0x1FFFF) != 0)", "return self.cart_access(address, width, seq)", f"hw {HW}/bus/128kb-boundary/128kb-boundary.gba", 1, ), ( "dma-first-cart-access-n", "bus.py", "value = self.cart_access(address, width, not self.dma_cart_fresh)", "value = self.cart_access(address, width, True)", f"hw {HW}/bus/128kb-boundary/128kb-boundary.gba", 1, ), ( "cpu-n-after-dma", "dma.py", "bus.cpu_seq_broken = True", "bus.cpu_seq_broken = False", f"hw {HW}/dma/force-nseq-access/force-nseq-access.gba", 1, ), ( "dma-runs-before-cpu-access", "dma.py", "if candidate.pending and candidate.due <= bus.now:", "if candidate.pending and candidate.due < bus.now:", f"hw {HW}/dma/start-delay/start-delay.gba", 1, ), ( "dma-start-delay", "dma.py", "START_DELAY = 3", "START_DELAY = 2", f"hw {HW}/dma/start-delay/start-delay.gba", 1, ), ("dma-internal-cycles", "dma.py", "END_IDLE = 1", "END_IDLE = 0", "suite 2", 1), ( "dma-latch-16-bit", "dma.py", "channel.latch = value | value << 16", "channel.latch = value", f"hw {HW}/dma/latch/latch.gba", 1, ), ( "dma-skips-bios-reads", "dma.py", "if source >= 0x02000000 and source < 0x10000000:", "if source < 0x10000000:", f"hw {HW}/dma/latch/latch.gba", 1, ), ( "dma-copies-cpu-open-bus", "dma.py", "bus.open_bus = piece | piece << 16", "pass", f"lib {JS}-alyosha/Bus/DMA_CPU_Bus_Interaction.gba", 1, ), ( "cpu-overlaps-dma-internal", "bus.py", " if self.stall_credit > 0:", " if False:", "pytest tests/test_devices.py::test_cpu_internal_cycles_overlap_dma", 1, ), ( "timer-start-tick", "timers.py", "START_TICK = 2", "START_TICK = 1", f"hw {HW}/timer/start-stop/start-stop.gba", 1, ), ( "timer-stop-keeps-tick", "timers.py", "end = time + 1 if stopping else time", "end = time", f"hw {HW}/timer/start-stop/start-stop.gba", 1, ), ( "timer-reload-lead", "timers.py", "RELOAD_LEAD = 0", "RELOAD_LEAD = 1", f"hw {HW}/timer/reload/reload.gba", 1, ), ( "timer-tick-before-reload", "timers.py", "and tick_at_or_after(time, timer.period) == time", "and False", f"hw {HW}/timer/tick-before-reload/tick-before-reload.gba", 1, ), ( "timer-overflow-seen-next-cycle", "timers.py", "when + 1, ORDER_TIMER, lambda t, timer=timer: self.overflow(timer, t - 1)", "when, ORDER_TIMER, lambda t, timer=timer: self.overflow(timer, t)", "suite 4", 1, ), ( "timer-count-up", "timers.py", " timer.counter += 1", " timer.counter += 2", f"hw {HW}/timer/tick-before-reload/tick-before-reload.gba", 1, ), ("irq-lag", "timers.py", "IRQ_LAG = 2", "IRQ_LAG = 1", "suite 4", 1), ("irq-if-delay", "irq.py", "IF_DELAY = 3", "IF_DELAY = 2", "suite 4", 1), ("irq-ie-delay", "irq.py", "IE_DELAY = 4", "IE_DELAY = 2", f"lib {JS}-alyosha/irq/IE.gba", 1), ( "irq-ime-delay", "irq.py", "IME_DELAY = 4", "IME_DELAY = 6", f"hw {HW}/irq/irq-delay/irq-delay.gba", 1, ), ("irq-if-acknowledge", "irq.py", "self.if_ &= ~(value & mask)", "self.if_ &= ~0", "suite 4", 1), ( "haltcnt-bios-only", "irq.py", "if mask & 0xFF00 and self.board.bus.fetch_in_bios:", "if mask & 0xFF00:", f"hw {HW}/haltcnt/haltcnt.gba", 1, ), ("halt-wake", "irq.py", "HALT_WAKE = 3", "HALT_WAKE = 2", f"hw {HW}/haltcnt/haltcnt.gba", 1), ( "postflg-set-only", "irq.py", "self.postflg |= value & 1", "self.postflg = value & 1", f"hw {HW}/haltcnt/haltcnt.gba", 1, ), ( "prefetch-after-write", "bus.py", "raw_seq = (access & SEQ or self.after_write) and not self.cpu_seq_broken", "raw_seq = access & SEQ and not self.cpu_seq_broken", "suite 2", 1, ), ( "prefetch-word-hit", "prefetch.py", "bus.now = max(start + 1, ready)", "bus.now = max(start + 2, ready)", "suite 2", 1, ), ( "prefetch-flush-on-data", "prefetch.py", "FLUSH_ON_DATA = 1", "FLUSH_ON_DATA = 0", "suite 2", 1, ), ("prefetch-finish-last", "prefetch.py", "\nFINISH_LAST = 1", "\nFINISH_LAST = 0", "suite 2", 1), ( "prefetch-miss-finish-last", "prefetch.py", "MISS_FINISH_LAST = 1", "MISS_FINISH_LAST = 0", f"lib {JS}-alyosha/prefetcher/prefetcher_branch_thumb.gba", 1, ), ( "prefetch-miss-restarts-s", "prefetch.py", 'self.next_n = False # "the prefetcher starts', 'self.next_n = True # "the prefetcher', "suite 2", 1, ), ( "prefetch-capacity", "prefetch.py", "if self.count >= CAPACITY:", "if self.count >= 4:", f"lib {JS}-alyosha/prefetcher/prefetcher_full_thumb.gba", 1, ), ( "prefetch-runs-across-128k", "prefetch.py", "BOUNDARY_STOP = 0", "BOUNDARY_STOP = 1", f"lib {AL}/prefetcher/prefetcher_boundary_1.gba", 1, ), # Rung 3: the picture, a line at a time (ppu/line.py, ppu/timing.py). ("text-hflip", "ppu/line.py", "j = 7 - i if hflip else i", "j = i", f"pic {SC}/text.gba", 1), ( "text-8bpp-hflip", "ppu/line.py", "index = row[7 - i] if hflip else row[i]", "index = row[i]", f"pic {SC}/text.gba", 1, ), ( "text-palette-bank", "ppu/line.py", "bank = (entry >> 12) << 5", "bank = 0", f"pic {SC}/text.gba", 1, ), ( "text-wide-map", "ppu/line.py", "block_row = (ty >> 5) * (2 if wide else 1)", "block_row = ty >> 5", f"pic {SC}/text.gba", 1, ), ( "text-tall-map", "ppu/line.py", "sy = (y + vofs) & (0x1FF if tall else 0xFF)", "sy = (y + vofs) & 0xFF", f"pic {SC}/text.gba", 1, ), ( "bg-priority-order", "ppu/line.py", " layers.sort()", " layers.reverse()", f"pic {SC}/text.gba", 1, ), ( "text-char-overflow", "ppu/line.py", "row = bytes((entry & 0xFF, entry >> 8)) * 4", "row = bytes(8)", f"pic {SC}/textoverflow.gba", 1, ), ( "affine-overflow-wrap", "ppu/line.py", " if wrap:", " if True:", f"pic {SC}/affine2.gba", 1, ), ( "affine-dy-per-dot", "ppu/line.py", "ty = (ref_y + pc * x) >> 8", "ty = ref_y >> 8", f"pic {SC}/affine1.gba", 1, ), ( "affine-reload-vblank", "ppu/timing.py", " self.reload_references()", " pass", f"pic {SC}/affine1.gba", 1, ), ( "affine-advance-pd", "ppu/timing.py", "ref[1] += signed16(regs[0x13])", "ref[1] += 0x100", "hwpic bgpd", 1, ), ( "affine-advance-before-draw", "ppu/timing.py", " if y:\n self.advance_references()", " if False:\n self.advance_references()", "hwpic bgpd", 1, ), ( "affine-write-copies", "ppu/timing.py", " self.ref[((low - 0x14) >> 3 << 1) | ((low >> 1) & 1)] = reference_point(", " _ = (", "hwpic bgx", 1, ), ( "display-enable-delay", "ppu/timing.py", "if since[i] == 3:", "if since[i] >= 1:", "hwpic dispcnt-latch", 1, ), ( "forced-blank-delay", "ppu/timing.py", " if self.blank_lines < 3:\n display", " if self.blank_lines < 1:\n display", "hwpic dispcnt-latch", 1, ), ("forced-blank-white", "ppu/line.py", "out[x] = WHITE", "out[x] = 0", "hwpic dispcnt-latch", 1), ( "frame-handover", "ppu/timing.py", "self.frame, self.shown = self.shown, self.frame", "pass", "hwpic bgx", 1, ), ( "bitmap-frame-select", "ppu/line.py", "page = 0xA000 if dispcnt & 0x10 and mode != 3 else 0", "page = 0", f"pic {SC}/bitmap4.gba", 1, ), ( "bitmap-mode5-size", "ppu/line.py", "width, height = (160, 128) if mode == 5 else (240, 160)", "width, height = (240, 160)", f"pic {SC}/bitmap5.gba", 1, ), ( "bitmap-obj-tiles", "ppu/line.py", "lowest = 0x14000 if mode >= 3 else 0x10000", "lowest = 0x10000", f"pic {SC}/bitmap3.gba", 1, ), ( "obj-1d-row-step", "ppu/line.py", "row_step = (width >> 3) if one_d else 32", "row_step = 32", f"pic {SC}/objs1d.gba", 1, ), ( "obj-vflip", "ppu/line.py", "py = height - 1 - line if a1 & 0x2000 else line", "py = line", f"pic {SC}/objs1d.gba", 1, ), ( "obj-x-wrap", "ppu/line.py", " if obj_x >= 256:", " if obj_x >= 512:", f"pic {SC}/objs1d.gba", 1, ), ( "obj-equal-priority-over-bg", "ppu/line.py", "if obj >= 0 and obj_p <= p:", "if obj >= 0 and obj_p < p:", f"pic {SC}/objs1d.gba", 1, ), ( "obj-oam-order", "ppu/line.py", " if color[x] >= 0:\n", " if False:\n", f"pic {SC}/objs1d.gba", 1, ), ( "obj-affine-double", "ppu/line.py", "box_w = width * 2 if double else width", "box_w = width", f"pic {SC}/objaffine.gba", 1, ), ( "obj-affine-centre", "ppu/line.py", "start_x = pb * dy - pa * (box_w >> 1)", "start_x = pb * dy", f"pic {SC}/objaffine.gba", 1, ), ( "obj-y-wrap", "ppu/line.py", "line = (y - (a0 & 0xFF)) & 0xFF", "line = (y - (a0 & 0xFF)) & 0x1FF", f"pic {SC}/objaffine.gba", 1, ), ( "obj-budget-affine-cost", "ppu/line.py", "cost = 10 + 2 * box_w if affine else width", "cost = width", f"pic {SC}/objbudget.gba", 1, ), ( "obj-budget-total", "ppu/line.py", "OBJ_CYCLES = 1210", "OBJ_CYCLES = 2420", f"pic {SC}/objbudget.gba", 1, ), ( "obj-budget-hblank-free", "ppu/line.py", "budget = OBJ_CYCLES_HBLANK_FREE if dispcnt & 0x20 else OBJ_CYCLES", "budget = OBJ_CYCLES", f"pic {SC}/objbudgetfree.gba", 1, ), ( "obj-window-mask", "ppu/line.py", "window[x] = True # OBJ window dots", "pass # OBJ window dots", f"pic {SC}/windows.gba", 1, ), ( "window-0-over-1", "ppu/line.py", "for win in (1, 0):", "for win in (0, 1):", f"pic {SC}/windows.gba", 1, ), ( "window-x1-past-x2", "ppu/line.py", "if end > limit or first > end:", "if end > limit:", f"pic {SC}/wingarbage.gba", 1, ), ( "no-window-effects-on", "ppu/line.py", " window[x] = 0x3F\n", " window[x] = 0x1F\n", f"pic {SC}/blendalpha.gba", 1, ), ( "alpha-coefficient-clamp", "ppu/line.py", "eva = min(alpha & 0x1F, 16)", "eva = alpha & 0x1F", f"pic {SC}/blendalpha2.gba", 1, ), ( "brighten-formula", "ppu/line.py", "r += ((31 - r) * evy) >> 4", "r += (r * evy) >> 4", f"pic {SC}/blendbright.gba", 1, ), ( "darken-formula", "ppu/line.py", "r -= (r * evy) >> 4", "r -= ((31 - r) * evy) >> 4", f"pic {SC}/blenddark.gba", 1, ), ( "semi-obj-blends", "ppu/line.py", " top = blend(top, second, eva, evb)\n elif first_targets", " pass\n elif first_targets", f"pic {SC}/blendbright.gba", 1, ), ( "mosaic-horizontal", "ppu/line.py", "buffer[x] = buffer[x - x % size]", "buffer[x] = buffer[x]", f"pic {SC}/mosaic.gba", 1, ), ( "mosaic-vertical-text", "ppu/line.py", " y -= y % vsize", " y -= 0", f"pic {SC}/mosaic.gba", 1, ), ( "green-swap", "ppu/line.py", "out[x] = (a & ~0x3E0) | (b & 0x3E0)", "out[x] = a", f"pic {SC}/greenswap.gba", 1, ), # Rung 4 (docs/validation.md "Rung 4"). ( "vmatch-flag-delay", "ppu/timing.py", "VMATCH_FLAG = 1", "VMATCH_FLAG = 0", "status", 1, ), ( "vblank-irq-offset", "ppu/timing.py", "VBLANK_IRQ = 2", "VBLANK_IRQ = 3", "status", 1, ), ( "hblank-flag-rise", "ppu/timing.py", "HBLANK_START = 1007", "HBLANK_START = 1006", "status", 1, ), ( "hblank-dma-request", "ppu/timing.py", "HBLANK_DMA = 1008", "HBLANK_DMA = 1009", "status", 1, ), ( "vblank-dma-request", "ppu/timing.py", "VBLANK_DMA = 1", "VBLANK_DMA = 3", "status", 1, ), ( "capture-request", "ppu/timing.py", "CAPTURE_REQUEST = 4", "CAPTURE_REQUEST = 6", "status", 1, ), ( "capture-from-line-2", "ppu/timing.py", " if self.vcount == 2:\n", " if 2 <= self.vcount < 162:\n", "status", 1, ), ( "lyc-write-match", "ppu/timing.py", " self.set_vmatch(self.vcount == self.dispstat >> 8, time)", " pass", "lyc", 1, ), ( "reference-latch", "ppu/timing.py", "REFERENCE_LATCH = 2", "REFERENCE_LATCH = 0", "hwpic bgx", 1, ), ( "dot-fetch-start", "ppu/dots.py", "FETCH_START = 37", "FETCH_START = 33", "hwpic mode3", 1, ), ( "greenswap-delay", "ppu/dots.py", "GREENSWAP_DELAY = 34", "GREENSWAP_DELAY = 0", "hwpic greenswap", 1, ), ( "greenswap-log", "ppu/dots.py", "swap = log[k][1]", "swap = swap", "hwpic greenswap", 1, ), ( "obj-fetch-start", "ppu/dots.py", "OBJ_START = 16", "OBJ_START = 10", f"libfree {AL}/ppu/Sprite_Last_VRAM_Access_Free.gba", 1, ), ( "obj-partial-fetch", "ppu/dots.py", " cost = self.f_budget\n", ' return "end"\n', f"libfree {AL}/ppu/Sprite_Last_VRAM_Access_Free.gba", 1, ), ( "obj-vram-busy", "ppu/dots.py", "if kind == region and start <= time < end:", "if False:", f"libfree {AL}/ppu/Sprite_Last_VRAM_Access_Free.gba", 1, ), ( "video-wait-one-cycle", "bus.py", " if dots.busy(region, address, self.now):", " while dots.busy(region, address, self.now):", f"libfree {AL}/ppu/Sprite_Last_VRAM_Access_Free.gba", 1, ), ( "pram-top-read", "ppu/dots.py", "pram_top[x] = not (direct and top_layer == 2)", "pram_top[x] = False", "pram", 1, ), ( "pram-second-read", "ppu/dots.py", "pram_second[x] = blended and not (direct and second_layer == 2)", "pram_second[x] = False", "pram", 1, ), ( "pram-read-cycles", "ppu/dots.py", "return self.pram_top[x] if phase == 0 else self.pram_second[x]", "return self.pram_top[x] if phase == 2 else self.pram_second[x]", "pram", 1, ), ( "window-flag-set", "ppu/dots.py", "if vcount == value >> 8:", "if vcount >= value >> 8:", "hwpic window_midframe", 1, ), ( "window-flag-clear", "ppu/dots.py", "if vcount == value & 0xFF:", "if vcount > 200:", "hwpic window_midframe", 1, ), ( "bg-enable-at-dot", "ppu/dots.py", " enabled = latched & dispcnt\n mode = latched & 7\n layers", " enabled = latched\n mode = latched & 7\n layers", "hwpic dispcnt-latch", 1, ), ( "forced-blank-at-dot", "ppu/dots.py", " if (latched | dispcnt) & 0x80:\n # Forced blank", " if latched & 0x80:\n # Forced blank", "hwpic dispcnt-latch", 1, ), ( "obj-fetch-current-enable", "ppu/dots.py", "on = self.ppu.regs[0] & 0x1000", "on = 1", f"pic {AL}/ppu/Sprite_Disable_Midline.gba", 1, ), ( "obj-one-line-ahead", "ppu/timing.py", "dots.begin_obj_fetch((y + 1) % LINES, origin)", "dots.begin_obj_fetch(y, origin)", f"pic {SC}/objaffine.gba", 1, ), ( "catch-up-vram-write", "bus.py", " self.dots.note_write(time)", " pass", "hwpic mode3", 2, ), ( "catch-up-register-write", "ppu/timing.py", " self.dots.note_write(time)\n", " pass\n", f"pic {AL}/ppu/stripes_x_offset.gba", 1, ), ( "line-obj-partial", "ppu/line.py", "last = (budget - 10 + 1) // 2 if affine else budget", "last = 0", f"pic {SC}/objbudget.gba", 1, ), ( "bitmap-vram-wait", "ppu/dots.py", "return mode <= 5 and bool(enabled & 0x400) and phase == 0", "return False", "hwpic mode3", 1, ), ( "text-vram-wait", "ppu/dots.py", "TEXT_READS_4BPP = 3", "TEXT_READS_4BPP = 0", "lyc", 1, ), ( "affine-vram-wait", "ppu/dots.py", "if enabled & 0x400 and phase < 2:", "if False:", "hwpic bgpd", 1, ), ( "obj-oam-busy", "ppu/dots.py", "self.f_busy.append((start, start + 10, OAM))", "pass", f"libfree {AL}/ppu/Sprite_Last_VRAM_Access_Free.gba", 1, ), # Rung 5: sound. The FIFO timing ROMs that pass (fifo_2 to _5, fifo_dma_disable_3 and _5) judge # the FIFO path; the mixer's levels have no hardware judge here (no recording, no audio # detector), so their faults go to unit tests: blind spots (docs/validation.md "Rung 5"). # mix()'s sound-off branch is not seeded: with the FIFOs emptied and the PSG reset at # sound off, removing it changes nothing (an equivalent mutant). ( "fifo-timer-select", "sound.py", "if (self.soundcnt_h >> (10 + 4 * which)) & 1 != timer:", "if (self.soundcnt_h >> (10 + 4 * which)) & 1 == timer:", f"lib {AL}/fifo_dma/fifo_3.gba", 1, ), # The FIFO DMA timing rules of 2026-11-23 (docs/validation.md "The FIFO DMA timing study"), # each judged by the hardware-captured ROM that fixed it. ( "fifo-request-threshold", "sound.py", "if held < REQUEST_BELOW:", "if held <= REQUEST_BELOW:", f"lib {AL}/fifo_dma/fifo_4.gba", 1, ), ( "fifo-full-counts-as-empty", "sound.py", "held = len(fifo) % FIFO_BYTES", "held = len(fifo)", f"lib {AL}/fifo_dma/fifo_5.gba", 1, ), ( "fifo-request-delay", "dma.py", "self.make_pending(channel, time + FIFO_DELAY)", "self.make_pending(channel, time + FIFO_DELAY - 1)", f"lib {AL}/fifo_dma/fifo_2.gba", 1, ), ( "fifo-pop", "sound.py", "self.samples[which] = fifo.pop(0)", "self.samples[which] = fifo[0]", "pytest tests/test_sound.py::test_fifo_pops_and_asks_below_16_bytes", 1, ), ( "fifo-push-while-off", "sound.py", "if not self.master:", "if False:", "pytest tests/test_sound.py::test_fifo_writes_while_sound_off_load_nothing", 1, ), ( "fifo-clear-on-sound-off", "sound.py", "if self.master and not master:", "if False:", "pytest tests/test_sound.py::test_sound_off_empties_the_fifos", 1, ), ( "psg-level-scale", "sound.py", "return ((2 * digital - 15) * (master + 1) * 16 // 15) >> share", "return ((2 * digital - 15) * (master + 1) * 16 // 16) >> share", "pytest tests/test_sound.py::test_psg_level_spans_a_quarter", 1, ), ( "fifo-level-scale", "sound.py", "return signed * (4 if full else 2)", "return signed * (4 if full else 4)", "pytest tests/test_sound.py::test_fifo_level_spans_the_full_range", 1, ), ( "mix-clip", "sound.py", "right = min(max(right + bias, 0), 0x3FF)", "right = min(max(right + bias, 0), 0x7FF)", "pytest tests/test_sound.py::test_mix_adds_bias_and_clips", 1, ), ( "output-resolution-cut", "sound.py", "shift = 1 + resolution", "shift = resolution", "pytest tests/test_sound.py::test_timer_drives_the_fifo_into_the_output", 1, ), # Rung 6: the aging cartridges' rules (AGS v10.0, three power cycles). ( "capture-ends-at-162", "ppu/timing.py", " board.dma.end_capture()\n", " pass\n", f"aging {AGS10}", 1, ), ("dma-nested-idle", "dma.py", "NESTED_IDLE = 0", "NESTED_IDLE = 1", f"aging {AGS10}", 1), ( "keycnt-and-none-selected", "keypad.py", " return (self.pressed & selected) == selected", " return selected != 0 and (self.pressed & selected) == selected", f"aging {AGS10}", 1, ), ] # Rung 4: the board draws with ppu/dots.py; ppu/line.py is the specification it is locksteped # against. Rung 3's faults in rules only ppu/line.py holds are judged by the lockstep on the same # ROM; rules both renderers share (constants and helpers dots.py imports) keep their picture # judge. Each line.py-only rule's copy in dots.py gets a mirrored fault with rung 3's judge. RUNG3_SHARED = {"obj-budget-total", "window-x1-past-x2", "brighten-formula", "darken-formula"} HW_ROMS = { "bgx": f"{HW}/ppu/bgx/bgx.gba", "bgpd": f"{HW}/ppu/bgpd/bgpd.gba", "dispcnt-latch": f"{HW}/ppu/dispcnt-latch/dispcnt-latch.gba", } RUNG3_MIRRORS = { # rule: (dots.py line, its fault, nth) "text-hflip": (" i = 7 - i\n", " i = i\n", 1), "text-palette-bank": ("at = ((entry >> 12) << 5) + index * 2", "at = index * 2", 1), "text-char-overflow": ( "else bytes((entry & 0xFF, entry >> 8)) * 4", "else bytes(8)", 1, ), "affine-dy-per-dot": ("ty = (ref_y + pc * source) >> 8", "ty = ref_y >> 8", 1), "forced-blank-white": (" raw[x] = WHITE\n", " raw[x] = 0\n", 1), "bitmap-frame-select": ("page = 0xA000 if regs[0] & 0x10 and mode != 3 else 0", "page = 0", 1), "bitmap-obj-tiles": ("lowest = 0x14000 if self.f_bitmap else 0x10000", "lowest = 0x10000", 1), "obj-vflip": ("ty = height - 1 - line if a1 & 0x2000 else line", "ty = line", 1), "obj-x-wrap": (" if obj_x >= 256:\n", " if False:\n", 1), "obj-oam-order": (" if self.f_addr[x] >= 0:\n", " if False:\n", 1), "obj-affine-centre": ("pb * dy - pa * (box_w >> 1),", "pb * dy,", 1), "obj-window-mask": (" self.f_win[x] = True\n", " pass\n", 1), "semi-obj-blends": ( " top = blend(top, second, eva, evb)\n blended = True\n elif", " pass\n elif", 1, ), "mosaic-horizontal": ("source = x - x % msize if msize > 1 else x", "source = x", 1), "green-swap": ("out[x] = (a & ~0x3E0) | (b & 0x3E0)", "out[x] = a", 1), } def _rung4_split(faults: list) -> list: out = [] for fault in faults: name, file, old, new, judge, nth = fault if file != "ppu/line.py" or name in RUNG3_SHARED or judge.startswith("lockstep"): out.append(fault) continue kind, _, target = judge.partition(" ") rom = HW_ROMS.get(target, target) if kind == "hwpic" else target out.append((name, file, old, new, f"lockstep {rom}", nth)) if name in RUNG3_MIRRORS: dots_old, dots_new, dots_nth = RUNG3_MIRRORS[name] out.append((f"{name}-dots", "ppu/dots.py", dots_old, dots_new, judge, dots_nth)) elif old in (ROOT / "src" / "gba_python" / "ppu" / "dots.py").read_text(): out.append((f"{name}-dots", "ppu/dots.py", old, new, judge, 1)) return out FAULTS = _rung4_split(FAULTS) def run_judge(judge: str, bios: str, src: Path | None, scratch: Path) -> object: """The judge's result: a pass count, a set of passing lines, or a status.""" env = dict(os.environ, PYPY_GC_NURSERY="1M") if src is not None: env["GBA_PYTHON_SRC"] = str(src) env["PYTHONPATH"] = str(src) kind, _, target = judge.partition(" ") out = scratch / "result.json" python = sys.executable if kind == "suite": command = [python, str(SCRIPTS / "board_suite.py"), target, "--jobs", "1"] elif kind == "hw": command = [python, str(SCRIPTS / "board_screens.py"), str(ROOT / target), "--jobs", "1"] elif kind == "hwpic": command = [python, str(SCRIPTS / "hw_pictures.py"), target] elif kind == "pic": frames = "120" if "/scenes/" in target else "300" if "/scenes/" in target: bios = "free" # the scenes have no logo: only the free BIOS boots them command = [python, str(SCRIPTS / "board_pictures.py"), str(ROOT / target)] command += ["--frames", frames, "--jobs", "1", "--out", str(scratch / "pictures")] elif kind in ("status", "pram", "lyc"): command = [python, str(SCRIPTS / "hw_menus.py"), kind, "--jobs", "4"] if kind == "lyc": bios = str( Path(os.environ["NO_INTRO_DIR"]) / "Nintendo - Game Boy Advance" / "[BIOS] Nintendo Game Boy Advance Boot ROM (World).zip" ) elif kind == "lockstep": frames = "120" if "/scenes/" in target else "300" command = [python, str(SCRIPTS / "lockstep_pictures.py"), str(ROOT / target)] command += ["--frames", frames, "--jobs", "1"] bios = "free" elif kind == "aging": command = [python, str(SCRIPTS / "board_aging.py"), target, "--jobs", "1"] command += ["--out", str(scratch / "aging")] elif kind == "saves": command = [python, str(SCRIPTS / "board_saves.py"), target, "--jobs", "1"] elif kind == "pytest": # A model unit test: only for a rule no passing hardware judge exercises (a recorded # blind spot in docs/validation.md); it shows the model's rule, not the hardware's. done = subprocess.run( ["nice", python, "-m", "pytest", "-q", "-p", "no:cacheprovider", str(ROOT / target)], env=env, capture_output=True, timeout=600, check=False, cwd=scratch, ) return "pass" if done.returncode == 0 else "fail" else: command = [python, str(SCRIPTS / "judge_text.py"), "--emu", "board", str(ROOT / target)] if kind == "libfree": bios = "free" command += ["--bios", bios, "--json", str(out)] subprocess.run(["nice", *command], env=env, capture_output=True, timeout=7200, check=False) if not out.exists(): return None data = json.loads(out.read_text()) if kind in ("status", "lyc"): return data["passes"] if kind == "lockstep": return {"coarse": data[0]["mismatched"]} if kind == "pram": return sum(item["pass"] for item in data) if kind == "suite": return data[0]["passes"] or 0 if kind == "aging": return data[0]["passes"] if kind == "hw": return sorted(line for line in data[0]["screen"] if ": PASS" in line) if kind == "pic": coarse = data[0].get("coarse_dots") return None if coarse is None else {"coarse": coarse} return data[0]["status"] def caught(baseline, result) -> bool: if result is None: return True if isinstance(baseline, int): return result < baseline if isinstance(baseline, list): return not set(baseline) <= set(result) if isinstance(baseline, dict): return result["coarse"] > baseline["coarse"] # further from the detector return baseline == "pass" and result != "pass" def apply_fault(src: Path, fault) -> None: name, file, old, new, _, nth = fault path = src / "gba_python" / file text = path.read_text() count = text.count(old) if count < nth: raise SystemExit(f"{name}: '{old}' not found in {file}") index = -1 for _ in range(nth): index = text.index(old, index + 1) path.write_text(text[:index] + new + text[index + len(old) :]) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--bios", default="free") parser.add_argument("--jobs", type=int, default=4) parser.add_argument("--only", action="append", default=[], help="fault names") parser.add_argument("--json", type=Path) args = parser.parse_args() faults = [f for f in FAULTS if not args.only or f[0] in args.only] # Every fault's line must exist exactly where it is named, before anything runs. for fault in faults: with tempfile.TemporaryDirectory(dir=scratch_root()) as scratch: src = Path(scratch) / "src" shutil.copytree(ROOT / "src", src) apply_fault(src, fault) judges = sorted({f[4] for f in faults}) print(f"{len(faults)} faults, {len(judges)} judges; baselines first", flush=True) def baseline(judge: str): with tempfile.TemporaryDirectory(dir=scratch_root()) as scratch: return judge, run_judge(judge, args.bios, None, Path(scratch)) with ThreadPoolExecutor(max_workers=args.jobs) as pool: baselines = dict(pool.map(baseline, judges)) for judge, result in baselines.items(): shown = len(result) if isinstance(result, list) else result print(f"baseline {shown!s:>6} {judge}", flush=True) def trial(fault): with tempfile.TemporaryDirectory(dir=scratch_root()) as scratch: src = Path(scratch) / "src" shutil.copytree(ROOT / "src", src, copy_function=shutil.copy) # fresh timestamps apply_fault(src, fault) result = run_judge(fault[4], args.bios, src, Path(scratch)) hit = caught(baselines[fault[4]], result) shown = len(result) if isinstance(result, list) else result print( f"{'caught' if hit else 'MISSED':7} {fault[0]:32} {shown!s:>6} {fault[4]}", flush=True ) return {"fault": fault[0], "judge": fault[4], "caught": hit, "result": shown} with ThreadPoolExecutor(max_workers=args.jobs) as pool: results = list(pool.map(trial, faults)) n = sum(r["caught"] for r in results) print(f"{n}/{len(results)} faults caught") if args.json: args.json.write_text( json.dumps( { "baselines": { k: (len(v) if isinstance(v, list) else v) for k, v in baselines.items() }, "results": results, }, indent=1, ) + "\n" ) return 0 if n == len(results) else 1 if __name__ == "__main__": sys.exit(main())