diff --git a/services/flysim/Cargo.lock b/services/flysim/Cargo.lock index f0f4a3f..90899cb 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -502,6 +502,7 @@ dependencies = [ "anyhow", "axum", "clap", + "fly-session", "fly-session-types", "flybrain-core", "flybrain-gb", diff --git a/services/flysim/crates/fly-session/src/legacy_parity.rs b/services/flysim/crates/fly-session/src/legacy_parity.rs index 14953d4..785b7b7 100644 --- a/services/flysim/crates/fly-session/src/legacy_parity.rs +++ b/services/flysim/crates/fly-session/src/legacy_parity.rs @@ -14,9 +14,14 @@ //! (`agent_to_chunks`). A state digest is exact equality of every membrane, trace, gain, rate, //! RNG and decoder field. //! -//! [`ReferenceSource`] is the seam for FND-01: a reader of `LegacyFrame`'s `FLY_TRACE` is a -//! second reference beside [`DirectReference`], producing the same records from the running -//! loop instead of from a transcription of it. Nothing here depends on it. +//! FND-01's `FLY_TRACE` (`flysim::trace`, `flysim-legacy-frame-trace-v1`) is the running loop's +//! own record. It carries digests and behaviour fields rather than full telemetry, and neither the +//! frames nor the `{boot, bound, location}` context, so it cannot drive a worker by itself: it +//! checks one. [`read_frame_trace`] reads it and [`check_against_trace`] holds a run's records to +//! it. `flysim/tests/agent_trace_parity.rs` is the host that runs `LegacyFrame` with the trace on, +//! records the missing inputs as a [`LegacyScript`], and checks both the worker and +//! [`DirectReference`] against the trace -- so the transcription is itself checked against the +//! service. [`ReferenceSource`] stays the seam for sources of full records. //! //! [`toy`] is the committed toy connectome the goldens run on; the real dataset is optional. @@ -546,9 +551,8 @@ pub fn compare(left: &[ParityRecord], right: &[ParityRecord]) -> Result<(), Stri /// A source of reference records for a script. /// -/// [`DirectReference`] is one. FND-01's `LegacyFrame` trace (`FLY_TRACE`) is meant to be the -/// other: it would produce the same records from the running legacy loop, and at that point the -/// transcription in [`DirectReference`] is itself checked against the service. +/// [`DirectSource`] and [`RestoredSource`] are the two. FND-01's `FLY_TRACE` records digests +/// rather than full records, so it is a check ([`check_against_trace`]) rather than a source. pub trait ReferenceSource { fn records(&mut self, script: &LegacyScript) -> Result, String>; } @@ -557,8 +561,10 @@ pub trait ReferenceSource { // The direct reference: NeuralAgent in `Sim::step_frame` order /// `NeuralAgent` driven the way `flysim::simloop::Sim` drives it, transcribed line by line from -/// `fresh_start`, `step_frame`, `recover` and `try_restore`, with the emulator, adapter and -/// macro layer replaced by the script's recorded outputs. +/// `fresh_start`, `step_frame`, `recover` and `try_restore` (since FND-01, one type: +/// `flysim::frame::LegacyFrame`'s `initialize`, `transition`, `rollback` and `restore`, whose two +/// reorderings touch disjoint state), with the emulator, adapter and macro layer replaced by the +/// script's recorded outputs. pub struct DirectReference { dataset: Arc, agent: NeuralAgent, @@ -757,7 +763,52 @@ pub struct DirectSource { impl ReferenceSource for DirectSource { fn records(&mut self, script: &LegacyScript) -> Result, String> { - let (mut reference, first) = DirectReference::fresh(self.dataset.clone(), script)?; + let (reference, first) = DirectReference::fresh(self.dataset.clone(), script)?; + reference.run(first, script) + } +} + +/// [`ReferenceSource`] from a legacy agent state (a `FLYSIM01` checkpoint's), the way the +/// stream restores after a restart: `LegacyFrame::restore` into a fresh process's transient. +pub struct RestoredSource { + pub dataset: Arc, + pub state: flybrain_core::agent::AgentState, +} + +impl ReferenceSource for RestoredSource { + fn records(&mut self, script: &LegacyScript) -> Result, String> { + let mut agent = DirectReference::build(self.dataset.clone(), &script.macro_channels)?; + agent.import_state(&self.state).map_err(|e| e.to_string())?; + let frame = script.frames[script.initial_frame].clone(); + let (width, height) = (agent.frame.width, agent.frame.height); + agent.network.set_visual_frame(&frame, width, height); + let reference = DirectReference { + dataset: self.dataset.clone(), + agent, + macro_channels: script.macro_channels.clone(), + remainder: self.state.remainder, + location: None, + held_channel: None, + blocked_since_ms: 0.0, + frame_buffer: frame, + boot: script.initial_context.boot, + bound: script.initial_context.bound.clone(), + reinforcements: legacy_reinforcements(&self.state), + }; + let mut first = reference.record(0, "restore", 0, 0, None, None); + first.telemetry = None; + first.state = Some(reference.state_digest()); + reference.run(first, script) + } +} + +impl DirectReference { + fn run( + mut self, + first: ParityRecord, + script: &LegacyScript, + ) -> Result, String> { + let reference = &mut self; let mut records = vec![first]; let mut boundary = 0u64; for (index, step) in script.steps.iter().enumerate() { @@ -1394,6 +1445,95 @@ impl AgentDriver { } self.acknowledge(reply.request_id).await } + + /// Starts the agent from a legacy agent state -- a `FLYSIM01` checkpoint's `agent`, with + /// 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 + /// payload. `learning.updates` starts at [`legacy_reinforcements`], because `FLYSIM01` does + /// not record every reinforcement call. + pub async fn seed_from_legacy_state( + &mut self, + rig: &mut LegacyRig, + agent_id: &Id, + initial_frame: usize, + state: &flybrain_core::agent::AgentState, + ) -> Result { + self.initialize(initial_frame).await?; + let template = self.capture().await?; + let bytes = legacy_state_payload(&template.bytes, state, &self.context)?; + let digest = digest_of_bytes(&bytes); + let artifact = crate::state::seal_payload(&self.client, &bytes, &digest) + .await + .map_err(domain)?; + let seeded = Captured { + result: CaptureResult { + payload: artifact.reference().clone(), + ..template.result + }, + artifact, + bytes, + scope: template.scope, + }; + let target = rig.replace(agent_id).await?; + self.restore_into(target, &seeded).await?; + let after = self.capture().await?; + let restored = payload_state_digest(&after.bytes)?; + if restored != 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)?; + Ok(ParityRecord { + index: 0, + kind: "restore", + boundary: self.boundary, + ticks: 0, + brain_ticks: state.network.ms as u64, + remainder: self.remainder, + decision: None, + telemetry: None, + spikes: None, + state: Some(restored), + }) + } +} + +/// 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, 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()) } /// Runs a script against the rig's agent, recording what the coordinator observes. @@ -1401,9 +1541,28 @@ pub async fn run_on_worker( rig: &mut LegacyRig, agent_id: &Id, script: &LegacyScript, +) -> Result, String> { + run_on_worker_from(rig, agent_id, script, None).await +} + +/// [`run_on_worker`], from a warm-up or, with `start`, from a legacy agent state +/// ([`AgentDriver::seed_from_legacy_state`]). +pub async fn run_on_worker_from( + rig: &mut LegacyRig, + agent_id: &Id, + script: &LegacyScript, + start: Option<&flybrain_core::agent::AgentState>, ) -> Result, String> { let mut driver = rig.driver(agent_id, script); - let mut records = vec![driver.initialize(script.initial_frame).await?]; + let first = match start { + None => driver.initialize(script.initial_frame).await?, + Some(state) => { + driver + .seed_from_legacy_state(rig, agent_id, script.initial_frame, state) + .await? + } + }; + let mut records = vec![first]; for (index, step) in script.steps.iter().enumerate() { let mut record = match step { ScriptStep::Frame { @@ -1477,6 +1636,324 @@ pub fn golden_json(script: &LegacyScript, records: &[ParityRecord]) -> Value { }) } +// ------------------------------------------------------------------------------------------- +// FND-01's FLY_TRACE: the running legacy loop as a reference + +/// The format name on the first line of a `FLY_TRACE` file (`flysim::trace::FORMAT`). +pub const FRAME_TRACE_FORMAT: &str = "flysim-legacy-frame-trace-v1"; + +/// One sugar or operator pulse admitted at the top of a legacy frame, before its ticks. +#[derive(Clone, Debug, PartialEq)] +pub enum TraceAdmission { + Sugar { + duration_ms: f64, + }, + /// `POST /reward`: `plasticity.reinforce(value)` at admission. It has no session-framework + /// counterpart, so a script cannot carry it and [`check_against_trace`] refuses a trace + /// that has one. + RewardPulse { + value: f64, + }, +} + +/// The agent-observable half of one `FLY_TRACE` transition line, `behaviour` only. +#[derive(Clone, Debug, PartialEq)] +pub struct TraceTransition { + pub step: u64, + pub admissions: Vec, + pub ticks: u64, + pub brain_ticks: u64, + pub remainder: RationalNs, + pub rates_digest: String, + pub spikes_digest: String, + pub spike_count: u64, + /// The decode's active set, as the executor was given it. + pub decision: Vec, + /// The mask the emulator was given: the executor's, not the decision's. + pub mask: u32, + pub framebuffer_digest: String, + /// `(value, stimulationMs)` in adapter order. + pub rewards: Vec, + /// The boundary actions, `save-slot` and `rollback`, in order. + pub boundary_actions: Vec, +} + +/// Reads a `FLY_TRACE` file: the header, an optional start-boundary line, then one line per +/// transition. +pub fn read_frame_trace(text: &str) -> Result, String> { + let mut lines = text.lines().filter(|l| !l.trim().is_empty()); + let header: Value = serde_json::from_str(lines.next().ok_or("an empty trace")?) + .map_err(|e| format!("the trace header: {e}"))?; + if header["format"] != FRAME_TRACE_FORMAT { + return Err(format!( + "the trace is {}, not {FRAME_TRACE_FORMAT}", + header["format"] + )); + } + let text_u64 = |v: &Value, key: &str| -> Result { + v[key] + .as_str() + .and_then(|s| s.parse().ok()) + .ok_or_else(|| format!("{key} is not a U64 string")) + }; + let string = |v: &Value, key: &str| -> Result { + v[key] + .as_str() + .map(str::to_owned) + .ok_or_else(|| format!("{key} is not a string")) + }; + let mut out = Vec::new(); + for (n, line) in lines.enumerate() { + let value: Value = + serde_json::from_str(line).map_err(|e| format!("trace line {}: {e}", n + 2))?; + let Some(b) = value.get("behaviour") else { + // The start boundary's captures: operational only. + continue; + }; + let admissions = b["admissions"] + .as_array() + .ok_or("admissions is not a list")? + .iter() + .map(|a| match a["kind"].as_str() { + Some("sugar") => a["durationMs"] + .as_f64() + .map(|duration_ms| TraceAdmission::Sugar { duration_ms }) + .ok_or_else(|| "a sugar admission without durationMs".to_owned()), + Some("reward") => a["value"] + .as_f64() + .map(|value| TraceAdmission::RewardPulse { value }) + .ok_or_else(|| "a reward admission without value".to_owned()), + other => Err(format!("an admission of kind {other:?}")), + }) + .collect::, _>>()?; + let rewards = b["rewards"] + .as_array() + .ok_or("rewards is not a list")? + .iter() + .map(|r| { + Ok(RewardEvent { + value: r["value"].as_f64().ok_or("a reward without value")?, + stimulation_ms: r["stimulationMs"] + .as_f64() + .ok_or("a reward without stimulationMs")?, + }) + }) + .collect::, String>>()?; + let decision = b["decision"] + .as_array() + .ok_or("decision is not a list")? + .iter() + .map(|c| c.as_str().map(str::to_owned).ok_or("a decision channel")) + .collect::, _>>()?; + let boundary_actions = b["boundaryActions"] + .as_array() + .ok_or("boundaryActions is not a list")? + .iter() + .map(|a| { + a["kind"] + .as_str() + .map(str::to_owned) + .ok_or("an action kind") + }) + .collect::, _>>()?; + out.push(TraceTransition { + step: text_u64(b, "step")?, + admissions, + ticks: text_u64(b, "ticksAdvanced")?, + brain_ticks: text_u64(b, "brainTicks")?, + remainder: RationalNs::from_json(&b["remainder"]) + .map_err(|e| format!("remainder: {}", e.0))?, + rates_digest: string(b, "ratesDigest")?, + spikes_digest: string(b, "spikesDigest")?, + spike_count: b["spikeCount"].as_u64().ok_or("spikeCount")?, + decision, + mask: b["mask"] + .as_u64() + .and_then(|m| u32::try_from(m).ok()) + .ok_or("mask")?, + framebuffer_digest: string(b, "framebufferDigest")?, + rewards, + boundary_actions, + }); + } + Ok(out) +} + +/// `FLY_TRACE`'s `ratesDigest` of a telemetry's rates: per tracked role in the network's +/// order, the name's length (u32 LE), the name, and the rate's f64 bits (LE). The role id is +/// the role name (`legacy-rate-role-id-v1`). +pub fn trace_rates_digest(telemetry: &AgentTelemetry) -> Result { + let mut bytes = Vec::new(); + for sample in &telemetry.rates { + let name = gameboy::rate_role_name(&sample.role_id).map_err(|e| e.0)?; + bytes.extend_from_slice(&(name.len() as u32).to_le_bytes()); + bytes.extend_from_slice(name.as_bytes()); + bytes.extend_from_slice(&sample.hz.to_bits().to_le_bytes()); + } + Ok(digest_of_bytes(&bytes)) +} + +/// What a trace check covered. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TraceCheck { + pub transitions: usize, + pub sugar: usize, + pub rewards: usize, + pub rollbacks: usize, + pub macro_decisions: usize, + pub pressed: usize, + pub spikes: u64, +} + +/// Checks the records of a run of `script` -- the worker's, or [`DirectReference`]'s -- +/// against the `FLY_TRACE` of the legacy loop that produced the script. +/// +/// The trace carries digests and the behaviour fields, not the full telemetry, so this is a +/// check rather than a [`ReferenceSource`]. It holds the script to the trace first (the same +/// sugar, frames and reward events, a rollback exactly where the loop rolled back), then each +/// frame record to its transition: ticks, brain clock, exact remainder, the rates digest, the +/// spike-set digest, and the decision as `gameboy-channels-v1` of the decode's active set under +/// the context the step was decided in. +pub fn check_against_trace( + script: &LegacyScript, + records: &[ParityRecord], + trace: &[TraceTransition], +) -> Result { + if records.len() != script.steps.len() + 1 { + return Err(format!( + "{} records for {} steps", + records.len(), + script.steps.len() + )); + } + let mut check = TraceCheck::default(); + let mut transitions = trace.iter(); + let mut last: Option<&TraceTransition> = None; + let mut bound = script.initial_context.bound.clone(); + let mut previous_ticks = records[0].brain_ticks; + for (index, step) in script.steps.iter().enumerate() { + let record = &records[index + 1]; + let at = |what: String| format!("step {index} (record {}): {what}", index + 1); + match step { + ScriptStep::Frame { + sugar, + frame, + rewards, + next_context, + } => { + let t = transitions + .next() + .ok_or_else(|| at("the trace ended".to_owned()))?; + let admitted: Vec = sugar + .iter() + .map(|d| TraceAdmission::Sugar { duration_ms: *d }) + .collect(); + if t.admissions != admitted { + return Err(at(format!( + "the trace admitted {:?}, the script {admitted:?}", + t.admissions + ))); + } + if digest_of_bytes(&script.frames[*frame]) != t.framebuffer_digest { + return Err(at("the script's frame is not the loop's".to_owned())); + } + if &t.rewards != rewards { + return Err(at(format!( + "the trace rewarded {:?}, the script {rewards:?}", + t.rewards + ))); + } + if t.boundary_actions.iter().any(|a| a == "rollback") + != matches!( + script.steps.get(index + 1), + Some(ScriptStep::Rollback { .. }) + ) + { + return Err(at("the script's rollback is not where the loop's is".into())); + } + if record.kind != "frame" { + return Err(at(format!("a {} record for a frame", record.kind))); + } + let mut differ = Vec::new(); + if record.ticks != t.ticks { + differ.push(format!("ticks {} != {}", record.ticks, t.ticks)); + } + if record.brain_ticks != t.brain_ticks { + differ.push(format!( + "brainTicks {} != {}", + record.brain_ticks, t.brain_ticks + )); + } + if record.remainder != t.remainder { + differ.push(format!( + "remainder {:?} != {:?}", + record.remainder, t.remainder + )); + } + let telemetry = record + .telemetry + .as_ref() + .ok_or_else(|| at("a frame record without telemetry".to_owned()))?; + if trace_rates_digest(telemetry)? != t.rates_digest { + differ.push("ratesDigest".to_owned()); + } + if record.spikes.as_deref() != Some(t.spikes_digest.as_str()) { + differ.push("spikesDigest".to_owned()); + } + let want = channels_decision(&t.decision, &bound); + if record.decision.as_ref() != Some(&want) { + differ.push(format!( + "decision {:?} != {:?} (active {:?})", + record.decision, want, t.decision + )); + } + if !differ.is_empty() { + return Err(at(format!( + "differs from trace step {}: {}", + t.step, + differ.join("; ") + ))); + } + check.transitions += 1; + check.sugar += sugar.len(); + check.rewards += rewards.len(); + check.spikes += t.spike_count; + check.macro_decisions += usize::from(want.macro_channel.is_some()); + check.pressed += usize::from(want.mask() != 0); + bound = next_context.bound.clone(); + previous_ticks = record.brain_ticks; + last = Some(t); + } + ScriptStep::Rollback { frame, context } => { + let t = last.ok_or_else(|| at("a rollback before any frame".to_owned()))?; + if !t.boundary_actions.iter().any(|a| a == "rollback") { + return Err(at("the loop did not roll back here".to_owned())); + } + if record.kind != "rollback" || record.ticks != 0 { + return Err(at(format!("a {} record with ticks", record.kind))); + } + if record.brain_ticks != previous_ticks { + return Err(at("a rollback moved the brain clock".to_owned())); + } + // The slot's frame is the rolled-back world's, which the trace does not digest; + // the next transition's ticks and spikes are what it drives. + let _ = frame; + check.rollbacks += 1; + bound = context.bound.clone(); + } + ScriptStep::Restore => { + return Err(at( + "a restore splits a trace in two; check each process's trace".to_owned(), + )); + } + } + } + if let Some(t) = transitions.next() { + return Err(format!("the trace goes on at step {}", t.step)); + } + Ok(check) +} + #[cfg(test)] mod tests { use super::*; diff --git a/services/flysim/crates/fly-session/tests/legacy_agent.rs b/services/flysim/crates/fly-session/tests/legacy_agent.rs index 285c1c6..36c91a0 100644 --- a/services/flysim/crates/fly-session/tests/legacy_agent.rs +++ b/services/flysim/crates/fly-session/tests/legacy_agent.rs @@ -606,7 +606,8 @@ mod fafb { } fn pokered_channels() -> Vec { - let file = fly_session_types::fixtures::load("gameboy-decoder-config.json").expect("vectors"); + let file = + fly_session_types::fixtures::load("gameboy-decoder-config.json").expect("vectors"); file["cases"][1]["macroChannels"] .as_array() .expect("the Pokemon Red macro group") @@ -632,20 +633,31 @@ mod fafb { sugar: if k == 12 { vec![400.0] } else { vec![] }, frame: k % 6, rewards: if k % 11 == 0 { - vec![RewardEvent { value: 0.5, stimulation_ms: 120.0 }] + vec![RewardEvent { + value: 0.5, + stimulation_ms: 120.0, + }] } else { vec![] }, next_context: ReadoutContext { boot: k < 10, bound: bound(k), - location: (k > 5).then_some(Location { area: 12, x: 3 + (k / 40) as u32, y: 7 }), + location: (k > 5).then_some(Location { + area: 12, + x: 3 + (k / 40) as u32, + y: 7, + }), }, }); if k == 60 { steps.push(ScriptStep::Rollback { frame: 2, - context: ReadoutContext { boot: false, bound: bound(k), location: None }, + context: ReadoutContext { + boot: false, + bound: bound(k), + location: None, + }, }); } if k == 75 { @@ -658,7 +670,11 @@ mod fafb { macro_channels: channels, frames: Arc::new(frame_pool(6, 783)), initial_frame: 0, - initial_context: ReadoutContext { boot: true, bound: vec![], location: None }, + initial_context: ReadoutContext { + boot: true, + bound: vec![], + location: None, + }, steps, checkpoints: [30, last].into_iter().collect(), } @@ -693,8 +709,14 @@ mod fafb { let script = script(90); let started = std::time::Instant::now(); let dataset = Arc::new(load_brain_dataset_from_dir(&dir).expect("the dataset loads")); - let want = DirectSource { dataset }.records(&script).expect("the reference runs"); - eprintln!("reference: {} records in {:?}", want.len(), started.elapsed()); + let want = DirectSource { dataset } + .records(&script) + .expect("the reference runs"); + eprintln!( + "reference: {} records in {:?}", + want.len(), + started.elapsed() + ); let summary = legacy_parity::golden_json(&script, &want); eprintln!("reference digest {}", summary["digest"]); for mode in [ExecutionMode::InProcess, ExecutionMode::Process] { @@ -708,16 +730,156 @@ mod fafb { macro_channels: script.macro_channels.clone(), worker_threads: 1, }; - let mut rig = LegacyRig::start(root.path(), mode, &[agent]).await.expect("the rig"); + let mut rig = LegacyRig::start(root.path(), mode, &[agent]) + .await + .expect("the rig"); let got = legacy_parity::run_on_worker(&mut rig, &id("fly-a"), &script) .await .unwrap_or_else(|e| panic!("{}: {e}", mode.label())); rig.stop().await; legacy_parity::compare(&want, &got).unwrap_or_else(|e| panic!("{}: {e}", mode.label())); - eprintln!("{}: {} records identical in {:?}", mode.label(), got.len(), started.elapsed()); + eprintln!( + "{}: {} records identical in {:?}", + mode.label(), + got.len(), + started.elapsed() + ); } for row in summary["rows"].as_array().expect("rows").iter().step_by(10) { eprintln!(" {}", row.as_str().expect("a row")); } } } + +/// FND-01's `FLY_TRACE` reader and check, without a ROM: a trace written in flysim's line shape +/// from the reference's own records is accepted, and each kind of disagreement is refused. The +/// real traces are `flysim/tests/agent_trace_parity.rs`. +mod frame_trace { + use super::*; + use fly_session::legacy_parity::{ + ScriptStep, check_against_trace, read_frame_trace, toy_raw_script, trace_rates_digest, + }; + use fly_session::types::{DomainType, digest_of_bytes}; + use flybrain_core::decoder::gameboy::GAMEBOY_BUTTONS; + use serde_json::json; + + /// `flysim::trace` lines for a script and its records. + fn trace_of(script: &LegacyScript, records: &[ParityRecord]) -> Vec { + let mut lines: Vec = Vec::new(); + for (index, step) in script.steps.iter().enumerate() { + let record = &records[index + 1]; + match step { + ScriptStep::Frame { + sugar, + frame, + rewards, + .. + } => { + let decision = record.decision.as_ref().expect("a decision"); + let mut active: Vec<&str> = GAMEBOY_BUTTONS + .iter() + .enumerate() + .filter(|(bit, _)| decision.buttons[*bit]) + .map(|(_, name)| *name) + .collect(); + if let Some(channel) = &decision.macro_channel { + active.push(channel); + } + lines.push(json!({ + "behaviour": { + "step": (lines.len() as u64).to_string(), + "admissions": sugar.iter().map(|d| json!({"kind": "sugar", "durationMs": d})).collect::>(), + "ticksAdvanced": record.ticks.to_string(), + "brainTicks": record.brain_ticks.to_string(), + "remainder": record.remainder.to_json(), + "ratesDigest": trace_rates_digest(record.telemetry.as_ref().expect("telemetry")).expect("rates"), + "spikesDigest": record.spikes.clone().expect("spikes"), + "spikeCount": 0, + "decision": active, + "mask": decision.mask(), + "macroEvents": [], + "framebufferDigest": digest_of_bytes(&script.frames[*frame]), + "wramDigest": "", + "rewards": rewards.iter().map(|r| json!({"kind": "toy", "value": r.value, "stimulationMs": r.stimulation_ms})).collect::>(), + "rank": 0, + "acknowledgedBoundary": (lines.len() as u64 + 1).to_string(), + "boundaryActions": [], + }, + "operational": {"captures": []}, + })); + } + ScriptStep::Rollback { .. } => { + let last = lines.last_mut().expect("a frame before the rollback"); + last["behaviour"]["boundaryActions"] + .as_array_mut() + .expect("a list") + .push(json!({"kind": "rollback", "slotId": "best", "stateDigest": null})); + } + ScriptStep::Restore => unreachable!("the raw script has no restore"), + } + } + lines + } + + fn text(lines: &[Value]) -> String { + let mut out = json!({"format": "flysim-legacy-frame-trace-v1"}).to_string(); + out.push('\n'); + out.push_str(&json!({"boundary": "0", "operational": {"captures": [{"checkpointId": "g1", "afterActions": 0}]}}).to_string()); + for line in lines { + out.push('\n'); + out.push_str(&line.to_string()); + } + out + } + + #[test] + fn a_trace_of_the_reference_checks_and_every_disagreement_is_refused() { + let script = toy_raw_script(80); + let records = reference(&script); + let lines = trace_of(&script, &records); + let trace = read_frame_trace(&text(&lines)).expect("the trace reads"); + assert_eq!(trace.len(), 80); + let check = check_against_trace(&script, &records, &trace).expect("the reference checks"); + assert_eq!( + (check.transitions, check.sugar, check.rollbacks), + (80, 1, 1) + ); + + let refused = |edit: &dyn Fn(&mut Vec)| { + let mut lines = lines.clone(); + edit(&mut lines); + let trace = read_frame_trace(&text(&lines)).expect("the trace reads"); + check_against_trace(&script, &records, &trace).expect_err("a disagreement") + }; + let e = refused(&|l| l[30]["behaviour"]["spikesDigest"] = json!("00")); + assert!(e.contains("spikesDigest"), "{e}"); + let e = refused(&|l| l[30]["behaviour"]["brainTicks"] = json!("1")); + assert!(e.contains("brainTicks"), "{e}"); + let e = refused(&|l| { + l[30]["behaviour"]["remainder"] = json!({"numerator": "0", "denominator": "1"}) + }); + assert!(e.contains("remainder"), "{e}"); + let e = refused(&|l| l[30]["behaviour"]["ratesDigest"] = json!("00")); + assert!(e.contains("ratesDigest"), "{e}"); + let e = refused(&|l| l[30]["behaviour"]["decision"] = json!(["select"])); + assert!(e.contains("decision"), "{e}"); + let e = refused(&|l| l[9]["behaviour"]["admissions"] = json!([])); + assert!(e.contains("admitted"), "{e}"); + let e = refused(&|l| { + l[9]["behaviour"]["admissions"] = json!([{"kind": "reward", "value": 1.0}]) + }); + assert!(e.contains("RewardPulse"), "{e}"); + let e = refused(&|l| l[5]["behaviour"]["framebufferDigest"] = json!("00")); + assert!(e.contains("frame"), "{e}"); + let e = refused(&|l| { + for line in l.iter_mut() { + line["behaviour"]["boundaryActions"] = json!([]); + } + }); + assert!(e.contains("rollback"), "{e}"); + let e = refused(&|l| { + l.pop(); + }); + assert!(e.contains("ended"), "{e}"); + } +} diff --git a/services/flysim/crates/flysim/Cargo.toml b/services/flysim/crates/flysim/Cargo.toml index b3184ba..3884630 100644 --- a/services/flysim/crates/flysim/Cargo.toml +++ b/services/flysim/crates/flysim/Cargo.toml @@ -55,6 +55,9 @@ unicode-normalization = "0.1" # The legacy profile's pinned identities (`tests/legacy_profile_identity.rs`): test-only, so the # service itself does not link the session types. fly-session-types = { path = "../fly-session-types" } +# AGENT-01's worker checked against this loop's FLY_TRACE (`tests/agent_trace_parity.rs`): +# test-only as well. fly-session does not depend on flysim, so this is no cycle. +fly-session = { path = "../fly-session" } futures-util = "0.3" # `default-features = false` drops the remote-reference resolver (and with it reqwest and a # TLS stack): `packages/feed/src/schema.json` is self-contained, so nothing has to be fetched. diff --git a/services/flysim/crates/flysim/tests/agent_trace_parity.rs b/services/flysim/crates/flysim/tests/agent_trace_parity.rs new file mode 100644 index 0000000..3f81d47 --- /dev/null +++ b/services/flysim/crates/flysim/tests/agent_trace_parity.rs @@ -0,0 +1,422 @@ +//! AGENT-01 against FND-01: the legacy agent worker, and the direct reference, checked against the +//! `FLY_TRACE` of the legacy frame the stream runs (`flysim::frame::LegacyFrame`). +//! +//! The trace records what the loop did to the brain as digests -- ticks, clock, exact remainder, +//! rates, the spike set, the decision -- but not everything a worker needs to be driven: the +//! frames (only their digests), and the `{boot, bound, location}` context the executor and the +//! adapter produced. So this test is the host: it runs `LegacyFrame` on the real emulator with the +//! trace on, records those inputs beside it as a `LegacyScript`, then drives the same script +//! through `LegacyAgentWorker` in every execution mode and through `DirectReference`, and holds +//! each record to its trace line (`fly_session::legacy_parity::check_against_trace`). The script +//! is checked against the trace as well: the same admissions, frames, reward events and rollback. +//! +//! Two runs, both explicit ROM jobs (`. bin/rom-env.sh`, never a download): +//! +//! - `toy_raw_from_power_on`: `FLY_ROM` only. The committed toy connectome in raw mode from +//! power-on, with two sugar admissions. Cheap enough for every ROM run of the workspace. +//! - `fafb_macros_from_a_checkpoint`: also `FLY_AGENT01_FAFB=1` and `data/fafb-v783`. The live +//! composition -- `gameboy-legacy-fafb-v783-v1`, macros mode -- restored from a stream +//! checkpoint (`FLY_AGENT01_TRACE_CHECKPOINT`, else `FLY_DOOR_CHECKPOINT`), with sugar and one +//! ratchet rollback onto the checkpoint's slot. The worker starts from the checkpoint's agent +//! state (`AgentDriver::seed_from_legacy_state`). +//! +//! `FLY_AGENT01_TRACE_FRAMES` sets the length (default 600 toy, 240 FAFB). The worker program for +//! process mode is the workspace's `fly-session` binary; a build that did not produce it skips +//! that mode and says so. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use fly_session::ExecutionMode; +use fly_session::fly_session_types::gameboy::{Location, ReadoutContext}; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_parity::{ + self, DirectSource, LegacyRig, LegacyScript, ParityRecord, ReferenceSource, RestoredSource, + RewardEvent, RigAgent, ScriptStep, TraceCheck, TraceTransition, toy, +}; +use fly_session::types::{digest_of_bytes, id}; +use flybrain_core::agent::{AgentConfig, AgentState, NeuralAgent}; +use flybrain_core::dataset::{BrainDataset, load_brain_dataset_from_dir}; +use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros; +use flybrain_gb::adapter::GameAdapter; +use flybrain_gb::pokemon_red::PokemonRedReward; +use flybrain_gb::ratchet::Ratchet; +use flybrain_gb::{AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator}; +use flysim::config::Config; +use flysim::frame::{LegacyFrame, Parts}; +use flysim::macros::{MacroLayer, macro_layer}; +use flysim::snapshot::MacroMode; +use flysim::trace::FrameTrace; + +fn rom() -> Option> { + let Some(path) = std::env::var_os("FLY_ROM") else { + eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)"); + return None; + }; + Some(std::fs::read(&path).unwrap_or_else(|e| panic!("FLY_ROM {path:?}: {e}"))) +} + +fn frames(default: usize) -> usize { + std::env::var("FLY_AGENT01_TRACE_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(default) +} + +fn context(adapter: &dyn GameAdapter, macros: Option<&MacroLayer>) -> ReadoutContext { + ReadoutContext { + boot: adapter.boot(), + bound: macros.map(MacroLayer::bound_channels).unwrap_or_default(), + location: adapter + .location() + .map(|(area, x, y)| Location { area, x, y }), + } +} + +/// Frames by content, so a still screen is stored once. +#[derive(Default)] +struct Pool { + frames: Vec>, + index: HashMap, +} + +impl Pool { + fn add(&mut self, frame: &[u8]) -> usize { + let digest = digest_of_bytes(frame); + *self.index.entry(digest).or_insert_with(|| { + self.frames.push(frame.to_vec()); + self.frames.len() - 1 + }) + } +} + +/// How the legacy run starts. +enum Start<'a> { + /// `LegacyFrame::initialize`: one frame with no button, then the warm-up on it. + PowerOn, + /// `LegacyFrame::restore` from a stream checkpoint, as `Sim::try_restore` does. + Checkpoint(&'a flysim::store::Checkpoint), +} + +struct LegacyRun { + script: LegacyScript, + trace: Vec, + /// The agent state the run started from, for a restored start. + start: Option, + rewards: Vec<&'static str>, +} + +/// The stream's frame on the real emulator with `FLY_TRACE` on, recording the script beside it. +/// +/// Sugar is admitted the way `Sim::stimulate` admits it (stimulate, then the trace), at the top of +/// the frame. `rollback_at` forces the ratchet's rollback at that boundary when the ratchet holds a +/// slot and did not roll back itself: `LegacyFrame::rollback` is exactly what `boundary` runs when +/// the ratchet fires, and whether it fires is the task's decision, not the agent's. +#[allow(clippy::too_many_arguments)] +fn run_legacy( + rom: &[u8], + data: &Arc, + start: Start<'_>, + mode: MacroMode, + frames: usize, + sugar: &[(usize, f64)], + rollback_at: Option, + trace_path: &Path, +) -> LegacyRun { + let mut emulator = Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES) + .expect("binjgb should accept the cartridge"); + let mut adapter = PokemonRedReward::new(); + let mut ratchet = Ratchet::with_policy(adapter.recovery_policy()); + let mut config = Config::default(); + config.loop_.game = "pokemon-red".to_string(); + config.macros.mode = mode; + let channels = if mode.dealt() { + flybrain_gb::macro_channels("pokemon-red") + } else { + Vec::new() + }; + let preset = gameboy_decoder_config_with_macros(&channels); + let hold_ms = preset + .macros + .as_ref() + .or(preset.exclusive.as_ref()) + .expect("the preset has a group") + .hold_ms; + let mut agent_config = AgentConfig::with_decoder(preset); + agent_config.warmup_ms = config.loop_.warmup_ms; + assert_eq!( + config.loop_.warmup_ms, + fly_session::fly_session_types::gameboy::WARMUP_MS, + "the stream's warm-up is the profile's" + ); + let mut agent = NeuralAgent::new(Arc::clone(data), agent_config).expect("a valid agent"); + let mut frame = + LegacyFrame::new().with_trace(Some(FrameTrace::create(trace_path).expect("a trace file"))); + let start_state = match start { + Start::PowerOn => { + frame + .initialize(&mut emulator, &mut agent) + .expect("the first frame and the warm-up"); + None + } + Start::Checkpoint(checkpoint) => { + frame + .restore( + &mut Parts { + agent: &mut agent, + emulator: &mut emulator, + adapter: &mut adapter, + ratchet: &mut ratchet, + macros: None, + }, + checkpoint, + ) + .expect("the checkpoint should restore"); + Some(checkpoint.agent.clone()) + } + }; + // `Sim::boot`: the macro layer is built after the restore or warm-up, seeded from the network + // as it then stands, and observes once before the first frame. + let mut macros = macro_layer(&config, hold_ms, agent.network.rng_state() as u32); + if let Some(layer) = macros.as_mut() { + let ledger = AdapterLedger(&adapter); + let _ = layer.observe(&mut emulator, &ledger, agent.network.ms); + } + + let mut pool = Pool::default(); + let initial_frame = pool.add(&frame.frame_buffer); + let initial_context = context(&adapter, macros.as_ref()); + let mut steps = Vec::new(); + let mut kinds = Vec::new(); + for k in 1..=frames { + let mut admitted = Vec::new(); + for (_, duration) in sugar.iter().filter(|(at, _)| *at == k) { + agent.network.stimulate(*duration); + if let Some(trace) = frame.trace_mut() { + trace.sugar(*duration); + } + admitted.push(*duration); + } + let mut parts = Parts { + agent: &mut agent, + emulator: &mut emulator, + adapter: &mut adapter, + ratchet: &mut ratchet, + macros: macros.as_mut(), + }; + let transition = frame.transition(&mut parts, &mut ()).expect("a frame"); + let produced = pool.add(&frame.frame_buffer); + let rewards: Vec = transition + .evaluated + .rewards + .iter() + .map(|event| { + kinds.push(event.kind); + RewardEvent { + value: event.value, + stimulation_ms: f64::from(event.stimulation_ms), + } + }) + .collect(); + // The next context is read after the evaluation and before the ratchet: what the task + // hands `Agent.Commit`. + let next_context = context(&*parts.adapter, parts.macros.as_deref()); + let boundary = frame + .boundary(&mut parts, &transition.evaluated.progress, transition.ms) + .expect("the boundary"); + steps.push(ScriptStep::Frame { + sugar: admitted, + frame: produced, + rewards, + next_context, + }); + let mut rolled_back = boundary.rollback.is_some(); + if !rolled_back && rollback_at == Some(k) && parts.ratchet.game().is_some() { + frame.rollback(&mut parts).expect("the forced rollback"); + rolled_back = true; + } + if rolled_back { + let restored = pool.add(&frame.frame_buffer); + steps.push(ScriptStep::Rollback { + frame: restored, + context: context(&*parts.adapter, parts.macros.as_deref()), + }); + } + } + frame.finish_trace(); + drop(frame); + let text = std::fs::read_to_string(trace_path).expect("the trace reads back"); + let trace = legacy_parity::read_frame_trace(&text).expect("a flysim-legacy-frame-trace-v1"); + LegacyRun { + script: LegacyScript { + name: format!("flysim-{}", mode.as_str()), + macro_channels: channels.iter().map(|c| (*c).to_owned()).collect(), + frames: Arc::new(pool.frames), + initial_frame, + initial_context, + steps, + checkpoints: Default::default(), + }, + trace, + start: start_state, + rewards: kinds, + } +} + +fn worker_modes() -> Vec { + let mut modes = vec![ExecutionMode::InProcess, ExecutionMode::Thread]; + let program = fly_session::launcher::default_worker_program(); + if program.is_file() { + modes.push(ExecutionMode::Process); + } else { + eprintln!( + "process mode skipped: no worker program at {} (build the fly-session binary, or set {})", + program.display(), + fly_session::launcher::WORKER_PROGRAM_ENV + ); + } + modes +} + +async fn on_worker( + mode: ExecutionMode, + run: &LegacyRun, + dataset_dir: PathBuf, + profile: LegacyProfileKind, +) -> Vec { + let root = tempfile::tempdir().expect("tmp"); + let agent = RigAgent { + agent_id: id("fly"), + port_id: id("p1"), + dataset_dir, + profile, + macro_channels: run.script.macro_channels.clone(), + worker_threads: 1, + }; + let mut rig = LegacyRig::start(root.path(), mode, &[agent]) + .await + .expect("the rig"); + let records = + legacy_parity::run_on_worker_from(&mut rig, &id("fly"), &run.script, run.start.as_ref()) + .await + .unwrap_or_else(|e| panic!("{}: {e}", mode.label())); + rig.stop().await; + records +} + +fn report(what: &str, check: &TraceCheck) { + eprintln!( + "{what}: {} transitions identical to FLY_TRACE ({} sugar, {} reward events, {} rollbacks, \ + {} macro decisions, {} pressed, {} spikes)", + check.transitions, + check.sugar, + check.rewards, + check.rollbacks, + check.macro_decisions, + check.pressed, + check.spikes + ); +} + +async fn check_all( + run: &LegacyRun, + reference: Vec, + dataset_dir: PathBuf, + profile: LegacyProfileKind, +) { + let check = legacy_parity::check_against_trace(&run.script, &reference, &run.trace) + .unwrap_or_else(|e| panic!("the direct reference against FLY_TRACE: {e}")); + report("direct reference", &check); + for mode in worker_modes() { + let started = std::time::Instant::now(); + let got = on_worker(mode, run, dataset_dir.clone(), profile).await; + let worker = legacy_parity::check_against_trace(&run.script, &got, &run.trace) + .unwrap_or_else(|e| panic!("{} against FLY_TRACE: {e}", mode.label())); + assert_eq!(worker, check); + // And record for record, telemetry included, the worker is the reference. + legacy_parity::compare(&reference, &got) + .unwrap_or_else(|e| panic!("{} against the direct reference: {e}", mode.label())); + report( + &format!("worker {} ({:?})", mode.label(), started.elapsed()), + &worker, + ); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn toy_raw_from_power_on() { + let Some(rom) = rom() else { return }; + let data = Arc::new(load_brain_dataset_from_dir(toy::dir()).expect("the toy dataset")); + let dir = tempfile::tempdir().expect("tmp"); + let n = frames(600); + let run = run_legacy( + &rom, + &data, + Start::PowerOn, + MacroMode::Raw, + n, + &[(40, 300.0), (n / 2, 500.0)], + None, + &dir.path().join("trace.jsonl"), + ); + assert_eq!(run.trace.len(), n); + let reference = DirectSource { dataset: data } + .records(&run.script) + .expect("the direct reference runs"); + check_all(&run, reference, toy::dir(), LegacyProfileKind::Toy).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fafb_macros_from_a_checkpoint() { + let Some(rom) = rom() else { return }; + if std::env::var_os("FLY_AGENT01_FAFB").is_none() { + eprintln!("skipping: FLY_AGENT01_FAFB is not set"); + return; + } + let Some(dataset_dir) = legacy_parity::fafb_dir() else { + eprintln!("skipping: data/fafb-v783 is not present in this checkout"); + return; + }; + let Some(path) = std::env::var_os("FLY_AGENT01_TRACE_CHECKPOINT") + .or_else(|| std::env::var_os("FLY_DOOR_CHECKPOINT")) + else { + eprintln!("skipping: neither FLY_AGENT01_TRACE_CHECKPOINT nor FLY_DOOR_CHECKPOINT is set"); + return; + }; + let checkpoint = flysim::store::load(Path::new(&path)).expect("a FLYSIM01 checkpoint"); + let data = Arc::new(load_brain_dataset_from_dir(&dataset_dir).expect("the dataset")); + let dir = tempfile::tempdir().expect("tmp"); + let n = frames(240); + let started = std::time::Instant::now(); + let run = run_legacy( + &rom, + &data, + Start::Checkpoint(&checkpoint), + MacroMode::Macros, + n, + &[(10, 400.0), (n / 2, 250.0)], + Some(n / 3), + &dir.path().join("trace.jsonl"), + ); + eprintln!( + "legacy loop: {n} frames from {} in {:?}; reward events {:?}", + Path::new(&path).display(), + started.elapsed(), + run.rewards + ); + assert!( + run.script + .steps + .iter() + .any(|s| matches!(s, ScriptStep::Rollback { .. })), + "the checkpoint holds no ratchet slot to roll back onto" + ); + let reference = RestoredSource { + dataset: data, + state: run.start.clone().expect("a restored start"), + } + .records(&run.script) + .expect("the direct reference runs"); + check_all(&run, reference, dataset_dir, LegacyProfileKind::Production).await; +}