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<N>), and the agent worker checks for a staged or activated restore before it builds the replacement network.
This commit is contained in:
parent
d211e53fab
commit
f0981825a0
11 changed files with 193 additions and 39 deletions
|
|
@ -312,6 +312,19 @@ pub fn encode_payload(
|
||||||
encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| e.to_string())
|
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<u64, String> {
|
||||||
|
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 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.
|
/// The `session` member is not validated here; `State.StageRestore` does that.
|
||||||
pub fn decode_payload_state(bytes: &[u8]) -> Result<AgentState, String> {
|
pub fn decode_payload_state(bytes: &[u8]) -> Result<AgentState, String> {
|
||||||
|
|
@ -1536,6 +1549,29 @@ impl LegacyAgentWorker {
|
||||||
if !state.warmed_up {
|
if !state.warmed_up {
|
||||||
return Err(incompatible("the staged agent state was never 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.
|
// A replacement fly: the dataset is loaded and checked here, not trusted.
|
||||||
let dataset = self.dataset()?;
|
let dataset = self.dataset()?;
|
||||||
let (mut agent, graph) = self.build_agent(dataset.clone(), seed)?;
|
let (mut agent, graph) = self.build_agent(dataset.clone(), seed)?;
|
||||||
|
|
@ -1560,27 +1596,6 @@ impl LegacyAgentWorker {
|
||||||
}
|
}
|
||||||
agent.network.set_visual_frame(frame, width, height);
|
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 {
|
self.staged = Some(StagedAgent {
|
||||||
token: token.clone(),
|
token: token.clone(),
|
||||||
checkpoint_id: params.checkpoint_id.clone(),
|
checkpoint_id: params.checkpoint_id.clone(),
|
||||||
|
|
|
||||||
|
|
@ -112,6 +112,9 @@ pub struct HostHalf {
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct Halves {
|
pub struct Halves {
|
||||||
pub agent: AgentState,
|
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 world: WorldState,
|
||||||
pub task: TaskHalf,
|
pub task: TaskHalf,
|
||||||
pub host: HostHalf,
|
pub host: HostHalf,
|
||||||
|
|
@ -132,6 +135,7 @@ pub fn world_state(world_payload: &[u8]) -> Result<WorldState, String> {
|
||||||
|
|
||||||
/// The `FLYSIM01` runtime fields of one boundary, exactly as `Sim::snapshot_state` fills them.
|
/// The `FLYSIM01` runtime fields of one boundary, exactly as `Sim::snapshot_state` fills them.
|
||||||
pub fn runtime_state(
|
pub fn runtime_state(
|
||||||
|
reinforcements: u64,
|
||||||
world: &WorldState,
|
world: &WorldState,
|
||||||
slot_id: &Id,
|
slot_id: &Id,
|
||||||
task: &TaskHalf,
|
task: &TaskHalf,
|
||||||
|
|
@ -158,6 +162,7 @@ pub fn runtime_state(
|
||||||
last_event_id: host.last_event_id,
|
last_event_id: host.last_event_id,
|
||||||
reward: task.reward.clone(),
|
reward: task.reward.clone(),
|
||||||
ratchet: task.ratchet,
|
ratchet: task.ratchet,
|
||||||
|
reinforcements: Some(reinforcements),
|
||||||
emulator,
|
emulator,
|
||||||
framebuffer,
|
framebuffer,
|
||||||
ratchet_game,
|
ratchet_game,
|
||||||
|
|
@ -169,12 +174,14 @@ pub fn runtime_state(
|
||||||
/// and the host's.
|
/// and the host's.
|
||||||
pub fn export_states(
|
pub fn export_states(
|
||||||
agent: &AgentState,
|
agent: &AgentState,
|
||||||
|
reinforcements: u64,
|
||||||
world: &WorldState,
|
world: &WorldState,
|
||||||
slot_id: &Id,
|
slot_id: &Id,
|
||||||
task: &TaskHalf,
|
task: &TaskHalf,
|
||||||
host: &HostHalf,
|
host: &HostHalf,
|
||||||
) -> Result<Vec<u8>, String> {
|
) -> Result<Vec<u8>, 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.
|
/// The `FLYSIM01` envelope of one boundary, from the two participants' capture payloads.
|
||||||
|
|
@ -186,8 +193,9 @@ pub fn export(
|
||||||
host: &HostHalf,
|
host: &HostHalf,
|
||||||
) -> Result<Vec<u8>, String> {
|
) -> Result<Vec<u8>, String> {
|
||||||
let agent = agent_state(agent_payload)?;
|
let agent = agent_state(agent_payload)?;
|
||||||
|
let reinforcements = legacy_agent::decode_payload_reinforcements(agent_payload)?;
|
||||||
let world = world_state(world_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)?;
|
.into_state(episode_id, slot_id, audio_sample_rate)?;
|
||||||
Ok(Halves {
|
Ok(Halves {
|
||||||
|
reinforcements: runtime
|
||||||
|
.reinforcements
|
||||||
|
.unwrap_or_else(|| legacy_reinforcements(&checkpoint.agent)),
|
||||||
agent: checkpoint.agent.clone(),
|
agent: checkpoint.agent.clone(),
|
||||||
world,
|
world,
|
||||||
task: TaskHalf {
|
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).
|
/// outcome and not to its own bytes (`legacy-gameboy-v1` section 16 amendment of 2026-09-29).
|
||||||
pub fn agent_payload(
|
pub fn agent_payload(
|
||||||
state: &AgentState,
|
state: &AgentState,
|
||||||
|
reinforcements: u64,
|
||||||
frame_on_screen: &[u8],
|
frame_on_screen: &[u8],
|
||||||
import: &AgentImport,
|
import: &AgentImport,
|
||||||
checkpoint_id: &Id,
|
checkpoint_id: &Id,
|
||||||
|
|
@ -304,7 +316,7 @@ pub fn agent_payload(
|
||||||
committed_step: source_scope.step,
|
committed_step: source_scope.step,
|
||||||
profile: &import.profile,
|
profile: &import.profile,
|
||||||
seed: import.seed,
|
seed: import.seed,
|
||||||
reinforcements: legacy_reinforcements(state),
|
reinforcements,
|
||||||
macro_channels: &import.macro_channels,
|
macro_channels: &import.macro_channels,
|
||||||
},
|
},
|
||||||
&accumulator,
|
&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
|
/// The scope a payload made from a `FLYSIM01` file records as its source: the session, the
|
||||||
/// [`LEGACY_SOURCE_EPOCH`] and the world's boundary.
|
/// [`LEGACY_SOURCE_EPOCH`] and the world's boundary.
|
||||||
pub fn legacy_source_scope(session_id: &Id, boundary: u64) -> Scope {
|
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() {
|
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 agent = agent(9_000.0, 0.75, 3.0);
|
||||||
let world = world_at(12_344, true);
|
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.
|
// Field for field what `Sim::snapshot_state` builds, through the one encoder.
|
||||||
let legacy = store::encode(
|
let legacy = store::encode(
|
||||||
&agent,
|
&agent,
|
||||||
|
|
@ -868,6 +886,7 @@ mod tests {
|
||||||
last_event_id: 77,
|
last_event_id: 77,
|
||||||
reward: task().reward,
|
reward: task().reward,
|
||||||
ratchet: task().ratchet,
|
ratchet: task().ratchet,
|
||||||
|
reinforcements: Some(55),
|
||||||
emulator: vec![7; 64],
|
emulator: vec![7; 64],
|
||||||
framebuffer: vec![9; FRAMEBUFFER_LEN],
|
framebuffer: vec![9; FRAMEBUFFER_LEN],
|
||||||
ratchet_game: vec![1, 2, 3],
|
ratchet_game: vec![1, 2, 3],
|
||||||
|
|
@ -878,11 +897,12 @@ mod tests {
|
||||||
assert_eq!(bytes, legacy);
|
assert_eq!(bytes, legacy);
|
||||||
let back = split(&bytes, &id("ep1"), &id("best"), 48_000).unwrap();
|
let back = split(&bytes, &id("ep1"), &id("best"), 48_000).unwrap();
|
||||||
assert_eq!(back.agent, agent);
|
assert_eq!(back.agent, agent);
|
||||||
|
assert_eq!(back.reinforcements, 55);
|
||||||
assert_eq!(back.world, world);
|
assert_eq!(back.world, world);
|
||||||
assert_eq!(back.task, task());
|
assert_eq!(back.task, task());
|
||||||
assert_eq!(back.host, host(4));
|
assert_eq!(back.host, host(4));
|
||||||
// And no slot is an empty ratchet snapshot, both ways.
|
// 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();
|
let back = split(&bytes, &id("ep1"), &id("best"), 48_000).unwrap();
|
||||||
assert!(back.world.slots.is_empty());
|
assert!(back.world.slots.is_empty());
|
||||||
}
|
}
|
||||||
|
|
@ -899,13 +919,13 @@ mod tests {
|
||||||
};
|
};
|
||||||
let scope = legacy_source_scope(&id("s1"), world.boundary);
|
let scope = legacy_source_scope(&id("s1"), world.boundary);
|
||||||
let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed();
|
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));
|
let world_bytes = world_payload(&world, &id("world"), &id("c1"), &scope, &"cd".repeat(32));
|
||||||
assert_eq!(agent_state(&agent_bytes).unwrap(), agent);
|
assert_eq!(agent_state(&agent_bytes).unwrap(), agent);
|
||||||
assert_eq!(world_state(&world_bytes).unwrap(), world);
|
assert_eq!(world_state(&world_bytes).unwrap(), world);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
export(&agent_bytes, &world_bytes, &id("best"), &task(), &host(9)).unwrap(),
|
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());
|
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();
|
gameboy::ReadoutContext { boot: true, bound: vec![], location: None }.to_typed();
|
||||||
let bytes = agent_payload(
|
let bytes = agent_payload(
|
||||||
&state,
|
&state,
|
||||||
|
legacy_reinforcements(&state),
|
||||||
&[0; FRAMEBUFFER_LEN],
|
&[0; FRAMEBUFFER_LEN],
|
||||||
&import,
|
&import,
|
||||||
&id("c1"),
|
&id("c1"),
|
||||||
|
|
@ -958,6 +979,50 @@ mod tests {
|
||||||
assert_eq!(session["accumulator"]["warmupOffset"], "2500");
|
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]
|
#[test]
|
||||||
fn the_task_ledger_carries_exactly_the_reward_and_the_ratchet() {
|
fn the_task_ledger_carries_exactly_the_reward_and_the_ratchet() {
|
||||||
let ledger = task().to_ledger(true);
|
let ledger = task().to_ledger(true);
|
||||||
|
|
@ -984,7 +1049,7 @@ mod tests {
|
||||||
let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed();
|
let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed();
|
||||||
LegacyCapture {
|
LegacyCapture {
|
||||||
boundary,
|
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(),
|
.unwrap(),
|
||||||
world_payload: world_payload(&world, &id("world"), &id("c"), &scope, &"cd".repeat(32)),
|
world_payload: world_payload(&world, &id("world"), &id("c"), &scope, &"cd".repeat(32)),
|
||||||
task: task(),
|
task: task(),
|
||||||
|
|
|
||||||
|
|
@ -1462,6 +1462,20 @@ impl AgentDriver {
|
||||||
agent_id: &Id,
|
agent_id: &Id,
|
||||||
initial_frame: usize,
|
initial_frame: usize,
|
||||||
state: &flybrain_core::agent::AgentState,
|
state: &flybrain_core::agent::AgentState,
|
||||||
|
) -> Result<ParityRecord, String> {
|
||||||
|
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<ParityRecord, String> {
|
) -> Result<ParityRecord, String> {
|
||||||
self.initialize(initial_frame).await?;
|
self.initialize(initial_frame).await?;
|
||||||
let template = self.capture().await?;
|
let template = self.capture().await?;
|
||||||
|
|
@ -1478,6 +1492,7 @@ impl AgentDriver {
|
||||||
};
|
};
|
||||||
let bytes = crate::legacy_checkpoint::agent_payload(
|
let bytes = crate::legacy_checkpoint::agent_payload(
|
||||||
state,
|
state,
|
||||||
|
reinforcements,
|
||||||
&self.frames[initial_frame],
|
&self.frames[initial_frame],
|
||||||
&import,
|
&import,
|
||||||
&template.result.checkpoint_id,
|
&template.result.checkpoint_id,
|
||||||
|
|
@ -1544,6 +1559,7 @@ pub async fn run_on_worker_from(
|
||||||
script: &LegacyScript,
|
script: &LegacyScript,
|
||||||
start: Option<&flybrain_core::agent::AgentState>,
|
start: Option<&flybrain_core::agent::AgentState>,
|
||||||
) -> Result<Vec<ParityRecord>, String> {
|
) -> Result<Vec<ParityRecord>, String> {
|
||||||
|
let start = start.map(|state| (state, legacy_reinforcements(state)));
|
||||||
run_script(rig, agent_id, script, start, false)
|
run_script(rig, agent_id, script, start, false)
|
||||||
.await
|
.await
|
||||||
.map(|(records, _)| records)
|
.map(|(records, _)| records)
|
||||||
|
|
@ -1555,7 +1571,7 @@ pub async fn run_on_worker_from_then_capture(
|
||||||
rig: &mut LegacyRig,
|
rig: &mut LegacyRig,
|
||||||
agent_id: &Id,
|
agent_id: &Id,
|
||||||
script: &LegacyScript,
|
script: &LegacyScript,
|
||||||
start: Option<&flybrain_core::agent::AgentState>,
|
start: Option<(&flybrain_core::agent::AgentState, u64)>,
|
||||||
) -> Result<(Vec<ParityRecord>, Vec<u8>), String> {
|
) -> Result<(Vec<ParityRecord>, Vec<u8>), String> {
|
||||||
let (records, captured) = run_script(rig, agent_id, script, start, true).await?;
|
let (records, captured) = run_script(rig, agent_id, script, start, true).await?;
|
||||||
Ok((records, captured.expect("a capture was asked for")))
|
Ok((records, captured.expect("a capture was asked for")))
|
||||||
|
|
@ -1565,15 +1581,15 @@ async fn run_script(
|
||||||
rig: &mut LegacyRig,
|
rig: &mut LegacyRig,
|
||||||
agent_id: &Id,
|
agent_id: &Id,
|
||||||
script: &LegacyScript,
|
script: &LegacyScript,
|
||||||
start: Option<&flybrain_core::agent::AgentState>,
|
start: Option<(&flybrain_core::agent::AgentState, u64)>,
|
||||||
capture_at_end: bool,
|
capture_at_end: bool,
|
||||||
) -> Result<(Vec<ParityRecord>, Option<Vec<u8>>), String> {
|
) -> Result<(Vec<ParityRecord>, Option<Vec<u8>>), String> {
|
||||||
let mut driver = rig.driver(agent_id, script);
|
let mut driver = rig.driver(agent_id, script);
|
||||||
let first = match start {
|
let first = match start {
|
||||||
None => driver.initialize(script.initial_frame).await?,
|
None => driver.initialize(script.initial_frame).await?,
|
||||||
Some(state) => {
|
Some((state, reinforcements)) => {
|
||||||
driver
|
driver
|
||||||
.seed_from_legacy_state(rig, agent_id, script.initial_frame, state)
|
.seed_with_reinforcements(rig, agent_id, script.initial_frame, state, reinforcements)
|
||||||
.await?
|
.await?
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -290,6 +290,11 @@ pub struct RuntimeState {
|
||||||
/// The adapter's own lifetime reward state.
|
/// The adapter's own lifetime reward state.
|
||||||
pub reward: serde_json::Value,
|
pub reward: serde_json::Value,
|
||||||
pub ratchet: flybrain_gb::RatchetState,
|
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<u64>,
|
||||||
pub emulator: Vec<u8>,
|
pub emulator: Vec<u8>,
|
||||||
pub framebuffer: Vec<u8>,
|
pub framebuffer: Vec<u8>,
|
||||||
/// The ratchet's best safe snapshot, if it has one.
|
/// 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("lastEventId", (runtime.last_event_id as f64).into());
|
||||||
manifest.set("reward", to_json_value(&runtime.reward)?);
|
manifest.set("reward", to_json_value(&runtime.reward)?);
|
||||||
manifest.set("ratchet", to_json_value(&serde_json::to_value(runtime.ratchet)?)?);
|
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;
|
let mut chunks = parts.chunks;
|
||||||
chunks.push((EMULATOR_CHUNK.to_string(), runtime.emulator.clone()));
|
chunks.push((EMULATOR_CHUNK.to_string(), runtime.emulator.clone()));
|
||||||
|
|
@ -389,6 +397,7 @@ pub fn decode(bytes: &[u8]) -> Result<Checkpoint> {
|
||||||
last_event_id: number("lastEventId").unwrap_or(0.0) as u64,
|
last_event_id: number("lastEventId").unwrap_or(0.0) as u64,
|
||||||
reward,
|
reward,
|
||||||
ratchet,
|
ratchet,
|
||||||
|
reinforcements: number("reinforcements").ok().map(|n| n as u64),
|
||||||
emulator: chunk(EMULATOR_CHUNK)?,
|
emulator: chunk(EMULATOR_CHUNK)?,
|
||||||
framebuffer: chunk(FRAMEBUFFER_CHUNK)?,
|
framebuffer: chunk(FRAMEBUFFER_CHUNK)?,
|
||||||
ratchet_game: chunk(RATCHET_GAME_CHUNK)?,
|
ratchet_game: chunk(RATCHET_GAME_CHUNK)?,
|
||||||
|
|
@ -456,6 +465,7 @@ mod tests {
|
||||||
last_event_id: 77,
|
last_event_id: 77,
|
||||||
reward: serde_json::json!({ "version": 3, "total": 1.25 }),
|
reward: serde_json::json!({ "version": 3, "total": 1.25 }),
|
||||||
ratchet: flybrain_gb::RatchetState { best: 3, ..Default::default() },
|
ratchet: flybrain_gb::RatchetState { best: 3, ..Default::default() },
|
||||||
|
reinforcements: Some(1_234),
|
||||||
emulator: vec![7; 64],
|
emulator: vec![7; 64],
|
||||||
framebuffer: vec![9; 32],
|
framebuffer: vec![9; 32],
|
||||||
ratchet_game: vec![1, 2, 3],
|
ratchet_game: vec![1, 2, 3],
|
||||||
|
|
@ -524,6 +534,16 @@ mod tests {
|
||||||
assert_eq!(encode(&back.agent, &back.runtime).unwrap(), bytes);
|
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]
|
#[test]
|
||||||
fn a_corrupted_or_truncated_envelope_is_rejected() {
|
fn a_corrupted_or_truncated_envelope_is_rejected() {
|
||||||
let bytes = encode(&agent_state(), &runtime(1)).unwrap();
|
let bytes = encode(&agent_state(), &runtime(1)).unwrap();
|
||||||
|
|
|
||||||
|
|
@ -198,6 +198,11 @@ pub struct LegacyFrame {
|
||||||
pub location: Option<(u32, u32, u32)>,
|
pub location: Option<(u32, u32, u32)>,
|
||||||
pub held_channel: Option<String>,
|
pub held_channel: Option<String>,
|
||||||
pub blocked_since_ms: f64,
|
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<FrameTrace>,
|
trace: Option<FrameTrace>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -219,6 +224,7 @@ impl LegacyFrame {
|
||||||
location: None,
|
location: None,
|
||||||
held_channel: None,
|
held_channel: None,
|
||||||
blocked_since_ms: 0.0,
|
blocked_since_ms: 0.0,
|
||||||
|
reinforcements: 0,
|
||||||
trace: None,
|
trace: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -248,6 +254,7 @@ impl LegacyFrame {
|
||||||
.map_err(|error| anyhow!("running the first frame: {error}"))?;
|
.map_err(|error| anyhow!("running the first frame: {error}"))?;
|
||||||
self.frame_buffer.copy_from_slice(emulator.framebuffer());
|
self.frame_buffer.copy_from_slice(emulator.framebuffer());
|
||||||
self.frame_counter = 1;
|
self.frame_counter = 1;
|
||||||
|
self.reinforcements = 0;
|
||||||
let audio = emulator.take_audio_u8();
|
let audio = emulator.take_audio_u8();
|
||||||
agent
|
agent
|
||||||
.warmup(Some(&self.frame_buffer))
|
.warmup(Some(&self.frame_buffer))
|
||||||
|
|
@ -305,6 +312,11 @@ impl LegacyFrame {
|
||||||
.map_err(|error| anyhow!("{error}"))?;
|
.map_err(|error| anyhow!("{error}"))?;
|
||||||
|
|
||||||
self.remainder = checkpoint.agent.remainder;
|
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.frame_counter = runtime.emulator_frame;
|
||||||
self.buttons = runtime.buttons;
|
self.buttons = runtime.buttons;
|
||||||
self.frame_buffer.copy_from_slice(&runtime.framebuffer);
|
self.frame_buffer.copy_from_slice(&runtime.framebuffer);
|
||||||
|
|
@ -576,6 +588,7 @@ impl LegacyFrame {
|
||||||
}
|
}
|
||||||
if agent.network.plasticity.enabled {
|
if agent.network.plasticity.enabled {
|
||||||
agent.network.plasticity.reinforce(total, ms);
|
agent.network.plasticity.reinforce(total, ms);
|
||||||
|
self.reinforcements += 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -326,6 +326,7 @@ mod tests {
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
let runtime = store::RuntimeState {
|
let runtime = store::RuntimeState {
|
||||||
|
reinforcements: None,
|
||||||
generation,
|
generation,
|
||||||
wall_ms: 1_700_000_000_000,
|
wall_ms: 1_700_000_000_000,
|
||||||
rom_sha256: "ab".repeat(32),
|
rom_sha256: "ab".repeat(32),
|
||||||
|
|
|
||||||
|
|
@ -1396,6 +1396,7 @@ impl Sim {
|
||||||
last_event_id: self.log.next_id().saturating_sub(1),
|
last_event_id: self.log.next_id().saturating_sub(1),
|
||||||
reward: self.adapter.export_state(),
|
reward: self.adapter.export_state(),
|
||||||
ratchet: self.ratchet.state,
|
ratchet: self.ratchet.state,
|
||||||
|
reinforcements: Some(self.frame.reinforcements),
|
||||||
emulator: self
|
emulator: self
|
||||||
.emulator
|
.emulator
|
||||||
.export_state()
|
.export_state()
|
||||||
|
|
|
||||||
|
|
@ -113,6 +113,7 @@ fn v6_checkpoint() -> Vec<u8> {
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
let runtime = RuntimeState {
|
let runtime = RuntimeState {
|
||||||
|
reinforcements: None,
|
||||||
generation: 41,
|
generation: 41,
|
||||||
wall_ms: 1_790_000_000_000,
|
wall_ms: 1_790_000_000_000,
|
||||||
rom_sha256: flybrain_gb::pokemon_red::SUPPORTED_ROM.to_string(),
|
rom_sha256: flybrain_gb::pokemon_red::SUPPORTED_ROM.to_string(),
|
||||||
|
|
|
||||||
|
|
@ -127,6 +127,7 @@ fn first_difference(left: &[u8], right: &[u8]) -> String {
|
||||||
("lastEventId", a.runtime.last_event_id == b.runtime.last_event_id),
|
("lastEventId", a.runtime.last_event_id == b.runtime.last_event_id),
|
||||||
("reward", a.runtime.reward == b.runtime.reward),
|
("reward", a.runtime.reward == b.runtime.reward),
|
||||||
("ratchet", a.runtime.ratchet == b.runtime.ratchet),
|
("ratchet", a.runtime.ratchet == b.runtime.ratchet),
|
||||||
|
("reinforcements", a.runtime.reinforcements == b.runtime.reinforcements),
|
||||||
("emulator", a.runtime.emulator == b.runtime.emulator),
|
("emulator", a.runtime.emulator == b.runtime.emulator),
|
||||||
("framebuffer", a.runtime.framebuffer == b.runtime.framebuffer),
|
("framebuffer", a.runtime.framebuffer == b.runtime.framebuffer),
|
||||||
("ratchetGame", a.runtime.ratchet_game == b.runtime.ratchet_game),
|
("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 restored_context = ReadoutContext { boot: false, bound: vec![], location: None };
|
||||||
let agent_bytes = lc::agent_payload(
|
let agent_bytes = lc::agent_payload(
|
||||||
&halves.agent,
|
&halves.agent,
|
||||||
|
halves.reinforcements,
|
||||||
&halves.world.framebuffer,
|
&halves.world.framebuffer,
|
||||||
&import,
|
&import,
|
||||||
&id("c1"),
|
&id("c1"),
|
||||||
|
|
@ -328,6 +330,7 @@ async fn every_real_checkpoint_round_trips_legacy_session_legacy() {
|
||||||
let legacy = store::encode(
|
let legacy = store::encode(
|
||||||
&checkpoint.agent,
|
&checkpoint.agent,
|
||||||
&RuntimeState {
|
&RuntimeState {
|
||||||
|
reinforcements: Some(halves.reinforcements),
|
||||||
emulator: emulator.export_state().expect("the emulator exports"),
|
emulator: emulator.export_state().expect("the emulator exports"),
|
||||||
reward: legacy_task.reward,
|
reward: legacy_task.reward,
|
||||||
ratchet: legacy_task.ratchet,
|
ratchet: legacy_task.ratchet,
|
||||||
|
|
@ -453,6 +456,7 @@ impl LegacyWorld {
|
||||||
last_event_id: host.last_event_id,
|
last_event_id: host.last_event_id,
|
||||||
reward: self.adapter.export_state(),
|
reward: self.adapter.export_state(),
|
||||||
ratchet: self.ratchet.state,
|
ratchet: self.ratchet.state,
|
||||||
|
reinforcements: Some(self.frame.reinforcements),
|
||||||
emulator: self.emulator.export_state().expect("the emulator exports"),
|
emulator: self.emulator.export_state().expect("the emulator exports"),
|
||||||
framebuffer: self.frame.frame_buffer.clone(),
|
framebuffer: self.frame.frame_buffer.clone(),
|
||||||
ratchet_game: self.ratchet.game().map(<[u8]>::to_vec).unwrap_or_default(),
|
ratchet_game: self.ratchet.game().map(<[u8]>::to_vec).unwrap_or_default(),
|
||||||
|
|
@ -650,7 +654,7 @@ async fn restore_then_continue(
|
||||||
&mut agents,
|
&mut agents,
|
||||||
&id("fly"),
|
&id("fly"),
|
||||||
&script,
|
&script,
|
||||||
Some(&halves.agent),
|
Some((&halves.agent, halves.reinforcements)),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.expect("the agent runs");
|
.expect("the agent runs");
|
||||||
|
|
@ -693,7 +697,7 @@ async fn restore_then_continue(
|
||||||
&mut agents,
|
&mut agents,
|
||||||
&id("fly"),
|
&id("fly"),
|
||||||
&one_step,
|
&one_step,
|
||||||
Some(&again.agent),
|
Some((&again.agent, again.reinforcements)),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.expect("the agent imports the export");
|
.expect("the agent imports the export");
|
||||||
|
|
|
||||||
|
|
@ -105,7 +105,7 @@ fn capture(k: u64, ratchet: RatchetState) -> LegacyCapture {
|
||||||
let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed();
|
let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed();
|
||||||
LegacyCapture {
|
LegacyCapture {
|
||||||
boundary: k,
|
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(),
|
.unwrap(),
|
||||||
world_payload: lc::world_payload(&world(k), &id("world"), &id("c"), &scope, &"cd".repeat(32)),
|
world_payload: lc::world_payload(&world(k), &id("world"), &id("c"), &scope, &"cd".repeat(32)),
|
||||||
task: TaskHalf { reward: serde_json::Value::Null, ratchet },
|
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,
|
last_event_id: k,
|
||||||
reward: serde_json::Value::Null,
|
reward: serde_json::Value::Null,
|
||||||
ratchet,
|
ratchet,
|
||||||
|
reinforcements: None,
|
||||||
emulator: vec![(k % 251) as u8; 256],
|
emulator: vec![(k % 251) as u8; 256],
|
||||||
framebuffer: vec![9; FRAMEBUFFER_LEN],
|
framebuffer: vec![9; FRAMEBUFFER_LEN],
|
||||||
ratchet_game: vec![1; 32],
|
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);
|
assert_eq!(restored.installed.task.ratchet.attempts, 0);
|
||||||
// And what the session runtime would save from it is the legacy bytes again.
|
// And what the session runtime would save from it is the legacy bytes again.
|
||||||
let halves = &restored.installed;
|
let halves = &restored.installed;
|
||||||
let again = lc::export_states(&halves.agent, &halves.world, &id("best"), &halves.task, &halves.host)
|
// 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();
|
.unwrap();
|
||||||
assert_eq!(again, std::fs::read(&restored.candidate.path).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);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -67,6 +67,7 @@ fn agent_state() -> flybrain_core::agent::AgentState {
|
||||||
|
|
||||||
fn checkpoint(generation: u64, frame: u64, rom: &str, compatibility: &str) -> Vec<u8> {
|
fn checkpoint(generation: u64, frame: u64, rom: &str, compatibility: &str) -> Vec<u8> {
|
||||||
let runtime = RuntimeState {
|
let runtime = RuntimeState {
|
||||||
|
reinforcements: None,
|
||||||
generation,
|
generation,
|
||||||
wall_ms: 1_757_000_000_000 + generation,
|
wall_ms: 1_757_000_000_000 + generation,
|
||||||
rom_sha256: rom.to_string(),
|
rom_sha256: rom.to_string(),
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue