fly-session: legacy_checkpoint, the session runtime's FLYSIM01 export, import, store policy and restore selection (STATE-02)

The export assembles a FLYSIM01 file from the agent's FLYAGT01 and the world's FLYENV01 capture
payloads, the task's {reward, ratchet} and the host's fields, through flysim-store's encoder.
The import reads a file back into those halves. The agent payload is the shipped form of
AGENT-01's prototype: learning.updates starts at plasticity.updates, and the file's framebuffer
goes in an inputFrame chunk that StageRestore installs, as the legacy restore does.
LegacyCheckpointer keeps the legacy loop's generations, hot and durable intervals, per-process
milestone archives and writer thread. restore_from_store walks the legacy candidate order and
takes the next candidate on any refusal. The agent worker's payload encoder is now one shared
function, and legacy_parity seeds through the shipped import.
This commit is contained in:
acamilo 2026-09-29 16:26:07 +00:00
parent 32631e2d02
commit 9c98281f4a
7 changed files with 1319 additions and 76 deletions

View file

@ -444,6 +444,7 @@ dependencies = [
"flybrain-core",
"flybrain-gb",
"flybus",
"flysim-store",
"serde_json",
"tempfile",
"tokio",

View file

@ -32,6 +32,8 @@ flybrain-core = { path = "../flybrain-core" }
flybrain-gb = { path = "../flybrain-gb" }
# The toy connectome fixture is written as gzipped `.binz` arrays, the dataset loader's format.
flate2 = { workspace = true }
# STATE-02: the FLYSIM01 store and the sugar journal, the same code the legacy loop writes with.
flysim-store = { path = "../flysim-store" }
serde_json = { workspace = true }
# `rt-multi-thread` is not only for the tests: a worker process and a dedicated-thread

View file

@ -49,6 +49,7 @@ Ready(k) ─ Prepare all agents concurrently ───────────
| `harness` | The runnable composition: router, the flies, one arena, one coordinator |
| `legacy_env` | ENV-01: the legacy Game Boy environment worker over binjgb -- the one-frame setup scaffold, the joypad batch, `f32le` audio, the per-boundary memory image, `gameboy-slots-v1`, the capture payload and the world's half of `FLYSIM01` |
| `legacy_env_parity` | ENV-01's parity harness: the toy cartridge, recorded scripts, the emulator driven directly in `LegacyFrame` order, the worker driven over the bus, and the replay of the service's own `FLY_TRACE` |
| `legacy_checkpoint` | STATE-02: the legacy composition's `FLYSIM01` checkpoints -- the export from the agent's and the world's capture payloads plus the task's and the host's halves, the import back (with the `learning.updates` rule), the legacy store policy (generations, hot/durable intervals, milestone archives) and the restore selection over the live store. The store code is the `flysim-store` crate, shared with `flysim` |
## Execution modes and the launcher

View file

@ -73,6 +73,10 @@ f767d48ff556fceae996e2ac73c0d0871df71101db0af414a0ffcd0bfb678489:\
/// The magic of the agent's capture payload: a `flybrain-core` checkpoint envelope whose
/// manifest and chunks are exactly `agent_to_chunks`, plus one `session` manifest member.
pub const PAYLOAD_MAGIC: &str = "FLYAGT01";
/// An optional payload chunk: the frame to install as the next input when the payload is
/// staged. Only the `FLYSIM01` import writes it (STATE-02), because the legacy restore
/// re-projects the saved framebuffer rather than trusting the saved visual drive.
pub const INPUT_FRAME_CHUNK: &str = "inputFrame";
/// The layout version of the `session` member.
pub const PAYLOAD_VERSION: u64 = 1;
/// The attachment a Commit reply carries the transition's spike bitset under.
@ -243,6 +247,79 @@ pub fn rational_remainder_to_legacy(remainder: &RationalNs) -> Result<f64, Strin
Ok(k as f64 / 32_768.0)
}
// -------------------------------------------------------------------------------------------
// The capture payload
/// Everything in a `FLYAGT01` capture payload's `session` member except the accumulator and the
/// context: whose state it is, where it was taken and under which identities.
#[derive(Clone, Copy, Debug)]
pub struct PayloadIdentity<'a> {
pub agent_id: &'a Id,
pub checkpoint_id: &'a Id,
pub source_scope: &'a Scope,
pub committed_step: u64,
pub profile: &'a AssetRef,
pub seed: i32,
/// Reinforcement calls applied since the fly's fresh start (`learning.updates`).
pub reinforcements: u64,
/// The composition's `executor.macroChannels`, in composition order; empty in raw mode.
pub macro_channels: &'a [String],
}
/// Encodes a `FLYAGT01` capture payload: `agent_to_chunks(state)` in `flybrain-core`'s envelope,
/// plus the `session` manifest member `State.StageRestore` reads back. `state.remainder` must
/// already be the accumulator's, as a capture sets it.
///
/// The worker's own `State.Capture` writes exactly this, and so does the `FLYSIM01` import
/// (`crate::legacy_checkpoint`), which is why it is one function.
pub fn encode_payload(
state: &AgentState,
identity: &PayloadIdentity<'_>,
accumulator: &TickAccumulator,
context: &TypedValue,
input_frame: Option<&[u8]>,
) -> Result<Vec<u8>, String> {
let mut chunks = agent_to_chunks(state);
if let Some(frame) = input_frame {
chunks.chunks.push((INPUT_FRAME_CHUNK.to_owned(), frame.to_vec()));
}
let channels: Vec<&str> = identity.macro_channels.iter().map(String::as_str).collect();
let session = json!({
"payloadVersion": PAYLOAD_VERSION,
"kind": "legacy-agent",
"agentId": identity.agent_id,
"checkpointId": identity.checkpoint_id,
"sourceScope": identity.source_scope.to_json(),
"committedStep": identity.committed_step.to_string(),
"profile": identity.profile.to_json(),
"seed": identity.seed,
"reinforcements": identity.reinforcements.to_string(),
"kernelVersion": gameboy::KERNEL_VERSION,
"plasticityVersion": gameboy::PLASTICITY_VERSION,
"macroChannels": identity.macro_channels,
"decoderConfigDigest": decoder_config_digest(&gameboy_decoder_config_with_macros(&channels)),
"accumulator": {
"tickDuration": accumulator.tick_duration().to_json(),
"remainder": accumulator.remainder().to_json(),
"executedTicks": accumulator.executed_ticks().to_string(),
"warmupOffset": accumulator.warmup_offset().to_string(),
},
"context": context.to_json(),
});
let mut manifest = chunks.manifest;
let session = JsonValue::parse(&session.to_string()).map_err(|e| e.to_string())?;
manifest.set("session", session);
encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| e.to_string())
}
/// 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<AgentState, String> {
let parts = decode_envelope(bytes, PAYLOAD_MAGIC)
.map_err(|e| format!("not a {PAYLOAD_MAGIC} envelope: {e}"))?;
agent_from_chunks(&parts.manifest, &parts).map_err(|e| e.to_string())
}
// -------------------------------------------------------------------------------------------
// The readout transient
@ -1191,43 +1268,23 @@ impl LegacyAgentWorker {
// The session owns the frame remainder, as the legacy loop does (`Sim::checkpoint`).
state.remainder = rational_remainder_to_legacy(&accumulator.remainder())
.map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))?;
let chunks = agent_to_chunks(&state);
let channels: Vec<&str> = self
.config
.macro_channels
.iter()
.map(String::as_str)
.collect();
let session = json!({
"payloadVersion": PAYLOAD_VERSION,
"kind": "legacy-agent",
"agentId": self.config.agent_id,
"checkpointId": checkpoint_id,
"sourceScope": scope.to_json(),
"committedStep": k.to_string(),
"profile": self.profile.asset.to_json(),
"seed": self.seed,
"reinforcements": self.reinforcements.to_string(),
"kernelVersion": gameboy::KERNEL_VERSION,
"plasticityVersion": gameboy::PLASTICITY_VERSION,
"macroChannels": self.config.macro_channels,
"decoderConfigDigest": decoder_config_digest(&gameboy_decoder_config_with_macros(&channels)),
"accumulator": {
"tickDuration": accumulator.tick_duration().to_json(),
"remainder": accumulator.remainder().to_json(),
"executedTicks": accumulator.executed_ticks().to_string(),
"warmupOffset": accumulator.warmup_offset().to_string(),
encode_payload(
&state,
&PayloadIdentity {
agent_id: &self.config.agent_id,
checkpoint_id,
source_scope: scope,
committed_step: k,
profile: &self.profile.asset,
seed: self.seed,
reinforcements: self.reinforcements,
macro_channels: &self.config.macro_channels,
},
"context": context.typed.to_json(),
});
let mut manifest = chunks.manifest;
let session = JsonValue::parse(&session.to_string()).map_err(|e| {
DomainError::new(ErrorCode::Internal, e.to_string(), MutationCertainty::None)
})?;
manifest.set("session", session);
encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| {
DomainError::new(ErrorCode::Internal, e.to_string(), MutationCertainty::None)
})
accumulator,
&context.typed,
None,
)
.map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))
}
async fn state_capture(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult<HandlerReply> {
@ -1493,6 +1550,16 @@ impl LegacyAgentWorker {
agent
.import_state(&state)
.map_err(|e| incompatible(format!("the agent state does not import: {e}")))?;
// A payload imported from `FLYSIM01` carries the frame on screen as its next input, and
// the restore installs it, as `LegacyFrame::restore` re-projects the saved framebuffer
// (`legacy_checkpoint::agent_payload`). A worker's own capture carries none.
if let Some(frame) = parts.chunk(INPUT_FRAME_CHUNK) {
let (width, height) = (agent.frame.width, agent.frame.height);
if frame.len() != width as usize * height as usize * 4 {
return Err(incompatible("the staged input frame is not the profile's view"));
}
agent.network.set_visual_frame(frame, width, height);
}
if let Some(staged) = &self.staged {
return Err(DomainError::before(
ErrorCode::Conflict,

File diff suppressed because it is too large Load diff

View file

@ -1450,10 +1450,10 @@ impl AgentDriver {
/// the loop's frame remainder in it -- instead of from a warm-up, the way the stream restores
/// after a restart (`legacy-transient-reset`).
///
/// This is the test side of an import nothing ships yet: the worker is initialized, its own
/// capture is taken as the template for the session member, the agent chunks and the clock
/// are replaced with `state`'s, and the result is restored into a replacement worker through
/// the ordinary `State.StageRestore` / `ActivateRestore`, which validates it like any other
/// The payload is the shipped `FLYSIM01` import's (`legacy_checkpoint::agent_payload`, STATE-02,
/// which replaced AGENT-01's prototype here): the worker is initialized, its capture names the
/// checkpoint and scope, and the import is restored into a replacement worker through the
/// ordinary `State.StageRestore` / `ActivateRestore`, which validates it like any other
/// payload. `learning.updates` starts at [`legacy_reinforcements`], because `FLYSIM01` does
/// not record every reinforcement call.
pub async fn seed_from_legacy_state(
@ -1465,7 +1465,25 @@ impl AgentDriver {
) -> Result<ParityRecord, String> {
self.initialize(initial_frame).await?;
let template = self.capture().await?;
let bytes = legacy_state_payload(&template.bytes, state, &self.context)?;
// The shipped import (STATE-02, `legacy_checkpoint::agent_payload`); the template capture
// only supplies the checkpoint, the scope and the composition's macro channels.
let macro_channels: Vec<String> =
serde_json::from_value(captured_session(&template.bytes)?["macroChannels"].clone())
.map_err(|e| format!("the template's macro channels: {e}"))?;
let import = crate::legacy_checkpoint::AgentImport {
agent_id: self.agent_id.clone(),
profile: self.profile.asset.clone(),
seed: LEGACY_SEED,
macro_channels,
};
let bytes = crate::legacy_checkpoint::agent_payload(
state,
&self.frames[initial_frame],
&import,
&template.result.checkpoint_id,
&template.scope,
&self.context,
)?;
let digest = digest_of_bytes(&bytes);
let artifact = crate::state::seal_payload(&self.client, &bytes, &digest)
.await
@ -1483,7 +1501,11 @@ impl AgentDriver {
self.restore_into(target, &seeded).await?;
let after = self.capture().await?;
let restored = payload_state_digest(&after.bytes)?;
if restored != state_digest(state) {
// Exact but for the visual drive, which the restore re-projects from the frame on screen
// as `LegacyFrame::restore` does (the direct reference does the same).
let mut expected = crate::legacy_checkpoint::agent_state(&after.bytes)?;
expected.network.visual_drive = state.network.visual_drive.clone();
if state_digest(&expected) != state_digest(state) {
return Err("the seeded worker's state is not the legacy state".to_owned());
}
self.remainder = legacy_remainder_to_rational(state.remainder)?;
@ -1502,39 +1524,8 @@ impl AgentDriver {
}
}
/// The reinforcement calls to start a legacy agent state's `learning.updates` at.
///
/// `FLYSIM01` records `plasticity.updates`, the reinforcements that moved a gain, but not every
/// call, and the contract requires `learning.changed <= learning.updates`. An import that starts
/// the call count at zero makes the first telemetry unreadable (found on the row-58 stream
/// checkpoint: `changed` is in the thousands), so it starts at the recorded count, a lower bound
/// on the calls actually made.
pub fn legacy_reinforcements(state: &flybrain_core::agent::AgentState) -> u64 {
state.network.plasticity.updates as u64
}
/// A worker capture with its agent chunks and clock replaced by a legacy agent state, and its
/// context by `context`: see [`AgentDriver::seed_from_legacy_state`].
pub fn legacy_state_payload(
template: &[u8],
state: &flybrain_core::agent::AgentState,
context: &TypedValue,
) -> Result<Vec<u8>, String> {
let mut session = captured_session(template)?;
let remainder = legacy_remainder_to_rational(state.remainder)?;
session["accumulator"]["remainder"] = remainder.to_json();
session["accumulator"]["executedTicks"] = json!((state.network.ms as u64).to_string());
session["reinforcements"] = json!(legacy_reinforcements(state).to_string());
session["context"] = context.to_json();
let chunks = agent_to_chunks(state);
let mut manifest = chunks.manifest;
manifest.set(
"session",
flybrain_core::json::JsonValue::parse(&session.to_string()).map_err(|e| e.to_string())?,
);
flybrain_core::envelope::encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks)
.map_err(|e| e.to_string())
}
/// The shipped import's rule (`crate::legacy_checkpoint`), re-exported for the harness.
pub use crate::legacy_checkpoint::legacy_reinforcements;
/// Runs a script against the rig's agent, recording what the coordinator observes.
pub async fn run_on_worker(
@ -1553,6 +1544,30 @@ pub async fn run_on_worker_from(
script: &LegacyScript,
start: Option<&flybrain_core::agent::AgentState>,
) -> Result<Vec<ParityRecord>, String> {
run_script(rig, agent_id, script, start, false)
.await
.map(|(records, _)| records)
}
/// [`run_on_worker_from`], then one `State.Capture` at the boundary the script ends on: the
/// records and the captured payload (STATE-02 writes a `FLYSIM01` export from it).
pub async fn run_on_worker_from_then_capture(
rig: &mut LegacyRig,
agent_id: &Id,
script: &LegacyScript,
start: Option<&flybrain_core::agent::AgentState>,
) -> Result<(Vec<ParityRecord>, Vec<u8>), String> {
let (records, captured) = run_script(rig, agent_id, script, start, true).await?;
Ok((records, captured.expect("a capture was asked for")))
}
async fn run_script(
rig: &mut LegacyRig,
agent_id: &Id,
script: &LegacyScript,
start: Option<&flybrain_core::agent::AgentState>,
capture_at_end: bool,
) -> Result<(Vec<ParityRecord>, Option<Vec<u8>>), String> {
let mut driver = rig.driver(agent_id, script);
let first = match start {
None => driver.initialize(script.initial_frame).await?,
@ -1604,7 +1619,12 @@ pub async fn run_on_worker_from(
}
records.push(record);
}
Ok(records)
let captured = if capture_at_end {
Some(driver.capture().await?.bytes)
} else {
None
};
Ok((records, captured))
}
fn captured_session(payload: &[u8]) -> Result<Value, String> {

View file

@ -30,6 +30,7 @@ pub mod environment;
pub mod harness;
pub mod launcher;
pub mod legacy_agent;
pub mod legacy_checkpoint;
pub mod legacy_env;
pub mod legacy_env_parity;
pub mod legacy_parity;