diff --git a/services/flysim/crates/fly-legacy-session/src/composition.rs b/services/flysim/crates/fly-legacy-session/src/composition.rs index 3332569..5b5e970 100644 --- a/services/flysim/crates/fly-legacy-session/src/composition.rs +++ b/services/flysim/crates/fly-legacy-session/src/composition.rs @@ -25,6 +25,12 @@ use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros; use flysim::snapshot::MacroMode; use crate::task::{PokeredConfig, PokeredTask, TaskRecord}; +use fly_session::legacy_checkpoint::{ + AgentImport, CheckpointerConfig, LegacyCapture, LegacyCheckpointer, RankChange, SaveKind, + SaveReport, now_wall_ms, +}; +use flysim::store::Checkpoint; +use std::time::Instant; fn grants(f: impl FnOnce(&mut Grants)) -> Grants { let mut g = Grants::default(); @@ -79,6 +85,157 @@ pub struct LegacySession { backend: BackendConfig, /// Which generation of the world is running: 1 is the one the session started. world_generation: u32, + /// The legacy store policy, once attached ([`LegacySession::attach_store`]). + checkpointer: Option, + saves: u64, + /// The feed event log's watermark the saves record: the restored file's, carried over (the + /// session runtime has no feed event log of its own before EDGE-01). + last_event_id: u64, +} + +/// Where the legacy store lives and how often it is written (the service's `[paths]` and +/// `[loop]`). +#[derive(Clone, Debug)] +pub struct StoreConfig { + pub hot_dir: PathBuf, + pub durable_dir: PathBuf, + pub keep_generations: usize, + pub hot_seconds: f64, + pub checkpoint_seconds: f64, + pub speed: f64, +} + +/// This build's legacy compatibility string (`flysim --print-compatibility`): the kernel, the +/// adapter, the profile's dataset fingerprint, the plasticity rule and the pokered symbols. It is +/// the restore gate and what every save records (`legacy-gameboy-v1` section 12). +pub fn compatibility_of(config: &LegacyConfig) -> String { + let adapter = flybrain_gb::pokemon_red::PokemonRedReward::new(); + let profile = config.profile.profile(); + flybrain_gb::Compatibility { + neural_kernel_version: gameboy::KERNEL_VERSION, + adapter: flybrain_gb::GameAdapter::id(&adapter), + dataset_fingerprint: &profile.dataset_fingerprint, + plasticity_version: gameboy::PLASTICITY_VERSION, + pokered_commit: &flybrain_gb::GameAdapter::symbol_provenance(&adapter), + } + .string() +} + +/// How a session came up. +#[derive(Debug)] +pub enum Boot { + /// No checkpoint in either store: a fresh fly, warmed up. + Fresh, + /// A candidate restored, after `skipped` were refused. + Restored { + candidate: flysim::store::Candidate, + skipped: Vec<(flysim::store::Candidate, String)>, + migrated_from: Option, + imported: crate::import::Imported, + }, +} + +/// `Sim::boot` on the session runtime: restore from the live FLYSIM01 stores in the legacy order +/// (hot latest, hot previous, durable latest, durable previous, milestone archives by rank), each +/// candidate held to the legacy gate (`RestoreGate`: the cartridge and the compatibility decision +/// with `FLY_ACCEPT_ADAPTERS`), falling to the next on *any* refusal -- unreadable, gated, or +/// refused by a participant's `State.StageRestore` or the task. A refused install fences its +/// session, so each attempt runs on a session of its own (a directory under `root` each). No +/// candidate at all is a fresh start; candidates that all fail are an error, as the legacy loop +/// refuses to start a fresh fly over them. Either way the store is attached and the startup +/// durable save is written, and the intervals run from then. +pub async fn boot( + root: &Path, + config: LegacyConfig, + store: &StoreConfig, +) -> Result<(LegacySession, Boot), String> { + let hot = flysim::store::Store::new(&store.hot_dir, store.keep_generations); + let durable = flysim::store::Store::new(&store.durable_dir, store.keep_generations); + let candidates = flysim::store::restore_order(&hot, &durable); + let rom = std::fs::read(&config.rom_path) + .map_err(|e| format!("the cartridge {}: {e}", config.rom_path.display()))?; + let adapter = flybrain_gb::pokemon_red::PokemonRedReward::new(); + let gate = fly_session::legacy_checkpoint::RestoreGate::from_env( + &sha256_hex(&rom), + &compatibility_of(&config), + flybrain_gb::GameAdapter::migrates_from(&adapter), + ); + let mut skipped: Vec<(flysim::store::Candidate, String)> = Vec::new(); + let mut outcome = None; + for (attempt, candidate) in candidates.iter().enumerate() { + let checkpoint = match flysim::store::load(&candidate.path) { + Ok(checkpoint) => checkpoint, + Err(e) => { + skipped.push((candidate.clone(), format!("{e:#}"))); + continue; + } + }; + let migrated_from = match gate.check(&checkpoint) { + Ok(from) => from, + Err(reason) => { + skipped.push((candidate.clone(), reason)); + continue; + } + }; + let mut session = + LegacySession::start(&root.join(format!("attempt-{attempt}")), config.clone()).await?; + let installed = match session.bootstrap().await { + Ok(()) => session.import_checkpoint(&checkpoint, &id("e2")).await, + Err(e) => Err(e), + }; + match installed { + Ok(imported) => { + let rank = session.task.rank(); + session.attach_store(store)?; + session + .checkpointer_mut() + .expect("attached") + .restored(rank, imported.rank_since_ms); + outcome = Some(( + session, + Boot::Restored { + candidate: candidate.clone(), + skipped: std::mem::take(&mut skipped), + migrated_from, + imported, + }, + )); + break; + } + Err(reason) => { + session.stop().await; + skipped.push((candidate.clone(), reason)); + } + } + } + let (mut session, boot) = match outcome { + Some(pair) => pair, + None if candidates.is_empty() => { + let mut session = LegacySession::start(&root.join("fresh"), config).await?; + session.bootstrap().await?; + session.attach_store(store)?; + (session, Boot::Fresh) + } + None => { + let reasons: Vec = skipped + .iter() + .map(|(candidate, reason)| format!("{}: {reason}", candidate.origin)) + .collect(); + return Err(format!( + "every one of the {} checkpoint candidates failed to load; refusing to start a \ + fresh run over them:\n{}", + candidates.len(), + reasons.join("\n") + )); + } + }; + // `Sim::boot`: a durable save of the state the process starts from, then the intervals. + session.save(SaveKind::Durable).await?; + session + .checkpointer_mut() + .expect("attached") + .start_intervals(Instant::now()); + Ok((session, boot)) } /// One transition as a parity run sees it. @@ -250,6 +407,9 @@ impl LegacySession { session_id, backend, world_generation: 1, + checkpointer: None, + saves: 0, + last_event_id: 0, }) } @@ -266,14 +426,29 @@ impl LegacySession { Ok(()) } + /// The agent's identity as an import stamps it. + pub fn agent_import(&self) -> AgentImport { + let (macro_channels, _) = channels_and_hold(self.config.macro_mode); + AgentImport { + agent_id: self.config.agent_id.clone(), + profile: self.config.profile.profile().asset, + seed: fly_session::legacy_parity::LEGACY_SEED, + macro_channels, + } + } + + /// This build's legacy compatibility string ([`compatibility_of`]). + pub fn compatibility(&self) -> String { + compatibility_of(&self.config) + } + /// Installs a FLYSIM01 checkpoint as this session's start (after [`LegacySession::bootstrap`], /// before any transition): the world is replaced by a fresh one (the environment stages a /// restore only on a replacement, as every group restore does), then [`crate::import`] runs /// the group install and the session resumes at the checkpoint's boundary. - pub async fn import_flysim01( + pub async fn import_checkpoint( &mut self, - bytes: &[u8], - checkpoint_id: &Id, + checkpoint: &Checkpoint, epoch: &Id, ) -> Result { if self.world_generation != 1 { @@ -303,13 +478,13 @@ impl LegacySession { .replace_participant(&id(ENV_WORKER), world) .map_err(|e| format!("replacing the world: {}", e.error.message))?; let rom = self.rom.clone(); + let agent = self.agent_import(); let imported = crate::import::import_flysim01( &mut self.coordinator, &self.task, - bytes, + checkpoint, &rom, - &self.config.agent_id, - checkpoint_id, + &agent, self.backend.audio_sample_rate, epoch, ) @@ -317,21 +492,148 @@ impl LegacySession { if self.config.record { self.coordinator.disable_pacing(); } + self.last_event_id = checkpoint.runtime.last_event_id; Ok(imported) } - /// One transition, with its details when recorded. - pub async fn step(&mut self) -> Result { + /// Decodes FLYSIM01 bytes and installs them ([`LegacySession::import_checkpoint`]). + pub async fn import_flysim01( + &mut self, + bytes: &[u8], + epoch: &Id, + ) -> Result { + let checkpoint = flysim::store::decode(bytes).map_err(|e| format!("FLYSIM01: {e:#}"))?; + self.import_checkpoint(&checkpoint, epoch).await + } + + // -- the store (STATE-02) ------------------------------------------------------------------ + + /// Attaches the legacy store policy (`LegacyCheckpointer`): FLYSIM01 generations in the hot + /// and durable stores, milestone archives, the legacy intervals. Rollbacks are deferred from + /// here on, so a milestone capture lands between the boundary's slot save and its rollback. + pub fn attach_store(&mut self, store: &StoreConfig) -> Result<(), String> { + let checkpointer = LegacyCheckpointer::open(CheckpointerConfig { + hot_dir: store.hot_dir.clone(), + durable_dir: store.durable_dir.clone(), + keep_generations: store.keep_generations, + hot_seconds: store.hot_seconds, + checkpoint_seconds: store.checkpoint_seconds, + compatibility: self.compatibility(), + speed: store.speed, + slot_id: id(crate::task::SLOT), + })?; + self.checkpointer = Some(checkpointer); + self.coordinator.defer_rollbacks(true); + Ok(()) + } + + pub fn checkpointer(&self) -> Option<&LegacyCheckpointer> { + self.checkpointer.as_ref() + } + + pub fn checkpointer_mut(&mut self) -> Option<&mut LegacyCheckpointer> { + self.checkpointer.as_mut() + } + + /// One save of the committed boundary, written by the checkpointer's writer thread; waits for + /// the commit, so a caller that goes on to read the store finds it. + pub async fn save(&mut self, kind: SaveKind) -> Result { + self.saves += 1; + let (boundary, world, agents) = self + .coordinator + .capture_payloads(&parse_id(&format!("legacy-save-{}", self.saves))?) + .await + .map_err(|e| format!("capture ({}): {}", e.detail, e.error.message))?; + let [(_, agent)] = <[(Id, Vec); 1]>::try_from(agents) + .map_err(|_| "the legacy composition has exactly one agent".to_owned())?; + let (task, _slot_filled) = self.task.task_half(); + let capture = LegacyCapture { + boundary, + agent_payload: agent, + world_payload: world, + task, + }; + let last_event_id = self.last_event_id; + let checkpointer = self.checkpointer.as_mut().ok_or("no store is attached")?; + let ticket = checkpointer.save(kind, capture, last_event_id, now_wall_ms())?; + ticket + .reply + .await + .map_err(|_| "the checkpoint writer stopped".to_owned())? + } + + /// One transition and what the legacy loop does at the boundary it reaches, in the declared + /// order (`legacy-gameboy-v1` sections 4 and 16): the slot save (inside the step), the + /// milestone archive when the rank climbed (`Sim::track_rank`), the rollback, a durable save + /// after it, then the interval saves (`checkpoint_if_due`). + pub async fn advance(&mut self) -> Result<(Step, Vec), String> { let report = self .coordinator .step() .await .map_err(|e| format!("step ({} at {}): {}", e.detail, e.phase, e.error.message))?; - Ok(Step { - report, - details: self.coordinator.take_details(), - records: self.task.take_records(), - }) + let mut saves = Vec::new(); + if self.checkpointer.is_some() { + let rank = self.task.rank(); + let ms = self.task.brain_ms(); + let change = self + .checkpointer + .as_mut() + .expect("attached") + .observe_rank(rank, ms); + if let Some(RankChange::Climbed(rank)) = change { + saves.push(self.save(SaveKind::Milestone(rank)).await?); + } + } + let rolled_back = self + .coordinator + .apply_pending_rollback() + .await + .map_err(|e| { + format!( + "rollback ({} at {}): {}", + e.detail, e.phase, e.error.message + ) + })?; + if self.checkpointer.is_some() { + if rolled_back { + saves.push(self.save(SaveKind::Durable).await?); + } + let due = self + .checkpointer + .as_mut() + .expect("attached") + .due(Instant::now()); + if let Some(kind) = due { + saves.push(self.save(kind).await?); + } + } + Ok(( + Step { + report, + details: self.coordinator.take_details(), + records: self.task.take_records(), + }, + saves, + )) + } + + /// One transition, with its details when recorded ([`LegacySession::advance`] without the + /// saves it reports). + pub async fn step(&mut self) -> Result { + self.advance().await.map(|(step, _)| step) + } + + /// A durable save, as the legacy loop takes on shutdown, then the store's writer is closed. + pub async fn shutdown_save(&mut self) -> Result, String> { + if self.checkpointer.is_none() { + return Ok(None); + } + let report = self.save(SaveKind::Durable).await?; + if let Some(checkpointer) = self.checkpointer.as_mut() { + checkpointer.close(); + } + Ok(Some(report)) } pub async fn stop(mut self) { diff --git a/services/flysim/crates/fly-legacy-session/src/import.rs b/services/flysim/crates/fly-legacy-session/src/import.rs index e74eda6..63dbed3 100644 --- a/services/flysim/crates/fly-legacy-session/src/import.rs +++ b/services/flysim/crates/fly-legacy-session/src/import.rs @@ -1,32 +1,28 @@ //! A FLYSIM01 checkpoint as a session's start: the legacy fly's own save, installed into the new //! runtime through the ordinary group restore (`Coordinator::import`). //! -//! Each participant gets its half of the file in its own capture format and validates it as one of -//! its own captures: +//! The halves are STATE-02's (`fly_session::legacy_checkpoint`): the world as ENV-01's `FLYENV01` +//! payload at `k = emulatorFrame - 1` with the ratchet's snapshot as slot `best`; the agent as its +//! `FLYAGT01` payload with the file's reinforcement count and the file's framebuffer as the next +//! input, as `LegacyFrame::restore` installs it; the task as `{reward, ratchet, slotFilled}`. The ids +//! come from the file (`flysim01-g`, source scope `(session, legacy, k)`). //! -//! - **the world**: `WorldState::from_flysim01` (ENV-01) at `k = emulatorFrame - 1`, the ratchet's -//! snapshot as the slot `best`, as a `FLYENV01` payload; -//! - **the agent**: the checkpoint's agent state in the worker's own `FLYAGT01` capture, the way -//! AGENT-01's parity harness seeds a worker (`legacy_parity::legacy_state_payload`), with -//! `learning.updates` started at `plasticity.updates` (legacy-gameboy-v1 section 13 amendment of -//! 2026-09-29) and the checkpoint's identity and boundary written in; -//! - **the task**: the adapter state and the ratchet state (FLYSIM01's `reward` and `ratchet`). -//! -//! The rest is `restore: legacy-transient-reset` (section 14): the executor starts fresh and -//! observes the restored boundary, the agent's readout transient starts as a fresh process has it. -//! The decision context the agent is given is computed here from the restored world -- the task's -//! own boot, bound channels and location on the checkpoint's memory image -- and the coordinator -//! holds the task to it after the install. +//! The rest is `restore: legacy-transient-reset` (`legacy-gameboy-v1` section 14): the executor +//! starts fresh and observes the restored boundary, and the agent's readout transient starts as a +//! fresh process has it. The decision context the agent resumes with is computed here, from the +//! task's ledger and the checkpoint's own memory image. After the install the coordinator holds the +//! task to it: `Task::restored` re-observes the restored world and must derive the same context. use std::collections::BTreeMap; -use serde_json::json; - use fly_session::coordinator::{Coordinator, ImportSpec, ImportedAgent}; -use fly_session::legacy_env::{PayloadHeader, WorldState}; -use fly_session::legacy_parity::legacy_state_payload; +use fly_session::legacy_agent::legacy_remainder_to_rational; +use fly_session::legacy_checkpoint::{ + AgentImport, agent_payload, halves, import_checkpoint_id, legacy_source_scope, world_payload, +}; use fly_session::types::*; use flybrain_gb::{DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator, MemoryImage}; +use flysim::store::Checkpoint; use crate::task::PokeredTask; @@ -36,90 +32,83 @@ pub struct Imported { pub boundary: u64, pub epoch: Id, pub brain_ticks: u64, + pub checkpoint_id: Id, + /// The file's `rankSinceMs` and generation, for the host's rank tracking and store. + pub rank_since_ms: f64, + pub generation: u64, } -/// The checkpoint's memory image at its boundary, read the way the environment reads it after an -/// import: the emulator state imported into a stopped emulator, then one bulk read. +/// The checkpoint's memory image at its boundary, read as the environment reads it after an +/// import: the emulator state imported into a stopped emulator, then MEM-01's one bulk read. pub fn image_of(rom: &[u8], emulator_state: &[u8]) -> Result { let mut emulator = Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES) .map_err(|e| format!("the cartridge: {e}"))?; emulator .import_state(emulator_state) .map_err(|e| format!("the emulator state: {e}"))?; - let mut image = MemoryImage::zeroed(); - emulator.read_memory_image_into(&mut image); - Ok(image) + Ok(emulator.read_memory_image()) } /// Installs a FLYSIM01 checkpoint as the start of a bootstrapped session that has taken no -/// transition. `task` is the composition's task object (the coordinator holds its two faces). -#[allow(clippy::too_many_arguments)] +/// transition, onto a replacement world. `task` is the composition's task object. pub async fn import_flysim01( coordinator: &mut Coordinator, task: &PokeredTask, - bytes: &[u8], + checkpoint: &Checkpoint, rom: &[u8], - agent_id: &Id, - checkpoint_id: &Id, + agent: &AgentImport, audio_sample_rate: u64, new_epoch: &Id, ) -> Result { - let checkpoint = flysim::store::decode(bytes).map_err(|e| format!("FLYSIM01: {e}"))?; let descriptor = coordinator .descriptor() .cloned() .ok_or("the session never bootstrapped")?; - let environment_id = coordinator.environment_ref().worker_id.clone(); - let world = WorldState::from_flysim01( - bytes, + let halves = halves( + checkpoint, coordinator.episode_id(), &id(crate::task::SLOT), audio_sample_rate, )?; - let boundary = world.boundary; - let scope = coordinator.import_scope(boundary); - let world_payload = world.encode(&PayloadHeader { - worker_id: environment_id, - checkpoint_id: checkpoint_id.clone(), - source_scope: scope.clone(), - configuration_digest: descriptor.configuration_digest.clone(), - }); + let boundary = halves.world.boundary; + let checkpoint_id = import_checkpoint_id(halves.host.generation); + let scope = legacy_source_scope(coordinator.session_id(), boundary); + let world = world_payload( + &halves.world, + &coordinator.environment_ref().worker_id, + &checkpoint_id, + &scope, + &descriptor.configuration_digest, + ); // The task's ledger, and from it and the restored image the context the agent resumes with. - let ledger = PokeredTask::ledger_from_flysim01( - &checkpoint.runtime.reward, - &checkpoint.runtime.ratchet, - !checkpoint.runtime.ratchet_game.is_empty(), - ); - let brain_ms = checkpoint.agent.network.ms; - let context = task.preview_context( - &ledger, - &image_of(rom, &checkpoint.runtime.emulator)?, - brain_ms, + let ledger = PokeredTask::ledger_of(&halves.task, !checkpoint.runtime.ratchet_game.is_empty()); + let brain_ms = halves.agent.network.ms; + let image = image_of(rom, &halves.world.emulator)?; + let context = task.preview_context(&ledger, &image, brain_ms)?; + let payload = agent_payload( + &halves.agent, + halves.reinforcements, + &checkpoint.runtime.framebuffer, + agent, + &checkpoint_id, + &scope, + &context, )?; - - // The agent: its own capture as the template, the legacy state written into it. - let template = coordinator - .capture_participant(agent_id) - .await - .map_err(|e| format!("the agent template: {}", e.error.message))?; - let payload = legacy_state_payload(&template, &checkpoint.agent, &context)?; - let payload = restamp_agent_payload(&payload, checkpoint_id, &scope, boundary)?; - let remainder = - fly_session::legacy_agent::legacy_remainder_to_rational(checkpoint.agent.remainder) - .map_err(|e| format!("the remainder: {e}"))?; - + let remainder = legacy_remainder_to_rational(halves.agent.remainder) + .map_err(|e| format!("the remainder: {e}"))?; let audio_positions: BTreeMap = descriptor .audio .iter() - .map(|stream| (stream.stream_id.clone(), world.audio_next_sample)) + .map(|stream| (stream.stream_id.clone(), halves.world.audio_next_sample)) .collect(); let spec = ImportSpec { checkpoint_id: checkpoint_id.clone(), + source_scope: scope, boundary, - world_payload, + world_payload: world, agents: vec![ImportedAgent { - agent_id: agent_id.clone(), + agent_id: agent.agent_id.clone(), payload, brain_ticks: brain_ms as u64, remainder, @@ -139,31 +128,8 @@ pub async fn import_flysim01( boundary, epoch: new_epoch.clone(), brain_ticks: brain_ms as u64, + checkpoint_id, + rank_since_ms: halves.host.rank_since_ms, + generation: halves.host.generation, }) } - -/// Writes the checkpoint's identity and boundary into an agent payload's session member: the -/// template was captured at boundary 0 under another checkpoint id. -fn restamp_agent_payload( - payload: &[u8], - checkpoint_id: &Id, - scope: &Scope, - boundary: u64, -) -> Result, String> { - let magic = fly_session::legacy_agent::PAYLOAD_MAGIC; - let parts = - flybrain_core::envelope::decode_envelope(payload, magic).map_err(|e| e.to_string())?; - let mut manifest = parts.manifest.clone(); - let session = manifest.get("session").ok_or("no session member")?; - let mut session: serde_json::Value = - serde_json::from_str(&session.stringify()).map_err(|e| e.to_string())?; - session["checkpointId"] = json!(checkpoint_id.as_str()); - session["sourceScope"] = scope.to_json(); - session["committedStep"] = json!(boundary.to_string()); - manifest.set( - "session", - flybrain_core::json::JsonValue::parse(&session.to_string()).map_err(|e| e.to_string())?, - ); - flybrain_core::envelope::encode_envelope(magic, &manifest, &parts.chunks) - .map_err(|e| e.to_string()) -} diff --git a/services/flysim/crates/fly-legacy-session/src/task.rs b/services/flysim/crates/fly-legacy-session/src/task.rs index f5de4fd..08fa240 100644 --- a/services/flysim/crates/fly-legacy-session/src/task.rs +++ b/services/flysim/crates/fly-legacy-session/src/task.rs @@ -30,6 +30,7 @@ use serde_json::{Value, json}; use fly_session::fly_session_types::gameboy::{ self, ChannelsDecision, Location, MemoryInspection, ReadoutContext, RollbackRequest, }; +use fly_session::legacy_checkpoint::TaskHalf; use fly_session::task::{ ActionExecutor, Bootstrap, Evaluation, Inspection, RollbackEvaluation, Task, }; @@ -38,7 +39,7 @@ use flybrain_core::decoder::gameboy::to_button_mask; use flybrain_gb::adapter::GameAdapter; use flybrain_gb::emulator::FRAMEBUFFER_LEN; use flybrain_gb::pokemon_red::PokemonRedReward; -use flybrain_gb::ratchet::{Ratchet, RatchetState, Snapshot}; +use flybrain_gb::ratchet::{Ratchet, Snapshot}; use flybrain_gb::{AdapterLedger, Cartridge, ImageReader, MemoryImage}; use flysim::config::Config; use flysim::macros::{MacroEvent, MacroLayer, macro_layer}; @@ -60,10 +61,12 @@ fn schema(name: &str) -> SchemaRef { SchemaRef::new(name, 1, &digest).expect("a task-local schema reference is valid") } -/// The task ledger's schema: the adapter state and the ratchet's (FLYSIM01's `reward` and -/// `ratchet`). +/// The task ledger's schema: STATE-02's `TaskHalf` ledger `{reward, ratchet, slotFilled}` -- +/// FLYSIM01's `reward` and `ratchet`, and whether the environment's slot `best` holds the +/// ratchet's snapshot. Nothing else: the executor's ledgers and the adapter's transient +/// observations are not captured (`legacy-transient-reset`). pub fn ledger_schema() -> SchemaRef { - schema("pokered.ledger.v1") + schema("pokered-task-ledger-v1") } /// The executor's capture: a marker only, because its state is transient (section 10, "Capture"). pub fn executor_schema() -> SchemaRef { @@ -269,25 +272,34 @@ impl PokeredTask { self.lock().ledgers() } - /// The ledger a FLYSIM01 checkpoint carries for the task: its `reward` and `ratchet`, and - /// whether it holds a ratchet snapshot (which the environment's slot `best` now holds). - pub fn ledger_from_flysim01( - reward: &Value, - ratchet: &RatchetState, - has_slot: bool, - ) -> TypedValue { - TypedValue::new( - ledger_schema(), - json!({ - "adapter": reward, - "ratchet": serde_json::to_value(ratchet).expect("the ratchet state serializes"), - "slot": has_slot, - "evaluations": 0, - "issued": 0, - "lastSourceStep": 0, - }), + /// The ledger of a task half (STATE-02's `TaskHalf`, FLYSIM01's `reward` and `ratchet`), with + /// whether the ratchet holds a snapshot (which the environment's slot `best` now holds). + pub fn ledger_of(half: &TaskHalf, slot_filled: bool) -> TypedValue { + TypedValue::new(ledger_schema(), half.to_ledger(slot_filled)) + .expect("a ledger fits the contract") + } + + /// The task's half of a FLYSIM01 export at the committed boundary, and whether the slot is + /// filled. + pub fn task_half(&self) -> (TaskHalf, bool) { + let inner = self.lock(); + ( + TaskHalf { + reward: inner.adapter.export_state(), + ratchet: inner.ratchet.state, + }, + inner.ratchet.snapshot.is_some(), ) - .expect("a ledger fits the contract") + } + + /// The brain time of the last transition (its Prepare's clock), in ms: `network.ms`. + pub fn brain_ms(&self) -> f64 { + self.lock().ms + } + + /// The adapter's ladder rank now (`Sim::track_rank` reads it after each transition). + pub fn rank(&self) -> u32 { + self.lock().adapter.progress().rank } /// The context a restore of `ledger` onto the boundary `image` shows at brain time `ms`: what @@ -718,19 +730,8 @@ impl Task for TaskFace { } fn capture(&self) -> DomainResult { - let inner = self.0.lock(); - TypedValue::new( - ledger_schema(), - json!({ - "adapter": inner.adapter.export_state(), - "ratchet": serde_json::to_value(inner.ratchet.state).expect("serializes"), - "slot": inner.ratchet.snapshot.is_some(), - "evaluations": inner.evaluations, - "issued": inner.issued, - "lastSourceStep": inner.last_source_step, - }), - ) - .map_err(|e| DomainError::invalid(e.0)) + let (half, slot_filled) = self.0.task_half(); + Ok(PokeredTask::ledger_of(&half, slot_filled)) } fn validate_restore(&self, state: &TypedValue) -> DomainResult<()> { @@ -743,7 +744,6 @@ impl Task for TaskFace { fn install_restore(&mut self, epoch: &Id, state: &TypedValue) -> DomainResult<()> { let mut inner = self.0.lock(); let (adapter, ratchet) = parse_ledger(&inner, state)?; - let number = |key: &str| state.value.get(key).and_then(Value::as_u64).unwrap_or(0); inner.adapter = adapter; inner.ratchet = ratchet; // `legacy-transient-reset`: a fresh executor, nothing running, empty ledgers. @@ -751,9 +751,9 @@ impl Task for TaskFace { inner.current = None; inner.open = None; inner.epoch = epoch.clone(); - inner.evaluations = number("evaluations"); - inner.issued = number("issued"); - inner.last_source_step = number("lastSourceStep"); + inner.evaluations = 0; + inner.issued = 0; + inner.last_source_step = 0; Ok(()) } @@ -776,34 +776,25 @@ fn parse_ledger(inner: &Inner, state: &TypedValue) -> DomainResult<(PokemonRedRe "the captured ledger is not a pokered-macros-v1 ledger", )); } - let mut adapter = PokemonRedReward::new(); - let reward = state + let half = TaskHalf::from_ledger(&state.value).map_err(state_error)?; + let slot_filled = state .value - .get("adapter") - .ok_or_else(|| state_error("the ledger has no adapter"))?; - if !reward.is_null() { + .get("slotFilled") + .and_then(Value::as_bool) + .ok_or_else(|| state_error("the ledger has no slotFilled"))?; + // `LegacyFrame::restore`'s order: the adapter (unless the file has none), then the ratchet + // bounded by the adapter's ladder. + let mut adapter = PokemonRedReward::new(); + if !half.reward.is_null() { adapter - .import_state(reward) + .import_state(&half.reward) .map_err(|e| state_error(format!("adapter: {e}")))?; } - let ratchet_state: RatchetState = serde_json::from_value( - state - .value - .get("ratchet") - .cloned() - .ok_or_else(|| state_error("the ledger has no ratchet"))?, - ) - .map_err(|e| state_error(format!("ratchet: {e}")))?; - let slot = state - .value - .get("slot") - .and_then(Value::as_bool) - .ok_or_else(|| state_error("the ledger has no slot flag"))?; let mut ratchet = Ratchet::with_policy(adapter.recovery_policy()); ratchet .import( - Some(ratchet_state), - slot.then(slot_marker), + Some(half.ratchet), + slot_filled.then(slot_marker), adapter.rank_ladder().len(), ) .map_err(|e| state_error(format!("ratchet: {e}")))?; @@ -907,7 +898,7 @@ impl ActionExecutor for ExecutorFace { /// Brain time in ms from the executor's clock: exact whole nanoseconds of whole milliseconds. pub fn clock_ms(clock: &RationalNs) -> DomainResult { - if clock.denominator != 1 || clock.numerator % 1_000_000 != 0 { + if clock.denominator != 1 || !clock.numerator.is_multiple_of(1_000_000) { return Err(DomainError::invalid( "the executor clock is not a whole number of milliseconds", )); diff --git a/services/flysim/crates/fly-legacy-session/tests/rollback_sequence.rs b/services/flysim/crates/fly-legacy-session/tests/rollback_sequence.rs index 351be42..036fae5 100644 --- a/services/flysim/crates/fly-legacy-session/tests/rollback_sequence.rs +++ b/services/flysim/crates/fly-legacy-session/tests/rollback_sequence.rs @@ -468,7 +468,7 @@ async fn run(mode: ExecutionMode) { vec![(3, 1), (6, 1)], "the trace carries the boundary actions" ); - let seen = seen.lock().unwrap(); + let seen = std::mem::take(&mut *seen.lock().unwrap()); let (boundary, restored) = seen.restored.clone().expect("the task rolled back"); assert_eq!(boundary, 6); assert_eq!( diff --git a/services/flysim/crates/fly-legacy-session/tests/session_trace.rs b/services/flysim/crates/fly-legacy-session/tests/session_trace.rs index fa3b306..fb960f5 100644 --- a/services/flysim/crates/fly-legacy-session/tests/session_trace.rs +++ b/services/flysim/crates/fly-legacy-session/tests/session_trace.rs @@ -262,7 +262,7 @@ async fn run_session( .unwrap_or_else(|e| panic!("Ready(0): {e}")); if let Start::Checkpoint(bytes) = start { session - .import_flysim01(bytes, &id("flysim01"), &id("e2")) + .import_flysim01(bytes, &id("e2")) .await .unwrap_or_else(|e| panic!("the FLYSIM01 import: {e}")); } @@ -477,6 +477,199 @@ async fn fafb_service_trace_checkpoints() { } } +/// Runs `frames` transitions of a booted session with the store attached, recording the +/// session's `FLY_TRACE` behaviours, ledgers and bound sets, and every save it took. +async fn run_booted( + session: &mut LegacySession, + frames: usize, +) -> (Run, Vec) { + let mut run = Run { + behaviours: Vec::new(), + ledgers: Vec::new(), + bounds: Vec::new(), + }; + let mut saves = Vec::new(); + for k in 1..=frames { + let (step, saved) = session + .advance() + .await + .unwrap_or_else(|e| panic!("frame {k}: {e}")); + saves.extend(saved); + let details = step.details.expect("details are recorded"); + let [record] = step.records.as_slice() else { + panic!("frame {k}: {} task records", step.records.len()); + }; + run.behaviours.push( + trace::line(&details, record).unwrap_or_else(|e| panic!("frame {k}: {e}"))["behaviour"] + .clone(), + ); + run.ledgers.push(record.ledgers.clone()); + run.bounds.push(record.bound.clone()); + } + (run, saves) +} + +/// The SHADOW-01 entry gate: the session runtime boots from a live FLYSIM01 store, runs, saves, +/// restarts and restores from its own save, and every segment matches the legacy loop's trace. +/// +/// The store holds one durable generation, a stream checkpoint (the FND-01 review's `rollback` +/// file when `FLY_ENV01_TRACE_DIR` is set: a ratchet rollback on the first boundary, so the +/// after-rollback durable save is exercised; else `FLY_DOOR_CHECKPOINT`). Process one boots from +/// it (the legacy candidate order and gate, `boot`), writes its startup durable save, runs +/// `FLY_TASK01_BOOT_FRAMES` transitions with the legacy boundary saves, and shuts down with a +/// durable save. Process two boots from the same store and so restores process one's shutdown +/// save -- a file the session runtime wrote -- and runs on. The legacy loop runs the first +/// segment from the original file and the second from process one's save, which is also the +/// proof that the legacy loop reads what the session runtime writes. In-process then process. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fafb_boot_run_save_restore() { + let Some(rom_path) = rom_path() else { return }; + let Some(dataset) = fafb() else { return }; + let source = std::env::var_os("FLY_ENV01_TRACE_DIR") + .map(|dir| PathBuf::from(dir).join("rollback.checkpoint")) + .filter(|p| p.is_file()) + .or_else(|| std::env::var_os("FLY_DOOR_CHECKPOINT").map(PathBuf::from)); + let Some(source) = source else { + eprintln!("skipping: no source checkpoint"); + return; + }; + let rom = std::fs::read(&rom_path).expect("the cartridge"); + let data = Arc::new(load_brain_dataset_from_dir(&dataset).expect("the dataset")); + let frames = env_usize("FLY_TASK01_BOOT_FRAMES", 900); + let original = std::fs::read(&source).expect("the checkpoint"); + let generation = flysim::store::decode(&original) + .expect("FLYSIM01") + .runtime + .generation; + for mode in modes() { + let root = tempfile::tempdir().expect("tmp"); + let store = fly_legacy_session::composition::StoreConfig { + hot_dir: root.path().join("hot"), + durable_dir: root.path().join("durable"), + keep_generations: 4, + // The intervals are wall clock; a parity run takes its saves at the boundaries the + // legacy loop names (startup, a climb, a rollback, shutdown) and not on a timer. + hot_seconds: 1e9, + checkpoint_seconds: 1e9, + speed: 1.0, + }; + flysim::store::Store::new(&store.durable_dir, store.keep_generations) + .commit(generation, &original, None) + .expect("the seeded store"); + let config = |mode| LegacyConfig { + mode, + rom_path: rom_path.clone(), + dataset_dir: dataset.clone(), + profile: LegacyProfileKind::Production, + macro_mode: MacroMode::Macros, + agent_id: id("fly"), + agent_threads: 1, + record: true, + }; + + // Process one. + let started = std::time::Instant::now(); + let (mut one, boot) = + fly_legacy_session::composition::boot(&root.path().join("p1"), config(mode), &store) + .await + .unwrap_or_else(|e| panic!("{}: boot one: {e}", mode.label())); + match &boot { + fly_legacy_session::composition::Boot::Restored { candidate, .. } => { + assert_eq!( + candidate.generation, + Some(generation), + "the seeded generation" + ); + } + other => panic!("boot one: {other:?}"), + } + let startup = one.checkpointer().expect("attached").next_generation() - 1; + assert!( + startup > generation, + "the startup save takes a generation above the store's" + ); + let (run_one, saves_one) = run_booted(&mut one, frames).await; + let shutdown = one + .shutdown_save() + .await + .expect("the shutdown save") + .expect("a store"); + one.stop().await; + assert!(shutdown.durable); + let legacy_one = run_legacy( + &rom, + &data, + &Start::Checkpoint(original.clone()), + MacroMode::Macros, + frames, + &Inputs::default(), + &root.path().join("legacy-one.jsonl"), + ); + let agreement = + trace::compare(&legacy_one.behaviours, &run_one.behaviours, &run_one.bounds) + .unwrap_or_else(|e| panic!("{} segment one: {e}", mode.label())); + compare_ledgers(&legacy_one.ledgers, &run_one.ledgers); + report( + &format!("boot segment one, {}", mode.label()), + &agreement, + started.elapsed(), + ); + eprintln!( + " saves: startup g{startup}, during the run {:?}, shutdown g{}", + saves_one + .iter() + .map(|s| (s.generation, s.durable, s.archive_rank)) + .collect::>(), + shutdown.generation + ); + if agreement.rollbacks > 0 { + assert!( + saves_one.iter().any(|s| s.durable), + "a rollback is followed by a durable save" + ); + } + + // Process two: restores process one's shutdown save. + let started = std::time::Instant::now(); + let (mut two, boot) = + fly_legacy_session::composition::boot(&root.path().join("p2"), config(mode), &store) + .await + .unwrap_or_else(|e| panic!("{}: boot two: {e}", mode.label())); + let restored_path = match &boot { + fly_legacy_session::composition::Boot::Restored { candidate, .. } => { + assert_eq!( + candidate.generation, + Some(shutdown.generation), + "the latest save" + ); + candidate.path.clone() + } + other => panic!("boot two: {other:?}"), + }; + let written = std::fs::read(&restored_path).expect("the session's own save"); + let (run_two, _) = run_booted(&mut two, frames).await; + two.stop().await; + let legacy_two = run_legacy( + &rom, + &data, + &Start::Checkpoint(written), + MacroMode::Macros, + frames, + &Inputs::default(), + &root.path().join("legacy-two.jsonl"), + ); + let agreement = + trace::compare(&legacy_two.behaviours, &run_two.behaviours, &run_two.bounds) + .unwrap_or_else(|e| panic!("{} segment two: {e}", mode.label())); + compare_ledgers(&legacy_two.ledgers, &run_two.ledgers); + report( + &format!("boot segment two, {}", mode.label()), + &agreement, + started.elapsed(), + ); + } +} + /// Thins a checkpoint's adapter ledger so the fly earns rewards: the current map is unvisited /// (an `AREA` payout on the first sample), its exits unfound (`boundary`), its ground unwalked /// (`exploration`), and no wild win is a replay (`battle`). diff --git a/services/flysim/crates/fly-session/src/coordinator.rs b/services/flysim/crates/fly-session/src/coordinator.rs index d737261..5b92b75 100644 --- a/services/flysim/crates/fly-session/src/coordinator.rs +++ b/services/flysim/crates/fly-session/src/coordinator.rs @@ -376,6 +376,9 @@ pub struct Coordinator { rollbacks: u64, /// The world's state format, when it is not the synthetic arena's. state_format_id: Option, + /// Leave a requested rollback for the host to apply (`apply_pending_rollback`). + defer_rollbacks: bool, + pending_rollback: Option<(u64, EpisodeRequest)>, lifecycle_acks: Vec<(WorkerRef, DomainRequestId)>, stats: Stats, /// The ordered actions this session took, for the ordering assertions. @@ -493,6 +496,8 @@ impl Coordinator { in_flight_admissions: Vec::new(), rollbacks: 0, state_format_id: None, + defer_rollbacks: false, + pending_rollback: None, lifecycle_acks: Vec::new(), stats: Stats::default(), audit: Vec::new(), @@ -625,6 +630,90 @@ impl Coordinator { self.state_format_id = Some(id(state_format_id)); } + /// Leave a rollback the task asks for pending at its boundary, for the host to apply with + /// [`Coordinator::apply_pending_rollback`] after its own captures there. No transition starts + /// while one is pending. + pub fn defer_rollbacks(&mut self, on: bool) { + self.defer_rollbacks = on; + } + + /// The boundary a deferred rollback waits at, if one does. + pub fn pending_rollback(&self) -> Option { + self.pending_rollback.as_ref().map(|(k, _)| *k) + } + + /// Applies a deferred rollback (the declared policy, `apply_rollback`), and adds it to the + /// last transition's trace and step details, where an immediate rollback would have been. + /// Returns whether one was pending. + pub async fn apply_pending_rollback(&mut self) -> Outcome { + let Some((boundary, request)) = self.pending_rollback.take() else { + return Ok(false); + }; + let (action, details) = self.apply_rollback(boundary, &request).await?; + if let Some(trace) = self.trace.transitions.last_mut() + && trace.behaviour.acknowledged_boundary == boundary + { + trace.behaviour.boundary_actions.push(action.clone()); + } + if let Some(step) = self.last_details.as_mut() + && step.step + 1 == boundary + { + step.boundary_actions.push(action); + step.rollback = Some(details); + } + Ok(true) + } + + /// One participant-coherent capture of the committed boundary for the legacy store + /// (STATE-02's `LegacyCheckpointer`): every participant's `State.Capture` payload under + /// `Capturing(k)`, released once read. The task's half is the host's to take from the task. + /// Taken after the boundary's slot save and before a pending rollback, as + /// `legacy-gameboy-v1` section 16 orders a milestone capture. + pub async fn capture_payloads( + &mut self, + checkpoint_id: &Id, + ) -> Outcome<(u64, Vec, Vec<(Id, Vec)>)> { + let origin = self.phases.phase(); + let Some(boundary) = origin.committed_boundary().filter(|_| origin.is_committed_boundary()) + else { + return Err(SessionFailure { + error: DomainError::before( + ErrorCode::InvalidPhase, + "a coherent capture is taken at a committed boundary only", + ), + phase: origin.label(), + detail: "capture".to_owned(), + participant: None, + }); + }; + self.transition(Phase::Capturing(boundary))?; + let mut participants = vec![self.environment.clone()]; + participants.extend(self.agents.iter().map(|slot| slot.worker.clone())); + let params = object(CaptureParams { checkpoint_id: checkpoint_id.clone() }.to_json()); + let want = vec![crate::state::PAYLOAD_ATTACHMENT.to_owned()]; + let mut payloads = Vec::new(); + for worker in participants { + let reply = self + .call(&worker, "State.Capture", Some(self.scope(boundary)), params.clone(), &[], &want) + .await?; + let Some(artifact) = reply.artifacts.get(crate::state::PAYLOAD_ATTACHMENT).cloned() else { + return Err(self.fail_now( + DomainError::before(ErrorCode::BufferInvalid, "State.Capture carried no payload"), + "capture", + )); + }; + let bytes = artifact.read_all().await.map_err(|e| { + self.fail_now(DomainError::before(ErrorCode::BufferInvalid, e.message.clone()), "capture") + })?; + self.acknowledge_replies(&worker, std::slice::from_ref(&reply.request_id)).await?; + payloads.push((worker.worker_id.clone(), bytes)); + } + self.transition(origin)?; + let world = payloads.remove(0).1; + self.audit.push(format!("captured-payloads:{checkpoint_id}@{boundary}")); + Ok((boundary, world, payloads)) + } + /// The world's compatibility as this composition declares it. fn world_compatibility(&self, descriptor: &EnvironmentDescriptor) -> crate::state::Compatibility { let mut compatibility = crate::state::Compatibility::of(descriptor); @@ -1477,6 +1566,9 @@ pub struct RollbackDetails { #[derive(Clone, Debug)] pub struct ImportSpec { pub checkpoint_id: Id, + /// The scope the payloads record as their source (for a FLYSIM01 file, + /// `legacy_checkpoint::legacy_source_scope`: the session, epoch `legacy`, the boundary). + pub source_scope: Scope, /// The boundary the checkpoint is at. pub boundary: u64, /// The environment's `State.Capture` payload. @@ -2043,6 +2135,16 @@ impl Coordinator { "step", )); }; + if let Some((boundary, _)) = &self.pending_rollback { + let boundary = *boundary; + return Err(self.fail_now( + DomainError::before( + ErrorCode::InvalidPhase, + format!("the rollback asked for at boundary {boundary} has not been applied"), + ), + "step", + )); + } if self.episode.is_some() { return Err(self.fail_now( DomainError::before( @@ -2221,9 +2323,16 @@ impl Coordinator { && request.kind == EpisodeRequestKind::Rollback { let request = request.clone(); - let (action, details) = self.apply_rollback(k + 1, &request).await?; - boundary_actions.push(action); - rollback_details = Some(details); + if self.defer_rollbacks { + // The host takes its captures at this boundary first (a milestone archive is + // captured after the slot save and before the rollback, legacy-gameboy-v1 + // section 16), then applies it: `apply_pending_rollback`. + self.pending_rollback = Some((k + 1, request)); + } else { + let (action, details) = self.apply_rollback(k + 1, &request).await?; + boundary_actions.push(action); + rollback_details = Some(details); + } } let event_ids: Vec = evaluation.events.iter().map(|e| e.id.clone()).collect(); @@ -4676,59 +4785,8 @@ impl Coordinator { } } - /// The scope an imported checkpoint's payloads record as their source: this session, its - /// current epoch, the boundary the checkpoint is at. - pub fn import_scope(&self, boundary: u64) -> Scope { - self.scope(boundary) - } - - /// One participant's `State.Capture` payload at the committed boundary, outside any group - /// capture: the template an importer rewrites a foreign agent state into. - pub async fn capture_participant(&mut self, worker_id: &Id) -> Outcome> { - let Some(boundary) = self.phases.phase().committed_boundary() else { - return Err(self.fail_now( - DomainError::before(ErrorCode::InvalidPhase, "a capture needs a committed boundary"), - "capture", - )); - }; - let worker = if self.environment.worker_id == *worker_id { - self.environment.clone() - } else { - match self.agents.iter().find(|slot| slot.agent_id == *worker_id) { - Some(slot) => slot.worker.clone(), - None => { - return Err(self.fail_now( - DomainError::before( - ErrorCode::IdentityMismatch, - format!("{worker_id} is not a participant"), - ), - "capture", - )); - } - } - }; - let params = object( - CaptureParams { checkpoint_id: id(&format!("template-{worker_id}")) }.to_json(), - ); - let want = vec![crate::state::PAYLOAD_ATTACHMENT.to_owned()]; - let reply = self - .call(&worker, "State.Capture", Some(self.scope(boundary)), params, &[], &want) - .await?; - let artifact = reply.artifacts.get(crate::state::PAYLOAD_ATTACHMENT).cloned(); - let Some(artifact) = artifact else { - return Err(self.fail_now( - DomainError::before(ErrorCode::BufferInvalid, "State.Capture carried no payload"), - "capture", - )); - }; - let bytes = artifact.read_all().await.map_err(|e| { - self.fail_now( - DomainError::before(ErrorCode::BufferInvalid, e.message.clone()), - "capture", - ) - })?; - self.acknowledge_replies(&worker, std::slice::from_ref(&reply.request_id)).await?; - Ok(bytes) + pub fn session_id(&self) -> &Id { + &self.session_id } /// Installs a checkpoint of another format as this session's start (TASK-01: the legacy @@ -4759,6 +4817,15 @@ impl Coordinator { } let descriptor = self.descriptor.clone().expect("bootstrapped"); let boundary = spec.boundary; + if spec.source_scope.step != boundary || spec.source_scope.session_id != self.session_id { + return Err(self.fail_now( + DomainError::before( + ErrorCode::IdentityMismatch, + "an import's source scope is this session at the imported boundary", + ), + "import", + )); + } let world_time = RationalNs::reduced( u128::from(descriptor.step_duration.numerator) * u128::from(boundary), u128::from(descriptor.step_duration.denominator), @@ -4881,7 +4948,7 @@ impl Coordinator { } let manifest = crate::state::CheckpointManifest { checkpoint_id: spec.checkpoint_id.clone(), - source_scope: self.scope(boundary), + source_scope: spec.source_scope.clone(), episode_id: self.episode_id.clone(), world_time, scheduler_id: "lockstep-v1".to_owned(),