From 23cc217221d281a5fca43e8f1131ccb2c7b9b2bf Mon Sep 17 00:00:00 2001 From: acamilo Date: Thu, 1 Oct 2026 21:55:12 +0000 Subject: [PATCH 01/27] flysim-session serves the feed over the bus: a test of the real binary against direct, and a restart under the edge --- .../crates/fly-legacy-session/Cargo.toml | 2 + .../fly-legacy-session/tests/feed_bus.rs | 402 ++++++++++++++++++ 2 files changed, 404 insertions(+) create mode 100644 services/flysim/crates/fly-legacy-session/tests/feed_bus.rs diff --git a/services/flysim/crates/fly-legacy-session/Cargo.toml b/services/flysim/crates/fly-legacy-session/Cargo.toml index 803adaf..51a6ecf 100644 --- a/services/flysim/crates/fly-legacy-session/Cargo.toml +++ b/services/flysim/crates/fly-legacy-session/Cargo.toml @@ -47,3 +47,5 @@ axum = "0.8" futures-util = "0.3" tokio-tungstenite = "0.29" tower = { version = "0.5", features = ["util"] } +# EDGE-02: the session runtime serves the feed over the bus (tests/feed_bus.rs). +fly-edge = { path = "../fly-edge" } diff --git a/services/flysim/crates/fly-legacy-session/tests/feed_bus.rs b/services/flysim/crates/fly-legacy-session/tests/feed_bus.rs new file mode 100644 index 0000000..4d01971 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/feed_bus.rs @@ -0,0 +1,402 @@ +//! EDGE-02: the session runtime serves the feed over the bus. +//! +//! `flysim-session` runs behind `flysim::serve`, so `FLY_FEED_VIA=bus` should work on it exactly +//! as on `flysim`. This runs the real `flysim-session` binary (the toy connectome, the real +//! cartridge, a store seeded by a legacy fresh start) twice from copies of the same store: +//! +//! - `direct`: the binary binds the feed port and a WebSocket client records it; +//! - `bus`: the binary binds nothing on the feed port, `fly-edge` (in process) does, and the same +//! client records that. The binary is then stopped and started again under the same edge, which +//! must unbind, reconnect and serve the new instance. +//! +//! The two recordings are compared snapshot by snapshot on the sim frame: the header minus the +//! fields that are wall clock by definition, and the three attachments byte for byte. Gated on +//! `FLY_ROM` (source `bin/rom-env.sh`): without it the test returns early. + +use std::collections::BTreeMap; +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command as Process, Stdio}; +use std::sync::Arc; +use std::sync::atomic::Ordering; +use std::time::{Duration, Instant}; + +use fly_edge::{EdgeConfig, EdgeMetrics}; +use flysim::config::{Config, FeedVia}; +use flysim::eventlog::EventRing; +use flysim::simloop::{Command, Shared, Sim, booting_snapshot}; +use flysim::snapshot::MacroMode; +use futures_util::{SinkExt as _, StreamExt as _}; +use serde_json::Value; +use tokio::sync::{mpsc, watch}; +use tokio_tungstenite::tungstenite::Message as WsMessage; + +fn rom_path() -> Option { + match std::env::var_os("FLY_ROM") { + Some(path) => Some(PathBuf::from(path)), + None => { + eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)"); + None + } + } +} + +fn free_port() -> SocketAddr { + std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() +} + +/// The service configuration: slow enough that a recorder on a loaded box sees every frame, every +/// frame published, no timed checkpoints. +fn config(rom: &Path, dataset: &Path, dir: &Path, via: FeedVia, bus_dir: &Path) -> Config { + let mut config = Config::default(); + config.paths.rom = rom.to_path_buf(); + config.paths.dataset = dataset.to_path_buf(); + config.paths.save_dir = dir.join("durable"); + config.paths.hot_dir = dir.join("hot"); + config.loop_.game = "pokemon-red".to_owned(); + config.loop_.speed = 0.25; + config.loop_.threads = 1; + config.loop_.snapshot_hz = 240.0; + config.loop_.hot_seconds = 1e9; + config.loop_.checkpoint_seconds = 1e9; + config.macros.mode = MacroMode::Raw; + config.chat.enabled = false; + config.feed.via = via; + config.feed.bus_dir = bus_dir.to_path_buf(); + config.feed.bind = free_port(); + config.control.bind = free_port(); + config.control.metrics_bind = Some(free_port()); + config +} + +/// A store seeded by a legacy fresh start, shut down cleanly (as `service_parity` does). +fn seed_by_legacy_fresh_start(rom: &Path, dataset: &Path, dir: &Path) { + let mut config = config(rom, dataset, dir, FeedVia::Direct, dir); + config.loop_.speed = 1.0; + let shared = Arc::new(Shared::new(config.clone(), EventRing::new())); + let (commands, command_rx) = mpsc::channel::(64); + let (snapshots_tx, mut snapshots) = + watch::channel(Arc::new(booting_snapshot(0, 0, MacroMode::Raw))); + let thread = std::thread::spawn(move || -> anyhow::Result<()> { + let mut sim = Sim::boot(shared, snapshots_tx, command_rx)?; + sim.run(&flysim::sdnotify::Notifier::from_env()) + }); + let rt = tokio::runtime::Runtime::new().unwrap(); + rt.block_on(async { + loop { + snapshots.changed().await.unwrap(); + if snapshots.borrow().header.frame >= 120 { + break; + } + } + let (reply, ack) = tokio::sync::oneshot::channel(); + commands.send(Command::Shutdown { reply }).await.unwrap(); + let _ = ack.await; + }); + thread.join().unwrap().unwrap(); +} + +fn seed(from: &Path, to: &Path) { + for sub in ["durable", "hot"] { + let dst = to.join(sub); + std::fs::create_dir_all(&dst).unwrap(); + if let Ok(entries) = std::fs::read_dir(from.join(sub)) { + for entry in entries.flatten() { + if entry.file_type().unwrap().is_file() { + std::fs::copy(entry.path(), dst.join(entry.file_name())).unwrap(); + } + } + } + } +} + +/// A running `flysim-session`, stopped (SIGTERM, then kill) when dropped. +struct Service { + child: Child, + config: Config, +} + +impl Service { + fn start(config: Config, work: &Path, name: &str) -> Service { + let path = work.join(format!("{name}.toml")); + std::fs::write(&path, toml::to_string(&config).unwrap()).unwrap(); + let log = std::fs::File::create(work.join(format!("{name}.log"))).unwrap(); + let child = Process::new(env!("CARGO_BIN_EXE_flysim-session")) + .arg("--config") + .arg(&path) + .env("FLY_SESSION_PROFILE", "toy") + .env("FLY_SESSION_DIR", work.join(format!("{name}-session"))) + // The test process's own cpus are not the sim's. + .env("FLY_SESSION_PIN", "0") + .env_remove("FLY_FEED_VIA") + .env_remove("FLY_BUS_DIR") + .env_remove("FLY_FEED_BIND") + .env_remove("FLY_CONTROL_BIND") + .env_remove("FLY_METRICS_ADDR") + .stdout(Stdio::null()) + .stderr(log) + .spawn() + .expect("flysim-session starts"); + Service { child, config } + } + + /// SIGTERM and wait for the clean stop (the unit's own way to stop it). + fn stop(&mut self) { + let pid = self.child.id().to_string(); + let _ = Process::new("kill").args(["-TERM", &pid]).status(); + let deadline = Instant::now() + Duration::from_secs(30); + while Instant::now() < deadline { + if self.child.try_wait().unwrap().is_some() { + return; + } + std::thread::sleep(Duration::from_millis(100)); + } + let _ = self.child.kill(); + let _ = self.child.wait(); + } + + /// Whether `flysim-session` itself holds the feed port (a connect succeeds and the peer is + /// not the edge): used only for the direct run, where it must. + fn log(&self, work: &Path, name: &str) -> PathBuf { + work.join(format!("{name}.log")) + } + + fn feed_bind(&self) -> SocketAddr { + self.config.feed.bind + } +} + +impl Drop for Service { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +/// What one running snapshot comes to on the wire. +#[derive(Debug, Clone, PartialEq)] +struct Seen { + header: Value, + attachments: Vec>, +} + +fn comparable(header: &Value) -> Value { + let mut value = header.clone(); + let map = value.as_object_mut().expect("a header is an object"); + for key in ["wallMs", "uptimeSeconds", "realtimeFactor", "seq"] { + map.remove(key); + } + if let Some(sugar) = map.get_mut("sugar").and_then(Value::as_object_mut) { + sugar.remove("cooldownMs"); + } + for list in ["events", "chat"] { + if let Some(items) = map.get_mut(list).and_then(Value::as_array_mut) { + for item in items { + if let Some(item) = item.as_object_mut() { + item.remove("wallMs"); + } + } + } + } + value +} + +fn parse(message: &[u8]) -> Seen { + let read = |at: usize| u32::from_le_bytes(message[at..at + 4].try_into().unwrap()) as usize; + let header_len = read(0); + let header: Value = serde_json::from_slice(&message[4..4 + header_len]).unwrap(); + let mut at = 4 + header_len; + let mut attachments = Vec::new(); + while at < message.len() { + let len = read(at); + attachments.push(message[at + 4..at + 4 + len].to_vec()); + at += 4 + len; + } + Seen { + header, + attachments, + } +} + +type Ws = + tokio_tungstenite::WebSocketStream>; + +/// Connect (retrying while nothing listens yet) and say `hello`. +async fn connect(addr: SocketAddr, within: Duration, log: &Path) -> Ws { + let url = format!("ws://{addr}/feed"); + let deadline = Instant::now() + within; + loop { + match tokio_tungstenite::connect_async(&url).await { + Ok((mut ws, _)) => { + let hello = serde_json::json!({ "protocol": 1, "client": "feed-bus-test", "wants": ["frame", "audio", "spikes"] }); + ws.send(WsMessage::Text(hello.to_string().into())) + .await + .unwrap(); + return ws; + } + Err(error) => { + assert!( + Instant::now() < deadline, + "{url}: {error}\n--- {} ---\n{}", + log.display(), + std::fs::read_to_string(log).unwrap_or_default() + ); + tokio::time::sleep(Duration::from_millis(100)).await; + } + } + } +} + +/// Running snapshots (three attachments) by sim frame, until `frames` of them or `within`. +async fn record(ws: &mut Ws, frames: usize, within: Duration) -> BTreeMap { + let deadline = tokio::time::Instant::now() + within; + let mut seen = BTreeMap::new(); + while seen.len() < frames { + let Ok(Some(Ok(message))) = tokio::time::timeout_at(deadline, ws.next()).await else { + break; + }; + if let WsMessage::Binary(bytes) = message { + let snapshot = parse(&bytes); + if snapshot.attachments.len() == 3 { + let frame = snapshot.header["frame"].as_u64().unwrap(); + seen.insert(frame, snapshot); + } + } + } + seen +} + +fn fresh_dir(root: &Path, seeded: &Path, name: &str) -> PathBuf { + let dir = root.join(name); + seed(seeded, &dir); + dir +} + +#[test] +fn the_session_runtime_serves_the_same_feed_over_the_bus() { + let Some(rom) = rom_path() else { return }; + let dataset = fly_session::legacy_parity::toy::dir(); + let root = tempfile::tempdir().unwrap(); + let seeded = root.path().join("seeded"); + std::fs::create_dir_all(&seeded).unwrap(); + seed_by_legacy_fresh_start(&rom, &dataset, &seeded); + let runtime = tokio::runtime::Runtime::new().unwrap(); + const FRAMES: usize = 90; + let within = Duration::from_secs(90); + + // Direct: the service binds the feed port itself. + let direct = { + let dir = fresh_dir(root.path(), &seeded, "direct"); + let bus = root.path().join("direct-bus"); + let mut service = Service::start( + config(&rom, &dataset, &dir, FeedVia::Direct, &bus), + root.path(), + "direct", + ); + let recorded = runtime.block_on(async { + let mut ws = connect( + service.feed_bind(), + Duration::from_secs(60), + &service.log(root.path(), "direct"), + ) + .await; + record(&mut ws, FRAMES, within).await + }); + service.stop(); + assert!(!bus.join("edge.sock").exists(), "direct mode opened a bus"); + recorded + }; + assert!( + direct.len() >= FRAMES, + "direct recorded {} running snapshots", + direct.len() + ); + + // Bus: the service leaves the feed port to the edge. + let bus_dir = root.path().join("bus"); + let bus = { + let dir = fresh_dir(root.path(), &seeded, "bus"); + let service_config = config(&rom, &dataset, &dir, FeedVia::Bus, &bus_dir); + let edge_addr = service_config.feed.bind; + let edge_metrics = Arc::new(EdgeMetrics::default()); + let edge = EdgeConfig { + retry: Duration::from_millis(100), + ..EdgeConfig::from_flysim(&service_config, None) + }; + let _edge = runtime.spawn(fly_edge::run(edge, Arc::clone(&edge_metrics))); + let mut service = Service::start(service_config.clone(), root.path(), "bus"); + let recorded = runtime.block_on(async { + // Nothing is bound until the edge has its first snapshot, and it is the edge that binds. + let mut ws = connect( + edge_addr, + Duration::from_secs(60), + &root.path().join("bus.log"), + ) + .await; + let recorded = record(&mut ws, FRAMES, within).await; + assert_eq!(edge_metrics.connected.load(Ordering::Relaxed), 1); + recorded + }); + service.stop(); + // The edge notices, drops its clients and unbinds the port. + let lost = Instant::now(); + while edge_metrics.connected.load(Ordering::Relaxed) != 0 { + assert!( + lost.elapsed() < Duration::from_secs(10), + "the edge never saw the bus go" + ); + std::thread::sleep(Duration::from_millis(50)); + } + assert!(edge_metrics.bus_lost.load(Ordering::Relaxed) >= 1); + + // A new instance under the same edge: it reconnects by itself and serves the new router. + let mut again = Service::start(service_config, root.path(), "bus-again"); + runtime.block_on(async { + let mut ws = connect( + edge_addr, + Duration::from_secs(60), + &root.path().join("bus-again.log"), + ) + .await; + let after = record(&mut ws, 10, within).await; + assert!( + after.len() >= 10, + "after the restart: {} running snapshots", + after.len() + ); + }); + assert_eq!(edge_metrics.connected.load(Ordering::Relaxed), 1); + again.stop(); + recorded + }; + assert!( + bus.len() >= FRAMES, + "bus recorded {} running snapshots", + bus.len() + ); + + // The same frames, the same bytes. + let mut compared = 0; + for (frame, a) in &direct { + let Some(b) = bus.get(frame) else { continue }; + assert_eq!( + comparable(&a.header), + comparable(&b.header), + "frame {frame}: header" + ); + assert_eq!(a.attachments.len(), b.attachments.len(), "frame {frame}"); + for (index, (x, y)) in a.attachments.iter().zip(&b.attachments).enumerate() { + assert!(x == y, "frame {frame}: attachment {index} differs"); + } + compared += 1; + } + eprintln!( + "session feed: direct {} and bus {} running snapshots, {compared} frames in common and identical", + direct.len(), + bus.len() + ); + assert!(compared >= FRAMES / 2, "only {compared} frames in common"); +} From 12321bb513a6253a585b8d80b8f486c8184ff911 Mon Sep 17 00:00:00 2001 From: acamilo Date: Thu, 1 Oct 2026 21:56:34 +0000 Subject: [PATCH 02/27] fly-edge: healthz fails when the bus goes silent; snapshot age gauge --- services/flysim/crates/fly-edge/src/lib.rs | 95 ++++++++++++++++++++-- 1 file changed, 88 insertions(+), 7 deletions(-) diff --git a/services/flysim/crates/fly-edge/src/lib.rs b/services/flysim/crates/fly-edge/src/lib.rs index cdf9375..46e4c3c 100644 --- a/services/flysim/crates/fly-edge/src/lib.rs +++ b/services/flysim/crates/fly-edge/src/lib.rs @@ -18,8 +18,9 @@ use std::net::SocketAddr; use std::path::PathBuf; use std::sync::Arc; +use std::sync::LazyLock; use std::sync::atomic::{AtomicU64, Ordering}; -use std::time::Duration; +use std::time::{Duration, Instant}; use anyhow::{Context, Result, anyhow}; use axum::extract::State; @@ -32,6 +33,19 @@ use flysim::feedbus; use flysim::metrics::{Metrics, metric}; use tokio::sync::{oneshot, watch}; +/// A subscription that has delivered nothing for this long is not serving: the loop publishes a +/// header at least every `1 / idle_snapshot_hz` even when paused, so silence this long means the +/// bus is wedged, not that the fly is idle. `/healthz` turns 503 so the watchdog restarts the edge +/// (it restarts nothing while flysim itself is unhealthy: that is flysim's check). +pub const STALE_AFTER: Duration = Duration::from_secs(15); + +static EPOCH: LazyLock = LazyLock::new(Instant::now); + +/// Milliseconds since the process first asked, plus one so that 0 can mean "never". +fn now_ms() -> u64 { + EPOCH.elapsed().as_millis() as u64 + 1 +} + /// What the edge needs to know. Built from flysim's own configuration, so both processes read /// one environment file and cannot disagree about the port, the bus directory or the cadence. #[derive(Debug, Clone)] @@ -75,9 +89,41 @@ pub struct EdgeMetrics { pub decode_failures: AtomicU64, /// Sessions that reached the bus but could not bind the feed port. pub bind_failures: AtomicU64, + /// [`now_ms`] when the last snapshot was taken off the bus; 0 before the first. + last_snapshot_ms: AtomicU64, } impl EdgeMetrics { + /// Note that a snapshot has just been taken off the bus. + fn snapshot_arrived(&self) { + self.snapshots.fetch_add(1, Ordering::Relaxed); + self.last_snapshot_ms.store(now_ms(), Ordering::Relaxed); + } + + /// Seconds since the last snapshot came off the bus, or `None` before the first. + pub fn snapshot_age(&self) -> Option { + match self.last_snapshot_ms.load(Ordering::Relaxed) { + 0 => None, + at => Some(Duration::from_millis(now_ms().saturating_sub(at))), + } + } + + /// Whether the edge is serving: subscribed, and hearing from the bus within [`STALE_AFTER`]. + pub fn health(&self) -> Result<(), String> { + self.health_within(STALE_AFTER) + } + + fn health_within(&self, stale_after: Duration) -> Result<(), String> { + if self.connected.load(Ordering::Relaxed) != 1 { + return Err("waiting for the feed bus".to_owned()); + } + match self.snapshot_age() { + Some(age) if age <= stale_after => Ok(()), + Some(age) => Err(format!("no snapshot for {} s", age.as_secs())), + None => Err("no snapshot yet".to_owned()), + } + } + pub fn render(&self) -> String { let mut out = String::with_capacity(1_024); let feed = &self.feed; @@ -116,6 +162,13 @@ impl EdgeMetrics { "1 while the edge is subscribed to the feed bus and serving.", self.connected.load(Ordering::Relaxed), ); + metric( + &mut out, + "fly_edge_snapshot_age_seconds", + "gauge", + "Seconds since the last snapshot came off the feed bus (-1 before the first).", + self.snapshot_age().map_or(-1.0, |age| age.as_secs_f64()), + ); metric( &mut out, "fly_edge_bus_lost_total", @@ -218,10 +271,9 @@ async fn prometheus(State(metrics): State>) -> impl IntoRespons } async fn healthz(State(metrics): State>) -> impl IntoResponse { - if metrics.connected.load(Ordering::Relaxed) == 1 { - (StatusCode::OK, "ok") - } else { - (StatusCode::SERVICE_UNAVAILABLE, "waiting for the feed bus") + match metrics.health() { + Ok(()) => (StatusCode::OK, "ok".to_owned()), + Err(why) => (StatusCode::SERVICE_UNAVAILABLE, why), } } @@ -291,7 +343,7 @@ async fn serve( listener: tokio::net::TcpListener, ) { let (snapshots, receiver) = watch::channel(Arc::new(first)); - metrics.snapshots.fetch_add(1, Ordering::Relaxed); + metrics.snapshot_arrived(); tracing::info!(feed = %config.feed_bind, bus = %config.bus_dir.display(), "serving the feed from the bus"); metrics.connected.store(1, Ordering::Relaxed); @@ -317,7 +369,7 @@ async fn serve( Ok(snapshot) => { drop(message); snapshots.send_replace(Arc::new(snapshot)); - metrics.snapshots.fetch_add(1, Ordering::Relaxed); + metrics.snapshot_arrived(); } Err(error) => { metrics.decode_failures.fetch_add(1, Ordering::Relaxed); @@ -342,3 +394,32 @@ async fn serve( tracing::warn!("the feed listener took more than 5 s to stop"); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn health_needs_the_bus_and_recent_snapshots() { + let metrics = EdgeMetrics::default(); + assert_eq!(metrics.snapshot_age(), None); + assert!(metrics.health().unwrap_err().contains("waiting")); + metrics.connected.store(1, Ordering::Relaxed); + assert!(metrics.health().unwrap_err().contains("no snapshot yet")); + metrics.snapshot_arrived(); + assert_eq!(metrics.health(), Ok(())); + std::thread::sleep(Duration::from_millis(40)); + assert!(metrics.snapshot_age().unwrap() >= Duration::from_millis(40)); + assert!( + metrics + .health_within(Duration::from_millis(10)) + .unwrap_err() + .contains("no snapshot for") + ); + metrics.snapshot_arrived(); + assert_eq!(metrics.health_within(Duration::from_millis(30)), Ok(())); + metrics.connected.store(0, Ordering::Relaxed); + assert!(metrics.health().is_err()); + assert!(metrics.render().contains("fly_edge_snapshot_age_seconds")); + } +} From 6612f9ae9ca487a5093f3b9b3db2827099ba1561 Mon Sep 17 00:00:00 2001 From: acamilo Date: Thu, 1 Oct 2026 22:10:44 +0000 Subject: [PATCH 03/27] feed bus in production: fly-feed switch, flysim wants the edge, watchdog checks the edge and falls back, deploy refuses a release without fly-edge --- infra/05-deploy.sh | 26 ++- infra/bin/fly-feed | 316 ++++++++++++++++++++++++++++++++ infra/bin/fly-watchdog | 76 +++++++- infra/config/fly-sudoers | 6 +- infra/tests/lint.sh | 351 +++++++++++++++++++++++++++++++++++- infra/units/flyedge.service | 65 ++++--- infra/units/flysim.service | 5 + 7 files changed, 805 insertions(+), 40 deletions(-) create mode 100755 infra/bin/fly-feed diff --git a/infra/05-deploy.sh b/infra/05-deploy.sh index af2d3fe..76bba21 100644 --- a/infra/05-deploy.sh +++ b/infra/05-deploy.sh @@ -124,6 +124,19 @@ need pct FLY_FEED_VIA_EFFECTIVE="$(feed_via_normalize "${FLY_FEED_VIA:-}")" \ || die "05-deploy: FLY_FEED_VIA must be 'direct' or 'bus', got '${FLY_FEED_VIA}'" +# The container's own value, read before anything changes. A `fly-feed bus` (or `direct`) on the +# container is not in the env file unless the operator put it there, and this deploy writes the env +# file's value into fly.env. Nothing breaks (flysim and flyedge.service both follow fly.env at +# their next start, so the feed stays served either way) but the mode would change at the next +# restart of flysim, which is not what anyone meant. Said once, loudly, here. +FLY_FEED_VIA_LIVE="$(ct_exec "$CTID" -- awk -F= '/^FLY_FEED_VIA=/ { v=$2 } END { print v }' /etc/fly/fly.env 2>/dev/null \ + | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)" +if [ -n "$FLY_FEED_VIA_LIVE" ] && [ "$FLY_FEED_VIA_LIVE" != "$FLY_FEED_VIA_EFFECTIVE" ]; then + log "05-deploy: WARNING: the container's fly.env says FLY_FEED_VIA=${FLY_FEED_VIA_LIVE} and $1 says ${FLY_FEED_VIA_EFFECTIVE};" \ + "this deploy writes ${FLY_FEED_VIA_EFFECTIVE}, which flysim applies at its next restart (no restart is done here)." \ + "If ${FLY_FEED_VIA_LIVE} is what you want, set FLY_FEED_VIA=${FLY_FEED_VIA_LIVE} in $1 and deploy again; \`fly-feed status\` shows both." +fi + # CHROMIUM_PROFILE is validated here, not left to the launcher: a typo or a # `vgl` on a container that never had VirtualGL installed would only show up as # flystage refusing to start, i.e. a black stream, minutes after the deploy @@ -422,6 +435,17 @@ The 'current' symlink has NOT been moved." log "05-deploy: flysim.service runs the session runtime; this release ships flysim-session with flysim's compatibility string" fi + # The feed bus (EDGE-02). Bus mode needs the release's fly-edge: without it flyedge.service's + # ConditionPathExists= skips the unit, flysim has left :7400 to it, and the stage has no feed. + # Refused when the env file asks for bus, and when the container is in bus mode now (an edge + # that is running keeps running, but the first time it restarts there is nothing to start; and + # the way back is `fly-feed direct`, which needs no binary of this release). + if [ "$FLY_FEED_VIA_EFFECTIVE" = bus ] || [ "$FLY_FEED_VIA_LIVE" = bus ]; then + ct_exec "$CTID" -- test -x "${release_path}/fly-edge" \ + || die "05-deploy: REFUSING to deploy release ${version}: the feed is on the bus (FLY_FEED_VIA=bus: $([ "$FLY_FEED_VIA_EFFECTIVE" = bus ] && echo "in $1" || echo "on the container")) and this release has no fly-edge. Run \`fly-feed direct\` in the container and set FLY_FEED_VIA=direct in $1 first, or deploy a release that ships fly-edge. The 'current' symlink has NOT been moved." + log "05-deploy: the feed is on the bus; this release ships fly-edge" + fi + log "05-deploy: flipping /opt/fly/current -> ${release_path} atomically" ct_exec "$CTID" -- sh -c "ln -sfn '$release_path' /opt/fly/current.tmp && mv -T /opt/fly/current.tmp /opt/fly/current" else @@ -770,7 +794,7 @@ fi # --------------------------------------------------------------------------- log "05-deploy: converging bin/ helpers to /opt/fly/bin" ct_exec "$CTID" -- mkdir -p /opt/fly/bin -for name in fly-watchdog fly-loop-recover fly-loop-reset fly-recap fly-retention fly-reset-to-milestone fly-cpu-confine fly-runtime fly-runtime-probation fly-shadow-run flypush flystage-launch flycast-launch wait-for-x wait-for-stage wait-for-health; do +for name in fly-watchdog fly-loop-recover fly-loop-reset fly-recap fly-retention fly-reset-to-milestone fly-cpu-confine fly-feed fly-runtime fly-runtime-probation fly-shadow-run flypush flystage-launch flycast-launch wait-for-x wait-for-stage wait-for-health; do converge_file "$CTID" "$INFRA_DIR/bin/$name" "/opt/fly/bin/$name" 0755 root:root >/dev/null done diff --git a/infra/bin/fly-feed b/infra/bin/fly-feed new file mode 100755 index 0000000..8e35241 --- /dev/null +++ b/infra/bin/fly-feed @@ -0,0 +1,316 @@ +#!/usr/bin/env bash +# infra/bin/fly-feed — who serves the feed WebSocket (ws://127.0.0.1:7400/feed): flysim itself +# (`direct`) or fly-edge over flysim's feed bus (`bus`). EDGE-02; docs/design/flybus.md, "Feed over +# the bus"; the runbook's "Feed over the bus". +# +# Usage (INSIDE the container, as root): +# fly-feed status configured, running, the edge and its counters (any user) +# fly-feed bus [--no-restart] [--no-rollback] +# fly-feed direct [--no-restart] [--no-wait] +# +# One line decides: FLY_FEED_VIA in /etc/fly/fly.env. flysim reads it, flyedge.service's +# ExecCondition= reads it, flysim.service has Wants=flyedge.service, so every start of flysim brings +# up the edge in bus mode and skips it in direct mode, whoever started flysim and on whichever +# runtime (flysim or flysim-session, `fly-runtime`): nothing else has to be enabled, started or +# remembered. `fly-feed bus|direct` rewrites that line, restarts flysim.service (the feed changes +# hands at the start, so the stream is down for the length of a flysim restart, exactly like the +# unstick rule's) and waits until the page is on the feed again. +# +# What "healthy" means after a switch, in this order, within FLY_FEED_HEALTH_TIMEOUT (300 s): +# 1. flysim's /healthz answers (a NEW invocation: the old process is not mistaken for it); +# 2. bus: the edge's /healthz answers 200 (subscribed, snapshots arriving); +# 3. if flystage.service is active: its page is on the feed (`fly_feed_clients` >= 1 on the +# counters of whoever serves it) and `fly_frames_sent_total` advances. Without a page unit +# (a box that only serves the feed) the wait ends at 2. +# If that does not happen, `bus` puts FLY_FEED_VIA back to what it was, restarts flysim and checks +# the same way (--no-rollback leaves it to the operator); `direct` is already the way back, so it +# only reports. A switch that is interrupted (ssh drops, INT/TERM/HUP) rolls back the same way. +# `--no-restart` only rewrites the line (the next start of flysim applies it). `--no-wait` restarts +# flysim without blocking and does not wait for health or roll anything back: it is what the +# watchdog runs (as a sudoers-granted `fly-feed direct --no-wait`) when the edge cannot be kept up. +# +# 05-deploy.sh writes FLY_FEED_VIA into fly.env from the operator's env file on every deploy and +# does not restart flysim. After a `fly-feed bus`, put FLY_FEED_VIA=bus in the env file too, or the +# next deploy writes `direct` back (the next flysim start would then follow it) and says so. +# +# Restarts count against flysim.service's start limit (3 in 10 minutes while the session runtime is +# selected, `fly-runtime`): a switch and its rollback are two. +# +# Every switch is logged to the journal (tag fly-feed) and ${FEED_LOG}. +set -euo pipefail + +: "${FLY_ENV_FILE:=/etc/fly/fly.env}" +: "${FLY_SERVICE:=flysim.service}" +: "${FLY_EDGE_SERVICE:=flyedge.service}" +: "${FLY_PAGE_SERVICE:=flystage.service}" +: "${FLY_RELEASE_DIR:=/opt/fly/current}" +: "${FLY_CONTROL_URL:=http://127.0.0.1:7401}" +: "${FLY_METRICS_URL:=http://127.0.0.1:9101}" +: "${FLY_EDGE_METRICS_URL:=http://127.0.0.1:9102}" +: "${FLY_PROC_DIR:=/proc}" +: "${FLY_FEED_HEALTH_TIMEOUT:=300}" +: "${FLY_FEED_LOG:=/var/lib/fly/feed.log}" +: "${FLY_FEED_LOCK:=/run/fly/feed.lock}" +: "${FLY_FEED_SAMPLE_SECONDS:=3}" +FEED_LOG="$FLY_FEED_LOG" + +log() { echo "fly-feed: $*" >&2; } +die() { log "$*"; exit 1; } + +record() { + if command -v logger >/dev/null 2>&1; then + logger -t fly-feed -- "$*" || true + fi + mkdir -p "$(dirname "$FEED_LOG")" 2>/dev/null || true + echo "$(date -u '+%Y-%m-%dT%H:%M:%SZ') $*" >>"$FEED_LOG" 2>/dev/null || log "could not append to $FEED_LOG" +} + +usage() { + echo "usage: fly-feed status | bus [--no-restart] [--no-rollback] [--no-wait] | direct [--no-restart] [--no-wait]" >&2 + exit 2 +} + +# direct | bus | invalid:. flysim reads the value case-insensitively; a missing line is direct. +configured() { + local value="" + if [ -f "$FLY_ENV_FILE" ]; then + value="$(awk -F= '/^FLY_FEED_VIA=/ { v=$0; sub(/^FLY_FEED_VIA=/, "", v); last=v } END { print last }' "$FLY_ENV_FILE" 2>/dev/null || true)" + fi + value="$(printf '%s' "$value" | tr -d ' \r"' | tr '[:upper:]' '[:lower:]')" + case "$value" in + ""|direct) echo direct ;; + bus) echo bus ;; + *) echo "invalid:${value}" ;; + esac +} + +# What the running flysim process started with (its environment, not the file): direct | bus | +# stopped | unknown. +running() { + local pid value + pid="$(systemctl show -p MainPID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)" + if [ -z "$pid" ] || [ "$pid" = 0 ]; then echo stopped; return; fi + if [ ! -r "${FLY_PROC_DIR}/${pid}/environ" ]; then echo unknown; return; fi + value="$(tr '\0' '\n' <"${FLY_PROC_DIR}/${pid}/environ" 2>/dev/null | awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)" + case "$value" in + bus) echo bus ;; + *) echo direct ;; + esac +} + +# The counters of whoever serves the feed in `via` mode. +metrics_url() { + if [ "$1" = bus ]; then echo "$FLY_EDGE_METRICS_URL"; else echo "$FLY_METRICS_URL"; fi +} + +# metric URL NAME -> the value of the first sample of NAME, or empty. +metric() { + curl -fsS --max-time 5 "$1/metrics" 2>/dev/null | awk -v n="$2" '$1 == n { print $2; exit }' || true +} + +# Whole-number part of a Prometheus value ("3", "3.0", "1e+06" is not expected for these). +whole() { printf '%.0f' "${1:-0}" 2>/dev/null || echo 0; } + +# The page is on the feed: at least one client, and the frames counter moves over a sample. +page_on_feed() { + local url first second clients + url="$(metrics_url "$1")" + clients="$(metric "$url" fly_feed_clients)" + [ "$(whole "$clients")" -ge 1 ] || return 1 + first="$(metric "$url" fly_frames_sent_total)" + sleep "$FLY_FEED_SAMPLE_SECONDS" + second="$(metric "$url" fly_frames_sent_total)" + [ -n "$first" ] && [ -n "$second" ] && [ "$(whole "$second")" -gt "$(whole "$first")" ] +} + +page_unit_active() { systemctl is-active --quiet "$FLY_PAGE_SERVICE" 2>/dev/null; } + +old_invocation="" +# Wait for a NEW flysim invocation to be healthy and the feed to be flowing in `via` mode. +healthy() { + local via="$1" deadline + deadline=$(( $(date +%s) + FLY_FEED_HEALTH_TIMEOUT )) + while [ "$(date +%s)" -lt "$deadline" ]; do + if [ -n "$old_invocation" ] \ + && [ "$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)" = "$old_invocation" ]; then + sleep 1 + continue + fi + if curl -fsS -o /dev/null --max-time 5 "${FLY_CONTROL_URL}/healthz" 2>/dev/null; then + if [ "$via" = bus ] && ! curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null; then + sleep 1 + continue + fi + if ! page_unit_active; then + log "healthy (${via}): ${FLY_PAGE_SERVICE} is not active, so no page to wait for" + return 0 + fi + if page_on_feed "$via"; then + log "healthy (${via}): the page is on the feed and frames are moving" + return 0 + fi + fi + sleep 1 + done + return 1 +} + +# Rewrite (or add) the FLY_FEED_VIA line, keeping every other line, the mode and the owner. +set_via() { + local value="$1" tmp + [ -f "$FLY_ENV_FILE" ] || die "no ${FLY_ENV_FILE}; deploy first (infra/05-deploy.sh writes it)" + tmp="$(mktemp "${FLY_ENV_FILE}.XXXXXX")" + awk -v v="$value" ' + /^FLY_FEED_VIA=/ { if (!done) { print "FLY_FEED_VIA=" v; done=1 } ; next } + { print } + END { if (!done) print "FLY_FEED_VIA=" v } + ' "$FLY_ENV_FILE" >"$tmp" + chmod --reference="$FLY_ENV_FILE" "$tmp" 2>/dev/null || chmod 0640 "$tmp" + chown --reference="$FLY_ENV_FILE" "$tmp" 2>/dev/null || true + mv -f "$tmp" "$FLY_ENV_FILE" +} + +locked=0 +take_lock() { + [ "$locked" -eq 0 ] || return 0 + mkdir -p "$(dirname "$FLY_FEED_LOCK")" 2>/dev/null || true + exec 8>>"$FLY_FEED_LOCK" + flock -w 60 8 || die "another fly-feed holds ${FLY_FEED_LOCK}; not switching" + locked=1 +} + +restart_flysim() { + systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true + old_invocation="$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)" + log "restarting ${FLY_SERVICE}" + # --no-block: a start that never becomes READY must not hold this process (and the lock); + # `healthy` proves it is talking to the new invocation. + systemctl restart --no-block "$FLY_SERVICE" +} + +status_report() { + local conf run edge_state url + conf="$(configured)" + run="$(running)" + echo "configured: ${conf}" + echo "running: ${run}" + if [ "$run" != stopped ] && [ "$run" != unknown ] && [ "$conf" != "$run" ] && [[ "$conf" != invalid:* ]]; then + echo " fly.env and the running flysim disagree: the next start of ${FLY_SERVICE} applies ${conf} (fly-feed ${conf} does it now)" + fi + edge_state="$(systemctl is-active "$FLY_EDGE_SERVICE" 2>/dev/null || true)" + echo "${FLY_EDGE_SERVICE}: ${edge_state:-unknown}" + url="$(metrics_url "$run")" + if [ "$run" = bus ]; then + if curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null; then + echo "edge healthz: ok" + else + echo "edge healthz: NOT OK ($(curl -sS --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>&1 | head -c 100))" + fi + echo "edge snapshot age: $(metric "$url" fly_edge_snapshot_age_seconds) s; bus lost: $(metric "$url" fly_edge_bus_lost_total); bind failures: $(metric "$url" fly_edge_bind_failures_total); decode failures: $(metric "$url" fly_edge_decode_failures_total)" + fi + echo "feed clients: $(metric "$url" fly_feed_clients) (counters of the ${run} server); frames sent: $(metric "$url" fly_frames_sent_total)" + if [ -f "$FEED_LOG" ]; then echo "last switch: $(tail -n1 "$FEED_LOG")"; fi +} + +[ $# -ge 1 ] || usage +command="$1"; shift +restart=1 +rollback=1 +wait_for_health=1 +for arg in "$@"; do + case "$arg" in + --no-restart) restart=0 ;; + --no-rollback) rollback=0 ;; + --no-wait) wait_for_health=0 ;; + *) usage ;; + esac +done + +case "$command" in + status) status_report; exit 0 ;; + bus|direct) ;; + *) usage ;; +esac + +[ "$(id -u)" -eq 0 ] || die "run as root (it writes ${FLY_ENV_FILE} and restarts ${FLY_SERVICE})" +before="$(configured)" +[[ "$before" != invalid:* ]] || die "FLY_FEED_VIA in ${FLY_ENV_FILE} is '${before#invalid:}', not direct or bus; fix it (a deploy rewrites it) before switching" + +if [ "$command" = bus ]; then + [ -x "${FLY_RELEASE_DIR}/fly-edge" ] || die "this release has no ${FLY_RELEASE_DIR}/fly-edge; bus mode needs one (deploy a release that ships it)" +fi + +take_lock +running_before="$(running)" +if [ "$before" = "$command" ] && [ "$running_before" = "$command" ] && [ "$restart" -eq 1 ]; then + log "already ${command}: fly.env says it and the running flysim started that way; nothing to do" + status_report + exit 0 +fi + +# An interrupted or failed `bus` puts the previous value back and restarts flysim on it. When +# the line already said bus (a deploy wrote it, the running flysim never started that way), the +# way back is direct: the state that worked. +back="$before" +if [ "$before" = bus ] && [ "$command" = bus ]; then back=direct; fi +switching=0 +restarted=0 +# shellcheck disable=SC2317 # runs from the EXIT trap +on_exit() { + local rc=$? + trap - EXIT INT TERM HUP + if [ "$switching" -eq 1 ]; then + switching=0 + set_via "$back" || true + record "${back} (switch to ${command} interrupted or failed (exit ${rc}); rolled back)" + if [ "$restarted" -eq 1 ]; then restart_flysim || true; fi + fi + exit "$rc" +} +trap on_exit EXIT +trap 'exit 130' INT +trap 'exit 143' TERM +trap 'exit 129' HUP + +switching=1 +set_via "$command" +record "${command} (was ${before}; flysim was running ${running_before})" +if [ "$restart" -ne 1 ]; then + switching=0 + log "FLY_FEED_VIA=${command} written; the next start of ${FLY_SERVICE} applies it" + exit 0 +fi +restarted=1 +restart_flysim +if [ "$wait_for_health" -ne 1 ]; then + switching=0 + record "${command}: flysim restart queued (--no-wait); health not checked" + log "restart queued; fly-feed status shows the result" + exit 0 +fi +if healthy "$command"; then + switching=0 + if [ "$command" = direct ] && systemctl is-active --quiet "$FLY_EDGE_SERVICE" 2>/dev/null; then + log "WARNING: ${FLY_EDGE_SERVICE} is still active in direct mode; stopping it" + systemctl stop "$FLY_EDGE_SERVICE" || true + fi + record "${command}: healthy" + log "the feed is served ${command}" + exit 0 +fi +log "the feed did not come up healthy (${command}) within ${FLY_FEED_HEALTH_TIMEOUT}s" +if [ "$command" = bus ] && [ "$rollback" -eq 1 ]; then + set_via "$back" + switching=0 + record "${back} (automatic rollback: ${command} was not healthy within ${FLY_FEED_HEALTH_TIMEOUT}s)" + restart_flysim + if healthy "$back"; then + log "rolled back to ${back}; it is healthy" + else + log "rolled back to ${back}, and it is NOT healthy either: journalctl -u ${FLY_SERVICE} -u ${FLY_EDGE_SERVICE}" + fi +else + switching=0 + record "${command}: NOT healthy; left as it is (journalctl -u ${FLY_SERVICE} -u ${FLY_EDGE_SERVICE})" +fi +exit 1 diff --git a/infra/bin/fly-watchdog b/infra/bin/fly-watchdog index 6d11c8c..807fdff 100755 --- a/infra/bin/fly-watchdog +++ b/infra/bin/fly-watchdog @@ -48,6 +48,7 @@ log_info() { # encoder actually opened (docs/design/gpu.md section 5). : "${FLY_ENCODER_METRIC:=${TEXTFILE_DIR}/fly_encoder.prom}" : "${FLY_ENV_FILE:=/etc/fly/fly.env}" +: "${FLY_PROC_DIR:=/proc}" # --- check 9 (capture freeze) inputs, infra/docs/capture-freeze.md --------- : "${FLY_REC_DIR:=/srv/fly/media/rec}" # flycast's 10-minute mpegts segments : "${FFMPEG:=/usr/bin/ffmpeg}" @@ -156,7 +157,7 @@ write_textfile_metrics() { { echo "# HELP fly_watchdog_restarts_total Restarts issued because that unit's own check failed (cascade restarts from another unit's escalation are counted only in fly_watchdog_escalations_total, not here)." echo "# TYPE fly_watchdog_restarts_total counter" - for unit in flysim flystage flycast mediamtx flypush flystage-web; do + for unit in flysim flystage flycast mediamtx flypush flystage-web flyedge; do echo "fly_watchdog_restarts_total{unit=\"${unit}\"} $(get_counter restarts_total "$unit")" done # Check 7's own restart reason, kept as a separate labelset on the @@ -357,25 +358,81 @@ check_flysim() { # bus"), which exports them under the same names. FLY_FEED_METRICS_URL in the # watchdog's own environment overrides both. # ============================================================================ +# `direct` or `bus`: who serves the feed RIGHT NOW. What fly.env says is what the next start of +# flysim does; what the running flysim started with (its environment: `fly-feed status` reads the +# same) is what is true. They differ between a deploy that changed FLY_FEED_VIA and the next +# restart, and judging the edge in that window would restart a flysim that is serving the feed +# itself. So: the running process when its environment can be read (flysim runs as the same user), +# else the file. Lowercased, because flysim reads the value case-insensitively; anything else, or +# no line, is direct. +feed_via() { + local via="" pid="" + pid="$(systemctl show -p MainPID --value flysim.service 2>/dev/null | head -n1 || true)" + if [ -n "$pid" ] && [ "$pid" != 0 ] && [ -r "${FLY_PROC_DIR}/${pid}/environ" ]; then + via="$(tr '\0' '\n' <"${FLY_PROC_DIR}/${pid}/environ" 2>/dev/null | awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)" + elif [ -f "$FLY_ENV_FILE" ]; then + via="$(awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' "$FLY_ENV_FILE" 2>/dev/null | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)" + fi + if [ "$via" = "bus" ]; then echo bus; else echo direct; fi +} + feed_metrics_url() { if [ -n "${FLY_FEED_METRICS_URL:-}" ]; then echo "$FLY_FEED_METRICS_URL" return fi - local via="" - if [ -f "$FLY_ENV_FILE" ]; then - # Lowercased: flysim reads the value case-insensitively, so `Bus` is bus mode. - via="$(awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' "$FLY_ENV_FILE" 2>/dev/null | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)" - fi - if [ "$via" = "bus" ]; then + if [ "$(feed_via)" = "bus" ]; then echo "$FLY_EDGE_METRICS_URL" else echo "$FLY_METRICS_URL" fi } +# Check 2a (FLY_FEED_VIA=bus only): the edge itself. flyedge.service active and its /healthz 200 +# (subscribed to flysim's bus, a snapshot within the last 15 s). Not judged while flysim is down +# or restarting (check 1's business: the edge follows it by itself), and one failed pass is let go: +# a flysim that has only just answered may not have published yet. After that: +# 2nd consecutive failure restart flyedge (the escalation's restart) +# 3rd and the page and the encoder (escalate's chain) +# 4th the edge cannot be kept up: the feed goes back to flysim, `fly-feed +# direct --no-wait` (a restart of flysim, one stream gap, then the page +# is served again by the process that always worked). It is logged as +# an escalation and leaves FLY_FEED_VIA=direct until an operator +# switches again; this check then does nothing. +check_flyedge() { + if [ "$(feed_via)" != "bus" ]; then + record_ok flyedge + return 0 + fi + if ! curl -fsS -o /dev/null --max-time 5 "${FLY_CONTROL_URL}/healthz" 2>/dev/null; then + return 0 + fi + if is_active flyedge.service \ + && curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null; then + record_ok flyedge + return 0 + fi + record_fail flyedge + local n + n="$(fail_count flyedge)" + if [ "$n" -ge 4 ] && fails_within_minutes flyedge 15; then + log_err "flyedge: ${n} consecutive failures, restarts did not bring it back: switching the feed to direct (fly-feed direct)" + inc_counter "escalations_total" + sudo /opt/fly/bin/fly-feed direct --no-wait || log_err "fly-feed direct FAILED; the edge stays down" + record_ok flyedge + elif [ "$n" -ge 2 ]; then + escalate flyedge flystage flycast + fi +} + check_flystage() { - local metrics frames clients ok=1 + local metrics frames clients ok=1 chain=(flycast) + if [ "$(feed_via)" = "bus" ] && [ -z "${FLY_FEED_METRICS_URL:-}" ]; then + # The edge serves the page. While it is down or silent that is check 2a's to fix, and a + # restarted page would only reconnect to nothing (and count towards a reboot). + curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null || return 0 + chain=(flyedge flycast) + fi metrics="$(curl -fsS "$(feed_metrics_url)/metrics" 2>/dev/null || true)" if [ -z "$metrics" ]; then ok=0 @@ -402,7 +459,7 @@ check_flystage() { record_ok flystage else record_fail flystage - escalate flystage flycast + escalate flystage "${chain[@]}" fi } @@ -1227,6 +1284,7 @@ check_loop() { main() { check_flysim + check_flyedge check_flystage check_flycast check_encoder diff --git a/infra/config/fly-sudoers b/infra/config/fly-sudoers index 8963a18..409ec9a 100644 --- a/infra/config/fly-sudoers +++ b/infra/config/fly-sudoers @@ -6,12 +6,13 @@ # ` and, on the 5-consecutive-failure escalation, a container # reboot. This is the minimum NOPASSWD surface for exactly what # bin/fly-watchdog's checks actually restart (flysim, flystage, flycast, -# mediamtx, flypush), plus reboot. No `systemctl stop`, no +# mediamtx, flypush, flyedge in bus mode), plus reboot. No `systemctl stop`, no # `enable`/`disable`, no arbitrary unit name, and no units this script # does not itself restart (xvfb, pulse, flystage-web are never touched by # fly-watchdog's checks, so they are not granted here). fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flysim.service fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flystage.service +fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flyedge.service fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flycast.service fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart mediamtx.service fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flypush.service @@ -20,3 +21,6 @@ fly ALL=(root) NOPASSWD: /usr/sbin/reboot # resets to a milestone archive through this one root wrapper, which validates the rung, # stops/resets/starts flysim and nothing else (infra/docs/loop-recovery.md). fly ALL=(root) NOPASSWD: /opt/fly/bin/fly-loop-reset +# Watchdog check 2a (FLY_FEED_VIA=bus): an edge that restarts cannot fix puts the feed back on +# flysim, with exactly these arguments and nothing else (infra/bin/fly-feed). +fly ALL=(root) NOPASSWD: /opt/fly/bin/fly-feed direct --no-wait diff --git a/infra/tests/lint.sh b/infra/tests/lint.sh index b8ad3d5..cdc3d12 100755 --- a/infra/tests/lint.sh +++ b/infra/tests/lint.sh @@ -459,9 +459,6 @@ else grep -qE '^ConditionPathExists=/opt/fly/current/fly-edge$' "$EDGE_UNIT" \ && pass "flyedge.service stays inactive on a release without fly-edge" \ || fail "flyedge.service needs ConditionPathExists=/opt/fly/current/fly-edge (a release before it has none)" - grep -qE '^Environment=FLY_EDGE_METRICS_ADDR=127\.0\.0\.1:' "$EDGE_UNIT" \ - && pass "flyedge.service keeps its metrics on loopback" \ - || fail "flyedge.service FLY_EDGE_METRICS_ADDR must be a 127.0.0.1 address" fi # Every unit a target's Wants=/Requires= names, with backslash continuations joined and # comments dropped: fly.target spreads both lists over several physical lines, and the @@ -1400,6 +1397,354 @@ else rm -rf "$fe_fixture" fi +# --------------------------------------------------------------------------- +# 3b2b. EDGE-02: the feed on the bus in production. fly.env's FLY_FEED_VIA is the one switch: +# flysim.service Wants= the edge, the edge's ExecCondition= skips it in direct mode, `fly-feed` +# rewrites the line and restarts flysim, the watchdog judges the edge only while flysim itself +# serves it through the bus. Driven for real against stubs. +# --------------------------------------------------------------------------- +echo "--- EDGE-02: flyedge is skipped in direct mode, started by every flysim start in bus mode ---" +grep -qE '^Wants=.*\bflyedge\.service\b' "$INFRA_DIR/units/flysim.service" \ + && pass "flysim.service Wants=flyedge.service (every flysim start brings the edge up in bus mode)" \ + || fail "flysim.service must Want flyedge.service: a stop and start of flysim (fly-loop-reset) would leave the edge down" +grep -qE '^ExecCondition=.*FLY_FEED_VIA.*\[Bb\]\[Uu\]\[Ss\]' "$EDGE_UNIT" \ + && pass "flyedge.service runs only when FLY_FEED_VIA is bus (ExecCondition=, any case)" \ + || fail "flyedge.service needs an ExecCondition= on FLY_FEED_VIA (case-insensitive bus)" +if grep -qE '^\[Install\]' "$EDGE_UNIT"; then + fail "flyedge.service has an [Install] section; flysim's Wants= is what starts it" +else + pass "flyedge.service has no [Install] section" +fi +grep -qE '^Environment=FLY_EDGE_METRICS_ADDR=[0-9.]+:9102$' "$EDGE_UNIT" \ + && pass "flyedge.service serves its metrics on :9102 (the dashboard's second target; the watchdog uses loopback)" \ + || fail "flyedge.service FLY_EDGE_METRICS_ADDR must be an address on :9102" +if grep -qE '^Wants=.*flyedge' "$INFRA_DIR/units/flysim-session.service"; then + fail "flysim-session.service Wants flyedge.service, whose Requires=flysim.service would start the unit it Conflicts with" +else + pass "flysim-session.service (the standalone rehearsal unit) does not pull the edge in" +fi +grep -qE 'for name in .*\bfly-feed\b.*; do$' "$INFRA_DIR/05-deploy.sh" \ + && pass "05-deploy.sh installs fly-feed" \ + || fail "05-deploy.sh must converge bin/fly-feed to /opt/fly/bin" +grep -qF 'this release has no fly-edge' "$INFRA_DIR/05-deploy.sh" \ + && grep -qF '"${release_path}/fly-edge"' "$INFRA_DIR/05-deploy.sh" \ + && pass "05-deploy.sh refuses a release without fly-edge while the feed is on the bus (before the symlink moves)" \ + || fail "05-deploy.sh must refuse a release without fly-edge when FLY_FEED_VIA is bus (env file or container)" +grep -qE '^fly ALL=\(root\) NOPASSWD: /usr/bin/systemctl restart flyedge\.service$' "$INFRA_DIR/config/fly-sudoers" \ + && grep -qE '^fly ALL=\(root\) NOPASSWD: /opt/fly/bin/fly-feed direct --no-wait$' "$INFRA_DIR/config/fly-sudoers" \ + && pass "sudoers lets the watchdog restart flyedge and run exactly 'fly-feed direct --no-wait'" \ + || fail "config/fly-sudoers must grant the watchdog 'systemctl restart flyedge.service' and 'fly-feed direct --no-wait'" + +echo "--- fly-feed: bus, direct, status, rollback ---" +ff_dir="$(mktemp -d "${TMPDIR:-/tmp}/fly-lint-feed.XXXXXX")" +mkdir -p "$ff_dir/bin" "$ff_dir/release" "$ff_dir/proc/4242" "$ff_dir/run" +cat > "$ff_dir/bin/systemctl" <<'FFSTUB' +#!/usr/bin/env bash +echo "$*" >> "$FF_DIR/systemctl.log" +case "$1" in + restart) n=$(( $(cat "$FF_DIR/invocation" 2>/dev/null || echo 1) + 1 )); echo "$n" > "$FF_DIR/invocation" + # the new flysim's environment is whatever fly.env says now + v="$(awk -F= '/^FLY_FEED_VIA=/ { v=$2 } END { print v }' "$FF_ENV")" + printf 'FLY_FEED_VIA=%s\0' "$v" > "$FF_DIR/proc/4242/environ" ;; + show) case "$*" in + *MainPID*) echo 4242 ;; + *InvocationID*) echo "inv$(cat "$FF_DIR/invocation" 2>/dev/null || echo 1)" ;; + esac ;; + is-active) + case "${*: -1}" in + flystage.service) [ "${FF_PAGE:-1}" = 1 ]; exit $? ;; + flyedge.service) [ "${FF_EDGE_ACTIVE:-0}" = 1 ]; exit $? ;; + esac ;; +esac +exit 0 +FFSTUB +cat > "$ff_dir/bin/curl" <<'FFSTUB' +#!/usr/bin/env bash +url="${*: -1}" +quiet=0; for a in "$@"; do [ "$a" = /dev/null ] && quiet=1; done +case "$url" in + http://control/healthz) [ "${FF_CONTROL_OK:-1}" = 1 ] || exit 22; exit 0 ;; + http://edge/healthz) [ "${FF_EDGE_OK:-1}" = 1 ] || exit 22; exit 0 ;; + http://sim/metrics|http://edge/metrics) + n=$(( $(cat "$FF_DIR/frames" 2>/dev/null || echo 1000) + 30 )); echo "$n" > "$FF_DIR/frames" + [ "${FF_FLAT:-0}" = 1 ] && n=1000 + echo "fly_feed_clients ${FF_CLIENTS:-1}"; echo "fly_frames_sent_total $n" + echo "fly_edge_snapshot_age_seconds 0.03"; echo "fly_edge_bus_lost_total 0" ;; + *) exit 22 ;; +esac +FFSTUB +printf '#!/usr/bin/env bash\necho 0\n' > "$ff_dir/bin/id" +printf '#!/usr/bin/env bash\ntrue\n' > "$ff_dir/bin/logger" +printf '#!/usr/bin/env bash\ntrue\n' > "$ff_dir/release/fly-edge" +chmod +x "$ff_dir"/bin/* "$ff_dir/release/fly-edge" +ff_env="$ff_dir/fly.env" +fly_feed() { + env FF_DIR="$ff_dir" FF_ENV="$ff_env" PATH="$ff_dir/bin:$PATH" FLY_ENV_FILE="$ff_env" \ + FLY_RELEASE_DIR="$ff_dir/release" FLY_PROC_DIR="$ff_dir/proc" FLY_FEED_LOG="$ff_dir/feed.log" \ + FLY_FEED_LOCK="$ff_dir/run/feed.lock" FLY_CONTROL_URL=http://control FLY_METRICS_URL=http://sim \ + FLY_EDGE_METRICS_URL=http://edge FLY_FEED_HEALTH_TIMEOUT=3 FLY_FEED_SAMPLE_SECONDS=0 \ + "$@" bash "$INFRA_DIR/bin/fly-feed" "${FF_ARGS[@]}" +} +ff_reset() { # ff_reset VIA_IN_FILE VIA_RUNNING + printf 'FLY_GAME=pokemon-red\nFLY_FEED_VIA=%s\nFLY_MACRO_MODE=raw\n' "$1" > "$ff_env" + chmod 0640 "$ff_env" + printf 'FLY_FEED_VIA=%s\0' "$2" > "$ff_dir/proc/4242/environ" + : > "$ff_dir/systemctl.log"; rm -f "$ff_dir/feed.log" "$ff_dir/frames" "$ff_dir/invocation" +} +ff_restarts() { grep -c '^restart --no-block flysim.service$' "$ff_dir/systemctl.log" || true; } + +ff_reset direct direct +FF_ARGS=(status) +ff_out="$(fly_feed 2>&1 || true)" +if printf '%s\n' "$ff_out" | grep -qx 'configured: direct' && printf '%s\n' "$ff_out" | grep -qx 'running: direct'; then + pass "fly-feed status: direct, running direct" +else + fail "fly-feed status wrong: $ff_out" +fi + +ff_reset direct direct +FF_ARGS=(bus) +if fly_feed && [ "$(grep -c '^FLY_FEED_VIA=' "$ff_env")" = 1 ] && grep -qx 'FLY_FEED_VIA=bus' "$ff_env" \ + && grep -qx 'FLY_GAME=pokemon-red' "$ff_env" && grep -qx 'FLY_MACRO_MODE=raw' "$ff_env" \ + && [ "$(stat -c %a "$ff_env")" = 640 ] && [ "$(ff_restarts)" = 1 ] && grep -q 'bus: healthy' "$ff_dir/feed.log"; then + pass "fly-feed bus: one FLY_FEED_VIA line, the rest and the mode kept, flysim restarted once, healthy on the edge's counters" +else + fail "fly-feed bus: wrong ($(tr '\n' ' ' < "$ff_env"); restarts $(ff_restarts); $(cat "$ff_dir/feed.log" 2>/dev/null))" +fi +FF_ARGS=(bus) +: > "$ff_dir/systemctl.log" +if fly_feed && [ "$(ff_restarts)" = 0 ]; then + pass "fly-feed bus when already bus and running bus: nothing to do, no restart" +else + fail "fly-feed bus must not restart flysim when fly.env and the running process already say bus" +fi +# A deploy wrote bus but the running flysim started direct: `bus` applies it (and a bus fly.env is not its own way back). +ff_reset bus direct +FF_ARGS=(bus) +if fly_feed && [ "$(ff_restarts)" = 1 ] && grep -qx 'FLY_FEED_VIA=bus' "$ff_env"; then + pass "fly-feed bus applies a fly.env that says bus to a flysim that started direct" +else + fail "fly-feed bus must restart flysim when fly.env says bus and it is running direct" +fi +ff_reset bus bus +FF_ARGS=(status) +ff_out="$(fly_feed 2>&1 || true)" +if printf '%s\n' "$ff_out" | grep -q '^edge healthz: ok'; then + pass "fly-feed status in bus mode reads the edge" +else + fail "fly-feed status in bus mode must report the edge's healthz" +fi +ff_reset Bus direct +FF_ARGS=(status) +ff_out="$(fly_feed 2>&1 || true)" +printf '%s\n' "$ff_out" | grep -qx 'configured: bus' \ + && pass "fly-feed reads FLY_FEED_VIA=Bus as bus (flysim lowercases it)" \ + || fail "fly-feed must read FLY_FEED_VIA case-insensitively" + +# A bus that never becomes healthy (the edge answers 503) rolls back to direct and says so. +ff_reset direct direct +FF_ARGS=(bus) +if fly_feed FF_EDGE_OK=0; then + fail "fly-feed bus must exit non-zero when the edge never becomes healthy" +elif grep -qx 'FLY_FEED_VIA=direct' "$ff_env" && [ "$(ff_restarts)" = 2 ] && grep -q 'automatic rollback' "$ff_dir/feed.log"; then + pass "fly-feed bus rolls back to direct, restarting flysim again, when the edge is not healthy" +else + fail "fly-feed bus rollback wrong ($(grep FLY_FEED_VIA "$ff_env"); restarts $(ff_restarts))" +fi +# A page that never reaches the feed (no clients) is not healthy either; --no-rollback leaves the switch in place. +ff_reset direct direct +FF_ARGS=(bus) +if fly_feed FF_CLIENTS=0; then + fail "fly-feed bus must not call a feed with no page on it healthy while flystage is active" +elif grep -qx 'FLY_FEED_VIA=direct' "$ff_env"; then + pass "fly-feed bus: a page that never connects is a failed switch, rolled back" +else + fail "fly-feed bus with no client must roll back" +fi +ff_reset direct direct +FF_ARGS=(bus --no-rollback) +if fly_feed FF_EDGE_OK=0; then + fail "--no-rollback: must still fail" +elif grep -qx 'FLY_FEED_VIA=bus' "$ff_env" && [ "$(ff_restarts)" = 1 ]; then + pass "fly-feed bus --no-rollback leaves the switch as it is when unhealthy" +else + fail "--no-rollback must leave FLY_FEED_VIA=bus and restart once" +fi +# Frames that never advance are not a feed. +ff_reset direct direct +FF_ARGS=(bus) +if fly_feed FF_FLAT=1; then fail "flat frames counter must not be healthy"; else pass "fly-feed bus: a frames counter that does not move is not healthy"; fi +# No page unit: the wait ends at the edge's healthz. +ff_reset direct direct +FF_ARGS=(bus) +fly_feed FF_PAGE=0 FF_CLIENTS=0 \ + && pass "fly-feed bus on a box with no active page unit waits for the edge only" \ + || fail "fly-feed bus with flystage inactive must succeed on the edge's healthz alone" +# A release without fly-edge refuses before touching anything. +ff_reset direct direct +rm -f "$ff_dir/release/fly-edge" +FF_ARGS=(bus) +if fly_feed; then + fail "fly-feed bus must refuse a release without fly-edge" +elif grep -qx 'FLY_FEED_VIA=direct' "$ff_env" && [ "$(ff_restarts)" = 0 ]; then + pass "fly-feed bus refuses a release without fly-edge, changing and restarting nothing" +else + fail "refusal must leave fly.env and flysim alone" +fi +printf '#!/usr/bin/env bash\ntrue\n' > "$ff_dir/release/fly-edge"; chmod +x "$ff_dir/release/fly-edge" +# direct: the way back, which works with no fly-edge at all and stops a lingering edge. +ff_reset bus bus +rm -f "$ff_dir/release/fly-edge" +FF_ARGS=(direct) +if fly_feed FF_EDGE_ACTIVE=1 && grep -qx 'FLY_FEED_VIA=direct' "$ff_env" && [ "$(ff_restarts)" = 1 ] \ + && grep -qx 'stop flyedge.service' "$ff_dir/systemctl.log" && grep -q 'direct: healthy' "$ff_dir/feed.log"; then + pass "fly-feed direct: back to flysim on :7400 with no fly-edge in the release, a lingering edge stopped" +else + fail "fly-feed direct wrong ($(grep FLY_FEED_VIA "$ff_env"); $(cat "$ff_dir/systemctl.log" | tr '\n' ';'))" +fi +printf '#!/usr/bin/env bash\ntrue\n' > "$ff_dir/release/fly-edge"; chmod +x "$ff_dir/release/fly-edge" +ff_reset bus bus +FF_ARGS=(direct --no-restart) +fly_feed && grep -qx 'FLY_FEED_VIA=direct' "$ff_env" && [ "$(ff_restarts)" = 0 ] \ + && pass "fly-feed direct --no-restart writes the line and restarts nothing" \ + || fail "--no-restart must only write fly.env" +ff_reset bus bus +FF_ARGS=(direct --no-wait) +fly_feed FF_CONTROL_OK=0 && [ "$(ff_restarts)" = 1 ] && grep -qx 'FLY_FEED_VIA=direct' "$ff_env" \ + && pass "fly-feed direct --no-wait (the watchdog's fallback) restarts flysim and returns without a health wait" \ + || fail "--no-wait must restart flysim and return 0 whatever the health" +ff_reset 'buss' direct +FF_ARGS=(bus) +if fly_feed; then fail "fly-feed must refuse an invalid FLY_FEED_VIA"; else pass "fly-feed refuses an invalid FLY_FEED_VIA in fly.env, touching nothing"; fi +# An interrupted switch (INT/TERM/HUP) rolls back: the stub restart hangs the health wait; kill it mid-way. +ff_reset direct direct +FF_ARGS=(bus) +env FF_DIR="$ff_dir" FF_ENV="$ff_env" PATH="$ff_dir/bin:$PATH" FLY_ENV_FILE="$ff_env" \ + FLY_RELEASE_DIR="$ff_dir/release" FLY_PROC_DIR="$ff_dir/proc" FLY_FEED_LOG="$ff_dir/feed.log" \ + FLY_FEED_LOCK="$ff_dir/run/feed.lock" FLY_CONTROL_URL=http://control FLY_METRICS_URL=http://sim \ + FLY_EDGE_METRICS_URL=http://edge FLY_FEED_HEALTH_TIMEOUT=30 FLY_FEED_SAMPLE_SECONDS=0 FF_EDGE_OK=0 \ + bash "$INFRA_DIR/bin/fly-feed" bus >/dev/null 2>&1 & +ff_pid=$! +sleep 2 +kill -TERM "$ff_pid" 2>/dev/null || true +for _ in 1 2 3 4 5 6 7 8 9 10; do kill -0 "$ff_pid" 2>/dev/null || break; sleep 0.5; done +(kill -0 "$ff_pid" 2>/dev/null && kill -KILL "$ff_pid" 2>/dev/null) || true +wait "$ff_pid" 2>/dev/null || true +if grep -qx 'FLY_FEED_VIA=direct' "$ff_env" && grep -q 'interrupted or failed' "$ff_dir/feed.log" 2>/dev/null; then + pass "fly-feed bus interrupted mid-switch puts FLY_FEED_VIA back" +else + fail "an interrupted fly-feed bus must roll back ($(grep FLY_FEED_VIA "$ff_env"); $(cat "$ff_dir/feed.log" 2>/dev/null | tr '\n' ';'))" +fi +rm -rf "$ff_dir" + +echo "--- fly-watchdog: check 2a (the edge) and check 2 in bus mode ---" +wf_dir="$(mktemp -d "${TMPDIR:-/tmp}/fly-lint-wdedge.XXXXXX")" +mkdir -p "$wf_dir/bin" "$wf_dir/proc/4242" "$wf_dir/run" "$wf_dir/state" "$wf_dir/textfile" +cat > "$wf_dir/bin/systemctl" <<'WFSTUB' +#!/usr/bin/env bash +case "$1" in + show) echo 4242 ;; + is-active) [ "${WF_EDGE_ACTIVE:-1}" = 1 ]; exit $? ;; + restart) echo "restart $2" >> "$WF_DIR/actions.log" ;; +esac +exit 0 +WFSTUB +cat > "$wf_dir/bin/sudo" <<'WFSTUB' +#!/usr/bin/env bash +if [ "$1" = /usr/bin/systemctl ]; then shift; exec systemctl "$@"; fi +echo "sudo $*" >> "$WF_DIR/actions.log" +exit 0 +WFSTUB +cat > "$wf_dir/bin/curl" <<'WFSTUB' +#!/usr/bin/env bash +url="${*: -1}" +case "$url" in + http://control/healthz) [ "${WF_CONTROL_OK:-1}" = 1 ] || exit 22 ;; + http://edge/healthz) [ "${WF_EDGE_OK:-1}" = 1 ] || exit 22 ;; + http://edge/metrics) echo "fly_frames_sent_total ${WF_EDGE_FRAMES:-100}"; echo "fly_feed_clients 1" ;; + http://sim/metrics) echo "fly_frames_sent_total ${WF_SIM_FRAMES:-0}"; echo "fly_feed_clients 0" ;; + *) exit 22 ;; +esac +WFSTUB +printf '#!/usr/bin/env bash\ncat >/dev/null\n' > "$wf_dir/bin/systemd-cat" +chmod +x "$wf_dir"/bin/* +sed '$d' "$INFRA_DIR/bin/fly-watchdog" > "$wf_dir/wd.sh" +wd_edge() { # wd_edge VIA_RUNNING 'ENV...' -- COMMANDS + local via="$1"; shift + printf 'FLY_FEED_VIA=%s\0' "$via" > "$wf_dir/proc/4242/environ" + env WF_DIR="$wf_dir" PATH="$wf_dir/bin:$PATH" FLY_PROC_DIR="$wf_dir/proc" FLY_ENV_FILE="$wf_dir/fly.env" \ + FLY_CONTROL_URL=http://control FLY_METRICS_URL=http://sim FLY_EDGE_METRICS_URL=http://edge \ + WD_RUN_DIR="$wf_dir/run" WD_STATE_DIR="$wf_dir/state" TEXTFILE_DIR="$wf_dir/textfile" \ + "$@" bash -c "source '$wf_dir/wd.sh'; $WD_CMDS" >/dev/null 2>&1 || true +} +wd_acts() { cat "$wf_dir/actions.log" 2>/dev/null | tr '\n' ';'; } +wd_reset() { : > "$wf_dir/actions.log"; rm -f "$wf_dir/run"/*; } +echo 'FLY_FEED_VIA=bus' > "$wf_dir/fly.env" + +wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge' +wd_edge direct +[ -z "$(wd_acts)" ] && pass "check 2a does nothing in direct mode" || fail "check 2a acted in direct mode: $(wd_acts)" +wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge; check_flyedge' +wd_edge bus WF_EDGE_OK=0 WF_CONTROL_OK=0 +[ -z "$(wd_acts)" ] && pass "check 2a leaves a down flysim to check 1" || fail "check 2a acted while flysim was down: $(wd_acts)" +wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge' +wd_edge bus WF_EDGE_OK=1 +[ -z "$(wd_acts)" ] && pass "check 2a: a healthy edge is left alone" || fail "check 2a acted on a healthy edge: $(wd_acts)" +wd_reset; WD_CMDS='check_flyedge' +wd_edge bus WF_EDGE_OK=0 +[ -z "$(wd_acts)" ] && pass "check 2a lets the first failed pass go (a flysim that only just answered)" || fail "check 2a acted on the first failure: $(wd_acts)" +wd_reset; WD_CMDS='check_flyedge; check_flyedge' +wd_edge bus WF_EDGE_OK=0 +case "$(wd_acts)" in + "restart flyedge.service;") pass "check 2a: the second failed pass restarts flyedge" ;; + *) fail "check 2a second failure should restart flyedge only: $(wd_acts)" ;; +esac +wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge' +wd_edge bus WF_EDGE_OK=0 +case "$(wd_acts)" in + "restart flyedge.service;restart flyedge.service;restart flystage.service;restart flycast.service;") pass "check 2a: the third restarts the page and the encoder as well" ;; + *) fail "check 2a third failure: $(wd_acts)" ;; +esac +wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge; check_flyedge' +wd_edge bus WF_EDGE_OK=0 +case "$(wd_acts)" in + *"sudo /opt/fly/bin/fly-feed direct --no-wait;") pass "check 2a: the fourth failed pass puts the feed back on flysim (fly-feed direct --no-wait)" ;; + *) fail "check 2a fourth failure must run fly-feed direct --no-wait: $(wd_acts)" ;; +esac +wd_reset; WD_CMDS='check_flyedge; check_flyedge' +wd_edge bus WF_EDGE_OK=1 WF_EDGE_ACTIVE=0 +case "$(wd_acts)" in + "restart flyedge.service;") pass "check 2a: an inactive edge in bus mode is a failure like an unhealthy one" ;; + *) fail "check 2a inactive edge: $(wd_acts)" ;; +esac +# fly.env says bus but the running flysim started direct (a deploy, not yet restarted): it serves the feed itself. +wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge; check_flyedge' +wd_edge direct WF_EDGE_OK=0 WF_EDGE_ACTIVE=0 +[ -z "$(wd_acts)" ] && pass "check 2a follows the running flysim, not fly.env: a pending switch is not an outage" || fail "check 2a acted on a pending switch: $(wd_acts)" +WD_CMDS='feed_metrics_url' +got="$(printf 'FLY_FEED_VIA=direct\0' > "$wf_dir/proc/4242/environ"; env WF_DIR="$wf_dir" PATH="$wf_dir/bin:$PATH" FLY_PROC_DIR="$wf_dir/proc" FLY_ENV_FILE="$wf_dir/fly.env" FLY_METRICS_URL=http://sim FLY_EDGE_METRICS_URL=http://edge WD_RUN_DIR="$wf_dir/run" WD_STATE_DIR="$wf_dir/state" TEXTFILE_DIR="$wf_dir/textfile" bash -c "source '$wf_dir/wd.sh'; feed_metrics_url" 2>/dev/null || true)" +[ "$got" = http://sim ] && pass "check 2 reads flysim's counters while the running flysim serves the feed itself" || fail "check 2 URL for a pending switch: $got" + +# Check 2 in bus mode: an unhealthy edge is check 2a's, not a reason to restart the page; a healthy +# edge with a flat frames counter restarts the page and, after three, the edge and the encoder. +wd_reset; WD_CMDS='check_flystage; check_flystage; check_flystage' +wd_edge bus WF_EDGE_OK=0 +[ -z "$(wd_acts)" ] && pass "check 2 in bus mode leaves a silent edge to check 2a (the page is not restarted)" || fail "check 2 restarted things while the edge was down: $(wd_acts)" +wd_reset; WD_CMDS='check_flystage; check_flystage; check_flystage; check_flystage' +wd_edge bus WF_EDGE_OK=1 WF_EDGE_FRAMES=100 +case "$(wd_acts)" in + "restart flystage.service;restart flystage.service;restart flystage.service;restart flyedge.service;restart flycast.service;") + pass "check 2 in bus mode: frames flat restarts the page, then the edge and the encoder in the chain" ;; + *) fail "check 2 bus chain: $(wd_acts)" ;; +esac +wd_reset; WD_CMDS='check_flystage; check_flystage; check_flystage; check_flystage' +wd_edge direct WF_SIM_FRAMES=100 +case "$(wd_acts)" in + *"restart flyedge"*) fail "check 2 in direct mode must not touch the edge: $(wd_acts)" ;; + *) pass "check 2 in direct mode never restarts the edge" ;; +esac +rm -rf "$wf_dir" + # --------------------------------------------------------------------------- # 3c. lib/common.sh cpuset_partition — the three-way cpuset split used by # 05-deploy.sh section 3b (flysim / page-capture / flycast). Run as its own diff --git a/infra/units/flyedge.service b/infra/units/flyedge.service index a0d0f17..f08e86c 100644 --- a/infra/units/flyedge.service +++ b/infra/units/flyedge.service @@ -1,30 +1,41 @@ # infra/units/flyedge.service — pushed to /etc/systemd/system/flyedge.service. # # The feed WebSocket served from flysim's feed bus (docs/design/flybus.md, -# "Feed over the bus"; services/flysim/crates/fly-edge). DISABLED BY DEFAULT: -# it is in no target's Wants=/Requires= and 07-enable.sh does not enable it. -# With FLY_FEED_VIA=direct (the default, written into /etc/fly/fly.env by -# 05-deploy.sh) flysim binds 127.0.0.1:7400 itself and this unit has nothing -# to do. To move the feed onto the bus on one container: +# "Feed over the bus"; services/flysim/crates/fly-edge). Whether it runs is +# decided by one line, FLY_FEED_VIA in /etc/fly/fly.env (05-deploy.sh writes it +# from the env file's FLY_FEED_VIA, default `direct`): # -# 1. FLY_FEED_VIA=bus in the env file, then 05-deploy.sh (rewrites fly.env); -# 2. systemctl enable --now flyedge.service; systemctl restart flysim.service -# (flysim stops binding :7400, the edge binds it once the first snapshot -# is on the bus); -# 3. nothing for the watchdog: check 2 reads FLY_FEED_VIA from fly.env and -# follows the feed counters to this unit's loopback /metrics. +# direct flysim binds 127.0.0.1:7400 itself. ExecCondition= below fails, so +# this unit starts as "skipped" (inactive, no failure, no restart). +# bus flysim publishes on its feed bus and leaves :7400 to this unit. # -# Back: FLY_FEED_VIA=direct, deploy, systemctl disable --now flyedge.service, -# restart flysim. +# flysim.service has Wants= on this unit, so EVERY start of flysim (the unstick +# rule's restart, fly-loop-reset's stop and start, fly-reset-to-milestone, a +# crash-restart, a reboot through fly.target) starts the edge in bus mode and +# skips it in direct mode; fly.env alone decides, and flysim and the edge can +# never disagree. This unit is in no target and has no [Install] section: +# `systemctl enable` has nothing to do. +# +# Switching a running container (infra/bin/fly-feed, "Feed over the bus" in +# docs/runbook.md; it is the whole procedure, with a health check and its own +# rollback): +# +# fly-feed bus FLY_FEED_VIA=bus in fly.env, restart flysim, wait for +# the edge and a client +# fly-feed direct the way back # # Ordering (docs/design/flybus.md, amendment "Feed store lifecycle"): flysim -# owns the router and its store under /run/fly/bus, so it starts first and -# the edge follows it. Requires= makes an explicit stop or restart of flysim -# (the unstick rule's `systemctl restart flysim.service` included) stop or -# restart the edge with it. A crash-restart of flysim is covered by the edge -# itself: it drops its clients, unbinds :7400 and reconnects every 500 ms, -# so nothing here has to be restarted by hand. The edge holds no state; the -# store is flysim's and a new router removes the previous one's directory. +# owns the router and its store under /run/fly/bus, so it starts first and the +# edge follows it. Requires= makes an explicit stop or restart of flysim stop +# or restart the edge with it. A crash-restart of flysim is covered by the edge +# itself: it drops its clients, unbinds :7400 and reconnects every 500 ms, so +# nothing here has to be restarted by hand. The edge holds no state; the store +# is flysim's and a new router removes the previous one's directory. +# +# CPUs: 05-deploy.sh writes this unit's cpuset drop-in on the page CPUs, never +# flysim's (the sim's CPUs are the sim's alone, docs/runbook.md "CPU partition"). +# The router and the publisher run inside flysim, on its own two-thread bus +# runtime. [Unit] Description=flyedge: the feed WebSocket served from flysim's feed bus After=flysim.service @@ -42,15 +53,17 @@ User=fly EnvironmentFile=/etc/fly/fly.env Environment=FLY_FEED_BIND=127.0.0.1:7400 Environment=FLY_BUS_DIR=/run/fly/bus -# Its own read-only /metrics and /healthz, for watchdog check 2 in bus mode. -# Loopback only: nothing off the container needs the edge's counters. -Environment=FLY_EDGE_METRICS_ADDR=127.0.0.1:9102 +# Its own read-only /metrics and /healthz: watchdog check 2 reads them in bus mode (over +# loopback), and so can the metrics dashboard, as a second target beside flysim's :9101, which +# reads 0 for the feed counters in bus mode. Same exposure as :9101 (the container's network). +Environment=FLY_EDGE_METRICS_ADDR=0.0.0.0:9102 +# Only in bus mode. EnvironmentFile= is the same fly.env flysim reads, so this is the value +# flysim started with (flysim reads it case-insensitively, so does this). Exit 1 means +# "skip": the unit goes inactive without failing and without being restarted. +ExecCondition=/bin/sh -c 'case "$$FLY_FEED_VIA" in [Bb][Uu][Ss]) ;; *) exit 1;; esac' ExecStart=/opt/fly/current/fly-edge Restart=always RestartSec=2 # A few snapshots in flight and a WebSocket per client; the store itself is # flysim's (tmpfs, bounded by feedbus::limits at 32 MiB). MemoryMax=256M - -[Install] -WantedBy=fly.target diff --git a/infra/units/flysim.service b/infra/units/flysim.service index dd0f6c0..1d7c72b 100644 --- a/infra/units/flysim.service +++ b/infra/units/flysim.service @@ -14,6 +14,11 @@ [Unit] Description=flysim: the fly brain, emulator, and control/feed APIs After=network.target +# Every start of flysim starts the feed edge when fly.env says FLY_FEED_VIA=bus, and skips it in +# direct mode (units/flyedge.service decides): a stop and start of flysim (fly-loop-reset, +# fly-reset-to-milestone) would otherwise leave the stage with nothing on :7400, because +# flyedge.service's Requires= stops the edge with flysim but does not bring it back. +Wants=flyedge.service StartLimitIntervalSec=300 StartLimitBurst=5 From 5ca3488c1f68033ecbedc01076e88c7b949d8f6d Mon Sep 17 00:00:00 2001 From: acamilo Date: Thu, 1 Oct 2026 23:17:58 +0000 Subject: [PATCH 04/27] runbook, flybus and tour: the feed over the bus in production --- docs/architecture-tour.md | 3 +- docs/design/flybus.md | 47 +++++++++++++++- infra/docs/runbook.md | 112 ++++++++++++++++++++++++++++++++++++++ infra/env/example.env | 9 ++- 4 files changed, 166 insertions(+), 5 deletions(-) diff --git a/docs/architecture-tour.md b/docs/architecture-tour.md index 1fb4c85..0742a68 100644 --- a/docs/architecture-tour.md +++ b/docs/architecture-tour.md @@ -136,7 +136,8 @@ publish. Pacing uses absolute deadlines at 1.0x by default; it never skips frame audio (binjgb's unipolar u8 converted and DC-blocked), and a 17,407-byte spike bitset. flysim serves it itself by default; with `FLY_FEED_VIA=bus` it publishes each snapshot on an embedded flybus router and the `fly-edge` process serves the same bytes - (`docs/design/flybus.md`, "Feed over the bus"). + (`docs/design/flybus.md`, "Feed over the bus"; on a container `fly-feed bus|direct` switches, runbook + "Feed over the bus"). - Control API (`docs/control-api.md`): loopback HTTP :7401. `POST /stimulate` (sugar: a timed PAM pulse, rate-limited server side), `POST /reward` (present, disabled by config), `POST /chat` (sanitized, deny-listed, ring of 12), `/status`, `/checkpoint`, `/pause`, `/resume`, diff --git a/docs/design/flybus.md b/docs/design/flybus.md index 1245167..9b681ca 100644 --- a/docs/design/flybus.md +++ b/docs/design/flybus.md @@ -1,7 +1,8 @@ # flybus: the communications bus -Status: **crate landed; the feed rides it behind `FLY_FEED_VIA=bus`, off by default**. -Written 2026-09-22, amended 2026-09-23 (EDGE-01, below). Index only; the +Status: **crate landed; the feed rides it behind `FLY_FEED_VIA=bus`, off by default; EDGE-02 +(2026-10-01) made it switchable in production with one command, `fly-feed bus|direct`**. +Written 2026-09-22, amended 2026-09-23 (EDGE-01) and 2026-10-01 (EDGE-02, below). Index only; the authority for the API and the wire format is the crate's own [README](../../services/flysim/crates/flybus/README.md), and the audit of the crate against the draft is the [conformance report](session-framework/bus-conformance.md). @@ -188,3 +189,45 @@ Accepted for now and written down rather than fixed: escalates. Switch back to `direct` first (the unit header's way back), then roll back. - **Old fixtures.** `cold-open`, `steady` and `big-moment` predate `game.scene` and cannot be a Rust `FeedHeader`, so fixture parity covers `macros`, `shop`, `center` and `bigpad`. + +### Amendment 2026-10-01: the feed in production (EDGE-02) + +- **The session runtime needed nothing.** `flysim-session` serves its listeners through + `flysim::serve`, the same function `flysim` does, so `FLY_FEED_VIA=bus` works on it as it was + written for legacy. It is now a test, not an inference: `fly-legacy-session/tests/feed_bus.rs` + runs the real `flysim-session` binary (toy connectome, the real cartridge) twice from copies of + one store, direct and bus, records both feeds over a WebSocket and requires every frame in + common to be identical (header minus the wall-clock fields, frame, audio and spike bytes), then + stops the binary and starts a new one under the same edge, which must unbind, reconnect and + serve. In the session runtime the router and publisher (`flysim-bus`, two threads) inherit the + host mask of `place_workers` (PERF-02), so they run on the host CPU with the listeners, never on + a pinned sweep CPU. +- **One switch.** `FLY_FEED_VIA` in `fly.env` decides everything: `flyedge.service` has an + `ExecCondition=` on it (skipped, not failed, in direct mode) and no `[Install]`; + `flysim.service` has `Wants=flyedge.service`, so every start of flysim, including the stop and + start of `fly-loop-reset` that `Requires=` alone left without an edge, brings the edge up in bus + mode. Checked on systemd 257 with the repo's own units: crash, restart and stop/start of flysim + all end with the edge serving; direct mode never starts it. `infra/bin/fly-feed bus|direct` + rewrites the line, restarts flysim, waits for a new invocation, the edge's `/healthz` and the + page on the feed (frames moving), and rolls itself back (to `direct`) when that does not happen + or when it is interrupted. It works on either runtime and survives `fly-runtime` changes. +- **Edge health.** `/healthz` is 503 unless the edge is subscribed **and** has taken a snapshot off + the bus within 15 s (`fly_edge_snapshot_age_seconds`): a loop publishes at least the 2 Hz idle + header, so silence means a wedged subscription, which `Subscription::next` alone would never + report. +- **Watchdog.** `feed_via` follows the *running* flysim's environment (a deploy that rewrote + fly.env but has not restarted flysim is not an outage). New check 2a judges the edge only while + flysim answers: second failed pass restarts it, third adds the page and the encoder, fourth + switches the feed back to flysim (`fly-feed direct --no-wait`, sudoers for exactly that line). + Check 2 in bus mode leaves a silent edge to 2a instead of restarting a page with nothing to + connect to. +- **Deploy.** `05-deploy.sh` installs `fly-feed`, refuses a release without `fly-edge` while the + env file or the container says `bus` (before `current` moves; `fly-feed direct` needs no + binary), and warns when the container's `FLY_FEED_VIA` differs from the env file's. flysim and + the edge both follow fly.env at their next start, so a disagreement never leaves the stage with + no feed. +- **Known limits, revisited.** *Feed counters off the container*: the edge's `/metrics` now listens + on `0.0.0.0:9102` like flysim's `:9101`; a dashboard adds it as a second target (the watchdog + stays on loopback). *Rollback while in bus mode*: refused by the deploy and one command by + `fly-feed direct`. *Store quota per router* and *old fixtures*: unchanged, accepted as written. + diff --git a/infra/docs/runbook.md b/infra/docs/runbook.md index ad0d9cc..ea05330 100644 --- a/infra/docs/runbook.md +++ b/infra/docs/runbook.md @@ -519,6 +519,118 @@ pct exec $CTID -- /opt/fly/bin/fly-runtime legacy # the one-command rollback cannot be enabled). It is for a rehearsal or a soak on a container whose `flysim.service` is stopped, not for switching the stream. +## Feed over the bus (EDGE-02) + +`ws://127.0.0.1:7400/feed` is served either by `flysim` itself (`direct`, how every release before +EDGE-01 did it, and the default) or by `fly-edge` from flysim's embedded feed bus (`bus`, +`docs/design/flybus.md` "Feed over the bus"). The WebSocket contract is the same bytes either way +(`docs/feed-protocol.md`); nothing about the fly, the readout or the compatibility string changes, +on either runtime (`flysim` or `flysim-session`, `fly-runtime`). The stage, the bridge and the +capture never see the difference. + +**One switch, one line.** `FLY_FEED_VIA` in `/etc/fly/fly.env` (written by every deploy from the +env file's `FLY_FEED_VIA`, default `direct`). flysim reads it, `flyedge.service` runs only when it +says `bus` (`ExecCondition=`; in direct mode the unit starts as "skipped", inactive and not +failed), and `flysim.service` has `Wants=flyedge.service`, so **every** start of flysim brings the +edge up in bus mode, whoever starts it: a reboot, the unstick rule's restart, `fly-loop-reset`'s +stop and start, `fly-reset-to-milestone`, a crash-restart. There is nothing to enable or start by +hand, and flysim and the edge cannot disagree. + +``` +pct exec $CTID -- /opt/fly/bin/fly-feed status # configured / running / the edge and its counters +pct exec $CTID -- /opt/fly/bin/fly-feed bus # switch (restarts flysim; rolls itself back if unhealthy) +pct exec $CTID -- /opt/fly/bin/fly-feed direct # the way back +``` + +### The live procedure + +Preconditions: the release has `fly-edge` (v0.7.6 and later; `ls /opt/fly/current/fly-edge`), +`fly-feed` is installed (`/opt/fly/bin/fly-feed`, converged by the deploy), the container is +claimed in the host log as for any host work, and `fly-feed status` says `configured: direct`, +`running: direct`. Pick a moment you would also pick for the unstick rule's restart: **the switch +restarts flysim**, so the stream shows the stage's reconnect screen for about a minute (the +restore, the warm-up and the page's reconnect; the rehearsal measured it, below), and the run +continues from the last checkpoint. It counts as one start against `flysim.service`'s start limit +(3 in 10 minutes on the session runtime), two if it rolls back: do not switch within ten minutes +of two other restarts. + +``` +# 1. Before: the baseline to compare with (keep the output). +pct exec $CTID -- /opt/fly/bin/fly-feed status +pct exec $CTID -- sh -c 'curl -s 127.0.0.1:9101/metrics | grep -E "^fly_(realtime_factor|lag_seconds|feed_clients|frames_sent_total) "' +pct exec $CTID -- fly-cpu-confine status # PERF-02: the sim's cpus are the sim's +# 2. Switch. Blocks until the page is on the feed again (FLY_FEED_HEALTH_TIMEOUT, 300 s) and prints +# "healthy (bus): the page is on the feed and frames are moving", exit 0. +pct exec $CTID -- /opt/fly/bin/fly-feed bus +# 3. Make it permanent for the next deploy: FLY_FEED_VIA=bus in the operator's env file for this +# container. (A deploy that finds fly.env and the env file disagreeing warns loudly and writes the +# env file's value; flysim applies it at its next restart.) +# 4. Look at it (below) for a few minutes, then at the end of the first hour and the first day. +pct exec $CTID -- /opt/fly/bin/fly-feed status +``` + +What `fly-feed bus` does, in order: refuses unless the release has `fly-edge`, takes +`/run/fly/feed.lock`, rewrites the one `FLY_FEED_VIA` line (every other line, the mode and the owner +kept), restarts `flysim.service` (`--no-block`, then waits for a **new** invocation's `/healthz`), +waits for the edge's `/healthz` (subscribed to the bus, a snapshot within 15 s) and, while +`flystage.service` is active, for the page: `fly_feed_clients >= 1` on the edge's counters with +`fly_frames_sent_total` advancing. Anything short of that within the timeout puts `FLY_FEED_VIA` +back to `direct`, restarts flysim again, checks it the same way and exits 1 (`--no-rollback` +leaves the failed switch in place for the operator; an interrupted switch, ssh dropped or INT, TERM +or HUP, rolls back too). Every switch is in the journal (`journalctl -t fly-feed`) and +`/var/lib/fly/feed.log`. + +### What to watch + +| Where | Healthy in bus mode | Wrong looks like | +| --- | --- | --- | +| `fly-feed status` | `configured: bus`, `running: bus`, `edge healthz: ok`, snapshot age under a second, `bus lost` and `bind failures` not growing | `running` differs from `configured` (a deploy wrote a new value; the next flysim start applies it); `edge healthz: NOT OK` | +| edge `:9102/metrics` (loopback for the watchdog; the same address answers on the container's network for the dashboard) | `fly_edge_bus_connected 1`, `fly_edge_snapshot_age_seconds` under 1, `fly_feed_clients 1` (the page; the bridge or a test adds more), `fly_frames_sent_total` rising about 30 a second, `fly_edge_decode_failures_total 0`, `fly_edge_bind_failures_total 0` | `bus_connected 0` (flysim down, or restarting), `bind_failures_total` rising (something else holds :7400: a flysim still in direct mode, a stale process), `decode_failures_total` rising (a mismatched flysim and fly-edge: deploy one release) | +| flysim `:9101/metrics` | `fly_bus_published_total` rising at the snapshot rate, `fly_bus_publish_failures_total` flat 0; `fly_feed_clients` and `fly_frames_sent_total` read **0 here in bus mode** (the counters belong to the edge) | publish failures rising: the store is full or the edge's seat is stuck; read `journalctl -u flysim -g "feed bus"` | +| `fly_realtime_factor`, `fly_lag_seconds` | the same as the baseline from step 1, within the usual noise: the publisher is one 6% thread on the host CPU, and the websocket writes it replaces were on that CPU in direct mode | a drop that persists for the hour: switch back (`fly-feed direct`) and compare | +| `ps -L -o pid,psr,comm -p $(pidof fly-edge)` / `grep Cpus_allowed_list /proc/$(pidof fly-edge)/status` | the page CPUs (`flyedge.service.d/cpuset.conf`, written by the deploy), never the sim's | an edge on the sim's CPUs: the cpuset drop-in is missing; re-run the deploy | +| `ls -R /run/fly/bus/store | wc -l`, `du -sk /run/fly/bus` | a few files, under 1 MB, flat for days (the router keeps one retained snapshot and what the edge is still reading) | growth: report it, restart flysim, switch back | +| `journalctl -u flyedge -u flysim -g "bus|feed|edge"`, `journalctl -t fly-watchdog -g flyedge` | `serving the feed from the bus` once per flysim start | `the feed bus went away` outside a flysim restart; a watchdog line `flyedge: ... failures` | +| the stream | the page is up, frames moving | the page on its reconnect screen: `fly-feed status`; if the edge is down `systemctl status flyedge`; `fly-feed direct` is the one-command answer | + +The watchdog follows the **running** mode (the running flysim's own environment, so a deploy that +changed `FLY_FEED_VIA` but has not restarted flysim is not an outage). Check 2 reads the feed +counters from the edge in bus mode; a new check 2a judges the edge itself, only while flysim answers +`/healthz` (a down flysim is check 1's): active and `/healthz` 200, one failed pass let go, then +the second pass restarts `flyedge`, the third restarts the page and the encoder as well, and the +fourth **puts the feed back on flysim** (`fly-feed direct --no-wait`, granted in sudoers with exactly +those arguments): one more flysim restart, and `FLY_FEED_VIA=direct` stays until an operator +switches again (put it in the env file too). Check 2 in bus mode leaves a silent edge to 2a rather +than restarting a page that has nothing to connect to, and its chain ends with the edge and the +encoder. + +### Rolling back + +- `fly-feed direct`: writes `direct`, restarts flysim, waits until the page is on flysim's own + feed, stops a lingering edge. It needs nothing from the release (it works on one without + `fly-edge`), and it is the way back if anything above looks wrong. It restarts flysim again, so + count it against the start limit. +- Automatic: a switch that does not become healthy (above), the watchdog's fourth failed pass, and + `fly-runtime fallback` (to legacy) all leave `FLY_FEED_VIA` alone: the setting is the same on both + runtimes. +- A deploy of a release **without** `fly-edge` is refused (before `/opt/fly/current` moves) while + the env file says `bus` or the container is in bus mode: `fly-feed direct` and set + `FLY_FEED_VIA=direct` in the env file first, then roll back or deploy. +- A reboot keeps whatever `fly.env` says. + +### Notes + +- **Dashboards.** In bus mode flysim's `:9101` reports `fly_feed_clients` and + `fly_frames_sent_total` as 0. Scrape the edge's `:9102` too (same names, plus the `fly_edge_*` + series); the metrics address is on every interface, as `:9101` is, and exposes nothing but + counters. +- **CPUs.** `flyedge.service` is confined to the page CPUs by the deploy's drop-in; the router and + the publisher run inside flysim, on its `flysim-bus` runtime (two threads on the host CPU, with + the listeners, not on a pinned sweep CPU). +- **The store** is `/run/fly/bus` (tmpfs, `fly` 0700, 32 MiB cap, in practice under 0.5 MB). A + reboot empties it; a crashed flysim's directory is removed by the next one. +- **Control (`:7401`)** stays in flysim and is not part of this switch. + ## Shadow run (SHADOW-01) The session runtime, run beside the live fly as the gate for the automatic cutover (CUT-01). The diff --git a/infra/env/example.env b/infra/env/example.env index e9d892d..4b16634 100644 --- a/infra/env/example.env +++ b/infra/env/example.env @@ -321,8 +321,13 @@ FLY_MACRO_MODE=raw # Who serves ws://127.0.0.1:7400/feed (docs/design/flybus.md, "Feed over the # bus"). direct: flysim binds it, as always. bus: flysim publishes every # snapshot on its embedded feed bus (/run/fly/bus) and flyedge.service serves -# the same bytes; enable that unit by hand (its header has the steps). -# Watchdog check 2 follows this setting to the edge's counters by itself. +# the same bytes. This line (written into fly.env by every deploy) is the only +# switch: flysim.service wants the edge, which starts only in bus mode. +# On a live container switch with `fly-feed bus` / `fly-feed direct` (restarts +# flysim, checks the page is back, rolls back by itself) and put the same value +# here afterwards, or the next deploy warns that it writes the old one back. +# Watchdog check 2 follows the running mode to the edge's counters by itself. +# Runbook: "Feed over the bus". FLY_FEED_VIA=direct # How long a macro leaves a target alone after a walk to it aborted "blocked" or # "timeout" (macros.md section 12.1). Session state, so a restart offers every From 1382f94cf395c8c9b13ef48f98e724060304f268 Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 00:43:32 +0000 Subject: [PATCH 05/27] runbook: what the rehearsal measured --- infra/docs/runbook.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/infra/docs/runbook.md b/infra/docs/runbook.md index ea05330..285b31f 100644 --- a/infra/docs/runbook.md +++ b/infra/docs/runbook.md @@ -618,6 +618,38 @@ encoder. `FLY_FEED_VIA=direct` in the env file first, then roll back or deploy. - A reboot keeps whatever `fly.env` says. +### What the rehearsal measured + +Before the first live switch (EDGE-02, 2026-10-02): the real fly (session runtime, real connectome, +macros mode, sim on four CPUs and the page and edge on two others, as on the container), the real +stage page in headless Chromium consuming through `fly-edge`, plus the repo's own units, `fly-feed` +and watchdog under a real systemd. The build box was shared and loaded (load average 8 to 30), so +**real-time factor is not comparable between the two runs**; the numbers below are the ones load does +not move much. The live switch is the real A/B: take the step 1 baseline and compare. + +| Measure | direct | bus | +| --- | --- | --- | +| WebSocket content, speed 0.25 so every frame is published, 4,261 and 5,406 frames compared | reference | frame, audio and spike attachments byte-equal on every frame; headers equal except a wall-clock "checkpoint saved" event that lands on different frames in any two runs | +| Latency, snapshot stamped by the sim to received by a local client (median / p95) | 1 / 3 ms | 7 / 14 ms (two hops: seal into the store, read out) | +| CPU per snapshot | 0.24 ms (flysim's websocket thread, on the host CPU) | 2.4 ms in flysim (`flysim-bus` publisher, on the host CPU, about 7% of a CPU at 30 Hz) and 1.1 ms in the edge (page CPUs) | +| Edge CPU and placement | n/a | 1.3% mean, 2.8% p95, only on the page CPUs | +| Router store | n/a | 116 KB steady (median), 238 KB peak, 6 to 9 files, flat over the run | +| Memory over 35 min plus the restarts | flysim 72 to 78 MB | flysim 65 to 69 MB, edge 8.3 to 9.6 MB; the page grows the same in both | +| Snapshots dropped on the way (heavy load) | none seen by a local client | 0.28% sequence gaps at the recorder (the edge sits on CPUs Chromium saturates); none on a quiet box | +| Page | 0 decode errors | 0 decode errors, gaps only under that load | + +Recovery, with the page (a reconnecting stage) as the witness: `kill -9 fly-edge`, a SIGTERM +restart of it, and two kills 0.1 s apart (the router's one seat for the edge is released at once) +each had the page streaming again in 0.7 to 0.9 s; a `kill -9` of flysim (router, publisher and +sim) had the edge serving the new router 3 s later and the page 3.4 s later; a SIGTERM restart of +flysim (the unstick rule) 4 and 5.3 s (the page's retries are 0.3 to 1 s apart, the sim restores +from its hot ring). Under the real systemd: `fly-feed bus` took 6 s from command to "page on the +feed", `fly-feed direct` 6 s, a `fly-feed bus` with a broken `fly-edge` rolled itself back after +the 40 s test timeout and left the page on flysim, a stop and start of flysim brought the edge +back by itself, and the watchdog's fourth failed pass switched a permanently broken edge back to +direct with the page connected again. The live restart is longer than these 6 s by the real +restore and warm-up; use the unstick rule's usual time. + ### Notes - **Dashboards.** In bus mode flysim's `:9101` reports `fly_feed_clients` and From 3ea56ef3f81d0e0eea790b8bc8d802d88a07d2d1 Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 01:12:56 +0000 Subject: [PATCH 06/27] tests: service_parity waits for the idle header instead of racing the pause The idle-headers check failed 8 of 12 runs on a loaded build box (main 46e25ef: 3 of 4). The script paused and resumed 2 ms apart, so whether the loop published a header-only idle snapshot in that window (due at 2 Hz) was wall-clock luck, and legacy and session often disagreed. Not a product race: the cadence is the protocol's. The recorder now holds the resume until the first idle header has been seen (bounded wait, 30 s), and the compare requires BOTH runtimes to have published one, rather than merely agreeing on whether any did. The first idle header is compared as before except for its `events` list: which publish carries the pause's events is wall clock, and the events are compared in the running snapshots and the event log. Also fixed, found once the first was gone (1 in 20 under load): the two sugars sent at one frame must be drained together; when the loop publishes a snapshot while they are being sent the run is flagged incomplete and repeated, like a missed frame. What it proves, unchanged: a pause makes each runtime publish header-only idle snapshots (status paused, no attachments) whose fields match the legacy loop, and the script's responses, feed, event log, journal and final checkpoint are identical between runtimes. Under load (build box, load ~25 on 6 cores), toy_raw_service_contracts: before 4/12 pass, after 40/40. --- .../tests/service_parity.rs | 53 +++++++++++++++++-- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/services/flysim/crates/fly-legacy-session/tests/service_parity.rs b/services/flysim/crates/fly-legacy-session/tests/service_parity.rs index c6245b6..53f50d8 100644 --- a/services/flysim/crates/fly-legacy-session/tests/service_parity.rs +++ b/services/flysim/crates/fly-legacy-session/tests/service_parity.rs @@ -11,7 +11,8 @@ //! - **feed**: every running snapshot, header field by field and attachments byte for byte, //! except the fields that are wall clock by definition (`wallMs`, `uptimeSeconds`, //! `realtimeFactor`, `sugar.cooldownMs`, an event's or chat line's `wallMs`) and `seq`, which -//! counts the idle headers a pause publishes at 2 Hz of wall clock; +//! counts the idle headers a pause publishes at 2 Hz of wall clock (the script holds the +//! resume until the recorder has seen the first one, so each runtime must publish one); //! - **control**: status code and body of every request (`/stimulate` 202 and 429 with the same //! `retryAfterMs`, `/reward` 403, `/chat` 202/422, `/checkpoint` the same generation, //! `/pause`, `/resume`, `/events`, `/healthz`), `/status` minus its wall-clock fields, and the @@ -315,6 +316,29 @@ fn record( )); // Sent now, in order, each drained before the next frame. for action in actions.iter().filter(|a| a.at == index) { + if action.path == "/resume" { + // The pause is only observable as idle headers if the loop stays + // paused until it has published one (a header-only publish is due + // within the 2 Hz idle period). Resuming 2 ms after the pause let a + // loaded box skip it in one runtime and not the other, so wait, bounded, + // for the condition instead of racing it. + let before = idle.len(); + let waited = Instant::now(); + while idle.len() == before { + match tokio::time::timeout(Duration::from_secs(30), snapshots.changed()).await { + Ok(Ok(())) => {} + other => panic!( + "{}: no idle header within 30 s of the pause ({other:?})", + runtime.label() + ), + } + let snap = Arc::clone(&snapshots.borrow_and_update()); + if snap.header.status == FeedStatus::Paused { + idle.push(comparable(&snap)); + } + } + eprintln!(" {}: idle header after {:.1?} paused", runtime.label(), waited.elapsed()); + } let router = router.clone(); let label = format!("{} {}", action_label(action), index); let action = action.clone(); @@ -323,6 +347,18 @@ fn record( tokio::time::sleep(Duration::from_millis(2)).await; pending.push((label, handle)); } + // Requests sent at one frame must all be drained together (two sugars before + // one commit): if the loop published another snapshot while they were being + // sent, a loaded box split them across frames and the run cannot be compared. + let group = actions.iter().filter(|a| a.at == index).count(); + let pauses = actions.iter().any(|a| a.at == index && a.path.starts_with("/pause")); + if group > 1 && !pauses && snapshots.has_changed().unwrap_or(false) { + eprintln!( + " {}: the loop moved on while {group} requests were sent at frame {index}; the run will be repeated", + runtime.label() + ); + complete = false; + } } FeedStatus::Paused => idle.push(comparable(&snapshot)), FeedStatus::Booting | FeedStatus::Error => {} @@ -491,9 +527,20 @@ fn compare(legacy: &Recording, session: &Recording, label: &str) { ); } } - assert_eq!(legacy.idle.is_empty(), session.idle.is_empty(), "{label}: idle headers"); + assert!(!legacy.idle.is_empty(), "{label}: the legacy pause published no idle header"); + assert!(!session.idle.is_empty(), "{label}: the session pause published no idle header"); if let (Some(a), Some(b)) = (legacy.idle.first(), session.idle.first()) { - same(&format!("{label}: the first idle header"), a, b); + // An idle header carries the events not yet published, and which publish that is (the + // pause's own or a later one, whichever the recorder saw first) is wall clock; the events + // themselves are compared in the running snapshots and the event log. + let strip = |v: &Value| { + let mut v = v.clone(); + if let Some(map) = v.as_object_mut() { + map.remove("events"); + } + v + }; + same(&format!("{label}: the first idle header"), &strip(a), &strip(b)); } assert_eq!(legacy.responses.len(), session.responses.len()); for ((la, sa, ba), (lb, sb, bb)) in legacy.responses.iter().zip(&session.responses) { From 0caade6b201f35d8b4a3220a88cf6b33fb01d7e3 Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 02:05:33 +0000 Subject: [PATCH 07/27] macros: rung 16 is an errand in Bill's house, its PC is a hidden event, and Cerulean's south is behind the trashed house (row 73) Rung 16's place was at(ROUTE_25), so inside Bill's house GO OBJECTIVE and GO OUT were both the door: the live Route 25 <-> Bill's house ring. It is now errand(BILLS_HOUSE): the room's people first, then its things, where the things include the cartridge's own hidden events, read from HiddenEventMaps/HiddenEventPointers ($11:$6A40/$6A96, pinned from CheckForHiddenEvent's operands and shape-checked on every read). A hidden event is only ever the errand's next step: GO ITEM, GO NPC and TALK elsewhere are unchanged. One with a SPRITE_FACING argument (Bill's PC) is approached and faced from that side only. Cerulean is split a third time: the town's ground ends at row 28, and Route 5 and Route 9 are on the ground behind the trashed house ($3e), in by its front door and out by the hole in its back wall. The house is on the map graph, so the objective toward rung 17 walks through it. ROM tests from the scout checkpoints (door ring, PC step, live row-71 Route 25, Cerulean south-half and trashed house) fail on main and pass here. No button, readout, catalog or adapter change; the compatibility string is unchanged. --- .../flysim/crates/flybrain-gb/src/adapter.rs | 14 + .../src/pokemon_red/macros/cartridge.rs | 2 + .../src/pokemon_red/macros/geography.rs | 52 +++- .../src/pokemon_red/macros/palette.rs | 77 ++++- .../src/pokemon_red/macros/path.rs | 18 ++ .../src/pokemon_red/macros/state.rs | 33 +++ .../src/pokemon_red/macros/tests.rs | 106 ++++++- .../flybrain-gb/src/pokemon_red/maps.rs | 10 + .../crates/flybrain-gb/src/pokemon_red/mod.rs | 11 +- .../flybrain-gb/src/pokemon_red/state.rs | 84 +++++- .../flybrain-gb/src/pokemon_red/tests.rs | 2 + .../crates/flysim/tests/rom_macros_mode.rs | 271 ++++++++++++++++++ 12 files changed, 673 insertions(+), 7 deletions(-) diff --git a/services/flysim/crates/flybrain-gb/src/adapter.rs b/services/flysim/crates/flybrain-gb/src/adapter.rs index d1d75f8..5b4d7c9 100644 --- a/services/flysim/crates/flybrain-gb/src/adapter.rs +++ b/services/flysim/crates/flybrain-gb/src/adapter.rs @@ -202,6 +202,15 @@ pub enum PlaceKind { Person, /// Something to press A at: the starter's Pokéball, an item ball, a sign. Object, + /// An errand in one room, step by step: its people first, and once none is left to talk to, + /// the things in it -- objects, signs, and the cartridge's own hidden events, such as the PC + /// a Bill's-house cell separator is started from (row 73, `docs/design/macros.md` 12.35). + /// + /// Not a list of steps, and no step is named: the room's state says which step is next, because + /// the cartridge shows and hides the people as the errand moves on. A person who has had their + /// conversation is in the talked ledger; a thing pressed is too; and what is left is the next + /// step. + Errand, } impl MapPlace { @@ -224,6 +233,11 @@ impl MapPlace { pub const fn object(map: u8) -> Self { Self { map, tile: None, warp: None, edge: None, target: Some(PlaceKind::Object) } } + + /// A place that is an errand in one room: its people, then its things ([`PlaceKind::Errand`]). + pub const fn errand(map: u8) -> Self { + Self { map, tile: None, warp: None, edge: None, target: Some(PlaceKind::Errand) } + } } /// Reasons an adapter refuses a checkpoint. diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/cartridge.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/cartridge.rs index 80ee959..2e90aca 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/cartridge.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/cartridge.rs @@ -286,6 +286,8 @@ pub enum TalkTarget { Sprite(u8), /// A sign, by its text id. Sign(u8), + /// A hidden event of the cartridge's own table, by its position in this map's list (row 73). + Hidden(u8), } /// One thing a macro can be *aimed at*, as the session's target ledgers name it. diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/geography.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/geography.rs index 21057bf..43e2789 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/geography.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/geography.rs @@ -173,6 +173,12 @@ const LINKS: &[(u8, u8)] = &[ // which from the back door's arrival is the back door. Which piece each door opens onto is // [`SPLIT`]'s business. (maps::CERULEAN_BADGE_HOUSE, maps::CERULEAN_CITY), + // The trashed house (row 73): its front door is the town's, the hole in its back wall the + // south's ([`SPLIT`]). It is the only road from the town to Route 5, rung 17's. + (maps::CERULEAN_TRASHED_HOUSE, maps::CERULEAN_CITY), + // Bill's house, rung 16's room (row 73): Route 25's door at (45, 3), and the house's two + // doormats back to the route (`LAST_MAP`). + (maps::BILLS_HOUSE, maps::ROUTE_25), (maps::ROCK_TUNNEL_1F, maps::ROUTE_10), (maps::INDIGO_PLATEAU_LOBBY, maps::INDIGO_PLATEAU), ]; @@ -252,6 +258,9 @@ const B2F_SOUTH: u8 = 2; const CERULEAN_TOWN: u8 = 0; #[cfg(test)] const CERULEAN_YARD: u8 = 1; +/// [`SPLIT`]'s third piece of Cerulean: the ground behind the trashed house (row 73). +#[cfg(test)] +const CERULEAN_SOUTH: u8 = 2; /// Every map whose ground is in pieces, with each piece's doors and neighbours. /// @@ -383,21 +392,33 @@ const SPLIT: &[Split] = &[ (3, 30, 19), (4, 13, 25), (5, 25, 25), - (7, 27, 9), (8, 9, 11), ], next: &[ Region::whole(maps::ROUTE_24), - Region::whole(maps::ROUTE_5), Region::piece(maps::ROUTE_4, EAST_SIDE), - Region::whole(maps::ROUTE_9), Region::whole(maps::CERULEAN_POKECENTER), Region::whole(maps::CERULEAN_GYM), Region::whole(maps::CERULEAN_MART), Region::whole(maps::CERULEAN_BADGE_HOUSE), + Region::whole(maps::CERULEAN_TRASHED_HOUSE), ], }, Piece { doors: &[(9, 9, 9)], next: &[Region::whole(maps::CERULEAN_BADGE_HOUSE)] }, + // Row 73: everything behind the trashed house. The town's own ground ends at row 28 -- + // the gap at (16, 28) and (17, 28) opens onto a wall and the trainer-tips sign -- and + // the south of the map, the road down to Route 5, and the east edge onto Route 9 are + // reached through the house: in by the front door at (27, 11), out by the hole in its + // back wall, which lands on (27, 9) in the Rocket's yard, and from there east and down + // (scout B3 flooded the grid: 378 of the map's 801 walkable tiles are the town's). + Piece { + doors: &[(7, 27, 9)], + next: &[ + Region::whole(maps::ROUTE_5), + Region::whole(maps::ROUTE_9), + Region::whole(maps::CERULEAN_TRASHED_HOUSE), + ], + }, ], }, ]; @@ -977,6 +998,31 @@ mod tests { assert!(warp_on(west, 1) && !warp_on(west, 2) && !edge_on(west, maps::CERULEAN_CITY)); } + #[test] + fn the_road_south_out_of_cerulean_is_through_the_trashed_house() { + // Row 73. The town's ground ends at row 28; Route 5 and Route 9 are on the ground behind + // the trashed house, reached in by its front door (Cerulean's warp 0) and out by the hole + // in its back wall, which lands on (27, 9) (warp 7). Scout B3: 0 of 6 seeds past the + // town's south edge in 43 brain minutes each while the house was off the graph. + let town = Region::piece(maps::CERULEAN_CITY, CERULEAN_TOWN); + let south = Region::piece(maps::CERULEAN_CITY, CERULEAN_SOUTH); + let house = Region::whole(maps::CERULEAN_TRASHED_HOUSE); + assert_eq!(arrival_by_warp(maps::CERULEAN_CITY, 0), Some(town), "the front door is the town's"); + assert_eq!(arrival_by_warp(maps::CERULEAN_CITY, 7), Some(south), "the hole lands behind the house"); + assert_eq!(arrival_by_edge(maps::CERULEAN_CITY, maps::ROUTE_5), Some(south)); + assert_eq!(arrival_by_edge(maps::CERULEAN_CITY, maps::ROUTE_9), Some(south)); + assert_eq!(next_step(town, maps::ROUTE_5), Some(house)); + assert_eq!(next_step(house, maps::ROUTE_5), Some(south)); + assert_eq!(next_step(south, maps::ROUTE_5), Some(Region::whole(maps::ROUTE_5))); + assert_eq!(next_step(house, maps::CERULEAN_GYM), Some(town)); + assert_eq!(region_at(maps::CERULEAN_CITY, 27, 9), south); + assert_eq!(region_at(maps::CERULEAN_CITY, 27, 12), town); + assert!(!edge_on(town, maps::ROUTE_5) && edge_on(south, maps::ROUTE_5)); + assert!(warp_on(south, 7) && !warp_on(town, 7) && !warp_on(south, 0)); + // Rung 17's road from Bill's house is now one the graph knows end to end. + assert!(hops(Region::whole(maps::BILLS_HOUSE), maps::VERMILION_CITY).is_some()); + } + #[test] fn the_road_from_pewter_to_cerulean_is_through_mt_moon_one_chamber_at_a_time() { // Row 59. Every step of the road, as the pieces the fly stands in, measured from the diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/palette.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/palette.rs index 23e40fc..a039154 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/palette.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/palette.rs @@ -2021,6 +2021,9 @@ pub fn facing_target(state: &mut dyn MacroState) -> Option { if let Some(target) = path::target_at(state, ahead) { return Some(target); } + if let Some(target) = objective_hidden_ahead(state, ahead, player.facing) { + return Some(target); + } // **Over a counter**, which is the symmetric half of [`counter_aims`] and was missing from it // (2026-09-17, measured on the cartridge in the Viridian mart). The game doubles its own // talking range over the tileset's counter tiles, so a fly standing at a counter facing the @@ -2111,7 +2114,17 @@ pub fn objective_goals(state: &mut dyn MacroState) -> Vec { // to walk to: `GO OBJECTIVE` walked to him, then back to the leader, and `TALK` was // the one press it never made room for. A fly facing a person the rung is waiting on // has nothing left for a walk to do. - if targets.iter().any(|(tile, _)| Some(*tile) == ahead) { + // A hidden event is faced only from the side it answers (row 73): beside Bill's PC + // facing it sideways is not the arrival, and the walk goes on to the tile below it. + let mut arrived = false; + for (tile, target) in &targets { + if Some(*tile) == ahead + && required_facing(state, *target).is_none_or(|need| need == player.facing) + { + arrived = true; + } + } + if arrived { return Vec::new(); } let mut ranked: Vec<(u32, Tile, TalkTarget)> = targets @@ -2120,8 +2133,12 @@ pub fn objective_goals(state: &mut dyn MacroState) -> Vec { .collect(); ranked.sort_unstable(); let Some((_, tile, target)) = ranked.first().copied() else { return Vec::new() }; + let need = required_facing(state, target); let mut aims = Vec::with_capacity(4); for facing in FACINGS { + if need.is_some_and(|need| need != opposite(facing)) { + continue; + } let Some(stand) = tile.step(facing) else { continue }; // Not a tile a script pushes the fly off (row 37); `approach` excludes the same. if state.pushed_tile(stand.x, stand.y) { @@ -2235,7 +2252,34 @@ pub fn objective_targets(state: &mut dyn MacroState) -> Vec<(Tile, TalkTarget)> // Not objects: every item ball in the game is a toggleable object, so a ball the run has // picked up and one out of sight read alike from outside the window. PlaceKind::Object => path::interactable_targets(state), + // Row 73: an errand in one room is its people first, and its things -- sprites, signs and + // the cartridge's hidden events -- once no person is left to talk to. Bill's house is the + // case: Bill (a Pokémon) asks for the cell separator and walks into the machine, the + // separator is a PC no sprite or sign stands for, and Bill comes out of the machine to + // hand over the ticket. The cartridge hides and shows the people as the errand moves, so + // the room's own state says which step is next; nothing here names a step. + // + // People first, because a thing pressed out of turn is in the talked ledger for the + // session: Bill's PC pressed before Bill has asked prints "the monitor" and does nothing, + // and a PC recorded as talked to would never be the errand's next step again. + PlaceKind::Errand => { + let mut people = path::person_targets(state); + people.extend(path::offscreen_person_targets(state)); + let people = open_targets(state, people); + if !people.is_empty() { + return people; + } + let mut things = path::interactable_targets(state); + things.extend(path::hidden_targets(state).into_iter().map(|(tile, target, _)| (tile, target))); + things + } }; + open_targets(state, targets) +} + +/// Whichever of `targets` the objective is still waiting on: not talked to, and not resting in +/// the blocked ledger. [`objective_targets`]' own filter, for each list it builds. +fn open_targets(state: &mut dyn MacroState, targets: Vec<(Tile, TalkTarget)>) -> Vec<(Tile, TalkTarget)> { targets .into_iter() .filter(|(_, target)| { @@ -2244,6 +2288,37 @@ pub fn objective_targets(state: &mut dyn MacroState) -> Vec<(Tile, TalkTarget)> .collect() } +/// The one side the objective's `target` is pressed from, when the cartridge names one: a hidden +/// event whose routine checks the player's facing (row 73, Bill's PC). `None` for every sprite and +/// sign, which answer from any side. +fn required_facing(state: &mut dyn MacroState, target: TalkTarget) -> Option { + let TalkTarget::Hidden(_) = target else { return None }; + path::hidden_targets(state) + .into_iter() + .find(|(_, hidden, _)| *hidden == target) + .and_then(|(_, _, facing)| facing) +} + +/// The objective's hidden event on the tile ahead, faced from the side it answers (row 73). +/// +/// The half of [`facing_target`] that is not the map's sprites and signs. Only the objective's +/// own next step is reported, never any other hidden event: a poster faced on the way past is not +/// a reason for `TALK`, and a PC pressed out of turn would retire the errand's own step +/// ([`objective_targets`]). +fn objective_hidden_ahead(state: &mut dyn MacroState, ahead: Tile, facing: Facing) -> Option { + // Most tiles of most maps are no hidden event's, and this is asked on every overworld frame. + if !path::hidden_targets(state).iter().any(|(tile, _, _)| *tile == ahead) { + return None; + } + let (_, target) = objective_targets(state) + .into_iter() + .find(|(tile, target)| *tile == ahead && matches!(target, TalkTarget::Hidden(_)))?; + match required_facing(state, target) { + Some(need) if need != facing => None, + _ => Some(target), + } +} + /// The exits the ledger has already recorded, for the log line. pub fn visited_exits(state: &mut dyn MacroState) -> Vec { path::exits(state) diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/path.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/path.rs index 3350784..f7603e4 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/path.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/path.rs @@ -366,6 +366,24 @@ pub fn interactable_targets(state: &mut dyn MacroState) -> Vec<(Tile, TalkTarget out } +/// The map's hidden events with the key the talked ledger records them under, and the one side +/// each is pressed from when the cartridge names one (row 73). +/// +/// Kept apart from [`interactable_targets`] on purpose, which is `GO ITEM`'s list: a hidden event +/// is every PC, poster, trash can and hidden item in Kanto, and a fly sent to each of them is a +/// fly reading posters. The one reader is the ladder's own errand list +/// ([`super::palette::objective_targets`]), which needs the one the rung is waiting on. +pub fn hidden_targets(state: &mut dyn MacroState) -> Vec<(Tile, TalkTarget, Option)> { + let mut out: Vec<(Tile, TalkTarget, Option)> = state + .hidden_events() + .iter() + .map(|event| (Tile::new(event.x, event.y), TalkTarget::Hidden(event.index), event.facing)) + .collect(); + out.sort_unstable_by_key(|(tile, target, _)| (*tile, *target)); + out.dedup_by_key(|(tile, _, _)| *tile); + out +} + /// Every person on the map with the key the talked ledger records them under. pub fn person_targets(state: &mut dyn MacroState) -> Vec<(Tile, TalkTarget)> { let mut out: Vec<(Tile, TalkTarget)> = state diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/state.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/state.rs index 2558e4b..498a049 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/state.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/state.rs @@ -413,6 +413,31 @@ pub struct Sign { pub text_id: u8, } +/// One hidden event on the current map: a tile the cartridge answers an A press at from its own +/// ROM table (`HiddenEventMaps` / `HiddenEventPointers`, `data/events/hidden_events.asm`) rather +/// than from a sprite or a sign (row 73, `docs/design/macros.md` 12.35). +/// +/// Bill's cell-separator PC, the Pokémon Center PCs, posters, bookshelves of one room, trash cans +/// and hidden items are all this. Nothing about one reaches WRAM until it has been pressed +/// (`CheckForHiddenEvent` searches the table on every A in the overworld), so the tile is read from +/// the cartridge image and the tile named here is the one to *face*, like a [`Sign`]'s. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct HiddenEvent { + pub x: u8, + pub y: u8, + /// The entry's position in this map's list, which is the identity the cartridge gives it + /// (`wHiddenEventIndex` counts the same way) and nothing more. + pub index: u8, + /// The one side the cartridge answers the press from, when the entry names one. + /// + /// The table's third byte is the routine's argument, and where it is a `SPRITE_FACING_*` + /// value it is the side the routine checks before it does anything (`BillsHousePC` returns at + /// once unless the player faces up). `None` for any other argument -- an item id, a text id, + /// `ANY_FACING` -- which leaves all four sides. An argument that is an item or a text id and + /// happens to equal a facing value only narrows the approach to one side; it never adds one. + pub facing: Option, +} + /// Whether a tile can be walked onto. /// /// `Unknown` is load-bearing: the tile ids a walkability test needs live in the screen buffer, so @@ -774,6 +799,14 @@ pub trait GameState { /// is visible, and not inherit it from here. fn signs(&mut self) -> Vec; + /// The current map's hidden events, from the cartridge's own table (row 73). + /// + /// Defaulted to none, which narrows: a seam with no cartridge image behind it knows the + /// sprites and the signs and nothing more, which is what every reader had before row 73. + fn hidden_events(&mut self) -> Vec { + Vec::new() + } + /// Whether the player could stand on this tile of the current map. fn walkable(&mut self, x: u8, y: u8) -> Walkable; diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs index 0188ebb..ca89a17 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs @@ -40,7 +40,8 @@ use super::super::maps; use super::plan; use super::state::{ Battle, BattleKind, BattleMenu, Connections, Cursor, EnemyMon, Facing, GameState, MapSize, - Mon, Move, Naming, Npc, Party, Pc, Player, Scene, Shop, ShopScreen, Sign, StartMenu, Status, TextBox, + HiddenEvent, Mon, Move, Naming, Npc, Party, Pc, Player, Scene, Shop, ShopScreen, Sign, StartMenu, + Status, TextBox, Walkable, Warp, }; @@ -95,6 +96,8 @@ struct World { /// Sprites the cartridge is not drawing only because they are off the screen (row 58). offscreen: Vec, signs: Vec, + /// The map's hidden events, as the cartridge's own table lists them (row 73). + hidden: Vec, list: List, cursor: u8, @@ -276,6 +279,7 @@ impl World { npcs: Vec::new(), offscreen: Vec::new(), signs: Vec::new(), + hidden: Vec::new(), list: List::None, cursor: 0, cursor_max: 0, @@ -791,6 +795,10 @@ impl GameState for World { self.signs.clone() } + fn hidden_events(&mut self) -> Vec { + self.hidden.clone() + } + fn walkable(&mut self, x: u8, y: u8) -> Walkable { let tile = Tile::new(x, y); let offscreen = self.window && { @@ -6615,3 +6623,99 @@ fn row69_confirm_on_a_keyboard_that_does_not_close_is_blocked() { world.glue_naming = true; assert_eq!(run(&mut world, MacroKind::Confirm).unwrap(), MacroAbort::Blocked); } + +/// Bill's house on the step the live ring never got past (row 73): the fly on the doormat, Bill +/// (a Pokémon, a person sprite) at (6, 5), the cell separator's PC a hidden event at (1, 4) that is +/// pressed facing up, and rung 16's place the house as an errand. +fn bills_house() -> World { + let mut world = World::room().at(2, 7); + world.map = maps::BILLS_HOUSE; + world.size = MapSize { width: 8, height: 8 }; + world.facing = Facing::Up; + // The back wall, the PC's own tile with it. + world = world.wall(&[(0, 3), (1, 3), (2, 3), (3, 3), (4, 3), (5, 3), (6, 3), (7, 3), (1, 4)]); + world.warps = vec![ + Warp { x: 2, y: 7, destination_warp: 0, destination_map: LAST_MAP }, + Warp { x: 3, y: 7, destination_warp: 0, destination_map: LAST_MAP }, + ]; + world.npcs = vec![Npc { slot: 1, picture: 0x2a, x: 6, y: 5, facing: Facing::Down }]; + world.hidden = vec![HiddenEvent { x: 1, y: 4, index: 0, facing: Some(Facing::Up) }]; + world.objective = Some(Objective { + map: world.map, + tile: None, + warp: None, + edge: None, + target: Some(PlaceKind::Errand), + }); + world +} + +#[test] +fn an_errand_is_its_people_first_and_the_room_is_not_left_while_one_is_waiting() { + // Row 73, live on v0.7.5: rung 16 was `at(ROUTE_25)`, so inside Bill's house `GO OBJECTIVE` + // and `GO OUT` were both the door, 30 to 60 times per ten brain minutes. As an errand, Bill is + // the target and the ways out are withheld while he is waiting (12.5's rule). + let mut world = bills_house(); + assert_eq!(super::palette::objective_targets(&mut world), vec![(Tile::new(6, 5), TalkTarget::Sprite(1))]); + assert!(on_the_pad(&mut world, MacroKind::GoObjective)); + assert!(!on_the_pad(&mut world, MacroKind::GoOut), "the house is not left while Bill is waiting"); + + // The PC is not the errand's step yet: faced out of turn it is not `TALK`'s, because a PC + // pressed before Bill has asked prints the monitor and would be in the talked ledger for good. + let mut world = bills_house().at(1, 5); + world.facing = Facing::Up; + assert!(!on_the_pad(&mut world, MacroKind::Talk)); + assert_eq!(super::palette::facing_target(&mut world), None); +} + +#[test] +fn a_hidden_event_is_the_errands_next_step_once_no_person_is_left_and_it_is_faced_from_its_side() { + // Bill has asked and walked into the machine: the cartridge has hidden his sprite and nobody + // else is in the room. The next step is the cell separator's PC, which no sprite or sign + // stands for -- the hidden event the scout pressed by hand on the cartridge (row 73). + let mut world = bills_house().at(3, 5); + world.npcs.clear(); + world.talked.insert(TalkTarget::Sprite(1)); + assert_eq!(super::palette::objective_targets(&mut world), vec![(Tile::new(1, 4), TalkTarget::Hidden(0))]); + assert!(!on_the_pad(&mut world, MacroKind::GoOut), "still not left: the PC is waiting"); + // `BillsHousePC` answers only a player facing up, so the walk's one aim is the tile below it. + let aims: Vec<(Tile, Option)> = + objective_goals(&mut world).iter().map(|aim| (aim.tile, aim.face)).collect(); + assert_eq!(aims, vec![(Tile::new(1, 5), Some(Facing::Up))]); + + // Beside it, facing it sideways, is not the arrival: nothing would answer the press. + let mut beside = bills_house().at(2, 4); + beside.npcs.clear(); + beside.talked.insert(TalkTarget::Sprite(1)); + beside.facing = Facing::Left; + assert!(!on_the_pad(&mut beside, MacroKind::Talk)); + assert!(on_the_pad(&mut beside, MacroKind::GoObjective)); + + // Below it, facing up: `TALK` is the press and the walk is done. + let mut below = bills_house().at(1, 5); + below.npcs.clear(); + below.talked.insert(TalkTarget::Sprite(1)); + below.facing = Facing::Up; + assert_eq!(super::palette::facing_target(&mut below), Some(TalkTarget::Hidden(0))); + assert!(on_the_pad(&mut below, MacroKind::Talk)); + assert!(!on_the_pad(&mut below, MacroKind::GoObjective)); + + // Pressed: Bill steps out of the machine, and he is the errand's last step. + below.talked.insert(TalkTarget::Hidden(0)); + below.npcs = vec![Npc { slot: 2, picture: 0x13, x: 4, y: 4, facing: Facing::Down }]; + assert_eq!(super::palette::objective_targets(&mut below), vec![(Tile::new(4, 4), TalkTarget::Sprite(2))]); +} + +#[test] +fn a_hidden_event_is_nobody_elses_target() { + // A hidden event is every PC, poster and trash can in Kanto. Outside the errand that names it + // no macro aims at one and `TALK` is not dealt in front of one: `GO ITEM` is what it was. + let mut world = bills_house().at(1, 5); + world.npcs.clear(); + world.facing = Facing::Up; + world.objective = Some(Objective { map: maps::ROUTE_25, tile: None, warp: None, edge: None, target: None }); + assert!(super::palette::untalked_objects(&mut world).is_empty()); + assert!(!on_the_pad(&mut world, MacroKind::GoItem)); + assert!(!on_the_pad(&mut world, MacroKind::Talk)); + assert_eq!(super::palette::facing_target(&mut world), None); +} diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/maps.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/maps.rs index e752ac3..6f15bb7 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/maps.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/maps.rs @@ -84,12 +84,22 @@ pub const MT_MOON_1F: u8 = 0x3b; pub const MT_MOON_B1F: u8 = 0x3c; pub const MT_MOON_B2F: u8 = 0x3d; pub const CERULEAN_POKECENTER: u8 = 0x40; +/// The house the Rockets robbed (row 73): the id before `CERULEAN_TRADE_HOUSE` and +/// `CERULEAN_POKECENTER` `$40`, and confirmed by the cartridge rather than by counting -- Cerulean +/// City's warp table names `$3e` at (27, 11) and at (27, 9), its front door and the hole in its +/// back wall. +pub const CERULEAN_TRASHED_HOUSE: u8 = 0x3e; pub const CERULEAN_GYM: u8 = 0x41; pub const CERULEAN_MART: u8 = 0x43; /// Route 4's Pokémon Center, the one beside Mt. Moon's mouth: the id straight after /// `CERULEAN_MART` `$43`, and confirmed by the cartridge rather than by counting -- Route 4's warp /// table names `$44` at (11, 5) (`tests/rom_macros_mode.rs`, row 59's door survey). pub const MT_MOON_POKECENTER: u8 = 0x44; +/// Bill's house on Route 25, where rung 16 (the S.S. Ticket) is earned (row 73). Confirmed by the +/// cartridge rather than by counting: Route 25's warp table names `$58` at (45, 3), and the +/// cartridge's own hidden-event map list (`HiddenEventMaps`) carries `$58` at the position the +/// disassembly lists `BILLS_HOUSE` in (`tests/rom_macros_mode.rs`, row 73). +pub const BILLS_HOUSE: u8 = 0x58; pub const ROCK_TUNNEL_1F: u8 = 0x52; pub const INDIGO_PLATEAU_LOBBY: u8 = 0xae; /// The house beside Cerulean's west road whose back door is the one way into the closed yard at diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/mod.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/mod.rs index b8f533f..8d6e2e6 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/mod.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/mod.rs @@ -222,6 +222,10 @@ const RUNG_PLACES: [Option; RANK_LADDER.len()] = { const fn object(map: u8) -> Option { Some(MapPlace::object(map)) } + /// A rung earned by an errand in one room: its people, then its things. + const fn errand(map: u8) -> Option { + Some(MapPlace::errand(map)) + } [ None, // 0 BOOT: nowhere. at(maps::REDS_HOUSE_2F), // 1 BEDROOM @@ -244,7 +248,12 @@ const RUNG_PLACES: [Option; RANK_LADDER.len()] = { at(maps::CERULEAN_CITY), // 13 CERULEAN CITY person(maps::CERULEAN_GYM), // 14 CASCADE BADGE, likewise at(maps::ROUTE_24), // 15 NUGGET BRIDGE, north out of Cerulean - at(maps::ROUTE_25), // 16 MET BILL, whose house is on Route 25 + // 16 MET BILL: the S.S. Ticket is Bill's thanks for an errand in his house -- talk to + // him (he is a Pokémon), press the cell separator's PC (a hidden event, not a sprite), + // talk to him again. One room, people then things: an errand (row 73). It was + // `at(ROUTE_25)`, and a fly on Route 25 was already "there", so inside the house + // `GO OBJECTIVE` was the door out to the route. + errand(maps::BILLS_HOUSE), at(maps::VERMILION_CITY), // 17 VERMILION CITY at(maps::VERMILION_CITY), // 18 HM CUT, on the S.S. Anne at Vermilion's dock None, // 19 THUNDER BADGE: Vermilion Gym, id not derived diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs index 69f1c35..93773ef 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs @@ -33,7 +33,7 @@ use super::macros::geography::Amenity; use super::mapgrid::{self, MapGrids}; use super::macros::state::{ BagItem, Battle, BattleKind, BattleMenu, Connections, Cursor, EnemyMon, Facing, GameState, - MapGrid, MapSize, Mon, Move, Naming, Npc, Party, Pc, Player, Scene, Shop, ShopScreen, Sign, StartMenu, + HiddenEvent, MapGrid, MapSize, Mon, Move, Naming, Npc, Party, Pc, Player, Scene, Shop, ShopScreen, Sign, StartMenu, Status, TextBox, Walkable, Warp, }; use super::symbols::ram; @@ -350,6 +350,30 @@ pub mod poke { /// The cartridge's item-use dispatch and the ids that name its routines (row 63, /// `docs/design/macros.md` 12.27). + /// The cartridge's hidden-event tables (row 73, `docs/design/macros.md` 12.35). + /// + /// `engine/overworld/hidden_events.asm`: `CheckForHiddenEvent` walks `HiddenEventMaps`, one + /// map id per byte to a `$ff`, and with the index it found there reads a little-endian pointer + /// out of `HiddenEventPointers` to that map's list. Both tables and every list are in the + /// routine's own `SECTION "Hidden Events Core"`, which `layout.link` places in ROM bank `$11`. + /// At the pinned commit the two tables are at `$11:$6A40` and `$11:$6A96`: read from the + /// operands of the routine's `ld hl, HiddenEventMaps` and `ld hl, HiddenEventPointers` on the + /// cartridge, and pinned by the ROM-gated test that reads them back from there. A list entry is + /// six bytes (`hidden_event`): y, x, the routine's argument, and the routine as `dba`. + pub mod hidden { + pub const TABLE_BANK: u8 = 0x11; + pub const MAPS_ADDRESS: u16 = 0x6a40; + pub const POINTERS_ADDRESS: u16 = 0x6a96; + pub const ENTRY_BYTES: u16 = 6; + /// More maps than the table has (85 at the pinned commit), and more entries than any one + /// map's list (Silph Co.'s and the Game Corner's are the long ones): a walk that runs past + /// either is not walking the table the disassembly describes, and answers nothing. + pub const MAX_MAPS: u16 = 128; + pub const MAX_ENTRIES: u16 = 32; + /// `SPRITE_FACING_DOWN`, `_UP`, `_LEFT`, `_RIGHT` (`constants/sprite_data_constants.asm`). + pub const FACINGS: [u8; 4] = [0x00, 0x04, 0x08, 0x0c]; + } + pub mod items { /// `engine/items/item_effects.asm`: `UseItem_` jumps through `ItemUsePtrTable`, one /// little-endian pointer per item id from `MASTER_BALL` (1) to `MAX_ELIXER` (`$53`), in @@ -2055,6 +2079,60 @@ pub fn signs(memory: &mut dyn MemoryReader) -> Vec { signs } +/// The current map's hidden events, read from the cartridge's own table ([`poke::hidden`]). +/// +/// Empty on a map the table does not list, when the seam has no cartridge image behind it, and +/// when the bytes are not the shape the disassembly describes -- a map list with no end, a pointer +/// outside the bank's window, a list longer than any map's, a tile off the loaded map. A table +/// this module cannot read is not one it reports, so a wrong address narrows (`GO OBJECTIVE` has +/// one less thing to aim at) and never invents a tile. +pub fn hidden_events(memory: &mut dyn MemoryReader) -> Vec { + hidden_events_inner(memory).unwrap_or_default() +} + +fn hidden_events_inner(memory: &mut dyn MemoryReader) -> Option> { + use poke::hidden::*; + let size = map_size(memory)?; + let map = read(memory, ram::wCurMap); + let mut index = None; + for position in 0..MAX_MAPS { + let id = memory.read_rom(TABLE_BANK, MAPS_ADDRESS + position)?; + if id == 0xff { + break; + } + if id > poke::MAX_MAP_ID || position + 1 == MAX_MAPS { + return None; + } + if id == map && index.is_none() { + index = Some(position); + } + } + let Some(position) = index else { return Some(Vec::new()) }; + let at = POINTERS_ADDRESS + 2 * position; + let list = u16::from_le_bytes([memory.read_rom(TABLE_BANK, at)?, memory.read_rom(TABLE_BANK, at + 1)?]); + if !(0x4000..0x8000).contains(&list) { + return None; + } + let mut out = Vec::new(); + for entry in 0..MAX_ENTRIES { + let base = list.checked_add(entry * ENTRY_BYTES)?; + let y = memory.read_rom(TABLE_BANK, base)?; + if y == 0xff { + return Some(out); + } + let x = memory.read_rom(TABLE_BANK, base + 1)?; + let argument = memory.read_rom(TABLE_BANK, base + 2)?; + let routine = + u16::from_le_bytes([memory.read_rom(TABLE_BANK, base + 4)?, memory.read_rom(TABLE_BANK, base + 5)?]); + if x >= size.width || y >= size.height || routine >= 0x8000 { + return None; + } + let facing = FACINGS.contains(&argument).then(|| facing_from(argument)); + out.push(HiddenEvent { x, y, index: entry as u8, facing }); + } + None +} + /// Which of the current map's edges lead to another map, from `wCurMapConnections`. pub fn connections(memory: &mut dyn MemoryReader) -> Connections { let bits = read(memory, ram::wCurMapConnections); @@ -2245,6 +2323,10 @@ impl GameState for PokeState<'_> { signs(self.memory) } + fn hidden_events(&mut self) -> Vec { + hidden_events(self.memory) + } + fn walkable(&mut self, x: u8, y: u8) -> Walkable { walkable(self.memory, x, y) } diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/tests.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/tests.rs index 8f4e17b..c6087ec 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/tests.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/tests.rs @@ -1273,6 +1273,8 @@ fn the_objective_is_the_next_unreached_rungs_place_where_the_catalog_knows_one() assert_eq!(RUNG_PLACES[11].map(|place| place.map), Some(maps::PEWTER_GYM), "BOULDER BADGE"); assert_eq!(RUNG_PLACES[14].map(|place| place.map), Some(maps::CERULEAN_GYM), "CASCADE BADGE"); assert_eq!(RUNG_PLACES[19], None, "THUNDER BADGE: Vermilion Gym's id is not derived"); + // Row 73: the ticket is an errand inside Bill's house, not the route the house is on. + assert_eq!(RUNG_PLACES[16], Some(crate::adapter::MapPlace::errand(maps::BILLS_HOUSE)), "MET BILL"); // And past the top of the ladder there is no next rung at all. assert_eq!(RUNG_PLACES.len(), RANK_LADDER.len()); assert_eq!(rung_place(&f.reward.seen, RANK_LADDER.len()), None); diff --git a/services/flysim/crates/flysim/tests/rom_macros_mode.rs b/services/flysim/crates/flysim/tests/rom_macros_mode.rs index d253f03..23715ba 100644 --- a/services/flysim/crates/flysim/tests/rom_macros_mode.rs +++ b/services/flysim/crates/flysim/tests/rom_macros_mode.rs @@ -5132,3 +5132,274 @@ fn row70_the_list_after_a_faint_is_still_a_forced_switch_and_is_answered() { assert!(turn_after.is_some(), "the forced switch was never answered: {:?}", drive.starts); assert_eq!(out, 1, "the Pokémon still standing (the Zubat, slot 1) was sent out"); } + +/// Route 25, Bill's house on it, and the flag rung 16 is (`constants/map_constants.asm`, +/// `constants/event_constants.asm`; `docs/design/ladder.md` verified bit 1372). +const ROUTE_25: u32 = 0x24; +const BILLS_HOUSE: u32 = 0x58; +const EVENT_GOT_SS_TICKET: u16 = 1372; + +/// A row-73 checkpoint named by `var`, or `None` to skip. +/// +/// Scout B3's, from the v0.7.5 tree and the live row-71 checkpoint (rung 15), plus the live one +/// itself (`FLY_ROW71_CHECKPOINT`, rom-env's existing name): +/// +/// - `FLY_ROW73_DOOR_CHECKPOINT` (`scout-b3-bills-ring-door`): the same ring, just inside the door. +/// - `FLY_ROW73_PC_CHECKPOINT` (`scout-b3-bills-pc-step`): a carry-forward by scripted presses -- +/// Bill has asked for the cell separator and walked into the machine, and the next step is the +/// PC, a hidden event no sprite or sign stands for. +fn row73_checkpoint(var: &str) -> Option { + std::env::var_os(var).map(|path| { + flysim::store::load(std::path::Path::new(&path)) + .expect("the checkpoint should be a FLYSIM01 envelope") + }) +} + +/// Row 73: the hidden-event table the macros read is the cartridge's own, and Bill's PC is in it. +/// +/// The two addresses are pinned the way `ItemUsePtrTable`'s is: they are the operands of +/// `CheckForHiddenEvent`'s own `ld hl, HiddenEventMaps` (followed by its `ld a, [hli] / ld b, a / +/// cp $ff`) and `ld hl, HiddenEventPointers` (followed by `add hl, de`), found in the routine's +/// bank. Then, standing in Bill's house, the seam reads one hidden event, the PC at (1, 4), pressed +/// facing up -- the entry the scout's scripted presses found by hand. +#[test] +fn row73_the_hidden_event_table_is_the_cartridges_and_bills_pc_is_in_it() { + use flybrain_gb::pokemon_red::macros::state::{Facing, HiddenEvent}; + use flybrain_gb::pokemon_red::state::{self, poke::hidden}; + let rom = skip_without_rom!(); + let gb = emulator(&rom); + let bank: Vec = (0x4000u16..0x8000) + .map(|address| gb.read_rom_bank(hidden::TABLE_BANK, address).expect("bank $11 is in the image")) + .collect(); + let [maps_low, maps_high] = hidden::MAPS_ADDRESS.to_le_bytes(); + let [pointers_low, pointers_high] = hidden::POINTERS_ADDRESS.to_le_bytes(); + let maps_load = [0x21, maps_low, maps_high, 0x2a, 0x47, 0xfe, 0xff]; + let pointers_load = [0x21, pointers_low, pointers_high, 0x19]; + let at = |needle: &[u8]| bank.windows(needle.len()).position(|window| window == needle); + let maps_at = at(&maps_load).expect("CheckForHiddenEvent loads HiddenEventMaps from the pinned address"); + let pointers_at = + at(&pointers_load).expect("CheckForHiddenEvent loads HiddenEventPointers from the pinned address"); + assert!(pointers_at > maps_at && pointers_at - maps_at < 32, "one routine: {maps_at:#x} {pointers_at:#x}"); + + let Some(checkpoint) = row73_checkpoint("FLY_ROW73_DOOR_CHECKPOINT") else { + eprintln!("skipped: no FLY_ROW73_DOOR_CHECKPOINT"); + return; + }; + let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint); + assert_eq!(run.map(), BILLS_HOUSE, "the checkpoint is inside Bill's house"); + assert_eq!( + state::hidden_events(&mut run.gb), + vec![HiddenEvent { x: 1, y: 4, index: 0, facing: Some(Facing::Up) }], + "Bill's house has one hidden event, the cell separator's PC" + ); +} + +/// Row 73, the trap: from inside the ring at Bill's door, macros mode earns rung 16 (the S.S. +/// Ticket). +/// +/// **Live on v0.7.5** (scout B3, six seeds, 2.8 brain hours): rung 16's place was `at(ROUTE_25)`, +/// so a fly on Route 25 was already "there". `GO ROUTE` walked it into Bill's house, and inside +/// `GO OBJECTIVE` -- an exit into the objective's own map is toward it -- and `GO OUT` walked it +/// straight back out, 30 to 60 times per ten brain minutes; `GO NPC` was chosen 0 times in about +/// 600 starts in the house. Behind that, the errand's middle step is the cell separator's PC, a +/// hidden event no macro could press, so even a fly that talked to Bill could not earn the rung. +/// +/// The claims, over the stub rotation (no brain, a readout that never names a macro): the fly +/// does not leave the house before the errand is done, and `EVENT_GOT_SS_TICKET` is set within the +/// budget. On main the flag is never set. +/// +/// ```sh +/// FLY_ROM=/path/to/pokemon-red.gb \ +/// FLY_ROW73_DOOR_CHECKPOINT=.local/checkpoints/scout-b3-bills-ring-door.checkpoint \ +/// cargo test --release -p flysim --test rom_macros_mode -- --nocapture row73 +/// ``` +#[test] +fn row73_the_fly_earns_the_ss_ticket_from_inside_the_ring_at_bills_door() { + let rom = skip_without_rom!(); + let Some(checkpoint) = row73_checkpoint("FLY_ROW73_DOOR_CHECKPOINT") else { + eprintln!("skipped: no FLY_ROW73_DOOR_CHECKPOINT"); + return; + }; + let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint); + assert_eq!(run.map(), BILLS_HOUSE, "the checkpoint is inside Bill's house"); + assert!(!run.event(EVENT_GOT_SS_TICKET), "the checkpoint has no ticket"); + let (_, out) = row73_drive_to_the_ticket(&mut run, 36_000); + assert_eq!(out, 0, "the house was left before the errand was done"); +} + +/// Row 73, the whole road: from the live row-71 checkpoint (v0.7.3, rung 15, in a wild battle on +/// Route 25) macros mode finishes the battle, walks to Bill's house and earns the ticket. Route +/// 25's own warp table is what pins `maps::BILLS_HOUSE`. +#[test] +fn row73_the_fly_walks_from_the_live_route_25_checkpoint_to_the_ss_ticket() { + let rom = skip_without_rom!(); + let Some(checkpoint) = row73_checkpoint("FLY_ROW71_CHECKPOINT") else { + eprintln!("skipped: no FLY_ROW71_CHECKPOINT"); + return; + }; + let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint); + assert_eq!(run.gb.read_wram(flybrain_gb::pokemon_red::symbols::ram::wCurMap), ROUTE_25 as u8); + assert!(!run.event(EVENT_GOT_SS_TICKET), "the checkpoint has no ticket"); + let warps = flybrain_gb::pokemon_red::state::warps(&mut run.gb); + assert!( + warps.iter().any(|warp| (warp.x, warp.y, u32::from(warp.destination_map)) == (45, 3, BILLS_HOUSE)), + "Route 25's door at (45, 3) leads to $58: {warps:?}" + ); + row73_drive_to_the_ticket(&mut run, 216_000); +} + +/// Row 73, the hidden event alone: Bill is in the machine, the next step is the PC, and macros mode +/// presses it and earns the ticket. On main no button on any pad presses a hidden event. +#[test] +fn row73_the_cell_separator_pc_is_pressed_and_bill_hands_over_the_ticket() { + let rom = skip_without_rom!(); + let Some(checkpoint) = row73_checkpoint("FLY_ROW73_PC_CHECKPOINT") else { + eprintln!("skipped: no FLY_ROW73_PC_CHECKPOINT"); + return; + }; + let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint); + assert_eq!(run.map(), BILLS_HOUSE, "the checkpoint is inside Bill's house"); + assert!(!run.event(EVENT_GOT_SS_TICKET), "the checkpoint has no ticket"); + row73_drive_to_the_ticket(&mut run, 36_000); +} + +/// Drive the stub rotation until the ticket's flag is set, counting the house's doors on the way: +/// `(into, out)`. +fn row73_drive_to_the_ticket(run: &mut Run, budget: u32) -> (u32, u32) { + let mut previous = run.map(); + let (mut into, mut out) = (0u32, 0u32); + let mut got = None; + for frame in 0..budget { + run.frame(); + let map = run.map(); + if map != previous && map != u32::MAX { + into += u32::from(map == BILLS_HOUSE); + out += u32::from(previous == BILLS_HOUSE); + previous = map; + } + if run.event(EVENT_GOT_SS_TICKET) { + got = Some(frame); + break; + } + } + eprintln!( + "ticket at {got:?} ({:.1} brain minutes), into the house {into} times, out {out}, rank {}, \ + talk on pad by map {:?}, talk starts {:?}, macros {:?}", + run.ms / 60_000.0, + run.adapter.progress().rank, + run.talk_on_pad_by_map, + run.talk_starts_by_map, + run.started + ); + assert!(got.is_some(), "no S.S. Ticket in {budget} frames: route {:?}, macros {:?}", run.route, run.started); + (into, out) +} + +const ROUTE_5: u32 = 0x10; +const CERULEAN_TRASHED_HOUSE: u32 = 0x3e; + +/// Where `GO OBJECTIVE` aims from here, read through the seam the macros read: the tiles. +fn row73_objective_aims(run: &mut Run) -> Vec<(u8, u8)> { + let ledger = AdapterLedger(&run.adapter); + let mut state = flybrain_gb::pokemon_red::state::PokeState::with_ledger(&mut run.gb, &ledger); + flybrain_gb::pokemon_red::macros::palette::objective_goals(&mut state) + .iter() + .map(|aim| (aim.tile.x, aim.tile.y)) + .collect() +} + +/// Row 73's third trap, on the seam: after the ticket, `GO OBJECTIVE` in the town aims at the +/// trashed house's front door, and inside the house at the hole in its back wall. +/// +/// On main the house is off the graph: in the town the objective toward Vermilion aimed at ground +/// the town's piece cannot reach (scout B3: `blocked` at (17, 28)), and inside the house the only +/// way toward an outdoor objective was the front door it came in by. From +/// `FLY_ROW73_SOUTH_CHECKPOINT` (`scout-b3-cerulean-south-half`, seed 4, 40 brain minutes, standing +/// at (10, 26) in the town's south-west) and `FLY_ROW73_TRASHED_CHECKPOINT` (the same run's seed 6, +/// going through the house's front door). +#[test] +fn row73_the_objective_south_of_cerulean_is_the_trashed_houses_two_doors() { + let rom = skip_without_rom!(); + if let Some(checkpoint) = row73_checkpoint("FLY_ROW73_SOUTH_CHECKPOINT") { + let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint); + assert_eq!(run.map(), CERULEAN_CITY, "the checkpoint is in Cerulean"); + assert!(run.event(EVENT_GOT_SS_TICKET), "the checkpoint has the ticket"); + assert_eq!(row73_objective_aims(&mut run), vec![(27, 11)], "the trashed house's front door"); + } else { + eprintln!("skipped: no FLY_ROW73_SOUTH_CHECKPOINT"); + } + let Some(checkpoint) = row73_checkpoint("FLY_ROW73_TRASHED_CHECKPOINT") else { + eprintln!("skipped: no FLY_ROW73_TRASHED_CHECKPOINT"); + return; + }; + let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint); + // Through the door with no button down: the warp's tear settles inside the house. + for _ in 0..240 { + run.gb.set_buttons(0); + run.gb.run_frame().expect("a frame should complete"); + run.ms += MS_PER_FRAME; + run.adapter.sample(&mut run.gb, run.ms); + } + assert_eq!(run.map(), CERULEAN_TRASHED_HOUSE, "inside the trashed house"); + let warps = flybrain_gb::pokemon_red::state::warps(&mut run.gb); + assert!( + warps.iter().any(|warp| (warp.x, warp.y, warp.destination_warp) == (3, 0, 7)), + "the hole in the back wall is the house's warp to Cerulean's (27, 9): {warps:?}" + ); + assert_eq!(row73_objective_aims(&mut run), vec![(3, 0)], "the hole in the back wall"); +} + +/// Row 73's third trap, after the ticket: the road south out of Cerulean is through the trashed +/// house, and macros mode takes it to Route 5. +/// +/// **Scout B3** (six seeds, 43 brain minutes each, from the ticket's carry-forward): 0 of 6 past +/// row 28 of Cerulean. The town's ground ends there; Route 5 is on the ground behind the trashed +/// house, in by its front door and out by the hole in its back wall, and the house was off the map +/// graph -- so `GO OBJECTIVE` toward Vermilion ended `blocked` at (17, 28) and the fly rang between +/// the town and its houses, 60 to 100 map changes per ten brain minutes. +/// +/// `FLY_ROW73_TRASHED_CHECKPOINT` (`scout-b3-cerulean-trashed-house`): seed 6, 40 brain minutes +/// in, going through the house's front door. `FLY_ROW73_TICKET_CHECKPOINT` +/// (`scout-b3-post-bill-ticket`): the carry-forward the Cerulean runs started from, in Bill's +/// house with the ticket. The claim from each: the fly is on Route 5 within the budget, and from +/// Bill's house in under half of what main needs. +#[test] +fn row73_the_fly_takes_the_trashed_house_south_to_route_5() { + let rom = skip_without_rom!(); + // Deterministic under the stub: on main the two take 54,442 and 63,880 frames, on the branch + // 52,081 and 27,067. The rotation does stumble through the house on main -- `GO ROUTE` takes + // every door in turn -- so this is the regression guard, and the seam test above is the claim + // main fails. + for (var, budget) in [("FLY_ROW73_TRASHED_CHECKPOINT", 72_000u32), ("FLY_ROW73_TICKET_CHECKPOINT", 48_000)] { + let Some(checkpoint) = row73_checkpoint(var) else { + eprintln!("skipped: no {var}"); + continue; + }; + let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint); + assert!(run.event(EVENT_GOT_SS_TICKET), "{var}: the checkpoint has the ticket"); + let mut previous = run.map(); + let (mut changes, mut into_the_house) = (0u32, 0u32); + let mut south = None; + for frame in 0..budget { + run.frame(); + let map = run.map(); + if map != previous && map != u32::MAX { + changes += 1; + into_the_house += u32::from(map == CERULEAN_TRASHED_HOUSE); + previous = map; + } + if map == ROUTE_5 { + south = Some(frame); + break; + } + } + let tail: Vec = run.route.iter().rev().take(24).rev().copied().collect(); + eprintln!( + "{var}: Route 5 at {south:?}, {changes} map changes, into the trashed house \ + {into_the_house} times, rank {}, last maps {tail:?}, macros {:?}", + run.adapter.progress().rank, + run.started + ); + assert!(south.is_some(), "{var}: not on Route 5 in {budget} frames: last maps {tail:?}"); + } +} From 872dcfc21414416136a81e5843ba5a2c79303cbf Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 02:18:22 +0000 Subject: [PATCH 08/27] docs: macros.md 12.35 and macros-wram.md 17 (row 73); the hidden-event list bound covers the Game Corner's 48 entries, checked on the cartridge --- docs/design/macros-wram.md | 26 ++++++ docs/design/macros.md | 88 +++++++++++++++++++ .../flybrain-gb/src/pokemon_red/state.rs | 7 +- .../crates/flysim/tests/rom_macros_mode.rs | 13 +++ 4 files changed, 131 insertions(+), 3 deletions(-) diff --git a/docs/design/macros-wram.md b/docs/design/macros-wram.md index 6ea508b..148bfb5 100644 --- a/docs/design/macros-wram.md +++ b/docs/design/macros-wram.md @@ -1077,3 +1077,29 @@ report their cursor (and its `max`) as the entry the same way. The offset is add list is on screen, because the byte outlives every list. Purchases still use only the first three rows (`MART_CURSOR_ROWS`, section 7). +## 17. The hidden-event tables (2026-10-02, `docs/design/macros.md` 12.35) + +Row 73. Two ROM tables, read through `MemoryReader::read_rom` from the cartridge image the process +already holds, never through the bus and never by switching banks. Pinned the way +`ItemUsePtrTable` is, and read back from the code that uses them by +`row73_the_hidden_event_table_is_the_cartridges_and_bills_pc_is_in_it` (FLY_ROM). + +| name | where | what reads it | +| --- | --- | --- | +| `HiddenEventMaps` | `$11:$6A40` | one map id per byte to a `$ff` (85 maps at the pinned commit); the operand of `CheckForHiddenEvent`'s `ld hl, HiddenEventMaps`, followed by `ld a, [hli] / ld b, a / cp $ff` | +| `HiddenEventPointers` | `$11:$6A96` | one little-endian pointer per map of the list above, into the same bank; the operand of the routine's `ld hl, HiddenEventPointers`, followed by `add hl, de` | + +Both are in `SECTION "Hidden Events Core"`, which `layout.link` places in bank `$11`. Each map's +list is six bytes an entry to a `$ff` (`hidden_event`): y, x, the routine's argument, and the +routine as `dba` (bank, then a little-endian address). The coordinates are in the same tile space as +`wXCoord`/`wYCoord`, like a sign's. + +**`state::hidden_events`** answers the current map's entries as `HiddenEvent { x, y, index, +facing }`: `index` is the entry's position in the map's list, which is how `wHiddenEventIndex` +counts and the talked ledger's key (`TalkTarget::Hidden`); `facing` is the argument when it is a +`SPRITE_FACING_*` value (`$00`, `$04`, `$08`, `$0C`), the side a routine such as `BillsHousePC` +checks. It answers nothing for a map list with no end within 128 entries or an id above `$f7`, a +pointer outside `$4000..$8000`, a list longer than 64 entries (the Game Corner's 48 are the longest), a tile off the loaded map or a +routine address at `$8000` or above. Bill's house (`$58`) has one entry: (1, 4), argument `$04`, +`BillsHousePC` at `$07:$6B6E`. + diff --git a/docs/design/macros.md b/docs/design/macros.md index bb7e3f4..76ed048 100644 --- a/docs/design/macros.md +++ b/docs/design/macros.md @@ -2155,6 +2155,94 @@ throws), `row71_a_ball_past_the_bags_window_is_thrown` (`FLY_ROW71_CHECKPOINT`, the live trap) and `row71_the_list_scroll_offset_is_where_the_cartridge_reads_it` (FLY_ROM). +### 12.35 An errand is its people, then its things, and a hidden event is a thing (2026-10-02, row 73) + +Live on v0.7.5, rung 15 (NUGGET BRIDGE), Route 24/25. Scout B3 measured it from the live +checkpoint on six seeds (2.8 brain hours): `GO ROUTE` walked the fly into Bill's house, and inside +it `GO OBJECTIVE` or `GO OUT` walked it straight back out, 30 to 60 times per ten brain minutes. +`GO NPC` was chosen 0 times in about 600 starts in the house, and new tiles stopped (2527 to 2531 +in 35 minutes). Rung 16 (MET BILL, `EVENT_GOT_SS_TICKET`) was never earned. + +- **The place was the route.** `RUNG_PLACES[16]` was `at(ROUTE_25)`, because the house's id was + not derived. A fly on Route 25 was already "there", so inside the house `GO OBJECTIVE` was an + exit into the objective's own map, which is the same door as `GO OUT`. That is row 29's lab loop + again, one rung later. +- **The rung is an errand, not a conversation.** `scripts/BillsHouse.asm`: Bill (a Pokémon, a + person sprite) asks for help and walks into the teleporter, the cartridge hides his sprite; the + cell separator is started from the PC at (1, 4), pressed facing up; Bill then steps out of the + machine as a second sprite and hands over the ticket. Two people and a thing, in that order. +- **The PC is a hidden event.** `wNumSigns` is 0 in the house and the only sprite is Bill: the PC + is an entry of the cartridge's own hidden-event table (`data/events/hidden_events.asm`), which + `CheckForHiddenEvent` searches on every A in the overworld. No macro could aim at it and `TALK` + was never dealt in front of it, so even a fly that talked to Bill could not earn the rung. + +What changed, all of it knowledge inside macros: + +- **`PlaceKind::Errand`.** Rung 16's place is `errand(BILLS_HOUSE)` (`$58`, confirmed by Route + 25's warp table and by the hidden-event map list). An errand's targets are the room's people, + drawn or off the screen, and once none is left untalked, its things: objects, signs and hidden + events. No step is named anywhere. The cartridge shows and hides the people as the errand moves + on, the talked ledger records what has been had, and what is left is the next step. People come + first because a thing pressed out of turn is in the talked ledger for the session: Bill's PC + pressed before he has asked prints the monitor and does nothing, and a PC recorded as talked to + would never be the next step again. Everything 12.5 and 12.22 give a person place applies: the + ways out are withheld while a target waits, `GO OBJECTIVE` aims at the four sides, facing a + target is the arrival and `TALK` is the press; the blocked ledger is the escape hatch. +- **Hidden events are read from the cartridge's table, not written down.** `state::hidden_events` + walks `HiddenEventMaps` and `HiddenEventPointers` in ROM bank `$11` through + `MemoryReader::read_rom`, the same read the move and item tables use: no WRAM is written and the + mapper's bank register is not touched. The two addresses are pinned from the operands of + `CheckForHiddenEvent`'s own `ld hl` instructions and checked on the cartridge + (`macros-wram.md` section 17); every read checks the table's shape and answers nothing for a + table that is not the one the disassembly describes, which narrows and never invents a tile. A + hard-coded `(1, 4)` would have been a number nobody can check from the running game; the table is + what the cartridge itself consults when the A is pressed. +- **A hidden event is only ever the errand's next step.** It is in `objective_targets` for an + errand and in `facing_target` (so `TALK` is dealt) only while it is that step. It is not added to + `GO ITEM`, `GO NPC` or `TALK` anywhere else. The table holds every PC, poster, trash can, + bookshelf and hidden item in Kanto; making them general targets would add a walk to most + buildings' pads and an entry to the talked ledger for each, which is a change to what the fly is + offered everywhere and not a fix for this trap. The day that is wanted it is one line in + `path::interactable_targets`, and it needs its own survey. +- **A hidden event's side.** Where the entry's argument is a `SPRITE_FACING_*` value it is the side + the routine checks before it does anything (`BillsHousePC` returns unless the player faces up), + so the walk's one aim is the tile on that side and only facing it from there is the arrival and + `TALK`'s precondition. An argument that is an item or a text id and happens to equal a facing + value only narrows the approach. + +The fly still chooses every press: `GO OBJECTIVE` to walk, `TALK` to press A, `YES`, `NO` or +`NEXT` in Bill's boxes. Nothing presses for it, no button is added to any pad, and the readout, the +catalog, the adapter and the compatibility string are unchanged. What the scene deals inside the +house is narrower than before, not wider: the ways out leave the pad while the errand waits. + +**The road after the ticket (the third trap).** With the ticket the objective is rung 17, +Vermilion, south through Cerulean. Cerulean's ground is in three pieces, not two: the town's ends at +row 28 (the gap at (16, 28) opens onto a wall and the trainer-tips sign), and the south of the map, +the road to Route 5 and the east edge onto Route 9 are reached through the trashed house (`$3e`), +in by its front door at (27, 11) and out by the hole in its back wall onto (27, 9) in the Rocket's +yard. Scout B3 flooded the grid: 378 of the map's 801 walkable tiles are the town's. The house was +off the map graph, so `GO OBJECTIVE` aimed at ground the town cannot reach (`blocked` at (17, 28)) +and the fly rang between the town and its houses (0 of 6 seeds past row 28 in 43 brain minutes +each). The house is now on the graph and the south is `SPLIT`'s third piece of Cerulean, so the +objective walks into the house and out through the hole. Before the ticket a guard stands on the +tile in front of the door (`TOGGLE_CERULEAN_GUARD_2`, (27, 12)), which the ticket's own script hides; the objective only +points south after the ticket. + +**Not fixed, predicted:** the road from Route 5 to Vermilion on the graph is Route 5, Saffron, +Route 6, as plain map edges. The cartridge's gate houses are guarded until the guard's drink is +given, and the way the game means is the Underground Path, whose houses are off the graph. No run +has reached Route 5's gate yet; it needs its own checkpoint and row. + +Tests: `an_errand_is_its_people_first_and_the_room_is_not_left_while_one_is_waiting`, +`a_hidden_event_is_the_errands_next_step_once_no_person_is_left_and_it_is_faced_from_its_side`, +`a_hidden_event_is_nobody_elses_target`, `the_road_south_out_of_cerulean_is_through_the_trashed_house`, +and on the cartridge `row73_the_hidden_event_table_is_the_cartridges_and_bills_pc_is_in_it`, +`row73_the_fly_earns_the_ss_ticket_from_inside_the_ring_at_bills_door`, +`row73_the_cell_separator_pc_is_pressed_and_bill_hands_over_the_ticket`, +`row73_the_fly_walks_from_the_live_route_25_checkpoint_to_the_ss_ticket`, +`row73_the_objective_south_of_cerulean_is_the_trashed_houses_two_doors` and +`row73_the_fly_takes_the_trashed_house_south_to_route_5`. + ## 13. Shops and Pokémon Centers (the operator, 2026-09-17: "refactor the shop macros. make it a ## priority to visit the shop at least once per area; make shop macros item purchases. same ## for the Pokécenter. heal should be a macro.") diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs index 93773ef..c99aaa8 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs @@ -366,10 +366,11 @@ pub mod poke { pub const POINTERS_ADDRESS: u16 = 0x6a96; pub const ENTRY_BYTES: u16 = 6; /// More maps than the table has (85 at the pinned commit), and more entries than any one - /// map's list (Silph Co.'s and the Game Corner's are the long ones): a walk that runs past - /// either is not walking the table the disassembly describes, and answers nothing. + /// map's list (the Game Corner's 48 slot machines and coins are the longest): a walk that + /// runs past either is not walking the table the disassembly describes, and answers + /// nothing. pub const MAX_MAPS: u16 = 128; - pub const MAX_ENTRIES: u16 = 32; + pub const MAX_ENTRIES: u16 = 64; /// `SPRITE_FACING_DOWN`, `_UP`, `_LEFT`, `_RIGHT` (`constants/sprite_data_constants.asm`). pub const FACINGS: [u8; 4] = [0x00, 0x04, 0x08, 0x0c]; } diff --git a/services/flysim/crates/flysim/tests/rom_macros_mode.rs b/services/flysim/crates/flysim/tests/rom_macros_mode.rs index 23715ba..6a68c3e 100644 --- a/services/flysim/crates/flysim/tests/rom_macros_mode.rs +++ b/services/flysim/crates/flysim/tests/rom_macros_mode.rs @@ -5180,6 +5180,19 @@ fn row73_the_hidden_event_table_is_the_cartridges_and_bills_pc_is_in_it() { let pointers_at = at(&pointers_load).expect("CheckForHiddenEvent loads HiddenEventPointers from the pinned address"); assert!(pointers_at > maps_at && pointers_at - maps_at < 32, "one routine: {maps_at:#x} {pointers_at:#x}"); + // Every map's list ends inside the bounds `state::hidden_events` holds the table to, so no map's + // events are refused for being long (the Game Corner's 48 are the longest). + let byte = |address: u16| bank[usize::from(address - 0x4000)]; + let mut maps = 0u16; + while byte(hidden::MAPS_ADDRESS + maps) != 0xff { + assert!(maps < hidden::MAX_MAPS, "the map list ends"); + let at = hidden::POINTERS_ADDRESS + 2 * maps; + let list = u16::from_le_bytes([byte(at), byte(at + 1)]); + let entries = (0..).take_while(|entry| byte(list + entry * hidden::ENTRY_BYTES) != 0xff).count(); + assert!(entries < usize::from(hidden::MAX_ENTRIES), "map {:#04x}: {entries}", byte(hidden::MAPS_ADDRESS + maps)); + maps += 1; + } + assert_eq!(maps, 85, "the pinned commit's 85 maps with hidden events"); let Some(checkpoint) = row73_checkpoint("FLY_ROW73_DOOR_CHECKPOINT") else { eprintln!("skipped: no FLY_ROW73_DOOR_CHECKPOINT"); From 49bae21a4d6c8dba215b94051ac8c60c8ede2d09 Mon Sep 17 00:00:00 2001 From: acamilo Date: Thu, 1 Oct 2026 22:10:47 +0000 Subject: [PATCH 09/27] scorecard: a multi-seed good-play regression harness (fly-scorecard) A fixed checkpoint set x seeds x brain minutes on the real connectome, on the session runtime or the legacy loop, reduced to JSON: rungs per hour, empty pad, watchdog check 10 rules, ladder-worthy traps, the shop-to-catch funnel, heals, whiteouts, battles, blocked macros. Compare mode pairs two cards by (checkpoint, seed) and judges each metric with a sign-flip permutation test and a tolerance. PokeredTask gains a read-only with_reader for the harness. --- docs/scorecard.md | 121 +++ services/flysim/Cargo.toml | 1 + .../crates/fly-legacy-session/src/task.rs | 13 + .../flysim/crates/fly-scorecard/Cargo.toml | 31 + .../crates/fly-scorecard/src/compare.rs | 584 +++++++++++ .../flysim/crates/fly-scorecard/src/lib.rs | 16 + .../flysim/crates/fly-scorecard/src/main.rs | 368 +++++++ .../flysim/crates/fly-scorecard/src/obs.rs | 146 +++ .../flysim/crates/fly-scorecard/src/runner.rs | 391 ++++++++ .../flysim/crates/fly-scorecard/src/suite.rs | 429 ++++++++ .../flysim/crates/fly-scorecard/src/tally.rs | 940 ++++++++++++++++++ .../crates/fly-scorecard/src/watchdog.rs | 401 ++++++++ .../fly-scorecard/tests/rom_scorecard.rs | 79 ++ tools/scorecard/checkpoints.json | 77 ++ tools/scorecard/overlay.sh | 35 + tools/scorecard/with-reader.patch | 24 + 16 files changed, 3656 insertions(+) create mode 100644 docs/scorecard.md create mode 100644 services/flysim/crates/fly-scorecard/Cargo.toml create mode 100644 services/flysim/crates/fly-scorecard/src/compare.rs create mode 100644 services/flysim/crates/fly-scorecard/src/lib.rs create mode 100644 services/flysim/crates/fly-scorecard/src/main.rs create mode 100644 services/flysim/crates/fly-scorecard/src/obs.rs create mode 100644 services/flysim/crates/fly-scorecard/src/runner.rs create mode 100644 services/flysim/crates/fly-scorecard/src/suite.rs create mode 100644 services/flysim/crates/fly-scorecard/src/tally.rs create mode 100644 services/flysim/crates/fly-scorecard/src/watchdog.rs create mode 100644 services/flysim/crates/fly-scorecard/tests/rom_scorecard.rs create mode 100644 tools/scorecard/checkpoints.json create mode 100755 tools/scorecard/overlay.sh create mode 100644 tools/scorecard/with-reader.patch diff --git a/docs/scorecard.md b/docs/scorecard.md new file mode 100644 index 0000000..b3e4227 --- /dev/null +++ b/docs/scorecard.md @@ -0,0 +1,121 @@ +# The behavioural scorecard + +A repeatable, multi-seed "good play" regression harness. The unit tests say the macros do what +they were written to; the trap hunt says a fly stuck in one place got out. Neither says whether a +release plays *better or worse* than the one before it across the places the fly actually is. The +scorecard does: a fixed set of checkpoints, K seeds each, T brain minutes each, on the real +connectome with the macro layer, reduced to one JSON per release and compared release against +release by a test over the paired runs, never by a single run. + +It measures and presses nothing. It restores a checkpoint, lets the brain play, and counts. The +ethos check (`docs/loop-review.md`) is untouched: the harness is outside the fly. + +```sh +export FLY_ROM=/path/to/the-cartridge # read, never copied +cargo build --release -p fly-scorecard # from services/flysim + +fly-scorecard list # the set, resolved, each checkpoint's rung +fly-scorecard suite --label v0.7.5 --out card.json # the set x 3 seeds x 12 brain minutes +fly-scorecard summary card.json # one screen of markdown +fly-scorecard compare old.json new.json # exit 1 when a metric regressed +fly-scorecard run-one --checkpoint X --seed 1 # one run, JSON out (--out FILE) +``` + +`--runtime session` (the default) runs the session composition the release cut over to +(`fly-legacy-session`, in-process, unpaced); `--runtime legacy` runs the stream's own frame +(`flysim::frame::LegacyFrame`). Both hand the same per-frame observation to the same tally, so a +card from one runtime is comparable with a card from the other. From the same checkpoint and seed +the two give identical reports apart from wall time (`tests/rom_scorecard.rs` holds it), which makes a scorecard +run on both a second piece of shadow evidence. `--mode raw` runs without the macro layer. + +## The set + +`tools/scorecard/checkpoints.json` names each checkpoint by the environment variable that holds +its path (the ROM tests' own, `rom-env.sh`), never by a path; `--extra id=path` adds more (the +newest live checkpoint, a trap's). The checkpoints are not committed (`.local/` is untracked). +`list` prints the rung each one stands on, from its reward ledger. The set has two or three +states at each of rungs 8, 9, 10, 11, 12 and 15; rungs 13 and 14 have no checkpoint yet and join +the set when the scout makes them (a new entry is a line in the JSON). A checkpoint missing from +the environment is named on stderr and, with `--strict`, an error. + +## Seeds + +A checkpoint restores a deterministic brain, so two runs from it would be the same run. A seed +therefore chooses how many frames the brain's readout is ignored before the measurement starts +(60 to 1,800 frames, a splitmix of the seed; seed 0 is none). The brain still ticks and its noise +generator still advances, the game sees no button, and from the first measured frame the readout +is the brain's own: the run sits on a different point of its own trajectory. The idle frames are +not measured. The same seed twice is the same run. + +## What a run reports + +One `RunReport` per (checkpoint, seed). Every number is computed from per-frame observations by +`tally.rs`, which has no emulator in it and is unit-tested on synthetic frames. + +| group | what | +| --- | --- | +| rungs | start, end, gained, the brain minute of each climb; reported per brain hour | +| places | the adapter's exploration count, start and end | +| empty pad | frames with the macro layer on, nothing running and no button dealt; seconds, share, longest stretch | +| watchdog | `fly-watchdog` check 10, rule for rule (`watchdog.rs`): probes, suspected, reasons, **confirmed** (two suspected probes in a row) and **ladder events** (one per run of two or more: a trap the recovery ladder would act on) | +| hunt | the trap hunt's windows (two brain minutes, fewer than four tiles or a sequence repeated more than ten times) | +| ratchet | rollbacks, split by game over and stall | +| macros | starts, done, blocked, timeout, refused, by macro | +| funnel | GO SHOP, BUY BALL, THROW BALL, catch: counts at each stage, balls gained and spent, species gained, and how far down the funnel the run got | +| heals | GO HEAL and the nurse's HEAL | +| whiteouts | the whole party fainted (a rising edge) | +| battles | started, ended, wild and trainer, won (a battle or trainer payout), lost (the party fainted in it), caught, other | +| rewards, scenes | counts and totals by adapter kind; frames by scene | + +The watchdog's rules are the shell's: the same thresholds, the same order, the same two-probe +memory for the zero-progress, unrewarded and unwon-battle rules. Two things differ, both about +time: a run is short, so the probe cadence is a parameter (default every 120 brain seconds, +first at 300; the stream's is five wall minutes) and the window is the last ten brain minutes or +the whole run when it is shorter; and the first probe compares the exploration count with the +run's starting count, which the live check lacks after a boot. + +## Compare + +`compare A.json B.json` pairs runs by (checkpoint, seed). Each metric (`compare.rs`, `METRICS`) +has a direction (more is better, less is better, or info), an absolute tolerance and a relative +one. For each metric the pairs give one difference, signed so that positive means B is worse. B +**fails** a metric when it is worse by more than the tolerance **and** a one-sided sign-flip +permutation test over the pairs gives p below alpha (default 0.05). It reports **better** by the +same two tests, and **pass** otherwise: a change inside the tolerance is noise however consistent, +and one bad run among eighteen is not a regression. The test is exact up to 20 pairs and a +fixed-seed Monte-Carlo beyond, so the same two cards always give the same verdicts. The +comparison also names its caveats (different lengths, different runtimes, fewer than eight +pairs, unpaired runs). Exit status 1 is a failed metric. + +The metrics: rungs per hour, places per hour, empty pad %, suspected probes %, ladder events per +hour, hunt windows flagged %, rollbacks per hour, blocked macro %, buy ball, throws and catches +per hour, battles won and lost per hour, whiteouts per hour. Heals per hour and macro starts per +minute are reported, never judged: healing more can follow losing more. + +## Cost and size + +A brain minute is about 25 wall seconds on a 5-thread session run on the build box (the legacy +loop is about a quarter faster). The default suite, twelve checkpoints by three seeds by twelve +brain minutes, is 432 brain minutes: two runs at a time, five threads each, on ten cores, a little +over an hour. More seeds tighten the test; longer runs let rungs climb. Three seeds of twelve +minutes is the smallest suite whose pair count (36) can reach p < 0.001. + +## What it does not do + +- It does not rebuild session ledgers a restore starts empty (the trap hunt's + `FLY_TRAP_SEED_*`); a trap that needs them is that tool's. +- Twelve brain minutes rarely climb two rungs. Rungs per hour is a rate over many runs, not a + per-run prediction; a release that is faster by a rung every few hours shows only across the + suite. +- It judges play against the previous release, not against a notion of good. A regression is + "worse than last time"; the absolute numbers say how good last time was. + +## Releases and nightly + +`tools/scorecard/overlay.sh ` puts the tool on the tree of an older release (the crate, +the set, the docs, and the one read-only accessor `PokeredTask::with_reader`), so a release that +predates it can be scored and its numbers are its own. The operator's nightly runner builds the +latest release tag on a build box, runs the suite, writes the card and a one-screen summary and +compares with the previous release's card. + +`tools/scorecard/baseline-v0.7.5.json` is the reference card of v0.7.5 (adapter v8). diff --git a/services/flysim/Cargo.toml b/services/flysim/Cargo.toml index 89a995a..55dec42 100644 --- a/services/flysim/Cargo.toml +++ b/services/flysim/Cargo.toml @@ -11,6 +11,7 @@ members = [ "crates/flybus", "crates/flysim", "crates/flysim-store", + "crates/fly-scorecard", ] [workspace.package] diff --git a/services/flysim/crates/fly-legacy-session/src/task.rs b/services/flysim/crates/fly-legacy-session/src/task.rs index f85694e..2cd14c2 100644 --- a/services/flysim/crates/fly-legacy-session/src/task.rs +++ b/services/flysim/crates/fly-legacy-session/src/task.rs @@ -368,6 +368,19 @@ impl PokeredTask { ) } + /// Read the committed boundary's memory image through the cartridge, as the macro engine + /// reads it, for a harness that measures play (the scorecard). `None` before the first + /// observation. Changes nothing. + pub fn with_reader( + &self, + f: impl FnOnce(&mut dyn flybrain_gb::MemoryReader) -> R, + ) -> Option { + let inner = self.lock(); + let (_, image) = inner.current.as_ref()?; + let mut reader = ImageReader::new(image, &inner.cartridge); + Some(f(&mut reader)) + } + /// The brain time of the last transition (its Prepare's clock), in ms: `network.ms`. pub fn brain_ms(&self) -> f64 { self.lock().ms diff --git a/services/flysim/crates/fly-scorecard/Cargo.toml b/services/flysim/crates/fly-scorecard/Cargo.toml new file mode 100644 index 0000000..4d1c6bd --- /dev/null +++ b/services/flysim/crates/fly-scorecard/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "fly-scorecard" +version.workspace = true +edition = "2024" +rust-version.workspace = true +license.workspace = true +publish = false +description = "The behavioural scorecard (B2): a repeatable multi-seed good-play regression harness over a fixed checkpoint set, on either runtime, with a release-against-release compare." + +[lib] +name = "fly_scorecard" +path = "src/lib.rs" + +[[bin]] +name = "fly-scorecard" +path = "src/main.rs" + +[dependencies] +# The unchanged engine under test: flysim's frame and macro layer (the legacy runtime), the +# session composition (the session runtime), flybrain-gb's adapter and state readers. +flysim = { path = "../flysim" } +fly-legacy-session = { path = "../fly-legacy-session" } +fly-session = { path = "../fly-session" } +flybrain-core = { path = "../flybrain-core" } +flybrain-gb = { path = "../flybrain-gb" } +anyhow = "1.0" +clap = { version = "4.5", features = ["derive"] } +serde = { workspace = true } +serde_json = { workspace = true } +tokio = { version = "1", features = ["rt", "rt-multi-thread", "sync", "time", "macros"] } +tempfile = "3" diff --git a/services/flysim/crates/fly-scorecard/src/compare.rs b/services/flysim/crates/fly-scorecard/src/compare.rs new file mode 100644 index 0000000..41a5dfe --- /dev/null +++ b/services/flysim/crates/fly-scorecard/src/compare.rs @@ -0,0 +1,584 @@ +//! Release A against release B: a verdict per metric from the runs, not from one run. +//! +//! The runs of the two suites are paired by `(checkpoint, seed)`. Each pair gives one difference +//! per metric, signed so that positive means B is worse. A metric fails when B is worse than A by +//! more than its tolerance **and** a sign-flip permutation test over the pairs says the shortfall +//! is not noise (one-sided, `alpha`). Otherwise it passes, and when B is better by the same two +//! tests it says so. A metric with no direction (`info`) is only reported. +//! +//! The test is exact up to 20 pairs and a fixed-seed Monte-Carlo beyond, so the same two suites +//! always give the same verdicts. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use crate::suite::SuiteReport; +use crate::tally::RunReport; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Direction { + /// More is better. + Up, + /// Less is better. + Down, + /// Reported, never judged. + Info, +} + +/// One metric: how to read it off a run, which way is good, and how big a change must be before +/// it can count. +pub struct Metric { + pub name: &'static str, + pub unit: &'static str, + pub direction: Direction, + /// A change smaller than this (in `unit`) is never a regression or an improvement. + pub abs_tol: f64, + /// ... nor one smaller than this share of A's mean. + pub rel_tol: f64, + pub read: fn(&RunReport) -> f64, +} + +fn per_hour(count: f64, run: &RunReport) -> f64 { + if run.minutes <= 0.0 { 0.0 } else { count * 60.0 / run.minutes } +} + +fn pct(part: f64, whole: f64) -> f64 { + if whole <= 0.0 { 0.0 } else { 100.0 * part / whole } +} + +/// The scorecard's metrics, in report order. +pub const METRICS: &[Metric] = &[ + Metric { + name: "rungs_per_hour", + unit: "rungs/h", + direction: Direction::Up, + abs_tol: 0.5, + rel_tol: 0.15, + read: |r| per_hour(f64::from(r.rungs.gained), r), + }, + Metric { + name: "places_per_hour", + unit: "places/h", + direction: Direction::Up, + abs_tol: 5.0, + rel_tol: 0.15, + read: |r| per_hour(f64::from(r.places_end.saturating_sub(r.places_start)), r), + }, + Metric { + name: "empty_pad_pct", + unit: "% of frames", + direction: Direction::Down, + abs_tol: 1.0, + rel_tol: 0.25, + read: |r| 100.0 * r.pad.empty_fraction, + }, + Metric { + name: "watchdog_suspected_pct", + unit: "% of probes", + direction: Direction::Down, + abs_tol: 5.0, + rel_tol: 0.25, + read: |r| pct(r.watchdog.suspected as f64, r.watchdog.probes as f64), + }, + Metric { + name: "ladder_events_per_hour", + unit: "traps/h", + direction: Direction::Down, + abs_tol: 0.5, + rel_tol: 0.25, + read: |r| per_hour(r.watchdog.ladder_events as f64, r), + }, + Metric { + name: "hunt_flagged_pct", + unit: "% of windows", + direction: Direction::Down, + abs_tol: 5.0, + rel_tol: 0.25, + read: |r| pct(r.hunt.flagged as f64, r.hunt.windows as f64), + }, + Metric { + name: "ratchet_rollbacks_per_hour", + unit: "rollbacks/h", + direction: Direction::Down, + abs_tol: 1.0, + rel_tol: 0.25, + read: |r| per_hour(f64::from(r.ratchet.rollbacks), r), + }, + Metric { + name: "blocked_macro_pct", + unit: "% of finishes", + direction: Direction::Down, + abs_tol: 2.0, + rel_tol: 0.25, + read: |r| { + let finishes = r.macros.done + r.macros.failed(); + pct(r.macros.failed() as f64, finishes as f64) + }, + }, + Metric { + name: "buy_ball_per_hour", + unit: "buys/h", + direction: Direction::Up, + abs_tol: 0.5, + rel_tol: 0.25, + read: |r| per_hour(r.funnel.buy_ball_done as f64, r), + }, + Metric { + name: "throws_per_hour", + unit: "throws/h", + direction: Direction::Up, + abs_tol: 0.5, + rel_tol: 0.25, + read: |r| per_hour(r.funnel.throw_ball_start as f64, r), + }, + Metric { + name: "catches_per_hour", + unit: "catches/h", + direction: Direction::Up, + abs_tol: 0.5, + rel_tol: 0.25, + read: |r| per_hour(r.funnel.catches as f64, r), + }, + Metric { + name: "battles_won_per_hour", + unit: "wins/h", + direction: Direction::Up, + abs_tol: 1.0, + rel_tol: 0.2, + read: |r| per_hour(r.battles.won as f64, r), + }, + Metric { + name: "battles_lost_per_hour", + unit: "losses/h", + direction: Direction::Down, + abs_tol: 0.5, + rel_tol: 0.25, + read: |r| per_hour(r.battles.lost as f64, r), + }, + Metric { + name: "whiteouts_per_hour", + unit: "whiteouts/h", + direction: Direction::Down, + abs_tol: 0.5, + rel_tol: 0.25, + read: |r| per_hour(r.whiteouts as f64, r), + }, + // Reported, never judged: healing more can follow losing more. + Metric { + name: "heals_per_hour", + unit: "heals/h", + direction: Direction::Info, + abs_tol: 0.0, + rel_tol: 0.0, + read: |r| per_hour(r.heals.heal_done as f64, r), + }, + Metric { + name: "macro_starts_per_minute", + unit: "starts/min", + direction: Direction::Info, + abs_tol: 0.0, + rel_tol: 0.0, + read: |r| if r.minutes <= 0.0 { 0.0 } else { r.macros.starts as f64 / r.minutes }, + }, +]; + +pub fn mean(values: &[f64]) -> f64 { + if values.is_empty() { 0.0 } else { values.iter().sum::() / values.len() as f64 } +} + +pub fn stdev(values: &[f64]) -> f64 { + if values.len() < 2 { + return 0.0; + } + let m = mean(values); + (values.iter().map(|v| (v - m).powi(2)).sum::() / (values.len() - 1) as f64).sqrt() +} + +/// One-sided sign-flip p-value for "the mean of `diffs` is greater than zero by more than chance": +/// the share of sign assignments whose mean is at least the observed one. Exact for up to 20 +/// differences, 20,000 fixed-seed draws beyond. +pub fn sign_flip_p(diffs: &[f64]) -> f64 { + let n = diffs.len(); + if n == 0 { + return 1.0; + } + let observed: f64 = diffs.iter().sum(); + let eps = 1e-9 * (1.0 + observed.abs()); + if n <= 20 { + let total = 1u64 << n; + let mut at_least = 0u64; + for mask in 0..total { + let sum: f64 = diffs + .iter() + .enumerate() + .map(|(i, d)| if mask >> i & 1 == 1 { -d } else { *d }) + .sum(); + if sum >= observed - eps { + at_least += 1; + } + } + return at_least as f64 / total as f64; + } + let draws = 20_000u64; + let mut state = 0x2545_f491_4f6c_dd1du64; + let mut at_least = 1u64; // the observed assignment is one of them + for _ in 0..draws { + let mut sum = 0.0; + let mut bits = 0u64; + for (i, d) in diffs.iter().enumerate() { + if i % 64 == 0 { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + bits = state; + } + sum += if bits >> (i % 64) & 1 == 1 { -d } else { *d }; + } + if sum >= observed - eps { + at_least += 1; + } + } + at_least as f64 / (draws + 1) as f64 +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Verdict { + Pass, + Better, + Fail, + Info, + /// No run of A pairs with a run of B. + None, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct MetricVerdict { + pub metric: String, + pub unit: String, + pub direction: Direction, + pub pairs: usize, + pub mean_a: f64, + pub mean_b: f64, + pub delta: f64, + /// The one-sided p of "B is worse" and of "B is better". + pub p_worse: f64, + pub p_better: f64, + /// The smallest change that counts, in the metric's unit. + pub tolerance: f64, + pub verdict: Verdict, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Comparison { + pub schema: String, + pub a: String, + pub b: String, + pub alpha: f64, + pub pairs: usize, + pub unpaired_a: usize, + pub unpaired_b: usize, + pub notes: Vec, + pub metrics: Vec, + /// Every metric that failed, in order. + pub failed: Vec, + pub pass: bool, +} + +fn key(run: &RunReport) -> (String, u32) { + (run.checkpoint.clone(), run.seed) +} + +/// Compares two suites. `alpha` is the one-sided significance level. +pub fn compare(a: &SuiteReport, b: &SuiteReport, alpha: f64) -> Comparison { + let by_key = |suite: &SuiteReport| -> BTreeMap<(String, u32), RunReport> { + suite.runs.iter().map(|run| (key(run), run.clone())).collect() + }; + let runs_a = by_key(a); + let runs_b = by_key(b); + let pairs: Vec<(&RunReport, &RunReport)> = + runs_a.iter().filter_map(|(k, ra)| runs_b.get(k).map(|rb| (ra, rb))).collect(); + let mut notes = Vec::new(); + if a.config.minutes != b.config.minutes { + notes.push(format!( + "the suites ran different lengths ({} and {} brain minutes): rates are comparable, counts are not", + a.config.minutes, b.config.minutes + )); + } + if a.runtime != b.runtime { + notes.push(format!("the suites ran on different runtimes ({} and {})", a.runtime, b.runtime)); + } + if a.config.probe_s != b.config.probe_s || a.config.window_s != b.config.window_s { + notes.push("the watchdog probes differ between the suites".to_owned()); + } + if pairs.len() < 8 { + notes.push(format!( + "only {} paired runs: the permutation test cannot reach alpha {alpha} with fewer than {} pairs", + pairs.len(), + (1.0 / alpha).log2().ceil() as usize + )); + } + let mut metrics = Vec::new(); + for metric in METRICS { + let va: Vec = pairs.iter().map(|(ra, _)| (metric.read)(ra)).collect(); + let vb: Vec = pairs.iter().map(|(_, rb)| (metric.read)(rb)).collect(); + let (mean_a, mean_b) = (mean(&va), mean(&vb)); + let delta = mean_b - mean_a; + let tolerance = metric.abs_tol.max(metric.rel_tol * mean_a.abs()); + // Signed so that positive is worse. + let sign = match metric.direction { + Direction::Up => -1.0, + Direction::Down | Direction::Info => 1.0, + }; + let worse: Vec = va.iter().zip(&vb).map(|(x, y)| sign * (y - x)).collect(); + let better: Vec = worse.iter().map(|d| -d).collect(); + let (p_worse, p_better) = (sign_flip_p(&worse), sign_flip_p(&better)); + let shortfall = sign * delta; + let verdict = if pairs.is_empty() { + Verdict::None + } else if metric.direction == Direction::Info { + Verdict::Info + } else if shortfall > tolerance && p_worse < alpha { + Verdict::Fail + } else if -shortfall > tolerance && p_better < alpha { + Verdict::Better + } else { + Verdict::Pass + }; + metrics.push(MetricVerdict { + metric: metric.name.to_owned(), + unit: metric.unit.to_owned(), + direction: metric.direction, + pairs: pairs.len(), + mean_a, + mean_b, + delta, + p_worse, + p_better, + tolerance, + verdict, + }); + } + let failed: Vec = metrics + .iter() + .filter(|m| m.verdict == Verdict::Fail) + .map(|m| m.metric.clone()) + .collect(); + Comparison { + schema: "fly-scorecard-compare-v1".to_owned(), + a: a.label.clone(), + b: b.label.clone(), + alpha, + pairs: pairs.len(), + unpaired_a: runs_a.len() - pairs.len(), + unpaired_b: runs_b.len() - pairs.len(), + notes, + pass: failed.is_empty() && !pairs.is_empty(), + failed, + metrics, + } +} + +impl Comparison { + /// The comparison as a markdown table. + pub fn markdown(&self) -> String { + let mut out = String::new(); + out.push_str(&format!( + "# Scorecard: {} vs {}: {}\n\n", + self.a, + self.b, + if self.pass { "PASS" } else { "FAIL" } + )); + out.push_str(&format!( + "{} paired runs (alpha {} one-sided, sign-flip test); {} only in {}, {} only in {}.\n\n", + self.pairs, self.alpha, self.unpaired_a, self.a, self.unpaired_b, self.b + )); + for note in &self.notes { + out.push_str(&format!("- note: {note}\n")); + } + if !self.notes.is_empty() { + out.push('\n'); + } + out.push_str(&format!( + "| metric | {} | {} | delta | tolerance | p worse | p better | verdict |\n", + self.a, self.b + )); + out.push_str("| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |\n"); + for m in &self.metrics { + let arrow = match m.direction { + Direction::Up => "up", + Direction::Down => "down", + Direction::Info => "info", + }; + out.push_str(&format!( + "| {} ({}, {}) | {:.2} | {:.2} | {:+.2} | {:.2} | {:.3} | {:.3} | {} |\n", + m.metric, + arrow, + m.unit, + m.mean_a, + m.mean_b, + m.delta, + m.tolerance, + m.p_worse, + m.p_better, + match m.verdict { + Verdict::Pass => "pass", + Verdict::Better => "better", + Verdict::Fail => "**FAIL**", + Verdict::Info => "info", + Verdict::None => "n/a", + } + )); + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::suite::{SuiteConfig, SuiteReport}; + + #[test] + fn the_exact_test_has_the_textbook_p() { + // Seven positive differences: only the all-positive assignment is as extreme. + assert!((sign_flip_p(&[1.0; 7]) - 1.0 / 128.0).abs() < 1e-12); + // All-negative: every assignment is at least as extreme as the observed. + assert!((sign_flip_p(&[-1.0; 7]) - 1.0).abs() < 1e-12); + // Nothing observed is no evidence. + assert_eq!(sign_flip_p(&[]), 1.0); + assert!((sign_flip_p(&[0.0; 5]) - 1.0).abs() < 1e-12); + // Mixed: three of four positive, the largest positive. + let p = sign_flip_p(&[3.0, 1.0, 1.0, -1.0]); + assert!(p > 0.0 && p < 0.5, "{p}"); + } + + #[test] + fn beyond_twenty_pairs_the_draws_are_fixed() { + let diffs: Vec = (0..30).map(|i| 1.0 + f64::from(i % 3)).collect(); + let p = sign_flip_p(&diffs); + assert_eq!(p, sign_flip_p(&diffs)); + assert!(p < 0.001, "{p}"); + let noise: Vec = (0..30).map(|i| if i % 2 == 0 { 1.0 } else { -1.0 }).collect(); + assert!(sign_flip_p(&noise) > 0.3); + } + + fn run(checkpoint: &str, seed: u32, mutate: impl FnOnce(&mut RunReport)) -> RunReport { + let mut r = RunReport { + checkpoint: checkpoint.to_owned(), + seed, + runtime: "session".into(), + mode: "macros".into(), + minutes: 12.0, + ..RunReport::default() + }; + r.macros.done = 100; + mutate(&mut r); + r + } + + fn suite(label: &str, runs: Vec) -> SuiteReport { + SuiteReport { + schema: crate::suite::SCHEMA.to_owned(), + label: label.to_owned(), + build: Default::default(), + runtime: "session".into(), + mode: "macros".into(), + config: SuiteConfig { minutes: 12.0, seeds: vec![1, 2, 3], ..SuiteConfig::default() }, + runs, + failed_runs: Vec::new(), + } + } + + fn many(label: &str, f: impl Fn(&str, u32, &mut RunReport)) -> SuiteReport { + let mut runs = Vec::new(); + for c in ["r08", "r09", "r10", "r11", "r12", "r13"] { + for s in 1..=3 { + runs.push(run(c, s, |r| f(c, s, r))); + } + } + suite(label, runs) + } + + #[test] + fn identical_suites_pass_with_nothing_better_or_worse() { + let a = many("a", |_, s, r| r.rungs.gained = s % 2); + let b = many("b", |_, s, r| r.rungs.gained = s % 2); + let c = compare(&a, &b, 0.05); + assert!(c.pass, "{:?}", c.failed); + assert!(c.metrics.iter().all(|m| matches!(m.verdict, Verdict::Pass | Verdict::Info))); + assert_eq!(c.pairs, 18); + } + + #[test] + fn a_consistent_drop_in_rungs_fails_and_a_single_bad_run_does_not() { + let a = many("a", |_, _, r| r.rungs.gained = 1); + let b = many("b", |_, _, r| r.rungs.gained = 0); + let c = compare(&a, &b, 0.05); + assert!(!c.pass); + assert_eq!(c.failed, vec!["rungs_per_hour".to_owned()]); + assert!(c.markdown().contains("**FAIL**")); + // One run of eighteen collapses: not significant, not a regression. + let b = many("b", |ck, s, r| r.rungs.gained = if ck == "r10" && s == 2 { 0 } else { 1 }); + assert!(compare(&a, &b, 0.05).pass); + } + + #[test] + fn a_rise_in_traps_fails_and_a_drop_is_better() { + let calm = many("a", |_, _, _| {}); + let trapped = many("b", |_, _, r| { + r.watchdog.ladder_events = 1; + r.watchdog.probes = 4; + r.watchdog.suspected = 3; + }); + let up = compare(&calm, &trapped, 0.05); + assert!(up.failed.contains(&"ladder_events_per_hour".to_owned()), "{:?}", up.failed); + assert!(up.failed.contains(&"watchdog_suspected_pct".to_owned())); + let down = compare(&trapped, &calm, 0.05); + assert!(down.pass); + let better: Vec<&str> = down + .metrics + .iter() + .filter(|m| m.verdict == Verdict::Better) + .map(|m| m.metric.as_str()) + .collect(); + assert!(better.contains(&"ladder_events_per_hour"), "{better:?}"); + } + + #[test] + fn a_change_inside_the_tolerance_is_noise_however_consistent() { + // 0.25 pp more empty pad on every run: significant, but under the 1 pp floor. + let a = many("a", |_, _, r| r.pad.empty_fraction = 0.10); + let b = many("b", |_, _, r| r.pad.empty_fraction = 0.1025); + let c = compare(&a, &b, 0.05); + let pad = c.metrics.iter().find(|m| m.metric == "empty_pad_pct").unwrap(); + assert_eq!(pad.verdict, Verdict::Pass, "{pad:?}"); + } + + #[test] + fn runs_pair_by_checkpoint_and_seed_and_unpaired_runs_are_reported() { + let a = many("a", |_, _, _| {}); + let mut b = many("b", |_, _, _| {}); + b.runs.retain(|r| r.checkpoint != "r13"); + let c = compare(&a, &b, 0.05); + assert_eq!((c.pairs, c.unpaired_a, c.unpaired_b), (15, 3, 0)); + let none = compare(&a, &suite("empty", Vec::new()), 0.05); + assert!(!none.pass); + assert!(none.metrics.iter().all(|m| m.verdict == Verdict::None)); + } + + #[test] + fn rates_are_per_brain_hour() { + let r = run("x", 1, |r| { + r.rungs.gained = 1; + r.whiteouts = 2; + }); + let get = |name: &str| (METRICS.iter().find(|m| m.name == name).unwrap().read)(&r); + assert!((get("rungs_per_hour") - 5.0).abs() < 1e-9); + assert!((get("whiteouts_per_hour") - 10.0).abs() < 1e-9); + let empty = RunReport::default(); + assert_eq!((METRICS[0].read)(&empty), 0.0); + } +} diff --git a/services/flysim/crates/fly-scorecard/src/lib.rs b/services/flysim/crates/fly-scorecard/src/lib.rs new file mode 100644 index 0000000..86de2f6 --- /dev/null +++ b/services/flysim/crates/fly-scorecard/src/lib.rs @@ -0,0 +1,16 @@ +//! The behavioural scorecard (B2): a repeatable multi-seed regression harness for good play. +//! +//! A fixed set of checkpoints, K seeds each, T brain minutes each, on the real connectome with the +//! macro layer, on the session runtime (default) or the legacy loop. Every run reduces to one +//! [`tally::RunReport`]; a suite is the set of runs ([`suite::SuiteReport`]); two suites compare +//! with a verdict per metric ([`compare::compare`]), by a test over the paired runs rather than +//! by one run. +//! +//! The harness measures and presses nothing. See `docs/scorecard.md`. + +pub mod compare; +pub mod obs; +pub mod runner; +pub mod suite; +pub mod tally; +pub mod watchdog; diff --git a/services/flysim/crates/fly-scorecard/src/main.rs b/services/flysim/crates/fly-scorecard/src/main.rs new file mode 100644 index 0000000..216068a --- /dev/null +++ b/services/flysim/crates/fly-scorecard/src/main.rs @@ -0,0 +1,368 @@ +//! `fly-scorecard`: run the behavioural scorecard, compare two releases, summarise a run. +//! +//! ```sh +//! export FLY_ROM=... # the cartridge, never copied anywhere +//! fly-scorecard list # the set, resolved, with each rung +//! fly-scorecard suite --label v0.7.5 --out card.json # the set x seeds x minutes +//! fly-scorecard compare old.json new.json # exit 1 when a metric regressed +//! fly-scorecard summary card.json # a one-screen markdown +//! fly-scorecard run-one --checkpoint X --seed 1 # one run, JSON on stdout +//! ``` +//! +//! The checkpoint set is `tools/scorecard/checkpoints.json`: each entry names the environment +//! variable that holds the checkpoint's path (the ROM tests' own, `rom-env.sh`). + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, anyhow, bail}; +use clap::{Parser, Subcommand}; +use flysim::snapshot::MacroMode; + +use fly_scorecard::compare::compare; +use fly_scorecard::runner::{Runtime, RunSpec, build_info, run_legacy, run_session}; +use fly_scorecard::suite::{ + CheckpointSet, ChildArgs, Job, SCHEMA, SuiteConfig, SuiteReport, note, run_jobs, +}; + +#[derive(Debug, Parser)] +#[command(name = "fly-scorecard", about = "The behavioural scorecard: multi-seed good-play regression.")] +struct Args { + #[command(subcommand)] + command: Cmd, +} + +#[derive(Debug, Subcommand)] +enum Cmd { + /// Resolve the checkpoint set and print each checkpoint's rung. + List { + #[arg(long, default_value = "tools/scorecard/checkpoints.json")] + set: PathBuf, + /// Extra checkpoints, `id=path`. + #[arg(long = "extra", value_name = "ID=PATH")] + extra: Vec, + }, + /// One run: a checkpoint, a seed. Prints the run's JSON on stdout. + RunOne { + #[arg(long)] + id: Option, + #[arg(long)] + checkpoint: PathBuf, + #[arg(long, default_value_t = 1)] + seed: u32, + #[arg(long, default_value_t = 12.0)] + minutes: f64, + #[arg(long, default_value = "session")] + runtime: String, + #[arg(long, default_value = "macros")] + mode: String, + #[arg(long, default_value_t = 5)] + threads: usize, + #[arg(long, default_value_t = 120.0)] + probe_s: f64, + #[arg(long, default_value_t = 600.0)] + window_s: f64, + #[arg(long)] + dataset: Option, + /// Write the JSON here instead of stdout (the emulator library prints on stdout). + #[arg(long)] + out: Option, + }, + /// The set times the seeds, `--jobs` at a time, as one JSON. + Suite { + #[arg(long, default_value = "tools/scorecard/checkpoints.json")] + set: PathBuf, + #[arg(long = "extra", value_name = "ID=PATH")] + extra: Vec, + /// Only these checkpoint ids (comma separated). + #[arg(long, value_delimiter = ',')] + only: Vec, + /// Seeds 1..=K. + #[arg(long, default_value_t = 3)] + seeds: u32, + #[arg(long, default_value_t = 12.0)] + minutes: f64, + #[arg(long, default_value = "session")] + runtime: String, + #[arg(long, default_value = "macros")] + mode: String, + /// Sweep threads per run. + #[arg(long, default_value_t = 5)] + threads: usize, + /// Runs at a time. + #[arg(long, default_value_t = 2)] + jobs: usize, + #[arg(long, default_value_t = 120.0)] + probe_s: f64, + #[arg(long, default_value_t = 600.0)] + window_s: f64, + /// Names the release or commit under test. + #[arg(long)] + label: String, + #[arg(long)] + out: PathBuf, + /// Also write the one-screen summary here. + #[arg(long)] + md: Option, + #[arg(long)] + dataset: Option, + /// Fail instead of running a smaller set when a checkpoint of the set is missing. + #[arg(long)] + strict: bool, + }, + /// Release A against release B. Exit 1 when a metric regressed. + Compare { + a: PathBuf, + b: PathBuf, + #[arg(long, default_value_t = 0.05)] + alpha: f64, + #[arg(long)] + json: Option, + #[arg(long)] + md: Option, + }, + /// A one-screen markdown of one suite. + Summary { + file: PathBuf, + #[arg(long, default_value = "tools/scorecard/checkpoints.json")] + set: PathBuf, + }, +} + +fn env_dataset(given: Option) -> PathBuf { + given + .or_else(|| std::env::var_os("FLY_MACRO_BRAIN").map(PathBuf::from)) + .or_else(|| std::env::var_os("FLY_DATASET").map(PathBuf::from)) + .unwrap_or_else(|| PathBuf::from("data/fafb-v783")) +} + +fn rom() -> Result { + std::env::var_os("FLY_ROM").map(PathBuf::from).ok_or_else(|| anyhow!("FLY_ROM is not set")) +} + +fn mode_of(text: &str) -> Result { + match text { + "raw" => Ok(MacroMode::Raw), + "macros" => Ok(MacroMode::Macros), + other => bail!("mode {other:?} is not raw or macros"), + } +} + +fn parse_extra(extra: &[String]) -> Result> { + extra + .iter() + .map(|item| { + let (id, path) = item.split_once('=').ok_or_else(|| anyhow!("--extra wants ID=PATH, got {item:?}"))?; + Ok((id.to_owned(), PathBuf::from(path))) + }) + .collect() +} + +/// The rung a checkpoint stands on, from its reward ledger. +fn rung_of(path: &Path) -> Result<(u32, &'static str, usize)> { + use flybrain_gb::adapter::GameAdapter; + let checkpoint = flysim::store::load(path)?; + let mut adapter = flybrain_gb::pokemon_red::PokemonRedReward::new(); + adapter.import_state(&checkpoint.runtime.reward).map_err(|e| anyhow!("{e}"))?; + let progress = adapter.progress(); + Ok((progress.rank, progress.rank_label, progress.unique_locations)) +} + +struct Resolved { + id: String, + path: PathBuf, + rung: Option, +} + +fn resolve(set_path: &Path, extra: &[String], only: &[String], strict: bool) -> Result> { + let set = CheckpointSet::load(set_path)?; + let (found, missing) = set.resolve(&|name| std::env::var(name).ok()); + if !missing.is_empty() { + eprintln!("scorecard: {} checkpoints of the set are missing: {}", missing.len(), missing.join(", ")); + if strict { + bail!("--strict: the set is not complete"); + } + } + let mut out: Vec = found + .into_iter() + .map(|(entry, path)| Resolved { id: entry.id, path, rung: Some(entry.rung) }) + .collect(); + for (id, path) in parse_extra(extra)? { + if !path.is_file() { + bail!("--extra {id}: {} is not a file", path.display()); + } + out.push(Resolved { id, path, rung: None }); + } + if !only.is_empty() { + out.retain(|r| only.contains(&r.id)); + } + if out.is_empty() { + bail!("no checkpoint to run"); + } + Ok(out) +} + +fn main() { + if let Err(error) = real_main() { + eprintln!("fly-scorecard: {error:#}"); + std::process::exit(2); + } +} + +fn real_main() -> Result<()> { + let args = Args::parse(); + match args.command { + Cmd::List { set, extra } => { + for r in resolve(&set, &extra, &[], false)? { + match rung_of(&r.path) { + Ok((rank, label, places)) => println!( + "{:<28} set rung {:>2} checkpoint rung {rank:>2} {label} ({places} places)", + r.id, + r.rung.map_or("-".to_owned(), |n| n.to_string()) + ), + Err(error) => println!("{:<28} unreadable: {error:#}", r.id), + } + } + Ok(()) + } + Cmd::RunOne { id, checkpoint, seed, minutes, runtime, mode, threads, probe_s, window_s, dataset, out } => { + let runtime = Runtime::parse(&runtime)?; + let id = id.unwrap_or_else(|| { + checkpoint.file_stem().map_or_else(|| "checkpoint".to_owned(), |s| s.to_string_lossy().into_owned()) + }); + let spec = RunSpec { + id, + checkpoint, + rom: rom()?, + dataset: env_dataset(dataset), + seed, + minutes, + threads, + mode: mode_of(&mode)?, + tally: RunSpec::tally_config(probe_s, window_s), + }; + let report = match runtime { + Runtime::Legacy => run_legacy(&spec)?, + Runtime::Session => tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build()? + .block_on(run_session(&spec))?, + }; + let text = serde_json::to_string(&report)? + "\n"; + match out { + Some(path) => std::fs::write(&path, text).with_context(|| format!("writing {}", path.display()))?, + None => print!("{text}"), + } + Ok(()) + } + Cmd::Suite { + set, extra, only, seeds, minutes, runtime, mode, threads, jobs, probe_s, window_s, label, out, md, + dataset, strict, + } => { + Runtime::parse(&runtime)?; + mode_of(&mode)?; + rom()?; + let resolved = resolve(&set, &extra, &only, strict)?; + let exe = std::env::current_exe().context("finding this executable")?; + let seed_list: Vec = (1..=seeds).collect(); + let mut queue = Vec::new(); + for r in &resolved { + for seed in &seed_list { + queue.push(Job { id: r.id.clone(), path: r.path.clone(), seed: *seed }); + } + } + let child = ChildArgs { + runtime: runtime.clone(), + mode: mode.clone(), + minutes, + threads, + probe_s, + window_s, + dataset: dataset.clone().or_else(|| Some(env_dataset(None))), + }; + let progress = out.with_extension("progress.log"); + let _ = std::fs::remove_file(&progress); + eprintln!( + "scorecard {label}: {} runs ({} checkpoints x {} seeds) of {minutes} brain min, {jobs} at a time, {threads} threads each", + queue.len(), + resolved.len(), + seed_list.len() + ); + let began = std::time::Instant::now(); + let outcomes = run_jobs(&exe, queue, &child, jobs, &|outcome| { + let line = match outcome { + Ok(run) => format!( + "{:>6.0}s done {} seed {}: rung {}->{} in {:.1} min, {:.0}s wall", + began.elapsed().as_secs_f64(), run.checkpoint, run.seed, run.rungs.start, run.rungs.end, + run.minutes, run.wall_seconds + ), + Err(failed) => format!( + "{:>6.0}s FAILED {} seed {}: {}", + began.elapsed().as_secs_f64(), failed.checkpoint, failed.seed, failed.error + ), + }; + eprintln!("{line}"); + note(&progress, &line); + }); + let mut runs = Vec::new(); + let mut failed_runs = Vec::new(); + for outcome in outcomes { + match outcome { + Ok(run) => runs.push(run), + Err(failed) => failed_runs.push(failed), + } + } + let suite = SuiteReport { + schema: SCHEMA.to_owned(), + label, + build: build_info(""), + runtime, + mode, + config: SuiteConfig { minutes, seeds: seed_list, threads, jobs, probe_s, window_s }, + runs, + failed_runs, + }; + let mut suite = suite; + suite.build.release = suite.label.clone(); + std::fs::write(&out, serde_json::to_string_pretty(&suite)? + "\n") + .with_context(|| format!("writing {}", out.display()))?; + let rungs: BTreeMap = + resolved.iter().filter_map(|r| r.rung.map(|n| (r.id.clone(), n))).collect(); + let markdown = suite.markdown(&rungs); + if let Some(md) = md { + std::fs::write(&md, &markdown).with_context(|| format!("writing {}", md.display()))?; + } + println!("{markdown}"); + eprintln!("scorecard: {:.0} s wall", began.elapsed().as_secs_f64()); + if suite.runs.is_empty() { + bail!("every run failed"); + } + Ok(()) + } + Cmd::Compare { a, b, alpha, json, md } => { + let (sa, sb) = (SuiteReport::load(&a)?, SuiteReport::load(&b)?); + let comparison = compare(&sa, &sb, alpha); + let markdown = comparison.markdown(); + if let Some(json) = json { + std::fs::write(&json, serde_json::to_string_pretty(&comparison)? + "\n")?; + } + if let Some(md) = md { + std::fs::write(&md, &markdown)?; + } + println!("{markdown}"); + if !comparison.pass { + std::process::exit(1); + } + Ok(()) + } + Cmd::Summary { file, set } => { + let suite = SuiteReport::load(&file)?; + let rungs: BTreeMap = CheckpointSet::load(&set) + .map(|s| s.checkpoints.into_iter().map(|e| (e.id, e.rung)).collect()) + .unwrap_or_default(); + println!("{}", suite.markdown(&rungs)); + Ok(()) + } + } +} diff --git a/services/flysim/crates/fly-scorecard/src/obs.rs b/services/flysim/crates/fly-scorecard/src/obs.rs new file mode 100644 index 0000000..1cc33f2 --- /dev/null +++ b/services/flysim/crates/fly-scorecard/src/obs.rs @@ -0,0 +1,146 @@ +//! What the scorecard sees of one frame, whichever runtime ran it. +//! +//! The legacy loop hands a harness a live emulator and the frame's events; the session runtime +//! hands it a task object holding the boundary's memory image. Both are reduced to the same +//! [`Frame`] here, so every metric is computed once ([`crate::tally`]) and a comparison between +//! the two runtimes cannot differ in what was measured. + +use flybrain_gb::MemoryReader; +use flybrain_gb::pokemon_red::state; +use flybrain_gb::pokemon_red::symbols::ram; + +/// One macro event: a start (`outcome` is `None`) or a finish. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MacroEv { + pub name: &'static str, + pub outcome: Option<&'static str>, +} + +/// A rollback the ratchet ran at this boundary. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Rolled { + /// The trigger was a game over, else a stall. + pub game_over: bool, +} + +/// Facts read off game memory on one frame. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Facts { + /// `wIsInBattle`: 0 none, 1 wild, 2 trainer, `$ff` the frame a battle is lost. + pub battle: u8, + /// Party members with a species (a half-written slot is not counted). + pub party: u8, + /// Of them, those with HP left. + pub alive: u8, + /// Poke Balls of every kind in the bag. + pub balls: u32, + pub money: u32, + /// Species owned (Pokedex bits). + pub owned: u32, + /// The map the player stands on, `0xff` when the adapter cannot place the player. + pub map: u32, +} + +impl Facts { + /// Every member of a non-empty party has fainted: the state a whiteout starts from. + pub fn all_fainted(&self) -> bool { + self.party > 0 && self.alive == 0 + } + + pub fn in_battle(&self) -> bool { + self.battle != 0 + } +} + +/// Reads [`Facts`] from any memory (a live emulator or a boundary image). +pub fn facts_of(memory: &mut dyn MemoryReader) -> Facts { + let battle = memory.read8(ram::wIsInBattle); + let party = state::party(memory); + let real: Vec<_> = party.mons.iter().filter(|mon| mon.species != 0).collect(); + let alive = real.iter().filter(|mon| mon.hp > 0).count(); + let balls: u32 = state::bag(memory) + .iter() + .filter(|item| (0x01..=0x04).contains(&item.id)) + .map(|item| u32::from(item.count)) + .sum(); + let money = state::money(memory); + let owned: u32 = (0..19u16).map(|i| memory.read8(ram::wPokedexOwned + i).count_ones()).sum(); + let map = state::player(memory).map_or(0xff, |player| u32::from(player.map)); + Facts { + battle, + party: real.len() as u8, + alive: alive as u8, + balls, + money, + owned, + map, + } +} + +/// One frame, as the scorecard takes it. +#[derive(Clone, Debug)] +pub struct Frame { + /// The brain clock of the frame, ms. + pub ms: f64, + /// The macro layer's events this frame: executed, abandoned and a rollback's, in order. + pub events: Vec, + /// Rewards paid this frame: the adapter's kind and value. + pub rewards: Vec<(&'static str, f64)>, + pub rank: u32, + /// Distinct places the adapter has observed (the exploration count). + pub places: u32, + /// `(map, x, y)` the adapter placed the player on, when it could. + pub location: Option<(u32, u32, u32)>, + /// The macro layer is on (macros mode). + pub macros_on: bool, + /// No macro runs and the scene dealt no button. + pub pad_empty: bool, + pub scene: &'static str, + pub rollback: Option, + pub facts: Facts, +} + +/// The idle frames a seed starts with. +/// +/// A checkpoint restores a deterministic brain, so two runs from it with different "seeds" would +/// be the same run. A seed therefore chooses how many frames the readout is ignored before the +/// measurement starts: the brain still ticks, the noise generator still advances, the game sees +/// no button, and from the first measured frame the brain is on a different point of its own +/// trajectory. Seed 0 is no idle at all (the run the trap hunt does from the same checkpoint). +/// Nothing presses for the fly and nothing changes what it chooses once the measurement starts. +pub fn idle_frames(seed: u32) -> u32 { + if seed == 0 { + return 0; + } + // splitmix64 of the seed, so consecutive seeds are unrelated; 1 to 30 seconds of idle. + let mut z = u64::from(seed).wrapping_add(0x9e37_79b9_7f4a_7c15); + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^= z >> 31; + 60 + (z % 1741) as u32 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn seed_zero_is_no_idle_and_seeds_differ() { + assert_eq!(idle_frames(0), 0); + let idles: Vec = (1..=8).map(idle_frames).collect(); + assert!(idles.iter().all(|n| (60..=1800).contains(n))); + let mut sorted = idles.clone(); + sorted.sort_unstable(); + sorted.dedup(); + assert_eq!(sorted.len(), idles.len(), "{idles:?}"); + assert_eq!(idle_frames(3), idle_frames(3)); + } + + #[test] + fn a_party_that_has_all_fainted() { + let down = Facts { party: 2, alive: 0, ..Facts::default() }; + assert!(down.all_fainted()); + assert!(!Facts { party: 2, alive: 1, ..Facts::default() }.all_fainted()); + assert!(!Facts::default().all_fainted(), "no party is not a whiteout"); + } +} diff --git a/services/flysim/crates/fly-scorecard/src/runner.rs b/services/flysim/crates/fly-scorecard/src/runner.rs new file mode 100644 index 0000000..917b407 --- /dev/null +++ b/services/flysim/crates/fly-scorecard/src/runner.rs @@ -0,0 +1,391 @@ +//! One run on a real brain: a checkpoint restored, the seed's idle frames, then the measured +//! brain minutes, on either runtime. +//! +//! Both runtimes drive the unchanged engine. The legacy runner is the stream's own frame +//! (`flysim::frame::LegacyFrame`, as the trap hunt runs it); the session runner is the session +//! composition the release cut over to (`fly_legacy_session::composition::LegacySession`, the +//! agent, the world and the task under one coordinator, in-process, unpaced). Each hands the same +//! [`Frame`] to the same [`Tally`]. +//! +//! Neither runner presses anything or changes what the brain chooses. The seed's idle frames +//! ignore the brain's readout for a while before the measurement starts ([`idle_frames`]); from +//! the first measured frame the readout is the brain's own. + +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Instant; + +use anyhow::{Context, Result, anyhow}; +use flybrain_core::agent::{AgentConfig, NeuralAgent}; +use flybrain_core::dataset::{BrainDataset, load_brain_dataset_from_dir}; +use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros; +use flybrain_core::lif::SweepPlan; +use flybrain_gb::adapter::GameAdapter; +use flybrain_gb::pokemon_red::PokemonRedReward; +use flybrain_gb::ratchet::Ratchet; +use flybrain_gb::{AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator}; +use flysim::config::Config; +use flysim::frame::{FrameObserver, LegacyFrame, Parts, RollbackTrigger}; +use flysim::macros::{MacroEvent, MacroLayer, macro_layer}; +use flysim::snapshot::MacroMode; + +use crate::obs::{Frame, MacroEv, Rolled, facts_of, idle_frames}; +use crate::tally::{RunReport, Tally, TallyConfig}; +use crate::watchdog::Rules; + +/// Which runtime ran it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Runtime { + Session, + Legacy, +} + +impl Runtime { + pub fn parse(text: &str) -> Result { + match text { + "session" => Ok(Self::Session), + "legacy" => Ok(Self::Legacy), + other => Err(anyhow!("runtime {other:?} is not session or legacy")), + } + } + + pub fn as_str(self) -> &'static str { + match self { + Self::Session => "session", + Self::Legacy => "legacy", + } + } +} + +/// Everything one run needs. +#[derive(Clone, Debug)] +pub struct RunSpec { + pub id: String, + pub checkpoint: PathBuf, + pub rom: PathBuf, + pub dataset: PathBuf, + pub seed: u32, + pub minutes: f64, + pub threads: usize, + pub mode: MacroMode, + pub tally: TallyConfig, +} + +impl RunSpec { + /// A tally configuration with the probe cadence and window the caller chose. + pub fn tally_config(probe_s: f64, window_s: f64) -> TallyConfig { + TallyConfig { + rules: Rules { window_ms: window_s * 1000.0, ..Rules::default() }, + probe_s, + ..TallyConfig::default() + } + } + + fn identity(&self, runtime: Runtime, idle: u32, wall: f64) -> RunReport { + RunReport { + checkpoint: self.id.clone(), + seed: self.seed, + runtime: runtime.as_str().to_owned(), + mode: self.mode.as_str().to_owned(), + idle_frames: idle, + wall_seconds: wall, + ..RunReport::default() + } + } +} + +fn conv(event: &MacroEvent) -> MacroEv { + MacroEv { name: event.name, outcome: event.outcome.map(|outcome| outcome.as_str()) } +} + +/// The measurement's start: it begins on the first frame after the idle frames, with the rung and +/// the exploration count the run stood on just before it. +struct Measure { + spec: RunSpec, + idle_left: u32, + prev: (u32, u32), + tally: Option, +} + +impl Measure { + fn new(spec: &RunSpec, rank: u32, places: u32) -> Self { + Self { spec: spec.clone(), idle_left: idle_frames(spec.seed), prev: (rank, places), tally: None } + } + + /// Takes one frame; true when the measured minutes are up. + fn take(&mut self, frame: Frame) -> bool { + let (rank, places) = (frame.rank, frame.places); + if self.idle_left > 0 { + self.idle_left -= 1; + self.prev = (rank, places); + return false; + } + let tally = self.tally.get_or_insert_with(|| { + Tally::new(self.spec.tally.clone(), frame.ms, self.prev.0, self.prev.1) + }); + tally.push(&frame); + tally.minutes() >= self.spec.minutes + } + + fn finish(self, runtime: Runtime, wall: f64) -> Result { + let idle = idle_frames(self.spec.seed); + let tally = self.tally.ok_or_else(|| anyhow!("no frame was measured"))?; + Ok(tally.finish(self.spec.identity(runtime, idle, wall))) + } +} + +// -- the legacy runtime ----------------------------------------------------------------------- + +/// The seed's idle frames, and the pad's state read just before the executor decides. +struct Idle { + left: u32, + pad_empty: bool, +} + +impl FrameObserver for Idle { + fn readout(&mut self, _ms: f64, _bound: Option<&[String]>, active: &mut Vec) { + if self.left > 0 { + self.left -= 1; + active.clear(); + } + } + + fn before_execute(&mut self, _frame: &LegacyFrame, parts: &mut Parts<'_>, _active: &[String]) { + self.pad_empty = parts + .macros + .as_deref() + .is_some_and(|layer| layer.running().is_none() && layer.feed_palette().is_empty()); + } +} + +fn load_dataset(spec: &RunSpec) -> Result> { + let data = load_brain_dataset_from_dir(&spec.dataset) + .map_err(|e| anyhow!("loading the connectome at {}: {e}", spec.dataset.display()))?; + Ok(Arc::new(data)) +} + +/// The stream's own frame, restored from the checkpoint as the stream restores it. +pub fn run_legacy(spec: &RunSpec) -> Result { + let began_wall = Instant::now(); + let rom = std::fs::read(&spec.rom).with_context(|| format!("reading {}", spec.rom.display()))?; + let checkpoint = flysim::store::load(&spec.checkpoint) + .with_context(|| format!("the checkpoint {}", spec.checkpoint.display()))?; + let data = load_dataset(spec)?; + + let mut emulator = Emulator::new(&rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES) + .map_err(|e| anyhow!("the cartridge: {e}"))?; + let mut adapter = PokemonRedReward::new(); + let channels = + if spec.mode.dealt() { flybrain_gb::macro_channels("pokemon-red") } else { Vec::new() }; + let preset = gameboy_decoder_config_with_macros(&channels); + let hold_ms = preset + .macros + .as_ref() + .or(preset.exclusive.as_ref()) + .map(|group| group.hold_ms) + .ok_or_else(|| anyhow!("the preset has no group"))?; + let mut ratchet = Ratchet::with_policy(adapter.recovery_policy()); + let mut agent = NeuralAgent::new(Arc::clone(&data), AgentConfig::with_decoder(preset)) + .map_err(|e| anyhow!("{e}"))?; + if spec.threads > 1 { + agent.set_sweep_plan(SweepPlan::with_threads(spec.threads).map_err(|e| anyhow!("{e}"))?); + } + let mut frame = LegacyFrame::new(); + frame + .restore( + &mut Parts { + agent: &mut agent, + emulator: &mut emulator, + adapter: &mut adapter, + ratchet: &mut ratchet, + macros: None, + }, + &checkpoint, + ) + .context("the checkpoint should restore")?; + let mut config = Config::default(); + config.loop_.game = "pokemon-red".to_string(); + config.macros.mode = spec.mode; + // As the service seeds it after a restore: the restored brain's own generator. + let mut macros: Option = + macro_layer(&config, hold_ms, agent.network.rng_state() as u32); + if let Some(layer) = macros.as_mut() { + let ledger = AdapterLedger(&adapter); + let _ = layer.observe(&mut emulator, &ledger, agent.network.ms); + } + + let start = adapter.progress(); + let mut measure = Measure::new(spec, start.rank, start.unique_locations as u32); + let mut observer = Idle { left: measure.idle_left, pad_empty: false }; + loop { + let mut parts = Parts { + agent: &mut agent, + emulator: &mut emulator, + adapter: &mut adapter, + ratchet: &mut ratchet, + macros: macros.as_mut(), + }; + let transition = frame.transition(&mut parts, &mut observer).context("a frame")?; + let boundary = frame + .boundary(&mut parts, &transition.evaluated.progress, transition.ms) + .context("the boundary")?; + let mut events: Vec = transition.executed.events.iter().map(conv).collect(); + events.extend(transition.evaluated.abandoned.iter().map(conv)); + let rolled = boundary.rollback.as_ref().map(|rollback| { + events.extend(rollback.events.iter().map(conv)); + Rolled { game_over: rollback.trigger == RollbackTrigger::GameOver } + }); + let progress = &transition.evaluated.progress; + let obs = Frame { + ms: transition.ms, + events, + rewards: transition.evaluated.rewards.iter().map(|r| (r.kind, r.value)).collect(), + rank: progress.rank, + places: progress.unique_locations as u32, + location: parts.adapter.location(), + macros_on: parts.macros.is_some(), + pad_empty: observer.pad_empty, + scene: parts.macros.as_deref().map_or("raw", MacroLayer::scene_name), + rollback: rolled, + facts: facts_of(parts.emulator), + }; + if measure.take(obs) { + break; + } + } + measure.finish(Runtime::Legacy, began_wall.elapsed().as_secs_f64()) +} + +// -- the session runtime ---------------------------------------------------------------------- + +/// The seed's idle frames on the session's executor: the same readout replacement the legacy +/// frame's observer makes. +struct IdleDriver { + left: u32, +} + +impl fly_legacy_session::driver::DecisionDriver for IdleDriver { + fn readout(&mut self, _ms: f64, _bound: &[String], active: &mut Vec) { + if self.left > 0 { + self.left -= 1; + active.clear(); + } + } +} + +/// The session composition the release runs, in-process and unpaced, from the checkpoint. +pub async fn run_session(spec: &RunSpec) -> Result { + use fly_legacy_session::composition::{LegacyConfig, LegacySession}; + use fly_session::ExecutionMode; + use fly_session::legacy_agent::LegacyProfileKind; + use fly_session::types::id; + + let began_wall = Instant::now(); + let checkpoint = flysim::store::load(&spec.checkpoint) + .with_context(|| format!("the checkpoint {}", spec.checkpoint.display()))?; + let root = tempfile::tempdir().context("a scratch directory")?; + let mut session = LegacySession::start( + root.path(), + LegacyConfig { + mode: ExecutionMode::InProcess, + rom_path: spec.rom.clone(), + dataset_dir: spec.dataset.clone(), + profile: LegacyProfileKind::Production, + macro_mode: spec.mode, + agent_id: id("fly"), + agent_threads: spec.threads.max(1), + record: false, + }, + ) + .await + .map_err(|e| anyhow!("{e}"))?; + session.bootstrap().await.map_err(|e| anyhow!("{e}"))?; + session + .import_checkpoint(&checkpoint, &id("e2")) + .await + .map_err(|e| anyhow!("importing the checkpoint: {e}"))?; + // A measurement runs as fast as the brain allows. + session.coordinator.disable_pacing(); + let task = session.task.clone(); + let (rank, places) = task.inspect(|adapter, _, _| { + let progress = adapter.progress(); + (progress.rank, progress.unique_locations as u32) + }); + let mut measure = Measure::new(spec, rank, places); + task.set_driver(Box::new(IdleDriver { left: measure.idle_left })); + + let outcome = async { + loop { + session.step().await.map_err(|e| anyhow!("{e}"))?; + let feed = task.take_feed(); + let ms = task.brain_ms(); + let mut events: Vec = feed.executed.iter().map(conv).collect(); + events.extend(feed.abandoned.iter().map(conv)); + let rolled = feed.rollback.as_ref().map(|(game_over, rollback_events)| { + events.extend(rollback_events.iter().map(conv)); + Rolled { game_over: *game_over } + }); + let (rank, places, location, macros_on, pad_empty, scene) = + task.inspect(|adapter, _, macros| { + let progress = adapter.progress(); + ( + progress.rank, + progress.unique_locations as u32, + adapter.location(), + macros.is_some(), + macros.is_some_and(|l| l.running().is_none() && l.feed_palette().is_empty()), + macros.map_or("raw", MacroLayer::scene_name), + ) + }); + let facts = task + .with_reader(|memory| facts_of(memory)) + .ok_or_else(|| anyhow!("the task has no boundary image"))?; + let obs = Frame { + ms, + events, + rewards: feed.rewards.iter().map(|r| (r.kind, r.value)).collect(), + rank, + places, + location, + macros_on, + pad_empty, + scene, + rollback: rolled, + facts, + }; + if measure.take(obs) { + break; + } + } + anyhow::Ok(()) + } + .await; + session.stop().await; + outcome?; + measure.finish(Runtime::Session, began_wall.elapsed().as_secs_f64()) +} + +/// The adapter and the compatibility digest of this build, for the report. +pub fn build_info(release: &str) -> crate::suite::BuildInfo { + use fly_legacy_session::composition::{LegacyConfig, compatibility_of}; + use fly_session::ExecutionMode; + use fly_session::legacy_agent::LegacyProfileKind; + use fly_session::types::id; + let adapter = GameAdapter::id(&PokemonRedReward::new()).to_owned(); + let compat = compatibility_of(&LegacyConfig { + mode: ExecutionMode::InProcess, + rom_path: PathBuf::new(), + dataset_dir: PathBuf::new(), + profile: LegacyProfileKind::Production, + macro_mode: MacroMode::Macros, + agent_id: id("fly"), + agent_threads: 1, + record: false, + }); + let digest = flybrain_core::dataset::sha256_hex(compat.as_bytes()); + crate::suite::BuildInfo { + release: release.to_owned(), + adapter, + compatibility_sha: digest.chars().take(12).collect(), + } +} diff --git a/services/flysim/crates/fly-scorecard/src/suite.rs b/services/flysim/crates/fly-scorecard/src/suite.rs new file mode 100644 index 0000000..4f779db --- /dev/null +++ b/services/flysim/crates/fly-scorecard/src/suite.rs @@ -0,0 +1,429 @@ +//! A suite: the checkpoint set times the seeds, run as child processes, aggregated. +//! +//! One run is one process (`fly-scorecard run-one`), so two runs never share a thread pool, a +//! tokio runtime or a brain. The suite starts `jobs` children at a time and collects the JSON each +//! prints. A child that fails is recorded as a failed run and never silently dropped: a suite with +//! failed runs says so in its summary and `compare` pairs only what finished. + +use std::collections::BTreeMap; +use std::io::Write as _; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::{Arc, Mutex}; + +use anyhow::{Context, Result, bail}; +use serde::{Deserialize, Serialize}; + +use crate::compare::{METRICS, mean, stdev}; +use crate::tally::RunReport; + +pub const SCHEMA: &str = "fly-scorecard-v1"; +pub const SET_SCHEMA: &str = "fly-scorecard-set-v1"; + +/// One checkpoint of the fixed set. Public files name the environment variable that holds the +/// path (the ROM tests' own, `rom-env.sh`), never a path. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct SetEntry { + pub id: String, + /// The rung the checkpoint is at, for the report's order and the by-rung table. + pub rung: u32, + pub env: String, + #[serde(default)] + pub note: String, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct CheckpointSet { + pub schema: String, + pub checkpoints: Vec, +} + +impl CheckpointSet { + pub fn load(path: &Path) -> Result { + let text = std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?; + let set: CheckpointSet = serde_json::from_str(&text).context("the checkpoint set")?; + if set.schema != SET_SCHEMA { + bail!("{}: schema {:?}, expected {SET_SCHEMA}", path.display(), set.schema); + } + let mut seen = std::collections::BTreeSet::new(); + for entry in &set.checkpoints { + if !seen.insert(entry.id.clone()) { + bail!("{}: checkpoint id {:?} twice", path.display(), entry.id); + } + } + Ok(set) + } + + /// The entries whose checkpoint file exists in this environment, with their paths, and the + /// ids that do not (reported, never skipped silently). + pub fn resolve(&self, env: &dyn Fn(&str) -> Option) -> (Vec<(SetEntry, PathBuf)>, Vec) { + let mut found = Vec::new(); + let mut missing = Vec::new(); + for entry in &self.checkpoints { + match env(&entry.env).map(PathBuf::from).filter(|path| path.is_file()) { + Some(path) => found.push((entry.clone(), path)), + None => missing.push(format!("{} (${})", entry.id, entry.env)), + } + } + (found, missing) + } +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct SuiteConfig { + /// Brain minutes measured per run. + pub minutes: f64, + pub seeds: Vec, + pub threads: usize, + pub jobs: usize, + pub probe_s: f64, + pub window_s: f64, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct BuildInfo { + /// The release or commit under test, as the caller names it. + pub release: String, + pub adapter: String, + /// The compatibility string's SHA-256 prefix (the string itself names no private value, but + /// the digest is enough to tell two builds' checkpoints apart). + pub compatibility_sha: String, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct FailedRun { + pub checkpoint: String, + pub seed: u32, + pub error: String, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct SuiteReport { + pub schema: String, + pub label: String, + pub build: BuildInfo, + pub runtime: String, + pub mode: String, + pub config: SuiteConfig, + pub runs: Vec, + pub failed_runs: Vec, +} + +impl SuiteReport { + pub fn load(path: &Path) -> Result { + let text = std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?; + let suite: SuiteReport = serde_json::from_str(&text).with_context(|| format!("{} is not a scorecard", path.display()))?; + if suite.schema != SCHEMA { + bail!("{}: schema {:?}, expected {SCHEMA}", path.display(), suite.schema); + } + Ok(suite) + } + + pub fn brain_hours(&self) -> f64 { + self.runs.iter().map(|run| run.minutes).sum::() / 60.0 + } + + /// The headline: totals over every run, as rates per brain hour where that is the unit. + pub fn headline(&self) -> Headline { + let hours = self.brain_hours(); + let sum = |f: &dyn Fn(&RunReport) -> f64| self.runs.iter().map(f).sum::(); + let per_hour = |x: f64| if hours > 0.0 { x / hours } else { 0.0 }; + let probes = sum(&|r| r.watchdog.probes as f64); + let windows = sum(&|r| r.hunt.windows as f64); + let frames = sum(&|r| r.frames as f64); + let finishes = sum(&|r| (r.macros.done + r.macros.failed()) as f64); + Headline { + runs: self.runs.len(), + brain_hours: hours, + rungs_per_hour: per_hour(sum(&|r| f64::from(r.rungs.gained))), + runs_with_a_climb: self.runs.iter().filter(|r| r.rungs.gained > 0).count(), + empty_pad_pct: if frames > 0.0 { 100.0 * sum(&|r| r.pad.empty_frames as f64) / frames } else { 0.0 }, + suspected_probe_pct: if probes > 0.0 { 100.0 * sum(&|r| r.watchdog.suspected as f64) / probes } else { 0.0 }, + ladder_events: self.runs.iter().map(|r| r.watchdog.ladder_events).sum(), + runs_with_a_ladder_event: self.runs.iter().filter(|r| r.watchdog.ladder_events > 0).count(), + hunt_flagged_pct: if windows > 0.0 { 100.0 * sum(&|r| r.hunt.flagged as f64) / windows } else { 0.0 }, + blocked_macro_pct: if finishes > 0.0 { 100.0 * sum(&|r| r.macros.failed() as f64) / finishes } else { 0.0 }, + buy_ball_done: self.runs.iter().map(|r| r.funnel.buy_ball_done).sum(), + throws: self.runs.iter().map(|r| r.funnel.throw_ball_start).sum(), + catches: self.runs.iter().map(|r| r.funnel.catches).sum(), + heals: self.runs.iter().map(|r| r.heals.heal_done).sum(), + whiteouts: self.runs.iter().map(|r| r.whiteouts).sum(), + battles_won: self.runs.iter().map(|r| r.battles.won).sum(), + battles_lost: self.runs.iter().map(|r| r.battles.lost).sum(), + ratchet_rollbacks: self.runs.iter().map(|r| u64::from(r.ratchet.rollbacks)).sum(), + } + } + + /// A one-screen summary: the headline, then a row per checkpoint with its seeds' spread. + pub fn markdown(&self, rungs: &BTreeMap) -> String { + let h = self.headline(); + let mut out = String::new(); + out.push_str(&format!( + "# Scorecard {}: {} runtime, {}\n\n", + self.label, self.runtime, self.mode + )); + out.push_str(&format!( + "{} runs, {:.2} brain hours ({} brain min each, seeds {:?}), adapter `{}`, compatibility `{}`.\n\n", + h.runs, + h.brain_hours, + self.config.minutes, + self.config.seeds, + self.build.adapter, + self.build.compatibility_sha + )); + if !self.failed_runs.is_empty() { + out.push_str(&format!("**{} runs failed:**\n", self.failed_runs.len())); + for failed in &self.failed_runs { + out.push_str(&format!("- {} seed {}: {}\n", failed.checkpoint, failed.seed, failed.error)); + } + out.push('\n'); + } + out.push_str("| headline | value |\n| --- | ---: |\n"); + let rows: Vec<(&str, String)> = vec![ + ("rungs per brain hour", format!("{:.2} ({} of {} runs climbed)", h.rungs_per_hour, h.runs_with_a_climb, h.runs)), + ("empty-pad time", format!("{:.2}% of frames", h.empty_pad_pct)), + ("watchdog probes suspected", format!("{:.1}%", h.suspected_probe_pct)), + ("ladder-worthy traps", format!("{} (in {} runs)", h.ladder_events, h.runs_with_a_ladder_event)), + ("trap-hunt windows flagged", format!("{:.1}%", h.hunt_flagged_pct)), + ("blocked macro finishes", format!("{:.1}%", h.blocked_macro_pct)), + ("buy ball / throw / catch", format!("{} / {} / {}", h.buy_ball_done, h.throws, h.catches)), + ("heals / whiteouts", format!("{} / {}", h.heals, h.whiteouts)), + ("battles won / lost", format!("{} / {}", h.battles_won, h.battles_lost)), + ("ratchet rollbacks", format!("{}", h.ratchet_rollbacks)), + ]; + for (name, value) in rows { + out.push_str(&format!("| {name} | {value} |\n")); + } + out.push_str("\n| checkpoint | rung | seeds | rungs/h | empty pad % | suspected % | traps | buy/throw/catch | won/lost | whiteouts |\n"); + out.push_str("| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- | --- | ---: |\n"); + let mut by: BTreeMap<&str, Vec<&RunReport>> = BTreeMap::new(); + for run in &self.runs { + by.entry(run.checkpoint.as_str()).or_default().push(run); + } + let mut order: Vec<(&str, &Vec<&RunReport>)> = by.iter().map(|(k, v)| (*k, v)).collect(); + order.sort_by_key(|(id, runs)| (rungs.get(*id).copied().unwrap_or(runs[0].rungs.start), *id)); + for (id, runs) in order { + let rate = |name: &str| -> Vec { + let metric = METRICS.iter().find(|m| m.name == name).expect("a metric"); + runs.iter().map(|r| (metric.read)(r)).collect() + }; + let rungs_h = rate("rungs_per_hour"); + let pad = rate("empty_pad_pct"); + let susp = rate("watchdog_suspected_pct"); + let sum = |f: &dyn Fn(&RunReport) -> u64| runs.iter().map(|r| f(r)).sum::(); + out.push_str(&format!( + "| {id} | {} | {} | {:.1} ± {:.1} | {:.1} | {:.0} | {} | {}/{}/{} | {}/{} | {} |\n", + rungs.get(id).copied().unwrap_or(runs[0].rungs.start), + runs.len(), + mean(&rungs_h), + stdev(&rungs_h), + mean(&pad), + mean(&susp), + sum(&|r| r.watchdog.ladder_events as u64), + sum(&|r| r.funnel.buy_ball_done), + sum(&|r| r.funnel.throw_ball_start), + sum(&|r| r.funnel.catches), + sum(&|r| r.battles.won), + sum(&|r| r.battles.lost), + sum(&|r| r.whiteouts), + )); + } + out + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Headline { + pub runs: usize, + pub brain_hours: f64, + pub rungs_per_hour: f64, + pub runs_with_a_climb: usize, + pub empty_pad_pct: f64, + pub suspected_probe_pct: f64, + pub ladder_events: usize, + pub runs_with_a_ladder_event: usize, + pub hunt_flagged_pct: f64, + pub blocked_macro_pct: f64, + pub buy_ball_done: u64, + pub throws: u64, + pub catches: u64, + pub heals: u64, + pub whiteouts: u64, + pub battles_won: u64, + pub battles_lost: u64, + pub ratchet_rollbacks: u64, +} + +/// One run to do: a checkpoint of the set, a seed. +#[derive(Clone, Debug)] +pub struct Job { + pub id: String, + pub path: PathBuf, + pub seed: u32, +} + +/// What every child shares. +#[derive(Clone, Debug)] +pub struct ChildArgs { + pub runtime: String, + pub mode: String, + pub minutes: f64, + pub threads: usize, + pub probe_s: f64, + pub window_s: f64, + pub dataset: Option, +} + +/// Runs the jobs `jobs` at a time as children of this executable, calling `done` as each one +/// finishes (so a caller can write partial results). Returns the finished runs and the failures, +/// in job order. +pub fn run_jobs( + exe: &Path, + jobs: Vec, + args: &ChildArgs, + parallel: usize, + done: &(dyn Fn(&Result) + Sync), +) -> Vec> { + let queue = Arc::new(Mutex::new(jobs.into_iter().enumerate().collect::>())); + let results = Arc::new(Mutex::new(Vec::new())); + std::thread::scope(|scope| { + for _ in 0..parallel.max(1) { + let queue = Arc::clone(&queue); + let results = Arc::clone(&results); + scope.spawn(move || { + loop { + let next = queue.lock().expect("queue").pop_front(); + let Some((index, job)) = next else { break }; + let outcome = run_child(exe, &job, args); + done(&outcome); + results.lock().expect("results").push((index, outcome)); + } + }); + } + }); + let mut results = Arc::try_unwrap(results).expect("all workers joined").into_inner().expect("results"); + results.sort_by_key(|(index, _)| *index); + results.into_iter().map(|(_, outcome)| outcome).collect() +} + +fn run_child(exe: &Path, job: &Job, args: &ChildArgs) -> Result { + let fail = |error: String| FailedRun { checkpoint: job.id.clone(), seed: job.seed, error }; + let mut command = Command::new(exe); + command + .arg("run-one") + .arg("--id") + .arg(&job.id) + .arg("--checkpoint") + .arg(&job.path) + .arg("--seed") + .arg(job.seed.to_string()) + .arg("--runtime") + .arg(&args.runtime) + .arg("--mode") + .arg(&args.mode) + .arg("--minutes") + .arg(args.minutes.to_string()) + .arg("--threads") + .arg(args.threads.to_string()) + .arg("--probe-s") + .arg(args.probe_s.to_string()) + .arg("--window-s") + .arg(args.window_s.to_string()); + if let Some(dataset) = &args.dataset { + command.arg("--dataset").arg(dataset); + } + // The report travels in a file: the emulator library prints the cartridge's header on stdout. + let report = tempfile::NamedTempFile::new().map_err(|e| fail(format!("a scratch file: {e}")))?; + command.arg("--out").arg(report.path()); + let status = command + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::inherit()) + .status() + .map_err(|e| fail(format!("starting the child: {e}")))?; + if !status.success() { + return Err(fail(format!("the child exited with {status}"))); + } + let text = std::fs::read(report.path()).map_err(|e| fail(format!("the child's report: {e}")))?; + serde_json::from_slice::(&text).map_err(|e| fail(format!("the child's report: {e}"))) +} + +/// Appends a line to a log, ignoring a failure to: progress is a courtesy. +pub fn note(path: &Path, line: &str) { + if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) { + let _ = writeln!(file, "{line}"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_set_is_resolved_from_the_environment_and_names_what_is_missing() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("a.checkpoint"); + std::fs::write(&file, b"x").unwrap(); + let set = CheckpointSet { + schema: SET_SCHEMA.to_owned(), + checkpoints: vec![ + SetEntry { id: "a".into(), rung: 8, env: "FLY_A".into(), note: String::new() }, + SetEntry { id: "b".into(), rung: 9, env: "FLY_B".into(), note: String::new() }, + SetEntry { id: "c".into(), rung: 9, env: "FLY_C".into(), note: String::new() }, + ], + }; + let env = |name: &str| match name { + "FLY_A" => Some(file.display().to_string()), + "FLY_C" => Some("/nonexistent/c.checkpoint".to_owned()), + _ => None, + }; + let (found, missing) = set.resolve(&env); + assert_eq!(found.len(), 1); + assert_eq!(found[0].0.id, "a"); + assert_eq!(missing, vec!["b ($FLY_B)".to_owned(), "c ($FLY_C)".to_owned()]); + } + + #[test] + fn the_shipped_set_parses_and_has_unique_ids() { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../../tools/scorecard/checkpoints.json"); + let set = CheckpointSet::load(&path).expect("the shipped set"); + assert!(set.checkpoints.len() >= 8); + assert!(set.checkpoints.iter().all(|e| e.env.starts_with("FLY_") && e.env.ends_with("_CHECKPOINT"))); + assert!(set.checkpoints.iter().all(|e| (8..=15).contains(&e.rung))); + } + + #[test] + fn a_suite_round_trips_and_summarises() { + let mut run = RunReport { + checkpoint: "r08".into(), + seed: 1, + runtime: "session".into(), + mode: "macros".into(), + minutes: 12.0, + frames: 1000, + ..RunReport::default() + }; + run.rungs.gained = 1; + run.watchdog.probes = 4; + run.macros.done = 9; + run.macros.blocked = 1; + let suite = SuiteReport { + schema: SCHEMA.to_owned(), + label: "t".into(), + build: BuildInfo::default(), + runtime: "session".into(), + mode: "macros".into(), + config: SuiteConfig { minutes: 12.0, seeds: vec![1], ..SuiteConfig::default() }, + runs: vec![run], + failed_runs: vec![FailedRun { checkpoint: "r09".into(), seed: 1, error: "boom".into() }], + }; + let text = serde_json::to_string(&suite).unwrap(); + let back: SuiteReport = serde_json::from_str(&text).unwrap(); + assert_eq!(back, suite); + let h = back.headline(); + assert!((h.rungs_per_hour - 5.0).abs() < 1e-9); + assert!((h.blocked_macro_pct - 10.0).abs() < 1e-9); + let md = back.markdown(&BTreeMap::new()); + assert!(md.contains("r08") && md.contains("1 runs failed") && md.contains("boom")); + } +} diff --git a/services/flysim/crates/fly-scorecard/src/tally.rs b/services/flysim/crates/fly-scorecard/src/tally.rs new file mode 100644 index 0000000..82e6da9 --- /dev/null +++ b/services/flysim/crates/fly-scorecard/src/tally.rs @@ -0,0 +1,940 @@ +//! One run's frames in, one [`RunReport`] out. +//! +//! Everything the scorecard measures about play is computed here from [`Frame`]s, with no +//! emulator, brain or runtime in sight, so every definition is unit-tested on synthetic frames. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde::{Deserialize, Serialize}; + +use crate::obs::{Facts, Frame}; +use crate::watchdog::{Ev, Probe, Rules, Watchdog}; + +/// One Game Boy frame of game time, ms (`70,224` cycles at `4,194,304` Hz). +pub const FRAME_MS: f64 = 1000.0 * 70_224.0 / 4_194_304.0; +const MINUTE_MS: f64 = 60_000.0; + +/// The trap hunt's window rules (`examples/trap_hunt.rs` in flysim), kept as it has them: two +/// brain minutes, stepped by fifteen seconds, fewer than four tiles or one macro sequence +/// repeated more than ten times (any period up to eight). +pub const HUNT_WINDOW_MS: f64 = 2.0 * MINUTE_MS; +pub const HUNT_STEP_MS: f64 = 15_000.0; +pub const HUNT_MIN_TILES: usize = 4; +pub const HUNT_MAX_REPEATS: usize = 10; +pub const HUNT_MAX_PERIOD: usize = 8; + +/// How a run is measured. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct TallyConfig { + pub rules: Rules, + /// Brain seconds between watchdog probes. + pub probe_s: f64, + /// Brain seconds before the first probe (a window needs some life in it). + pub first_probe_s: f64, +} + +impl Default for TallyConfig { + fn default() -> Self { + Self { rules: Rules::default(), probe_s: 120.0, first_probe_s: 300.0 } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct RungReport { + pub start: u32, + pub end: u32, + pub gained: u32, + /// `[rung, brain minute]` for every climb. + pub climbs: Vec<(u32, f64)>, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct PadReport { + /// Frames with the macro layer on, nothing running and no button dealt. + pub empty_frames: u64, + pub empty_seconds: f64, + pub empty_fraction: f64, + pub longest_empty_seconds: f64, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct WatchdogReport { + pub probes: usize, + pub suspected: usize, + /// Probes that were suspected with the one before also suspected (the loop recovery's + /// "confirmed": two fresh suspected reports in a row). + pub confirmed: usize, + /// Runs of two or more suspected probes: each is one trap the recovery ladder would act on. + pub ladder_events: usize, + pub reasons: BTreeMap, + pub flagged: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct HuntWindow { + pub at_min: f64, + pub tiles: usize, + pub macros: usize, + pub cycle: Option<(String, usize)>, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct HuntReport { + pub windows: usize, + pub flagged: usize, + /// The first twenty flagged windows. + pub first_flagged: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct RatchetReport { + pub rollbacks: u32, + pub game_over: u32, + pub stall: u32, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct MacroCounts { + pub start: u64, + pub done: u64, + pub blocked: u64, + pub timeout: u64, + pub refused: u64, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct MacroReport { + pub starts: u64, + pub done: u64, + pub blocked: u64, + pub timeout: u64, + pub refused: u64, + pub by_macro: BTreeMap, +} + +impl MacroReport { + /// Finishes that were not `done`, which is what "blocked macro counts" asks for. + pub fn failed(&self) -> u64 { + self.blocked + self.timeout + self.refused + } +} + +/// GO SHOP, BUY BALL, THROW BALL, catch, and the bag around them. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct FunnelReport { + pub go_shop_start: u64, + pub go_shop_done: u64, + pub buy_ball_start: u64, + pub buy_ball_done: u64, + pub throw_ball_start: u64, + pub throw_ball_done: u64, + /// `catch` rewards: a wild Pokemon kept. + pub catches: u64, + /// New species owned (Pokedex bits that went up). + pub species_gained: u64, + pub balls_gained: u64, + pub balls_spent: u64, + /// How far down GO SHOP done, BUY BALL done, THROW BALL start, catch the run got, in order of + /// first occurrence (0 to 4). + pub depth: u32, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct HealReport { + pub go_heal_start: u64, + pub go_heal_done: u64, + pub heal_start: u64, + /// The nurse's `HEAL` finished: a party healed. + pub heal_done: u64, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct BattleReport { + pub started: u64, + pub ended: u64, + pub wild: u64, + pub trainer: u64, + /// Ended with a battle or trainer payout. + pub won: u64, + /// Ended with the whole party fainted. + pub lost: u64, + /// A wild Pokemon kept. + pub caught: u64, + /// Ended otherwise (run away, a ball thrown away from the kept Pokemon, ...). + pub other: u64, + pub longest_frames: u64, + pub still_running: bool, + pub macros_in_longest: u64, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct RewardTotals { + pub n: u64, + pub total: f64, +} + +/// One run: a checkpoint, a seed, a runtime, some brain minutes. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct RunReport { + pub checkpoint: String, + pub seed: u32, + pub runtime: String, + pub mode: String, + /// Brain minutes measured (after the seed's idle frames). + pub minutes: f64, + pub frames: u64, + pub idle_frames: u32, + pub wall_seconds: f64, + pub rungs: RungReport, + pub places_start: u32, + pub places_end: u32, + pub pad: PadReport, + pub watchdog: WatchdogReport, + pub hunt: HuntReport, + pub ratchet: RatchetReport, + pub macros: MacroReport, + pub funnel: FunnelReport, + pub heals: HealReport, + pub whiteouts: u64, + pub battles: BattleReport, + pub rewards: BTreeMap, + pub scenes: BTreeMap, + pub ended_map: u32, +} + +/// The battle in progress. +#[derive(Clone, Debug, Default)] +struct Battle { + frames: u64, + macros: u64, + won: bool, + caught: bool, + fainted: bool, +} + +pub struct Tally { + config: TallyConfig, + began_ms: f64, + last_ms: f64, + frames: u64, + start_rank: u32, + rank: u32, + start_places: u32, + places: u32, + climbs: Vec<(u32, f64)>, + macros_on: bool, + empty_frames: u64, + empty_run: u64, + longest_empty: u64, + events: Vec, + watchdog: Watchdog, + next_probe_ms: f64, + probes: Vec, + steps: Vec<(f64, u32, u32, u32)>, + starts: Vec<(f64, &'static str)>, + ratchet: RatchetReport, + macro_report: MacroReport, + funnel: FunnelReport, + funnel_order: [Option; 4], + heals: HealReport, + whiteouts: u64, + was_fainted: bool, + battles: BattleReport, + battle: Option, + rewards: BTreeMap, + scenes: BTreeMap, + last_facts: Option, + ended_map: u32, +} + +/// The feed's kind for an adapter reward kind (`flysim::snapshot::RewardKind::from_adapter`), or +/// an empty string where the feed has no counter. The watchdog reads the feed's names. +pub fn feed_kind(adapter_kind: &str) -> &'static str { + flysim::snapshot::RewardKind::from_adapter(adapter_kind).map_or("", |kind| kind.as_str()) +} + +impl Tally { + /// The first frame's brain clock, rung and exploration count are the run's start. Nothing + /// before it is measured. + pub fn new(config: TallyConfig, began_ms: f64, rank: u32, places: u32) -> Self { + let watchdog = Watchdog::new(config.rules.clone(), places); + let next_probe_ms = began_ms + config.first_probe_s * 1000.0; + Self { + config, + began_ms, + last_ms: began_ms, + frames: 0, + start_rank: rank, + rank, + start_places: places, + places, + climbs: Vec::new(), + macros_on: false, + empty_frames: 0, + empty_run: 0, + longest_empty: 0, + events: Vec::new(), + watchdog, + next_probe_ms, + probes: Vec::new(), + steps: Vec::new(), + starts: Vec::new(), + ratchet: RatchetReport::default(), + macro_report: MacroReport::default(), + funnel: FunnelReport::default(), + funnel_order: [None; 4], + heals: HealReport::default(), + whiteouts: 0, + was_fainted: false, + battles: BattleReport::default(), + battle: None, + rewards: BTreeMap::new(), + scenes: BTreeMap::new(), + last_facts: None, + ended_map: 0xff, + } + } + + /// Brain minutes measured so far. + pub fn minutes(&self) -> f64 { + (self.last_ms - self.began_ms) / MINUTE_MS + } + + pub fn push(&mut self, frame: &Frame) { + let ms = frame.ms; + self.frames += 1; + self.last_ms = ms; + self.macros_on |= frame.macros_on; + if frame.rank != self.rank { + if frame.rank > self.rank { + self.climbs.push((frame.rank, (ms - self.began_ms) / MINUTE_MS)); + self.events.push(Ev::Milestone { ms }); + } + self.rank = frame.rank; + } + self.places = frame.places; + if let Some((map, x, y)) = frame.location { + self.steps.push((ms, map, x, y)); + } + *self.scenes.entry(frame.scene.to_owned()).or_insert(0) += 1; + + // The pad. + if frame.macros_on && frame.pad_empty { + self.empty_frames += 1; + self.empty_run += 1; + self.longest_empty = self.longest_empty.max(self.empty_run); + } else { + self.empty_run = 0; + } + + // Macros. + for event in &frame.events { + let counts = self.macro_report.by_macro.entry(event.name.to_owned()).or_default(); + match event.outcome { + None => { + counts.start += 1; + self.macro_report.starts += 1; + self.starts.push((ms, event.name)); + if let Some(battle) = self.battle.as_mut() { + battle.macros += 1; + } + } + Some("done") => { + counts.done += 1; + self.macro_report.done += 1; + } + Some("blocked") => { + counts.blocked += 1; + self.macro_report.blocked += 1; + } + Some("timeout") => { + counts.timeout += 1; + self.macro_report.timeout += 1; + } + Some("refused") => { + counts.refused += 1; + self.macro_report.refused += 1; + } + Some(_) => {} + } + self.events.push(Ev::Macro { ms, name: event.name, outcome: event.outcome }); + self.funnel_and_heals(ms, event.name, event.outcome); + } + + // Rewards. + let mut won_now = false; + let mut caught_now = false; + for (kind, value) in &frame.rewards { + let totals = self.rewards.entry((*kind).to_owned()).or_default(); + totals.n += 1; + totals.total += value; + self.events.push(Ev::Reward { ms, kind: feed_kind(kind) }); + match *kind { + "battle" | "trainer" => won_now = true, + "catch" => { + caught_now = true; + self.funnel.catches += 1; + self.note_stage(3, ms); + } + _ => {} + } + } + + // The ratchet. + if let Some(rolled) = frame.rollback { + self.ratchet.rollbacks += 1; + if rolled.game_over { + self.ratchet.game_over += 1; + } else { + self.ratchet.stall += 1; + } + } + + // Memory: bag, party, battles. + let facts = frame.facts; + if let Some(last) = self.last_facts { + if facts.balls > last.balls { + self.funnel.balls_gained += u64::from(facts.balls - last.balls); + } + if facts.balls < last.balls { + self.funnel.balls_spent += u64::from(last.balls - facts.balls); + } + if facts.owned > last.owned { + self.funnel.species_gained += u64::from(facts.owned - last.owned); + } + } + self.last_facts = Some(facts); + self.ended_map = facts.map; + let fainted = facts.all_fainted(); + if fainted && !self.was_fainted { + self.whiteouts += 1; + } + self.was_fainted = fainted; + match (facts.in_battle(), self.battle.as_mut()) { + (true, None) => { + self.battles.started += 1; + if facts.battle == 2 { + self.battles.trainer += 1; + } else { + self.battles.wild += 1; + } + self.battle = Some(Battle { + frames: 1, + won: won_now, + caught: caught_now, + fainted, + ..Battle::default() + }); + } + (true, Some(battle)) => { + battle.frames += 1; + battle.won |= won_now; + battle.caught |= caught_now; + battle.fainted |= fainted; + } + (false, Some(battle)) => { + battle.won |= won_now; + battle.caught |= caught_now; + battle.fainted |= fainted; + let battle = self.battle.take().expect("a battle"); + self.end_battle(battle); + } + (false, None) => {} + } + + // Probes. + while ms >= self.next_probe_ms { + let at_min = (self.next_probe_ms - self.began_ms) / MINUTE_MS; + let probe = self.watchdog.probe(&self.events, self.places, at_min); + self.probes.push(probe); + self.next_probe_ms += self.config.probe_s * 1000.0; + } + } + + fn end_battle(&mut self, battle: Battle) { + self.battles.ended += 1; + if battle.frames > self.battles.longest_frames { + self.battles.longest_frames = battle.frames; + self.battles.macros_in_longest = battle.macros; + } + if battle.won { + self.battles.won += 1; + } else if battle.fainted { + self.battles.lost += 1; + } else if battle.caught { + self.battles.caught += 1; + } else { + self.battles.other += 1; + } + if battle.caught { + // A catch that is also a win payout counts once as a win and is still a catch. + if battle.won { + self.battles.caught += 1; + } + } + } + + fn funnel_and_heals(&mut self, ms: f64, name: &str, outcome: Option<&str>) { + let f = &mut self.funnel; + let h = &mut self.heals; + let mut stage = None; + match (name, outcome) { + ("GO SHOP", None) => f.go_shop_start += 1, + ("GO SHOP", Some("done")) => { + f.go_shop_done += 1; + stage = Some(0); + } + ("BUY BALL", None) => f.buy_ball_start += 1, + ("BUY BALL", Some("done")) => { + f.buy_ball_done += 1; + stage = Some(1); + } + ("THROW BALL", None) => { + f.throw_ball_start += 1; + stage = Some(2); + } + ("THROW BALL", Some("done")) => f.throw_ball_done += 1, + ("GO HEAL", None) => h.go_heal_start += 1, + ("GO HEAL", Some("done")) => h.go_heal_done += 1, + ("HEAL", None) => h.heal_start += 1, + ("HEAL", Some("done")) => h.heal_done += 1, + _ => {} + } + if let Some(stage) = stage { + self.note_stage(stage, ms); + } + } + + fn note_stage(&mut self, stage: usize, ms: f64) { + self.funnel_order[stage].get_or_insert(ms); + } + + /// The run's report. `checkpoint`, `seed`, `runtime` and the rest of the identity are the + /// caller's. + pub fn finish(mut self, identity: RunReport) -> RunReport { + // The funnel's depth: stages in order of first occurrence, each after the last one. + let mut depth = 0; + let mut after = f64::NEG_INFINITY; + for first in self.funnel_order { + match first { + Some(ms) if ms >= after => { + depth += 1; + after = ms; + } + _ => break, + } + } + self.funnel.depth = depth; + if let Some(battle) = self.battle.take() { + self.battles.still_running = true; + self.battles.longest_frames = self.battles.longest_frames.max(battle.frames); + } + let minutes = self.minutes(); + let seconds = |frames: u64| frames as f64 * FRAME_MS / 1000.0; + + // The watchdog. + let mut watchdog = WatchdogReport { probes: self.probes.len(), ..Default::default() }; + let mut run = 0usize; + for probe in &self.probes { + if probe.suspected { + watchdog.suspected += 1; + run += 1; + if run >= 2 { + watchdog.confirmed += 1; + } + if run == 2 { + watchdog.ladder_events += 1; + } + if let Some(reason) = &probe.reason { + *watchdog.reasons.entry(reason.clone()).or_insert(0) += 1; + } + if watchdog.flagged.len() < 20 { + watchdog.flagged.push(probe.clone()); + } + } else { + run = 0; + } + } + + let hunt = hunt(&self.steps, &self.starts, self.began_ms, self.last_ms); + let macro_report = std::mem::take(&mut self.macro_report); + RunReport { + minutes, + frames: self.frames, + rungs: RungReport { + start: self.start_rank, + end: self.rank, + gained: self.rank.saturating_sub(self.start_rank), + climbs: self.climbs, + }, + places_start: self.start_places, + places_end: self.places, + pad: PadReport { + empty_frames: self.empty_frames, + empty_seconds: seconds(self.empty_frames), + empty_fraction: if self.frames == 0 || !self.macros_on { + 0.0 + } else { + self.empty_frames as f64 / self.frames as f64 + }, + longest_empty_seconds: seconds(self.longest_empty), + }, + watchdog, + hunt, + ratchet: self.ratchet, + macros: macro_report, + funnel: self.funnel, + heals: self.heals, + whiteouts: self.whiteouts, + battles: self.battles, + rewards: self.rewards, + scenes: self.scenes, + ended_map: self.ended_map, + ..identity + } + } +} + +/// The longest run of one repeated block in `names`, as `(block, repeats)` +/// (`examples/trap_hunt.rs`: every period up to eight, every offset). +pub fn longest_cycle(names: &[&'static str]) -> Option<(String, usize)> { + let mut best: Option<(String, usize)> = None; + for period in 1..=HUNT_MAX_PERIOD.min(names.len()) { + let mut start = 0; + while start + period <= names.len() { + let block = &names[start..start + period]; + let mut repeats = 1; + while start + period * (repeats + 1) <= names.len() + && &names[start + period * repeats..start + period * (repeats + 1)] == block + { + repeats += 1; + } + if best.as_ref().is_none_or(|(_, known)| repeats > *known) { + best = Some((block.join(", "), repeats)); + } + start += period * repeats; + } + } + best +} + +/// Every window of the run that is a trap by the trap hunt's rules: it did things (a window with +/// no macro in it is the fly choosing nothing, which is the doctrine working) and either stood on +/// fewer than four distinct tiles or repeated one macro sequence more than ten times. +pub fn hunt( + steps: &[(f64, u32, u32, u32)], + starts: &[(f64, &'static str)], + began_ms: f64, + ended_ms: f64, +) -> HuntReport { + let mut report = HuntReport::default(); + let mut at = began_ms; + while at + HUNT_WINDOW_MS <= ended_ms { + let until = at + HUNT_WINDOW_MS; + report.windows += 1; + let tiles: BTreeSet<(u32, u32, u32)> = steps + .iter() + .filter(|(ms, ..)| *ms >= at && *ms < until) + .map(|(_, map, x, y)| (*map, *x, *y)) + .collect(); + let names: Vec<&'static str> = starts + .iter() + .filter(|(ms, _)| *ms >= at && *ms < until) + .map(|(_, name)| *name) + .collect(); + let cycle = longest_cycle(&names).filter(|(_, repeats)| *repeats > HUNT_MAX_REPEATS); + let stuck = tiles.len() < HUNT_MIN_TILES && !names.is_empty(); + if stuck || cycle.is_some() { + report.flagged += 1; + if report.first_flagged.len() < 20 { + report.first_flagged.push(HuntWindow { + at_min: (at - began_ms) / MINUTE_MS, + tiles: tiles.len(), + macros: names.len(), + cycle, + }); + } + } + at += HUNT_STEP_MS; + } + report +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::obs::{MacroEv, Rolled}; + + fn frame(ms: f64) -> Frame { + Frame { + ms, + events: Vec::new(), + rewards: Vec::new(), + rank: 8, + places: 100, + location: Some((1, (ms / 1000.0) as u32 % 50, 3)), + macros_on: true, + pad_empty: false, + scene: "overworld", + rollback: None, + facts: Facts { party: 2, alive: 2, balls: 3, money: 500, owned: 10, map: 1, battle: 0 }, + } + } + + fn ev(name: &'static str, outcome: Option<&'static str>) -> MacroEv { + MacroEv { name, outcome } + } + + fn run(frames: &[Frame]) -> RunReport { + let mut tally = Tally::new(TallyConfig::default(), 0.0, 8, 100); + for frame in frames { + tally.push(frame); + } + tally.finish(RunReport { checkpoint: "t".into(), ..RunReport::default() }) + } + + #[test] + fn rungs_climb_and_are_timed() { + let mut a = frame(1000.0); + a.rank = 9; + let mut b = frame(61_000.0); + b.rank = 10; + let report = run(&[a, b]); + assert_eq!((report.rungs.start, report.rungs.end, report.rungs.gained), (8, 10, 2)); + assert_eq!(report.rungs.climbs, vec![(9, 1000.0 / 60_000.0), (10, 61_000.0 / 60_000.0)]); + } + + #[test] + fn the_empty_pad_is_counted_in_seconds_and_in_its_longest_stretch() { + let mut frames = Vec::new(); + for i in 0..10u64 { + let mut f = frame(i as f64 * FRAME_MS); + f.pad_empty = (2..7).contains(&i) || i == 9; + frames.push(f); + } + let report = run(&frames); + assert_eq!(report.pad.empty_frames, 6); + assert!((report.pad.empty_fraction - 0.6).abs() < 1e-9); + assert!((report.pad.longest_empty_seconds - 5.0 * FRAME_MS / 1000.0).abs() < 1e-9); + } + + #[test] + fn raw_mode_has_no_pad_to_be_empty() { + let mut f = frame(0.0); + f.macros_on = false; + f.pad_empty = true; + assert_eq!(run(&[f]).pad.empty_fraction, 0.0); + } + + #[test] + fn the_shop_to_catch_funnel_counts_each_stage_and_its_depth() { + let mut frames = Vec::new(); + let script: [(&'static str, Option<&'static str>); 6] = [ + ("GO SHOP", None), + ("GO SHOP", Some("done")), + ("BUY BALL", None), + ("BUY BALL", Some("done")), + ("THROW BALL", None), + ("THROW BALL", Some("done")), + ]; + for (i, (name, outcome)) in script.iter().enumerate() { + let mut f = frame(i as f64 * 1000.0); + f.events = vec![ev(name, *outcome)]; + frames.push(f); + } + let mut f = frame(7000.0); + f.rewards = vec![("catch", 5.0), ("species", 1.0)]; + frames.push(f); + let report = run(&frames); + let funnel = &report.funnel; + assert_eq!( + (funnel.go_shop_done, funnel.buy_ball_done, funnel.throw_ball_start, funnel.catches), + (1, 1, 1, 1) + ); + assert_eq!(funnel.depth, 4); + assert_eq!(report.macros.starts, 3); + assert_eq!(report.macros.done, 3); + assert_eq!(report.rewards["catch"].n, 1); + } + + #[test] + fn a_funnel_that_skips_the_shop_stops_at_depth_zero() { + let mut f = frame(0.0); + f.events = vec![ev("BUY BALL", Some("done"))]; + // Stage 0 never occurred: depth counts the unbroken prefix only. + assert_eq!(run(&[f]).funnel.depth, 0); + } + + #[test] + fn blocked_refused_and_timed_out_macros_are_counted_by_macro() { + let mut f = frame(0.0); + f.events = vec![ + ev("GO ROUTE", Some("refused")), + ev("GO ROUTE", Some("refused")), + ev("GO OUT", Some("blocked")), + ev("GO NPC", Some("timeout")), + ev("NEXT", Some("done")), + ]; + let report = run(&[f]); + assert_eq!(report.macros.failed(), 4); + assert_eq!(report.macros.by_macro["GO ROUTE"].refused, 2); + assert_eq!(report.macros.done, 1); + } + + #[test] + fn heals_are_the_nurses_heal_and_the_walk_to_her() { + let mut f = frame(0.0); + f.events = vec![ + ev("GO HEAL", None), + ev("GO HEAL", Some("done")), + ev("HEAL", None), + ev("HEAL", Some("done")), + ]; + let heals = run(&[f]).heals; + assert_eq!((heals.go_heal_done, heals.heal_done), (1, 1)); + } + + fn battle_frames(kind: u8, n: usize, from_ms: f64) -> Vec { + (0..n) + .map(|i| { + let mut f = frame(from_ms + i as f64 * FRAME_MS); + f.facts.battle = kind; + f + }) + .collect() + } + + #[test] + fn a_battle_is_won_lost_or_caught_by_what_ended_it() { + let mut frames = Vec::new(); + // A won trainer battle. + frames.extend(battle_frames(2, 5, 0.0)); + let mut win = frame(100.0); + win.rewards = vec![("trainer", 1.0)]; + frames.push(win); + // A wild battle lost: the party faints inside it, then a whiteout. + frames.extend(battle_frames(1, 3, 200.0)); + let mut down = battle_frames(1, 3, 300.0); + for f in &mut down { + f.facts.alive = 0; + } + frames.extend(down); + let mut after = frame(400.0); + after.facts.alive = 0; + frames.push(after); + frames.push(frame(500.0)); + // A wild battle caught. + frames.extend(battle_frames(1, 4, 600.0)); + let mut catch = battle_frames(1, 1, 700.0); + catch[0].rewards = vec![("catch", 3.0)]; + frames.extend(catch); + frames.push(frame(800.0)); + // One run away from. + frames.extend(battle_frames(1, 2, 900.0)); + frames.push(frame(1000.0)); + // One still running at the end. + frames.extend(battle_frames(1, 2, 1100.0)); + let report = run(&frames); + let b = &report.battles; + assert_eq!((b.started, b.ended), (5, 4)); + assert_eq!((b.trainer, b.wild), (1, 4)); + assert_eq!((b.won, b.lost, b.caught, b.other), (1, 1, 1, 1)); + assert!(b.still_running); + assert_eq!(report.whiteouts, 1); + assert_eq!(report.funnel.catches, 1); + } + + #[test] + fn bag_and_dex_changes_become_ball_and_species_counts() { + let mut a = frame(0.0); + a.facts.balls = 5; + let mut b = frame(1000.0); + b.facts.balls = 3; + let mut c = frame(2000.0); + c.facts.balls = 8; + c.facts.owned = 12; + let report = run(&[a, b, c]); + assert_eq!((report.funnel.balls_spent, report.funnel.balls_gained), (2, 5)); + assert_eq!(report.funnel.species_gained, 2); + } + + #[test] + fn ratchet_rollbacks_are_split_by_trigger() { + let mut a = frame(0.0); + a.rollback = Some(Rolled { game_over: true }); + let mut b = frame(1.0); + b.rollback = Some(Rolled { game_over: false }); + let report = run(&[a, b]); + assert_eq!((report.ratchet.rollbacks, report.ratchet.game_over, report.ratchet.stall), (2, 1, 1)); + } + + /// The Viridian cycle on three tiles for twelve minutes: the watchdog confirms it and so does + /// the trap hunt. + #[test] + fn a_ring_is_caught_by_both_instruments() { + let names = ["GO NPC", "GO OUT", "NEXT", "GO FRONTIER"]; + let mut frames = Vec::new(); + let mut i = 0usize; + let mut ms = 0.0; + while ms < 12.0 * MINUTE_MS { + let mut f = frame(ms); + f.location = Some((1, (i % 3) as u32, 3)); + if ((ms / FRAME_MS) as u64).is_multiple_of(180) { + f.events = vec![ev(names[i % 4], None), ev(names[i % 4], Some("done"))]; + i += 1; + } + frames.push(f); + ms += FRAME_MS; + } + let report = run(&frames); + assert!(report.watchdog.suspected >= 2, "{:?}", report.watchdog); + assert!(report.watchdog.ladder_events >= 1); + assert!(report.watchdog.confirmed >= 1); + assert!(report.watchdog.reasons.get("sequence").copied().unwrap_or(0) > 0); + assert!(report.hunt.flagged > 0 && report.hunt.windows > 0, "{:?}", report.hunt); + // The run explored nothing: the count never moved. + assert_eq!(report.places_end, report.places_start); + } + + /// The same cadence of macros on a fly that keeps finding new tiles is not a trap. + #[test] + fn a_walk_that_finds_places_is_not_flagged() { + let names = ["GO NPC", "GO OUT", "NEXT", "GO FRONTIER"]; + let mut frames = Vec::new(); + let mut i = 0usize; + let mut ms = 0.0; + while ms < 12.0 * MINUTE_MS { + let mut f = frame(ms); + f.location = Some((1, (ms / 1000.0) as u32, 3)); + f.places = 100 + (ms / 10_000.0) as u32; + if ((ms / FRAME_MS) as u64).is_multiple_of(180) { + f.events = vec![ev(names[i % 4], None), ev(names[i % 4], Some("done"))]; + i += 1; + } + frames.push(f); + ms += FRAME_MS; + } + let report = run(&frames); + assert_eq!(report.watchdog.suspected, 0, "{:?}", report.watchdog); + assert_eq!(report.hunt.flagged, 0); + assert!(report.watchdog.probes >= 4); + } + + #[test] + fn the_hunt_ignores_a_window_with_no_macro_in_it() { + let steps: Vec<(f64, u32, u32, u32)> = (0..9000).map(|i| (i as f64 * 20.0, 1, 1, 1)).collect(); + let report = hunt(&steps, &[], 0.0, 180_000.0); + assert!(report.windows > 0); + assert_eq!(report.flagged, 0); + // The same ground with a macro in each window is a stand-still. + let starts: Vec<(f64, &'static str)> = (0..18).map(|i| (i as f64 * 10_000.0, "NEXT")).collect(); + assert!(hunt(&steps, &starts, 0.0, 180_000.0).flagged > 0); + } + + #[test] + fn the_longest_cycle_finds_the_shortest_block_and_its_repeats() { + let names = ["A", "B", "A", "B", "A", "B", "C"]; + assert_eq!(longest_cycle(&names), Some(("A, B".to_string(), 3))); + assert_eq!(longest_cycle(&[]), None); + } +} diff --git a/services/flysim/crates/fly-scorecard/src/watchdog.rs b/services/flysim/crates/fly-scorecard/src/watchdog.rs new file mode 100644 index 0000000..50c0abe --- /dev/null +++ b/services/flysim/crates/fly-scorecard/src/watchdog.rs @@ -0,0 +1,401 @@ +//! `fly-watchdog` check 10 (loop suspected), as a function of a run's events. +//! +//! The live check reads the event log's tail, the exploration count from `/status.json` and its +//! own state files; this reads the same three things from a run. The rules, their order and every +//! default are the shell's (`infra/bin/fly-watchdog`, `loop_analyze` and `check_loop`), so a run +//! that would have raised the flag on the stream raises it here. Two differences, both about time: +//! +//! - the probe cadence is a parameter (the stream's is every five wall minutes; a run is short, +//! so the scorecard probes more often), and a window is the last `window_ms` of brain time or +//! the whole run when it is shorter; +//! - the exploration count the first probe compares with is the run's starting count, which the +//! live check does not have for its first probe after a boot. +//! +//! Like the shell, this reads and reports. It never acts. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +/// The thresholds of `fly-watchdog`'s `WD_LOOP_*` variables. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Rules { + pub window_ms: f64, + pub max_period: usize, + pub max_distinct: usize, + pub min_repeats: usize, + pub dominance_pct: usize, + pub min_events: usize, + pub stall_pct: usize, + pub busy_min: usize, + pub fight_min: usize, +} + +impl Default for Rules { + fn default() -> Self { + Self { + window_ms: 600_000.0, + max_period: 8, + max_distinct: 4, + min_repeats: 20, + dominance_pct: 95, + min_events: 20, + stall_pct: 90, + busy_min: 100, + fight_min: 24, + } + } +} + +/// One line of the event log the check reads: a macro event, a reward or a rung. +#[derive(Clone, Debug, PartialEq)] +pub enum Ev { + /// ` start` is `outcome: None`; a finish carries its word (done, blocked, timeout, + /// refused). + Macro { ms: f64, name: &'static str, outcome: Option<&'static str> }, + /// A reward, with the feed's kind (`wildwin`, `trainer`, `badge`, `pokedex`, `area`, ...), or + /// an empty string for an adapter kind the feed has no counter for. + Reward { ms: f64, kind: &'static str }, + Milestone { ms: f64 }, +} + +/// `loop_analyze`'s result for one window. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Analysis { + pub starts: usize, + pub decisions: usize, + pub distinct: usize, + pub top_name: String, + pub top_count: usize, + pub period: usize, + pub repeats: usize, + pub refused: usize, + pub blocked: usize, + pub timeout: usize, + pub done: usize, + pub rewards: usize, + pub fights: usize, + pub wins: usize, + pub progress: usize, + pub window_from: f64, + pub window_to: f64, +} + +fn is_lasting(kind: &str) -> bool { + matches!(kind, "milestone" | "pokedex" | "area" | "trainer" | "badge") +} + +/// `loop_analyze`: the window ends at the newest macro event. +pub fn analyze(events: &[Ev], rules: &Rules) -> Analysis { + let last_macro = events.iter().rev().find_map(|event| match event { + Ev::Macro { ms, .. } => Some(*ms), + _ => None, + }); + let Some(to) = last_macro else { return Analysis::default() }; + let from = to - rules.window_ms; + let mut a = Analysis { window_from: from, window_to: to, ..Analysis::default() }; + for event in events { + let (ms, kind) = match event { + Ev::Reward { ms, kind } => (*ms, *kind), + Ev::Milestone { ms } => (*ms, "milestone"), + Ev::Macro { .. } => continue, + }; + if ms < from { + continue; + } + if is_lasting(kind) { + a.progress += 1; + } + if kind == "milestone" { + continue; + } + a.rewards += 1; + if matches!(kind, "wildwin" | "trainer" | "badge") { + a.wins += 1; + } + } + let mut seq: Vec<&'static str> = Vec::new(); + let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new(); + for event in events { + let Ev::Macro { ms, name, outcome } = event else { continue }; + if *ms < from { + continue; + } + match outcome { + Some("blocked") => { + a.blocked += 1; + continue; + } + Some("timeout") => { + a.timeout += 1; + continue; + } + Some("done") => { + a.done += 1; + continue; + } + Some("refused") => a.refused += 1, + None => a.starts += 1, + Some(_) => continue, + } + seq.push(name); + if matches!(*name, "MOVE 1" | "MOVE 2" | "MOVE 3" | "MOVE 4") { + a.fights += 1; + } + let n = counts.entry(name).or_insert(0); + *n += 1; + if *n > a.top_count { + a.top_count = *n; + a.top_name = (*name).to_owned(); + } + } + a.decisions = seq.len(); + a.distinct = counts.len(); + let k = seq.len(); + let mut p = 1; + while p <= rules.max_period && p * 2 <= k { + let mut r = 1; + while (r + 1) * p <= k { + let same = (0..p).all(|j| seq[k - 1 - j] == seq[k - 1 - r * p - j]); + if !same { + break; + } + r += 1; + } + if r >= 2 { + a.period = p; + a.repeats = r; + break; + } + p += 1; + } + a +} + +/// One probe's verdict. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Probe { + /// Brain minutes into the run. + pub at_min: f64, + pub suspected: bool, + pub reason: Option, + pub decisions: usize, + pub distinct: usize, + pub period: usize, + pub repeats: usize, + pub done: usize, + pub failed: usize, + pub rewards: usize, + pub fights: usize, + pub wins: usize, + pub places_delta: i64, +} + +/// `check_loop`'s memory between probes. +#[derive(Clone, Debug)] +pub struct Watchdog { + pub rules: Rules, + prev_places: i64, + prev_idle: bool, + prev_busy: bool, + prev_unwon: bool, +} + +impl Watchdog { + /// `places` is the exploration count the run starts with. + pub fn new(rules: Rules, places: u32) -> Self { + Self { + rules, + prev_places: i64::from(places), + prev_idle: false, + prev_busy: false, + prev_unwon: false, + } + } + + /// One probe over every event so far. + pub fn probe(&mut self, events: &[Ev], places: u32, at_min: f64) -> Probe { + let rules = &self.rules; + let a = analyze(events, rules); + let delta = i64::from(places) - self.prev_places; + self.prev_places = i64::from(places); + // `grown` is 1 unless the count is known not to have grown. + let grown = delta > 0; + let idle = a.decisions > 0 && a.done == 0 && !grown; + let busy = a.decisions >= rules.busy_min && a.rewards == 0 && !grown; + let unwon = a.fights >= rules.fight_min && a.wins == 0 && !grown; + let failed = a.refused + a.blocked + a.timeout; + let mut reason = None; + if a.decisions > 0 && !grown { + reason = if a.decisions >= rules.min_events + && failed * 100 >= a.decisions * rules.stall_pct + { + Some("stalled") + } else if idle && self.prev_idle { + Some("zero-progress") + } else if a.distinct <= rules.max_distinct && a.repeats >= rules.min_repeats { + Some("sequence") + } else if a.decisions >= rules.min_events + && a.top_count * 100 >= a.decisions * rules.dominance_pct + { + Some("dominant") + } else if busy && self.prev_busy { + Some("unrewarded") + } else if unwon && self.prev_unwon { + Some("unwon-battles") + } else { + None + }; + } + self.prev_idle = idle; + self.prev_busy = busy; + self.prev_unwon = unwon; + Probe { + at_min, + suspected: reason.is_some(), + reason: reason.map(str::to_owned), + decisions: a.decisions, + distinct: a.distinct, + period: a.period, + repeats: a.repeats, + done: a.done, + failed, + rewards: a.rewards, + fights: a.fights, + wins: a.wins, + places_delta: delta, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn start(ms: f64, name: &'static str) -> [Ev; 2] { + [ + Ev::Macro { ms, name, outcome: None }, + Ev::Macro { ms: ms + 1.0, name, outcome: Some("done") }, + ] + } + + fn cycle(names: &[&'static str], times: usize) -> Vec { + let mut events = Vec::new(); + let mut ms = 0.0; + for _ in 0..times { + for name in names { + events.extend(start(ms, name)); + ms += 3000.0; + } + } + events + } + + #[test] + fn the_viridian_cycle_is_a_sequence_when_nothing_is_explored() { + // GO NPC, GO OUT, NEXT, GO FRONTIER, every three brain seconds, 25 times. + let events = cycle(&["GO NPC", "GO OUT", "NEXT", "GO FRONTIER"], 25); + let a = analyze(&events, &Rules::default()); + assert_eq!((a.period, a.repeats, a.distinct), (4, 25, 4)); + let mut watchdog = Watchdog::new(Rules::default(), 100); + let probe = watchdog.probe(&events, 100, 5.0); + assert!(probe.suspected); + assert_eq!(probe.reason.as_deref(), Some("sequence")); + // The same sequence on a fly that is still finding places is a long walk, not a loop. + let mut watchdog = Watchdog::new(Rules::default(), 100); + assert!(!watchdog.probe(&events, 101, 5.0).suspected); + } + + #[test] + fn a_pad_of_one_refusing_button_is_a_stall() { + let mut events = Vec::new(); + for i in 0..30 { + events.push(Ev::Macro { + ms: 1000.0 * i as f64, + name: "GO ROUTE", + outcome: Some("refused"), + }); + } + let mut watchdog = Watchdog::new(Rules::default(), 7); + let probe = watchdog.probe(&events, 7, 1.0); + assert_eq!(probe.reason.as_deref(), Some("stalled")); + assert_eq!(probe.failed, 30); + } + + #[test] + fn unrewarded_needs_two_probes() { + // Ten distinct names (a period past the cap), all done, no reward, 120 decisions, no new + // ground: row 58's shape. The first probe remembers it and only the second flags. + let names = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]; + let mut events = Vec::new(); + let mut ms = 0.0; + for _ in 0..12 { + for name in names { + events.extend(start(ms, name)); + ms += 1000.0; + } + } + let mut watchdog = Watchdog::new(Rules::default(), 5); + let first = watchdog.probe(&events, 5, 3.0); + assert!(!first.suspected, "{first:?}"); + let second = watchdog.probe(&events, 5, 5.0); + assert_eq!(second.reason.as_deref(), Some("unrewarded"), "{second:?}"); + // One new place clears it. + let third = watchdog.probe(&events, 6, 7.0); + assert!(!third.suspected); + } + + #[test] + fn rewards_and_rungs_inside_the_window_are_counted() { + let mut events = cycle(&["GO FRONTIER", "NEXT"], 3); + events.push(Ev::Reward { ms: 100.0, kind: "wildwin" }); + events.push(Ev::Reward { ms: 200.0, kind: "" }); + events.push(Ev::Milestone { ms: 300.0 }); + let a = analyze(&events, &Rules::default()); + assert_eq!((a.rewards, a.wins, a.progress), (2, 1, 1)); + // A reward before the window's start is not in it. + let rules = Rules { window_ms: 1000.0, ..Rules::default() }; + let late = analyze(&events, &rules); + assert_eq!(late.rewards, 0); + } + + #[test] + fn a_window_with_no_macro_is_not_a_loop() { + let mut watchdog = Watchdog::new(Rules::default(), 5); + let probe = watchdog.probe(&[Ev::Reward { ms: 5.0, kind: "wildwin" }], 5, 5.0); + assert!(!probe.suspected); + assert_eq!(probe.decisions, 0); + } + + #[test] + fn the_shortest_period_wins() { + let events = cycle(&["X", "Y"], 40); + let a = analyze(&events, &Rules::default()); + assert_eq!((a.period, a.repeats), (2, 40)); + } + + #[test] + fn fights_without_a_win_flag_on_the_second_probe_only() { + let mut events = Vec::new(); + let moves = ["MOVE 1", "MOVE 2"]; + let mut ms = 0.0; + // Alternate MOVE n with a varying filler so no short cycle or dominant name forms. + let fillers = ["NEXT", "TALK", "YES", "NO", "BACK", "MENU", "CLOSE"]; + for i in 0..30usize { + events.extend(start(ms, moves[i % 2])); + ms += 1000.0; + events.extend(start(ms, fillers[(i * 3 + i / 4) % fillers.len()])); + ms += 1000.0; + } + let rules = Rules { min_repeats: 1000, ..Rules::default() }; + let mut watchdog = Watchdog::new(rules, 9); + let first = watchdog.probe(&events, 9, 4.0); + assert!(!first.suspected, "{first:?}"); + let second = watchdog.probe(&events, 9, 6.0); + assert_eq!(second.reason.as_deref(), Some("unwon-battles"), "{second:?}"); + // A win in the window clears it. + events.push(Ev::Reward { ms: 100.0, kind: "wildwin" }); + let third = watchdog.probe(&events, 9, 8.0); + assert!(!third.suspected); + } +} diff --git a/services/flysim/crates/fly-scorecard/tests/rom_scorecard.rs b/services/flysim/crates/fly-scorecard/tests/rom_scorecard.rs new file mode 100644 index 0000000..ef02c15 --- /dev/null +++ b/services/flysim/crates/fly-scorecard/tests/rom_scorecard.rs @@ -0,0 +1,79 @@ +//! The scorecard on the real cartridge and connectome: a short run per runtime from a real +//! checkpoint. ROM-gated: `FLY_ROM`, `FLY_DOOR_CHECKPOINT` (rom-env.sh) and `data/fafb-v783`; +//! without them each test prints why and returns (source rom-env.sh, or it covers nothing). +//! +//! What it holds: +//! - a run measures something (frames, a pad, macros) and its minutes are the minutes asked for; +//! - the same seed twice is the same run, and two seeds are not (the idle frames); +//! - the session runtime and the legacy loop, from the same checkpoint and seed, give the same +//! report: what the scorecard measures does not depend on which runtime ran it. + +use std::path::PathBuf; + +use fly_scorecard::runner::{RunSpec, run_legacy, run_session}; +use fly_scorecard::tally::RunReport; +use flysim::snapshot::MacroMode; + +fn spec(seed: u32) -> Option { + let rom = std::env::var_os("FLY_ROM").map(PathBuf::from); + let checkpoint = std::env::var_os("FLY_DOOR_CHECKPOINT").map(PathBuf::from); + let dataset = fly_session::legacy_parity::fafb_dir(); + let (Some(rom), Some(checkpoint), Some(dataset)) = (rom, checkpoint, dataset) else { + eprintln!("skipping: FLY_ROM, FLY_DOOR_CHECKPOINT or data/fafb-v783 missing"); + return None; + }; + Some(RunSpec { + id: "door".to_owned(), + checkpoint, + rom, + dataset, + seed, + minutes: 0.4, + threads: 2, + mode: MacroMode::Macros, + tally: RunSpec::tally_config(5.0, 20.0), + }) +} + +/// A report with what legitimately differs between runs of the same thing blanked. +fn essence(mut report: RunReport) -> RunReport { + report.wall_seconds = 0.0; + report.runtime = String::new(); + report +} + +#[test] +fn the_legacy_loop_is_measured_reproducibly_and_seeds_differ() { + let (Some(a), Some(b), Some(c)) = (spec(0), spec(3), spec(4)) else { return }; + let first = run_legacy(&a).expect("a legacy run"); + assert!(first.frames > 1000, "{} frames", first.frames); + assert!((first.minutes - 0.4).abs() < 0.01, "{} minutes", first.minutes); + assert_eq!(first.idle_frames, 0); + assert!(first.macros.starts > 0, "the macro layer dealt nothing"); + assert!(first.scenes.values().sum::() == first.frames); + assert_eq!(essence(first.clone()), essence(run_legacy(&a).expect("a second run"))); + let (x, y) = (run_legacy(&b).expect("seed 3"), run_legacy(&c).expect("seed 4")); + assert_ne!(x.idle_frames, y.idle_frames); + assert!(x.idle_frames > 0); + // Different starting points of the brain's own trajectory: the runs need not agree. + eprintln!( + "seed 0/3/4 macro starts {}/{}/{}, pad {:.3}/{:.3}/{:.3}", + first.macros.starts, + x.macros.starts, + y.macros.starts, + first.pad.empty_fraction, + x.pad.empty_fraction, + y.pad.empty_fraction + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn the_session_runtime_and_the_legacy_loop_measure_the_same_run() { + let Some(spec) = spec(2) else { return }; + let legacy = run_legacy(&spec).expect("the legacy run"); + let session = run_session(&spec).await.expect("the session run"); + assert_eq!(session.runtime, "session"); + assert_eq!(legacy.runtime, "legacy"); + assert!(session.frames > 1000); + assert_eq!(essence(legacy), essence(session)); +} diff --git a/tools/scorecard/checkpoints.json b/tools/scorecard/checkpoints.json new file mode 100644 index 0000000..2633100 --- /dev/null +++ b/tools/scorecard/checkpoints.json @@ -0,0 +1,77 @@ +{ + "schema": "fly-scorecard-set-v1", + "checkpoints": [ + { + "id": "r08-viridian-city", + "rung": 8, + "env": "FLY_SCORECARD_R08_CHECKPOINT", + "note": "Viridian City on its first visit, few places known" + }, + { + "id": "r09-viridian-mart", + "rung": 9, + "env": "FLY_ROW66_MART_CHECKPOINT", + "note": "the Viridian mart, rung 9 on the ledger (the shop and ball funnel)" + }, + { + "id": "r09-forest-catch", + "rung": 9, + "env": "FLY_CATCH_CHECKPOINT", + "note": "Viridian Forest, one ball in the bag" + }, + { + "id": "r09-forest-row60", + "rung": 9, + "env": "FLY_ROW60_CHECKPOINT", + "note": "rung 9, the row 60 state" + }, + { + "id": "r10-pewter-center", + "rung": 10, + "env": "FLY_CENTER_CHECKPOINT", + "note": "Pewter City, at the Pokemon Center" + }, + { + "id": "r10-pewter-gym", + "rung": 10, + "env": "FLY_ROW67_CHECKPOINT", + "note": "the live Pewter Gym battle" + }, + { + "id": "r11-mart", + "rung": 11, + "env": "FLY_MART_CHECKPOINT", + "note": "rung 11, at a mart" + }, + { + "id": "r11-badge", + "rung": 11, + "env": "FLY_BADGE_CHECKPOINT", + "note": "Boulder Badge in hand" + }, + { + "id": "r12-mt-moon", + "rung": 12, + "env": "FLY_MT_MOON_CHECKPOINT", + "note": "Mt. Moon entered" + }, + { + "id": "r12-row64", + "rung": 12, + "env": "FLY_ROW64_CHECKPOINT", + "note": "rung 12, the row 64 live state" + }, + { + "id": "r15-yard", + "rung": 15, + "env": "FLY_ROW65_YARD_CHECKPOINT", + "note": "rung 15, a yard past Cerulean" + }, + { + "id": "r15-nugget-bridge", + "rung": 15, + "env": "FLY_ROW71_CHECKPOINT", + "note": "Route 25, the bag-window trap's state" + } + ] +} diff --git a/tools/scorecard/overlay.sh b/tools/scorecard/overlay.sh new file mode 100755 index 0000000..1c04319 --- /dev/null +++ b/tools/scorecard/overlay.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Put the scorecard on an older release's tree, so a release that predates the tool can be scored. +# +# tools/scorecard/overlay.sh +# +# Copies the fly-scorecard crate, the checkpoint set and the docs from of this +# repository into (a checkout of the release to score), adds the crate to the +# workspace, and applies the one accessor the session runtime needs +# (`PokeredTask::with_reader`, read-only). Nothing else in the release changes, so the numbers +# are the release's own. A no-op on a tree that already has the tool. +set -euo pipefail + +ref="${1:?usage: overlay.sh }" +target="${2:?usage: overlay.sh }" +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +repo="$(git -C "$here" rev-parse --show-toplevel)" +ws="$target/services/flysim/Cargo.toml" +task="$target/services/flysim/crates/fly-legacy-session/src/task.rs" + +[ -f "$ws" ] && [ -f "$task" ] || { echo "overlay: $target is not a flybrain tree with the session runtime" >&2; exit 1; } + +if [ ! -d "$target/services/flysim/crates/fly-scorecard" ]; then + git -C "$repo" archive "$ref" services/flysim/crates/fly-scorecard tools/scorecard docs/scorecard.md \ + | tar -x -C "$target" +fi +if ! grep -q '"crates/fly-scorecard"' "$ws"; then + sed -i 's#^ "crates/flysim-store",# "crates/flysim-store",\n "crates/fly-scorecard",#' "$ws" + grep -q '"crates/fly-scorecard"' "$ws" || { echo "overlay: could not add the crate to the workspace" >&2; exit 1; } +fi +if ! grep -q 'pub fn with_reader' "$task"; then + (cd "$target" && git apply --recount "$here/with-reader.patch" 2>/dev/null) \ + || (cd "$target" && patch -p1 --forward < "$here/with-reader.patch") \ + || { echo "overlay: with-reader.patch does not apply to this tree" >&2; exit 1; } +fi +echo "overlay: scorecard from $ref on $target" diff --git a/tools/scorecard/with-reader.patch b/tools/scorecard/with-reader.patch new file mode 100644 index 0000000..f9acd74 --- /dev/null +++ b/tools/scorecard/with-reader.patch @@ -0,0 +1,24 @@ +diff --git a/services/flysim/crates/fly-legacy-session/src/task.rs b/services/flysim/crates/fly-legacy-session/src/task.rs +index f85694e..2cd14c2 100644 +--- a/services/flysim/crates/fly-legacy-session/src/task.rs ++++ b/services/flysim/crates/fly-legacy-session/src/task.rs +@@ -368,6 +368,19 @@ impl PokeredTask { + ) + } + ++ /// Read the committed boundary's memory image through the cartridge, as the macro engine ++ /// reads it, for a harness that measures play (the scorecard). `None` before the first ++ /// observation. Changes nothing. ++ pub fn with_reader( ++ &self, ++ f: impl FnOnce(&mut dyn flybrain_gb::MemoryReader) -> R, ++ ) -> Option { ++ let inner = self.lock(); ++ let (_, image) = inner.current.as_ref()?; ++ let mut reader = ImageReader::new(image, &inner.cartridge); ++ Some(f(&mut reader)) ++ } ++ + /// The brain time of the last transition (its Prepare's clock), in ms: `network.ms`. + pub fn brain_ms(&self) -> f64 { + self.lock().ms From ae5db47801cdf1530588301af2a6df6394ee8af9 Mon Sep 17 00:00:00 2001 From: acamilo Date: Thu, 1 Oct 2026 22:11:50 +0000 Subject: [PATCH 10/27] scorecard: the overlay can be run from a copy outside a checkout --- tools/scorecard/overlay.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tools/scorecard/overlay.sh b/tools/scorecard/overlay.sh index 1c04319..e11fdb9 100755 --- a/tools/scorecard/overlay.sh +++ b/tools/scorecard/overlay.sh @@ -13,7 +13,9 @@ set -euo pipefail ref="${1:?usage: overlay.sh }" target="${2:?usage: overlay.sh }" here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -repo="$(git -C "$here" rev-parse --show-toplevel)" +# SCORECARD_REPO names the repository holding when this script was extracted +# from it (a copy outside any checkout). +repo="${SCORECARD_REPO:-$(git -C "$here" rev-parse --show-toplevel)}" ws="$target/services/flysim/Cargo.toml" task="$target/services/flysim/crates/fly-legacy-session/src/task.rs" From d7547085e569821b192eecbee58c3699cd043699 Mon Sep 17 00:00:00 2001 From: acamilo Date: Thu, 1 Oct 2026 23:00:06 +0000 Subject: [PATCH 11/27] scorecard: ten brain minutes, four threads, two jobs: the cost the box can bear --- docs/scorecard.md | 19 +++++++++++-------- .../flysim/crates/fly-scorecard/src/main.rs | 8 ++++---- .../flysim/crates/fly-scorecard/src/tally.rs | 2 +- 3 files changed, 16 insertions(+), 13 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index b3e4227..58dc3bd 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -15,7 +15,7 @@ export FLY_ROM=/path/to/the-cartridge # read, never copied cargo build --release -p fly-scorecard # from services/flysim fly-scorecard list # the set, resolved, each checkpoint's rung -fly-scorecard suite --label v0.7.5 --out card.json # the set x 3 seeds x 12 brain minutes +fly-scorecard suite --label v0.7.5 --out card.json # the set x 3 seeds x 10 brain minutes fly-scorecard summary card.json # one screen of markdown fly-scorecard compare old.json new.json # exit 1 when a metric regressed fly-scorecard run-one --checkpoint X --seed 1 # one run, JSON out (--out FILE) @@ -70,7 +70,7 @@ One `RunReport` per (checkpoint, seed). Every number is computed from per-frame The watchdog's rules are the shell's: the same thresholds, the same order, the same two-probe memory for the zero-progress, unrewarded and unwon-battle rules. Two things differ, both about time: a run is short, so the probe cadence is a parameter (default every 120 brain seconds, -first at 300; the stream's is five wall minutes) and the window is the last ten brain minutes or +first at 240; the stream's is five wall minutes) and the window is the last ten brain minutes or the whole run when it is shorter; and the first probe compares the exploration count with the run's starting count, which the live check lacks after a boot. @@ -94,17 +94,20 @@ minute are reported, never judged: healing more can follow losing more. ## Cost and size -A brain minute is about 25 wall seconds on a 5-thread session run on the build box (the legacy -loop is about a quarter faster). The default suite, twelve checkpoints by three seeds by twelve -brain minutes, is 432 brain minutes: two runs at a time, five threads each, on ten cores, a little -over an hour. More seeds tighten the test; longer runs let rungs climb. Three seeds of twelve -minutes is the smallest suite whose pair count (36) can reach p < 0.001. +On the ten-core build box a session run costs about 15 to 20 wall seconds per brain minute of +throughput, whatever the split: one job of five threads, two of four and three of three were +within 20% of each other (two jobs of four threads was best, and is the default; the legacy loop +is about a quarter faster). The default suite, twelve checkpoints by three seeds by ten brain +minutes, is 360 brain minutes: about an hour and a half on a quiet box. The box is shared: a +compile storm beside it triples the wall time and changes no number. More seeds tighten the +test; longer runs let rungs climb. Three seeds is the smallest suite whose pair count (36) can +reach p < 0.001. ## What it does not do - It does not rebuild session ledgers a restore starts empty (the trap hunt's `FLY_TRAP_SEED_*`); a trap that needs them is that tool's. -- Twelve brain minutes rarely climb two rungs. Rungs per hour is a rate over many runs, not a +- Ten brain minutes rarely climb two rungs. Rungs per hour is a rate over many runs, not a per-run prediction; a release that is faster by a rung every few hours shows only across the suite. - It judges play against the previous release, not against a notion of good. A regression is diff --git a/services/flysim/crates/fly-scorecard/src/main.rs b/services/flysim/crates/fly-scorecard/src/main.rs index 216068a..6bd378d 100644 --- a/services/flysim/crates/fly-scorecard/src/main.rs +++ b/services/flysim/crates/fly-scorecard/src/main.rs @@ -50,13 +50,13 @@ enum Cmd { checkpoint: PathBuf, #[arg(long, default_value_t = 1)] seed: u32, - #[arg(long, default_value_t = 12.0)] + #[arg(long, default_value_t = 10.0)] minutes: f64, #[arg(long, default_value = "session")] runtime: String, #[arg(long, default_value = "macros")] mode: String, - #[arg(long, default_value_t = 5)] + #[arg(long, default_value_t = 4)] threads: usize, #[arg(long, default_value_t = 120.0)] probe_s: f64, @@ -80,14 +80,14 @@ enum Cmd { /// Seeds 1..=K. #[arg(long, default_value_t = 3)] seeds: u32, - #[arg(long, default_value_t = 12.0)] + #[arg(long, default_value_t = 10.0)] minutes: f64, #[arg(long, default_value = "session")] runtime: String, #[arg(long, default_value = "macros")] mode: String, /// Sweep threads per run. - #[arg(long, default_value_t = 5)] + #[arg(long, default_value_t = 4)] threads: usize, /// Runs at a time. #[arg(long, default_value_t = 2)] diff --git a/services/flysim/crates/fly-scorecard/src/tally.rs b/services/flysim/crates/fly-scorecard/src/tally.rs index 82e6da9..54d585e 100644 --- a/services/flysim/crates/fly-scorecard/src/tally.rs +++ b/services/flysim/crates/fly-scorecard/src/tally.rs @@ -35,7 +35,7 @@ pub struct TallyConfig { impl Default for TallyConfig { fn default() -> Self { - Self { rules: Rules::default(), probe_s: 120.0, first_probe_s: 300.0 } + Self { rules: Rules::default(), probe_s: 120.0, first_probe_s: 240.0 } } } From 3181c5ef7b4a95c4049748515f1c69d5c3a889d8 Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 00:10:39 +0000 Subject: [PATCH 12/27] scorecard: one thread per run and eight runs at a time, and --resume --- docs/scorecard.md | 18 +++---- .../flysim/crates/fly-scorecard/src/main.rs | 47 ++++++++++++++++--- 2 files changed, 51 insertions(+), 14 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 58dc3bd..b751554 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -94,14 +94,16 @@ minute are reported, never judged: healing more can follow losing more. ## Cost and size -On the ten-core build box a session run costs about 15 to 20 wall seconds per brain minute of -throughput, whatever the split: one job of five threads, two of four and three of three were -within 20% of each other (two jobs of four threads was best, and is the default; the legacy loop -is about a quarter faster). The default suite, twelve checkpoints by three seeds by ten brain -minutes, is 360 brain minutes: about an hour and a half on a quiet box. The box is shared: a -compile storm beside it triples the wall time and changes no number. More seeds tighten the -test; longer runs let rungs climb. Three seeds is the smallest suite whose pair count (36) can -reach p < 0.001. +A run's brain minute costs about 75 CPU seconds however it is split, and the result does not +depend on the thread count (the same seed gives an identical report at one thread and at four). +The split matters for wall time, because a run's sweep pool spins at its barriers: on a quiet +ten-core box two jobs of four threads are fine, but on a box shared with compiles and tests one +job of four threads ran five times slower per brain minute than one-thread jobs did. So the +default is one thread per run and eight runs at a time. The default suite, twelve checkpoints by +three seeds by ten brain minutes, is 360 brain minutes: about three quarters of an hour of ten +quiet cores, about twice that when the box is busy. More seeds tighten the test; longer runs let +rungs climb. Three seeds is the smallest suite whose pair count (36) can reach p < 0.001. +`--resume` keeps the runs an interrupted suite had finished (`.runs.jsonl`). ## What it does not do diff --git a/services/flysim/crates/fly-scorecard/src/main.rs b/services/flysim/crates/fly-scorecard/src/main.rs index 6bd378d..ccebc8b 100644 --- a/services/flysim/crates/fly-scorecard/src/main.rs +++ b/services/flysim/crates/fly-scorecard/src/main.rs @@ -21,6 +21,7 @@ use flysim::snapshot::MacroMode; use fly_scorecard::compare::compare; use fly_scorecard::runner::{Runtime, RunSpec, build_info, run_legacy, run_session}; +use fly_scorecard::tally::RunReport; use fly_scorecard::suite::{ CheckpointSet, ChildArgs, Job, SCHEMA, SuiteConfig, SuiteReport, note, run_jobs, }; @@ -56,7 +57,7 @@ enum Cmd { runtime: String, #[arg(long, default_value = "macros")] mode: String, - #[arg(long, default_value_t = 4)] + #[arg(long, default_value_t = 1)] threads: usize, #[arg(long, default_value_t = 120.0)] probe_s: f64, @@ -86,11 +87,13 @@ enum Cmd { runtime: String, #[arg(long, default_value = "macros")] mode: String, - /// Sweep threads per run. - #[arg(long, default_value_t = 4)] + /// Sweep threads per run. One: a run's pool spins at its barriers, so on a box shared with + /// other jobs one-thread runs lose far less than four-thread ones, and the result does + /// not depend on the count. + #[arg(long, default_value_t = 1)] threads: usize, /// Runs at a time. - #[arg(long, default_value_t = 2)] + #[arg(long, default_value_t = 8)] jobs: usize, #[arg(long, default_value_t = 120.0)] probe_s: f64, @@ -109,6 +112,9 @@ enum Cmd { /// Fail instead of running a smaller set when a checkpoint of the set is missing. #[arg(long)] strict: bool, + /// Keep the runs an earlier invocation finished (`.runs.jsonl`) and run the rest. + #[arg(long)] + resume: bool, }, /// Release A against release B. Exit 1 when a metric regressed. Compare { @@ -258,7 +264,7 @@ fn real_main() -> Result<()> { } Cmd::Suite { set, extra, only, seeds, minutes, runtime, mode, threads, jobs, probe_s, window_s, label, out, md, - dataset, strict, + dataset, strict, resume, } => { Runtime::parse(&runtime)?; mode_of(&mode)?; @@ -266,12 +272,33 @@ fn real_main() -> Result<()> { let resolved = resolve(&set, &extra, &only, strict)?; let exe = std::env::current_exe().context("finding this executable")?; let seed_list: Vec = (1..=seeds).collect(); + // Every finished run is appended to `.runs.jsonl` at once, so a suite that dies + // (a box that reboots, a job that is killed) keeps what it finished. + let runs_log = out.with_extension("runs.jsonl"); + let mut prior: Vec = Vec::new(); + if resume { + if let Ok(text) = std::fs::read_to_string(&runs_log) { + prior = text + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .filter(|run| run.runtime == runtime && run.mode == mode && run.minutes >= minutes - 0.01) + .collect(); + } + } else { + let _ = std::fs::remove_file(&runs_log); + } let mut queue = Vec::new(); for r in &resolved { for seed in &seed_list { + if prior.iter().any(|run| run.checkpoint == r.id && run.seed == *seed) { + continue; + } queue.push(Job { id: r.id.clone(), path: r.path.clone(), seed: *seed }); } } + if !prior.is_empty() { + eprintln!("scorecard: resuming with {} finished runs, {} to go", prior.len(), queue.len()); + } let child = ChildArgs { runtime: runtime.clone(), mode: mode.clone(), @@ -304,8 +331,13 @@ fn real_main() -> Result<()> { }; eprintln!("{line}"); note(&progress, &line); + if let Ok(run) = outcome + && let Ok(text) = serde_json::to_string(run) + { + note(&runs_log, &text); + } }); - let mut runs = Vec::new(); + let mut runs = prior; let mut failed_runs = Vec::new(); for outcome in outcomes { match outcome { @@ -313,6 +345,9 @@ fn real_main() -> Result<()> { Err(failed) => failed_runs.push(failed), } } + let order: BTreeMap<&str, usize> = + resolved.iter().enumerate().map(|(i, r)| (r.id.as_str(), i)).collect(); + runs.sort_by_key(|run| (order.get(run.checkpoint.as_str()).copied().unwrap_or(usize::MAX), run.seed)); let suite = SuiteReport { schema: SCHEMA.to_owned(), label, From ae052214951ec5b3a337f29f32f7949c7b274eb9 Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 01:55:13 +0000 Subject: [PATCH 13/27] scorecard: the v0.7.5 reference card and what it shows; the hunt's windows are reported, not judged --- docs/scorecard.md | 41 +++++++++++++++++-- .../crates/fly-scorecard/src/compare.rs | 10 +++-- .../flysim/crates/fly-scorecard/src/suite.rs | 17 ++++++++ tools/scorecard/baseline-v0.7.5.json | 1 + 4 files changed, 62 insertions(+), 7 deletions(-) create mode 100644 tools/scorecard/baseline-v0.7.5.json diff --git a/docs/scorecard.md b/docs/scorecard.md index b751554..dbff0e2 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -88,9 +88,12 @@ comparison also names its caveats (different lengths, different runtimes, fewer pairs, unpaired runs). Exit status 1 is a failed metric. The metrics: rungs per hour, places per hour, empty pad %, suspected probes %, ladder events per -hour, hunt windows flagged %, rollbacks per hour, blocked macro %, buy ball, throws and catches -per hour, battles won and lost per hour, whiteouts per hour. Heals per hour and macro starts per -minute are reported, never judged: healing more can follow losing more. +hour, rollbacks per hour, blocked macro %, buy ball, throws and catches per hour, battles won and +lost per hour, whiteouts per hour. Heals per hour, macro starts per minute and the trap hunt's +flagged windows are reported, never judged: healing more can follow losing more, and a fly that +fights for most of a run presses NEXT through battle text more than ten times in two minutes, +which the hunt reads as a repeated sequence (nine windows in ten are flagged on the baseline, so +the number has no room to move). ## Cost and size @@ -123,4 +126,34 @@ predates it can be scored and its numbers are its own. The operator's nightly ru latest release tag on a build box, runs the suite, writes the card and a one-screen summary and compares with the previous release's card. -`tools/scorecard/baseline-v0.7.5.json` is the reference card of v0.7.5 (adapter v8). +## The v0.7.5 baseline + +`tools/scorecard/baseline-v0.7.5.json` is the reference card of v0.7.5 (adapter v8, +compatibility `ff09d7dd5483`): the default set, 12 checkpoints by 3 seeds by 10 brain minutes on +the session runtime, 6.0 brain hours, 6,130 s wall on a shared build box. + +| headline | v0.7.5 | +| --- | ---: | +| rungs per brain hour | 1.50 (9 of 36 runs climbed) | +| empty-pad time | 6.96% of frames | +| watchdog probes suspected | 2.8% | +| ladder-worthy traps | 1 (one run, `r09-forest-catch`) | +| blocked macro finishes | 0.5% | +| buy ball / throw / catch | 10 / 10 / 8 | +| heals / whiteouts | 9 / 46 | +| battles won / lost | 33 / 45 | +| ratchet rollbacks | 1 | + +What the card shows about v0.7.5, worth reading before the next release is compared with it: + +- **The fly fights for most of the frames it is given.** On nine of the twelve checkpoints a + battle is half to nine tenths of the frames, and it loses more than it wins (45 lost, 33 won; + 46 whiteouts). The longest single battle is 18,354 frames (five brain minutes, a trainer, on + `r11-mart`); `r09-forest-catch` has one of 26,245 frames in a wild battle. +- **`r15-nugget-bridge` keeps walking and finds nothing.** After the Oddish is caught (all three + seeds), the fly spends the rest of the run in the overworld, GO OBJECTIVE and GO OUT + alternating 13 times each in ten minutes, with the exploration count unmoved (2,527). The + watchdog does not flag it (a ring this slow stays under its twenty repeats), so no recovery + step would act on it. +- The shop-to-catch funnel closes: buy ball, throw and catch all occur, across rungs 9 to 15. + diff --git a/services/flysim/crates/fly-scorecard/src/compare.rs b/services/flysim/crates/fly-scorecard/src/compare.rs index 41a5dfe..7bc5c92 100644 --- a/services/flysim/crates/fly-scorecard/src/compare.rs +++ b/services/flysim/crates/fly-scorecard/src/compare.rs @@ -90,12 +90,16 @@ pub const METRICS: &[Metric] = &[ rel_tol: 0.25, read: |r| per_hour(r.watchdog.ladder_events as f64, r), }, + // The trap hunt's windows are reported, not judged: a fly that fights for most of a run + // presses NEXT through battle text more than ten times in two minutes, which that instrument + // reads as a repeated sequence, so on these checkpoints nine windows in ten are flagged and + // the number has no room to move. The watchdog's rules above are the judged ones. Metric { name: "hunt_flagged_pct", unit: "% of windows", - direction: Direction::Down, - abs_tol: 5.0, - rel_tol: 0.25, + direction: Direction::Info, + abs_tol: 0.0, + rel_tol: 0.0, read: |r| pct(r.hunt.flagged as f64, r.hunt.windows as f64), }, Metric { diff --git a/services/flysim/crates/fly-scorecard/src/suite.rs b/services/flysim/crates/fly-scorecard/src/suite.rs index 4f779db..52c7c3d 100644 --- a/services/flysim/crates/fly-scorecard/src/suite.rs +++ b/services/flysim/crates/fly-scorecard/src/suite.rs @@ -392,6 +392,23 @@ mod tests { assert!(set.checkpoints.iter().all(|e| (8..=15).contains(&e.rung))); } + #[test] + fn the_committed_baseline_is_a_valid_card_and_passes_against_itself() { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../../tools/scorecard/baseline-v0.7.5.json"); + let card = SuiteReport::load(&path).expect("the reference card"); + assert_eq!(card.label, "v0.7.5"); + assert_eq!(card.build.adapter, "pokered-unique8-v8"); + assert_eq!(card.runs.len(), 36); + assert!(card.failed_runs.is_empty()); + assert!(card.runs.iter().all(|run| run.frames > 30_000 && run.minutes >= 10.0)); + let comparison = crate::compare::compare(&card, &card, 0.05); + assert!(comparison.pass, "{:?}", comparison.failed); + assert_eq!(comparison.pairs, 36); + // Nothing in a public card names a path or a host. + let text = std::fs::read_to_string(&path).unwrap(); + assert!(!text.contains("/home/") && !text.contains("192.168")); + } + #[test] fn a_suite_round_trips_and_summarises() { let mut run = RunReport { diff --git a/tools/scorecard/baseline-v0.7.5.json b/tools/scorecard/baseline-v0.7.5.json new file mode 100644 index 0000000..77498b3 --- /dev/null +++ b/tools/scorecard/baseline-v0.7.5.json @@ -0,0 +1 @@ +{"schema":"fly-scorecard-v1","label":"v0.7.5","build":{"release":"v0.7.5","adapter":"pokered-unique8-v8","compatibility_sha":"ff09d7dd5483"},"runtime":"session","mode":"macros","config":{"minutes":10.0,"seeds":[1,2,3],"threads":1,"jobs":8,"probe_s":120.0,"window_s":600.0},"runs":[{"checkpoint":"r08-viridian-city","seed":1,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":1306,"wall_seconds":1741.282509168,"rungs":{"start":8,"end":9,"gained":1,"climbs":[[9,9.11055]]},"places_start":313,"places_end":540,"pad":{"empty_frames":1608,"empty_seconds":26.922271728515625,"empty_fraction":0.04486857525531559,"longest_empty_seconds":2.2435226440429688},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":19,"first_flagged":[{"at_min":0.0,"tiles":102,"macros":93,"cycle":["NEXT",14]},{"at_min":0.25,"tiles":91,"macros":89,"cycle":["NEXT",14]},{"at_min":0.5,"tiles":77,"macros":86,"cycle":["NEXT",14]},{"at_min":0.75,"tiles":78,"macros":80,"cycle":["NEXT",14]},{"at_min":4.5,"tiles":78,"macros":109,"cycle":["NEXT",13]},{"at_min":4.75,"tiles":78,"macros":108,"cycle":["NEXT",13]},{"at_min":5.0,"tiles":96,"macros":103,"cycle":["NEXT",13]},{"at_min":5.25,"tiles":133,"macros":87,"cycle":["NEXT",13]},{"at_min":5.5,"tiles":157,"macros":75,"cycle":["NEXT",13]},{"at_min":5.75,"tiles":150,"macros":80,"cycle":["NEXT",13]},{"at_min":6.0,"tiles":118,"macros":94,"cycle":["NEXT",13]},{"at_min":6.25,"tiles":82,"macros":113,"cycle":["NEXT",16]},{"at_min":6.5,"tiles":84,"macros":113,"cycle":["NEXT",16]},{"at_min":6.75,"tiles":84,"macros":113,"cycle":["NEXT",16]},{"at_min":7.0,"tiles":84,"macros":113,"cycle":["NEXT",16]},{"at_min":7.25,"tiles":66,"macros":119,"cycle":["NEXT",16]},{"at_min":7.5,"tiles":79,"macros":112,"cycle":["NEXT",16]},{"at_min":7.75,"tiles":91,"macros":105,"cycle":["NEXT",16]},{"at_min":8.0,"tiles":91,"macros":106,"cycle":["NEXT",16]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":435,"done":433,"blocked":1,"timeout":0,"refused":0,"by_macro":{"GO FRONTIER":{"start":35,"done":34,"blocked":1,"timeout":0,"refused":0},"GO ITEM":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"GO NPC":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":34,"done":34,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"GO SHOP":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO WARP":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"MOVE 1":{"start":14,"done":14,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":271,"done":270,"blocked":0,"timeout":0,"refused":0},"NO":{"start":29,"done":29,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"YES":{"start":26,"done":26,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":2,"go_shop_done":2,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":1},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":0,"heal_done":0},"whiteouts":1,"battles":{"started":5,"ended":4,"wild":5,"trainer":0,"won":3,"lost":1,"caught":0,"other":0,"longest_frames":2951,"still_running":true,"macros_in_longest":62},"rewards":{"battle":{"n":3,"total":0.30000000000000004},"boundary":{"n":15,"total":1.1000000000000003},"damage":{"n":14,"total":0.8586466165413533},"exploration":{"n":27,"total":1.3500000000000005},"map":{"n":4,"total":0.8},"milestone":{"n":3,"total":3.0},"talk":{"n":3,"total":0.30000000000000004}},"scenes":{"battle":10472,"dialog":5608,"overworld":17971,"unknown":1787},"ended_map":51},{"checkpoint":"r08-viridian-city","seed":2,"runtime":"session","mode":"macros","minutes":10.000133333333334,"frames":35838,"idle_frames":835,"wall_seconds":1771.572439235,"rungs":{"start":8,"end":9,"gained":1,"climbs":[[9,6.099083333333334]]},"places_start":313,"places_end":601,"pad":{"empty_frames":1363,"empty_seconds":22.820308685302734,"empty_fraction":0.038032256264300464,"longest_empty_seconds":2.260265350341797},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":22,"first_flagged":[{"at_min":2.75,"tiles":49,"macros":119,"cycle":["NEXT",14]},{"at_min":3.0,"tiles":46,"macros":126,"cycle":["NEXT",14]},{"at_min":3.25,"tiles":52,"macros":125,"cycle":["NEXT",14]},{"at_min":3.5,"tiles":88,"macros":108,"cycle":["NEXT",14]},{"at_min":3.75,"tiles":126,"macros":91,"cycle":["NEXT",14]},{"at_min":4.0,"tiles":164,"macros":72,"cycle":["NEXT",14]},{"at_min":4.25,"tiles":180,"macros":66,"cycle":["NEXT",14]},{"at_min":4.5,"tiles":153,"macros":78,"cycle":["NEXT",13]},{"at_min":4.75,"tiles":153,"macros":79,"cycle":["NEXT",13]},{"at_min":5.0,"tiles":153,"macros":78,"cycle":["NEXT",13]},{"at_min":5.25,"tiles":168,"macros":70,"cycle":["NEXT",15]},{"at_min":5.5,"tiles":169,"macros":69,"cycle":["NEXT",15]},{"at_min":5.75,"tiles":166,"macros":67,"cycle":["NEXT",15]},{"at_min":6.0,"tiles":128,"macros":84,"cycle":["NEXT",17]},{"at_min":6.25,"tiles":96,"macros":98,"cycle":["NEXT",18]},{"at_min":6.5,"tiles":94,"macros":99,"cycle":["NEXT",18]},{"at_min":6.75,"tiles":94,"macros":98,"cycle":["NEXT",18]},{"at_min":7.0,"tiles":110,"macros":90,"cycle":["NEXT",18]},{"at_min":7.25,"tiles":123,"macros":83,"cycle":["NEXT",18]},{"at_min":7.5,"tiles":101,"macros":94,"cycle":["NEXT",18]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":452,"done":452,"blocked":0,"timeout":0,"refused":1,"by_macro":{"GO FRONTIER":{"start":18,"done":18,"blocked":0,"timeout":0,"refused":0},"GO NPC":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":21,"done":21,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":6,"done":6,"blocked":0,"timeout":0,"refused":1},"GO SHOP":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"GO WARP":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"HEAL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"MOVE 1":{"start":17,"done":17,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":306,"done":306,"blocked":0,"timeout":0,"refused":0},"NO":{"start":37,"done":37,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"YES":{"start":32,"done":32,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":3,"go_shop_done":3,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":1},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":1,"heal_done":1},"whiteouts":1,"battles":{"started":4,"ended":4,"wild":3,"trainer":1,"won":3,"lost":1,"caught":0,"other":0,"longest_frames":3852,"still_running":false,"macros_in_longest":78},"rewards":{"battle":{"n":3,"total":0.30000000000000004},"boundary":{"n":15,"total":1.1000000000000003},"damage":{"n":15,"total":0.7185185185185186},"exploration":{"n":34,"total":1.7000000000000008},"map":{"n":4,"total":0.8},"milestone":{"n":3,"total":3.0},"talk":{"n":4,"total":0.4}},"scenes":{"battle":11657,"dialog":7370,"overworld":15225,"unknown":1586},"ended_map":13},{"checkpoint":"r08-viridian-city","seed":3,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":883,"wall_seconds":1792.518225502,"rungs":{"start":8,"end":9,"gained":1,"climbs":[[9,5.093416666666666]]},"places_start":313,"places_end":609,"pad":{"empty_frames":1633,"empty_seconds":27.340839385986328,"empty_fraction":0.04556615882582733,"longest_empty_seconds":2.2435226440429688},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":27,"first_flagged":[{"at_min":0.0,"tiles":118,"macros":93,"cycle":["NEXT",16]},{"at_min":0.25,"tiles":100,"macros":101,"cycle":["NEXT",16]},{"at_min":0.5,"tiles":77,"macros":109,"cycle":["NEXT",16]},{"at_min":0.75,"tiles":52,"macros":120,"cycle":["NEXT",16]},{"at_min":2.5,"tiles":151,"macros":78,"cycle":["NEXT",14]},{"at_min":2.75,"tiles":151,"macros":78,"cycle":["NEXT",14]},{"at_min":3.0,"tiles":168,"macros":71,"cycle":["NEXT",14]},{"at_min":3.25,"tiles":203,"macros":54,"cycle":["NEXT",14]},{"at_min":3.5,"tiles":205,"macros":51,"cycle":["NEXT",14]},{"at_min":3.75,"tiles":207,"macros":51,"cycle":["NEXT",14]},{"at_min":4.0,"tiles":185,"macros":57,"cycle":["NEXT",14]},{"at_min":4.25,"tiles":147,"macros":75,"cycle":["NEXT",17]},{"at_min":4.5,"tiles":143,"macros":76,"cycle":["NEXT",17]},{"at_min":4.75,"tiles":143,"macros":75,"cycle":["NEXT",17]},{"at_min":5.0,"tiles":126,"macros":83,"cycle":["NEXT",17]},{"at_min":5.25,"tiles":91,"macros":99,"cycle":["NEXT",17]},{"at_min":5.5,"tiles":57,"macros":116,"cycle":["NEXT",17]},{"at_min":5.75,"tiles":49,"macros":120,"cycle":["NEXT",17]},{"at_min":6.0,"tiles":33,"macros":132,"cycle":["NEXT",13]},{"at_min":6.25,"tiles":33,"macros":131,"cycle":["NEXT",13]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":448,"done":447,"blocked":0,"timeout":0,"refused":0,"by_macro":{"GO FRONTIER":{"start":15,"done":15,"blocked":0,"timeout":0,"refused":0},"GO HEAL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO NPC":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":26,"done":26,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO SHOP":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"GO WARP":{"start":2,"done":1,"blocked":0,"timeout":0,"refused":0},"HEAL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"MOVE 1":{"start":17,"done":17,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":307,"done":307,"blocked":0,"timeout":0,"refused":0},"NO":{"start":36,"done":36,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"YES":{"start":27,"done":27,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":3,"go_shop_done":3,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":1},"heals":{"go_heal_start":1,"go_heal_done":1,"heal_start":1,"heal_done":1},"whiteouts":2,"battles":{"started":4,"ended":4,"wild":3,"trainer":1,"won":2,"lost":2,"caught":0,"other":0,"longest_frames":5532,"still_running":false,"macros_in_longest":112},"rewards":{"battle":{"n":2,"total":0.2},"boundary":{"n":14,"total":1.0000000000000002},"damage":{"n":16,"total":0.617777777777778},"exploration":{"n":36,"total":1.800000000000001},"map":{"n":4,"total":0.8},"milestone":{"n":3,"total":3.0},"talk":{"n":4,"total":0.4}},"scenes":{"battle":11847,"dialog":6905,"overworld":15249,"unknown":1837},"ended_map":51},{"checkpoint":"r09-viridian-mart","seed":1,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":1306,"wall_seconds":1822.196384669,"rungs":{"start":9,"end":9,"gained":0,"climbs":[]},"places_start":638,"places_end":742,"pad":{"empty_frames":1953,"empty_seconds":32.69850540161133,"empty_fraction":0.0544952285283777,"longest_empty_seconds":13.260223388671875},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":71,"macros":91,"cycle":["NEXT",26]},{"at_min":0.25,"tiles":68,"macros":102,"cycle":["NEXT",26]},{"at_min":0.5,"tiles":32,"macros":117,"cycle":["NEXT",26]},{"at_min":0.75,"tiles":34,"macros":117,"cycle":["NEXT",26]},{"at_min":1.0,"tiles":71,"macros":98,"cycle":["NEXT",26]},{"at_min":1.25,"tiles":108,"macros":80,"cycle":["NEXT",20]},{"at_min":1.5,"tiles":123,"macros":72,"cycle":["NEXT",13]},{"at_min":1.75,"tiles":121,"macros":89,"cycle":["NEXT",13]},{"at_min":2.0,"tiles":120,"macros":89,"cycle":["NEXT",13]},{"at_min":2.25,"tiles":139,"macros":80,"cycle":["NEXT",15]},{"at_min":2.5,"tiles":139,"macros":79,"cycle":["NEXT",15]},{"at_min":2.75,"tiles":109,"macros":90,"cycle":["NEXT",15]},{"at_min":3.0,"tiles":72,"macros":109,"cycle":["NEXT",18]},{"at_min":3.25,"tiles":35,"macros":127,"cycle":["NEXT",18]},{"at_min":3.5,"tiles":53,"macros":118,"cycle":["NEXT",18]},{"at_min":3.75,"tiles":67,"macros":112,"cycle":["NEXT",18]},{"at_min":4.0,"tiles":67,"macros":112,"cycle":["NEXT",18]},{"at_min":4.25,"tiles":48,"macros":121,"cycle":["NEXT",18]},{"at_min":4.5,"tiles":48,"macros":123,"cycle":["NEXT",18]},{"at_min":4.75,"tiles":56,"macros":118,"cycle":["NEXT",16]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":478,"done":475,"blocked":2,"timeout":0,"refused":1,"by_macro":{"BACK":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"BUY BALL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"CONFIRM":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO FRONTIER":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"GO ITEM":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO NPC":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":10,"done":10,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":4,"done":3,"blocked":1,"timeout":0,"refused":1},"GO SHOP":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO WARP":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"LEAVE":{"start":2,"done":1,"blocked":1,"timeout":0,"refused":0},"MOVE 1":{"start":21,"done":21,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":417,"done":416,"blocked":0,"timeout":0,"refused":0},"NO":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"SWITCH":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"THROW BALL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":1,"go_shop_done":1,"buy_ball_start":1,"buy_ball_done":1,"throw_ball_start":1,"throw_ball_done":1,"catches":1,"species_gained":1,"balls_gained":1,"balls_spent":1,"depth":1},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":0,"heal_done":0},"whiteouts":1,"battles":{"started":8,"ended":7,"wild":6,"trainer":2,"won":5,"lost":1,"caught":1,"other":0,"longest_frames":3763,"still_running":true,"macros_in_longest":62},"rewards":{"battle":{"n":5,"total":0.5},"boundary":{"n":6,"total":0.45},"catch":{"n":1,"total":0.1},"damage":{"n":19,"total":1.152982456140351},"exploration":{"n":13,"total":0.65},"map":{"n":1,"total":0.2},"species":{"n":1,"total":0.5}},"scenes":{"battle":21342,"battle-switch":42,"dialog":286,"overworld":11729,"shop":486,"unknown":1953},"ended_map":51},{"checkpoint":"r09-viridian-mart","seed":2,"runtime":"session","mode":"macros","minutes":10.000133333333334,"frames":35838,"idle_frames":835,"wall_seconds":1781.891459443,"rungs":{"start":9,"end":9,"gained":0,"climbs":[]},"places_start":638,"places_end":717,"pad":{"empty_frames":713,"empty_seconds":11.937549591064453,"empty_fraction":0.019895083430995032,"longest_empty_seconds":2.1095809936523438},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":122,"macros":85,"cycle":["NEXT",14]},{"at_min":0.25,"tiles":108,"macros":94,"cycle":["NEXT",14]},{"at_min":0.5,"tiles":91,"macros":106,"cycle":["NEXT",14]},{"at_min":0.75,"tiles":124,"macros":91,"cycle":["NEXT",14]},{"at_min":1.0,"tiles":130,"macros":88,"cycle":["NEXT",14]},{"at_min":1.25,"tiles":118,"macros":92,"cycle":["NEXT",14]},{"at_min":1.5,"tiles":83,"macros":110,"cycle":["NEXT",14]},{"at_min":1.75,"tiles":50,"macros":124,"cycle":["NEXT",14]},{"at_min":2.0,"tiles":50,"macros":124,"cycle":["NEXT",14]},{"at_min":2.25,"tiles":50,"macros":124,"cycle":["NEXT",14]},{"at_min":2.5,"tiles":44,"macros":127,"cycle":["NEXT",14]},{"at_min":2.75,"tiles":11,"macros":142,"cycle":["NEXT",14]},{"at_min":3.0,"tiles":5,"macros":145,"cycle":["NEXT",14]},{"at_min":3.25,"tiles":9,"macros":145,"cycle":["NEXT",14]},{"at_min":3.5,"tiles":33,"macros":132,"cycle":["NEXT",14]},{"at_min":3.75,"tiles":33,"macros":133,"cycle":["NEXT",14]},{"at_min":4.0,"tiles":33,"macros":133,"cycle":["NEXT",13]},{"at_min":4.25,"tiles":33,"macros":132,"cycle":["NEXT",13]},{"at_min":4.5,"tiles":62,"macros":118,"cycle":["NEXT",13]},{"at_min":4.75,"tiles":76,"macros":112,"cycle":["NEXT",13]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":604,"done":604,"blocked":0,"timeout":0,"refused":0,"by_macro":{"CONFIRM":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO FRONTIER":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":11,"done":11,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO SHOP":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"LEAVE":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"MOVE 1":{"start":35,"done":35,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":9,"done":9,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":539,"done":539,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":1,"go_shop_done":1,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":1},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":0,"heal_done":0},"whiteouts":0,"battles":{"started":7,"ended":6,"wild":6,"trainer":1,"won":6,"lost":0,"caught":0,"other":0,"longest_frames":7430,"still_running":true,"macros_in_longest":117},"rewards":{"battle":{"n":6,"total":0.5000000000000001},"boundary":{"n":6,"total":0.44999999999999996},"damage":{"n":33,"total":1.0835978835978837},"exploration":{"n":9,"total":0.44999999999999996},"map":{"n":1,"total":0.2}},"scenes":{"battle":28086,"dialog":188,"overworld":6614,"shop":238,"unknown":712},"ended_map":51},{"checkpoint":"r09-viridian-mart","seed":3,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":883,"wall_seconds":1776.245883734,"rungs":{"start":9,"end":10,"gained":1,"climbs":[[10,5.879766666666667]]},"places_start":638,"places_end":809,"pad":{"empty_frames":3225,"empty_seconds":53.9952278137207,"empty_fraction":0.08998828059601541,"longest_empty_seconds":24.779205322265625},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":32,"first_flagged":[{"at_min":0.0,"tiles":111,"macros":73,"cycle":["NEXT",25]},{"at_min":0.25,"tiles":108,"macros":66,"cycle":["NEXT",25]},{"at_min":0.5,"tiles":104,"macros":69,"cycle":["NEXT",26]},{"at_min":0.75,"tiles":110,"macros":66,"cycle":["NEXT",26]},{"at_min":1.0,"tiles":111,"macros":64,"cycle":["NEXT",26]},{"at_min":1.25,"tiles":140,"macros":49,"cycle":["NEXT",26]},{"at_min":1.5,"tiles":140,"macros":47,"cycle":["NEXT",26]},{"at_min":1.75,"tiles":140,"macros":47,"cycle":["NEXT",14]},{"at_min":2.0,"tiles":140,"macros":58,"cycle":["NEXT",14]},{"at_min":2.25,"tiles":140,"macros":76,"cycle":["NEXT",14]},{"at_min":2.5,"tiles":111,"macros":89,"cycle":["NEXT",14]},{"at_min":2.75,"tiles":73,"macros":107,"cycle":["NEXT",22]},{"at_min":3.0,"tiles":62,"macros":115,"cycle":["NEXT",28]},{"at_min":3.25,"tiles":38,"macros":128,"cycle":["NEXT",28]},{"at_min":3.5,"tiles":38,"macros":131,"cycle":["NEXT",28]},{"at_min":3.75,"tiles":38,"macros":130,"cycle":["NEXT",28]},{"at_min":4.0,"tiles":64,"macros":120,"cycle":["NEXT",28]},{"at_min":4.25,"tiles":86,"macros":105,"cycle":["NEXT",28]},{"at_min":4.5,"tiles":91,"macros":93,"cycle":["NEXT",24]},{"at_min":4.75,"tiles":92,"macros":90,"cycle":["NEXT",14]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":458,"done":458,"blocked":0,"timeout":0,"refused":1,"by_macro":{"BACK":{"start":12,"done":12,"blocked":0,"timeout":0,"refused":0},"BUY BALL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"CONFIRM":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO FRONTIER":{"start":14,"done":14,"blocked":0,"timeout":0,"refused":0},"GO HEAL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO NPC":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":13,"done":13,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":6,"done":6,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":1},"GO SHOP":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"HEAL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"LEAVE":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"MOVE 1":{"start":20,"done":20,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":340,"done":340,"blocked":0,"timeout":0,"refused":0},"NO":{"start":16,"done":16,"blocked":0,"timeout":0,"refused":0},"SWITCH":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"THROW BALL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"YES":{"start":14,"done":14,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":3,"go_shop_done":3,"buy_ball_start":1,"buy_ball_done":1,"throw_ball_start":1,"throw_ball_done":1,"catches":1,"species_gained":1,"balls_gained":1,"balls_spent":1,"depth":4},"heals":{"go_heal_start":1,"go_heal_done":1,"heal_start":1,"heal_done":1},"whiteouts":1,"battles":{"started":5,"ended":4,"wild":2,"trainer":3,"won":1,"lost":1,"caught":1,"other":1,"longest_frames":5344,"still_running":true,"macros_in_longest":110},"rewards":{"battle":{"n":1,"total":0.1},"boundary":{"n":22,"total":1.6500000000000008},"catch":{"n":1,"total":0.1},"damage":{"n":16,"total":0.734313725490196},"exploration":{"n":18,"total":0.9000000000000002},"map":{"n":6,"total":1.2},"species":{"n":1,"total":0.5},"talk":{"n":3,"total":0.30000000000000004},"trainer":{"n":1,"total":0.5}},"scenes":{"battle":16737,"battle-switch":118,"dialog":3437,"overworld":11868,"shop":483,"unknown":3195},"ended_map":54},{"checkpoint":"r09-forest-catch","seed":1,"runtime":"session","mode":"macros","minutes":10.000133333333334,"frames":35838,"idle_frames":1306,"wall_seconds":1810.909996418,"rungs":{"start":9,"end":9,"gained":0,"climbs":[]},"places_start":1906,"places_end":1906,"pad":{"empty_frames":2499,"empty_seconds":41.840023040771484,"empty_fraction":0.06973045370835426,"longest_empty_seconds":37.78828811645508},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":19,"macros":93,"cycle":["NEXT",27]},{"at_min":0.25,"tiles":19,"macros":93,"cycle":["NEXT",13]},{"at_min":0.5,"tiles":19,"macros":101,"cycle":["NEXT",13]},{"at_min":0.75,"tiles":19,"macros":119,"cycle":["NEXT",13]},{"at_min":1.0,"tiles":19,"macros":137,"cycle":["NEXT",13]},{"at_min":1.25,"tiles":1,"macros":144,"cycle":null},{"at_min":1.5,"tiles":1,"macros":144,"cycle":null},{"at_min":1.75,"tiles":1,"macros":144,"cycle":null},{"at_min":2.0,"tiles":1,"macros":144,"cycle":null},{"at_min":2.25,"tiles":1,"macros":144,"cycle":null},{"at_min":2.5,"tiles":1,"macros":145,"cycle":null},{"at_min":2.75,"tiles":1,"macros":145,"cycle":null},{"at_min":3.0,"tiles":1,"macros":145,"cycle":null},{"at_min":3.25,"tiles":1,"macros":147,"cycle":null},{"at_min":3.5,"tiles":1,"macros":145,"cycle":null},{"at_min":3.75,"tiles":1,"macros":146,"cycle":null},{"at_min":4.0,"tiles":1,"macros":146,"cycle":null},{"at_min":4.25,"tiles":1,"macros":146,"cycle":null},{"at_min":4.5,"tiles":1,"macros":145,"cycle":null},{"at_min":4.75,"tiles":1,"macros":146,"cycle":null}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":642,"done":641,"blocked":0,"timeout":0,"refused":0,"by_macro":{"BACK":{"start":58,"done":58,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":2,"done":1,"blocked":0,"timeout":0,"refused":0},"GO WARP":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"MOVE 1":{"start":73,"done":73,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":39,"done":39,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":466,"done":466,"blocked":0,"timeout":0,"refused":0},"THROW BALL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":0,"go_shop_done":0,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":1,"throw_ball_done":1,"catches":1,"species_gained":1,"balls_gained":0,"balls_spent":1,"depth":0},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":0,"heal_done":0},"whiteouts":1,"battles":{"started":4,"ended":4,"wild":4,"trainer":0,"won":0,"lost":1,"caught":1,"other":2,"longest_frames":26245,"still_running":false,"macros_in_longest":534},"rewards":{"catch":{"n":1,"total":0.1},"damage":{"n":2,"total":0.05333333333333334},"species":{"n":1,"total":0.5}},"scenes":{"battle":31193,"overworld":2145,"unknown":2500},"ended_map":12},{"checkpoint":"r09-forest-catch","seed":2,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":835,"wall_seconds":1740.121022569,"rungs":{"start":9,"end":9,"gained":0,"climbs":[]},"places_start":1906,"places_end":1912,"pad":{"empty_frames":874,"empty_seconds":14.633125305175781,"empty_fraction":0.024387521625090686,"longest_empty_seconds":2.2435226440429688},"watchdog":{"probes":4,"suspected":1,"confirmed":0,"ladder_events":0,"reasons":{"unrewarded":1},"flagged":[{"at_min":6.0,"suspected":true,"reason":"unrewarded","decisions":364,"distinct":10,"period":1,"repeats":8,"done":363,"failed":0,"rewards":0,"fights":20,"wins":0,"places_delta":0}]},"hunt":{"windows":33,"flagged":30,"first_flagged":[{"at_min":0.0,"tiles":88,"macros":106,"cycle":["NEXT",16]},{"at_min":0.25,"tiles":98,"macros":101,"cycle":["NEXT",13]},{"at_min":0.5,"tiles":101,"macros":99,"cycle":["NEXT",13]},{"at_min":0.75,"tiles":75,"macros":112,"cycle":["NEXT",13]},{"at_min":1.0,"tiles":75,"macros":112,"cycle":["NEXT",13]},{"at_min":1.25,"tiles":83,"macros":105,"cycle":["NEXT",13]},{"at_min":1.5,"tiles":83,"macros":105,"cycle":["NEXT",15]},{"at_min":1.75,"tiles":83,"macros":105,"cycle":["NEXT",15]},{"at_min":2.0,"tiles":47,"macros":122,"cycle":["NEXT",15]},{"at_min":2.25,"tiles":37,"macros":127,"cycle":["NEXT",15]},{"at_min":2.5,"tiles":29,"macros":131,"cycle":["NEXT",15]},{"at_min":2.75,"tiles":25,"macros":132,"cycle":["NEXT",15]},{"at_min":3.0,"tiles":9,"macros":140,"cycle":["NEXT",15]},{"at_min":3.25,"tiles":1,"macros":147,"cycle":["NEXT",12]},{"at_min":3.5,"tiles":1,"macros":146,"cycle":["NEXT",16]},{"at_min":3.75,"tiles":23,"macros":136,"cycle":["NEXT",17]},{"at_min":4.0,"tiles":23,"macros":136,"cycle":["NEXT",17]},{"at_min":4.25,"tiles":23,"macros":135,"cycle":["NEXT",17]},{"at_min":4.5,"tiles":51,"macros":121,"cycle":["NEXT",17]},{"at_min":4.75,"tiles":89,"macros":104,"cycle":["NEXT",17]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":430,"done":428,"blocked":0,"timeout":1,"refused":0,"by_macro":{"BACK":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"GO FRONTIER":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO HEAL":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":9,"done":7,"blocked":0,"timeout":1,"refused":0},"GO WARP":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"HEAL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"MOVE 1":{"start":6,"done":6,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":13,"done":13,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"MOVE 4":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":345,"done":345,"blocked":0,"timeout":0,"refused":0},"RUN":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"THROW BALL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"YES":{"start":35,"done":35,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":0,"go_shop_done":0,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":1,"throw_ball_done":1,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":1,"depth":0},"heals":{"go_heal_start":2,"go_heal_done":2,"heal_start":1,"heal_done":1},"whiteouts":1,"battles":{"started":7,"ended":7,"wild":6,"trainer":1,"won":0,"lost":1,"caught":0,"other":6,"longest_frames":8567,"still_running":false,"macros_in_longest":174},"rewards":{"damage":{"n":1,"total":0.18666666666666668},"exploration":{"n":1,"total":0.05},"talk":{"n":1,"total":0.1}},"scenes":{"battle":18243,"dialog":2146,"overworld":14581,"unknown":868},"ended_map":1},{"checkpoint":"r09-forest-catch","seed":3,"runtime":"session","mode":"macros","minutes":10.000133333333334,"frames":35838,"idle_frames":883,"wall_seconds":1181.610469782,"rungs":{"start":9,"end":9,"gained":0,"climbs":[]},"places_start":1906,"places_end":1908,"pad":{"empty_frames":740,"empty_seconds":12.389602661132812,"empty_fraction":0.02064847368714772,"longest_empty_seconds":2.2435226440429688},"watchdog":{"probes":4,"suspected":2,"confirmed":1,"ladder_events":1,"reasons":{"unrewarded":1,"unwon-battles":1},"flagged":[{"at_min":6.0,"suspected":true,"reason":"unrewarded","decisions":373,"distinct":8,"period":0,"repeats":0,"done":373,"failed":0,"rewards":0,"fights":32,"wins":0,"places_delta":0},{"at_min":8.0,"suspected":true,"reason":"unwon-battles","decisions":497,"distinct":11,"period":1,"repeats":13,"done":497,"failed":0,"rewards":1,"fights":40,"wins":0,"places_delta":0}]},"hunt":{"windows":33,"flagged":32,"first_flagged":[{"at_min":0.0,"tiles":115,"macros":94,"cycle":["NEXT",16]},{"at_min":0.25,"tiles":132,"macros":85,"cycle":["NEXT",13]},{"at_min":0.5,"tiles":132,"macros":83,"cycle":["NEXT",13]},{"at_min":0.75,"tiles":100,"macros":98,"cycle":["NEXT",15]},{"at_min":1.0,"tiles":90,"macros":103,"cycle":["NEXT",15]},{"at_min":1.25,"tiles":85,"macros":105,"cycle":["NEXT",15]},{"at_min":1.5,"tiles":48,"macros":122,"cycle":["NEXT",15]},{"at_min":1.75,"tiles":38,"macros":126,"cycle":["NEXT",15]},{"at_min":2.0,"tiles":20,"macros":134,"cycle":["NEXT",15]},{"at_min":2.25,"tiles":3,"macros":142,"cycle":["NEXT",15]},{"at_min":2.5,"tiles":1,"macros":145,"cycle":["NEXT",12]},{"at_min":2.75,"tiles":1,"macros":146,"cycle":["NEXT",12]},{"at_min":3.0,"tiles":1,"macros":144,"cycle":["NEXT",12]},{"at_min":3.25,"tiles":1,"macros":145,"cycle":["NEXT",12]},{"at_min":3.5,"tiles":1,"macros":145,"cycle":["NEXT",12]},{"at_min":3.75,"tiles":1,"macros":145,"cycle":["NEXT",12]},{"at_min":4.0,"tiles":1,"macros":145,"cycle":["NEXT",12]},{"at_min":4.25,"tiles":1,"macros":146,"cycle":["NEXT",11]},{"at_min":4.5,"tiles":4,"macros":144,"cycle":["NEXT",12]},{"at_min":4.75,"tiles":22,"macros":136,"cycle":["NEXT",12]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":522,"done":521,"blocked":0,"timeout":1,"refused":0,"by_macro":{"BACK":{"start":14,"done":14,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":9,"done":8,"blocked":0,"timeout":1,"refused":0},"GO WARP":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"MOVE 1":{"start":20,"done":20,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":16,"done":16,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"MOVE 4":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":436,"done":436,"blocked":0,"timeout":0,"refused":0},"RUN":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"THROW BALL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"YES":{"start":11,"done":11,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":0,"go_shop_done":0,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":1,"throw_ball_done":1,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":1,"depth":0},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":0,"heal_done":0},"whiteouts":1,"battles":{"started":8,"ended":8,"wild":7,"trainer":1,"won":0,"lost":1,"caught":0,"other":7,"longest_frames":14806,"still_running":false,"macros_in_longest":300},"rewards":{"damage":{"n":2,"total":0.36000000000000004}},"scenes":{"battle":24268,"dialog":593,"overworld":10245,"unknown":732},"ended_map":1},{"checkpoint":"r09-forest-row60","seed":1,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":1306,"wall_seconds":1233.728451404,"rungs":{"start":9,"end":9,"gained":0,"climbs":[]},"places_start":600,"places_end":621,"pad":{"empty_frames":772,"empty_seconds":12.925369262695312,"empty_fraction":0.021541380657402756,"longest_empty_seconds":2.2435226440429688},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":50,"macros":122,"cycle":["NEXT",13]},{"at_min":0.25,"tiles":40,"macros":126,"cycle":["NEXT",18]},{"at_min":0.5,"tiles":51,"macros":109,"cycle":["NEXT",18]},{"at_min":0.75,"tiles":51,"macros":109,"cycle":["NEXT",18]},{"at_min":1.0,"tiles":51,"macros":110,"cycle":["NEXT",18]},{"at_min":1.25,"tiles":51,"macros":114,"cycle":["NEXT",18]},{"at_min":1.5,"tiles":49,"macros":124,"cycle":["NEXT",18]},{"at_min":1.75,"tiles":57,"macros":120,"cycle":["NEXT",18]},{"at_min":2.0,"tiles":57,"macros":120,"cycle":["NEXT",14]},{"at_min":2.25,"tiles":46,"macros":127,"cycle":["NEXT",14]},{"at_min":2.5,"tiles":10,"macros":143,"cycle":["NEXT",14]},{"at_min":2.75,"tiles":21,"macros":137,"cycle":["NEXT",18]},{"at_min":3.0,"tiles":40,"macros":128,"cycle":["NEXT",18]},{"at_min":3.25,"tiles":40,"macros":128,"cycle":["NEXT",18]},{"at_min":3.5,"tiles":40,"macros":128,"cycle":["NEXT",18]},{"at_min":3.75,"tiles":31,"macros":132,"cycle":["NEXT",18]},{"at_min":4.0,"tiles":31,"macros":132,"cycle":["NEXT",18]},{"at_min":4.25,"tiles":65,"macros":115,"cycle":["NEXT",18]},{"at_min":4.5,"tiles":88,"macros":106,"cycle":["NEXT",14]},{"at_min":4.75,"tiles":78,"macros":111,"cycle":["NEXT",14]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":585,"done":585,"blocked":0,"timeout":0,"refused":0,"by_macro":{"GO FRONTIER":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"GO HEAL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":13,"done":13,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO WARP":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"MOVE 1":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":36,"done":36,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":517,"done":517,"blocked":0,"timeout":0,"refused":0},"NO":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"RUN":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"YES":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":0,"go_shop_done":0,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":0},"heals":{"go_heal_start":1,"go_heal_done":1,"heal_start":0,"heal_done":0},"whiteouts":3,"battles":{"started":7,"ended":6,"wild":7,"trainer":0,"won":2,"lost":3,"caught":0,"other":1,"longest_frames":8574,"still_running":true,"macros_in_longest":85},"rewards":{"battle":{"n":2,"total":0.2},"boundary":{"n":2,"total":0.15000000000000002},"damage":{"n":3,"total":0.4},"exploration":{"n":2,"total":0.1},"map":{"n":1,"total":0.2},"talk":{"n":1,"total":0.1}},"scenes":{"battle":26357,"dialog":1073,"overworld":7656,"unknown":752},"ended_map":51},{"checkpoint":"r09-forest-row60","seed":2,"runtime":"session","mode":"macros","minutes":10.000133333333334,"frames":35838,"idle_frames":835,"wall_seconds":1240.363548133,"rungs":{"start":9,"end":9,"gained":0,"climbs":[]},"places_start":600,"places_end":626,"pad":{"empty_frames":825,"empty_seconds":13.812732696533203,"empty_fraction":0.02302025782688766,"longest_empty_seconds":2.260265350341797},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":91,"macros":96,"cycle":["NEXT",13]},{"at_min":0.25,"tiles":86,"macros":95,"cycle":["NEXT",11]},{"at_min":0.5,"tiles":124,"macros":77,"cycle":["NEXT",11]},{"at_min":0.75,"tiles":126,"macros":77,"cycle":["NEXT",13]},{"at_min":1.0,"tiles":126,"macros":77,"cycle":["NEXT",13]},{"at_min":1.25,"tiles":120,"macros":79,"cycle":["NEXT",13]},{"at_min":1.5,"tiles":88,"macros":96,"cycle":["NEXT",13]},{"at_min":1.75,"tiles":102,"macros":97,"cycle":["NEXT",13]},{"at_min":2.0,"tiles":120,"macros":93,"cycle":["NEXT",13]},{"at_min":2.25,"tiles":96,"macros":104,"cycle":["NEXT",15]},{"at_min":2.5,"tiles":58,"macros":121,"cycle":["NEXT",15]},{"at_min":2.75,"tiles":56,"macros":121,"cycle":["NEXT",15]},{"at_min":3.0,"tiles":56,"macros":122,"cycle":["NEXT",16]},{"at_min":3.25,"tiles":70,"macros":116,"cycle":["NEXT",16]},{"at_min":3.5,"tiles":82,"macros":109,"cycle":["NEXT",16]},{"at_min":3.75,"tiles":87,"macros":107,"cycle":["NEXT",16]},{"at_min":4.0,"tiles":85,"macros":108,"cycle":["NEXT",16]},{"at_min":4.25,"tiles":85,"macros":108,"cycle":["NEXT",16]},{"at_min":4.5,"tiles":85,"macros":108,"cycle":["NEXT",16]},{"at_min":4.75,"tiles":85,"macros":108,"cycle":["NEXT",14]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":517,"done":517,"blocked":0,"timeout":0,"refused":0,"by_macro":{"GO FRONTIER":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":16,"done":16,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO WARP":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"HEAL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"MOVE 1":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":28,"done":28,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":450,"done":450,"blocked":0,"timeout":0,"refused":0},"NO":{"start":9,"done":9,"blocked":0,"timeout":0,"refused":0},"RUN":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"YES":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":0,"go_shop_done":0,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":0},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":1,"heal_done":1},"whiteouts":3,"battles":{"started":7,"ended":6,"wild":7,"trainer":0,"won":2,"lost":2,"caught":0,"other":2,"longest_frames":5038,"still_running":true,"macros_in_longest":103},"rewards":{"battle":{"n":2,"total":0.2},"boundary":{"n":2,"total":0.15000000000000002},"damage":{"n":3,"total":0.4},"exploration":{"n":3,"total":0.15000000000000002},"map":{"n":1,"total":0.2},"talk":{"n":1,"total":0.1}},"scenes":{"battle":22623,"dialog":1729,"overworld":10682,"unknown":804},"ended_map":51},{"checkpoint":"r09-forest-row60","seed":3,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":883,"wall_seconds":1231.367963652,"rungs":{"start":9,"end":9,"gained":0,"climbs":[]},"places_start":600,"places_end":628,"pad":{"empty_frames":1113,"empty_seconds":18.634632110595703,"empty_fraction":0.03105642055918299,"longest_empty_seconds":2.2435226440429688},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":51,"macros":124,"cycle":["NEXT",16]},{"at_min":0.25,"tiles":50,"macros":119,"cycle":["NEXT",16]},{"at_min":0.5,"tiles":79,"macros":103,"cycle":["NEXT",16]},{"at_min":0.75,"tiles":105,"macros":88,"cycle":["NEXT",16]},{"at_min":1.0,"tiles":143,"macros":71,"cycle":["NEXT",16]},{"at_min":1.25,"tiles":147,"macros":69,"cycle":["NEXT",16]},{"at_min":1.5,"tiles":145,"macros":71,"cycle":["NEXT",16]},{"at_min":1.75,"tiles":145,"macros":76,"cycle":["NEXT",16]},{"at_min":2.0,"tiles":145,"macros":78,"cycle":["NEXT",14]},{"at_min":2.25,"tiles":130,"macros":85,"cycle":["NEXT",15]},{"at_min":2.5,"tiles":130,"macros":85,"cycle":["NEXT",15]},{"at_min":2.75,"tiles":125,"macros":90,"cycle":["NEXT",15]},{"at_min":3.0,"tiles":87,"macros":107,"cycle":["NEXT",15]},{"at_min":3.25,"tiles":83,"macros":108,"cycle":["NEXT",15]},{"at_min":3.5,"tiles":83,"macros":108,"cycle":["NEXT",15]},{"at_min":3.75,"tiles":96,"macros":102,"cycle":["NEXT",15]},{"at_min":4.0,"tiles":135,"macros":83,"cycle":["NEXT",15]},{"at_min":4.25,"tiles":118,"macros":87,"cycle":["NEXT",15]},{"at_min":4.5,"tiles":80,"macros":105,"cycle":["NEXT",18]},{"at_min":4.75,"tiles":59,"macros":115,"cycle":["NEXT",18]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":494,"done":493,"blocked":0,"timeout":0,"refused":0,"by_macro":{"GO FRONTIER":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"GO HEAL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":15,"done":15,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"MOVE 1":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":27,"done":27,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":438,"done":437,"blocked":0,"timeout":0,"refused":0},"RUN":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":0,"go_shop_done":0,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":0},"heals":{"go_heal_start":1,"go_heal_done":1,"heal_start":0,"heal_done":0},"whiteouts":3,"battles":{"started":8,"ended":7,"wild":7,"trainer":1,"won":2,"lost":3,"caught":0,"other":2,"longest_frames":5052,"still_running":true,"macros_in_longest":102},"rewards":{"battle":{"n":2,"total":0.2},"boundary":{"n":2,"total":0.15000000000000002},"damage":{"n":2,"total":0.4},"exploration":{"n":3,"total":0.15000000000000002},"map":{"n":1,"total":0.2}},"scenes":{"battle":22565,"dialog":108,"overworld":12064,"unknown":1101},"ended_map":51},{"checkpoint":"r10-pewter-center","seed":1,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":1306,"wall_seconds":1196.708311581,"rungs":{"start":10,"end":10,"gained":0,"climbs":[]},"places_start":2227,"places_end":2311,"pad":{"empty_frames":14678,"empty_seconds":245.74944305419922,"empty_fraction":0.40956526591885706,"longest_empty_seconds":11.920806884765625},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":120,"macros":73,"cycle":["YES",27]},{"at_min":0.25,"tiles":98,"macros":76,"cycle":["YES",27]},{"at_min":0.5,"tiles":87,"macros":87,"cycle":["YES",27]},{"at_min":0.75,"tiles":87,"macros":100,"cycle":["YES",27]},{"at_min":1.0,"tiles":65,"macros":116,"cycle":["YES",27]},{"at_min":1.25,"tiles":29,"macros":129,"cycle":["YES",27]},{"at_min":1.5,"tiles":16,"macros":137,"cycle":["YES",27]},{"at_min":1.75,"tiles":15,"macros":136,"cycle":["NEXT",17]},{"at_min":2.0,"tiles":9,"macros":137,"cycle":["NEXT",25]},{"at_min":2.25,"tiles":44,"macros":126,"cycle":["NEXT",25]},{"at_min":2.5,"tiles":45,"macros":120,"cycle":["NEXT",25]},{"at_min":2.75,"tiles":45,"macros":113,"cycle":["NEXT",25]},{"at_min":3.0,"tiles":45,"macros":107,"cycle":["NEXT",25]},{"at_min":3.25,"tiles":45,"macros":101,"cycle":["NEXT",25]},{"at_min":3.5,"tiles":45,"macros":94,"cycle":["GO HEAL, GO ROUTE",31]},{"at_min":3.75,"tiles":45,"macros":89,"cycle":["GO ROUTE, GO HEAL",36]},{"at_min":4.0,"tiles":38,"macros":85,"cycle":["GO ROUTE, GO HEAL",42]},{"at_min":4.25,"tiles":5,"macros":95,"cycle":["GO ROUTE, GO HEAL",47]},{"at_min":4.5,"tiles":5,"macros":95,"cycle":["GO ROUTE, GO HEAL",47]},{"at_min":4.75,"tiles":5,"macros":95,"cycle":["GO ROUTE, GO HEAL",47]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":473,"done":473,"blocked":0,"timeout":0,"refused":0,"by_macro":{"BACK":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO FRONTIER":{"start":28,"done":28,"blocked":0,"timeout":0,"refused":0},"GO HEAL":{"start":101,"done":101,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":105,"done":105,"blocked":0,"timeout":0,"refused":0},"GO SHOP":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"LEAVE":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"MOVE 1":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"MOVE 4":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":123,"done":123,"blocked":0,"timeout":0,"refused":0},"NO":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"YES":{"start":93,"done":93,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":1,"go_shop_done":1,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":1},"heals":{"go_heal_start":101,"go_heal_done":101,"heal_start":0,"heal_done":0},"whiteouts":0,"battles":{"started":2,"ended":1,"wild":0,"trainer":2,"won":0,"lost":0,"caught":0,"other":1,"longest_frames":6289,"still_running":true,"macros_in_longest":128},"rewards":{"boundary":{"n":4,"total":0.30000000000000004},"damage":{"n":2,"total":0.46287878787878795},"exploration":{"n":9,"total":0.44999999999999996},"map":{"n":3,"total":0.6000000000000001},"talk":{"n":5,"total":0.5},"trainer":{"n":1,"total":0.5}},"scenes":{"battle":6468,"dialog":4477,"overworld":9930,"shop":57,"unknown":14906},"ended_map":54},{"checkpoint":"r10-pewter-center","seed":2,"runtime":"session","mode":"macros","minutes":10.000133333333334,"frames":35838,"idle_frames":835,"wall_seconds":1227.102947416,"rungs":{"start":10,"end":11,"gained":1,"climbs":[[11,8.5318]]},"places_start":2227,"places_end":2330,"pad":{"empty_frames":5722,"empty_seconds":95.80176544189453,"empty_fraction":0.15966292761872872,"longest_empty_seconds":11.920806884765625},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":120,"macros":72,"cycle":["YES",27]},{"at_min":0.25,"tiles":93,"macros":80,"cycle":["YES",27]},{"at_min":0.5,"tiles":85,"macros":90,"cycle":["YES",27]},{"at_min":0.75,"tiles":83,"macros":103,"cycle":["YES",27]},{"at_min":1.0,"tiles":63,"macros":117,"cycle":["YES",27]},{"at_min":1.25,"tiles":23,"macros":130,"cycle":["YES",27]},{"at_min":1.5,"tiles":14,"macros":137,"cycle":["YES",25]},{"at_min":1.75,"tiles":14,"macros":138,"cycle":["NEXT",25]},{"at_min":2.0,"tiles":36,"macros":125,"cycle":["NEXT",25]},{"at_min":2.25,"tiles":45,"macros":120,"cycle":["NEXT",25]},{"at_min":2.5,"tiles":45,"macros":115,"cycle":["NEXT",25]},{"at_min":2.75,"tiles":45,"macros":108,"cycle":["NEXT",25]},{"at_min":3.0,"tiles":48,"macros":102,"cycle":["NEXT",25]},{"at_min":3.25,"tiles":71,"macros":90,"cycle":["NEXT",25]},{"at_min":3.5,"tiles":84,"macros":87,"cycle":["GO ROUTE, GO HEAL",22]},{"at_min":3.75,"tiles":91,"macros":72,"cycle":["GO HEAL, GO ROUTE",23]},{"at_min":4.0,"tiles":90,"macros":74,"cycle":["GO HEAL, GO ROUTE",22]},{"at_min":4.25,"tiles":95,"macros":79,"cycle":["GO HEAL, GO ROUTE",17]},{"at_min":4.5,"tiles":95,"macros":82,"cycle":["YES",19]},{"at_min":4.75,"tiles":95,"macros":88,"cycle":["YES",19]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":515,"done":515,"blocked":0,"timeout":0,"refused":0,"by_macro":{"BACK":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"GO FRONTIER":{"start":38,"done":38,"blocked":0,"timeout":0,"refused":0},"GO HEAL":{"start":26,"done":26,"blocked":0,"timeout":0,"refused":0},"GO ITEM":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":7,"done":7,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":28,"done":28,"blocked":0,"timeout":0,"refused":0},"GO SHOP":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"HEAL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"LEAVE":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"MOVE 1":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"MOVE 4":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":228,"done":228,"blocked":0,"timeout":0,"refused":0},"NO":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":9,"done":9,"blocked":0,"timeout":0,"refused":0},"YES":{"start":155,"done":155,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":1,"go_shop_done":1,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":1},"heals":{"go_heal_start":26,"go_heal_done":26,"heal_start":1,"heal_done":1},"whiteouts":0,"battles":{"started":2,"ended":2,"wild":0,"trainer":2,"won":0,"lost":0,"caught":0,"other":2,"longest_frames":6289,"still_running":false,"macros_in_longest":127},"rewards":{"badge":{"n":1,"total":3.0},"boundary":{"n":4,"total":0.30000000000000004},"damage":{"n":4,"total":0.9545454545454547},"exploration":{"n":11,"total":0.5499999999999999},"map":{"n":3,"total":0.6000000000000001},"talk":{"n":6,"total":0.6},"trainer":{"n":2,"total":1.0}},"scenes":{"battle":12056,"dialog":8013,"overworld":9912,"shop":57,"unknown":5800},"ended_map":2},{"checkpoint":"r10-pewter-center","seed":3,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":883,"wall_seconds":1278.685814797,"rungs":{"start":10,"end":11,"gained":1,"climbs":[[11,7.08775]]},"places_start":2227,"places_end":2342,"pad":{"empty_frames":2848,"empty_seconds":47.6832275390625,"empty_fraction":0.07946872035269825,"longest_empty_seconds":11.920806884765625},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":117,"macros":73,"cycle":["YES",27]},{"at_min":0.25,"tiles":100,"macros":74,"cycle":["YES",27]},{"at_min":0.5,"tiles":89,"macros":84,"cycle":["YES",27]},{"at_min":0.75,"tiles":89,"macros":97,"cycle":["YES",27]},{"at_min":1.0,"tiles":67,"macros":113,"cycle":["YES",27]},{"at_min":1.25,"tiles":40,"macros":119,"cycle":["YES",27]},{"at_min":1.5,"tiles":60,"macros":115,"cycle":["YES",27]},{"at_min":1.75,"tiles":88,"macros":99,"cycle":["NEXT",25]},{"at_min":2.0,"tiles":94,"macros":102,"cycle":["NEXT",25]},{"at_min":2.25,"tiles":95,"macros":92,"cycle":["NEXT",25]},{"at_min":2.5,"tiles":99,"macros":80,"cycle":["NEXT",25]},{"at_min":2.75,"tiles":108,"macros":75,"cycle":["NEXT",24]},{"at_min":3.0,"tiles":108,"macros":72,"cycle":["YES",19]},{"at_min":3.25,"tiles":103,"macros":79,"cycle":["YES",19]},{"at_min":3.5,"tiles":99,"macros":92,"cycle":["NEXT",22]},{"at_min":3.75,"tiles":88,"macros":109,"cycle":["NEXT",22]},{"at_min":4.0,"tiles":79,"macros":108,"cycle":["NEXT",22]},{"at_min":4.25,"tiles":41,"macros":125,"cycle":["NEXT",22]},{"at_min":4.5,"tiles":13,"macros":139,"cycle":["NEXT",29]},{"at_min":4.75,"tiles":1,"macros":144,"cycle":["NEXT",43]}]},"ratchet":{"rollbacks":1,"game_over":0,"stall":1},"macros":{"starts":457,"done":398,"blocked":58,"timeout":0,"refused":0,"by_macro":{"BACK":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO FRONTIER":{"start":102,"done":45,"blocked":56,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":10,"done":8,"blocked":2,"timeout":0,"refused":0},"GO OUT":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":6,"done":6,"blocked":0,"timeout":0,"refused":0},"GO SHOP":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"LEAVE":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"MOVE 4":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":182,"done":182,"blocked":0,"timeout":0,"refused":0},"NO":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":7,"done":7,"blocked":0,"timeout":0,"refused":0},"YES":{"start":136,"done":136,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":1,"go_shop_done":1,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":1},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":0,"heal_done":0},"whiteouts":0,"battles":{"started":2,"ended":2,"wild":0,"trainer":2,"won":0,"lost":0,"caught":0,"other":2,"longest_frames":6247,"still_running":false,"macros_in_longest":129},"rewards":{"badge":{"n":1,"total":3.0},"boundary":{"n":4,"total":0.30000000000000004},"damage":{"n":4,"total":0.9666666666666667},"exploration":{"n":13,"total":0.65},"map":{"n":3,"total":0.6000000000000001},"talk":{"n":5,"total":0.5},"trainer":{"n":2,"total":1.0}},"scenes":{"battle":9229,"dialog":6614,"overworld":17061,"shop":57,"unknown":2877},"ended_map":54},{"checkpoint":"r10-pewter-gym","seed":1,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":1306,"wall_seconds":1223.406602229,"rungs":{"start":10,"end":10,"gained":0,"climbs":[]},"places_start":844,"places_end":847,"pad":{"empty_frames":2333,"empty_seconds":39.060733795166016,"empty_fraction":0.06509849880015627,"longest_empty_seconds":3.6499099731445312},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":32,"macros":129,"cycle":["NEXT",15]},{"at_min":0.25,"tiles":35,"macros":126,"cycle":["NEXT",15]},{"at_min":0.5,"tiles":52,"macros":116,"cycle":["NEXT",15]},{"at_min":0.75,"tiles":49,"macros":116,"cycle":["NEXT",16]},{"at_min":1.0,"tiles":49,"macros":118,"cycle":["NEXT",16]},{"at_min":1.25,"tiles":49,"macros":118,"cycle":["NEXT",16]},{"at_min":1.5,"tiles":49,"macros":119,"cycle":["NEXT",16]},{"at_min":1.75,"tiles":49,"macros":118,"cycle":["NEXT",16]},{"at_min":2.0,"tiles":49,"macros":108,"cycle":["NEXT",16]},{"at_min":2.25,"tiles":49,"macros":108,"cycle":["NEXT",16]},{"at_min":2.5,"tiles":49,"macros":115,"cycle":["NEXT",15]},{"at_min":2.75,"tiles":49,"macros":118,"cycle":["NEXT",16]},{"at_min":3.0,"tiles":49,"macros":119,"cycle":["NEXT",16]},{"at_min":3.25,"tiles":49,"macros":119,"cycle":["NEXT",16]},{"at_min":3.5,"tiles":49,"macros":117,"cycle":["NEXT",16]},{"at_min":3.75,"tiles":49,"macros":110,"cycle":["NEXT",16]},{"at_min":4.0,"tiles":49,"macros":105,"cycle":["NEXT",16]},{"at_min":4.25,"tiles":49,"macros":115,"cycle":["NEXT",16]},{"at_min":4.5,"tiles":49,"macros":118,"cycle":["NEXT",15]},{"at_min":4.75,"tiles":49,"macros":119,"cycle":["NEXT",15]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":573,"done":573,"blocked":0,"timeout":0,"refused":0,"by_macro":{"GO FRONTIER":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO NPC":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":12,"done":12,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":30,"done":30,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":500,"done":500,"blocked":0,"timeout":0,"refused":0},"NO":{"start":14,"done":14,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":7,"done":7,"blocked":0,"timeout":0,"refused":0},"YES":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":0,"go_shop_done":0,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":0},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":0,"heal_done":0},"whiteouts":5,"battles":{"started":6,"ended":5,"wild":0,"trainer":6,"won":0,"lost":5,"caught":0,"other":0,"longest_frames":4818,"still_running":true,"macros_in_longest":97},"rewards":{"damage":{"n":3,"total":0.25},"exploration":{"n":1,"total":0.05}},"scenes":{"battle":23562,"dialog":3201,"overworld":6727,"unknown":2348},"ended_map":54},{"checkpoint":"r10-pewter-gym","seed":2,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":835,"wall_seconds":1188.091592094,"rungs":{"start":10,"end":10,"gained":0,"climbs":[]},"places_start":844,"places_end":848,"pad":{"empty_frames":2503,"empty_seconds":41.9069938659668,"empty_fraction":0.06984206707963614,"longest_empty_seconds":3.6499099731445312},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":35,"macros":128,"cycle":["NEXT",15]},{"at_min":0.25,"tiles":47,"macros":120,"cycle":["NEXT",15]},{"at_min":0.5,"tiles":54,"macros":111,"cycle":["NEXT",15]},{"at_min":0.75,"tiles":50,"macros":115,"cycle":["NEXT",16]},{"at_min":1.0,"tiles":50,"macros":119,"cycle":["NEXT",16]},{"at_min":1.25,"tiles":50,"macros":119,"cycle":["NEXT",16]},{"at_min":1.5,"tiles":50,"macros":119,"cycle":["NEXT",16]},{"at_min":1.75,"tiles":50,"macros":119,"cycle":["NEXT",16]},{"at_min":2.0,"tiles":50,"macros":107,"cycle":["NEXT",16]},{"at_min":2.25,"tiles":51,"macros":111,"cycle":["NEXT",16]},{"at_min":2.5,"tiles":51,"macros":117,"cycle":["NEXT",14]},{"at_min":2.75,"tiles":51,"macros":116,"cycle":["NEXT",17]},{"at_min":3.0,"tiles":51,"macros":116,"cycle":["NEXT",17]},{"at_min":3.25,"tiles":51,"macros":116,"cycle":["NEXT",17]},{"at_min":3.5,"tiles":51,"macros":116,"cycle":["NEXT",17]},{"at_min":3.75,"tiles":51,"macros":113,"cycle":["NEXT",17]},{"at_min":4.0,"tiles":51,"macros":108,"cycle":["NEXT",17]},{"at_min":4.25,"tiles":51,"macros":113,"cycle":["NEXT",17]},{"at_min":4.5,"tiles":51,"macros":116,"cycle":["NEXT",15]},{"at_min":4.75,"tiles":51,"macros":118,"cycle":["NEXT",15]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":570,"done":569,"blocked":0,"timeout":0,"refused":0,"by_macro":{"GO FRONTIER":{"start":6,"done":6,"blocked":0,"timeout":0,"refused":0},"GO NPC":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":12,"done":12,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":29,"done":29,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":493,"done":492,"blocked":0,"timeout":0,"refused":0},"NO":{"start":20,"done":20,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":0,"go_shop_done":0,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":0},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":0,"heal_done":0},"whiteouts":5,"battles":{"started":6,"ended":5,"wild":0,"trainer":6,"won":0,"lost":5,"caught":0,"other":0,"longest_frames":4823,"still_running":true,"macros_in_longest":97},"rewards":{"damage":{"n":4,"total":0.35},"exploration":{"n":1,"total":0.05}},"scenes":{"battle":23158,"dialog":3188,"overworld":6952,"unknown":2540},"ended_map":54},{"checkpoint":"r10-pewter-gym","seed":3,"runtime":"session","mode":"macros","minutes":10.000133333333334,"frames":35838,"idle_frames":883,"wall_seconds":1220.82823556,"rungs":{"start":10,"end":10,"gained":0,"climbs":[]},"places_start":844,"places_end":844,"pad":{"empty_frames":2645,"empty_seconds":44.28445816040039,"empty_fraction":0.07380434176014286,"longest_empty_seconds":3.6499099731445312},"watchdog":{"probes":4,"suspected":1,"confirmed":0,"ladder_events":0,"reasons":{"unwon-battles":1},"flagged":[{"at_min":10.0,"suspected":true,"reason":"unwon-battles","decisions":564,"distinct":7,"period":1,"repeats":18,"done":564,"failed":0,"rewards":9,"fights":33,"wins":0,"places_delta":0}]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":35,"macros":126,"cycle":["NEXT",16]},{"at_min":0.25,"tiles":51,"macros":118,"cycle":["NEXT",16]},{"at_min":0.5,"tiles":54,"macros":110,"cycle":["NEXT",16]},{"at_min":0.75,"tiles":51,"macros":114,"cycle":["NEXT",21]},{"at_min":1.0,"tiles":51,"macros":116,"cycle":["NEXT",21]},{"at_min":1.25,"tiles":51,"macros":115,"cycle":["NEXT",21]},{"at_min":1.5,"tiles":51,"macros":115,"cycle":["NEXT",21]},{"at_min":1.75,"tiles":51,"macros":113,"cycle":["NEXT",21]},{"at_min":2.0,"tiles":51,"macros":98,"cycle":["NEXT",21]},{"at_min":2.25,"tiles":51,"macros":108,"cycle":["NEXT",21]},{"at_min":2.5,"tiles":51,"macros":116,"cycle":["NEXT",16]},{"at_min":2.75,"tiles":51,"macros":116,"cycle":["NEXT",16]},{"at_min":3.0,"tiles":51,"macros":117,"cycle":["NEXT",16]},{"at_min":3.25,"tiles":51,"macros":116,"cycle":["NEXT",16]},{"at_min":3.5,"tiles":51,"macros":116,"cycle":["NEXT",16]},{"at_min":3.75,"tiles":51,"macros":105,"cycle":["NEXT",16]},{"at_min":4.0,"tiles":51,"macros":111,"cycle":["NEXT",16]},{"at_min":4.25,"tiles":51,"macros":116,"cycle":["NEXT",14]},{"at_min":4.5,"tiles":51,"macros":116,"cycle":["NEXT",15]},{"at_min":4.75,"tiles":51,"macros":116,"cycle":["NEXT",15]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":564,"done":564,"blocked":0,"timeout":0,"refused":0,"by_macro":{"GO FRONTIER":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":13,"done":13,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":23,"done":23,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":10,"done":10,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":494,"done":494,"blocked":0,"timeout":0,"refused":0},"NO":{"start":17,"done":17,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":0,"go_shop_done":0,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":0},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":0,"heal_done":0},"whiteouts":5,"battles":{"started":6,"ended":5,"wild":0,"trainer":6,"won":0,"lost":5,"caught":0,"other":0,"longest_frames":4908,"still_running":true,"macros_in_longest":98},"rewards":{"damage":{"n":9,"total":0.8166666666666667}},"scenes":{"battle":23106,"dialog":3214,"overworld":6850,"unknown":2668},"ended_map":54},{"checkpoint":"r11-mart","seed":1,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":1306,"wall_seconds":1184.638210407,"rungs":{"start":11,"end":11,"gained":0,"climbs":[]},"places_start":3031,"places_end":3043,"pad":{"empty_frames":1101,"empty_seconds":18.433719635009766,"empty_fraction":0.030721580445337352,"longest_empty_seconds":3.7503662109375},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":46,"macros":121,"cycle":["NEXT",25]},{"at_min":0.25,"tiles":28,"macros":126,"cycle":["NEXT",25]},{"at_min":0.5,"tiles":7,"macros":134,"cycle":["NEXT",25]},{"at_min":0.75,"tiles":7,"macros":133,"cycle":["NEXT",25]},{"at_min":1.0,"tiles":7,"macros":134,"cycle":["NEXT",25]},{"at_min":1.25,"tiles":7,"macros":134,"cycle":["NEXT",20]},{"at_min":1.5,"tiles":7,"macros":133,"cycle":["NEXT",20]},{"at_min":1.75,"tiles":7,"macros":133,"cycle":["NEXT",20]},{"at_min":2.0,"tiles":7,"macros":134,"cycle":["NEXT",20]},{"at_min":2.25,"tiles":7,"macros":136,"cycle":["NEXT",20]},{"at_min":2.5,"tiles":1,"macros":141,"cycle":["NEXT",20]},{"at_min":2.75,"tiles":3,"macros":144,"cycle":["NEXT",21]},{"at_min":3.0,"tiles":5,"macros":138,"cycle":["NEXT",21]},{"at_min":3.25,"tiles":5,"macros":137,"cycle":["NEXT",21]},{"at_min":3.5,"tiles":5,"macros":138,"cycle":["NEXT",21]},{"at_min":3.75,"tiles":5,"macros":137,"cycle":["NEXT",21]},{"at_min":4.0,"tiles":5,"macros":137,"cycle":["NEXT",21]},{"at_min":4.25,"tiles":5,"macros":138,"cycle":["NEXT",21]},{"at_min":4.5,"tiles":5,"macros":137,"cycle":["NEXT",17]},{"at_min":4.75,"tiles":3,"macros":138,"cycle":["NEXT",17]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":682,"done":679,"blocked":2,"timeout":0,"refused":0,"by_macro":{"GO FRONTIER":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"LEAVE":{"start":3,"done":2,"blocked":1,"timeout":0,"refused":0},"MOVE 1":{"start":7,"done":7,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":12,"done":12,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":11,"done":10,"blocked":1,"timeout":0,"refused":0},"MOVE 4":{"start":10,"done":10,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":616,"done":615,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"YES":{"start":14,"done":14,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":0,"go_shop_done":0,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":0},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":0,"heal_done":0},"whiteouts":0,"battles":{"started":3,"ended":2,"wild":0,"trainer":3,"won":0,"lost":0,"caught":0,"other":2,"longest_frames":18354,"still_running":true,"macros_in_longest":152},"rewards":{"damage":{"n":10,"total":1.3791169494617772},"exploration":{"n":1,"total":0.05},"talk":{"n":1,"total":0.1},"trainer":{"n":2,"total":1.0}},"scenes":{"battle":32330,"dialog":624,"overworld":1555,"shop":216,"unknown":1113},"ended_map":14},{"checkpoint":"r11-mart","seed":2,"runtime":"session","mode":"macros","minutes":10.000133333333334,"frames":35838,"idle_frames":835,"wall_seconds":1196.253799831,"rungs":{"start":11,"end":11,"gained":0,"climbs":[]},"places_start":3031,"places_end":3052,"pad":{"empty_frames":1482,"empty_seconds":24.81269073486328,"empty_fraction":0.04135275405993638,"longest_empty_seconds":3.7503662109375},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":45,"macros":121,"cycle":["NEXT",18]},{"at_min":0.25,"tiles":25,"macros":131,"cycle":["NEXT",18]},{"at_min":0.5,"tiles":1,"macros":142,"cycle":["NEXT",27]},{"at_min":0.75,"tiles":1,"macros":145,"cycle":["NEXT",28]},{"at_min":1.0,"tiles":1,"macros":143,"cycle":["NEXT",28]},{"at_min":1.25,"tiles":1,"macros":142,"cycle":["NEXT",28]},{"at_min":1.5,"tiles":1,"macros":137,"cycle":["NEXT",28]},{"at_min":1.75,"tiles":1,"macros":137,"cycle":["NEXT",28]},{"at_min":2.0,"tiles":1,"macros":136,"cycle":["NEXT",28]},{"at_min":2.25,"tiles":1,"macros":136,"cycle":["NEXT",19]},{"at_min":2.5,"tiles":7,"macros":133,"cycle":["NEXT",25]},{"at_min":2.75,"tiles":7,"macros":127,"cycle":["NEXT",25]},{"at_min":3.0,"tiles":7,"macros":130,"cycle":["NEXT",25]},{"at_min":3.25,"tiles":7,"macros":130,"cycle":["NEXT",25]},{"at_min":3.5,"tiles":7,"macros":136,"cycle":["NEXT",25]},{"at_min":3.75,"tiles":9,"macros":129,"cycle":["NEXT",25]},{"at_min":4.0,"tiles":9,"macros":129,"cycle":["NEXT",25]},{"at_min":4.25,"tiles":9,"macros":128,"cycle":["NEXT",20]},{"at_min":4.5,"tiles":5,"macros":132,"cycle":["NEXT",20]},{"at_min":4.75,"tiles":5,"macros":138,"cycle":["NEXT",20]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":667,"done":662,"blocked":4,"timeout":0,"refused":0,"by_macro":{"GO FRONTIER":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"LEAVE":{"start":3,"done":2,"blocked":1,"timeout":0,"refused":0},"MOVE 1":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":11,"done":10,"blocked":1,"timeout":0,"refused":0},"MOVE 3":{"start":12,"done":10,"blocked":2,"timeout":0,"refused":0},"MOVE 4":{"start":10,"done":10,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":601,"done":600,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"YES":{"start":17,"done":17,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":0,"go_shop_done":0,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":0},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":0,"heal_done":0},"whiteouts":0,"battles":{"started":4,"ended":3,"wild":0,"trainer":4,"won":0,"lost":0,"caught":0,"other":3,"longest_frames":13884,"still_running":true,"macros_in_longest":274},"rewards":{"damage":{"n":8,"total":1.3279310344827586},"exploration":{"n":2,"total":0.1},"talk":{"n":1,"total":0.1},"trainer":{"n":3,"total":1.5}},"scenes":{"battle":31617,"dialog":748,"overworld":1769,"shop":201,"unknown":1503},"ended_map":14},{"checkpoint":"r11-mart","seed":3,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":883,"wall_seconds":1194.33071849,"rungs":{"start":11,"end":11,"gained":0,"climbs":[]},"places_start":3031,"places_end":3041,"pad":{"empty_frames":1097,"empty_seconds":18.366748809814453,"empty_fraction":0.030609967074055472,"longest_empty_seconds":3.7503662109375},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":44,"macros":113,"cycle":["NEXT",17]},{"at_min":0.25,"tiles":21,"macros":120,"cycle":["NEXT",17]},{"at_min":0.5,"tiles":1,"macros":131,"cycle":["NEXT",18]},{"at_min":0.75,"tiles":1,"macros":134,"cycle":["NEXT",18]},{"at_min":1.0,"tiles":1,"macros":130,"cycle":["NEXT",18]},{"at_min":1.25,"tiles":1,"macros":131,"cycle":["NEXT",19]},{"at_min":1.5,"tiles":7,"macros":121,"cycle":["NEXT",20]},{"at_min":1.75,"tiles":7,"macros":123,"cycle":["NEXT",20]},{"at_min":2.0,"tiles":7,"macros":130,"cycle":["NEXT",20]},{"at_min":2.25,"tiles":7,"macros":133,"cycle":["NEXT",21]},{"at_min":2.5,"tiles":7,"macros":133,"cycle":["NEXT",21]},{"at_min":2.75,"tiles":7,"macros":134,"cycle":["NEXT",21]},{"at_min":3.0,"tiles":7,"macros":137,"cycle":["NEXT",21]},{"at_min":3.25,"tiles":7,"macros":136,"cycle":["NEXT",21]},{"at_min":3.5,"tiles":5,"macros":137,"cycle":["NEXT",21]},{"at_min":3.75,"tiles":5,"macros":138,"cycle":["NEXT",21]},{"at_min":4.0,"tiles":5,"macros":138,"cycle":["NEXT",19]},{"at_min":4.25,"tiles":5,"macros":138,"cycle":["NEXT",19]},{"at_min":4.5,"tiles":5,"macros":139,"cycle":["NEXT",19]},{"at_min":4.75,"tiles":5,"macros":138,"cycle":["NEXT",19]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":672,"done":666,"blocked":6,"timeout":0,"refused":0,"by_macro":{"GO FRONTIER":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"LEAVE":{"start":3,"done":2,"blocked":1,"timeout":0,"refused":0},"MOVE 1":{"start":9,"done":9,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":9,"done":9,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":14,"done":10,"blocked":4,"timeout":0,"refused":0},"MOVE 4":{"start":11,"done":10,"blocked":1,"timeout":0,"refused":0},"NEXT":{"start":605,"done":605,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"YES":{"start":14,"done":14,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":0,"go_shop_done":0,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":0},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":0,"heal_done":0},"whiteouts":0,"battles":{"started":3,"ended":2,"wild":0,"trainer":3,"won":0,"lost":0,"caught":0,"other":2,"longest_frames":16170,"still_running":true,"macros_in_longest":184},"rewards":{"damage":{"n":9,"total":1.35},"exploration":{"n":1,"total":0.05},"talk":{"n":1,"total":0.1},"trainer":{"n":2,"total":1.0}},"scenes":{"battle":32484,"dialog":624,"overworld":1417,"shop":201,"unknown":1112},"ended_map":14},{"checkpoint":"r11-badge","seed":1,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":1306,"wall_seconds":1206.568099841,"rungs":{"start":11,"end":11,"gained":0,"climbs":[]},"places_start":1896,"places_end":1920,"pad":{"empty_frames":2856,"empty_seconds":47.817169189453125,"empty_fraction":0.079691947095262,"longest_empty_seconds":31.71068572998047},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":82,"macros":97,"cycle":["NEXT",18]},{"at_min":0.25,"tiles":44,"macros":113,"cycle":["NEXT",18]},{"at_min":0.5,"tiles":39,"macros":126,"cycle":["NEXT",18]},{"at_min":0.75,"tiles":4,"macros":140,"cycle":["NEXT",18]},{"at_min":1.0,"tiles":1,"macros":145,"cycle":["NEXT",18]},{"at_min":1.25,"tiles":1,"macros":145,"cycle":["NEXT",18]},{"at_min":1.5,"tiles":1,"macros":146,"cycle":["NEXT",27]},{"at_min":1.75,"tiles":1,"macros":144,"cycle":["NEXT",27]},{"at_min":2.0,"tiles":1,"macros":145,"cycle":["NEXT",27]},{"at_min":2.25,"tiles":1,"macros":145,"cycle":["NEXT",27]},{"at_min":2.5,"tiles":1,"macros":145,"cycle":["NEXT",27]},{"at_min":2.75,"tiles":1,"macros":145,"cycle":["NEXT",27]},{"at_min":3.0,"tiles":1,"macros":146,"cycle":["NEXT",27]},{"at_min":3.25,"tiles":5,"macros":145,"cycle":["NEXT",22]},{"at_min":3.5,"tiles":5,"macros":141,"cycle":["NEXT",22]},{"at_min":3.75,"tiles":5,"macros":142,"cycle":["NEXT",22]},{"at_min":4.0,"tiles":5,"macros":141,"cycle":["NEXT",22]},{"at_min":4.25,"tiles":20,"macros":135,"cycle":["NEXT",22]},{"at_min":4.5,"tiles":20,"macros":136,"cycle":["NEXT",22]},{"at_min":4.75,"tiles":20,"macros":135,"cycle":["NEXT",22]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":578,"done":576,"blocked":1,"timeout":0,"refused":0,"by_macro":{"BUY BALL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"CONFIRM":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"GO FRONTIER":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO ITEM":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":8,"done":7,"blocked":0,"timeout":0,"refused":0},"GO SHOP":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"LEAVE":{"start":1,"done":0,"blocked":1,"timeout":0,"refused":0},"MOVE 1":{"start":8,"done":8,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":17,"done":17,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":8,"done":8,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":516,"done":516,"blocked":0,"timeout":0,"refused":0},"NO":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"THROW BALL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"YES":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":3,"go_shop_done":3,"buy_ball_start":1,"buy_ball_done":1,"throw_ball_start":1,"throw_ball_done":1,"catches":1,"species_gained":1,"balls_gained":1,"balls_spent":1,"depth":4},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":0,"heal_done":0},"whiteouts":1,"battles":{"started":3,"ended":3,"wild":1,"trainer":2,"won":0,"lost":1,"caught":1,"other":1,"longest_frames":15281,"still_running":false,"macros_in_longest":312},"rewards":{"boundary":{"n":4,"total":0.3},"catch":{"n":1,"total":0.1},"damage":{"n":6,"total":0.6793103448275862},"exploration":{"n":2,"total":0.1},"map":{"n":1,"total":0.2},"species":{"n":1,"total":0.5},"talk":{"n":1,"total":0.1},"trainer":{"n":1,"total":0.5}},"scenes":{"battle":26769,"dialog":489,"overworld":5198,"shop":509,"unknown":2873},"ended_map":13},{"checkpoint":"r11-badge","seed":2,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":835,"wall_seconds":1179.023839768,"rungs":{"start":11,"end":11,"gained":0,"climbs":[]},"places_start":1896,"places_end":1919,"pad":{"empty_frames":3088,"empty_seconds":51.70147705078125,"empty_fraction":0.08616552262961102,"longest_empty_seconds":33.56912612915039},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":84,"macros":96,"cycle":["NEXT",14]},{"at_min":0.25,"tiles":51,"macros":110,"cycle":["NEXT",14]},{"at_min":0.5,"tiles":39,"macros":124,"cycle":["NEXT",14]},{"at_min":0.75,"tiles":10,"macros":137,"cycle":["NEXT",14]},{"at_min":1.0,"tiles":1,"macros":147,"cycle":["NEXT",17]},{"at_min":1.25,"tiles":1,"macros":146,"cycle":["NEXT",17]},{"at_min":1.5,"tiles":1,"macros":146,"cycle":["NEXT",25]},{"at_min":1.75,"tiles":1,"macros":147,"cycle":["NEXT",25]},{"at_min":2.0,"tiles":1,"macros":146,"cycle":["NEXT",25]},{"at_min":2.25,"tiles":1,"macros":146,"cycle":["NEXT",25]},{"at_min":2.5,"tiles":1,"macros":147,"cycle":["NEXT",25]},{"at_min":2.75,"tiles":1,"macros":147,"cycle":["NEXT",25]},{"at_min":3.0,"tiles":1,"macros":146,"cycle":["NEXT",25]},{"at_min":3.25,"tiles":5,"macros":141,"cycle":["NEXT",20]},{"at_min":3.5,"tiles":5,"macros":141,"cycle":["NEXT",20]},{"at_min":3.75,"tiles":5,"macros":140,"cycle":["NEXT",20]},{"at_min":4.0,"tiles":32,"macros":128,"cycle":["NEXT",20]},{"at_min":4.25,"tiles":59,"macros":116,"cycle":["NEXT",20]},{"at_min":4.5,"tiles":59,"macros":115,"cycle":["NEXT",20]},{"at_min":4.75,"tiles":59,"macros":116,"cycle":["NEXT",20]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":586,"done":585,"blocked":1,"timeout":0,"refused":0,"by_macro":{"BACK":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"BUY BALL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"CONFIRM":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"GO FRONTIER":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO ITEM":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":7,"done":7,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO SHOP":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"LEAVE":{"start":1,"done":0,"blocked":1,"timeout":0,"refused":0},"MOVE 1":{"start":9,"done":9,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":17,"done":17,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":11,"done":11,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":520,"done":520,"blocked":0,"timeout":0,"refused":0},"NO":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"THROW BALL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"YES":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":3,"go_shop_done":3,"buy_ball_start":1,"buy_ball_done":1,"throw_ball_start":1,"throw_ball_done":1,"catches":1,"species_gained":1,"balls_gained":1,"balls_spent":1,"depth":4},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":0,"heal_done":0},"whiteouts":1,"battles":{"started":3,"ended":3,"wild":1,"trainer":2,"won":0,"lost":1,"caught":1,"other":1,"longest_frames":14838,"still_running":false,"macros_in_longest":304},"rewards":{"boundary":{"n":4,"total":0.3},"catch":{"n":1,"total":0.1},"damage":{"n":7,"total":0.6724137931034483},"exploration":{"n":2,"total":0.1},"map":{"n":1,"total":0.2},"species":{"n":1,"total":0.5},"talk":{"n":1,"total":0.1},"trainer":{"n":1,"total":0.5}},"scenes":{"battle":27104,"dialog":490,"overworld":4632,"shop":508,"unknown":3104},"ended_map":13},{"checkpoint":"r11-badge","seed":3,"runtime":"session","mode":"macros","minutes":10.000133333333334,"frames":35838,"idle_frames":883,"wall_seconds":1162.504942165,"rungs":{"start":11,"end":11,"gained":0,"climbs":[]},"places_start":1896,"places_end":1922,"pad":{"empty_frames":1210,"empty_seconds":20.25867462158203,"empty_fraction":0.03376304481276857,"longest_empty_seconds":3.7001380920410156},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":92,"macros":102,"cycle":["NEXT",15]},{"at_min":0.25,"tiles":54,"macros":118,"cycle":["NEXT",15]},{"at_min":0.5,"tiles":26,"macros":131,"cycle":["NEXT",15]},{"at_min":0.75,"tiles":1,"macros":143,"cycle":["NEXT",17]},{"at_min":1.0,"tiles":1,"macros":146,"cycle":["NEXT",20]},{"at_min":1.25,"tiles":1,"macros":146,"cycle":["NEXT",22]},{"at_min":1.5,"tiles":1,"macros":146,"cycle":["NEXT",22]},{"at_min":1.75,"tiles":1,"macros":145,"cycle":["NEXT",22]},{"at_min":2.0,"tiles":1,"macros":146,"cycle":["NEXT",22]},{"at_min":2.25,"tiles":1,"macros":146,"cycle":["NEXT",22]},{"at_min":2.5,"tiles":1,"macros":146,"cycle":["NEXT",22]},{"at_min":2.75,"tiles":5,"macros":145,"cycle":["NEXT",21]},{"at_min":3.0,"tiles":5,"macros":140,"cycle":["NEXT",21]},{"at_min":3.25,"tiles":5,"macros":141,"cycle":["NEXT",21]},{"at_min":3.5,"tiles":26,"macros":131,"cycle":["NEXT",21]},{"at_min":3.75,"tiles":35,"macros":127,"cycle":["NEXT",21]},{"at_min":4.0,"tiles":35,"macros":127,"cycle":["NEXT",21]},{"at_min":4.25,"tiles":35,"macros":127,"cycle":["NEXT",21]},{"at_min":4.5,"tiles":36,"macros":127,"cycle":["NEXT",14]},{"at_min":4.75,"tiles":69,"macros":112,"cycle":["NEXT",14]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":595,"done":593,"blocked":2,"timeout":0,"refused":0,"by_macro":{"BUY BALL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"CONFIRM":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO FRONTIER":{"start":3,"done":2,"blocked":1,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":10,"done":10,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO SHOP":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"LEAVE":{"start":2,"done":1,"blocked":1,"timeout":0,"refused":0},"MOVE 1":{"start":9,"done":9,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":21,"done":21,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":9,"done":9,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":524,"done":524,"blocked":0,"timeout":0,"refused":0},"NO":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"YES":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":5,"go_shop_done":5,"buy_ball_start":1,"buy_ball_done":1,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":1,"balls_spent":0,"depth":2},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":0,"heal_done":0},"whiteouts":1,"battles":{"started":4,"ended":3,"wild":2,"trainer":2,"won":0,"lost":1,"caught":0,"other":2,"longest_frames":13729,"still_running":true,"macros_in_longest":281},"rewards":{"boundary":{"n":4,"total":0.3},"damage":{"n":8,"total":0.8793103448275863},"exploration":{"n":2,"total":0.1},"map":{"n":1,"total":0.2},"talk":{"n":1,"total":0.1},"trainer":{"n":1,"total":0.5}},"scenes":{"battle":27498,"dialog":517,"overworld":6018,"shop":603,"unknown":1202},"ended_map":13},{"checkpoint":"r12-mt-moon","seed":1,"runtime":"session","mode":"macros","minutes":10.000133333333334,"frames":35838,"idle_frames":1306,"wall_seconds":1318.978157634,"rungs":{"start":12,"end":12,"gained":0,"climbs":[]},"places_start":1919,"places_end":1964,"pad":{"empty_frames":7168,"empty_seconds":120.01171875,"empty_fraction":0.20001116133712818,"longest_empty_seconds":112.37704467773438},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":30,"macros":115,"cycle":["NEXT",17]},{"at_min":0.25,"tiles":29,"macros":118,"cycle":["NEXT",17]},{"at_min":0.5,"tiles":19,"macros":122,"cycle":["NEXT",17]},{"at_min":0.75,"tiles":1,"macros":131,"cycle":["NEXT",17]},{"at_min":1.0,"tiles":1,"macros":131,"cycle":["NEXT",17]},{"at_min":1.25,"tiles":19,"macros":123,"cycle":["NEXT",18]},{"at_min":1.5,"tiles":19,"macros":123,"cycle":["NEXT",18]},{"at_min":1.75,"tiles":19,"macros":124,"cycle":["NEXT",18]},{"at_min":2.0,"tiles":19,"macros":132,"cycle":["NEXT",18]},{"at_min":2.25,"tiles":19,"macros":139,"cycle":["NEXT",18]},{"at_min":2.5,"tiles":19,"macros":137,"cycle":["NEXT",18]},{"at_min":2.75,"tiles":19,"macros":138,"cycle":["NEXT",18]},{"at_min":3.0,"tiles":19,"macros":138,"cycle":["NEXT",17]},{"at_min":3.25,"tiles":6,"macros":144,"cycle":["NEXT",17]},{"at_min":3.5,"tiles":6,"macros":145,"cycle":["NEXT",17]},{"at_min":3.75,"tiles":6,"macros":144,"cycle":["NEXT",17]},{"at_min":4.0,"tiles":6,"macros":143,"cycle":["NEXT",17]},{"at_min":4.25,"tiles":6,"macros":144,"cycle":["NEXT",17]},{"at_min":4.5,"tiles":6,"macros":145,"cycle":["NEXT",17]},{"at_min":4.75,"tiles":6,"macros":144,"cycle":["NEXT",16]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":544,"done":540,"blocked":4,"timeout":0,"refused":0,"by_macro":{"GO FRONTIER":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO WARP":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"HEAL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":24,"done":22,"blocked":2,"timeout":0,"refused":0},"MOVE 3":{"start":10,"done":8,"blocked":2,"timeout":0,"refused":0},"NEXT":{"start":492,"done":492,"blocked":0,"timeout":0,"refused":0},"NO":{"start":7,"done":7,"blocked":0,"timeout":0,"refused":0},"YES":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":0,"go_shop_done":0,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":0},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":1,"heal_done":1},"whiteouts":1,"battles":{"started":4,"ended":4,"wild":3,"trainer":1,"won":2,"lost":1,"caught":0,"other":1,"longest_frames":8203,"still_running":false,"macros_in_longest":154},"rewards":{"battle":{"n":2,"total":0.2},"boundary":{"n":1,"total":0.1},"damage":{"n":8,"total":0.65},"exploration":{"n":5,"total":0.25},"talk":{"n":1,"total":0.1},"trainer":{"n":1,"total":0.5}},"scenes":{"battle":25469,"dialog":1653,"overworld":1580,"unknown":7136},"ended_map":15},{"checkpoint":"r12-mt-moon","seed":2,"runtime":"session","mode":"macros","minutes":10.000133333333334,"frames":35838,"idle_frames":835,"wall_seconds":1270.405618564,"rungs":{"start":12,"end":12,"gained":0,"climbs":[]},"places_start":1919,"places_end":1965,"pad":{"empty_frames":1107,"empty_seconds":18.534175872802734,"empty_fraction":0.03088900050226017,"longest_empty_seconds":2.2435226440429688},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":53,"macros":124,"cycle":["NEXT",16]},{"at_min":0.25,"tiles":52,"macros":125,"cycle":["NEXT",17]},{"at_min":0.5,"tiles":29,"macros":133,"cycle":["NEXT",17]},{"at_min":0.75,"tiles":1,"macros":147,"cycle":["NEXT",17]},{"at_min":1.0,"tiles":1,"macros":147,"cycle":["NEXT",17]},{"at_min":1.25,"tiles":1,"macros":146,"cycle":["NEXT",17]},{"at_min":1.5,"tiles":9,"macros":139,"cycle":["NEXT",17]},{"at_min":1.75,"tiles":9,"macros":140,"cycle":["NEXT",17]},{"at_min":2.0,"tiles":9,"macros":139,"cycle":["NEXT",15]},{"at_min":2.25,"tiles":9,"macros":139,"cycle":["NEXT",15]},{"at_min":2.5,"tiles":17,"macros":136,"cycle":["NEXT",22]},{"at_min":2.75,"tiles":27,"macros":132,"cycle":["NEXT",22]},{"at_min":3.0,"tiles":27,"macros":131,"cycle":["NEXT",22]},{"at_min":3.25,"tiles":27,"macros":132,"cycle":["NEXT",22]},{"at_min":3.5,"tiles":19,"macros":139,"cycle":["NEXT",22]},{"at_min":3.75,"tiles":19,"macros":138,"cycle":["NEXT",22]},{"at_min":4.0,"tiles":19,"macros":139,"cycle":["NEXT",22]},{"at_min":4.25,"tiles":19,"macros":137,"cycle":["NEXT",16]},{"at_min":4.5,"tiles":11,"macros":142,"cycle":["NEXT",16]},{"at_min":4.75,"tiles":8,"macros":142,"cycle":["NEXT",17]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":656,"done":656,"blocked":0,"timeout":0,"refused":0,"by_macro":{"GO HEAL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":9,"done":9,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":28,"done":28,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":8,"done":8,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":598,"done":598,"blocked":0,"timeout":0,"refused":0},"NO":{"start":9,"done":9,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"YES":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":0,"go_shop_done":0,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":0},"heals":{"go_heal_start":1,"go_heal_done":1,"heal_start":0,"heal_done":0},"whiteouts":2,"battles":{"started":5,"ended":4,"wild":3,"trainer":2,"won":2,"lost":2,"caught":0,"other":0,"longest_frames":9342,"still_running":true,"macros_in_longest":192},"rewards":{"battle":{"n":2,"total":0.2},"damage":{"n":4,"total":0.4},"exploration":{"n":5,"total":0.25},"talk":{"n":1,"total":0.1}},"scenes":{"battle":29725,"dialog":1487,"overworld":3513,"unknown":1113},"ended_map":59},{"checkpoint":"r12-mt-moon","seed":3,"runtime":"session","mode":"macros","minutes":10.000133333333334,"frames":35838,"idle_frames":883,"wall_seconds":1272.803479504,"rungs":{"start":12,"end":12,"gained":0,"climbs":[]},"places_start":1919,"places_end":1965,"pad":{"empty_frames":951,"empty_seconds":15.922313690185547,"empty_fraction":0.026536079022266866,"longest_empty_seconds":2.2435226440429688},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":38,"macros":131,"cycle":["NEXT",15]},{"at_min":0.25,"tiles":37,"macros":131,"cycle":["NEXT",15]},{"at_min":0.5,"tiles":25,"macros":135,"cycle":["NEXT",15]},{"at_min":0.75,"tiles":10,"macros":143,"cycle":["NEXT",15]},{"at_min":1.0,"tiles":10,"macros":143,"cycle":["NEXT",15]},{"at_min":1.25,"tiles":24,"macros":134,"cycle":["NEXT",15]},{"at_min":1.5,"tiles":24,"macros":132,"cycle":["NEXT",19]},{"at_min":1.75,"tiles":24,"macros":132,"cycle":["NEXT",19]},{"at_min":2.0,"tiles":24,"macros":131,"cycle":["NEXT",19]},{"at_min":2.25,"tiles":24,"macros":131,"cycle":["NEXT",19]},{"at_min":2.5,"tiles":15,"macros":136,"cycle":["NEXT",19]},{"at_min":2.75,"tiles":15,"macros":134,"cycle":["NEXT",19]},{"at_min":3.0,"tiles":15,"macros":135,"cycle":["NEXT",19]},{"at_min":3.25,"tiles":1,"macros":144,"cycle":["NEXT",16]},{"at_min":3.5,"tiles":1,"macros":146,"cycle":["NEXT",16]},{"at_min":3.75,"tiles":14,"macros":140,"cycle":["NEXT",22]},{"at_min":4.0,"tiles":51,"macros":122,"cycle":["NEXT",22]},{"at_min":4.25,"tiles":52,"macros":122,"cycle":["NEXT",22]},{"at_min":4.5,"tiles":52,"macros":122,"cycle":["NEXT",22]},{"at_min":4.75,"tiles":52,"macros":123,"cycle":["NEXT",22]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":673,"done":672,"blocked":0,"timeout":0,"refused":0,"by_macro":{"GO HEAL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":6,"done":6,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO WARP":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":27,"done":27,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":9,"done":9,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":615,"done":614,"blocked":0,"timeout":0,"refused":0},"NO":{"start":11,"done":11,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"YES":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":0,"go_shop_done":0,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":0},"heals":{"go_heal_start":1,"go_heal_done":1,"heal_start":0,"heal_done":0},"whiteouts":1,"battles":{"started":5,"ended":4,"wild":3,"trainer":2,"won":3,"lost":1,"caught":0,"other":0,"longest_frames":8380,"still_running":true,"macros_in_longest":170},"rewards":{"battle":{"n":3,"total":0.30000000000000004},"damage":{"n":7,"total":0.7},"exploration":{"n":5,"total":0.25},"talk":{"n":1,"total":0.1}},"scenes":{"battle":30655,"dialog":1535,"overworld":2693,"unknown":955},"ended_map":59},{"checkpoint":"r12-row64","seed":1,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":1306,"wall_seconds":1251.868233194,"rungs":{"start":12,"end":13,"gained":1,"climbs":[[13,0.6035833333333334]]},"places_start":3290,"places_end":3411,"pad":{"empty_frames":1704,"empty_seconds":28.529571533203125,"empty_fraction":0.047547296166080694,"longest_empty_seconds":3.6833953857421875},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":30,"first_flagged":[{"at_min":0.75,"tiles":75,"macros":94,"cycle":["NEXT",16]},{"at_min":1.0,"tiles":68,"macros":98,"cycle":["NEXT",16]},{"at_min":1.25,"tiles":54,"macros":105,"cycle":["NEXT",16]},{"at_min":1.5,"tiles":44,"macros":118,"cycle":["NEXT",16]},{"at_min":1.75,"tiles":39,"macros":124,"cycle":["NEXT",16]},{"at_min":2.0,"tiles":9,"macros":139,"cycle":["NEXT",16]},{"at_min":2.25,"tiles":8,"macros":138,"cycle":["NEXT",16]},{"at_min":2.5,"tiles":1,"macros":146,"cycle":["NEXT",20]},{"at_min":2.75,"tiles":1,"macros":146,"cycle":["NEXT",20]},{"at_min":3.0,"tiles":1,"macros":146,"cycle":["NEXT",20]},{"at_min":3.25,"tiles":1,"macros":146,"cycle":["NEXT",20]},{"at_min":3.5,"tiles":1,"macros":146,"cycle":["NEXT",20]},{"at_min":3.75,"tiles":1,"macros":145,"cycle":["NEXT",20]},{"at_min":4.0,"tiles":1,"macros":145,"cycle":["NEXT",20]},{"at_min":4.25,"tiles":1,"macros":146,"cycle":["NEXT",18]},{"at_min":4.5,"tiles":21,"macros":136,"cycle":["NEXT",21]},{"at_min":4.75,"tiles":23,"macros":130,"cycle":["NEXT",21]},{"at_min":5.0,"tiles":23,"macros":130,"cycle":["NEXT",21]},{"at_min":5.25,"tiles":23,"macros":130,"cycle":["NEXT",21]},{"at_min":5.5,"tiles":23,"macros":130,"cycle":["NEXT",21]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":593,"done":591,"blocked":2,"timeout":0,"refused":0,"by_macro":{"BUY BALL":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"CONFIRM":{"start":9,"done":9,"blocked":0,"timeout":0,"refused":0},"GO FRONTIER":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"GO HEAL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":9,"done":9,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO SHOP":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"LEAVE":{"start":3,"done":1,"blocked":2,"timeout":0,"refused":0},"MOVE 2":{"start":26,"done":26,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":9,"done":9,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":505,"done":505,"blocked":0,"timeout":0,"refused":0},"NO":{"start":14,"done":14,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"YES":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":2,"go_shop_done":2,"buy_ball_start":2,"buy_ball_done":2,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":2,"balls_spent":0,"depth":2},"heals":{"go_heal_start":1,"go_heal_done":1,"heal_start":0,"heal_done":0},"whiteouts":1,"battles":{"started":3,"ended":2,"wild":0,"trainer":3,"won":0,"lost":1,"caught":0,"other":1,"longest_frames":14070,"still_running":true,"macros_in_longest":287},"rewards":{"boundary":{"n":10,"total":0.75},"damage":{"n":8,"total":0.49999999999999994},"exploration":{"n":12,"total":0.6},"map":{"n":4,"total":0.8},"talk":{"n":4,"total":0.4},"trainer":{"n":1,"total":0.5}},"scenes":{"battle":24498,"dialog":2604,"overworld":5839,"shop":1117,"unknown":1780},"ended_map":65},{"checkpoint":"r12-row64","seed":2,"runtime":"session","mode":"macros","minutes":10.000133333333334,"frames":35838,"idle_frames":835,"wall_seconds":1243.961956574,"rungs":{"start":12,"end":13,"gained":1,"climbs":[[13,0.5502666666666667]]},"places_start":3290,"places_end":3398,"pad":{"empty_frames":1516,"empty_seconds":25.381942749023438,"empty_fraction":0.042301467715832354,"longest_empty_seconds":3.6833953857421875},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":171,"macros":53,"cycle":["NEXT",11]},{"at_min":0.25,"tiles":134,"macros":67,"cycle":["NEXT",16]},{"at_min":0.5,"tiles":96,"macros":85,"cycle":["NEXT",16]},{"at_min":0.75,"tiles":63,"macros":100,"cycle":["NEXT",17]},{"at_min":1.0,"tiles":45,"macros":118,"cycle":["NEXT",17]},{"at_min":1.25,"tiles":34,"macros":126,"cycle":["NEXT",27]},{"at_min":1.5,"tiles":9,"macros":138,"cycle":["NEXT",27]},{"at_min":1.75,"tiles":5,"macros":140,"cycle":["NEXT",27]},{"at_min":2.0,"tiles":8,"macros":143,"cycle":["NEXT",27]},{"at_min":2.25,"tiles":24,"macros":132,"cycle":["NEXT",27]},{"at_min":2.5,"tiles":24,"macros":131,"cycle":["NEXT",27]},{"at_min":2.75,"tiles":24,"macros":131,"cycle":["NEXT",27]},{"at_min":3.0,"tiles":24,"macros":131,"cycle":["NEXT",24]},{"at_min":3.25,"tiles":27,"macros":129,"cycle":["NEXT",24]},{"at_min":3.5,"tiles":40,"macros":125,"cycle":["NEXT",24]},{"at_min":3.75,"tiles":46,"macros":121,"cycle":["NEXT",17]},{"at_min":4.0,"tiles":71,"macros":107,"cycle":["NEXT",17]},{"at_min":4.25,"tiles":55,"macros":120,"cycle":["NEXT",15]},{"at_min":4.5,"tiles":55,"macros":121,"cycle":["NEXT",14]},{"at_min":4.75,"tiles":55,"macros":121,"cycle":["NEXT",14]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":536,"done":534,"blocked":2,"timeout":0,"refused":0,"by_macro":{"BUY BALL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"CONFIRM":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"GO FRONTIER":{"start":7,"done":6,"blocked":1,"timeout":0,"refused":0},"GO HEAL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":19,"done":19,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"GO SHOP":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"ITEM":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"LEAVE":{"start":2,"done":1,"blocked":1,"timeout":0,"refused":0},"MOVE 2":{"start":11,"done":11,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"MOVE 4":{"start":10,"done":10,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":445,"done":445,"blocked":0,"timeout":0,"refused":0},"NO":{"start":18,"done":18,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"YES":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":2,"go_shop_done":2,"buy_ball_start":1,"buy_ball_done":1,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":1,"balls_spent":0,"depth":2},"heals":{"go_heal_start":1,"go_heal_done":1,"heal_start":0,"heal_done":0},"whiteouts":1,"battles":{"started":6,"ended":5,"wild":4,"trainer":2,"won":0,"lost":1,"caught":0,"other":4,"longest_frames":6948,"still_running":true,"macros_in_longest":142},"rewards":{"boundary":{"n":10,"total":0.75},"damage":{"n":10,"total":1.1612244897959183},"exploration":{"n":10,"total":0.49999999999999994},"map":{"n":4,"total":0.8},"talk":{"n":4,"total":0.4},"trainer":{"n":1,"total":0.5}},"scenes":{"battle":21392,"dialog":2651,"overworld":9505,"shop":696,"unknown":1594},"ended_map":51},{"checkpoint":"r12-row64","seed":3,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":883,"wall_seconds":1255.822722559,"rungs":{"start":12,"end":13,"gained":1,"climbs":[[13,0.7852333333333333]]},"places_start":3290,"places_end":3340,"pad":{"empty_frames":1159,"empty_seconds":19.404796600341797,"empty_fraction":0.0323399743289246,"longest_empty_seconds":3.733623504638672},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":32,"first_flagged":[{"at_min":0.0,"tiles":118,"macros":87,"cycle":["NEXT",16]},{"at_min":0.25,"tiles":113,"macros":87,"cycle":["NEXT",16]},{"at_min":0.5,"tiles":79,"macros":103,"cycle":["NEXT",16]},{"at_min":0.75,"tiles":41,"macros":121,"cycle":["NEXT",20]},{"at_min":1.0,"tiles":2,"macros":139,"cycle":["NEXT",20]},{"at_min":1.25,"tiles":1,"macros":141,"cycle":["NEXT",20]},{"at_min":1.5,"tiles":1,"macros":145,"cycle":["NEXT",20]},{"at_min":1.75,"tiles":16,"macros":141,"cycle":["NEXT",20]},{"at_min":2.0,"tiles":16,"macros":141,"cycle":["NEXT",20]},{"at_min":2.25,"tiles":32,"macros":134,"cycle":["NEXT",20]},{"at_min":2.5,"tiles":32,"macros":134,"cycle":["NEXT",19]},{"at_min":2.75,"tiles":32,"macros":134,"cycle":["NEXT",19]},{"at_min":3.0,"tiles":32,"macros":133,"cycle":["NEXT",19]},{"at_min":3.25,"tiles":58,"macros":121,"cycle":["NEXT",19]},{"at_min":3.5,"tiles":58,"macros":120,"cycle":["NEXT",16]},{"at_min":3.75,"tiles":43,"macros":126,"cycle":["NEXT",16]},{"at_min":4.0,"tiles":43,"macros":126,"cycle":["NEXT",14]},{"at_min":4.25,"tiles":27,"macros":131,"cycle":["NEXT",14]},{"at_min":4.5,"tiles":45,"macros":123,"cycle":["NEXT",13]},{"at_min":4.75,"tiles":59,"macros":108,"cycle":["NEXT",13]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":531,"done":530,"blocked":0,"timeout":0,"refused":0,"by_macro":{"GO ITEM":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":14,"done":14,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO SHOP":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"HEAL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"ITEM":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"MOVE 1":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":15,"done":15,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"MOVE 4":{"start":8,"done":8,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":463,"done":462,"blocked":0,"timeout":0,"refused":0},"NO":{"start":12,"done":12,"blocked":0,"timeout":0,"refused":0},"RUN":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"YES":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":3,"go_shop_done":3,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":1},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":1,"heal_done":1},"whiteouts":1,"battles":{"started":7,"ended":6,"wild":6,"trainer":1,"won":0,"lost":1,"caught":0,"other":5,"longest_frames":8265,"still_running":true,"macros_in_longest":167},"rewards":{"boundary":{"n":5,"total":0.35},"damage":{"n":7,"total":1.0852941176470587},"exploration":{"n":4,"total":0.2},"map":{"n":2,"total":0.4},"talk":{"n":1,"total":0.1}},"scenes":{"battle":22911,"dialog":2312,"overworld":9408,"unknown":1207},"ended_map":51},{"checkpoint":"r15-yard","seed":1,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":1306,"wall_seconds":1275.632209411,"rungs":{"start":15,"end":15,"gained":0,"climbs":[]},"places_start":3515,"places_end":3547,"pad":{"empty_frames":1328,"empty_seconds":22.23431396484375,"empty_fraction":0.037055639265584014,"longest_empty_seconds":3.5661964416503906},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":78,"macros":112,"cycle":["NEXT",18]},{"at_min":0.25,"tiles":71,"macros":112,"cycle":["NEXT",18]},{"at_min":0.5,"tiles":58,"macros":117,"cycle":["NEXT",18]},{"at_min":0.75,"tiles":55,"macros":119,"cycle":["NEXT",18]},{"at_min":1.0,"tiles":55,"macros":120,"cycle":["NEXT",18]},{"at_min":1.25,"tiles":76,"macros":111,"cycle":["NEXT",18]},{"at_min":1.5,"tiles":101,"macros":94,"cycle":["NEXT",18]},{"at_min":1.75,"tiles":104,"macros":85,"cycle":["NEXT",13]},{"at_min":2.0,"tiles":99,"macros":88,"cycle":["NEXT",13]},{"at_min":2.25,"tiles":74,"macros":98,"cycle":["NEXT",13]},{"at_min":2.5,"tiles":109,"macros":81,"cycle":["NEXT",13]},{"at_min":2.75,"tiles":114,"macros":79,"cycle":["NEXT",13]},{"at_min":3.0,"tiles":114,"macros":80,"cycle":["NEXT",13]},{"at_min":3.25,"tiles":93,"macros":88,"cycle":["NEXT",13]},{"at_min":3.5,"tiles":86,"macros":104,"cycle":["NEXT",13]},{"at_min":3.75,"tiles":77,"macros":112,"cycle":["NEXT",14]},{"at_min":4.0,"tiles":67,"macros":117,"cycle":["NEXT",14]},{"at_min":4.25,"tiles":56,"macros":120,"cycle":["NEXT",14]},{"at_min":4.5,"tiles":54,"macros":121,"cycle":["NEXT",14]},{"at_min":4.75,"tiles":82,"macros":108,"cycle":["NEXT",14]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":466,"done":463,"blocked":2,"timeout":0,"refused":1,"by_macro":{"BUY BALL":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"CONFIRM":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"GO FRONTIER":{"start":5,"done":3,"blocked":2,"timeout":0,"refused":0},"GO HEAL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":20,"done":19,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":1},"GO SHOP":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"HEAL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"LEAVE":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"MOVE 1":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":13,"done":13,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":377,"done":377,"blocked":0,"timeout":0,"refused":0},"NO":{"start":17,"done":17,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"YES":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":3,"go_shop_done":3,"buy_ball_start":2,"buy_ball_done":2,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":2,"balls_spent":0,"depth":2},"heals":{"go_heal_start":1,"go_heal_done":1,"heal_start":1,"heal_done":1},"whiteouts":1,"battles":{"started":6,"ended":6,"wild":5,"trainer":1,"won":0,"lost":1,"caught":0,"other":5,"longest_frames":4959,"still_running":false,"macros_in_longest":102},"rewards":{"boundary":{"n":2,"total":0.15000000000000002},"damage":{"n":5,"total":1.0},"exploration":{"n":2,"total":0.1},"map":{"n":2,"total":0.4},"talk":{"n":5,"total":0.5}},"scenes":{"battle":17567,"dialog":3433,"overworld":12704,"shop":775,"unknown":1359},"ended_map":14},{"checkpoint":"r15-yard","seed":2,"runtime":"session","mode":"macros","minutes":10.000133333333334,"frames":35838,"idle_frames":835,"wall_seconds":1235.921977595,"rungs":{"start":15,"end":15,"gained":0,"climbs":[]},"places_start":3515,"places_end":3537,"pad":{"empty_frames":1547,"empty_seconds":25.90096664428711,"empty_fraction":0.04316647134326693,"longest_empty_seconds":3.6833953857421875},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":84,"macros":104,"cycle":["NEXT",17]},{"at_min":0.25,"tiles":74,"macros":107,"cycle":["NEXT",17]},{"at_min":0.5,"tiles":76,"macros":109,"cycle":["NEXT",17]},{"at_min":0.75,"tiles":64,"macros":114,"cycle":["NEXT",17]},{"at_min":1.0,"tiles":56,"macros":121,"cycle":["NEXT",17]},{"at_min":1.25,"tiles":56,"macros":120,"cycle":["NEXT",17]},{"at_min":1.5,"tiles":67,"macros":115,"cycle":["NEXT",14]},{"at_min":1.75,"tiles":99,"macros":99,"cycle":["NEXT",13]},{"at_min":2.0,"tiles":119,"macros":91,"cycle":["NEXT",13]},{"at_min":2.25,"tiles":93,"macros":102,"cycle":["NEXT",13]},{"at_min":2.5,"tiles":94,"macros":99,"cycle":["NEXT",11]},{"at_min":2.75,"tiles":120,"macros":88,"cycle":["NEXT",11]},{"at_min":3.0,"tiles":120,"macros":89,"cycle":["NEXT",14]},{"at_min":3.25,"tiles":120,"macros":90,"cycle":["NEXT",14]},{"at_min":3.5,"tiles":109,"macros":94,"cycle":["NEXT",14]},{"at_min":3.75,"tiles":89,"macros":108,"cycle":["NEXT",14]},{"at_min":4.0,"tiles":101,"macros":104,"cycle":["NEXT",14]},{"at_min":4.25,"tiles":123,"macros":91,"cycle":["NEXT",14]},{"at_min":4.5,"tiles":85,"macros":107,"cycle":["NEXT",14]},{"at_min":4.75,"tiles":64,"macros":116,"cycle":["NEXT",13]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":508,"done":506,"blocked":1,"timeout":0,"refused":1,"by_macro":{"GO FRONTIER":{"start":4,"done":3,"blocked":1,"timeout":0,"refused":0},"GO HEAL":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO ITEM":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":18,"done":18,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":1},"GO SHOP":{"start":6,"done":5,"blocked":0,"timeout":0,"refused":0},"GO WARP":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"MOVE 1":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":15,"done":15,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":6,"done":6,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":422,"done":422,"blocked":0,"timeout":0,"refused":0},"NO":{"start":16,"done":16,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"YES":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":6,"go_shop_done":5,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":1},"heals":{"go_heal_start":2,"go_heal_done":2,"heal_start":0,"heal_done":0},"whiteouts":1,"battles":{"started":7,"ended":7,"wild":6,"trainer":1,"won":0,"lost":1,"caught":0,"other":6,"longest_frames":3852,"still_running":false,"macros_in_longest":79},"rewards":{"boundary":{"n":4,"total":0.3},"damage":{"n":6,"total":1.1},"exploration":{"n":2,"total":0.1},"map":{"n":2,"total":0.4},"talk":{"n":4,"total":0.4}},"scenes":{"battle":19656,"dialog":3036,"overworld":11569,"unknown":1577},"ended_map":58},{"checkpoint":"r15-yard","seed":3,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":883,"wall_seconds":680.704734927,"rungs":{"start":15,"end":15,"gained":0,"climbs":[]},"places_start":3515,"places_end":3530,"pad":{"empty_frames":1553,"empty_seconds":26.001422882080078,"empty_fraction":0.04333389140018974,"longest_empty_seconds":3.6833953857421875},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":33,"first_flagged":[{"at_min":0.0,"tiles":84,"macros":103,"cycle":["NEXT",18]},{"at_min":0.25,"tiles":70,"macros":109,"cycle":["NEXT",18]},{"at_min":0.5,"tiles":79,"macros":108,"cycle":["NEXT",18]},{"at_min":0.75,"tiles":64,"macros":115,"cycle":["NEXT",18]},{"at_min":1.0,"tiles":56,"macros":122,"cycle":["NEXT",18]},{"at_min":1.25,"tiles":56,"macros":123,"cycle":["NEXT",17]},{"at_min":1.5,"tiles":56,"macros":122,"cycle":["NEXT",15]},{"at_min":1.75,"tiles":63,"macros":118,"cycle":["NEXT",14]},{"at_min":2.0,"tiles":63,"macros":118,"cycle":["NEXT",14]},{"at_min":2.25,"tiles":42,"macros":126,"cycle":["NEXT",14]},{"at_min":2.5,"tiles":12,"macros":139,"cycle":["NEXT",13]},{"at_min":2.75,"tiles":43,"macros":124,"cycle":["NEXT",13]},{"at_min":3.0,"tiles":82,"macros":106,"cycle":["NEXT",13]},{"at_min":3.25,"tiles":118,"macros":89,"cycle":["NEXT",13]},{"at_min":3.5,"tiles":148,"macros":75,"cycle":["NEXT",13]},{"at_min":3.75,"tiles":179,"macros":60,"cycle":["NEXT",11]},{"at_min":4.0,"tiles":186,"macros":57,"cycle":["NEXT",13]},{"at_min":4.25,"tiles":186,"macros":58,"cycle":["NEXT",13]},{"at_min":4.5,"tiles":188,"macros":58,"cycle":["NEXT",13]},{"at_min":4.75,"tiles":167,"macros":68,"cycle":["NEXT",13]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":436,"done":434,"blocked":1,"timeout":1,"refused":1,"by_macro":{"GO FRONTIER":{"start":3,"done":2,"blocked":1,"timeout":0,"refused":0},"GO ITEM":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":22,"done":21,"blocked":0,"timeout":1,"refused":0},"GO OUT":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":1},"GO SHOP":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"GO WARP":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"MOVE 1":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"MOVE 2":{"start":12,"done":12,"blocked":0,"timeout":0,"refused":0},"MOVE 3":{"start":6,"done":6,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":370,"done":370,"blocked":0,"timeout":0,"refused":0},"NO":{"start":5,"done":5,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":5,"go_shop_done":5,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":0,"throw_ball_done":0,"catches":0,"species_gained":0,"balls_gained":0,"balls_spent":0,"depth":1},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":0,"heal_done":0},"whiteouts":1,"battles":{"started":8,"ended":7,"wild":7,"trainer":1,"won":0,"lost":1,"caught":0,"other":6,"longest_frames":3956,"still_running":true,"macros_in_longest":81},"rewards":{"boundary":{"n":4,"total":0.3},"damage":{"n":6,"total":1.2},"exploration":{"n":2,"total":0.1},"talk":{"n":2,"total":0.2}},"scenes":{"battle":18474,"dialog":946,"overworld":14841,"unknown":1577},"ended_map":59},{"checkpoint":"r15-nugget-bridge","seed":1,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":1306,"wall_seconds":674.564169632,"rungs":{"start":15,"end":15,"gained":0,"climbs":[]},"places_start":2527,"places_end":2528,"pad":{"empty_frames":3344,"empty_seconds":55.98760986328125,"empty_fraction":0.09330877839165132,"longest_empty_seconds":6.445941925048828},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":9,"first_flagged":[{"at_min":0.0,"tiles":68,"macros":61,"cycle":["NEXT",22]},{"at_min":5.5,"tiles":85,"macros":47,"cycle":["NEXT",13]},{"at_min":5.75,"tiles":85,"macros":49,"cycle":["NEXT",13]},{"at_min":6.0,"tiles":85,"macros":52,"cycle":["NEXT",13]},{"at_min":6.25,"tiles":85,"macros":51,"cycle":["NEXT",13]},{"at_min":6.5,"tiles":84,"macros":50,"cycle":["NEXT",13]},{"at_min":6.75,"tiles":80,"macros":47,"cycle":["NEXT",13]},{"at_min":7.0,"tiles":79,"macros":39,"cycle":["NEXT",13]},{"at_min":7.25,"tiles":64,"macros":33,"cycle":["NEXT",12]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":173,"done":171,"blocked":1,"timeout":0,"refused":0,"by_macro":{"GO FRONTIER":{"start":26,"done":25,"blocked":0,"timeout":0,"refused":0},"GO ITEM":{"start":2,"done":1,"blocked":1,"timeout":0,"refused":0},"GO NPC":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":17,"done":17,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":7,"done":7,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":25,"done":25,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":80,"done":80,"blocked":0,"timeout":0,"refused":0},"NO":{"start":4,"done":4,"blocked":0,"timeout":0,"refused":0},"SWITCH":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":9,"done":9,"blocked":0,"timeout":0,"refused":0},"THROW BALL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":0,"go_shop_done":0,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":1,"throw_ball_done":1,"catches":1,"species_gained":1,"balls_gained":0,"balls_spent":1,"depth":0},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":0,"heal_done":0},"whiteouts":0,"battles":{"started":2,"ended":2,"wild":2,"trainer":0,"won":0,"lost":0,"caught":1,"other":1,"longest_frames":1434,"still_running":false,"macros_in_longest":22},"rewards":{"catch":{"n":1,"total":0.1},"species":{"n":1,"total":0.5}},"scenes":{"battle":2374,"dialog":2000,"overworld":28075,"unknown":3389},"ended_map":36},{"checkpoint":"r15-nugget-bridge","seed":2,"runtime":"session","mode":"macros","minutes":10.000133333333334,"frames":35838,"idle_frames":835,"wall_seconds":679.297827897,"rungs":{"start":15,"end":15,"gained":0,"climbs":[]},"places_start":2527,"places_end":2527,"pad":{"empty_frames":4264,"empty_seconds":71.39089965820312,"empty_fraction":0.11897985378648362,"longest_empty_seconds":18.015151977539062},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":1,"first_flagged":[{"at_min":0.0,"tiles":59,"macros":51,"cycle":["NEXT",22]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":146,"done":146,"blocked":0,"timeout":0,"refused":0,"by_macro":{"GO FRONTIER":{"start":25,"done":25,"blocked":0,"timeout":0,"refused":0},"GO ITEM":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO NPC":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":13,"done":13,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":13,"done":13,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":27,"done":27,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":55,"done":55,"blocked":0,"timeout":0,"refused":0},"NO":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":8,"done":8,"blocked":0,"timeout":0,"refused":0},"THROW BALL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":0,"go_shop_done":0,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":1,"throw_ball_done":1,"catches":1,"species_gained":1,"balls_gained":0,"balls_spent":1,"depth":0},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":0,"heal_done":0},"whiteouts":0,"battles":{"started":1,"ended":1,"wild":1,"trainer":0,"won":0,"lost":0,"caught":1,"other":0,"longest_frames":2125,"still_running":false,"macros_in_longest":22},"rewards":{"catch":{"n":1,"total":0.1},"species":{"n":1,"total":0.5}},"scenes":{"battle":1049,"dialog":1870,"overworld":28602,"unknown":4317},"ended_map":88},{"checkpoint":"r15-nugget-bridge","seed":3,"runtime":"session","mode":"macros","minutes":10.00015,"frames":35838,"idle_frames":883,"wall_seconds":667.070451439,"rungs":{"start":15,"end":15,"gained":0,"climbs":[]},"places_start":2527,"places_end":2527,"pad":{"empty_frames":5238,"empty_seconds":87.69829559326172,"empty_fraction":0.1461577096936213,"longest_empty_seconds":28.646770477294922},"watchdog":{"probes":4,"suspected":0,"confirmed":0,"ladder_events":0,"reasons":{},"flagged":[]},"hunt":{"windows":33,"flagged":1,"first_flagged":[{"at_min":0.0,"tiles":58,"macros":45,"cycle":["NEXT",22]}]},"ratchet":{"rollbacks":0,"game_over":0,"stall":0},"macros":{"starts":138,"done":137,"blocked":0,"timeout":0,"refused":0,"by_macro":{"GO FRONTIER":{"start":21,"done":21,"blocked":0,"timeout":0,"refused":0},"GO ITEM":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0},"GO NPC":{"start":2,"done":2,"blocked":0,"timeout":0,"refused":0},"GO OBJECTIVE":{"start":17,"done":17,"blocked":0,"timeout":0,"refused":0},"GO OUT":{"start":12,"done":12,"blocked":0,"timeout":0,"refused":0},"GO ROUTE":{"start":30,"done":29,"blocked":0,"timeout":0,"refused":0},"NEXT":{"start":45,"done":45,"blocked":0,"timeout":0,"refused":0},"NO":{"start":3,"done":3,"blocked":0,"timeout":0,"refused":0},"TALK":{"start":6,"done":6,"blocked":0,"timeout":0,"refused":0},"THROW BALL":{"start":1,"done":1,"blocked":0,"timeout":0,"refused":0}}},"funnel":{"go_shop_start":0,"go_shop_done":0,"buy_ball_start":0,"buy_ball_done":0,"throw_ball_start":1,"throw_ball_done":1,"catches":1,"species_gained":1,"balls_gained":0,"balls_spent":1,"depth":0},"heals":{"go_heal_start":0,"go_heal_done":0,"heal_start":0,"heal_done":0},"whiteouts":0,"battles":{"started":1,"ended":1,"wild":1,"trainer":0,"won":0,"lost":0,"caught":1,"other":0,"longest_frames":2760,"still_running":false,"macros_in_longest":22},"rewards":{"catch":{"n":1,"total":0.1},"species":{"n":1,"total":0.5}},"scenes":{"battle":1049,"dialog":1398,"overworld":28095,"unknown":5296},"ended_map":36}],"failed_runs":[]} From 7dc744fe63ec6cf459128591bd6526beb5cda274 Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 02:29:15 +0000 Subject: [PATCH 14/27] scorecard: the lockfile gains the crate --- services/flysim/Cargo.lock | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/services/flysim/Cargo.lock b/services/flysim/Cargo.lock index 1676957..827747a 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -476,6 +476,23 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "fly-scorecard" +version = "0.1.1" +dependencies = [ + "anyhow", + "clap", + "fly-legacy-session", + "fly-session", + "flybrain-core", + "flybrain-gb", + "flysim", + "serde", + "serde_json", + "tempfile", + "tokio", +] + [[package]] name = "fly-session" version = "0.1.1" From 076a6bcbbf6214abb195f3f8078268500525c7d3 Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 03:04:34 +0000 Subject: [PATCH 15/27] BUS-01 review notes: shadow check refuses on the session runtime (N1), workers die with their parent via PR_SET_PDEATHSIG (N2), test for the Hello digest refusal (N3) --- infra/bin/fly-shadow-run | 6 ++ infra/tests/lint.sh | 17 +++++ services/flysim/Cargo.lock | 1 + services/flysim/crates/fly-session/Cargo.toml | 2 + .../flysim/crates/fly-session/src/launcher.rs | 27 +++++++ .../crates/fly-session/tests/orphans.rs | 74 +++++++++++++++++++ .../crates/flybus/tests/conformance_wire.rs | 64 ++++++++++++++++ 7 files changed, 191 insertions(+) create mode 100644 services/flysim/crates/fly-session/tests/orphans.rs diff --git a/infra/bin/fly-shadow-run b/infra/bin/fly-shadow-run index 41c3f42..4b301f2 100755 --- a/infra/bin/fly-shadow-run +++ b/infra/bin/fly-shadow-run @@ -518,6 +518,12 @@ check() { esac done set -- "${pass[@]}" + # Only the legacy loop writes the trace the shadow follows: if the live fly moved to the session + # runtime during the window, the verdict no longer covers what would be cut over. + if [ -f "$RUNTIME_DROPIN" ]; then + echo "cutover refused: flysim.service runs the session runtime, which writes no trace for a shadow to follow (switch the live fly to legacy for the shadow window: fly-runtime legacy)" + exit 1 + fi # A tripped guard, a shadow that is not running, or a run that no guard watched never allows a # cutover, whatever the verdict file says: the guard timer must be active and its baseline # present (G1-a). diff --git a/infra/tests/lint.sh b/infra/tests/lint.sh index b7347b9..ba4c397 100755 --- a/infra/tests/lint.sh +++ b/infra/tests/lint.sh @@ -870,6 +870,23 @@ if command -v python3 >/dev/null 2>&1; then else fail "fly-shadow-run check --bus must pass --require-arm bus/process to fly-shadow check ($(cat "$cb_tmp/args" 2>/dev/null))" fi + # BUS-01 review N1: `check` (plain and --bus) refuses while the live fly runs the session + # runtime, which writes no trace for the shadow to follow, and never asks fly-shadow. + printf '[Service]\nExecStart=/opt/fly/current/flysim-session\n' > "$cb_tmp/10-runtime.conf" + for ck_args in "" "--bus"; do + rm -f "$cb_tmp/args" + ck_rc=0 + # shellcheck disable=SC2086 + ck_out="$(PATH="$cb_tmp/bin:$PATH" FLY_SHADOW_DIR="$cb_tmp/shadow" FLY_SHADOW_BIN="$cb_tmp/fly-shadow" \ + FLY_SHADOW_REMOTE_DROPIN_DIR="$cb_tmp/none.d" FLY_ENV_FILE="$cb_tmp/none.env" \ + FLY_RUNTIME_DROPIN="$cb_tmp/10-runtime.conf" \ + "$INFRA_DIR/bin/fly-shadow-run" check $ck_args 2>&1)" || ck_rc=$? + if [ "$ck_rc" -ne 0 ] && echo "$ck_out" | grep -q 'runs the session runtime' && [ ! -e "$cb_tmp/args" ]; then + pass "fly-shadow-run check${ck_args:+ $ck_args} refuses while the live fly runs the session runtime" + else + fail "fly-shadow-run check${ck_args:+ $ck_args} must refuse while the session runtime drop-in exists (rc=$ck_rc): $ck_out" + fi + done rm -rf "$cb_tmp" fi # SHADOW-02: `check` in remote mode also needs the relay healthy now (relay.json under a minute diff --git a/services/flysim/Cargo.lock b/services/flysim/Cargo.lock index 1676957..21bcef7 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -486,6 +486,7 @@ dependencies = [ "flybrain-gb", "flybus", "flysim-store", + "libc", "serde_json", "tempfile", "tokio", diff --git a/services/flysim/crates/fly-session/Cargo.toml b/services/flysim/crates/fly-session/Cargo.toml index 1af661b..059177e 100644 --- a/services/flysim/crates/fly-session/Cargo.toml +++ b/services/flysim/crates/fly-session/Cargo.toml @@ -36,6 +36,8 @@ flate2 = { workspace = true } flysim-store = { path = "../flysim-store" } serde_json = { workspace = true } +# PR_SET_PDEATHSIG for worker processes (a child never outlives its parent, systemd or not). +libc = "0.2" # `rt-multi-thread` is not only for the tests: a worker process and a dedicated-thread # worker each build their own runtime sized to the launcher's thread allocation. tokio = { version = "1", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "io-util"] } diff --git a/services/flysim/crates/fly-session/src/launcher.rs b/services/flysim/crates/fly-session/src/launcher.rs index d1e2a51..5a5970e 100644 --- a/services/flysim/crates/fly-session/src/launcher.rs +++ b/services/flysim/crates/fly-session/src/launcher.rs @@ -548,6 +548,32 @@ pub fn default_worker_program() -> PathBuf { PathBuf::from(name) } +/// Makes `command`'s child die with its parent (BUS-01 review N2): the kernel sends it SIGKILL when +/// the parent *thread* that spawned it exits, so a worker never outlives its coordinator even outside +/// systemd's cgroup kill (a hung worker used to survive a killed parent, once for 47 hours). +/// +/// Linux delivers the signal when the spawning thread ends, not the whole process, so spawn from a +/// thread that lives as long as the process: a runtime worker or the main thread, never a +/// short-lived blocking-pool thread. Setting the signal races a parent that already died; the child +/// checks its parent id after setting it and exits if it was already re-parented. +pub fn die_with_parent(command: &mut std::process::Command) { + use std::os::unix::process::CommandExt; + let parent = std::process::id() as libc::pid_t; + // SAFETY: the closure runs between fork and exec and calls only async-signal-safe functions + // (prctl, getppid, _exit); it allocates nothing and takes no locks. + unsafe { + command.pre_exec(move || { + if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL as libc::c_ulong, 0, 0, 0) != 0 { + return Err(std::io::Error::last_os_error()); + } + if libc::getppid() != parent { + libc::_exit(1); + } + Ok(()) + }); + } +} + impl Launcher { /// Connects the supervisor and prepares the launcher. Nothing is started yet. pub async fn start( @@ -1011,6 +1037,7 @@ impl Launcher { } } command.stdin(std::process::Stdio::null()); + die_with_parent(&mut command); let child = command.spawn().map_err(|e| { DomainError::new( ErrorCode::BackendFailure, diff --git a/services/flysim/crates/fly-session/tests/orphans.rs b/services/flysim/crates/fly-session/tests/orphans.rs new file mode 100644 index 0000000..ab0fcbe --- /dev/null +++ b/services/flysim/crates/fly-session/tests/orphans.rs @@ -0,0 +1,74 @@ +//! BUS-01 review N2: a worker process never outlives its parent, outside systemd too. +//! +//! The test re-executes its own binary as the "parent" (selected by an environment variable), +//! which spawns one worker through the launcher's `die_with_parent` and one plain control child, +//! then waits. The outer test `kill -9`s the parent and checks the worker is gone within a bound +//! while the control child, which has no death signal, survives (so the check can fail). + +use std::io::{BufRead, BufReader}; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +const ROLE: &str = "FLY_TEST_ORPHAN_PARENT"; +const BOUND: Duration = Duration::from_secs(5); + +/// True while `pid` is a live process (a zombie awaiting its reaper counts as gone). +fn alive(pid: u32) -> bool { + match std::fs::read_to_string(format!("/proc/{pid}/stat")) { + Ok(stat) => { + let state = stat.rsplit(')').next().unwrap_or("").trim().chars().next(); + state != Some('Z') && state != Some('X') + } + Err(_) => false, + } +} + +fn wait_gone(pid: u32) -> bool { + let start = Instant::now(); + while start.elapsed() < BOUND { + if !alive(pid) { + return true; + } + std::thread::sleep(Duration::from_millis(50)); + } + false +} + +#[test] +fn a_killed_parent_takes_its_workers_with_it() { + if std::env::var_os(ROLE).is_some() { + // The parent: spawn a protected worker and an unprotected control, report, then wait. + let mut worker = Command::new("sleep"); + worker.arg("300"); + fly_session::launcher::die_with_parent(&mut worker); + let worker = worker.spawn().unwrap(); + let control = Command::new("sleep").arg("300").spawn().unwrap(); + println!("{} {}", worker.id(), control.id()); + std::thread::sleep(Duration::from_secs(600)); + return; + } + let mut parent = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "a_killed_parent_takes_its_workers_with_it", "--nocapture", "--test-threads=1"]) + .env(ROLE, "1") + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let mut lines = BufReader::new(parent.stdout.take().unwrap()).lines(); + let (worker, control) = loop { + let line = lines.next().expect("the parent reports its children").unwrap(); + let ids: Vec = line.split_whitespace().filter_map(|t| t.parse().ok()).collect(); + if ids.len() == 2 { + break (ids[0], ids[1]); + } + }; + assert!(alive(worker) && alive(control)); + // SIGKILL: no cleanup runs in the parent, so only the kernel can take the worker down. + unsafe { libc::kill(parent.id() as i32, libc::SIGKILL) }; + parent.wait().unwrap(); + let worker_gone = wait_gone(worker); + let control_survived = alive(control); + unsafe { libc::kill(control as i32, libc::SIGKILL) }; + unsafe { libc::kill(worker as i32, libc::SIGKILL) }; + assert!(worker_gone, "the worker outlived its killed parent"); + assert!(control_survived, "the control child should have survived (the check cannot fail otherwise)"); +} diff --git a/services/flysim/crates/flybus/tests/conformance_wire.rs b/services/flysim/crates/flybus/tests/conformance_wire.rs index 06ad73d..83f3555 100644 --- a/services/flysim/crates/flybus/tests/conformance_wire.rs +++ b/services/flysim/crates/flybus/tests/conformance_wire.rs @@ -589,6 +589,70 @@ both_transports!( hello_reports_the_contract_digest_and_valid_limits, ); +// ------------------------------------------------------------------------------------------- +// Review note N3 (BUS-01): the SDK refuses a router whose contract digest is not its own, at +// Hello, with the explicit version-mismatch error. The wire change that added `readLocation` +// moved the digest, so a client and router built from different sources must not talk. + +/// Serves one Hello on `server` the way the router does, announcing `digest`. +async fn answer_hello_with(server: tokio::io::DuplexStream, digest: String) { + let (mut rd, mut wr) = tokio::io::split(server); + let bytes = read_frame(&mut rd).await.unwrap().expect("a hello frame"); + let hello = Envelope::decode(&bytes).unwrap(); + assert_eq!(hello.op, "bus.hello"); + let value = json!({ + "routerId": "router-1", "connectionId": "conn-1", + "selectedMajor": 1, "selectedMinor": 0, + "contractDigest": digest, + "limits": Limits::default().to_json(), + }); + let mut body = Map::new(); + body.insert("ok".into(), json!(true)); + body.insert("value".into(), value); + let mut reply = Envelope::new("bus-1".into(), Kind::Reply, "bus.hello", body); + reply.reply_to = Some(hello.id); + write_frame(&mut wr, &reply.encode().unwrap()).await.unwrap(); + // Keep the connection open until the client has decided. + tokio::time::sleep(Duration::from_secs(2)).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_client_refuses_a_router_with_a_different_contract_digest_at_hello() { + let dir = tempfile::tempdir().unwrap(); + let wrong = "0".repeat(64); + assert_ne!(wrong, contract_digest()); + let (client_end, server_end) = tokio::io::duplex(64 * 1024); + tokio::spawn(answer_hello_with(server_end, wrong)); + let refused = within( + "hello", + flybus::Client::connect( + flybus::Transport::from_stream(client_end), + flybus::ClientConfig::new("digest-client", dir.path()), + ), + ) + .await; + let err = refused.err().expect("a mismatched digest must be refused"); + assert_eq!(err.code, flybus::ErrorCode::VersionMismatch); + assert_eq!(err.message, "router speaks a different contract"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn the_same_fake_router_with_the_right_digest_is_accepted() { + let dir = tempfile::tempdir().unwrap(); + let (client_end, server_end) = tokio::io::duplex(64 * 1024); + tokio::spawn(answer_hello_with(server_end, contract_digest())); + let client = within( + "hello", + flybus::Client::connect( + flybus::Transport::from_stream(client_end), + flybus::ClientConfig::new("digest-client", dir.path()), + ), + ) + .await + .expect("a matching digest is accepted"); + assert_eq!(client.info().contract_digest, contract_digest()); +} + // ------------------------------------------------------------------------------------------- // bus-v1 §11 acceptance test 1: "In-memory transport must pass the same tests as Unix // sockets." Every test above already runs on both (that is what `both_transports!` is for); From 49309a83bd243c7c2ad3a93d83eb4a6abe1e50c1 Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 03:50:50 +0000 Subject: [PATCH 16/27] scorecard: per-checkpoint trap rule, Holm over the metric family, throws count throws, children die with the suite, LegacyConfig fields The compare could not fail a trap confined to one checkpoint: add a rule per checkpoint (B trapped on two or more runs and two more than A, or a blocked-macro storm A lacks). Holm-adjust the sign-flip p-values over the judged metrics (the unadjusted family false-failed about 15% of releases). throws_per_hour counts THROW BALL done, not starts; blocked throws are their own reported metric. run-one children get PR_SET_PDEATHSIG. runner.rs sets transport and placements (main's LegacyConfig); overlay.sh drops those lines for trees without the fields. --- .../flysim/crates/fly-scorecard/Cargo.toml | 1 + .../crates/fly-scorecard/src/compare.rs | 369 ++++++++++++++++-- .../flysim/crates/fly-scorecard/src/runner.rs | 6 + .../flysim/crates/fly-scorecard/src/suite.rs | 29 +- tools/scorecard/overlay.sh | 6 + 5 files changed, 377 insertions(+), 34 deletions(-) diff --git a/services/flysim/crates/fly-scorecard/Cargo.toml b/services/flysim/crates/fly-scorecard/Cargo.toml index 4d1c6bd..7d570a6 100644 --- a/services/flysim/crates/fly-scorecard/Cargo.toml +++ b/services/flysim/crates/fly-scorecard/Cargo.toml @@ -29,3 +29,4 @@ serde = { workspace = true } serde_json = { workspace = true } tokio = { version = "1", features = ["rt", "rt-multi-thread", "sync", "time", "macros"] } tempfile = "3" +libc = "0.2" diff --git a/services/flysim/crates/fly-scorecard/src/compare.rs b/services/flysim/crates/fly-scorecard/src/compare.rs index 7bc5c92..500303f 100644 --- a/services/flysim/crates/fly-scorecard/src/compare.rs +++ b/services/flysim/crates/fly-scorecard/src/compare.rs @@ -3,8 +3,13 @@ //! The runs of the two suites are paired by `(checkpoint, seed)`. Each pair gives one difference //! per metric, signed so that positive means B is worse. A metric fails when B is worse than A by //! more than its tolerance **and** a sign-flip permutation test over the pairs says the shortfall -//! is not noise (one-sided, `alpha`). Otherwise it passes, and when B is better by the same two -//! tests it says so. A metric with no direction (`info`) is only reported. +//! is not noise (one-sided, `alpha`, Holm-adjusted over the judged metrics so the whole compare +//! has a family-wise false-fail rate of at most `alpha` under "nothing changed", where the +//! unadjusted per-metric test had about 15% over 13 metrics). Otherwise it passes, and when B is +//! better by the same two tests it says so. A metric with no direction (`info`) is only reported. +//! +//! The pooled test cannot see a trap confined to one place (three seeds of one checkpoint among +//! thirty-six pairs), so a second, non-statistical rule runs per checkpoint: see [`trap_rule`]. //! //! The test is exact up to 20 pairs and a fixed-seed Monte-Carlo beyond, so the same two suites //! always give the same verdicts. @@ -135,7 +140,17 @@ pub const METRICS: &[Metric] = &[ direction: Direction::Up, abs_tol: 0.5, rel_tol: 0.25, - read: |r| per_hour(r.funnel.throw_ball_start as f64, r), + read: |r| per_hour(r.funnel.throw_ball_done as f64, r), + }, + // Reported, never judged on its own: a blocked THROW BALL storm is the trap rule's and the + // watchdog's business, and `throws_per_hour` above counts only throws that happened. + Metric { + name: "throw_ball_blocked_per_hour", + unit: "blocked/h", + direction: Direction::Info, + abs_tol: 0.0, + rel_tol: 0.0, + read: |r| per_hour(r.macros.by_macro.get("THROW BALL").map_or(0, |c| c.blocked) as f64, r), }, Metric { name: "catches_per_hour", @@ -247,6 +262,106 @@ pub fn sign_flip_p(diffs: &[f64]) -> f64 { at_least as f64 / (draws + 1) as f64 } +/// Holm's step-down adjustment: the adjusted p of each value (same order), so that rejecting +/// where `adjusted < alpha` controls the family-wise error rate at `alpha` under any dependence +/// between the tests. +pub fn holm_adjust(ps: &[f64]) -> Vec { + let m = ps.len(); + let mut order: Vec = (0..m).collect(); + order.sort_by(|&i, &j| ps[i].total_cmp(&ps[j])); + let mut adjusted = vec![1.0; m]; + let mut running = 0.0f64; + for (rank, &i) in order.iter().enumerate() { + running = running.max(((m - rank) as f64 * ps[i]).min(1.0)); + adjusted[i] = running; + } + adjusted +} + +/// Blocked finishes of one macro in one run that make a storm no watchdog window is needed to +/// read: the row-71 bag bug blocked THROW BALL 131 times in ten brain minutes. +pub const STORM_BLOCKED: u64 = 50; +/// Trapped runs of B on a checkpoint (and this many more than A) that fail the checkpoint. +pub const TRAP_RUNS: usize = 2; + +/// Why a run counts as trapped, if it does: a recovery-ladder event (two suspected watchdog +/// probes in a row, any rule including stalled and zero-progress), at least half the probes +/// suspected, or a blocked-macro storm. +pub fn trapped(run: &RunReport) -> Option { + if let Some((name, n)) = storm(run) { + return Some(format!("{n} blocked {name}")); + } + let w = &run.watchdog; + if w.ladder_events > 0 { + return Some(format!("{} ladder event(s), {}/{} probes suspected", w.ladder_events, w.suspected, w.probes)); + } + if w.probes >= 2 && w.suspected * 2 >= w.probes { + return Some(format!("{}/{} probes suspected", w.suspected, w.probes)); + } + None +} + +/// The macro with the most blocked finishes in the run when that is a storm. +pub fn storm(run: &RunReport) -> Option<(String, u64)> { + run.macros + .by_macro + .iter() + .map(|(name, c)| (name.clone(), c.blocked)) + .filter(|(_, n)| *n >= STORM_BLOCKED) + .max_by_key(|(_, n)| *n) +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct CheckpointTrap { + pub checkpoint: String, + pub runs_a: usize, + pub runs_b: usize, + pub trapped_a: usize, + pub trapped_b: usize, + pub storms_a: usize, + pub storms_b: usize, + /// What B's trapped runs looked like (seed: reason). + pub detail: Vec, +} + +/// The per-checkpoint trap rule, independent of the cross-seed test: a checkpoint FAILS when B is +/// trapped on at least `TRAP_RUNS` of its runs and on at least `TRAP_RUNS` more than A, or when B +/// has a blocked-macro storm on any run and A has none on that checkpoint. A fault confined to one +/// place cannot fail the pooled test (three seeds give a sign-flip p of at least 1/8, and the +/// shift is diluted over every checkpoint), but it is exactly the regression class this exists +/// for. Returns the failing checkpoints. +pub fn trap_rule(a: &SuiteReport, b: &SuiteReport) -> Vec { + let mut ids: Vec<&str> = b.runs.iter().map(|r| r.checkpoint.as_str()).collect(); + ids.sort_unstable(); + ids.dedup(); + let mut failing = Vec::new(); + for id in ids { + let ra: Vec<&RunReport> = a.runs.iter().filter(|r| r.checkpoint == id).collect(); + let rb: Vec<&RunReport> = b.runs.iter().filter(|r| r.checkpoint == id).collect(); + if ra.is_empty() { + continue; + } + let trapped_a = ra.iter().filter(|r| trapped(r).is_some()).count(); + let trapped_b = rb.iter().filter(|r| trapped(r).is_some()).count(); + let storms_a = ra.iter().filter(|r| storm(r).is_some()).count(); + let storms_b = rb.iter().filter(|r| storm(r).is_some()).count(); + let fails = (trapped_b >= TRAP_RUNS && trapped_b >= trapped_a + TRAP_RUNS) || (storms_b > 0 && storms_a == 0); + if fails { + failing.push(CheckpointTrap { + checkpoint: id.to_owned(), + runs_a: ra.len(), + runs_b: rb.len(), + trapped_a, + trapped_b, + storms_a, + storms_b, + detail: rb.iter().filter_map(|r| trapped(r).map(|why| format!("seed {}: {why}", r.seed))).collect(), + }); + } + } + failing +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Verdict { @@ -270,6 +385,11 @@ pub struct MetricVerdict { /// The one-sided p of "B is worse" and of "B is better". pub p_worse: f64, pub p_better: f64, + /// The same, Holm-adjusted over the judged metrics (what the verdict uses). + #[serde(default)] + pub p_worse_adj: f64, + #[serde(default)] + pub p_better_adj: f64, /// The smallest change that counts, in the metric's unit. pub tolerance: f64, pub verdict: Verdict, @@ -286,7 +406,10 @@ pub struct Comparison { pub unpaired_b: usize, pub notes: Vec, pub metrics: Vec, - /// Every metric that failed, in order. + /// Checkpoints the per-checkpoint trap rule failed. + #[serde(default)] + pub trapped_checkpoints: Vec, + /// Every metric that failed, in order, then `trap@` for each failed checkpoint. pub failed: Vec, pub pass: bool, } @@ -324,29 +447,56 @@ pub fn compare(a: &SuiteReport, b: &SuiteReport, alpha: f64) -> Comparison { (1.0 / alpha).log2().ceil() as usize )); } + // First the raw p-values of every metric, then Holm over the judged ones. + struct Raw { + mean_a: f64, + mean_b: f64, + delta: f64, + tolerance: f64, + shortfall: f64, + p_worse: f64, + p_better: f64, + } + let raws: Vec = METRICS + .iter() + .map(|metric| { + let va: Vec = pairs.iter().map(|(ra, _)| (metric.read)(ra)).collect(); + let vb: Vec = pairs.iter().map(|(_, rb)| (metric.read)(rb)).collect(); + let (mean_a, mean_b) = (mean(&va), mean(&vb)); + let delta = mean_b - mean_a; + // Signed so that positive is worse. + let sign = match metric.direction { + Direction::Up => -1.0, + Direction::Down | Direction::Info => 1.0, + }; + let worse: Vec = va.iter().zip(&vb).map(|(x, y)| sign * (y - x)).collect(); + let better: Vec = worse.iter().map(|d| -d).collect(); + Raw { + mean_a, + mean_b, + delta, + tolerance: metric.abs_tol.max(metric.rel_tol * mean_a.abs()), + shortfall: sign * delta, + p_worse: sign_flip_p(&worse), + p_better: sign_flip_p(&better), + } + }) + .collect(); + let judged: Vec = (0..METRICS.len()).filter(|&i| METRICS[i].direction != Direction::Info).collect(); + let adj_worse = holm_adjust(&judged.iter().map(|&i| raws[i].p_worse).collect::>()); + let adj_better = holm_adjust(&judged.iter().map(|&i| raws[i].p_better).collect::>()); let mut metrics = Vec::new(); - for metric in METRICS { - let va: Vec = pairs.iter().map(|(ra, _)| (metric.read)(ra)).collect(); - let vb: Vec = pairs.iter().map(|(_, rb)| (metric.read)(rb)).collect(); - let (mean_a, mean_b) = (mean(&va), mean(&vb)); - let delta = mean_b - mean_a; - let tolerance = metric.abs_tol.max(metric.rel_tol * mean_a.abs()); - // Signed so that positive is worse. - let sign = match metric.direction { - Direction::Up => -1.0, - Direction::Down | Direction::Info => 1.0, - }; - let worse: Vec = va.iter().zip(&vb).map(|(x, y)| sign * (y - x)).collect(); - let better: Vec = worse.iter().map(|d| -d).collect(); - let (p_worse, p_better) = (sign_flip_p(&worse), sign_flip_p(&better)); - let shortfall = sign * delta; + for (i, metric) in METRICS.iter().enumerate() { + let raw = &raws[i]; + let slot = judged.iter().position(|&j| j == i); + let (p_worse_adj, p_better_adj) = slot.map_or((raw.p_worse, raw.p_better), |k| (adj_worse[k], adj_better[k])); let verdict = if pairs.is_empty() { Verdict::None } else if metric.direction == Direction::Info { Verdict::Info - } else if shortfall > tolerance && p_worse < alpha { + } else if raw.shortfall > raw.tolerance && p_worse_adj < alpha { Verdict::Fail - } else if -shortfall > tolerance && p_better < alpha { + } else if -raw.shortfall > raw.tolerance && p_better_adj < alpha { Verdict::Better } else { Verdict::Pass @@ -356,20 +506,24 @@ pub fn compare(a: &SuiteReport, b: &SuiteReport, alpha: f64) -> Comparison { unit: metric.unit.to_owned(), direction: metric.direction, pairs: pairs.len(), - mean_a, - mean_b, - delta, - p_worse, - p_better, - tolerance, + mean_a: raw.mean_a, + mean_b: raw.mean_b, + delta: raw.delta, + p_worse: raw.p_worse, + p_better: raw.p_better, + p_worse_adj, + p_better_adj, + tolerance: raw.tolerance, verdict, }); } - let failed: Vec = metrics + let trapped_checkpoints = trap_rule(a, b); + let mut failed: Vec = metrics .iter() .filter(|m| m.verdict == Verdict::Fail) .map(|m| m.metric.clone()) .collect(); + failed.extend(trapped_checkpoints.iter().map(|t| format!("trap@{}", t.checkpoint))); Comparison { schema: "fly-scorecard-compare-v1".to_owned(), a: a.label.clone(), @@ -382,6 +536,7 @@ pub fn compare(a: &SuiteReport, b: &SuiteReport, alpha: f64) -> Comparison { pass: failed.is_empty() && !pairs.is_empty(), failed, metrics, + trapped_checkpoints, } } @@ -396,7 +551,7 @@ impl Comparison { if self.pass { "PASS" } else { "FAIL" } )); out.push_str(&format!( - "{} paired runs (alpha {} one-sided, sign-flip test); {} only in {}, {} only in {}.\n\n", + "{} paired runs (alpha {} one-sided, sign-flip test, Holm over the judged metrics); {} only in {}, {} only in {}.\n\n", self.pairs, self.alpha, self.unpaired_a, self.a, self.unpaired_b, self.b )); for note in &self.notes { @@ -406,7 +561,7 @@ impl Comparison { out.push('\n'); } out.push_str(&format!( - "| metric | {} | {} | delta | tolerance | p worse | p better | verdict |\n", + "| metric | {} | {} | delta | tolerance | p worse (Holm) | p better (Holm) | verdict |\n", self.a, self.b )); out.push_str("| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |\n"); @@ -425,8 +580,8 @@ impl Comparison { m.mean_b, m.delta, m.tolerance, - m.p_worse, - m.p_better, + m.p_worse_adj, + m.p_better_adj, match m.verdict { Verdict::Pass => "pass", Verdict::Better => "better", @@ -436,6 +591,24 @@ impl Comparison { } )); } + if !self.trapped_checkpoints.is_empty() { + out.push_str("\n**Per-checkpoint trap rule: FAIL**\n\n"); + for t in &self.trapped_checkpoints { + out.push_str(&format!( + "- `{}`: {} trapped / {} storm run(s) of {} in {}, against {} / {} of {} in {} ({})\n", + t.checkpoint, + t.trapped_b, + t.storms_b, + t.runs_b, + self.b, + t.trapped_a, + t.storms_a, + t.runs_a, + self.a, + t.detail.join("; ") + )); + } + } out } } @@ -573,6 +746,138 @@ mod tests { assert!(none.metrics.iter().all(|m| m.verdict == Verdict::None)); } + fn row71(r: &mut RunReport) { + // The v0.7.3 row-71 bag bug: THROW BALL started and blocked 131 times, suspected on every probe. + let c = r.macros.by_macro.entry("THROW BALL".into()).or_default(); + c.start = 132; + c.blocked = 131; + r.macros.blocked = 131; + r.watchdog.probes = 4; + r.watchdog.suspected = 4; + r.watchdog.ladder_events = 1; + } + + #[test] + fn a_trap_on_one_checkpoint_fails_though_the_pooled_test_cannot_see_it() { + let a = many("a", |_, _, _| {}); + let b = many("b", |ck, _, r| { + if ck == "r10" { + row71(r) + } + }); + let c = compare(&a, &b, 0.05); + assert!(!c.pass); + assert!(c.failed.contains(&"trap@r10".to_owned()), "{:?}", c.failed); + assert_eq!(c.trapped_checkpoints.len(), 1); + assert_eq!(c.trapped_checkpoints[0].trapped_b, 3); + assert!(c.markdown().contains("`r10`")); + // ... while the same suite against itself passes. + assert!(compare(&b, &b, 0.05).pass); + assert!(compare(&a, &a, 0.05).pass); + } + + #[test] + fn the_trap_rule_wants_two_seeds_or_a_storm_and_a_clean_a() { + let a = many("a", |_, _, _| {}); + // One trapped seed with no storm: not enough. + let one = many("b", |ck, s, r| { + if ck == "r10" && s == 1 { + r.watchdog.probes = 4; + r.watchdog.suspected = 3; + r.watchdog.ladder_events = 1; + } + }); + assert!(trap_rule(&a, &one).is_empty()); + // Two trapped seeds fail it. + let two = many("b", |ck, s, r| { + if ck == "r10" && s <= 2 { + r.watchdog.probes = 4; + r.watchdog.suspected = 3; + r.watchdog.ladder_events = 1; + } + }); + assert_eq!(trap_rule(&a, &two)[0].checkpoint, "r10"); + // One seed with a storm fails it. + let storm_one = many("b", |ck, s, r| { + if ck == "r11" && s == 3 { + r.macros.by_macro.entry("GO OUT".into()).or_default().blocked = 50; + } + }); + assert_eq!(trap_rule(&a, &storm_one)[0].checkpoint, "r11"); + // The same storm in A as well is not new. + assert!(trap_rule(&storm_one, &storm_one).is_empty()); + // A was trapped on two seeds already: B trapped on the same two is not a new trap. + assert!(trap_rule(&two, &two).is_empty()); + } + + #[test] + fn a_blocked_throw_is_not_a_throw() { + let r = run("x", 1, |r| { + r.funnel.throw_ball_start = 132; + r.funnel.throw_ball_done = 1; + row71(r); + }); + let get = |name: &str| (METRICS.iter().find(|m| m.name == name).unwrap().read)(&r); + assert!((get("throws_per_hour") - 5.0).abs() < 1e-9); + assert!((get("throw_ball_blocked_per_hour") - 131.0 * 5.0).abs() < 1e-9); + } + + #[test] + fn holm_adjusts_step_down_and_never_below_the_raw_p() { + let adj = holm_adjust(&[0.01, 0.04, 0.03, 0.20]); + let want = [0.04, 0.09, 0.09, 0.20]; + for (x, y) in adj.iter().zip(want) { + assert!((x - y).abs() < 1e-12, "{adj:?}"); + } + assert!(holm_adjust(&[]).is_empty()); + assert_eq!(holm_adjust(&[0.6, 0.9]), vec![1.0, 1.0]); + } + + /// The false-fail rate of the whole compare under "nothing changed but the trajectory": + /// resample each checkpoint's seeds with replacement (A is the committed v0.7.5 card, B a + /// bootstrap of it) and count failing compares. Slow; run with `--ignored --nocapture`. + #[test] + #[ignore = "a simulation: about a minute in release"] + fn null_false_fail_rate() { + let text = include_str!("../../../../../tools/scorecard/baseline-v0.7.5.json"); + let a: SuiteReport = serde_json::from_str(text).expect("baseline"); + let mut ids: Vec = a.runs.iter().map(|r| r.checkpoint.clone()).collect(); + ids.dedup(); + let mut state = 0x9e37_79b9_7f4a_7c15u64; + let mut next = move |n: usize| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state % n as u64) as usize + }; + let (reps, mut fails, mut metric_fails, mut trap_fails) = (200, 0, 0, 0); + let mut by_checkpoint = BTreeMap::new(); + for _ in 0..reps { + let mut b = a.clone(); + b.label = "boot".into(); + b.runs.clear(); + for id in &ids { + let pool: Vec<&RunReport> = a.runs.iter().filter(|r| &r.checkpoint == id).collect(); + for (seed, _) in pool.iter().enumerate() { + let mut r = pool[next(pool.len())].clone(); + r.seed = pool[seed].seed; + b.runs.push(r); + } + } + let c = compare(&a, &b, 0.05); + if !c.pass { + fails += 1; + } + metric_fails += usize::from(c.failed.iter().any(|f| !f.starts_with("trap@"))); + trap_fails += usize::from(!c.trapped_checkpoints.is_empty()); + for t in &c.trapped_checkpoints { + *by_checkpoint.entry(t.checkpoint.clone()).or_insert(0usize) += 1; + } + } + println!("null compares: {fails}/{reps} fail ({metric_fails} by a metric, {trap_fails} by the trap rule)"); + println!("trap rule by checkpoint: {by_checkpoint:?}"); + } + #[test] fn rates_are_per_brain_hour() { let r = run("x", 1, |r| { diff --git a/services/flysim/crates/fly-scorecard/src/runner.rs b/services/flysim/crates/fly-scorecard/src/runner.rs index 917b407..6cc62b1 100644 --- a/services/flysim/crates/fly-scorecard/src/runner.rs +++ b/services/flysim/crates/fly-scorecard/src/runner.rs @@ -275,6 +275,7 @@ impl fly_legacy_session::driver::DecisionDriver for IdleDriver { /// The session composition the release runs, in-process and unpaced, from the checkpoint. pub async fn run_session(spec: &RunSpec) -> Result { + use fly_legacy_session::composition::Transport; // overlay:bus01 use fly_legacy_session::composition::{LegacyConfig, LegacySession}; use fly_session::ExecutionMode; use fly_session::legacy_agent::LegacyProfileKind; @@ -288,6 +289,8 @@ pub async fn run_session(spec: &RunSpec) -> Result { root.path(), LegacyConfig { mode: ExecutionMode::InProcess, + transport: Transport::default(), // overlay:bus01 + placements: Default::default(), // overlay:bus01 rom_path: spec.rom.clone(), dataset_dir: spec.dataset.clone(), profile: LegacyProfileKind::Production, @@ -367,6 +370,7 @@ pub async fn run_session(spec: &RunSpec) -> Result { /// The adapter and the compatibility digest of this build, for the report. pub fn build_info(release: &str) -> crate::suite::BuildInfo { + use fly_legacy_session::composition::Transport; // overlay:bus01 use fly_legacy_session::composition::{LegacyConfig, compatibility_of}; use fly_session::ExecutionMode; use fly_session::legacy_agent::LegacyProfileKind; @@ -374,6 +378,8 @@ pub fn build_info(release: &str) -> crate::suite::BuildInfo { let adapter = GameAdapter::id(&PokemonRedReward::new()).to_owned(); let compat = compatibility_of(&LegacyConfig { mode: ExecutionMode::InProcess, + transport: Transport::default(), // overlay:bus01 + placements: Default::default(), // overlay:bus01 rom_path: PathBuf::new(), dataset_dir: PathBuf::new(), profile: LegacyProfileKind::Production, diff --git a/services/flysim/crates/fly-scorecard/src/suite.rs b/services/flysim/crates/fly-scorecard/src/suite.rs index 52c7c3d..ec2abbc 100644 --- a/services/flysim/crates/fly-scorecard/src/suite.rs +++ b/services/flysim/crates/fly-scorecard/src/suite.rs @@ -144,7 +144,7 @@ impl SuiteReport { hunt_flagged_pct: if windows > 0.0 { 100.0 * sum(&|r| r.hunt.flagged as f64) / windows } else { 0.0 }, blocked_macro_pct: if finishes > 0.0 { 100.0 * sum(&|r| r.macros.failed() as f64) / finishes } else { 0.0 }, buy_ball_done: self.runs.iter().map(|r| r.funnel.buy_ball_done).sum(), - throws: self.runs.iter().map(|r| r.funnel.throw_ball_start).sum(), + throws: self.runs.iter().map(|r| r.funnel.throw_ball_done).sum(), catches: self.runs.iter().map(|r| r.funnel.catches).sum(), heals: self.runs.iter().map(|r| r.heals.heal_done).sum(), whiteouts: self.runs.iter().map(|r| r.whiteouts).sum(), @@ -221,7 +221,7 @@ impl SuiteReport { mean(&susp), sum(&|r| r.watchdog.ladder_events as u64), sum(&|r| r.funnel.buy_ball_done), - sum(&|r| r.funnel.throw_ball_start), + sum(&|r| r.funnel.throw_ball_done), sum(&|r| r.funnel.catches), sum(&|r| r.battles.won), sum(&|r| r.battles.lost), @@ -306,6 +306,30 @@ pub fn run_jobs( results.into_iter().map(|(_, outcome)| outcome).collect() } +/// The child gets SIGKILL when this process dies (PR_SET_PDEATHSIG), so a killed or timed-out +/// suite leaves no `run-one` behind. The parent-pid check closes the race where the parent +/// died between the fork and the prctl. +#[cfg(target_os = "linux")] +fn die_with_parent(command: &mut Command) { + use std::os::unix::process::CommandExt; + // SAFETY: only async-signal-safe calls (prctl, getppid, _exit) run between fork and exec. + unsafe { + let parent = libc::getpid(); + command.pre_exec(move || { + if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL as libc::c_ulong, 0, 0, 0) != 0 { + return Err(std::io::Error::last_os_error()); + } + if libc::getppid() != parent { + libc::_exit(1); + } + Ok(()) + }); + } +} + +#[cfg(not(target_os = "linux"))] +fn die_with_parent(_command: &mut Command) {} + fn run_child(exe: &Path, job: &Job, args: &ChildArgs) -> Result { let fail = |error: String| FailedRun { checkpoint: job.id.clone(), seed: job.seed, error }; let mut command = Command::new(exe); @@ -335,6 +359,7 @@ fn run_child(exe: &Path, job: &Job, args: &ChildArgs) -> Result/dev/null; then + sed -i '/overlay:bus01/d' "$target/services/flysim/crates/fly-scorecard/src/runner.rs" +fi if ! grep -q '"crates/fly-scorecard"' "$ws"; then sed -i 's#^ "crates/flysim-store",# "crates/flysim-store",\n "crates/fly-scorecard",#' "$ws" grep -q '"crates/fly-scorecard"' "$ws" || { echo "overlay: could not add the crate to the workspace" >&2; exit 1; } From eaae6fd82a4eb7d6c8448b2ec4465e348546b47c Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 04:22:39 +0000 Subject: [PATCH 17/27] EDGE-02 notes: bus threads on an aux cpu (FLY_SESSION_AUX_CPUS, SESSION_AUX_CPUS in the deploy), fly-feed direct never rolled back, watchdog falls back to direct at the 4th failure and never reboots for the edge; runbook cost corrected --- docs/design/flybus.md | 13 ++-- infra/05-deploy.sh | 17 +++- infra/bin/fly-feed | 14 +++- infra/bin/fly-watchdog | 7 +- infra/docs/runbook.md | 20 +++-- infra/env/example.env | 6 ++ infra/lib/common.sh | 39 ++++++++-- infra/tests/lint.sh | 64 ++++++++++++++- .../crates/fly-legacy-session/src/service.rs | 35 +++++++-- .../fly-legacy-session/tests/feed_bus.rs | 78 +++++++++++++++++++ .../flysim/crates/flybrain-core/src/pool.rs | 76 ++++++++++++++++++ services/flysim/crates/flysim/src/lib.rs | 7 ++ 12 files changed, 345 insertions(+), 31 deletions(-) diff --git a/docs/design/flybus.md b/docs/design/flybus.md index 716998e..2512d2c 100644 --- a/docs/design/flybus.md +++ b/docs/design/flybus.md @@ -201,8 +201,11 @@ Accepted for now and written down rather than fixed: common to be identical (header minus the wall-clock fields, frame, audio and spike bytes), then stops the binary and starts a new one under the same edge, which must unbind, reconnect and serve. In the session runtime the router and publisher (`flysim-bus`, two threads) inherit the - host mask of `place_workers` (PERF-02), so they run on the host CPU with the listeners, never on - a pinned sweep CPU. + host mask of `place_workers` (PERF-02): on the host CPU with the listeners and the sim's dispatcher, + never on a pinned sweep CPU. That shared CPU costs the sim about a millisecond a frame (review + N1), so `FLY_SESSION_AUX_CPUS` moves them: `place_workers_aux` takes the aux CPUs out of the + sim's set and the `flysim-bus` runtime pins itself to them (`SESSION_AUX_CPUS` in the deploy puts + one page CPU into `flysim.slice` for it). - **One switch.** `FLY_FEED_VIA` in `fly.env` decides everything: `flyedge.service` has an `ExecCondition=` on it (skipped, not failed, in direct mode) and no `[Install]`; `flysim.service` has `Wants=flyedge.service`, so every start of flysim, including the stop and @@ -210,8 +213,8 @@ Accepted for now and written down rather than fixed: mode. Checked on systemd 257 with the repo's own units: crash, restart and stop/start of flysim all end with the edge serving; direct mode never starts it. `infra/bin/fly-feed bus|direct` rewrites the line, restarts flysim, waits for a new invocation, the edge's `/healthz` and the - page on the feed (frames moving), and rolls itself back (to `direct`) when that does not happen - or when it is interrupted. It works on either runtime and survives `fly-runtime` changes. + page on the feed (frames moving), and rolls a `bus` switch back (to `direct`) when that does not happen + or when it is interrupted; `direct` is never rolled back. It works on either runtime and survives `fly-runtime` changes. - **Edge health.** `/healthz` is 503 unless the edge is subscribed **and** has taken a snapshot off the bus within 15 s (`fly_edge_snapshot_age_seconds`): a loop publishes at least the 2 Hz idle header, so silence means a wedged subscription, which `Subscription::next` alone would never @@ -219,7 +222,7 @@ Accepted for now and written down rather than fixed: - **Watchdog.** `feed_via` follows the *running* flysim's environment (a deploy that rewrote fly.env but has not restarted flysim is not an outage). New check 2a judges the edge only while flysim answers: second failed pass restarts it, third adds the page and the encoder, fourth - switches the feed back to flysim (`fly-feed direct --no-wait`, sudoers for exactly that line). + switches the feed back to flysim (`fly-feed direct --no-wait`, sudoers for exactly that line), whatever the time the failures were spread over; an edge fault never reboots. Check 2 in bus mode leaves a silent edge to 2a instead of restarting a page with nothing to connect to. - **Deploy.** `05-deploy.sh` installs `fly-feed`, refuses a release without `fly-edge` while the diff --git a/infra/05-deploy.sh b/infra/05-deploy.sh index 255f89d..039b8d0 100644 --- a/infra/05-deploy.sh +++ b/infra/05-deploy.sh @@ -197,6 +197,11 @@ NEED_RELOAD=0 # --------------------------------------------------------------------------- RAYON_THREADS_EFFECTIVE="${RAYON_THREADS:-3}" ENCODER_CORES_EFFECTIVE="${ENCODER_CORES:-2}" +# Page cpus given to flysim's bus threads (EDGE-02 review N1): added to flysim.slice, taken from the +# page group, named to the session as FLY_SESSION_AUX_CPUS. 0 (the default) changes nothing. +SESSION_AUX_EFFECTIVE="${SESSION_AUX_CPUS:-0}" +case "$SESSION_AUX_EFFECTIVE" in ''|*[!0-9]*) die "SESSION_AUX_CPUS ('${SESSION_AUX_EFFECTIVE}') must be a number of cpus (0 = none)" ;; esac +SESSION_AUX_LIST="" DEPLOY_CPUS="" # 1 once the cpuset partition is in force for this deploy (section 3b writes it); fly.env says so to # flysim-session, which pins its sweep workers only into a cpuset that is the sim's alone. @@ -208,6 +213,10 @@ if [ -n "${CPUSET:-}" ]; then read -r _deploy_sim_cpus DEPLOY_CPUS _deploy_encoder_cpus \ <<< "$(cpuset_partition "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")" PARTITION_ACTIVE=1 + if [ "$SESSION_AUX_EFFECTIVE" -gt 0 ]; then + _aux_split="$(cpuset_aux_split "$DEPLOY_CPUS" "$SESSION_AUX_EFFECTIVE")" || exit 1 + read -r DEPLOY_CPUS SESSION_AUX_LIST <<< "$_aux_split" + fi log "05-deploy: heavy in-container steps pinned to the page cpus (${DEPLOY_CPUS}) so extraction/verification cannot compete with flysim" else log "05-deploy: NOT pinning the heavy in-container steps — the fly-cpuset block in" \ @@ -606,6 +615,10 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT else echo "FLY_SESSION_PIN=0" fi + # EDGE-02 review N1: the bus threads' own cpu, in flysim.slice and in nobody else's set. + if [ "$PARTITION_ACTIVE" -eq 1 ] && [ -n "$SESSION_AUX_LIST" ]; then + echo "FLY_SESSION_AUX_CPUS=${SESSION_AUX_LIST}" + fi echo "FLY_MACRO_MODE=${FLY_MACRO_MODE:-raw}" # Who serves the feed WebSocket (docs/design/flybus.md, "Feed over the # bus"). "direct" is the default and is flysim binding :7400 itself, as @@ -614,7 +627,7 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT # never enables: see that unit's header for the switch. Written # unconditionally, like FLY_MACRO_MODE, so one grep says which a box runs. # Watchdog check 2 reads this line to know whose /metrics carries the - # feed counters (flysim's :9101, or flyedge's loopback :9102). + # feed counters (flysim's :9101, or flyedge's :9102 (all interfaces, counters only)). # Validated and lowercased above (feed_via_normalize). echo "FLY_FEED_VIA=${FLY_FEED_VIA_EFFECTIVE}" # Who serves the control API on :7401 (docs/design/flybus.md, "Control over @@ -758,7 +771,7 @@ if [ -n "${CPUSET:-}" ]; then "Run 01-create-ct.sh first; an AllowedCPUs= outside the container's own cpuset" \ "leaves cpuset.cpus.effective empty and the unit unstartable." else - plan="$(cpuset_dropin_plan "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")" + plan="$(cpuset_dropin_plan "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE" "$SESSION_AUX_EFFECTIVE")" log "05-deploy: cpuset partition — $(echo "$plan" | awk '$1 !~ /=$/ {printf "%s%s=%s", sep, $1, $2; sep=", "}')" tmp_dropin="$(mktemp)" # flyedge is off by default, but its drop-in is written with the rest so that the day diff --git a/infra/bin/fly-feed b/infra/bin/fly-feed index 8e35241..c78b5ce 100755 --- a/infra/bin/fly-feed +++ b/infra/bin/fly-feed @@ -24,7 +24,10 @@ # (a box that only serves the feed) the wait ends at 2. # If that does not happen, `bus` puts FLY_FEED_VIA back to what it was, restarts flysim and checks # the same way (--no-rollback leaves it to the operator); `direct` is already the way back, so it -# only reports. A switch that is interrupted (ssh drops, INT/TERM/HUP) rolls back the same way. +# only reports. `direct` is the safe terminal state: once the line says direct nothing, an +# interrupted switch included (ssh drops, INT/TERM/HUP), puts bus back, and an interrupted +# `direct` restarts flysim itself so the running process matches the line. An interrupted `bus` +# rolls back the same way as a failed one. # `--no-restart` only rewrites the line (the next start of flysim applies it). `--no-wait` restarts # flysim without blocking and does not wait for health or roll anything back: it is what the # watchdog runs (as a sudoers-granted `fly-feed direct --no-wait`) when the edge cannot be kept up. @@ -253,6 +256,9 @@ fi # way back is direct: the state that worked. back="$before" if [ "$before" = bus ] && [ "$command" = bus ]; then back=direct; fi +# Direct is where a failed bus ends up, so a switch TO direct has nowhere safer to go: it is never +# undone (it used to roll back to `before`, which sent an operator escaping a bad bus back onto it). +if [ "$command" = direct ]; then back=direct; fi switching=0 restarted=0 # shellcheck disable=SC2317 # runs from the EXIT trap @@ -262,7 +268,11 @@ on_exit() { if [ "$switching" -eq 1 ]; then switching=0 set_via "$back" || true - record "${back} (switch to ${command} interrupted or failed (exit ${rc}); rolled back)" + if [ "$command" = direct ]; then + record "direct (switch to direct interrupted (exit ${rc}); kept: direct is the safe state, flysim restarted to match)" + else + record "${back} (switch to ${command} interrupted or failed (exit ${rc}); rolled back)" + fi if [ "$restarted" -eq 1 ]; then restart_flysim || true; fi fi exit "$rc" diff --git a/infra/bin/fly-watchdog b/infra/bin/fly-watchdog index 276c22f..2166b49 100755 --- a/infra/bin/fly-watchdog +++ b/infra/bin/fly-watchdog @@ -454,7 +454,12 @@ check_flyedge() { record_fail flyedge local n n="$(fail_count flyedge)" - if [ "$n" -ge 4 ] && fails_within_minutes flyedge 15; then + # From the 4th consecutive failure on, whatever the time the failures were spread over (passes + # are skipped while flysim is down, so a flapping flysim stretches the run past any window): the + # fallback to direct comes first and a reboot is never the answer to an edge fault. Only + # n = 2 and 3 reach escalate (its reboot needs 5), and a failed `fly-feed direct` is retried on + # the next pass instead of falling through to it. + if [ "$n" -ge 4 ]; then log_err "flyedge: ${n} consecutive failures, restarts did not bring it back: switching the feed to direct (fly-feed direct)" inc_counter "escalations_total" sudo /opt/fly/bin/fly-feed direct --no-wait || log_err "fly-feed direct FAILED; the edge stays down" diff --git a/infra/docs/runbook.md b/infra/docs/runbook.md index 74e1ff4..4b5e9f3 100644 --- a/infra/docs/runbook.md +++ b/infra/docs/runbook.md @@ -596,8 +596,9 @@ waits for the edge's `/healthz` (subscribed to the bus, a snapshot within 15 s) `flystage.service` is active, for the page: `fly_feed_clients >= 1` on the edge's counters with `fly_frames_sent_total` advancing. Anything short of that within the timeout puts `FLY_FEED_VIA` back to `direct`, restarts flysim again, checks it the same way and exits 1 (`--no-rollback` -leaves the failed switch in place for the operator; an interrupted switch, ssh dropped or INT, TERM -or HUP, rolls back too). Every switch is in the journal (`journalctl -t fly-feed`) and +leaves the failed switch in place for the operator; an interrupted `bus`, ssh dropped or INT, TERM +or HUP, rolls back too). `direct` is the safe terminal state and is never rolled back: an interrupted +`fly-feed direct` leaves `FLY_FEED_VIA=direct` and restarts flysim so the running process matches. Every switch is in the journal (`journalctl -t fly-feed`) and `/var/lib/fly/feed.log`. ### What to watch @@ -607,7 +608,7 @@ or HUP, rolls back too). Every switch is in the journal (`journalctl -t fly-feed | `fly-feed status` | `configured: bus`, `running: bus`, `edge healthz: ok`, snapshot age under a second, `bus lost` and `bind failures` not growing | `running` differs from `configured` (a deploy wrote a new value; the next flysim start applies it); `edge healthz: NOT OK` | | edge `:9102/metrics` (loopback for the watchdog; the same address answers on the container's network for the dashboard) | `fly_edge_bus_connected 1`, `fly_edge_snapshot_age_seconds` under 1, `fly_feed_clients 1` (the page; the bridge or a test adds more), `fly_frames_sent_total` rising about 30 a second, `fly_edge_decode_failures_total 0`, `fly_edge_bind_failures_total 0` | `bus_connected 0` (flysim down, or restarting), `bind_failures_total` rising (something else holds :7400: a flysim still in direct mode, a stale process), `decode_failures_total` rising (a mismatched flysim and fly-edge: deploy one release) | | flysim `:9101/metrics` | `fly_bus_published_total` rising at the snapshot rate, `fly_bus_publish_failures_total` flat 0; `fly_feed_clients` and `fly_frames_sent_total` read **0 here in bus mode** (the counters belong to the edge) | publish failures rising: the store is full or the edge's seat is stuck; read `journalctl -u flysim -g "feed bus"` | -| `fly_realtime_factor`, `fly_lag_seconds` | the same as the baseline from step 1, within the usual noise: the publisher is one 6% thread on the host CPU, and the websocket writes it replaces were on that CPU in direct mode | a drop that persists for the hour: switch back (`fly-feed direct`) and compare | +| `fly_realtime_factor`, `fly_lag_seconds` | the same as the baseline from step 1, within the usual noise: the publisher is about 2 ms of CPU per snapshot (10x the direct websocket write), so with `SESSION_AUX_CPUS=1` it runs on its own CPU and the number is unchanged; without it, expect a loss of 1 to 2 ms of the 3.7 to 5.7 ms of headroom per frame | a drop that persists for the hour: switch back (`fly-feed direct`) and compare | | `ps -L -o pid,psr,comm -p $(pidof fly-edge)` / `grep Cpus_allowed_list /proc/$(pidof fly-edge)/status` | the page CPUs (`flyedge.service.d/cpuset.conf`, written by the deploy), never the sim's | an edge on the sim's CPUs: the cpuset drop-in is missing; re-run the deploy | | `ls -R /run/fly/bus/store | wc -l`, `du -sk /run/fly/bus` | a few files, under 1 MB, flat for days (the router keeps one retained snapshot and what the edge is still reading) | growth: report it, restart flysim, switch back | | `journalctl -u flyedge -u flysim -g "bus|feed|edge"`, `journalctl -t fly-watchdog -g flyedge` | `serving the feed from the bus` once per flysim start | `the feed bus went away` outside a flysim restart; a watchdog line `flyedge: ... failures` | @@ -651,7 +652,7 @@ not move much. The live switch is the real A/B: take the step 1 baseline and com | --- | --- | --- | | WebSocket content, speed 0.25 so every frame is published, 4,261 and 5,406 frames compared | reference | frame, audio and spike attachments byte-equal on every frame; headers equal except a wall-clock "checkpoint saved" event that lands on different frames in any two runs | | Latency, snapshot stamped by the sim to received by a local client (median / p95) | 1 / 3 ms | 7 / 14 ms (two hops: seal into the store, read out) | -| CPU per snapshot | 0.24 ms (flysim's websocket thread, on the host CPU) | 2.4 ms in flysim (`flysim-bus` publisher, on the host CPU, about 7% of a CPU at 30 Hz) and 1.1 ms in the edge (page CPUs) | +| CPU per snapshot | 0.24 ms (flysim's websocket thread, on the host CPU) | 2.4 ms in flysim (`flysim-bus` publisher: on the aux CPU with `SESSION_AUX_CPUS`, else on the host CPU with the sim's dispatcher, about 7% of a CPU at 30 Hz and on the critical path) and 1.1 ms in the edge (page CPUs) | | Edge CPU and placement | n/a | 1.3% mean, 2.8% p95, only on the page CPUs | | Router store | n/a | 116 KB steady (median), 238 KB peak, 6 to 9 files, flat over the run | | Memory over 35 min plus the restarts | flysim 72 to 78 MB | flysim 65 to 69 MB, edge 8.3 to 9.6 MB; the page grows the same in both | @@ -677,8 +678,15 @@ restore and warm-up; use the unstick rule's usual time. series); the metrics address is on every interface, as `:9101` is, and exposes nothing but counters. - **CPUs.** `flyedge.service` is confined to the page CPUs by the deploy's drop-in; the router and - the publisher run inside flysim, on its `flysim-bus` runtime (two threads on the host CPU, with - the listeners, not on a pinned sweep CPU). + the publisher run inside flysim, on its `flysim-bus` runtime: two threads plus tokio's blocking + pool, which does the artifact copies. **Give it a CPU of its own** (`SESSION_AUX_CPUS=1` in the + operator's env file, a page CPU added to `flysim.slice`; the deploy writes it to `fly.env` as + `FLY_SESSION_AUX_CPUS`, and the session pins the bus runtime there and the sweep and dispatcher to + the rest). Without it the runtime shares the host CPU with the sim's dispatcher, which costs about + 1 ms per frame measured (the publisher is 1.3 to 2.5 ms of CPU per snapshot, 30 a second, on the + critical path; the barrier stalls behind it). Check: `grep Cpus_allowed_list /proc/$(pidof + flysim-session)/task/*/status` for the `flysim-bus` threads shows the aux CPU alone. Set it, run the + deploy, restart flysim, and only then `fly-feed bus`. - **The store** is `/run/fly/bus` (tmpfs, `fly` 0700, 32 MiB cap, in practice under 0.5 MB). A reboot empties it; a crashed flysim's directory is removed by the next one. - **Control (`:7401`)** stays in flysim and is not part of this switch. diff --git a/infra/env/example.env b/infra/env/example.env index 89f85d4..a892e02 100644 --- a/infra/env/example.env +++ b/infra/env/example.env @@ -138,6 +138,12 @@ RAYON_THREADS=3 # cpuset_partition (default 2 when unset). flycast gets its own group rather # than sharing the page group — see lib/common.sh's cpuset_partition header. ENCODER_CORES=2 +# SESSION_AUX_CPUS: how many page cpus (taken from the end of the page group) flysim.slice gets in +# addition to the sim's, for the session runtime's bus threads (the feed publisher and router when +# FLY_FEED_VIA / FLY_CONTROL_VIA is bus). The sweep and its dispatcher never use them, the page and the +# encoder never see them. Default 0 (none): the bus threads then share the sim's host cpu, which costs +# +1 to 2 ms per frame (EDGE-02 review N1). Set 1 on a partitioned container before `fly-feed bus`. +SESSION_AUX_CPUS=0 # --- CUDA LIF backend ------------------------------------------------------- # 1 makes 05-deploy.sh write FLY_LIF_CUDA=1 into /etc/fly/fly.env, which is what diff --git a/infra/lib/common.sh b/infra/lib/common.sh index 275ce46..f751883 100755 --- a/infra/lib/common.sh +++ b/infra/lib/common.sh @@ -202,31 +202,56 @@ cpuset_partition() { echo "$sim_cpus $page_cpus $encoder_cpus" } -# cpuset_dropin_plan CPUSET RAYON_THREADS [ENCODER_CORES] — print one "UNIT-NAME CPUS" line for every +# cpuset_aux_split PAGE_CPUS COUNT — take the LAST COUNT cpus of the page group for flysim's +# auxiliary threads (EDGE-02 review N1: the bus runtime, which must not share the sim's +# dispatcher cpu). Echoes "PAGE_REST AUX"; dies if that would leave no page cpu. +cpuset_aux_split() { + local page="$1" count="$2" n + n="$(echo "$page" | awk -F, '{print NF}')" + if [ "$count" -ge "$n" ]; then + die "cpuset_aux_split: SESSION_AUX_CPUS=${count} leaves no page cpu out of '${page}'. Widen CPUSET or lower SESSION_AUX_CPUS." + fi + echo "$(echo "$page" | cut -d, -f1-"$(( n - count ))") $(echo "$page" | cut -d, -f"$(( n - count + 1 ))"-)" +} + +# cpuset_dropin_plan CPUSET RAYON_THREADS [ENCODER_CORES] [AUX_COUNT] — print one "UNIT-NAME CPUS" line for every # AllowedCPUs= drop-in 05-deploy.sh writes (UNIT-NAME includes its suffix, e.g. flysim.service, # flysim.slice), and then the two lines that name the confinement lists for bin/fly-cpu-confine: # -# flysim.slice the sim's CPUs (flysim.service and flysim-session.service run in it); +# flysim.slice the sim's CPUs plus AUX_COUNT page cpus (default 0) taken from the end of the +# page group for flysim's bus threads, exclusive to flysim like the rest (flysim.service and flysim-session.service run in it); # flysim.service, flysim-session.service the same set (belt and braces: a unit outside the # slice is still bounded); # xvfb, flystage, flystage-web, pulse, mediamtx, flyedge, flycontrol-edge the page CPUs; # flycast the encoder CPUs; # flyshadow page + encoder (never the sim's); +# FLY_AUX_CPUS= only with AUX_COUNT > 0: the aux cpus (fly.env's FLY_SESSION_AUX_CPUS); # FLY_SIM_CPUS / FLY_OTHER_CPUS "=": the lists /etc/fly/cpuset.env carries; OTHER is every CPU # of CPUSET that is not the sim's, in CPUSET order. # # One function so the deploy and infra/tests/lint.sh cannot disagree about the plan. Dies like # cpuset_partition does. cpuset_dropin_plan() { - local cpuset="$1" rayon="$2" encoder="${3:-2}" sim page enc u - read -r sim page enc <<< "$(cpuset_partition "$cpuset" "$rayon" "$encoder")" || return 1 - echo "flysim.slice $sim" - for u in flysim flysim-session; do echo "${u}.service $sim"; done + local cpuset="$1" rayon="$2" encoder="${3:-2}" aux_count="${4:-0}" sim page enc u aux="" slice_cpus + local out + out="$(cpuset_partition "$cpuset" "$rayon" "$encoder")" || return 1 + read -r sim page enc <<< "$out" + if [ "$aux_count" -gt 0 ]; then + # not `read <<< "$(...)"`: die inside the substitution would only end the subshell + out="$(cpuset_aux_split "$page" "$aux_count")" || return 1 + read -r page aux <<< "$out" + fi + slice_cpus="$sim" + [ -n "$aux" ] && slice_cpus="${sim},${aux}" + echo "flysim.slice $slice_cpus" + for u in flysim flysim-session; do echo "${u}.service $slice_cpus"; done for u in xvfb flystage flystage-web pulse mediamtx flyedge flycontrol-edge; do echo "${u}.service $page"; done echo "flycast.service $enc" echo "flyshadow.service ${page},${enc}" - echo "FLY_SIM_CPUS= $sim" + echo "FLY_SIM_CPUS= $slice_cpus" echo "FLY_OTHER_CPUS= ${page},${enc}" + [ -n "$aux" ] && echo "FLY_AUX_CPUS= $aux" + return 0 } # cpuset_dropin_text UNIT-NAME CPUS ENV_LABEL — the AllowedCPUs= drop-in 05-deploy.sh converges to diff --git a/infra/tests/lint.sh b/infra/tests/lint.sh index d44020f..5ad9bc8 100755 --- a/infra/tests/lint.sh +++ b/infra/tests/lint.sh @@ -1836,6 +1836,26 @@ if grep -qx 'FLY_FEED_VIA=direct' "$ff_env" && grep -q 'interrupted or failed' " else fail "an interrupted fly-feed bus must roll back ($(grep FLY_FEED_VIA "$ff_env"); $(cat "$ff_dir/feed.log" 2>/dev/null | tr '\n' ';'))" fi +# N2 (EDGE-02 notes): an interrupted `fly-feed direct` is never rolled back to bus: direct is the +# safe terminal state, and flysim is restarted so the running process matches the line. +ff_reset bus bus +env FF_DIR="$ff_dir" FF_ENV="$ff_env" PATH="$ff_dir/bin:$PATH" FLY_ENV_FILE="$ff_env" \ + FLY_RELEASE_DIR="$ff_dir/release" FLY_PROC_DIR="$ff_dir/proc" FLY_FEED_LOG="$ff_dir/feed.log" \ + FLY_FEED_LOCK="$ff_dir/run/feed.lock" FLY_CONTROL_URL=http://control FLY_METRICS_URL=http://sim \ + FLY_EDGE_METRICS_URL=http://edge FLY_FEED_HEALTH_TIMEOUT=30 FLY_FEED_SAMPLE_SECONDS=0 FF_CONTROL_OK=0 \ + bash "$INFRA_DIR/bin/fly-feed" direct >/dev/null 2>&1 & +ff_pid=$! +sleep 2 +kill -TERM "$ff_pid" 2>/dev/null || true +for _ in 1 2 3 4 5 6 7 8 9 10; do kill -0 "$ff_pid" 2>/dev/null || break; sleep 0.5; done +(kill -0 "$ff_pid" 2>/dev/null && kill -KILL "$ff_pid" 2>/dev/null) || true +wait "$ff_pid" 2>/dev/null || true +if grep -qx 'FLY_FEED_VIA=direct' "$ff_env" && ! grep -q 'FLY_FEED_VIA=bus' "$ff_env" \ + && grep -q 'kept: direct is the safe state' "$ff_dir/feed.log" 2>/dev/null && [ "$(ff_restarts)" -ge 2 ]; then + pass "fly-feed direct interrupted mid-switch stays on direct (never back to bus), flysim restarted to match" +else + fail "an interrupted fly-feed direct must end on direct ($(grep FLY_FEED_VIA "$ff_env"); restarts $(ff_restarts); $(cat "$ff_dir/feed.log" 2>/dev/null | tr '\n' ';'))" +fi rm -rf "$ff_dir" echo "--- fly-watchdog: check 2a (the edge) and check 2 in bus mode ---" @@ -1912,6 +1932,21 @@ case "$(wd_acts)" in *"sudo /opt/fly/bin/fly-feed direct --no-wait;") pass "check 2a: the fourth failed pass puts the feed back on flysim (fly-feed direct --no-wait)" ;; *) fail "check 2a fourth failure must run fly-feed direct --no-wait: $(wd_acts)" ;; esac +# N3 (EDGE-02 notes): failures spread over more than 15 minutes (passes are skipped while flysim is +# down) still fall back to direct from the 4th, and a long run of edge failures never reboots. +wd_reset; WD_CMDS='f="$(fails_file flyedge)"; for i in 1 2 3 4 5 6; do echo $(( $(now) - 7200 + i )) >> "$f"; done; check_flyedge' +wd_edge bus WF_EDGE_OK=0 +case "$(wd_acts)" in + "sudo /opt/fly/bin/fly-feed direct --no-wait;") pass "check 2a: failures older than 15 minutes still fall back to direct, with no restart chain and no reboot" ;; + *) fail "check 2a with a stretched failure run must run fly-feed direct only: $(wd_acts)" ;; +esac +wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge; check_flyedge; check_flyedge; check_flyedge; check_flyedge; check_flyedge' +wd_edge bus WF_EDGE_OK=0 +if ! grep -q reboot "$wf_dir/actions.log" 2>/dev/null && [ ! -e "$wf_dir/state/last-reboot" ]; then + pass "check 2a: eight failed passes (fly-feed direct unable to fix it) never reboot the container" +else + fail "an edge fault must never reboot: $(wd_acts)" +fi wd_reset; WD_CMDS='check_flyedge; check_flyedge' wd_edge bus WF_EDGE_OK=1 WF_EDGE_ACTIVE=0 case "$(wd_acts)" in @@ -2032,8 +2067,8 @@ set -euo pipefail PLANEOF chmod +x "$plan_bin" check_plan() { - local label="$1" cpuset="$2" rayon="$3" encoder="$4" plan sim other u cpus bad="" - plan="$("$plan_bin" cpuset_dropin_plan "$cpuset" "$rayon" "$encoder" 2>&1)" || { fail "cpuset_dropin_plan: $label: died: $plan"; return 0; } + local label="$1" cpuset="$2" rayon="$3" encoder="$4" aux="${5:-0}" plan sim other u cpus bad="" + plan="$("$plan_bin" cpuset_dropin_plan "$cpuset" "$rayon" "$encoder" "$aux" 2>&1)" || { fail "cpuset_dropin_plan: $label: died: $plan"; return 0; } sim="$(awk '$1 == "flysim.slice" {print $2}' <<< "$plan")" other="$(awk '$1 == "FLY_OTHER_CPUS=" {print $2}' <<< "$plan")" [ "$sim" = "$(awk '$1 == "FLY_SIM_CPUS=" {print $2}' <<< "$plan")" ] || bad="$bad SIM-list-differs-from-slice" @@ -2042,7 +2077,7 @@ check_plan() { done # every other unit, and the confinement list, is disjoint from the sim's cpus while read -r u cpus; do - case "$u" in flysim.slice|flysim.service|flysim-session.service|FLY_SIM_CPUS=) continue ;; esac + case "$u" in flysim.slice|flysim.service|flysim-session.service|FLY_SIM_CPUS=|FLY_AUX_CPUS=) continue ;; esac if [ -n "$(comm -12 <(tr ',' '\n' <<< "$sim" | sort) <(tr ',' '\n' <<< "$cpus" | sort))" ]; then bad="$bad $u-overlaps-sim" fi @@ -2060,6 +2095,29 @@ check_plan() { } check_plan "release shape (sixteen cpus, four sim, four encoder)" "1,3,5,7,9,11,13,15,29,31,33,35,17,19,37,39" 4 4 check_plan "ten cpus, ENCODER_CORES=3" "1,3,5,7,9,11,13,15,17,19" 4 3 +check_plan "release shape with one aux cpu (EDGE-02 N1)" "1,3,5,7,9,11,13,15,29,31,33,35,17,19,37,39" 4 4 1 +check_plan "release shape with two aux cpus" "1,3,5,7,9,11,13,15,29,31,33,35,17,19,37,39" 4 4 2 +# The aux cpu is the last page cpu, is in flysim.slice, is in FLY_SIM_CPUS (so fly-cpu-confine keeps every +# other process off it), is named in FLY_AUX_CPUS and is in no page or encoder unit. +aux_plan="$("$plan_bin" cpuset_dropin_plan "1,3,5,7,9,11,13,15,29,31,33,35,17,19,37,39" 4 4 1 2>&1)" +if [ "$(awk '$1 == "flysim.slice" {print $2}' <<< "$aux_plan")" = "1,3,5,7,35" ] \ + && [ "$(awk '$1 == "FLY_SIM_CPUS=" {print $2}' <<< "$aux_plan")" = "1,3,5,7,35" ] \ + && [ "$(awk '$1 == "FLY_AUX_CPUS=" {print $2}' <<< "$aux_plan")" = "35" ] \ + && [ "$(awk '$1 == "xvfb.service" {print $2}' <<< "$aux_plan")" = "9,11,13,15,29,31,33" ] \ + && ! grep -q "FLY_AUX_CPUS=" <<< "$("$plan_bin" cpuset_dropin_plan "1,3,5,7,9,11,13,15,29,31,33,35,17,19,37,39" 4 4 2>&1)"; then + pass "cpuset_dropin_plan: the aux cpu (35) is flysim.slice's, in FLY_SIM_CPUS, off every page unit; none without SESSION_AUX_CPUS" +else + fail "cpuset_dropin_plan: aux cpu wiring wrong: $aux_plan" +fi +if "$plan_bin" cpuset_dropin_plan "1,3,5,7,9,11,13,15,17,19" 4 3 3 >/dev/null 2>&1; then + fail "cpuset_dropin_plan: SESSION_AUX_CPUS that leaves no page cpu must be refused" +else + pass "cpuset_dropin_plan: SESSION_AUX_CPUS that leaves no page cpu is refused" +fi +grep -q 'FLY_SESSION_AUX_CPUS=${SESSION_AUX_LIST}' "$INFRA_DIR/05-deploy.sh" \ + && grep -q 'SESSION_AUX_EFFECTIVE")"' "$INFRA_DIR/05-deploy.sh" \ + && pass "05-deploy.sh writes FLY_SESSION_AUX_CPUS and passes the aux count to the plan" \ + || fail "05-deploy.sh must write FLY_SESSION_AUX_CPUS and pass SESSION_AUX_EFFECTIVE to cpuset_dropin_plan" check_plan "eight cpus, default encoder" "1,3,5,7,9,11,13,15" 4 "" check_plan "dev shape (RAYON_THREADS=2)" "0,2,4,6,8,10,12,14" 2 "" # the generated drop-ins: a slice gets [Slice], a service [Service], both AllowedCPUs= diff --git a/services/flysim/crates/fly-legacy-session/src/service.rs b/services/flysim/crates/fly-legacy-session/src/service.rs index ec97f2f..4293af0 100644 --- a/services/flysim/crates/fly-legacy-session/src/service.rs +++ b/services/flysim/crates/fly-legacy-session/src/service.rs @@ -83,9 +83,13 @@ pub const SESSION_PROFILE_ENV: &str = "FLY_SESSION_PROFILE"; /// `0` keeps every thread floating over the cpuset; anything else, or unset, places them /// ([`place_threads`]). pub const SESSION_PIN_ENV: &str = "FLY_SESSION_PIN"; -/// Process mode: a CPU list for the service process (router, coordinator, listeners, checkpoint -/// writer) and the environment process, instead of the sweep's host CPU (BUS-01). It must lie in -/// the unit's cpuset (on the containers, `flysim.slice`'s AllowedCPUs). +/// A CPU list for the threads that are not the sim, instead of the sweep's host CPU. It must lie +/// in the unit's cpuset (on the containers, `flysim.slice`'s AllowedCPUs, where 05-deploy.sh adds +/// it with `SESSION_AUX_CPUS`) and is exclusive to those threads. Process mode (BUS-01): the +/// service process (router, coordinator, listeners, checkpoint writer) and the environment +/// process. In-process and thread modes (EDGE-02): the `flysim-bus` runtime, i.e. the feed +/// publisher, the router and the control services; the sweep workers, the dispatcher and every +/// other thread are placed on the rest. pub const SESSION_AUX_CPUS_ENV: &str = "FLY_SESSION_AUX_CPUS"; /// How the service composes its session, beyond flysim's own [`Config`]. @@ -348,8 +352,29 @@ fn place_threads(config: &Config, options: &mut ServiceOptions) { ); return; } - if std::env::var_os(SESSION_AUX_CPUS_ENV).is_some() { - tracing::warn!("{SESSION_AUX_CPUS_ENV} is for process mode; ignored"); + // In-process and thread modes: FLY_SESSION_AUX_CPUS names cpus of the unit's cpuset that are + // not the sim's. The sweep and the dispatcher are placed on the rest, and the bus runtime + // (feed publisher, router, control services) on these (EDGE-02 review N1). + if let Some(value) = std::env::var(SESSION_AUX_CPUS_ENV).ok().filter(|v| !v.is_empty()) { + match flybrain_core::pool::parse_cpu_list(&value) { + None => tracing::warn!("{SESSION_AUX_CPUS_ENV}={value:?} is not a cpu list; ignored"), + Some(aux) => match flybrain_core::pool::place_workers_aux(workers, &aux) { + Some((placement, aux)) => { + tracing::info!( + sweep_workers = ?placement.workers, + host = ?placement.host, + bus_aux = ?aux, + "sweep workers pinned one per cpu; the bus runtime on the aux cpus, every \ + other thread on the host cpus" + ); + return; + } + None => tracing::warn!( + "{SESSION_AUX_CPUS_ENV}={value:?} is not inside the cpuset, or leaves fewer \ + cpus than sweep threads; ignored (the bus runtime shares the host cpus)" + ), + }, + } } match flybrain_core::pool::place_workers(workers) { Some(placement) => tracing::info!( diff --git a/services/flysim/crates/fly-legacy-session/tests/feed_bus.rs b/services/flysim/crates/fly-legacy-session/tests/feed_bus.rs index 4d01971..ee33b7f 100644 --- a/services/flysim/crates/fly-legacy-session/tests/feed_bus.rs +++ b/services/flysim/crates/fly-legacy-session/tests/feed_bus.rs @@ -121,6 +121,11 @@ struct Service { impl Service { fn start(config: Config, work: &Path, name: &str) -> Service { + Service::start_env(config, work, name, &[]) + } + + /// [`Service::start`] with extra environment, which wins over the test's defaults. + fn start_env(config: Config, work: &Path, name: &str, envs: &[(&str, &str)]) -> Service { let path = work.join(format!("{name}.toml")); std::fs::write(&path, toml::to_string(&config).unwrap()).unwrap(); let log = std::fs::File::create(work.join(format!("{name}.log"))).unwrap(); @@ -136,6 +141,7 @@ impl Service { .env_remove("FLY_FEED_BIND") .env_remove("FLY_CONTROL_BIND") .env_remove("FLY_METRICS_ADDR") + .envs(envs.iter().copied()) .stdout(Stdio::null()) .stderr(log) .spawn() @@ -400,3 +406,75 @@ fn the_session_runtime_serves_the_same_feed_over_the_bus() { ); assert!(compared >= FRAMES / 2, "only {compared} frames in common"); } + +/// The cpus a `/proc/.../status` says a thread may run on. +fn allowed_cpus(status: &Path) -> Vec { + let text = std::fs::read_to_string(status).unwrap_or_default(); + let line = text + .lines() + .find_map(|l| l.strip_prefix("Cpus_allowed_list:")) + .unwrap_or("") + .trim() + .to_owned(); + flybrain_core::pool::parse_cpu_list(&line).unwrap_or_default() +} + +/// EDGE-02 review N1: with `FLY_SESSION_AUX_CPUS` the feed publisher's runtime (`flysim-bus`, its +/// blocking pool included) runs on the aux cpu alone, and no other thread of the service may. +/// Needs a toy store and three cpus (two sweep workers and one aux); no ROM. +#[test] +fn the_bus_threads_run_on_the_aux_cpu_and_nothing_else_does() { + let allowed = allowed_cpus(Path::new("/proc/self/status")); + if allowed.len() < 3 { + eprintln!("skipping: needs three cpus, have {allowed:?}"); + return; + } + let Some(rom) = rom_path() else { return }; + let aux = *allowed.last().unwrap(); + let dataset = fly_session::legacy_parity::toy::dir(); + let root = tempfile::tempdir().unwrap(); + let seeded = root.path().join("seeded"); + std::fs::create_dir_all(&seeded).unwrap(); + seed_by_legacy_fresh_start(&rom, &dataset, &seeded); + let dir = fresh_dir(root.path(), &seeded, "aux"); + let mut config = config(&rom, &dataset, &dir, FeedVia::Bus, &root.path().join("aux-bus")); + config.loop_.threads = 2; + let aux_text = aux.to_string(); + let service = Service::start_env( + config, + root.path(), + "aux", + &[("FLY_SESSION_PIN", "1"), ("FLY_SESSION_AUX_CPUS", &aux_text)], + ); + let task_dir = PathBuf::from(format!("/proc/{}/task", service.child.id())); + let deadline = Instant::now() + Duration::from_secs(60); + loop { + let mut bus = 0; + let mut others = Vec::new(); + for task in std::fs::read_dir(&task_dir).into_iter().flatten().flatten() { + let comm = std::fs::read_to_string(task.path().join("comm")) + .unwrap_or_default() + .trim() + .to_owned(); + let cpus = allowed_cpus(&task.path().join("status")); + if comm == "flysim-bus" { + bus += 1; + assert_eq!(cpus, vec![aux], "a flysim-bus thread is on {cpus:?}, not on {aux}"); + } else { + others.push((comm, cpus)); + } + } + if bus >= 2 && others.len() >= 3 { + for (comm, cpus) in &others { + assert!(!cpus.contains(&aux), "thread {comm} may run on the aux cpu {aux}: {cpus:?}"); + } + return; + } + assert!( + Instant::now() < deadline, + "never saw the bus threads: {bus} bus, {} others", + others.len() + ); + std::thread::sleep(Duration::from_millis(200)); + } +} diff --git a/services/flysim/crates/flybrain-core/src/pool.rs b/services/flysim/crates/flybrain-core/src/pool.rs index 93b4bee..418a323 100644 --- a/services/flysim/crates/flybrain-core/src/pool.rs +++ b/services/flysim/crates/flybrain-core/src/pool.rs @@ -33,6 +33,9 @@ type Job = dyn Fn(usize) + Sync; /// (`1..workers`) runs on `WORKER_CPUS[i - 1]`. Unset -- the default, and always for the legacy /// loop -- the workers float over the process's CPUs as they always have. static WORKER_CPUS: OnceLock> = OnceLock::new(); +/// The CPUs of the process's auxiliary threads (the bus runtime), when [`place_workers_aux`] +/// reserved some outside the sim's set. +static AUX_CPUS: OnceLock> = OnceLock::new(); struct Shared { /// Bumped once per dispatch. A worker runs when this differs from what it last saw. @@ -296,6 +299,56 @@ pub fn place_workers(workers: usize) -> Option { Some(placement) } +/// Splits `allowed` like [`split_cpus`], after taking `aux` out of it: `aux` must be a non-empty +/// subset of `allowed` and leave at least `workers` CPUs for the sim. Returns the sim's placement +/// (sweep workers, dispatcher and host, never an `aux` CPU) and the aux list. `None` otherwise. +pub fn split_cpus_aux( + allowed: &[usize], + workers: usize, + aux: &[usize], +) -> Option<(Placement, Vec)> { + let mut aux = aux.to_vec(); + aux.sort_unstable(); + aux.dedup(); + if aux.is_empty() || aux.iter().any(|c| !allowed.contains(c)) { + return None; + } + let rest: Vec = allowed.iter().copied().filter(|c| !aux.contains(c)).collect(); + Some((split_cpus(&rest, workers)?, aux)) +} + +/// [`place_workers`] with `aux` CPUs reserved for the process's auxiliary threads (the feed +/// publisher and the bus runtime): the sweep workers, the dispatcher and every ordinary thread +/// stay off them, and [`confine_to_aux`] (the bus runtime's `on_thread_start`) puts a thread on +/// them. `None`, and nothing changed, when `aux` is not a subset of the allowed CPUs, leaves too +/// few for the sim, or a placement was already made. Placement decides only the CPU. +pub fn place_workers_aux(workers: usize, aux: &[usize]) -> Option<(Placement, Vec)> { + if WORKER_CPUS.get().is_some() { + return None; + } + let (placement, aux) = split_cpus_aux(&affinity::allowed()?, workers, aux)?; + if !affinity::set_current(&placement.host) { + return None; + } + WORKER_CPUS.set(placement.workers.clone()).ok()?; + let _ = AUX_CPUS.set(aux.clone()); + Some((placement, aux)) +} + +/// Confines the calling thread to the aux CPUs [`place_workers_aux`] reserved. A no-op (false) +/// when none were: the thread keeps what it inherited. +pub fn confine_to_aux() -> bool { + match AUX_CPUS.get() { + Some(aux) => affinity::set_current(aux), + None => false, + } +} + +/// The aux CPUs reserved by [`place_workers_aux`], if any. +pub fn aux_cpus() -> Option<&'static [usize]> { + AUX_CPUS.get().map(Vec::as_slice) +} + /// [`place_workers`] with a plan made elsewhere (BUS-01): a separate agent process is handed its /// placement by the launcher, which split the service's cpuset, instead of splitting its own mask. /// Confines the calling thread (and every thread it spawns afterwards) to `placement.host` and @@ -448,6 +501,29 @@ impl<'a, T> SharedSlice<'a, T> { mod tests { use super::*; + #[test] + fn aux_cpus_are_taken_out_of_the_sim_set() { + // The release layout plus one page cpu: sweep 3,5,7, host 1, bus threads on 9. + let (placement, aux) = split_cpus_aux(&[1, 3, 5, 7, 9], 4, &[9]).expect("a plan"); + assert_eq!(placement.workers, vec![3, 5, 7]); + assert_eq!(placement.host, vec![1]); + assert_eq!(aux, vec![9]); + // No aux cpu is ever a worker or host cpu, whatever its position. + let (p, a) = split_cpus_aux(&[1, 3, 5, 7, 9, 11], 4, &[3, 11, 3]).expect("a plan"); + assert_eq!(a, vec![3, 11]); + assert!(p.workers.iter().chain(&p.host).all(|c| !a.contains(c))); + // Refused: not in the allowed set, empty, or too few left for the sim. + assert_eq!(split_cpus_aux(&[1, 3, 5, 7], 4, &[9]), None); + assert_eq!(split_cpus_aux(&[1, 3, 5, 7, 9], 4, &[]), None); + assert_eq!(split_cpus_aux(&[1, 3, 5, 7], 4, &[7]), None); + } + + #[test] + fn confining_to_aux_without_a_reservation_is_a_no_op() { + assert!(aux_cpus().is_none()); + assert!(!confine_to_aux()); + } + #[test] fn every_index_runs_exactly_once() { for workers in [1usize, 2, 3, 7] { diff --git a/services/flysim/crates/flysim/src/lib.rs b/services/flysim/crates/flysim/src/lib.rs index 9888b26..fbd9e0f 100644 --- a/services/flysim/crates/flysim/src/lib.rs +++ b/services/flysim/crates/flysim/src/lib.rs @@ -196,6 +196,13 @@ where let bus_runtime = tokio::runtime::Builder::new_multi_thread() .worker_threads(2) .thread_name("flysim-bus") + // EDGE-02 review N1: the router, the publisher and the artifact copies cost + // milliseconds a frame; on the sim's dispatcher cpu they stall every barrier. When the + // session reserved aux cpus (FLY_SESSION_AUX_CPUS) these threads, the blocking pool + // included, run there; otherwise they keep the host mask they inherited. + .on_thread_start(|| { + flybrain_core::pool::confine_to_aux(); + }) .enable_all() .build() .context("building the bus runtime")?; From 2bae8a7b6ab285ce53697f6cea8cf071efcea2d2 Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 04:26:09 +0000 Subject: [PATCH 18/27] macros-traps: row 73, with the multi-seed hunt before and after --- infra/docs/macros-traps.md | 59 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/infra/docs/macros-traps.md b/infra/docs/macros-traps.md index 7cd9870..4a55ee7 100644 --- a/infra/docs/macros-traps.md +++ b/infra/docs/macros-traps.md @@ -3736,3 +3736,62 @@ Trap hunt, 10 brain minutes with the real connectome from the trap checkpoint: The watchdog and the ladder flagged the trap correctly. The restart could not help, because the trap is in the game state and the hot checkpoint is inside it (row 70's lesson again). Only a reset or the fix ends it. + +## 2026-10-02, row 73: Route 25 and Bill's house, a PC no macro could press, and Cerulean's south + +### What was live + +v0.7.5, rung 15 (NUGGET BRIDGE), Route 24/25. After row 71's battle trap was fixed the fly kept a +busy ring with no progress: `GO ROUTE` into Bill's house (`$58`, door (45, 3)), `GO OBJECTIVE` or +`GO OUT` straight back out. Scout B3 measured it from the live checkpoint: on six seeds (2.8 +brain hours) the pad in the house was always `GO OBJECTIVE, GO OUT, GO NPC, GO FRONTIER`, `GO OUT` +16-51 and `GO OBJECTIVE` 16-60 starts per ten brain minutes, `GO NPC` 0 in about 600 starts, and +new tiles 2527 to 2531 in 35 minutes. Rung 16 was never earned. + +### Mechanism + +- **Rung 16's place was the route.** `RUNG_PLACES[16]` was `at(ROUTE_25)`. A fly on Route 25 was + already there, so in the house `GO OBJECTIVE` was an exit into the objective's map: the same + door as `GO OUT`. +- **The errand's middle step was unpressable.** The ticket is Bill's errand + (`scripts/BillsHouse.asm`): talk to Bill as a Pokémon, press the cell separator's PC at (1, 4) + facing up, talk to Bill when he steps out. The PC is a hidden event (`wNumSigns` 0, one sprite), + and no macro aimed at hidden events or dealt `TALK` in front of one. Scout B3 confirmed the + press on the cartridge by hand. +- **After the ticket, the town is two pieces.** Cerulean's town ground ends at row 28; Route 5 is + on the ground behind the trashed house (`$3e`), in by its front door and out by the hole in its + back wall. The house was off the map graph, so `GO OBJECTIVE` toward Vermilion ended `blocked` + at (17, 28) and the fly rang between the town and its houses (scout: 0 of 6 seeds past row 28 in + 43 brain minutes each, from a carry-forward made by scripted presses). + +| # | trap | trigger | test | fix, or why it is left | +| --- | --- | --- | --- | --- | +| 73 | rung 16's place was Route 25, so inside Bill's house `GO OBJECTIVE` and `GO OUT` were both the door; the errand's PC is a hidden event no macro could press; after the ticket, Cerulean's south was off the graph | rung 15 on Route 25 (live), and any fly with the ticket in Cerulean | `an_errand_is_its_people_first_and_the_room_is_not_left_while_one_is_waiting`, `a_hidden_event_is_the_errands_next_step_once_no_person_is_left_and_it_is_faced_from_its_side`, `a_hidden_event_is_nobody_elses_target`, `the_road_south_out_of_cerulean_is_through_the_trashed_house`; `row73_*` in `rom_macros_mode.rs` (`FLY_ROW73_DOOR_CHECKPOINT`, `FLY_ROW73_PC_CHECKPOINT`, `FLY_ROW71_CHECKPOINT`, `FLY_ROW73_SOUTH_CHECKPOINT`, `FLY_ROW73_TRASHED_CHECKPOINT`, `FLY_ROW73_TICKET_CHECKPOINT`) | **fixed**: rung 16 is `errand(BILLS_HOUSE)`, people then things; hidden events read from the cartridge's own table (`$11:$6A40`/`$6A96`), only ever as the errand's next step, faced from the side the entry names (`docs/design/macros.md` 12.35, `macros-wram.md` 17); Cerulean's third piece and the trashed house on the graph | +| 73a | the road from Route 5 to Vermilion is plain map edges through Saffron, whose gates are guarded until the drink; the Underground Path's houses are off the graph | a fly on Route 5 with rung 17 next | none yet | **left**: predicted, not reached by the scout; the branch hunt's flies reach Route 5's gate (`$46`) and the Underground Path house (`$47`). Needs its own checkpoint and row | + +| test (stub rotation) | 74a3c12 | branch | +| --- | --- | --- | +| `row73_the_fly_earns_the_ss_ticket_from_inside_the_ring_at_bills_door` | no ticket in 36,000 frames, out of the house and the Route 24/25 ring. **Fails** | ticket at 4,743 frames, never out of the house. Passes | +| `row73_the_cell_separator_pc_is_pressed_and_bill_hands_over_the_ticket` | no ticket in 36,000 frames. **Fails** | ticket at 2,116 frames. Passes | +| `row73_the_fly_walks_from_the_live_route_25_checkpoint_to_the_ss_ticket` | no ticket in 216,000 frames (60 brain minutes), 1,019 times into the house and 1,019 out. **Fails** | ticket at 9,876 frames. Passes | +| `row73_the_objective_south_of_cerulean_is_the_trashed_houses_two_doors` | aims at the town's bottom row (unreachable). **Fails** | the house's front door, then the hole in its back wall. Passes | +| `row73_the_fly_takes_the_trashed_house_south_to_route_5` | trashed house 54,442; ticket carry-forward not in 48,000 (63,880). **Fails** | 52,081 and 27,067. Passes | +| `row73_the_hidden_event_table_is_the_cartridges_and_bills_pc_is_in_it` | does not compile (new seam) | passes | + +Trap hunt, real connectome, 15 brain minutes per seed, six seeds per arm. The palette seed does not +make runs differ (row 68), so the seeds are the game run 0, 7, 19, 41, 97 and 211 frames ahead of +the brain before the first hold (scout B3's `FLY_TRAP_AHEAD`, a scratch patch, not committed): + +| from | arm | rung 16 | distinct (map, tile) | Bill's-house ring (`GO ROUTE` / `GO OUT` / `GO OBJECTIVE` at net 0) | reached Route 5 | +| --- | --- | --- | --- | --- | --- | +| live row-71 checkpoint (rung 15, Route 25) | 74a3c12 | 0 of 6 | 83-105 | 36-47 / 18-22 / 18-27 per seed | 0 of 6 | +| live row-71 checkpoint | branch | **6 of 6**, at 2.0-2.3 brain minutes | 200-517 | 2-24 / 3-30 / none at net 0 (the walks go somewhere) | 3 of 6 inside the 15 minutes | +| ticket carry-forward (rung 16, Bill's house) | 74a3c12 | (has it) | 328-400 | -- | 0 of 6 (ends in the town, the bike shop or the centre) | +| ticket carry-forward | branch | (has it) | 273-439 | -- | **5 of 6**; four of them on into Route 5's gate (`$46`) or the Underground Path house (`$47`) | + +The two-minute window flags do not measure this trap: the ring crosses more than four tiles, so +the base arm flags only the opening battle text (1 of 53), and the branch arm's flags (28-49 of 53) +are `NEXT` runs inside long battles it now reaches -- the Rocket in the yard behind the trashed +house and Route 24/5 trainers (one battle 23,954 frames and 462 macros; the base's ticket seed 19 +has the same 17,235-frame battle). Every one ended; none is a ring. Route 5 is counted from the +hunt's text-box maps and its final map, so it is a floor. From a2449488a5f74aeced1bfe93840434cb1739c683 Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 04:40:14 +0000 Subject: [PATCH 19/27] scorecard: the lockfile gains libc for the crate; docs for the trap rule, Holm and the throws metric --- docs/scorecard.md | 25 +++++++++++++++++++++---- services/flysim/Cargo.lock | 1 + 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index dbff0e2..9fd7b42 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -80,16 +80,33 @@ run's starting count, which the live check lacks after a boot. has a direction (more is better, less is better, or info), an absolute tolerance and a relative one. For each metric the pairs give one difference, signed so that positive means B is worse. B **fails** a metric when it is worse by more than the tolerance **and** a one-sided sign-flip -permutation test over the pairs gives p below alpha (default 0.05). It reports **better** by the +permutation test over the pairs gives a **Holm-adjusted** p below alpha (default 0.05; Holm over +the judged metrics, so the whole compare, not each metric, has a false-fail rate of at most +alpha when nothing changed; unadjusted, 13 metrics at 0.05 each false-failed about 15% of +releases in a bootstrap of the baseline, with Holm 0 of 200). It reports **better** by the same two tests, and **pass** otherwise: a change inside the tolerance is noise however consistent, and one bad run among eighteen is not a regression. The test is exact up to 20 pairs and a fixed-seed Monte-Carlo beyond, so the same two cards always give the same verdicts. The comparison also names its caveats (different lengths, different runtimes, fewer than eight -pairs, unpaired runs). Exit status 1 is a failed metric. +pairs, unpaired runs). Exit status 1 is a failed metric or a failed checkpoint. + +**The trap rule.** The pooled test cannot see a fault confined to one place: three seeds of one +checkpoint give a sign-flip p of at least 1/8, and the shift is diluted over thirty-six pairs +(the row-71 bag bug, 131 blocked THROW BALLs in every seed of one checkpoint, passed the pooled +compare even spliced into an otherwise identical suite). So each checkpoint is also judged on its +own, without statistics: it **fails**, named as `trap@`, when B is trapped on at least +two of its runs and on at least two more than A, or when any run of B has a blocked-macro storm +(50 or more blocked finishes of one macro) and no run of A on that checkpoint does. A run is +trapped on a recovery-ladder event (two suspected watchdog probes in a row, any rule: stalled, +zero-progress, sequence, ...), on at least half its probes suspected, or on a storm. Costs: with +three seeds a checkpoint whose trap is a coin flip in A already (r09-forest-catch, r10-pewter-center +on the baseline) can fail by chance when B traps all three seeds (about 1 in 27 each by bootstrap, +so roughly 7% of releases that changed nothing but the trajectory); five seeds make it 1 in 243. +Identical suites never fail. The metrics: rungs per hour, places per hour, empty pad %, suspected probes %, ladder events per -hour, rollbacks per hour, blocked macro %, buy ball, throws and catches per hour, battles won and -lost per hour, whiteouts per hour. Heals per hour, macro starts per minute and the trap hunt's +hour, rollbacks per hour, blocked macro %, buy ball, throws (THROW BALL that finished, not blocked starts) and catches per hour, battles won and +lost per hour, whiteouts per hour. Blocked throws per hour, heals per hour, macro starts per minute and the trap hunt's flagged windows are reported, never judged: healing more can follow losing more, and a fly that fights for most of a run presses NEXT through battle text more than ten times in two minutes, which the hunt reads as a repeated sequence (nine windows in ten are flagged on the baseline, so diff --git a/services/flysim/Cargo.lock b/services/flysim/Cargo.lock index 827747a..ea5f0d5 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -487,6 +487,7 @@ dependencies = [ "flybrain-core", "flybrain-gb", "flysim", + "libc", "serde", "serde_json", "tempfile", From 210296a0ffca5c4f1028217fdf90bc3ba30e20fe Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 05:00:24 +0000 Subject: [PATCH 20/27] docs: v0.7.6 status --- docs/stream-mvp-plan.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/stream-mvp-plan.md b/docs/stream-mvp-plan.md index 81b18cd..3f6c98e 100644 --- a/docs/stream-mvp-plan.md +++ b/docs/stream-mvp-plan.md @@ -1016,3 +1016,11 @@ median; a two-fly transition near 10 to 12 ms at the median in every execution m zero divergence; `check` allowed the switch; the 30-minute speed probation passed at a median 1.000x real time with no lag growth. Legacy stays one command away (`fly-runtime legacy`); RETIRE-01 after a clean week. +- 2026-10-02 (v0.7.6, flybus groundwork, nothing switched): the control API as flybus RPC with + per-agent grants (CTRL-01, `FLY_CONTROL_VIA`), the video feed over the bus in production form + (EDGE-02, `fly-feed bus|direct`), the session's agent and world as processes on the router's + Unix sockets (BUS-01, `fly-runtime session --bus`), an optional aux cpu for bus threads off the + sim's cores, and a per-frame work metric for both runtimes. All default off; the live stream + is unchanged until each is switched on with its rollback. Also: the multi-seed behavioural + scorecard (nightly), two stale ROM tests fixed and every ROM suite mapped (row 72), and the + parity test's idle-header race. From 4935dcc04542dade4949e8d977f96c05c5d5c760 Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 05:15:45 +0000 Subject: [PATCH 21/27] BUS-01 review notes: clippy fixes in the new tests --- services/flysim/crates/fly-session/tests/orphans.rs | 7 ++++--- services/flysim/crates/flybus/tests/conformance_wire.rs | 4 +++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/services/flysim/crates/fly-session/tests/orphans.rs b/services/flysim/crates/fly-session/tests/orphans.rs index ab0fcbe..f78ee98 100644 --- a/services/flysim/crates/fly-session/tests/orphans.rs +++ b/services/flysim/crates/fly-session/tests/orphans.rs @@ -41,10 +41,11 @@ fn a_killed_parent_takes_its_workers_with_it() { let mut worker = Command::new("sleep"); worker.arg("300"); fly_session::launcher::die_with_parent(&mut worker); - let worker = worker.spawn().unwrap(); - let control = Command::new("sleep").arg("300").spawn().unwrap(); + let mut worker = worker.spawn().unwrap(); + let mut control = Command::new("sleep").arg("300").spawn().unwrap(); println!("{} {}", worker.id(), control.id()); - std::thread::sleep(Duration::from_secs(600)); + let _ = worker.wait(); + let _ = control.wait(); return; } let mut parent = Command::new(std::env::current_exe().unwrap()) diff --git a/services/flysim/crates/flybus/tests/conformance_wire.rs b/services/flysim/crates/flybus/tests/conformance_wire.rs index 83f3555..d28e8f3 100644 --- a/services/flysim/crates/flybus/tests/conformance_wire.rs +++ b/services/flysim/crates/flybus/tests/conformance_wire.rs @@ -631,7 +631,9 @@ async fn a_client_refuses_a_router_with_a_different_contract_digest_at_hello() { ), ) .await; - let err = refused.err().expect("a mismatched digest must be refused"); + let Err(err) = refused else { + panic!("a mismatched digest must be refused"); + }; assert_eq!(err.code, flybus::ErrorCode::VersionMismatch); assert_eq!(err.message, "router speaks a different contract"); } From 9d5dd398caebd0b930064911463ea26507e35875 Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 06:06:08 +0000 Subject: [PATCH 22/27] Cargo.lock: the fly-edge dependency the EDGE-02/CTRL-01 merge resolution left out --- services/flysim/Cargo.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/services/flysim/Cargo.lock b/services/flysim/Cargo.lock index ea5f0d5..f9e6693 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -460,6 +460,7 @@ dependencies = [ "axum", "clap", "fly-control-edge", + "fly-edge", "fly-session", "flybrain-core", "flybrain-gb", From 91d0214cbc6eaa14a0c5f040e3355dcac785ed9b Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 06:19:39 +0000 Subject: [PATCH 23/27] flysim integration test: assert the feed's structure, not a wall-clock rate The publish cadence is a 30 Hz wall-clock timer, so the 25..31 Hz bound failed on a loaded box (22.5 Hz in the v0.7.6 gate). Log the rate, bound it only against the 2 Hz idle path, and assert what is deterministic: contiguous seq, at least one frame per snapshot, brain time advancing 16-17 ticks per frame. Two more load-dependent races in the same test: /status read the boot header (a 1-rung ladder) right after /healthz, and the first feed message after the restart could be the frame-0 boot header. Wait for a running snapshot in both. --- .../flysim/crates/flysim/tests/integration.rs | 35 +++++++++++++++---- 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/services/flysim/crates/flysim/tests/integration.rs b/services/flysim/crates/flysim/tests/integration.rs index bfeb8a2..3ec8a2c 100644 --- a/services/flysim/crates/flysim/tests/integration.rs +++ b/services/flysim/crates/flysim/tests/integration.rs @@ -361,9 +361,10 @@ async fn the_service_streams_takes_sugar_checkpoints_and_resumes_after_being_kil let feed_hz = (headers.len() - 1) as f64 * 1000.0 / published_span_ms; let arrival_hz = (headers.len() - 1) as f64 / first_at.elapsed().as_secs_f64(); eprintln!( - "[timing] {} snapshots published over {:.3} s: {feed_hz:.2} Hz (contract: 30 Hz while\n\ - \x20 running; the ceiling is one snapshot per two 16.74 ms emulator frames,\n\ - \x20 29.86 Hz). Client-side arrival rate {arrival_hz:.2} Hz.", + "[timing] {} snapshots published over {:.3} s: {feed_hz:.2} Hz (contract: a 30 Hz wall-clock\n\ + \x20 timer while running; one snapshot per loop pass at most, so the rate is the\n\ + \x20 timer's on an idle box and falls with the box's load). Client-side arrival\n\ + \x20 rate {arrival_hz:.2} Hz.", headers.len(), published_span_ms / 1000.0 ); @@ -371,12 +372,29 @@ async fn the_service_streams_takes_sugar_checkpoints_and_resumes_after_being_kil "[timing] first snapshot {:.3} s after connecting", first_at.duration_since(connected_at).as_secs_f64() ); + // The publish cadence is a wall-clock timer (`docs/feed-protocol.md`: "30 snapshots per + // second wall-clock while running"), so how many emulator frames sit between two snapshots + // is not fixed: 2 on an idle box (33.5 ms), but 1 or 3 whenever the timer and the 16.74 ms + // frame clock drift against each other, and 1 per snapshot for most of a run when the box is + // loaded and the loop is behind real time. Asserting 25..31 Hz here failed ~1 run in 3 with + // sibling tests booting sims in parallel (22.5 Hz in the v0.7.6 gate). The wall rate is + // therefore only logged, with a bound that tells "running" from the 2 Hz idle path. assert!( - (25.0..31.0).contains(&feed_hz), - "the feed published at {feed_hz:.2} Hz, which is not the contract's 30 Hz" + feed_hz > 2.5, + "the feed published at {feed_hz:.2} Hz, which is the paused/booting cadence, not a running one" ); + // What is deterministic is the structure: contiguous seq, the emulator advancing at least one + // frame per snapshot, and the brain clock advancing exactly with the frames it ran (the + // 1 ms kernel takes 16 or 17 ticks per 16.74 ms frame, carrying the remainder). for pair in headers.windows(2) { assert_eq!(pair[1].seq, pair[0].seq + 1, "a snapshot was dropped between publishes"); + let frames = pair[1].frame.checked_sub(pair[0].frame).expect("frame went backwards"); + assert!(frames >= 1, "a running snapshot with no emulator frame behind it"); + let brain = pair[1].brain_ms - pair[0].brain_ms; + assert!( + (16.0 * frames as f64 - 0.5..=17.0 * frames as f64 + 0.5).contains(&brain), + "{brain} ms of brain time over {frames} frames, expected 16 or 17 ticks each" + ); } let (_, metrics) = http_blocking(service.control_port, "GET", "/metrics", None).unwrap(); for name in ["fly_lag_seconds", "fly_realtime_factor", "fly_feed_clients"] { @@ -620,7 +638,12 @@ async fn the_service_streams_takes_sugar_checkpoints_and_resumes_after_being_kil .expect("open") .expect("readable"); if let Message::Binary(bytes) = message { - resumed = Some(split(&bytes).0); + // `/healthz` can answer while the first thing on the feed is still the 2 Hz boot + // header (frame 0, before the restore reaches the loop): wait for a running one. + let header = split(&bytes).0; + if header.status == flysim::snapshot::FeedStatus::Running { + resumed = Some(header); + } } } let resumed = resumed.unwrap(); From 8b696f8f1c6a24d6f83272b31cbbf8326de61209 Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 07:34:50 +0000 Subject: [PATCH 24/27] docs: the feed runs over flybus --- docs/stream-mvp-plan.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/stream-mvp-plan.md b/docs/stream-mvp-plan.md index 3f6c98e..2a9bea2 100644 --- a/docs/stream-mvp-plan.md +++ b/docs/stream-mvp-plan.md @@ -1024,3 +1024,7 @@ median; a two-fly transition near 10 to 12 ms at the median in every execution m is unchanged until each is switched on with its rollback. Also: the multi-seed behavioural scorecard (nightly), two stale ROM tests fixed and every ROM suite mapped (row 72), and the parity test's idle-header race. +- 2026-10-02 07:13Z: the stream's video feed runs over flybus (`fly-feed bus`, one aux cpu for the + bus threads). Over the first 20 minutes the sim's mean work per frame fell from 15.2 to about + 14.5 ms and its p99 from 46 to about 21 ms (the publisher left the sim's shared cpu); realtime + factor unchanged at about 1.0. Rollback: `fly-feed direct`. From bbbfe4b68a0d8adbdd6402531f6dca61a67bd39c Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 07:56:18 +0000 Subject: [PATCH 25/27] docs: control runs over flybus --- docs/stream-mvp-plan.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/stream-mvp-plan.md b/docs/stream-mvp-plan.md index 2a9bea2..53fae9a 100644 --- a/docs/stream-mvp-plan.md +++ b/docs/stream-mvp-plan.md @@ -1028,3 +1028,9 @@ median; a two-fly transition near 10 to 12 ms at the median in every execution m bus threads). Over the first 20 minutes the sim's mean work per frame fell from 15.2 to about 14.5 ms and its p99 from 46 to about 21 ms (the publisher left the sim's shared cpu); realtime factor unchanged at about 1.0. Rollback: `fly-feed direct`. +- 2026-10-02 07:41Z: the control API runs over flybus too (`FLY_CONTROL_VIA=bus`): `:7401` is + served by the control edge calling flysim's RPC services under per-client grants. First 15 + minutes: bus connected, calls flowing, no failures, no restarts, realtime factor about 1.0. + Both switches are in the host env, so a deploy keeps them. The session's agent and world stay + on the in-process lane: over the router they cost 2.5 to 3.5 ms a frame, more than the + release box's headroom (live work about 14.5 of 16.74 ms); the GPU brain is the way there. From 49e48a507525a7acbd862e090d4b849b04fcddfa Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 09:40:44 +0000 Subject: [PATCH 26/27] macros: row 73 review notes -- an errand room's talked entries are forgotten when the fly leaves it, a one-sided target with no standable tile is not waited for, an off-map hidden-event entry is skipped N3: the talked ledger never forgot within a session, but the cartridge re-shows Bill after the fly leaves and a Bill whose bag was full never hands over the ticket. While the objective is an errand in a room the palette notes the room, and on the first frame the fly stands elsewhere with that errand still the objective it forgets that room's talked entries (Talked::forget_map). N4: a hidden event pressed from one side whose only stand tile is pushed had no aim, earned no blocked entry and kept the exits withheld. It now leaves the errand's list at once (palette::servable). N1: state::hidden_events skipped nothing; one entry off its own map voided the whole map's list. It now skips that entry and keeps the others. N2: the item-use dispatch doc comment is back on mod items. --- docs/design/macros.md | 16 ++++ .../flybrain-gb/src/pokemon_red/fake_wram.rs | 23 ++++++ .../src/pokemon_red/macros/cartridge.rs | 7 ++ .../src/pokemon_red/macros/driver.rs | 76 ++++++++++++++++++- .../src/pokemon_red/macros/palette.rs | 19 ++++- .../src/pokemon_red/macros/tests.rs | 21 +++++ .../flybrain-gb/src/pokemon_red/state.rs | 14 +++- .../src/pokemon_red/state/tests.rs | 20 +++++ .../crates/flysim/tests/rom_macros_mode.rs | 54 +++++++++++++ 9 files changed, 241 insertions(+), 9 deletions(-) diff --git a/docs/design/macros.md b/docs/design/macros.md index 76ed048..5e00cc6 100644 --- a/docs/design/macros.md +++ b/docs/design/macros.md @@ -2209,6 +2209,22 @@ What changed, all of it knowledge inside macros: so the walk's one aim is the tile on that side and only facing it from there is the arrival and `TALK`'s precondition. An argument that is an item or a text id and happens to equal a facing value only narrows the approach. +- **An errand is recoverable inside one session (row 73 review).** The talked ledger is the + session's and never forgot, but the cartridge re-shows people: Route 25's script resets Bill's + event once the fly has left, and a Bill whose bag was full never handed over the ticket. A + conversation had on the last visit then retired this one's and the rung was unreachable until a + restart. The palette now notes the room while the errand is the objective and, on the first + frame the fly stands anywhere else with that errand still the objective, forgets that room's + talked entries (`Talked::forget_map`). Other rooms' entries and a room that is not the errand + keep theirs. The bag-full case needs no extra rule: nothing is left to aim at, the exits return, + and the fly leaves and comes back. +- **A one-sided target nobody can stand in front of is not waited for.** If every tile a hidden + event can be pressed from is one the cartridge pushes the fly off (the pushed ledger, row 37), + the walk had no aim, so no walk ended `blocked` and the ways out stayed withheld for good. Such + a target leaves the errand's list at once (`palette::servable`), which returns the exits. +- **A hidden-event entry off its own map is skipped.** The Safari Zone gate lists a nugget + "inaccessible" at (10, 1) on an 8 x 6 map, and the rest houses a copied Pokecenter PC; one such + entry no longer voids the rest of the map's list. The fly still chooses every press: `GO OBJECTIVE` to walk, `TALK` to press A, `YES`, `NO` or `NEXT` in Bill's boxes. Nothing presses for it, no button is added to any pad, and the readout, the diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/fake_wram.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/fake_wram.rs index c7951be..6fe8414 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/fake_wram.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/fake_wram.rs @@ -460,6 +460,29 @@ impl Wram { self } + /// The cartridge's hidden-event table with one map in it: `HiddenEventMaps` listing `map`, + /// `HiddenEventPointers` pointing at a list of `(y, x, argument)` entries (six bytes each, the + /// routine's `dba` a bank-$11 address). + pub fn hidden_table(&mut self, map: u8, entries: &[(u8, u8, u8)]) -> &mut Self { + use super::state::poke::hidden::{ENTRY_BYTES, MAPS_ADDRESS, POINTERS_ADDRESS, TABLE_BANK}; + let list = 0x7000u16; + let mut put = |address: u16, byte: u8| { + self.rom.insert((TABLE_BANK, address), byte); + }; + put(MAPS_ADDRESS, map); + put(MAPS_ADDRESS + 1, 0xff); + put(POINTERS_ADDRESS, (list & 0xff) as u8); + put(POINTERS_ADDRESS + 1, (list >> 8) as u8); + for (index, (y, x, argument)) in entries.iter().enumerate() { + let base = list + index as u16 * ENTRY_BYTES; + for (offset, byte) in [*y, *x, *argument, TABLE_BANK, 0x00, 0x60].into_iter().enumerate() { + put(base + offset as u16, byte); + } + } + put(list + entries.len() as u16 * ENTRY_BYTES, 0xff); + self + } + /// The cartridge's `ItemUsePtrTable`, one pointer per item id, grouped the way the pinned /// commit groups them: the balls share one routine, the potions, drinks, status heals and /// revives another, the four X stat items another, the four PP restores another, and every diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/cartridge.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/cartridge.rs index 2e90aca..d871a20 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/cartridge.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/cartridge.rs @@ -691,6 +691,13 @@ impl Talked { self.0.insert((map, target)); } + /// Forget everything talked to on `map` (row 73's errand: the cartridge shows the room's + /// people again after the fly leaves, and a conversation had on the last visit is not this + /// one's). + pub fn forget_map(&mut self, map: u8) { + self.0.retain(|(at, _)| *at != map); + } + /// How many things this session has talked to, for a log line and the tests. pub fn len(&self) -> usize { self.0.len() diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/driver.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/driver.rs index 733a84b..f3c7db3 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/driver.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/driver.rs @@ -107,6 +107,11 @@ pub struct PokemonPalette { nearest: Option<(u8, u32)>, /// Whether the last `observe` was the frame that number fell on. nearer: bool, + /// The map the fly was last seen standing in while the ladder's objective was an errand in + /// it (row 73). On leaving it with the errand still the objective, the talked entries of that + /// room are forgotten: Route 25 re-shows Bill, and a Bill whose bag was full never handed + /// over the ticket, so a conversation had on the last visit must not retire this one's. + errand_seen: Option, /// The map of the last frame that was not a warp's tear, and how many tear frames have run /// since (row 58, [`PokemonPalette::tear`], [`TEAR_FRAMES`]). /// @@ -150,6 +155,7 @@ impl PokemonPalette { grids: MapGrids::default(), nearest: None, nearer: false, + errand_seen: None, settled: None, tear_frames: 0, naming_since: None, @@ -316,7 +322,7 @@ impl MacroPalette for PokemonPalette { // name gets the whole bound and a restore starts it again. self.naming_since = naming.map(|_| self.naming_since.unwrap_or(self.now_ms)); let naming_elapsed = self.naming_since.map_or(0.0, |since| (self.now_ms - since).max(0.0)); - let (scene, bindings, raw, standing, stepping, approach) = { + let (scene, bindings, raw, standing, stepping, approach, errand) = { let Self { machine, mode, @@ -372,12 +378,28 @@ impl MacroPalette for PokemonPalette { let hops = geography::hops(palette::region_here(&mut state)?, objective.map)?; Some((objective.map, hops)) }); + // Row 73: whether the objective is an errand, and in which room. + let errand = standing.and_then(|_| { + let objective = palette::objective_place(&mut state)?; + (objective.target == Some(crate::adapter::PlaceKind::Errand)).then_some(objective.map) + }); *cached = Some(palette); - (scene, bindings, raw, standing, stepping, approach) + (scene, bindings, raw, standing, stepping, approach, errand) }; // Section 12.7: the macro layer's own answer to "has the run stood here", because the // adapter's reward ledger cannot record a doormat. if let Some(player) = standing { + if let Some(room) = self.errand_seen + && player.map != room + { + if errand == Some(room) { + self.talked.forget_map(room); + } + self.errand_seen = None; + } + if errand == Some(player.map) { + self.errand_seen = Some(player.map); + } // New ground under the fly is the one thing that can change which tiles of this map // it can reach, so it is what clears the map's frontier mark (section 12.14). A tile // the ledger already had changes nothing and clears nothing. @@ -594,7 +616,7 @@ mod tests { use crate::pokemon_red::fake_wram::{self, REDS_HOUSE_1F, WALL_TILE, Wram}; use crate::pokemon_red::macros::geography::Amenity; use crate::pokemon_red::maps; - use crate::pokemon_red::macros::cartridge::{Edge, ExitId, MacroState}; + use crate::pokemon_red::macros::cartridge::{Edge, ExitId, MacroState, TalkLedger, TalkTarget}; /// A ledger with one exit in it, for the wiring test below. struct OneVisited(MapExit); @@ -784,6 +806,54 @@ mod tests { assert!(palette.nearer_the_objective(), "out of the front door is nearer still"); } + /// A ledger whose objective is the errand in one room (row 73). + struct ErrandIn(u8); + + impl RunLedger for ErrandIn { + fn exit_visited(&self, _exit: MapExit) -> bool { + false + } + + fn objective(&self) -> Option { + Some(crate::adapter::MapPlace::errand(self.0)) + } + } + + #[test] + fn an_errand_rooms_talked_entries_are_forgotten_when_the_fly_leaves_it() { + // Row 73 review N3. The talked ledger is the session's and never forgot, but the + // cartridge re-shows Bill after the fly leaves (Route 25's script resets his event), and a + // Bill whose bag was full never gave the ticket: a conversation had on the last visit + // retired this one's, and rung 16 was unreachable until a restart. + let mut wram = Wram::new(); + wram.started().map(maps::BILLS_HOUSE, 8, 8, 2, 6).facing(0).house_collision(); + let mut palette = PokemonPalette::new(7); + let ledger = ErrandIn(maps::BILLS_HOUSE); + palette.observe(&mut wram, &ledger); + palette.talked.record(maps::BILLS_HOUSE, TalkTarget::Sprite(1)); + // A conversation elsewhere is not the errand's and stays. + palette.talked.record(maps::VIRIDIAN_CITY, TalkTarget::Sprite(2)); + palette.observe(&mut wram, &ledger); + assert_eq!(palette.talked(), 2, "still in the room: nothing is forgotten"); + + wram.map(maps::ROUTE_25, 40, 10, 45, 4); + palette.observe(&mut wram, &ledger); + palette.observe(&mut wram, &ledger); + assert!(!palette.talked.talked(maps::BILLS_HOUSE, TalkTarget::Sprite(1)), "left: asked again"); + assert!(palette.talked.talked(maps::VIRIDIAN_CITY, TalkTarget::Sprite(2)), "other rooms keep theirs"); + + // And a room that is not the objective's errand keeps its entries on leaving. + let mut wram = Wram::new(); + wram.started().map(maps::BILLS_HOUSE, 8, 8, 2, 6).facing(0).house_collision(); + let mut palette = PokemonPalette::new(7); + let elsewhere = Bound(maps::PEWTER_GYM); + palette.observe(&mut wram, &elsewhere); + palette.talked.record(maps::BILLS_HOUSE, TalkTarget::Sprite(1)); + wram.map(maps::ROUTE_25, 40, 10, 45, 4); + palette.observe(&mut wram, &elsewhere); + assert_eq!(palette.talked(), 1); + } + #[test] fn standing_on_new_ground_is_what_clears_a_maps_frontier_mark() { // Section 12.14's other half, wired: the mark is written by a `GO FRONTIER` that could diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/palette.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/palette.rs index a039154..76ccaae 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/palette.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/palette.rs @@ -2282,12 +2282,27 @@ pub fn objective_targets(state: &mut dyn MacroState) -> Vec<(Tile, TalkTarget)> fn open_targets(state: &mut dyn MacroState, targets: Vec<(Tile, TalkTarget)>) -> Vec<(Tile, TalkTarget)> { targets .into_iter() - .filter(|(_, target)| { - !state.talked(*target) && !state.blocked(TargetKey::Thing(*target)) + .filter(|(tile, target)| { + !state.talked(*target) + && !state.blocked(TargetKey::Thing(*target)) + && servable(state, *tile, *target) }) .collect() } +/// Whether some tile the objective's `target` can be pressed from is not one a script pushes the +/// fly off (row 37). Only a one-sided hidden event can fail this: its single stand tile is the +/// only door in, and with that tile pushed the walk has no aim, so it never ends in a refusal +/// that earns a blocked entry -- and while a target waits the exits are withheld, so the room +/// became a trap. A target nobody can stand in front of is not one the rung is waiting on, and +/// it leaves the list at once: the exits are back the frame the pushed tile is learned. +fn servable(state: &mut dyn MacroState, tile: Tile, target: TalkTarget) -> bool { + let Some(need) = required_facing(state, target) else { return true }; + FACINGS.into_iter().filter(|facing| need == opposite(*facing)).any(|facing| { + tile.step(facing).is_some_and(|stand| !state.pushed_tile(stand.x, stand.y)) + }) +} + /// The one side the objective's `target` is pressed from, when the cartridge names one: a hidden /// event whose routine checks the player's facing (row 73, Bill's PC). `None` for every sprite and /// sign, which answer from any side. diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs index ca89a17..7aaa237 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs @@ -6706,6 +6706,27 @@ fn a_hidden_event_is_the_errands_next_step_once_no_person_is_left_and_it_is_face assert_eq!(super::palette::objective_targets(&mut below), vec![(Tile::new(4, 4), TalkTarget::Sprite(2))]); } +#[test] +fn a_one_sided_target_whose_only_stand_tile_is_pushed_is_not_waited_for() { + // Row 73 review N4. The PC answers only from below; if the cartridge pushes the fly off + // that tile the walk has no aim, so no walk ever ends `blocked`, and while a target waited the + // exits were withheld for good. The target leaves the list and the way out is back. + let mut world = bills_house().at(3, 5); + world.npcs.clear(); + world.talked.insert(TalkTarget::Sprite(1)); + assert_eq!(super::palette::objective_targets(&mut world).len(), 1); + assert!(!on_the_pad(&mut world, MacroKind::GoOut)); + world.pushes.insert(Tile::new(1, 5)); + assert!(super::palette::objective_targets(&mut world).is_empty(), "nobody can stand in front of it"); + assert!(on_the_pad(&mut world, MacroKind::GoOut), "so the room is not a trap"); + // A pushed tile somewhere else changes nothing. + let mut other = bills_house().at(3, 5); + other.npcs.clear(); + other.talked.insert(TalkTarget::Sprite(1)); + other.pushes.insert(Tile::new(2, 5)); + assert_eq!(super::palette::objective_targets(&mut other).len(), 1); +} + #[test] fn a_hidden_event_is_nobody_elses_target() { // A hidden event is every PC, poster and trash can in Kanto. Outside the errand that names it diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs index c99aaa8..5361fd8 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs @@ -348,8 +348,6 @@ pub mod poke { pub const TYPE_ELECTRIC: u8 = 0x17; } - /// The cartridge's item-use dispatch and the ids that name its routines (row 63, - /// `docs/design/macros.md` 12.27). /// The cartridge's hidden-event tables (row 73, `docs/design/macros.md` 12.35). /// /// `engine/overworld/hidden_events.asm`: `CheckForHiddenEvent` walks `HiddenEventMaps`, one @@ -375,6 +373,8 @@ pub mod poke { pub const FACINGS: [u8; 4] = [0x00, 0x04, 0x08, 0x0c]; } + /// The cartridge's item-use dispatch and the ids that name its routines (row 63, + /// `docs/design/macros.md` 12.27). pub mod items { /// `engine/items/item_effects.asm`: `UseItem_` jumps through `ItemUsePtrTable`, one /// little-endian pointer per item id from `MASTER_BALL` (1) to `MAX_ELIXER` (`$53`), in @@ -2084,7 +2084,7 @@ pub fn signs(memory: &mut dyn MemoryReader) -> Vec { /// /// Empty on a map the table does not list, when the seam has no cartridge image behind it, and /// when the bytes are not the shape the disassembly describes -- a map list with no end, a pointer -/// outside the bank's window, a list longer than any map's, a tile off the loaded map. A table +/// outside the bank's window, a list longer than any map's. An entry whose tile is off the loaded map is skipped, not fatal. A table /// this module cannot read is not one it reports, so a wrong address narrows (`GO OBJECTIVE` has /// one less thing to aim at) and never invents a tile. pub fn hidden_events(memory: &mut dyn MemoryReader) -> Vec { @@ -2125,9 +2125,15 @@ fn hidden_events_inner(memory: &mut dyn MemoryReader) -> Option let argument = memory.read_rom(TABLE_BANK, base + 2)?; let routine = u16::from_le_bytes([memory.read_rom(TABLE_BANK, base + 4)?, memory.read_rom(TABLE_BANK, base + 5)?]); - if x >= size.width || y >= size.height || routine >= 0x8000 { + if routine >= 0x8000 { return None; } + // The cartridge has entries off their own map (the Safari Zone gate's inaccessible + // nugget, the rest houses' copied Pokecenter PC): the map's other entries are still + // good, so only the bad one is skipped. The entry index stays the list position. + if x >= size.width || y >= size.height { + continue; + } let facing = FACINGS.contains(&argument).then(|| facing_from(argument)); out.push(HiddenEvent { x, y, index: entry as u8, facing }); } diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/state/tests.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/state/tests.rs index ea8183c..2585e36 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/state/tests.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/state/tests.rs @@ -1462,3 +1462,23 @@ fn the_naming_screen_reads_unknown_in_a_battle_and_title_before_the_game() { wram.naming_screen(0, 7); assert_eq!(crate::pokemon_red::scene::detect(&mut wram), Scene::Title); } + +#[test] +fn an_off_map_hidden_event_is_skipped_and_the_maps_other_entries_are_kept() { + // Row 73 review N1. The Safari Zone gate lists a nugget at (10, 1) on an 8 x 6 map, and the + // rest houses a copied Pokecenter PC at (13, 3) on 8 x 8 maps: one entry off its own map used + // to void the list. + let mut wram = Wram::new(); + // Two blocks by two is a 4 x 4 tile map. + wram.map(0x5d, 2, 2, 1, 1).hidden_table(0x5d, &[(1, 10, 0x00), (2, 1, 0x04), (9, 1, 0x08), (0, 3, 0x17)]); + let events = hidden_events(&mut wram); + assert_eq!( + events.iter().map(|event| (event.x, event.y, event.index)).collect::>(), + vec![(1, 2, 1), (3, 0, 3)], + "the entries on the map, under their own list positions" + ); + // A list with nothing wrong in it is what it was. + let mut wram = Wram::new(); + wram.map(0x5d, 2, 2, 1, 1).hidden_table(0x5d, &[(2, 1, 0x04)]); + assert_eq!(hidden_events(&mut wram).len(), 1); +} diff --git a/services/flysim/crates/flysim/tests/rom_macros_mode.rs b/services/flysim/crates/flysim/tests/rom_macros_mode.rs index 6a68c3e..da0e2bf 100644 --- a/services/flysim/crates/flysim/tests/rom_macros_mode.rs +++ b/services/flysim/crates/flysim/tests/rom_macros_mode.rs @@ -5276,6 +5276,60 @@ fn row73_the_cell_separator_pc_is_pressed_and_bill_hands_over_the_ticket() { row73_drive_to_the_ticket(&mut run, 36_000); } +/// Row 73 review N3: the errand is recoverable inside one session. The talked ledger is the +/// session's and the cartridge re-shows Bill once the fly has left (Route 25's script resets his +/// event), so a conversation had on the last visit must not retire this one's: the room's talked +/// entries are forgotten when the fly leaves it with the errand still the objective. +/// +/// From the door checkpoint, over the stub rotation: wait for the first `TALK` in the house, then +/// walk the fly out by hand (the macros withhold the exits while the errand waits, which is the +/// point), and the stub earns the ticket from there, in the same session. +#[test] +fn row73_the_errand_survives_leaving_the_house_mid_conversation() { + let rom = skip_without_rom!(); + let Some(checkpoint) = row73_checkpoint("FLY_ROW73_DOOR_CHECKPOINT") else { + eprintln!("skipped: no FLY_ROW73_DOOR_CHECKPOINT"); + return; + }; + let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint); + assert_eq!(run.map(), BILLS_HOUSE, "the checkpoint is inside Bill's house"); + let mut talked = false; + for _ in 0..24_000 { + run.frame(); + if run.talk_starts_by_map.get(&BILLS_HOUSE).copied().unwrap_or(0) > 0 { + talked = true; + break; + } + } + assert!(talked, "no TALK in the house: {:?}", run.talk_starts_by_map); + assert!(!run.event(EVENT_GOT_SS_TICKET), "the ticket is not earned by the first conversation"); + // Out by hand: along the room to the doormat's columns (2 and 3) and down, pressing B between + // the cartridge's own text. + let mut out = false; + let mut last = None; + for frame in 0..4_800u32 { + let here = flybrain_gb::pokemon_red::state::player(&mut run.gb); + last = here.map(|player| (player.map, player.x, player.y)); + let heading = match here { + Some(player) if player.x < 2 => flybrain_gb::buttons::RIGHT, + Some(player) if player.x > 3 => flybrain_gb::buttons::LEFT, + _ => flybrain_gb::buttons::DOWN, + }; + run.gb.set_buttons(if frame % 16 < 12 { heading } else { flybrain_gb::buttons::B }); + run.gb.run_frame().expect("a frame should complete"); + run.ms += MS_PER_FRAME; + run.adapter.sample(&mut run.gb, run.ms); + if run.map() != BILLS_HOUSE && run.map() != u32::MAX { + out = true; + break; + } + } + assert!(out, "the fly could not be walked out of the house, last at {last:?}"); + run.gb.set_buttons(0); + // Back to the macros, in the same session: the errand is Bill's again, and the ticket is earned. + row73_drive_to_the_ticket(&mut run, 120_000); +} + /// Drive the stub rotation until the ticket's flag is set, counting the house's doors on the way: /// `(into, out)`. fn row73_drive_to_the_ticket(run: &mut Run, budget: u32) -> (u32, u32) { From 37b3195b0b218d8f37f80ea67746133d7ba19aa2 Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 09:43:02 +0000 Subject: [PATCH 27/27] docs: v0.7.7 status --- docs/stream-mvp-plan.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/stream-mvp-plan.md b/docs/stream-mvp-plan.md index 53fae9a..a7bc4cd 100644 --- a/docs/stream-mvp-plan.md +++ b/docs/stream-mvp-plan.md @@ -1034,3 +1034,12 @@ median; a two-fly transition near 10 to 12 ms at the median in every execution m Both switches are in the host env, so a deploy keeps them. The session's agent and world stay on the in-process lane: over the router they cost 2.5 to 3.5 ms a frame, more than the release box's headroom (live work about 14.5 of 16.74 ms); the GPU brain is the way there. +- 2026-10-02 (v0.7.7, loop review): row 73. The scout found rung 16 unreachable: its place was + "on Route 25", so inside Bill's house the walks just left again, and Bill's PC is a hidden + object no macro could press. Rung 16 is now Bill's errand inside the house (people first, then + things; exits off the pad while the errand waits), and hidden objects are read from the + cartridge's own table and become a target only as that errand's next step. Cerulean's north half + joins the map graph through the trashed house. Trap hunts: rung 16 in 0 of 6 seeds before, 6 of 6 + after; Route 5 from the ticket 0 of 6 before, 5 of 6 after. Review: APPROVE-WITH-NOTES; notes + fixed. Also: bus worker children die with their parent; the feed test asserts structure, not a + wall-clock rate.