"""Run a conformance manifest on the reference and the fast core in lockstep. z80-rust had to prove equivalence through JSON traces piped into the reference's ``diff``. Both cores here are Python, so they run side by side in one process instead, and at every instruction boundary this compares: * the T-states ``step()`` returned, * every ``CPUState`` field (all 28, via ``capture_state()``), * every bus access the step made: kind, address, value, in order. Memory needs no separate comparison: both sides start from the same image and every write is a compared bus access. The reference side is the pinned ``z80_python`` install and its own ``ConformanceHost`` and manifest loader, untouched. The fast side is built only through the public API (``Z80CPU(read_byte, write_byte, *, read_port, write_port)``, ``restore_state``, the lifecycle requests, and the register attributes a host may read and write), so nothing of the fast core's own conformance code is trusted. The stop and trap rules are the reference's (docs/conformance.md): events, then cpm traps, ``at_pc``, ``on_halt``, then the step budget. python validation/lockstep.py MANIFEST.json [MANIFEST.json ...] python validation/lockstep.py --random FIRST_SEED COUNT STEPS python validation/lockstep.py --run ... (the fast core through run(1), not step()) Exit status 0 when every manifest is identical, 1 on the first divergence (printed with the step, the instruction address, and every differing field). """ from __future__ import annotations import sys import time from collections.abc import Callable from dataclasses import dataclass, fields from operator import attrgetter from pathlib import Path import z80_python.conformance as reference_conformance from z80_python.state import CPUState as ReferenceState import z80_python_fast from z80_python_fast.state import CPUState as FastState FIELDS = tuple(f.name for f in fields(ReferenceState)) if tuple(f.name for f in fields(FastState)) != FIELDS: raise SystemExit("CPUState fields differ between the reference and the fast core") _state = attrgetter(*FIELDS) @dataclass(frozen=True) class Divergence: step: int pc: int what: str reference: object fast: object def __str__(self) -> str: return ( f"step {self.step:,} at PC 0x{self.pc:04X}: {self.what}\n" f" reference: {self.reference}\n" f" fast: {self.fast}" ) @dataclass(frozen=True) class Result: steps: int t_states: int reason: str divergence: Divergence | None def _logged_bus( memory: bytearray, port_read_value: int, log: list ) -> tuple[Callable, Callable, Callable, Callable]: append = log.append def read_byte(address: int) -> int: value = memory[address] append(("r", address, value)) return value def write_byte(address: int, value: int) -> None: append(("w", address, value)) memory[address] = value def read_port(port: int) -> int: append(("in", port, port_read_value)) return port_read_value def write_port(port: int, value: int) -> None: append(("out", port, value)) return read_byte, write_byte, read_port, write_port def _cpm_trap(cpu: object, memory: bytearray, output: bytearray) -> bool: """The cpm-minimal traps of docs/conformance.md, through public registers only.""" if cpu.pc == 0x0000: return True if cpu.pc != 0x0005: return False function = cpu.c if function == 0: return True if function == 2: output.append(cpu.e) elif function == 9: address = (cpu.d << 8) | cpu.e while memory[address] != 0x24: output.append(memory[address]) address = (address + 1) & 0xFFFF else: raise ValueError(f"cpm-minimal: unsupported BDOS function {function}") sp = cpu.sp cpu.pc = memory[sp] | (memory[(sp + 1) & 0xFFFF] << 8) cpu.sp = (sp + 2) & 0xFFFF return False def _apply(cpu: object, event: object) -> None: if event.kind == "nmi": cpu.request_non_maskable_interrupt() elif event.kind == "int": cpu.request_maskable_interrupt(event.vector) elif event.kind == "int_clear": cpu.clear_maskable_interrupt() elif event.kind == "reset": cpu.request_reset() else: cpu.clear_reset() def run(path: Path, *, progress_every: int = 0, entry: str = "step") -> Result: manifest = reference_conformance.load_manifest(path) return run_manifest(manifest, progress_every=progress_every, entry=entry) def _step(step: Callable[[], int]) -> int | tuple[str, str]: """``step()``, or the exception it raised as a comparable value.""" try: return step() except Exception as exc: # both cores must refuse the same things the same way return (type(exc).__name__, str(exc)) def run_manifest(manifest: object, *, progress_every: int = 0, entry: str = "step") -> Result: """Lockstep over ``manifest``. ``entry="run"`` drives the fast core through ``run(1)`` instead of ``step()``: every boundary costs at least 3 T-states, so ``run(1)`` is exactly one boundary, through run()'s own loop body.""" ref = reference_conformance.ConformanceHost(manifest) ref_log: list = [] ref_memory = ref.memory ( ref.read_byte, ref.write_byte, ref.read_port, ref.write_port, ) = _logged_bus(ref_memory, manifest.port_read_value, ref_log) fast_memory = bytearray(0x10000) for segment in manifest.memory: fast_memory[segment.address : segment.address + len(segment.data)] = segment.data fast_log: list = [] read_byte, write_byte, read_port, write_port = _logged_bus( fast_memory, manifest.port_read_value, fast_log ) fast = z80_python_fast.Z80CPU(read_byte, write_byte, read_port=read_port, write_port=write_port) fast.restore_state(FastState(**{name: getattr(manifest.initial, name) for name in FIELDS})) fast_output = bytearray() if ref_memory != fast_memory: raise AssertionError("initial memory images differ") ref_capture = ref.capture_state fast_capture = fast.capture_state ref_step = ref.step fast_step = fast.step if entry == "step" else lambda: fast.run(1) events = list(manifest.events) stop = manifest.stop cpm = manifest.host == "cpm-minimal" steps = 0 t_states = 0 reason = "max_steps" started = time.perf_counter() def diverged(what: str, a: object, b: object) -> Result: return Result(steps, t_states, "divergence", Divergence(steps, pc, what, a, b)) pc = ref.pc while steps < stop.max_steps: while events and events[0].at_step == steps: event = events.pop(0) reference_conformance._apply_event(ref, event) _apply(fast, event) if cpm: ref_stop = ref.handle_cpm_trap() fast_stop = _cpm_trap(fast, fast_memory, fast_output) if ref_stop != fast_stop or ref.output != fast_output: return diverged("cpm trap", (ref_stop, ref.output), (fast_stop, fast_output)) if ref_stop: reason = "cpm_exit" break pc = ref.pc if pc in stop.at_pc: reason = "at_pc" break if ( stop.on_halt and ref.halted and not events and not ref.reset_pending and not ref.non_maskable_interrupt_pending and not ref.maskable_interrupt_pending ): reason = "halted" break ref_log.clear() fast_log.clear() ref_t = _step(ref_step) fast_t = _step(fast_step) if ref_t != fast_t: return diverged("T-states", ref_t, fast_t) if type(ref_t) is tuple: return Result(steps, t_states, f"both raised {ref_t[0]}", None) if ref_log != fast_log: return diverged("bus accesses", ref_log, fast_log) ref_state = _step(lambda: _state(ref_capture())) fast_state = _step(lambda: _state(fast_capture())) if type(ref_state) is tuple and len(ref_state) == 2 and ref_state == fast_state: # Both refused the same way; the run stops here, with the refusal # compared. (Before z80-python PR #18, EI;DI left ei_delay at -1, which # CPUState rejects: that is how the fuzz found it.) return Result(steps + 1, t_states + ref_t, f"both capture_state {ref_state}", None) if ref_state != fast_state: if len(ref_state) != len(fast_state): return diverged("capture_state", ref_state, fast_state) differing = [ f"{name}: {a!r} vs {b!r}" for name, a, b in zip(FIELDS, ref_state, fast_state, strict=True) if a != b ] return diverged("CPUState " + ", ".join(differing), ref_state, fast_state) steps += 1 t_states += ref_t if progress_every and steps % progress_every == 0: rate = steps / (time.perf_counter() - started) print(f" {manifest.name}: {steps:,} steps, {rate:,.0f}/s", file=sys.stderr, flush=True) if ref_memory != fast_memory: raise AssertionError("memory differs although every write matched") return Result(steps, t_states, reason, None) def random_manifest(seed: int, steps: int) -> object: """Random memory, random registers, and a random schedule of lifecycle events. Random bytes execute every page (main, CB, ED, DD/FD, DD CB/FD CB), prefix runs, block repeats, HALT, and the interrupt modes, in sequences no hand-written program would try. IM 0 with a non-RST vector raises in both cores; that ends the run, and the refusal itself is compared. """ import random rc = reference_conformance rng = random.Random(seed) memory = rng.randbytes(0x10000) word = lambda: rng.randrange(0x10000) # noqa: E731 byte = lambda: rng.randrange(0x100) # noqa: E731 initial = ReferenceState( a=byte(), f=byte(), b=byte(), c=byte(), d=byte(), e=byte(), h=byte(), l=byte(), ix=word(), iy=word(), sp=word(), pc=word(), wz=word(), i=byte(), r=byte(), iff1=rng.random() < 0.5, iff2=rng.random() < 0.5, im=rng.choice((0, 1, 2)), af_alt=word(), bc_alt=word(), de_alt=word(), hl_alt=word(), q=byte(), ) # fmt: skip events = [] at = 0 while True: at += int(rng.expovariate(1 / 200)) + 1 if at >= steps: break kind = rng.choices(rc.EVENT_KINDS, weights=(2, 6, 2, 1, 1))[0] # Mostly RST opcodes, which every mode accepts; now and then any byte. vector = byte() if rng.random() < 0.02 else 0xC7 | (rng.randrange(8) << 3) events.append(rc.Event(at, kind, vector)) events.append(rc.Event(steps // 2, "reset_clear")) events.sort(key=lambda event: event.at_step) return rc.Manifest( name=f"random-{seed}", memory=(rc.MemorySegment(0, memory),), initial=initial, stop=rc.StopRule(max_steps=steps), events=tuple(events), ) def main(argv: list[str] | None = None) -> int: args = list(argv if argv is not None else sys.argv[1:]) if not args: print(__doc__, file=sys.stderr) return 2 entry = "step" if args[0] == "--run": entry = "run" args = args[1:] if args[0] == "--random": first, count, steps = (int(value) for value in args[1:4]) jobs = [ (f"random seed {seed}", random_manifest(seed, steps)) for seed in range(first, first + count) ] else: jobs = [(arg, Path(arg)) for arg in args] for label, job in jobs: started = time.perf_counter() runner = run if isinstance(job, Path) else run_manifest result = runner(job, entry=entry) path = label seconds = time.perf_counter() - started if result.divergence is not None: print(f"DIVERGED {path}: {result.divergence}") return 1 print( f"identical {path}: {result.steps:,} boundaries, {result.t_states:,} T-states, " f"stopped by {result.reason}, {seconds:.1f} s" ) return 0 if __name__ == "__main__": raise SystemExit(main())