fly-legacy-session: flysim-session, the session runtime as the live service

The service host (service.rs, bin flysim-session) runs the legacy composition
behind flysim::serve with flysim's own Config and keeps Sim's order and
bookkeeping: TASK-01's boot (legacy candidate order and gate), boot events,
chat sidecar, sugar journal (runtime fly-session), startup/shutdown durable
saves, queued hot/durable/milestone/after-rollback saves on the wall clock,
macro/reward/milestone/recovery/sugar/checkpoint events, the recovering
status, flysim's Pacer, sd_notify ready/watchdog, and the 30 Hz feed built
by flysim's feed_* functions from the committed view, the step's audio
through the legacy DC blocker, the OR of the commits' spike bitsets, the
task's adapter/ratchet/macro layer and the agent's Legacy.FeedStatus.

Task: FeedRecord (executed/rewards/abandoned/rollback events), the applied
mask (0 after a rollback, the checkpoint's after an import), inspect().
Composition: boot_unsaved, save_queued, the event-log watermark setter.

Tests: service_parity (legacy Sim vs session host behind flysim's router,
one scripted request set, every header/attachment/response/event/journal
line and the final checkpoint compared), journal_replay (a killed session
run's journal replayed from the seed in the legacy loop onto its last hot
checkpoint), unit tests for the audio path and the feed status;
examples/seed_store.
This commit is contained in:
acamilo 2026-09-29 20:31:13 +00:00
parent 4fcd9233c7
commit 98f29e47c6
11 changed files with 2626 additions and 14 deletions

View file

@ -439,14 +439,23 @@ dependencies = [
name = "fly-legacy-session" name = "fly-legacy-session"
version = "0.1.1" version = "0.1.1"
dependencies = [ dependencies = [
"anyhow",
"axum",
"clap",
"fly-session", "fly-session",
"flybrain-core", "flybrain-core",
"flybrain-gb", "flybrain-gb",
"flybus", "flybus",
"flysim", "flysim",
"futures-util",
"serde_json", "serde_json",
"tempfile", "tempfile",
"tokio", "tokio",
"tokio-tungstenite",
"toml",
"tower",
"tracing",
"tracing-subscriber",
] ]
[[package]] [[package]]

View file

@ -5,24 +5,40 @@ edition = "2024"
rust-version.workspace = true rust-version.workspace = true
license.workspace = true license.workspace = true
publish = false publish = false
description = "The live fly's composition on the session framework: the pokered-macros-v1 task and executor, the FLYSIM01 import, and the parity harness against the legacy loop's FLY_TRACE." description = "The live fly's composition on the session framework: the pokered-macros-v1 task and executor, the FLYSIM01 import, the parity harness against the legacy loop's FLY_TRACE, and the flysim-session service."
[lib] [lib]
name = "fly_legacy_session" name = "fly_legacy_session"
path = "src/lib.rs" path = "src/lib.rs"
# SERVE-01: the session runtime as the live service, a drop-in for `flysim`.
[[bin]]
name = "flysim-session"
path = "src/bin/flysim-session.rs"
[dependencies] [dependencies]
# The session framework and its legacy workers (AGENT-01, ENV-01). # The session framework and its legacy workers (AGENT-01, ENV-01).
fly-session = { path = "../fly-session" } fly-session = { path = "../fly-session" }
flybus = { path = "../flybus" } flybus = { path = "../flybus" }
# The unchanged legacy engine the task and executor run: flysim's macro layer, flybrain-gb's # The unchanged legacy engine the task and executor run: flysim's macro layer, flybrain-gb's
# palette, macro executor, PokeState, reward adapter and ratchet, read through MEM-01's image. # palette, macro executor, PokeState, reward adapter and ratchet, read through MEM-01's image.
# flysim is a library dependency only; nothing here changes the service it builds. # flysim is a library dependency only; nothing here changes the service it builds. SERVE-01's
# `flysim-session` runs the session behind flysim's own listeners (`flysim::serve`).
flysim = { path = "../flysim" } flysim = { path = "../flysim" }
flybrain-gb = { path = "../flybrain-gb" } flybrain-gb = { path = "../flybrain-gb" }
flybrain-core = { path = "../flybrain-core" } flybrain-core = { path = "../flybrain-core" }
serde_json = { workspace = true } serde_json = { workspace = true }
tokio = { version = "1", features = ["rt", "rt-multi-thread", "sync", "time", "macros"] } tokio = { version = "1", features = ["rt", "rt-multi-thread", "sync", "time", "macros"] }
# The service entry point (SERVE-01), with flysim's own versions of each.
anyhow = "1.0"
clap = { version = "4.5", features = ["derive"] }
toml = "0.9"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
[dev-dependencies] [dev-dependencies]
tempfile = "3" tempfile = "3"
axum = "0.8"
futures-util = "0.3"
tokio-tungstenite = "0.29"
tower = { version = "0.5", features = ["util"] }

View file

@ -0,0 +1,26 @@
//! Seed a FLYSIM01 store with one checkpoint file, as its own generation (a soak or rehearsal
//! starting from a pulled stream checkpoint; SERVE-01).
//!
//! ```sh
//! cargo run --release -p fly-legacy-session --example seed_store -- <file.checkpoint> <durable-dir>
//! ```
fn main() {
let args: Vec<String> = std::env::args().collect();
let [_, file, dir] = args.as_slice() else {
eprintln!("usage: seed_store <file.checkpoint> <durable-dir>");
std::process::exit(2);
};
let bytes = std::fs::read(file).expect("reading the checkpoint");
let checkpoint = flysim::store::decode(&bytes).expect("a FLYSIM01 checkpoint");
let generation = checkpoint.runtime.generation;
let store = flysim::store::Store::new(std::path::Path::new(dir), 2);
store.create().expect("creating the store");
store
.commit(generation, &bytes, None)
.expect("committing the checkpoint");
println!(
"seeded {dir} with generation {generation} (frame {}, compatibility {})",
checkpoint.runtime.emulator_frame, checkpoint.runtime.compatibility
);
}

View file

@ -0,0 +1,102 @@
//! `flysim-session`: the live fly on the session runtime, as a drop-in for `flysim` (SERVE-01).
//!
//! ```sh
//! flysim-session # what flysim.service runs after `fly-runtime session`
//! flysim-session --print-compatibility
//! ```
//!
//! It reads exactly `flysim`'s configuration (`/etc/fly/fly.env` through the unit, or
//! `--config flysim.toml`), writes the same checkpoint stores, event log, sugar journal and chat
//! sidecar, and serves the same feed, control API and metrics. Three variables are its own:
//! `FLY_SESSION_DIR` (the session's router store and sockets, default `/run/fly/session`),
//! `FLY_SESSION_MODE` (`in-process`, `thread` or `process`) and `FLY_SESSION_PROFILE`
//! (`production`, or `toy` for tests).
//!
//! The one-shot flags are `flysim`'s: `--check-config`, `--print-compatibility` (the session's
//! own string, which must equal `flysim`'s), `--print-state-compatibility` and
//! `--reset-to-milestone` (the store is shared, so these are `flysim`'s own functions).
use anyhow::Result;
use clap::Parser;
use flysim::config::Config;
#[derive(Debug, Parser)]
#[command(
name = "flysim-session",
about = "The fly brain and its Game Boy on the session runtime: flysim's feed, control API and checkpoints.",
version
)]
struct Args {
/// Path to `flysim.toml`. Without it, defaults plus `FLY_*` / `FLYSIM_*` environment
/// overrides are used, exactly as for `flysim`.
#[arg(long, value_name = "PATH")]
config: Option<std::path::PathBuf>,
/// Print the resolved configuration and exit.
#[arg(long)]
check_config: bool,
/// Print the checkpoint compatibility string this build would write, and exit.
#[arg(long)]
print_compatibility: bool,
/// Print the compatibility string the checkpoints in this directory carry, and exit.
#[arg(long, value_name = "DIR")]
print_state_compatibility: Option<std::path::PathBuf>,
/// Restart the run from the milestone archive for this ladder rung, and exit (with the
/// service stopped; `flysim --reset-to-milestone`, the same store).
#[arg(long, value_name = "RANK")]
reset_to_milestone: Option<u32>,
}
fn main() -> Result<()> {
let args = Args::parse();
init_tracing();
let config = Config::load(args.config.as_deref())?;
let options = fly_legacy_session::service::ServiceOptions::from_env()?;
tracing::info!(config = ?config, options = ?options, "resolved configuration");
if args.check_config {
println!("{}", toml::to_string_pretty(&config)?);
return Ok(());
}
if args.print_compatibility {
println!(
"{}",
fly_legacy_session::service::compatibility_string(&config, &options)?
);
return Ok(());
}
if let Some(dir) = args.print_state_compatibility.as_deref() {
if let Some(found) = flysim::store::state_compatibility(dir) {
println!("{found}");
}
return Ok(());
}
if let Some(rank) = args.reset_to_milestone {
let stamp = flysim::reset::utc_stamp(flysim::eventlog::now_wall_ms());
let durable = config.paths.save_dir.clone();
let hot = config.paths.hot_dir.clone();
let archive = flysim::reset::default_archive_dir(&durable, &stamp);
for line in flysim::reset::reset_to_milestone(&durable, &hot, rank, &archive)? {
println!("{line}");
}
return Ok(());
}
fly_legacy_session::service::run(config, options)
}
/// Logs go to stderr, as `flysim`'s do (binjgb prints the cartridge header to stdout).
fn init_tracing() {
use tracing_subscriber::EnvFilter;
let filter = EnvFilter::try_from_env("FLYSIM_LOG")
.or_else(|_| EnvFilter::try_from_default_env())
.unwrap_or_else(|_| EnvFilter::new("info"));
tracing_subscriber::fmt()
.with_env_filter(filter)
.with_writer(std::io::stderr)
.with_target(false)
.init();
}

View file

@ -27,7 +27,7 @@ use flysim::snapshot::MacroMode;
use crate::task::{PokeredConfig, PokeredTask, TaskRecord}; use crate::task::{PokeredConfig, PokeredTask, TaskRecord};
use fly_session::legacy_checkpoint::{ use fly_session::legacy_checkpoint::{
AgentImport, CheckpointerConfig, LegacyCapture, LegacyCheckpointer, RankChange, SaveKind, AgentImport, CheckpointerConfig, LegacyCapture, LegacyCheckpointer, RankChange, SaveKind,
SaveReport, now_wall_ms, SaveReport, SaveTicket, now_wall_ms,
}; };
use flysim::store::Checkpoint; use flysim::store::Checkpoint;
use std::time::Instant; use std::time::Instant;
@ -148,6 +148,25 @@ pub async fn boot(
root: &Path, root: &Path,
config: LegacyConfig, config: LegacyConfig,
store: &StoreConfig, store: &StoreConfig,
) -> Result<(LegacySession, Boot), String> {
let (mut session, boot) = boot_unsaved(root, config, store).await?;
// `Sim::boot`: a durable save of the state the process starts from, then the intervals.
session.save(SaveKind::Durable).await?;
session
.checkpointer_mut()
.expect("attached")
.start_intervals(Instant::now());
Ok((session, boot))
}
/// [`boot`] up to the store: the restore (or the fresh start) with the store attached, but no
/// startup save yet and the intervals not started. The service host (SERVE-01) writes its boot
/// events first, so the startup save records their watermark as the legacy one does, and then
/// takes the save and starts the intervals itself.
pub async fn boot_unsaved(
root: &Path,
config: LegacyConfig,
store: &StoreConfig,
) -> Result<(LegacySession, Boot), String> { ) -> Result<(LegacySession, Boot), String> {
let hot = flysim::store::Store::new(&store.hot_dir, store.keep_generations); let hot = flysim::store::Store::new(&store.hot_dir, store.keep_generations);
let durable = flysim::store::Store::new(&store.durable_dir, store.keep_generations); let durable = flysim::store::Store::new(&store.durable_dir, store.keep_generations);
@ -208,7 +227,7 @@ pub async fn boot(
} }
} }
} }
let (mut session, boot) = match outcome { let (session, boot) = match outcome {
Some(pair) => pair, Some(pair) => pair,
None if candidates.is_empty() => { None if candidates.is_empty() => {
let mut session = LegacySession::start(&root.join("fresh"), config).await?; let mut session = LegacySession::start(&root.join("fresh"), config).await?;
@ -229,12 +248,6 @@ pub async fn boot(
)); ));
} }
}; };
// `Sim::boot`: a durable save of the state the process starts from, then the intervals.
session.save(SaveKind::Durable).await?;
session
.checkpointer_mut()
.expect("attached")
.start_intervals(Instant::now());
Ok((session, boot)) Ok((session, boot))
} }
@ -535,9 +548,23 @@ impl LegacySession {
self.checkpointer.as_mut() self.checkpointer.as_mut()
} }
/// One save of the committed boundary, written by the checkpointer's writer thread; waits for /// The feed event log's watermark the next save records (`lastEventId`): the restored
/// the commit, so a caller that goes on to read the store finds it. /// file's until a host that keeps a feed event log sets its own.
pub async fn save(&mut self, kind: SaveKind) -> Result<SaveReport, String> { pub fn last_event_id(&self) -> u64 {
self.last_event_id
}
/// The service host's event log watermark, recorded by every save from now on as the legacy
/// loop records `log.next_id() - 1` (SERVE-01).
pub fn set_last_event_id(&mut self, last_event_id: u64) {
self.last_event_id = last_event_id;
}
/// One save of the committed boundary, queued on the checkpointer's writer thread without
/// waiting for it: the capture is taken now (so it is this boundary), the encoding and the
/// fsyncs happen off the loop, and the ticket resolves when the writer committed it. This is
/// the legacy loop's `checkpoint` (SERVE-01); [`LegacySession::save`] waits.
pub async fn save_queued(&mut self, kind: SaveKind) -> Result<SaveTicket, String> {
self.saves += 1; self.saves += 1;
let (boundary, world, agents) = self let (boundary, world, agents) = self
.coordinator .coordinator
@ -555,7 +582,13 @@ impl LegacySession {
}; };
let last_event_id = self.last_event_id; let last_event_id = self.last_event_id;
let checkpointer = self.checkpointer.as_mut().ok_or("no store is attached")?; let checkpointer = self.checkpointer.as_mut().ok_or("no store is attached")?;
let ticket = checkpointer.save(kind, capture, last_event_id, now_wall_ms())?; checkpointer.save(kind, capture, last_event_id, now_wall_ms())
}
/// One save of the committed boundary, written by the checkpointer's writer thread; waits for
/// the commit, so a caller that goes on to read the store finds it.
pub async fn save(&mut self, kind: SaveKind) -> Result<SaveReport, String> {
let ticket = self.save_queued(kind).await?;
ticket ticket
.reply .reply
.await .await

View file

@ -124,6 +124,9 @@ pub async fn import_flysim01(
coordinator coordinator
.resume() .resume()
.map_err(|e| format!("resuming the import: {}", e.error.message))?; .map_err(|e| format!("resuming the import: {}", e.error.message))?;
// The joypad on the restored boundary, as the legacy `LegacyFrame::restore` installs it: what
// a feed header reports until the executor applies its first mask (SERVE-01).
task.set_mask(checkpoint.runtime.buttons);
Ok(Imported { Ok(Imported {
boundary, boundary,
epoch: new_epoch.clone(), epoch: new_epoch.clone(),

View file

@ -7,6 +7,8 @@
//! - [`admission`]: sugar by the legacy rules; the operator reward pulse refused. //! - [`admission`]: sugar by the legacy rules; the operator reward pulse refused.
//! - [`trace`]: the session's `FLY_TRACE`, in the legacy loop's format, and the comparison. //! - [`trace`]: the session's `FLY_TRACE`, in the legacy loop's format, and the comparison.
//! - [`driver`]: a stub readout for parity runs that must earn rewards. //! - [`driver`]: a stub readout for parity runs that must earn rewards.
//! - [`service`]: the composition as the live service behind flysim's listeners (SERVE-01),
//! the `flysim-session` binary.
//! //!
//! `docs/design/session-framework/legacy-gameboy-v1.md` is the contract, `implementation.md` //! `docs/design/session-framework/legacy-gameboy-v1.md` is the contract, `implementation.md`
//! TASK-01 the record. //! TASK-01 the record.
@ -15,5 +17,6 @@ pub mod admission;
pub mod composition; pub mod composition;
pub mod driver; pub mod driver;
pub mod import; pub mod import;
pub mod service;
pub mod task; pub mod task;
pub mod trace; pub mod trace;

File diff suppressed because it is too large Load diff

View file

@ -156,6 +156,20 @@ pub fn ledgers_of(
.to_string() .to_string()
} }
/// What one transition gave the feed (SERVE-01), in the order the legacy loop emits it: the
/// executor's starts and finishes, the rewards, the observation's abandonments, and a rollback's
/// trigger and macro events. Kept whether or not a parity run records, because the service host
/// publishes it; taken once per transition ([`PokeredTask::take_feed`]).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct FeedRecord {
pub executed: Vec<MacroEvent>,
pub rewards: Vec<flybrain_gb::adapter::RewardEvent>,
pub abandoned: Vec<MacroEvent>,
/// `Some((game_over, events))` when the ratchet's rollback ran at this boundary: the trigger
/// (a game over, else a stall) and the executor's cancel-and-observe events.
pub rollback: Option<(bool, Vec<MacroEvent>)>,
}
/// How the object is configured. Everything here is composition, not state. /// How the object is configured. Everything here is composition, not state.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct PokeredConfig { pub struct PokeredConfig {
@ -190,6 +204,12 @@ struct Inner {
driver: Option<Box<dyn crate::driver::DecisionDriver>>, driver: Option<Box<dyn crate::driver::DecisionDriver>>,
/// Addresses the engine read that the image does not capture ([`Watched`]). /// Addresses the engine read that the image does not capture ([`Watched`]).
uncaptured: std::collections::BTreeSet<u16>, uncaptured: std::collections::BTreeSet<u16>,
/// The feed's view of the transitions since the last [`PokeredTask::take_feed`].
feed: FeedRecord,
/// The joypad mask the executor last applied (the legacy `frame.buttons`).
mask: u32,
/// Whether the rollback asked for at the last boundary was a game over (else a stall).
rollback_game_over: bool,
} }
/// The one object. [`PokeredTask::task`] and [`PokeredTask::executor`] are its two faces; the /// The one object. [`PokeredTask::task`] and [`PokeredTask::executor`] are its two faces; the
@ -229,6 +249,9 @@ impl PokeredTask {
records: Vec::new(), records: Vec::new(),
driver: None, driver: None,
uncaptured: std::collections::BTreeSet::new(), uncaptured: std::collections::BTreeSet::new(),
feed: FeedRecord::default(),
mask: 0,
rollback_game_over: false,
})), })),
}) })
} }
@ -261,6 +284,38 @@ impl PokeredTask {
self.lock().uncaptured.iter().copied().collect() self.lock().uncaptured.iter().copied().collect()
} }
/// The feed's record of the transitions since the last call (SERVE-01).
pub fn take_feed(&self) -> FeedRecord {
std::mem::take(&mut self.lock().feed)
}
/// The joypad mask the executor last applied, as the legacy header's `buttons` reads it.
pub fn mask(&self) -> u32 {
self.lock().mask
}
/// The joypad mask a restore installed (the checkpoint's `buttons`), before any apply.
pub fn set_mask(&self, mask: u32) {
self.lock().mask = mask;
}
/// Read the adapter, the ratchet and the macro layer as they stand at the committed
/// boundary: the parts of a feed header that are the task's (SERVE-01). Changes nothing.
pub fn inspect<R>(
&self,
f: impl FnOnce(&PokemonRedReward, &Ratchet, Option<&MacroLayer>) -> R,
) -> R {
let inner = self.lock();
f(&inner.adapter, &inner.ratchet, inner.macros.as_ref())
}
/// Whether this cartridge earns semantic rewards (`adapter.rom_allowed`), which the legacy
/// header reports as `game.semanticRewards`.
pub fn semantic_rewards(&self) -> bool {
let inner = self.lock();
inner.adapter.rom_allowed(&inner.cartridge.sha256_hex())
}
/// The records since the last call. /// The records since the last call.
pub fn take_records(&self) -> Vec<TaskRecord> { pub fn take_records(&self) -> Vec<TaskRecord> {
std::mem::take(&mut self.lock().records) std::mem::take(&mut self.lock().records)
@ -583,6 +638,8 @@ impl Task for TaskFace {
adapter.sample(&mut reader, ms) adapter.sample(&mut reader, ms)
}; };
let abandoned = inner.observe(&image, ms); let abandoned = inner.observe(&image, ms);
inner.feed.rewards.extend(rewards.iter().cloned());
inner.feed.abandoned.extend(abandoned.iter().cloned());
let progress = inner.adapter.progress(); let progress = inner.adapter.progress();
// `LegacyFrame::boundary`, the decision half: the ratchet captures on a safe frame above // `LegacyFrame::boundary`, the decision half: the ratchet captures on a safe frame above
@ -634,6 +691,7 @@ impl Task for TaskFace {
} }
events.push(task_event); events.push(task_event);
} }
inner.rollback_game_over = game_over;
let episode = recover.then(|| EpisodeRequest { let episode = recover.then(|| EpisodeRequest {
kind: EpisodeRequestKind::Rollback, kind: EpisodeRequestKind::Rollback,
reason: id(if game_over { "game-over" } else { "stall" }), reason: id(if game_over { "game-over" } else { "stall" }),
@ -689,6 +747,10 @@ impl Task for TaskFace {
None => Vec::new(), None => Vec::new(),
}; };
events.extend(inner.observe(&image, ms)); events.extend(inner.observe(&image, ms));
let game_over = inner.rollback_game_over;
inner.feed.rollback = Some((game_over, events.clone()));
// `LegacyFrame::rollback` releases every button with the restored slot.
inner.mask = 0;
if let Some(record) = inner.open.as_mut() { if let Some(record) = inner.open.as_mut() {
record.rolled_back = true; record.rolled_back = true;
record record
@ -750,6 +812,7 @@ impl Task for TaskFace {
inner.macros = fresh_layer(&inner.config); inner.macros = fresh_layer(&inner.config);
inner.current = None; inner.current = None;
inner.open = None; inner.open = None;
inner.feed = FeedRecord::default();
inner.epoch = epoch.clone(); inner.epoch = epoch.clone();
inner.evaluations = 0; inner.evaluations = 0;
inner.issued = 0; inner.issued = 0;
@ -860,6 +923,8 @@ impl ActionExecutor for ExecutorFace {
None => (raw, Vec::new()), None => (raw, Vec::new()),
} }
}; };
inner.mask = mask;
inner.feed.executed.extend(events.iter().cloned());
if inner.config.record { if inner.config.record {
inner.open = Some(TaskRecord { inner.open = Some(TaskRecord {
boundary: scope.step, boundary: scope.step,

View file

@ -0,0 +1,189 @@
//! SERVE-01: the sugar journal a killed session-runtime service wrote, replayed.
//!
//! A `flysim-session` process restores a seed checkpoint, admits sugar through `POST /stimulate`
//! (each admission journaled, frame-stamped, before the frame that applies it), writes its hot
//! checkpoints every `hot_seconds`, and is killed with `SIGKILL`. Its successor restores the
//! newest hot checkpoint. This test takes the seed, the killed process's journal segment and that
//! hot checkpoint, and replays the segment's inputs from the seed in the **legacy** loop
//! (`flysim::frame::LegacyFrame`, FND-01's harness) up to the checkpoint's frame. The replay must
//! land on the checkpoint exactly: the network, the plasticity, the decoder, the remainder, the
//! emulator, the frame on screen, the adapter's ledger and the ratchet. That is the journal's whole
//! promise -- the seed plus the journal is the run -- and it holds across the two runtimes.
//!
//! Gated on `FLY_ROM` and `FLY_SERVE01_REPLAY_DIR`, a directory holding `seed.checkpoint`,
//! `target.checkpoint` (the hot checkpoint the successor restored) and `hot/` (the journal
//! files). `FLY_MACRO_MODE` is the run's mode (default `macros`).
use std::path::PathBuf;
use std::sync::Arc;
use flybrain_core::agent::{AgentConfig, NeuralAgent};
use flybrain_core::dataset::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::{FrameObserver, LegacyFrame, Parts};
use flysim::macros::macro_layer;
use flysim::snapshot::MacroMode;
struct Quiet;
impl FrameObserver for Quiet {}
#[test]
fn a_killed_session_runs_journal_replays_onto_its_hot_checkpoint_in_the_legacy_loop() {
let Some(rom) = std::env::var_os("FLY_ROM").map(PathBuf::from) else {
eprintln!("skipping: FLY_ROM is not set");
return;
};
let Some(dir) = std::env::var_os("FLY_SERVE01_REPLAY_DIR").map(PathBuf::from) else {
eprintln!("skipping: FLY_SERVE01_REPLAY_DIR is not set");
return;
};
let Some(dataset) = fly_session::legacy_parity::fafb_dir() else {
eprintln!("skipping: no data/fafb-v783");
return;
};
let mode = match std::env::var("FLY_MACRO_MODE").as_deref() {
Ok("raw") => MacroMode::Raw,
_ => MacroMode::Macros,
};
let seed = flysim::store::decode(&std::fs::read(dir.join("seed.checkpoint")).unwrap())
.expect("the seed");
let target = flysim::store::decode(&std::fs::read(dir.join("target.checkpoint")).unwrap())
.expect("the target");
let segments = flysim::journal::read_segments(&dir.join("hot")).expect("the journal");
// The killed process: the segment whose boot header names the seed's generation.
let segment = segments
.iter()
.find(|s| {
s.boot.as_ref().and_then(|b| b["generation"].as_u64())
== Some(seed.runtime.generation)
&& s.boot.as_ref().and_then(|b| b["runtime"].as_str()) == Some("fly-session")
})
.expect("a fly-session segment that booted from the seed");
let boot = segment.boot.as_ref().unwrap();
assert_eq!(
boot["startFrame"].as_str(),
Some(seed.runtime.emulator_frame.to_string().as_str()),
"the boot header starts at the seed's frame"
);
let inputs: Vec<(u64, f64, f64)> = segment
.inputs
.iter()
.filter(|line| line["kind"] == "sugar")
.map(|line| {
(
line["frame"].as_str().unwrap().parse().unwrap(),
line["brainMs"].as_f64().unwrap(),
line["durationMs"].as_f64().unwrap(),
)
})
.collect();
let applied: Vec<_> = inputs
.iter()
.filter(|(frame, _, _)| *frame < target.runtime.emulator_frame)
.collect();
eprintln!(
"replaying {} of the segment's {} sugar inputs from frame {} to frame {} ({} frames); \
{} segments in the journal",
applied.len(),
inputs.len(),
seed.runtime.emulator_frame,
target.runtime.emulator_frame,
target.runtime.emulator_frame - seed.runtime.emulator_frame,
segments.len()
);
assert!(!applied.is_empty(), "the run admitted sugar before its last hot checkpoint");
let rom = std::fs::read(&rom).unwrap();
let data = Arc::new(load_brain_dataset_from_dir(&dataset).expect("the dataset"));
let mut emulator =
Emulator::new(&rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES).expect("binjgb");
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_owned();
config.macros.mode = mode;
let (channels, hold_ms) = fly_legacy_session::composition::channels_and_hold(mode);
let channels: Vec<&str> = channels.iter().map(String::as_str).collect();
let mut agent_config =
AgentConfig::with_decoder(gameboy_decoder_config_with_macros(&channels));
agent_config.warmup_ms = config.loop_.warmup_ms;
let mut agent = NeuralAgent::new(Arc::clone(&data), agent_config).expect("an agent");
// The sweep's thread count does not change a number (the live loop runs 3, the harnesses 1).
let threads = std::env::var("FLY_SERVE01_REPLAY_THREADS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(3usize);
if threads > 1 {
agent.set_sweep_plan(
flybrain_core::lif::SweepPlan::with_threads(threads).expect("a sweep plan"),
);
}
let mut frame = LegacyFrame::new();
frame
.restore(
&mut Parts {
agent: &mut agent,
emulator: &mut emulator,
adapter: &mut adapter,
ratchet: &mut ratchet,
macros: None,
},
&seed,
)
.expect("the seed restores");
let mut macros = macro_layer(&config, hold_ms, agent.network.rng_state() as u32);
if let Some(layer) = macros.as_mut() {
let _ = layer.observe(&mut emulator, &AdapterLedger(&adapter), agent.network.ms);
}
let started = std::time::Instant::now();
let mut stamped = 0;
while frame.frame_counter < target.runtime.emulator_frame {
for (at, brain_ms, duration) in &inputs {
if *at == frame.frame_counter {
assert_eq!(
agent.network.ms, *brain_ms,
"the journal's brainMs at frame {at}"
);
agent.network.stimulate(*duration);
stamped += 1;
}
}
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 Quiet).expect("a frame");
frame
.boundary(&mut parts, &transition.evaluated.progress, transition.ms)
.expect("the boundary");
}
assert_eq!(stamped, applied.len(), "every input before the checkpoint was applied");
assert_eq!(frame.frame_counter, target.runtime.emulator_frame);
let mut state = agent.export_state();
state.remainder = frame.remainder;
assert!(state == target.agent, "the agent state (network, plasticity, decoder, remainder)");
assert_eq!(
emulator.export_state().expect("the emulator"),
target.runtime.emulator,
"the emulator state"
);
assert_eq!(frame.frame_buffer, target.runtime.framebuffer, "the frame on screen");
assert_eq!(adapter.export_state(), target.runtime.reward, "the adapter's ledger");
assert_eq!(ratchet.state, target.runtime.ratchet, "the ratchet");
eprintln!(
"IDENTICAL: {} frames, {stamped} journaled sugar inputs, agent/emulator/frame/adapter/ratchet \
equal to the killed process's hot generation {} ({:.1?})",
target.runtime.emulator_frame - seed.runtime.emulator_frame,
target.runtime.generation,
started.elapsed()
);
}

View file

@ -0,0 +1,785 @@
//! SERVE-01: the session runtime's service host against the legacy service loop, at the level
//! of the two binding contracts (`docs/feed-protocol.md`, `docs/control-api.md`).
//!
//! Both runtimes are started from the same seeded FLYSIM01 store, behind flysim's own control
//! router (`flysim::api::router`) and snapshot slot, and driven by the same script of control
//! requests, each sent on the snapshot of a named frame so it lands before the next one (the loop
//! is paced slowly enough that a request always arrives while it sleeps). Every published feed
//! header and its three attachments, every control response, the event log, the sugar journal
//! and the final checkpoint are compared:
//!
//! - **feed**: every running snapshot, header field by field and attachments byte for byte,
//! except the fields that are wall clock by definition (`wallMs`, `uptimeSeconds`,
//! `realtimeFactor`, `sugar.cooldownMs`, an event's or chat line's `wallMs`) and `seq`, which
//! counts the idle headers a pause publishes at 2 Hz of wall clock;
//! - **control**: status code and body of every request (`/stimulate` 202 and 429 with the same
//! `retryAfterMs`, `/reward` 403, `/chat` 202/422, `/checkpoint` the same generation,
//! `/pause`, `/resume`, `/events`, `/healthz`), `/status` minus its wall-clock fields, and the
//! `/metrics` series names;
//! - **store**: the event log file, the journal lines (minus `wallMs`, the boot header's runtime
//! and wall clock), and the final durable checkpoint decoded (minus `wallMs`).
//!
//! Gated on `FLY_ROM` (source `bin/rom-env.sh`). `toy_raw_*` uses the committed toy connectome and
//! a store seeded by a legacy fresh start; `fafb_*` (also `FLY_SERVE01_FAFB`) the real connectome
//! from the ENV-01 service trace's `rollback` checkpoint, which rolls back on its first boundary.
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use axum::body::Body;
use axum::http::{Method, Request};
use fly_legacy_session::service::{ServiceOptions, run_host};
use fly_session::launcher::ExecutionMode;
use fly_session::legacy_agent::LegacyProfileKind;
use flysim::AppState;
use flysim::config::Config;
use flysim::eventlog::EventRing;
use flysim::simloop::{Command, Shared, Sim, booting_snapshot};
use flysim::snapshot::{FeedStatus, MacroMode, Snapshot};
use serde_json::{Value, json};
use tokio::sync::{mpsc, watch};
use tower::ServiceExt;
fn rom_path() -> Option<PathBuf> {
match std::env::var_os("FLY_ROM") {
Some(path) => Some(PathBuf::from(path)),
None => {
eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)");
None
}
}
}
/// `FLYSIM_LOG=info` shows both runtimes' logs.
fn init_tracing() {
if let Ok(filter) = std::env::var("FLYSIM_LOG") {
let _ = tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::new(filter))
.with_writer(std::io::stderr)
.try_init();
}
}
fn sha(bytes: &[u8]) -> String {
fly_session::types::sha256_hex(bytes)
}
/// Which runtime is behind the router.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Runtime {
Legacy,
Session(ExecutionMode),
}
impl Runtime {
fn label(&self) -> String {
match self {
Runtime::Legacy => "legacy".to_owned(),
Runtime::Session(mode) => format!("session ({})", mode.label()),
}
}
}
/// One control request of the script: at the snapshot of running frame `at` (counted from the
/// first running snapshot, 0-based), send `method path body`.
#[derive(Clone, Debug)]
struct Action {
at: usize,
method: Method,
path: &'static str,
body: Option<Value>,
}
fn act(at: usize, method: Method, path: &'static str, body: Option<Value>) -> Action {
Action {
at,
method,
path,
body,
}
}
/// The script both runtimes are driven by.
fn script() -> Vec<Action> {
let sugar = || Some(json!({"by": "viewer_one", "source": "points", "durationMs": 300}));
vec![
act(2, Method::GET, "/healthz", None),
act(3, Method::POST, "/stimulate", sugar()),
// Inside the pulse: refused with the pulse's own retry.
act(4, Method::POST, "/stimulate", sugar()),
act(5, Method::POST, "/reward", Some(json!({"value": 1.0, "by": "op", "source": "operator"}))),
act(6, Method::POST, "/chat", Some(json!({"by": "viewer_two", "text": "go fly go"}))),
act(7, Method::POST, "/chat", Some(json!({"by": "not a name!", "text": "hello"}))),
act(8, Method::POST, "/stimulate", Some(json!({"by": "x"}))),
act(12, Method::POST, "/checkpoint", None),
// Two sugars before one commit (the TASK-01 review's N1): the legacy drain refuses the
// second with the first one's pulse as the retry, and so must the session's.
act(24, Method::POST, "/stimulate", Some(json!({"by": "viewer_five", "source": "points", "durationMs": 600}))),
act(24, Method::POST, "/stimulate", Some(json!({"by": "viewer_six", "source": "chat"}))),
act(40, Method::POST, "/stimulate", Some(json!({"by": "viewer_three", "source": "chat"}))),
act(41, Method::POST, "/stimulate", Some(json!({"by": "viewer_three", "source": "chat", "durationMs": 5000}))),
act(60, Method::POST, "/pause", None),
act(60, Method::POST, "/pause", None),
act(60, Method::POST, "/resume", None),
act(70, Method::GET, "/events?since=0&limit=500", None),
act(80, Method::POST, "/chat", Some(json!({"by": "viewer_two", "text": "again", "bot": true}))),
act(90, Method::GET, "/nope", None),
act(95, Method::POST, "/stimulate", Some(json!({"by": "viewer_four", "source": "points", "durationMs": 50}))),
]
}
/// What one run produced.
struct Recording {
/// Every running snapshot: the comparable header and the attachments' digests.
running: Vec<(Value, [String; 3])>,
/// The idle headers a pause published (compared for shape, not count).
idle: Vec<Value>,
responses: Vec<(String, u16, Value)>,
status: Value,
metric_names: Vec<String>,
events: Vec<Value>,
event_file: Vec<Value>,
journal: Vec<Value>,
final_checkpoint: Value,
}
/// The header without the fields that are wall clock by definition.
fn comparable(snapshot: &Snapshot) -> Value {
let mut value = serde_json::to_value(&snapshot.header).expect("a header serializes");
let map = value.as_object_mut().expect("an object");
for key in ["wallMs", "uptimeSeconds", "realtimeFactor", "seq"] {
map.remove(key);
}
if let Some(sugar) = map.get_mut("sugar").and_then(Value::as_object_mut) {
sugar.remove("cooldownMs");
}
for list in ["events", "chat"] {
if let Some(items) = map.get_mut(list).and_then(Value::as_array_mut) {
for item in items {
if let Some(item) = item.as_object_mut() {
item.remove("wallMs");
}
}
}
}
value
}
fn without_wall(mut value: Value) -> Value {
if let Some(map) = value.as_object_mut() {
map.remove("wallMs");
}
value
}
async fn call(router: axum::Router, action: &Action) -> (u16, Value) {
let request = Request::builder()
.method(action.method.clone())
.uri(action.path);
let request = match &action.body {
Some(body) => request
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(body).unwrap())),
None => request.body(Body::empty()),
}
.unwrap();
let response = router.oneshot(request).await.unwrap();
let status = response.status().as_u16();
let bytes = axum::body::to_bytes(response.into_body(), 16 << 20)
.await
.unwrap();
let value = serde_json::from_slice(&bytes)
.unwrap_or_else(|_| Value::String(String::from_utf8_lossy(&bytes).into_owned()));
(status, value)
}
/// The service configuration of a run: flysim's defaults with the store under `dir`, every frame
/// published, no timed checkpoints (the script and the boundaries take them), chat on.
fn config(rom: &Path, dataset: &Path, dir: &Path, mode: MacroMode, speed: f64) -> Config {
let mut config = Config::default();
config.paths.rom = rom.to_path_buf();
config.paths.dataset = dataset.to_path_buf();
config.paths.save_dir = dir.join("durable");
config.paths.hot_dir = dir.join("hot");
config.loop_.game = "pokemon-red".to_owned();
config.loop_.speed = speed;
config.loop_.threads = 1;
config.loop_.snapshot_hz = 1_000_000.0;
config.loop_.hot_seconds = 1e9;
config.loop_.checkpoint_seconds = 1e9;
config.macros.mode = mode;
config.chat.enabled = true;
config
}
/// Start `runtime` over `config` behind the control router, drive the script for `frames`
/// running snapshots, shut down, and collect everything.
fn record(
runtime: Runtime,
config: Config,
profile: LegacyProfileKind,
frames: usize,
actions: &[Action],
) -> Recording {
let shared = Arc::new(Shared::new(config.clone(), EventRing::new()));
let (commands, command_rx) = mpsc::channel::<Command>(flysim::simloop::COMMAND_QUEUE);
let (snapshots_tx, snapshots) = watch::channel(Arc::new(booting_snapshot(
0,
0,
config.macros.mode,
)));
let state = AppState {
shared: Arc::clone(&shared),
commands: commands.clone(),
snapshots: snapshots.clone(),
};
let session_dir = config.paths.save_dir.parent().unwrap().join("session");
let loop_shared = Arc::clone(&shared);
let thread = std::thread::spawn(move || -> anyhow::Result<()> {
let notifier = flysim::sdnotify::Notifier::from_env();
match runtime {
Runtime::Legacy => {
let mut sim = Sim::boot(loop_shared, snapshots_tx, command_rx)?;
sim.run(&notifier)
}
Runtime::Session(mode) => {
let options = ServiceOptions {
mode,
profile,
session_dir,
};
run_host(loop_shared, snapshots_tx, command_rx, &notifier, &options)
}
}
});
let driver = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.unwrap();
let router = flysim::api::router(state.clone());
let metrics_router = flysim::api::metrics_router(state.clone());
let recording = driver.block_on(async {
let mut snapshots = snapshots;
let mut running: Vec<(Value, [String; 3])> = Vec::new();
let mut idle = Vec::new();
let mut pending = Vec::new();
let mut last_frame: Option<u64> = None;
let deadline = Instant::now() + Duration::from_secs(1800);
while running.len() < frames {
assert!(Instant::now() < deadline, "{}: the run stalled", runtime.label());
match tokio::time::timeout(Duration::from_secs(120), snapshots.changed()).await {
Ok(Ok(())) => {}
// The loop is gone: its own error is the failure (the thread is joined below).
Ok(Err(_)) => break,
Err(_) => panic!(
"{}: no snapshot for 120 s after {} running",
runtime.label(),
running.len()
),
}
let snapshot = Arc::clone(&snapshots.borrow_and_update());
match snapshot.header.status {
FeedStatus::Running | FeedStatus::Recovering => {
// Every frame publishes; a gap means the recorder fell behind the loop.
let frame = snapshot.header.frame;
if let Some(last) = last_frame {
assert_eq!(
frame,
last + 1,
"{}: the recorder missed a frame (pace the loop slower)",
runtime.label()
);
}
last_frame = Some(frame);
let index = running.len();
if index.is_multiple_of(30) {
eprintln!(" {}: running snapshot {index} (frame {frame})", runtime.label());
}
running.push((
comparable(&snapshot),
[
sha(&snapshot.frame),
sha(&snapshot.audio),
sha(&snapshot.spikes),
],
));
// Sent now, in order, each drained before the next frame.
for action in actions.iter().filter(|a| a.at == index) {
let router = router.clone();
let label = format!("{} {}", action_label(action), index);
let action = action.clone();
let handle = tokio::spawn(async move { call(router, &action).await });
// One at a time, so the loop drains them in script order.
tokio::time::sleep(Duration::from_millis(2)).await;
pending.push((label, handle));
}
}
FeedStatus::Paused => idle.push(comparable(&snapshot)),
FeedStatus::Booting | FeedStatus::Error => {}
}
}
// Stop at once, so the final save is of the frame after the last one recorded.
let (reply, ack) = tokio::sync::oneshot::channel();
if commands.send(Command::Shutdown { reply }).await.is_ok() {
let _ = ack.await;
}
let mut responses = Vec::new();
for (label, handle) in pending {
let (status, body) = handle.await.unwrap();
responses.push((label, status, body));
}
let (_, status) = call(
router.clone(),
&act(0, Method::GET, "/status", None),
)
.await;
let (_, metrics) = call(
metrics_router.clone(),
&act(0, Method::GET, "/metrics", None),
)
.await;
let metric_names: Vec<String> = metrics
.as_str()
.unwrap_or_default()
.lines()
.filter(|l| !l.starts_with('#') && !l.is_empty())
.filter_map(|l| l.split([' ', '{']).next())
.map(str::to_owned)
.collect();
(running, idle, responses, status, metric_names)
});
thread
.join()
.expect("the loop thread")
.unwrap_or_else(|e| panic!("{}: {e:#}", runtime.label()));
let (running, idle, responses, status, metric_names) = recording;
assert_eq!(running.len(), frames, "{}: the loop stopped early", runtime.label());
let events: Vec<Value> = shared
.events
.page(0, flysim::eventlog::RING_CAPACITY)
.into_iter()
.map(|e| without_wall(serde_json::to_value(e).unwrap()))
.collect();
let event_file: Vec<Value> =
flysim::eventlog::read_events(&config.paths.save_dir.join("events.jsonl"))
.unwrap_or_default()
.into_iter()
.map(|e| without_wall(serde_json::to_value(e).unwrap()))
.collect();
let journal: Vec<Value> = flysim::journal::read(&config.paths.hot_dir.join(flysim::journal::FILE_NAME))
.unwrap_or_default()
.into_iter()
.map(|mut line| {
if let Some(boot) = line.get_mut("boot").and_then(Value::as_object_mut) {
boot.remove("runtime");
boot.remove("wallMs");
}
without_wall(line)
})
.collect();
let durable = flysim::store::Store::new(&config.paths.save_dir, 64);
let latest = durable.highest_generation();
let bytes = std::fs::read(
flysim::store::restore_order(
&flysim::store::Store::new(&config.paths.hot_dir, 64),
&durable,
)
.into_iter()
.find(|c| c.generation == Some(latest))
.expect("the final save")
.path,
)
.unwrap();
let final_checkpoint = checkpoint_json(&bytes);
Recording {
running,
idle,
responses,
status,
metric_names,
events,
event_file,
journal,
final_checkpoint,
}
}
fn action_label(action: &Action) -> String {
format!("{} {}", action.method, action.path)
}
/// A FLYSIM01 checkpoint as comparable JSON: the runtime half without `wallMs`, and a digest of
/// every agent array.
fn checkpoint_json(bytes: &[u8]) -> Value {
let checkpoint = flysim::store::decode(bytes).expect("FLYSIM01");
let runtime = &checkpoint.runtime;
let agent = &checkpoint.agent;
json!({
"generation": runtime.generation,
"romSha256": runtime.rom_sha256,
"emulatorFrame": runtime.emulator_frame,
"compatibility": runtime.compatibility,
"buttons": runtime.buttons,
"rankSinceMs": runtime.rank_since_ms,
"lastEventId": runtime.last_event_id,
"reward": runtime.reward,
"ratchet": serde_json::to_value(runtime.ratchet).unwrap(),
"emulator": sha(&runtime.emulator),
"framebuffer": sha(&runtime.framebuffer),
"ratchetGame": sha(&runtime.ratchet_game),
"agent": sha(format!("{agent:?}").as_bytes()),
})
}
/// Field-by-field comparison with the first difference as the failure.
fn same(what: &str, a: &Value, b: &Value) {
if a != b {
panic!(
"{what} differs:\n legacy {}\n session {}",
truncate(a),
truncate(b)
);
}
}
fn truncate(value: &Value) -> String {
let text = value.to_string();
if text.len() > 4000 {
format!("{}...", &text[..4000])
} else {
text
}
}
fn compare(legacy: &Recording, session: &Recording, label: &str) {
assert_eq!(
legacy.running.len(),
session.running.len(),
"{label}: running snapshots"
);
for (n, ((a, da), (b, db))) in legacy.running.iter().zip(&session.running).enumerate() {
if a != b {
// Name the first differing field.
let (Some(am), Some(bm)) = (a.as_object(), b.as_object()) else {
panic!()
};
for key in am.keys().chain(bm.keys()) {
same(
&format!("{label}: snapshot {n} (frame {}) {key}", a["frame"]),
&a[key.as_str()],
&b[key.as_str()],
);
}
}
for (i, name) in ["frame", "audio", "spikes"].iter().enumerate() {
assert_eq!(
da[i], db[i],
"{label}: snapshot {n} (frame {}) attachment {name}",
a["frame"]
);
}
}
assert_eq!(legacy.idle.is_empty(), session.idle.is_empty(), "{label}: idle headers");
if let (Some(a), Some(b)) = (legacy.idle.first(), session.idle.first()) {
same(&format!("{label}: the first idle header"), a, b);
}
assert_eq!(legacy.responses.len(), session.responses.len());
for ((la, sa, ba), (lb, sb, bb)) in legacy.responses.iter().zip(&session.responses) {
assert_eq!(la, lb);
assert_eq!(sa, sb, "{label}: {la} status");
let strip = |v: &Value| {
let mut v = v.clone();
if let Some(events) = v.get_mut("events").and_then(Value::as_array_mut) {
for e in events {
if let Some(e) = e.as_object_mut() {
e.remove("wallMs");
}
}
}
v
};
same(&format!("{label}: {la} body"), &strip(ba), &strip(bb));
}
let status = |v: &Value| {
let mut v = v.clone();
let map = v.as_object_mut().unwrap();
for key in ["wallMs", "uptimeSeconds", "realtimeFactor", "seq"] {
map.remove(key);
}
if let Some(s) = map.get_mut("sugar").and_then(Value::as_object_mut) {
s.remove("cooldownMs");
}
if let Some(c) = map.get_mut("checkpoint").and_then(Value::as_object_mut) {
c.remove("latestWallMs");
}
if let Some(items) = map.get_mut("chat").and_then(Value::as_array_mut) {
for item in items {
item.as_object_mut().unwrap().remove("wallMs");
}
}
v
};
// `/status` is read between frames on both sides; the frame it lands on is the driver's
// timing, so only its shape and its stable parts are compared.
let (a, b) = (status(&legacy.status), status(&session.status));
for key in ["version", "status", "chat"] {
same(&format!("{label}: /status {key}"), &a[key], &b[key]);
}
let keys = |v: &Value| v.as_object().unwrap().keys().cloned().collect::<Vec<_>>();
assert_eq!(keys(&a), keys(&b), "{label}: /status fields");
assert_eq!(
keys(&a["decoder"]),
keys(&b["decoder"]),
"{label}: /status decoder fields"
);
same(
&format!("{label}: /status decoder channels"),
&json!(a["decoder"]["channels"].as_array().map(|c| c.iter().map(|x| (x["channel"].clone(), x["role"].clone())).collect::<Vec<_>>())),
&json!(b["decoder"]["channels"].as_array().map(|c| c.iter().map(|x| (x["channel"].clone(), x["role"].clone())).collect::<Vec<_>>())),
);
assert_eq!(legacy.metric_names, session.metric_names, "{label}: /metrics series");
same(&format!("{label}: event ring"), &json!(legacy.events), &json!(session.events));
same(
&format!("{label}: events.jsonl"),
&json!(legacy.event_file),
&json!(session.event_file),
);
same(&format!("{label}: sugar journal"), &json!(legacy.journal), &json!(session.journal));
same(
&format!("{label}: final checkpoint"),
&legacy.final_checkpoint,
&session.final_checkpoint,
);
}
/// Copy a seeded store (both directories) into a run's own directory.
fn seed(from: &Path, to: &Path) {
for sub in ["durable", "hot"] {
let src = from.join(sub);
let dst = to.join(sub);
std::fs::create_dir_all(&dst).unwrap();
if let Ok(entries) = std::fs::read_dir(&src) {
for entry in entries.flatten() {
if entry.file_type().unwrap().is_file() {
std::fs::copy(entry.path(), dst.join(entry.file_name())).unwrap();
}
}
}
}
}
fn modes() -> Vec<ExecutionMode> {
let mut modes = vec![ExecutionMode::InProcess];
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 {}", program.display());
}
modes
}
#[allow(clippy::too_many_arguments)]
fn run_pair(
rom: &Path,
dataset: &Path,
seeded: &Path,
profile: LegacyProfileKind,
mode: MacroMode,
speed: f64,
frames: usize,
label: &str,
) {
init_tracing();
let actions = script();
let root = tempfile::tempdir().unwrap();
let dir = root.path().join("legacy");
seed(seeded, &dir);
let started = Instant::now();
let legacy = record(
Runtime::Legacy,
config(rom, dataset, &dir, mode, speed),
profile,
frames,
&actions,
);
eprintln!("{label}: legacy {} running snapshots in {:.1?}", legacy.running.len(), started.elapsed());
for exec in modes() {
let dir = root.path().join(format!("session-{}", exec.label()));
seed(seeded, &dir);
let started = Instant::now();
let session = record(
Runtime::Session(exec),
config(rom, dataset, &dir, mode, speed),
profile,
frames,
&actions,
);
let label = format!("{label}, {}", exec.label());
compare(&legacy, &session, &label);
let rewards = legacy
.events
.iter()
.filter(|e| e["kind"] == "reward")
.count();
let macros = legacy.events.iter().filter(|e| e["kind"] == "macro").count();
let kinds: std::collections::BTreeMap<String, usize> =
legacy.events.iter().fold(Default::default(), |mut m, e| {
*m.entry(e["kind"].as_str().unwrap_or("?").to_owned()).or_default() += 1;
m
});
eprintln!("{label}: event kinds {kinds:?}");
eprintln!(
"{label}: IDENTICAL -- {} running snapshots (frames, audio, spikes byte-equal), {} idle, \
{} control responses, {} events ({rewards} reward, {macros} macro), {} journal lines, \
final checkpoint g{} equal ({:.1?})",
session.running.len(),
session.idle.len(),
session.responses.len(),
session.events.len(),
session.journal.len(),
session.final_checkpoint["generation"],
started.elapsed()
);
for (what, status, body) in &session.responses {
eprintln!(" {what} -> {status} {}", truncate(body));
}
}
}
/// A store seeded by a legacy fresh start of `seconds` wall seconds, shut down cleanly.
fn seed_by_legacy_fresh_start(rom: &Path, dataset: &Path, dir: &Path, mode: MacroMode) {
let config = config(rom, dataset, dir, mode, 1.0);
let shared = Arc::new(Shared::new(config.clone(), EventRing::new()));
let (commands, command_rx) = mpsc::channel::<Command>(64);
let (snapshots_tx, mut snapshots) =
watch::channel(Arc::new(booting_snapshot(0, 0, mode)));
let thread = std::thread::spawn(move || -> anyhow::Result<()> {
let mut sim = Sim::boot(shared, snapshots_tx, command_rx)?;
sim.run(&flysim::sdnotify::Notifier::from_env())
});
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
loop {
snapshots.changed().await.unwrap();
if snapshots.borrow().header.frame >= 120 {
break;
}
}
let (reply, ack) = tokio::sync::oneshot::channel();
commands.send(Command::Shutdown { reply }).await.unwrap();
let _ = ack.await;
});
thread.join().unwrap().unwrap();
}
#[test]
fn toy_raw_service_contracts() {
let Some(rom) = rom_path() else { return };
let dataset = fly_session::legacy_parity::toy::dir();
let seeded = tempfile::tempdir().unwrap();
seed_by_legacy_fresh_start(&rom, &dataset, seeded.path(), MacroMode::Raw);
run_pair(
&rom,
&dataset,
seeded.path(),
LegacyProfileKind::Toy,
MacroMode::Raw,
0.25,
120,
"toy raw",
);
}
// No toy macros run: AGENT-01's worker refuses a macro channel whose rate role the dataset does
// not track, and the committed toy connectome tracks none (the legacy loop merges them in). The
// production connectome tracks them all; `fafb_macros_*` below is the macros-mode run.
/// The real connectome from the live service's `rollback` checkpoint (ENV-01 traces): the
/// ratchet rolls back on the first boundary, so the recovery event, the `recovering` status and
/// the after-rollback durable save are on the contract too.
#[test]
fn fafb_macros_service_contracts_through_a_rollback() {
let Some(rom) = rom_path() else { return };
if std::env::var_os("FLY_SERVE01_FAFB").is_none() {
eprintln!("skipping: FLY_SERVE01_FAFB is not set");
return;
}
let Some(dataset) = fly_session::legacy_parity::fafb_dir() else {
eprintln!("skipping: no data/fafb-v783");
return;
};
// `FLY_SERVE01_FAFB_CHECKPOINT` picks another start (a reward-bearing one for a long run).
let source = std::env::var_os("FLY_SERVE01_FAFB_CHECKPOINT")
.map(PathBuf::from)
.or_else(|| {
std::env::var_os("FLY_ENV01_TRACE_DIR")
.map(|dir| PathBuf::from(dir).join("rollback.checkpoint"))
.filter(|p| p.is_file())
})
.or_else(|| std::env::var_os("FLY_DOOR_CHECKPOINT").map(PathBuf::from));
let Some(source) = source else {
eprintln!("skipping: no source checkpoint");
return;
};
eprintln!("fafb: from {}", source.display());
let mut bytes = std::fs::read(&source).unwrap();
if std::env::var_os("FLY_SERVE01_THIN").is_some() {
bytes = reward_bearing(&bytes);
}
let generation = flysim::store::decode(&bytes).unwrap().runtime.generation;
let seeded = tempfile::tempdir().unwrap();
flysim::store::Store::new(seeded.path().join("durable"), 4)
.commit(generation, &bytes, None)
.unwrap();
let frames = std::env::var("FLY_SERVE01_FAFB_FRAMES")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(120);
let speed = std::env::var("FLY_SERVE01_FAFB_SPEED")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0.1);
run_pair(
&rom,
&dataset,
seeded.path(),
LegacyProfileKind::Production,
MacroMode::Macros,
speed,
frames,
"fafb macros",
);
}
/// TASK-01's ledger thinning (`session_trace.rs`), so a brain run from a stream checkpoint earns
/// rewards: the current map unvisited, its exits unfound, its ground unwalked, no wild win a
/// replay (`FLY_SERVE01_THIN`).
fn reward_bearing(bytes: &[u8]) -> Vec<u8> {
let mut checkpoint = flysim::store::decode(bytes).expect("FLYSIM01");
let reward = &mut checkpoint.runtime.reward;
let map = reward["location"]
.as_str()
.and_then(|l| l.split(':').next())
.unwrap_or("0")
.to_owned();
if let Some(seen) = reward["seen"].as_array_mut() {
seen.retain(|key| {
let key = key.as_str().unwrap_or("");
key != format!("map:{map}") && !key.starts_with(&format!("boundary:{map}:"))
});
}
if let Some(tiles) = reward["tiles"].as_array_mut() {
tiles.retain(|tile| !tile.as_str().unwrap_or("").starts_with(&format!("{map}:")));
}
if let Some(counts) = reward["tileCounts"].as_object_mut() {
counts.remove(&map);
}
reward["wildWins"] = json!({});
reward["replayBlocked"] = json!([]);
flysim::store::encode(&checkpoint.agent, &checkpoint.runtime).expect("encodes")
}