From 32631e2d02413d1d186d0b14b08579f10d66a994 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 15:31:13 +0000 Subject: [PATCH 1/6] flysim-store: the FLYSIM01 store and the sugar journal in one crate; journal boot header, rotation and reset clearing store.rs and journal.rs move unchanged from flysim into the new flysim-store crate, which flysim re-exports, so the session runtime can write and read the same store (STATE-02). The journal gains a per-process boot header, rotation at 4 MiB with three kept files, and clear(), which flysim --reset-to-milestone now calls after copying the stores aside. --- services/flysim/Cargo.lock | 14 + services/flysim/Cargo.toml | 1 + .../flysim/crates/flysim-store/Cargo.toml | 27 + .../flysim/crates/flysim-store/src/journal.rs | 515 ++++++++++++++ .../flysim/crates/flysim-store/src/lib.rs | 12 + .../flysim/crates/flysim-store/src/store.rs | 645 ++++++++++++++++++ services/flysim/crates/flysim/Cargo.toml | 2 + services/flysim/crates/flysim/src/journal.rs | 176 +---- services/flysim/crates/flysim/src/reset.rs | 29 + services/flysim/crates/flysim/src/simloop.rs | 16 + services/flysim/crates/flysim/src/store.rs | 645 +----------------- 11 files changed, 1268 insertions(+), 814 deletions(-) create mode 100644 services/flysim/crates/flysim-store/Cargo.toml create mode 100644 services/flysim/crates/flysim-store/src/journal.rs create mode 100644 services/flysim/crates/flysim-store/src/lib.rs create mode 100644 services/flysim/crates/flysim-store/src/store.rs diff --git a/services/flysim/Cargo.lock b/services/flysim/Cargo.lock index d87a04a..d356eee 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -508,6 +508,7 @@ dependencies = [ "flybrain-core", "flybrain-gb", "flybus", + "flysim-store", "futures-util", "jsonschema", "serde", @@ -523,6 +524,19 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "flysim-store" +version = "0.1.1" +dependencies = [ + "anyhow", + "flybrain-core", + "flybrain-gb", + "serde", + "serde_json", + "tempfile", + "tracing", +] + [[package]] name = "foldhash" version = "0.2.0" diff --git a/services/flysim/Cargo.toml b/services/flysim/Cargo.toml index 2def2d3..2673363 100644 --- a/services/flysim/Cargo.toml +++ b/services/flysim/Cargo.toml @@ -8,6 +8,7 @@ members = [ "crates/flybrain-gb", "crates/flybus", "crates/flysim", + "crates/flysim-store", ] [workspace.package] diff --git a/services/flysim/crates/flysim-store/Cargo.toml b/services/flysim/crates/flysim-store/Cargo.toml new file mode 100644 index 0000000..aaef1aa --- /dev/null +++ b/services/flysim/crates/flysim-store/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "flysim-store" +version.workspace = true +edition = "2024" +rust-version.workspace = true +license.workspace = true +publish = false +description = "The FLYSIM01 checkpoint store (envelope, generations, milestone archives) and the sugar journal, shared by flysim and the session runtime." + +[lib] +name = "flysim_store" +path = "src/lib.rs" + +# STATE-02: `flysim` (the legacy loop) and `fly-session` (the session runtime) write and read +# the same store, so the code lives here once and both link it. No dependency on either of +# them, and nothing async: the writer threads belong to the callers. +[dependencies] +flybrain-core = { path = "../flybrain-core" } +flybrain-gb = { path = "../flybrain-gb" } + +anyhow = "1.0" +serde = { workspace = true } +serde_json = { workspace = true } +tracing = "0.1" + +[dev-dependencies] +tempfile = "3" diff --git a/services/flysim/crates/flysim-store/src/journal.rs b/services/flysim/crates/flysim-store/src/journal.rs new file mode 100644 index 0000000..f487b66 --- /dev/null +++ b/services/flysim/crates/flysim-store/src/journal.rs @@ -0,0 +1,515 @@ +//! The sugar journal: every admitted audience input, stamped with the frame it was applied before. +//! +//! `sugar-journal.jsonl` in `[paths] hot_dir`, one JSON object per line, append-only. It is not +//! part of a checkpoint and nothing reads it back into the fly: it is the record a shadow run +//! (the session framework's CUT-01, `docs/design/session-framework/legacy-gameboy-v1.md` section +//! 15) replays audience input from. The legacy loop applies an admitted sugar at once, in the +//! command drain at the top of a frame, so an input is fully placed by the transition it precedes: +//! +//! ```json +//! {"frame":"6465126","brainMs":108246189,"kind":"sugar","durationMs":400,"by":"viewer","source":"twitch","eventId":81234,"wallMs":1790000000000} +//! ``` +//! +//! - `frame` is the frame counter when the input was applied, which is the `step` of the next +//! transition in the frame trace (`crate::trace`): replay applies it before that transition's +//! ticks. A restore carries the frame counter, so stamps continue across restarts. +//! - `kind` is `sugar` (a `reward-pulse` stimulation of `durationMs`, after the admission rules +//! and the clamp) or `reward` (an operator's `POST /reward`, one reinforcement of `value`). +//! - `brainMs` cross-checks the stamp; `eventId` joins the event log; `wallMs` is for people. +//! +//! Refused requests are not journalled: admission is wall-clock policy, and a replay applies what +//! was admitted. A write that fails is a warning, never a refusal: the input has already reached +//! the fly. +//! +//! **Boot header, rotation and reset (STATE-02, before SHADOW-01).** Three things a replay needs +//! that the first version left open: +//! +//! - *Boot header.* Every process writes one header line when it starts, before any input: +//! +//! ```json +//! {"journal":"flysim-sugar-journal-v1","boot":{"runtime":"flysim","startFrame":"6465126","brainMs":108246189,"origin":"hot latest generation 230739","generation":230739,"compatibility":"…","wallMs":1790000000000}} +//! ``` +//! +//! A restore splits a run into processes, and a restored process starts from a checkpoint that +//! can be older than the last input the previous process journalled (a hot copy is up to five +//! seconds old, a milestone reset much more). The header is where a reader cuts the journal +//! into per-process segments ([`read_segments`]) and learns which checkpoint each one replays +//! from. It has no `frame` member, so [`read`], which keeps input lines only, skips it. +//! - *Rotation.* The journal lives on tmpfs. When the next line would take it past +//! [`MAX_BYTES`], the file becomes `sugar-journal-1.jsonl` (older ones shift up, the oldest +//! beyond [`KEEP_ROTATIONS`] is removed) and a fresh file starts with a `continues` line that +//! repeats the boot header, so every file can be read on its own. +//! - *Reset.* [`clear`] removes the journal and its rotations. `flysim --reset-to-milestone` +//! calls it (after copying the stores aside), because a reset rewinds the frame counter to the +//! rung's: inputs stamped with the abandoned run's frames would otherwise sit in front of the +//! new run's and read as if they were in its future. + +use std::fs::{File, OpenOptions}; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +/// The journal's file name inside the hot directory. +pub const FILE_NAME: &str = "sugar-journal.jsonl"; + +/// The format name in every header line. +pub const FORMAT: &str = "flysim-sugar-journal-v1"; + +/// The size a journal file may reach before it is rotated. Sugar is rate-limited per minute, so +/// this is days of input; the bound exists because the hot directory is tmpfs. +pub const MAX_BYTES: u64 = 4 << 20; + +/// Rotated files kept beside the live one: `sugar-journal-1.jsonl` (newest) and up. +pub const KEEP_ROTATIONS: usize = 3; + +/// What was applied. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Input { + Sugar { duration_ms: f64 }, + Reward { value: f64 }, +} + +/// One journal line. +#[derive(Debug, Clone, PartialEq)] +pub struct Entry<'a> { + pub frame: u64, + pub brain_ms: f64, + pub input: Input, + pub by: &'a str, + pub source: &'a str, + pub event_id: u64, + pub wall_ms: u64, +} + +impl Entry<'_> { + pub fn to_json(&self) -> Value { + let mut line = json!({ "frame": self.frame.to_string(), "brainMs": self.brain_ms }); + let map = line.as_object_mut().expect("an object"); + match self.input { + Input::Sugar { duration_ms } => { + map.insert("kind".into(), "sugar".into()); + map.insert("durationMs".into(), json!(duration_ms)); + } + Input::Reward { value } => { + map.insert("kind".into(), "reward".into()); + map.insert("value".into(), json!(value)); + } + } + map.insert("by".into(), self.by.into()); + map.insert("source".into(), self.source.into()); + map.insert("eventId".into(), self.event_id.into()); + map.insert("wallMs".into(), self.wall_ms.into()); + line + } +} + +/// The header a process writes when it starts: where its inputs begin. +#[derive(Debug, Clone, PartialEq)] +pub struct BootHeader { + /// `flysim` for the legacy loop, `fly-session` for the session runtime. + pub runtime: String, + /// The frame counter the process starts at: its first input can be stamped no earlier. + pub start_frame: u64, + pub brain_ms: f64, + /// `fresh start`, or the restore candidate's origin (`hot latest generation 7`, ...). + pub origin: String, + /// The generation restored from, if the candidate names one. + pub generation: Option, + pub compatibility: String, + pub wall_ms: u64, +} + +impl BootHeader { + pub fn to_json(&self) -> Value { + json!({ + "runtime": self.runtime, + "startFrame": self.start_frame.to_string(), + "brainMs": self.brain_ms, + "origin": self.origin, + "generation": self.generation, + "compatibility": self.compatibility, + "wallMs": self.wall_ms, + }) + } +} + +/// The append-only journal, rotated at [`MAX_BYTES`]. +pub struct SugarJournal { + dir: PathBuf, + path: PathBuf, + file: Option, + /// Bytes in the live file, as far as this process knows. + bytes: u64, + max_bytes: u64, + keep: usize, + /// The boot header this process wrote, repeated at the top of every rotated-in file. + boot: Option, +} + +impl SugarJournal { + pub fn new(hot_dir: &Path) -> Self { + Self::with_limits(hot_dir, MAX_BYTES, KEEP_ROTATIONS) + } + + pub fn with_limits(hot_dir: &Path, max_bytes: u64, keep: usize) -> Self { + Self { + dir: hot_dir.to_path_buf(), + path: hot_dir.join(FILE_NAME), + file: None, + bytes: 0, + max_bytes: max_bytes.max(1), + keep, + boot: None, + } + } + + pub fn path(&self) -> &Path { + &self.path + } + + /// Write this process's boot header. Called once, when the process knows where it starts + /// (after its restore or its warm-up) and before it admits anything. + pub fn boot(&mut self, header: &BootHeader) { + let boot = header.to_json(); + self.append(&json!({ "journal": FORMAT, "boot": boot.clone() })); + // Set after the line is written: a rotation that line itself triggers must not open + // the new file with a `continues` naming a boot that is not in the journal yet. + self.boot = Some(boot); + } + + /// Append one input line. + pub fn record(&mut self, entry: &Entry<'_>) { + self.append(&entry.to_json()); + } + + /// One line, one `write` of the whole line, so a crash leaves at most a torn last line, + /// which a reader skips and the next open terminates. + fn append(&mut self, value: &Value) { + let mut line = value.to_string(); + line.push('\n'); + if self.file.is_none() && !self.open() { + return; + } + if self.bytes > 0 && self.bytes + line.len() as u64 > self.max_bytes { + self.rotate(); + if !self.open() { + return; + } + } + if let Some(file) = self.file.as_mut() { + match file.write_all(line.as_bytes()) { + Ok(()) => self.bytes += line.len() as u64, + Err(error) => { + tracing::warn!(%error, path = %self.path.display(), "could not append to the sugar journal"); + // Reopen on the next input rather than write through a broken handle. + self.file = None; + } + } + } + } + + /// Open the live file for appending. One whose last line is torn gets its newline, so the + /// next line is whole; one already at the limit is rotated by the caller's next append. + fn open(&mut self) -> bool { + let file = OpenOptions::new().create(true).read(true).append(true).open(&self.path); + let mut file = match file { + Ok(file) => file, + Err(error) => { + tracing::warn!(%error, path = %self.path.display(), "could not open the sugar journal"); + return false; + } + }; + let mut length = file.metadata().map(|m| m.len()).unwrap_or(0); + if length > 0 && !ends_with_newline(&mut file, length) && file.write_all(b"\n").is_ok() { + length += 1; + } + self.bytes = length; + let fresh = length == 0; + self.file = Some(file); + if fresh && let Some(boot) = self.boot.clone() { + // A file this process starts after a rotation says whose inputs follow. + self.append(&json!({ "journal": FORMAT, "continues": boot })); + } + true + } + + fn rotate(&mut self) { + self.file = None; + self.shift_rotations(); + } + + /// `sugar-journal.jsonl` -> `-1`, `-1` -> `-2`, ..., dropping what falls past `keep`. + fn shift_rotations(&mut self) { + if self.keep == 0 { + let _ = std::fs::remove_file(&self.path); + return; + } + let _ = std::fs::remove_file(rotation_path(&self.dir, self.keep)); + for index in (1..self.keep).rev() { + let from = rotation_path(&self.dir, index); + if from.exists() { + let _ = std::fs::rename(&from, rotation_path(&self.dir, index + 1)); + } + } + if let Err(error) = std::fs::rename(&self.path, rotation_path(&self.dir, 1)) { + tracing::warn!(%error, path = %self.path.display(), "could not rotate the sugar journal"); + } + } +} + +fn ends_with_newline(file: &mut File, length: u64) -> bool { + let mut last = [0u8; 1]; + file.seek(SeekFrom::Start(length - 1)) + .and_then(|_| file.read_exact(&mut last)) + .map(|()| last[0] == b'\n') + .unwrap_or(true) +} + +/// `sugar-journal-.jsonl`: index 1 is the newest rotation. +pub fn rotation_path(hot_dir: &Path, index: usize) -> PathBuf { + hot_dir.join(format!("sugar-journal-{index}.jsonl")) +} + +/// Is `name` the journal or one of its rotations? +pub fn is_journal_file(name: &str) -> bool { + name == FILE_NAME + || name + .strip_prefix("sugar-journal-") + .and_then(|rest| rest.strip_suffix(".jsonl")) + .is_some_and(|index| !index.is_empty() && index.bytes().all(|b| b.is_ascii_digit())) +} + +/// Remove the journal and every rotation from `hot_dir`: a reset starts a new record. Returns +/// how many files went. A missing directory is zero files. +pub fn clear(hot_dir: &Path) -> std::io::Result { + if !hot_dir.is_dir() { + return Ok(0); + } + let mut removed = 0; + for entry in std::fs::read_dir(hot_dir)?.flatten() { + if is_journal_file(&entry.file_name().to_string_lossy()) { + std::fs::remove_file(entry.path())?; + removed += 1; + } + } + Ok(removed) +} + +/// Read a journal back: every whole input line, in order. A torn or unreadable line is skipped, +/// and so is every header. +pub fn read(path: &Path) -> std::io::Result> { + let text = std::fs::read_to_string(path)?; + Ok(text + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .filter(|value| value.get("frame").is_some()) + .collect()) +} + +/// One process's inputs: its boot header (absent for lines written before headers existed) and +/// the inputs it admitted, in order. +#[derive(Debug, Clone, PartialEq)] +pub struct Segment { + pub boot: Option, + pub inputs: Vec, +} + +/// The whole journal of `hot_dir`, oldest rotation first, cut into per-process segments at each +/// boot header. A `continues` line keeps the segment it names open across a rotation. +pub fn read_segments(hot_dir: &Path) -> std::io::Result> { + let mut files: Vec<(usize, PathBuf)> = Vec::new(); + if hot_dir.is_dir() { + for entry in std::fs::read_dir(hot_dir)?.flatten() { + let name = entry.file_name().to_string_lossy().to_string(); + if let Some(index) = name + .strip_prefix("sugar-journal-") + .and_then(|rest| rest.strip_suffix(".jsonl")) + .and_then(|index| index.parse::().ok()) + { + files.push((index, entry.path())); + } + } + } + files.sort_by(|a, b| b.0.cmp(&a.0)); + let live = hot_dir.join(FILE_NAME); + if live.exists() { + files.push((0, live)); + } + let mut segments: Vec = Vec::new(); + for (_, path) in files { + let text = std::fs::read_to_string(&path)?; + for value in text.lines().filter_map(|line| serde_json::from_str::(line).ok()) { + if let Some(boot) = value.get("boot") { + segments.push(Segment { boot: Some(boot.clone()), inputs: Vec::new() }); + } else if let Some(boot) = value.get("continues") { + let open = segments.last().is_some_and(|s| s.boot.as_ref() == Some(boot)); + if !open { + segments.push(Segment { boot: Some(boot.clone()), inputs: Vec::new() }); + } + } else if value.get("frame").is_some() { + if segments.is_empty() { + segments.push(Segment { boot: None, inputs: Vec::new() }); + } + segments.last_mut().expect("a segment").inputs.push(value); + } + } + } + Ok(segments) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn inputs_are_appended_with_their_frame_and_survive_a_reopen() { + let dir = tempfile::tempdir().expect("a temp dir"); + let mut journal = SugarJournal::new(dir.path()); + assert!( + !journal.path().exists(), + "nothing is written before an input" + ); + let sugar = Entry { + frame: 42, + brain_ms: 703.0, + input: Input::Sugar { duration_ms: 400.0 }, + by: "viewer", + source: "test", + event_id: 7, + wall_ms: 1, + }; + journal.record(&sugar); + drop(journal); + let mut journal = SugarJournal::new(dir.path()); + journal.record(&Entry { + frame: 43, + input: Input::Reward { value: 0.5 }, + event_id: 8, + ..sugar + }); + // A torn tail from a crash is skipped, not fatal. + std::fs::OpenOptions::new() + .append(true) + .open(journal.path()) + .and_then(|mut file| file.write_all(b"{\"frame\":\"44\",\"kin")) + .expect("appending a torn line"); + let lines = read(journal.path()).expect("the journal reads back"); + assert_eq!(lines.len(), 2); + assert_eq!(lines[0]["frame"], "42"); + assert_eq!(lines[0]["kind"], "sugar"); + assert_eq!(lines[0]["durationMs"], 400.0); + assert_eq!(lines[1]["frame"], "43"); + assert_eq!(lines[1]["kind"], "reward"); + assert_eq!(lines[1]["value"], 0.5); + assert_eq!(lines[1]["eventId"], 8); + } + + fn header(frame: u64, origin: &str) -> BootHeader { + BootHeader { + runtime: "flysim".to_string(), + start_frame: frame, + brain_ms: frame as f64 * 16.74, + origin: origin.to_string(), + generation: Some(frame), + compatibility: "kernel/adapter/fingerprint".to_string(), + wall_ms: 1, + } + } + + fn sugar(frame: u64, event_id: u64) -> Entry<'static> { + Entry { + frame, + brain_ms: frame as f64, + input: Input::Sugar { duration_ms: 300.0 }, + by: "viewer", + source: "test", + event_id, + wall_ms: 1, + } + } + + #[test] + fn each_process_writes_a_boot_header_that_cuts_the_journal_into_segments() { + let dir = tempfile::tempdir().unwrap(); + let mut journal = SugarJournal::new(dir.path()); + journal.boot(&header(100, "fresh start")); + journal.record(&sugar(120, 1)); + journal.record(&sugar(130, 2)); + drop(journal); + // A crash tore the last line; the next process terminates it before its header. + std::fs::OpenOptions::new() + .append(true) + .open(dir.path().join(FILE_NAME)) + .and_then(|mut file| file.write_all(b"{\"frame\":\"13")) + .unwrap(); + // The restart restored an older hot copy: its inputs start below the torn one's frame. + let mut journal = SugarJournal::new(dir.path()); + journal.boot(&header(125, "hot latest generation 125")); + journal.record(&sugar(126, 3)); + let segments = read_segments(dir.path()).unwrap(); + assert_eq!(segments.len(), 2); + assert_eq!(segments[0].boot.as_ref().unwrap()["origin"], "fresh start"); + assert_eq!(segments[0].inputs.len(), 2); + assert_eq!(segments[1].boot.as_ref().unwrap()["startFrame"], "125"); + assert_eq!(segments[1].boot.as_ref().unwrap()["generation"], 125); + assert_eq!(segments[1].inputs.len(), 1); + assert_eq!(segments[1].inputs[0]["frame"], "126"); + // The input-only reader skips headers and the torn line, as before. + let inputs = read(journal.path()).unwrap(); + assert_eq!(inputs.len(), 3); + } + + #[test] + fn the_journal_rotates_at_its_limit_and_keeps_a_bounded_number_of_files() { + let dir = tempfile::tempdir().unwrap(); + let mut journal = SugarJournal::with_limits(dir.path(), 600, 2); + journal.boot(&header(1, "fresh start")); + for event in 0..40 { + journal.record(&sugar(10 + event, event)); + } + for path in [dir.path().join(FILE_NAME), rotation_path(dir.path(), 1), rotation_path(dir.path(), 2)] { + let length = std::fs::metadata(&path).unwrap().len(); + assert!(length <= 600, "{} is {length} bytes", path.display()); + } + assert!(!rotation_path(dir.path(), 3).exists(), "only two rotations are kept"); + // Every file says whose inputs it holds, and the segments join across the rotations. + let live = std::fs::read_to_string(dir.path().join(FILE_NAME)).unwrap(); + let first: Value = serde_json::from_str(live.lines().next().unwrap()).unwrap(); + assert_eq!(first["journal"], FORMAT); + assert_eq!(first["continues"]["origin"], "fresh start", "{live}"); + let segments = read_segments(dir.path()).unwrap(); + assert_eq!(segments.len(), 1, "one process, one segment: {segments:?}"); + let frames: Vec = segments[0] + .inputs + .iter() + .map(|v| v["frame"].as_str().unwrap().parse().unwrap()) + .collect(); + assert!(frames.windows(2).all(|w| w[1] == w[0] + 1), "in order, no gap inside the kept files"); + assert_eq!(*frames.last().unwrap(), 49); + } + + #[test] + fn clear_removes_the_journal_and_its_rotations_and_nothing_else() { + let dir = tempfile::tempdir().unwrap(); + let mut journal = SugarJournal::with_limits(dir.path(), 300, 3); + journal.boot(&header(1, "fresh start")); + for event in 0..10 { + journal.record(&sugar(10 + event, event)); + } + std::fs::write(dir.path().join("manifest.json"), "{}").unwrap(); + std::fs::write(dir.path().join("sugar-journal-x.jsonl"), "").unwrap(); + let removed = clear(dir.path()).unwrap(); + assert!(removed >= 2, "{removed}"); + let left: Vec = std::fs::read_dir(dir.path()) + .unwrap() + .flatten() + .map(|e| e.file_name().to_string_lossy().to_string()) + .collect(); + let mut left = left; + left.sort(); + assert_eq!(left, vec!["manifest.json", "sugar-journal-x.jsonl"]); + assert_eq!(clear(&dir.path().join("missing")).unwrap(), 0); + assert!(read_segments(dir.path()).unwrap().is_empty()); + } +} diff --git a/services/flysim/crates/flysim-store/src/lib.rs b/services/flysim/crates/flysim-store/src/lib.rs new file mode 100644 index 0000000..0d18ad8 --- /dev/null +++ b/services/flysim/crates/flysim-store/src/lib.rs @@ -0,0 +1,12 @@ +//! The `FLYSIM01` checkpoint store and the sugar journal. +//! +//! `FLYSIM01` is the checkpoint format of record for the legacy Game Boy composition until +//! RETIRE-01 (`docs/design/session-framework/legacy-gameboy-v1.md` section 16). Two runtimes write +//! and read it: the legacy loop (`flysim`) and the session runtime (`fly-session`, STATE-02). This +//! crate is the one copy of the code both use, moved here unchanged from `flysim::store` and +//! `flysim::journal`, which re-export it, so a store written by either is the other's store: the +//! same envelope bytes, the same generations and `manifest.json`, the same milestone archives and +//! rotation, and the same restore order. + +pub mod journal; +pub mod store; diff --git a/services/flysim/crates/flysim-store/src/store.rs b/services/flysim/crates/flysim-store/src/store.rs new file mode 100644 index 0000000..586e6c0 --- /dev/null +++ b/services/flysim/crates/flysim-store/src/store.rs @@ -0,0 +1,645 @@ +//! Checkpoint persistence: the `FLYSIM01` envelope, the atomic commit, the generations and the +//! milestone archives. +//! +//! `docs/design/flysim.md` section 8, as amended by the contract override at the top of that +//! document: +//! +//! - the envelope is `flybrain-core`'s frozen `encodeEnvelope` layout with the magic `FLYSIM01`, +//! carrying the seven agent chunks plus `emulator`, `framebuffer`, `ratchetGame` and +//! `ratchetFrame`; +//! - a commit writes `.checkpoint.tmp`, fsyncs it, renames it, fsyncs the directory, and +//! then does the same for `manifest.json`. **The manifest rename is the commit point**: a +//! crash before it leaves an unreferenced file that is never loaded; +//! - durable commits go to `save_dir` every `checkpoint_seconds` (default 300) and on every +//! event that matters; a hot copy goes to `hot_dir` (tmpfs) every `hot_seconds` (default 5); +//! - the first commit at a new best rank also writes `milestone-.checkpoint`, which later +//! rotations never unlink. + +use std::collections::BTreeMap; +use std::fs::{File, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use flybrain_core::envelope::{EnvelopeParts, decode_envelope, encode_envelope}; +use flybrain_core::json::JsonValue; +use serde::{Deserialize, Serialize}; + +/// Envelope magic. Chunk names stay `[a-zA-Z]+` so the TypeScript `decodeEnvelope` can read a +/// flysim checkpoint for recap and inspection tooling. +pub const MAGIC: &str = "FLYSIM01"; + +/// Chunk names flysim adds to `flybrain-core`'s `AGENT_CHUNK_NAMES`. +pub const EMULATOR_CHUNK: &str = "emulator"; +pub const FRAMEBUFFER_CHUNK: &str = "framebuffer"; +pub const RATCHET_GAME_CHUNK: &str = "ratchetGame"; +pub const RATCHET_FRAME_CHUNK: &str = "ratchetFrame"; + +/// `manifest.json`: which generations are current, and which are archived forever. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct StoreManifest { + /// Highest generation ever allocated in this store. + pub generation: u64, + /// The generation to restore first. + pub latest: Option, + /// The generation to restore if `latest` will not load. + pub previous: Option, + /// Best-rank archives, rank to generation. Their files are never rotated away. + pub archives: BTreeMap, +} + +impl StoreManifest { + fn record(&mut self, generation: u64, archive_rank: Option) { + self.generation = self.generation.max(generation); + if self.latest != Some(generation) { + self.previous = self.latest; + self.latest = Some(generation); + } + if let Some(rank) = archive_rank { + self.archives.insert(rank, generation); + } + } + + /// Generations that must survive rotation. + fn referenced(&self) -> Vec { + let mut out: Vec = self.latest.into_iter().chain(self.previous).collect(); + out.extend(self.archives.values().copied()); + out + } +} + +/// One restore candidate, in the order it should be tried. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Candidate { + pub path: PathBuf, + /// Human description for the log and for `/status`'s fallback reporting. + pub origin: String, + pub generation: Option, +} + +/// A checkpoint directory: `.checkpoint`, `milestone-.checkpoint`, `manifest.json`. +#[derive(Debug, Clone)] +pub struct Store { + dir: PathBuf, + keep_generations: usize, +} + +impl Store { + pub fn new(dir: impl Into, keep_generations: usize) -> Self { + Self { dir: dir.into(), keep_generations: keep_generations.max(1) } + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + pub fn create(&self) -> Result<()> { + std::fs::create_dir_all(&self.dir) + .with_context(|| format!("creating checkpoint directory {}", self.dir.display())) + } + + pub fn manifest_path(&self) -> PathBuf { + self.dir.join("manifest.json") + } + + pub fn generation_path(&self, generation: u64) -> PathBuf { + self.dir.join(format!("{generation}.checkpoint")) + } + + pub fn archive_path(&self, rank: u32) -> PathBuf { + self.dir.join(format!("milestone-{rank}.checkpoint")) + } + + /// Read `manifest.json`, or `None` when it is absent or unreadable. + pub fn manifest(&self) -> Option { + let text = std::fs::read_to_string(self.manifest_path()).ok()?; + match serde_json::from_str(&text) { + Ok(manifest) => Some(manifest), + Err(error) => { + tracing::warn!(%error, path = %self.manifest_path().display(), "unreadable store manifest"); + None + } + } + } + + /// Highest generation the store has ever allocated, from the manifest and from the files on + /// disk (an unreferenced file from a crashed commit still counts, so a generation number is + /// never reused). + pub fn highest_generation(&self) -> u64 { + let mut highest = self.manifest().map_or(0, |manifest| manifest.generation); + if let Ok(entries) = std::fs::read_dir(&self.dir) { + for entry in entries.flatten() { + if let Some(generation) = parse_generation(&entry.file_name().to_string_lossy()) { + highest = highest.max(generation); + } + } + } + highest + } + + /// Restore candidates from this store, in order: latest, previous, then the archives by + /// descending rank. + pub fn candidates(&self, label: &str) -> Vec { + let Some(manifest) = self.manifest() else { + return Vec::new(); + }; + let mut out = Vec::new(); + for (kind, generation) in [("latest", manifest.latest), ("previous", manifest.previous)] { + if let Some(generation) = generation { + out.push(Candidate { + path: self.generation_path(generation), + origin: format!("{label} {kind} generation {generation}"), + generation: Some(generation), + }); + } + } + for (rank, generation) in manifest.archives.iter().rev() { + out.push(Candidate { + path: self.generation_path(*generation), + origin: format!("{label} archived generation {generation} (rank {rank})"), + generation: Some(*generation), + }); + out.push(Candidate { + path: self.archive_path(*rank), + origin: format!("{label} milestone archive rank {rank}"), + generation: Some(*generation), + }); + } + out.retain(|candidate| candidate.path.exists()); + out + } + + /// Write `bytes` as `generation`, commit it, archive it if `archive_rank` is set, then rotate. + /// + /// The sequence is exactly section 8's: payload tmp, fsync, rename, dir fsync, then manifest + /// tmp, fsync, rename, dir fsync. + pub fn commit( + &self, + generation: u64, + bytes: &[u8], + archive_rank: Option, + ) -> Result { + self.create()?; + write_atomic(&self.generation_path(generation), bytes)?; + if let Some(rank) = archive_rank { + write_atomic(&self.archive_path(rank), bytes)?; + } + let mut manifest = self.manifest().unwrap_or_default(); + manifest.record(generation, archive_rank); + let text = serde_json::to_vec_pretty(&manifest)?; + write_atomic(&self.manifest_path(), &text)?; + self.rotate(&manifest)?; + Ok(manifest) + } + + /// Stage a payload without committing it. Only the crash-simulation test uses this: it is + /// the state a `kill -9` between the tmp write and the rename leaves behind. + pub fn stage_for_test(&self, generation: u64, bytes: &[u8]) -> Result { + self.create()?; + let path = tmp_path(&self.generation_path(generation)); + write_and_sync(&path, bytes)?; + Ok(path) + } + + /// Remove generation files that the manifest no longer references, keeping the newest + /// `keep_generations` and never touching an archive. + fn rotate(&self, manifest: &StoreManifest) -> Result<()> { + let referenced = manifest.referenced(); + let mut generations: Vec = Vec::new(); + for entry in std::fs::read_dir(&self.dir)?.flatten() { + let name = entry.file_name().to_string_lossy().to_string(); + if let Some(generation) = parse_generation(&name) { + generations.push(generation); + } else if name.ends_with(".checkpoint.tmp") { + // A tmp file from an interrupted commit is never loadable; clean it up. + let _ = std::fs::remove_file(entry.path()); + } + } + generations.sort_unstable_by(|a, b| b.cmp(a)); + for (index, generation) in generations.iter().enumerate() { + if referenced.contains(generation) || index < self.keep_generations { + continue; + } + let path = self.generation_path(*generation); + if let Err(error) = std::fs::remove_file(&path) { + tracing::warn!(%error, path = %path.display(), "could not rotate a checkpoint"); + } + } + Ok(()) + } +} + +/// `milestone-.checkpoint` is an independent file, so it is not a generation. +fn parse_generation(name: &str) -> Option { + name.strip_suffix(".checkpoint")?.parse().ok() +} + +fn tmp_path(path: &Path) -> PathBuf { + let mut name = path.as_os_str().to_os_string(); + name.push(".tmp"); + PathBuf::from(name) +} + +/// tmp write, fsync, rename, directory fsync. +pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> { + let tmp = tmp_path(path); + write_and_sync(&tmp, bytes)?; + std::fs::rename(&tmp, path) + .with_context(|| format!("renaming {} to {}", tmp.display(), path.display()))?; + sync_dir(path.parent().unwrap_or(Path::new("."))) +} + +fn write_and_sync(path: &Path, bytes: &[u8]) -> Result<()> { + let mut file = OpenOptions::new() + .create(true) + .write(true) + .truncate(true) + .open(path) + .with_context(|| format!("creating {}", path.display()))?; + file.write_all(bytes)?; + file.flush()?; + file.sync_all().with_context(|| format!("fsync {}", path.display()))?; + Ok(()) +} + +fn sync_dir(dir: &Path) -> Result<()> { + // Opening a directory read-only and fsyncing it is what makes the rename durable. + File::open(dir) + .and_then(|file| file.sync_all()) + .with_context(|| format!("fsync directory {}", dir.display())) +} + +// --------------------------------------------------------------------------------------------- +// The envelope +// --------------------------------------------------------------------------------------------- + +/// Everything a checkpoint carries besides the agent's own chunks. +#[derive(Debug, Clone, PartialEq)] +pub struct RuntimeState { + pub generation: u64, + pub wall_ms: u64, + pub rom_sha256: String, + pub emulator_frame: u64, + pub compatibility: String, + pub speed: f64, + pub buttons: u32, + /// Simulated milliseconds at which the current milestone rank was reached. + pub rank_since_ms: f64, + pub last_event_id: u64, + /// The adapter's own lifetime reward state. + pub reward: serde_json::Value, + pub ratchet: flybrain_gb::RatchetState, + pub emulator: Vec, + pub framebuffer: Vec, + /// The ratchet's best safe snapshot, if it has one. + pub ratchet_game: Vec, + pub ratchet_frame: Vec, +} + +/// A decoded checkpoint: the agent half plus the runtime half. +#[derive(Debug, Clone)] +pub struct Checkpoint { + pub agent: flybrain_core::agent::AgentState, + pub runtime: RuntimeState, +} + +/// Encode an agent state plus the runtime state into one `FLYSIM01` envelope. +pub fn encode( + agent: &flybrain_core::agent::AgentState, + runtime: &RuntimeState, +) -> Result> { + let parts = flybrain_core::envelope::agent_to_chunks(agent); + let mut manifest = parts.manifest; + manifest.set("generation", (runtime.generation as f64).into()); + manifest.set("wallMs", (runtime.wall_ms as f64).into()); + manifest.set("romHash", runtime.rom_sha256.as_str().into()); + manifest.set("emulatorFrame", (runtime.emulator_frame as f64).into()); + manifest.set("compatibility", runtime.compatibility.as_str().into()); + manifest.set("speed", runtime.speed.into()); + manifest.set("buttons", f64::from(runtime.buttons).into()); + manifest.set("rankSinceMs", runtime.rank_since_ms.into()); + manifest.set("lastEventId", (runtime.last_event_id as f64).into()); + manifest.set("reward", to_json_value(&runtime.reward)?); + manifest.set("ratchet", to_json_value(&serde_json::to_value(runtime.ratchet)?)?); + + let mut chunks = parts.chunks; + chunks.push((EMULATOR_CHUNK.to_string(), runtime.emulator.clone())); + chunks.push((FRAMEBUFFER_CHUNK.to_string(), runtime.framebuffer.clone())); + chunks.push((RATCHET_GAME_CHUNK.to_string(), runtime.ratchet_game.clone())); + chunks.push((RATCHET_FRAME_CHUNK.to_string(), runtime.ratchet_frame.clone())); + + encode_envelope(MAGIC, &manifest, &chunks).map_err(|error| anyhow::anyhow!("{error}")) +} + +/// Decode and structurally validate a `FLYSIM01` envelope. +/// +/// Value-level validation belongs to the importers: `NeuralAgent::import_state` is +/// self-validating and a no-op on failure, and `Ratchet::import` rejects an impossible state. +pub fn decode(bytes: &[u8]) -> Result { + let parts: EnvelopeParts = + decode_envelope(bytes, MAGIC).map_err(|error| anyhow::anyhow!("{error}"))?; + let manifest = parts.manifest.clone(); + let agent = flybrain_core::envelope::agent_from_chunks(&manifest, &parts) + .map_err(|error| anyhow::anyhow!("{error}"))?; + + let string = |key: &str| -> Result { + manifest + .get(key) + .and_then(JsonValue::as_str) + .map(str::to_string) + .ok_or_else(|| anyhow::anyhow!("checkpoint manifest is missing {key}")) + }; + let number = |key: &str| -> Result { + manifest + .get(key) + .and_then(JsonValue::as_f64) + .ok_or_else(|| anyhow::anyhow!("checkpoint manifest is missing {key}")) + }; + let chunk = |name: &str| -> Result> { + parts + .chunk(name) + .map(<[u8]>::to_vec) + .ok_or_else(|| anyhow::anyhow!("checkpoint is missing the {name} chunk")) + }; + + let ratchet_json = manifest + .get("ratchet") + .ok_or_else(|| anyhow::anyhow!("checkpoint manifest is missing ratchet"))?; + let ratchet: flybrain_gb::RatchetState = serde_json::from_str(&ratchet_json.stringify()) + .context("checkpoint ratchet state is not readable")?; + let reward = manifest + .get("reward") + .map(|value| serde_json::from_str(&value.stringify())) + .transpose() + .context("checkpoint reward state is not readable")? + .unwrap_or(serde_json::Value::Null); + + Ok(Checkpoint { + agent, + runtime: RuntimeState { + generation: number("generation")? as u64, + wall_ms: number("wallMs")? as u64, + rom_sha256: string("romHash")?, + emulator_frame: number("emulatorFrame")? as u64, + compatibility: string("compatibility")?, + speed: number("speed")?, + buttons: number("buttons")? as u32, + rank_since_ms: number("rankSinceMs").unwrap_or(0.0), + last_event_id: number("lastEventId").unwrap_or(0.0) as u64, + reward, + ratchet, + emulator: chunk(EMULATOR_CHUNK)?, + framebuffer: chunk(FRAMEBUFFER_CHUNK)?, + ratchet_game: chunk(RATCHET_GAME_CHUNK)?, + ratchet_frame: chunk(RATCHET_FRAME_CHUNK)?, + }, + }) +} + +/// Read and decode a candidate, so a caller can try the next one on any failure. +pub fn load(path: &Path) -> Result { + let bytes = + std::fs::read(path).with_context(|| format!("reading checkpoint {}", path.display()))?; + decode(&bytes).with_context(|| format!("decoding checkpoint {}", path.display())) +} + +fn to_json_value(value: &serde_json::Value) -> Result { + JsonValue::parse(&serde_json::to_string(value)?).map_err(|error| anyhow::anyhow!("{error}")) +} + +/// The restore order: the tmpfs hot copy first, then the durable store. +/// +/// The hot copy is written every few seconds and the durable one every few minutes, so the hot +/// copy is normally the newest state that exists; it is a first-class candidate because it uses +/// the identical envelope and the identical atomic sequence, and not a partial dump. +/// The compatibility string the newest decodable checkpoint in `dir` carries, if any. +/// +/// The store's own `manifest.json` is only an index (generation, latest, previous, archives) — +/// the compatibility string lives in each checkpoint's own `FLYSIM01` envelope manifest, so +/// answering "what will this build refuse?" means decoding a checkpoint. Candidates are tried +/// newest first and a corrupt one is skipped, which is the same order and the same tolerance +/// `Sim::boot` restores with. +/// +/// `flysim --print-state-compatibility DIR` is this, and `infra/05-deploy.sh` compares its +/// answer with `--print-compatibility` before flipping the `current` symlink. +pub fn state_compatibility(dir: &Path) -> Option { + let store = Store::new(dir, 8); + for candidate in store.candidates("durable") { + if let Ok(checkpoint) = load(&candidate.path) { + return Some(checkpoint.runtime.compatibility); + } + } + None +} + +pub fn restore_order(hot: &Store, durable: &Store) -> Vec { + let mut out = hot.candidates("hot"); + out.extend(durable.candidates("durable")); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn runtime(generation: u64) -> RuntimeState { + RuntimeState { + generation, + wall_ms: 1_700_000_000_000, + rom_sha256: "ab".repeat(32), + emulator_frame: 12_345, + compatibility: "kernel/adapter/fingerprint".to_string(), + speed: 1.0, + buttons: 0b0001_0000, + rank_since_ms: 4_242.0, + last_event_id: 77, + reward: serde_json::json!({ "version": 3, "total": 1.25 }), + ratchet: flybrain_gb::RatchetState { best: 3, ..Default::default() }, + emulator: vec![7; 64], + framebuffer: vec![9; 32], + ratchet_game: vec![1, 2, 3], + ratchet_frame: vec![4, 5, 6], + } + } + + fn agent_state() -> flybrain_core::agent::AgentState { + use flybrain_core::decoder::DecoderState; + use flybrain_core::lif::LifState; + use flybrain_core::ordered::NumberMap; + use flybrain_core::plasticity::PlasticityState; + flybrain_core::agent::AgentState { + version: 1, + remainder: 0.75, + warmed_up: true, + network: LifState { + membrane: vec![0.5, -0.25], + refractory: vec![0, 3], + last_spike_ms: vec![-1_000_000.0, 12.0], + visual_drive: vec![0.1], + rng: -12_345, + reward_remaining: 40.0, + ms: 9_000.0, + population_rate: 1.5, + rates: NumberMap::from_pairs([("forward", 2.0), ("reward_pam", 0.5)]), + plasticity: PlasticityState { + version: "fly-kc-mbon-rstdp-v2".to_string(), + topology: 42, + enabled: true, + updates: 3.0, + signal: 0.25, + gains: vec![1.0, 0.9], + traces: vec![0.0, 0.1], + touched: vec![0.0, 8_000.0], + }, + }, + decoder: DecoderState { + version: 4, + calibrated: true, + baseline: NumberMap::from_pairs([("forward", 1.0)]), + held_until: NumberMap::new(), + next_allowed: NumberMap::new(), + next_decision: 100.0, + current: Some("a".to_string()), + fatigue: NumberMap::new(), + macro_next_decision: 0.0, + macro_current: None, + macro_fatigue: NumberMap::new(), + }, + } + } + + #[test] + fn the_envelope_round_trips_every_field_and_chunk() { + let agent = agent_state(); + let runtime = runtime(4); + let bytes = encode(&agent, &runtime).unwrap(); + assert!(bytes.starts_with(MAGIC.as_bytes())); + + let back = decode(&bytes).unwrap(); + assert_eq!(back.agent, agent); + assert_eq!(back.runtime, runtime); + + // Re-encoding the decoded state is byte-identical, so a restore-and-save cycle is stable. + assert_eq!(encode(&back.agent, &back.runtime).unwrap(), bytes); + } + + #[test] + fn a_corrupted_or_truncated_envelope_is_rejected() { + let bytes = encode(&agent_state(), &runtime(1)).unwrap(); + assert!(decode(&bytes[..bytes.len() - 1]).is_err(), "truncated"); + + let mut flipped = bytes.clone(); + let middle = flipped.len() / 2; + flipped[middle] ^= 0xff; + assert!(decode(&flipped).is_err(), "checksum"); + + let mut trailing = bytes.clone(); + trailing.push(0); + assert!(decode(&trailing).is_err(), "trailing bytes"); + + let mut wrong_magic = bytes; + wrong_magic[0] = b'X'; + assert!(decode(&wrong_magic).is_err(), "magic"); + } + + #[test] + fn a_commit_is_atomic_and_a_crash_before_the_rename_leaves_a_loadable_store() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::new(dir.path(), 2); + let first = encode(&agent_state(), &runtime(1)).unwrap(); + store.commit(1, &first, None).unwrap(); + + // kill -9 between the tmp write and the rename. + let mut broken = encode(&agent_state(), &runtime(2)).unwrap(); + broken.truncate(broken.len() / 2); + let staged = store.stage_for_test(2, &broken).unwrap(); + assert!(staged.exists()); + + let manifest = store.manifest().unwrap(); + assert_eq!(manifest.latest, Some(1)); + let candidates = store.candidates("durable"); + assert_eq!(candidates.len(), 1, "the staged tmp file is not a candidate: {candidates:?}"); + assert_eq!(load(&candidates[0].path).unwrap().runtime.generation, 1); + + // The next successful commit cleans the orphan up. + let second = encode(&agent_state(), &runtime(3)).unwrap(); + store.commit(3, &second, None).unwrap(); + assert!(!staged.exists()); + assert_eq!(store.manifest().unwrap().latest, Some(3)); + assert_eq!(store.manifest().unwrap().previous, Some(1)); + } + + #[test] + fn a_payload_renamed_without_its_manifest_is_never_loaded() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::new(dir.path(), 2); + store.commit(1, &encode(&agent_state(), &runtime(1)).unwrap(), None).unwrap(); + + // The payload rename succeeded, the manifest rename did not: the commit point is the + // manifest, so generation 2 is invisible. + write_atomic(&store.generation_path(2), b"not even an envelope").unwrap(); + let candidates = store.candidates("durable"); + assert_eq!(candidates.len(), 1); + assert_eq!(candidates[0].generation, Some(1)); + assert_eq!(store.highest_generation(), 2, "but the number is not reused"); + } + + #[test] + fn the_restore_order_is_hot_then_durable_then_archives_by_descending_rank() { + let dir = tempfile::tempdir().unwrap(); + let durable = Store::new(dir.path().join("durable"), 2); + let hot = Store::new(dir.path().join("hot"), 2); + let bytes = encode(&agent_state(), &runtime(1)).unwrap(); + + durable.commit(1, &bytes, Some(1)).unwrap(); + durable.commit(2, &bytes, Some(4)).unwrap(); + durable.commit(3, &bytes, None).unwrap(); + hot.commit(7, &bytes, None).unwrap(); + + let order: Vec = + restore_order(&hot, &durable).into_iter().map(|c| c.origin).collect(); + assert_eq!( + order, + vec![ + "hot latest generation 7", + "durable latest generation 3", + "durable previous generation 2", + "durable archived generation 2 (rank 4)", + "durable milestone archive rank 4", + "durable archived generation 1 (rank 1)", + "durable milestone archive rank 1", + ] + ); + } + + #[test] + fn rotation_keeps_the_referenced_generations_and_never_unlinks_an_archive() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::new(dir.path(), 2); + let bytes = encode(&agent_state(), &runtime(1)).unwrap(); + store.commit(1, &bytes, Some(2)).unwrap(); + for generation in 2..=6 { + store.commit(generation, &bytes, None).unwrap(); + } + assert!(store.generation_path(6).exists(), "latest"); + assert!(store.generation_path(5).exists(), "previous"); + assert!(store.generation_path(1).exists(), "archived generation"); + assert!(store.archive_path(2).exists(), "milestone archive"); + assert!(!store.generation_path(3).exists(), "rotated away"); + assert!(!store.generation_path(4).exists(), "rotated away"); + } + + #[test] + fn an_empty_or_manifestless_directory_offers_no_candidates() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::new(dir.path().join("missing"), 2); + assert!(store.candidates("durable").is_empty()); + assert_eq!(store.highest_generation(), 0); + + let store = Store::new(dir.path(), 2); + store.create().unwrap(); + std::fs::write(store.manifest_path(), "{ not json").unwrap(); + assert!(store.candidates("durable").is_empty(), "an unreadable manifest is not fatal"); + } +} diff --git a/services/flysim/crates/flysim/Cargo.toml b/services/flysim/crates/flysim/Cargo.toml index 3884630..37d9b1b 100644 --- a/services/flysim/crates/flysim/Cargo.toml +++ b/services/flysim/crates/flysim/Cargo.toml @@ -31,6 +31,8 @@ cuda = ["flybrain-core/cuda"] flybrain-core = { path = "../flybrain-core" } flybrain-gb = { path = "../flybrain-gb" } flybus = { path = "../flybus" } +# The FLYSIM01 store and the sugar journal, shared with the session runtime (STATE-02). +flysim-store = { path = "../flysim-store" } anyhow = "1.0" axum = { version = "0.8", features = ["ws"] } diff --git a/services/flysim/crates/flysim/src/journal.rs b/services/flysim/crates/flysim/src/journal.rs index 019c54a..99073ad 100644 --- a/services/flysim/crates/flysim/src/journal.rs +++ b/services/flysim/crates/flysim/src/journal.rs @@ -1,176 +1,6 @@ //! The sugar journal: every admitted audience input, stamped with the frame it was applied before. //! -//! `sugar-journal.jsonl` in `[paths] hot_dir`, one JSON object per line, append-only. It is not -//! part of a checkpoint and nothing reads it back into the fly: it is the record a shadow run -//! (the session framework's CUT-01, `docs/design/session-framework/legacy-gameboy-v1.md` section -//! 15) replays audience input from. The legacy loop applies an admitted sugar at once, in the -//! command drain at the top of a frame, so an input is fully placed by the transition it precedes: -//! -//! ```json -//! {"frame":"6465126","brainMs":108246189,"kind":"sugar","durationMs":400,"by":"viewer","source":"twitch","eventId":81234,"wallMs":1790000000000} -//! ``` -//! -//! - `frame` is the frame counter when the input was applied, which is the `step` of the next -//! transition in the frame trace (`crate::trace`): replay applies it before that transition's -//! ticks. A restore carries the frame counter, so stamps continue across restarts. -//! - `kind` is `sugar` (a `reward-pulse` stimulation of `durationMs`, after the admission rules -//! and the clamp) or `reward` (an operator's `POST /reward`, one reinforcement of `value`). -//! - `brainMs` cross-checks the stamp; `eventId` joins the event log; `wallMs` is for people. -//! -//! Refused requests are not journalled: admission is wall-clock policy, and a replay applies what -//! was admitted. A write that fails is a warning, never a refusal: the input has already reached -//! the fly. +//! The code lives in the `flysim-store` crate, which the session runtime links too (STATE-02). +//! This module re-exports it. -use std::fs::{File, OpenOptions}; -use std::io::Write; -use std::path::{Path, PathBuf}; - -use serde_json::{Value, json}; - -/// The journal's file name inside the hot directory. -pub const FILE_NAME: &str = "sugar-journal.jsonl"; - -/// What was applied. -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum Input { - Sugar { duration_ms: f64 }, - Reward { value: f64 }, -} - -/// One journal line. -#[derive(Debug, Clone, PartialEq)] -pub struct Entry<'a> { - pub frame: u64, - pub brain_ms: f64, - pub input: Input, - pub by: &'a str, - pub source: &'a str, - pub event_id: u64, - pub wall_ms: u64, -} - -impl Entry<'_> { - pub fn to_json(&self) -> Value { - let mut line = json!({ "frame": self.frame.to_string(), "brainMs": self.brain_ms }); - let map = line.as_object_mut().expect("an object"); - match self.input { - Input::Sugar { duration_ms } => { - map.insert("kind".into(), "sugar".into()); - map.insert("durationMs".into(), json!(duration_ms)); - } - Input::Reward { value } => { - map.insert("kind".into(), "reward".into()); - map.insert("value".into(), json!(value)); - } - } - map.insert("by".into(), self.by.into()); - map.insert("source".into(), self.source.into()); - map.insert("eventId".into(), self.event_id.into()); - map.insert("wallMs".into(), self.wall_ms.into()); - line - } -} - -/// The append-only journal. Opened on the first input, so a run nobody feeds writes no file. -pub struct SugarJournal { - path: PathBuf, - file: Option, -} - -impl SugarJournal { - pub fn new(hot_dir: &Path) -> Self { - Self { - path: hot_dir.join(FILE_NAME), - file: None, - } - } - - pub fn path(&self) -> &Path { - &self.path - } - - /// Append one line. Each line is one `write` of the whole line, so a crash leaves at most a - /// torn last line, which a reader skips. - pub fn record(&mut self, entry: &Entry<'_>) { - if self.file.is_none() { - match OpenOptions::new() - .create(true) - .append(true) - .open(&self.path) - { - Ok(file) => self.file = Some(file), - Err(error) => { - tracing::warn!(%error, path = %self.path.display(), "could not open the sugar journal"); - return; - } - } - } - let mut line = entry.to_json().to_string(); - line.push('\n'); - if let Some(file) = self.file.as_mut() - && let Err(error) = file.write_all(line.as_bytes()) - { - tracing::warn!(%error, path = %self.path.display(), "could not append to the sugar journal"); - // Reopen on the next input rather than write through a broken handle. - self.file = None; - } - } -} - -/// Read a journal back: every whole line, in order. A torn or unreadable line is skipped. -pub fn read(path: &Path) -> std::io::Result> { - let text = std::fs::read_to_string(path)?; - Ok(text - .lines() - .filter_map(|line| serde_json::from_str::(line).ok()) - .filter(|value| value.get("frame").is_some()) - .collect()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn inputs_are_appended_with_their_frame_and_survive_a_reopen() { - let dir = tempfile::tempdir().expect("a temp dir"); - let mut journal = SugarJournal::new(dir.path()); - assert!( - !journal.path().exists(), - "nothing is written before an input" - ); - let sugar = Entry { - frame: 42, - brain_ms: 703.0, - input: Input::Sugar { duration_ms: 400.0 }, - by: "viewer", - source: "test", - event_id: 7, - wall_ms: 1, - }; - journal.record(&sugar); - drop(journal); - let mut journal = SugarJournal::new(dir.path()); - journal.record(&Entry { - frame: 43, - input: Input::Reward { value: 0.5 }, - event_id: 8, - ..sugar - }); - // A torn tail from a crash is skipped, not fatal. - std::fs::OpenOptions::new() - .append(true) - .open(journal.path()) - .and_then(|mut file| file.write_all(b"{\"frame\":\"44\",\"kin")) - .expect("appending a torn line"); - let lines = read(journal.path()).expect("the journal reads back"); - assert_eq!(lines.len(), 2); - assert_eq!(lines[0]["frame"], "42"); - assert_eq!(lines[0]["kind"], "sugar"); - assert_eq!(lines[0]["durationMs"], 400.0); - assert_eq!(lines[1]["frame"], "43"); - assert_eq!(lines[1]["kind"], "reward"); - assert_eq!(lines[1]["value"], 0.5); - assert_eq!(lines[1]["eventId"], 8); - } -} +pub use flysim_store::journal::*; diff --git a/services/flysim/crates/flysim/src/reset.rs b/services/flysim/crates/flysim/src/reset.rs index d610950..3256270 100644 --- a/services/flysim/crates/flysim/src/reset.rs +++ b/services/flysim/crates/flysim/src/reset.rs @@ -32,6 +32,10 @@ //! talked, reached, pushed-back) are memory-only by contract //! (`docs/design/macros.md` section 12.1: "a restored run offers every target once more"), //! so stopping flysim is what resets those and this has nothing to do. +//! 6. **clears the sugar journal** (`crate::journal::clear`): the journal and its rotations in the +//! hot store. The reset rewinds the frame counter to the rung's, so inputs stamped with the +//! abandoned run's frames would otherwise precede the new run's and read as its future. The +//! dated archive of step 1 keeps the old journal. use std::collections::BTreeMap; use std::path::{Path, PathBuf}; @@ -161,6 +165,11 @@ pub fn reset_to_milestone( memory-only and are reset by stopping flysim)" )); + // 6. The sugar journal, copied aside in step 1. + let journals = crate::journal::clear(hot_dir) + .with_context(|| format!("clearing the sugar journal in {}", hot_dir.display()))?; + report.push(format!("cleared the sugar journal: {journals} files removed")); + Ok(report) } @@ -379,6 +388,21 @@ mod tests { }; state_dir(&durable, &[3, 5, 9, 11], spent); state_dir(&hot, &[11], spent); + // The abandoned run's sugar journal, rotated once. + let mut journal = crate::journal::SugarJournal::with_limits(&hot, 200, 3); + for frame in 0..4 { + journal.record(&crate::journal::Entry { + frame: 900 + frame, + brain_ms: 0.0, + input: crate::journal::Input::Sugar { duration_ms: 300.0 }, + by: "viewer", + source: "test", + event_id: frame, + wall_ms: 1, + }); + } + drop(journal); + assert!(crate::journal::rotation_path(&hot, 1).is_file()); let archive = tmp.path().join("archive-20260922"); let report = reset_to_milestone(&durable, &hot, 5, &archive).unwrap(); @@ -397,6 +421,11 @@ mod tests { assert!(!durable.join("events.jsonl").exists()); assert!(!durable.join("events-20260921.jsonl").exists()); assert!(!hot.join("milestone-11.checkpoint").exists()); + // The journal is cleared, and the archive keeps it. + assert!(!hot.join(crate::journal::FILE_NAME).exists()); + assert!(!crate::journal::rotation_path(&hot, 1).exists()); + assert!(archive.join("hot").join(crate::journal::FILE_NAME).is_file()); + assert!(report.iter().any(|line| line.starts_with("cleared the sugar journal: 4 files")), "{report:?}"); // Both stores restore the rung, and the counters are back. for store in [Store::new(&hot, KEEP_GENERATIONS), Store::new(&durable, KEEP_GENERATIONS)] { diff --git a/services/flysim/crates/flysim/src/simloop.rs b/services/flysim/crates/flysim/src/simloop.rs index ff04d30..7604081 100644 --- a/services/flysim/crates/flysim/src/simloop.rs +++ b/services/flysim/crates/flysim/src/simloop.rs @@ -389,6 +389,9 @@ pub struct Sim { compatibility: String, semantic_rewards: bool, restored: bool, + /// Where this process started, for the sugar journal's boot header: the restore candidate's + /// origin and generation, or a fresh start. + boot_origin: (String, Option), /// Per-phase timing, off unless `FLY_PROFILE_SECONDS` is set (`crate::profile`). profiler: Profiler, } @@ -595,6 +598,7 @@ impl Sim { compatibility, semantic_rewards, restored: false, + boot_origin: ("fresh start".to_string(), None), profiler: Profiler::from_env(now), agent, emulator, @@ -641,6 +645,17 @@ impl Sim { // the whole warm-up — or, after a restore, every neuron that has ever fired, since the // checkpoint's `lastSpikeMs` values are absolute brain milliseconds. sim.last_publish_ms = sim.agent.network.ms; + // The journal's boot header: this process's inputs start here, whatever the previous + // process journalled after the checkpoint it restored (`crate::journal`). + sim.journal.boot(&crate::journal::BootHeader { + runtime: "flysim".to_string(), + start_frame: sim.frame.frame_counter, + brain_ms: sim.agent.network.ms, + origin: sim.boot_origin.0.clone(), + generation: sim.boot_origin.1, + compatibility: sim.compatibility.clone(), + wall_ms: now_wall_ms(), + }); sim.status = FeedStatus::Running; // A durable commit immediately after startup or restore (section 8), so the 300-second // interval is a ceiling on routine loss only, and so a broken write path is found now @@ -685,6 +700,7 @@ impl Sim { "restored" ); self.restored = true; + self.boot_origin = (candidate.origin.clone(), candidate.generation); self.emit(NewEvent::new( FeedEventKind::System, format!("Restored from {}", candidate.origin), diff --git a/services/flysim/crates/flysim/src/store.rs b/services/flysim/crates/flysim/src/store.rs index 586e6c0..abea562 100644 --- a/services/flysim/crates/flysim/src/store.rs +++ b/services/flysim/crates/flysim/src/store.rs @@ -1,645 +1,8 @@ //! Checkpoint persistence: the `FLYSIM01` envelope, the atomic commit, the generations and the //! milestone archives. //! -//! `docs/design/flysim.md` section 8, as amended by the contract override at the top of that -//! document: -//! -//! - the envelope is `flybrain-core`'s frozen `encodeEnvelope` layout with the magic `FLYSIM01`, -//! carrying the seven agent chunks plus `emulator`, `framebuffer`, `ratchetGame` and -//! `ratchetFrame`; -//! - a commit writes `.checkpoint.tmp`, fsyncs it, renames it, fsyncs the directory, and -//! then does the same for `manifest.json`. **The manifest rename is the commit point**: a -//! crash before it leaves an unreferenced file that is never loaded; -//! - durable commits go to `save_dir` every `checkpoint_seconds` (default 300) and on every -//! event that matters; a hot copy goes to `hot_dir` (tmpfs) every `hot_seconds` (default 5); -//! - the first commit at a new best rank also writes `milestone-.checkpoint`, which later -//! rotations never unlink. +//! The code lives in the `flysim-store` crate, which the session runtime links too (STATE-02), so +//! both write byte-identical checkpoints into the same store. This module re-exports it, and every +//! `flysim::store` path keeps working. -use std::collections::BTreeMap; -use std::fs::{File, OpenOptions}; -use std::io::Write; -use std::path::{Path, PathBuf}; - -use anyhow::{Context, Result}; -use flybrain_core::envelope::{EnvelopeParts, decode_envelope, encode_envelope}; -use flybrain_core::json::JsonValue; -use serde::{Deserialize, Serialize}; - -/// Envelope magic. Chunk names stay `[a-zA-Z]+` so the TypeScript `decodeEnvelope` can read a -/// flysim checkpoint for recap and inspection tooling. -pub const MAGIC: &str = "FLYSIM01"; - -/// Chunk names flysim adds to `flybrain-core`'s `AGENT_CHUNK_NAMES`. -pub const EMULATOR_CHUNK: &str = "emulator"; -pub const FRAMEBUFFER_CHUNK: &str = "framebuffer"; -pub const RATCHET_GAME_CHUNK: &str = "ratchetGame"; -pub const RATCHET_FRAME_CHUNK: &str = "ratchetFrame"; - -/// `manifest.json`: which generations are current, and which are archived forever. -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(default)] -pub struct StoreManifest { - /// Highest generation ever allocated in this store. - pub generation: u64, - /// The generation to restore first. - pub latest: Option, - /// The generation to restore if `latest` will not load. - pub previous: Option, - /// Best-rank archives, rank to generation. Their files are never rotated away. - pub archives: BTreeMap, -} - -impl StoreManifest { - fn record(&mut self, generation: u64, archive_rank: Option) { - self.generation = self.generation.max(generation); - if self.latest != Some(generation) { - self.previous = self.latest; - self.latest = Some(generation); - } - if let Some(rank) = archive_rank { - self.archives.insert(rank, generation); - } - } - - /// Generations that must survive rotation. - fn referenced(&self) -> Vec { - let mut out: Vec = self.latest.into_iter().chain(self.previous).collect(); - out.extend(self.archives.values().copied()); - out - } -} - -/// One restore candidate, in the order it should be tried. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Candidate { - pub path: PathBuf, - /// Human description for the log and for `/status`'s fallback reporting. - pub origin: String, - pub generation: Option, -} - -/// A checkpoint directory: `.checkpoint`, `milestone-.checkpoint`, `manifest.json`. -#[derive(Debug, Clone)] -pub struct Store { - dir: PathBuf, - keep_generations: usize, -} - -impl Store { - pub fn new(dir: impl Into, keep_generations: usize) -> Self { - Self { dir: dir.into(), keep_generations: keep_generations.max(1) } - } - - pub fn dir(&self) -> &Path { - &self.dir - } - - pub fn create(&self) -> Result<()> { - std::fs::create_dir_all(&self.dir) - .with_context(|| format!("creating checkpoint directory {}", self.dir.display())) - } - - pub fn manifest_path(&self) -> PathBuf { - self.dir.join("manifest.json") - } - - pub fn generation_path(&self, generation: u64) -> PathBuf { - self.dir.join(format!("{generation}.checkpoint")) - } - - pub fn archive_path(&self, rank: u32) -> PathBuf { - self.dir.join(format!("milestone-{rank}.checkpoint")) - } - - /// Read `manifest.json`, or `None` when it is absent or unreadable. - pub fn manifest(&self) -> Option { - let text = std::fs::read_to_string(self.manifest_path()).ok()?; - match serde_json::from_str(&text) { - Ok(manifest) => Some(manifest), - Err(error) => { - tracing::warn!(%error, path = %self.manifest_path().display(), "unreadable store manifest"); - None - } - } - } - - /// Highest generation the store has ever allocated, from the manifest and from the files on - /// disk (an unreferenced file from a crashed commit still counts, so a generation number is - /// never reused). - pub fn highest_generation(&self) -> u64 { - let mut highest = self.manifest().map_or(0, |manifest| manifest.generation); - if let Ok(entries) = std::fs::read_dir(&self.dir) { - for entry in entries.flatten() { - if let Some(generation) = parse_generation(&entry.file_name().to_string_lossy()) { - highest = highest.max(generation); - } - } - } - highest - } - - /// Restore candidates from this store, in order: latest, previous, then the archives by - /// descending rank. - pub fn candidates(&self, label: &str) -> Vec { - let Some(manifest) = self.manifest() else { - return Vec::new(); - }; - let mut out = Vec::new(); - for (kind, generation) in [("latest", manifest.latest), ("previous", manifest.previous)] { - if let Some(generation) = generation { - out.push(Candidate { - path: self.generation_path(generation), - origin: format!("{label} {kind} generation {generation}"), - generation: Some(generation), - }); - } - } - for (rank, generation) in manifest.archives.iter().rev() { - out.push(Candidate { - path: self.generation_path(*generation), - origin: format!("{label} archived generation {generation} (rank {rank})"), - generation: Some(*generation), - }); - out.push(Candidate { - path: self.archive_path(*rank), - origin: format!("{label} milestone archive rank {rank}"), - generation: Some(*generation), - }); - } - out.retain(|candidate| candidate.path.exists()); - out - } - - /// Write `bytes` as `generation`, commit it, archive it if `archive_rank` is set, then rotate. - /// - /// The sequence is exactly section 8's: payload tmp, fsync, rename, dir fsync, then manifest - /// tmp, fsync, rename, dir fsync. - pub fn commit( - &self, - generation: u64, - bytes: &[u8], - archive_rank: Option, - ) -> Result { - self.create()?; - write_atomic(&self.generation_path(generation), bytes)?; - if let Some(rank) = archive_rank { - write_atomic(&self.archive_path(rank), bytes)?; - } - let mut manifest = self.manifest().unwrap_or_default(); - manifest.record(generation, archive_rank); - let text = serde_json::to_vec_pretty(&manifest)?; - write_atomic(&self.manifest_path(), &text)?; - self.rotate(&manifest)?; - Ok(manifest) - } - - /// Stage a payload without committing it. Only the crash-simulation test uses this: it is - /// the state a `kill -9` between the tmp write and the rename leaves behind. - pub fn stage_for_test(&self, generation: u64, bytes: &[u8]) -> Result { - self.create()?; - let path = tmp_path(&self.generation_path(generation)); - write_and_sync(&path, bytes)?; - Ok(path) - } - - /// Remove generation files that the manifest no longer references, keeping the newest - /// `keep_generations` and never touching an archive. - fn rotate(&self, manifest: &StoreManifest) -> Result<()> { - let referenced = manifest.referenced(); - let mut generations: Vec = Vec::new(); - for entry in std::fs::read_dir(&self.dir)?.flatten() { - let name = entry.file_name().to_string_lossy().to_string(); - if let Some(generation) = parse_generation(&name) { - generations.push(generation); - } else if name.ends_with(".checkpoint.tmp") { - // A tmp file from an interrupted commit is never loadable; clean it up. - let _ = std::fs::remove_file(entry.path()); - } - } - generations.sort_unstable_by(|a, b| b.cmp(a)); - for (index, generation) in generations.iter().enumerate() { - if referenced.contains(generation) || index < self.keep_generations { - continue; - } - let path = self.generation_path(*generation); - if let Err(error) = std::fs::remove_file(&path) { - tracing::warn!(%error, path = %path.display(), "could not rotate a checkpoint"); - } - } - Ok(()) - } -} - -/// `milestone-.checkpoint` is an independent file, so it is not a generation. -fn parse_generation(name: &str) -> Option { - name.strip_suffix(".checkpoint")?.parse().ok() -} - -fn tmp_path(path: &Path) -> PathBuf { - let mut name = path.as_os_str().to_os_string(); - name.push(".tmp"); - PathBuf::from(name) -} - -/// tmp write, fsync, rename, directory fsync. -pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> { - let tmp = tmp_path(path); - write_and_sync(&tmp, bytes)?; - std::fs::rename(&tmp, path) - .with_context(|| format!("renaming {} to {}", tmp.display(), path.display()))?; - sync_dir(path.parent().unwrap_or(Path::new("."))) -} - -fn write_and_sync(path: &Path, bytes: &[u8]) -> Result<()> { - let mut file = OpenOptions::new() - .create(true) - .write(true) - .truncate(true) - .open(path) - .with_context(|| format!("creating {}", path.display()))?; - file.write_all(bytes)?; - file.flush()?; - file.sync_all().with_context(|| format!("fsync {}", path.display()))?; - Ok(()) -} - -fn sync_dir(dir: &Path) -> Result<()> { - // Opening a directory read-only and fsyncing it is what makes the rename durable. - File::open(dir) - .and_then(|file| file.sync_all()) - .with_context(|| format!("fsync directory {}", dir.display())) -} - -// --------------------------------------------------------------------------------------------- -// The envelope -// --------------------------------------------------------------------------------------------- - -/// Everything a checkpoint carries besides the agent's own chunks. -#[derive(Debug, Clone, PartialEq)] -pub struct RuntimeState { - pub generation: u64, - pub wall_ms: u64, - pub rom_sha256: String, - pub emulator_frame: u64, - pub compatibility: String, - pub speed: f64, - pub buttons: u32, - /// Simulated milliseconds at which the current milestone rank was reached. - pub rank_since_ms: f64, - pub last_event_id: u64, - /// The adapter's own lifetime reward state. - pub reward: serde_json::Value, - pub ratchet: flybrain_gb::RatchetState, - pub emulator: Vec, - pub framebuffer: Vec, - /// The ratchet's best safe snapshot, if it has one. - pub ratchet_game: Vec, - pub ratchet_frame: Vec, -} - -/// A decoded checkpoint: the agent half plus the runtime half. -#[derive(Debug, Clone)] -pub struct Checkpoint { - pub agent: flybrain_core::agent::AgentState, - pub runtime: RuntimeState, -} - -/// Encode an agent state plus the runtime state into one `FLYSIM01` envelope. -pub fn encode( - agent: &flybrain_core::agent::AgentState, - runtime: &RuntimeState, -) -> Result> { - let parts = flybrain_core::envelope::agent_to_chunks(agent); - let mut manifest = parts.manifest; - manifest.set("generation", (runtime.generation as f64).into()); - manifest.set("wallMs", (runtime.wall_ms as f64).into()); - manifest.set("romHash", runtime.rom_sha256.as_str().into()); - manifest.set("emulatorFrame", (runtime.emulator_frame as f64).into()); - manifest.set("compatibility", runtime.compatibility.as_str().into()); - manifest.set("speed", runtime.speed.into()); - manifest.set("buttons", f64::from(runtime.buttons).into()); - manifest.set("rankSinceMs", runtime.rank_since_ms.into()); - manifest.set("lastEventId", (runtime.last_event_id as f64).into()); - manifest.set("reward", to_json_value(&runtime.reward)?); - manifest.set("ratchet", to_json_value(&serde_json::to_value(runtime.ratchet)?)?); - - let mut chunks = parts.chunks; - chunks.push((EMULATOR_CHUNK.to_string(), runtime.emulator.clone())); - chunks.push((FRAMEBUFFER_CHUNK.to_string(), runtime.framebuffer.clone())); - chunks.push((RATCHET_GAME_CHUNK.to_string(), runtime.ratchet_game.clone())); - chunks.push((RATCHET_FRAME_CHUNK.to_string(), runtime.ratchet_frame.clone())); - - encode_envelope(MAGIC, &manifest, &chunks).map_err(|error| anyhow::anyhow!("{error}")) -} - -/// Decode and structurally validate a `FLYSIM01` envelope. -/// -/// Value-level validation belongs to the importers: `NeuralAgent::import_state` is -/// self-validating and a no-op on failure, and `Ratchet::import` rejects an impossible state. -pub fn decode(bytes: &[u8]) -> Result { - let parts: EnvelopeParts = - decode_envelope(bytes, MAGIC).map_err(|error| anyhow::anyhow!("{error}"))?; - let manifest = parts.manifest.clone(); - let agent = flybrain_core::envelope::agent_from_chunks(&manifest, &parts) - .map_err(|error| anyhow::anyhow!("{error}"))?; - - let string = |key: &str| -> Result { - manifest - .get(key) - .and_then(JsonValue::as_str) - .map(str::to_string) - .ok_or_else(|| anyhow::anyhow!("checkpoint manifest is missing {key}")) - }; - let number = |key: &str| -> Result { - manifest - .get(key) - .and_then(JsonValue::as_f64) - .ok_or_else(|| anyhow::anyhow!("checkpoint manifest is missing {key}")) - }; - let chunk = |name: &str| -> Result> { - parts - .chunk(name) - .map(<[u8]>::to_vec) - .ok_or_else(|| anyhow::anyhow!("checkpoint is missing the {name} chunk")) - }; - - let ratchet_json = manifest - .get("ratchet") - .ok_or_else(|| anyhow::anyhow!("checkpoint manifest is missing ratchet"))?; - let ratchet: flybrain_gb::RatchetState = serde_json::from_str(&ratchet_json.stringify()) - .context("checkpoint ratchet state is not readable")?; - let reward = manifest - .get("reward") - .map(|value| serde_json::from_str(&value.stringify())) - .transpose() - .context("checkpoint reward state is not readable")? - .unwrap_or(serde_json::Value::Null); - - Ok(Checkpoint { - agent, - runtime: RuntimeState { - generation: number("generation")? as u64, - wall_ms: number("wallMs")? as u64, - rom_sha256: string("romHash")?, - emulator_frame: number("emulatorFrame")? as u64, - compatibility: string("compatibility")?, - speed: number("speed")?, - buttons: number("buttons")? as u32, - rank_since_ms: number("rankSinceMs").unwrap_or(0.0), - last_event_id: number("lastEventId").unwrap_or(0.0) as u64, - reward, - ratchet, - emulator: chunk(EMULATOR_CHUNK)?, - framebuffer: chunk(FRAMEBUFFER_CHUNK)?, - ratchet_game: chunk(RATCHET_GAME_CHUNK)?, - ratchet_frame: chunk(RATCHET_FRAME_CHUNK)?, - }, - }) -} - -/// Read and decode a candidate, so a caller can try the next one on any failure. -pub fn load(path: &Path) -> Result { - let bytes = - std::fs::read(path).with_context(|| format!("reading checkpoint {}", path.display()))?; - decode(&bytes).with_context(|| format!("decoding checkpoint {}", path.display())) -} - -fn to_json_value(value: &serde_json::Value) -> Result { - JsonValue::parse(&serde_json::to_string(value)?).map_err(|error| anyhow::anyhow!("{error}")) -} - -/// The restore order: the tmpfs hot copy first, then the durable store. -/// -/// The hot copy is written every few seconds and the durable one every few minutes, so the hot -/// copy is normally the newest state that exists; it is a first-class candidate because it uses -/// the identical envelope and the identical atomic sequence, and not a partial dump. -/// The compatibility string the newest decodable checkpoint in `dir` carries, if any. -/// -/// The store's own `manifest.json` is only an index (generation, latest, previous, archives) — -/// the compatibility string lives in each checkpoint's own `FLYSIM01` envelope manifest, so -/// answering "what will this build refuse?" means decoding a checkpoint. Candidates are tried -/// newest first and a corrupt one is skipped, which is the same order and the same tolerance -/// `Sim::boot` restores with. -/// -/// `flysim --print-state-compatibility DIR` is this, and `infra/05-deploy.sh` compares its -/// answer with `--print-compatibility` before flipping the `current` symlink. -pub fn state_compatibility(dir: &Path) -> Option { - let store = Store::new(dir, 8); - for candidate in store.candidates("durable") { - if let Ok(checkpoint) = load(&candidate.path) { - return Some(checkpoint.runtime.compatibility); - } - } - None -} - -pub fn restore_order(hot: &Store, durable: &Store) -> Vec { - let mut out = hot.candidates("hot"); - out.extend(durable.candidates("durable")); - out -} - -#[cfg(test)] -mod tests { - use super::*; - - fn runtime(generation: u64) -> RuntimeState { - RuntimeState { - generation, - wall_ms: 1_700_000_000_000, - rom_sha256: "ab".repeat(32), - emulator_frame: 12_345, - compatibility: "kernel/adapter/fingerprint".to_string(), - speed: 1.0, - buttons: 0b0001_0000, - rank_since_ms: 4_242.0, - last_event_id: 77, - reward: serde_json::json!({ "version": 3, "total": 1.25 }), - ratchet: flybrain_gb::RatchetState { best: 3, ..Default::default() }, - emulator: vec![7; 64], - framebuffer: vec![9; 32], - ratchet_game: vec![1, 2, 3], - ratchet_frame: vec![4, 5, 6], - } - } - - fn agent_state() -> flybrain_core::agent::AgentState { - use flybrain_core::decoder::DecoderState; - use flybrain_core::lif::LifState; - use flybrain_core::ordered::NumberMap; - use flybrain_core::plasticity::PlasticityState; - flybrain_core::agent::AgentState { - version: 1, - remainder: 0.75, - warmed_up: true, - network: LifState { - membrane: vec![0.5, -0.25], - refractory: vec![0, 3], - last_spike_ms: vec![-1_000_000.0, 12.0], - visual_drive: vec![0.1], - rng: -12_345, - reward_remaining: 40.0, - ms: 9_000.0, - population_rate: 1.5, - rates: NumberMap::from_pairs([("forward", 2.0), ("reward_pam", 0.5)]), - plasticity: PlasticityState { - version: "fly-kc-mbon-rstdp-v2".to_string(), - topology: 42, - enabled: true, - updates: 3.0, - signal: 0.25, - gains: vec![1.0, 0.9], - traces: vec![0.0, 0.1], - touched: vec![0.0, 8_000.0], - }, - }, - decoder: DecoderState { - version: 4, - calibrated: true, - baseline: NumberMap::from_pairs([("forward", 1.0)]), - held_until: NumberMap::new(), - next_allowed: NumberMap::new(), - next_decision: 100.0, - current: Some("a".to_string()), - fatigue: NumberMap::new(), - macro_next_decision: 0.0, - macro_current: None, - macro_fatigue: NumberMap::new(), - }, - } - } - - #[test] - fn the_envelope_round_trips_every_field_and_chunk() { - let agent = agent_state(); - let runtime = runtime(4); - let bytes = encode(&agent, &runtime).unwrap(); - assert!(bytes.starts_with(MAGIC.as_bytes())); - - let back = decode(&bytes).unwrap(); - assert_eq!(back.agent, agent); - assert_eq!(back.runtime, runtime); - - // Re-encoding the decoded state is byte-identical, so a restore-and-save cycle is stable. - assert_eq!(encode(&back.agent, &back.runtime).unwrap(), bytes); - } - - #[test] - fn a_corrupted_or_truncated_envelope_is_rejected() { - let bytes = encode(&agent_state(), &runtime(1)).unwrap(); - assert!(decode(&bytes[..bytes.len() - 1]).is_err(), "truncated"); - - let mut flipped = bytes.clone(); - let middle = flipped.len() / 2; - flipped[middle] ^= 0xff; - assert!(decode(&flipped).is_err(), "checksum"); - - let mut trailing = bytes.clone(); - trailing.push(0); - assert!(decode(&trailing).is_err(), "trailing bytes"); - - let mut wrong_magic = bytes; - wrong_magic[0] = b'X'; - assert!(decode(&wrong_magic).is_err(), "magic"); - } - - #[test] - fn a_commit_is_atomic_and_a_crash_before_the_rename_leaves_a_loadable_store() { - let dir = tempfile::tempdir().unwrap(); - let store = Store::new(dir.path(), 2); - let first = encode(&agent_state(), &runtime(1)).unwrap(); - store.commit(1, &first, None).unwrap(); - - // kill -9 between the tmp write and the rename. - let mut broken = encode(&agent_state(), &runtime(2)).unwrap(); - broken.truncate(broken.len() / 2); - let staged = store.stage_for_test(2, &broken).unwrap(); - assert!(staged.exists()); - - let manifest = store.manifest().unwrap(); - assert_eq!(manifest.latest, Some(1)); - let candidates = store.candidates("durable"); - assert_eq!(candidates.len(), 1, "the staged tmp file is not a candidate: {candidates:?}"); - assert_eq!(load(&candidates[0].path).unwrap().runtime.generation, 1); - - // The next successful commit cleans the orphan up. - let second = encode(&agent_state(), &runtime(3)).unwrap(); - store.commit(3, &second, None).unwrap(); - assert!(!staged.exists()); - assert_eq!(store.manifest().unwrap().latest, Some(3)); - assert_eq!(store.manifest().unwrap().previous, Some(1)); - } - - #[test] - fn a_payload_renamed_without_its_manifest_is_never_loaded() { - let dir = tempfile::tempdir().unwrap(); - let store = Store::new(dir.path(), 2); - store.commit(1, &encode(&agent_state(), &runtime(1)).unwrap(), None).unwrap(); - - // The payload rename succeeded, the manifest rename did not: the commit point is the - // manifest, so generation 2 is invisible. - write_atomic(&store.generation_path(2), b"not even an envelope").unwrap(); - let candidates = store.candidates("durable"); - assert_eq!(candidates.len(), 1); - assert_eq!(candidates[0].generation, Some(1)); - assert_eq!(store.highest_generation(), 2, "but the number is not reused"); - } - - #[test] - fn the_restore_order_is_hot_then_durable_then_archives_by_descending_rank() { - let dir = tempfile::tempdir().unwrap(); - let durable = Store::new(dir.path().join("durable"), 2); - let hot = Store::new(dir.path().join("hot"), 2); - let bytes = encode(&agent_state(), &runtime(1)).unwrap(); - - durable.commit(1, &bytes, Some(1)).unwrap(); - durable.commit(2, &bytes, Some(4)).unwrap(); - durable.commit(3, &bytes, None).unwrap(); - hot.commit(7, &bytes, None).unwrap(); - - let order: Vec = - restore_order(&hot, &durable).into_iter().map(|c| c.origin).collect(); - assert_eq!( - order, - vec![ - "hot latest generation 7", - "durable latest generation 3", - "durable previous generation 2", - "durable archived generation 2 (rank 4)", - "durable milestone archive rank 4", - "durable archived generation 1 (rank 1)", - "durable milestone archive rank 1", - ] - ); - } - - #[test] - fn rotation_keeps_the_referenced_generations_and_never_unlinks_an_archive() { - let dir = tempfile::tempdir().unwrap(); - let store = Store::new(dir.path(), 2); - let bytes = encode(&agent_state(), &runtime(1)).unwrap(); - store.commit(1, &bytes, Some(2)).unwrap(); - for generation in 2..=6 { - store.commit(generation, &bytes, None).unwrap(); - } - assert!(store.generation_path(6).exists(), "latest"); - assert!(store.generation_path(5).exists(), "previous"); - assert!(store.generation_path(1).exists(), "archived generation"); - assert!(store.archive_path(2).exists(), "milestone archive"); - assert!(!store.generation_path(3).exists(), "rotated away"); - assert!(!store.generation_path(4).exists(), "rotated away"); - } - - #[test] - fn an_empty_or_manifestless_directory_offers_no_candidates() { - let dir = tempfile::tempdir().unwrap(); - let store = Store::new(dir.path().join("missing"), 2); - assert!(store.candidates("durable").is_empty()); - assert_eq!(store.highest_generation(), 0); - - let store = Store::new(dir.path(), 2); - store.create().unwrap(); - std::fs::write(store.manifest_path(), "{ not json").unwrap(); - assert!(store.candidates("durable").is_empty(), "an unreadable manifest is not fatal"); - } -} +pub use flysim_store::store::*; From 9c98281f4a1b66b22d1ba40593180d0f24f08847 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 16:26:07 +0000 Subject: [PATCH 2/6] fly-session: legacy_checkpoint, the session runtime's FLYSIM01 export, import, store policy and restore selection (STATE-02) The export assembles a FLYSIM01 file from the agent's FLYAGT01 and the world's FLYENV01 capture payloads, the task's {reward, ratchet} and the host's fields, through flysim-store's encoder. The import reads a file back into those halves. The agent payload is the shipped form of AGENT-01's prototype: learning.updates starts at plasticity.updates, and the file's framebuffer goes in an inputFrame chunk that StageRestore installs, as the legacy restore does. LegacyCheckpointer keeps the legacy loop's generations, hot and durable intervals, per-process milestone archives and writer thread. restore_from_store walks the legacy candidate order and takes the next candidate on any refusal. The agent worker's payload encoder is now one shared function, and legacy_parity seeds through the shipped import. --- services/flysim/Cargo.lock | 1 + services/flysim/crates/fly-session/Cargo.toml | 2 + services/flysim/crates/fly-session/README.md | 1 + .../crates/fly-session/src/legacy_agent.rs | 139 +- .../fly-session/src/legacy_checkpoint.rs | 1151 +++++++++++++++++ .../crates/fly-session/src/legacy_parity.rs | 100 +- services/flysim/crates/fly-session/src/lib.rs | 1 + 7 files changed, 1319 insertions(+), 76 deletions(-) create mode 100644 services/flysim/crates/fly-session/src/legacy_checkpoint.rs diff --git a/services/flysim/Cargo.lock b/services/flysim/Cargo.lock index d356eee..3c6e925 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -444,6 +444,7 @@ dependencies = [ "flybrain-core", "flybrain-gb", "flybus", + "flysim-store", "serde_json", "tempfile", "tokio", diff --git a/services/flysim/crates/fly-session/Cargo.toml b/services/flysim/crates/fly-session/Cargo.toml index ee1e7d4..1af661b 100644 --- a/services/flysim/crates/fly-session/Cargo.toml +++ b/services/flysim/crates/fly-session/Cargo.toml @@ -32,6 +32,8 @@ flybrain-core = { path = "../flybrain-core" } flybrain-gb = { path = "../flybrain-gb" } # The toy connectome fixture is written as gzipped `.binz` arrays, the dataset loader's format. flate2 = { workspace = true } +# STATE-02: the FLYSIM01 store and the sugar journal, the same code the legacy loop writes with. +flysim-store = { path = "../flysim-store" } serde_json = { workspace = true } # `rt-multi-thread` is not only for the tests: a worker process and a dedicated-thread diff --git a/services/flysim/crates/fly-session/README.md b/services/flysim/crates/fly-session/README.md index 46ef664..639ae58 100644 --- a/services/flysim/crates/fly-session/README.md +++ b/services/flysim/crates/fly-session/README.md @@ -49,6 +49,7 @@ Ready(k) ─ Prepare all agents concurrently ─────────── | `harness` | The runnable composition: router, the flies, one arena, one coordinator | | `legacy_env` | ENV-01: the legacy Game Boy environment worker over binjgb -- the one-frame setup scaffold, the joypad batch, `f32le` audio, the per-boundary memory image, `gameboy-slots-v1`, the capture payload and the world's half of `FLYSIM01` | | `legacy_env_parity` | ENV-01's parity harness: the toy cartridge, recorded scripts, the emulator driven directly in `LegacyFrame` order, the worker driven over the bus, and the replay of the service's own `FLY_TRACE` | +| `legacy_checkpoint` | STATE-02: the legacy composition's `FLYSIM01` checkpoints -- the export from the agent's and the world's capture payloads plus the task's and the host's halves, the import back (with the `learning.updates` rule), the legacy store policy (generations, hot/durable intervals, milestone archives) and the restore selection over the live store. The store code is the `flysim-store` crate, shared with `flysim` | ## Execution modes and the launcher diff --git a/services/flysim/crates/fly-session/src/legacy_agent.rs b/services/flysim/crates/fly-session/src/legacy_agent.rs index a846993..876fc8c 100644 --- a/services/flysim/crates/fly-session/src/legacy_agent.rs +++ b/services/flysim/crates/fly-session/src/legacy_agent.rs @@ -73,6 +73,10 @@ f767d48ff556fceae996e2ac73c0d0871df71101db0af414a0ffcd0bfb678489:\ /// The magic of the agent's capture payload: a `flybrain-core` checkpoint envelope whose /// manifest and chunks are exactly `agent_to_chunks`, plus one `session` manifest member. pub const PAYLOAD_MAGIC: &str = "FLYAGT01"; +/// An optional payload chunk: the frame to install as the next input when the payload is +/// staged. Only the `FLYSIM01` import writes it (STATE-02), because the legacy restore +/// re-projects the saved framebuffer rather than trusting the saved visual drive. +pub const INPUT_FRAME_CHUNK: &str = "inputFrame"; /// The layout version of the `session` member. pub const PAYLOAD_VERSION: u64 = 1; /// The attachment a Commit reply carries the transition's spike bitset under. @@ -243,6 +247,79 @@ pub fn rational_remainder_to_legacy(remainder: &RationalNs) -> Result { + pub agent_id: &'a Id, + pub checkpoint_id: &'a Id, + pub source_scope: &'a Scope, + pub committed_step: u64, + pub profile: &'a AssetRef, + pub seed: i32, + /// Reinforcement calls applied since the fly's fresh start (`learning.updates`). + pub reinforcements: u64, + /// The composition's `executor.macroChannels`, in composition order; empty in raw mode. + pub macro_channels: &'a [String], +} + +/// Encodes a `FLYAGT01` capture payload: `agent_to_chunks(state)` in `flybrain-core`'s envelope, +/// plus the `session` manifest member `State.StageRestore` reads back. `state.remainder` must +/// already be the accumulator's, as a capture sets it. +/// +/// The worker's own `State.Capture` writes exactly this, and so does the `FLYSIM01` import +/// (`crate::legacy_checkpoint`), which is why it is one function. +pub fn encode_payload( + state: &AgentState, + identity: &PayloadIdentity<'_>, + accumulator: &TickAccumulator, + context: &TypedValue, + input_frame: Option<&[u8]>, +) -> Result, String> { + let mut chunks = agent_to_chunks(state); + if let Some(frame) = input_frame { + chunks.chunks.push((INPUT_FRAME_CHUNK.to_owned(), frame.to_vec())); + } + let channels: Vec<&str> = identity.macro_channels.iter().map(String::as_str).collect(); + let session = json!({ + "payloadVersion": PAYLOAD_VERSION, + "kind": "legacy-agent", + "agentId": identity.agent_id, + "checkpointId": identity.checkpoint_id, + "sourceScope": identity.source_scope.to_json(), + "committedStep": identity.committed_step.to_string(), + "profile": identity.profile.to_json(), + "seed": identity.seed, + "reinforcements": identity.reinforcements.to_string(), + "kernelVersion": gameboy::KERNEL_VERSION, + "plasticityVersion": gameboy::PLASTICITY_VERSION, + "macroChannels": identity.macro_channels, + "decoderConfigDigest": decoder_config_digest(&gameboy_decoder_config_with_macros(&channels)), + "accumulator": { + "tickDuration": accumulator.tick_duration().to_json(), + "remainder": accumulator.remainder().to_json(), + "executedTicks": accumulator.executed_ticks().to_string(), + "warmupOffset": accumulator.warmup_offset().to_string(), + }, + "context": context.to_json(), + }); + let mut manifest = chunks.manifest; + let session = JsonValue::parse(&session.to_string()).map_err(|e| e.to_string())?; + manifest.set("session", session); + encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| e.to_string()) +} + +/// The agent state a `FLYAGT01` capture payload carries, with the accumulator's remainder in it. +/// The `session` member is not validated here; `State.StageRestore` does that. +pub fn decode_payload_state(bytes: &[u8]) -> Result { + let parts = decode_envelope(bytes, PAYLOAD_MAGIC) + .map_err(|e| format!("not a {PAYLOAD_MAGIC} envelope: {e}"))?; + agent_from_chunks(&parts.manifest, &parts).map_err(|e| e.to_string()) +} + // ------------------------------------------------------------------------------------------- // The readout transient @@ -1191,43 +1268,23 @@ impl LegacyAgentWorker { // The session owns the frame remainder, as the legacy loop does (`Sim::checkpoint`). state.remainder = rational_remainder_to_legacy(&accumulator.remainder()) .map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))?; - let chunks = agent_to_chunks(&state); - let channels: Vec<&str> = self - .config - .macro_channels - .iter() - .map(String::as_str) - .collect(); - let session = json!({ - "payloadVersion": PAYLOAD_VERSION, - "kind": "legacy-agent", - "agentId": self.config.agent_id, - "checkpointId": checkpoint_id, - "sourceScope": scope.to_json(), - "committedStep": k.to_string(), - "profile": self.profile.asset.to_json(), - "seed": self.seed, - "reinforcements": self.reinforcements.to_string(), - "kernelVersion": gameboy::KERNEL_VERSION, - "plasticityVersion": gameboy::PLASTICITY_VERSION, - "macroChannels": self.config.macro_channels, - "decoderConfigDigest": decoder_config_digest(&gameboy_decoder_config_with_macros(&channels)), - "accumulator": { - "tickDuration": accumulator.tick_duration().to_json(), - "remainder": accumulator.remainder().to_json(), - "executedTicks": accumulator.executed_ticks().to_string(), - "warmupOffset": accumulator.warmup_offset().to_string(), + encode_payload( + &state, + &PayloadIdentity { + agent_id: &self.config.agent_id, + checkpoint_id, + source_scope: scope, + committed_step: k, + profile: &self.profile.asset, + seed: self.seed, + reinforcements: self.reinforcements, + macro_channels: &self.config.macro_channels, }, - "context": context.typed.to_json(), - }); - let mut manifest = chunks.manifest; - let session = JsonValue::parse(&session.to_string()).map_err(|e| { - DomainError::new(ErrorCode::Internal, e.to_string(), MutationCertainty::None) - })?; - manifest.set("session", session); - encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| { - DomainError::new(ErrorCode::Internal, e.to_string(), MutationCertainty::None) - }) + accumulator, + &context.typed, + None, + ) + .map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None)) } async fn state_capture(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { @@ -1493,6 +1550,16 @@ impl LegacyAgentWorker { agent .import_state(&state) .map_err(|e| incompatible(format!("the agent state does not import: {e}")))?; + // A payload imported from `FLYSIM01` carries the frame on screen as its next input, and + // the restore installs it, as `LegacyFrame::restore` re-projects the saved framebuffer + // (`legacy_checkpoint::agent_payload`). A worker's own capture carries none. + if let Some(frame) = parts.chunk(INPUT_FRAME_CHUNK) { + let (width, height) = (agent.frame.width, agent.frame.height); + if frame.len() != width as usize * height as usize * 4 { + return Err(incompatible("the staged input frame is not the profile's view")); + } + agent.network.set_visual_frame(frame, width, height); + } if let Some(staged) = &self.staged { return Err(DomainError::before( ErrorCode::Conflict, diff --git a/services/flysim/crates/fly-session/src/legacy_checkpoint.rs b/services/flysim/crates/fly-session/src/legacy_checkpoint.rs new file mode 100644 index 0000000..8ff27ad --- /dev/null +++ b/services/flysim/crates/fly-session/src/legacy_checkpoint.rs @@ -0,0 +1,1151 @@ +//! STATE-02: the legacy Game Boy composition's checkpoints, in `FLYSIM01`, the format of record. +//! +//! `legacy-gameboy-v1` section 16 and the operator's decision of 2026-09-23: `FLYSIM01` stays +//! the format of record until RETIRE-01, and the session runtime exports a `FLYSIM01` envelope on +//! every durable save, which the current `flysim` reads under its unchanged compatibility string. +//! The deploy gate, `fly-reset-to-milestone` and `fly-loop-reset` keep working on those files. This +//! module is that export, the import back, the store policy around them and the restore selection: +//! +//! | `FLYSIM01` | Owner in the session runtime | Here | +//! | --- | --- | --- | +//! | the seven agent chunks and `remainder` | the agent (`FLYAGT01` capture payload) | [`agent_state`], [`agent_payload`] | +//! | `emulator`, `framebuffer`, `emulatorFrame`, `buttons`, `romHash`, `ratchetGame`, `ratchetFrame` | the environment (`FLYENV01`; the ratchet's snapshot is slot `best`) | [`world_state`], [`world_payload`] | +//! | `reward`, `ratchet` | the task's ledger | [`TaskHalf`] | +//! | `generation`, `wallMs`, `compatibility`, `speed`, `rankSinceMs`, `lastEventId` | the host (store, feed, rank tracking) | [`HostHalf`], [`LegacyCheckpointer`] | +//! +//! **Byte compatibility is by construction.** The envelope is written by +//! `flysim_store::store::encode`, the one function the legacy loop writes with, from the same +//! values: [`export`] builds a `RuntimeState` field for field as `Sim::snapshot_state` does. The +//! store is `flysim_store::store::Store`, so generations, `manifest.json`, `milestone-` +//! archives, `keep_generations` rotation and the restore order are the legacy store's own code. +//! The tests prove the rest on real checkpoints: legacy -> session -> legacy and session -> +//! legacy -> session round trips, and restore-then-continue against the legacy loop's +//! `FLY_TRACE`. +//! +//! **Restore is `legacy-transient-reset`** (`legacy-gameboy-v1` section 14): what `FLYSIM01` +//! carries is restored; the executor's ledgers, the running macro, the readout transient and the +//! adapter's transient observations are not in it and start cleared. +//! +//! **Declared difference, archive order** (`legacy-gameboy-v1` sections 4 and 16, operator +//! 2026-09-23): a milestone archive written by the session runtime is captured *after* that +//! boundary's slot save, so it holds the post-capture ratchet and slot (`best = r`, rung `r`'s +//! snapshot), where the legacy loop's holds `best = r-1` and rung `r-1`'s. Both are ordinary +//! `FLYSIM01` files and each runtime restores the other's. + +use std::sync::mpsc; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use fly_session_types::gameboy; +use flybrain_core::agent::AgentState; +use flybrain_gb::RatchetState; +use flysim_store::store::{self, Candidate, Checkpoint, RuntimeState, Store}; +use serde_json::Value; +use tokio::sync::oneshot; + +use crate::clock::TickAccumulator; +use crate::legacy_agent::{self, PayloadIdentity, legacy_remainder_to_rational}; +use crate::legacy_env::{Flysim01World, PayloadHeader, WorldState}; +use crate::types::*; + +pub use flysim_store::journal; +pub use flysim_store::store as flysim01; + +/// The source epoch of a payload made from a `FLYSIM01` file: the legacy file has no session +/// identity, so the imported payloads say where they came from rather than invent one. +pub const LEGACY_SOURCE_EPOCH: &str = "legacy"; + +// ------------------------------------------------------------------------------------------- +// The halves + +/// The task's half of a `FLYSIM01` checkpoint: the manifest members `reward` and `ratchet`. +/// +/// This is the `pokered-macros-v1` task ledger (`legacy-gameboy-v1` section 10: "the adapter +/// state (FLYSIM01's `reward` chunk) and the ratchet state"). The executor's ledgers are not in +/// it (`legacy-transient-reset`). +#[derive(Clone, Debug, PartialEq)] +pub struct TaskHalf { + /// `GameAdapter::export_state`, exactly as `FLYSIM01` records it; `null` for an adapter that + /// has none, which a restore then leaves alone. + pub reward: Value, + pub ratchet: RatchetState, +} + +impl TaskHalf { + /// `{reward, ratchet, slotFilled}`: the ledger value the task captures and installs. + /// `slotFilled` says whether the ratchet has a snapshot, which lives in the environment's + /// slot `best`; it is derived, never stored in `FLYSIM01`. + pub fn to_ledger(&self, slot_filled: bool) -> Value { + serde_json::json!({ + "reward": self.reward, + "ratchet": serde_json::to_value(self.ratchet).expect("a ratchet state serializes"), + "slotFilled": slot_filled, + }) + } + + pub fn from_ledger(value: &Value) -> Result { + let ratchet = value.get("ratchet").ok_or("the task ledger has no ratchet")?; + Ok(TaskHalf { + reward: value.get("reward").cloned().unwrap_or(Value::Null), + ratchet: serde_json::from_value(ratchet.clone()) + .map_err(|e| format!("the task ledger's ratchet: {e}"))?, + }) + } +} + +/// The host's half: what neither the agent, the world nor the task owns. +#[derive(Clone, Debug, PartialEq)] +pub struct HostHalf { + pub generation: u64, + pub wall_ms: u64, + /// The legacy compatibility string (`flysim --print-compatibility`), recorded, not + /// reinterpreted; it is still the restore gate (`legacy-gameboy-v1` section 12). + pub compatibility: String, + pub speed: f64, + /// Brain milliseconds at which the current ladder rank was reached. + pub rank_since_ms: f64, + /// The feed event log's watermark: the last event id issued. + pub last_event_id: u64, +} + +/// A `FLYSIM01` checkpoint read into its owners' halves. +#[derive(Clone, Debug)] +pub struct Halves { + pub agent: AgentState, + pub world: WorldState, + pub task: TaskHalf, + pub host: HostHalf, +} + +// ------------------------------------------------------------------------------------------- +// Export + +/// The agent state a `FLYAGT01` capture payload carries (its remainder is the accumulator's). +pub fn agent_state(agent_payload: &[u8]) -> Result { + legacy_agent::decode_payload_state(agent_payload) +} + +/// The world a `FLYENV01` capture payload carries. +pub fn world_state(world_payload: &[u8]) -> Result { + WorldState::decode(world_payload).map(|(_, state)| state) +} + +/// The `FLYSIM01` runtime fields of one boundary, exactly as `Sim::snapshot_state` fills them. +pub fn runtime_state( + world: &WorldState, + slot_id: &Id, + task: &TaskHalf, + host: &HostHalf, +) -> RuntimeState { + let Flysim01World { + rom_hash, + emulator_frame, + buttons, + emulator, + framebuffer, + ratchet_game, + ratchet_frame, + } = world.flysim01_chunks(slot_id); + RuntimeState { + generation: host.generation, + wall_ms: host.wall_ms, + rom_sha256: rom_hash, + emulator_frame, + compatibility: host.compatibility.clone(), + speed: host.speed, + buttons, + rank_since_ms: host.rank_since_ms, + last_event_id: host.last_event_id, + reward: task.reward.clone(), + ratchet: task.ratchet, + emulator, + framebuffer, + ratchet_game, + ratchet_frame, + } +} + +/// The `FLYSIM01` envelope of one boundary, from the agent's state, the world, the task's half +/// and the host's. +pub fn export_states( + agent: &AgentState, + world: &WorldState, + slot_id: &Id, + task: &TaskHalf, + host: &HostHalf, +) -> Result, String> { + store::encode(agent, &runtime_state(world, slot_id, task, host)).map_err(|e| format!("{e:#}")) +} + +/// The `FLYSIM01` envelope of one boundary, from the two participants' capture payloads. +pub fn export( + agent_payload: &[u8], + world_payload: &[u8], + slot_id: &Id, + task: &TaskHalf, + host: &HostHalf, +) -> Result, String> { + let agent = agent_state(agent_payload)?; + let world = world_state(world_payload)?; + export_states(&agent, &world, slot_id, task, host) +} + +// ------------------------------------------------------------------------------------------- +// Import + +/// Reads a decoded `FLYSIM01` checkpoint into its owners' halves. The world is at boundary +/// `emulatorFrame - setupFrames` with the ratchet's snapshot as slot `slot_id`. +pub fn halves( + checkpoint: &Checkpoint, + episode_id: &Id, + slot_id: &Id, + audio_sample_rate: u64, +) -> Result { + let runtime = &checkpoint.runtime; + let world = Flysim01World { + rom_hash: runtime.rom_sha256.clone(), + emulator_frame: runtime.emulator_frame, + buttons: runtime.buttons, + emulator: runtime.emulator.clone(), + framebuffer: runtime.framebuffer.clone(), + ratchet_game: runtime.ratchet_game.clone(), + ratchet_frame: runtime.ratchet_frame.clone(), + } + .into_state(episode_id, slot_id, audio_sample_rate)?; + Ok(Halves { + agent: checkpoint.agent.clone(), + world, + task: TaskHalf { + reward: runtime.reward.clone(), + ratchet: runtime.ratchet, + }, + host: HostHalf { + generation: runtime.generation, + wall_ms: runtime.wall_ms, + compatibility: runtime.compatibility.clone(), + speed: runtime.speed, + rank_since_ms: runtime.rank_since_ms, + last_event_id: runtime.last_event_id, + }, + }) +} + +/// Decodes `FLYSIM01` bytes into halves. +pub fn split( + bytes: &[u8], + episode_id: &Id, + slot_id: &Id, + audio_sample_rate: u64, +) -> Result { + let checkpoint = store::decode(bytes).map_err(|e| format!("{e:#}"))?; + halves(&checkpoint, episode_id, slot_id, audio_sample_rate) +} + +/// 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 by AGENT-01 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 (`legacy-gameboy-v1` section 13, amendment of +/// 2026-09-29). +pub fn legacy_reinforcements(state: &AgentState) -> u64 { + state.network.plasticity.updates as u64 +} + +/// The session accumulator of a legacy agent state: its exact remainder, every tick it has run +/// (`network.ms`, warm-up included) and the profile's warm-up as the offset. +pub fn legacy_accumulator(state: &AgentState) -> Result { + let ms = state.network.ms; + if !ms.is_finite() || ms < 0.0 || ms.fract() != 0.0 { + return Err(format!("the agent's brain clock {ms} ms is not a whole tick count")); + } + let ticks = ms as u64; + let warmup = if state.warmed_up { gameboy::WARMUP_MS.min(ticks) } else { 0 }; + TickAccumulator::restored( + gameboy::tick_duration(), + legacy_remainder_to_rational(state.remainder)?, + ticks, + warmup, + ) +} + +/// What the agent's imported payload is stamped with besides its state. +#[derive(Clone, Debug)] +pub struct AgentImport { + pub agent_id: Id, + pub profile: AssetRef, + pub seed: i32, + pub macro_channels: Vec, +} + +/// A `FLYAGT01` payload for `State.StageRestore` from a legacy agent state, the shipped form of +/// AGENT-01's `seed_from_legacy_state` prototype. `context` is the decision context the task +/// gives the restored agent for its next Prepare (`{boot, bound, location}` after the executor +/// observed the restored world). `frame_on_screen` is the file's `framebuffer`: the restore +/// installs it as the next input, as `LegacyFrame::restore` does, so a file whose saved visual +/// drive is not its framebuffer's projection (a survey checkpoint, say) restores to the legacy +/// outcome and not to its own bytes (`legacy-gameboy-v1` section 16 amendment of 2026-09-29). +pub fn agent_payload( + state: &AgentState, + frame_on_screen: &[u8], + import: &AgentImport, + checkpoint_id: &Id, + source_scope: &Scope, + context: &TypedValue, +) -> Result, String> { + let accumulator = legacy_accumulator(state)?; + legacy_agent::encode_payload( + state, + &PayloadIdentity { + agent_id: &import.agent_id, + checkpoint_id, + source_scope, + committed_step: source_scope.step, + profile: &import.profile, + seed: import.seed, + reinforcements: legacy_reinforcements(state), + macro_channels: &import.macro_channels, + }, + &accumulator, + context, + Some(frame_on_screen), + ) +} + +/// A `FLYENV01` payload for `State.StageRestore` from a world read out of `FLYSIM01`. +pub fn world_payload( + world: &WorldState, + worker_id: &Id, + checkpoint_id: &Id, + source_scope: &Scope, + configuration_digest: &Digest, +) -> Vec { + world.encode(&PayloadHeader { + worker_id: worker_id.clone(), + checkpoint_id: checkpoint_id.clone(), + source_scope: source_scope.clone(), + configuration_digest: configuration_digest.clone(), + }) +} + +/// The scope a payload made from a `FLYSIM01` file records as its source: the session, the +/// [`LEGACY_SOURCE_EPOCH`] and the world's boundary. +pub fn legacy_source_scope(session_id: &Id, boundary: u64) -> Scope { + scope_at(session_id, LEGACY_SOURCE_EPOCH, boundary) +} + +// ------------------------------------------------------------------------------------------- +// Restore selection + +/// What a candidate must be to be restored: the legacy loop's `try_restore` gate. +#[derive(Clone, Debug)] +pub struct RestoreGate { + pub rom_sha256: String, + /// This build's compatibility string. + pub compatibility: String, + /// The adapter ids this build's adapter migrates from (`GameAdapter::migrates_from`). + pub migrates_from: Vec, + /// `FLY_ACCEPT_ADAPTERS`, parsed (`flybrain_gb::compatibility::accepted_adapters`). + pub accepted: Vec, +} + +impl RestoreGate { + /// The gate with `FLY_ACCEPT_ADAPTERS` read from the process environment, as `try_restore` + /// reads it: a property of a deploy, not of a run. + pub fn from_env(rom_sha256: &str, compatibility: &str, migrates_from: &[&str]) -> RestoreGate { + RestoreGate { + rom_sha256: rom_sha256.to_owned(), + compatibility: compatibility.to_owned(), + migrates_from: migrates_from.iter().map(|s| (*s).to_owned()).collect(), + accepted: flybrain_gb::compatibility::accepted_adapters( + std::env::var(flybrain_gb::compatibility::ACCEPT_ADAPTERS_ENV).ok().as_deref(), + ), + } + } + + /// `Ok` for a restorable checkpoint (with the adapter it migrates from, if any), or why not. + pub fn check(&self, checkpoint: &Checkpoint) -> Result, String> { + let runtime = &checkpoint.runtime; + if runtime.rom_sha256 != self.rom_sha256 { + return Err(format!("checkpoint is for another cartridge ({})", runtime.rom_sha256)); + } + let migrates: Vec<&str> = self.migrates_from.iter().map(String::as_str).collect(); + match flybrain_gb::compatibility::decide( + &runtime.compatibility, + &self.compatibility, + &migrates, + &self.accepted, + ) { + flybrain_gb::compatibility::RestoreDecision::Exact => Ok(None), + flybrain_gb::compatibility::RestoreDecision::MigrateAdapter { from } => Ok(Some(from)), + flybrain_gb::compatibility::RestoreDecision::Refuse(reason) => Err(format!( + "compatibility mismatch: {reason}\n checkpoint: {}\n this build: {}", + runtime.compatibility, self.compatibility + )), + } + } +} + +/// One restored candidate. +#[derive(Clone, Debug)] +pub struct Restored { + pub candidate: Candidate, + /// Candidates refused before this one, with why: the legacy `restore_fallback` metric. + pub skipped: Vec<(Candidate, String)>, + pub migrated_from: Option, + pub checkpoint: Checkpoint, + pub installed: T, +} + +/// The outcome of a restore over the live store. +#[derive(Debug)] +pub enum Selection { + /// No candidate exists: warm up a fresh fly. + Fresh, + Restored(Box>), + /// Candidates exist and every one failed. The legacy loop exits non-zero here rather than + /// silently start a fresh fly over them, and so must the session runtime. + Refused(Vec<(Candidate, String)>), +} + +/// Restores from the live `FLYSIM01` stores in the legacy order -- hot latest, hot previous, +/// durable latest, durable previous, then the milestone archives by descending rank +/// (`store::restore_order`) -- trying the next candidate on *any* failure: unreadable, +/// another cartridge, refused compatibility, or `install` refusing it (a participant's +/// `State.StageRestore` or the task's validation). This is `Sim::restore_or_warm_up`. +pub async fn restore_from_store( + hot: &Store, + durable: &Store, + gate: &RestoreGate, + mut install: F, +) -> Selection +where + F: FnMut(Checkpoint) -> Fut, + Fut: std::future::Future>, +{ + let candidates = store::restore_order(hot, durable); + if candidates.is_empty() { + return Selection::Fresh; + } + let mut skipped: Vec<(Candidate, String)> = Vec::new(); + for candidate in candidates { + let checkpoint = match store::load(&candidate.path) { + Ok(checkpoint) => checkpoint, + Err(e) => { + skipped.push((candidate, format!("{e:#}"))); + continue; + } + }; + let migrated_from = match gate.check(&checkpoint) { + Ok(from) => from, + Err(reason) => { + skipped.push((candidate, reason)); + continue; + } + }; + match install(checkpoint.clone()).await { + Ok(installed) => { + return Selection::Restored(Box::new(Restored { + candidate, + skipped, + migrated_from, + checkpoint, + installed, + })); + } + Err(reason) => skipped.push((candidate, reason)), + } + } + Selection::Refused(skipped) +} + +// ------------------------------------------------------------------------------------------- +// The store policy + +/// Why a save is taken. Each maps onto the legacy loop's call site. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SaveKind { + /// `checkpoint_if_due`, the hot interval: `hot_dir`, every `hot_seconds`. + Hot, + /// A durable save: the interval (`checkpoint_seconds`), startup/restore, after a rollback, + /// a forced checkpoint, a pause and shutdown. + Durable, + /// `track_rank`: a climb to a new rank. Durable, and archived as `milestone-` when the + /// rank is above every rank this process archived. + Milestone(u32), +} + +/// A rank change the task reported, as `Sim::track_rank` sees it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RankChange { + Climbed(u32), + FellBack(u32), +} + +/// The configuration the legacy loop reads from `[paths]` and `[loop]`. +#[derive(Clone, Debug)] +pub struct CheckpointerConfig { + pub hot_dir: std::path::PathBuf, + pub durable_dir: std::path::PathBuf, + pub keep_generations: usize, + pub hot_seconds: f64, + pub checkpoint_seconds: f64, + pub compatibility: String, + pub speed: f64, + /// The environment's slot that holds the ratchet's snapshot (`best`). + pub slot_id: Id, +} + +/// One participant-coherent capture of a boundary, ready to be written. +#[derive(Clone, Debug)] +pub struct LegacyCapture { + pub boundary: u64, + pub agent_payload: Vec, + pub world_payload: Vec, + pub task: TaskHalf, +} + +/// What a committed save wrote. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SaveReport { + pub generation: u64, + pub durable: bool, + pub archive_rank: Option, + pub bytes: usize, +} + +/// A save that was queued; its reply resolves when the writer committed it (or failed). +pub struct SaveTicket { + pub generation: u64, + pub durable: bool, + pub archive_rank: Option, + pub reply: oneshot::Receiver>, +} + +struct WriteJob { + durable: bool, + archive_rank: Option, + capture: LegacyCapture, + host: HostHalf, + slot_id: Id, + reply: oneshot::Sender>, +} + +/// The session runtime's `FLYSIM01` store policy: the legacy loop's, call site for call site. +/// +/// - generations come from one counter over both stores, starting above the highest either +/// has ever allocated (`Sim::boot`); +/// - a hot copy every `hot_seconds`, a durable one every `checkpoint_seconds`, the durable +/// interval resetting the hot one (`checkpoint_if_due`); +/// - the first durable commit at a new best rank of *this process* is also written as +/// `milestone-.checkpoint` (`checkpoint_with_reply`'s `best_archived_rank`); +/// - the encoding and the fsyncs run on a writer thread, off the session's runtime. +pub struct LegacyCheckpointer { + config: CheckpointerConfig, + hot: Store, + durable: Store, + next_generation: u64, + best_archived_rank: Option, + rank: u32, + rank_since_ms: f64, + next_hot: Instant, + next_durable: Instant, + writer: Option>, + thread: Option>, +} + +impl LegacyCheckpointer { + /// Creates both store directories and starts the writer. + pub fn open(config: CheckpointerConfig) -> Result { + let durable = Store::new(&config.durable_dir, config.keep_generations); + let hot = Store::new(&config.hot_dir, config.keep_generations); + durable.create().map_err(|e| format!("{e:#}"))?; + hot.create().map_err(|e| format!("{e:#}"))?; + let next_generation = durable.highest_generation().max(hot.highest_generation()) + 1; + let (tx, rx) = mpsc::channel::(); + let (writer_hot, writer_durable) = (hot.clone(), durable.clone()); + let thread = std::thread::Builder::new() + .name("legacy-checkpoint".to_owned()) + .spawn(move || { + while let Ok(job) = rx.recv() { + let store = if job.durable { &writer_durable } else { &writer_hot }; + let generation = job.host.generation; + let result = export( + &job.capture.agent_payload, + &job.capture.world_payload, + &job.slot_id, + &job.capture.task, + &job.host, + ) + .and_then(|bytes| { + store + .commit(generation, &bytes, job.archive_rank) + .map(|_| bytes.len()) + .map_err(|e| format!("{e:#}")) + }) + .map(|bytes| SaveReport { + generation, + durable: job.durable, + archive_rank: job.archive_rank, + bytes, + }); + let _ = job.reply.send(result); + } + }) + .map_err(|e| format!("spawning the checkpoint writer: {e}"))?; + let now = Instant::now(); + Ok(LegacyCheckpointer { + config, + hot, + durable, + next_generation, + best_archived_rank: None, + rank: 0, + rank_since_ms: 0.0, + next_hot: now, + next_durable: now, + writer: Some(tx), + thread: Some(thread), + }) + } + + pub fn hot(&self) -> &Store { + &self.hot + } + + pub fn durable(&self) -> &Store { + &self.durable + } + + pub fn config(&self) -> &CheckpointerConfig { + &self.config + } + + /// The generation the next save will take. + pub fn next_generation(&self) -> u64 { + self.next_generation + } + + pub fn rank(&self) -> u32 { + self.rank + } + + pub fn rank_since_ms(&self) -> f64 { + self.rank_since_ms + } + + /// After a restore: the ladder rank the restored task reports and the checkpoint's + /// `rankSinceMs` (`Sim::try_restore`). A fresh start keeps rank 0. + pub fn restored(&mut self, rank: u32, rank_since_ms: f64) { + self.rank = rank; + self.rank_since_ms = rank_since_ms; + } + + /// Both intervals run from now: called right after the startup durable commit, as + /// `Sim::boot` does, so the loop's first boundary does not write a second one. + pub fn start_intervals(&mut self, now: Instant) { + self.next_hot = now + Duration::from_secs_f64(self.config.hot_seconds); + self.next_durable = now + Duration::from_secs_f64(self.config.checkpoint_seconds); + } + + /// `Sim::track_rank`: the rank after a transition. A climb is a milestone save. + pub fn observe_rank(&mut self, rank: u32, brain_ms: f64) -> Option { + if rank == self.rank { + return None; + } + let climbed = rank > self.rank; + self.rank = rank; + self.rank_since_ms = brain_ms; + Some(if climbed { RankChange::Climbed(rank) } else { RankChange::FellBack(rank) }) + } + + /// `Sim::checkpoint_if_due`: the interval save due now, if any. + pub fn due(&mut self, now: Instant) -> Option { + let hot_period = Duration::from_secs_f64(self.config.hot_seconds); + let durable_period = Duration::from_secs_f64(self.config.checkpoint_seconds); + if now >= self.next_durable { + self.next_durable = now + durable_period; + self.next_hot = now + hot_period; + Some(SaveKind::Durable) + } else if now >= self.next_hot { + self.next_hot = now + hot_period; + Some(SaveKind::Hot) + } else { + None + } + } + + /// Queues one save of `capture`. The generation is allocated here, on the caller's thread, + /// in call order, and a milestone archive is decided here too, exactly as + /// `Sim::checkpoint_with_reply` decides both before handing the write to its thread. + pub fn save( + &mut self, + kind: SaveKind, + capture: LegacyCapture, + last_event_id: u64, + wall_ms: u64, + ) -> Result { + let durable = kind != SaveKind::Hot; + let archive_rank = match kind { + SaveKind::Milestone(rank) => Some(rank), + _ => None, + } + .filter(|rank| durable && self.best_archived_rank.is_none_or(|best| *rank > best)); + let generation = self.next_generation; + self.next_generation += 1; + if let Some(rank) = archive_rank { + self.best_archived_rank = Some(rank); + } + let host = HostHalf { + generation, + wall_ms, + compatibility: self.config.compatibility.clone(), + speed: self.config.speed, + rank_since_ms: self.rank_since_ms, + last_event_id, + }; + let (tx, rx) = oneshot::channel(); + let job = WriteJob { + durable, + archive_rank, + capture, + host, + slot_id: self.config.slot_id.clone(), + reply: tx, + }; + self.writer + .as_ref() + .ok_or("the checkpoint writer is gone")? + .send(job) + .map_err(|_| "the checkpoint writer stopped".to_owned())?; + Ok(SaveTicket { + generation, + durable, + archive_rank, + reply: rx, + }) + } + + /// Restore candidates in the legacy order. + pub fn candidates(&self) -> Vec { + store::restore_order(&self.hot, &self.durable) + } + + /// Stops the writer after every queued save committed. + pub fn close(&mut self) { + self.writer = None; + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +impl Drop for LegacyCheckpointer { + fn drop(&mut self) { + self.close(); + } +} + +/// The current wall clock in milliseconds, for `wallMs`. +pub fn now_wall_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::legacy_env::{SlotState, sample_at, world_time_at}; + use flybrain_gb::emulator::FRAMEBUFFER_LEN; + + fn agent(ms: f64, remainder: f64, updates: f64) -> AgentState { + use flybrain_core::decoder::DecoderState; + use flybrain_core::lif::LifState; + use flybrain_core::ordered::NumberMap; + use flybrain_core::plasticity::PlasticityState; + AgentState { + version: 1, + remainder, + warmed_up: true, + network: LifState { + membrane: vec![0.5, -0.25], + refractory: vec![0, 3], + last_spike_ms: vec![-1_000_000.0, 12.0], + visual_drive: vec![0.1], + rng: -12_345, + reward_remaining: 40.0, + ms, + population_rate: 1.5, + rates: NumberMap::from_pairs([("forward", 2.0), ("reward_pam", 0.5)]), + plasticity: PlasticityState { + version: "fly-kc-mbon-rstdp-v2".to_string(), + topology: 42, + enabled: true, + updates, + signal: 0.25, + gains: vec![1.0, 0.9], + traces: vec![0.0, 0.1], + touched: vec![0.0, 8_000.0], + }, + }, + decoder: DecoderState { + version: 4, + calibrated: true, + baseline: NumberMap::from_pairs([("forward", 1.0)]), + held_until: NumberMap::new(), + next_allowed: NumberMap::new(), + next_decision: 100.0, + current: Some("a".to_string()), + fatigue: NumberMap::new(), + macro_next_decision: 0.0, + macro_current: None, + macro_fatigue: NumberMap::new(), + }, + } + } + + fn world_at(boundary: u64, slot: bool) -> WorldState { + let world_time = world_time_at(boundary).unwrap(); + WorldState { + rom_digest: "ab".repeat(32), + episode_id: id("ep1"), + boundary, + audio_next_sample: sample_at(&world_time, 48_000), + world_time, + engine_frame: boundary + 1, + buttons: 0b0001_0000, + emulator: vec![7; 64], + framebuffer: vec![9; FRAMEBUFFER_LEN], + slots: if slot { + vec![( + id("best"), + SlotState { game: vec![1, 2, 3], frame: vec![4; FRAMEBUFFER_LEN], boundary }, + )] + } else { + Vec::new() + }, + } + } + + fn task() -> TaskHalf { + TaskHalf { + reward: serde_json::json!({ "version": 3, "total": 1.25 }), + ratchet: RatchetState { best: 3, attempts: 1, ..Default::default() }, + } + } + + fn host(generation: u64) -> HostHalf { + HostHalf { + generation, + wall_ms: 1_700_000_000_000, + compatibility: "kernel/adapter/fingerprint".to_owned(), + speed: 1.0, + rank_since_ms: 4_242.0, + last_event_id: 77, + } + } + + #[test] + fn the_export_is_the_legacy_encoder_on_the_same_values_and_splits_back_into_its_halves() { + let agent = agent(9_000.0, 0.75, 3.0); + let world = world_at(12_344, true); + let bytes = export_states(&agent, &world, &id("best"), &task(), &host(4)).unwrap(); + // Field for field what `Sim::snapshot_state` builds, through the one encoder. + let legacy = store::encode( + &agent, + &RuntimeState { + generation: 4, + wall_ms: 1_700_000_000_000, + rom_sha256: "ab".repeat(32), + emulator_frame: 12_345, + compatibility: "kernel/adapter/fingerprint".to_owned(), + speed: 1.0, + buttons: 0b0001_0000, + rank_since_ms: 4_242.0, + last_event_id: 77, + reward: task().reward, + ratchet: task().ratchet, + emulator: vec![7; 64], + framebuffer: vec![9; FRAMEBUFFER_LEN], + ratchet_game: vec![1, 2, 3], + ratchet_frame: vec![4; FRAMEBUFFER_LEN], + }, + ) + .unwrap(); + assert_eq!(bytes, legacy); + let back = split(&bytes, &id("ep1"), &id("best"), 48_000).unwrap(); + assert_eq!(back.agent, agent); + assert_eq!(back.world, world); + assert_eq!(back.task, task()); + assert_eq!(back.host, host(4)); + // And no slot is an empty ratchet snapshot, both ways. + let bytes = export_states(&agent, &world_at(5, false), &id("best"), &task(), &host(1)).unwrap(); + let back = split(&bytes, &id("ep1"), &id("best"), 48_000).unwrap(); + assert!(back.world.slots.is_empty()); + } + + #[test] + fn the_export_from_capture_payloads_equals_the_export_from_states() { + let agent = agent(9_000.0, 0.75, 3.0); + let world = world_at(700, true); + let import = AgentImport { + agent_id: id("fly"), + profile: gameboy::profile_asset_ref(), + seed: 22_222, + macro_channels: vec!["macro_talk".to_owned()], + }; + let scope = legacy_source_scope(&id("s1"), world.boundary); + let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed(); + let agent_bytes = agent_payload(&agent, &world.framebuffer, &import, &id("c1"), &scope, &context).unwrap(); + let world_bytes = world_payload(&world, &id("world"), &id("c1"), &scope, &"cd".repeat(32)); + assert_eq!(agent_state(&agent_bytes).unwrap(), agent); + assert_eq!(world_state(&world_bytes).unwrap(), world); + assert_eq!( + export(&agent_bytes, &world_bytes, &id("best"), &task(), &host(9)).unwrap(), + export_states(&agent, &world, &id("best"), &task(), &host(9)).unwrap() + ); + assert!(export(&world_bytes, &agent_bytes, &id("best"), &task(), &host(9)).is_err()); + } + + #[test] + fn the_import_starts_the_accumulator_and_the_reinforcement_count_from_the_legacy_state() { + let state = agent(108_246_189.0, 0.75, 4_321.0); + let accumulator = legacy_accumulator(&state).unwrap(); + assert_eq!(accumulator.brain_ticks(), 108_246_189); + assert_eq!(accumulator.warmup_offset(), gameboy::WARMUP_MS); + assert_eq!( + crate::legacy_agent::rational_remainder_to_legacy(&accumulator.remainder()).unwrap(), + 0.75 + ); + assert_eq!(legacy_reinforcements(&state), 4_321); + // A clock that is not whole ticks, or a remainder that is not k/32768 ms, is refused. + assert!(legacy_accumulator(&agent(10.5, 0.0, 0.0)).is_err()); + assert!(legacy_accumulator(&agent(10.0, 0.1, 0.0)).is_err()); + let session = { + let import = AgentImport { + agent_id: id("fly"), + profile: gameboy::profile_asset_ref(), + seed: 22_222, + macro_channels: Vec::new(), + }; + let context = + gameboy::ReadoutContext { boot: true, bound: vec![], location: None }.to_typed(); + let bytes = agent_payload( + &state, + &[0; FRAMEBUFFER_LEN], + &import, + &id("c1"), + &legacy_source_scope(&id("s1"), 40), + &context, + ) + .unwrap(); + let parts = flybrain_core::envelope::decode_envelope( + &bytes, + crate::legacy_agent::PAYLOAD_MAGIC, + ) + .unwrap(); + let session: Value = + serde_json::from_str(&parts.manifest.get("session").unwrap().stringify()).unwrap(); + session + }; + assert_eq!(session["reinforcements"], "4321"); + assert_eq!(session["committedStep"], "40"); + assert_eq!(session["sourceScope"]["epoch"], LEGACY_SOURCE_EPOCH); + assert_eq!(session["accumulator"]["executedTicks"], "108246189"); + assert_eq!(session["accumulator"]["warmupOffset"], "2500"); + } + + #[test] + fn the_task_ledger_carries_exactly_the_reward_and_the_ratchet() { + let ledger = task().to_ledger(true); + assert_eq!(ledger["slotFilled"], true); + assert_eq!(TaskHalf::from_ledger(&ledger).unwrap(), task()); + assert_eq!( + ledger["ratchet"], + serde_json::to_value(task().ratchet).unwrap(), + "the FLYSIM01 manifest's own spelling" + ); + assert!(TaskHalf::from_ledger(&serde_json::json!({ "reward": null })).is_err()); + } + + fn capture(boundary: u64) -> LegacyCapture { + let agent = agent(9_000.0 + boundary as f64, 0.75, 3.0); + let world = world_at(boundary, boundary > 1); + let scope = legacy_source_scope(&id("s1"), boundary); + let import = AgentImport { + agent_id: id("fly"), + profile: gameboy::profile_asset_ref(), + seed: 22_222, + macro_channels: Vec::new(), + }; + let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed(); + LegacyCapture { + boundary, + agent_payload: agent_payload(&agent, &world.framebuffer, &import, &id("c"), &scope, &context) + .unwrap(), + world_payload: world_payload(&world, &id("world"), &id("c"), &scope, &"cd".repeat(32)), + task: task(), + } + } + + fn config(root: &std::path::Path) -> CheckpointerConfig { + CheckpointerConfig { + hot_dir: root.join("hot"), + durable_dir: root.join("state"), + keep_generations: 2, + hot_seconds: 5.0, + checkpoint_seconds: 300.0, + compatibility: "kernel/adapter/fingerprint".to_owned(), + speed: 1.0, + slot_id: id("best"), + } + } + + fn commit(checkpointer: &mut LegacyCheckpointer, kind: SaveKind, boundary: u64) -> SaveReport { + let ticket = checkpointer.save(kind, capture(boundary), boundary, 1).unwrap(); + ticket.reply.blocking_recv().unwrap().unwrap() + } + + #[test] + fn the_checkpointer_keeps_the_legacy_generations_archives_and_rotation() { + let dir = tempfile::tempdir().unwrap(); + // A store the legacy loop already wrote to: generation numbers are never reused. + let durable = Store::new(dir.path().join("state"), 2); + durable.create().unwrap(); + durable.stage_for_test(41, b"a crashed commit").unwrap(); + std::fs::rename( + dir.path().join("state/41.checkpoint.tmp"), + dir.path().join("state/41.checkpoint"), + ) + .unwrap(); + let mut checkpointer = LegacyCheckpointer::open(config(dir.path())).unwrap(); + assert_eq!(checkpointer.next_generation(), 42); + + let first = commit(&mut checkpointer, SaveKind::Durable, 10); + assert_eq!((first.generation, first.durable, first.archive_rank), (42, true, None)); + let hot = commit(&mut checkpointer, SaveKind::Hot, 11); + assert_eq!((hot.generation, hot.durable), (43, false)); + assert_eq!(checkpointer.hot().manifest().unwrap().latest, Some(43)); + + // A climb: rank and rankSinceMs as track_rank keeps them, and the first archive. + assert_eq!(checkpointer.observe_rank(0, 1.0), None); + assert_eq!(checkpointer.observe_rank(4, 500.0), Some(RankChange::Climbed(4))); + let archived = commit(&mut checkpointer, SaveKind::Milestone(4), 12); + assert_eq!(archived.archive_rank, Some(4)); + assert!(checkpointer.durable().archive_path(4).is_file()); + let decoded = store::load(&checkpointer.durable().archive_path(4)).unwrap(); + assert_eq!(decoded.runtime.generation, 44); + assert_eq!(decoded.runtime.rank_since_ms, 500.0); + assert_eq!(decoded.runtime.last_event_id, 12); + // Falling back and climbing to the same rank again is not a new best for this process. + assert_eq!(checkpointer.observe_rank(3, 600.0), Some(RankChange::FellBack(3))); + assert_eq!(checkpointer.observe_rank(4, 700.0), Some(RankChange::Climbed(4))); + let again = commit(&mut checkpointer, SaveKind::Milestone(4), 13); + assert_eq!((again.durable, again.archive_rank), (true, None)); + assert_eq!(store::load(&checkpointer.durable().archive_path(4)).unwrap().runtime.generation, 44); + + for boundary in 14..20 { + commit(&mut checkpointer, SaveKind::Durable, boundary); + } + let manifest = checkpointer.durable().manifest().unwrap(); + assert_eq!(manifest.archives.get(&4), Some(&44)); + assert!(checkpointer.durable().generation_path(44).is_file(), "an archived generation stays"); + assert!(!checkpointer.durable().generation_path(46).exists(), "rotated away"); + assert_eq!(manifest.previous.map(|p| p + 1), manifest.latest); + checkpointer.close(); + + // The next process allocates above everything either store holds. + let checkpointer = LegacyCheckpointer::open(config(dir.path())).unwrap(); + assert_eq!(checkpointer.next_generation(), manifest.latest.unwrap() + 1); + } + + #[test] + fn the_intervals_are_the_legacy_loops() { + let dir = tempfile::tempdir().unwrap(); + let mut checkpointer = LegacyCheckpointer::open(config(dir.path())).unwrap(); + let start = Instant::now(); + checkpointer.start_intervals(start); + assert_eq!(checkpointer.due(start + Duration::from_secs(1)), None); + assert_eq!(checkpointer.due(start + Duration::from_secs(5)), Some(SaveKind::Hot)); + assert_eq!(checkpointer.due(start + Duration::from_secs(6)), None); + assert_eq!(checkpointer.due(start + Duration::from_secs(10)), Some(SaveKind::Hot)); + // The durable interval wins and restarts the hot one. + let at = start + Duration::from_secs(300); + assert_eq!(checkpointer.due(at), Some(SaveKind::Durable)); + assert_eq!(checkpointer.due(at + Duration::from_secs(4)), None); + assert_eq!(checkpointer.due(at + Duration::from_secs(5)), Some(SaveKind::Hot)); + } + + fn gate() -> RestoreGate { + RestoreGate { + rom_sha256: "ab".repeat(32), + compatibility: "kernel/adapter/fingerprint".to_owned(), + migrates_from: Vec::new(), + accepted: Vec::new(), + } + } + + fn select( + checkpointer: &LegacyCheckpointer, + gate: &RestoreGate, + refuse: &[u64], + ) -> Selection { + let refuse = refuse.to_vec(); + let runtime = tokio::runtime::Builder::new_current_thread().build().unwrap(); + runtime.block_on(restore_from_store(checkpointer.hot(), checkpointer.durable(), gate, |c| { + let refuse = refuse.clone(); + async move { + if refuse.contains(&c.runtime.generation) { + Err(format!("participant refused generation {}", c.runtime.generation)) + } else { + Ok(c.runtime.generation) + } + } + })) + } + + #[test] + fn restore_walks_the_legacy_order_and_takes_the_next_candidate_on_any_refusal() { + let dir = tempfile::tempdir().unwrap(); + let mut checkpointer = LegacyCheckpointer::open(config(dir.path())).unwrap(); + assert!(matches!(select(&checkpointer, &gate(), &[]), Selection::Fresh)); + commit(&mut checkpointer, SaveKind::Milestone(3), 10); // 1, archive 3 + commit(&mut checkpointer, SaveKind::Durable, 11); // 2 + commit(&mut checkpointer, SaveKind::Durable, 12); // 3 + commit(&mut checkpointer, SaveKind::Hot, 13); // 4 + commit(&mut checkpointer, SaveKind::Hot, 14); // 5 + + let Selection::Restored(first) = select(&checkpointer, &gate(), &[]) else { panic!() }; + assert_eq!((first.installed, first.candidate.origin.as_str()), (5, "hot latest generation 5")); + assert!(first.skipped.is_empty()); + + // A torn hot latest, then a participant that refuses hot previous: durable latest. + std::fs::write(checkpointer.hot().generation_path(5), b"torn").unwrap(); + let Selection::Restored(next) = select(&checkpointer, &gate(), &[4]) else { panic!() }; + assert_eq!(next.installed, 3); + assert_eq!(next.skipped.len(), 2); + // Everything above the archive refused: the archive's generation, then its own file. + let Selection::Restored(deep) = select(&checkpointer, &gate(), &[2, 3, 4]) else { panic!() }; + assert_eq!(deep.installed, 1); + assert_eq!(deep.candidate.origin, "durable archived generation 1 (rank 3)"); + + // Another cartridge or another brain: refused by name, and nothing restores. + let other = RestoreGate { rom_sha256: "cd".repeat(32), ..gate() }; + let Selection::Refused(reasons) = select(&checkpointer, &other, &[]) else { panic!() }; + assert!(reasons.iter().all(|(_, why)| why.contains("another cartridge") || why.contains("decoding"))); + let newer = RestoreGate { compatibility: "kernel/adapter-v2/fingerprint".to_owned(), ..gate() }; + assert!(matches!(select(&checkpointer, &newer, &[]), Selection::Refused(_))); + // The operator's adapter migration is the legacy decision, unchanged. + let migrating = RestoreGate { + compatibility: "kernel/adapter-v2/fingerprint".to_owned(), + migrates_from: vec!["adapter".to_owned()], + accepted: vec!["adapter".to_owned()], + ..gate() + }; + let Selection::Restored(migrated) = select(&checkpointer, &migrating, &[]) else { panic!() }; + assert_eq!(migrated.migrated_from.as_deref(), Some("adapter")); + } +} diff --git a/services/flysim/crates/fly-session/src/legacy_parity.rs b/services/flysim/crates/fly-session/src/legacy_parity.rs index 785b7b7..07af25f 100644 --- a/services/flysim/crates/fly-session/src/legacy_parity.rs +++ b/services/flysim/crates/fly-session/src/legacy_parity.rs @@ -1450,10 +1450,10 @@ impl AgentDriver { /// the loop's frame remainder in it -- instead of from a warm-up, the way the stream restores /// after a restart (`legacy-transient-reset`). /// - /// This is the test side of an import nothing ships yet: the worker is initialized, its own - /// capture is taken as the template for the session member, the agent chunks and the clock - /// are replaced with `state`'s, and the result is restored into a replacement worker through - /// the ordinary `State.StageRestore` / `ActivateRestore`, which validates it like any other + /// The payload is the shipped `FLYSIM01` import's (`legacy_checkpoint::agent_payload`, STATE-02, + /// which replaced AGENT-01's prototype here): the worker is initialized, its capture names the + /// checkpoint and scope, and the import is restored into a replacement worker through the + /// ordinary `State.StageRestore` / `ActivateRestore`, which validates it like any other /// payload. `learning.updates` starts at [`legacy_reinforcements`], because `FLYSIM01` does /// not record every reinforcement call. pub async fn seed_from_legacy_state( @@ -1465,7 +1465,25 @@ impl AgentDriver { ) -> Result { self.initialize(initial_frame).await?; let template = self.capture().await?; - let bytes = legacy_state_payload(&template.bytes, state, &self.context)?; + // The shipped import (STATE-02, `legacy_checkpoint::agent_payload`); the template capture + // only supplies the checkpoint, the scope and the composition's macro channels. + let macro_channels: Vec = + serde_json::from_value(captured_session(&template.bytes)?["macroChannels"].clone()) + .map_err(|e| format!("the template's macro channels: {e}"))?; + let import = crate::legacy_checkpoint::AgentImport { + agent_id: self.agent_id.clone(), + profile: self.profile.asset.clone(), + seed: LEGACY_SEED, + macro_channels, + }; + let bytes = crate::legacy_checkpoint::agent_payload( + state, + &self.frames[initial_frame], + &import, + &template.result.checkpoint_id, + &template.scope, + &self.context, + )?; let digest = digest_of_bytes(&bytes); let artifact = crate::state::seal_payload(&self.client, &bytes, &digest) .await @@ -1483,7 +1501,11 @@ impl AgentDriver { self.restore_into(target, &seeded).await?; let after = self.capture().await?; let restored = payload_state_digest(&after.bytes)?; - if restored != state_digest(state) { + // Exact but for the visual drive, which the restore re-projects from the frame on screen + // as `LegacyFrame::restore` does (the direct reference does the same). + let mut expected = crate::legacy_checkpoint::agent_state(&after.bytes)?; + expected.network.visual_drive = state.network.visual_drive.clone(); + if state_digest(&expected) != state_digest(state) { return Err("the seeded worker's state is not the legacy state".to_owned()); } self.remainder = legacy_remainder_to_rational(state.remainder)?; @@ -1502,39 +1524,8 @@ impl AgentDriver { } } -/// The reinforcement calls to start a legacy agent state's `learning.updates` at. -/// -/// `FLYSIM01` records `plasticity.updates`, the reinforcements that moved a gain, but not every -/// call, and the contract requires `learning.changed <= learning.updates`. An import that starts -/// the call count at zero makes the first telemetry unreadable (found on the row-58 stream -/// checkpoint: `changed` is in the thousands), so it starts at the recorded count, a lower bound -/// on the calls actually made. -pub fn legacy_reinforcements(state: &flybrain_core::agent::AgentState) -> u64 { - state.network.plasticity.updates as u64 -} - -/// A worker capture with its agent chunks and clock replaced by a legacy agent state, and its -/// context by `context`: see [`AgentDriver::seed_from_legacy_state`]. -pub fn legacy_state_payload( - template: &[u8], - state: &flybrain_core::agent::AgentState, - context: &TypedValue, -) -> Result, String> { - let mut session = captured_session(template)?; - let remainder = legacy_remainder_to_rational(state.remainder)?; - session["accumulator"]["remainder"] = remainder.to_json(); - session["accumulator"]["executedTicks"] = json!((state.network.ms as u64).to_string()); - session["reinforcements"] = json!(legacy_reinforcements(state).to_string()); - session["context"] = context.to_json(); - let chunks = agent_to_chunks(state); - let mut manifest = chunks.manifest; - manifest.set( - "session", - flybrain_core::json::JsonValue::parse(&session.to_string()).map_err(|e| e.to_string())?, - ); - flybrain_core::envelope::encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks) - .map_err(|e| e.to_string()) -} +/// The shipped import's rule (`crate::legacy_checkpoint`), re-exported for the harness. +pub use crate::legacy_checkpoint::legacy_reinforcements; /// Runs a script against the rig's agent, recording what the coordinator observes. pub async fn run_on_worker( @@ -1553,6 +1544,30 @@ pub async fn run_on_worker_from( script: &LegacyScript, start: Option<&flybrain_core::agent::AgentState>, ) -> Result, String> { + run_script(rig, agent_id, script, start, false) + .await + .map(|(records, _)| records) +} + +/// [`run_on_worker_from`], then one `State.Capture` at the boundary the script ends on: the +/// records and the captured payload (STATE-02 writes a `FLYSIM01` export from it). +pub async fn run_on_worker_from_then_capture( + rig: &mut LegacyRig, + agent_id: &Id, + script: &LegacyScript, + start: Option<&flybrain_core::agent::AgentState>, +) -> Result<(Vec, Vec), String> { + let (records, captured) = run_script(rig, agent_id, script, start, true).await?; + Ok((records, captured.expect("a capture was asked for"))) +} + +async fn run_script( + rig: &mut LegacyRig, + agent_id: &Id, + script: &LegacyScript, + start: Option<&flybrain_core::agent::AgentState>, + capture_at_end: bool, +) -> Result<(Vec, Option>), String> { let mut driver = rig.driver(agent_id, script); let first = match start { None => driver.initialize(script.initial_frame).await?, @@ -1604,7 +1619,12 @@ pub async fn run_on_worker_from( } records.push(record); } - Ok(records) + let captured = if capture_at_end { + Some(driver.capture().await?.bytes) + } else { + None + }; + Ok((records, captured)) } fn captured_session(payload: &[u8]) -> Result { diff --git a/services/flysim/crates/fly-session/src/lib.rs b/services/flysim/crates/fly-session/src/lib.rs index 51ae391..63edd03 100644 --- a/services/flysim/crates/fly-session/src/lib.rs +++ b/services/flysim/crates/fly-session/src/lib.rs @@ -30,6 +30,7 @@ pub mod environment; pub mod harness; pub mod launcher; pub mod legacy_agent; +pub mod legacy_checkpoint; pub mod legacy_env; pub mod legacy_env_parity; pub mod legacy_parity; From 1faccd290844c318e3531625257591eb0d5e9da4 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 16:26:07 +0000 Subject: [PATCH 3/6] flysim: STATE-02 proofs: real-checkpoint round trips, restore-then-continue against FLY_TRACE, and the reset tools both ways --- .../flysim/crates/flysim/tests/state_02.rs | 825 ++++++++++++++++++ .../crates/flysim/tests/state_02_store.rs | 334 +++++++ 2 files changed, 1159 insertions(+) create mode 100644 services/flysim/crates/flysim/tests/state_02.rs create mode 100644 services/flysim/crates/flysim/tests/state_02_store.rs diff --git a/services/flysim/crates/flysim/tests/state_02.rs b/services/flysim/crates/flysim/tests/state_02.rs new file mode 100644 index 0000000..a23b39a --- /dev/null +++ b/services/flysim/crates/flysim/tests/state_02.rs @@ -0,0 +1,825 @@ +//! STATE-02: the session runtime's checkpoints are the legacy loop's `FLYSIM01`, on real +//! checkpoints and against the running legacy frame. +//! +//! Three proofs, all explicit ROM jobs (`. bin/rom-env.sh`, never a download): +//! +//! - `every_real_checkpoint_round_trips_legacy_session_legacy` (`FLY_ROM` and the rom-env +//! checkpoints): each checkpoint is read into its owners' halves by the shipped import, the +//! world is restored into the real environment worker and captured again, the agent state goes +//! through the `FLYAGT01` payload the import builds, the task half through the Pokémon adapter +//! and the ratchet, and the `FLYSIM01` export is compared with the original file byte for byte. +//! - `toy_restore_then_continue` (`FLY_ROM`): the legacy frame warms a toy fly up from power-on, +//! the legacy loop writes a checkpoint into a store, and from that store the legacy loop and +//! the session runtime each restore and run on. The session runtime's world and agent are +//! held to the legacy loop's `FLY_TRACE` transition by transition, its export at the end is +//! compared byte for byte with the legacy loop's own checkpoint of the same boundary, and that +//! export then goes session -> legacy -> session unchanged. +//! - `fafb_restore_then_continue` (also `FLY_STATE02_FAFB=1` and `data/fafb-v783`): the same +//! with the live composition, `gameboy-legacy-fafb-v783-v1` in macros mode, from a stream +//! checkpoint (`FLY_STATE02_CHECKPOINT`, else `FLY_ROW67_CHECKPOINT`), with sugar and a ratchet +//! rollback. +//! +//! The executor and the task's per-frame evaluation are TASK-01's; here the joypad masks come +//! from the trace and the task's end-of-run half from the legacy loop, which is what makes the +//! world and the agent comparable on their own. `FLY_STATE02_FRAMES` sets the run length +//! (default 600 toy, 300 FAFB). + +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_checkpoint::{self as lc, HostHalf, Selection, TaskHalf}; +use fly_session::legacy_env::{self, BackendConfig}; +use fly_session::legacy_env_parity::{EnvRecord, EnvRig, FlyTrace}; +use fly_session::legacy_parity::{ + self, LegacyRig, LegacyScript, RewardEvent, RigAgent, ScriptStep, TraceTransition, toy, +}; +use fly_session::types::{digest_of_bytes, id}; +use flybrain_core::agent::{AgentConfig, 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, Snapshot}; +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::store::{self, Checkpoint, RuntimeState, Store}; +use flysim::trace::FrameTrace; + +const EPISODE: &str = "ep1"; + +fn rom_path() -> 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(PathBuf::from(path)) +} + +fn frames(default: usize) -> usize { + std::env::var("FLY_STATE02_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(default) +} + +fn slot() -> fly_session::types::Id { + id(legacy_env::DEFAULT_SLOT) +} + +/// Every stream checkpoint rom-env names, once each, by variable name. +fn rom_env_checkpoints() -> Vec<(String, PathBuf)> { + let mut seen: HashMap = HashMap::new(); + for (key, value) in std::env::vars() { + if key.starts_with("FLY_") && key.ends_with("_CHECKPOINT") { + let path = PathBuf::from(value); + if path.is_file() { + seen.entry(path).or_insert(key); + } + } + } + let mut out: Vec<(String, PathBuf)> = seen.into_iter().map(|(p, k)| (k, p)).collect(); + out.sort(); + out +} + +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 }), + } +} + +/// The host fields the two runtimes are given alike, so their bytes are comparable. +fn host_of(runtime: &RuntimeState, generation: u64) -> HostHalf { + HostHalf { + generation, + wall_ms: runtime.wall_ms, + compatibility: runtime.compatibility.clone(), + speed: runtime.speed, + rank_since_ms: runtime.rank_since_ms, + last_event_id: runtime.last_event_id, + } +} + +/// The field that first differs between two `FLYSIM01` files, for a readable failure. +fn first_difference(left: &[u8], right: &[u8]) -> String { + let (Ok(a), Ok(b)) = (store::decode(left), store::decode(right)) else { + return "one side does not decode".to_owned(); + }; + let checks: Vec<(&str, bool)> = vec![ + ("agent", a.agent == b.agent), + ("generation", a.runtime.generation == b.runtime.generation), + ("wallMs", a.runtime.wall_ms == b.runtime.wall_ms), + ("romHash", a.runtime.rom_sha256 == b.runtime.rom_sha256), + ("emulatorFrame", a.runtime.emulator_frame == b.runtime.emulator_frame), + ("compatibility", a.runtime.compatibility == b.runtime.compatibility), + ("speed", a.runtime.speed == b.runtime.speed), + ("buttons", a.runtime.buttons == b.runtime.buttons), + ("rankSinceMs", a.runtime.rank_since_ms == b.runtime.rank_since_ms), + ("lastEventId", a.runtime.last_event_id == b.runtime.last_event_id), + ("reward", a.runtime.reward == b.runtime.reward), + ("ratchet", a.runtime.ratchet == b.runtime.ratchet), + ("emulator", a.runtime.emulator == b.runtime.emulator), + ("framebuffer", a.runtime.framebuffer == b.runtime.framebuffer), + ("ratchetGame", a.runtime.ratchet_game == b.runtime.ratchet_game), + ("ratchetFrame", a.runtime.ratchet_frame == b.runtime.ratchet_frame), + ]; + let differing: Vec<&str> = checks.iter().filter(|(_, same)| !same).map(|(n, _)| *n).collect(); + if differing.is_empty() { + "every field decodes equal; the bytes differ in layout".to_owned() + } else { + format!("differing fields: {}", differing.join(", ")) + } +} + +/// Which world fields differ, and where the first differing emulator byte is. +fn world_difference(a: &fly_session::legacy_env::WorldState, b: &fly_session::legacy_env::WorldState) -> String { + let mut out = Vec::new(); + if a.boundary != b.boundary || a.engine_frame != b.engine_frame { + out.push(format!("boundary/frame {}/{} vs {}/{}", a.boundary, a.engine_frame, b.boundary, b.engine_frame)); + } + if a.world_time != b.world_time || a.audio_next_sample != b.audio_next_sample { + out.push("clock".to_owned()); + } + if a.buttons != b.buttons { + out.push(format!("buttons {} vs {}", a.buttons, b.buttons)); + } + if a.framebuffer != b.framebuffer { + out.push("framebuffer".to_owned()); + } + if a.slots != b.slots { + out.push("slots".to_owned()); + } + if a.emulator != b.emulator { + let first = a.emulator.iter().zip(&b.emulator).position(|(x, y)| x != y); + let count = a.emulator.iter().zip(&b.emulator).filter(|(x, y)| x != y).count(); + out.push(format!( + "emulator ({} vs {} bytes, first difference at {first:?}, {count} bytes differ)", + a.emulator.len(), + b.emulator.len() + )); + } + if a.rom_digest != b.rom_digest || a.episode_id != b.episode_id { + out.push("identity".to_owned()); + } + out.join("; ") +} + +// ------------------------------------------------------------------------------------------- +// The session runtime's world, through the environment worker + +/// The world half of `halves` restored into the environment worker through the shipped payload, +/// the worker driven by `ops`, then captured: the records and the captured payload. +async fn world_on_worker( + rig: &mut EnvRig, + halves: &lc::Halves, + ops: &[fly_session::legacy_env_parity::EnvOp], +) -> (Vec, Vec) { + use fly_session::legacy_env_parity::EnvOp; + let mut driver = rig.driver(); + let source = lc::legacy_source_scope(&rig.session_id, halves.world.boundary); + let captured = driver.payload_of(&halves.world, source.clone()).await.expect("sealed"); + // The harness's sealing is the shipped encoder with the same header. + let descriptor = legacy_env::LegacyGameboyEnvironment::descriptor_for(&BackendConfig::legacy( + &halves.world.rom_digest, + )); + assert_eq!( + captured.bytes, + lc::world_payload( + &halves.world, + &rig.worker_id, + &captured.result.checkpoint_id, + &source, + &descriptor.configuration_digest, + ), + "the world payload is the shipped import's" + ); + let target = driver.target().clone(); + let mut records = vec![driver.restore_into(target, &captured).await.expect("the world restores")]; + for op in ops { + records.push(match op { + EnvOp::Advance(mask) => driver.advance(*mask).await.expect("advance"), + EnvOp::SaveSlot(slot) => driver.save_slot(slot).await.expect("save slot"), + EnvOp::Rollback(slot) => driver.rollback(slot).await.expect("rollback"), + EnvOp::CaptureRestore => unreachable!("not in these scripts"), + }); + } + let bytes = driver.capture().await.expect("the world captures").bytes; + (records, bytes) +} + +async fn env_rig(root: &Path, rom: &Path, rom_digest: &str) -> EnvRig { + EnvRig::start(root, ExecutionMode::InProcess, rom, BackendConfig::legacy(rom_digest)) + .await + .expect("the environment rig") +} + +/// The task half through the objects TASK-01's task holds: the adapter and the ratchet. +fn task_through_adapter(task: &TaskHalf, snapshot: Option) -> TaskHalf { + let mut adapter = PokemonRedReward::new(); + if !task.reward.is_null() { + adapter.import_state(&task.reward).expect("the adapter imports its state"); + } + let mut ratchet = Ratchet::with_policy(adapter.recovery_policy()); + ratchet + .import(Some(task.ratchet), snapshot, adapter.rank_ladder().len()) + .expect("the ratchet imports its state"); + TaskHalf { + reward: adapter.export_state(), + ratchet: ratchet.state, + } +} + +// ------------------------------------------------------------------------------------------- +// 1. legacy -> session -> legacy on every real checkpoint + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn every_real_checkpoint_round_trips_legacy_session_legacy() { + let Some(rom) = rom_path() else { return }; + let checkpoints = rom_env_checkpoints(); + if checkpoints.is_empty() { + eprintln!("skipping: no FLY_*_CHECKPOINT is set (source bin/rom-env.sh)"); + return; + } + let root = tempfile::tempdir().expect("tmp"); + let mut identical = 0; + let mut semantic = Vec::new(); + for (name, path) in &checkpoints { + let original = std::fs::read(path).expect("the checkpoint reads"); + let checkpoint = store::decode(&original).expect("a FLYSIM01 checkpoint"); + let halves = lc::halves(&checkpoint, &id(EPISODE), &slot(), legacy_env::DEFAULT_AUDIO_RATE) + .expect("the halves"); + + // The world: into the real environment worker and out again. + let rig_root = root.path().join(name.to_lowercase()); + let mut rig = env_rig(&rig_root, &rom, &halves.world.rom_digest).await; + let (_, world_bytes) = world_on_worker(&mut rig, &halves, &[]).await; + rig.stop().await; + let world = lc::world_state(&world_bytes).expect("the captured world"); + + // Everything but the emulator's bytes is the file's; those are the legacy restore's + // (import, then the recorded joypad applied), compared below through the export. + let expected = fly_session::legacy_env::WorldState { + emulator: world.emulator.clone(), + ..halves.world.clone() + }; + assert!( + world == expected, + "{name}: the world restores and captures exactly: {}", + world_difference(&expected, &world) + ); + + // The agent: the FLYAGT01 payload the import builds carries exactly the legacy state. + let import = lc::AgentImport { + agent_id: id("fly"), + profile: fly_session::fly_session_types::gameboy::profile_asset_ref(), + seed: legacy_parity::LEGACY_SEED, + macro_channels: flybrain_gb::macro_channels("pokemon-red") + .iter() + .map(|c| (*c).to_owned()) + .collect(), + }; + let restored_context = ReadoutContext { boot: false, bound: vec![], location: None }; + let agent_bytes = lc::agent_payload( + &halves.agent, + &halves.world.framebuffer, + &import, + &id("c1"), + &lc::legacy_source_scope(&id("legacy"), halves.world.boundary), + &restored_context.to_typed(), + ) + .expect("the agent payload"); + + // The task: through the adapter and the ratchet, as the task object holds them. + let snapshot = (!checkpoint.runtime.ratchet_game.is_empty()).then(|| Snapshot { + game: checkpoint.runtime.ratchet_game.clone(), + frame: checkpoint.runtime.ratchet_frame.clone(), + }); + let task = task_through_adapter(&halves.task, snapshot); + + let exported = lc::export(&agent_bytes, &world_bytes, &slot(), &task, &halves.host) + .expect("the export"); + // And legacy again: the legacy store reads it and writes it back unchanged. + let back = store::decode(&exported).expect("the legacy loop reads the export"); + assert_eq!(store::encode(&back.agent, &back.runtime).unwrap(), exported); + + // The legacy loop's own restore outcome of the same file, checkpointed at once: what + // `LegacyFrame::restore` leaves in the emulator (import, then `set_buttons(buttons)`), + // the adapter (import, export) and the ratchet (import). The agent's import is exact + // (AGENT-01; the FAFB proof below restores it into both runtimes). + let rom_bytes = std::fs::read(&rom).expect("the ROM reads"); + let mut emulator = Emulator::new(&rom_bytes, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES) + .expect("binjgb should accept the cartridge"); + emulator.import_state(&checkpoint.runtime.emulator).expect("the emulator imports"); + emulator.set_buttons(checkpoint.runtime.buttons as u8); + let snapshot = (!checkpoint.runtime.ratchet_game.is_empty()).then(|| Snapshot { + game: checkpoint.runtime.ratchet_game.clone(), + frame: checkpoint.runtime.ratchet_frame.clone(), + }); + let legacy_task = task_through_adapter(&halves.task, snapshot); + let legacy = store::encode( + &checkpoint.agent, + &RuntimeState { + emulator: emulator.export_state().expect("the emulator exports"), + reward: legacy_task.reward, + ratchet: legacy_task.ratchet, + ..checkpoint.runtime.clone() + }, + ) + .expect("the legacy encoder"); + assert!( + exported == legacy, + "{name}: the session export is not the legacy restore outcome: {}", + first_difference(&legacy, &exported) + ); + if exported == original { + identical += 1; + eprintln!("{name}: {} bytes, byte-identical to the file", original.len()); + } else { + // Both runtimes restore the same: what moved is the file's, and the reason is named. + let mut why = first_difference(&original, &exported); + if why.contains("reward") { + // Only an older adapter's state moves: the adapter's own import migration. + let adapter = checkpoint.runtime.compatibility.split('/').nth(1).unwrap_or(""); + assert_ne!(adapter, PokemonRedReward::new().id(), "{name}: {why}"); + why.push_str(&format!(" (written by adapter {adapter}, migrated on import)")); + } + eprintln!("{name}: {} bytes, the legacy restore outcome; vs the file: {why}", original.len()); + semantic.push(format!("{name} ({why})")); + } + } + eprintln!( + "legacy -> session -> legacy: {} checkpoints, every export equal to the legacy restore \ + outcome; {identical} byte-identical to the file, {} not: {semantic:?}", + checkpoints.len(), + semantic.len() + ); +} + +// ------------------------------------------------------------------------------------------- +// 2 and 3. restore then continue, against the legacy loop's trace + +/// A legacy brain and everything the legacy frame drives. +struct LegacyWorld { + agent: NeuralAgent, + emulator: Emulator, + adapter: PokemonRedReward, + ratchet: Ratchet, + frame: LegacyFrame, + macros: Option, +} + +fn legacy_world( + rom: &[u8], + data: &Arc, + mode: MacroMode, + trace: Option<&Path>, +) -> (LegacyWorld, Vec) { + let emulator = Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES) + .expect("binjgb should accept the cartridge"); + let adapter = PokemonRedReward::new(); + let ratchet = Ratchet::with_policy(adapter.recovery_policy()); + let channels = if mode.dealt() { + flybrain_gb::macro_channels("pokemon-red") + } else { + Vec::new() + }; + let preset = gameboy_decoder_config_with_macros(&channels); + let mut agent_config = AgentConfig::with_decoder(preset); + agent_config.warmup_ms = Config::default().loop_.warmup_ms; + let agent = NeuralAgent::new(Arc::clone(data), agent_config).expect("a valid agent"); + let frame = LegacyFrame::new().with_trace( + trace.map(|path| FrameTrace::create(path).expect("a trace file")), + ); + ( + LegacyWorld { agent, emulator, adapter, ratchet, frame, macros: None }, + channels.iter().map(|c| (*c).to_owned()).collect(), + ) +} + +impl LegacyWorld { + fn parts(&mut self) -> Parts<'_> { + Parts { + agent: &mut self.agent, + emulator: &mut self.emulator, + adapter: &mut self.adapter, + ratchet: &mut self.ratchet, + macros: self.macros.as_mut(), + } + } + + /// `Sim::boot` after its restore or warm-up: the macro layer, seeded from the network, and + /// one observation before the first frame. + fn deal(&mut self, mode: MacroMode) { + 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; + self.macros = macro_layer(&config, hold_ms, self.agent.network.rng_state() as u32); + if let Some(layer) = self.macros.as_mut() { + let ledger = AdapterLedger(&self.adapter); + let _ = layer.observe(&mut self.emulator, &ledger, self.agent.network.ms); + } + } + + /// `Sim::snapshot_state` with the host fields given. + fn checkpoint(&mut self, host: &HostHalf) -> Vec { + let mut agent = self.agent.export_state(); + agent.remainder = self.frame.remainder; + let runtime = RuntimeState { + generation: host.generation, + wall_ms: host.wall_ms, + rom_sha256: self.emulator.rom_sha256(), + emulator_frame: self.frame.frame_counter, + compatibility: host.compatibility.clone(), + speed: host.speed, + buttons: self.frame.buttons, + rank_since_ms: host.rank_since_ms, + last_event_id: host.last_event_id, + reward: self.adapter.export_state(), + ratchet: self.ratchet.state, + emulator: self.emulator.export_state().expect("the emulator exports"), + framebuffer: self.frame.frame_buffer.clone(), + ratchet_game: self.ratchet.game().map(<[u8]>::to_vec).unwrap_or_default(), + ratchet_frame: self.ratchet.frame().map(<[u8]>::to_vec).unwrap_or_default(), + }; + store::encode(&agent, &runtime).expect("the legacy encoder") + } + + fn task(&self) -> TaskHalf { + TaskHalf { reward: self.adapter.export_state(), ratchet: self.ratchet.state } + } +} + +/// 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 + }) + } +} + +/// The legacy loop restored from `checkpoint` and run `n` frames with `FLY_TRACE` on: the trace, +/// the agent's script, and the legacy world at the end. +#[allow(clippy::too_many_arguments)] +fn legacy_run( + rom: &[u8], + data: &Arc, + checkpoint: &Checkpoint, + mode: MacroMode, + n: usize, + sugar: &[(usize, f64)], + rollback_at: Option, + trace_path: &Path, +) -> (LegacyWorld, LegacyScript, Vec) { + let (mut world, channels) = legacy_world(rom, data, mode, Some(trace_path)); + { + let mut frame = std::mem::replace(&mut world.frame, LegacyFrame::new()); + frame.restore(&mut world.parts(), checkpoint).expect("the checkpoint restores"); + world.frame = frame; + } + world.deal(mode); + let mut pool = Pool::default(); + let initial_frame = pool.add(&world.frame.frame_buffer); + let initial_context = context(&world.adapter, world.macros.as_ref()); + let mut steps = Vec::new(); + for k in 1..=n { + let mut admitted = Vec::new(); + for (_, duration) in sugar.iter().filter(|(at, _)| *at == k) { + world.agent.network.stimulate(*duration); + if let Some(trace) = world.frame.trace_mut() { + trace.sugar(*duration); + } + admitted.push(*duration); + } + let mut frame = std::mem::replace(&mut world.frame, LegacyFrame::new()); + let mut parts = world.parts(); + let transition = frame.transition(&mut parts, &mut ()).expect("a frame"); + // The frame this transition produced, before a rollback puts the slot's on screen. + let produced = pool.add(&frame.frame_buffer); + let rewards: Vec = transition + .evaluated + .rewards + .iter() + .map(|event| RewardEvent { value: event.value, stimulation_ms: f64::from(event.stimulation_ms) }) + .collect(); + let next_context = context(&*parts.adapter, parts.macros.as_deref()); + let boundary = frame + .boundary(&mut parts, &transition.evaluated.progress, transition.ms) + .expect("the boundary"); + 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; + } + let rollback_context = rolled_back.then(|| context(&*parts.adapter, parts.macros.as_deref())); + world.frame = frame; + steps.push(ScriptStep::Frame { sugar: admitted, frame: produced, rewards, next_context }); + if let Some(context) = rollback_context { + steps.push(ScriptStep::Rollback { frame: pool.add(&world.frame.frame_buffer), context }); + } + } + world.frame.finish_trace(); + 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"); + let script = LegacyScript { + name: format!("state-02-{}", mode.as_str()), + macro_channels: channels, + frames: Arc::new(pool.frames), + initial_frame, + initial_context, + steps, + checkpoints: Default::default(), + }; + (world, script, trace) +} + +async fn agent_rig(root: &Path, dataset_dir: PathBuf, profile: LegacyProfileKind, channels: &[String]) -> LegacyRig { + let agent = RigAgent { + agent_id: id("fly"), + port_id: id("p1"), + dataset_dir, + profile, + macro_channels: channels.to_vec(), + worker_threads: 2, + }; + LegacyRig::start(root, ExecutionMode::InProcess, &[agent]).await.expect("the agent rig") +} + +/// What one restore-then-continue proves, for the report line. +struct Proof { + transitions: usize, + world_values: usize, + rollbacks: usize, + sugar: usize, + bytes: usize, +} + +/// The whole proof from one `FLYSIM01` start: +/// +/// 1. the start is committed into a durable store, under a torn hot copy, and the session +/// runtime selects it the legacy way; +/// 2. the legacy loop restores the same bytes and runs `n` frames with the trace on; +/// 3. the session runtime's world and agent, restored through the shipped import, run the +/// same transitions and are held to that trace; +/// 4. at the end the session runtime's `FLYSIM01` export equals the legacy loop's checkpoint of +/// the same boundary, byte for byte; +/// 5. that export restores into a fresh legacy loop, whose checkpoint is the same bytes, and +/// back into a fresh session runtime, whose export is the same bytes again. +#[allow(clippy::too_many_arguments)] +async fn restore_then_continue( + rom_path: &Path, + data: &Arc, + dataset_dir: PathBuf, + profile: LegacyProfileKind, + start: &[u8], + mode: MacroMode, + n: usize, + sugar: &[(usize, f64)], + rollback_at: Option, +) -> Proof { + let rom = std::fs::read(rom_path).expect("the ROM reads"); + let root = tempfile::tempdir().expect("tmp"); + + // 1. The live store: a durable generation under a torn hot one. + let start_checkpoint = store::decode(start).expect("the start decodes"); + let durable = Store::new(root.path().join("state"), 8); + let hot = Store::new(root.path().join("hot"), 8); + durable.commit(start_checkpoint.runtime.generation, start, None).expect("commit"); + hot.commit(start_checkpoint.runtime.generation + 1, b"torn by a crash", None).expect("commit"); + let gate = lc::RestoreGate { + rom_sha256: start_checkpoint.runtime.rom_sha256.clone(), + compatibility: start_checkpoint.runtime.compatibility.clone(), + migrates_from: Vec::new(), + accepted: Vec::new(), + }; + let selection = lc::restore_from_store(&hot, &durable, &gate, |checkpoint| async move { + lc::halves(&checkpoint, &id(EPISODE), &slot(), legacy_env::DEFAULT_AUDIO_RATE) + }) + .await; + let Selection::Restored(restored) = selection else { + panic!("the durable generation should restore: {selection:?}") + }; + assert_eq!(restored.skipped.len(), 1, "the torn hot copy is skipped"); + let halves = restored.installed; + let generation = start_checkpoint.runtime.generation + 10; + let host = host_of(&start_checkpoint.runtime, generation); + + // 2. The legacy loop from the same bytes. + let trace_path = root.path().join("trace.jsonl"); + let (mut legacy, script, trace) = + legacy_run(&rom, data, &restored.checkpoint, mode, n, sugar, rollback_at, &trace_path); + assert_eq!(trace.len(), n); + let legacy_bytes = legacy.checkpoint(&host); + + // 3a. The world, through the environment worker, driven by the trace's masks and boundary + // actions and held to its frame, WRAM and slot digests. + let fly_trace = FlyTrace::read(&trace_path, None).expect("the trace as the world reads it"); + let env_script = fly_trace.script("state-02", Arc::new(start.to_vec())); + let mut env = env_rig(&root.path().join("env"), rom_path, &halves.world.rom_digest).await; + let (records, world_bytes) = world_on_worker(&mut env, &halves, &env_script.ops).await; + let world_values = fly_trace.check(&records).expect("the world against FLY_TRACE"); + + // 3b. The agent, seeded through the shipped import and held to the trace. + let mut agents = agent_rig(&root.path().join("agent"), dataset_dir.clone(), profile, &script.macro_channels).await; + let (agent_records, agent_bytes) = legacy_parity::run_on_worker_from_then_capture( + &mut agents, + &id("fly"), + &script, + Some(&halves.agent), + ) + .await + .expect("the agent runs"); + let check = legacy_parity::check_against_trace(&script, &agent_records, &trace) + .expect("the agent against FLY_TRACE"); + + // 4. The session runtime's export at the last boundary is the legacy loop's checkpoint. + let session_bytes = + lc::export(&agent_bytes, &world_bytes, &slot(), &legacy.task(), &host).expect("the export"); + assert!( + session_bytes == legacy_bytes, + "session export vs legacy checkpoint after {n} frames: {}", + first_difference(&legacy_bytes, &session_bytes) + ); + + // 5a. session -> legacy: a fresh legacy loop restores the export and checkpoints it again. + let exported = store::decode(&session_bytes).expect("the legacy loop reads the export"); + let (mut fresh, _) = legacy_world(&rom, data, mode, None); + { + let mut frame = std::mem::replace(&mut fresh.frame, LegacyFrame::new()); + frame.restore(&mut fresh.parts(), &exported).expect("the legacy loop restores the export"); + fresh.frame = frame; + } + let host_after = host_of(&exported.runtime, exported.runtime.generation); + assert_eq!(fresh.checkpoint(&host_after), session_bytes, "session -> legacy is exact"); + + // 5b. -> session: a fresh environment and a fresh agent import it and export it again. + let again = lc::split(&session_bytes, &id(EPISODE), &slot(), legacy_env::DEFAULT_AUDIO_RATE) + .expect("the halves again"); + env.replace().await.expect("a fresh environment worker"); + let (_, world_again) = world_on_worker(&mut env, &again, &[]).await; + agents.replace(&id("fly")).await.expect("a fresh agent worker"); + // The import installs the frame on screen: the export's own. + let one_step = LegacyScript { + frames: Arc::new(vec![again.world.framebuffer.clone()]), + initial_frame: 0, + ..script.clone_shallow() + }; + let (_, agent_again) = legacy_parity::run_on_worker_from_then_capture( + &mut agents, + &id("fly"), + &one_step, + Some(&again.agent), + ) + .await + .expect("the agent imports the export"); + let round = lc::export(&agent_again, &world_again, &slot(), &again.task, &again.host) + .expect("the export again"); + assert!( + round == session_bytes, + "session -> legacy -> session: {}", + first_difference(&session_bytes, &round) + ); + env.stop().await; + agents.stop().await; + + Proof { + transitions: check.transitions, + world_values, + rollbacks: check.rollbacks, + sugar: check.sugar, + bytes: session_bytes.len(), + } +} + +trait CloneShallow { + fn clone_shallow(&self) -> LegacyScript; +} + +impl CloneShallow for LegacyScript { + fn clone_shallow(&self) -> LegacyScript { + LegacyScript { + name: self.name.clone(), + macro_channels: self.macro_channels.clone(), + frames: Arc::clone(&self.frames), + initial_frame: self.initial_frame, + initial_context: self.initial_context.clone(), + steps: Vec::new(), + checkpoints: Default::default(), + } + } +} + +fn report(what: &str, n: usize, proof: &Proof) { + eprintln!( + "{what}: {n} frames restored from the store and run on; world {} values and agent {} \ + transitions identical to FLY_TRACE ({} sugar, {} rollbacks); the {}-byte FLYSIM01 export \ + equals the legacy checkpoint of the same boundary and survives session -> legacy -> \ + session unchanged", + proof.world_values, proof.transitions, proof.sugar, proof.rollbacks, proof.bytes + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn toy_restore_then_continue() { + let Some(rom_path) = rom_path() else { return }; + let rom = std::fs::read(&rom_path).expect("the ROM reads"); + let data = Arc::new(load_brain_dataset_from_dir(toy::dir()).expect("the toy dataset")); + // A toy fly warmed up from power-on and run a while by the legacy frame: the checkpoint the + // legacy loop would write of it. + let (mut warm, _) = legacy_world(&rom, &data, MacroMode::Raw, None); + warm.frame.initialize(&mut warm.emulator, &mut warm.agent).expect("the fresh start"); + for _ in 0..120 { + let mut frame = std::mem::replace(&mut warm.frame, LegacyFrame::new()); + let mut parts = warm.parts(); + let transition = frame.transition(&mut parts, &mut ()).expect("a frame"); + frame.boundary(&mut parts, &transition.evaluated.progress, transition.ms).expect("a boundary"); + warm.frame = frame; + } + let start = warm.checkpoint(&HostHalf { + generation: 7, + wall_ms: 1_790_000_000_000, + compatibility: "toy/compat".to_owned(), + speed: 1.0, + rank_since_ms: 0.0, + last_event_id: 3, + }); + let n = frames(600); + let proof = restore_then_continue( + &rom_path, + &data, + toy::dir(), + LegacyProfileKind::Toy, + &start, + MacroMode::Raw, + n, + &[(20, 300.0), (n / 2, 500.0)], + None, + ) + .await; + report("toy raw", n, &proof); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fafb_restore_then_continue() { + let Some(rom_path) = rom_path() else { return }; + if std::env::var_os("FLY_STATE02_FAFB").is_none() { + eprintln!("skipping: FLY_STATE02_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_STATE02_CHECKPOINT") + .or_else(|| std::env::var_os("FLY_ROW67_CHECKPOINT")) + else { + eprintln!("skipping: neither FLY_STATE02_CHECKPOINT nor FLY_ROW67_CHECKPOINT is set"); + return; + }; + let start = std::fs::read(&path).expect("the checkpoint reads"); + let data = Arc::new(load_brain_dataset_from_dir(&dataset_dir).expect("the dataset")); + let n = frames(300); + let started = std::time::Instant::now(); + let proof = restore_then_continue( + &rom_path, + &data, + dataset_dir, + LegacyProfileKind::Production, + &start, + MacroMode::Macros, + n, + &[(10, 400.0), (n / 2, 250.0)], + Some(n / 3), + ) + .await; + report( + &format!("FAFB macros from {} ({:?})", Path::new(&path).display(), started.elapsed()), + n, + &proof, + ); +} diff --git a/services/flysim/crates/flysim/tests/state_02_store.rs b/services/flysim/crates/flysim/tests/state_02_store.rs new file mode 100644 index 0000000..89b10e5 --- /dev/null +++ b/services/flysim/crates/flysim/tests/state_02_store.rs @@ -0,0 +1,334 @@ +//! STATE-02: the session runtime's `FLYSIM01` store and the operator's tools, both ways. +//! +//! `fly-reset-to-milestone` and `fly-loop-reset` must keep working on a store the session runtime +//! wrote (`legacy-gameboy-v1` section 16), and the session runtime must restore a store the +//! legacy loop wrote and the tools reset. These run the real scripts from `infra/bin` and the +//! real `flysim --reset-to-milestone` against stores in a temporary directory, with `systemctl` +//! stubbed out. No ROM and no dataset: the checkpoints are synthetic but complete envelopes. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use fly_session::fly_session_types::gameboy; +use fly_session::legacy_checkpoint::{ + self as lc, AgentImport, CheckpointerConfig, LegacyCapture, LegacyCheckpointer, RankChange, + RestoreGate, SaveKind, Selection, TaskHalf, +}; +use fly_session::legacy_env::{SlotState, WorldState, sample_at, world_time_at}; +use fly_session::types::id; +use flybrain_core::agent::AgentState; +use flybrain_gb::RatchetState; +use flybrain_gb::emulator::FRAMEBUFFER_LEN; +use flysim::journal::{self, BootHeader, Entry, Input, SugarJournal}; +use flysim::store::{self, RuntimeState, Store}; + +const COMPAT: &str = "lif-1ms-f64-v2/pokered-unique8-v7/fingerprint/fly-kc-mbon-rstdp-v2"; + +fn repo() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../..") +} + +fn agent(ms: f64) -> AgentState { + use flybrain_core::decoder::DecoderState; + use flybrain_core::lif::LifState; + use flybrain_core::ordered::NumberMap; + use flybrain_core::plasticity::PlasticityState; + AgentState { + version: 1, + remainder: 0.5, + warmed_up: true, + network: LifState { + membrane: vec![0.5, -0.25], + refractory: vec![0, 3], + last_spike_ms: vec![-1_000_000.0, 12.0], + visual_drive: vec![0.1], + rng: -12_345, + reward_remaining: 0.0, + ms, + population_rate: 1.5, + rates: NumberMap::from_pairs([("forward", 2.0)]), + plasticity: PlasticityState { + version: "fly-kc-mbon-rstdp-v2".to_string(), + topology: 42, + enabled: true, + updates: 17.0, + signal: 0.25, + gains: vec![1.0, 0.9], + traces: vec![0.0, 0.1], + touched: vec![0.0, 8_000.0], + }, + }, + decoder: DecoderState { + version: 4, + calibrated: true, + baseline: NumberMap::from_pairs([("forward", 1.0)]), + held_until: NumberMap::new(), + next_allowed: NumberMap::new(), + next_decision: 100.0, + current: None, + fatigue: NumberMap::new(), + macro_next_decision: 0.0, + macro_current: None, + macro_fatigue: NumberMap::new(), + }, + } +} + +fn world(boundary: u64) -> WorldState { + let world_time = world_time_at(boundary).unwrap(); + WorldState { + rom_digest: "ab".repeat(32), + episode_id: id("ep1"), + boundary, + audio_next_sample: sample_at(&world_time, 48_000), + world_time, + engine_frame: boundary + 1, + buttons: 0, + emulator: vec![(boundary % 251) as u8; 256], + framebuffer: vec![9; FRAMEBUFFER_LEN], + slots: vec![( + id("best"), + SlotState { game: vec![1; 32], frame: vec![4; FRAMEBUFFER_LEN], boundary }, + )], + } +} + +/// A complete capture of boundary `k`, as the participants would hand it over. +fn capture(k: u64, ratchet: RatchetState) -> LegacyCapture { + let scope = lc::legacy_source_scope(&id("s1"), k); + let import = AgentImport { + agent_id: id("fly"), + profile: gameboy::profile_asset_ref(), + seed: 22_222, + macro_channels: Vec::new(), + }; + let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed(); + LegacyCapture { + boundary: k, + agent_payload: lc::agent_payload(&agent(9_000.0 + k as f64), &world(k).framebuffer, &import, &id("c"), &scope, &context) + .unwrap(), + world_payload: lc::world_payload(&world(k), &id("world"), &id("c"), &scope, &"cd".repeat(32)), + task: TaskHalf { reward: serde_json::Value::Null, ratchet }, + } +} + +fn config(root: &Path) -> CheckpointerConfig { + CheckpointerConfig { + hot_dir: root.join("hot"), + durable_dir: root.join("state"), + keep_generations: 8, + hot_seconds: 5.0, + checkpoint_seconds: 300.0, + compatibility: COMPAT.to_owned(), + speed: 1.0, + slot_id: id("best"), + } +} + +fn save(checkpointer: &mut LegacyCheckpointer, kind: SaveKind, k: u64, ratchet: RatchetState) { + let ticket = checkpointer.save(kind, capture(k, ratchet), k, 1_790_000_000_000).unwrap(); + ticket.reply.blocking_recv().unwrap().unwrap(); +} + +fn stub(dir: &Path, name: &str, body: &str) -> PathBuf { + use std::os::unix::fs::PermissionsExt; + let path = dir.join(name); + std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + path +} + +/// A PATH whose `systemctl` says every unit is inactive, so the scripts believe flysim is stopped. +fn tools(root: &Path) -> (String, PathBuf) { + let bin = root.join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + stub(&bin, "systemctl", "exit 3"); + let flysim = stub(root, "flysim-build", &format!("[ \"$1\" = --print-compatibility ] && echo \"{COMPAT}\"")); + (format!("{}:/usr/bin:/bin", bin.display()), flysim) +} + +fn loop_reset_list(root: &Path, state: &Path) -> Vec { + let (path, flysim) = tools(root); + let env_file = root.join("fly.env"); + std::fs::write(&env_file, "").unwrap(); + let out = Command::new(repo().join("infra/bin/fly-loop-reset")) + .arg("--list") + .env_clear() + .env("PATH", path) + .env("FLY_LOOP_RESET_TEST_STATE_DIR", state) + .env("FLY_LOOP_RESET_TEST_ENV_FILE", &env_file) + .env("FLY_LOOP_RESET_TEST_FLYSIM", &flysim) + .env("FLY_LOOP_RESET_TEST_LIVE_FLYSIM", &flysim) + .output() + .expect("fly-loop-reset runs"); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + String::from_utf8_lossy(&out.stdout).split_whitespace().map(|r| r.parse().unwrap()).collect() +} + +fn reset_to_milestone(root: &Path, durable: &Path, hot: &Path, rank: u32) { + let (path, _) = tools(root); + let out = Command::new(repo().join("infra/bin/fly-reset-to-milestone")) + .arg(rank.to_string()) + .env_clear() + .env("PATH", path) + .env("FLY_STATE_DIR", durable) + .env("FLY_STATE_HOT_DIR", hot) + .env("FLY_BIN", env!("CARGO_BIN_EXE_flysim")) + .env("FLY_USER", "no-such-user-state02") + .output() + .expect("fly-reset-to-milestone runs"); + assert!( + out.status.success(), + "{}\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); +} + +fn gate() -> RestoreGate { + RestoreGate { + rom_sha256: "ab".repeat(32), + compatibility: COMPAT.to_owned(), + migrates_from: Vec::new(), + accepted: Vec::new(), + } +} + +fn session_restore(hot: &Path, durable: &Path) -> Box> { + let runtime = tokio::runtime::Builder::new_current_thread().build().unwrap(); + let selection = runtime.block_on(lc::restore_from_store( + &Store::new(hot, 8), + &Store::new(durable, 8), + &gate(), + |checkpoint| async move { lc::halves(&checkpoint, &id("ep1"), &id("best"), 48_000) }, + )); + match selection { + Selection::Restored(restored) => restored, + other => panic!("the session runtime should restore: {other:?}"), + } +} + +fn spent(best: u64) -> RatchetState { + RatchetState { best, attempts: 2, recoveries: 5, ..RatchetState::default() } +} + +#[test] +fn a_store_the_session_runtime_writes_is_reset_by_the_legacy_tools() { + let root = tempfile::tempdir().unwrap(); + let mut checkpointer = LegacyCheckpointer::open(config(root.path())).unwrap(); + let (hot, durable) = (root.path().join("hot"), root.path().join("state")); + + // The session runtime's own journal, with its boot header. + let mut sugar = SugarJournal::new(&hot); + sugar.boot(&BootHeader { + runtime: "fly-session".to_owned(), + start_frame: 11, + brain_ms: 9_010.0, + origin: "fresh start".to_owned(), + generation: None, + compatibility: COMPAT.to_owned(), + wall_ms: 1, + }); + sugar.record(&Entry { + frame: 40, + brain_ms: 9_040.0, + input: Input::Sugar { duration_ms: 300.0 }, + by: "viewer", + source: "test", + event_id: 1, + wall_ms: 1, + }); + + // A run: a startup save, two climbs, hot copies and durable intervals in between. + save(&mut checkpointer, SaveKind::Durable, 10, spent(2)); + assert_eq!(checkpointer.observe_rank(3, 9_020.0), Some(RankChange::Climbed(3))); + save(&mut checkpointer, SaveKind::Milestone(3), 20, spent(3)); + save(&mut checkpointer, SaveKind::Hot, 25, spent(3)); + assert_eq!(checkpointer.observe_rank(5, 9_050.0), Some(RankChange::Climbed(5))); + save(&mut checkpointer, SaveKind::Milestone(5), 50, spent(5)); + save(&mut checkpointer, SaveKind::Durable, 60, spent(5)); + save(&mut checkpointer, SaveKind::Hot, 65, spent(5)); + checkpointer.close(); + + // fly-loop-reset reads the compatibility out of the session runtime's archives. + assert_eq!(loop_reset_list(root.path(), &durable), vec![3, 5]); + // `flysim --print-state-compatibility` does too. + assert_eq!(store::state_compatibility(&durable).as_deref(), Some(COMPAT)); + + // fly-reset-to-milestone 3, the real script and the real binary. + reset_to_milestone(root.path(), &durable, &hot, 3); + assert!(!durable.join("milestone-5.checkpoint").exists()); + assert!(!hot.join(journal::FILE_NAME).exists(), "the reset clears the sugar journal"); + + // The legacy order and the session runtime agree on what comes back: rung 3, budget back. + let legacy_first = store::restore_order(&Store::new(&hot, 8), &Store::new(&durable, 8)); + let legacy = store::load(&legacy_first[0].path).unwrap(); + let restored = session_restore(&hot, &durable); + assert_eq!(restored.candidate, legacy_first[0]); + assert_eq!(restored.installed.task.ratchet.best, 3); + assert_eq!( + (restored.installed.task.ratchet.attempts, restored.installed.task.ratchet.recoveries), + (0, 0) + ); + assert_eq!(restored.installed.world.boundary, 20); + assert_eq!(restored.installed.agent, legacy.agent); + + // The session runtime carries on over the reset store: generations above everything, and + // its own first climb is archived again (a new process's best). + let mut checkpointer = LegacyCheckpointer::open(config(root.path())).unwrap(); + assert!(checkpointer.next_generation() > legacy.runtime.generation); + checkpointer.restored(3, restored.installed.host.rank_since_ms); + assert_eq!(checkpointer.observe_rank(4, 9_100.0), Some(RankChange::Climbed(4))); + save(&mut checkpointer, SaveKind::Milestone(4), 90, spent(4)); + checkpointer.close(); + assert_eq!(loop_reset_list(root.path(), &durable), vec![3, 4]); +} + +#[test] +fn a_store_the_legacy_loop_wrote_and_the_tools_reset_is_restored_by_the_session_runtime() { + let root = tempfile::tempdir().unwrap(); + let (hot, durable) = (root.path().join("hot"), root.path().join("state")); + let legacy_hot = Store::new(&hot, 8); + let legacy_durable = Store::new(&durable, 8); + // Exactly what `Sim`'s writer thread commits. + let bytes = |generation: u64, k: u64, ratchet: RatchetState| { + store::encode( + &agent(9_000.0 + k as f64), + &RuntimeState { + generation, + wall_ms: 1, + rom_sha256: "ab".repeat(32), + emulator_frame: k + 1, + compatibility: COMPAT.to_owned(), + speed: 1.0, + buttons: 0, + rank_since_ms: 0.0, + last_event_id: k, + reward: serde_json::Value::Null, + ratchet, + emulator: vec![(k % 251) as u8; 256], + framebuffer: vec![9; FRAMEBUFFER_LEN], + ratchet_game: vec![1; 32], + ratchet_frame: vec![4; FRAMEBUFFER_LEN], + }, + ) + .unwrap() + }; + legacy_durable.commit(1, &bytes(1, 10, spent(2)), None).unwrap(); + legacy_durable.commit(2, &bytes(2, 20, spent(2)), Some(2)).unwrap(); + legacy_durable.commit(3, &bytes(3, 30, spent(4)), Some(4)).unwrap(); + legacy_hot.commit(4, &bytes(4, 35, spent(4)), None).unwrap(); + + assert_eq!(loop_reset_list(root.path(), &durable), vec![2, 4]); + reset_to_milestone(root.path(), &durable, &hot, 2); + + let restored = session_restore(&hot, &durable); + assert_eq!(restored.installed.world.boundary, 20); + assert_eq!(restored.installed.task.ratchet.best, 2); + assert_eq!(restored.installed.task.ratchet.attempts, 0); + // And what the session runtime would save from it is the legacy bytes again. + let halves = &restored.installed; + let again = lc::export_states(&halves.agent, &halves.world, &id("best"), &halves.task, &halves.host) + .unwrap(); + assert_eq!(again, std::fs::read(&restored.candidate.path).unwrap()); +} From d211e53fab7a1c858bc929640adb89266133d4f3 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 16:26:07 +0000 Subject: [PATCH 4/6] docs: STATE-02 in the implementation guide and the legacy-gameboy-v1 section 16 amendment (2026-09-29) --- .../session-framework/implementation.md | 115 ++++++++++++++++++ .../session-framework/legacy-gameboy-v1.md | 33 +++++ 2 files changed, 148 insertions(+) diff --git a/docs/design/session-framework/implementation.md b/docs/design/session-framework/implementation.md index b0b02bd..ce8904c 100644 --- a/docs/design/session-framework/implementation.md +++ b/docs/design/session-framework/implementation.md @@ -353,6 +353,121 @@ for new epoch metadata; corrupt any participant and installation fails as a grou reply doesn't advance durable metadata; failure during activation cannot resume half a world. Checkpoint queue stress remains bounded; verify old media/parser data cannot cross recovery. +### STATE-02 — The legacy composition's checkpoints in `FLYSIM01` (port slice) + +**2026-09-29: built** on `port/state-02` off `port/integration` and awaiting review. The operator's +decision of 2026-09-23 makes `FLYSIM01` the format of record until RETIRE-01, and the session +runtime exports it on every durable save ([legacy-gameboy-v1](legacy-gameboy-v1.md) section 16). +This slice is that export, the import back, the store policy and the restore selection. It adds +no `FLYSESS1` production file. Nothing in `flysim`'s frame, checkpoint bytes or compatibility +string changes. + +- **One store, two runtimes.** `flysim`'s `store.rs` and `journal.rs` move unchanged into the new + crate `flysim-store`, which `flysim` re-exports (`flysim::store`, `flysim::journal`) and + `fly-session` links. Both runtimes write through the one `store::encode` and commit through the + one `Store`, so they share the envelope bytes, the generations, `manifest.json`, the + `milestone-` archives, `keep_generations` rotation and the restore order by construction. +- **Export** (`fly-session::legacy_checkpoint`). A `FLYSIM01` file is assembled from its owners' + halves: the agent's `FLYAGT01` capture payload (the seven agent chunks, the remainder already the + accumulator's), the world's `FLYENV01` payload (emulator, frame on screen, joypad, frame + counter, cartridge digest, and slot `best` as `ratchetGame`/`ratchetFrame`), the task's + `{reward, ratchet}` and the host's `{generation, wallMs, compatibility, speed, rankSinceMs, + lastEventId}`. `runtime_state` builds the legacy `RuntimeState` field for field as + `Sim::snapshot_state` does. +- **Import.** `split`/`halves` read a `FLYSIM01` file back into those halves. `agent_payload` is + the shipped form of AGENT-01's `seed_from_legacy_state` prototype. It builds the `FLYAGT01` + payload a replacement agent stages, using the same encoder the worker's own capture uses + (`legacy_agent::encode_payload`). The accumulator is `{remainder, executedTicks = network.ms, + warmupOffset = 2500}`, and `learning.updates` starts at `plasticity.updates` + (`legacy_reinforcements`, section 13 amendment). The payload also carries the file's + `framebuffer` as an `inputFrame` chunk, which `State.StageRestore` installs as the next input. + `LegacyFrame::restore` re-projects the framebuffer and does not keep the saved visual drive, + and the two differ on the row 65 yard survey checkpoint (found here; see the section 13 + amendment). `world_payload` is ENV-01's `FLYENV01` from + the same world. The source scope of both is `(session, "legacy", emulatorFrame - 1)`. + `legacy_parity` now seeds its workers through this import. +- **Store policy.** `LegacyCheckpointer` follows `Sim` at each call site: + - one generation counter over both stores, starting above the highest either has allocated; + - a hot copy every `hot_seconds`, and a durable one every `checkpoint_seconds`, which also + restarts the hot interval; + - a durable save for a climb, archived as `milestone-` when the rank is above every rank + this process has archived (`best_archived_rank`, per process as in the legacy loop); + - rank tracking as in `track_rank`; + - encoding and fsyncs on a writer thread. +- **Restore selection.** `restore_from_store` walks `store::restore_order`: hot latest, hot + previous, durable latest, durable previous, then the archives by descending rank, each as its + generation and then as its `milestone-` file. It checks the legacy gate: the cartridge, and + `flybrain_gb::compatibility::decide` with `FLY_ACCEPT_ADAPTERS`. It moves to the next candidate + on *any* refusal, including a participant's `State.StageRestore`. It reports `Fresh` when no + candidate exists, and `Refused` when every candidate failed. In that case the runtime must exit + as `Sim::restore_or_warm_up` does. +- **Sugar journal** (the FND-01 review note, before SHADOW-01). A per-process boot header + records the runtime, start frame, brain ms, restore origin, generation and compatibility. The + journal rotates at 4 MiB and keeps three files; every rotated-in file starts with a + `continues` line. `journal::clear` removes the journal. `flysim` writes the header at boot, and + `flysim --reset-to-milestone` clears the journal after it has copied both stores aside. + `read_segments` cuts the journal into per-process segments. `read` still returns input lines + only. + +**Boundary order the session host must keep** (section 16, and section 11 step 6). At `Ready(k+1)` +the order is: + +1. `Environment.SaveSlot`, if one is due. +2. The milestone capture, if the rank climbed. +3. The rollback, if one was requested. +4. The durable capture after the rollback, then the hot and durable interval saves. + +The capture itself uses `State.Capture` on the world and the agent at the same committed +boundary, plus the task's ledger, `{reward, ratchet, slotFilled}` (`TaskHalf::to_ledger`). Wiring +it into the coordinator and the boot-time restore path is left to the legacy composition's +coordinator (TASK-01); this slice ships the pieces and proves them on the workers. + +**Proof** (flysim `tests/state_02.rs`, `tests/state_02_store.rs`; `fly-session` +`legacy_checkpoint` unit tests): + +- *legacy -> session -> legacy on 18 real checkpoints* (every distinct rom-env checkpoint, which + includes the row 64, row 65 and row 67 ones). Each file is split and the world is restored + into the real environment worker and captured again. The agent goes through the imported + `FLYAGT01` payload and the task through the Pokémon adapter and the ratchet. Every export is + byte-identical to the legacy loop's own restore outcome of the same file, checkpointed at once. + Six exports are byte-identical to the file itself. The other twelve differ in named fields + only. Eleven were written by adapters v5 or v6, and the adapter's import migrates their + `reward` state. One, a survey checkpoint, also has a joypad byte in the emulator state that + its own `buttons` field does not match; both runtimes apply `buttons` on restore. +- *Restore then continue, toy connectome, raw mode* (every ROM run). The legacy frame writes a + checkpoint. The session runtime selects it from a store whose hot copy is torn. The legacy + loop and the session runtime then each run 600 frames from it. World: 1,800 values identical + to `FLY_TRACE` (frame, WRAM). Agent: 600 transitions identical (ticks, clock, exact remainder, + rates, spikes, decision). The session runtime's export at the last boundary is byte-identical + to the legacy loop's checkpoint of that boundary. That export also survives session -> legacy + -> session unchanged: a fresh legacy loop restores it and checkpoints the same bytes, and a + fresh world and agent import it and export the same bytes. +- *The same with `gameboy-legacy-fafb-v783-v1` in macros mode* from the row 67 checkpoint, with + sugar and a ratchet rollback (`FLY_STATE02_FAFB=1`). Four checkpoints were run for 1,800 frames + each: rows 58, 64 and 67, and the row 65 yard survey. Each run has 5,400 world values and 1,800 + agent transitions identical to the trace, with 2 sugar and 1 rollback. Each export is + byte-identical to the legacy checkpoint and survives session -> legacy -> session. +- *The tools, both ways* (`tests/state_02_store.rs`, the real `infra/bin` scripts and the real + binary). `fly-loop-reset --list` and `--print-state-compatibility` read a store the session + runtime wrote. `fly-reset-to-milestone` promotes its rung with the recovery budget back and + clears the journal. The legacy order and the session runtime then choose the same candidate, + and the session runtime carries on above every generation and archives its next climb. The + other way round, the session runtime restores a store the legacy writer wrote and the tool + reset, and it would save it as the same bytes. + +**Not in this slice, and why:** + +- *The coordinator hook and the boot-time restore.* Both need the legacy composition's + bootstrap, which is TASK-01's. The restore order is Initialize-free: stage and activate the + world, have the task install `{reward, ratchet}` and observe O[k] for the first context + (`{boot, bound, location: null}`), then build the agent's payload with that context + (`agent_payload`) and stage and activate it. +- *The task's per-frame half in the proofs.* The executor and the task's evaluation are TASK-01's. + The proofs take the joypad masks from the trace and the task's end-of-run `{reward, ratchet}` + from the legacy loop. +- *Declared difference, archive order* (sections 4 and 16). A session-runtime milestone archive + holds the post-capture ratchet and slot. It is excluded from the shadow comparison. + ### PUBLISH-01 — Committed snapshots and observer isolation **Depends on:** SESSION-02, MEDIA-01; public v2 contract work is a separate prerequisite to diff --git a/docs/design/session-framework/legacy-gameboy-v1.md b/docs/design/session-framework/legacy-gameboy-v1.md index 32c1410..6cd6313 100644 --- a/docs/design/session-framework/legacy-gameboy-v1.md +++ b/docs/design/session-framework/legacy-gameboy-v1.md @@ -544,6 +544,39 @@ current `flysim` reads, under the unchanged compatibility string. The deploy gat checkpoint may be written beside it, but it is not what a restore selects until RETIRE-01 says so. +**Amendment, 2026-09-29 (STATE-02).** Five readings of this section, fixed by building it +([implementation guide](implementation.md) STATE-02): + +- *"A FLYSIM01 envelope that the current `flysim` reads" means the same bytes.* The session + runtime writes through the legacy loop's own encoder and store, which now live in the crate + `flysim-store` that both link. For the same state it writes the same bytes, and it keeps the + same generations, `manifest.json`, `milestone-` archives, rotation and restore order. The + owners of the fields are: the agent (the seven agent chunks, the remainder), the environment + (`emulator`, `framebuffer`, `emulatorFrame`, `buttons`, `romHash`, and slot `best` as + `ratchetGame` and `ratchetFrame`), the task (`reward`, `ratchet`) and the host (`generation`, + `wallMs`, `compatibility`, `speed`, `rankSinceMs`, `lastEventId`). +- *The milestone archive is per process, as in the legacy loop.* A rank climb is archived when + the rank is above every rank *this process* has archived. After a restart, the first climb + rewrites `milestone-` even if an older process had archived that rank. That is the + legacy behaviour, and the reset tools rely on the newest archive of a rung. +- *A restore is the legacy restore, candidate for candidate.* The candidate order is hot latest, + hot previous, durable latest, durable previous, then the archives by descending rank. The gate + is the cartridge and the compatibility decision. A refusal at any step, including a + participant's `State.StageRestore`, moves to the next candidate. If every candidate fails, the + runtime does not start. The world applies the recorded `buttons` on restore, as + `LegacyFrame::restore` does, so a file whose emulator state disagrees with its own `buttons` + restores to the same state in both runtimes, not to the file's bytes. +- *The visual drive after a `FLYSIM01` import is the framebuffer's projection* (a correction to + section 13's *Restore*, "the two are the same values"). They are the same on stream + checkpoints. On the row 65 yard survey checkpoint they are not: the first transition's rates + and spikes differed from the legacy loop's. The import therefore carries the framebuffer in + the agent payload (chunk `inputFrame`), and `State.StageRestore` installs it after the import, + as `LegacyFrame::restore` does. A worker's own capture carries no such chunk and restores + exactly. +- *The sugar journal is the shadow run's input record.* It gets a per-process boot header, is + rotated at 4 MiB with three kept files, and `fly-reset-to-milestone` clears it + (`flysim-store::journal`). It is not a checkpoint and nothing restores from it. + ## 17. PROF-02b: MaleCNS bundles (later) Dataset manifests, original-ID mapping, anatomical roles, sensory and readout bindings, strict From f0981825a0a2df14535f87562c48ba1c2616a2ca Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 17:17:56 +0000 Subject: [PATCH 5/6] FLYSIM01 carries the reinforcement count; the import takes its ids from the file; StageRestore refuses conflicts before building a network AGENT-01 review: learning.updates fell back to plasticity.updates on every FLYSIM01 round trip. Both runtimes now count reinforcement calls the same way (one per commit while the rule is enabled) and write the count as the optional manifest member reinforcements, which old readers ignore and old files lack (a reader then starts from plasticity.updates, once). The import's checkpoint id is the file's generation (flysim01-g), and the agent worker checks for a staged or activated restore before it builds the replacement network. --- .../crates/fly-session/src/legacy_agent.rs | 57 ++++++++----- .../fly-session/src/legacy_checkpoint.rs | 81 +++++++++++++++++-- .../crates/fly-session/src/legacy_parity.rs | 24 +++++- .../flysim/crates/flysim-store/src/store.rs | 20 +++++ services/flysim/crates/flysim/src/frame.rs | 13 +++ services/flysim/crates/flysim/src/reset.rs | 1 + services/flysim/crates/flysim/src/simloop.rs | 1 + .../crates/flysim/tests/compat_migration.rs | 1 + .../flysim/crates/flysim/tests/state_02.rs | 8 +- .../crates/flysim/tests/state_02_store.rs | 25 +++++- services/flysim/crates/flysim/tests/store.rs | 1 + 11 files changed, 193 insertions(+), 39 deletions(-) diff --git a/services/flysim/crates/fly-session/src/legacy_agent.rs b/services/flysim/crates/fly-session/src/legacy_agent.rs index 876fc8c..3367247 100644 --- a/services/flysim/crates/fly-session/src/legacy_agent.rs +++ b/services/flysim/crates/fly-session/src/legacy_agent.rs @@ -312,6 +312,19 @@ pub fn encode_payload( encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| e.to_string()) } +/// The reinforcement calls a `FLYAGT01` capture payload records (`learning.updates`). +pub fn decode_payload_reinforcements(bytes: &[u8]) -> Result { + let parts = decode_envelope(bytes, PAYLOAD_MAGIC) + .map_err(|e| format!("not a {PAYLOAD_MAGIC} envelope: {e}"))?; + let session = parts.manifest.get("session").ok_or("the agent payload has no session member")?; + let session: Value = serde_json::from_str(&session.stringify()).map_err(|e| e.to_string())?; + session + .get("reinforcements") + .and_then(Value::as_str) + .and_then(|text| text.parse().ok()) + .ok_or_else(|| "the agent payload has no reinforcement count".to_owned()) +} + /// The agent state a `FLYAGT01` capture payload carries, with the accumulator's remainder in it. /// The `session` member is not validated here; `State.StageRestore` does that. pub fn decode_payload_state(bytes: &[u8]) -> Result { @@ -1536,6 +1549,29 @@ impl LegacyAgentWorker { if !state.warmed_up { return Err(incompatible("the staged agent state was never warmed up")); } + // The conflicts first: a worker already holding a staged restore, or a token already + // activated, is refused before a replacement network is built for nothing. + if let Some(staged) = &self.staged { + return Err(DomainError::before( + ErrorCode::Conflict, + format!( + "this worker already holds the staged restore {} for checkpoint {}", + staged.token, staged.checkpoint_id + ), + )); + } + let token = crate::agent::restore_token( + ¶ms.checkpoint_id, + &scope, + &actual, + &self.config.incarnation_id, + ); + if self.activated.contains(&token) { + return Err(DomainError::before( + ErrorCode::Conflict, + "this exact restore was already activated on this worker", + )); + } // A replacement fly: the dataset is loaded and checked here, not trusted. let dataset = self.dataset()?; let (mut agent, graph) = self.build_agent(dataset.clone(), seed)?; @@ -1560,27 +1596,6 @@ impl LegacyAgentWorker { } agent.network.set_visual_frame(frame, width, height); } - if let Some(staged) = &self.staged { - return Err(DomainError::before( - ErrorCode::Conflict, - format!( - "this worker already holds the staged restore {} for checkpoint {}", - staged.token, staged.checkpoint_id - ), - )); - } - let token = crate::agent::restore_token( - ¶ms.checkpoint_id, - &scope, - &actual, - &self.config.incarnation_id, - ); - if self.activated.contains(&token) { - return Err(DomainError::before( - ErrorCode::Conflict, - "this exact restore was already activated on this worker", - )); - } self.staged = Some(StagedAgent { token: token.clone(), checkpoint_id: params.checkpoint_id.clone(), diff --git a/services/flysim/crates/fly-session/src/legacy_checkpoint.rs b/services/flysim/crates/fly-session/src/legacy_checkpoint.rs index 8ff27ad..7e0210a 100644 --- a/services/flysim/crates/fly-session/src/legacy_checkpoint.rs +++ b/services/flysim/crates/fly-session/src/legacy_checkpoint.rs @@ -112,6 +112,9 @@ pub struct HostHalf { #[derive(Clone, Debug)] pub struct Halves { pub agent: AgentState, + /// The agent's reinforcement calls (`learning.updates`): the file's `reinforcements`, or + /// [`legacy_reinforcements`] for a file from before the counter. + pub reinforcements: u64, pub world: WorldState, pub task: TaskHalf, pub host: HostHalf, @@ -132,6 +135,7 @@ pub fn world_state(world_payload: &[u8]) -> Result { /// The `FLYSIM01` runtime fields of one boundary, exactly as `Sim::snapshot_state` fills them. pub fn runtime_state( + reinforcements: u64, world: &WorldState, slot_id: &Id, task: &TaskHalf, @@ -158,6 +162,7 @@ pub fn runtime_state( last_event_id: host.last_event_id, reward: task.reward.clone(), ratchet: task.ratchet, + reinforcements: Some(reinforcements), emulator, framebuffer, ratchet_game, @@ -169,12 +174,14 @@ pub fn runtime_state( /// and the host's. pub fn export_states( agent: &AgentState, + reinforcements: u64, world: &WorldState, slot_id: &Id, task: &TaskHalf, host: &HostHalf, ) -> Result, String> { - store::encode(agent, &runtime_state(world, slot_id, task, host)).map_err(|e| format!("{e:#}")) + store::encode(agent, &runtime_state(reinforcements, world, slot_id, task, host)) + .map_err(|e| format!("{e:#}")) } /// The `FLYSIM01` envelope of one boundary, from the two participants' capture payloads. @@ -186,8 +193,9 @@ pub fn export( host: &HostHalf, ) -> Result, String> { let agent = agent_state(agent_payload)?; + let reinforcements = legacy_agent::decode_payload_reinforcements(agent_payload)?; let world = world_state(world_payload)?; - export_states(&agent, &world, slot_id, task, host) + export_states(&agent, reinforcements, &world, slot_id, task, host) } // ------------------------------------------------------------------------------------------- @@ -213,6 +221,9 @@ pub fn halves( } .into_state(episode_id, slot_id, audio_sample_rate)?; Ok(Halves { + reinforcements: runtime + .reinforcements + .unwrap_or_else(|| legacy_reinforcements(&checkpoint.agent)), agent: checkpoint.agent.clone(), world, task: TaskHalf { @@ -288,6 +299,7 @@ pub struct AgentImport { /// outcome and not to its own bytes (`legacy-gameboy-v1` section 16 amendment of 2026-09-29). pub fn agent_payload( state: &AgentState, + reinforcements: u64, frame_on_screen: &[u8], import: &AgentImport, checkpoint_id: &Id, @@ -304,7 +316,7 @@ pub fn agent_payload( committed_step: source_scope.step, profile: &import.profile, seed: import.seed, - reinforcements: legacy_reinforcements(state), + reinforcements, macro_channels: &import.macro_channels, }, &accumulator, @@ -329,6 +341,12 @@ pub fn world_payload( }) } +/// The checkpoint id of the payloads imported from a `FLYSIM01` file: its generation, so two +/// imports of one file name the same checkpoint and imports of two files never do. +pub fn import_checkpoint_id(generation: u64) -> Id { + id(&format!("flysim01-g{generation}")) +} + /// The scope a payload made from a `FLYSIM01` file records as its source: the session, the /// [`LEGACY_SOURCE_EPOCH`] and the world's boundary. pub fn legacy_source_scope(session_id: &Id, boundary: u64) -> Scope { @@ -852,7 +870,7 @@ mod tests { fn the_export_is_the_legacy_encoder_on_the_same_values_and_splits_back_into_its_halves() { let agent = agent(9_000.0, 0.75, 3.0); let world = world_at(12_344, true); - let bytes = export_states(&agent, &world, &id("best"), &task(), &host(4)).unwrap(); + let bytes = export_states(&agent, 55, &world, &id("best"), &task(), &host(4)).unwrap(); // Field for field what `Sim::snapshot_state` builds, through the one encoder. let legacy = store::encode( &agent, @@ -868,6 +886,7 @@ mod tests { last_event_id: 77, reward: task().reward, ratchet: task().ratchet, + reinforcements: Some(55), emulator: vec![7; 64], framebuffer: vec![9; FRAMEBUFFER_LEN], ratchet_game: vec![1, 2, 3], @@ -878,11 +897,12 @@ mod tests { assert_eq!(bytes, legacy); let back = split(&bytes, &id("ep1"), &id("best"), 48_000).unwrap(); assert_eq!(back.agent, agent); + assert_eq!(back.reinforcements, 55); assert_eq!(back.world, world); assert_eq!(back.task, task()); assert_eq!(back.host, host(4)); // And no slot is an empty ratchet snapshot, both ways. - let bytes = export_states(&agent, &world_at(5, false), &id("best"), &task(), &host(1)).unwrap(); + let bytes = export_states(&agent, 3, &world_at(5, false), &id("best"), &task(), &host(1)).unwrap(); let back = split(&bytes, &id("ep1"), &id("best"), 48_000).unwrap(); assert!(back.world.slots.is_empty()); } @@ -899,13 +919,13 @@ mod tests { }; let scope = legacy_source_scope(&id("s1"), world.boundary); let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed(); - let agent_bytes = agent_payload(&agent, &world.framebuffer, &import, &id("c1"), &scope, &context).unwrap(); + let agent_bytes = agent_payload(&agent, 70, &world.framebuffer, &import, &id("c1"), &scope, &context).unwrap(); let world_bytes = world_payload(&world, &id("world"), &id("c1"), &scope, &"cd".repeat(32)); assert_eq!(agent_state(&agent_bytes).unwrap(), agent); assert_eq!(world_state(&world_bytes).unwrap(), world); assert_eq!( export(&agent_bytes, &world_bytes, &id("best"), &task(), &host(9)).unwrap(), - export_states(&agent, &world, &id("best"), &task(), &host(9)).unwrap() + export_states(&agent, 70, &world, &id("best"), &task(), &host(9)).unwrap() ); assert!(export(&world_bytes, &agent_bytes, &id("best"), &task(), &host(9)).is_err()); } @@ -935,6 +955,7 @@ mod tests { gameboy::ReadoutContext { boot: true, bound: vec![], location: None }.to_typed(); let bytes = agent_payload( &state, + legacy_reinforcements(&state), &[0; FRAMEBUFFER_LEN], &import, &id("c1"), @@ -958,6 +979,50 @@ mod tests { assert_eq!(session["accumulator"]["warmupOffset"], "2500"); } + #[test] + fn the_reinforcement_count_survives_every_round_trip_and_starts_at_the_lower_bound_once() { + // A file from before the counter: the import starts at plasticity.updates. + let agent = agent(9_000.0, 0.75, 40.0); + let world = world_at(10, true); + let mut runtime = runtime_state(0, &world, &id("best"), &task(), &host(1)); + runtime.reinforcements = None; + let old = store::encode(&agent, &runtime).unwrap(); + let halves = split(&old, &id("ep1"), &id("best"), 48_000).unwrap(); + assert_eq!(halves.reinforcements, 40); + // The session runs on and counts 900 more calls than the gains moved; the export carries + // them, and every later import, legacy or session, starts where the last one stopped. + let bytes = export_states(&agent, 940, &world, &id("best"), &task(), &host(2)).unwrap(); + let again = split(&bytes, &id("ep1"), &id("best"), 48_000).unwrap(); + assert_eq!(again.reinforcements, 940); + let import = AgentImport { + agent_id: id("fly"), + profile: gameboy::profile_asset_ref(), + seed: 22_222, + macro_channels: Vec::new(), + }; + let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed(); + let payload = agent_payload( + &again.agent, + again.reinforcements, + &again.world.framebuffer, + &import, + &import_checkpoint_id(again.host.generation), + &legacy_source_scope(&id("s1"), again.world.boundary), + &context, + ) + .unwrap(); + assert_eq!(crate::legacy_agent::decode_payload_reinforcements(&payload).unwrap(), 940); + let world_bytes = world_payload( + &again.world, + &id("world"), + &import_checkpoint_id(again.host.generation), + &legacy_source_scope(&id("s1"), again.world.boundary), + &"cd".repeat(32), + ); + assert_eq!(export(&payload, &world_bytes, &id("best"), &again.task, &again.host).unwrap(), bytes); + assert_eq!(import_checkpoint_id(2), id("flysim01-g2")); + } + #[test] fn the_task_ledger_carries_exactly_the_reward_and_the_ratchet() { let ledger = task().to_ledger(true); @@ -984,7 +1049,7 @@ mod tests { let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed(); LegacyCapture { boundary, - agent_payload: agent_payload(&agent, &world.framebuffer, &import, &id("c"), &scope, &context) + agent_payload: agent_payload(&agent, 3, &world.framebuffer, &import, &id("c"), &scope, &context) .unwrap(), world_payload: world_payload(&world, &id("world"), &id("c"), &scope, &"cd".repeat(32)), task: task(), diff --git a/services/flysim/crates/fly-session/src/legacy_parity.rs b/services/flysim/crates/fly-session/src/legacy_parity.rs index 07af25f..24d5f41 100644 --- a/services/flysim/crates/fly-session/src/legacy_parity.rs +++ b/services/flysim/crates/fly-session/src/legacy_parity.rs @@ -1462,6 +1462,20 @@ impl AgentDriver { agent_id: &Id, initial_frame: usize, state: &flybrain_core::agent::AgentState, + ) -> Result { + self.seed_with_reinforcements(rig, agent_id, initial_frame, state, legacy_reinforcements(state)) + .await + } + + /// [`AgentDriver::seed_from_legacy_state`] with the reinforcement count a `FLYSIM01` file + /// records (`legacy_checkpoint::Halves::reinforcements`). + pub async fn seed_with_reinforcements( + &mut self, + rig: &mut LegacyRig, + agent_id: &Id, + initial_frame: usize, + state: &flybrain_core::agent::AgentState, + reinforcements: u64, ) -> Result { self.initialize(initial_frame).await?; let template = self.capture().await?; @@ -1478,6 +1492,7 @@ impl AgentDriver { }; let bytes = crate::legacy_checkpoint::agent_payload( state, + reinforcements, &self.frames[initial_frame], &import, &template.result.checkpoint_id, @@ -1544,6 +1559,7 @@ pub async fn run_on_worker_from( script: &LegacyScript, start: Option<&flybrain_core::agent::AgentState>, ) -> Result, String> { + let start = start.map(|state| (state, legacy_reinforcements(state))); run_script(rig, agent_id, script, start, false) .await .map(|(records, _)| records) @@ -1555,7 +1571,7 @@ pub async fn run_on_worker_from_then_capture( rig: &mut LegacyRig, agent_id: &Id, script: &LegacyScript, - start: Option<&flybrain_core::agent::AgentState>, + start: Option<(&flybrain_core::agent::AgentState, u64)>, ) -> Result<(Vec, Vec), String> { let (records, captured) = run_script(rig, agent_id, script, start, true).await?; Ok((records, captured.expect("a capture was asked for"))) @@ -1565,15 +1581,15 @@ async fn run_script( rig: &mut LegacyRig, agent_id: &Id, script: &LegacyScript, - start: Option<&flybrain_core::agent::AgentState>, + start: Option<(&flybrain_core::agent::AgentState, u64)>, capture_at_end: bool, ) -> Result<(Vec, Option>), String> { let mut driver = rig.driver(agent_id, script); let first = match start { None => driver.initialize(script.initial_frame).await?, - Some(state) => { + Some((state, reinforcements)) => { driver - .seed_from_legacy_state(rig, agent_id, script.initial_frame, state) + .seed_with_reinforcements(rig, agent_id, script.initial_frame, state, reinforcements) .await? } }; diff --git a/services/flysim/crates/flysim-store/src/store.rs b/services/flysim/crates/flysim-store/src/store.rs index 586e6c0..2e4e562 100644 --- a/services/flysim/crates/flysim-store/src/store.rs +++ b/services/flysim/crates/flysim-store/src/store.rs @@ -290,6 +290,11 @@ pub struct RuntimeState { /// The adapter's own lifetime reward state. pub reward: serde_json::Value, pub ratchet: flybrain_gb::RatchetState, + /// Reinforcement calls the fly has had: one per committed frame while the rule is enabled, + /// zero sums included (the session runtime's `learning.updates`). An optional manifest member + /// since STATE-02 (2026-09-29): a file without it predates the counter, and a reader starts + /// from its `plasticity.updates`, a lower bound. Readers that do not know it ignore it. + pub reinforcements: Option, pub emulator: Vec, pub framebuffer: Vec, /// The ratchet's best safe snapshot, if it has one. @@ -322,6 +327,9 @@ pub fn encode( manifest.set("lastEventId", (runtime.last_event_id as f64).into()); manifest.set("reward", to_json_value(&runtime.reward)?); manifest.set("ratchet", to_json_value(&serde_json::to_value(runtime.ratchet)?)?); + if let Some(reinforcements) = runtime.reinforcements { + manifest.set("reinforcements", (reinforcements as f64).into()); + } let mut chunks = parts.chunks; chunks.push((EMULATOR_CHUNK.to_string(), runtime.emulator.clone())); @@ -389,6 +397,7 @@ pub fn decode(bytes: &[u8]) -> Result { last_event_id: number("lastEventId").unwrap_or(0.0) as u64, reward, ratchet, + reinforcements: number("reinforcements").ok().map(|n| n as u64), emulator: chunk(EMULATOR_CHUNK)?, framebuffer: chunk(FRAMEBUFFER_CHUNK)?, ratchet_game: chunk(RATCHET_GAME_CHUNK)?, @@ -456,6 +465,7 @@ mod tests { last_event_id: 77, reward: serde_json::json!({ "version": 3, "total": 1.25 }), ratchet: flybrain_gb::RatchetState { best: 3, ..Default::default() }, + reinforcements: Some(1_234), emulator: vec![7; 64], framebuffer: vec![9; 32], ratchet_game: vec![1, 2, 3], @@ -524,6 +534,16 @@ mod tests { assert_eq!(encode(&back.agent, &back.runtime).unwrap(), bytes); } + #[test] + fn a_file_without_the_reinforcement_count_still_reads_and_writes_as_before() { + let runtime = RuntimeState { reinforcements: None, ..runtime(4) }; + let bytes = encode(&agent_state(), &runtime).unwrap(); + assert!(!String::from_utf8_lossy(&bytes[..4096.min(bytes.len())]).contains("reinforcements")); + let back = decode(&bytes).unwrap(); + assert_eq!(back.runtime.reinforcements, None); + assert_eq!(encode(&back.agent, &back.runtime).unwrap(), bytes); + } + #[test] fn a_corrupted_or_truncated_envelope_is_rejected() { let bytes = encode(&agent_state(), &runtime(1)).unwrap(); diff --git a/services/flysim/crates/flysim/src/frame.rs b/services/flysim/crates/flysim/src/frame.rs index 8b023c8..d916a56 100644 --- a/services/flysim/crates/flysim/src/frame.rs +++ b/services/flysim/crates/flysim/src/frame.rs @@ -198,6 +198,11 @@ pub struct LegacyFrame { pub location: Option<(u32, u32, u32)>, pub held_channel: Option, pub blocked_since_ms: f64, + /// Reinforcement calls since the fly's fresh start: one per commit while the rule is + /// enabled, zero sums included; checkpointed (`reinforcements`, STATE-02). It is the session + /// agent's `learning.updates`, counted the same way, so a checkpoint carries it across both + /// runtimes. Counting changes nothing the fly does. + pub reinforcements: u64, trace: Option, } @@ -219,6 +224,7 @@ impl LegacyFrame { location: None, held_channel: None, blocked_since_ms: 0.0, + reinforcements: 0, trace: None, } } @@ -248,6 +254,7 @@ impl LegacyFrame { .map_err(|error| anyhow!("running the first frame: {error}"))?; self.frame_buffer.copy_from_slice(emulator.framebuffer()); self.frame_counter = 1; + self.reinforcements = 0; let audio = emulator.take_audio_u8(); agent .warmup(Some(&self.frame_buffer)) @@ -305,6 +312,11 @@ impl LegacyFrame { .map_err(|error| anyhow!("{error}"))?; self.remainder = checkpoint.agent.remainder; + // A file from before the counter starts it at the recorded `plasticity.updates`, a lower + // bound (legacy-gameboy-v1 section 13 amendment of 2026-09-29). + self.reinforcements = runtime + .reinforcements + .unwrap_or(checkpoint.agent.network.plasticity.updates as u64); self.frame_counter = runtime.emulator_frame; self.buttons = runtime.buttons; self.frame_buffer.copy_from_slice(&runtime.framebuffer); @@ -576,6 +588,7 @@ impl LegacyFrame { } if agent.network.plasticity.enabled { agent.network.plasticity.reinforce(total, ms); + self.reinforcements += 1; } } diff --git a/services/flysim/crates/flysim/src/reset.rs b/services/flysim/crates/flysim/src/reset.rs index 3256270..c142541 100644 --- a/services/flysim/crates/flysim/src/reset.rs +++ b/services/flysim/crates/flysim/src/reset.rs @@ -326,6 +326,7 @@ mod tests { }, }; let runtime = store::RuntimeState { + reinforcements: None, generation, wall_ms: 1_700_000_000_000, rom_sha256: "ab".repeat(32), diff --git a/services/flysim/crates/flysim/src/simloop.rs b/services/flysim/crates/flysim/src/simloop.rs index 7604081..f83d831 100644 --- a/services/flysim/crates/flysim/src/simloop.rs +++ b/services/flysim/crates/flysim/src/simloop.rs @@ -1396,6 +1396,7 @@ impl Sim { last_event_id: self.log.next_id().saturating_sub(1), reward: self.adapter.export_state(), ratchet: self.ratchet.state, + reinforcements: Some(self.frame.reinforcements), emulator: self .emulator .export_state() diff --git a/services/flysim/crates/flysim/tests/compat_migration.rs b/services/flysim/crates/flysim/tests/compat_migration.rs index 2234d56..cf70694 100644 --- a/services/flysim/crates/flysim/tests/compat_migration.rs +++ b/services/flysim/crates/flysim/tests/compat_migration.rs @@ -113,6 +113,7 @@ fn v6_checkpoint() -> Vec { }, }; let runtime = RuntimeState { + reinforcements: None, generation: 41, wall_ms: 1_790_000_000_000, rom_sha256: flybrain_gb::pokemon_red::SUPPORTED_ROM.to_string(), diff --git a/services/flysim/crates/flysim/tests/state_02.rs b/services/flysim/crates/flysim/tests/state_02.rs index a23b39a..984009f 100644 --- a/services/flysim/crates/flysim/tests/state_02.rs +++ b/services/flysim/crates/flysim/tests/state_02.rs @@ -127,6 +127,7 @@ fn first_difference(left: &[u8], right: &[u8]) -> String { ("lastEventId", a.runtime.last_event_id == b.runtime.last_event_id), ("reward", a.runtime.reward == b.runtime.reward), ("ratchet", a.runtime.ratchet == b.runtime.ratchet), + ("reinforcements", a.runtime.reinforcements == b.runtime.reinforcements), ("emulator", a.runtime.emulator == b.runtime.emulator), ("framebuffer", a.runtime.framebuffer == b.runtime.framebuffer), ("ratchetGame", a.runtime.ratchet_game == b.runtime.ratchet_game), @@ -290,6 +291,7 @@ async fn every_real_checkpoint_round_trips_legacy_session_legacy() { let restored_context = ReadoutContext { boot: false, bound: vec![], location: None }; let agent_bytes = lc::agent_payload( &halves.agent, + halves.reinforcements, &halves.world.framebuffer, &import, &id("c1"), @@ -328,6 +330,7 @@ async fn every_real_checkpoint_round_trips_legacy_session_legacy() { let legacy = store::encode( &checkpoint.agent, &RuntimeState { + reinforcements: Some(halves.reinforcements), emulator: emulator.export_state().expect("the emulator exports"), reward: legacy_task.reward, ratchet: legacy_task.ratchet, @@ -453,6 +456,7 @@ impl LegacyWorld { last_event_id: host.last_event_id, reward: self.adapter.export_state(), ratchet: self.ratchet.state, + reinforcements: Some(self.frame.reinforcements), emulator: self.emulator.export_state().expect("the emulator exports"), framebuffer: self.frame.frame_buffer.clone(), ratchet_game: self.ratchet.game().map(<[u8]>::to_vec).unwrap_or_default(), @@ -650,7 +654,7 @@ async fn restore_then_continue( &mut agents, &id("fly"), &script, - Some(&halves.agent), + Some((&halves.agent, halves.reinforcements)), ) .await .expect("the agent runs"); @@ -693,7 +697,7 @@ async fn restore_then_continue( &mut agents, &id("fly"), &one_step, - Some(&again.agent), + Some((&again.agent, again.reinforcements)), ) .await .expect("the agent imports the export"); diff --git a/services/flysim/crates/flysim/tests/state_02_store.rs b/services/flysim/crates/flysim/tests/state_02_store.rs index 89b10e5..df8541f 100644 --- a/services/flysim/crates/flysim/tests/state_02_store.rs +++ b/services/flysim/crates/flysim/tests/state_02_store.rs @@ -105,7 +105,7 @@ fn capture(k: u64, ratchet: RatchetState) -> LegacyCapture { let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed(); LegacyCapture { boundary: k, - agent_payload: lc::agent_payload(&agent(9_000.0 + k as f64), &world(k).framebuffer, &import, &id("c"), &scope, &context) + agent_payload: lc::agent_payload(&agent(9_000.0 + k as f64), 17 + k, &world(k).framebuffer, &import, &id("c"), &scope, &context) .unwrap(), world_payload: lc::world_payload(&world(k), &id("world"), &id("c"), &scope, &"cd".repeat(32)), task: TaskHalf { reward: serde_json::Value::Null, ratchet }, @@ -306,6 +306,7 @@ fn a_store_the_legacy_loop_wrote_and_the_tools_reset_is_restored_by_the_session_ last_event_id: k, reward: serde_json::Value::Null, ratchet, + reinforcements: None, emulator: vec![(k % 251) as u8; 256], framebuffer: vec![9; FRAMEBUFFER_LEN], ratchet_game: vec![1; 32], @@ -328,7 +329,23 @@ fn a_store_the_legacy_loop_wrote_and_the_tools_reset_is_restored_by_the_session_ assert_eq!(restored.installed.task.ratchet.attempts, 0); // And what the session runtime would save from it is the legacy bytes again. let halves = &restored.installed; - let again = lc::export_states(&halves.agent, &halves.world, &id("best"), &halves.task, &halves.host) - .unwrap(); - assert_eq!(again, std::fs::read(&restored.candidate.path).unwrap()); + // And the session runtime would save it as the legacy loop's own restore would: the same + // bytes plus the reinforcement count the legacy loop now also writes (from the lower bound). + assert_eq!(halves.reinforcements, 17); + let again = lc::export_states( + &halves.agent, + halves.reinforcements, + &halves.world, + &id("best"), + &halves.task, + &halves.host, + ) + .unwrap(); + let file = store::load(&restored.candidate.path).unwrap(); + let expected = store::encode( + &file.agent, + &RuntimeState { reinforcements: Some(17), ..file.runtime }, + ) + .unwrap(); + assert_eq!(again, expected); } diff --git a/services/flysim/crates/flysim/tests/store.rs b/services/flysim/crates/flysim/tests/store.rs index 983a1e9..536c336 100644 --- a/services/flysim/crates/flysim/tests/store.rs +++ b/services/flysim/crates/flysim/tests/store.rs @@ -67,6 +67,7 @@ fn agent_state() -> flybrain_core::agent::AgentState { fn checkpoint(generation: u64, frame: u64, rom: &str, compatibility: &str) -> Vec { let runtime = RuntimeState { + reinforcements: None, generation, wall_ms: 1_757_000_000_000 + generation, rom_sha256: rom.to_string(), From 0d41cc2003030171b5fd3fe026b523447c735189 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 17:18:10 +0000 Subject: [PATCH 6/6] docs: STATE-02, the reinforcement count in FLYSIM01 and the import's ids --- .../session-framework/implementation.md | 27 ++++++++++++++----- .../session-framework/legacy-gameboy-v1.md | 10 +++++-- 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/docs/design/session-framework/implementation.md b/docs/design/session-framework/implementation.md index ce8904c..146e5e7 100644 --- a/docs/design/session-framework/implementation.md +++ b/docs/design/session-framework/implementation.md @@ -378,14 +378,25 @@ string changes. the shipped form of AGENT-01's `seed_from_legacy_state` prototype. It builds the `FLYAGT01` payload a replacement agent stages, using the same encoder the worker's own capture uses (`legacy_agent::encode_payload`). The accumulator is `{remainder, executedTicks = network.ms, - warmupOffset = 2500}`, and `learning.updates` starts at `plasticity.updates` - (`legacy_reinforcements`, section 13 amendment). The payload also carries the file's + warmupOffset = 2500}`. `learning.updates` is the file's `reinforcements`. A file from before + that member starts at `plasticity.updates` once (`legacy_reinforcements`, section 13 + amendment). The checkpoint id is the file's generation (`flysim01-g`). No template worker + is involved. This fixes the four points the AGENT-01 review raised against the prototype: + template dependence, borrowed ids, no compatibility gate (the gate is `restore_from_store`'s, + below), and the count falling back on every round trip. The payload also carries the file's `framebuffer` as an `inputFrame` chunk, which `State.StageRestore` installs as the next input. `LegacyFrame::restore` re-projects the framebuffer and does not keep the saved visual drive, and the two differ on the row 65 yard survey checkpoint (found here; see the section 13 amendment). `world_payload` is ENV-01's `FLYENV01` from the same world. The source scope of both is `(session, "legacy", emulatorFrame - 1)`. `legacy_parity` now seeds its workers through this import. +- **`reinforcements`, an optional `FLYSIM01` manifest member.** `LegacyFrame` now counts + reinforcement calls the way the agent worker does: one per commit while the rule is enabled, + zero sums included. `Sim` writes the count, and `LegacyFrame::restore` reads it (falling back + to `plasticity.updates`), so the count survives every round trip in either runtime. Readers + that predate it ignore it. The member changes no behaviour and not the compatibility string, + but it does change legacy checkpoint bytes: a file written from now on is the old layout plus + this member. - **Store policy.** `LegacyCheckpointer` follows `Sim` at each call site: - one generation counter over both stores, starting above the highest either has allocated; - a hot copy every `hot_seconds`, and a durable one every `checkpoint_seconds`, which also @@ -401,6 +412,8 @@ string changes. on *any* refusal, including a participant's `State.StageRestore`. It reports `Fresh` when no candidate exists, and `Refused` when every candidate failed. In that case the runtime must exit as `Sim::restore_or_warm_up` does. +- **The agent worker** now refuses a conflicting stage (a restore already staged, or a token + already activated) before it builds a replacement network (AGENT-01 review). - **Sugar journal** (the FND-01 review note, before SHADOW-01). A per-process boot header records the runtime, start frame, brain ms, restore origin, generation and compatibility. The journal rotates at 4 MiB and keeps three files; every rotated-in file starts with a @@ -430,10 +443,12 @@ coordinator (TASK-01); this slice ships the pieces and proves them on the worker into the real environment worker and captured again. The agent goes through the imported `FLYAGT01` payload and the task through the Pokémon adapter and the ratchet. Every export is byte-identical to the legacy loop's own restore outcome of the same file, checkpointed at once. - Six exports are byte-identical to the file itself. The other twelve differ in named fields - only. Eleven were written by adapters v5 or v6, and the adapter's import migrates their - `reward` state. One, a survey checkpoint, also has a joypad byte in the emulator state that - its own `buttons` field does not match; both runtimes apply `buttons` on restore. + Against the files themselves, every export differs only in named fields. All 18 gain + `reinforcements`, because the files predate it. Twelve written by adapters v5 or v6 also + differ in `reward`, which the adapter's import migrates. One survey checkpoint also differs in + a joypad byte of its emulator state that its own `buttons` field does not match; both runtimes + apply `buttons` on restore. Before the counter was added, six of the 18 were byte-identical to + the file. - *Restore then continue, toy connectome, raw mode* (every ROM run). The legacy frame writes a checkpoint. The session runtime selects it from a store whose hot copy is torn. The legacy loop and the session runtime then each run 600 frames from it. World: 1,800 values identical diff --git a/docs/design/session-framework/legacy-gameboy-v1.md b/docs/design/session-framework/legacy-gameboy-v1.md index 6cd6313..dac77af 100644 --- a/docs/design/session-framework/legacy-gameboy-v1.md +++ b/docs/design/session-framework/legacy-gameboy-v1.md @@ -544,7 +544,7 @@ current `flysim` reads, under the unchanged compatibility string. The deploy gat checkpoint may be written beside it, but it is not what a restore selects until RETIRE-01 says so. -**Amendment, 2026-09-29 (STATE-02).** Five readings of this section, fixed by building it +**Amendment, 2026-09-29 (STATE-02).** Six readings of this section, fixed by building it ([implementation guide](implementation.md) STATE-02): - *"A FLYSIM01 envelope that the current `flysim` reads" means the same bytes.* The session @@ -554,7 +554,8 @@ says so. owners of the fields are: the agent (the seven agent chunks, the remainder), the environment (`emulator`, `framebuffer`, `emulatorFrame`, `buttons`, `romHash`, and slot `best` as `ratchetGame` and `ratchetFrame`), the task (`reward`, `ratchet`) and the host (`generation`, - `wallMs`, `compatibility`, `speed`, `rankSinceMs`, `lastEventId`). + `wallMs`, `compatibility`, `speed`, `rankSinceMs`, `lastEventId`); the agent's reinforcement + count, `reinforcements`, is new (below). - *The milestone archive is per process, as in the legacy loop.* A rank climb is archived when the rank is above every rank *this process* has archived. After a restart, the first climb rewrites `milestone-` even if an older process had archived that rank. That is the @@ -573,6 +574,11 @@ says so. the agent payload (chunk `inputFrame`), and `State.StageRestore` installs it after the import, as `LegacyFrame::restore` does. A worker's own capture carries no such chunk and restores exactly. +- *`learning.updates` is carried in `FLYSIM01`.* This corrects section 13's *Learning telemetry* + amendment, which started every import at `plasticity.updates` and so dropped the count on + every round trip. Both runtimes count reinforcement calls the same way and write the count + as the optional manifest member `reinforcements`. A file without it (every file from before + 2026-09-29) starts at `plasticity.updates` once. - *The sugar journal is the shadow run's input record.* It gets a per-process boot header, is rotated at 4 MiB with three kept files, and `fly-reset-to-milestone` clears it (`flysim-store::journal`). It is not a checkpoint and nothing restores from it.