diff --git a/services/flysim/crates/fly-legacy-session/Cargo.toml b/services/flysim/crates/fly-legacy-session/Cargo.toml index dba2810..11b3ce4 100644 --- a/services/flysim/crates/fly-legacy-session/Cargo.toml +++ b/services/flysim/crates/fly-legacy-session/Cargo.toml @@ -11,6 +11,11 @@ description = "The live fly's composition on the session framework: the pokered- name = "fly_legacy_session" path = "src/lib.rs" +# SHADOW-01: the session runtime run beside the live fly (`infra/units/flyshadow.service`). +[[bin]] +name = "fly-shadow" +path = "src/bin/fly-shadow.rs" + [dependencies] # The session framework and its legacy workers (AGENT-01, ENV-01). fly-session = { path = "../fly-session" } @@ -22,7 +27,7 @@ flysim = { path = "../flysim" } flybrain-gb = { path = "../flybrain-gb" } flybrain-core = { path = "../flybrain-core" } serde_json = { workspace = true } -tokio = { version = "1", features = ["rt", "rt-multi-thread", "sync", "time", "macros"] } +tokio = { version = "1", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] } [dev-dependencies] tempfile = "3" diff --git a/services/flysim/crates/fly-legacy-session/examples/reward_bearing.rs b/services/flysim/crates/fly-legacy-session/examples/reward_bearing.rs new file mode 100644 index 0000000..166b292 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/examples/reward_bearing.rs @@ -0,0 +1,39 @@ +//! `reward_bearing IN OUT`: a copy of a FLYSIM01 checkpoint with its adapter ledger thinned so the +//! real brain earns rewards where the fly already stands -- the current map unvisited (an `AREA` +//! payout on the first sample), its exits unfound (`boundary`), its ground unwalked +//! (`exploration`), no wild win a replay (`battle`). TASK-01's brain arm +//! (`tests/session_trace.rs`), as a file for SHADOW-01's rehearsal (`tools/shadow-rehearsal.sh`), +//! where the real service restores it. A test fixture, never a stream checkpoint. + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let [input, output] = args.as_slice() else { + eprintln!("usage: reward_bearing IN OUT"); + std::process::exit(2); + }; + let bytes = std::fs::read(input).expect("the checkpoint reads"); + let mut checkpoint = flysim::store::decode(&bytes).expect("FLYSIM01"); + let reward = &mut checkpoint.runtime.reward; + let map = reward["location"] + .as_str() + .and_then(|l| l.split(':').next()) + .unwrap_or("0") + .to_owned(); + if let Some(seen) = reward["seen"].as_array_mut() { + seen.retain(|key| { + let key = key.as_str().unwrap_or(""); + key != format!("map:{map}") && !key.starts_with(&format!("boundary:{map}:")) + }); + } + if let Some(tiles) = reward["tiles"].as_array_mut() { + tiles.retain(|tile| !tile.as_str().unwrap_or("").starts_with(&format!("{map}:"))); + } + if let Some(counts) = reward["tileCounts"].as_object_mut() { + counts.remove(&map); + } + reward["wildWins"] = serde_json::json!({}); + reward["replayBlocked"] = serde_json::json!([]); + let out = flysim::store::encode(&checkpoint.agent, &checkpoint.runtime).expect("encodes"); + std::fs::write(output, out).expect("the copy writes"); + eprintln!("thinned map {map}: {output}"); +} diff --git a/services/flysim/crates/fly-legacy-session/src/bin/fly-shadow.rs b/services/flysim/crates/fly-legacy-session/src/bin/fly-shadow.rs new file mode 100644 index 0000000..5c4ceb9 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/bin/fly-shadow.rs @@ -0,0 +1,327 @@ +//! `fly-shadow`: SHADOW-01, the session runtime run beside the live fly. +//! +//! ```text +//! fly-shadow run [options] follow the live trace, compare, write the verdict (the unit) +//! fly-shadow check [options] exit 0 only if the verdict allows the cutover (CUT-01's hook) +//! ``` +//! +//! `run` reads the live service's own configuration the way flysim does (`/etc/fly/fly.env` through +//! the unit's `EnvironmentFile`, `FLY_STATE`, `FLY_STATE_HOT`, ...): the cartridge, the dataset, the +//! stores (read only), the macro mode, the speed and the metrics listener. Options: +//! +//! | Option | Default | +//! | --- | --- | +//! | `--trace-dir DIR` | `$FLY_TRACE_DIR` | +//! | `--out DIR` | `$FLY_SHADOW_DIR`: `verdict.json`, `divergence.json` | +//! | `--spool DIR` | `/spool` | +//! | `--work DIR` | `$FLY_SHADOW_WORK`, else `/work`: sockets and artifact stores | +//! | `--mode in-process\|thread\|process` | `in-process` | +//! | `--threads N` | `$FLY_SHADOW_THREADS`, else 2: the shadow agent's sweep threads | +//! | `--required-brain-seconds S` | 10800 | +//! | `--max-live-lag-seconds S` | 0.5; the shadow pauses 60 s whenever the live `fly_lag_seconds` grew by more than S within 30 s (0 disables) | +//! | `--metrics HOST:PORT` | the live metrics listener | +//! | `--spool-max-mib N` | 512 | +//! | `--context N` | 30 transition pairs before a divergence | +//! | `--all-files` | follow every trace file present, oldest first (a rehearsal) | +//! | `--keep-traces` | keep compared trace files | +//! | `--keep-spool` | keep every spooled live checkpoint (a rehearsal replays them) | +//! | `--exit-on-pass` | exit once the verdict is `pass` | +//! | `--max-transitions N` | stop after N compared transitions | +//! +//! Exit status: 0 passed or stopped, 3 diverged, 2 the shadow's own error. +//! +//! `check --verdict FILE [--binary FILE] [--compatibility STRING] [--max-age-seconds N]`: the +//! cutover rule of `fly_legacy_session::shadow::verdict`. `--binary` is the session-runtime binary +//! CUT-01 switches to (default: `fly-session` beside this executable); it must be one of the +//! shadowed release's binaries by name and SHA-256. `--compatibility` defaults to this build's +//! legacy compatibility string. + +use std::path::PathBuf; +use std::time::Duration; + +use fly_legacy_session::shadow::{self, LagGuard, ShadowConfig, StopFlag, verdict}; +use fly_session::ExecutionMode; + +fn usage() -> ! { + eprintln!("usage: fly-shadow run [options] | fly-shadow check --verdict FILE [options]"); + std::process::exit(2); +} + +fn die(message: impl std::fmt::Display) -> ! { + eprintln!("fly-shadow: {message}"); + std::process::exit(2); +} + +struct Args(Vec); + +impl Args { + fn flag(&mut self, name: &str) -> bool { + match self.0.iter().position(|a| a == name) { + Some(i) => { + self.0.remove(i); + true + } + None => false, + } + } + + fn value(&mut self, name: &str) -> Option { + let i = self.0.iter().position(|a| a == name)?; + if i + 1 >= self.0.len() { + die(format!("{name} needs a value")); + } + let value = self.0.remove(i + 1); + self.0.remove(i); + Some(value) + } + + fn parsed(&mut self, name: &str) -> Option { + self.value(name).map(|v| { + v.parse() + .unwrap_or_else(|_| die(format!("{name}: cannot parse {v:?}"))) + }) + } + + fn done(self) { + if !self.0.is_empty() { + die(format!("unknown arguments: {:?}", self.0)); + } + } +} + +fn env_path(name: &str) -> Option { + std::env::var_os(name) + .filter(|v| !v.is_empty()) + .map(PathBuf::from) +} + +fn file_sha256(path: &std::path::Path) -> String { + let bytes = std::fs::read(path).unwrap_or_else(|e| die(format!("{}: {e}", path.display()))); + shadow::sha256_hex(&bytes) +} + +fn this_binary() -> PathBuf { + std::env::current_exe().unwrap_or_else(|e| die(format!("current_exe: {e}"))) +} + +/// SHA-256 of the release binaries beside this one, by name. +fn release_binaries() -> std::collections::BTreeMap { + let dir = this_binary() + .parent() + .map(PathBuf::from) + .unwrap_or_default(); + ["fly-shadow", "fly-session", "flysim", "fly-edge"] + .iter() + .filter_map(|name| { + let path = dir.join(name); + path.is_file() + .then(|| ((*name).to_owned(), file_sha256(&path))) + }) + .collect() +} + +fn main() { + let mut argv: Vec = std::env::args().skip(1).collect(); + if argv.is_empty() { + usage(); + } + let command = argv.remove(0); + let mut args = Args(argv); + match command.as_str() { + "run" => run(args), + "check" => { + let verdict_path: PathBuf = args + .value("--verdict") + .map(PathBuf::from) + .unwrap_or_else(|| usage()); + let binary = args.value("--binary").map_or_else( + || this_binary().with_file_name("fly-session"), + PathBuf::from, + ); + let compatibility = args.value("--compatibility"); + let max_age: i64 = args.parsed("--max-age-seconds").unwrap_or(300); + args.done(); + let compatibility = compatibility.unwrap_or_else(|| { + let config = flysim::config::Config::load(None).unwrap_or_else(|e| die(e)); + flysim::simloop::compatibility_string(&config).unwrap_or_else(|e| die(e)) + }); + let text = std::fs::read_to_string(&verdict_path) + .unwrap_or_else(|e| die(format!("{}: {e}", verdict_path.display()))); + let value: serde_json::Value = + serde_json::from_str(&text).unwrap_or_else(|e| die(format!("verdict: {e}"))); + let now = verdict::parse_iso(&verdict::now_iso()).expect("now parses"); + let name = binary + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let sha = file_sha256(&binary); + match verdict::allows_cutover(&value, (&name, &sha), &compatibility, now, max_age) { + Ok(()) => println!("cutover allowed: {}", value["reason"]), + Err(reason) => { + println!("cutover refused: {reason}"); + std::process::exit(1); + } + } + } + _ => usage(), + } +} + +fn run(mut args: Args) { + let config = flysim::config::Config::load(None).unwrap_or_else(|e| die(format!("{e:#}"))); + let out_dir = args + .value("--out") + .map(PathBuf::from) + .or_else(|| env_path("FLY_SHADOW_DIR")) + .unwrap_or_else(|| die("--out or FLY_SHADOW_DIR is required")); + let trace_dir = args + .value("--trace-dir") + .map(PathBuf::from) + .or_else(|| env_path(flysim::trace::DIR_ENV)) + .unwrap_or_else(|| die("--trace-dir or FLY_TRACE_DIR is required")); + let spool_dir = args + .value("--spool") + .map(PathBuf::from) + .unwrap_or_else(|| out_dir.join("spool")); + let work_dir = args + .value("--work") + .map(PathBuf::from) + .or_else(|| env_path("FLY_SHADOW_WORK")) + .unwrap_or_else(|| out_dir.join("work")); + let mode = match args.value("--mode").as_deref() { + None | Some("in-process") => ExecutionMode::InProcess, + Some("thread") => ExecutionMode::Thread, + Some("process") => ExecutionMode::Process, + Some(other) => die(format!("--mode {other:?}")), + }; + let agent_threads: usize = args.parsed("--threads").unwrap_or_else(|| { + std::env::var("FLY_SHADOW_THREADS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(2) + }); + let required: f64 = args + .parsed("--required-brain-seconds") + .unwrap_or(shadow::REQUIRED_BRAIN_SECONDS); + let max_lag: f64 = args.parsed("--max-live-lag-seconds").unwrap_or(0.5); + let metrics = args.value("--metrics").or_else(|| { + config.control.metrics_bind.map(|addr| { + if addr.ip().is_unspecified() { + format!("127.0.0.1:{}", addr.port()) + } else { + addr.to_string() + } + }) + }); + let spool_mib: u64 = args.parsed("--spool-max-mib").unwrap_or(512); + let context_lines: usize = args.parsed("--context").unwrap_or(30); + let all_files = args.flag("--all-files"); + let keep_traces = args.flag("--keep-traces"); + let keep_spool = args.flag("--keep-spool"); + let exit_on_pass = args.flag("--exit-on-pass"); + let max_transitions: Option = args.parsed("--max-transitions"); + // Undocumented: the toy connectome, for tests only. + let profile = match args.value("--profile") { + None => fly_session::legacy_agent::LegacyProfileKind::Production, + Some(p) => { + fly_session::legacy_agent::LegacyProfileKind::parse(&p).unwrap_or_else(|e| die(e)) + } + }; + args.done(); + + if config.loop_.game != "pokemon-red" { + die(format!( + "the legacy composition is Pokémon Red, not {:?}", + config.loop_.game + )); + } + if u64::from(config.feed.audio_hz) != fly_session::legacy_env::DEFAULT_AUDIO_RATE { + die(format!( + "the live service's audio rate {} is not the legacy environment's {}", + config.feed.audio_hz, + fly_session::legacy_env::DEFAULT_AUDIO_RATE + )); + } + let lag_guard = (max_lag > 0.0) + .then_some(()) + .and(metrics) + .map(|metrics_addr| LagGuard { + metrics_addr, + growth_seconds: max_lag, + window: Duration::from_secs(30), + back_off: Duration::from_secs(60), + }); + let shadow_config = ShadowConfig { + trace_dir, + hot_dir: config.paths.hot_dir.clone(), + durable_dir: config.paths.save_dir.clone(), + out_dir, + spool_dir, + work_dir, + rom_path: config.paths.rom.clone(), + dataset_dir: config.paths.dataset.clone(), + profile, + macro_mode: config.macros.mode, + speed: config.loop_.speed, + mode, + agent_threads, + required_brain_seconds: required, + all_files, + keep_traces, + keep_spool, + exit_on_pass, + max_transitions, + spool_max_bytes: spool_mib << 20, + context_lines, + poll: Duration::from_millis(100), + lag_guard, + binary_sha256: file_sha256(&this_binary()), + binaries: release_binaries(), + release: this_binary() + .parent() + .and_then(|d| d.canonicalize().ok()) + .map(|d| d.display().to_string()) + .unwrap_or_default(), + }; + eprintln!( + "fly-shadow: {} mode, {} threads, following {} (stores {} and {}, read only)", + mode.label(), + agent_threads, + shadow_config.trace_dir.display(), + shadow_config.hot_dir.display(), + shadow_config.durable_dir.display() + ); + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .unwrap_or_else(|e| die(format!("tokio: {e}"))); + let stop = StopFlag::default(); + let ended = runtime.block_on(async { + let signals = stop.clone(); + tokio::spawn(async move { + use tokio::signal::unix::{SignalKind, signal}; + let mut term = signal(SignalKind::terminate()).expect("SIGTERM"); + let mut int = signal(SignalKind::interrupt()).expect("SIGINT"); + tokio::select! { + _ = term.recv() => {} + _ = int.recv() => {} + } + eprintln!("fly-shadow: stopping"); + signals.request(); + }); + shadow::run(shadow_config, stop).await + }); + match ended { + Ok((shadow::Ended::Diverged, _)) => std::process::exit(3), + Ok((ended, verdict)) => { + eprintln!( + "fly-shadow: {ended:?}; {} transitions ({:.1} brain s) identical, verdict {}", + verdict.agreement.transitions, + verdict.brain_seconds(), + verdict.status.as_str() + ); + } + Err(e) => die(e), + } +} diff --git a/services/flysim/crates/fly-legacy-session/src/lib.rs b/services/flysim/crates/fly-legacy-session/src/lib.rs index d1cda7c..86b694d 100644 --- a/services/flysim/crates/fly-legacy-session/src/lib.rs +++ b/services/flysim/crates/fly-legacy-session/src/lib.rs @@ -7,6 +7,8 @@ //! - [`admission`]: sugar by the legacy rules; the operator reward pulse refused. //! - [`trace`]: the session's `FLY_TRACE`, in the legacy loop's format, and the comparison. //! - [`driver`]: a stub readout for parity runs that must earn rewards. +//! - [`shadow`]: SHADOW-01, the session runtime following the live fly's trace, the comparator and +//! the verdict CUT-01 reads. //! //! `docs/design/session-framework/legacy-gameboy-v1.md` is the contract, `implementation.md` //! TASK-01 the record. @@ -15,5 +17,6 @@ pub mod admission; pub mod composition; pub mod driver; pub mod import; +pub mod shadow; pub mod task; pub mod trace; diff --git a/services/flysim/crates/fly-legacy-session/src/shadow/checkpoint.rs b/services/flysim/crates/fly-legacy-session/src/shadow/checkpoint.rs new file mode 100644 index 0000000..3baaae6 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/shadow/checkpoint.rs @@ -0,0 +1,169 @@ +//! Checkpoint bytes at a live save: the shadow's own export of the same boundary, byte for byte +//! against the file the live service wrote, after the named substitutions. +//! +//! The shadow never writes to the live stores. At a boundary where the live trace records a +//! capture `g`, the shadow takes its own participant-coherent capture of that boundary (in the +//! position the live one had: before or after that boundary's rollback), exports it as FLYSIM01 +//! through the one encoder both runtimes share (STATE-02), and compares the bytes with the live +//! file. The host fields the shadow cannot own are the live file's: `generation`, `wallMs` and +//! `lastEventId` (declared `host-fields`). `compatibility` and `speed` are the shadow's own +//! configuration and `rankSinceMs` its own rank tracking, so a difference in any of them is a +//! divergence. A legacy milestone archive taken before that boundary's slot save +//! (`afterActions` 0 ahead of a `save-slot`) holds the pre-capture ratchet and slot: the live +//! file's `ratchet`, `ratchetGame` and `ratchetFrame` stand in for the shadow's there (declared +//! `archive-order`) and everything else must still be identical. + +use fly_session::legacy_checkpoint::{self, HostHalf, TaskHalf}; +use fly_session::types::id; +use flysim::store; + +/// The shadow's capture of one boundary. +#[derive(Clone, Debug)] +pub struct ShadowCapture { + pub boundary: u64, + pub world_payload: Vec, + pub agent_payload: Vec, + pub task: TaskHalf, + /// The shadow's `rankSinceMs` at the capture. + pub rank_since_ms: f64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Outcome { + Identical, + /// Identical after a declared difference. + Declared, +} + +/// A checkpoint that differs: the explanation and the shadow's export, kept for the review. +#[derive(Debug)] +pub struct Mismatch { + pub detail: String, + pub shadow_bytes: Vec, +} + +/// Compares the live file's bytes with the shadow's export of the same boundary. +pub fn compare( + live: &[u8], + capture: &ShadowCapture, + compatibility: &str, + speed: f64, + archive_order: bool, +) -> Result> { + let fail = |detail: String| { + Box::new(Mismatch { + detail, + shadow_bytes: Vec::new(), + }) + }; + let live_checkpoint = store::decode(live).map_err(|e| fail(format!("the live file: {e:#}")))?; + let host = HostHalf { + generation: live_checkpoint.runtime.generation, + wall_ms: live_checkpoint.runtime.wall_ms, + compatibility: compatibility.to_owned(), + speed, + rank_since_ms: capture.rank_since_ms, + last_event_id: live_checkpoint.runtime.last_event_id, + }; + let mut bytes = legacy_checkpoint::export( + &capture.agent_payload, + &capture.world_payload, + &id(crate::task::SLOT), + &capture.task, + &host, + ) + .map_err(fail)?; + if archive_order { + let mut shadow = + store::decode(&bytes).map_err(|e| fail(format!("the shadow export: {e:#}")))?; + shadow.runtime.ratchet = live_checkpoint.runtime.ratchet; + shadow.runtime.ratchet_game = live_checkpoint.runtime.ratchet_game.clone(); + shadow.runtime.ratchet_frame = live_checkpoint.runtime.ratchet_frame.clone(); + bytes = + store::encode(&shadow.agent, &shadow.runtime).map_err(|e| fail(format!("{e:#}")))?; + } + if bytes == live { + return Ok(if archive_order { + Outcome::Declared + } else { + Outcome::Identical + }); + } + Err(Box::new(Mismatch { + detail: explain(&live_checkpoint, &bytes), + shadow_bytes: bytes, + })) +} + +/// Which members differ, for the divergence report. +fn explain(live: &store::Checkpoint, shadow_bytes: &[u8]) -> String { + let shadow = match store::decode(shadow_bytes) { + Ok(shadow) => shadow, + Err(e) => return format!("the shadow export does not decode: {e:#}"), + }; + let (l, s) = (&live.runtime, &shadow.runtime); + let mut fields = Vec::new(); + macro_rules! field { + ($name:literal, $a:expr, $b:expr) => { + if $a != $b { + fields.push($name); + } + }; + } + field!("romSha256", l.rom_sha256, s.rom_sha256); + field!("emulatorFrame", l.emulator_frame, s.emulator_frame); + field!("compatibility", l.compatibility, s.compatibility); + field!("speed", l.speed, s.speed); + field!("buttons", l.buttons, s.buttons); + field!("rankSinceMs", l.rank_since_ms, s.rank_since_ms); + field!("reward", l.reward, s.reward); + field!("ratchet", l.ratchet, s.ratchet); + field!("reinforcements", l.reinforcements, s.reinforcements); + field!("emulator", l.emulator, s.emulator); + field!("framebuffer", l.framebuffer, s.framebuffer); + field!("ratchetGame", l.ratchet_game, s.ratchet_game); + field!("ratchetFrame", l.ratchet_frame, s.ratchet_frame); + let agent_same = store::encode(&shadow.agent, &live.runtime) + .ok() + .zip(store::encode(&live.agent, &live.runtime).ok()) + .is_some_and(|(a, b)| a == b); + if !agent_same { + fields.push("agent"); + } + let mut detail = format!( + "generation {}: the shadow's export differs from the live file in {}", + live.runtime.generation, + if fields.is_empty() { + "the encoding only".to_owned() + } else { + fields.join(", ") + } + ); + if fields.contains(&"rankSinceMs") { + detail.push_str(&format!( + " (rankSinceMs live {} shadow {})", + l.rank_since_ms, s.rank_since_ms + )); + } + if fields.contains(&"emulator") { + let first = l.emulator.iter().zip(&s.emulator).position(|(a, b)| a != b); + let count = l + .emulator + .iter() + .zip(&s.emulator) + .filter(|(a, b)| a != b) + .count(); + detail.push_str(&format!( + " (emulator: {} vs {} bytes, {count} differ, first at {first:?})", + l.emulator.len(), + s.emulator.len() + )); + } + if fields.contains(&"ratchet") { + detail.push_str(&format!( + " (ratchet live {:?} shadow {:?})", + l.ratchet, s.ratchet + )); + } + detail +} diff --git a/services/flysim/crates/fly-legacy-session/src/shadow/follow.rs b/services/flysim/crates/fly-legacy-session/src/shadow/follow.rs new file mode 100644 index 0000000..36c3407 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/shadow/follow.rs @@ -0,0 +1,142 @@ +//! Following the live service's `FLY_TRACE_DIR`: one file per flysim process, named +//! `trace--.jsonl`, so the names sort in start order. A file is a *segment*: +//! the process that wrote it restored one checkpoint (its startup save names it), ran, and ended +//! where the next file begins. +//! +//! The live recorder buffers about a megabyte, so lines arrive in bursts some seconds late and the +//! last line of a file may be incomplete until the next burst. A reader therefore hands out only +//! complete lines. A file has ended when it has no more complete lines *and* a newer file exists: +//! systemd starts the next process only after the previous one exited, and a process flushes its +//! trace on the way out. A process killed hard loses its unflushed tail; those transitions are +//! simply not compared. + +use std::fs::File; +use std::io::{BufRead, BufReader}; +use std::path::{Path, PathBuf}; + +/// The trace files in `dir`, in start order. +pub fn trace_files(dir: &Path) -> std::io::Result> { + let mut files: Vec = std::fs::read_dir(dir)? + .filter_map(|entry| entry.ok().map(|e| e.path())) + .filter(|path| { + path.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.starts_with("trace-") && n.ends_with(".jsonl")) + }) + .collect(); + files.sort(); + Ok(files) +} + +/// The first trace file in `dir` that sorts after `after` (or the first of all). +pub fn next_file(dir: &Path, after: Option<&Path>) -> std::io::Result> { + Ok(trace_files(dir)? + .into_iter() + .find(|path| after.is_none_or(|after| path.file_name() > after.file_name()))) +} + +/// Whether a file newer than `path` exists in its directory. +pub fn superseded(path: &Path) -> bool { + let Some(dir) = path.parent() else { + return false; + }; + matches!(next_file(dir, Some(path)), Ok(Some(_))) +} + +/// A reader of one growing file that returns complete lines only. +pub struct Follower { + path: PathBuf, + reader: BufReader, + partial: Vec, + pub lines: u64, + /// Bytes of complete lines handed out. + pub consumed: u64, +} + +impl Follower { + pub fn open(path: &Path) -> std::io::Result { + Ok(Follower { + path: path.to_owned(), + reader: BufReader::with_capacity(1 << 20, File::open(path)?), + partial: Vec::new(), + lines: 0, + consumed: 0, + }) + } + + pub fn path(&self) -> &Path { + &self.path + } + + /// The next complete line, if one has been written; `None` when the reader is at the end of + /// what exists so far (an incomplete last line is kept for the next call). + pub fn next_line(&mut self) -> std::io::Result> { + let read = self.reader.read_until(b'\n', &mut self.partial)?; + if read == 0 || self.partial.last() != Some(&b'\n') { + return Ok(None); + } + self.consumed += self.partial.len() as u64; + self.partial.pop(); + let line = String::from_utf8(std::mem::take(&mut self.partial)) + .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?; + self.lines += 1; + Ok(Some(line)) + } + + /// About how many complete lines are written but not yet read: the bytes beyond the reader + /// over the mean line length so far. + pub fn backlog_lines(&self) -> u64 { + let Ok(len) = std::fs::metadata(&self.path).map(|m| m.len()) else { + return 0; + }; + if self.lines == 0 { + return 0; + } + let mean = (self.consumed / self.lines).max(1); + len.saturating_sub(self.consumed) / mean + } + + /// Bytes of an incomplete last line held back. + pub fn pending_bytes(&self) -> usize { + self.partial.len() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write; + + #[test] + fn complete_lines_only_and_files_in_start_order() { + let dir = tempfile::tempdir().unwrap(); + let a = dir.path().join("trace-0000000000100-7.jsonl"); + let b = dir.path().join("trace-0000000000200-9.jsonl"); + std::fs::write(dir.path().join("other.txt"), b"x").unwrap(); + let mut file = File::create(&a).unwrap(); + file.write_all(b"{\"format\":1}\n{\"half").unwrap(); + file.flush().unwrap(); + let mut follower = Follower::open(&a).unwrap(); + assert_eq!( + follower.next_line().unwrap().as_deref(), + Some("{\"format\":1}") + ); + assert_eq!(follower.next_line().unwrap(), None); + assert_eq!(follower.pending_bytes(), 6); + assert!(!superseded(&a)); + file.write_all(b"\":2}\n").unwrap(); + file.flush().unwrap(); + assert_eq!( + follower.next_line().unwrap().as_deref(), + Some("{\"half\":2}") + ); + assert_eq!(follower.next_line().unwrap(), None); + std::fs::write(&b, b"").unwrap(); + assert!(superseded(&a)); + assert!(!superseded(&b)); + assert_eq!(trace_files(dir.path()).unwrap(), vec![a.clone(), b.clone()]); + assert_eq!(next_file(dir.path(), None).unwrap(), Some(a.clone())); + assert_eq!(next_file(dir.path(), Some(&a)).unwrap(), Some(b.clone())); + assert_eq!(next_file(dir.path(), Some(&b)).unwrap(), None); + } +} diff --git a/services/flysim/crates/fly-legacy-session/src/shadow/mod.rs b/services/flysim/crates/fly-legacy-session/src/shadow/mod.rs new file mode 100644 index 0000000..b0c8631 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/shadow/mod.rs @@ -0,0 +1,992 @@ +//! SHADOW-01: the session runtime run beside the live legacy fly, transition by transition, as +//! the gate for the automatic cutover (CUT-01). `docs/design/session-framework/legacy-gameboy-v1.md` +//! section 18 is the contract; this module is its implementation. +//! +//! **What "the same inputs" means.** The legacy loop is deterministic given its start state and +//! the admissions applied at the top of each frame. Everything nondeterministic it consumes +//! reaches the fly through exactly two doors: +//! +//! 1. *The start state.* Each flysim process restores a checkpoint with +//! `legacy-transient-reset` (or warms up a fresh fly) and writes a durable startup save of the +//! state it starts from. The trace's boundary line names that save (`g`). A restart, a +//! watchdog kill, `fly-loop-recover` and `fly-reset-to-milestone` are all a new process, so a +//! new file and a new start. +//! 2. *Admissions.* Sugar (the rate limiter and the pulse rule run on wall time and the live +//! pulse) and an operator reward pulse are applied at the top of a frame, and each lands in that +//! transition's `admissions`. +//! +//! Wall time reaches nothing else the fly does: pacing, the publish rate, the checkpoint +//! intervals, chat (a caption track) and pause (no frames run) change no transition. The per-frame +//! trace records which checkpoints were taken where, so the shadow reproduces those too. +//! +//! So the shadow follows the live trace (`FLY_TRACE_DIR`): for each process file it boots a new +//! session from that process's own startup save through the ordinary FLYSIM01 import, replays each +//! transition's admissions into the admission queue, runs the transition, and compares its own +//! trace line with the live one field by field -- ticks, clock, remainder, rates, spikes, +//! decision, pad, macro events, frame, work RAM, rewards, rank, slot saves and rollbacks -- plus +//! the ledger digest where the live trace carries one (`FLY_TRACE_LEDGERS`), and the FLYSIM01 bytes +//! of every live save it can still read ([`checkpoint`]). The first difference stops the shadow +//! with a `diverged` verdict and the context around it. + +pub mod checkpoint; +pub mod follow; +pub mod spool; +pub mod verdict; + +use std::collections::VecDeque; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +use serde_json::Value; + +use fly_session::ExecutionMode; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::types::{id, parse_id}; +use flysim::snapshot::MacroMode; + +use crate::admission::LegacyAdmission; +use crate::composition::{LegacyConfig, LegacySession}; +use crate::trace::{self, Agreement, Difference}; +use checkpoint::ShadowCapture; +use follow::Follower; +use spool::Spool; +use verdict::{Checkpoints, Cost, Divergence, Skipped, Status, Verdict}; + +/// Lowercase hex SHA-256. +pub fn sha256_hex(bytes: &[u8]) -> String { + flysim::trace::sha256_hex(bytes) +} + +/// 3 hours of live brain time: the operator's decision of 2026-09-23. +pub const REQUIRED_BRAIN_SECONDS: f64 = 10_800.0; + +/// How the shadow runs. +#[derive(Clone, Debug)] +pub struct ShadowConfig { + /// The live service's `FLY_TRACE_DIR`. + pub trace_dir: PathBuf, + /// The live stores, read only (`FLY_STATE_HOT`, `FLY_STATE`). + pub hot_dir: PathBuf, + pub durable_dir: PathBuf, + /// `verdict.json`, `divergence.json`. + pub out_dir: PathBuf, + pub spool_dir: PathBuf, + /// The session's sockets and artifact stores, one directory per segment. + pub work_dir: PathBuf, + pub rom_path: PathBuf, + pub dataset_dir: PathBuf, + /// The agent profile: the production one on the stream; the toy connectome in tests. + pub profile: LegacyProfileKind, + /// The live service's configuration that a save records or the composition needs. + pub macro_mode: MacroMode, + pub speed: f64, + pub mode: ExecutionMode, + pub agent_threads: usize, + pub required_brain_seconds: f64, + /// Follow every trace file present at start, oldest first (a rehearsal), rather than only the + /// newest. + pub all_files: bool, + /// Keep trace files of finished segments (default: delete them once compared). + pub keep_traces: bool, + /// Keep every spooled checkpoint (a rehearsal replays them afterwards). + pub keep_spool: bool, + pub exit_on_pass: bool, + /// Stop after this many compared transitions (a bounded rehearsal); `None` runs on. + pub max_transitions: Option, + pub spool_max_bytes: u64, + pub context_lines: usize, + pub poll: Duration, + /// Stay behind a live fly that is behind real time. + pub lag_guard: Option, + /// The sha256 of the shadow binary (the candidate), for the verdict. + pub binary_sha256: String, + /// The release binaries beside it, by name, and their directory (the verdict's `candidate`). + pub binaries: std::collections::BTreeMap, + pub release: String, +} + +/// The back-off that keeps the shadow from costing the live fly real time. +/// +/// flysim's `fly_lag_seconds` is the *accumulated* pacing shortfall of the process: it never +/// recovers, and it grows only when the loop fell more than a second behind its schedule +/// (`pacing::MAX_CATCHUP`). So the signal is its growth, not its value: when it has grown by more +/// than `growth_seconds` within the last `window`, the shadow pauses between frames for +/// `back_off`, and again for as long as the growth continues. A metrics listener that cannot be +/// read never pauses the shadow (the guard is a backstop; the unit's `SCHED_IDLE` is the plan). +#[derive(Clone, Debug)] +pub struct LagGuard { + /// `host:port` of the live metrics listener. + pub metrics_addr: String, + pub growth_seconds: f64, + pub window: Duration, + pub back_off: Duration, +} + +/// Whether the live lag grew by more than `growth` seconds within `window` of the newest sample. +/// Samples are `(when, fly_lag_seconds)`, oldest first; a restart (the value falling) is growth +/// from zero. +pub fn lag_grew(samples: &VecDeque<(Instant, f64)>, window: Duration, growth: f64) -> bool { + let Some(&(newest_at, newest)) = samples.back() else { + return false; + }; + let mut floor = newest; + for &(at, value) in samples.iter().rev() { + if newest_at.duration_since(at) > window { + break; + } + floor = floor.min(value); + } + newest - floor > growth +} + +/// What the poller shares: the last lag read (ms, `u64::MAX` unknown) and whether to back off. +pub struct LagState { + pub lag_ms: AtomicU64, + pub back_off: AtomicBool, +} + +/// How a run ended. +#[derive(Debug, PartialEq, Eq)] +pub enum Ended { + Pass, + Diverged, + Stopped, + Limit, +} + +/// Why a segment ended. +enum SegmentEnd { + /// The process's file ended (the next one began). + Completed, + /// Nothing more could be compared in it. + Skipped(String), + Diverged(Box), + Stop(Ended), +} + +/// A stop request (SIGTERM or SIGINT), checked between frames. +#[derive(Clone, Default)] +pub struct StopFlag(Arc); + +impl StopFlag { + pub fn request(&self) { + self.0.store(true, Ordering::Relaxed); + } + + pub fn requested(&self) -> bool { + self.0.load(Ordering::Relaxed) + } +} + +/// Polls the live `fly_lag_seconds` every two seconds and applies [`LagGuard`]. +fn spawn_lag_poller(guard: &LagGuard, stop: StopFlag) -> Arc { + let state = Arc::new(LagState { + lag_ms: AtomicU64::new(u64::MAX), + back_off: AtomicBool::new(false), + }); + let out = Arc::clone(&state); + let guard = guard.clone(); + std::thread::Builder::new() + .name("fly-shadow-lag".to_owned()) + .spawn(move || { + let mut samples: VecDeque<(Instant, f64)> = VecDeque::new(); + let mut until: Option = None; + while !stop.requested() { + let now = Instant::now(); + match read_lag_seconds(&guard.metrics_addr) { + Some(lag) => { + out.lag_ms.store((lag * 1000.0) as u64, Ordering::Relaxed); + // A new process starts from zero: forget the old one's samples. + if samples.back().is_some_and(|&(_, last)| lag < last) { + samples.clear(); + } + samples.push_back((now, lag)); + while samples + .front() + .is_some_and(|&(at, _)| now.duration_since(at) > guard.window * 2) + { + samples.pop_front(); + } + if lag_grew(&samples, guard.window, guard.growth_seconds) { + until = Some(now + guard.back_off); + } + } + None => out.lag_ms.store(u64::MAX, Ordering::Relaxed), + } + out.back_off + .store(until.is_some_and(|u| now < u), Ordering::Relaxed); + std::thread::sleep(Duration::from_secs(2)); + } + }) + .expect("the lag poller starts"); + state +} + +/// `GET /metrics` over plain HTTP/1.0, the `fly_lag_seconds` sample. +pub fn read_lag_seconds(addr: &str) -> Option { + use std::io::{Read, Write}; + let mut stream = std::net::TcpStream::connect(addr).ok()?; + stream.set_read_timeout(Some(Duration::from_secs(2))).ok()?; + stream + .set_write_timeout(Some(Duration::from_secs(2))) + .ok()?; + write!(stream, "GET /metrics HTTP/1.0\r\nHost: {addr}\r\n\r\n").ok()?; + let mut body = String::new(); + stream.read_to_string(&mut body).ok()?; + parse_lag_seconds(&body) +} + +pub fn parse_lag_seconds(text: &str) -> Option { + text.lines() + .filter(|line| !line.starts_with('#')) + .find_map(|line| { + let mut parts = line.split_whitespace(); + (parts.next()? == "fly_lag_seconds").then(|| parts.next()?.parse().ok())? + }) +} + +/// The live trace's capture ids: `g`. +fn generation_of_capture(capture: &Value) -> Option { + capture["checkpointId"] + .as_str()? + .strip_prefix('g')? + .parse() + .ok() +} + +/// Runs the shadow until it passes (with `exit_on_pass`), diverges, is stopped, or reaches +/// `max_transitions`. +pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict), String> { + for dir in [&config.out_dir, &config.work_dir, &config.trace_dir] { + std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + } + let session_config = LegacyConfig { + mode: config.mode, + rom_path: config.rom_path.clone(), + dataset_dir: config.dataset_dir.clone(), + profile: config.profile, + macro_mode: config.macro_mode, + agent_id: id("fly"), + agent_threads: config.agent_threads, + record: true, + }; + let compatibility = crate::composition::compatibility_of(&session_config); + let mut spool = Spool::new( + &config.spool_dir, + vec![config.hot_dir.clone(), config.durable_dir.clone()], + config.spool_max_bytes, + ) + .map_err(|e| format!("the spool: {e}"))?; + if config.keep_spool { + spool = spool.keep_all(); + } + let spool_thread = spool.spawn(Duration::from_millis(250), Duration::from_secs(3 * 3600)); + let lag = config + .lag_guard + .as_ref() + .map(|guard| spawn_lag_poller(guard, stop.clone())); + let mut shadow = Shadow { + verdict: Verdict { + status: Status::Running, + reason: "following the live trace".to_owned(), + binary_sha256: config.binary_sha256.clone(), + binaries: config.binaries.clone(), + release: config.release.clone(), + compatibility: compatibility.clone(), + execution_mode: config.mode.label().to_owned(), + agent_threads: config.agent_threads, + required_brain_seconds: config.required_brain_seconds, + agreement: Agreement::default(), + brain_ms: 0.0, + ledger_checks: 0, + checkpoints: Checkpoints::default(), + segments_compared: 0, + skipped: Vec::new(), + divergence: None, + started_at: verdict::now_iso(), + passed_at: None, + current_trace: None, + lag_transitions: 0, + live_lag_seconds: None, + spool_evicted: 0, + cost: Cost::default(), + }, + config, + session_config, + compatibility, + spool, + lag, + stop, + last_write: Instant::now() - Duration::from_secs(60), + }; + shadow.write(); + let ended = shadow.follow().await; + shadow.spool.stop(); + let _ = spool_thread.join(); + let ended = ended?; + match ended { + Ended::Diverged => {} + Ended::Pass => {} + Ended::Stopped | Ended::Limit => { + if shadow.verdict.status == Status::Running { + shadow.verdict.status = Status::Stopped; + shadow.verdict.reason = match ended { + Ended::Limit => "stopped at the transition limit".to_owned(), + _ => "stopped before the window was complete".to_owned(), + }; + } + } + } + shadow.write(); + if shadow.verdict.status != Status::Diverged { + shadow.spool.clear(); + } + Ok((ended, shadow.verdict)) +} + +struct Shadow { + config: ShadowConfig, + session_config: LegacyConfig, + compatibility: String, + spool: Spool, + lag: Option>, + stop: StopFlag, + verdict: Verdict, + last_write: Instant, +} + +impl Shadow { + fn write(&mut self) { + self.verdict.spool_evicted = self.spool.evicted(); + self.verdict.live_lag_seconds = self.lag.as_ref().and_then(|lag| { + let ms = lag.lag_ms.load(Ordering::Relaxed); + (ms != u64::MAX).then(|| ms as f64 / 1000.0) + }); + let path = self.config.out_dir.join("verdict.json"); + if let Err(e) = verdict::write_json(&path, &self.verdict.to_json()) { + eprintln!("fly-shadow: could not write {}: {e}", path.display()); + } + self.last_write = Instant::now(); + } + + fn write_if_due(&mut self) { + if self.last_write.elapsed() >= Duration::from_secs(5) { + self.write(); + } + } + + fn diverged(&mut self, divergence: Divergence) { + eprintln!( + "fly-shadow: DIVERGED ({}) in {} at step {:?}: {}", + divergence.kind, + divergence.trace, + divergence.step, + divergence + .difference + .as_ref() + .map_or(divergence.detail.clone(), |d| d.to_string()) + ); + let path = self.config.out_dir.join("divergence.json"); + if let Err(e) = verdict::write_json(&path, &divergence.to_json()) { + eprintln!("fly-shadow: could not write {}: {e}", path.display()); + } + self.verdict.status = Status::Diverged; + self.verdict.passed_at = None; + self.verdict.reason = format!("diverged: {}", divergence.kind); + self.verdict.divergence = Some(divergence); + self.write(); + } + + /// The segment loop: each process file in start order. + async fn follow(&mut self) -> Result { + let dir = self.config.trace_dir.clone(); + let mut current: Option = if self.config.all_files { + None + } else { + // Only the newest file present at start: older processes are history whose startup + // saves are gone. + follow::trace_files(&dir) + .map_err(|e| format!("{}: {e}", dir.display()))? + .into_iter() + .rev() + .nth(1) + }; + loop { + let next = loop { + if self.stop.requested() { + return Ok(Ended::Stopped); + } + match follow::next_file(&dir, current.as_deref()) { + Ok(Some(path)) => break path, + Ok(None) => {} + Err(e) => return Err(format!("{}: {e}", dir.display())), + } + self.write_if_due(); + tokio::time::sleep(self.config.poll).await; + }; + let name = next + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + eprintln!("fly-shadow: following {name}"); + self.verdict.current_trace = Some(name.clone()); + let compared_before = self.verdict.agreement.transitions; + let end = self.segment(&next).await; + let compared = self.verdict.agreement.transitions - compared_before; + match end { + SegmentEnd::Completed => { + eprintln!("fly-shadow: {name} ended; {compared} transitions identical"); + if !self.config.keep_traces { + let _ = std::fs::remove_file(&next); + } + } + SegmentEnd::Skipped(reason) => { + eprintln!("fly-shadow: {name} skipped after {compared} transitions: {reason}"); + self.verdict.skipped.push(Skipped { + trace: name, + transitions_compared: compared, + reason, + }); + if !self.config.keep_traces { + let _ = std::fs::remove_file(&next); + } + } + SegmentEnd::Diverged(divergence) => { + self.diverged(*divergence); + return Ok(Ended::Diverged); + } + SegmentEnd::Stop(ended) => return Ok(ended), + } + self.write(); + current = Some(next); + } + } + + /// Waits for the next complete line of a segment; `None` when the segment has ended. + async fn next_line(&mut self, follower: &mut Follower) -> Result, SegmentEnd> { + loop { + match follower.next_line() { + Ok(Some(line)) => return Ok(Some(line)), + Ok(None) => {} + Err(e) => return Err(SegmentEnd::Skipped(format!("reading the trace: {e}"))), + } + if self.stop.requested() { + return Err(SegmentEnd::Stop(Ended::Stopped)); + } + if follow::superseded(follower.path()) { + // The next process exists, so this one has exited and flushed: one more read for + // a final flush racing the directory listing, then the segment is over. + tokio::time::sleep(Duration::from_millis(500)).await; + return match follower.next_line() { + Ok(line) => Ok(line), + Err(e) => Err(SegmentEnd::Skipped(format!("reading the trace: {e}"))), + }; + } + self.verdict.lag_transitions = 0; + self.write_if_due(); + tokio::time::sleep(self.config.poll).await; + } + } + + async fn segment(&mut self, path: &Path) -> SegmentEnd { + let name = path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let mut follower = match Follower::open(path) { + Ok(f) => f, + Err(e) => return SegmentEnd::Skipped(format!("open: {e}")), + }; + // The header. + let header: Value = match self.next_line(&mut follower).await { + Ok(Some(line)) => match serde_json::from_str(&line) { + Ok(v) => v, + Err(e) => return SegmentEnd::Skipped(format!("header: {e}")), + }, + Ok(None) => return SegmentEnd::Skipped("an empty trace".to_owned()), + Err(end) => return end, + }; + if header["format"] != trace::FORMAT { + return SegmentEnd::Skipped(format!("not {}: {}", trace::FORMAT, header["format"])); + } + // The start boundary and its startup save. + let start: Value = match self.next_line(&mut follower).await { + Ok(Some(line)) => match serde_json::from_str(&line) { + Ok(v) => v, + Err(e) => return SegmentEnd::Skipped(format!("start line: {e}")), + }, + Ok(None) => return SegmentEnd::Skipped("the process ran no transition".to_owned()), + Err(end) => return end, + }; + let Some(startup) = start["operational"]["captures"] + .as_array() + .and_then(|c| c.first()) + .and_then(generation_of_capture) + .filter(|_| start.get("boundary").is_some()) + else { + return SegmentEnd::Skipped("no startup save at the start boundary".to_owned()); + }; + let bytes = { + let mut waited = Duration::ZERO; + loop { + if let Some(bytes) = self.spool.read(startup) { + break bytes; + } + if waited >= Duration::from_secs(30) { + return SegmentEnd::Skipped(format!( + "the startup save g{startup} is no longer in the stores or the spool" + )); + } + tokio::time::sleep(Duration::from_millis(500)).await; + waited += Duration::from_millis(500); + } + }; + let checkpoint = match flysim::store::decode(&bytes) { + Ok(c) => c, + Err(e) => { + return SegmentEnd::Diverged(Box::new(self.boot_failure( + &name, + format!("the startup save g{startup} does not decode: {e:#}"), + ))); + } + }; + // The legacy gate, as the live process applied it to its own save. + let adapter = flybrain_gb::pokemon_red::PokemonRedReward::new(); + let gate = fly_session::legacy_checkpoint::RestoreGate::from_env( + &checkpoint.runtime.rom_sha256, + &self.compatibility, + flybrain_gb::GameAdapter::migrates_from(&adapter), + ); + if let Err(reason) = gate.check(&checkpoint) { + return SegmentEnd::Skipped(format!( + "the live process's startup save is not this candidate's to restore ({reason}): \ + is the shadow the build the live service runs?" + )); + } + let segment_dir = self.config.work_dir.join(format!("segment-{startup}")); + let _ = std::fs::remove_dir_all(&segment_dir); + let started = Instant::now(); + let mut session = + match LegacySession::start(&segment_dir, self.session_config.clone()).await { + Ok(s) => s, + Err(e) => return SegmentEnd::Skipped(format!("the session did not start: {e}")), + }; + // A fresh start (the stores were empty): the live process ran the one-frame scaffold and + // the warm-up from power-on, and the shadow does the same (`Environment.Initialize`, + // `Agent.Initialize`) rather than import the startup save. An import would not be the + // same emulator: binjgb's audio resampler phase is not in its exported state, so an + // imported emulator's channel accumulators drift from a powered-on one's (found by + // `tests/shadow.rs`). Every other start is a restore on both sides, and the same. + let fresh = checkpoint.runtime.emulator_frame == 1; + let booted: Result = match session.bootstrap().await { + Ok(()) if fresh => Ok(0.0), + Ok(()) => session + .import_checkpoint(&checkpoint, &id("e2")) + .await + .map(|imported| imported.rank_since_ms), + Err(e) => Err(e), + }; + let rank_since_ms = match booted { + Ok(ms) => ms, + Err(e) => { + session.stop().await; + let _ = std::fs::remove_dir_all(&segment_dir); + return SegmentEnd::Diverged(Box::new(self.boot_failure( + &name, + format!("the session runtime could not restore the live save g{startup}: {e}"), + ))); + } + }; + if fresh { + // The fresh fly's startup save must be the shadow's own boundary 0, byte for byte. + let outcome = match session + .coordinator + .capture_payloads(&id("shadow-fresh")) + .await + { + Ok((boundary, world_payload, agents)) => match agents.into_iter().next() { + Some((_, agent_payload)) => checkpoint::compare( + &bytes, + &ShadowCapture { + boundary, + world_payload, + agent_payload, + task: session.task.task_half().0, + rank_since_ms, + }, + &self.compatibility, + self.config.speed, + false, + ) + .map_err(|m| m.detail), + None => Err("a capture with no agent".to_owned()), + }, + Err(e) => Err(format!("capture: {}", e.error.message)), + }; + match outcome { + Ok(_) => self.verdict.checkpoints.identical += 1, + Err(detail) => { + session.stop().await; + return SegmentEnd::Diverged(Box::new(self.boot_failure( + &name, + format!("a fresh start: the startup save g{startup} is not the shadow's boundary 0: {detail}"), + ))); + } + } + } + eprintln!( + "fly-shadow: {name}: {} g{startup} (boundary {}) in {:?}", + if fresh { "fresh start, as" } else { "restored" }, + checkpoint.runtime.emulator_frame.saturating_sub(1), + started.elapsed() + ); + self.spool.set_floor(startup + 1); + self.verdict.segments_compared += 1; + // Rollbacks wait for the boundary's captures, as the host orders them (section 16). + session.coordinator.defer_rollbacks(true); + let end = self + .run_segment(&name, &mut follower, &mut session, rank_since_ms) + .await; + session.stop().await; + let _ = std::fs::remove_dir_all(&segment_dir); + end + } + + fn boot_failure(&self, name: &str, detail: String) -> Divergence { + Divergence { + kind: "boot".to_owned(), + trace: name.to_owned(), + step: None, + difference: None, + detail, + context: Vec::new(), + } + } + + async fn run_segment( + &mut self, + name: &str, + follower: &mut Follower, + session: &mut LegacySession, + rank_since_ms: f64, + ) -> SegmentEnd { + let mut admission = LegacyAdmission::new(session.coordinator.admissions(), id("fly")); + let mut rank = session.task.rank(); + let mut rank_since_ms = rank_since_ms; + let mut context: VecDeque<(Value, Value)> = VecDeque::new(); + let mut captures_taken: u64 = 0; + loop { + let line = match self.next_line(follower).await { + Ok(Some(line)) => line, + Ok(None) => return SegmentEnd::Completed, + Err(end) => return end, + }; + let live: Value = match serde_json::from_str(&line) { + Ok(v) => v, + Err(e) => return SegmentEnd::Skipped(format!("a trace line: {e}")), + }; + if live.get("truncated").is_some() { + return SegmentEnd::Skipped("the live trace reached its byte cap".to_owned()); + } + let Some(behaviour) = live.get("behaviour").cloned() else { + continue; + }; + let step: Option = behaviour["step"].as_str().and_then(|s| s.parse().ok()); + // The admissions of this transition, replayed as the live loop applied them. + for admission_line in behaviour["admissions"].as_array().into_iter().flatten() { + match admission_line["kind"].as_str() { + Some("sugar") => { + let Some(duration) = admission_line["durationMs"].as_f64() else { + return SegmentEnd::Skipped("a sugar with no duration".to_owned()); + }; + admission.replay_sugar(duration); + } + Some("reward") => { + return SegmentEnd::Skipped(format!( + "an operator reward pulse at step {step:?} (declared \ + operator-reward-pulse: not available on the session runtime)" + )); + } + other => { + return SegmentEnd::Skipped(format!("an unknown admission {other:?}")); + } + } + } + // Back off while the live fly is losing real time ([`LagGuard`]). + if let Some(lag) = self.lag.clone() { + let throttle = Instant::now(); + while lag.back_off.load(Ordering::Relaxed) { + if self.stop.requested() { + return SegmentEnd::Stop(Ended::Stopped); + } + self.write_if_due(); + tokio::time::sleep(Duration::from_millis(200)).await; + } + self.verdict.cost.throttled_ms += throttle.elapsed().as_secs_f64() * 1000.0; + } + let t0 = Instant::now(); + if let Err(e) = session.coordinator.step().await { + return SegmentEnd::Diverged(Box::new(Divergence { + kind: "session-error".to_owned(), + trace: name.to_owned(), + step, + difference: None, + detail: format!("step ({} at {}): {}", e.detail, e.phase, e.error.message), + context: context.into_iter().collect(), + })); + } + // `Sim::track_rank`, before the boundary's captures. + let now_rank = session.task.rank(); + if now_rank != rank { + rank = now_rank; + rank_since_ms = session.task.brain_ms(); + } + // The live captures at this boundary, each where the live loop took it: before the + // rollback (a milestone archive), or after it. + let actions: Vec = behaviour["boundaryActions"] + .as_array() + .into_iter() + .flatten() + .map(|a| a["kind"].as_str().unwrap_or("").to_owned()) + .collect(); + let rollback_at = actions.iter().position(|k| k == "rollback"); + let live_captures: Vec<(u64, usize)> = live["operational"]["captures"] + .as_array() + .into_iter() + .flatten() + .filter_map(|c| { + Some(( + generation_of_capture(c)?, + c["afterActions"].as_u64()? as usize, + )) + }) + .collect(); + let mut taken: Vec<(u64, usize, ShadowCapture)> = Vec::new(); + for pass in [false, true] { + if pass && let Err(e) = session.coordinator.apply_pending_rollback().await { + return SegmentEnd::Diverged(Box::new(Divergence { + kind: "session-error".to_owned(), + trace: name.to_owned(), + step, + difference: None, + detail: format!( + "rollback ({} at {}): {}", + e.detail, e.phase, e.error.message + ), + context: context.into_iter().collect(), + })); + } + for (generation, after) in &live_captures { + let after_rollback = rollback_at.is_some_and(|r| *after > r); + if after_rollback != pass { + continue; + } + captures_taken += 1; + let checkpoint_id = + parse_id(&format!("shadow-{captures_taken}")).expect("a valid id"); + match session.coordinator.capture_payloads(&checkpoint_id).await { + Ok((boundary, world_payload, agents)) => { + let Some((_, agent_payload)) = agents.into_iter().next() else { + return SegmentEnd::Skipped("a capture with no agent".to_owned()); + }; + taken.push(( + *generation, + *after, + ShadowCapture { + boundary, + world_payload, + agent_payload, + task: session.task.task_half().0, + rank_since_ms, + }, + )); + } + Err(e) => { + return SegmentEnd::Diverged(Box::new(Divergence { + kind: "session-error".to_owned(), + trace: name.to_owned(), + step, + difference: None, + detail: format!( + "capture ({} at {}): {}", + e.detail, e.phase, e.error.message + ), + context: context.into_iter().collect(), + })); + } + } + } + } + let details = session.coordinator.take_details(); + let records = session.task.take_records(); + let elapsed = t0.elapsed().as_secs_f64() * 1000.0; + self.verdict.cost.record(elapsed); + let (Some(details), [record]) = (details, records.as_slice()) else { + return SegmentEnd::Skipped("the session recorded no transition".to_owned()); + }; + let mut shadow_line = match trace::line(&details, record) { + Ok(line) => line["behaviour"].clone(), + Err(e) => return SegmentEnd::Skipped(format!("the shadow's trace line: {e}")), + }; + if behaviour.get("ledgersDigest").is_some() { + shadow_line["ledgersDigest"] = Value::String(sha256_hex(record.ledgers.as_bytes())); + self.verdict.ledger_checks += 1; + } + context.push_back((behaviour.clone(), shadow_line.clone())); + while context.len() > self.config.context_lines { + context.pop_front(); + } + if let Err(difference) = trace::compare_line(&behaviour, &shadow_line, &record.bound) { + let kind = if difference.field == "ledgersDigest" { + "ledgers" + } else { + "transition" + }; + let detail = if kind == "ledgers" { + format!( + "the shadow's ledgers after the boundary: {}", + record.ledgers + ) + } else { + String::new() + }; + return SegmentEnd::Diverged(Box::new(Divergence { + kind: kind.to_owned(), + trace: name.to_owned(), + step, + difference: Some(*difference), + detail, + context: context.into_iter().collect(), + })); + } + // The live saves at this boundary, byte for byte. + let save_slots_before = |after: usize| { + actions[..after.min(actions.len())] + .iter() + .filter(|k| *k == "save-slot") + .count() + }; + let total_save_slots = actions.iter().filter(|k| *k == "save-slot").count(); + for (generation, after, capture) in &taken { + let Some(live_bytes) = self.spool.read(*generation) else { + self.verdict.checkpoints.unavailable += 1; + continue; + }; + let archive_order = save_slots_before(*after) < total_save_slots; + match checkpoint::compare( + &live_bytes, + capture, + &self.compatibility, + self.config.speed, + archive_order, + ) { + Ok(checkpoint::Outcome::Identical) => self.verdict.checkpoints.identical += 1, + Ok(checkpoint::Outcome::Declared) => self.verdict.checkpoints.declared += 1, + Err(mismatch) => { + // Both files, for the review. + let out = &self.config.out_dir; + let _ = std::fs::write( + out.join(format!("divergence-live-g{generation}.checkpoint")), + &live_bytes, + ); + let _ = std::fs::write( + out.join(format!("divergence-shadow-g{generation}.checkpoint")), + &mismatch.shadow_bytes, + ); + return SegmentEnd::Diverged(Box::new(Divergence { + kind: "checkpoint".to_owned(), + trace: name.to_owned(), + step, + difference: Some(Difference { + field: format!("checkpoint g{generation}"), + legacy: Value::String(sha256_hex(&live_bytes)), + session: Value::String(format!("boundary {}", capture.boundary)), + }), + detail: mismatch.detail, + context: context.into_iter().collect(), + })); + } + } + self.spool.set_floor(*generation + 1); + } + self.verdict.agreement.count(&behaviour); + if self.verdict.agreement.transitions.is_multiple_of(600) { + self.verdict.lag_transitions = follower.backlog_lines(); + } + self.verdict.brain_ms += behaviour["ticksAdvanced"] + .as_str() + .and_then(|s| s.parse::().ok()) + .unwrap_or(0.0); + if self.verdict.status == Status::Running + && self.verdict.brain_seconds() >= self.config.required_brain_seconds + { + self.verdict.status = Status::Pass; + self.verdict.passed_at = Some(verdict::now_iso()); + self.verdict.reason = format!( + "{} s of live brain time compared with zero divergence", + self.config.required_brain_seconds + ); + eprintln!("fly-shadow: PASS ({})", self.verdict.reason); + self.write(); + if self.config.exit_on_pass { + return SegmentEnd::Stop(Ended::Pass); + } + } + if self + .config + .max_transitions + .is_some_and(|max| self.verdict.agreement.transitions >= max) + { + return SegmentEnd::Stop(Ended::Limit); + } + self.write_if_due(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_lag_sample_is_read_from_the_exposition() { + let text = "# HELP fly_lag_seconds lag\n# TYPE fly_lag_seconds gauge\nfly_lag_seconds 0.25\nfly_other 3\n"; + assert_eq!(parse_lag_seconds(text), Some(0.25)); + assert_eq!(parse_lag_seconds("fly_lag_seconds_total 3\n"), None); + } + + #[test] + fn the_guard_backs_off_on_growth_not_on_an_old_lag() { + let t0 = Instant::now(); + let at = |s: u64| t0 + Duration::from_secs(s); + let window = Duration::from_secs(30); + // An old lag of 40 s that no longer grows: no back-off. + let steady: VecDeque<_> = (0..20).map(|i| (at(i * 2), 40.0)).collect(); + assert!(!lag_grew(&steady, window, 0.5)); + // It grew by 1.2 s within the window: back off. + let mut grew = steady.clone(); + grew.push_back((at(40), 41.2)); + assert!(lag_grew(&grew, window, 0.5)); + // The same growth, but longer ago than the window: no longer. + let mut old = grew.clone(); + for i in 21..45 { + old.push_back((at(i * 2), 41.2)); + } + assert!(!lag_grew(&old, window, 0.5)); + assert!(!lag_grew(&VecDeque::new(), window, 0.5)); + } + + #[test] + fn capture_ids() { + assert_eq!( + generation_of_capture(&serde_json::json!({"checkpointId": "g42", "afterActions": 0})), + Some(42) + ); + assert_eq!( + generation_of_capture(&serde_json::json!({"checkpointId": "x"})), + None + ); + } +} diff --git a/services/flysim/crates/fly-legacy-session/src/shadow/spool.rs b/services/flysim/crates/fly-legacy-session/src/shadow/spool.rs new file mode 100644 index 0000000..5258ed6 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/shadow/spool.rs @@ -0,0 +1,251 @@ +//! The spool: copies of the live stores' checkpoint generations, taken as they appear. +//! +//! The live service keeps two generations per store (`keep_generations`) and writes a hot one +//! every five seconds, so a hot file lives about ten seconds, while the trace line that names it +//! arrives some seconds after the capture (the recorder buffers) and the shadow may be further +//! behind still. The spool thread therefore polls both store directories and copies every new +//! `.checkpoint` into the spool at once. Store commits write `.checkpoint.tmp` and rename +//! it, so a file under its final name is complete; one rotated away mid-copy is skipped. +//! +//! The spool is bounded: generations below the shadow's floor (already compared, or of a finished +//! segment) are deleted, and above `max_bytes` the oldest pending ones go first; a capture whose +//! file is gone is reported as unavailable, never as a divergence. The spool only reads the live +//! stores; it never writes, renames or deletes anything in them. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::{Duration, SystemTime}; + +/// The generation of a store file name, `.checkpoint`. +pub fn generation_of(name: &str) -> Option { + name.strip_suffix(".checkpoint")?.parse().ok() +} + +fn spool_name(generation: u64) -> String { + format!("g{generation}.checkpoint") +} + +/// Shared between the copying thread and the shadow. +#[derive(Clone)] +pub struct Spool { + dir: PathBuf, + sources: Vec, + max_bytes: u64, + floor: Arc, + stop: Arc, + evicted: Arc, + /// Keep every copy (a rehearsal that replays the run again afterwards): no floor, no bound. + keep: bool, +} + +impl Spool { + pub fn new(dir: &Path, sources: Vec, max_bytes: u64) -> std::io::Result { + std::fs::create_dir_all(dir)?; + Ok(Spool { + dir: dir.to_owned(), + sources, + max_bytes, + floor: Arc::new(AtomicU64::new(0)), + stop: Arc::new(AtomicBool::new(false)), + evicted: Arc::new(AtomicU64::new(0)), + keep: false, + }) + } + + /// Keep every copy: the floor and the byte bound delete nothing. + pub fn keep_all(mut self) -> Spool { + self.keep = true; + self + } + + /// Generations below `floor` are no longer needed. + pub fn set_floor(&self, floor: u64) { + self.floor.fetch_max(floor, Ordering::Relaxed); + } + + /// Pending generations dropped for space. + pub fn evicted(&self) -> u64 { + self.evicted.load(Ordering::Relaxed) + } + + /// Where generation `generation` can be read: the spool's copy, else a live store's file. + pub fn path(&self, generation: u64) -> Option { + let spooled = self.dir.join(spool_name(generation)); + if spooled.is_file() { + return Some(spooled); + } + self.sources + .iter() + .map(|dir| dir.join(format!("{generation}.checkpoint"))) + .find(|path| path.is_file()) + } + + /// Reads generation `generation`, from the spool or a live store (a file rotated away between + /// the lookup and the read is `None`). + pub fn read(&self, generation: u64) -> Option> { + let spooled = self.dir.join(spool_name(generation)); + if let Ok(bytes) = std::fs::read(&spooled) { + return Some(bytes); + } + self.sources + .iter() + .find_map(|dir| std::fs::read(dir.join(format!("{generation}.checkpoint"))).ok()) + } + + pub fn stop(&self) { + self.stop.store(true, Ordering::Relaxed); + } + + /// Starts the copying thread. The first scan copies only files modified within `window` + /// (the stores' permanent milestone archives are old and not needed); later scans copy every + /// new generation. + pub fn spawn(&self, period: Duration, window: Duration) -> std::thread::JoinHandle<()> { + let spool = self.clone(); + std::thread::Builder::new() + .name("fly-shadow-spool".to_owned()) + .spawn(move || { + let mut state = ScanState::default(); + let mut first = true; + while !spool.stop.load(Ordering::Relaxed) { + spool.scan(&mut state, first.then_some(window)); + first = false; + std::thread::sleep(period); + } + }) + .expect("the spool thread starts") + } + + /// One pass: copy what is new, delete what is below the floor, keep within the byte bound. + pub fn scan(&self, state: &mut ScanState, only_newer_than: Option) { + let floor = self.floor.load(Ordering::Relaxed); + let now = SystemTime::now(); + for source in &self.sources { + let Ok(entries) = std::fs::read_dir(source) else { + continue; + }; + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(generation) = name.to_str().and_then(generation_of) else { + continue; + }; + if (generation < floor && !self.keep) || state.seen.contains(&generation) { + continue; + } + if let Some(window) = only_newer_than { + let recent = entry + .metadata() + .and_then(|m| m.modified()) + .ok() + .and_then(|t| now.duration_since(t).ok()) + .is_some_and(|age| age <= window); + if !recent { + state.seen.insert(generation); + continue; + } + } + let target = self.dir.join(spool_name(generation)); + let tmp = self.dir.join(format!("{}.tmp", spool_name(generation))); + match std::fs::copy(entry.path(), &tmp) { + Ok(bytes) => { + if std::fs::rename(&tmp, &target).is_ok() { + state.held.insert(generation, bytes); + } + state.seen.insert(generation); + } + // Rotated away mid-copy: gone for good; the next scan will not see it either. + Err(_) => { + let _ = std::fs::remove_file(&tmp); + } + } + } + } + if self.keep { + return; + } + let below: Vec = state.held.range(..floor).map(|(g, _)| *g).collect(); + for generation in below { + let _ = std::fs::remove_file(self.dir.join(spool_name(generation))); + state.held.remove(&generation); + } + while state.held.values().sum::() > self.max_bytes { + let Some((&generation, _)) = state.held.iter().next() else { + break; + }; + let _ = std::fs::remove_file(self.dir.join(spool_name(generation))); + state.held.remove(&generation); + self.evicted.fetch_add(1, Ordering::Relaxed); + } + } + + /// Removes every spooled file (the shadow is done). + pub fn clear(&self) { + if self.keep { + return; + } + if let Ok(entries) = std::fs::read_dir(&self.dir) { + for entry in entries.flatten() { + let name = entry.file_name(); + if name + .to_str() + .is_some_and(|n| n.starts_with('g') && n.contains(".checkpoint")) + { + let _ = std::fs::remove_file(entry.path()); + } + } + } + } +} + +/// What one spool thread has copied and seen. +#[derive(Default)] +pub struct ScanState { + seen: BTreeSet, + held: BTreeMap, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn copies_new_generations_releases_below_the_floor_and_stays_bounded() { + let live = tempfile::tempdir().unwrap(); + let hot = live.path().join("hot"); + let durable = live.path().join("durable"); + std::fs::create_dir_all(&hot).unwrap(); + std::fs::create_dir_all(&durable).unwrap(); + let spool_dir = live.path().join("spool"); + let spool = Spool::new(&spool_dir, vec![hot.clone(), durable.clone()], 25).unwrap(); + std::fs::write(hot.join("5.checkpoint"), [1u8; 10]).unwrap(); + std::fs::write(durable.join("6.checkpoint"), [2u8; 10]).unwrap(); + std::fs::write(durable.join("manifest.json"), b"{}").unwrap(); + std::fs::write(hot.join("7.checkpoint.tmp"), [3u8; 10]).unwrap(); + let mut state = ScanState::default(); + spool.scan(&mut state, Some(Duration::from_secs(3600))); + assert!(spool_dir.join("g5.checkpoint").is_file()); + assert!(spool_dir.join("g6.checkpoint").is_file()); + assert!(!spool_dir.join("g7.checkpoint").exists()); + // The live store rotates 5 away: the spool still has it. + std::fs::remove_file(hot.join("5.checkpoint")).unwrap(); + assert_eq!(spool.read(5), Some(vec![1u8; 10])); + // A third file overflows the 25-byte bound: the oldest pending goes. + std::fs::write(hot.join("8.checkpoint"), [4u8; 10]).unwrap(); + spool.scan(&mut state, None); + assert_eq!(spool.evicted(), 1); + assert_eq!(spool.read(5), None); + assert!(spool.path(8).is_some()); + // Below the floor is released. + spool.set_floor(8); + spool.scan(&mut state, None); + assert!(!spool_dir.join("g6.checkpoint").exists()); + // Still readable from the live store while it is there. + assert_eq!(spool.read(6), Some(vec![2u8; 10])); + // The live stores were never touched. + assert!(durable.join("manifest.json").is_file()); + assert!(hot.join("8.checkpoint").is_file()); + spool.clear(); + assert!(!spool_dir.join("g8.checkpoint").exists()); + } +} diff --git a/services/flysim/crates/fly-legacy-session/src/shadow/verdict.rs b/services/flysim/crates/fly-legacy-session/src/shadow/verdict.rs new file mode 100644 index 0000000..7ac381a --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/shadow/verdict.rs @@ -0,0 +1,441 @@ +//! The verdict file, `fly-shadow-verdict-v1`: the contract CUT-01's automatic cutover reads. +//! +//! The shadow rewrites `verdict.json` in its output directory atomically (temporary file, rename) +//! every few seconds and at every change of status. The fields CUT-01 relies on: +//! +//! | Field | Meaning | +//! | --- | --- | +//! | `format` | `fly-shadow-verdict-v1` | +//! | `status` | `running`, `pass`, `diverged`, `stopped` or `error` | +//! | `candidate` | what was shadowed: `binarySha256` of the shadow binary; `binaries`, the SHA-256 of every release binary beside it by name (`fly-shadow`, `fly-session`, `flysim`, `fly-edge`: the session-runtime service CUT-01 switches to is built from the same tree in the same release); `release`, that directory; `compatibility` and its `compatibilitySha256`; `executionMode`; `agentThreads` | +//! | `required.brainSeconds` | the window the decision names: 10,800 s (3 h) of live brain time | +//! | `compared.brainSeconds`, `compared.transitions` | how much of the live fly was compared, transition by transition, with zero divergence | +//! | `passedAt` | when `compared.brainSeconds` first reached `required.brainSeconds` with no divergence | +//! | `firstDivergence` | `null`, or the first difference with its context (also `divergence.json`) | +//! | `declaredDifferences` | the named exclusions the comparison applied | +//! +//! `pass` is sticky only while nothing diverges: a shadow that keeps running after it passed and +//! then finds a difference turns the verdict to `diverged`. `stopped` is a shadow that exited +//! before it passed (a `pass` stays `pass` when the shadow stops). `error` is the shadow's own +//! failure (it could not read its inputs), which proves nothing either way. +//! +//! **The cutover rule (for CUT-01).** Cut over only if, read at the moment of cutting over: +//! `format` is `fly-shadow-verdict-v1`; `status` is `pass`; `firstDivergence` is `null`; +//! the session-runtime binary being switched to is one of `candidate.binaries`, by name and +//! SHA-256 (the shadow proved the release it shipped in, not another build); +//! `candidate.compatibility` is the live service's `--print-compatibility`; and `updatedAt` is no +//! older than a few minutes (the shadow is still following). Anything else keeps the legacy fly. + +use std::path::Path; + +use serde_json::{Value, json}; + +use crate::trace::{Agreement, Difference}; + +pub const FORMAT: &str = "fly-shadow-verdict-v1"; + +/// The declared differences the comparison applies, by name (`legacy-gameboy-v1`). +pub const DECLARED: [(&str, &str); 5] = [ + ( + "archive-order", + "a legacy milestone archive holds the pre-capture ratchet and slot (sections 4, 16): the \ + live file's ratchet, ratchetGame and ratchetFrame stand in for the shadow's in that capture", + ), + ( + "decision-list-order", + "the decision is compared as gameboy-channels-v1: buttons down and the first bound channel \ + held (section 6)", + ), + ( + "host-fields", + "generation, wallMs and lastEventId are the live file's: the session runtime has no feed \ + event log before EDGE-01 and allocates no generations as a shadow", + ), + ( + "admission-replay", + "sugar is replayed from the live trace's admissions, not re-decided: admission reads a \ + one-commit-stale pulse by the operator's decision (section 15)", + ), + ( + "operator-reward-pulse", + "a live POST /reward pulse cannot be reproduced (section 15 amendment): the rest of that \ + segment is reported uncompared, not diverged", + ), +]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Status { + Running, + Pass, + Diverged, + Stopped, + Error, +} + +impl Status { + pub fn as_str(self) -> &'static str { + match self { + Status::Running => "running", + Status::Pass => "pass", + Status::Diverged => "diverged", + Status::Stopped => "stopped", + Status::Error => "error", + } + } +} + +/// What the checkpoint comparisons found. +#[derive(Clone, Debug, Default)] +pub struct Checkpoints { + /// Byte-identical after the host fields. + pub identical: u64, + /// Byte-identical after the host fields and a declared difference. + pub declared: u64, + /// Named in the trace but rotated away before the spool copied it. + pub unavailable: u64, +} + +/// A segment the shadow did not (fully) compare, and why. +#[derive(Clone, Debug)] +pub struct Skipped { + pub trace: String, + pub transitions_compared: u64, + pub reason: String, +} + +/// The first divergence and its context. +#[derive(Clone, Debug)] +pub struct Divergence { + /// `transition`, `ledgers`, `checkpoint`, `boot` or `session-error`. + pub kind: String, + pub trace: String, + pub step: Option, + pub difference: Option, + pub detail: String, + /// The last transition lines before it, live and shadow, oldest first. + pub context: Vec<(Value, Value)>, +} + +impl Divergence { + pub fn to_json(&self) -> Value { + json!({ + "kind": self.kind, + "trace": self.trace, + "step": self.step.map(|s| s.to_string()), + "field": self.difference.as_ref().map(|d| d.field.clone()), + "live": self.difference.as_ref().map(|d| d.legacy.clone()), + "shadow": self.difference.as_ref().map(|d| d.session.clone()), + "detail": self.detail, + "context": self.context.iter().map(|(live, shadow)| json!({"live": live, "shadow": shadow})).collect::>(), + }) + } +} + +/// The per-frame cost of the shadow, wall time. +#[derive(Clone, Debug, Default)] +pub struct Cost { + samples: Vec, + pub total_ms: f64, + pub frames: u64, + pub throttled_ms: f64, +} + +impl Cost { + /// Keeps the last 36,000 frames (10 minutes) for the percentiles. + pub fn record(&mut self, ms: f64) { + self.total_ms += ms; + self.frames += 1; + if self.samples.len() == 36_000 { + self.samples.remove(0); + } + self.samples.push(ms); + } + + pub fn to_json(&self) -> Value { + let mut sorted = self.samples.clone(); + sorted.sort_by(f64::total_cmp); + let pct = |p: f64| { + if sorted.is_empty() { + return Value::Null; + } + let i = ((sorted.len() - 1) as f64 * p).round() as usize; + json!((sorted[i] * 1000.0).round() / 1000.0) + }; + json!({ + "framesTimed": self.frames, + "msPerFrameMean": if self.frames == 0 { Value::Null } else { json!(((self.total_ms / self.frames as f64) * 1000.0).round() / 1000.0) }, + "msPerFrameP50": pct(0.5), + "msPerFrameP99": pct(0.99), + "throttledSeconds": (self.throttled_ms / 1000.0).round(), + }) + } +} + +/// Everything the verdict file says. +#[derive(Clone, Debug)] +pub struct Verdict { + pub status: Status, + pub reason: String, + pub binary_sha256: String, + /// SHA-256 of the release binaries beside the shadow, by file name. + pub binaries: std::collections::BTreeMap, + /// The directory they are in. + pub release: String, + pub compatibility: String, + pub execution_mode: String, + pub agent_threads: usize, + pub required_brain_seconds: f64, + pub agreement: Agreement, + pub brain_ms: f64, + pub ledger_checks: u64, + pub checkpoints: Checkpoints, + pub segments_compared: u64, + pub skipped: Vec, + pub divergence: Option, + pub started_at: String, + pub passed_at: Option, + pub current_trace: Option, + /// Complete live lines not yet compared in the current segment, when known. + pub lag_transitions: u64, + pub live_lag_seconds: Option, + pub spool_evicted: u64, + pub cost: Cost, +} + +pub fn now_iso() -> String { + let ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as i64); + iso(ms) +} + +/// UTC `YYYY-MM-DDTHH:MM:SS.mmmZ` from Unix milliseconds (civil-from-days). +pub fn iso(ms: i64) -> String { + let secs = ms.div_euclid(1000); + let millis = ms.rem_euclid(1000); + let days = secs.div_euclid(86_400); + let rem = secs.rem_euclid(86_400); + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = if m <= 2 { y + 1 } else { y }; + format!( + "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{millis:03}Z", + rem / 3600, + (rem % 3600) / 60, + rem % 60 + ) +} + +impl Verdict { + pub fn brain_seconds(&self) -> f64 { + self.brain_ms / 1000.0 + } + + pub fn to_json(&self) -> Value { + let a = &self.agreement; + json!({ + "format": FORMAT, + "status": self.status.as_str(), + "reason": self.reason, + "candidate": { + "binarySha256": self.binary_sha256, + "binaries": self.binaries, + "release": self.release, + "compatibility": self.compatibility, + "compatibilitySha256": crate::shadow::sha256_hex(self.compatibility.as_bytes()), + "executionMode": self.execution_mode, + "agentThreads": self.agent_threads, + }, + "required": {"brainSeconds": self.required_brain_seconds}, + "compared": { + "brainSeconds": (self.brain_seconds() * 1000.0).round() / 1000.0, + "transitions": a.transitions, + "segments": self.segments_compared, + "sugar": a.sugar, + "rewards": a.rewards, + "rewardKinds": a.reward_kinds, + "macroEvents": a.macro_events, + "pressed": a.pressed, + "slotSaves": a.saves, + "rollbacks": a.rollbacks, + "spikes": a.spikes, + "ledgerChecks": self.ledger_checks, + "checkpoints": { + "identical": self.checkpoints.identical, + "declared": self.checkpoints.declared, + "unavailable": self.checkpoints.unavailable, + }, + }, + "skipped": self.skipped.iter().map(|s| json!({ + "trace": s.trace, "transitionsCompared": s.transitions_compared, "reason": s.reason, + })).collect::>(), + "declaredDifferences": DECLARED.iter().map(|(name, what)| json!({"name": name, "what": what})).collect::>(), + "firstDivergence": self.divergence.as_ref().map(|d| { + let mut v = d.to_json(); + if let Some(o) = v.as_object_mut() { o.remove("context"); } + v + }), + "startedAt": self.started_at, + "updatedAt": now_iso(), + "passedAt": self.passed_at, + "currentTrace": self.current_trace, + "lagTransitions": self.lag_transitions, + "liveLagSeconds": self.live_lag_seconds, + "spoolEvicted": self.spool_evicted, + "cost": self.cost.to_json(), + }) + } +} + +/// Writes `value` to `path` atomically. +pub fn write_json(path: &Path, value: &Value) -> std::io::Result<()> { + let tmp = path.with_extension("json.tmp"); + let mut text = serde_json::to_string_pretty(value).expect("JSON serializes"); + text.push('\n'); + std::fs::write(&tmp, text)?; + std::fs::rename(&tmp, path) +} + +/// Reads a verdict file and says whether it allows the cutover, by the rule in the module notes. +/// `binary` is the file name and SHA-256 of the session-runtime binary CUT-01 switches to, and +/// `compatibility` the live service's; `max_age_s` bounds `updatedAt`. +pub fn allows_cutover( + verdict: &Value, + binary: (&str, &str), + compatibility: &str, + now_ms: i64, + max_age_s: i64, +) -> Result<(), String> { + if verdict["format"] != FORMAT { + return Err(format!("not {FORMAT}")); + } + if verdict["status"] != "pass" { + return Err(format!("status is {}", verdict["status"])); + } + if !verdict["firstDivergence"].is_null() { + return Err("a divergence is recorded".to_owned()); + } + let (name, sha256) = binary; + if verdict["candidate"]["binaries"][name] != sha256 { + return Err(format!( + "the verdict is for another build: {name} {sha256} is not among the shadowed release's binaries" + )); + } + if verdict["candidate"]["compatibility"] != compatibility { + return Err("the verdict is for another compatibility string".to_owned()); + } + let compared = verdict["compared"]["brainSeconds"].as_f64().unwrap_or(0.0); + let required = verdict["required"]["brainSeconds"] + .as_f64() + .unwrap_or(f64::INFINITY); + if compared < required { + return Err(format!("{compared} of {required} brain seconds compared")); + } + let updated = verdict["updatedAt"] + .as_str() + .and_then(parse_iso) + .ok_or("no updatedAt")?; + if now_ms - updated > max_age_s * 1000 { + return Err(format!( + "the verdict is {} s old", + (now_ms - updated) / 1000 + )); + } + Ok(()) +} + +/// Parses [`iso`]'s format back to Unix milliseconds. +pub fn parse_iso(text: &str) -> Option { + let b = text.as_bytes(); + if b.len() != 24 || b[23] != b'Z' { + return None; + } + let n = |r: std::ops::Range| -> Option { text.get(r)?.parse().ok() }; + let (y, m, d) = (n(0..4)?, n(5..7)?, n(8..10)?); + let (hh, mm, ss, ms) = (n(11..13)?, n(14..16)?, n(17..19)?, n(20..23)?); + let y = if m <= 2 { y - 1 } else { y }; + let era = y.div_euclid(400); + let yoe = y - era * 400; + let mp = if m > 2 { m - 3 } else { m + 9 }; + let doy = (153 * mp + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + let days = era * 146_097 + doe - 719_468; + Some(((days * 86_400 + hh * 3600 + mm * 60 + ss) * 1000) + ms) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn iso_round_trips() { + for ms in [0i64, 951_782_400_123, 1_790_000_000_999, 4_102_444_800_000] { + assert_eq!(parse_iso(&iso(ms)), Some(ms), "{}", iso(ms)); + } + assert_eq!(iso(0), "1970-01-01T00:00:00.000Z"); + assert_eq!(iso(951_782_400_123), "2000-02-29T00:00:00.123Z"); + } + + fn verdict(status: Status, brain_ms: f64) -> Value { + Verdict { + status, + reason: String::new(), + binary_sha256: "b".repeat(64), + binaries: [("fly-session".to_owned(), "b".repeat(64))].into(), + release: "/opt/fly/releases/test".to_owned(), + compatibility: "c".to_owned(), + execution_mode: "in-process".to_owned(), + agent_threads: 2, + required_brain_seconds: 10_800.0, + agreement: Agreement::default(), + brain_ms, + ledger_checks: 0, + checkpoints: Checkpoints::default(), + segments_compared: 1, + skipped: Vec::new(), + divergence: None, + started_at: now_iso(), + passed_at: None, + current_trace: None, + lag_transitions: 0, + live_lag_seconds: None, + spool_evicted: 0, + cost: Cost::default(), + } + .to_json() + } + + #[test] + fn the_cutover_rule() { + let now = parse_iso(&now_iso()).unwrap(); + let sha = "b".repeat(64); + let bin = ("fly-session", sha.as_str()); + let pass = verdict(Status::Pass, 10_800_000.0); + assert_eq!(allows_cutover(&pass, bin, "c", now, 300), Ok(())); + let other = "a".repeat(64); + assert!(allows_cutover(&pass, ("fly-session", &other), "c", now, 300).is_err()); + assert!(allows_cutover(&pass, ("fly-other", &sha), "c", now, 300).is_err()); + assert!(allows_cutover(&pass, bin, "other", now, 300).is_err()); + assert!(allows_cutover(&pass, bin, "c", now + 301_000, 300).is_err()); + let short = verdict(Status::Pass, 10_799_000.0); + assert!(allows_cutover(&short, bin, "c", now, 300).is_err()); + for status in [ + Status::Running, + Status::Diverged, + Status::Stopped, + Status::Error, + ] { + assert!(allows_cutover(&verdict(status, 10_800_000.0), bin, "c", now, 300).is_err()); + } + let mut diverged = pass.clone(); + diverged["firstDivergence"] = json!({"kind": "transition"}); + assert!(allows_cutover(&diverged, bin, "c", now, 300).is_err()); + } +} diff --git a/services/flysim/crates/fly-legacy-session/src/task.rs b/services/flysim/crates/fly-legacy-session/src/task.rs index db3f2bf..47e1aaa 100644 --- a/services/flysim/crates/fly-legacy-session/src/task.rs +++ b/services/flysim/crates/fly-legacy-session/src/task.rs @@ -144,23 +144,7 @@ pub fn ledgers_of( ratchet: &Ratchet, macros: Option<&MacroLayer>, ) -> String { - let executor = match macros { - Some(layer) => json!({ - "scene": layer.scene_name(), - "bound": layer.bound_channels(), - "running": layer.running(), - "counts": format!("{:?}", layer.counts()), - "nearer": layer.nearer_the_objective(), - }), - None => Value::Null, - }; - json!({ - "adapter": adapter.export_state(), - "ratchet": serde_json::to_value(ratchet.state).expect("serializes"), - "slot": ratchet.snapshot.is_some(), - "executor": executor, - }) - .to_string() + flysim::frame::ledgers_string(adapter, ratchet, macros) } /// How the object is configured. Everything here is composition, not state. diff --git a/services/flysim/crates/fly-legacy-session/src/trace.rs b/services/flysim/crates/fly-legacy-session/src/trace.rs index 9bb33cd..dea7a22 100644 --- a/services/flysim/crates/fly-legacy-session/src/trace.rs +++ b/services/flysim/crates/fly-legacy-session/src/trace.rs @@ -165,6 +165,91 @@ pub struct Agreement { pub spikes: u64, } +/// The first field two transition lines disagree on, with both values. +#[derive(Clone, Debug, PartialEq)] +pub struct Difference { + pub field: String, + pub legacy: Value, + pub session: Value, +} + +impl std::fmt::Display for Difference { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}:\n legacy {}\n session {}", + self.field, self.legacy, self.session + ) + } +} + +/// One transition, field by field over the union of both lines' keys, the decision as +/// [`channels`] of the session's bound set for that transition. +pub fn compare_line( + legacy: &Value, + session: &Value, + bound: &[String], +) -> Result<(), Box> { + let (Some(a_map), Some(b_map)) = (legacy.as_object(), session.as_object()) else { + return Err(Box::new(Difference { + field: "(line)".to_owned(), + legacy: legacy.clone(), + session: session.clone(), + })); + }; + let keys: BTreeSet<&String> = a_map.keys().chain(b_map.keys()).collect(); + for key in keys { + let (x, y) = (&legacy[key.as_str()], &session[key.as_str()]); + let same = if key == "decision" { + channels(x, bound) == channels(y, bound) + } else { + x == y + }; + if !same { + return Err(Box::new(Difference { + field: key.clone(), + legacy: x.clone(), + session: y.clone(), + })); + } + } + Ok(()) +} + +impl Agreement { + /// Counts one agreed transition line. + pub fn count(&mut self, line: &Value) { + self.transitions += 1; + for admission in line["admissions"].as_array().into_iter().flatten() { + match admission["kind"].as_str() { + Some("sugar") => self.sugar += 1, + Some("reward") => self.reward_pulses += 1, + _ => {} + } + } + for reward in line["rewards"].as_array().into_iter().flatten() { + self.rewards += 1; + if let Some(kind) = reward["kind"].as_str() + && !self.reward_kinds.iter().any(|k| k == kind) + { + self.reward_kinds.push(kind.to_owned()); + } + } + self.macro_events += line["macroEvents"].as_array().map_or(0, |v| v.len() as u64); + if line["mask"].as_u64().unwrap_or(0) != 0 { + self.pressed += 1; + } + for action in line["boundaryActions"].as_array().into_iter().flatten() { + match action["kind"].as_str() { + Some("save-slot") => self.saves += 1, + Some("rollback") => self.rollbacks += 1, + _ => {} + } + } + self.spikes += line["spikeCount"].as_u64().unwrap_or(0); + } +} + /// Every transition identical, field by field; the decision as [`channels`] of the session's bound /// set for that transition. The first difference is the error, with both values. pub fn compare( @@ -184,52 +269,9 @@ pub fn compare( } let mut agreement = Agreement::default(); for (n, (a, b)) in legacy.iter().zip(session).enumerate() { - let (Some(a_map), Some(b_map)) = (a.as_object(), b.as_object()) else { - return Err(format!("transition {n}: not an object")); - }; - let keys: BTreeSet<&String> = a_map.keys().chain(b_map.keys()).collect(); - for key in keys { - let (x, y) = (&a[key.as_str()], &b[key.as_str()]); - let same = if key == "decision" { - channels(x, &bounds[n]) == channels(y, &bounds[n]) - } else { - x == y - }; - if !same { - return Err(format!( - "transition {n} (step {}) {key}:\n legacy {x}\n session {y}", - a["step"] - )); - } - } - agreement.transitions += 1; - for admission in a["admissions"].as_array().into_iter().flatten() { - match admission["kind"].as_str() { - Some("sugar") => agreement.sugar += 1, - Some("reward") => agreement.reward_pulses += 1, - _ => {} - } - } - for reward in a["rewards"].as_array().into_iter().flatten() { - agreement.rewards += 1; - if let Some(kind) = reward["kind"].as_str() - && !agreement.reward_kinds.iter().any(|k| k == kind) - { - agreement.reward_kinds.push(kind.to_owned()); - } - } - agreement.macro_events += a["macroEvents"].as_array().map_or(0, |v| v.len() as u64); - if a["mask"].as_u64().unwrap_or(0) != 0 { - agreement.pressed += 1; - } - for action in a["boundaryActions"].as_array().into_iter().flatten() { - match action["kind"].as_str() { - Some("save-slot") => agreement.saves += 1, - Some("rollback") => agreement.rollbacks += 1, - _ => {} - } - } - agreement.spikes += a["spikeCount"].as_u64().unwrap_or(0); + compare_line(a, b, &bounds[n]) + .map_err(|d| format!("transition {n} (step {}) {d}", a["step"]))?; + agreement.count(a); } Ok(agreement) } diff --git a/services/flysim/crates/fly-legacy-session/tests/shadow.rs b/services/flysim/crates/fly-legacy-session/tests/shadow.rs new file mode 100644 index 0000000..150453c --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/shadow.rs @@ -0,0 +1,458 @@ +//! SHADOW-01 end to end, on the committed toy connectome in raw mode (an explicit ROM job: +//! `FLY_ROM`, and the workspace's `flysim` binary beside this test's). +//! +//! The *real* `flysim` service runs with the shadow's trace switches (`FLY_TRACE_DIR`, +//! `FLY_TRACE_LEDGERS=1`, a hot save every second), takes sugar through its control API and is +//! restarted once; the shadow (`fly_legacy_session::shadow::run`) follows it from its first frame. +//! Every transition, ledger digest and live save must agree, across both processes. +//! +//! Then the negative controls, on copies of the same trace and spool: a work-RAM digest flipped, +//! a sugar removed, a ledger digest flipped and a live save's bytes changed must each stop a +//! fresh shadow with a `diverged` verdict naming the right kind, field and step. +//! +//! The FAFB rehearsal of the same pipeline, at stream scale, is `tools/shadow-rehearsal.sh`. + +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::time::{Duration, Instant}; + +use serde_json::Value; + +use fly_legacy_session::shadow::{self, Ended, ShadowConfig, StopFlag, verdict::Status}; +use fly_session::ExecutionMode; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_parity; +use flysim::snapshot::MacroMode; + +fn flysim_binary() -> Option { + let exe = std::env::current_exe().ok()?; + let release = exe.parent()?.parent()?; + let path = release.join("flysim"); + path.is_file().then_some(path) +} + +fn free_port() -> u16 { + std::net::TcpListener::bind("127.0.0.1:0") + .expect("an ephemeral port") + .local_addr() + .expect("its address") + .port() +} + +fn http(port: u16, method: &str, path: &str, body: Option<&str>) -> Option<(u16, String)> { + let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).ok()?; + stream.set_read_timeout(Some(Duration::from_secs(5))).ok()?; + let body = body.unwrap_or(""); + write!( + stream, + "{method} {path} HTTP/1.0\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ) + .ok()?; + let mut text = String::new(); + stream.read_to_string(&mut text).ok()?; + let status = text.split_whitespace().nth(1)?.parse().ok()?; + let body = text + .split_once("\r\n\r\n") + .map_or("", |(_, b)| b) + .to_owned(); + Some((status, body)) +} + +struct Live { + child: Child, + control: u16, +} + +struct LiveDirs { + hot: PathBuf, + durable: PathBuf, + trace: PathBuf, +} + +fn start_live(binary: &Path, rom: &Path, dirs: &LiveDirs, log: &Path) -> Live { + let control = free_port(); + let child = Command::new(binary) + .env("FLY_ROM", rom) + .env("FLY_DATASET", legacy_parity::toy::dir()) + .env("FLY_STATE", &dirs.durable) + .env("FLY_STATE_HOT", &dirs.hot) + .env("FLY_FEED_BIND", format!("127.0.0.1:{}", free_port())) + .env("FLY_CONTROL_BIND", format!("127.0.0.1:{control}")) + .env("FLY_METRICS_ADDR", format!("127.0.0.1:{}", free_port())) + .env("FLY_MACRO_MODE", "raw") + .env("FLY_CHAT_ENABLED", "false") + .env("FLYSIM_LOOP_GAME", "pokemon-red") + .env("FLYSIM_LOOP_SPEED", "0") + .env("FLYSIM_LOOP_HOT_SECONDS", "1") + .env("FLYSIM_LOOP_CHECKPOINT_SECONDS", "4") + .env("RAYON_NUM_THREADS", "1") + .env("FLY_TRACE_DIR", &dirs.trace) + .env("FLY_TRACE_LEDGERS", "1") + .env_remove("FLY_TRACE") + .env_remove("NOTIFY_SOCKET") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(std::fs::File::create(log).expect("a log")) + .spawn() + .expect("flysim starts"); + let live = Live { child, control }; + let deadline = Instant::now() + Duration::from_secs(240); + while live.brain_ms().is_none() { + assert!(Instant::now() < deadline, "flysim never ran"); + std::thread::sleep(Duration::from_millis(200)); + } + live +} + +impl Live { + fn brain_ms(&self) -> Option { + let (status, body) = http(self.control, "GET", "/status", None)?; + let v: Value = serde_json::from_str(&body).ok()?; + (status == 200 && v["status"] == "running").then(|| v["brainMs"].as_f64())? + } + + fn sugar(&self, ms: u32) { + let body = format!(r#"{{"durationMs":{ms},"by":"shadow-test","source":"operator"}}"#); + let (status, text) = + http(self.control, "POST", "/stimulate", Some(&body)).expect("the control API"); + assert!( + (200..300).contains(&status), + "sugar refused: {status} {text}" + ); + } + + fn run_for(&self, brain_ms: f64) { + let start = self.brain_ms().expect("running"); + while self.brain_ms().unwrap_or(start) < start + brain_ms { + std::thread::sleep(Duration::from_millis(100)); + } + } + + fn stop(mut self) { + let _ = Command::new("kill") + .args(["-TERM", &self.child.id().to_string()]) + .status(); + let _ = self.child.wait(); + } +} + +fn config( + rom: &Path, + root: &Path, + trace: &Path, + sources: (&Path, &Path), + spool: &Path, +) -> ShadowConfig { + ShadowConfig { + trace_dir: trace.to_owned(), + hot_dir: sources.0.to_owned(), + durable_dir: sources.1.to_owned(), + out_dir: root.join("out"), + spool_dir: spool.to_owned(), + work_dir: root.join("work"), + rom_path: rom.to_owned(), + dataset_dir: legacy_parity::toy::dir(), + profile: LegacyProfileKind::Toy, + macro_mode: MacroMode::Raw, + speed: 0.0, + mode: ExecutionMode::InProcess, + agent_threads: 1, + required_brain_seconds: 30.0, + all_files: true, + keep_traces: true, + keep_spool: true, + exit_on_pass: false, + max_transitions: None, + spool_max_bytes: 1 << 30, + context_lines: 5, + poll: Duration::from_millis(20), + lag_guard: None, + binary_sha256: "test".to_owned(), + binaries: Default::default(), + release: String::new(), + } +} + +fn transitions(trace: &Path) -> Vec<(PathBuf, usize)> { + shadow::follow::trace_files(trace) + .unwrap() + .into_iter() + .map(|path| { + let n = std::fs::read_to_string(&path) + .unwrap() + .lines() + .filter(|l| l.contains("\"behaviour\"")) + .count(); + (path, n) + }) + .collect() +} + +fn verdict_of(out: &Path) -> Value { + std::fs::read_to_string(out.join("verdict.json")) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or(Value::Null) +} + +/// Copies `trace` into a new directory, applying `edit` to the first file's lines. +fn tampered(trace: &Path, to: &Path, edit: impl Fn(usize, &mut Value) -> bool) -> u64 { + std::fs::create_dir_all(to).unwrap(); + let mut step = None; + for (i, (path, _)) in transitions(trace).into_iter().enumerate() { + let text = std::fs::read_to_string(&path).unwrap(); + let mut out = String::new(); + let mut n = 0; + for line in text.lines() { + let mut v: Value = serde_json::from_str(line).unwrap(); + if i == 0 && v.get("behaviour").is_some() { + if step.is_none() && edit(n, &mut v) { + step = v["behaviour"]["step"].as_str().and_then(|s| s.parse().ok()); + } + n += 1; + } + out.push_str(&v.to_string()); + out.push('\n'); + } + std::fs::write(to.join(path.file_name().unwrap()), out).unwrap(); + } + step.expect("the edit applied") +} + +/// The shadow on a thread of its own with its own runtime (the session's future is not `Send`). +fn spawn_shadow( + config: ShadowConfig, + stop: StopFlag, +) -> std::thread::JoinHandle> { + std::thread::spawn(move || { + tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .expect("a runtime") + .block_on(shadow::run(config, stop)) + }) +} + +fn diverges( + rom: &Path, + root: &Path, + trace: &Path, + spool: &Path, + empty: &Path, +) -> shadow::verdict::Verdict { + let _ = std::fs::remove_dir_all(root.join("out")); + let config = config(rom, root, trace, (empty, empty), spool); + let stop = StopFlag::default(); + let handle = spawn_shadow(config, stop.clone()); + let deadline = Instant::now() + Duration::from_secs(600); + while !handle.is_finished() { + if Instant::now() > deadline { + stop.request(); + } + std::thread::sleep(Duration::from_millis(100)); + } + let (ended, verdict) = handle.join().unwrap().expect("the shadow ran"); + assert_eq!(ended, Ended::Diverged, "{:?}", verdict.reason); + verdict +} + +#[test] +fn the_shadow_follows_the_real_service_and_catches_every_planted_difference() { + let Some(rom) = std::env::var_os("FLY_ROM").map(PathBuf::from) else { + eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)"); + return; + }; + let Some(binary) = flysim_binary() else { + eprintln!("skipping: no flysim binary beside this test (cargo test --workspace builds it)"); + return; + }; + // `FLY_SHADOW_TEST_DIR` keeps everything for a look afterwards. + let tmp = tempfile::tempdir().unwrap(); + let kept = std::env::var_os("FLY_SHADOW_TEST_DIR").map(PathBuf::from); + if let Some(dir) = &kept { + let _ = std::fs::remove_dir_all(dir); + std::fs::create_dir_all(dir).unwrap(); + } + let root_path = kept.unwrap_or_else(|| tmp.path().to_owned()); + let root = &root_path; + let dirs = LiveDirs { + hot: root.join("live/hot"), + durable: root.join("live/durable"), + trace: root.join("live/trace"), + }; + let spool = root.join("shadow/spool"); + let shadow_root = root.join("shadow"); + let config = config( + &rom, + &shadow_root, + &dirs.trace, + (&dirs.hot, &dirs.durable), + &spool, + ); + let out = config.out_dir.clone(); + let stop = StopFlag::default(); + let handle = spawn_shadow(config, stop.clone()); + + // Process one: a fresh fly (the stores are empty), two sugars, 25 brain seconds. + let live = start_live(&binary, &rom, &dirs, &root.join("flysim-1.log")); + live.sugar(300); + live.run_for(8_000.0); + live.sugar(700); + live.run_for(17_000.0); + live.stop(); + // Process two: restores its own latest save, a sugar, 15 brain seconds. + let live = start_live(&binary, &rom, &dirs, &root.join("flysim-2.log")); + live.run_for(5_000.0); + live.sugar(450); + live.run_for(10_000.0); + live.stop(); + + let files = transitions(&dirs.trace); + assert_eq!(files.len(), 2, "one trace file per process"); + let total: usize = files.iter().map(|(_, n)| n).sum(); + let deadline = Instant::now() + Duration::from_secs(600); + loop { + let v = verdict_of(&out); + if v["compared"]["transitions"].as_u64() == Some(total as u64) || handle.is_finished() { + break; + } + assert!( + Instant::now() < deadline, + "the shadow did not catch up: {v}" + ); + std::thread::sleep(Duration::from_millis(200)); + } + stop.request(); + let (ended, verdict) = handle.join().unwrap().expect("the shadow ran"); + let v = verdict_of(&out); + eprintln!( + "shadow: {ended:?} {}", + serde_json::to_string_pretty(&v).unwrap() + ); + assert_eq!(ended, Ended::Stopped); + assert!(verdict.divergence.is_none()); + assert_eq!( + verdict.status, + Status::Pass, + "40 brain seconds against a 30 s window" + ); + assert_eq!(verdict.agreement.transitions, total as u64); + assert_eq!(verdict.segments_compared, 2); + assert!(verdict.skipped.is_empty(), "{:?}", verdict.skipped); + assert_eq!(verdict.agreement.sugar, 3); + assert_eq!( + verdict.ledger_checks, total as u64, + "a ledger digest every boundary" + ); + // At least the fresh fly's startup save and both shutdown saves; the hot saves, one a wall + // second, add as many more as the box's speed gives. + assert!( + verdict.checkpoints.identical >= 3, + "live saves compared byte for byte: {:?}", + verdict.checkpoints + ); + + // The negative controls, each on a copy. + let empty = root.join("empty"); + std::fs::create_dir_all(&empty).unwrap(); + let neg = root.join("neg"); + + let at = tampered(&dirs.trace, &neg.join("wram/trace"), |n, v| { + (n == 700) + .then(|| v["behaviour"]["wramDigest"] = Value::String("0".repeat(64))) + .is_some() + }); + let got = diverges( + &rom, + &neg.join("wram"), + &neg.join("wram/trace"), + &spool, + &empty, + ); + let d = got.divergence.expect("a divergence"); + assert_eq!((d.kind.as_str(), d.step), ("transition", Some(at))); + assert_eq!(d.difference.unwrap().field, "wramDigest"); + assert!(!d.context.is_empty()); + assert_eq!(got.status, Status::Diverged); + + let at = tampered(&dirs.trace, &neg.join("ledgers/trace"), |n, v| { + (n == 900) + .then(|| v["behaviour"]["ledgersDigest"] = Value::String("0".repeat(64))) + .is_some() + }); + let got = diverges( + &rom, + &neg.join("ledgers"), + &neg.join("ledgers/trace"), + &spool, + &empty, + ); + let d = got.divergence.expect("a divergence"); + assert_eq!((d.kind.as_str(), d.step), ("ledgers", Some(at))); + + // A sugar the live loop applied, missing from the shadow's inputs: the brain differs from + // that transition on, and the comparison says where. + let at = tampered(&dirs.trace, &neg.join("sugar/trace"), |_, v| { + let had = v["behaviour"]["admissions"] + .as_array() + .is_some_and(|a| !a.is_empty()); + if had { + v["behaviour"]["admissions"] = Value::Array(Vec::new()); + // The admissions field itself would differ first; hold it to the tampered value. + } + had + }); + let got = diverges( + &rom, + &neg.join("sugar"), + &neg.join("sugar/trace"), + &spool, + &empty, + ); + let d = got.divergence.expect("a divergence"); + eprintln!( + "sugar removed at step {at}: diverged at {:?} on {:?}", + d.step, d.difference + ); + assert_eq!(d.kind, "transition"); + assert!(d.step.is_some_and(|s| s >= at)); + + // A live save whose bytes differ (its rankSinceMs moved by one ms). + let copy = neg.join("save/spool"); + std::fs::create_dir_all(©).unwrap(); + for entry in std::fs::read_dir(&spool).unwrap().flatten() { + std::fs::copy(entry.path(), copy.join(entry.file_name())).unwrap(); + } + let (first, _) = transitions(&dirs.trace).remove(0); + let text = std::fs::read_to_string(&first).unwrap(); + let (generation, at) = text + .lines() + .filter_map(|l| serde_json::from_str::(l).ok()) + .filter(|v| v.get("behaviour").is_some()) + .find_map(|v| { + let capture = v["operational"]["captures"].as_array()?.first()?.clone(); + let generation: u64 = capture["checkpointId"] + .as_str()? + .strip_prefix('g')? + .parse() + .ok()?; + let step: u64 = v["behaviour"]["step"].as_str()?.parse().ok()?; + Some((generation, step)) + }) + .expect("a live save during the run"); + let path = copy.join(format!("g{generation}.checkpoint")); + let mut checkpoint = flysim::store::load(&path).unwrap(); + checkpoint.runtime.rank_since_ms += 1.0; + std::fs::write( + &path, + flysim::store::encode(&checkpoint.agent, &checkpoint.runtime).unwrap(), + ) + .unwrap(); + let got = diverges(&rom, &neg.join("save"), &dirs.trace, ©, &empty); + let d = got.divergence.expect("a divergence"); + assert_eq!((d.kind.as_str(), d.step), ("checkpoint", Some(at))); + assert!(d.detail.contains("rankSinceMs"), "{}", d.detail); +}