From f0981825a0a2df14535f87562c48ba1c2616a2ca Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 17:17:56 +0000 Subject: [PATCH] FLYSIM01 carries the reinforcement count; the import takes its ids from the file; StageRestore refuses conflicts before building a network AGENT-01 review: learning.updates fell back to plasticity.updates on every FLYSIM01 round trip. Both runtimes now count reinforcement calls the same way (one per commit while the rule is enabled) and write the count as the optional manifest member reinforcements, which old readers ignore and old files lack (a reader then starts from plasticity.updates, once). The import's checkpoint id is the file's generation (flysim01-g), and the agent worker checks for a staged or activated restore before it builds the replacement network. --- .../crates/fly-session/src/legacy_agent.rs | 57 ++++++++----- .../fly-session/src/legacy_checkpoint.rs | 81 +++++++++++++++++-- .../crates/fly-session/src/legacy_parity.rs | 24 +++++- .../flysim/crates/flysim-store/src/store.rs | 20 +++++ services/flysim/crates/flysim/src/frame.rs | 13 +++ services/flysim/crates/flysim/src/reset.rs | 1 + services/flysim/crates/flysim/src/simloop.rs | 1 + .../crates/flysim/tests/compat_migration.rs | 1 + .../flysim/crates/flysim/tests/state_02.rs | 8 +- .../crates/flysim/tests/state_02_store.rs | 25 +++++- services/flysim/crates/flysim/tests/store.rs | 1 + 11 files changed, 193 insertions(+), 39 deletions(-) diff --git a/services/flysim/crates/fly-session/src/legacy_agent.rs b/services/flysim/crates/fly-session/src/legacy_agent.rs index 876fc8c..3367247 100644 --- a/services/flysim/crates/fly-session/src/legacy_agent.rs +++ b/services/flysim/crates/fly-session/src/legacy_agent.rs @@ -312,6 +312,19 @@ pub fn encode_payload( encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| e.to_string()) } +/// The reinforcement calls a `FLYAGT01` capture payload records (`learning.updates`). +pub fn decode_payload_reinforcements(bytes: &[u8]) -> Result { + let parts = decode_envelope(bytes, PAYLOAD_MAGIC) + .map_err(|e| format!("not a {PAYLOAD_MAGIC} envelope: {e}"))?; + let session = parts.manifest.get("session").ok_or("the agent payload has no session member")?; + let session: Value = serde_json::from_str(&session.stringify()).map_err(|e| e.to_string())?; + session + .get("reinforcements") + .and_then(Value::as_str) + .and_then(|text| text.parse().ok()) + .ok_or_else(|| "the agent payload has no reinforcement count".to_owned()) +} + /// The agent state a `FLYAGT01` capture payload carries, with the accumulator's remainder in it. /// The `session` member is not validated here; `State.StageRestore` does that. pub fn decode_payload_state(bytes: &[u8]) -> Result { @@ -1536,6 +1549,29 @@ impl LegacyAgentWorker { if !state.warmed_up { return Err(incompatible("the staged agent state was never warmed up")); } + // The conflicts first: a worker already holding a staged restore, or a token already + // activated, is refused before a replacement network is built for nothing. + if let Some(staged) = &self.staged { + return Err(DomainError::before( + ErrorCode::Conflict, + format!( + "this worker already holds the staged restore {} for checkpoint {}", + staged.token, staged.checkpoint_id + ), + )); + } + 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 worker", + )); + } // A replacement fly: the dataset is loaded and checked here, not trusted. let dataset = self.dataset()?; let (mut agent, graph) = self.build_agent(dataset.clone(), seed)?; @@ -1560,27 +1596,6 @@ impl LegacyAgentWorker { } agent.network.set_visual_frame(frame, width, height); } - if let Some(staged) = &self.staged { - return Err(DomainError::before( - ErrorCode::Conflict, - format!( - "this worker already holds the staged restore {} for checkpoint {}", - staged.token, staged.checkpoint_id - ), - )); - } - 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 worker", - )); - } self.staged = Some(StagedAgent { token: token.clone(), checkpoint_id: params.checkpoint_id.clone(), diff --git a/services/flysim/crates/fly-session/src/legacy_checkpoint.rs b/services/flysim/crates/fly-session/src/legacy_checkpoint.rs index 8ff27ad..7e0210a 100644 --- a/services/flysim/crates/fly-session/src/legacy_checkpoint.rs +++ b/services/flysim/crates/fly-session/src/legacy_checkpoint.rs @@ -112,6 +112,9 @@ pub struct HostHalf { #[derive(Clone, Debug)] pub struct Halves { pub agent: AgentState, + /// The agent's reinforcement calls (`learning.updates`): the file's `reinforcements`, or + /// [`legacy_reinforcements`] for a file from before the counter. + pub reinforcements: u64, pub world: WorldState, pub task: TaskHalf, pub host: HostHalf, @@ -132,6 +135,7 @@ pub fn world_state(world_payload: &[u8]) -> Result { /// The `FLYSIM01` runtime fields of one boundary, exactly as `Sim::snapshot_state` fills them. pub fn runtime_state( + reinforcements: u64, world: &WorldState, slot_id: &Id, task: &TaskHalf, @@ -158,6 +162,7 @@ pub fn runtime_state( last_event_id: host.last_event_id, reward: task.reward.clone(), ratchet: task.ratchet, + reinforcements: Some(reinforcements), emulator, framebuffer, ratchet_game, @@ -169,12 +174,14 @@ pub fn runtime_state( /// and the host's. pub fn export_states( agent: &AgentState, + reinforcements: u64, world: &WorldState, slot_id: &Id, task: &TaskHalf, host: &HostHalf, ) -> Result, String> { - store::encode(agent, &runtime_state(world, slot_id, task, host)).map_err(|e| format!("{e:#}")) + store::encode(agent, &runtime_state(reinforcements, world, slot_id, task, host)) + .map_err(|e| format!("{e:#}")) } /// The `FLYSIM01` envelope of one boundary, from the two participants' capture payloads. @@ -186,8 +193,9 @@ pub fn export( host: &HostHalf, ) -> Result, String> { let agent = agent_state(agent_payload)?; + let reinforcements = legacy_agent::decode_payload_reinforcements(agent_payload)?; let world = world_state(world_payload)?; - export_states(&agent, &world, slot_id, task, host) + export_states(&agent, reinforcements, &world, slot_id, task, host) } // ------------------------------------------------------------------------------------------- @@ -213,6 +221,9 @@ pub fn halves( } .into_state(episode_id, slot_id, audio_sample_rate)?; Ok(Halves { + reinforcements: runtime + .reinforcements + .unwrap_or_else(|| legacy_reinforcements(&checkpoint.agent)), agent: checkpoint.agent.clone(), world, task: TaskHalf { @@ -288,6 +299,7 @@ pub struct AgentImport { /// outcome and not to its own bytes (`legacy-gameboy-v1` section 16 amendment of 2026-09-29). pub fn agent_payload( state: &AgentState, + reinforcements: u64, frame_on_screen: &[u8], import: &AgentImport, checkpoint_id: &Id, @@ -304,7 +316,7 @@ pub fn agent_payload( committed_step: source_scope.step, profile: &import.profile, seed: import.seed, - reinforcements: legacy_reinforcements(state), + reinforcements, macro_channels: &import.macro_channels, }, &accumulator, @@ -329,6 +341,12 @@ pub fn world_payload( }) } +/// The checkpoint id of the payloads imported from a `FLYSIM01` file: its generation, so two +/// imports of one file name the same checkpoint and imports of two files never do. +pub fn import_checkpoint_id(generation: u64) -> Id { + id(&format!("flysim01-g{generation}")) +} + /// The scope a payload made from a `FLYSIM01` file records as its source: the session, the /// [`LEGACY_SOURCE_EPOCH`] and the world's boundary. pub fn legacy_source_scope(session_id: &Id, boundary: u64) -> Scope { @@ -852,7 +870,7 @@ mod tests { fn the_export_is_the_legacy_encoder_on_the_same_values_and_splits_back_into_its_halves() { let agent = agent(9_000.0, 0.75, 3.0); let world = world_at(12_344, true); - let bytes = export_states(&agent, &world, &id("best"), &task(), &host(4)).unwrap(); + let bytes = export_states(&agent, 55, &world, &id("best"), &task(), &host(4)).unwrap(); // Field for field what `Sim::snapshot_state` builds, through the one encoder. let legacy = store::encode( &agent, @@ -868,6 +886,7 @@ mod tests { last_event_id: 77, reward: task().reward, ratchet: task().ratchet, + reinforcements: Some(55), emulator: vec![7; 64], framebuffer: vec![9; FRAMEBUFFER_LEN], ratchet_game: vec![1, 2, 3], @@ -878,11 +897,12 @@ mod tests { assert_eq!(bytes, legacy); let back = split(&bytes, &id("ep1"), &id("best"), 48_000).unwrap(); assert_eq!(back.agent, agent); + assert_eq!(back.reinforcements, 55); assert_eq!(back.world, world); assert_eq!(back.task, task()); assert_eq!(back.host, host(4)); // And no slot is an empty ratchet snapshot, both ways. - let bytes = export_states(&agent, &world_at(5, false), &id("best"), &task(), &host(1)).unwrap(); + let bytes = export_states(&agent, 3, &world_at(5, false), &id("best"), &task(), &host(1)).unwrap(); let back = split(&bytes, &id("ep1"), &id("best"), 48_000).unwrap(); assert!(back.world.slots.is_empty()); } @@ -899,13 +919,13 @@ mod tests { }; let scope = legacy_source_scope(&id("s1"), world.boundary); let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed(); - let agent_bytes = agent_payload(&agent, &world.framebuffer, &import, &id("c1"), &scope, &context).unwrap(); + let agent_bytes = agent_payload(&agent, 70, &world.framebuffer, &import, &id("c1"), &scope, &context).unwrap(); let world_bytes = world_payload(&world, &id("world"), &id("c1"), &scope, &"cd".repeat(32)); assert_eq!(agent_state(&agent_bytes).unwrap(), agent); assert_eq!(world_state(&world_bytes).unwrap(), world); assert_eq!( export(&agent_bytes, &world_bytes, &id("best"), &task(), &host(9)).unwrap(), - export_states(&agent, &world, &id("best"), &task(), &host(9)).unwrap() + export_states(&agent, 70, &world, &id("best"), &task(), &host(9)).unwrap() ); assert!(export(&world_bytes, &agent_bytes, &id("best"), &task(), &host(9)).is_err()); } @@ -935,6 +955,7 @@ mod tests { gameboy::ReadoutContext { boot: true, bound: vec![], location: None }.to_typed(); let bytes = agent_payload( &state, + legacy_reinforcements(&state), &[0; FRAMEBUFFER_LEN], &import, &id("c1"), @@ -958,6 +979,50 @@ mod tests { assert_eq!(session["accumulator"]["warmupOffset"], "2500"); } + #[test] + fn the_reinforcement_count_survives_every_round_trip_and_starts_at_the_lower_bound_once() { + // A file from before the counter: the import starts at plasticity.updates. + let agent = agent(9_000.0, 0.75, 40.0); + let world = world_at(10, true); + let mut runtime = runtime_state(0, &world, &id("best"), &task(), &host(1)); + runtime.reinforcements = None; + let old = store::encode(&agent, &runtime).unwrap(); + let halves = split(&old, &id("ep1"), &id("best"), 48_000).unwrap(); + assert_eq!(halves.reinforcements, 40); + // The session runs on and counts 900 more calls than the gains moved; the export carries + // them, and every later import, legacy or session, starts where the last one stopped. + let bytes = export_states(&agent, 940, &world, &id("best"), &task(), &host(2)).unwrap(); + let again = split(&bytes, &id("ep1"), &id("best"), 48_000).unwrap(); + assert_eq!(again.reinforcements, 940); + let import = AgentImport { + agent_id: id("fly"), + profile: gameboy::profile_asset_ref(), + seed: 22_222, + macro_channels: Vec::new(), + }; + let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed(); + let payload = agent_payload( + &again.agent, + again.reinforcements, + &again.world.framebuffer, + &import, + &import_checkpoint_id(again.host.generation), + &legacy_source_scope(&id("s1"), again.world.boundary), + &context, + ) + .unwrap(); + assert_eq!(crate::legacy_agent::decode_payload_reinforcements(&payload).unwrap(), 940); + let world_bytes = world_payload( + &again.world, + &id("world"), + &import_checkpoint_id(again.host.generation), + &legacy_source_scope(&id("s1"), again.world.boundary), + &"cd".repeat(32), + ); + assert_eq!(export(&payload, &world_bytes, &id("best"), &again.task, &again.host).unwrap(), bytes); + assert_eq!(import_checkpoint_id(2), id("flysim01-g2")); + } + #[test] fn the_task_ledger_carries_exactly_the_reward_and_the_ratchet() { let ledger = task().to_ledger(true); @@ -984,7 +1049,7 @@ mod tests { let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed(); LegacyCapture { boundary, - agent_payload: agent_payload(&agent, &world.framebuffer, &import, &id("c"), &scope, &context) + agent_payload: agent_payload(&agent, 3, &world.framebuffer, &import, &id("c"), &scope, &context) .unwrap(), world_payload: world_payload(&world, &id("world"), &id("c"), &scope, &"cd".repeat(32)), task: task(), diff --git a/services/flysim/crates/fly-session/src/legacy_parity.rs b/services/flysim/crates/fly-session/src/legacy_parity.rs index 07af25f..24d5f41 100644 --- a/services/flysim/crates/fly-session/src/legacy_parity.rs +++ b/services/flysim/crates/fly-session/src/legacy_parity.rs @@ -1462,6 +1462,20 @@ impl AgentDriver { agent_id: &Id, initial_frame: usize, state: &flybrain_core::agent::AgentState, + ) -> Result { + self.seed_with_reinforcements(rig, agent_id, initial_frame, state, legacy_reinforcements(state)) + .await + } + + /// [`AgentDriver::seed_from_legacy_state`] with the reinforcement count a `FLYSIM01` file + /// records (`legacy_checkpoint::Halves::reinforcements`). + pub async fn seed_with_reinforcements( + &mut self, + rig: &mut LegacyRig, + agent_id: &Id, + initial_frame: usize, + state: &flybrain_core::agent::AgentState, + reinforcements: u64, ) -> Result { self.initialize(initial_frame).await?; let template = self.capture().await?; @@ -1478,6 +1492,7 @@ impl AgentDriver { }; let bytes = crate::legacy_checkpoint::agent_payload( state, + reinforcements, &self.frames[initial_frame], &import, &template.result.checkpoint_id, @@ -1544,6 +1559,7 @@ pub async fn run_on_worker_from( script: &LegacyScript, start: Option<&flybrain_core::agent::AgentState>, ) -> Result, String> { + let start = start.map(|state| (state, legacy_reinforcements(state))); run_script(rig, agent_id, script, start, false) .await .map(|(records, _)| records) @@ -1555,7 +1571,7 @@ pub async fn run_on_worker_from_then_capture( rig: &mut LegacyRig, agent_id: &Id, script: &LegacyScript, - start: Option<&flybrain_core::agent::AgentState>, + start: Option<(&flybrain_core::agent::AgentState, u64)>, ) -> Result<(Vec, Vec), String> { let (records, captured) = run_script(rig, agent_id, script, start, true).await?; Ok((records, captured.expect("a capture was asked for"))) @@ -1565,15 +1581,15 @@ async fn run_script( rig: &mut LegacyRig, agent_id: &Id, script: &LegacyScript, - start: Option<&flybrain_core::agent::AgentState>, + start: Option<(&flybrain_core::agent::AgentState, u64)>, capture_at_end: bool, ) -> Result<(Vec, Option>), String> { let mut driver = rig.driver(agent_id, script); let first = match start { None => driver.initialize(script.initial_frame).await?, - Some(state) => { + Some((state, reinforcements)) => { driver - .seed_from_legacy_state(rig, agent_id, script.initial_frame, state) + .seed_with_reinforcements(rig, agent_id, script.initial_frame, state, reinforcements) .await? } }; diff --git a/services/flysim/crates/flysim-store/src/store.rs b/services/flysim/crates/flysim-store/src/store.rs index 586e6c0..2e4e562 100644 --- a/services/flysim/crates/flysim-store/src/store.rs +++ b/services/flysim/crates/flysim-store/src/store.rs @@ -290,6 +290,11 @@ pub struct RuntimeState { /// The adapter's own lifetime reward state. pub reward: serde_json::Value, pub ratchet: flybrain_gb::RatchetState, + /// Reinforcement calls the fly has had: one per committed frame while the rule is enabled, + /// zero sums included (the session runtime's `learning.updates`). An optional manifest member + /// since STATE-02 (2026-09-29): a file without it predates the counter, and a reader starts + /// from its `plasticity.updates`, a lower bound. Readers that do not know it ignore it. + pub reinforcements: Option, pub emulator: Vec, pub framebuffer: Vec, /// The ratchet's best safe snapshot, if it has one. @@ -322,6 +327,9 @@ pub fn encode( manifest.set("lastEventId", (runtime.last_event_id as f64).into()); manifest.set("reward", to_json_value(&runtime.reward)?); manifest.set("ratchet", to_json_value(&serde_json::to_value(runtime.ratchet)?)?); + if let Some(reinforcements) = runtime.reinforcements { + manifest.set("reinforcements", (reinforcements as f64).into()); + } let mut chunks = parts.chunks; chunks.push((EMULATOR_CHUNK.to_string(), runtime.emulator.clone())); @@ -389,6 +397,7 @@ pub fn decode(bytes: &[u8]) -> Result { last_event_id: number("lastEventId").unwrap_or(0.0) as u64, reward, ratchet, + reinforcements: number("reinforcements").ok().map(|n| n as u64), emulator: chunk(EMULATOR_CHUNK)?, framebuffer: chunk(FRAMEBUFFER_CHUNK)?, ratchet_game: chunk(RATCHET_GAME_CHUNK)?, @@ -456,6 +465,7 @@ mod tests { last_event_id: 77, reward: serde_json::json!({ "version": 3, "total": 1.25 }), ratchet: flybrain_gb::RatchetState { best: 3, ..Default::default() }, + reinforcements: Some(1_234), emulator: vec![7; 64], framebuffer: vec![9; 32], ratchet_game: vec![1, 2, 3], @@ -524,6 +534,16 @@ mod tests { assert_eq!(encode(&back.agent, &back.runtime).unwrap(), bytes); } + #[test] + fn a_file_without_the_reinforcement_count_still_reads_and_writes_as_before() { + let runtime = RuntimeState { reinforcements: None, ..runtime(4) }; + let bytes = encode(&agent_state(), &runtime).unwrap(); + assert!(!String::from_utf8_lossy(&bytes[..4096.min(bytes.len())]).contains("reinforcements")); + let back = decode(&bytes).unwrap(); + assert_eq!(back.runtime.reinforcements, None); + assert_eq!(encode(&back.agent, &back.runtime).unwrap(), bytes); + } + #[test] fn a_corrupted_or_truncated_envelope_is_rejected() { let bytes = encode(&agent_state(), &runtime(1)).unwrap(); diff --git a/services/flysim/crates/flysim/src/frame.rs b/services/flysim/crates/flysim/src/frame.rs index 8b023c8..d916a56 100644 --- a/services/flysim/crates/flysim/src/frame.rs +++ b/services/flysim/crates/flysim/src/frame.rs @@ -198,6 +198,11 @@ pub struct LegacyFrame { pub location: Option<(u32, u32, u32)>, pub held_channel: Option, pub blocked_since_ms: f64, + /// Reinforcement calls since the fly's fresh start: one per commit while the rule is + /// enabled, zero sums included; checkpointed (`reinforcements`, STATE-02). It is the session + /// agent's `learning.updates`, counted the same way, so a checkpoint carries it across both + /// runtimes. Counting changes nothing the fly does. + pub reinforcements: u64, trace: Option, } @@ -219,6 +224,7 @@ impl LegacyFrame { location: None, held_channel: None, blocked_since_ms: 0.0, + reinforcements: 0, trace: None, } } @@ -248,6 +254,7 @@ impl LegacyFrame { .map_err(|error| anyhow!("running the first frame: {error}"))?; self.frame_buffer.copy_from_slice(emulator.framebuffer()); self.frame_counter = 1; + self.reinforcements = 0; let audio = emulator.take_audio_u8(); agent .warmup(Some(&self.frame_buffer)) @@ -305,6 +312,11 @@ impl LegacyFrame { .map_err(|error| anyhow!("{error}"))?; self.remainder = checkpoint.agent.remainder; + // A file from before the counter starts it at the recorded `plasticity.updates`, a lower + // bound (legacy-gameboy-v1 section 13 amendment of 2026-09-29). + self.reinforcements = runtime + .reinforcements + .unwrap_or(checkpoint.agent.network.plasticity.updates as u64); self.frame_counter = runtime.emulator_frame; self.buttons = runtime.buttons; self.frame_buffer.copy_from_slice(&runtime.framebuffer); @@ -576,6 +588,7 @@ impl LegacyFrame { } if agent.network.plasticity.enabled { agent.network.plasticity.reinforce(total, ms); + self.reinforcements += 1; } } diff --git a/services/flysim/crates/flysim/src/reset.rs b/services/flysim/crates/flysim/src/reset.rs index 3256270..c142541 100644 --- a/services/flysim/crates/flysim/src/reset.rs +++ b/services/flysim/crates/flysim/src/reset.rs @@ -326,6 +326,7 @@ mod tests { }, }; let runtime = store::RuntimeState { + reinforcements: None, generation, wall_ms: 1_700_000_000_000, rom_sha256: "ab".repeat(32), diff --git a/services/flysim/crates/flysim/src/simloop.rs b/services/flysim/crates/flysim/src/simloop.rs index 7604081..f83d831 100644 --- a/services/flysim/crates/flysim/src/simloop.rs +++ b/services/flysim/crates/flysim/src/simloop.rs @@ -1396,6 +1396,7 @@ impl Sim { last_event_id: self.log.next_id().saturating_sub(1), reward: self.adapter.export_state(), ratchet: self.ratchet.state, + reinforcements: Some(self.frame.reinforcements), emulator: self .emulator .export_state() diff --git a/services/flysim/crates/flysim/tests/compat_migration.rs b/services/flysim/crates/flysim/tests/compat_migration.rs index 2234d56..cf70694 100644 --- a/services/flysim/crates/flysim/tests/compat_migration.rs +++ b/services/flysim/crates/flysim/tests/compat_migration.rs @@ -113,6 +113,7 @@ fn v6_checkpoint() -> Vec { }, }; let runtime = RuntimeState { + reinforcements: None, generation: 41, wall_ms: 1_790_000_000_000, rom_sha256: flybrain_gb::pokemon_red::SUPPORTED_ROM.to_string(), diff --git a/services/flysim/crates/flysim/tests/state_02.rs b/services/flysim/crates/flysim/tests/state_02.rs index a23b39a..984009f 100644 --- a/services/flysim/crates/flysim/tests/state_02.rs +++ b/services/flysim/crates/flysim/tests/state_02.rs @@ -127,6 +127,7 @@ fn first_difference(left: &[u8], right: &[u8]) -> String { ("lastEventId", a.runtime.last_event_id == b.runtime.last_event_id), ("reward", a.runtime.reward == b.runtime.reward), ("ratchet", a.runtime.ratchet == b.runtime.ratchet), + ("reinforcements", a.runtime.reinforcements == b.runtime.reinforcements), ("emulator", a.runtime.emulator == b.runtime.emulator), ("framebuffer", a.runtime.framebuffer == b.runtime.framebuffer), ("ratchetGame", a.runtime.ratchet_game == b.runtime.ratchet_game), @@ -290,6 +291,7 @@ async fn every_real_checkpoint_round_trips_legacy_session_legacy() { let restored_context = ReadoutContext { boot: false, bound: vec![], location: None }; let agent_bytes = lc::agent_payload( &halves.agent, + halves.reinforcements, &halves.world.framebuffer, &import, &id("c1"), @@ -328,6 +330,7 @@ async fn every_real_checkpoint_round_trips_legacy_session_legacy() { let legacy = store::encode( &checkpoint.agent, &RuntimeState { + reinforcements: Some(halves.reinforcements), emulator: emulator.export_state().expect("the emulator exports"), reward: legacy_task.reward, ratchet: legacy_task.ratchet, @@ -453,6 +456,7 @@ impl LegacyWorld { last_event_id: host.last_event_id, reward: self.adapter.export_state(), ratchet: self.ratchet.state, + reinforcements: Some(self.frame.reinforcements), emulator: self.emulator.export_state().expect("the emulator exports"), framebuffer: self.frame.frame_buffer.clone(), ratchet_game: self.ratchet.game().map(<[u8]>::to_vec).unwrap_or_default(), @@ -650,7 +654,7 @@ async fn restore_then_continue( &mut agents, &id("fly"), &script, - Some(&halves.agent), + Some((&halves.agent, halves.reinforcements)), ) .await .expect("the agent runs"); @@ -693,7 +697,7 @@ async fn restore_then_continue( &mut agents, &id("fly"), &one_step, - Some(&again.agent), + Some((&again.agent, again.reinforcements)), ) .await .expect("the agent imports the export"); diff --git a/services/flysim/crates/flysim/tests/state_02_store.rs b/services/flysim/crates/flysim/tests/state_02_store.rs index 89b10e5..df8541f 100644 --- a/services/flysim/crates/flysim/tests/state_02_store.rs +++ b/services/flysim/crates/flysim/tests/state_02_store.rs @@ -105,7 +105,7 @@ fn capture(k: u64, ratchet: RatchetState) -> LegacyCapture { let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed(); LegacyCapture { boundary: k, - agent_payload: lc::agent_payload(&agent(9_000.0 + k as f64), &world(k).framebuffer, &import, &id("c"), &scope, &context) + agent_payload: lc::agent_payload(&agent(9_000.0 + k as f64), 17 + k, &world(k).framebuffer, &import, &id("c"), &scope, &context) .unwrap(), world_payload: lc::world_payload(&world(k), &id("world"), &id("c"), &scope, &"cd".repeat(32)), task: TaskHalf { reward: serde_json::Value::Null, ratchet }, @@ -306,6 +306,7 @@ fn a_store_the_legacy_loop_wrote_and_the_tools_reset_is_restored_by_the_session_ last_event_id: k, reward: serde_json::Value::Null, ratchet, + reinforcements: None, emulator: vec![(k % 251) as u8; 256], framebuffer: vec![9; FRAMEBUFFER_LEN], ratchet_game: vec![1; 32], @@ -328,7 +329,23 @@ fn a_store_the_legacy_loop_wrote_and_the_tools_reset_is_restored_by_the_session_ assert_eq!(restored.installed.task.ratchet.attempts, 0); // And what the session runtime would save from it is the legacy bytes again. let halves = &restored.installed; - let again = lc::export_states(&halves.agent, &halves.world, &id("best"), &halves.task, &halves.host) - .unwrap(); - assert_eq!(again, std::fs::read(&restored.candidate.path).unwrap()); + // And the session runtime would save it as the legacy loop's own restore would: the same + // bytes plus the reinforcement count the legacy loop now also writes (from the lower bound). + assert_eq!(halves.reinforcements, 17); + let again = lc::export_states( + &halves.agent, + halves.reinforcements, + &halves.world, + &id("best"), + &halves.task, + &halves.host, + ) + .unwrap(); + let file = store::load(&restored.candidate.path).unwrap(); + let expected = store::encode( + &file.agent, + &RuntimeState { reinforcements: Some(17), ..file.runtime }, + ) + .unwrap(); + assert_eq!(again, expected); } diff --git a/services/flysim/crates/flysim/tests/store.rs b/services/flysim/crates/flysim/tests/store.rs index 983a1e9..536c336 100644 --- a/services/flysim/crates/flysim/tests/store.rs +++ b/services/flysim/crates/flysim/tests/store.rs @@ -67,6 +67,7 @@ fn agent_state() -> flybrain_core::agent::AgentState { fn checkpoint(generation: u64, frame: u64, rom: &str, compatibility: &str) -> Vec { let runtime = RuntimeState { + reinforcements: None, generation, wall_ms: 1_757_000_000_000 + generation, rom_sha256: rom.to_string(),