Merge port/mem-01 (unreviewed, integration base)

This commit is contained in:
acamilo 2026-09-29 15:59:32 +00:00
commit 2defc4947a
10 changed files with 1483 additions and 26 deletions

View file

@ -249,6 +249,43 @@ adapter. Keep `legacy-gameboy-v1` separately routed with exact old ordering/hash
its own identity and public adapter selection. No console-specific state enters generic its own identity and public adapter selection. No console-specific state enters generic
session types. ROM-backed checks are optional explicit jobs, not required downloads. session types. ROM-backed checks are optional explicit jobs, not required downloads.
### MEM-01 — The boundary memory image (port slice)
**2026-09-29: built** on `port/mem-01` off v0.6.5 and awaiting review. It changes no live
behaviour: nothing in `flysim` calls the new read, and the compatibility string is unchanged. It
delivers the piece of ENV-01 above that reads "add the one read-only bulk memory read to the shim
and prove it mutates nothing", together with the executor-side reader that TASK-01 and the
CUT-01 shadow need.
- **Shim.** `fly_gb_read_memory_image(gb, out, 65536)` fills the buffer in address order.
`Emulator::read_memory_image{,_into}` wraps it. There is no new write path.
[legacy-gameboy-v1](legacy-gameboy-v1.md) section 8 carries a dated amendment (2026-09-29):
VRAM, OAM and I/O are not captured and read `$FF`. binjgb's read of those windows runs a
catch-up that moves the exported state. Every memory byte is captured exactly.
- **Executor reader.** `flybrain_gb::{MemoryImage, Cartridge, ImageReader}`. `ImageReader`
implements `MemoryReader`. The palette, `MacroLayer`, `PokeState` and `PokemonRedReward` run
over it unchanged; this is the same code, not a port. The emulator's own bank reads now go
through the same `Cartridge::read_bank`.
- **Proof.** flybrain-gb `tests/rom_memory_image.rs` (ROM) checks three things. The exported
state is byte-identical before and after each bulk read over 4,200 boot frames. The image
equals the single and cached reads. Reading every frame leaves framebuffers, audio and state
frame-for-frame equal to a run that is never read. flysim `tests/rom_memory_image.rs` runs a
live arm and an image-only shadow arm (task and executor) from nine rom-env checkpoints for
3,000 frames each: 27,000 frames with about 5.5 M `MacroState` answers, deals, pads,
decisions, rewards, ledgers and rollbacks. It finds 0 mismatches and 0 reads outside the
captured ranges.
- **Cost.** A bulk read has a median of 0.31 ms per boundary, 1.9 % of a 16.74 ms frame or
about 209 MB/s of reading. This is the same cost as the 57,120 single reads it replaces. The
image is 3.91 MB/s at 59.7275 fps. A 64 KiB copy has a median of 5 µs, and the optional
SHA-256 digest a median of 0.36 ms. Means and p99 values are dominated by preemption: the
measurement ran on the shared 4-core build box at load 16.
**For ENV-01:** after `run_frame` and after a slot import, publish
`read_memory_image` as the `gameboy-memory-inspection-v1` artifact (`MEMORY_IMAGE_CONTENT_TYPE`,
65,536 bytes, digest optional, `romDigest` = `Cartridge::sha256_hex`). **For TASK-01:** build
the executor over `ImageReader::new(&O[k], &cartridge)` in Phase B and over O[k+1] in Phase C,
retaining O[k] until then. The `Cartridge` comes from `Cartridge::verified(rom, contentDigest)`.
### STATE-01 — Coherent all-participant checkpoint/recovery ### STATE-01 — Coherent all-participant checkpoint/recovery
**Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01. **Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01.

View file

@ -169,7 +169,8 @@ interface GameboyMemoryInspection {
} }
``` ```
- **The image.** Byte *i* is what `fly_gb_read_mem(i)` returns at this boundary, which is - **The image.** (Amended 2026-09-29, below: the register windows are not captured.) Byte *i*
is what `fly_gb_read_mem(i)` returns at this boundary, which is
what every task and executor read in the legacy loop sees through the per-frame read cache. what every task and executor read in the legacy loop sees through the per-frame read cache.
It is a listed bus attachment, content type `application/octet-stream`. Its digest is optional, It is a listed bus attachment, content type `application/octet-stream`. Its digest is optional,
because it is a transient live artifact ([state-media-v1](state-media-v1.md) section 1). At because it is a transient live artifact ([state-media-v1](state-media-v1.md) section 1). At
@ -187,6 +188,38 @@ interface GameboyMemoryInspection {
- **Retention.** The coordinator keeps O[k]'s image until transition k→k+1 has been evaluated. - **Retention.** The coordinator keeps O[k]'s image until transition k→k+1 has been evaluated.
The executor reads it in Phase B, and the task reads old and new images in Phase C. The executor reads it in Phase B, and the task reads old and new images in Phase C.
**Amendment, 2026-09-29 (MEM-01).** The image captures the address space's *memory*, not its
*registers*. The two proofs this section demands contradicted each other for three windows: a
read of VRAM (`$8000-$9FFF`), OAM (`$FE00-$FE9F`) or I/O with the APU and wave RAM
(`$FF00-$FF7F`) goes through binjgb's lazy catch-up (`ppu_synchronize`, `timer_synchronize`,
`serial_synchronize`, `intr_synchronize`, `apu_synchronize`) before it answers. The catch-up
rewrites the subsystem's sync bookkeeping, so the exported state changes. On a boot run it
changed on 104 to 105 of 105 sampled boundaries for each window. A full 65,536-byte read
through `emulator_read_mem` is therefore not read-only by the state-comparison test. The amended
rule:
- **Captured**: `$0000-$7FFF` (ROM as mapped), `$A000-$FDFF` (cartridge RAM, work RAM and its
echo), `$FEA0-$FEFF` (the unused block) and `$FF80-$FFFF` (high RAM and `IE`). Byte *i* is
exactly what `fly_gb_read_mem(i)` returns at this boundary. binjgb reads each of these
straight out of an array, with no catch-up.
- **Not captured**: the three register windows above. They read `$FF` (binjgb's
`INVALID_READ_BYTE`), and the shim does not call `emulator_read_mem` for them.
- **Unchanged**: the artifact is still 65,536 bytes in address order,
`application/octet-stream`, with an optional digest. `gameboy-memory-inspection-v1` is
therefore unchanged, and so are its schema digest and the contract digest.
- **Why no task or executor loses anything**: none of them reads a register window. The Pokémon
adapter, scene detector and macro engine read WRAM, HRAM and ROM only. MEM-01's equivalence
harness (flysim `tests/rom_memory_image.rs`) counts every address the image-backed arm reads
over 27,000 frames from nine checkpoints and finds no read outside the captured ranges. A future
task that needs a register must amend this section first. A register cannot be captured
read-only through this shim.
The shim function is `fly_gb_read_memory_image(gb, out, 65536)`, and in Rust it is
`Emulator::read_memory_image{,_into}`. The executor's reader is `flybrain_gb::ImageReader`,
which pairs a `MemoryImage` with a `Cartridge`. `Cartridge::verified` refuses a ROM whose SHA-256
is not the environment's `contentDigest`. The emulator answers its own bank reads through the same
`Cartridge::read_bank`.
## 9. Environment ## 9. Environment
- **Initialize.** The backend configuration declares a setup scaffold of **one frame with no - **Initialize.** The backend configuration declares a setup scaffold of **one frame with no

View file

@ -15,6 +15,7 @@ ROM bytes -> Emulator::run_frame -> RGBA frame + PCM + WRAM
| Module | What it is | | Module | What it is |
| --- | --- | | --- | --- |
| `emulator` | Safe wrapper over binjgb: frames, framebuffer, buttons, WRAM, audio, save states, ROM hash | | `emulator` | Safe wrapper over binjgb: frames, framebuffer, buttons, WRAM, audio, save states, ROM hash |
| `image` | The boundary memory image (`read_memory_image`), the `Cartridge` and `ImageReader`, which runs the macros and adapters over an image instead of a live emulator (MEM-01) |
| `adapter` | `GameAdapter`, `RewardEvent`, `ProgressSnapshot`, `MemoryReader`, `adapter_for` | | `adapter` | `GameAdapter`, `RewardEvent`, `ProgressSnapshot`, `MemoryReader`, `adapter_for` |
| `pokemon_red` | The `pokered-unique8-v7` reward adapter, its catalog and its generated symbol table | | `pokemon_red` | The `pokered-unique8-v7` reward adapter, its catalog and its generated symbol table |
| `platformer` | The `sml-progress-v1` Super Mario Land adapter, its catalog and its RAM map | | `platformer` | The `sml-progress-v1` Super Mario Land adapter, its catalog and its RAM map |

View file

@ -127,6 +127,51 @@ u8 fly_gb_read_mem(FlyGb* gb, u16 address) {
return emulator_read_mem(gb->e, address); return emulator_read_mem(gb->e, address);
} }
/*
* The boundary memory image (MEM-01, legacy-gameboy-v1 section 8 as amended
* 2026-09-29): the CPU address space $0000..=$FFFF in address order.
*
* Every *memory* byte is exactly what fly_gb_read_mem returns for it: ROM as
* mapped ($0000-$7FFF), cartridge RAM ($A000-$BFFF), work RAM and its echo
* ($C000-$FDFF), the unused block ($FEA0-$FEFF), high RAM ($FF80-$FFFE) and
* IE ($FFFF). binjgb reads all of these straight out of its arrays.
*
* The *register* windows are not captured and read as FLY_GB_NOT_CAPTURED:
* VRAM ($8000-$9FFF), OAM ($FE00-$FE9F) and I/O, APU and wave RAM
* ($FF00-$FF7F). binjgb's read of those first runs a lazy catch-up
* (ppu_synchronize, timer_/serial_/intr_synchronize, apu_synchronize) that
* rewrites the subsystem's sync bookkeeping, so reading them would change the
* exported state and could not be called read-only. Nothing a task or an
* executor reads lives there (flysim tests/rom_memory_image.rs records every
* address they read).
*
* Read-only: the captured bytes are the same emulator_read_mem the single read
* makes, and nothing but `out` is written. fly_gb_set_buttons stays the only
* write into a running game; there is no memory-write path.
*/
#define FLY_GB_MEMORY_IMAGE_SIZE 0x10000u
#define FLY_GB_NOT_CAPTURED 0xffu
size_t fly_gb_memory_image_size(void) { return FLY_GB_MEMORY_IMAGE_SIZE; }
static int fly_gb_captured(u32 address) {
if (address >= 0x8000u && address <= 0x9fffu) return 0; /* VRAM */
if (address >= 0xfe00u && address <= 0xfe9fu) return 0; /* OAM */
if (address >= 0xff00u && address <= 0xff7fu) return 0; /* I/O, APU, wave */
return 1;
}
int fly_gb_read_memory_image(FlyGb* gb, u8* out, size_t size) {
u32 address;
if (out == NULL || size != FLY_GB_MEMORY_IMAGE_SIZE) return -1;
for (address = 0; address < FLY_GB_MEMORY_IMAGE_SIZE; ++address) {
out[address] = fly_gb_captured(address)
? emulator_read_mem(gb->e, (u16)address)
: (u8)FLY_GB_NOT_CAPTURED;
}
return 0;
}
u32 fly_gb_audio_frequency(FlyGb* gb) { u32 fly_gb_audio_frequency(FlyGb* gb) {
return emulator_get_audio_buffer(gb->e)->frequency; return emulator_get_audio_buffer(gb->e)->frequency;
} }

View file

@ -3,10 +3,9 @@
use std::ffi::c_void; use std::ffi::c_void;
use std::fmt; use std::fmt;
use sha2::{Digest, Sha256};
use crate::adapter::MemoryReader; use crate::adapter::MemoryReader;
use crate::ffi; use crate::ffi;
use crate::image::{Cartridge, MEMORY_IMAGE_LEN, MemoryImage};
/// Game Boy screen geometry, from `emulator.h`. /// Game Boy screen geometry, from `emulator.h`.
pub const SCREEN_WIDTH: usize = 160; pub const SCREEN_WIDTH: usize = 160;
@ -26,10 +25,6 @@ pub const CPU_TICKS_PER_SECOND: u64 = 4_194_304;
/// so there is no `NEW_FRAME` event to wait for yet. /// so there is no `NEW_FRAME` event to wait for yet.
const MAX_FRAME_ATTEMPTS: u32 = 120; const MAX_FRAME_ATTEMPTS: u32 = 120;
/// Bytes in one ROM bank (`$4000`), which is how [`Emulator::read_rom_bank`]
/// turns a bank number and a CPU address into an offset in the cartridge image.
const ROM_BANK_BYTES: usize = 0x4000;
/// Audio frequency flysim runs the emulator at. binjgb resamples internally to /// Audio frequency flysim runs the emulator at. binjgb resamples internally to
/// whatever is requested, so this is only a default. /// whatever is requested, so this is only a default.
pub const DEFAULT_AUDIO_FREQUENCY: u32 = 48_000; pub const DEFAULT_AUDIO_FREQUENCY: u32 = 48_000;
@ -144,9 +139,9 @@ pub struct Emulator {
/// The shim owns its own padded copy behind the handle and does not hand it /// The shim owns its own padded copy behind the handle and does not hand it
/// back, so this is a second one. It is read-only from here: nothing in this /// back, so this is a second one. It is read-only from here: nothing in this
/// workspace writes a ROM byte, and the bank-addressed read is the only /// workspace writes a ROM byte, and the bank-addressed read is the only
/// reason it is kept. /// reason it is kept. The same [`Cartridge`] an image-backed executor holds
rom: std::sync::Arc<[u8]>, /// (MEM-01), so a bank read is one rule over one set of bytes on both sides.
rom_sha256: [u8; 32], rom: Cartridge,
audio_frequency: u32, audio_frequency: u32,
/// Raw binjgb samples drained since the last [`Emulator::take_audio`]. /// Raw binjgb samples drained since the last [`Emulator::take_audio`].
pending_audio: Vec<u8>, pending_audio: Vec<u8>,
@ -178,8 +173,7 @@ impl Emulator {
debug_assert_eq!(unsafe { ffi::fly_gb_frame_buffer_size() }, FRAMEBUFFER_LEN); debug_assert_eq!(unsafe { ffi::fly_gb_frame_buffer_size() }, FRAMEBUFFER_LEN);
Ok(Self { Ok(Self {
gb, gb,
rom: rom.into(), rom: Cartridge::new(rom),
rom_sha256: Sha256::digest(rom).into(),
audio_frequency, audio_frequency,
pending_audio: Vec::new(), pending_audio: Vec::new(),
cache: FrameCache::new(), cache: FrameCache::new(),
@ -263,14 +257,45 @@ impl Emulator {
/// No bank register is written and the emulator's state does not move: this /// No bank register is written and the emulator's state does not move: this
/// is a read of bytes the process already owns. /// is a read of bytes the process already owns.
pub fn read_rom_bank(&self, bank: u8, address: u16) -> Option<u8> { pub fn read_rom_bank(&self, bank: u8, address: u16) -> Option<u8> {
let offset = match address { self.rom.read_bank(bank, address)
0x0000..=0x3fff => usize::from(address), }
0x4000..=0x7fff => {
usize::from(bank) * ROM_BANK_BYTES + usize::from(address) - ROM_BANK_BYTES /// The cartridge this emulator runs, as the executor's ROM asset holds it.
} pub fn cartridge(&self) -> Cartridge {
_ => return None, self.rom.clone()
}; }
self.rom.get(offset).copied()
/// The boundary memory image: the CPU address space in one bulk read
/// (`legacy-gameboy-v1` section 8, MEM-01).
///
/// For every memory address ([`crate::image::CAPTURED`]) byte *i* is what
/// [`Emulator::read_uncached`] returns for *i* now, and so what
/// [`Emulator::read_wram`] returns for it anywhere between this frame and
/// the next: the per-frame cache is only ever filled from the same read, and
/// nothing between two frames moves the emulator. The register windows
/// (VRAM, OAM, I/O) read [`crate::image::NOT_CAPTURED`], because binjgb's
/// read of a register runs a catch-up that moves the exported state.
///
/// Read-only: the emulator's exported state is byte-identical before and
/// after, and a run read in bulk every frame is frame-for-frame identical to
/// one never read (`tests/rom_memory_image.rs`). The per-frame cache is
/// neither consulted nor filled.
pub fn read_memory_image(&self) -> MemoryImage {
let mut image = MemoryImage::zeroed();
self.read_memory_image_into(&mut image);
image
}
/// [`Emulator::read_memory_image`] into an image the caller already owns,
/// so a boundary's read allocates nothing.
pub fn read_memory_image_into(&self, image: &mut MemoryImage) {
debug_assert_eq!(unsafe { ffi::fly_gb_memory_image_size() }, MEMORY_IMAGE_LEN);
let out = image.as_mut_bytes();
let code =
unsafe { ffi::fly_gb_read_memory_image(self.gb, out.as_mut_ptr(), MEMORY_IMAGE_LEN) };
// The only refusals are a null buffer and a wrong size, and both are
// ruled out by the type.
assert_eq!(code, 0, "fly_gb_read_memory_image refused a {MEMORY_IMAGE_LEN}-byte buffer");
} }
/// Sample rate of the raw buffer, as binjgb configured it. /// Sample rate of the raw buffer, as binjgb configured it.
@ -345,12 +370,7 @@ impl Emulator {
/// SHA-256 of the ROM bytes as supplied, lowercase hex. This is the /// SHA-256 of the ROM bytes as supplied, lowercase hex. This is the
/// `romSha256` half of the checkpoint compatibility string. /// `romSha256` half of the checkpoint compatibility string.
pub fn rom_sha256(&self) -> String { pub fn rom_sha256(&self) -> String {
let mut hex = String::with_capacity(64); self.rom.sha256_hex()
for byte in self.rom_sha256 {
use fmt::Write;
let _ = write!(hex, "{byte:02x}");
}
hex
} }
/// Emulated CPU ticks since boot. /// Emulated CPU ticks since boot.

View file

@ -38,6 +38,8 @@ unsafe extern "C" {
pub fn fly_gb_set_buttons(gb: *mut FlyGb, mask: u32); pub fn fly_gb_set_buttons(gb: *mut FlyGb, mask: u32);
pub fn fly_gb_read_mem(gb: *mut FlyGb, address: u16) -> u8; pub fn fly_gb_read_mem(gb: *mut FlyGb, address: u16) -> u8;
pub fn fly_gb_memory_image_size() -> usize;
pub fn fly_gb_read_memory_image(gb: *mut FlyGb, out: *mut u8, size: usize) -> c_int;
pub fn fly_gb_audio_frequency(gb: *mut FlyGb) -> u32; pub fn fly_gb_audio_frequency(gb: *mut FlyGb) -> u32;
pub fn fly_gb_audio_size(gb: *mut FlyGb) -> usize; pub fn fly_gb_audio_size(gb: *mut FlyGb) -> usize;

View file

@ -0,0 +1,321 @@
//! The boundary memory image and the cartridge beside it (MEM-01).
//!
//! `docs/design/session-framework/legacy-gameboy-v1.md` section 8: on the session framework the
//! macros run in the coordinator's action executor, not beside a live emulator. What they read
//! there is one 64 KiB image of the CPU address space per boundary, carried as an artifact in the
//! observation's `inspection`, plus the ROM as an `AssetRef`. This module is the read side of that
//! seam and nothing else:
//!
//! - [`MemoryImage`] is the image: for every memory address ([`CAPTURED`]) byte *i* is what
//! `fly_gb_read_mem(i)` returned at the boundary, taken in one bulk read by
//! [`crate::Emulator::read_memory_image`]; the register windows read [`NOT_CAPTURED`].
//! - [`Cartridge`] is the ROM, content-addressed by its SHA-256, answering the bank-addressed
//! reads the image cannot ([`MemoryReader::read_rom`]).
//! - [`ImageReader`] puts the two behind [`MemoryReader`], so the **same** macro engine, scene
//! detector and reward adapter that read a live [`crate::Emulator`] read an image instead. There
//! is no second implementation of any rule: [`crate::pokemon_red::state::PokeState`] takes a
//! `&mut dyn MemoryReader`, and this is one.
//!
//! Nothing here writes to a game. An image is a copy; reading it cannot move an emulator.
use std::fmt;
use std::sync::Arc;
use sha2::{Digest, Sha256};
use crate::adapter::MemoryReader;
/// Bytes in one image: `$0000..=$FFFF`. `fly-session-types`' `gameboy::MEMORY_IMAGE_BYTES`.
pub const MEMORY_IMAGE_LEN: usize = 0x1_0000;
/// The artifact's content type (`legacy-gameboy-v1` section 8: "a listed bus attachment, content
/// type `application/octet-stream`"). The encoding is the raw bytes in address order, nothing
/// before and nothing after, so the artifact's `byteLength` is always [`MEMORY_IMAGE_LEN`].
pub const MEMORY_IMAGE_CONTENT_TYPE: &str = "application/octet-stream";
/// What an address outside [`CAPTURED`] holds in an image: `$FF`, which is also what binjgb
/// returns for a read the hardware refuses (`INVALID_READ_BYTE`).
pub const NOT_CAPTURED: u8 = 0xff;
/// The address ranges an image captures, inclusive: every *memory* byte of the address space.
///
/// Each one is exactly what `fly_gb_read_mem` returned at the boundary: ROM as mapped, cartridge
/// RAM, work RAM and its echo, the unused block, high RAM and `IE`. The three *register* windows
/// between them -- VRAM `$8000-$9FFF`, OAM `$FE00-$FE9F`, I/O with the APU and wave RAM
/// `$FF00-$FF7F` -- are not captured and read [`NOT_CAPTURED`]: binjgb's read of a register
/// first runs the subsystem's lazy catch-up (`ppu_synchronize`, `timer_synchronize`, ...), which
/// rewrites its sync bookkeeping, so reading one moves the exported state (`legacy-gameboy-v1`
/// section 8, amendment of 2026-09-29). Nothing the tasks or executors read is in them.
pub const CAPTURED: [(u16, u16); 4] =
[(0x0000, 0x7fff), (0xa000, 0xfdff), (0xfea0, 0xfeff), (0xff80, 0xffff)];
/// Whether an image captures `address` ([`CAPTURED`]).
pub fn captured(address: u16) -> bool {
CAPTURED.iter().any(|&(low, high)| (low..=high).contains(&address))
}
/// Bytes in one ROM bank (`$4000`).
const ROM_BANK_BYTES: usize = 0x4000;
/// Why an image or a cartridge was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ImageError {
/// An image is exactly [`MEMORY_IMAGE_LEN`] bytes.
ImageSize { actual: usize },
/// The cartridge's SHA-256 is not the one the composition names.
RomDigest { expected: String, actual: String },
}
impl fmt::Display for ImageError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ImageSize { actual } => {
write!(f, "a memory image is {MEMORY_IMAGE_LEN} bytes, got {actual}")
}
Self::RomDigest { expected, actual } => {
write!(f, "the cartridge's sha256 is {actual}, the composition names {expected}")
}
}
}
}
impl std::error::Error for ImageError {}
/// One boundary's view of the CPU address space.
///
/// Owned and immutable once taken: it is the payload of an inspection artifact, which the
/// coordinator keeps until the transition that reads it has been evaluated
/// (`state-media-v1` section 3, RT-01a amendment).
#[derive(Clone, PartialEq, Eq)]
pub struct MemoryImage {
bytes: Box<[u8; MEMORY_IMAGE_LEN]>,
}
impl MemoryImage {
/// An image of zeroes, to be filled by [`crate::Emulator::read_memory_image_into`].
pub fn zeroed() -> Self {
let bytes: Box<[u8]> = vec![0u8; MEMORY_IMAGE_LEN].into_boxed_slice();
Self { bytes: bytes.try_into().expect("exactly MEMORY_IMAGE_LEN bytes") }
}
/// Decode an artifact's bytes. Exactly [`MEMORY_IMAGE_LEN`] of them, or refused.
pub fn from_bytes(bytes: &[u8]) -> Result<Self, ImageError> {
if bytes.len() != MEMORY_IMAGE_LEN {
return Err(ImageError::ImageSize { actual: bytes.len() });
}
let mut image = Self::zeroed();
image.bytes.copy_from_slice(bytes);
Ok(image)
}
/// The artifact's bytes: the address space in address order.
pub fn as_bytes(&self) -> &[u8; MEMORY_IMAGE_LEN] {
&self.bytes
}
pub(crate) fn as_mut_bytes(&mut self) -> &mut [u8; MEMORY_IMAGE_LEN] {
&mut self.bytes
}
/// The byte at a CPU address.
pub fn byte(&self, address: u16) -> u8 {
self.bytes[usize::from(address)]
}
/// SHA-256 of the artifact's bytes, 64 lowercase hex digits: the bus `Digest` encoding.
///
/// Optional on the live artifact (a transient frame, `state-media-v1` section 1); mandatory
/// only if an image is ever carried in a checkpoint payload.
pub fn sha256_hex(&self) -> String {
hex(&Sha256::digest(self.bytes.as_slice()))
}
}
impl fmt::Debug for MemoryImage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MemoryImage").field("sha256", &self.sha256_hex()).finish()
}
}
/// The ROM, as the executor holds it: the composition's `AssetRef`, content-addressed.
///
/// Cheap to clone (one `Arc`). The emulator holds one too, for its own [`MemoryReader::read_rom`],
/// so the live reader and the image reader answer a bank read from the same function over the
/// same bytes.
#[derive(Clone)]
pub struct Cartridge {
bytes: Arc<[u8]>,
sha256: [u8; 32],
}
impl Cartridge {
/// The cartridge as supplied: the bytes the emulator was given, before its padding.
pub fn new(rom: &[u8]) -> Self {
Self { bytes: rom.into(), sha256: Sha256::digest(rom).into() }
}
/// The cartridge only if its SHA-256 is `expected` (lowercase hex), which is how the executor
/// refuses a ROM that is not the environment's `contentDigest` (`legacy-gameboy-v1` section 8).
pub fn verified(rom: &[u8], expected: &str) -> Result<Self, ImageError> {
let cartridge = Self::new(rom);
let actual = cartridge.sha256_hex();
if actual != expected {
return Err(ImageError::RomDigest { expected: expected.to_string(), actual });
}
Ok(cartridge)
}
/// SHA-256 of the ROM bytes as supplied, lowercase hex: the compatibility string's `romSha256`,
/// the environment's `contentDigest` and the inspection's `romDigest`.
pub fn sha256_hex(&self) -> String {
hex(&self.sha256)
}
pub fn len(&self) -> usize {
self.bytes.len()
}
pub fn is_empty(&self) -> bool {
self.bytes.is_empty()
}
/// One byte of ROM bank `bank` at CPU address `address`: see [`MemoryReader::read_rom`].
pub fn read_bank(&self, bank: u8, address: u16) -> Option<u8> {
let offset = match address {
0x0000..=0x3fff => usize::from(address),
0x4000..=0x7fff => {
usize::from(bank) * ROM_BANK_BYTES + usize::from(address) - ROM_BANK_BYTES
}
_ => return None,
};
self.bytes.get(offset).copied()
}
}
impl fmt::Debug for Cartridge {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Cartridge")
.field("sha256", &self.sha256_hex())
.field("len", &self.bytes.len())
.finish()
}
}
/// A [`MemoryReader`] over one boundary's image and the cartridge.
///
/// What the executor hands the macro engine in Phase B, and the task in Phase C: the same
/// `&mut dyn MemoryReader` the legacy loop hands them with a live emulator behind it. It needs no
/// cache of its own, because an image is already one frame's reads.
#[derive(Debug, Clone, Copy)]
pub struct ImageReader<'a> {
image: &'a MemoryImage,
rom: &'a Cartridge,
}
impl<'a> ImageReader<'a> {
pub fn new(image: &'a MemoryImage, rom: &'a Cartridge) -> Self {
Self { image, rom }
}
pub fn image(&self) -> &'a MemoryImage {
self.image
}
}
impl MemoryReader for ImageReader<'_> {
fn read8(&mut self, address: u16) -> u8 {
self.image.byte(address)
}
fn read_rom(&mut self, bank: u8, address: u16) -> Option<u8> {
self.rom.read_bank(bank, address)
}
}
fn hex(bytes: &[u8]) -> String {
use fmt::Write;
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
let _ = write!(out, "{byte:02x}");
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_image_is_exactly_the_address_space() {
assert_eq!(MEMORY_IMAGE_LEN, usize::from(u16::MAX) + 1);
assert_eq!(
MemoryImage::from_bytes(&[0; MEMORY_IMAGE_LEN - 1]).unwrap_err(),
ImageError::ImageSize { actual: MEMORY_IMAGE_LEN - 1 }
);
assert_eq!(
MemoryImage::from_bytes(&[0; MEMORY_IMAGE_LEN + 1]).unwrap_err(),
ImageError::ImageSize { actual: MEMORY_IMAGE_LEN + 1 }
);
}
#[test]
fn the_encoding_is_the_bytes_in_address_order() {
let bytes: Vec<u8> = (0..MEMORY_IMAGE_LEN).map(|i| (i ^ (i >> 8)) as u8).collect();
let image = MemoryImage::from_bytes(&bytes).unwrap();
assert_eq!(image.as_bytes().as_slice(), bytes.as_slice());
let rom = Cartridge::new(&[0; 0x8000]);
let mut reader = ImageReader::new(&image, &rom);
for address in [0x0000u16, 0x00ff, 0xc000, 0xd35e, 0xff80, 0xffff] {
assert_eq!(reader.read8(address), bytes[usize::from(address)], "{address:#06x}");
}
// The digest is over exactly those bytes, in the bus `Digest` encoding.
assert_eq!(image.sha256_hex(), hex(&Sha256::digest(&bytes)));
assert_eq!(image.sha256_hex().len(), 64);
assert!(image.sha256_hex().bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)));
}
#[test]
fn the_captured_ranges_are_the_memory_between_the_register_windows() {
let captured_count = (0..=u16::MAX).filter(|&address| captured(address)).count();
// 64 KiB less VRAM (8 KiB), OAM (160 B) and I/O (128 B).
assert_eq!(captured_count, MEMORY_IMAGE_LEN - 0x2000 - 0xa0 - 0x80);
for register in [0x8000u16, 0x9fff, 0xfe00, 0xfe9f, 0xff00, 0xff44, 0xff7f] {
assert!(!captured(register), "{register:#06x}");
}
for memory in [0x0000u16, 0x7fff, 0xa000, 0xc000, 0xdfff, 0xe000, 0xfdff, 0xfea0, 0xff80, 0xffff] {
assert!(captured(memory), "{memory:#06x}");
}
// Every symbol the Pokémon macros and adapter name is in WRAM or HRAM.
use crate::pokemon_red::symbols::ram;
for symbol in [ram::wCurMap, ram::wPartyCount, ram::wTileMap, ram::wStatusFlags7, ram::wListMenuID] {
assert!(captured(symbol), "{symbol:#06x}");
}
}
#[test]
fn a_bank_read_is_the_emulators_rule() {
// Four banks, each byte naming its bank.
let rom: Vec<u8> = (0..4 * ROM_BANK_BYTES).map(|i| (i / ROM_BANK_BYTES) as u8).collect();
let cartridge = Cartridge::new(&rom);
// Bank 0 is always mapped, whatever the bank asked for.
assert_eq!(cartridge.read_bank(3, 0x0100), Some(0));
assert_eq!(cartridge.read_bank(3, 0x4000), Some(3));
assert_eq!(cartridge.read_bank(1, 0x7fff), Some(1));
// A bank the cartridge does not have, and an address that is not ROM.
assert_eq!(cartridge.read_bank(4, 0x4000), None);
assert_eq!(cartridge.read_bank(1, 0x8000), None);
assert_eq!(cartridge.read_bank(1, 0xc000), None);
}
#[test]
fn a_cartridge_is_refused_under_another_digest() {
let rom = [7u8; 0x8000];
let digest = Cartridge::new(&rom).sha256_hex();
assert!(Cartridge::verified(&rom, &digest).is_ok());
let wrong = "0".repeat(64);
assert!(matches!(
Cartridge::verified(&rom, &wrong),
Err(ImageError::RomDigest { .. })
));
}
}

View file

@ -20,6 +20,7 @@ pub mod adapter;
pub mod compatibility; pub mod compatibility;
pub mod emulator; pub mod emulator;
mod ffi; mod ffi;
pub mod image;
pub mod macros; pub mod macros;
mod ordered; mod ordered;
pub mod platformer; pub mod platformer;
@ -32,6 +33,10 @@ pub use adapter::{
adapter_for, adapter_for_with_rom_pin, adapter_for, adapter_for_with_rom_pin,
}; };
pub use compatibility::Compatibility; pub use compatibility::Compatibility;
pub use image::{
CAPTURED, Cartridge, ImageError, ImageReader, MEMORY_IMAGE_CONTENT_TYPE, MEMORY_IMAGE_LEN,
MemoryImage, NOT_CAPTURED, captured,
};
pub use emulator::{ pub use emulator::{
DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator, FRAMEBUFFER_LEN, GbError, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator, FRAMEBUFFER_LEN, GbError,
SCREEN_HEIGHT, SCREEN_WIDTH, buttons, SCREEN_HEIGHT, SCREEN_WIDTH, buttons,

View file

@ -0,0 +1,303 @@
//! The shim's one bulk read, on the real cartridge (MEM-01, `legacy-gameboy-v1` section 8).
//!
//! Gated on `FLY_ROM` like every ROM test here; skips cleanly without it:
//!
//! ```sh
//! . the operator's rom env script # or FLY_ROM=... alone
//! cargo test --release -p flybrain-gb --test rom_memory_image -- --nocapture
//! ```
//!
//! What section 8 asks the implementing slice to prove, at every boundary of a run that goes from
//! power-on through the intro, the title and the naming screens into the bedroom:
//!
//! 1. **Read-only.** The emulator's exported state is byte-identical before and after the read.
//! 2. **Equal to the single reads.** Every captured byte equals the `fly_gb_read_mem` call for
//! its address and what the per-frame cached read (the one every task and executor use)
//! returns; every uncaptured one is `$FF`.
//! 3. **Nothing moves downstream.** Two emulators in lockstep, one read in bulk at every boundary
//! and one never, produce the same framebuffers, audio and states frame for frame.
//! 4. **Why the register windows are out.** Reading them one byte at a time, as a full image
//! would, does move the exported state (binjgb's lazy PPU/timer/serial catch-up), which is
//! the amendment of 2026-09-29 to section 8.
use flybrain_gb::adapter::MemoryReader;
use flybrain_gb::{
CAPTURED, Cartridge, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator, ImageReader,
MEMORY_IMAGE_LEN, MemoryImage, NOT_CAPTURED, buttons, captured,
};
fn rom() -> Option<Vec<u8>> {
let path = std::env::var_os("FLY_ROM")?;
match std::fs::read(&path) {
Ok(bytes) => Some(bytes),
Err(error) => panic!("FLY_ROM is set to {path:?} but could not be read: {error}"),
}
}
fn boot(rom: &[u8]) -> Emulator {
Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES)
.expect("binjgb should accept the ROM")
}
/// A pad that gets from power-on into the game and walks: A through the intro and the naming
/// screens (a pulse every sixteen frames), then a slow rotation of directions with A between.
fn pad(frame: u32) -> u8 {
if frame < 3_000 {
if frame % 16 < 2 { buttons::A } else { buttons::NONE }
} else {
match (frame / 24) % 6 {
0 => buttons::DOWN,
1 => buttons::RIGHT,
2 => buttons::UP,
3 => buttons::A,
4 => buttons::LEFT,
_ => buttons::START,
}
}
}
const FRAMES: u32 = 4_200;
#[test]
fn the_bulk_read_is_read_only_and_equals_the_single_reads() {
let Some(rom) = rom() else {
eprintln!("skipped: FLY_ROM is not set");
return;
};
let mut gb = boot(&rom);
let mut image = MemoryImage::zeroed();
let mut checked = 0u32;
for frame in 0..FRAMES {
gb.set_buttons(pad(frame));
gb.run_frame().expect("a frame");
let _ = gb.take_audio_u8();
let before = gb.export_state().expect("state");
gb.read_memory_image_into(&mut image);
let after = gb.export_state().expect("state");
assert!(before == after, "frame {frame}: the bulk read moved the emulator's state");
// Every byte, every 7th frame (a full sweep is 65,536 FFI calls); the WRAM/HRAM windows
// the macros read, every frame.
let full = frame % 7 == 0;
for address in 0..=u16::MAX {
let wanted = full || (0xc000..0xe000).contains(&address) || address >= 0xff80;
if !wanted {
continue;
}
if !captured(address) {
assert_eq!(image.byte(address), NOT_CAPTURED, "frame {frame}: {address:#06x}");
continue;
}
assert_eq!(
image.byte(address),
gb.read_uncached(address),
"frame {frame}: {address:#06x} differs from the single read"
);
assert_eq!(
image.byte(address),
gb.read_wram(address),
"frame {frame}: {address:#06x} differs from the cached read"
);
}
if full {
checked += 1;
}
// The single reads above moved nothing either.
assert!(after == gb.export_state().expect("state"), "frame {frame}: the single reads moved it");
}
assert!(checked > 500, "{checked} full sweeps");
}
#[test]
fn reading_in_bulk_every_frame_changes_nothing_downstream() {
let Some(rom) = rom() else {
eprintln!("skipped: FLY_ROM is not set");
return;
};
let mut read = boot(&rom);
let mut plain = boot(&rom);
let mut image = MemoryImage::zeroed();
for frame in 0..FRAMES {
read.read_memory_image_into(&mut image);
for gb in [&mut read, &mut plain] {
gb.set_buttons(pad(frame));
gb.run_frame().expect("a frame");
}
assert_eq!(read.take_audio_u8(), plain.take_audio_u8(), "frame {frame}: audio");
assert!(read.framebuffer() == plain.framebuffer(), "frame {frame}: framebuffer");
assert_eq!(read.ticks(), plain.ticks(), "frame {frame}: ticks");
if frame % 50 == 0 {
assert!(
read.export_state().unwrap() == plain.export_state().unwrap(),
"frame {frame}: state"
);
}
}
assert!(read.export_state().unwrap() == plain.export_state().unwrap());
}
#[test]
fn an_image_reader_answers_what_the_emulator_answers() {
let Some(rom) = rom() else {
eprintln!("skipped: FLY_ROM is not set");
return;
};
let mut gb = boot(&rom);
let cartridge = Cartridge::verified(&rom, &gb.rom_sha256()).expect("the emulator's own ROM");
assert_eq!(cartridge.sha256_hex(), gb.cartridge().sha256_hex());
for frame in 0..3_200 {
gb.set_buttons(pad(frame));
gb.run_frame().expect("a frame");
}
let image = gb.read_memory_image();
assert_eq!(image.as_bytes().len(), MEMORY_IMAGE_LEN);
let mut reader = ImageReader::new(&image, &cartridge);
for &(low, high) in &CAPTURED {
for address in low..=high {
assert_eq!(
reader.read8(address),
MemoryReader::read8(&mut gb, address),
"{address:#06x}"
);
}
}
// Every bank the cartridge has, and one past it.
let banks = u8::try_from(rom.len().div_ceil(0x4000)).unwrap_or(u8::MAX);
for bank in 0..=banks {
for address in (0u16..0x8000).step_by(97).chain([0x3fff, 0x4000, 0x7fff, 0x8000, 0xc000]) {
assert_eq!(
reader.read_rom(bank, address),
MemoryReader::read_rom(&mut gb, bank, address),
"bank {bank} {address:#06x}"
);
}
}
}
/// The amendment's reason, measured: over the same run, reading any of the three register windows
/// one byte at a time -- which is what a full 64 KiB image through `fly_gb_read_mem` would do --
/// changes the exported state on some boundary, and reading the captured ranges never does.
#[test]
fn the_register_windows_are_the_reads_that_move_the_state() {
let Some(rom) = rom() else {
eprintln!("skipped: FLY_ROM is not set");
return;
};
let mut gb = boot(&rom);
let windows: [(&str, u16, u16); 3] =
[("vram", 0x8000, 0x9fff), ("oam", 0xfe00, 0xfe9f), ("io", 0xff00, 0xff7f)];
let mut moved = [0u32; 3];
let mut sampled = 0u32;
for frame in 0..FRAMES {
gb.set_buttons(pad(frame));
gb.run_frame().expect("a frame");
if frame % 40 != 0 {
continue;
}
sampled += 1;
for (index, &(_, low, high)) in windows.iter().enumerate() {
// A throwaway copy of this boundary, so each window is measured from the same state.
let state = gb.export_state().expect("state");
let mut probe = boot(&rom);
probe.import_state(&state).expect("same build");
for address in low..=high {
let _ = probe.read_uncached(address);
}
if probe.export_state().expect("state") != state {
moved[index] += 1;
}
}
}
eprintln!(
"{sampled} boundaries: {}",
windows
.iter()
.zip(moved)
.map(|((name, ..), n)| format!("{name} moved the state on {n}"))
.collect::<Vec<_>>()
.join(", ")
);
// The PPU's and the timer's catch-ups run on almost every boundary.
assert!(moved[0] > 0, "reading VRAM never moved the state");
assert!(moved[2] > 0, "reading I/O never moved the state");
}
/// The per-boundary cost (MEM-01 deliverable 4), printed for the report rather than asserted:
/// it is wall time on whatever box runs it. What it does assert is only that one read fits
/// comfortably inside a frame (16.74 ms), which a loaded box also meets.
///
/// - `bulk`: the shim's read into an owned image, which is what the environment pays per boundary;
/// - `copy`: cloning an image (64 KiB `memcpy`), what handing it to a store that copies costs;
/// - `digest`: SHA-256 of the image, which the live artifact may omit;
/// - `single`: the same captured addresses through 57,120 single FFI reads, for comparison.
#[test]
fn the_bulk_read_costs_a_fraction_of_a_frame() {
use std::time::{Duration, Instant};
let Some(rom) = rom() else {
eprintln!("skipped: FLY_ROM is not set");
return;
};
let mut gb = boot(&rom);
for frame in 0..3_200 {
gb.set_buttons(pad(frame));
gb.run_frame().expect("a frame");
}
const ROUNDS: usize = 2_000;
let mut bulk = Vec::with_capacity(ROUNDS);
let mut copy = Vec::with_capacity(ROUNDS);
let mut digest = Vec::with_capacity(ROUNDS);
let mut single = Vec::with_capacity(ROUNDS / 20);
let mut image = MemoryImage::zeroed();
let mut sink = 0u64;
for round in 0..ROUNDS {
gb.set_buttons(pad(3_200 + round as u32));
gb.run_frame().expect("a frame");
let start = Instant::now();
gb.read_memory_image_into(&mut image);
bulk.push(start.elapsed());
let start = Instant::now();
let copied = image.clone();
copy.push(start.elapsed());
sink += u64::from(copied.byte(0xd35e));
let start = Instant::now();
sink += image.sha256_hex().len() as u64;
digest.push(start.elapsed());
if round % 20 == 0 {
let start = Instant::now();
for &(low, high) in &CAPTURED {
for address in low..=high {
sink += u64::from(gb.read_uncached(address));
}
}
single.push(start.elapsed());
}
}
let stats = |name: &str, samples: &mut Vec<Duration>| {
samples.sort();
let at = |q: f64| samples[((samples.len() - 1) as f64 * q) as usize].as_secs_f64() * 1e6;
let mean = samples.iter().sum::<Duration>().as_secs_f64() * 1e6 / samples.len() as f64;
eprintln!(
"{name:>7}: mean {mean:8.1} us median {:8.1} us p99 {:8.1} us ({} samples)",
at(0.5),
at(0.99),
samples.len()
);
at(0.5)
};
let median = stats("bulk", &mut bulk);
stats("copy", &mut copy);
stats("digest", &mut digest);
stats("single", &mut single);
let fps = 59.7275;
eprintln!(
"image {} B/boundary = {:.3} MB/s at {fps} fps; bulk median {:.2}% of a {:.2} ms frame; \
bulk read throughput {:.0} MB/s (sink {sink})",
MEMORY_IMAGE_LEN,
MEMORY_IMAGE_LEN as f64 * fps / 1e6,
median / 1e3 / (1e3 / fps) * 100.0,
1e3 / fps,
MEMORY_IMAGE_LEN as f64 / median,
);
assert!(median < 8_000.0, "a bulk read took {median} us at the median");
}

View file

@ -0,0 +1,690 @@
//! MEM-01: the macro engine over a boundary's memory image is the macro engine over the live
//! emulator, frame by frame, on the real cartridge.
//!
//! Gated on `FLY_ROM` and the checkpoints `the operator's rom env script` exports; every
//! scenario whose checkpoint is not set is skipped, and without `FLY_ROM` the whole test is:
//!
//! ```sh
//! . the operator's rom env script
//! cargo test --release -p flysim --test rom_memory_image -- --nocapture
//! ```
//!
//! ## What runs
//!
//! Two copies of the Pokémon task and executor over one cartridge. The **live** arm is the
//! stream's own frame (`LegacyFrame::execute` and `stub_advance`, the stub-readout drivers' path):
//! its `MacroLayer` and `PokemonRedReward` read the emulator through `MemoryReader`, and its mask
//! is the one the emulator is given. The **shadow** arm is what the session framework's
//! `pokered-macros-v1` executor will be (`legacy-gameboy-v1` sections 8 and 10): a second
//! `MacroLayer` and a second `PokemonRedReward`, built by the same constructors, that never see the
//! emulator. They read one `MemoryImage` per boundary, taken with the shim's bulk read and
//! retained from the evaluation of `k-1 -> k` through the decision at `k`, plus the ROM as a
//! `Cartridge`. Both arms get the same decoded channels from the same stub readout (the shipping
//! decoder fed synthetic rates, as `rom_macros_mode.rs` does).
//!
//! ## What is compared, every frame
//!
//! - **The deal and the pad:** bound channels, scene, the feed's palette strip, the running macro,
//! the empty-pad clock, and the rollback's "nearer the objective" signal.
//! - **The decision:** mask, macro events and silence reason from `decide`.
//! - **The evaluation:** reward events, the abandonment `observe` reports, progress, location,
//! snapshot safety and game over; the adapter's whole exported ledger every 30 frames.
//! - **Every `MacroState` answer**, through `PokeState` with the adapter's ledger: scene, player,
//! map size, party, battle, text box, start menu, shop, PC, money, bag, NPCs on and off screen,
//! signs, warps, connections, walkability, counters, pushed/visited tiles around the player,
//! script and text latches, the YES/NO prompt, the A latch, frontier exhaustion, the decoded
//! map grid, the step destination, shop stock, move and item refusals, the exit, map and
//! objective ledgers, the path layer's exits, frontier and targets, the scene's palette set and
//! every macro's precondition.
//! - **Rollbacks:** twice per scenario the ratchet's game-only rollback is replayed on both arms
//! (cancel, import, release buttons, clear transients, re-observe on an image read after the
//! import), and the events and the next frames must agree.
//!
//! And one thing the shadow can check that the live arm cannot: every address it read is inside
//! the image's captured ranges, so the register windows the image leaves out
//! (`legacy-gameboy-v1` section 8, amended 2026-09-29) are never asked for.
use std::time::{Duration, Instant};
use flybrain_core::decoder::PopulationDecoder;
use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros;
use flybrain_core::ordered::NumberMap;
use flybrain_gb::adapter::MemoryReader;
use flybrain_gb::pokemon_red::PokemonRedReward;
use flybrain_gb::pokemon_red::macros::cartridge::{Edge, ExitId, MacroState};
use flybrain_gb::pokemon_red::macros::palette::{MacroKind, precondition, scene_set};
use flybrain_gb::pokemon_red::macros::path;
use flybrain_gb::pokemon_red::state::PokeState;
use flybrain_gb::{
AdapterLedger, Cartridge, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator,
GameAdapter, ImageReader, MEMORY_IMAGE_LEN, MemoryImage, captured,
};
use flysim::config::Config;
use flysim::frame::LegacyFrame;
use flysim::macros::{MacroLayer, macro_layer};
use flysim::snapshot::MacroMode;
const MS_PER_FRAME: f64 = 1000.0 / 59.7275;
const FRAMES_PER_SECOND: f64 = 59.7275;
const BURST_MS: f64 = 100.0;
const SEED: u32 = 20_260_916;
const HOT: f64 = 16.0;
const REST: f64 = 10.0;
const HOLDS_PER_SLOT: usize = 3;
/// Frames per scenario; `FLY_MEMIMAGE_FRAMES` overrides.
const DEFAULT_FRAMES: u32 = 3_000;
/// The scenarios: the checkpoint's `rom-env.sh` variable, what it is there to cover, and a
/// channel the stub leans on every other burst. A scenario that leans on `macro_menu` also has
/// the harness open the start menu itself on an overworld boundary every 250 frames (the first idle one after) (START held
/// for three frames on the emulator, then twenty idle, both arms re-observing the image after):
/// the palette's own MENU press does not reliably leave the menu up long enough to be seen.
const SCENARIOS: &[(&str, &str, Option<&str>)] = &[
("FLY_CENTER_CHECKPOINT", "centre", None),
("FLY_MART_CHECKPOINT", "mart", None),
("FLY_CATCH_CHECKPOINT", "forest battles", None),
("FLY_GYM_CHECKPOINT", "gym", None),
("FLY_DOOR_CHECKPOINT", "overworld door", None),
("FLY_BUILDING_CHECKPOINT", "building", None),
("FLY_MT_MOON_CHECKPOINT", "cave", None),
("FLY_ROW62_MART_CHECKPOINT", "mart 2", None),
("FLY_PEWTER_CHECKPOINT", "start menu", Some("macro_menu")),
];
fn rates(hot: Option<&str>) -> NumberMap {
let mut rates = NumberMap::new();
for channel in flybrain_gb::macro_channels("pokemon-red") {
rates.set(channel, REST);
}
for bucket in 0..8 {
rates.set(&format!("command_{bucket}"), REST);
}
if let Some(channel) = hot {
rates.set(channel, HOT);
}
rates
}
fn rom() -> Option<Vec<u8>> {
let path = std::env::var_os("FLY_ROM")?;
match std::fs::read(&path) {
Ok(bytes) => Some(bytes),
Err(error) => panic!("FLY_ROM is set to {path:?} but could not be read: {error}"),
}
}
/// The shadow's reader: the image and the cartridge, counting what is asked of it.
struct Recording<'a> {
inner: ImageReader<'a>,
seen: &'a mut Vec<u64>,
uncaptured: &'a mut u64,
}
impl MemoryReader for Recording<'_> {
fn read8(&mut self, address: u16) -> u8 {
let index = usize::from(address);
self.seen[index >> 6] |= 1 << (index & 63);
if !captured(address) {
*self.uncaptured += 1;
}
self.inner.read8(address)
}
fn read_rom(&mut self, bank: u8, address: u16) -> Option<u8> {
self.inner.read_rom(bank, address)
}
}
/// Every `MacroState` answer this frame, as text, in a fixed order.
fn sweep(state: &mut dyn MacroState) -> Vec<String> {
let mut out = Vec::with_capacity(512);
macro_rules! q {
($label:expr, $value:expr) => {
out.push(format!("{}={:?}", $label, $value))
};
}
let scene = state.scene();
q!("scene", scene);
let player = state.player();
q!("player", player);
q!("map_size", state.map_size());
q!("party", state.party());
q!("battle", state.battle());
q!("text_box", state.text_box());
q!("start_menu", state.start_menu());
q!("shop", state.shop());
q!("pc", state.pc());
q!("money", state.money());
q!("bag", state.bag());
q!("npcs", state.npcs());
q!("offscreen_npcs", state.offscreen_npcs());
q!("signs", state.signs());
let warps = state.warps();
q!("warps", warps);
q!("connections", state.connections());
q!("scripted", state.scripted());
q!("text_open", state.text_open());
q!("yes_no", state.yes_no_prompt());
q!("a_latched", state.a_latched());
q!("frontier_exhausted", state.frontier_exhausted());
// The grid can be a few thousand tiles; its equality is what matters, so compare it whole
// through its Debug text but keep only a digest of it.
let grid = state.map_grid().map(|grid| {
use sha2::Digest;
let text = format!("{grid:?}");
format!("{:x}", sha2::Sha256::digest(text.as_bytes()))
});
q!("map_grid", grid);
q!("stepping_onto", state.stepping_onto());
q!("shop_stock", state.shop_stock());
q!("objective", state.objective());
if let Some(player) = player {
for y in player.y.saturating_sub(6)..=player.y.saturating_add(6) {
for x in player.x.saturating_sub(6)..=player.x.saturating_add(7) {
out.push(format!(
"tile({x},{y})={:?}/{}/{}/{}",
state.walkable(x, y),
state.counter_tile(x, y),
state.pushed_tile(x, y),
state.tile_visited(x, y),
));
}
}
}
for index in 0..u8::try_from(warps.len()).unwrap_or(u8::MAX) {
q!(format!("exit_visited(warp {index})"), state.exit_visited(ExitId::Warp(index)));
}
for edge in [Edge::North, Edge::South, Edge::East, Edge::West] {
q!(format!("exit_visited({edge:?})"), state.exit_visited(ExitId::Edge(edge)));
}
let maps: Vec<u8> = (0..=u8::MAX).filter(|&map| state.map_visited(map)).collect();
q!("maps_visited", maps);
let moves: Vec<u8> = (1..=165).filter(|&id| state.move_without_effect(id)).collect();
q!("moves_without_effect", moves);
let items: Vec<u8> = (1..=u8::MAX).filter(|&id| state.item_refused(id)).collect();
q!("items_refused", items);
q!("exits", path::exits(state));
q!("frontier", path::frontier(state));
q!("interactables", path::interactables(state));
q!("interactable_targets", path::interactable_targets(state));
q!("person_targets", path::person_targets(state));
q!("offscreen_person_targets", path::offscreen_person_targets(state));
q!("scene_set", scene_set(scene, state));
let preconditions: Vec<(MacroKind, bool)> =
MacroKind::ALL.iter().map(|&kind| (kind, precondition(kind, state))).collect();
q!("preconditions", preconditions);
out
}
/// What one scenario covered, for the report.
#[derive(Default)]
struct Coverage {
frames: u64,
swept: u64,
answers: u64,
scenes: std::collections::BTreeMap<&'static str, u64>,
maps: std::collections::BTreeSet<u32>,
started: u64,
rewards: u64,
rollbacks: u64,
menus_opened: u64,
distinct_addresses: u64,
uncaptured: u64,
read_time: Duration,
reads: u64,
digest_time: Duration,
}
/// Mismatches are collected, not panicked on, so a failure reports its first few frames.
struct Diff {
label: String,
first: Vec<String>,
count: u64,
}
impl Diff {
fn check(&mut self, frame: u64, what: &str, live: String, shadow: String) {
if live != shadow {
self.count += 1;
if self.first.len() < 8 {
self.first.push(format!(
"{} frame {frame} {what}:\n live {live}\n shadow {shadow}",
self.label
));
}
}
}
}
/// The shim's bulk read, timed.
fn read_image(gb: &Emulator, image: &mut MemoryImage, cov: &mut Coverage) {
let start = Instant::now();
gb.read_memory_image_into(image);
cov.read_time += start.elapsed();
cov.reads += 1;
}
fn run(
rom: &[u8],
label: &str,
checkpoint: &flysim::store::Checkpoint,
frames: u32,
lean: Option<&str>,
) -> (Coverage, Diff) {
let mut gb = Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES)
.expect("binjgb should accept the cartridge");
gb.import_state(&checkpoint.runtime.emulator).expect("the checkpoint's emulator state");
// The executor's ROM asset: refused unless it is the environment's content.
let cartridge = Cartridge::verified(rom, &gb.rom_sha256()).expect("the environment's ROM");
let mut live_adapter = PokemonRedReward::new();
let mut shadow_adapter = PokemonRedReward::new();
live_adapter.import_state(&checkpoint.runtime.reward).expect("reward ledger");
shadow_adapter.import_state(&checkpoint.runtime.reward).expect("reward ledger");
let channels = flybrain_gb::macro_channels("pokemon-red");
let preset = gameboy_decoder_config_with_macros(&channels);
let hold_ms = preset.macros.as_ref().expect("a macro group").hold_ms;
let mut decoder = PopulationDecoder::new(preset).expect("the preset is well formed");
decoder.calibrate(&rates(None));
let mut config = Config::default();
config.loop_.game = "pokemon-red".to_string();
config.macros.mode = MacroMode::Macros;
config.validate().expect("pokemon-red has a palette");
let mut live: MacroLayer = macro_layer(&config, hold_ms, SEED).expect("a layer");
let mut shadow: MacroLayer = macro_layer(&config, hold_ms, SEED).expect("a layer");
let mut cov = Coverage::default();
let mut diff = Diff { label: label.to_string(), first: Vec::new(), count: 0 };
let mut seen = vec![0u64; MEMORY_IMAGE_LEN / 64];
let mut uncaptured = 0u64;
// O[0]: the boundary's image, retained until the next transition is evaluated.
let mut image = MemoryImage::zeroed();
read_image(&gb, &mut image, &mut cov);
let mut ms = 0.0;
{
let a = live.observe(&mut gb, &AdapterLedger(&live_adapter), ms);
let mut reader = Recording {
inner: ImageReader::new(&image, &cartridge),
seen: &mut seen,
uncaptured: &mut uncaptured,
};
let b = shadow.observe(&mut reader, &AdapterLedger(&shadow_adapter), ms);
diff.check(0, "initial observe", format!("{a:?}"), format!("{b:?}"));
}
let mut frame = LegacyFrame::new();
let mut next_burst = ms;
let mut burst = 0usize;
// The ratchet's slot: a state taken early, restored twice.
let mut slot: Option<Vec<u8>> = None;
let rollback_at = [frames / 3, 2 * frames / 3];
let mut menu_due = false;
for k in 0..u64::from(frames) {
// --- The deal and the pad, at boundary k.
let bound = live.bound_channels();
diff.check(k, "bound", format!("{bound:?}"), format!("{:?}", shadow.bound_channels()));
diff.check(k, "scene", live.scene_name().into(), shadow.scene_name().into());
diff.check(
k,
"palette",
format!("{:?}", live.feed_palette()),
format!("{:?}", shadow.feed_palette()),
);
diff.check(k, "running", format!("{:?}", live.running()), format!("{:?}", shadow.running()));
diff.check(
k,
"pad_empty_ms",
format!("{:?}", live.pad_empty_ms(ms)),
format!("{:?}", shadow.pad_empty_ms(ms)),
);
diff.check(
k,
"nearer",
format!("{:?}", live.nearer_the_objective()),
format!("{:?}", shadow.nearer_the_objective()),
);
*cov.scenes.entry(live.scene_name()).or_default() += 1;
if let Some(map) = live_adapter.map_id() {
cov.maps.insert(map);
}
// --- Every MacroState answer over O[k], both ways.
{
let live_answers = {
let ledger = AdapterLedger(&live_adapter);
let mut state = PokeState::with_ledger(&mut gb, &ledger);
sweep(&mut state)
};
let shadow_answers = {
let ledger = AdapterLedger(&shadow_adapter);
let mut reader = Recording {
inner: ImageReader::new(&image, &cartridge),
seen: &mut seen,
uncaptured: &mut uncaptured,
};
let mut state = PokeState::with_ledger(&mut reader, &ledger);
sweep(&mut state)
};
cov.swept += 1;
cov.answers += live_answers.len() as u64;
if live_answers != shadow_answers {
if live_answers.len() != shadow_answers.len() {
diff.check(
k,
"answer count",
live_answers.len().to_string(),
shadow_answers.len().to_string(),
);
}
for (a, b) in live_answers.iter().zip(&shadow_answers) {
diff.check(k, "MacroState", a.clone(), b.clone());
}
}
}
// --- The stub readout, then Phase B on both arms.
let bursting = ms < next_burst + BURST_MS;
let rotation = channels[(burst / HOLDS_PER_SLOT) % channels.len()];
let hot = bursting.then_some(match lean {
Some(channel) if burst.is_multiple_of(2) => channel,
_ => rotation,
});
if ms >= next_burst + hold_ms {
next_burst = ms;
burst += 1;
}
let active = decoder.decode_bound(&rates(hot), ms, false, None, Some(&bound));
let executed = frame.execute(Some(&mut live), &active, 0, ms, &mut gb, &live_adapter);
let decided = {
let mut reader = Recording {
inner: ImageReader::new(&image, &cartridge),
seen: &mut seen,
uncaptured: &mut uncaptured,
};
shadow.decide(&active, 0, ms, &mut reader, &AdapterLedger(&shadow_adapter))
};
diff.check(k, "mask", executed.mask.to_string(), decided.mask.to_string());
diff.check(k, "events", format!("{:?}", executed.events), format!("{:?}", decided.events));
diff.check(
k,
"silence",
format!("{:?}", executed.silence),
format!("{:?}", decided.silence),
);
cov.started += executed.events.iter().filter(|event| event.outcome.is_none()).count() as u64;
// --- The environment runs the live mask; O[k+1] is read once, in bulk.
ms += MS_PER_FRAME;
let evaluated = frame
.stub_advance(Some(&mut live), &mut gb, &mut live_adapter, ms)
.expect("a frame");
read_image(&gb, &mut image, &mut cov);
if k % 64 == 0 {
let start = Instant::now();
let _ = image.sha256_hex();
cov.digest_time += start.elapsed();
}
// --- Phase C on the shadow, over the image alone.
let (rewards, abandoned) = {
let mut reader = Recording {
inner: ImageReader::new(&image, &cartridge),
seen: &mut seen,
uncaptured: &mut uncaptured,
};
let rewards = shadow_adapter.sample(&mut reader, ms);
let abandoned = shadow.observe(&mut reader, &AdapterLedger(&shadow_adapter), ms);
(rewards, abandoned)
};
cov.rewards += evaluated.rewards.len() as u64;
diff.check(k, "rewards", format!("{:?}", evaluated.rewards), format!("{rewards:?}"));
diff.check(k, "abandoned", format!("{:?}", evaluated.abandoned), format!("{abandoned:?}"));
diff.check(
k,
"progress",
format!("{:?}", evaluated.progress),
format!("{:?}", shadow_adapter.progress()),
);
diff.check(
k,
"location",
format!("{:?}", live_adapter.location()),
format!("{:?}", shadow_adapter.location()),
);
diff.check(
k,
"safe/over",
format!("{}/{}", live_adapter.safe_for_snapshot(), live_adapter.game_over()),
format!("{}/{}", shadow_adapter.safe_for_snapshot(), shadow_adapter.game_over()),
);
if k % 30 == 0 {
diff.check(
k,
"adapter ledger",
live_adapter.export_state().to_string(),
shadow_adapter.export_state().to_string(),
);
}
// --- The start-menu scenario: the harness opens the menu, both arms observe the result.
if lean == Some("macro_menu") && k % 250 == 125 {
menu_due = true;
}
if menu_due
&& live.scene_name() == "overworld"
&& live.running().is_none()
{
for (mask, frames) in [(flybrain_gb::buttons::START, 3), (0, 20)] {
gb.set_buttons(mask);
for _ in 0..frames {
gb.run_frame().expect("a frame");
}
}
let _ = gb.take_audio_u8();
let a = live.observe(&mut gb, &AdapterLedger(&live_adapter), ms);
read_image(&gb, &mut image, &mut cov);
let b = {
let mut reader = Recording {
inner: ImageReader::new(&image, &cartridge),
seen: &mut seen,
uncaptured: &mut uncaptured,
};
shadow.observe(&mut reader, &AdapterLedger(&shadow_adapter), ms)
};
diff.check(k, "menu opened", format!("{a:?}"), format!("{b:?}"));
menu_due = false;
cov.menus_opened += 1;
}
// --- The ratchet's slot and its rollback, on both arms.
if k == 100 {
slot = Some(gb.export_state().expect("state"));
}
if rollback_at.contains(&(k as u32))
&& let Some(state) = slot.as_ref()
{
let a = {
let mut events = live.cancel(ms);
gb.import_state(state).expect("the slot");
gb.set_buttons(0);
live_adapter.clear_transient();
events.extend(live.observe(&mut gb, &AdapterLedger(&live_adapter), ms));
events
};
// The environment's RestoreSlot returns "a memory image read after the import".
read_image(&gb, &mut image, &mut cov);
let b = {
let mut events = shadow.cancel(ms);
shadow_adapter.clear_transient();
let mut reader = Recording {
inner: ImageReader::new(&image, &cartridge),
seen: &mut seen,
uncaptured: &mut uncaptured,
};
events.extend(shadow.observe(&mut reader, &AdapterLedger(&shadow_adapter), ms));
events
};
diff.check(k, "rollback", format!("{a:?}"), format!("{b:?}"));
cov.rollbacks += 1;
}
cov.frames += 1;
}
diff.check(
u64::from(frames),
"final adapter ledger",
live_adapter.export_state().to_string(),
shadow_adapter.export_state().to_string(),
);
diff.check(
u64::from(frames),
"counts",
format!("{:?}", live.counts()),
format!("{:?}", shadow.counts()),
);
cov.distinct_addresses = seen.iter().map(|word| u64::from(word.count_ones())).sum();
cov.uncaptured = uncaptured;
(cov, diff)
}
#[test]
fn the_macros_over_the_image_are_the_macros_over_the_emulator() {
let Some(rom) = rom() else {
eprintln!("skipped: FLY_ROM is not set");
return;
};
let frames = std::env::var("FLY_MEMIMAGE_FRAMES")
.ok()
.and_then(|value| value.parse().ok())
.unwrap_or(DEFAULT_FRAMES);
let mut all_scenes = std::collections::BTreeSet::new();
let mut all_maps = std::collections::BTreeSet::new();
let mut failures = Vec::new();
let mut ran = 0;
let (mut read_time, mut reads, mut total_frames, mut total_answers) =
(Duration::ZERO, 0u64, 0u64, 0u64);
for &(variable, label, lean) in SCENARIOS {
let Some(path) = std::env::var_os(variable) else {
eprintln!("{label}: skipped, {variable} is not set");
continue;
};
let checkpoint = flysim::store::load(std::path::Path::new(&path))
.expect("the checkpoint should be a FLYSIM01 envelope");
let started = Instant::now();
let (cov, diff) = run(&rom, label, &checkpoint, frames, lean);
ran += 1;
eprintln!(
"{label} ({variable}): {} frames, {} sweeps / {} answers, {} macros started, {} rewards, \
{} rollbacks, {} menus opened, {} distinct addresses read ({} uncaptured reads), maps {:x?}, scenes {:?}; \
bulk read {:.1} us mean; digest {:.1} us mean; {} mismatches; {:.0} s",
cov.frames,
cov.swept,
cov.answers,
cov.started,
cov.rewards,
cov.rollbacks,
cov.menus_opened,
cov.distinct_addresses,
cov.uncaptured,
cov.maps,
cov.scenes,
cov.read_time.as_secs_f64() * 1e6 / cov.reads.max(1) as f64,
cov.digest_time.as_secs_f64() * 1e6 / cov.frames.div_ceil(64).max(1) as f64,
diff.count,
started.elapsed().as_secs_f64(),
);
for line in &diff.first {
eprintln!("{line}");
}
if diff.count > 0 {
failures.push(format!("{label}: {} mismatches", diff.count));
}
if cov.uncaptured > 0 {
failures.push(format!("{label}: {} reads outside the captured ranges", cov.uncaptured));
}
all_scenes.extend(cov.scenes.keys().copied());
all_maps.extend(cov.maps.iter().copied());
read_time += cov.read_time;
reads += cov.reads;
total_frames += cov.frames;
total_answers += cov.answers;
}
if ran == 0 {
eprintln!("skipped: no scenario checkpoint is set (source rom-env.sh)");
return;
}
let mean = read_time.as_secs_f64() / reads.max(1) as f64;
eprintln!(
"total: {ran} scenarios, {total_frames} frames, {total_answers} MacroState answers equal; \
scenes {all_scenes:?}; bulk read {:.1} us mean per boundary = {:.2}% of a {:.2} ms frame; \
{:.2} MB/s of image at {FRAMES_PER_SECOND} fps",
mean * 1e6,
mean * 1e3 / MS_PER_FRAME * 100.0,
MS_PER_FRAME,
MEMORY_IMAGE_LEN as f64 * FRAMES_PER_SECOND / 1e6,
);
assert!(failures.is_empty(), "{failures:#?}");
// The coverage the slice promised, when the full checkpoint set is present.
if ran == SCENARIOS.len() {
for scene in ["overworld", "battle", "menu", "dialog", "shop"] {
assert!(all_scenes.contains(scene), "no {scene} frame in {all_scenes:?}");
}
let centres = [0x29u32, 0x3a, 0x40, 0x44];
assert!(
centres.iter().any(|map| all_maps.contains(map)),
"no Pokemon Center in {all_maps:x?}"
);
}
}
/// The inspection artifact (`gameboy-memory-inspection-v1`, `legacy-gameboy-v1` section 8): an
/// image encodes as exactly its 65,536 bytes in address order, `application/octet-stream`, with
/// an optional SHA-256 digest in the bus `Digest` encoding, and its `romDigest` is the
/// cartridge's. No ROM needed: a synthetic image and cartridge carry the same shapes.
#[test]
fn an_image_encodes_as_the_memory_inspection_artifact() {
use fly_session_types::gameboy::{MEMORY_IMAGE_BYTES, MemoryInspection};
use fly_session_types::workers::AssetRef;
use fly_session_types::ArtifactRef;
use flybrain_gb::MEMORY_IMAGE_CONTENT_TYPE;
assert_eq!(MEMORY_IMAGE_LEN as u64, MEMORY_IMAGE_BYTES);
let bytes: Vec<u8> = (0..MEMORY_IMAGE_LEN).map(|i| ((i * 31) >> 3) as u8).collect();
let image = MemoryImage::from_bytes(&bytes).expect("a full image");
let rom: Vec<u8> = (0..0x8000).map(|i| (i % 251) as u8).collect();
let cartridge = Cartridge::new(&rom);
let memory = ArtifactRef {
store_id: "session".into(),
artifact_id: "inspection-0".into(),
generation: 1,
byte_length: image.as_bytes().len() as u64,
content_type: MEMORY_IMAGE_CONTENT_TYPE.into(),
digest: Some(image.sha256_hex()),
};
let inspection = MemoryInspection { memory, rom_digest: cartridge.sha256_hex() };
let typed = inspection.to_typed();
let back = MemoryInspection::from_typed(&typed).expect("the schema accepts it");
assert_eq!(back, inspection);
let asset = AssetRef {
id: "pokemon-red".into(),
digest: cartridge.sha256_hex(),
byte_length: rom.len() as u64,
format: "gb-rom".into(),
};
back.validate_against(&cartridge.sha256_hex(), &asset).expect("one ROM on all three sides");
// The bytes the artifact carries decode back to the same image.
assert_eq!(MemoryImage::from_bytes(image.as_bytes()).expect("round trip"), image);
// A truncated image is refused by both sides of the seam.
let mut short = inspection.clone();
short.memory.byte_length = MEMORY_IMAGE_BYTES - 1;
assert!(MemoryInspection::from_typed(&short.to_typed()).is_err());
assert!(MemoryImage::from_bytes(&bytes[1..]).is_err());
// Another ROM is refused.
let other = Cartridge::new(&rom[1..]);
assert!(back.validate_against(&other.sha256_hex(), &asset).is_err());
}