flybrain/services/flysim/crates/fly-legacy-session/src/composition.rs
acamilo b2fd148f52 session: the live composition's participants on the router (BUS-01)
FLY_SESSION_TRANSPORT=bus (flysim-session --transport bus) runs the
agent and the world as socket clients of the session's router, one
process each by default (FLY_SESSION_MODE=thread and in-process too);
local, the PERF-01 lane, stays the default. Results, traces, checkpoints
and the compatibility string are the same in every arm (SessionArm:
local, bus/in-process, bus/thread, bus/process; FLY_PARITY_ARMS picks
them for the parity suites).

- process-mode placement: the service splits its cpuset as PERF-02 does
  and hands each process its CPUs (--host-cpus, --sweep-cpus;
  Launcher::place_process; pool::apply_placement); FLY_SESSION_AUX_CPUS
  moves the service and the world
- the launcher's own clients in memory in thread and process modes
- participants on a one-worker runtime; long handlers under
  block_in_place, which fixes a process-mode boot that failed when
  Agent.Initialize outlived the 2 s probe on a loaded box
- writers allocated ahead (WriterPool); a worker's own seals cached by
  clone, not a second hold
- over the bus the agent's Commit attaches its feed status, which the
  host reads instead of calling Legacy.FeedStatus at every publish
- fly-shadow --mode / FLY_SHADOW_MODE names the topology, forwarded to a
  remote box; the verdict records candidate.transport; fly-shadow check
  --require-arm

legacy-gameboy-v1 section 12 and 18 carry the dated amendments.
2026-10-02 00:09:41 +00:00

949 lines
39 KiB
Rust

//! The legacy Game Boy composition on the session framework: one legacy agent (AGENT-01), the
//! legacy environment (ENV-01), and the `pokered-macros-v1` task and executor (this crate) in the
//! coordinator, over one router, in any of the launcher's execution modes.
//!
//! This is the whole new runtime of the live fly short of its edge (EDGE-01) and its FLYSIM01
//! export (STATE-02): what CUT-01's shadow runs beside the legacy service.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use flybus::{Grants, Pattern, Policy, RouterConfig};
use fly_session::coordinator::{AgentSlot, Coordinator, StepDetails, StepReport};
use fly_session::fly_session_types::extensions::ROLLBACK_POLICY;
use fly_session::fly_session_types::gameboy;
use fly_session::launcher::{
ExecutionMode, Launcher, LegacyAgentLaunch, LegacyEnvironmentLaunch, ProcessCpus,
SUPERVISOR_CLIENT, ThreadBudget, Via,
};
use fly_session::legacy_agent::{LegacyProfileKind, SPIKES_ATTACHMENT};
use fly_session::legacy_env::BackendConfig;
use fly_session::task::ActionExecutor;
use fly_session::types::*;
use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros;
use flysim::snapshot::MacroMode;
use crate::task::{PokeredConfig, PokeredTask, TaskRecord};
use fly_session::legacy_checkpoint::{
AgentImport, CheckpointerConfig, LegacyCapture, LegacyCheckpointer, RankChange, SaveKind,
SaveReport, SaveTicket, TaskHalf, now_wall_ms,
};
use flysim::store::Checkpoint;
use std::time::Instant;
fn grants(f: impl FnOnce(&mut Grants)) -> Grants {
let mut g = Grants::default();
f(&mut g);
g
}
/// The transitions a service session keeps in memory for diagnosis (about a minute at 60 Hz).
const HISTORY: usize = 4096;
/// A service session's committed-snapshot cadence on the session topic: once a second of frames
/// (every 60th boundary), plus every boundary with task events or boundary actions, which the
/// coordinator always publishes. The live presentation is the legacy feed (`docs/feed-protocol.md`,
/// 30 Hz, built by the service host from the committed boundary), not this topic, which nothing
/// in the release subscribes to; each snapshot attaches a sealed copy of the frame and the audio
/// chunk, so publishing it every other frame cost about 0.7 ms a frame on the release CPU
/// (PERF-01; was 2).
const SNAPSHOT_EVERY: u64 = 60;
const COORDINATOR_CLIENT: &str = "coordinator";
const ENV_CLIENT: &str = "legacy-world";
const ENV_SERVICE: &str = "env.world";
const ENV_WORKER: &str = "world";
/// The environment's worker id, which [`LegacyConfig::placements`] names it by.
pub const WORLD_WORKER: &str = ENV_WORKER;
const AGENT_CLIENT: &str = "legacy-fly";
/// How the session's participants reach each other (BUS-01).
///
/// - `Local`: in-process participants are called over the local lane (PERF-01): no bus message
/// and no store file per call. Only [`ExecutionMode::InProcess`] has a lane.
/// - `Bus`: every participant is a client of the session's router over a Unix-domain socket,
/// launcher-bound to its identity, with its artifacts in the router's store: the topology that
/// takes more flies and more worlds by configuration. In-process, thread and process modes all
/// run it; thread and process modes have no other transport.
///
/// Neither changes a result, a trace or a checkpoint: the transport carries the same domain calls
/// to the same endpoints (`legacy-gameboy-v1` section 12, amendment 2026-10-01 BUS-01).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Transport {
#[default]
Local,
Bus,
}
impl Transport {
pub fn label(&self) -> &'static str {
match self {
Transport::Local => "local",
Transport::Bus => "bus",
}
}
/// `local` or `bus`.
pub fn parse(value: &str) -> Result<Transport, String> {
match value {
"local" => Ok(Transport::Local),
"bus" => Ok(Transport::Bus),
other => Err(format!("transport {other:?}: local or bus")),
}
}
/// The launcher transport for a mode: the lane only in process and only when asked for (and
/// not turned off by `FLY_SESSION_LOCAL_LANE=0`, which keeps an in-memory bus); Unix sockets
/// for the bus, and always for a thread or a process.
pub fn via(&self, mode: ExecutionMode) -> Via {
match (self, mode) {
(Transport::Local, ExecutionMode::InProcess) if local_lane_enabled() => Via::Local,
(Transport::Local, ExecutionMode::InProcess) => Via::Memory,
_ => Via::Unix,
}
}
}
/// One way to run the composition: where the participants run and how they are reached.
/// `local` (in-process over the lane, the release default until the bus cutover), `bus/in-process`,
/// `bus/thread` and `bus/process`. Parity runs and measurements name them this way
/// (`FLY_PARITY_ARMS`, `FLY_PERF_ARMS`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SessionArm {
pub mode: ExecutionMode,
pub transport: Transport,
}
impl SessionArm {
pub const LOCAL: SessionArm = SessionArm {
mode: ExecutionMode::InProcess,
transport: Transport::Local,
};
pub const BUS_IN_PROCESS: SessionArm = SessionArm {
mode: ExecutionMode::InProcess,
transport: Transport::Bus,
};
pub const BUS_THREAD: SessionArm = SessionArm {
mode: ExecutionMode::Thread,
transport: Transport::Bus,
};
pub const BUS_PROCESS: SessionArm = SessionArm {
mode: ExecutionMode::Process,
transport: Transport::Bus,
};
pub fn label(&self) -> String {
match self.transport {
Transport::Local => "local".to_owned(),
Transport::Bus => format!("bus/{}", self.mode.label()),
}
}
/// `local`, `bus` (= `bus/process`), `bus/in-process`, `bus/thread`, `bus/process`; also the
/// bare mode names `in-process` (= local), `thread` and `process` (= the bus).
pub fn parse(value: &str) -> Result<SessionArm, String> {
Ok(match value.trim() {
"local" | "in-process" => SessionArm::LOCAL,
"bus/in-process" => SessionArm::BUS_IN_PROCESS,
"bus/thread" | "thread" => SessionArm::BUS_THREAD,
"bus" | "bus/process" | "process" => SessionArm::BUS_PROCESS,
other => {
return Err(format!(
"{other:?}: local, bus/in-process, bus/thread or bus/process"
));
}
})
}
/// The arms a parity run compares with the legacy loop: `FLY_PARITY_ARMS` (a list of
/// [`SessionArm::parse`] names), else `local`, `bus/thread` and `bus/process`. Process mode
/// needs the workspace's `fly-session` binary; a build without it skips that arm and says so.
pub fn parity_arms() -> Vec<SessionArm> {
let arms = match std::env::var("FLY_PARITY_ARMS") {
Ok(list) if !list.trim().is_empty() => SessionArm::parse_list(&list)
.unwrap_or_else(|e| panic!("FLY_PARITY_ARMS: {e}")),
_ => vec![SessionArm::LOCAL, SessionArm::BUS_THREAD, SessionArm::BUS_PROCESS],
};
let program = fly_session::launcher::default_worker_program();
arms.into_iter()
.filter(|arm| {
let runnable = arm.mode != ExecutionMode::Process || program.is_file();
if !runnable {
eprintln!(
"{} skipped: no worker program at {}",
arm.label(),
program.display()
);
}
runnable
})
.collect()
}
/// A comma-separated list of [`SessionArm::parse`] names.
pub fn parse_list(value: &str) -> Result<Vec<SessionArm>, String> {
value
.split(',')
.filter(|part| !part.trim().is_empty())
.map(SessionArm::parse)
.collect()
}
}
/// How one legacy session is composed.
#[derive(Clone, Debug)]
pub struct LegacyConfig {
pub mode: ExecutionMode,
/// The transport in-process participants use; thread and process modes always use the bus.
pub transport: Transport,
/// Process mode: where each participant process's threads run, by worker id (the agent's
/// id, [`WORLD_WORKER`]). Empty: they float (BUS-01).
pub placements: BTreeMap<Id, ProcessCpus>,
pub rom_path: PathBuf,
pub dataset_dir: PathBuf,
pub profile: LegacyProfileKind,
pub macro_mode: MacroMode,
pub agent_id: Id,
pub agent_threads: usize,
/// Record the step details and the task records (a parity run).
pub record: bool,
}
/// `FLY_SESSION_LOCAL_LANE=0` keeps in-process participants on the bus: a measurement knob,
/// so the local lane can be compared with the bus path in one build. On by default.
pub const LOCAL_LANE_ENV: &str = "FLY_SESSION_LOCAL_LANE";
fn local_lane_enabled() -> bool {
std::env::var(LOCAL_LANE_ENV).map_or(true, |v| v != "0")
}
/// The macro channels and the macro group's hold for a mode: the decoder preset flysim builds.
pub fn channels_and_hold(mode: MacroMode) -> (Vec<String>, f64) {
let channels: Vec<&str> = if mode.dealt() {
flybrain_gb::macro_channels(crate::task::GAME)
} else {
Vec::new()
};
let preset = gameboy_decoder_config_with_macros(&channels);
let hold_ms = preset
.macros
.as_ref()
.or(preset.exclusive.as_ref())
.map_or(0.0, |group| group.hold_ms);
(channels.iter().map(|c| (*c).to_owned()).collect(), hold_ms)
}
/// A running legacy session: its launcher, its coordinator and the task object.
pub struct LegacySession {
pub coordinator: Coordinator,
pub task: PokeredTask,
pub launcher: Launcher,
pub rom: Vec<u8>,
pub config: LegacyConfig,
session_id: Id,
backend: BackendConfig,
/// Which generation of the world is running: 1 is the one the session started.
world_generation: u32,
/// The legacy store policy, once attached ([`LegacySession::attach_store`]).
checkpointer: Option<LegacyCheckpointer>,
saves: u64,
/// Saves on the writer thread whose outcome has not been collected.
pending_saves: Vec<SaveTicket>,
/// Captures sent and not yet collected ([`LegacySession::begin_save`]).
pending_captures: Vec<(fly_session::coordinator::PendingCapture, SaveKind, TaskHalf)>,
/// The feed event log's watermark the saves record: the restored file's, carried over (the
/// session runtime has no feed event log of its own before EDGE-01).
last_event_id: u64,
}
/// Where the legacy store lives and how often it is written (the service's `[paths]` and
/// `[loop]`).
#[derive(Clone, Debug)]
pub struct StoreConfig {
pub hot_dir: PathBuf,
pub durable_dir: PathBuf,
pub keep_generations: usize,
pub hot_seconds: f64,
pub checkpoint_seconds: f64,
pub speed: f64,
}
/// This build's legacy compatibility string (`flysim --print-compatibility`): the kernel, the
/// adapter, the profile's dataset fingerprint, the plasticity rule and the pokered symbols. It is
/// the restore gate and what every save records (`legacy-gameboy-v1` section 12).
pub fn compatibility_of(config: &LegacyConfig) -> String {
let adapter = flybrain_gb::pokemon_red::PokemonRedReward::new();
let profile = config.profile.profile();
flybrain_gb::Compatibility {
neural_kernel_version: gameboy::KERNEL_VERSION,
adapter: flybrain_gb::GameAdapter::id(&adapter),
dataset_fingerprint: &profile.dataset_fingerprint,
plasticity_version: gameboy::PLASTICITY_VERSION,
pokered_commit: &flybrain_gb::GameAdapter::symbol_provenance(&adapter),
}
.string()
}
/// How a session came up.
#[derive(Debug)]
pub enum Boot {
/// No checkpoint in either store: a fresh fly, warmed up.
Fresh,
/// A candidate restored, after `skipped` were refused.
Restored {
candidate: flysim::store::Candidate,
skipped: Vec<(flysim::store::Candidate, String)>,
migrated_from: Option<String>,
imported: crate::import::Imported,
},
}
/// `Sim::boot` on the session runtime: restore from the live FLYSIM01 stores in the legacy order
/// (hot latest, hot previous, durable latest, durable previous, milestone archives by rank), each
/// candidate held to the legacy gate (`RestoreGate`: the cartridge and the compatibility decision
/// with `FLY_ACCEPT_ADAPTERS`), falling to the next on *any* refusal -- unreadable, gated, or
/// refused by a participant's `State.StageRestore` or the task. A refused install fences its
/// session, so each attempt runs on a session of its own (a directory under `root` each). No
/// candidate at all is a fresh start; candidates that all fail are an error, as the legacy loop
/// refuses to start a fresh fly over them. Either way the store is attached and the startup
/// durable save is written, and the intervals run from then.
pub async fn boot(
root: &Path,
config: LegacyConfig,
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> {
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 candidates = flysim::store::restore_order(&hot, &durable);
let rom = std::fs::read(&config.rom_path)
.map_err(|e| format!("the cartridge {}: {e}", config.rom_path.display()))?;
let adapter = flybrain_gb::pokemon_red::PokemonRedReward::new();
let gate = fly_session::legacy_checkpoint::RestoreGate::from_env(
&sha256_hex(&rom),
&compatibility_of(&config),
flybrain_gb::GameAdapter::migrates_from(&adapter),
);
let mut skipped: Vec<(flysim::store::Candidate, String)> = Vec::new();
let mut outcome = None;
for (attempt, candidate) in candidates.iter().enumerate() {
let checkpoint = match flysim::store::load(&candidate.path) {
Ok(checkpoint) => checkpoint,
Err(e) => {
skipped.push((candidate.clone(), format!("{e:#}")));
continue;
}
};
let migrated_from = match gate.check(&checkpoint) {
Ok(from) => from,
Err(reason) => {
skipped.push((candidate.clone(), reason));
continue;
}
};
let mut session =
LegacySession::start(&root.join(format!("attempt-{attempt}")), config.clone()).await?;
let installed = match session.bootstrap().await {
Ok(()) => session.import_checkpoint(&checkpoint, &id("e2")).await,
Err(e) => Err(e),
};
match installed {
Ok(imported) => {
let rank = session.task.rank();
session.attach_store(store)?;
session
.checkpointer_mut()
.expect("attached")
.restored(rank, imported.rank_since_ms);
outcome = Some((
session,
Boot::Restored {
candidate: candidate.clone(),
skipped: std::mem::take(&mut skipped),
migrated_from,
imported,
},
));
break;
}
Err(reason) => {
session.stop().await;
skipped.push((candidate.clone(), reason));
}
}
}
let (session, boot) = match outcome {
Some(pair) => pair,
None if candidates.is_empty() => {
let mut session = LegacySession::start(&root.join("fresh"), config).await?;
session.bootstrap().await?;
session.attach_store(store)?;
(session, Boot::Fresh)
}
None => {
let reasons: Vec<String> = skipped
.iter()
.map(|(candidate, reason)| format!("{}: {reason}", candidate.origin))
.collect();
return Err(format!(
"every one of the {} checkpoint candidates failed to load; refusing to start a \
fresh run over them:\n{}",
candidates.len(),
reasons.join("\n")
));
}
};
Ok((session, boot))
}
/// A save [`LegacySession::advance`] queued at the boundary it reached.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SaveQueued {
pub generation: u64,
pub durable: bool,
pub archive_rank: Option<u32>,
}
/// One transition as a parity run sees it.
pub struct Step {
pub report: StepReport,
pub details: Option<StepDetails>,
pub records: Vec<TaskRecord>,
}
impl LegacySession {
/// Builds the router, launches the world and the fly, and builds the coordinator with the task
/// object's two faces. Nothing has been initialized yet.
pub async fn start(root: &Path, config: LegacyConfig) -> Result<LegacySession, String> {
let rom = std::fs::read(&config.rom_path)
.map_err(|e| format!("the cartridge {}: {e}", config.rom_path.display()))?;
let rom_digest = sha256_hex(&rom);
let session_id = id("legacy");
let epoch = id("e1");
let store_root = root.join("store");
let sockets = root.join("sockets");
std::fs::create_dir_all(&sockets).map_err(|e| format!("sockets: {e}"))?;
let agent_service = format!("agent.{}", config.agent_id);
let policy = Policy::closed()
.client(
COORDINATOR_CLIENT,
grants(|g| {
g.call = vec![Pattern::prefix("agent."), Pattern::prefix("env.")];
g.publish = vec![Pattern::prefix("session.")];
g.manage_topics = vec![Pattern::prefix("session.")];
g.register = vec![Pattern::prefix("session.")];
}),
)
// The launcher's supervisor: health checks and shutdown, never a registration.
.client(
SUPERVISOR_CLIENT,
grants(|g| g.call = vec![Pattern::prefix("agent."), Pattern::prefix("env.")]),
)
.client(
ENV_CLIENT,
grants(|g| g.register = vec![Pattern::exact(ENV_SERVICE)]),
)
.client(
&format!("{ENV_CLIENT}-r2"),
grants(|g| g.register = vec![Pattern::exact(ENV_SERVICE)]),
)
.client(
AGENT_CLIENT,
grants(|g| g.register = vec![Pattern::exact(&agent_service)]),
);
let mut router_config = RouterConfig::new(&store_root);
router_config.policy = policy;
let router = flybus::Router::new(router_config).map_err(|e| format!("router: {e}"))?;
let budget = ThreadBudget::new(2 + config.agent_threads, 1).map_err(|e| e.message)?;
let mut launcher = Launcher::start(
router,
config.mode,
// `Transport::Local`: in-process participants are called over the local lane: the same
// worker shell, no bus message and no store file per artifact (PERF-01, `workers-v1`
// amendment). `Transport::Bus`: every participant is a socket client of the router,
// whatever its mode (BUS-01); a thread or a separate process always is.
config.transport.via(config.mode),
&store_root,
&sockets,
budget,
)
.await
.map_err(|e| format!("launcher: {}", e.message))?;
for (worker, cpus) in &config.placements {
launcher.place_process(worker, cpus.clone());
}
let mut backend = BackendConfig::legacy(&rom_digest);
backend.slots = vec![id(crate::task::SLOT)];
launcher
.launch_legacy_environment(LegacyEnvironmentLaunch {
session_id: session_id.clone(),
worker_id: id(ENV_WORKER),
incarnation_id: id("world-inc-1"),
worker_threads: 1,
rom_path: config.rom_path.clone(),
backend: backend.clone(),
client_id: ENV_CLIENT.to_owned(),
service: ENV_SERVICE.to_owned(),
})
.await
.map_err(|e| format!("the world: {}", e.message))?;
let environment = launcher
.worker(&id(ENV_WORKER))
.expect("launched")
.worker_ref();
let (macro_channels, hold_ms) = channels_and_hold(config.macro_mode);
let identity = launcher
.launch_legacy_agent(LegacyAgentLaunch {
session_id: session_id.clone(),
agent_id: config.agent_id.clone(),
port_id: id(fly_session::legacy_env::DEFAULT_PORT),
incarnation_id: parse_id(&format!("{}-inc-1", config.agent_id))?,
worker_threads: config.agent_threads,
dataset_dir: config.dataset_dir.clone(),
profile: config.profile,
macro_channels: macro_channels.clone(),
client_id: AGENT_CLIENT.to_owned(),
service: agent_service,
})
.await
.map_err(|e| format!("the fly: {}", e.message))?;
let agent_ref = launcher
.worker(&config.agent_id)
.expect("launched")
.worker_ref();
let mut slot = AgentSlot::new(
agent_ref,
config.agent_id.clone(),
id(fly_session::legacy_env::DEFAULT_PORT),
config.profile.profile().asset,
fly_session::legacy_parity::LEGACY_SEED,
);
slot.worker_threads = identity.worker_threads as u64;
slot.model_version = gameboy::KERNEL_VERSION.to_owned();
slot.plasticity_version = gameboy::PLASTICITY_VERSION.to_owned();
let task = PokeredTask::new(
PokeredConfig {
agent_id: config.agent_id.clone(),
port_id: id(fly_session::legacy_env::DEFAULT_PORT),
mode: config.macro_mode,
macro_channels,
hold_ms,
record: config.record,
},
&rom,
&rom_digest,
&epoch,
)?;
let client = launcher
.connect(COORDINATOR_CLIENT)
.await
.map_err(|e| format!("connect: {}", e.message))?;
let executors: BTreeMap<Id, Box<dyn ActionExecutor>> =
BTreeMap::from([(config.agent_id.clone(), task.executor())]);
let mut coordinator = Coordinator::new(
client,
session_id.clone(),
epoch,
id("ep1"),
environment,
vec![slot],
task.task(),
executors,
);
coordinator.set_environment_config(
backend.asset_ref(),
fly_session::environment::synthetic_asset("pokered-task", gameboy::EXECUTOR_ID),
);
coordinator.set_media(
&[gameboy::VIEW_ID],
&[fly_session::legacy_env::AUDIO_STREAM_ID],
);
coordinator.set_state_format(fly_session::legacy_env::STATE_FORMAT_ID);
coordinator.set_decision_schema(gameboy::CHANNELS.schema_ref());
coordinator
.declare_rollback_policy(ROLLBACK_POLICY)
.map_err(|e| e.message)?;
// The legacy loop runs as fast as its brain allows when measured, and the service paces
// itself; a parity run is a measurement.
if config.record {
coordinator.request_commit_attachments(&[SPIKES_ATTACHMENT]);
} else {
// A service session runs indefinitely: its in-memory history stays bounded.
coordinator.bound_history(HISTORY);
// The legacy feed publishes at `snapshot_hz` (30 Hz) from a 60 Hz loop.
coordinator.snapshot_every(SNAPSHOT_EVERY);
}
Ok(LegacySession {
coordinator,
task,
launcher,
rom,
config,
session_id,
backend,
world_generation: 1,
checkpointer: None,
saves: 0,
pending_saves: Vec::new(),
pending_captures: Vec::new(),
last_event_id: 0,
})
}
/// Hello, `Environment.Initialize` (the one-frame scaffold), the task's bootstrap on O[0],
/// `Agent.Initialize` (the warm-up): `Ready(0)`.
pub async fn bootstrap(&mut self) -> Result<(), String> {
self.coordinator
.bootstrap()
.await
.map_err(|e| format!("bootstrap ({}): {}", e.detail, e.error.message))?;
if self.config.record {
self.coordinator.disable_pacing();
}
Ok(())
}
/// The agent's identity as an import stamps it.
pub fn agent_import(&self) -> AgentImport {
let (macro_channels, _) = channels_and_hold(self.config.macro_mode);
AgentImport {
agent_id: self.config.agent_id.clone(),
profile: self.config.profile.profile().asset,
seed: fly_session::legacy_parity::LEGACY_SEED,
macro_channels,
}
}
/// This build's legacy compatibility string ([`compatibility_of`]).
pub fn compatibility(&self) -> String {
compatibility_of(&self.config)
}
/// Installs a FLYSIM01 checkpoint as this session's start (after [`LegacySession::bootstrap`],
/// before any transition): the world is replaced by a fresh one (the environment stages a
/// restore only on a replacement, as every group restore does), then [`crate::import`] runs
/// the group install and the session resumes at the checkpoint's boundary.
pub async fn import_checkpoint(
&mut self,
checkpoint: &Checkpoint,
epoch: &Id,
) -> Result<crate::import::Imported, String> {
if self.world_generation != 1 {
return Err("this session has already replaced its world".to_owned());
}
self.launcher.reap(&id(ENV_WORKER), &id("import")).await;
self.world_generation = 2;
self.launcher
.launch_legacy_environment(LegacyEnvironmentLaunch {
session_id: self.session_id.clone(),
worker_id: id(ENV_WORKER),
incarnation_id: id("world-inc-2"),
worker_threads: 1,
rom_path: self.config.rom_path.clone(),
backend: self.backend.clone(),
client_id: format!("{ENV_CLIENT}-r2"),
service: ENV_SERVICE.to_owned(),
})
.await
.map_err(|e| format!("the replacement world: {}", e.message))?;
let world = self
.launcher
.worker(&id(ENV_WORKER))
.expect("launched")
.worker_ref();
self.coordinator
.replace_participant(&id(ENV_WORKER), world)
.map_err(|e| format!("replacing the world: {}", e.error.message))?;
let rom = self.rom.clone();
let agent = self.agent_import();
let imported = crate::import::import_flysim01(
&mut self.coordinator,
&self.task,
checkpoint,
&rom,
&agent,
self.backend.audio_sample_rate,
epoch,
)
.await?;
if self.config.record {
self.coordinator.disable_pacing();
}
self.last_event_id = checkpoint.runtime.last_event_id;
Ok(imported)
}
/// Decodes FLYSIM01 bytes and installs them ([`LegacySession::import_checkpoint`]).
pub async fn import_flysim01(
&mut self,
bytes: &[u8],
epoch: &Id,
) -> Result<crate::import::Imported, String> {
let checkpoint = flysim::store::decode(bytes).map_err(|e| format!("FLYSIM01: {e:#}"))?;
self.import_checkpoint(&checkpoint, epoch).await
}
// -- the store (STATE-02) ------------------------------------------------------------------
/// Attaches the legacy store policy (`LegacyCheckpointer`): FLYSIM01 generations in the hot
/// and durable stores, milestone archives, the legacy intervals. Rollbacks are deferred from
/// here on, so a milestone capture lands between the boundary's slot save and its rollback.
pub fn attach_store(&mut self, store: &StoreConfig) -> Result<(), String> {
let checkpointer = LegacyCheckpointer::open(CheckpointerConfig {
hot_dir: store.hot_dir.clone(),
durable_dir: store.durable_dir.clone(),
keep_generations: store.keep_generations,
hot_seconds: store.hot_seconds,
checkpoint_seconds: store.checkpoint_seconds,
compatibility: self.compatibility(),
speed: store.speed,
slot_id: id(crate::task::SLOT),
})?;
self.checkpointer = Some(checkpointer);
self.coordinator.defer_rollbacks(true);
Ok(())
}
pub fn checkpointer(&self) -> Option<&LegacyCheckpointer> {
self.checkpointer.as_ref()
}
pub fn checkpointer_mut(&mut self) -> Option<&mut LegacyCheckpointer> {
self.checkpointer.as_mut()
}
/// The feed event log's watermark the next save records (`lastEventId`): the restored
/// file's until a host that keeps a feed event log sets its own.
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, written by the checkpointer's writer thread; waits for
/// the commit, so a caller that goes on to read the store finds it. For the startup and
/// shutdown saves, which the legacy loop takes blocking too.
pub async fn save(&mut self, kind: SaveKind) -> Result<SaveReport, String> {
let ticket = self.queue_save(kind).await?;
ticket
.reply
.await
.map_err(|_| "the checkpoint writer stopped".to_owned())?
}
/// One save of the committed boundary, queued: the participants capture now (the boundary's
/// state) and the encoding and fsync run on the checkpointer's writer thread while the loop
/// goes on, as the legacy loop hands its saves to its writer thread (TASK-01 review N4). The
/// outcome is collected by [`LegacySession::completed_saves`].
pub async fn queue_save(&mut self, kind: SaveKind) -> Result<SaveTicket, String> {
self.begin_save(kind).await?;
let mut tickets = self.finish_captures().await?;
let last = tickets
.pop()
.ok_or_else(|| "no save was begun".to_owned())?;
self.pending_saves.extend(tickets);
Ok(last)
}
/// Begins one save of the committed boundary: every participant's `State.Capture` is sent
/// (each takes its state now) and the task's half is taken now; the session may step on
/// while the agent encodes and seals its payload off its lock
/// (`Coordinator::begin_capture`, TASK-01 review N5). [`LegacySession::finish_captures`]
/// hands it to the writer.
pub async fn begin_save(&mut self, kind: SaveKind) -> Result<(), String> {
self.saves += 1;
let capture = self
.coordinator
.begin_capture(&parse_id(&format!("legacy-save-{}", self.saves))?)
.await
.map_err(|e| format!("capture ({}): {}", e.detail, e.error.message))?;
let (task, _slot_filled) = self.task.task_half();
self.pending_captures.push((capture, kind, task));
Ok(())
}
/// Collects every begun capture, in order, and queues it to the checkpointer's writer.
pub async fn finish_captures(&mut self) -> Result<Vec<SaveTicket>, String> {
let mut tickets = Vec::new();
for (capture, kind, task) in std::mem::take(&mut self.pending_captures) {
let (boundary, world, agents) = self
.coordinator
.finish_capture(capture)
.await
.map_err(|e| format!("capture ({}): {}", e.detail, e.error.message))?;
let [(_, agent)] = <[(Id, Vec<u8>); 1]>::try_from(agents)
.map_err(|_| "the legacy composition has exactly one agent".to_owned())?;
let capture = LegacyCapture {
boundary,
agent_payload: agent,
world_payload: world,
task,
};
let last_event_id = self.last_event_id;
let checkpointer = self.checkpointer.as_mut().ok_or("no store is attached")?;
tickets.push(checkpointer.save(kind, capture, last_event_id, now_wall_ms())?);
}
Ok(tickets)
}
/// The saves queued so far that have committed (or failed), without waiting; with `wait`,
/// every queued save's outcome. Every outcome is reported, a failed save as its own `Err`
/// beside the others (TASK-01 review R2-2): the caller decides.
pub async fn completed_saves(&mut self, wait: bool) -> Vec<Result<SaveReport, String>> {
let mut done = Vec::new();
let mut still = Vec::new();
for mut ticket in std::mem::take(&mut self.pending_saves) {
let stopped = || Err("the checkpoint writer stopped".to_owned());
if wait {
done.push((&mut ticket.reply).await.unwrap_or_else(|_| stopped()));
} else {
match ticket.reply.try_recv() {
Ok(result) => done.push(result),
Err(tokio::sync::oneshot::error::TryRecvError::Empty) => still.push(ticket),
Err(tokio::sync::oneshot::error::TryRecvError::Closed) => done.push(stopped()),
}
}
}
self.pending_saves = still;
done
}
/// Hands every begun capture to the writer now and reports what was queued. `advance` does
/// this after the next step so the agent's sealing overlaps it; a step that fails does it
/// before returning the error, and a caller that pauses (or is about to stop stepping) calls
/// this so a save begun at the last boundary reaches the writer as the legacy loop's
/// immediate hand-off would have (TASK-01 review R2-1).
pub async fn flush_captures(&mut self) -> Result<Vec<SaveQueued>, String> {
let mut saves = Vec::new();
for ticket in self.finish_captures().await? {
saves.push(SaveQueued {
generation: ticket.generation,
durable: ticket.durable,
archive_rank: ticket.archive_rank,
});
self.pending_saves.push(ticket);
}
Ok(saves)
}
/// One transition and what the legacy loop does at the boundary it reaches, in the declared
/// order (`legacy-gameboy-v1` sections 4 and 16): the slot save (inside the step), the
/// milestone archive when the rank climbed (`Sim::track_rank`), the rollback, a durable save
/// after it, then the interval saves (`checkpoint_if_due`).
pub async fn advance(&mut self) -> Result<(Step, Vec<SaveQueued>), String> {
let report = match self.coordinator.step().await {
Ok(report) => report,
Err(e) => {
// The legacy writer already has the saves of the earlier boundaries: hand the
// begun captures over before reporting the failure (TASK-01 review R2-1).
let flushed = self.flush_captures().await.err();
let mut message =
format!("step ({} at {}): {}", e.detail, e.phase, e.error.message);
if let Some(flush) = flushed {
message.push_str(&format!("; and the pending saves: {flush}"));
}
return Err(message);
}
};
// The captures begun at the last boundary: the agent sealed its payload while this
// transition's Prepare ticked.
let saves = self.flush_captures().await?;
if self.checkpointer.is_some() {
let rank = self.task.rank();
let ms = self.task.brain_ms();
let change = self
.checkpointer
.as_mut()
.expect("attached")
.observe_rank(rank, ms);
if let Some(RankChange::Climbed(rank)) = change {
self.begin_save(SaveKind::Milestone(rank)).await?;
}
}
let rolled_back = self
.coordinator
.apply_pending_rollback()
.await
.map_err(|e| {
format!(
"rollback ({} at {}): {}",
e.detail, e.phase, e.error.message
)
})?;
if self.checkpointer.is_some() {
if rolled_back {
self.begin_save(SaveKind::Durable).await?;
}
let due = self
.checkpointer
.as_mut()
.expect("attached")
.due(Instant::now());
if let Some(kind) = due {
self.begin_save(kind).await?;
}
}
Ok((
Step {
report,
details: self.coordinator.take_details(),
records: self.task.take_records(),
},
saves,
))
}
/// One transition, with its details when recorded ([`LegacySession::advance`] without the
/// saves it reports).
pub async fn step(&mut self) -> Result<Step, String> {
self.advance().await.map(|(step, _)| step)
}
/// A durable save, as the legacy loop takes on shutdown, then the store's writer is closed.
pub async fn shutdown_save(&mut self) -> Result<Option<SaveReport>, String> {
if self.checkpointer.is_none() {
return Ok(None);
}
self.flush_captures().await?;
let report = self.save(SaveKind::Durable).await?;
let outcomes = self.completed_saves(true).await;
if let Some(checkpointer) = self.checkpointer.as_mut() {
checkpointer.close();
}
// Every queued save has been waited for; the first failure is the shutdown's.
for outcome in outcomes {
outcome?;
}
Ok(Some(report))
}
pub async fn stop(mut self) {
self.launcher.reap_all(&id("done")).await;
}
}