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.
This commit is contained in:
acamilo 2026-09-29 15:31:13 +00:00
parent ae878ede41
commit 32631e2d02
11 changed files with 1268 additions and 814 deletions

View file

@ -508,6 +508,7 @@ dependencies = [
"flybrain-core", "flybrain-core",
"flybrain-gb", "flybrain-gb",
"flybus", "flybus",
"flysim-store",
"futures-util", "futures-util",
"jsonschema", "jsonschema",
"serde", "serde",
@ -523,6 +524,19 @@ dependencies = [
"unicode-normalization", "unicode-normalization",
] ]
[[package]]
name = "flysim-store"
version = "0.1.1"
dependencies = [
"anyhow",
"flybrain-core",
"flybrain-gb",
"serde",
"serde_json",
"tempfile",
"tracing",
]
[[package]] [[package]]
name = "foldhash" name = "foldhash"
version = "0.2.0" version = "0.2.0"

View file

@ -8,6 +8,7 @@ members = [
"crates/flybrain-gb", "crates/flybrain-gb",
"crates/flybus", "crates/flybus",
"crates/flysim", "crates/flysim",
"crates/flysim-store",
] ]
[workspace.package] [workspace.package]

View file

@ -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"

View file

@ -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<u64>,
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<File>,
/// 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<Value>,
}
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-<index>.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<usize> {
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<Vec<Value>> {
let text = std::fs::read_to_string(path)?;
Ok(text
.lines()
.filter_map(|line| serde_json::from_str::<Value>(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<Value>,
pub inputs: Vec<Value>,
}
/// 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<Vec<Segment>> {
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::<usize>().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<Segment> = 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::<Value>(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<u64> = 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<String> = 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());
}
}

View file

@ -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;

View file

@ -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 `<gen>.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-<rank>.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<u64>,
/// The generation to restore if `latest` will not load.
pub previous: Option<u64>,
/// Best-rank archives, rank to generation. Their files are never rotated away.
pub archives: BTreeMap<u32, u64>,
}
impl StoreManifest {
fn record(&mut self, generation: u64, archive_rank: Option<u32>) {
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<u64> {
let mut out: Vec<u64> = 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<u64>,
}
/// A checkpoint directory: `<gen>.checkpoint`, `milestone-<rank>.checkpoint`, `manifest.json`.
#[derive(Debug, Clone)]
pub struct Store {
dir: PathBuf,
keep_generations: usize,
}
impl Store {
pub fn new(dir: impl Into<PathBuf>, 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<StoreManifest> {
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<Candidate> {
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<u32>,
) -> Result<StoreManifest> {
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<PathBuf> {
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<u64> = 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-<rank>.checkpoint` is an independent file, so it is not a generation.
fn parse_generation(name: &str) -> Option<u64> {
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<u8>,
pub framebuffer: Vec<u8>,
/// The ratchet's best safe snapshot, if it has one.
pub ratchet_game: Vec<u8>,
pub ratchet_frame: Vec<u8>,
}
/// 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<Vec<u8>> {
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<Checkpoint> {
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<String> {
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<f64> {
manifest
.get(key)
.and_then(JsonValue::as_f64)
.ok_or_else(|| anyhow::anyhow!("checkpoint manifest is missing {key}"))
};
let chunk = |name: &str| -> Result<Vec<u8>> {
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<Checkpoint> {
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> {
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<String> {
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<Candidate> {
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<String> =
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");
}
}

View file

@ -31,6 +31,8 @@ cuda = ["flybrain-core/cuda"]
flybrain-core = { path = "../flybrain-core" } flybrain-core = { path = "../flybrain-core" }
flybrain-gb = { path = "../flybrain-gb" } flybrain-gb = { path = "../flybrain-gb" }
flybus = { path = "../flybus" } 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" anyhow = "1.0"
axum = { version = "0.8", features = ["ws"] } axum = { version = "0.8", features = ["ws"] }

View file

@ -1,176 +1,6 @@
//! The sugar journal: every admitted audience input, stamped with the frame it was applied before. //! 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 //! The code lives in the `flysim-store` crate, which the session runtime links too (STATE-02).
//! part of a checkpoint and nothing reads it back into the fly: it is the record a shadow run //! This module re-exports it.
//! (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.
use std::fs::{File, OpenOptions}; pub use flysim_store::journal::*;
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<File>,
}
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<Vec<Value>> {
let text = std::fs::read_to_string(path)?;
Ok(text
.lines()
.filter_map(|line| serde_json::from_str::<Value>(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);
}
}

View file

@ -32,6 +32,10 @@
//! talked, reached, pushed-back) are memory-only by contract //! talked, reached, pushed-back) are memory-only by contract
//! (`docs/design/macros.md` section 12.1: "a restored run offers every target once more"), //! (`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. //! 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::collections::BTreeMap;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@ -161,6 +165,11 @@ pub fn reset_to_milestone(
memory-only and are reset by stopping flysim)" 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) Ok(report)
} }
@ -379,6 +388,21 @@ mod tests {
}; };
state_dir(&durable, &[3, 5, 9, 11], spent); state_dir(&durable, &[3, 5, 9, 11], spent);
state_dir(&hot, &[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 archive = tmp.path().join("archive-20260922");
let report = reset_to_milestone(&durable, &hot, 5, &archive).unwrap(); 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.jsonl").exists());
assert!(!durable.join("events-20260921.jsonl").exists()); assert!(!durable.join("events-20260921.jsonl").exists());
assert!(!hot.join("milestone-11.checkpoint").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. // Both stores restore the rung, and the counters are back.
for store in [Store::new(&hot, KEEP_GENERATIONS), Store::new(&durable, KEEP_GENERATIONS)] { for store in [Store::new(&hot, KEEP_GENERATIONS), Store::new(&durable, KEEP_GENERATIONS)] {

View file

@ -389,6 +389,9 @@ pub struct Sim {
compatibility: String, compatibility: String,
semantic_rewards: bool, semantic_rewards: bool,
restored: 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<u64>),
/// Per-phase timing, off unless `FLY_PROFILE_SECONDS` is set (`crate::profile`). /// Per-phase timing, off unless `FLY_PROFILE_SECONDS` is set (`crate::profile`).
profiler: Profiler, profiler: Profiler,
} }
@ -595,6 +598,7 @@ impl Sim {
compatibility, compatibility,
semantic_rewards, semantic_rewards,
restored: false, restored: false,
boot_origin: ("fresh start".to_string(), None),
profiler: Profiler::from_env(now), profiler: Profiler::from_env(now),
agent, agent,
emulator, emulator,
@ -641,6 +645,17 @@ impl Sim {
// the whole warm-up — or, after a restore, every neuron that has ever fired, since the // the whole warm-up — or, after a restore, every neuron that has ever fired, since the
// checkpoint's `lastSpikeMs` values are absolute brain milliseconds. // checkpoint's `lastSpikeMs` values are absolute brain milliseconds.
sim.last_publish_ms = sim.agent.network.ms; 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; sim.status = FeedStatus::Running;
// A durable commit immediately after startup or restore (section 8), so the 300-second // 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 // interval is a ceiling on routine loss only, and so a broken write path is found now
@ -685,6 +700,7 @@ impl Sim {
"restored" "restored"
); );
self.restored = true; self.restored = true;
self.boot_origin = (candidate.origin.clone(), candidate.generation);
self.emit(NewEvent::new( self.emit(NewEvent::new(
FeedEventKind::System, FeedEventKind::System,
format!("Restored from {}", candidate.origin), format!("Restored from {}", candidate.origin),

View file

@ -1,645 +1,8 @@
//! Checkpoint persistence: the `FLYSIM01` envelope, the atomic commit, the generations and the //! Checkpoint persistence: the `FLYSIM01` envelope, the atomic commit, the generations and the
//! milestone archives. //! milestone archives.
//! //!
//! `docs/design/flysim.md` section 8, as amended by the contract override at the top of that //! The code lives in the `flysim-store` crate, which the session runtime links too (STATE-02), so
//! document: //! both write byte-identical checkpoints into the same store. This module re-exports it, and every
//! //! `flysim::store` path keeps working.
//! - 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 `<gen>.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-<rank>.checkpoint`, which later
//! rotations never unlink.
use std::collections::BTreeMap; pub use flysim_store::store::*;
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<u64>,
/// The generation to restore if `latest` will not load.
pub previous: Option<u64>,
/// Best-rank archives, rank to generation. Their files are never rotated away.
pub archives: BTreeMap<u32, u64>,
}
impl StoreManifest {
fn record(&mut self, generation: u64, archive_rank: Option<u32>) {
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<u64> {
let mut out: Vec<u64> = 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<u64>,
}
/// A checkpoint directory: `<gen>.checkpoint`, `milestone-<rank>.checkpoint`, `manifest.json`.
#[derive(Debug, Clone)]
pub struct Store {
dir: PathBuf,
keep_generations: usize,
}
impl Store {
pub fn new(dir: impl Into<PathBuf>, 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<StoreManifest> {
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<Candidate> {
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<u32>,
) -> Result<StoreManifest> {
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<PathBuf> {
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<u64> = 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-<rank>.checkpoint` is an independent file, so it is not a generation.
fn parse_generation(name: &str) -> Option<u64> {
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<u8>,
pub framebuffer: Vec<u8>,
/// The ratchet's best safe snapshot, if it has one.
pub ratchet_game: Vec<u8>,
pub ratchet_frame: Vec<u8>,
}
/// 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<Vec<u8>> {
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<Checkpoint> {
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<String> {
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<f64> {
manifest
.get(key)
.and_then(JsonValue::as_f64)
.ok_or_else(|| anyhow::anyhow!("checkpoint manifest is missing {key}"))
};
let chunk = |name: &str| -> Result<Vec<u8>> {
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<Checkpoint> {
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> {
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<String> {
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<Candidate> {
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<String> =
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");
}
}