diff --git a/services/flysim/Cargo.lock b/services/flysim/Cargo.lock index 25f88d6..aa51bcd 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -440,6 +440,8 @@ name = "fly-session" version = "0.1.1" dependencies = [ "fly-session-types", + "flybrain-core", + "flybrain-gb", "flybus", "serde_json", "tempfile", diff --git a/services/flysim/crates/fly-session/Cargo.toml b/services/flysim/crates/fly-session/Cargo.toml index 25d9a76..579efc1 100644 --- a/services/flysim/crates/fly-session/Cargo.toml +++ b/services/flysim/crates/fly-session/Cargo.toml @@ -23,6 +23,11 @@ path = "src/bin/fly-session.rs" # Everything else this crate needs is std or Tokio. fly-session-types = { path = "../fly-session-types" } flybus = { path = "../flybus" } +# ENV-01: the legacy Game Boy environment worker drives the binjgb emulator through +# flybrain-gb's safe wrapper, and flybrain-core's frozen envelope layout reads and writes the +# world's half of a FLYSIM01 checkpoint. (AGENT-01 adds flybrain-core for the agent as well.) +flybrain-core = { path = "../flybrain-core" } +flybrain-gb = { path = "../flybrain-gb" } serde_json = { workspace = true } # `rt-multi-thread` is not only for the tests: a worker process and a dedicated-thread diff --git a/services/flysim/crates/fly-session/src/legacy_env.rs b/services/flysim/crates/fly-session/src/legacy_env.rs new file mode 100644 index 0000000..be49534 --- /dev/null +++ b/services/flysim/crates/fly-session/src/legacy_env.rs @@ -0,0 +1,1627 @@ +//! ENV-01: the Game Boy compatibility environment worker of the legacy composition. +//! +//! `legacy-gameboy-v1` sections 7 to 9, 11, 14 and 16, and the RT-01a amendments to +//! `workers-v1` (sections 3 and 7), `step-v1` (section 6) and `state-media-v1` (sections 2 to 5). +//! It is the emulator half of flysim's `LegacyFrame`, moved behind the environment methods, and it +//! makes exactly the emulator calls `LegacyFrame` makes, in the same order: +//! +//! | `LegacyFrame` (flysim `frame.rs`) | this worker | +//! | --- | --- | +//! | `initialize`: `run_frame`, framebuffer, `take_audio_u8` (the counter becomes 1) | `Environment.Initialize`: the one-frame setup scaffold, no button down; O[0] with `engineFrame` "1", its audio discarded | +//! | `run` + `take_frame`: `set_buttons(mask)`, `run_frame`, framebuffer, `take_audio_u8` | `Environment.Advance`: the joypad mask of the one port, then O[k+1] with its f32 audio chunk | +//! | `boundary`'s capture: `export_state` + the frame on screen | `Environment.SaveSlot` (`gameboy-slots-v1`) | +//! | `rollback` via `recover_game`: `import_state`, `set_buttons(0)` twice, the slot's frame | `Environment.RestoreSlot` under a new epoch, no frame run | +//! | `restore` from FLYSIM01: `import_state`, `set_buttons(buttons)`, the saved framebuffer | `State.StageRestore` + `State.ActivateRestore` | +//! +//! What the worker adds is only what the contracts ask for and the legacy loop never needed: +//! native audio as `f32le` (`sample / 255`, no filtering: the DC blocker is the edge's), one +//! memory image per boundary as the `gameboy-memory-inspection-v1` inspection, the rational world +//! clock, epochs, batch identity and the capture payload. +//! +//! The joypad is the only write into a running game. `import_state` is a write only on the +//! declared recovery paths (a slot restore and a group restore), exactly as it is in flysim. +//! +//! The memory image is read through [`memory_image`], the one seam MEM-01 replaces with the shim's +//! bulk read. Until then its body is 65,536 `fly_gb_read_mem` calls through the existing +//! `read_uncached`, which is by definition the image `legacy-gameboy-v1` section 8 specifies. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::PathBuf; + +use fly_session_types::extensions::{ + MAX_SLOTS, METHOD_RESTORE_SLOT, METHOD_SAVE_SLOT, RestoreSlotParams, RestoreSlotResult, + SLOTS_CAPABILITY, SaveSlotParams, SaveSlotResult, +}; +use fly_session_types::gameboy::{self, MemoryInspection}; +use flybrain_core::envelope::{decode_envelope, encode_envelope}; +use flybrain_core::json::JsonValue; +use flybrain_gb::emulator::{DEFAULT_AUDIO_FRAMES, Emulator, FRAMEBUFFER_LEN}; +use serde_json::{Value, json}; + +use crate::media::{self, AUDIO_CONTENT_TYPE, FRAME_CONTENT_TYPE}; +// `crate::types` is this crate's facade over the shared `fly-session-types` crate; the +// glob keeps the contract's own names in sight instead of restating them. +use crate::types::*; +use crate::worker::{BoxFuture, HandlerCtx, HandlerReply, StatusCell, WorkerEndpoint}; + +/// The one audio stream: binjgb's stereo mix at the configured rate. +pub const AUDIO_STREAM_ID: &str = "apu"; +/// The attachment the boundary's memory image travels under. +pub const MEMORY_ATTACHMENT: &str = "inspection.memory"; +/// The memory image's content type (`legacy-gameboy-v1` section 8). +pub const MEMORY_CONTENT_TYPE: &str = "application/octet-stream"; +/// The legacy composition declares one slot. +pub const DEFAULT_SLOT: &str = "best"; +/// The legacy port. +pub const DEFAULT_PORT: &str = "p1"; +/// flysim's default `feed.audio_hz`. +pub const DEFAULT_AUDIO_RATE: u64 = 48_000; +/// Stereo. +pub const AUDIO_CHANNELS: u64 = 2; +/// The backend configuration document's form. +pub const BACKEND_CONFIG_FORM: &str = "gameboy-backend-config-v1"; +/// The capture payload's envelope magic: flybrain-core's frozen layout, like FLYSIM01's. +pub const PAYLOAD_MAGIC: &str = "FLYENV01"; +/// The capture payload's layout version. +pub const PAYLOAD_VERSION: u64 = 1; +/// The state format this environment captures under (a participant compatibility identity). +pub const STATE_FORMAT_ID: &str = "fly-gb-env-v1"; +/// The FLYSIM01 magic, for the world's half of a legacy checkpoint. +pub const FLYSIM01_MAGIC: &str = "FLYSIM01"; + +/// The capabilities the worker advertises in `Worker.Hello`. +pub fn capabilities() -> Vec { + vec![ + id("world-step-v1"), + id("pixel-observation-v1"), + id(crate::state::CHECKPOINT_CAPABILITY), + id(SLOTS_CAPABILITY), + ] +} + +// ------------------------------------------------------------------------------------------- +// The emulator seams + +/// The boundary's memory image: byte `i` is `fly_gb_read_mem(i)` (`legacy-gameboy-v1` section 8), +/// read without leaving a trace in the emulator. +/// +/// **The MEM-01 seam.** MEM-01 adds one read-only bulk read to the binjgb shim; when it lands the +/// 65,536 reads below become that one call and nothing else in this worker changes. The interim +/// body is the same function called 65,536 times through the existing `read_uncached`, so the +/// bytes are already the specified ones; the per-frame read cache is neither consulted nor +/// filled. +/// +/// **Why the save and the import.** `emulator_read_mem` is not state-neutral: reading OAM, VRAM, +/// the serial and timer registers, `IF`, `STAT` or `LY` runs binjgb's lazy synchronisation up to +/// the current tick, which changes the bytes `export_state` writes (never, in a 3,199-frame +/// replay, a frame or WRAM). The legacy loop reads none of them between a frame and the ratchet's +/// capture, so a slot saved after an unguarded image read would not be the slot the service +/// saves. The image is therefore read between an `export_state` and an `import_state` of the same +/// bytes, which leaves the emulator exactly as the frame left it (`tests/legacy_env.rs`, +/// `the_memory_image_leaves_the_emulator_as_it_found_it`). +pub fn memory_image(emulator: &mut Emulator) -> Result, String> { + let saved = emulator + .export_state() + .map_err(|e| format!("saving before the image: {e}"))?; + let image = (0..=u16::MAX) + .map(|address| emulator.read_uncached(address)) + .collect(); + emulator + .import_state(&saved) + .map_err(|e| format!("restoring after the image: {e}"))?; + Ok(image) +} + +/// binjgb's unsigned 8-bit interleaved stereo as the declared `f32le-interleaved`, with binjgb's +/// own host rule `sample / 255`: unipolar, silence at exactly 0.0. No filtering; the DC blocker +/// is the edge's presentation state (`legacy-gameboy-v1` section 9). +pub fn audio_f32le(raw: &[u8]) -> Vec { + let mut out = Vec::with_capacity(raw.len() * 4); + for &sample in raw { + let value = f32::from(sample) / flybrain_gb::emulator::AUDIO_FULL_SCALE; + out.extend_from_slice(&value.to_le_bytes()); + } + out +} + +/// The legacy mask of one complete port control: bit `i` is `GAMEBOY_BUTTONS[i]`, which is +/// `flybrain_gb::emulator::buttons`' order (`legacy-gameboy-v1` sections 6 and 7). +pub fn mask_of(control: &PortControl) -> u8 { + control + .buttons + .iter() + .enumerate() + .filter(|(_, button)| button.down) + .fold(0u8, |mask, (bit, _)| mask | (1u8 << bit)) +} + +/// The complete port control for a legacy mask. +pub fn control_of(port_id: &str, mask: u8) -> PortControl { + PortControl { + port_id: port_id.to_owned(), + buttons: gameboy::GAMEBOY_BUTTONS + .iter() + .enumerate() + .map(|(bit, button)| ButtonState { + id: (*button).to_owned(), + down: mask & (1u8 << bit) != 0, + }) + .collect(), + axes: Vec::new(), + } +} + +/// `ControllerSchema {schema: gameboy-joypad-v1, buttons: [up, down, left, right, a, b, start, +/// select], axes: []}` (`legacy-gameboy-v1` section 7). +pub fn joypad_schema() -> ControllerSchema { + ControllerSchema { + schema: gameboy::JOYPAD.schema_ref(), + buttons: gameboy::GAMEBOY_BUTTONS + .iter() + .map(|b| (*b).to_owned()) + .collect(), + axes: Vec::new(), + } +} + +/// The `lcd` view: 160 x 144 `rgba8`, row stride 640, no render delay. +pub fn view_descriptor() -> ViewDescriptor { + ViewDescriptor { + view_id: gameboy::VIEW_ID.to_owned(), + width: gameboy::VIEW_WIDTH, + height: gameboy::VIEW_HEIGHT, + row_stride: gameboy::VIEW_WIDTH * 4, + pixel_aspect_numerator: 1, + pixel_aspect_denominator: 1, + observation_delay_steps: 0, + } +} + +/// The `apu` stream at `sample_rate`, stereo. +pub fn audio_descriptor(sample_rate: u64) -> AudioDescriptor { + AudioDescriptor { + stream_id: id(AUDIO_STREAM_ID), + sample_rate, + channels: AUDIO_CHANNELS, + } +} + +/// The backend identity: the vendored binjgb core behind flybrain-gb's shim, with the size of its +/// save state on this target (an ABI-dependent layout a state is only valid under). +pub fn backend_digest() -> Digest { + digest_of_bytes( + format!( + "fly-session/gameboy-backend-v1\nbinjgb+flybrain-gb-shim\nstateBytes={}\n", + Emulator::state_size() + ) + .as_bytes(), + ) +} + +// ------------------------------------------------------------------------------------------- +// The backend configuration + +/// `gameboy-backend-config-v1`: everything about the backend that is identity. The cartridge is +/// named by digest, never by path; the setup scaffold, the slots and the audio configuration are +/// the composition's `environment` block. Its canonical bytes are the `backendConfig` AssetRef. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BackendConfig { + /// SHA-256 of the cartridge: the environment's `contentDigest` and the executor's `rom`. + pub rom_digest: Digest, + pub port_id: Id, + pub slots: Vec, + pub audio_sample_rate: u64, + /// binjgb's audio buffer, in stereo frames (flysim: `DEFAULT_AUDIO_FRAMES`). + pub audio_buffer_frames: u64, + /// The declared setup scaffold. The legacy composition declares exactly one frame. + pub setup_frames: u64, +} + +impl BackendConfig { + /// The legacy composition's configuration for a cartridge. + pub fn legacy(rom_digest: &str) -> BackendConfig { + BackendConfig { + rom_digest: rom_digest.to_owned(), + port_id: id(DEFAULT_PORT), + slots: vec![id(DEFAULT_SLOT)], + audio_sample_rate: DEFAULT_AUDIO_RATE, + audio_buffer_frames: u64::from(DEFAULT_AUDIO_FRAMES), + setup_frames: gameboy::SETUP_FRAMES, + } + } + + pub fn to_json(&self) -> Value { + json!({ + "form": BACKEND_CONFIG_FORM, + "romDigest": self.rom_digest, + "portId": self.port_id, + "slots": self.slots, + "audio": { + "sampleRate": self.audio_sample_rate, + "channels": AUDIO_CHANNELS, + "bufferFrames": self.audio_buffer_frames, + }, + "setupFrames": self.setup_frames, + "view": gameboy::VIEW_ID, + "controllerSchema": gameboy::JOYPAD.id, + "inspectionSchema": gameboy::MEMORY_INSPECTION.id, + }) + } + + /// The canonical bytes (RFC 8785) the AssetRef digests. + pub fn canonical_bytes(&self) -> Vec { + canonicalize(&self.to_json()) + .expect("a backend configuration canonicalizes") + .into_bytes() + } + + pub fn asset_ref(&self) -> AssetRef { + let bytes = self.canonical_bytes(); + AssetRef { + id: id("gameboy-backend-config"), + digest: digest_of_bytes(&bytes), + byte_length: bytes.len() as u64, + format: id(BACKEND_CONFIG_FORM), + } + } + + /// Refuses a configuration this worker cannot be: another scaffold, no slot or too many, an + /// audio configuration binjgb cannot run, a malformed digest. + pub fn validate(&self) -> Result<(), String> { + if !is_digest(&self.rom_digest) { + return Err("romDigest must be 64 lowercase hex digits".to_owned()); + } + if !is_id(&self.port_id) { + return Err("portId is not an Id".to_owned()); + } + if self.setup_frames != gameboy::SETUP_FRAMES { + return Err(format!( + "the legacy composition declares a setup scaffold of exactly {} frame, not {}", + gameboy::SETUP_FRAMES, + self.setup_frames + )); + } + if self.slots.is_empty() || self.slots.len() > MAX_SLOTS { + return Err(format!("1..={MAX_SLOTS} slots")); + } + let unique: BTreeSet<&Id> = self.slots.iter().collect(); + if unique.len() != self.slots.len() || self.slots.iter().any(|s| !is_id(s)) { + return Err("slots must be unique Ids".to_owned()); + } + if !(8_000..=192_000).contains(&self.audio_sample_rate) { + return Err("audio sampleRate must be 8000..=192000".to_owned()); + } + if self.audio_buffer_frames == 0 || self.audio_buffer_frames > u64::from(u32::MAX) { + return Err("audio bufferFrames must be a positive u32".to_owned()); + } + Ok(()) + } +} + +/// What one environment worker is started with. Everything crosses a process boundary as argv. +#[derive(Clone, Debug)] +pub struct LegacyEnvironmentConfig { + pub session_id: Id, + pub worker_id: Id, + pub incarnation_id: Id, + pub worker_threads: usize, + /// Where the cartridge is. Read-only, outside the checkout; never identity. + pub rom_path: PathBuf, + /// The backend this worker is: `Environment.Initialize` must name exactly this document, and + /// the cartridge at `rom_path` must be the one it names. + pub backend: BackendConfig, +} + +// ------------------------------------------------------------------------------------------- +// World state: what a capture carries + +/// One slot: the emulator's exported state and the frame that was on screen, as the ratchet's +/// `Snapshot` holds them, plus the boundary it was saved at. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SlotState { + pub game: Vec, + pub frame: Vec, + pub boundary: u64, +} + +/// The world at one committed boundary, as data. `State.Capture` encodes it, `State.StageRestore` +/// decodes it, and [`WorldState::from_flysim01`] / [`WorldState::flysim01_chunks`] convert its +/// FLYSIM01 half. +#[derive(Clone, Debug, PartialEq)] +pub struct WorldState { + pub rom_digest: Digest, + pub episode_id: Id, + pub boundary: u64, + pub world_time: RationalNs, + /// The legacy frame counter: `engineFrame`, FLYSIM01's `emulatorFrame`. + pub engine_frame: u64, + /// The mask on the joypad (FLYSIM01's `buttons`). + pub buttons: u8, + pub emulator: Vec, + /// The frame on screen: the last one produced, or a restored slot's. + pub framebuffer: Vec, + /// Declared slots in composition order; a slot never saved is absent. + pub slots: Vec<(Id, SlotState)>, + /// Where the next audio chunk starts, relative to the episode's audio origin. + pub audio_next_sample: u64, +} + +/// The header of a capture payload: whose, which checkpoint, which boundary, which backend. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PayloadHeader { + pub worker_id: Id, + pub checkpoint_id: Id, + pub source_scope: Scope, + /// The backend configuration digest the world ran under. + pub configuration_digest: Digest, +} + +/// The FLYSIM01 fields the world owns: the manifest scalars and the four chunks +/// (`crates/flysim/src/store.rs`: `romHash`, `emulatorFrame`, `buttons`; `emulator`, +/// `framebuffer`, `ratchetGame`, `ratchetFrame`). The agent's half is `agent_to_chunks`; the +/// task's is the adapter and ratchet state. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Flysim01World { + pub rom_hash: String, + pub emulator_frame: u64, + pub buttons: u32, + pub emulator: Vec, + pub framebuffer: Vec, + pub ratchet_game: Vec, + pub ratchet_frame: Vec, +} + +fn slot_chunk_names(index: usize) -> (String, String) { + let letter = (b'A' + index as u8) as char; + (format!("slotGame{letter}"), format!("slotFrame{letter}")) +} + +fn to_core_json(value: &Value) -> JsonValue { + JsonValue::parse(&value.to_string()).expect("serde_json output is JSON") +} + +fn from_core_json(value: &JsonValue) -> Result { + serde_json::from_str(&value.stringify()).map_err(|e| format!("manifest: {e}")) +} + +impl WorldState { + /// The world at the boundary `k = emulatorFrame - setupFrames` of a legacy checkpoint. + /// + /// FLYSIM01 carries the emulator, the frame on screen, the joypad, the frame counter and the + /// ratchet's one slot, which is the composition's slot `best`. It carries no boundary number, + /// world clock or audio position, because the legacy loop has none; they are derived from the + /// frame counter, which advances exactly once per transition and never across a rollback, so + /// `engineFrame = k + 1` holds for a legacy run from its fresh start on. The audio position is + /// the sample of `worldTime` at the configured rate, rounded down; the first chunk after the + /// restore marks the discontinuity, so no continuity is claimed across it. + pub fn from_flysim01( + bytes: &[u8], + episode_id: &Id, + slot_id: &Id, + audio_sample_rate: u64, + ) -> Result { + let world = Flysim01World::decode(bytes)?; + world.into_state(episode_id, slot_id, audio_sample_rate) + } + + /// The world's half of a FLYSIM01 export: the composition's first slot is the ratchet's. + pub fn flysim01_chunks(&self, slot_id: &Id) -> Flysim01World { + let slot = self + .slots + .iter() + .find(|(id, _)| id == slot_id) + .map(|(_, s)| s); + Flysim01World { + rom_hash: self.rom_digest.clone(), + emulator_frame: self.engine_frame, + buttons: u32::from(self.buttons), + emulator: self.emulator.clone(), + framebuffer: self.framebuffer.clone(), + ratchet_game: slot.map(|s| s.game.clone()).unwrap_or_default(), + ratchet_frame: slot.map(|s| s.frame.clone()).unwrap_or_default(), + } + } + + /// Encodes the capture payload: flybrain-core's envelope with [`PAYLOAD_MAGIC`], the scalars + /// in the manifest and every byte array as a chunk. + pub fn encode(&self, header: &PayloadHeader) -> Vec { + let slots: Vec = self + .slots + .iter() + .map( + |(slot_id, slot)| json!({"slotId": slot_id, "boundary": slot.boundary.to_string()}), + ) + .collect(); + let manifest = json!({ + "payloadVersion": PAYLOAD_VERSION, + "kind": "gameboy-environment", + "workerId": header.worker_id, + "checkpointId": header.checkpoint_id, + "sourceScope": header.source_scope.to_json(), + "configurationDigest": header.configuration_digest, + "romDigest": self.rom_digest, + "episodeId": self.episode_id, + "committedStep": self.boundary.to_string(), + "worldTime": self.world_time.to_json(), + "engineFrame": self.engine_frame.to_string(), + "buttons": self.buttons, + "audioNextSample": self.audio_next_sample.to_string(), + "slots": slots, + }); + let mut chunks = vec![ + ("emulator".to_owned(), self.emulator.clone()), + ("framebuffer".to_owned(), self.framebuffer.clone()), + ]; + for (index, (_, slot)) in self.slots.iter().enumerate() { + let (game, frame) = slot_chunk_names(index); + chunks.push((game, slot.game.clone())); + chunks.push((frame, slot.frame.clone())); + } + encode_envelope(PAYLOAD_MAGIC, &to_core_json(&manifest), &chunks) + .expect("letter-only chunk names and an ASCII magic encode") + } + + /// Decodes a capture payload. Shapes are checked here; identities by the caller. + pub fn decode(bytes: &[u8]) -> Result<(PayloadHeader, WorldState), String> { + let parts = decode_envelope(bytes, PAYLOAD_MAGIC).map_err(|e| e.to_string())?; + let manifest = from_core_json(&parts.manifest)?; + let text = |key: &str| -> Result { + manifest + .get(key) + .and_then(Value::as_str) + .map(str::to_owned) + .ok_or_else(|| format!("the world payload has no {key}")) + }; + let number = |key: &str| -> Result { + text(key)? + .parse::() + .map_err(|_| format!("the world payload's {key} is not a U64")) + }; + if manifest.get("payloadVersion").and_then(Value::as_u64) != Some(PAYLOAD_VERSION) { + return Err("the world payload is another payload version".to_owned()); + } + if text("kind")? != "gameboy-environment" { + return Err("this payload is not a Game Boy world's state".to_owned()); + } + let chunk = |name: &str| -> Result, String> { + parts + .chunk(name) + .map(<[u8]>::to_vec) + .ok_or_else(|| format!("the world payload has no {name} chunk")) + }; + let source_scope = Scope::from_json( + manifest + .get("sourceScope") + .ok_or("the world payload has no sourceScope")?, + ) + .map_err(|e| format!("sourceScope: {}", e.0))?; + let world_time = RationalNs::from_json( + manifest + .get("worldTime") + .ok_or("the world payload has no worldTime")?, + ) + .map_err(|e| format!("worldTime: {}", e.0))?; + let buttons = manifest + .get("buttons") + .and_then(Value::as_u64) + .and_then(|b| u8::try_from(b).ok()) + .ok_or("the world payload's buttons are not a mask")?; + let slot_list = manifest + .get("slots") + .and_then(Value::as_array) + .ok_or("the world payload has no slot list")?; + if slot_list.len() > MAX_SLOTS { + return Err(format!( + "the world payload holds more than {MAX_SLOTS} slots" + )); + } + let mut slots = Vec::with_capacity(slot_list.len()); + for (index, entry) in slot_list.iter().enumerate() { + let slot_id = entry + .get("slotId") + .and_then(Value::as_str) + .ok_or("a captured slot has no slotId")?; + let slot_id = parse_id(slot_id)?; + let boundary = entry + .get("boundary") + .and_then(Value::as_str) + .and_then(|b| b.parse::().ok()) + .ok_or("a captured slot has no boundary")?; + let (game, frame) = slot_chunk_names(index); + let slot = SlotState { + game: chunk(&game)?, + frame: chunk(&frame)?, + boundary, + }; + if slot.frame.len() != FRAMEBUFFER_LEN { + return Err(format!( + "slot {slot_id}'s frame is not {FRAMEBUFFER_LEN} bytes" + )); + } + slots.push((slot_id, slot)); + } + let framebuffer = chunk("framebuffer")?; + if framebuffer.len() != FRAMEBUFFER_LEN { + return Err(format!("the framebuffer is not {FRAMEBUFFER_LEN} bytes")); + } + let header = PayloadHeader { + worker_id: parse_id(&text("workerId")?)?, + checkpoint_id: parse_id(&text("checkpointId")?)?, + source_scope, + configuration_digest: text("configurationDigest")?, + }; + let state = WorldState { + rom_digest: text("romDigest")?, + episode_id: parse_id(&text("episodeId")?)?, + boundary: number("committedStep")?, + world_time, + engine_frame: number("engineFrame")?, + buttons, + emulator: chunk("emulator")?, + framebuffer, + slots, + audio_next_sample: number("audioNextSample")?, + }; + Ok((header, state)) + } +} + +/// The world time of boundary `k`: `k x stepDuration`, exactly. +pub fn world_time_at(boundary: u64) -> Result { + let step = gameboy::step_duration(); + RationalNs::reduced( + u128::from(step.numerator) * u128::from(boundary), + u128::from(step.denominator), + ) + .map_err(|e| e.0) +} + +/// The sample of `world_time` at `rate`, rounded down. +pub fn sample_at(world_time: &RationalNs, rate: u64) -> u64 { + let numerator = u128::from(world_time.numerator) * u128::from(rate); + let denominator = u128::from(world_time.denominator) * 1_000_000_000u128; + (numerator / denominator) as u64 +} + +impl Flysim01World { + /// Reads the world's fields of a FLYSIM01 envelope. The agent's chunks and the task's manifest + /// entries are left to their owners. + pub fn decode(bytes: &[u8]) -> Result { + let parts = decode_envelope(bytes, FLYSIM01_MAGIC).map_err(|e| e.to_string())?; + let manifest = &parts.manifest; + let chunk = |name: &str| -> Result, String> { + parts + .chunk(name) + .map(<[u8]>::to_vec) + .ok_or_else(|| format!("checkpoint is missing the {name} chunk")) + }; + let number = |key: &str| -> Result { + manifest + .get(key) + .and_then(JsonValue::as_f64) + .ok_or_else(|| format!("checkpoint manifest is missing {key}")) + }; + Ok(Flysim01World { + rom_hash: manifest + .get("romHash") + .and_then(JsonValue::as_str) + .map(str::to_owned) + .ok_or("checkpoint manifest is missing romHash")?, + emulator_frame: number("emulatorFrame")? as u64, + buttons: number("buttons")? as u32, + emulator: chunk("emulator")?, + framebuffer: chunk("framebuffer")?, + ratchet_game: chunk("ratchetGame")?, + ratchet_frame: chunk("ratchetFrame")?, + }) + } + + /// This world as the environment's state at `k = emulatorFrame - setupFrames`. + pub fn into_state( + self, + episode_id: &Id, + slot_id: &Id, + audio_sample_rate: u64, + ) -> Result { + if self.framebuffer.len() != FRAMEBUFFER_LEN { + return Err(format!( + "checkpoint framebuffer is {} bytes", + self.framebuffer.len() + )); + } + if self.emulator_frame < gameboy::SETUP_FRAMES { + return Err("checkpoint frame counter is before the setup scaffold".to_owned()); + } + let buttons = + u8::try_from(self.buttons).map_err(|_| "checkpoint buttons are not a mask")?; + let boundary = self.emulator_frame - gameboy::SETUP_FRAMES; + let world_time = world_time_at(boundary)?; + let slots = if self.ratchet_game.is_empty() { + Vec::new() + } else { + if self.ratchet_frame.len() != FRAMEBUFFER_LEN { + return Err("the ratchet snapshot has no framebuffer".to_owned()); + } + vec![( + slot_id.clone(), + SlotState { + game: self.ratchet_game, + frame: self.ratchet_frame, + boundary, + }, + )] + }; + Ok(WorldState { + rom_digest: self.rom_hash, + episode_id: episode_id.clone(), + boundary, + audio_next_sample: sample_at(&world_time, audio_sample_rate), + world_time, + engine_frame: self.emulator_frame, + buttons, + emulator: self.emulator, + framebuffer: self.framebuffer, + slots, + }) + } + + /// The manifest entries and chunks this world contributes to a FLYSIM01 export, in + /// `store::encode`'s order. The caller merges them with the agent's and the task's. + pub fn manifest_entries(&self) -> Vec<(&'static str, JsonValue)> { + vec![ + ("romHash", self.rom_hash.as_str().into()), + ("emulatorFrame", (self.emulator_frame as f64).into()), + ("buttons", f64::from(self.buttons).into()), + ] + } + + pub fn chunks(&self) -> Vec<(String, Vec)> { + vec![ + ("emulator".to_owned(), self.emulator.clone()), + ("framebuffer".to_owned(), self.framebuffer.clone()), + ("ratchetGame".to_owned(), self.ratchet_game.clone()), + ("ratchetFrame".to_owned(), self.ratchet_frame.clone()), + ] + } +} + +// ------------------------------------------------------------------------------------------- +// The worker + +/// The live world: an emulator at a committed boundary. +struct Live { + emulator: Emulator, + epoch: Id, + episode_id: Id, + descriptor: EnvironmentDescriptor, + boundary: u64, + world_time: RationalNs, + engine_frame: u64, + buttons: u8, + framebuffer: Vec, + slots: BTreeMap, + /// Batch ids applied in this epoch. + batches: BTreeSet, + audio_next_sample: u64, + /// The next chunk starts a new timeline: after a slot restore or a group restore. + audio_discontinuity: bool, +} + +/// A validated replacement world the live session cannot see yet, on a stopped emulator of its +/// own (`state-media-v1` section 5: "stage a stopped replacement emulator"). +struct Staged { + token: Id, + checkpoint_id: Id, + scope: Scope, + emulator: Emulator, + state: WorldState, + descriptor: EnvironmentDescriptor, +} + +/// The Game Boy environment endpoint. +pub struct LegacyGameboyEnvironment { + config: LegacyEnvironmentConfig, + status: StatusCell, + live: Option, + staged: Option, + activated: BTreeSet, +} + +fn incompatible(message: impl std::fmt::Display) -> DomainError { + DomainError::before(ErrorCode::IncompatibleState, message) +} + +fn backend_failure(message: impl std::fmt::Display) -> DomainError { + DomainError::new( + ErrorCode::BackendFailure, + message, + MutationCertainty::Applied, + ) +} + +impl LegacyGameboyEnvironment { + pub fn new(config: LegacyEnvironmentConfig) -> LegacyGameboyEnvironment { + LegacyGameboyEnvironment { + config, + status: StatusCell::new(), + live: None, + staged: None, + activated: BTreeSet::new(), + } + } + + pub fn status(&self) -> StatusCell { + self.status.clone() + } + + /// The descriptor this worker advertises: built from its launch configuration alone, so a + /// replacement computes the same one before it has run a frame. + pub fn descriptor_for(backend: &BackendConfig) -> EnvironmentDescriptor { + EnvironmentDescriptor { + backend_digest: backend_digest(), + content_digest: backend.rom_digest.clone(), + configuration_digest: backend.asset_ref().digest, + step_duration: gameboy::step_duration(), + ports: vec![PortDescriptor { + port_id: backend.port_id.clone(), + controls: joypad_schema(), + }], + inspection_schema: gameboy::MEMORY_INSPECTION.schema_ref(), + views: vec![view_descriptor()], + audio: vec![audio_descriptor(backend.audio_sample_rate)], + recovery: Recovery::ExactCheckpoint, + determinism: Determinism::FixedBuild, + } + } + + fn build_descriptor(&self) -> DomainResult { + self.config + .backend + .validate() + .map_err(|e| incompatible(format!("this worker's backend configuration: {e}")))?; + let descriptor = LegacyGameboyEnvironment::descriptor_for(&self.config.backend); + descriptor.validate().map_err(DomainError::invalid)?; + Ok(descriptor) + } + + /// The participant compatibility digest of a capture: the descriptor's identities under this + /// worker's own state format. + pub fn compatibility_digest(descriptor: &EnvironmentDescriptor) -> Digest { + crate::state::Compatibility { + state_format_id: id(STATE_FORMAT_ID), + ..crate::state::Compatibility::of(descriptor) + } + .digest() + } + + /// Boots the configured cartridge, refusing one that is not the cartridge the backend + /// configuration names. Nothing has run on the emulator it returns. + fn boot(&self) -> DomainResult { + let rom = std::fs::read(&self.config.rom_path).map_err(|e| { + DomainError::before( + ErrorCode::BackendFailure, + format!("the cartridge could not be read: {e}"), + ) + })?; + let actual = digest_of_bytes(&rom); + if actual != self.config.backend.rom_digest { + return Err(incompatible(format!( + "the cartridge is {actual}, not the {} this backend configuration names", + self.config.backend.rom_digest + ))); + } + let emulator = Emulator::new( + &rom, + self.config.backend.audio_sample_rate as u32, + self.config.backend.audio_buffer_frames as u32, + ) + .map_err(|e| DomainError::before(ErrorCode::BackendFailure, format!("booting: {e}")))?; + if emulator.audio_frequency() as u64 != self.config.backend.audio_sample_rate { + return Err(incompatible(format!( + "binjgb runs its audio at {} Hz, not the configured {}", + emulator.audio_frequency(), + self.config.backend.audio_sample_rate + ))); + } + Ok(emulator) + } + + fn check_session(&self, scope: &Scope) -> DomainResult<()> { + if scope.session_id != self.config.session_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "this environment belongs to another session", + )); + } + Ok(()) + } + + /// The live world at exactly the scope's epoch and boundary. + fn live_at(&mut self, scope: &Scope, what: &str) -> DomainResult<&mut Live> { + self.check_session(scope)?; + let live = self.live.as_mut().ok_or_else(|| { + DomainError::before(ErrorCode::InvalidPhase, "this environment is uninitialized") + })?; + if live.epoch != scope.epoch { + return Err(DomainError::before( + ErrorCode::StaleEpoch, + format!("{what} names an epoch this environment is not in"), + )); + } + if scope.step != live.boundary { + return Err(DomainError::before( + if scope.step < live.boundary { + ErrorCode::StaleStep + } else { + ErrorCode::FutureStep + }, + format!("{what} must name the boundary the world is at"), + )); + } + Ok(live) + } + + /// The observation of the live world: the frame on screen as one immutable artifact (sensory + /// and broadcast), the memory image read now, and the audio chunk of the interval just run, + /// if there was one. + async fn observation( + live: &mut Live, + client: &flybus::Client, + audio: Option>, + ) -> DomainResult<(WorldObservation, Vec<(String, flybus::Artifact)>)> { + let frame = + media::seal_copy(client, FRAME_CONTENT_TYPE.to_owned(), &live.framebuffer).await?; + let image = memory_image(&mut live.emulator).map_err(backend_failure)?; + let memory = media::seal_copy(client, MEMORY_CONTENT_TYPE.to_owned(), &image).await?; + let view = ViewRef { + view_id: gameboy::VIEW_ID.to_owned(), + produced_step: live.boundary, + pixels: frame.reference().clone(), + }; + let inspection = MemoryInspection { + memory: memory.reference().clone(), + rom_digest: live.descriptor.content_digest.clone(), + } + .to_typed(); + let mut attachments = vec![ + (media::view_attachment(gameboy::VIEW_ID), frame), + (MEMORY_ATTACHMENT.to_owned(), memory), + ]; + let mut chunks = Vec::new(); + if let Some(raw) = audio { + if raw.len() % AUDIO_CHANNELS as usize != 0 { + return Err(backend_failure("binjgb returned half a stereo frame")); + } + let frames = (raw.len() / AUDIO_CHANNELS as usize) as u64; + let samples = + media::seal_copy(client, AUDIO_CONTENT_TYPE.to_owned(), &audio_f32le(&raw)).await?; + chunks.push(AudioRef { + stream_id: id(AUDIO_STREAM_ID), + first_sample: live.audio_next_sample, + sample_frames: frames, + samples: samples.reference().clone(), + discontinuity: live.audio_discontinuity, + }); + attachments.push((media::audio_attachment(AUDIO_STREAM_ID), samples)); + live.audio_next_sample = live + .audio_next_sample + .checked_add(frames) + .ok_or_else(|| backend_failure("the audio position overflows"))?; + live.audio_discontinuity = false; + } + let observation = WorldObservation { + boundary: live.boundary, + world_time: live.world_time, + engine_frame: Some(live.engine_frame.to_string()), + sensory_views: vec![view.clone()], + inspection, + broadcast_views: vec![view], + audio: chunks, + }; + observation + .validate_against(&live.descriptor) + .map_err(|e| { + backend_failure(format!( + "the observation does not fit the descriptor: {}", + e.0 + )) + })?; + Ok((observation, attachments)) + } + + // -- Environment.Initialize -------------------------------------------------------------- + + async fn initialize(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + self.check_session(&scope)?; + if self.live.is_some() || self.staged.is_some() { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + "this environment is already initialized", + )); + } + if scope.step != 0 { + return Err(DomainError::before( + ErrorCode::FutureStep, + "Environment.Initialize uses the new epoch at step 0", + )); + } + let params: EnvironmentInitializeParams = ctx.params()?; + let descriptor = self.build_descriptor()?; + let own = self.config.backend.asset_ref(); + if params.backend_config != own { + return Err(incompatible(format!( + "Environment.Initialize names the backend configuration {}, and this worker is {}", + params.backend_config.digest, own.digest + ))); + } + match params.port_bindings.as_slice() { + [(port_id, _agent)] if *port_id == self.config.backend.port_id => {} + _ => { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + format!( + "the legacy composition binds exactly one port, {}", + self.config.backend.port_id + ), + )); + } + } + let mut emulator = self.boot()?; + // The declared setup scaffold: one frame with no button down, attributed to no fly + // (`LegacyFrame::initialize`). Its audio is not published; the audio origin is the first + // sample of transition 0 -> 1. + emulator + .run_frame() + .map_err(|e| backend_failure(format!("running the setup frame: {e}")))?; + let framebuffer = emulator.framebuffer().to_vec(); + let _setup_audio = emulator.take_audio_u8(); + let mut live = Live { + emulator, + epoch: scope.epoch.clone(), + episode_id: params.episode_id.clone(), + descriptor: descriptor.clone(), + boundary: 0, + world_time: RationalNs::ZERO, + engine_frame: gameboy::SETUP_FRAMES, + buttons: 0, + framebuffer, + slots: BTreeMap::new(), + batches: BTreeSet::new(), + audio_next_sample: 0, + audio_discontinuity: false, + }; + let (observation, attachments) = + LegacyGameboyEnvironment::observation(&mut live, ctx.client, None).await?; + self.live = Some(live); + // The world is stopped when O[0] goes out and cannot free-run while the brain warms up. + self.status.set_state(WorkerState::Ready); + self.status.set_scope(Some(scope)); + self.status.progress(1); + let result = EnvironmentInitializeResult { + descriptor, + observation, + }; + let mut reply = HandlerReply::from(&result); + reply.artifacts = attachments; + Ok(reply) + } + + // -- Environment.Advance ----------------------------------------------------------------- + + async fn advance(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + let params: AdvanceParams = ctx.params()?; + let status = self.status.clone(); + let live = self.live_at(&scope, "Environment.Advance")?; + if live.batches.contains(¶ms.batch_id) { + return Err(DomainError::before( + ErrorCode::Conflict, + format!( + "batch {} was already applied in this epoch", + params.batch_id + ), + )); + } + // One complete batch: the one port, every button in descriptor order, no axes. + match params.controls.as_slice() { + [control] if control.port_id == live.descriptor.ports[0].port_id => { + control + .validate_against(&live.descriptor.ports[0].controls) + .map_err(|e| DomainError::invalid(e.0))?; + } + _ => { + return Err(DomainError::invalid(format!( + "the batch must hold exactly one control, for port {}", + live.descriptor.ports[0].port_id + ))); + } + } + let mask = mask_of(¶ms.controls[0]); + let digest = controls_digest(¶ms.controls); + let applied_from = live.boundary; + + // `LegacyFrame::run` and `take_frame`: the joypad, one frame, the frame it drew, its audio. + live.buttons = mask; + live.emulator.set_buttons(mask); + live.emulator + .run_frame() + .map_err(|e| backend_failure(format!("frame {}: {e}", live.engine_frame + 1)))?; + live.engine_frame += 1; + live.framebuffer + .copy_from_slice(live.emulator.framebuffer()); + let audio = live.emulator.take_audio_u8(); + live.boundary += 1; + live.world_time = live + .world_time + .checked_add(&live.descriptor.step_duration) + .map_err(|e| backend_failure(e.0))?; + live.batches.insert(params.batch_id.clone()); + status.set_batch(params.batch_id.clone()); + status.set_scope(Some(scope_at( + &scope.session_id, + &scope.epoch, + live.boundary, + ))); + status.progress(1); + + let (observation, attachments) = + LegacyGameboyEnvironment::observation(live, ctx.client, Some(audio)).await?; + let result = StepResult { + batch_id: params.batch_id, + applied_from_step: applied_from, + next_step: live.boundary, + applied_controls_digest: digest, + observation, + }; + let mut reply = HandlerReply::from(&result); + reply.artifacts = attachments; + Ok(reply) + } + + // -- gameboy-slots-v1 -------------------------------------------------------------------- + + async fn save_slot(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + let params: SaveSlotParams = ctx.params()?; + let declared = self.config.backend.slots.contains(¶ms.slot_id); + let status = self.status.clone(); + let live = self.live_at(&scope, METHOD_SAVE_SLOT)?; + if !declared { + return Err(DomainError::invalid(format!( + "slot {} is not a slot this composition declares", + params.slot_id + ))); + } + status.set_state(WorkerState::Capturing); + // The ratchet's capture: the exported state and the frame on screen. + let game = live.emulator.export_state().map_err(|e| { + status.set_state(WorkerState::Ready); + DomainError::before( + ErrorCode::BackendFailure, + format!("exporting the state: {e}"), + ) + })?; + let result = SaveSlotResult { + slot_id: params.slot_id.clone(), + boundary: live.boundary, + state_digest: digest_of_bytes(&game), + byte_length: game.len() as u64, + }; + live.slots.insert( + params.slot_id, + SlotState { + game, + frame: live.framebuffer.clone(), + boundary: live.boundary, + }, + ); + status.set_state(WorkerState::Ready); + status.progress(1); + result + .validate_against_scope(&scope) + .map_err(|e| DomainError::invalid(e.0))?; + Ok(HandlerReply::from(&result)) + } + + async fn restore_slot(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + self.check_session(&scope)?; + let params: RestoreSlotParams = ctx.params()?; + params + .validate_against_scope(&scope) + .map_err(|e| DomainError::invalid(e.0))?; + let status = self.status.clone(); + let prior = scope_at(&scope.session_id, ¶ms.prior_epoch, scope.step); + let live = self.live_at(&prior, METHOD_RESTORE_SLOT)?; + let slot = live.slots.get(¶ms.slot_id).cloned().ok_or_else(|| { + DomainError::before( + ErrorCode::InvalidPhase, + format!("slot {} holds nothing to restore", params.slot_id), + ) + })?; + if slot.frame.len() != FRAMEBUFFER_LEN { + return Err(incompatible("the slot's frame is not a 160x144 RGBA frame")); + } + status.set_state(WorkerState::Restoring); + // `recover_game` then `LegacyFrame::rollback`: import the slot, release every button + // (both calls, as flysim makes them), and the slot's frame is the frame on screen. No + // frame runs. + live.emulator.import_state(&slot.game).map_err(|e| { + DomainError::new( + ErrorCode::BackendFailure, + format!("restoring slot {}: {e}", params.slot_id), + MutationCertainty::Unknown, + ) + })?; + live.emulator.set_buttons(0); + live.framebuffer.copy_from_slice(&slot.frame); + live.buttons = 0; + live.emulator.set_buttons(0); + live.epoch = scope.epoch.clone(); + live.batches.clear(); + live.audio_discontinuity = true; + let (observation, attachments) = + LegacyGameboyEnvironment::observation(live, ctx.client, None).await?; + status.set_state(WorkerState::Ready); + status.set_scope(Some(scope.clone())); + status.progress(1); + let result = RestoreSlotResult { + slot_id: params.slot_id, + committed_step: scope.step, + observation, + }; + result + .validate_against_scope(&scope) + .map_err(|e| DomainError::new(ErrorCode::Internal, e.0, MutationCertainty::Applied))?; + let mut reply = HandlerReply::from(&result); + reply.artifacts = attachments; + Ok(reply) + } + + // -- State.Capture / StageRestore / ActivateRestore -------------------------------------- + + async fn state_capture(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + let params: CaptureParams = ctx.params()?; + let worker_id = self.config.worker_id.clone(); + let slot_order = self.config.backend.slots.clone(); + let status = self.status.clone(); + let live = self.live_at(&scope, "State.Capture")?; + let previous = status.state(); + status.set_state(WorkerState::Capturing); + let emulator = live.emulator.export_state().map_err(|e| { + status.set_state(previous); + DomainError::before( + ErrorCode::BackendFailure, + format!("exporting the state: {e}"), + ) + })?; + let state = WorldState { + rom_digest: live.descriptor.content_digest.clone(), + episode_id: live.episode_id.clone(), + boundary: live.boundary, + world_time: live.world_time, + engine_frame: live.engine_frame, + buttons: live.buttons, + emulator, + framebuffer: live.framebuffer.clone(), + slots: slot_order + .iter() + .filter_map(|slot_id| { + live.slots + .get(slot_id) + .map(|s| (slot_id.clone(), s.clone())) + }) + .collect(), + audio_next_sample: live.audio_next_sample, + }; + let header = PayloadHeader { + worker_id, + checkpoint_id: params.checkpoint_id.clone(), + source_scope: scope.clone(), + configuration_digest: live.descriptor.configuration_digest.clone(), + }; + let bytes = state.encode(&header); + let digest = digest_of_bytes(&bytes); + let artifact = crate::state::seal_payload(ctx.client, &bytes, &digest).await?; + status.set_state(previous); + let result = CaptureResult { + checkpoint_id: params.checkpoint_id, + boundary: live.boundary, + compatibility_digest: LegacyGameboyEnvironment::compatibility_digest(&live.descriptor), + payload: artifact.reference().clone(), + }; + Ok(HandlerReply::with_artifacts( + object(result.to_json()), + vec![(crate::state::PAYLOAD_ATTACHMENT.to_owned(), artifact)], + )) + } + + async fn state_stage_restore(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + self.check_session(&scope)?; + if self.live.is_some() { + // A world already running a boundary is not a quiescent replacement: the group + // replaces it rather than restoring over a live one. + return Err(DomainError::before( + ErrorCode::InvalidPhase, + "State.StageRestore needs an uninitialized replacement environment", + )); + } + if let Some(staged) = &self.staged { + return Err(DomainError::before( + ErrorCode::Conflict, + format!( + "this environment already holds the staged restore {} for checkpoint {}", + staged.token, staged.checkpoint_id + ), + )); + } + let params: StageRestoreParams = ctx.params()?; + if params.source_scope.step != scope.step { + return Err(DomainError::invalid( + "State.StageRestore's scope step must be the source boundary", + )); + } + if params.source_scope.epoch == scope.epoch { + return Err(DomainError::before( + ErrorCode::StaleEpoch, + "State.StageRestore proposes the epoch the checkpoint was captured in", + )); + } + let artifact = ctx.artifact(crate::state::PAYLOAD_ATTACHMENT)?; + if artifact.reference() != ¶ms.payload { + return Err(DomainError::before( + ErrorCode::BufferInvalid, + "the staged payload attachment is not the artifact the request names", + )); + } + let bytes = artifact.read_all().await.map_err(|e| { + DomainError::before( + ErrorCode::BufferInvalid, + format!("the staged payload could not be read: {}", e.message), + ) + })?; + let declared = params + .payload + .digest + .clone() + .ok_or_else(|| incompatible("a checkpoint payload must carry a content digest"))?; + let actual = digest_of_bytes(&bytes); + if actual != declared || bytes.len() as u64 != params.payload.byte_length { + return Err(incompatible( + "the staged payload is not the content the request declares", + )); + } + let (header, state) = WorldState::decode(&bytes).map_err(incompatible)?; + if header.worker_id != self.config.worker_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "the staged payload belongs to another world", + )); + } + if header.checkpoint_id != params.checkpoint_id { + return Err(incompatible( + "the staged payload belongs to another checkpoint", + )); + } + if header.source_scope != params.source_scope || state.boundary != scope.step { + return Err(incompatible( + "the staged payload was captured at another source scope", + )); + } + let descriptor = self.build_descriptor()?; + if header.configuration_digest != descriptor.configuration_digest { + return Err(incompatible( + "the staged world was captured under another backend configuration", + )); + } + if state.rom_digest != descriptor.content_digest { + return Err(incompatible(format!( + "the staged world runs the cartridge {}, not this backend's {}", + state.rom_digest, descriptor.content_digest + ))); + } + let expected = LegacyGameboyEnvironment::compatibility_digest(&descriptor); + if expected != params.compatibility_digest { + return Err(incompatible(format!( + "the staged world's compatibility {expected} is not the {} the restore requires", + params.compatibility_digest + ))); + } + for (slot_id, _) in &state.slots { + if !self.config.backend.slots.contains(slot_id) { + return Err(incompatible(format!("slot {slot_id} is not declared here"))); + } + } + if state.world_time != world_time_at(state.boundary).map_err(incompatible)? { + return Err(incompatible("the staged world clock is not its boundary's")); + } + // Validation that needs a mutation happens on a stopped replacement emulator: the + // import either succeeds there or the live nothing is touched. + let mut emulator = self.boot()?; + emulator + .import_state(&state.emulator) + .map_err(|e| incompatible(format!("the emulator state does not load: {e}")))?; + let token = crate::agent::restore_token( + ¶ms.checkpoint_id, + &scope, + &actual, + &self.config.incarnation_id, + ); + if self.activated.contains(&token) { + return Err(DomainError::before( + ErrorCode::Conflict, + "this exact restore was already activated on this environment", + )); + } + self.staged = Some(Staged { + token: token.clone(), + checkpoint_id: params.checkpoint_id.clone(), + scope, + emulator, + state, + descriptor, + }); + self.status.set_state(WorkerState::StagedRestore); + let result = StageRestoreResult { + checkpoint_id: params.checkpoint_id, + restore_token: token, + }; + Ok(HandlerReply::from(&result)) + } + + /// Installs the staged world and returns its observation: nothing runs, the view is the saved + /// frame, the memory image is read after the import, and there is no audio chunk; the next + /// one marks the discontinuity. The legacy restore's joypad write is repeated here + /// (`LegacyFrame::restore`: `set_buttons(runtime.buttons)`). + async fn state_activate_restore(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let params: ActivateRestoreParams = ctx.params()?; + if self.activated.contains(¶ms.restore_token) { + return Err(DomainError::before( + ErrorCode::Conflict, + "this restore token has already been activated", + )); + } + let Some(staged) = self.staged.take() else { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + "this environment holds no staged restore", + )); + }; + if staged.token != params.restore_token { + let token = staged.token.clone(); + self.staged = Some(staged); + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + format!( + "this environment's staged restore is {token}, not {}", + params.restore_token + ), + )); + } + self.status.set_state(WorkerState::Restoring); + let Staged { + token, + checkpoint_id, + scope, + mut emulator, + state, + descriptor, + } = staged; + emulator.set_buttons(state.buttons); + let mut live = Live { + emulator, + epoch: scope.epoch.clone(), + episode_id: state.episode_id, + descriptor, + boundary: state.boundary, + world_time: state.world_time, + engine_frame: state.engine_frame, + buttons: state.buttons, + framebuffer: state.framebuffer, + slots: state.slots.into_iter().collect(), + batches: BTreeSet::new(), + audio_next_sample: state.audio_next_sample, + audio_discontinuity: true, + }; + let (observation, attachments) = + LegacyGameboyEnvironment::observation(&mut live, ctx.client, None).await?; + self.live = Some(live); + self.activated.insert(token); + self.status.set_state(WorkerState::Ready); + self.status.set_scope(Some(scope.clone())); + let result = ActivateRestoreResult { + committed_step: scope.step, + checkpoint_id, + observation: Some(observation), + }; + result + .validate_for_role(Role::Environment) + .map_err(|e| DomainError::invalid(e.0))?; + let mut reply = HandlerReply::from(&result); + reply.artifacts = attachments; + Ok(reply) + } +} + +impl WorkerEndpoint for LegacyGameboyEnvironment { + fn worker_id(&self) -> Id { + self.config.worker_id.clone() + } + + fn incarnation_id(&self) -> Id { + self.config.incarnation_id.clone() + } + + fn session_id(&self) -> Id { + self.config.session_id.clone() + } + + fn role(&self) -> Role { + Role::Environment + } + + fn capabilities(&self) -> Vec { + capabilities() + } + + fn status_cell(&self) -> StatusCell { + self.status.clone() + } + + fn worker_threads(&self) -> u64 { + self.config.worker_threads as u64 + } + + fn methods(&self) -> Vec<&'static str> { + vec![ + "Environment.Initialize", + "Environment.Advance", + METHOD_SAVE_SLOT, + METHOD_RESTORE_SLOT, + "State.Capture", + "State.StageRestore", + "State.ActivateRestore", + ] + } + + fn handle<'a>(&'a mut self, ctx: HandlerCtx<'a>) -> BoxFuture<'a, DomainResult> { + Box::pin(async move { + match ctx.method { + "Environment.Initialize" => self.initialize(&ctx).await, + "Environment.Advance" => self.advance(&ctx).await, + METHOD_SAVE_SLOT => self.save_slot(&ctx).await, + METHOD_RESTORE_SLOT => self.restore_slot(&ctx).await, + "State.Capture" => self.state_capture(&ctx).await, + "State.StageRestore" => self.state_stage_restore(&ctx).await, + "State.ActivateRestore" => self.state_activate_restore(&ctx).await, + other => Err(DomainError::before( + ErrorCode::Unsupported, + format!("{other} is not a Game Boy environment method"), + )), + } + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_mask_and_the_control_are_one_order() { + for mask in 0..=u8::MAX { + let control = control_of("p1", mask); + control + .validate_against(&joypad_schema()) + .expect("complete"); + assert_eq!(mask_of(&control), mask); + } + // Bit order is flybrain-gb's. + assert_eq!( + mask_of(&control_of("p1", flybrain_gb::emulator::buttons::START)), + 1 << 6 + ); + assert_eq!(gameboy::GAMEBOY_BUTTONS[6], "start"); + } + + #[test] + fn audio_is_sample_over_255_with_silence_at_zero() { + let bytes = audio_f32le(&[0, 255, 51]); + let values: Vec = bytes + .chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect(); + assert_eq!(values, vec![0.0, 1.0, 51.0 / 255.0]); + } + + #[test] + fn the_world_clock_is_the_boundary_times_the_frame() { + assert_eq!(world_time_at(0).unwrap(), RationalNs::ZERO); + let mut acc = RationalNs::ZERO; + for k in 1..=1000u64 { + acc = acc.checked_add(&gameboy::step_duration()).unwrap(); + assert_eq!(world_time_at(k).unwrap(), acc); + } + // 1000 frames at 48 kHz: 16742.68 ms -> 803,649 whole samples. + assert_eq!(sample_at(&world_time_at(1000).unwrap(), 48_000), 803_649); + } + + #[test] + fn the_backend_configuration_refuses_another_scaffold_and_bad_slots() { + let good = BackendConfig::legacy(&"ab".repeat(32)); + good.validate().unwrap(); + let mut two = good.clone(); + two.setup_frames = 2; + assert!(two.validate().unwrap_err().contains("setup scaffold")); + let mut none = good.clone(); + none.slots.clear(); + assert!(none.validate().is_err()); + let mut five = good.clone(); + five.slots = (0..5).map(|i| id(&format!("s{i}"))).collect(); + assert!(five.validate().is_err()); + // The digest moves with every identity field. + let mut rate = good.clone(); + rate.audio_sample_rate = 44_100; + assert_ne!(rate.asset_ref().digest, good.asset_ref().digest); + } + + #[test] + fn the_payload_round_trips_and_the_flysim01_half_is_the_legacy_layout() { + let slot = SlotState { + game: vec![7; 33], + frame: vec![9; FRAMEBUFFER_LEN], + boundary: 41, + }; + let state = WorldState { + rom_digest: "cd".repeat(32), + episode_id: id("ep1"), + boundary: 99, + world_time: world_time_at(99).unwrap(), + engine_frame: 100, + buttons: 0b1001_0000, + emulator: vec![1, 2, 3], + framebuffer: vec![4; FRAMEBUFFER_LEN], + slots: vec![(id("best"), slot.clone())], + audio_next_sample: 12_345, + }; + let header = PayloadHeader { + worker_id: id("world"), + checkpoint_id: id("c1"), + source_scope: scope_at("s", "e1", 99), + configuration_digest: "ef".repeat(32), + }; + let bytes = state.encode(&header); + assert_eq!(WorldState::decode(&bytes).unwrap(), (header, state.clone())); + + // The FLYSIM01 half, through flybrain-core's envelope with flysim's chunk names. + let world = state.flysim01_chunks(&id("best")); + let mut manifest = JsonValue::object(); + for (key, value) in world.manifest_entries() { + manifest.set(key, value); + } + let envelope = encode_envelope(FLYSIM01_MAGIC, &manifest, &world.chunks()).unwrap(); + let back = WorldState::from_flysim01(&envelope, &id("ep1"), &id("best"), 48_000).unwrap(); + assert_eq!(back.boundary, 99); + assert_eq!(back.engine_frame, 100); + assert_eq!(back.buttons, state.buttons); + assert_eq!(back.emulator, state.emulator); + assert_eq!(back.framebuffer, state.framebuffer); + assert_eq!( + back.slots, + vec![( + id("best"), + SlotState { + boundary: 99, + ..slot + } + )] + ); + assert_eq!( + back.audio_next_sample, + sample_at(&world_time_at(99).unwrap(), 48_000) + ); + } +} diff --git a/services/flysim/crates/fly-session/src/legacy_env_parity.rs b/services/flysim/crates/fly-session/src/legacy_env_parity.rs new file mode 100644 index 0000000..f226aae --- /dev/null +++ b/services/flysim/crates/fly-session/src/legacy_env_parity.rs @@ -0,0 +1,1544 @@ +//! ENV-01's parity harness: recorded button inputs, a reference that drives the emulator directly +//! the way flysim's `LegacyFrame` does, the same inputs driven through a launched +//! [`LegacyGameboyEnvironment`] over the bus, and a record-by-record comparison. +//! +//! ```text +//! EnvScript ──> DirectEmulator (flybrain-gb Emulator in LegacyFrame order) ──> Vec +//! ──> EnvDriver (Environment.* / State.* RPCs to a launched worker) ──> Vec +//! └─ compare() ─┘ +//! FlyTrace (FND-01 FLY_TRACE of the running service) ──> replay_trace() through the worker +//! ``` +//! +//! An [`EnvRecord`] is everything both sides can observe of the world at one boundary: the +//! boundary, the engine frame and the world clock, the mask that produced it, the digest of the +//! frame on screen, of the whole 64 KiB memory image and of its WRAM window (the field FND-01's +//! trace records), the audio chunk (position, length, digest of the `f32le` bytes, discontinuity), +//! and at a slot save or a capture the digest of the exported emulator state. Equality of the +//! state digest is equality of every byte binjgb saves: CPU, memory, PPU, APU, timers, joypad. +//! +//! Three sources of recorded inputs: +//! +//! - [`toy_cart`]: a cartridge this module assembles (a few hundred bytes of our own code, no +//! game content) that reads the joypad and folds it into WRAM, VRAM, scroll, palette and a +//! square-wave channel, so frames, memory and audio all depend on the inputs. It runs with no +//! ROM installed; the committed goldens are its records. +//! - a `FLYSIM01` checkpoint with the real cartridge (`FLY_ROM`, rom-env), driven by a seeded +//! button walk with slot saves, rollbacks and a capture/restore; +//! - [`FlyTrace`]: a `FLY_TRACE` written by the running service (FND-01), whose masks and +//! boundary actions are replayed from its start checkpoint, and whose recorded frame, WRAM and +//! slot-state digests the worker must reproduce. This is "legacy fixtures unchanged" measured +//! against the service itself rather than against a transcription of it. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use fly_session_types::extensions::{ + METHOD_RESTORE_SLOT, METHOD_SAVE_SLOT, ROLLBACK_POLICY, RestoreSlotParams, RestoreSlotResult, + SaveSlotParams, SaveSlotResult, +}; +use fly_session_types::gameboy::{self, MemoryInspection}; +use flybrain_gb::emulator::{Emulator, FRAMEBUFFER_LEN}; +use flybus::{Client, Grants, Pattern, Policy, Router, RouterConfig}; +use serde_json::{Value, json}; + +use crate::launcher::{ + ExecutionMode, Launcher, LegacyEnvironmentLaunch, SUPERVISOR_CLIENT, ThreadBudget, Via, +}; +use crate::legacy_env::{ + self, AUDIO_STREAM_ID, BackendConfig, MEMORY_ATTACHMENT, PayloadHeader, SlotState, WorldState, + audio_f32le, control_of, memory_image, world_time_at, +}; +use crate::media::{AudioTimelines, ObservationOrigin, check_required_audio, check_required_views}; +use crate::rpc::{Serials, WorkerRef, call}; +use crate::types::*; + +/// The WRAM window FND-01's trace digests (`crates/flysim/src/trace.rs`). +pub const WRAM: std::ops::RangeInclusive = 0xc000..=0xdfff; + +// ------------------------------------------------------------------------------------------- +// The toy cartridge + +pub mod toy_cart { + //! A 32 KiB cartridge assembled here: our own program, no game content, nothing committed but + //! this code. binjgb runs it without a boot ROM from the post-boot state (LCD on, BG from + //! tile data at `$8000`, map at `$9800`). + //! + //! Once per frame, at the start of vertical blank, it reads the joypad into `$C000`, counts + //! frames in `$C001`, accumulates the pad into `$C002`, scrolls the background by both, writes + //! the accumulator into one byte of tile 0 (which the whole background map shows), sets the + //! palette from the pad, and triggers square channel 1 at a pitch set by the pad whenever a + //! button is down. Frames, memory and audio therefore all depend on the recorded inputs. + + /// The title bytes at `$0134`; a variant changes the last one, so its digest differs. + const TITLE: &[u8] = b"FLYTOYCART"; + + struct Asm { + out: Vec, + } + + impl Asm { + fn here(&self) -> usize { + self.out.len() + } + fn emit(&mut self, bytes: &[u8]) { + self.out.extend_from_slice(bytes); + } + /// `jr cc, target` with `opcode` 0x18 (always), 0x20 (nz) or 0x28 (z). + fn jr_to(&mut self, opcode: u8, target: usize) { + let next = self.here() as i64 + 2; + let offset = target as i64 - next; + assert!((-128..=127).contains(&offset), "jr out of range"); + self.emit(&[opcode, offset as i8 as u8]); + } + /// A forward `jr cc` whose target is patched later; returns the offset byte's index. + fn jr_forward(&mut self, opcode: u8) -> usize { + self.emit(&[opcode, 0]); + self.here() - 1 + } + fn patch_forward(&mut self, at: usize) { + let offset = self.here() as i64 - (at as i64 + 1); + assert!((0..=127).contains(&offset)); + self.out[at] = offset as u8; + } + } + + fn program() -> Vec { + let mut a = Asm { out: Vec::new() }; + a.emit(&[0xf3]); // di + a.emit(&[0x31, 0xfe, 0xff]); // ld sp, $fffe + a.emit(&[0x3e, 0x80, 0xe0, 0x26]); // NR52: sound on + a.emit(&[0x3e, 0x77, 0xe0, 0x24]); // NR50: full volume both sides + a.emit(&[0x3e, 0xff, 0xe0, 0x25]); // NR51: every channel both sides + let wait_vblank = a.here(); + a.emit(&[0xf0, 0x44, 0xfe, 0x90]); // ldh a,[LY]; cp 144 + a.jr_to(0x20, wait_vblank); // jr nz + // The directions, then the buttons, active low. + a.emit(&[0x3e, 0x20, 0xe0, 0x00, 0xf0, 0x00, 0xf0, 0x00]); // select d-pad, read twice + a.emit(&[0x2f, 0xe6, 0x0f, 0xcb, 0x37, 0x47]); // cpl; and $0f; swap a; ld b,a + a.emit(&[0x3e, 0x10, 0xe0, 0x00, 0xf0, 0x00, 0xf0, 0x00]); // select buttons, read twice + a.emit(&[0x2f, 0xe6, 0x0f, 0xb0]); // cpl; and $0f; or b + a.emit(&[0xea, 0x00, 0xc0, 0x47]); // ld [$c000],a; ld b,a + a.emit(&[0x21, 0x01, 0xc0, 0x34]); // ld hl,$c001; inc [hl] + a.emit(&[0xfa, 0x02, 0xc0, 0x80, 0xea, 0x02, 0xc0]); // $c002 += pad + a.emit(&[0xe0, 0x43]); // SCX = accumulator + a.emit(&[0xfa, 0x01, 0xc0, 0xe0, 0x42]); // SCY = frame count + a.emit(&[0xe6, 0x0f, 0x6f, 0x26, 0x80]); // hl = $8000 + (count & 15) + a.emit(&[0xfa, 0x02, 0xc0, 0x77]); // [hl] = accumulator + a.emit(&[0x78, 0xee, 0xe4, 0xe0, 0x47]); // BGP = pad ^ $e4 + a.emit(&[0x78, 0xa7]); // ld a,b; and a + let skip = a.jr_forward(0x28); // jr z, no sound + a.emit(&[0x3e, 0x80, 0xe0, 0x11]); // NR11: 50% duty + a.emit(&[0x3e, 0xf0, 0xe0, 0x12]); // NR12: volume 15, no envelope + a.emit(&[0x78, 0xe0, 0x13]); // NR13: pitch low = pad + a.emit(&[0x3e, 0x87, 0xe0, 0x14]); // NR14: trigger, pitch high 7 + a.patch_forward(skip); + let wait_out = a.here(); + a.emit(&[0xf0, 0x44, 0xfe, 0x90]); // ldh a,[LY]; cp 144 + a.jr_to(0x28, wait_out); // jr z: leave vertical blank first + a.jr_to(0x18, wait_vblank); + a.out + } + + /// The cartridge. `variant` 0 is the one the goldens run; any other is another cartridge + /// with another digest (for the wrong-ROM refusals). + pub fn rom(variant: u8) -> Vec { + let mut rom = vec![0u8; 0x8000]; + rom[0x100..0x104].copy_from_slice(&[0x00, 0xc3, 0x50, 0x01]); // nop; jp $0150 + rom[0x134..0x134 + TITLE.len()].copy_from_slice(TITLE); + rom[0x134 + TITLE.len()] = b'0' + (variant % 10); + rom[0x147] = 0x00; // ROM only + rom[0x148] = 0x00; // 32 KiB + rom[0x149] = 0x00; // no RAM + rom[0x14a] = 0x01; + let program = program(); + rom[0x150..0x150 + program.len()].copy_from_slice(&program); + let mut header = 0u8; + for byte in &rom[0x134..0x14d] { + header = header.wrapping_sub(*byte).wrapping_sub(1); + } + rom[0x14d] = header; + let global: u16 = rom + .iter() + .enumerate() + .filter(|(i, _)| *i != 0x14e && *i != 0x14f) + .fold(0u16, |sum, (_, b)| sum.wrapping_add(u16::from(*b))); + rom[0x14e..0x150].copy_from_slice(&global.to_be_bytes()); + rom + } +} + +// ------------------------------------------------------------------------------------------- +// Scripts and records + +/// One operation of a script, applied at the boundary the world is at. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum EnvOp { + /// One transition with this joypad mask. + Advance(u8), + /// `Environment.SaveSlot` at the committed boundary. + SaveSlot(Id), + /// `Environment.RestoreSlot` under a new epoch (`legacy-ratchet-rollback-v1`). + Rollback(Id), + /// `State.Capture`, then a group restore of that payload into a fresh replacement worker + /// under a new epoch (a restart of the service, `legacy-transient-reset`). + CaptureRestore, +} + +/// Where a script starts. +#[derive(Clone, Debug)] +pub enum EnvStart { + /// `Environment.Initialize`: the one-frame setup scaffold. + Fresh, + /// A `FLYSIM01` checkpoint's world, restored into a fresh worker. + Flysim01(Arc>), +} + +#[derive(Clone, Debug)] +pub struct EnvScript { + pub name: String, + pub start: EnvStart, + pub ops: Vec, +} + +/// One audio chunk as both sides see it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AudioRecord { + pub first_sample: u64, + pub frames: u64, + pub digest: Digest, + pub discontinuity: bool, +} + +/// What both sides observe of the world after one operation. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EnvRecord { + pub index: u64, + pub op: &'static str, + pub boundary: u64, + pub engine_frame: u64, + pub world_time: RationalNs, + pub mask: Option, + pub frame: Digest, + pub memory: Digest, + pub wram: Digest, + pub audio: Option, + /// The exported emulator state: at a slot save, the slot's; at a capture, the world's. + pub state: Option, +} + +impl EnvRecord { + pub fn to_json(&self) -> Value { + json!({ + "index": self.index, + "op": self.op, + "boundary": self.boundary.to_string(), + "engineFrame": self.engine_frame.to_string(), + "worldTime": self.world_time.to_json(), + "mask": self.mask, + "frame": self.frame, + "memory": self.memory, + "wram": self.wram, + "audio": self.audio.as_ref().map(|a| json!({ + "firstSample": a.first_sample.to_string(), + "frames": a.frames, + "digest": a.digest, + "discontinuity": a.discontinuity, + })), + "state": self.state, + }) + } + + pub fn row(&self) -> String { + format!( + "#{} {} k={} f={} mask={:?} frame={} mem={} audio={:?} state={:?}", + self.index, + self.op, + self.boundary, + self.engine_frame, + self.mask, + &self.frame[..12], + &self.memory[..12], + self.audio.as_ref().map(|a| ( + a.first_sample, + a.frames, + a.digest[..12].to_owned(), + a.discontinuity + )), + self.state.as_ref().map(|s| s[..12].to_owned()), + ) + } +} + +/// The first difference between two record lists, or none. +pub fn compare(left: &[EnvRecord], right: &[EnvRecord]) -> Result<(), String> { + for (a, b) in left.iter().zip(right) { + if a != b { + return Err(format!( + "records differ at #{}:\n left: {}\n right: {}", + a.index, + a.row(), + b.row() + )); + } + } + if left.len() != right.len() { + return Err(format!("{} records against {}", left.len(), right.len())); + } + Ok(()) +} + +/// The golden form of a script's records. +pub fn golden_json(script: &EnvScript, records: &[EnvRecord]) -> Value { + json!({ + "format": "fly-session/legacy-env-golden-v1", + "script": script.name, + "records": records.iter().map(EnvRecord::to_json).collect::>(), + }) +} + +async fn read_attachment( + artifacts: &BTreeMap, + op: &str, + name: &str, +) -> Result, String> { + let artifact = artifacts + .get(name) + .ok_or_else(|| format!("{op}: no {name} attachment"))?; + artifact.read_all().await.map_err(|e| e.message) +} + +fn memory_record(image: &[u8]) -> (Digest, Digest) { + (digest_of_bytes(image), digest_of_bytes(&image[WRAM])) +} + +fn audio_record(first_sample: u64, raw_f32: &[u8], discontinuity: bool) -> AudioRecord { + AudioRecord { + first_sample, + frames: (raw_f32.len() / 4 / legacy_env::AUDIO_CHANNELS as usize) as u64, + digest: digest_of_bytes(raw_f32), + discontinuity, + } +} + +// ------------------------------------------------------------------------------------------- +// The direct reference + +/// The emulator driven directly, call for call as flysim's `LegacyFrame` drives it (`initialize`, +/// `run` + `take_frame`, the ratchet's capture, `recover_game` + `rollback`, `restore`), with the +/// session's boundary, clock and audio position kept beside it. +pub struct DirectEmulator { + rom: Arc>, + backend: BackendConfig, + emulator: Emulator, + framebuffer: Vec, + engine_frame: u64, + buttons: u8, + boundary: u64, + world_time: RationalNs, + audio_next: u64, + discontinuity: bool, + slots: BTreeMap, + episode_id: Id, + index: u64, +} + +impl DirectEmulator { + fn boot(rom: &[u8], backend: &BackendConfig) -> Result { + Emulator::new( + rom, + backend.audio_sample_rate as u32, + backend.audio_buffer_frames as u32, + ) + .map_err(|e| e.to_string()) + } + + fn record( + &mut self, + op: &'static str, + mask: Option, + audio: Option, + state: Option, + ) -> EnvRecord { + let image = memory_image(&mut self.emulator).expect("the image reads"); + let (memory, wram) = memory_record(&image); + let record = EnvRecord { + index: self.index, + op, + boundary: self.boundary, + engine_frame: self.engine_frame, + world_time: self.world_time, + mask, + frame: digest_of_bytes(&self.framebuffer), + memory, + wram, + audio, + state, + }; + self.index += 1; + record + } + + /// `LegacyFrame::initialize`: one frame, no button pressed. + pub fn fresh( + rom: Arc>, + backend: BackendConfig, + ) -> Result<(DirectEmulator, EnvRecord), String> { + let mut emulator = DirectEmulator::boot(&rom, &backend)?; + emulator.run_frame().map_err(|e| e.to_string())?; + let framebuffer = emulator.framebuffer().to_vec(); + let _ = emulator.take_audio_u8(); + let mut direct = DirectEmulator { + rom, + backend, + emulator, + framebuffer, + engine_frame: 1, + buttons: 0, + boundary: 0, + world_time: RationalNs::ZERO, + audio_next: 0, + discontinuity: false, + slots: BTreeMap::new(), + episode_id: id("ep1"), + index: 0, + }; + let record = direct.record("initialize", None, None, None); + Ok((direct, record)) + } + + /// `Sim::try_restore` + `LegacyFrame::restore`: a new emulator, `import_state`, + /// `set_buttons(buttons)`, the saved framebuffer, and the ratchet's snapshot. + pub fn from_state( + rom: Arc>, + backend: BackendConfig, + state: WorldState, + index: u64, + ) -> Result<(DirectEmulator, EnvRecord), String> { + let mut emulator = DirectEmulator::boot(&rom, &backend)?; + emulator + .import_state(&state.emulator) + .map_err(|e| e.to_string())?; + emulator.set_buttons(state.buttons); + let mut direct = DirectEmulator { + rom, + backend, + emulator, + framebuffer: state.framebuffer, + engine_frame: state.engine_frame, + buttons: state.buttons, + boundary: state.boundary, + world_time: state.world_time, + audio_next: state.audio_next_sample, + discontinuity: true, + slots: state.slots.into_iter().collect(), + episode_id: state.episode_id, + index, + }; + let record = direct.record("restore", None, None, None); + Ok((direct, record)) + } + + /// `LegacyFrame::run` + `take_frame`. + pub fn advance(&mut self, mask: u8) -> Result { + self.buttons = mask; + self.emulator.set_buttons(mask); + self.emulator.run_frame().map_err(|e| e.to_string())?; + self.engine_frame += 1; + self.framebuffer + .copy_from_slice(self.emulator.framebuffer()); + let raw = self.emulator.take_audio_u8(); + self.boundary += 1; + self.world_time = self + .world_time + .checked_add(&gameboy::step_duration()) + .map_err(|e| e.0)?; + let samples = audio_f32le(&raw); + let audio = audio_record(self.audio_next, &samples, self.discontinuity); + self.audio_next += audio.frames; + self.discontinuity = false; + Ok(self.record("advance", Some(mask), Some(audio), None)) + } + + /// The ratchet's capture in `LegacyFrame::boundary`: `export_state` and the frame on screen. + pub fn save_slot(&mut self, slot_id: &Id) -> Result { + let game = self.emulator.export_state().map_err(|e| e.to_string())?; + let digest = digest_of_bytes(&game); + self.slots.insert( + slot_id.clone(), + SlotState { + game, + frame: self.framebuffer.clone(), + boundary: self.boundary, + }, + ); + Ok(self.record("save-slot", None, None, Some(digest))) + } + + /// `recover_game` + `LegacyFrame::rollback`, the emulator's half. + pub fn rollback(&mut self, slot_id: &Id) -> Result { + let slot = self.slots.get(slot_id).cloned().ok_or("no such slot")?; + self.emulator + .import_state(&slot.game) + .map_err(|e| e.to_string())?; + self.emulator.set_buttons(0); + self.framebuffer.copy_from_slice(&slot.frame); + self.buttons = 0; + self.emulator.set_buttons(0); + self.discontinuity = true; + Ok(self.record("rollback", None, None, None)) + } + + /// The world a capture holds at this boundary. + pub fn state(&mut self) -> Result { + Ok(WorldState { + rom_digest: self.backend.rom_digest.clone(), + episode_id: self.episode_id.clone(), + boundary: self.boundary, + world_time: self.world_time, + engine_frame: self.engine_frame, + buttons: self.buttons, + emulator: self.emulator.export_state().map_err(|e| e.to_string())?, + framebuffer: self.framebuffer.clone(), + slots: self + .backend + .slots + .iter() + .filter_map(|s| self.slots.get(s).map(|slot| (s.clone(), slot.clone()))) + .collect(), + audio_next_sample: self.audio_next, + }) + } + + /// A capture and a restart of the service onto it: a new emulator restored from the state. + pub fn capture_restore(self) -> Result<(DirectEmulator, EnvRecord, EnvRecord), String> { + let mut this = self; + let state = this.state()?; + let capture = this.record("capture", None, None, Some(world_digest(&state))); + let (restored, record) = + DirectEmulator::from_state(this.rom.clone(), this.backend.clone(), state, this.index)?; + Ok((restored, capture, record)) + } +} + +/// The digest of a world's content: every byte array and every scalar, without the payload +/// header (which names the worker and the checkpoint, not the world). +pub fn world_digest(state: &WorldState) -> Digest { + let slots: Vec = state + .slots + .iter() + .map(|(id, slot)| { + json!({ + "slotId": id, + "boundary": slot.boundary.to_string(), + "game": digest_of_bytes(&slot.game), + "frame": digest_of_bytes(&slot.frame), + }) + }) + .collect(); + digest_of(&json!({ + "romDigest": state.rom_digest, + "episodeId": state.episode_id, + "boundary": state.boundary.to_string(), + "worldTime": state.world_time.to_json(), + "engineFrame": state.engine_frame.to_string(), + "buttons": state.buttons, + "emulator": digest_of_bytes(&state.emulator), + "framebuffer": digest_of_bytes(&state.framebuffer), + "audioNextSample": state.audio_next_sample.to_string(), + "slots": slots, + })) + .expect("a world digest canonicalizes") +} + +/// Runs a script on the direct reference. +pub fn run_direct( + rom: Arc>, + backend: &BackendConfig, + script: &EnvScript, +) -> Result, String> { + let (mut direct, first) = match &script.start { + EnvStart::Fresh => DirectEmulator::fresh(rom, backend.clone())?, + EnvStart::Flysim01(bytes) => { + let state = WorldState::from_flysim01( + bytes, + &id("ep1"), + &backend.slots[0], + backend.audio_sample_rate, + )?; + DirectEmulator::from_state(rom, backend.clone(), state, 0)? + } + }; + let mut records = vec![first]; + for op in &script.ops { + match op { + EnvOp::Advance(mask) => records.push(direct.advance(*mask)?), + EnvOp::SaveSlot(slot) => records.push(direct.save_slot(slot)?), + EnvOp::Rollback(slot) => records.push(direct.rollback(slot)?), + EnvOp::CaptureRestore => { + let (next, capture, restore) = direct.capture_restore()?; + records.push(capture); + records.push(restore); + direct = next; + } + } + } + Ok(records) +} + +// ------------------------------------------------------------------------------------------- +// The rig: a router, a launcher in one mode, the environment it started + +const DRIVER_CLIENT: &str = "env-driver"; +const MAX_GENERATIONS: u32 = 8; + +fn env_service(worker_id: &str) -> String { + format!("env.{worker_id}") +} + +fn env_client(worker_id: &str, generation: u32) -> String { + format!("world-{worker_id}-r{generation}") +} + +fn grants(f: impl FnOnce(&mut Grants)) -> Grants { + let mut g = Grants::default(); + f(&mut g); + g +} + +fn domain(e: DomainError) -> String { + format!("{:?}: {}", e.code, e.message) +} + +/// The smallest composition that runs [`LegacyGameboyEnvironment`] under `fly-session`'s own +/// supervisor, in one execution mode. The coordinator's part is played by an [`EnvDriver`]. +pub struct EnvRig { + pub launcher: Launcher, + pub client: Client, + pub session_id: Id, + pub worker_id: Id, + pub mode: ExecutionMode, + rom_path: PathBuf, + backend: BackendConfig, + generation: u32, +} + +impl EnvRig { + pub async fn start( + root: &Path, + mode: ExecutionMode, + rom_path: &Path, + backend: BackendConfig, + ) -> Result { + let session_id = id("legacy"); + let worker_id = id("world"); + let store_root = root.join("store"); + let sockets = root.join("sockets"); + std::fs::create_dir_all(&sockets).map_err(|e| format!("sockets: {e}"))?; + let service = env_service(&worker_id); + let mut policy = Policy::closed() + .client( + DRIVER_CLIENT, + grants(|g| g.call = vec![Pattern::prefix("env.")]), + ) + .client( + SUPERVISOR_CLIENT, + grants(|g| g.call = vec![Pattern::prefix("env.")]), + ); + for generation in 1..=MAX_GENERATIONS { + policy = policy.client( + &env_client(&worker_id, generation), + grants(|g| g.register = vec![Pattern::exact(&service)]), + ); + } + let mut config = RouterConfig::new(&store_root); + config.policy = policy; + let router = Router::new(config).map_err(|e| format!("router: {e}"))?; + let budget = ThreadBudget::new(3, 1).map_err(|e| e.message)?; + let launcher = Launcher::start(router, mode, Via::Unix, &store_root, &sockets, budget) + .await + .map_err(|e| format!("launcher: {}", e.message))?; + let client = launcher + .connect(DRIVER_CLIENT) + .await + .map_err(|e| format!("connect: {}", e.message))?; + let mut rig = EnvRig { + launcher, + client, + session_id, + worker_id, + mode, + rom_path: rom_path.to_owned(), + backend, + generation: 0, + }; + rig.launch().await?; + Ok(rig) + } + + /// The launch specification of the next generation. + pub fn next_spec(&self) -> LegacyEnvironmentLaunch { + let generation = self.generation + 1; + LegacyEnvironmentLaunch { + session_id: self.session_id.clone(), + worker_id: self.worker_id.clone(), + incarnation_id: parse_id(&format!("{}-inc-{generation}", self.worker_id)) + .expect("an incarnation id"), + worker_threads: 1, + rom_path: self.rom_path.clone(), + backend: self.backend.clone(), + client_id: env_client(&self.worker_id, generation), + service: env_service(&self.worker_id), + } + } + + async fn launch(&mut self) -> Result { + let spec = self.next_spec(); + self.generation += 1; + self.launcher + .launch_legacy_environment(spec) + .await + .map_err(|e| e.message)?; + Ok(self.worker_ref()) + } + + /// Launches a worker from an explicit specification (for the refusals), as the next + /// generation. + pub async fn launch_spec( + &mut self, + spec: LegacyEnvironmentLaunch, + ) -> Result { + self.launcher.reap(&self.worker_id, &id("replaced")).await; + self.generation += 1; + self.launcher.launch_legacy_environment(spec).await?; + Ok(self.worker_ref()) + } + + pub fn worker_ref(&self) -> WorkerRef { + self.launcher + .worker(&self.worker_id) + .expect("launched") + .worker_ref() + } + + /// Stops the worker and starts its replacement: a new process in process mode, with a new + /// incarnation and client identity, uninitialized. + pub async fn replace(&mut self) -> Result { + self.launcher.reap(&self.worker_id, &id("replaced")).await; + self.launch().await + } + + pub async fn stop(mut self) { + self.launcher.reap_all(&id("done")).await; + } + + pub fn driver(&self) -> EnvDriver { + EnvDriver { + client: self.client.clone(), + target: self.worker_ref(), + session_id: self.session_id.clone(), + worker_id: self.worker_id.clone(), + backend: self.backend.clone(), + descriptor: None, + epoch_serial: 1, + boundary: 0, + serials: Serials::default(), + batches: 0, + timelines: AudioTimelines::default(), + index: 0, + checkpoints: 0, + last: None, + } + } +} + +/// The coordinator's side of the environment: scopes, epochs, batch ids, the descriptor it was +/// given, and the coordinator's own media checks on every observation. +pub struct EnvDriver { + client: Client, + target: WorkerRef, + session_id: Id, + worker_id: Id, + backend: BackendConfig, + descriptor: Option, + epoch_serial: u32, + boundary: u64, + serials: Serials, + batches: u64, + timelines: AudioTimelines, + index: u64, + checkpoints: u64, + /// The last observation's record, which a slot save and a capture repeat. + last: Option, +} + +/// A captured payload, held for a restore. +pub struct Captured { + pub result: CaptureResult, + pub artifact: flybus::Artifact, + pub bytes: Vec, + pub scope: Scope, +} + +const WANT: [&str; 3] = ["view.lcd", MEMORY_ATTACHMENT, "audio.apu"]; + +impl EnvDriver { + fn epoch(&self) -> Id { + id(&format!("e{}", self.epoch_serial)) + } + + pub fn scope(&self) -> Scope { + scope_at(&self.session_id, &self.epoch(), self.boundary) + } + + pub fn boundary(&self) -> u64 { + self.boundary + } + + pub fn target(&self) -> &WorkerRef { + &self.target + } + + pub fn descriptor(&self) -> Option<&EnvironmentDescriptor> { + self.descriptor.as_ref() + } + + /// Moves the driver to the next epoch without telling the worker, to address it wrongly. + pub fn bump_epoch(&mut self) { + self.epoch_serial += 1; + } + + pub fn set_target(&mut self, target: WorkerRef) { + self.target = target; + } + + async fn call( + &mut self, + method: &str, + scope: Option, + params: Value, + attachments: &[(&str, &flybus::Artifact)], + ) -> Result { + let reply = self + .call_raw(method, scope, params, attachments) + .await + .map_err(|e| format!("{method}: {}", domain(e)))?; + reply + .result() + .map_err(|e| format!("{method}: {}", domain(e)))?; + Ok(reply) + } + + /// One call with any params, its domain outcome returned as it stands. + pub async fn call_raw( + &mut self, + method: &str, + scope: Option, + params: Value, + attachments: &[(&str, &flybus::Artifact)], + ) -> Result { + let request_id = self.serials.next(&self.target.service); + self.retry_raw(request_id, method, scope, params, attachments) + .await + } + + /// The same request id again: a domain retry, or a duplicate. + pub async fn retry_raw( + &mut self, + request_id: DomainRequestId, + method: &str, + scope: Option, + params: Value, + attachments: &[(&str, &flybus::Artifact)], + ) -> Result { + let want: Vec = WANT + .iter() + .map(|w| (*w).to_owned()) + .chain([crate::state::PAYLOAD_ATTACHMENT.to_owned()]) + .collect(); + call( + &self.client, + &self.target, + method, + scope, + object(params), + attachments, + request_id, + &want, + ) + .await + } + + async fn acknowledge(&mut self, request_id: DomainRequestId) -> Result<(), String> { + let params = AcknowledgeParams { + request_ids: vec![request_id], + }; + self.call("Worker.Acknowledge", None, params.to_json(), &[]) + .await + .map(|_| ()) + } + + /// The `Environment.Initialize` params for this backend. + pub fn initialize_params(&self) -> EnvironmentInitializeParams { + EnvironmentInitializeParams { + backend_config: self.backend.asset_ref(), + task_config: crate::environment::synthetic_asset("pokered-task", "pokered-macros-v1"), + episode_id: id("ep1"), + port_bindings: vec![(self.backend.port_id.clone(), id("fly"))], + } + } + + /// Reads one observation's artifacts into a record, after the coordinator's Phase C checks: + /// the descriptor's shapes, the required view at its producing boundary, the audio rule for + /// the observation's origin, the audio timeline, the memory image's schema and ROM. + async fn observe( + &mut self, + op: &'static str, + mask: Option, + observation: &WorldObservation, + artifacts: &BTreeMap, + origin: ObservationOrigin, + state: Option, + ) -> Result { + let descriptor = self.descriptor.clone().ok_or("no descriptor")?; + observation.validate_against(&descriptor).map_err(|e| e.0)?; + check_required_views(&descriptor, observation).map_err(domain)?; + check_required_audio(&descriptor, observation, origin).map_err(domain)?; + self.timelines + .accept(&descriptor, observation) + .map_err(domain)?; + if observation.boundary != self.boundary { + return Err(format!( + "{op}: observation at {} for boundary {}", + observation.boundary, self.boundary + )); + } + if observation.world_time != world_time_at(self.boundary)? { + return Err(format!( + "{op}: the world clock is not boundary {}'s", + self.boundary + )); + } + let engine_frame: u64 = observation + .engine_frame + .as_deref() + .ok_or("no engineFrame")? + .parse() + .map_err(|_| "engineFrame is not a counter")?; + let inspection = MemoryInspection::from_typed(&observation.inspection).map_err(|e| e.0)?; + if inspection.rom_digest != descriptor.content_digest { + return Err("the inspection names another cartridge".to_owned()); + } + let view = &observation.sensory_views[0]; + let frame = read_attachment(artifacts, op, "view.lcd").await?; + if frame.len() != FRAMEBUFFER_LEN || artifacts["view.lcd"].reference() != &view.pixels { + return Err(format!("{op}: the view attachment is not the view")); + } + if observation.broadcast_views != observation.sensory_views { + return Err(format!("{op}: the broadcast view is not the sensory one")); + } + let image = read_attachment(artifacts, op, MEMORY_ATTACHMENT).await?; + if image.len() != gameboy::MEMORY_IMAGE_BYTES as usize + || artifacts[MEMORY_ATTACHMENT].reference() != &inspection.memory + { + return Err(format!( + "{op}: the memory attachment is not the inspection's image" + )); + } + let audio = match observation.audio.first() { + Some(chunk) => { + let samples = read_attachment(artifacts, op, "audio.apu").await?; + if artifacts["audio.apu"].reference() != &chunk.samples + || chunk.stream_id != AUDIO_STREAM_ID + { + return Err(format!("{op}: the audio attachment is not the chunk")); + } + if samples.len() as u64 != chunk.sample_frames * legacy_env::AUDIO_CHANNELS * 4 { + return Err(format!("{op}: the chunk's length is not its sampleFrames")); + } + Some(audio_record( + chunk.first_sample, + &samples, + chunk.discontinuity, + )) + } + None => None, + }; + let (memory, wram) = memory_record(&image); + let record = EnvRecord { + index: self.index, + op, + boundary: self.boundary, + engine_frame, + world_time: observation.world_time, + mask, + frame: digest_of_bytes(&frame), + memory, + wram, + audio, + state, + }; + self.index += 1; + self.last = Some(record.clone()); + Ok(record) + } + + /// Checks the descriptor the worker advertised against the composition's declaration. + fn accept_descriptor(&mut self, descriptor: &EnvironmentDescriptor) -> Result<(), String> { + descriptor.validate().map_err(|e| e.0)?; + let expected = legacy_env::LegacyGameboyEnvironment::descriptor_for(&self.backend); + if *descriptor != expected { + return Err("the environment advertised another descriptor".to_owned()); + } + if descriptor.step_duration != gameboy::step_duration() + || descriptor.content_digest != self.backend.rom_digest + || descriptor.configuration_digest != self.backend.asset_ref().digest + || descriptor.inspection_schema != gameboy::MEMORY_INSPECTION.schema_ref() + { + return Err("the descriptor is not the legacy composition's".to_owned()); + } + self.descriptor = Some(descriptor.clone()); + Ok(()) + } + + /// `Environment.Initialize`: O[0] after the one-frame scaffold. + pub async fn initialize(&mut self) -> Result { + let params = self.initialize_params(); + let reply = self + .call( + "Environment.Initialize", + Some(self.scope()), + params.to_json(), + &[], + ) + .await?; + let result: EnvironmentInitializeResult = reply.parse().map_err(domain)?; + self.accept_descriptor(&result.descriptor)?; + self.timelines = AudioTimelines::fresh(&result.descriptor); + let record = self + .observe( + "initialize", + None, + &result.observation, + &reply.artifacts, + ObservationOrigin::Installed, + None, + ) + .await?; + self.acknowledge(reply.request_id).await?; + Ok(record) + } + + /// The `AdvanceParams` of the next batch. + pub fn advance_params(&mut self, mask: u8) -> AdvanceParams { + self.batches += 1; + AdvanceParams { + batch_id: id(&format!("b{}-{}", self.epoch_serial, self.batches)), + controls: vec![control_of(&self.backend.port_id, mask)], + } + } + + /// `Environment.Advance` with one complete joypad batch. + pub async fn advance(&mut self, mask: u8) -> Result { + let params = self.advance_params(mask); + let reply = self + .call( + "Environment.Advance", + Some(self.scope()), + params.to_json(), + &[], + ) + .await?; + let result: StepResult = reply.parse().map_err(domain)?; + if result.applied_from_step != self.boundary || result.next_step != self.boundary + 1 { + return Err("Environment.Advance moved another interval".to_owned()); + } + if result.applied_controls_digest != controls_digest(¶ms.controls) + || result.batch_id != params.batch_id + { + return Err("Environment.Advance applied another batch".to_owned()); + } + self.boundary += 1; + self.observe( + "advance", + Some(mask), + &result.observation, + &reply.artifacts, + ObservationOrigin::Transition, + None, + ) + .await + } + + /// A record that changes no observation: the last one's, renumbered. + fn repeat(&mut self, op: &'static str, state: Option) -> Result { + let last = self.last.clone().ok_or("no observation yet")?; + let record = EnvRecord { + index: self.index, + op, + mask: None, + audio: None, + state, + ..last + }; + self.index += 1; + Ok(record) + } + + /// `Environment.SaveSlot` at the committed boundary. + pub async fn save_slot(&mut self, slot_id: &Id) -> Result { + let params = SaveSlotParams { + slot_id: slot_id.clone(), + }; + let scope = self.scope(); + let reply = self + .call(METHOD_SAVE_SLOT, Some(scope.clone()), params.to_json(), &[]) + .await?; + let result: SaveSlotResult = reply.parse().map_err(domain)?; + result.validate_against_scope(&scope).map_err(|e| e.0)?; + if result.slot_id != *slot_id { + return Err("SaveSlot saved another slot".to_owned()); + } + self.repeat("save-slot", Some(result.state_digest)) + } + + /// The `RestoreSlotParams` of a rollback from the current epoch. + pub fn restore_slot_params(&self, slot_id: &Id) -> RestoreSlotParams { + RestoreSlotParams { + slot_id: slot_id.clone(), + prior_epoch: self.epoch(), + policy: ROLLBACK_POLICY.to_owned(), + } + } + + /// `Environment.RestoreSlot` under the next epoch, same boundary. + pub async fn rollback(&mut self, slot_id: &Id) -> Result { + let params = self.restore_slot_params(slot_id); + self.epoch_serial += 1; + let scope = self.scope(); + let reply = self + .call( + METHOD_RESTORE_SLOT, + Some(scope.clone()), + params.to_json(), + &[], + ) + .await?; + let result: RestoreSlotResult = reply.parse().map_err(domain)?; + result.validate_against_scope(&scope).map_err(|e| e.0)?; + let descriptor = self.descriptor.clone().ok_or("no descriptor")?; + self.timelines = + AudioTimelines::restored(&descriptor, &self.timelines.positions()).map_err(domain)?; + self.observe( + "rollback", + None, + &result.observation, + &reply.artifacts, + ObservationOrigin::Installed, + None, + ) + .await + } + + /// `State.Capture` at the committed boundary, acknowledged. + pub async fn capture(&mut self) -> Result { + self.checkpoints += 1; + let scope = self.scope(); + let params = CaptureParams { + checkpoint_id: id(&format!("c{}", self.checkpoints)), + }; + let reply = self + .call("State.Capture", Some(scope.clone()), params.to_json(), &[]) + .await?; + let result: CaptureResult = reply.parse().map_err(domain)?; + let artifact = reply + .artifacts + .get(crate::state::PAYLOAD_ATTACHMENT) + .cloned() + .ok_or("State.Capture carried no payload")?; + let bytes = artifact.read_all().await.map_err(|e| e.message)?; + if Some(digest_of_bytes(&bytes)) != result.payload.digest { + return Err("the capture payload is not the digest it declares".to_owned()); + } + self.acknowledge(reply.request_id).await?; + Ok(Captured { + result, + artifact, + bytes, + scope, + }) + } + + /// A capture's record: the last observation plus the digest of the captured world. + pub fn capture_record(&mut self, captured: &Captured) -> Result { + let (_, state) = WorldState::decode(&captured.bytes)?; + self.repeat("capture", Some(world_digest(&state))) + } + + /// A group restore of `captured` into `target`, a fresh replacement worker, under a new epoch. + pub async fn restore_into( + &mut self, + target: WorkerRef, + captured: &Captured, + ) -> Result { + self.target = target; + self.epoch_serial += 1; + let (_, state) = WorldState::decode(&captured.bytes)?; + self.boundary = captured.scope.step; + let params = StageRestoreParams { + checkpoint_id: captured.result.checkpoint_id.clone(), + source_scope: captured.scope.clone(), + compatibility_digest: captured.result.compatibility_digest.clone(), + payload: captured.artifact.reference().clone(), + }; + let reply = self + .call( + "State.StageRestore", + Some(self.scope()), + params.to_json(), + &[(crate::state::PAYLOAD_ATTACHMENT, &captured.artifact)], + ) + .await?; + let staged: StageRestoreResult = reply.parse().map_err(domain)?; + self.acknowledge(reply.request_id).await?; + let params = ActivateRestoreParams { + restore_token: staged.restore_token, + }; + let reply = self + .call("State.ActivateRestore", None, params.to_json(), &[]) + .await?; + let activated: ActivateRestoreResult = reply.parse().map_err(domain)?; + if activated.committed_step != self.boundary { + return Err("State.ActivateRestore landed on another boundary".to_owned()); + } + let observation = activated + .observation + .ok_or("the environment restored no observation")?; + let descriptor = legacy_env::LegacyGameboyEnvironment::descriptor_for(&self.backend); + self.descriptor = Some(descriptor.clone()); + let positions = BTreeMap::from([(id(AUDIO_STREAM_ID), state.audio_next_sample)]); + self.timelines = AudioTimelines::restored(&descriptor, &positions).map_err(domain)?; + let record = self + .observe( + "restore", + None, + &observation, + &reply.artifacts, + ObservationOrigin::Installed, + None, + ) + .await?; + self.acknowledge(reply.request_id).await?; + Ok(record) + } + + /// Seals `state` as a capture payload this worker would have written at `source`, for a + /// restore that starts from a legacy checkpoint rather than from a capture. + pub async fn payload_of( + &mut self, + state: &WorldState, + source: Scope, + ) -> Result { + self.checkpoints += 1; + let checkpoint_id = id(&format!("c{}", self.checkpoints)); + let descriptor = legacy_env::LegacyGameboyEnvironment::descriptor_for(&self.backend); + let header = PayloadHeader { + worker_id: self.worker_id.clone(), + checkpoint_id: checkpoint_id.clone(), + source_scope: source.clone(), + configuration_digest: descriptor.configuration_digest.clone(), + }; + let bytes = state.encode(&header); + let digest = digest_of_bytes(&bytes); + let artifact = crate::state::seal_payload(&self.client, &bytes, &digest) + .await + .map_err(domain)?; + Ok(Captured { + result: CaptureResult { + checkpoint_id, + boundary: state.boundary, + compatibility_digest: legacy_env::LegacyGameboyEnvironment::compatibility_digest( + &descriptor, + ), + payload: artifact.reference().clone(), + }, + artifact, + bytes, + scope: source, + }) + } + + /// Starts the world from a `FLYSIM01` checkpoint, the way the service starts after a restart: + /// its world half becomes this environment's payload and is group-restored into the (fresh, + /// uninitialized) worker under epoch `e2`. + pub async fn restore_flysim01(&mut self, checkpoint: &[u8]) -> Result { + let state = WorldState::from_flysim01( + checkpoint, + &id("ep1"), + &self.backend.slots[0], + self.backend.audio_sample_rate, + )?; + // The legacy file carries no session identity: its source scope is a legacy epoch. + let source = scope_at(&self.session_id, "legacy", state.boundary); + let captured = self.payload_of(&state, source).await?; + let target = self.target.clone(); + self.restore_into(target, &captured).await + } +} + +/// Runs a script on a launched worker. `CaptureRestore` replaces the worker: a new process in +/// process mode. +pub async fn run_on_worker(rig: &mut EnvRig, script: &EnvScript) -> Result, String> { + let mut driver = rig.driver(); + let mut records = vec![match &script.start { + EnvStart::Fresh => driver.initialize().await?, + EnvStart::Flysim01(bytes) => driver.restore_flysim01(bytes).await?, + }]; + for op in &script.ops { + match op { + EnvOp::Advance(mask) => records.push(driver.advance(*mask).await?), + EnvOp::SaveSlot(slot) => records.push(driver.save_slot(slot).await?), + EnvOp::Rollback(slot) => records.push(driver.rollback(slot).await?), + EnvOp::CaptureRestore => { + let captured = driver.capture().await?; + records.push(driver.capture_record(&captured)?); + let target = rig.replace().await?; + records.push(driver.restore_into(target, &captured).await?); + } + } + } + Ok(records) +} + +// ------------------------------------------------------------------------------------------- +// Scripts + +/// A seeded button walk, the way the fly plays: a held direction for a while, sometimes a +/// button, sometimes nothing. xorshift32, so the script is reproducible from its seed. +pub fn button_walk(frames: usize, seed: u32) -> Vec { + let mut state = seed.max(1); + let mut next = || { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + state + }; + let mut masks = Vec::with_capacity(frames); + while masks.len() < frames { + let pick = next(); + let hold = 4 + (pick >> 8) as usize % 21; + let mask = match pick % 10 { + 0..=5 => 1u8 << (pick >> 4 & 3), // a direction + 6 => flybrain_gb::emulator::buttons::A, + 7 => flybrain_gb::emulator::buttons::B, + 8 => 0, + _ => (1u8 << (pick >> 4 & 3)) | flybrain_gb::emulator::buttons::A, + }; + for _ in 0..hold { + masks.push(mask); + } + } + masks.truncate(frames); + masks +} + +/// A script over `masks` with the boundary actions a ratchet and a restart would take: a slot +/// save, two rollbacks onto it (the second after a capture/restore, so the slot crosses a +/// restore), a second save, and a rollback that lands on a boundary where a save happened too +/// (save first, then roll back: `legacy-gameboy-v1` section 11 step 1). +pub fn scripted(name: &str, start: EnvStart, masks: &[u8]) -> EnvScript { + let slot = id(legacy_env::DEFAULT_SLOT); + let n = masks.len(); + let mut ops = Vec::new(); + for (t, mask) in masks.iter().enumerate() { + ops.push(EnvOp::Advance(*mask)); + if t == n / 8 { + ops.push(EnvOp::SaveSlot(slot.clone())); + } + if t == n * 3 / 8 { + ops.push(EnvOp::Rollback(slot.clone())); + } + if t == n / 2 { + ops.push(EnvOp::CaptureRestore); + } + if t == n * 5 / 8 { + ops.push(EnvOp::Rollback(slot.clone())); + } + if t == n * 3 / 4 { + ops.push(EnvOp::SaveSlot(slot.clone())); + ops.push(EnvOp::Rollback(slot.clone())); + } + } + EnvScript { + name: name.to_owned(), + start, + ops, + } +} + +/// The toy cartridge's golden script: a fresh start and 240 frames. +pub fn toy_script() -> EnvScript { + scripted( + "toy-cart-fresh-240", + EnvStart::Fresh, + &button_walk(240, 20_260_929), + ) +} + +/// The committed golden of [`toy_script`]. +pub fn toy_golden_path() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/legacy-env/toy-cart.golden.json") +} + +// ------------------------------------------------------------------------------------------- +// FND-01's trace + +/// One transition of a `flysim-legacy-frame-trace-v1` trace, as the environment sees it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TraceFrame { + /// The legacy frame counter before the transition: `engineFrame` of O[k]. + pub step: u64, + pub mask: u8, + pub framebuffer: Digest, + pub wram: Digest, + /// `save-slot` (with the slot's state digest) and `rollback`, in the order applied. + pub actions: Vec<(String, Option)>, +} + +/// The environment's half of a `FLY_TRACE` written by the running service. +#[derive(Clone, Debug)] +pub struct FlyTrace { + pub frames: Vec, +} + +impl FlyTrace { + pub fn read(path: &Path, limit: Option) -> Result { + let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; + let mut lines = text.lines(); + let header: Value = + serde_json::from_str(lines.next().ok_or("empty trace")?).map_err(|e| e.to_string())?; + if header.get("format").and_then(Value::as_str) != Some("flysim-legacy-frame-trace-v1") { + return Err("not a flysim-legacy-frame-trace-v1 trace".to_owned()); + } + let mut frames = Vec::new(); + for line in lines { + if limit.is_some_and(|n| frames.len() >= n) { + break; + } + let value: Value = serde_json::from_str(line).map_err(|e| e.to_string())?; + let Some(b) = value.get("behaviour") else { + continue; + }; + let text = |key: &str| { + b.get(key) + .and_then(Value::as_str) + .map(str::to_owned) + .ok_or_else(|| format!("trace: no {key}")) + }; + let mut actions = Vec::new(); + for action in b + .get("boundaryActions") + .and_then(Value::as_array) + .ok_or("trace: no boundaryActions")? + { + let kind = action + .get("kind") + .and_then(Value::as_str) + .ok_or("trace: action kind")? + .to_owned(); + let digest = action + .get("stateDigest") + .and_then(Value::as_str) + .map(str::to_owned); + actions.push((kind, digest)); + } + frames.push(TraceFrame { + step: text("step")?.parse().map_err(|_| "trace: step")?, + mask: b + .get("mask") + .and_then(Value::as_u64) + .and_then(|m| u8::try_from(m).ok()) + .ok_or("trace: mask")?, + framebuffer: text("framebufferDigest")?, + wram: text("wramDigest")?, + actions, + }); + } + Ok(FlyTrace { frames }) + } + + /// The script this trace's environment inputs make, from its start checkpoint. + pub fn script(&self, name: &str, checkpoint: Arc>) -> EnvScript { + let slot = id(legacy_env::DEFAULT_SLOT); + let mut ops = Vec::new(); + for frame in &self.frames { + ops.push(EnvOp::Advance(frame.mask)); + for (kind, _) in &frame.actions { + ops.push(if kind == "save-slot" { + EnvOp::SaveSlot(slot.clone()) + } else { + EnvOp::Rollback(slot.clone()) + }); + } + } + EnvScript { + name: name.to_owned(), + start: EnvStart::Flysim01(checkpoint), + ops, + } + } + + /// Checks records produced by [`FlyTrace::script`] against what the service recorded: each + /// transition's engine frame, frame digest and WRAM digest, each slot save's state digest. + /// Returns the number of values compared. + pub fn check(&self, records: &[EnvRecord]) -> Result { + let mut at = 1; // records[0] is the restore + let mut compared = 0; + for (t, frame) in self.frames.iter().enumerate() { + let before = &records[at - 1]; + let record = records + .get(at) + .ok_or_else(|| format!("no record for transition {t}"))?; + if record.op != "advance" || before.engine_frame != frame.step { + return Err(format!( + "transition {t}: the world was at frame {} and the service at {}", + before.engine_frame, frame.step + )); + } + if record.frame != frame.framebuffer { + return Err(format!( + "transition {t} (frame {}): the frame differs from the service's", + frame.step + )); + } + if record.wram != frame.wram { + return Err(format!( + "transition {t} (frame {}): WRAM differs from the service's", + frame.step + )); + } + compared += 3; + at += 1; + for (kind, digest) in &frame.actions { + let record = records.get(at).ok_or("a boundary action has no record")?; + if kind == "save-slot" { + if record.op != "save-slot" || record.state != *digest { + return Err(format!( + "transition {t}: the slot saved is not the service's" + )); + } + compared += 1; + } else if record.op != "rollback" { + return Err(format!( + "transition {t}: no rollback where the service rolled back" + )); + } + at += 1; + } + } + if at != records.len() { + return Err("records beyond the trace".to_owned()); + } + Ok(compared) + } +} diff --git a/services/flysim/crates/fly-session/src/lib.rs b/services/flysim/crates/fly-session/src/lib.rs index 6849001..4b92dc5 100644 --- a/services/flysim/crates/fly-session/src/lib.rs +++ b/services/flysim/crates/fly-session/src/lib.rs @@ -29,6 +29,8 @@ pub mod dedup; pub mod environment; pub mod harness; pub mod launcher; +pub mod legacy_env; +pub mod legacy_env_parity; pub mod measure; pub mod media; pub mod metrics; diff --git a/services/flysim/crates/fly-session/src/worker.rs b/services/flysim/crates/fly-session/src/worker.rs index e361af3..4451900 100644 --- a/services/flysim/crates/fly-session/src/worker.rs +++ b/services/flysim/crates/fly-session/src/worker.rs @@ -606,6 +606,13 @@ async fn execute( fn classify_default(method: &str) -> Option { match method { "Agent.Prepare" | "Agent.Commit" | "Environment.Advance" => Some(OpClass::StepMutation), + // The extension methods of `workers-v1` section 7 are mutations under the step operation + // key (`legacy-gameboy-v1` section 11): `SaveSlot` at `(e, k)`, `RestoreSlot` and + // `Agent.Rollback` at the new epoch `(e', k)`. A lost reply replays from the same cache + // rather than rolling back twice. + "Agent.Rollback" | "Environment.SaveSlot" | "Environment.RestoreSlot" => { + Some(OpClass::StepMutation) + } // `ipc-v1` section 5 retains lifecycle *and capture* replies until // `Worker.Acknowledge`. The restore methods join them: their replies carry a // once-only token and, for an environment, the restored observation's artifact, and a