# Save states Decided 2026-11-23 (README, "Next"): the board gets save states here first, then megadrive-rust and megadrive-rust-fast transcribe them, then play-md uses them for save slots, rewind and run-ahead. This document is the specification; the implementation is `src/megadrive_python/state.py`, the tests `tests/test_state.py` and `scripts/state_roundtrip.py`. A save state is **everything that changes as the console runs, and nothing that does not**. The one property that matters, and the one the tests check, is *equivalence*: a run saved at any point where a state may be taken and loaded into a freshly built console continues exactly as the run that was never interrupted, instruction for instruction, picture for picture, sample for sample. ## Where a state may be taken **Between two 68000 steps** (`System.step`): any instruction boundary of the 68000, not only a frame's end. That is the scheduler's own boundary (system.py, "One scheduler"): at it the 68000 has finished an instruction (or exception entry) with every stall it suffered added, the Z80 has been run up to the 68000's clock less the arbiter's cut-off, and the VDP, the sound chips and the SVP are lazy and hold their own clocks. Nothing is part way through a Python call. So a state can fall inside a raster line, inside a VRAM fill or copy DMA, with a Z80 instruction held part way by a bus request (`System._z80_partial`), with accesses pre-arbitrated, with samples in the chips' queues the host has not yet taken, and with a picture half drawn. `save_state` refuses to run inside the Z80's catch-up (`System._in_z80`), the only re-entrant path a caller could reach. What "mid-DMA" can mean here (provisional, measured on `tests/examples/board-tour.bin`, 2026-11-23): a VRAM fill or copy runs across 68000 steps and is caught in flight (`VDP.fill_running` at step 198). A 68000-to-VDP transfer holds the 68000 off the bus, so the step that started it is not over until it is; no boundary inside one was found in that program. The transfer's fields (`transfer_active`, `transfer_pending`, `transfer_next_read`, `dma_bus`) are saved all the same. Smaller units than a 68000 step (between two bus cycles of an instruction, between two Z80 instructions run inside one catch-up) are not supported: the cores' state captures are defined at instruction boundaries. ## The format ``` MAGIC 8 bytes b"MDPYSTAT" LENGTH 4 bytes the header's length, big-endian HEADER JSON {"format": "megadrive-python state", "version": 3, "rom_sha1": ..., "machine": ..., "wiring": {...}, "devices": {"slot": {"name": ..., "version": n}, "port": {...}}} BODY zlib JSON: {"m68k": {...}, "z80": {...}, "system": , "devices": {"slot": , "port": }} ``` `devices` holds an entry for each socket that has a device (none on a plain console: `{}`). The header is read and checked **before the body is decompressed**, and a state is refused (`StateError`) for: - another magic or format: not a megadrive-python state; - another `version` (`state.VERSION`, raised whenever any saved attribute anywhere in the graph, the cores' included, is added, removed, renamed or changes meaning); - another cartridge: `rom_sha1` is the SHA-1 of the slot cartridge's image, followed by a lock-on board's patch ROM and the cartridge plugged into its top, in that order ("" for an empty slot); - another machine (`Machine.name`, so a PAL state never loads into an NTSC console, a Model 1 into a Model 2, or `nuked-md` into `genesis`); - another wiring: the TMSS boot ROM's SHA-1 (or none), the class of each control port's device (a 6-button state into a 3-button console is refused rather than swapping the host's pad object), and the expansion sockets' devices; - a socket device of another name or **another state version** (`devices`: the device's class and its `state_version`, socket 10), or a device in a socket the state had empty or the reverse. Then the body is decoded and both CPU states are validated by their cores' own state types (`m68000_python.state.CPUState`, `z80_python.state.CPUState`) before anything is written. **Loading is all or nothing**: should the graph fail to apply part way, or a socket device's `load_state` refuse its value, the system and its devices are put back as they were before the load began, attributes the failed load added removed again (`test_a_damaged_body_changes_nothing`, `test_a_device_that_refuses_its_value_changes_nothing`). The body holds no code. Loading creates nothing but classes of this package and of its cores (`state.MODULES`), of the attached socket devices' packages, and plain data. ### The graph `system` is the `System` object, encoded by walking its attributes depth first in attribute order. Each value is plain JSON or a tagged object: | Encoded | Is | | --- | --- | | `null`, `true`, number, string | itself (floats round-trip exactly through `repr`) | | `[...]` | a list | | `{"tuple": [...]}`, `{"frozenset": [...]}`, `{"set": [...]}` | the container | | `{"dict": [[k, v], ...]}` | a dict, in insertion order | | `{"bytearray": base64}` | a bytearray (RAMs, VRAM, the renderer's line buffers) | | `{"image": n}` | an immutable byte string of length *n*: the ROM image or a window built from it at power-on; never written, the loading system's own is kept. Also a tuple named in `state.IMAGES`, a table built from the ROM at power-on (the SVP's `rom_words`, 1 M words: written by value it was most of a Virtua Racing state, about 1 MB, until version 2) | | `{"config": "module:NAME..."}` | configuration: an object a module of `MODULES` holds at its top level, or anything reachable from one (`megadrive_python.vdp:H40`, `megadrive_python.vdp:H40.slots_active`, `megadrive_python.vdp:HV_UNITS[1]`, an EEPROM board, a sound table). Written by name, so a mode switch is saved as *which* mode; the loader never writes into configuration in place | | `{"enum": "class", "name": ...}` | an enum member | | `{"namedtuple": "class", "items": [...]}` | a NamedTuple of ours | | `{"object": "module.Class", "fields": {...}}` | an object of one of `MODULES` (`__dict__` and `__slots__`) | | `{"ref": "path"}` | a second path to an object or mutable container already written at `path` | | `{"wiring": "module.Class"}` | an object of a socket device's packages met in the console's walk (the device in `board.slot`/`board.port`, its parts in `System.clocked` and `System.audio_sources`, the VDP's line and picture devices): the loading system's own object of that class is kept, and its state comes from the device's value (since version 3) | References keep the sharing: the cartridge on the bus is the one in the slot (`board.cartridge`, `board._slot_bus`), the renderer's output row is one of its line buffers, an EEPROM and the cartridge RAM it was handed are one bytearray. Loading updates objects and containers **in place** where the loading system has one of the same kind at the same path, so the references the host holds (the pad it presses, the renderer it reads) stay valid (`test_loaded_in_place`). ### What is not saved - **Wiring**: callables and lists of them (the CPUs' bus handlers, the board's catch-up hooks bound to the system, the SSP1601's dispatch table). Checked: no callable attribute changes between a fresh system and one that has run (a scratch check walked Sonic, SoR2 and Gunstar after 400 frames: the only differing skipped attributes were the CPU objects themselves). - **Configuration**: frozen dataclasses (`Machine`, `VDPVariant`, `FMVariant`, `PSGVariant`), classes, modules, and everything reachable from a module-level object (above). The whole reach, not only the top: the VDP holds the line tables' own slot lists (`VDP.slots` *is* `H40.slots_active`), and the first version of this format, which named only module-level objects and their immediate contents, saved that list by value and loaded it into the table every console in the process shares. Two systems in one process then agreed with each other (both had the corrupted table), so only a load into a fresh process showed it: Super Street Fighter II parted from its run 50 frames after the load, Virtua Racing at once (2026-11-23). `test_a_load_never_writes_configuration` holds it; a scratch check over Super Street Fighter II, Virtua Racing, Overdrive 2 (PAL) and Sonic 3, 300 frames each, found the board writes no configuration container while it runs but the pure, lazily filled `VMode._vsync_cache`. - **The CPU objects**: their `capture_state()` is saved instead, as `m68k` and `z80`. - **The ROM**: immutable byte strings (above). An object that changes such a value at run time must hold a bytearray instead; none does (checked 2026-11-23: every `bytes` attribute in the board is set at construction). - **The host's settings** (`state.HOST`): `AudioPath.sample_rate`, the FM generator's switch `YM2612.enabled` and the drawing switches `VDP.rendering` and `VDP.undrawn_frame` (since version 2, when they stopped changing anything software sees). The loading system keeps its own. - **Pure caches** (`state.SKIPPED`): `System._z80_timings`, z80-python's access offsets by instruction bytes. ## Socket devices (socket 10, since version 3) A 32X in the slot or a Sega CD on the port is a board of its own in its own repository (docs/expansion-sockets.md). Its side of a state is its own, through `sockets.SavedDevice`: ```python class SavedDevice(Protocol): state_version: int # the device's own format version def save_state(self) -> object: ... # its state as a value def load_state(self, state: object) -> None: ... # the value back # optional: state_packages (default: the class's package), state_skip ``` - **The value** is what the walk can encode: plain data and objects of the device's packages (`state_packages`), walked as the board's own are -- every attribute, depth first, callables as wiring, the packages' module-level tables as configuration. A device typically gives `{"device": self, "sub": dataclasses.asdict(cpu.capture_state())}` and lists the CPU attribute in `state_skip` (pairs of qualified class and attribute the walk leaves alone, as `HOST` does), and names a medium it holds (a disc) inside the value, refusing another in `load_state`. `save_state` must have no side effects: the loader calls it on the loading console to have something to restore into. - **One encoder for both sides.** The console is walked first; where it meets a device object it writes `{"wiring": class}` (above). Then each device's value is walked by the same encoder (`devices.slot`, `devices.port`), so a path from the device to one of the console's objects (`board`, the cartridge a 32X holds) or to a container both hold (a picture row the device returned and the renderer keeps) is a reference, and sharing is restored across the boundary. The decoder follows the same order with one table. - **Nothing of a device is lost silently.** Every device object the console's walk met must be in some device's value, or the save is refused (`test_a_device_part_in_no_devices_value_is_refused`); a device in a socket without socket 10 cannot be saved at all (`test_a_device_without_the_socket_cannot_be_saved`). - **Refused before anything is touched**: the header names each socket's device and its `state_version`; another device or version is refused by `check_header`, before the body is decompressed (`test_a_device_at_another_state_version_is_refused_before_anything`). A device's own checks inside its value (its BIOS, its disc) run in `load_state`, after the console's graph; a refusal there is rolled back (above). A device's `load_state` must accept the value its own `save_state` gave, which the rollback hands it. - **The console's own records about a device are the console's state** and are saved in its graph: socket 8's leftovers (`AudioPath._sources`: each further source's samples not yet used and its fractional position among them, found again by the loading console's own source), the picture rows the device returned (`Renderer._composite`). So a load -- a rewind, a run-ahead frame -- continues a source's interpolation where it stood instead of restarting it from the source's next list (`test_the_further_sources_leftovers_survive_a_load`, which also shows the sound parting at once when the leftovers are dropped). ## Inventory What the walk saves, read off it on 2026-11-23 (Sonic the Hedgehog at frame 30, and the cartridges of the sweep for their boards). The walk is the authority, not this list: a new attribute is saved without anyone writing it here, and `VERSION` moves with the graph. **CPUs** (the cores' captures; neither core needed a change: both capture everything that decides the next step at an instruction boundary) - 68000 (m68000-python `CPUState`): D0-D7, A0-A6, USP, SSP, SR, PC, IR, IRC (the prefetch queue), the IPL input, the NMI edge, a pending trace, STOP, the double-fault halt, and the clock count (the E clock's phase comes from it). - Z80 (z80-python `CPUState`): every register and its alternate, WZ (MEMPTR), I, R, IFF1/2, IM, Q, HALT, the EI delay, a pending reset, the pending maskable vector, a pending NMI. **System (the scheduler)**: `mclk` (the 68000's time), `z80_mclk`, the instruction counts, `z80_deferred`, `_z80_partial` (a Z80 instruction held part way), `_stall_credited`, the reset button's `reset_pressed` and `reset_at`, `_probe_bus_ends`/`_probe_bus_cart` (the last probe's bus cycles), `clocked` and `audio_sources` (the SVP by reference; a socket device's parts as wiring, their state in the device's value). **Board, bus and arbiter**: work RAM (64 KB), Z80 RAM (8 KB), the Z80 bank register, the Z80's reset and bus-request lines, TMSS (`tmss_register`, `tmss_cart_selected`, which of boot ROM and cartridge `cartridge` is), every arbiter and refresh field (`step_start`, `stall`, `m68k_last_access`, `m68k_accesses`, `m68k_pending_stall`, `m68k_resume_at`, `m68k_step_end`, `z80_offsets`, `z80_access`, `z80_bus_access`, `z80_prearbitrated`, `z80_stall`, `z80_space_stall`, `z80_hold`, `grant_wait`, `busack_at`, `cart_refresh_due`, `cart_refresh_pulse_end`, `z80_refresh_taken`, `ram_refresh_due`, `dma_bus`, the bank-access counters), the FM's and PSG's clocks (`fm_mclk`, `psg_mclk`) and the FM status port's fade (`fm_status_kept`, `fm_status_at`), the FM lags, and the `refresh_enabled`/`arbiter_enabled` switches. **VDP**: the 24 registers, VRAM, CRAM, VSRAM (and its size), the control port's `code`/`address`/`original_address`/`pending`, the four-entry FIFO (`fifo`, `fifo_ready`, `fifo_cpu_ready`, `fifo_read`, `fifo_write`), the read buffer and its timing, DMA (`fill_running`, `transfer_active`, `transfer_pending`, `dma_trigger_armed`, `transfer_cached`, `transfer_value`, `transfer_next_read`, `_read_inc`), interrupts (`vint_pending`, `hint_pending`, `vint_raised`, `hint_raised`, `exint_pending`, `hint_counter`, the Z80's /INT window `z80_irq_start`/`z80_irq_end`), the F flag, odd field, latched HV, the frame count, the vertical scroll latches (`vscroll_latch`, `_vscroll_before`, `_column_before`), the line state (`v`, `previous_v`, `border`, `line_start`, `line_end`, `mclk`, the slot list and `slot_index`, `hblank_at`, `vint_at`, `odd_at`, `render_at`, `collision_at`, `hold`), which `hmode`/`vmode` is in force and the interlace flags, the HV unit (configuration, by name), the debug register. **Renderer**: both frames' line buffers (`pixels`/`_done_pixels`, widths, palettes, dots, blanked flags), the line being drawn (`_line_start`, `_drawn`, `_row`, `_width`, `_backdrop`, `_out`), the sprite caches and collision flag, `_tiles`, the palette cache and its dirty flag. **I/O**: the version register, and per port the data, control, serial registers and the device: a 3-button pad's buttons; a 6-button pad's buttons, `th_level`, the edge count, `last_change` and `mode_switch` (its timeout state). **FM** (ym2612-python, saved through the walk; no core change): every register, the address latch, the F-number latches, channel 3's special mode, the LFO, both timers and the prescaler, the status flags, BUSY, CSM, the DAC, the test registers, the envelope counter and divider, `reset_held`, the clock remainder, the samples not yet taken; per channel the algorithm, feedback and its history, panning, the modulation depths and output; per operator every rate and level, the phase, the envelope phase and attenuation, SSG state and the key state. **PSG** (sn76489-python, likewise): the three tone and the noise register, the four volumes, the latch, the counters and outputs, the LFSR, the stereo and test registers, the clock remainder, the samples not yet taken. **Analogue path**: the PSG box filter's accumulator and phase, the low-pass poles' state, the DC blocker's last input and output, the resampler's phase and previous frame, and per further source (socket 8) the samples not yet used and the fractional position among them. **Cartridge**: the battery RAM and its mapping and protection bits, the Sega (SSF2) mapper's eight banks, the serial EEPROM (its state machine, address, buffers and memory) and its two lines, the J-Cart's TH and devices, every pirate board's registers, the lock-on board's second cartridge; on Virtua Racing the SVP's memory controller (DRAM, IRAM, the PM registers, XST, status, the idle-loop tracker) and the SSP1601 itself (ssp1601-python, through the walk; no core change): X, Y, A, ST, PC, the stack and its pointer, the pointer registers, both internal RAMs, the cycle count. ## Versions - **1** (2026-11-23): the first. - **2** (2026-11-23): `VDP.rendering` left out (a host's setting, as `VDP.undrawn_frame`, added after), and the SVP's `rom_words` written as `{"image": n}` instead of by value. A version 1 state is refused. - **3** (2026-11-25): socket 10, the socket devices' own state: the header's `devices` (each socket's device and its `state_version`), the body's `devices`, the `{"wiring": class}` tag. A console with nothing plugged in saves what version 2 saved, with `"devices": {}` in both; a version 2 state is refused. ## Tests - `tests/test_state.py` (no ROM; 20 tests): `board-tour.bin` saved at step 0, 1, 187, 198 (inside the VRAM fill), 1409 (a Z80 instruction held by a bus request), 5,000 and 23,456, each loaded into a fresh system and run 4,000 more steps: every step's clocks and PCs, then RAM, Z80 RAM, VRAM, CRAM, the picture and the sound identical, and the whole state equal right after the load and at the end. `h32-sprites.bin` likewise on a PAL console with a 6-button pad. Plus: loading in place, the refusals, all or nothing, the host's settings, and one state loaded twice (rewind). Socket 10, with a test-only slot device (`tests/fake_devices.py`, `FakeSavedDevice`, holding the tour cartridge and a sound source whose level changes every sample): its side round-trips and the run continues identically with the host taking the sound in chunks; its source's leftovers survive a load; another device version, another device and no device are refused before anything changes; a device without the socket and a device part no value holds are refused at save; a device refusing its value changes nothing. - `scripts/state_roundtrip.py` (cartridges from `$NO_INTRO_DIR`): the uninterrupted run writes a line per frame (a CRC of every 68000 step's clock and PC with the Z80's clock and PC after it, the instruction counts, the picture, work RAM, Z80 RAM, VRAM, CRAM, VSRAM, the battery RAM or EEPROM, the sound the host took); each state is loaded into a fresh system that runs on to the end writing the same lines. Every line must match, and the two systems' whole states must be equal right after the load and at the end. The pad follows a fixed script (Start, then the buttons eight frames each) so games leave their title screens. Results are in [validation.md](validation.md), "Save states". - **Seeded faults** (2026-11-23, the final code): each of 30 attributes dropped from the format in turn (`SKIPPED` widened by one name, everywhere it occurs), Sonic the Hedgehog saved at frame 150 + 700 steps and judged by the sweep's checks: **22 caught**. The other 8 (`attenuation`, `vsram`, `timer_a_counter`, `th_level`, `slot_index`, `busy_clocks`, `vint_pending`, `hv_latched`) hold, at that save point, exactly the values a fresh console holds (checked one by one), so dropping them changes nothing there: equivalent mutants, not counted. Without the whole-state comparison right after the load, 18 of the 30 went unseen by the per-frame lines alone, because Sonic rewrites CRAM and VSRAM every frame and the FIFO drains in microseconds: continuation alone is not a strong enough judge, which is why the whole-state comparison is part of every check. ## For the Rust tiers (provisional, 2026-11-23) The format is **not shared** between the tiers, as in the famicom line (famicom-rust `src/state.rs`: "a state is portable between builds of this crate, not to the reference"). The Python walk is tied to Python's object graph; the Rust tiers serialise their own structs (serde) behind a header of the same content (magic, version, ROM SHA-1, machine, wiring), refused up front the same way, and prove equivalence the same way: the save-state rung (save at slices, load into a fresh console, traces identical to the uninterrupted run). So there is no cross-tier load check. What the tiers do share is this document: the inventory above is what each must save, and the boundary (between 68000 steps) is where each may. ### Adopting version 3 (socket 10) downstream - **megadrive-rust** (`pin-2-od2`, which has the sockets at 0959147; its state is version 3 there with "devices are wiring, not saved"): a `SavedDevice` trait beside `BusDevice` (`state_version() -> u32`, `save_state() -> serde value or bytes`, `load_state(&mut self, value) -> Result`), the header's `devices` (each socket's `BusDevice::name` and its version) checked with the rest before anything changes, the device values in the body after the console's, and **`AudioPath::sources` saved** (today `#[serde(skip)]`: a 32X or Sega CD source restarts its interpolation on every load, a click per frame with run-ahead) -- it is already index-based (`Vec<(usize, Vec<(f64, f64)>, f64)>`), so it serialises as it is; likewise the renderer's line waiting to be handed over and the rows the device returned. Raise its state version to 4. The rung: the save-state rung with the reference's test-only devices, plus the five socket-10 cases above. - **megadrive-rust-fast**: merges the same, after megadrive-rust; one refusal for play-md's players if it lands before play-md's next deploy (decisions M2, B3). - **segacd-python**: implement `SavedDevice` on `MegaCD` (`state_version = 1`; `save_state` gives `{"device": self, "sub68k": asdict(self.sub.capture_state()), "disc": disc_identity(...), "bios_sha1": ...}`; `state_skip` names the sub CPU and the drive's disc; `load_state` refuses another disc or BIOS and restores the sub CPU), then replace `src/segacd_python/state.py`'s borrowed `_Encoder`, `_Decoder`, `MODULES` swap and its own header with megadrive-python's `save_state`/`load_state`; its `test_the_borrowed_parts_of_megadrive_python_are_there` goes. Repin to this commit. - **sega32x-python**: its pickle-based `savestate.py` (at megadrive-python 5c6d1b7) can move to `SavedDevice` on `Sega32X` (`state_packages = ("sega32x_python", "sh2_python")`, since sh2-python's `capture_state` holds no cache lines or write-buffer end and the SH-2 objects are to be walked whole; the SH2Side closures are callables, so wiring, and `rewire` runs in `load_state`), with the boot ROMs named in the value as the Sega CD's BIOS is. Its owner decides; until then its own format stands.